Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ADT/StringExtras.h
//===-- llvm/ADT/StringExtras.h - Useful string functions -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains some functions that are useful when dealing with strings. // //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_STRINGEXTRAS_H #define LLVM_ADT_STRINGEXTRAS_H #include "llvm/ADT/StringRef.h" #include "llvm/Support/DataTypes.h" #include <iterator> namespace llvm { template<typename T> class SmallVectorImpl; /// hexdigit - Return the hexadecimal character for the /// given number \p X (which should be less than 16). static inline char hexdigit(unsigned X, bool LowerCase = false) { const char HexChar = LowerCase ? 'a' : 'A'; return X < 10 ? '0' + X : HexChar + X - 10; } /// Construct a string ref from a boolean. static inline StringRef toStringRef(bool B) { return StringRef(B ? "true" : "false"); } /// Interpret the given character \p C as a hexadecimal digit and return its /// value. /// /// If \p C is not a valid hex digit, -1U is returned. static inline unsigned hexDigitValue(char C) { if (C >= '0' && C <= '9') return C-'0'; if (C >= 'a' && C <= 'f') return C-'a'+10U; if (C >= 'A' && C <= 'F') return C-'A'+10U; return -1U; } /// utohex_buffer - Emit the specified number into the buffer specified by /// BufferEnd, returning a pointer to the start of the string. This can be used /// like this: (note that the buffer must be large enough to handle any number): /// char Buffer[40]; /// printf("0x%s", utohex_buffer(X, Buffer+40)); /// /// This should only be used with unsigned types. /// template<typename IntTy> static inline char *utohex_buffer(IntTy X, char *BufferEnd, bool LowerCase = false) { char *BufPtr = BufferEnd; *--BufPtr = 0; // Null terminate buffer. if (X == 0) { #pragma prefast(suppress: 22102, "buffer for BufferEnd always has room for one char") *--BufPtr = '0'; // Handle special case. return BufPtr; } while (X) { unsigned char Mod = static_cast<unsigned char>(X) & 15; #pragma prefast(suppress: 22103, "X runs down to zero before end of buffer depending on type - cannot express for template in SAL") *--BufPtr = hexdigit(Mod, LowerCase); X >>= 4; } return BufPtr; } static inline std::string utohexstr(uint64_t X, bool LowerCase = false) { char Buffer[17]; return utohex_buffer(X, Buffer+17, LowerCase); } static inline std::string utostr_32(uint32_t X, bool isNeg = false) { char Buffer[11]; char *BufPtr = Buffer+11; if (X == 0) *--BufPtr = '0'; // Handle special case... while (X) { #pragma prefast(suppress: 22102, "X runs down to zero before end of buffer") *--BufPtr = '0' + char(X % 10); X /= 10; } if (isNeg) *--BufPtr = '-'; // Add negative sign... return std::string(BufPtr, Buffer+11); } static inline std::string utostr(uint64_t X, bool isNeg = false) { char Buffer[21]; char *BufPtr = Buffer+21; if (X == 0) *--BufPtr = '0'; // Handle special case... while (X) { #pragma prefast(suppress: 22102, "X runs down to zero before end of buffer") *--BufPtr = '0' + char(X % 10); X /= 10; } if (isNeg) *--BufPtr = '-'; // Add negative sign... return std::string(BufPtr, Buffer+21); } static inline std::string itostr(int64_t X) { if (X < 0) return utostr(static_cast<uint64_t>(-X), true); else return utostr(static_cast<uint64_t>(X)); } /// StrInStrNoCase - Portable version of strcasestr. Locates the first /// occurrence of string 's1' in string 's2', ignoring case. Returns /// the offset of s2 in s1 or npos if s2 cannot be found. StringRef::size_type StrInStrNoCase(StringRef s1, StringRef s2); /// getToken - This function extracts one token from source, ignoring any /// leading characters that appear in the Delimiters string, and ending the /// token at any of the characters that appear in the Delimiters string. If /// there are no tokens in the source string, an empty string is returned. /// The function returns a pair containing the extracted token and the /// remaining tail string. std::pair<StringRef, StringRef> getToken(StringRef Source, StringRef Delimiters = " \t\n\v\f\r"); /// SplitString - Split up the specified string according to the specified /// delimiters, appending the result fragments to the output list. void SplitString(StringRef Source, SmallVectorImpl<StringRef> &OutFragments, StringRef Delimiters = " \t\n\v\f\r"); /// HashString - Hash function for strings. /// /// This is the Bernstein hash function. // // FIXME: Investigate whether a modified bernstein hash function performs // better: http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx // X*33+c -> X*33^c static inline unsigned HashString(StringRef Str, unsigned Result = 0) { for (StringRef::size_type i = 0, e = Str.size(); i != e; ++i) Result = Result * 33 + (unsigned char)Str[i]; return Result; } /// Returns the English suffix for an ordinal integer (-st, -nd, -rd, -th). static inline StringRef getOrdinalSuffix(unsigned Val) { // It is critically important that we do this perfectly for // user-written sequences with over 100 elements. switch (Val % 100) { case 11: case 12: case 13: return "th"; default: switch (Val % 10) { case 1: return "st"; case 2: return "nd"; case 3: return "rd"; default: return "th"; } } } template <typename IteratorT> inline std::string join_impl(IteratorT Begin, IteratorT End, StringRef Separator, std::input_iterator_tag) { std::string S; if (Begin == End) return S; S += (*Begin); while (++Begin != End) { S += Separator; S += (*Begin); } return S; } template <typename IteratorT> inline std::string join_impl(IteratorT Begin, IteratorT End, StringRef Separator, std::forward_iterator_tag) { std::string S; if (Begin == End) return S; size_t Len = (std::distance(Begin, End) - 1) * Separator.size(); for (IteratorT I = Begin; I != End; ++I) Len += (*Begin).size(); S.reserve(Len); S += (*Begin); while (++Begin != End) { S += Separator; S += (*Begin); } return S; } /// Joins the strings in the range [Begin, End), adding Separator between /// the elements. template <typename IteratorT> inline std::string join(IteratorT Begin, IteratorT End, StringRef Separator) { typedef typename std::iterator_traits<IteratorT>::iterator_category tag; return join_impl(Begin, End, Separator, tag()); } } // End llvm namespace #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ADT/PriorityQueue.h
//===- llvm/ADT/PriorityQueue.h - Priority queues ---------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PriorityQueue class. // //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_PRIORITYQUEUE_H #define LLVM_ADT_PRIORITYQUEUE_H #include <algorithm> #include <queue> namespace llvm { /// PriorityQueue - This class behaves like std::priority_queue and /// provides a few additional convenience functions. /// template<class T, class Sequence = std::vector<T>, class Compare = std::less<typename Sequence::value_type> > class PriorityQueue : public std::priority_queue<T, Sequence, Compare> { public: explicit PriorityQueue(const Compare &compare = Compare(), const Sequence &sequence = Sequence()) : std::priority_queue<T, Sequence, Compare>(compare, sequence) {} template<class Iterator> PriorityQueue(Iterator begin, Iterator end, const Compare &compare = Compare(), const Sequence &sequence = Sequence()) : std::priority_queue<T, Sequence, Compare>(begin, end, compare, sequence) {} /// erase_one - Erase one element from the queue, regardless of its /// position. This operation performs a linear search to find an element /// equal to t, but then uses all logarithmic-time algorithms to do /// the erase operation. /// void erase_one(const T &t) { // Linear-search to find the element. typename Sequence::size_type i = std::find(this->c.begin(), this->c.end(), t) - this->c.begin(); // Logarithmic-time heap bubble-up. while (i != 0) { typename Sequence::size_type parent = (i - 1) / 2; this->c[i] = this->c[parent]; i = parent; } // The element we want to remove is now at the root, so we can use // priority_queue's plain pop to remove it. this->pop(); } /// reheapify - If an element in the queue has changed in a way that /// affects its standing in the comparison function, the queue's /// internal state becomes invalid. Calling reheapify() resets the /// queue's state, making it valid again. This operation has time /// complexity proportional to the number of elements in the queue, /// so don't plan to use it a lot. /// void reheapify() { std::make_heap(this->c.begin(), this->c.end(), this->comp); } /// clear - Erase all elements from the queue. /// void clear() { this->c.clear(); } }; } // End llvm namespace #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ADT/iterator_range.h
//===- iterator_range.h - A range adaptor for iterators ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This provides a very simple, boring adaptor for a begin and end iterator /// into a range type. This should be used to build range views that work well /// with range based for loops and range based constructors. /// /// Note that code here follows more standards-based coding conventions as it /// is mirroring proposed interfaces for standardization. /// //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_ITERATOR_RANGE_H #define LLVM_ADT_ITERATOR_RANGE_H #include <utility> namespace llvm { /// \brief A range adaptor for a pair of iterators. /// /// This just wraps two iterators into a range-compatible interface. Nothing /// fancy at all. template <typename IteratorT> class iterator_range { IteratorT begin_iterator, end_iterator; public: iterator_range(IteratorT begin_iterator, IteratorT end_iterator) : begin_iterator(std::move(begin_iterator)), end_iterator(std::move(end_iterator)) {} IteratorT begin() const { return begin_iterator; } IteratorT end() const { return end_iterator; } }; /// \brief Convenience function for iterating over sub-ranges. /// /// This provides a bit of syntactic sugar to make using sub-ranges /// in for loops a bit easier. Analogous to std::make_pair(). template <class T> iterator_range<T> make_range(T x, T y) { return iterator_range<T>(std::move(x), std::move(y)); } template <typename T> iterator_range<T> make_range(std::pair<T, T> p) { return iterator_range<T>(std::move(p.first), std::move(p.second)); } } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ADT/DenseMap.h
//===- llvm/ADT/DenseMap.h - Dense probed hash table ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the DenseMap class. // //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_DENSEMAP_H #define LLVM_ADT_DENSEMAP_H #include "llvm/ADT/DenseMapInfo.h" #include "llvm/ADT/EpochTracker.h" #include "llvm/Support/AlignOf.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/PointerLikeTypeTraits.h" #include "llvm/Support/type_traits.h" #include <algorithm> #include <cassert> #include <climits> #include <cstddef> #include <cstring> #include <iterator> #include <new> #include <utility> namespace llvm { namespace detail { // We extend a pair to allow users to override the bucket type with their own // implementation without requiring two members. template <typename KeyT, typename ValueT> struct DenseMapPair : public std::pair<KeyT, ValueT> { KeyT &getFirst() { return std::pair<KeyT, ValueT>::first; } const KeyT &getFirst() const { return std::pair<KeyT, ValueT>::first; } ValueT &getSecond() { return std::pair<KeyT, ValueT>::second; } const ValueT &getSecond() const { return std::pair<KeyT, ValueT>::second; } }; } template < typename KeyT, typename ValueT, typename KeyInfoT = DenseMapInfo<KeyT>, typename Bucket = detail::DenseMapPair<KeyT, ValueT>, bool IsConst = false> class DenseMapIterator; template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT, typename BucketT> class DenseMapBase : public DebugEpochBase { public: typedef unsigned size_type; typedef KeyT key_type; typedef ValueT mapped_type; typedef BucketT value_type; typedef DenseMapIterator<KeyT, ValueT, KeyInfoT, BucketT> iterator; typedef DenseMapIterator<KeyT, ValueT, KeyInfoT, BucketT, true> const_iterator; inline iterator begin() { // When the map is empty, avoid the overhead of AdvancePastEmptyBuckets(). return empty() ? end() : iterator(getBuckets(), getBucketsEnd(), *this); } inline iterator end() { return iterator(getBucketsEnd(), getBucketsEnd(), *this, true); } inline const_iterator begin() const { return empty() ? end() : const_iterator(getBuckets(), getBucketsEnd(), *this); } inline const_iterator end() const { return const_iterator(getBucketsEnd(), getBucketsEnd(), *this, true); } bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const { return getNumEntries() == 0; } unsigned size() const { return getNumEntries(); } /// Grow the densemap so that it has at least Size buckets. Does not shrink void resize(size_type Size) { incrementEpoch(); if (Size > getNumBuckets()) grow(Size); } void clear() { incrementEpoch(); if (getNumEntries() == 0 && getNumTombstones() == 0) return; // If the capacity of the array is huge, and the # elements used is small, // shrink the array. if (getNumEntries() * 4 < getNumBuckets() && getNumBuckets() > 64) { shrink_and_clear(); return; } const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey(); unsigned NumEntries = getNumEntries(); for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) { if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey)) { if (!KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) { P->getSecond().~ValueT(); --NumEntries; } P->getFirst() = EmptyKey; } } assert(NumEntries == 0 && "Node count imbalance!"); setNumEntries(0); setNumTombstones(0); } /// Return 1 if the specified key is in the map, 0 otherwise. size_type count(const KeyT &Val) const { const BucketT *TheBucket; return LookupBucketFor(Val, TheBucket) ? 1 : 0; } iterator find(const KeyT &Val) { BucketT *TheBucket; if (LookupBucketFor(Val, TheBucket)) return iterator(TheBucket, getBucketsEnd(), *this, true); return end(); } const_iterator find(const KeyT &Val) const { const BucketT *TheBucket; if (LookupBucketFor(Val, TheBucket)) return const_iterator(TheBucket, getBucketsEnd(), *this, true); return end(); } /// Alternate version of find() which allows a different, and possibly /// less expensive, key type. /// The DenseMapInfo is responsible for supplying methods /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key /// type used. template<class LookupKeyT> iterator find_as(const LookupKeyT &Val) { BucketT *TheBucket; if (LookupBucketFor(Val, TheBucket)) return iterator(TheBucket, getBucketsEnd(), *this, true); return end(); } template<class LookupKeyT> const_iterator find_as(const LookupKeyT &Val) const { const BucketT *TheBucket; if (LookupBucketFor(Val, TheBucket)) return const_iterator(TheBucket, getBucketsEnd(), *this, true); return end(); } /// lookup - Return the entry for the specified key, or a default /// constructed value if no such entry exists. ValueT lookup(const KeyT &Val) const { const BucketT *TheBucket; if (LookupBucketFor(Val, TheBucket)) return TheBucket->getSecond(); return ValueT(); } // Inserts key,value pair into the map if the key isn't already in the map. // If the key is already in the map, it returns false and doesn't update the // value. std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) { return try_emplace(KV.first, KV.second); } // Inserts key,value pair into the map if the key isn't already in the map. // If the key is already in the map, it returns false and doesn't update the // value. std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) { return try_emplace(std::move(KV.first), std::move(KV.second)); } // Inserts key,value pair into the map if the key isn't already in the map. // The value is constructed in-place if the key is not in the map, otherwise // it is not moved. template <typename... Ts> std::pair<iterator, bool> try_emplace(KeyT &&Key, Ts &&... Args) { BucketT *TheBucket; if (LookupBucketFor(Key, TheBucket)) return std::make_pair(iterator(TheBucket, getBucketsEnd(), *this, true), false); // Already in map. // Otherwise, insert the new element. TheBucket = InsertIntoBucket(TheBucket, std::move(Key), std::forward<Ts>(Args)...); return std::make_pair(iterator(TheBucket, getBucketsEnd(), *this, true), true); } // Inserts key,value pair into the map if the key isn't already in the map. // The value is constructed in-place if the key is not in the map, otherwise // it is not moved. template <typename... Ts> std::pair<iterator, bool> try_emplace(const KeyT &Key, Ts &&... Args) { BucketT *TheBucket; if (LookupBucketFor(Key, TheBucket)) return std::make_pair(iterator(TheBucket, getBucketsEnd(), *this, true), false); // Already in map. // Otherwise, insert the new element. TheBucket = InsertIntoBucket(TheBucket, Key, std::forward<Ts>(Args)...); return std::make_pair(iterator(TheBucket, getBucketsEnd(), *this, true), true); } /// Alternate version of insert() which allows a different, and possibly /// less expensive, key type. /// The DenseMapInfo is responsible for supplying methods /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key /// type used. template <typename LookupKeyT> std::pair<iterator, bool> insert_as(std::pair<KeyT, ValueT> &&KV, const LookupKeyT &Val) { BucketT *TheBucket; if (LookupBucketFor(Val, TheBucket)) return std::make_pair(iterator(TheBucket, getBucketsEnd(), *this, true), false); // Already in map. // Otherwise, insert the new element. TheBucket = InsertIntoBucketWithLookup(TheBucket, std::move(KV.first), std::move(KV.second), Val); return std::make_pair(iterator(TheBucket, getBucketsEnd(), *this, true), true); } /// insert - Range insertion of pairs. template<typename InputIt> void insert(InputIt I, InputIt E) { for (; I != E; ++I) insert(*I); } bool erase(const KeyT &Val) { BucketT *TheBucket; if (!LookupBucketFor(Val, TheBucket)) return false; // not in map. TheBucket->getSecond().~ValueT(); TheBucket->getFirst() = getTombstoneKey(); decrementNumEntries(); incrementNumTombstones(); return true; } void erase(iterator I) { BucketT *TheBucket = &*I; TheBucket->getSecond().~ValueT(); TheBucket->getFirst() = getTombstoneKey(); decrementNumEntries(); incrementNumTombstones(); } value_type& FindAndConstruct(const KeyT &Key) { BucketT *TheBucket; if (LookupBucketFor(Key, TheBucket)) return *TheBucket; return *InsertIntoBucket(TheBucket, Key); } ValueT &operator[](const KeyT &Key) { return FindAndConstruct(Key).second; } value_type& FindAndConstruct(KeyT &&Key) { BucketT *TheBucket; if (LookupBucketFor(Key, TheBucket)) return *TheBucket; return *InsertIntoBucket(TheBucket, std::move(Key)); } ValueT &operator[](KeyT &&Key) { return FindAndConstruct(std::move(Key)).second; } /// isPointerIntoBucketsArray - Return true if the specified pointer points /// somewhere into the DenseMap's array of buckets (i.e. either to a key or /// value in the DenseMap). bool isPointerIntoBucketsArray(const void *Ptr) const { return Ptr >= getBuckets() && Ptr < getBucketsEnd(); } /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets /// array. In conjunction with the previous method, this can be used to /// determine whether an insertion caused the DenseMap to reallocate. const void *getPointerIntoBucketsArray() const { return getBuckets(); } protected: DenseMapBase() = default; void destroyAll() { if (getNumBuckets() == 0) // Nothing to do. return; const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey(); for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) { if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) && !KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) P->getSecond().~ValueT(); P->getFirst().~KeyT(); } } void initEmpty() { setNumEntries(0); setNumTombstones(0); assert((getNumBuckets() & (getNumBuckets()-1)) == 0 && "# initial buckets must be a power of two!"); const KeyT EmptyKey = getEmptyKey(); for (BucketT *B = getBuckets(), *E = getBucketsEnd(); B != E; ++B) new (&B->getFirst()) KeyT(EmptyKey); } void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd) { initEmpty(); // Insert all the old elements. const KeyT EmptyKey = getEmptyKey(); const KeyT TombstoneKey = getTombstoneKey(); for (BucketT *B = OldBucketsBegin, *E = OldBucketsEnd; B != E; ++B) { if (!KeyInfoT::isEqual(B->getFirst(), EmptyKey) && !KeyInfoT::isEqual(B->getFirst(), TombstoneKey)) { // Insert the key/value into the new table. BucketT *DestBucket; bool FoundVal = LookupBucketFor(B->getFirst(), DestBucket); (void)FoundVal; // silence warning. assert(!FoundVal && "Key already in new map?"); DestBucket->getFirst() = std::move(B->getFirst()); new (&DestBucket->getSecond()) ValueT(std::move(B->getSecond())); incrementNumEntries(); // Free the value. B->getSecond().~ValueT(); } B->getFirst().~KeyT(); } } template <typename OtherBaseT> void copyFrom( const DenseMapBase<OtherBaseT, KeyT, ValueT, KeyInfoT, BucketT> &other) { assert(&other != this); assert(getNumBuckets() == other.getNumBuckets()); setNumEntries(other.getNumEntries()); setNumTombstones(other.getNumTombstones()); if (isPodLike<KeyT>::value && isPodLike<ValueT>::value) memcpy(reinterpret_cast<void *>(getBuckets()), other.getBuckets(), getNumBuckets() * sizeof(BucketT)); else for (size_t i = 0; i < getNumBuckets(); ++i) { new (&getBuckets()[i].getFirst()) KeyT(other.getBuckets()[i].getFirst()); if (!KeyInfoT::isEqual(getBuckets()[i].getFirst(), getEmptyKey()) && !KeyInfoT::isEqual(getBuckets()[i].getFirst(), getTombstoneKey())) new (&getBuckets()[i].getSecond()) ValueT(other.getBuckets()[i].getSecond()); } } static unsigned getHashValue(const KeyT &Val) { return KeyInfoT::getHashValue(Val); } template<typename LookupKeyT> static unsigned getHashValue(const LookupKeyT &Val) { return KeyInfoT::getHashValue(Val); } static const KeyT getEmptyKey() { return KeyInfoT::getEmptyKey(); } static const KeyT getTombstoneKey() { return KeyInfoT::getTombstoneKey(); } private: unsigned getNumEntries() const { return static_cast<const DerivedT *>(this)->getNumEntries(); } void setNumEntries(unsigned Num) { static_cast<DerivedT *>(this)->setNumEntries(Num); } void incrementNumEntries() { setNumEntries(getNumEntries() + 1); } void decrementNumEntries() { setNumEntries(getNumEntries() - 1); } unsigned getNumTombstones() const { return static_cast<const DerivedT *>(this)->getNumTombstones(); } void setNumTombstones(unsigned Num) { static_cast<DerivedT *>(this)->setNumTombstones(Num); } void incrementNumTombstones() { setNumTombstones(getNumTombstones() + 1); } void decrementNumTombstones() { setNumTombstones(getNumTombstones() - 1); } const BucketT *getBuckets() const { return static_cast<const DerivedT *>(this)->getBuckets(); } BucketT *getBuckets() { return static_cast<DerivedT *>(this)->getBuckets(); } unsigned getNumBuckets() const { return static_cast<const DerivedT *>(this)->getNumBuckets(); } BucketT *getBucketsEnd() { return getBuckets() + getNumBuckets(); } const BucketT *getBucketsEnd() const { return getBuckets() + getNumBuckets(); } void grow(unsigned AtLeast) { static_cast<DerivedT *>(this)->grow(AtLeast); } void shrink_and_clear() { static_cast<DerivedT *>(this)->shrink_and_clear(); } template <typename KeyArg, typename... ValueArgs> BucketT *InsertIntoBucket(BucketT *TheBucket, KeyArg &&Key, ValueArgs &&... Values) { TheBucket = InsertIntoBucketImpl(Key, Key, TheBucket); TheBucket->getFirst() = std::forward<KeyArg>(Key); ::new (&TheBucket->getSecond()) ValueT(std::forward<ValueArgs>(Values)...); return TheBucket; } template <typename LookupKeyT> BucketT *InsertIntoBucketWithLookup(BucketT *TheBucket, KeyT &&Key, ValueT &&Value, LookupKeyT &Lookup) { TheBucket = InsertIntoBucketImpl(Key, Lookup, TheBucket); TheBucket->getFirst() = std::move(Key); ::new (&TheBucket->getSecond()) ValueT(std::move(Value)); return TheBucket; } template <typename LookupKeyT> BucketT *InsertIntoBucketImpl(const KeyT &Key, const LookupKeyT &Lookup, BucketT *TheBucket) { incrementEpoch(); // If the load of the hash table is more than 3/4, or if fewer than 1/8 of // the buckets are empty (meaning that many are filled with tombstones), // grow the table. // // The later case is tricky. For example, if we had one empty bucket with // tons of tombstones, failing lookups (e.g. for insertion) would have to // probe almost the entire table until it found the empty bucket. If the // table completely filled with tombstones, no lookup would ever succeed, // causing infinite loops in lookup. unsigned NewNumEntries = getNumEntries() + 1; unsigned NumBuckets = getNumBuckets(); if (LLVM_UNLIKELY(NewNumEntries * 4 >= NumBuckets * 3)) { this->grow(NumBuckets * 2); LookupBucketFor(Key, TheBucket); NumBuckets = getNumBuckets(); } else if (LLVM_UNLIKELY(NumBuckets-(NewNumEntries+getNumTombstones()) <= NumBuckets/8)) { this->grow(NumBuckets); LookupBucketFor(Key, TheBucket); } assert(TheBucket); // Only update the state after we've grown our bucket space appropriately // so that when growing buckets we have self-consistent entry count. incrementNumEntries(); // If we are writing over a tombstone, remember this. const KeyT EmptyKey = getEmptyKey(); if (!KeyInfoT::isEqual(TheBucket->getFirst(), EmptyKey)) decrementNumTombstones(); return TheBucket; } /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in /// FoundBucket. If the bucket contains the key and a value, this returns /// true, otherwise it returns a bucket with an empty marker or tombstone and /// returns false. template<typename LookupKeyT> bool LookupBucketFor(const LookupKeyT &Val, const BucketT *&FoundBucket) const { const BucketT *BucketsPtr = getBuckets(); const unsigned NumBuckets = getNumBuckets(); if (NumBuckets == 0) { FoundBucket = nullptr; return false; } // FoundTombstone - Keep track of whether we find a tombstone while probing. const BucketT *FoundTombstone = nullptr; const KeyT EmptyKey = getEmptyKey(); const KeyT TombstoneKey = getTombstoneKey(); assert(!KeyInfoT::isEqual(Val, EmptyKey) && !KeyInfoT::isEqual(Val, TombstoneKey) && "Empty/Tombstone value shouldn't be inserted into map!"); unsigned BucketNo = getHashValue(Val) & (NumBuckets-1); unsigned ProbeAmt = 1; while (1) { const BucketT *ThisBucket = BucketsPtr + BucketNo; // Found Val's bucket? If so, return it. if (LLVM_LIKELY(KeyInfoT::isEqual(Val, ThisBucket->getFirst()))) { FoundBucket = ThisBucket; return true; } // If we found an empty bucket, the key doesn't exist in the set. // Insert it and return the default value. if (LLVM_LIKELY(KeyInfoT::isEqual(ThisBucket->getFirst(), EmptyKey))) { // If we've already seen a tombstone while probing, fill it in instead // of the empty bucket we eventually probed to. FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket; return false; } // If this is a tombstone, remember it. If Val ends up not in the map, we // prefer to return it than something that would require more probing. if (KeyInfoT::isEqual(ThisBucket->getFirst(), TombstoneKey) && !FoundTombstone) FoundTombstone = ThisBucket; // Remember the first tombstone found. // Otherwise, it's a hash collision or a tombstone, continue quadratic // probing. BucketNo += ProbeAmt++; BucketNo &= (NumBuckets-1); } } template <typename LookupKeyT> bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) { const BucketT *ConstFoundBucket; bool Result = const_cast<const DenseMapBase *>(this) ->LookupBucketFor(Val, ConstFoundBucket); FoundBucket = const_cast<BucketT *>(ConstFoundBucket); return Result; } public: /// Return the approximate size (in bytes) of the actual map. /// This is just the raw memory used by DenseMap. /// If entries are pointers to objects, the size of the referenced objects /// are not included. size_t getMemorySize() const { return getNumBuckets() * sizeof(BucketT); } }; template <typename KeyT, typename ValueT, typename KeyInfoT = DenseMapInfo<KeyT>, typename BucketT = detail::DenseMapPair<KeyT, ValueT>> class DenseMap : public DenseMapBase<DenseMap<KeyT, ValueT, KeyInfoT, BucketT>, KeyT, ValueT, KeyInfoT, BucketT> { // Lift some types from the dependent base class into this class for // simplicity of referring to them. typedef DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT> BaseT; friend class DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT>; BucketT *Buckets; unsigned NumEntries; unsigned NumTombstones; unsigned NumBuckets; public: explicit DenseMap(unsigned NumInitBuckets = 0) { init(NumInitBuckets); } DenseMap(const DenseMap &other) : BaseT() { init(0); copyFrom(other); } DenseMap(DenseMap &&other) : BaseT() { init(0); swap(other); } template<typename InputIt> DenseMap(const InputIt &I, const InputIt &E) { init(NextPowerOf2(std::distance(I, E))); this->insert(I, E); } ~DenseMap() { this->destroyAll(); operator delete(Buckets); } void swap(DenseMap& RHS) { this->incrementEpoch(); RHS.incrementEpoch(); std::swap(Buckets, RHS.Buckets); std::swap(NumEntries, RHS.NumEntries); std::swap(NumTombstones, RHS.NumTombstones); std::swap(NumBuckets, RHS.NumBuckets); } DenseMap& operator=(const DenseMap& other) { if (&other != this) copyFrom(other); return *this; } DenseMap& operator=(DenseMap &&other) { this->destroyAll(); operator delete(Buckets); init(0); swap(other); return *this; } void copyFrom(const DenseMap& other) { this->destroyAll(); operator delete(Buckets); if (allocateBuckets(other.NumBuckets)) { this->BaseT::copyFrom(other); } else { NumEntries = 0; NumTombstones = 0; } } void init(unsigned InitBuckets) { if (allocateBuckets(InitBuckets)) { this->BaseT::initEmpty(); } else { NumEntries = 0; NumTombstones = 0; } } void grow(unsigned AtLeast) { unsigned OldNumBuckets = NumBuckets; BucketT *OldBuckets = Buckets; allocateBuckets(std::max<unsigned>(64, static_cast<unsigned>(NextPowerOf2(AtLeast-1)))); assert(Buckets); if (!OldBuckets) { this->BaseT::initEmpty(); return; } this->moveFromOldBuckets(OldBuckets, OldBuckets+OldNumBuckets); // Free the old table. operator delete(OldBuckets); } void shrink_and_clear() { unsigned OldNumEntries = NumEntries; this->destroyAll(); // Reduce the number of buckets. unsigned NewNumBuckets = 0; if (OldNumEntries) NewNumBuckets = std::max(64, 1 << (Log2_32_Ceil(OldNumEntries) + 1)); if (NewNumBuckets == NumBuckets) { this->BaseT::initEmpty(); return; } operator delete(Buckets); init(NewNumBuckets); } private: unsigned getNumEntries() const { return NumEntries; } void setNumEntries(unsigned Num) { NumEntries = Num; } unsigned getNumTombstones() const { return NumTombstones; } void setNumTombstones(unsigned Num) { NumTombstones = Num; } BucketT *getBuckets() const { return Buckets; } unsigned getNumBuckets() const { return NumBuckets; } bool allocateBuckets(unsigned Num) { // HLSL Change Starts - reorder statement to clean up properly on OOM if (Num == 0) { NumBuckets = 0; Buckets = nullptr; return false; } Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) * Num)); NumBuckets = Num; // HLSL Change Ends - reorder statement to clean up properly on OOM return true; } }; template <typename KeyT, typename ValueT, unsigned InlineBuckets = 4, typename KeyInfoT = DenseMapInfo<KeyT>, typename BucketT = detail::DenseMapPair<KeyT, ValueT>> class SmallDenseMap : public DenseMapBase< SmallDenseMap<KeyT, ValueT, InlineBuckets, KeyInfoT, BucketT>, KeyT, ValueT, KeyInfoT, BucketT> { // Lift some types from the dependent base class into this class for // simplicity of referring to them. typedef DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT> BaseT; friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT>; unsigned Small : 1; unsigned NumEntries : 31; unsigned NumTombstones; struct LargeRep { BucketT *Buckets; unsigned NumBuckets; }; /// A "union" of an inline bucket array and the struct representing /// a large bucket. This union will be discriminated by the 'Small' bit. AlignedCharArrayUnion<BucketT[InlineBuckets], LargeRep> storage; public: explicit SmallDenseMap(unsigned NumInitBuckets = 0) { init(NumInitBuckets); } SmallDenseMap(const SmallDenseMap &other) : BaseT() { init(0); copyFrom(other); } SmallDenseMap(SmallDenseMap &&other) : BaseT() { init(0); swap(other); } template<typename InputIt> SmallDenseMap(const InputIt &I, const InputIt &E) { init(NextPowerOf2(std::distance(I, E))); this->insert(I, E); } ~SmallDenseMap() { this->destroyAll(); deallocateBuckets(); } void swap(SmallDenseMap& RHS) { unsigned TmpNumEntries = RHS.NumEntries; RHS.NumEntries = NumEntries; NumEntries = TmpNumEntries; std::swap(NumTombstones, RHS.NumTombstones); const KeyT EmptyKey = this->getEmptyKey(); const KeyT TombstoneKey = this->getTombstoneKey(); if (Small && RHS.Small) { // If we're swapping inline bucket arrays, we have to cope with some of // the tricky bits of DenseMap's storage system: the buckets are not // fully initialized. Thus we swap every key, but we may have // a one-directional move of the value. for (unsigned i = 0, e = InlineBuckets; i != e; ++i) { BucketT *LHSB = &getInlineBuckets()[i], *RHSB = &RHS.getInlineBuckets()[i]; bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->getFirst(), EmptyKey) && !KeyInfoT::isEqual(LHSB->getFirst(), TombstoneKey)); bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->getFirst(), EmptyKey) && !KeyInfoT::isEqual(RHSB->getFirst(), TombstoneKey)); if (hasLHSValue && hasRHSValue) { // Swap together if we can... std::swap(*LHSB, *RHSB); continue; } // Swap separately and handle any assymetry. std::swap(LHSB->getFirst(), RHSB->getFirst()); if (hasLHSValue) { new (&RHSB->getSecond()) ValueT(std::move(LHSB->getSecond())); LHSB->getSecond().~ValueT(); } else if (hasRHSValue) { new (&LHSB->getSecond()) ValueT(std::move(RHSB->getSecond())); RHSB->getSecond().~ValueT(); } } return; } if (!Small && !RHS.Small) { std::swap(getLargeRep()->Buckets, RHS.getLargeRep()->Buckets); std::swap(getLargeRep()->NumBuckets, RHS.getLargeRep()->NumBuckets); return; } SmallDenseMap &SmallSide = Small ? *this : RHS; SmallDenseMap &LargeSide = Small ? RHS : *this; // First stash the large side's rep and move the small side across. LargeRep TmpRep = std::move(*LargeSide.getLargeRep()); LargeSide.getLargeRep()->~LargeRep(); LargeSide.Small = true; // This is similar to the standard move-from-old-buckets, but the bucket // count hasn't actually rotated in this case. So we have to carefully // move construct the keys and values into their new locations, but there // is no need to re-hash things. for (unsigned i = 0, e = InlineBuckets; i != e; ++i) { BucketT *NewB = &LargeSide.getInlineBuckets()[i], *OldB = &SmallSide.getInlineBuckets()[i]; new (&NewB->getFirst()) KeyT(std::move(OldB->getFirst())); OldB->getFirst().~KeyT(); if (!KeyInfoT::isEqual(NewB->getFirst(), EmptyKey) && !KeyInfoT::isEqual(NewB->getFirst(), TombstoneKey)) { new (&NewB->getSecond()) ValueT(std::move(OldB->getSecond())); OldB->getSecond().~ValueT(); } } // The hard part of moving the small buckets across is done, just move // the TmpRep into its new home. SmallSide.Small = false; new (SmallSide.getLargeRep()) LargeRep(std::move(TmpRep)); } SmallDenseMap& operator=(const SmallDenseMap& other) { if (&other != this) copyFrom(other); return *this; } SmallDenseMap& operator=(SmallDenseMap &&other) { this->destroyAll(); deallocateBuckets(); init(0); swap(other); return *this; } void copyFrom(const SmallDenseMap& other) { this->destroyAll(); deallocateBuckets(); Small = true; if (other.getNumBuckets() > InlineBuckets) { Small = false; new (getLargeRep()) LargeRep(allocateBuckets(other.getNumBuckets())); } this->BaseT::copyFrom(other); } void init(unsigned InitBuckets) { Small = true; if (InitBuckets > InlineBuckets) { Small = false; new (getLargeRep()) LargeRep(allocateBuckets(InitBuckets)); } this->BaseT::initEmpty(); } void grow(unsigned AtLeast) { if (AtLeast >= InlineBuckets) AtLeast = std::max<unsigned>(64, NextPowerOf2(AtLeast-1)); if (Small) { if (AtLeast < InlineBuckets) return; // Nothing to do. // First move the inline buckets into a temporary storage. AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage; BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer); BucketT *TmpEnd = TmpBegin; // Loop over the buckets, moving non-empty, non-tombstones into the // temporary storage. Have the loop move the TmpEnd forward as it goes. const KeyT EmptyKey = this->getEmptyKey(); const KeyT TombstoneKey = this->getTombstoneKey(); LargeRep LR(allocateBuckets(AtLeast)); // HLSL Change - used to be at 'Now make', but let's fail alloc before invoking .dtors for (BucketT *P = getBuckets(), *E = P + InlineBuckets; P != E; ++P) { if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) && !KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) { assert(size_t(TmpEnd - TmpBegin) < InlineBuckets && "Too many inline buckets!"); new (&TmpEnd->getFirst()) KeyT(std::move(P->getFirst())); new (&TmpEnd->getSecond()) ValueT(std::move(P->getSecond())); ++TmpEnd; P->getSecond().~ValueT(); } P->getFirst().~KeyT(); } // Now make this map use the large rep, and move all the entries back // into it. *getLargeRepForTransition() = LR; // HLSL Change - assign allocated & init'ed block instead Small = false; // HLSL Change - used to be prior to allocation this->moveFromOldBuckets(TmpBegin, TmpEnd); return; } LargeRep OldRep = std::move(*getLargeRep()); getLargeRep()->~LargeRep(); if (AtLeast <= InlineBuckets) { Small = true; } else { new (getLargeRep()) LargeRep(allocateBuckets(AtLeast)); } this->moveFromOldBuckets(OldRep.Buckets, OldRep.Buckets+OldRep.NumBuckets); // Free the old table. operator delete(OldRep.Buckets); } void shrink_and_clear() { unsigned OldSize = this->size(); this->destroyAll(); // Reduce the number of buckets. unsigned NewNumBuckets = 0; if (OldSize) { NewNumBuckets = 1 << (Log2_32_Ceil(OldSize) + 1); if (NewNumBuckets > InlineBuckets && NewNumBuckets < 64u) NewNumBuckets = 64; } if ((Small && NewNumBuckets <= InlineBuckets) || (!Small && NewNumBuckets == getLargeRep()->NumBuckets)) { this->BaseT::initEmpty(); return; } deallocateBuckets(); init(NewNumBuckets); } private: unsigned getNumEntries() const { return NumEntries; } void setNumEntries(unsigned Num) { assert(Num < INT_MAX && "Cannot support more than INT_MAX entries"); NumEntries = Num; } unsigned getNumTombstones() const { return NumTombstones; } void setNumTombstones(unsigned Num) { NumTombstones = Num; } const BucketT *getInlineBuckets() const { assert(Small); // Note that this cast does not violate aliasing rules as we assert that // the memory's dynamic type is the small, inline bucket buffer, and the // 'storage.buffer' static type is 'char *'. return reinterpret_cast<const BucketT *>(storage.buffer); } BucketT *getInlineBuckets() { return const_cast<BucketT *>( const_cast<const SmallDenseMap *>(this)->getInlineBuckets()); } const LargeRep *getLargeRep() const { assert(!Small); // Note, same rule about aliasing as with getInlineBuckets. return reinterpret_cast<const LargeRep *>(storage.buffer); } LargeRep *getLargeRep() { return const_cast<LargeRep *>( const_cast<const SmallDenseMap *>(this)->getLargeRep()); } // HLSL Change Starts - avoid Small check, as we are in the process of transitioning const LargeRep *getLargeRepForTransition() const { // Note, same rule about aliasing as with getInlineBuckets. return reinterpret_cast<const LargeRep *>(storage.buffer); } LargeRep *getLargeRepForTransition() { return const_cast<LargeRep *>( const_cast<const SmallDenseMap *>(this)->getLargeRepForTransition()); } // HLSL Change Ends const BucketT *getBuckets() const { return Small ? getInlineBuckets() : getLargeRep()->Buckets; } BucketT *getBuckets() { return const_cast<BucketT *>( const_cast<const SmallDenseMap *>(this)->getBuckets()); } unsigned getNumBuckets() const { return Small ? InlineBuckets : getLargeRep()->NumBuckets; } void deallocateBuckets() { if (Small) return; operator delete(getLargeRep()->Buckets); getLargeRep()->~LargeRep(); } LargeRep allocateBuckets(unsigned Num) { assert(Num > InlineBuckets && "Must allocate more buckets than are inline"); LargeRep Rep = { static_cast<BucketT*>(operator new(sizeof(BucketT) * Num)), Num }; return Rep; } }; template <typename KeyT, typename ValueT, typename KeyInfoT, typename Bucket, bool IsConst> class DenseMapIterator : DebugEpochBase::HandleBase { typedef DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true> ConstIterator; friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true>; friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, false>; public: typedef ptrdiff_t difference_type; typedef typename std::conditional<IsConst, const Bucket, Bucket>::type value_type; typedef value_type *pointer; typedef value_type &reference; typedef std::forward_iterator_tag iterator_category; private: pointer Ptr, End; public: DenseMapIterator() : Ptr(nullptr), End(nullptr) {} DenseMapIterator(pointer Pos, pointer E, const DebugEpochBase &Epoch, bool NoAdvance = false) : DebugEpochBase::HandleBase(&Epoch), Ptr(Pos), End(E) { assert(isHandleInSync() && "invalid construction!"); if (!NoAdvance) AdvancePastEmptyBuckets(); } // Converting ctor from non-const iterators to const iterators. SFINAE'd out // for const iterator destinations so it doesn't end up as a user defined copy // constructor. template <bool IsConstSrc, typename = typename std::enable_if<!IsConstSrc && IsConst>::type> DenseMapIterator( const DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, IsConstSrc> &I) : DebugEpochBase::HandleBase(I), Ptr(I.Ptr), End(I.End) {} reference operator*() const { assert(isHandleInSync() && "invalid iterator access!"); return *Ptr; } pointer operator->() const { assert(isHandleInSync() && "invalid iterator access!"); return Ptr; } bool operator==(const ConstIterator &RHS) const { assert((!Ptr || isHandleInSync()) && "handle not in sync!"); assert((!RHS.Ptr || RHS.isHandleInSync()) && "handle not in sync!"); assert(getEpochAddress() == RHS.getEpochAddress() && "comparing incomparable iterators!"); return Ptr == RHS.Ptr; } bool operator!=(const ConstIterator &RHS) const { assert((!Ptr || isHandleInSync()) && "handle not in sync!"); assert((!RHS.Ptr || RHS.isHandleInSync()) && "handle not in sync!"); assert(getEpochAddress() == RHS.getEpochAddress() && "comparing incomparable iterators!"); return Ptr != RHS.Ptr; } inline DenseMapIterator& operator++() { // Preincrement assert(isHandleInSync() && "invalid iterator access!"); ++Ptr; AdvancePastEmptyBuckets(); return *this; } DenseMapIterator operator++(int) { // Postincrement assert(isHandleInSync() && "invalid iterator access!"); DenseMapIterator tmp = *this; ++*this; return tmp; } private: void AdvancePastEmptyBuckets() { const KeyT Empty = KeyInfoT::getEmptyKey(); const KeyT Tombstone = KeyInfoT::getTombstoneKey(); while (Ptr != End && (KeyInfoT::isEqual(Ptr->getFirst(), Empty) || KeyInfoT::isEqual(Ptr->getFirst(), Tombstone))) ++Ptr; } }; template<typename KeyT, typename ValueT, typename KeyInfoT> static inline size_t capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT> &X) { return X.getMemorySize(); } } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ADT/SmallVector.h
//===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the SmallVector class. // //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_SMALLVECTOR_H #define LLVM_ADT_SMALLVECTOR_H #include "llvm/ADT/iterator_range.h" #include "llvm/Support/AlignOf.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/type_traits.h" #include <algorithm> #include <cassert> #include <cstddef> #include <cstdlib> #include <cstring> #include <initializer_list> #include <iterator> #include <memory> namespace llvm { /// This is all the non-templated stuff common to all SmallVectors. class SmallVectorBase { protected: void *BeginX, *EndX, *CapacityX; protected: SmallVectorBase(void *FirstEl, size_t Size) : BeginX(FirstEl), EndX(FirstEl), CapacityX((char*)FirstEl+Size) {} /// This is an implementation of the grow() method which only works /// on POD-like data types and is out of line to reduce code duplication. void grow_pod(void *FirstEl, size_t MinSizeInBytes, size_t TSize); public: /// This returns size()*sizeof(T). size_t size_in_bytes() const { return size_t((char*)EndX - (char*)BeginX); } /// capacity_in_bytes - This returns capacity()*sizeof(T). size_t capacity_in_bytes() const { return size_t((char*)CapacityX - (char*)BeginX); } bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const { return BeginX == EndX; } }; template <typename T, unsigned N> struct SmallVectorStorage; /// This is the part of SmallVectorTemplateBase which does not depend on whether /// the type T is a POD. The extra dummy template argument is used by ArrayRef /// to avoid unnecessarily requiring T to be complete. template <typename T, typename = void> class SmallVectorTemplateCommon : public SmallVectorBase { private: template <typename, unsigned> friend struct SmallVectorStorage; // Allocate raw space for N elements of type T. If T has a ctor or dtor, we // don't want it to be automatically run, so we need to represent the space as // something else. Use an array of char of sufficient alignment. typedef llvm::AlignedCharArrayUnion<T> U; U FirstEl; // Space after 'FirstEl' is clobbered, do not add any instance vars after it. protected: SmallVectorTemplateCommon(size_t Size) : SmallVectorBase(&FirstEl, Size) {} void grow_pod(size_t MinSizeInBytes, size_t TSize) { SmallVectorBase::grow_pod(&FirstEl, MinSizeInBytes, TSize); } /// Return true if this is a smallvector which has not had dynamic /// memory allocated for it. bool isSmall() const { return BeginX == static_cast<const void*>(&FirstEl); } /// Put this vector in a state of being small. void resetToSmall() { BeginX = EndX = CapacityX = &FirstEl; } void setEnd(T *P) { this->EndX = P; } public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T value_type; typedef T *iterator; typedef const T *const_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; typedef T &reference; typedef const T &const_reference; typedef T *pointer; typedef const T *const_pointer; // forward iterator creation methods. iterator begin() { return (iterator)this->BeginX; } const_iterator begin() const { return (const_iterator)this->BeginX; } iterator end() { return (iterator)this->EndX; } const_iterator end() const { return (const_iterator)this->EndX; } protected: iterator capacity_ptr() { return (iterator)this->CapacityX; } const_iterator capacity_ptr() const { return (const_iterator)this->CapacityX;} public: // reverse iterator creation methods. reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin());} size_type size() const { return end()-begin(); } size_type max_size() const { return size_type(-1) / sizeof(T); } /// Return the total number of elements in the currently allocated buffer. size_t capacity() const { return capacity_ptr() - begin(); } /// Return a pointer to the vector's buffer, even if empty(). pointer data() { return pointer(begin()); } /// Return a pointer to the vector's buffer, even if empty(). const_pointer data() const { return const_pointer(begin()); } reference operator[](size_type idx) { assert(idx < size()); return begin()[idx]; } const_reference operator[](size_type idx) const { assert(idx < size()); return begin()[idx]; } reference front() { assert(!empty()); return begin()[0]; } const_reference front() const { assert(!empty()); return begin()[0]; } reference back() { assert(!empty()); return end()[-1]; } const_reference back() const { assert(!empty()); return end()[-1]; } }; /// SmallVectorTemplateBase<isPodLike = false> - This is where we put method /// implementations that are designed to work with non-POD-like T's. template <typename T, bool isPodLike> class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> { protected: SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {} static void destroy_range(T *S, T *E) { while (S != E) { --E; E->~T(); } } /// Use move-assignment to move the range [I, E) onto the /// objects starting with "Dest". This is just <memory>'s /// std::move, but not all stdlibs actually provide that. template<typename It1, typename It2> static It2 move(It1 I, It1 E, It2 Dest) { for (; I != E; ++I, ++Dest) *Dest = ::std::move(*I); return Dest; } /// Use move-assignment to move the range /// [I, E) onto the objects ending at "Dest", moving objects /// in reverse order. This is just <algorithm>'s /// std::move_backward, but not all stdlibs actually provide that. template<typename It1, typename It2> static It2 move_backward(It1 I, It1 E, It2 Dest) { while (I != E) *--Dest = ::std::move(*--E); return Dest; } /// Move the range [I, E) into the uninitialized memory starting with "Dest", /// constructing elements as needed. template<typename It1, typename It2> static void uninitialized_move(It1 I, It1 E, It2 Dest) { for (; I != E; ++I, ++Dest) ::new ((void*) &*Dest) T(::std::move(*I)); } /// Copy the range [I, E) onto the uninitialized memory starting with "Dest", /// constructing elements as needed. template<typename It1, typename It2> static void uninitialized_copy(It1 I, It1 E, It2 Dest) { std::uninitialized_copy(I, E, Dest); } /// Grow the allocated memory (without initializing new elements), doubling /// the size of the allocated memory. Guarantees space for at least one more /// element, or MinSize more elements if specified. void grow(size_t MinSize = 0); public: void push_back(const T &Elt) { if (LLVM_UNLIKELY(this->EndX >= this->CapacityX)) this->grow(); ::new ((void*) this->end()) T(Elt); this->setEnd(this->end()+1); } void push_back(T &&Elt) { if (LLVM_UNLIKELY(this->EndX >= this->CapacityX)) this->grow(); ::new ((void*) this->end()) T(::std::move(Elt)); this->setEnd(this->end()+1); } void pop_back() { this->setEnd(this->end()-1); this->end()->~T(); } }; // Define this out-of-line to dissuade the C++ compiler from inlining it. template <typename T, bool isPodLike> void SmallVectorTemplateBase<T, isPodLike>::grow(size_t MinSize) { size_t CurCapacity = this->capacity(); size_t CurSize = this->size(); // Always grow, even from zero. size_t NewCapacity = size_t(NextPowerOf2(CurCapacity+2)); if (NewCapacity < MinSize) NewCapacity = MinSize; T *NewElts = (T*)new char[NewCapacity*sizeof(T)]; // HLSL Change: Use overridable operator new // Move the elements over. this->uninitialized_move(this->begin(), this->end(), NewElts); // Destroy the original elements. destroy_range(this->begin(), this->end()); // If this wasn't grown from the inline copy, deallocate the old space. if (!this->isSmall()) delete[] (char*)this->begin(); // HLSL Change: Use overridable operator delete this->setEnd(NewElts+CurSize); this->BeginX = NewElts; this->CapacityX = this->begin()+NewCapacity; } /// SmallVectorTemplateBase<isPodLike = true> - This is where we put method /// implementations that are designed to work with POD-like T's. template <typename T> class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> { protected: SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {} // No need to do a destroy loop for POD's. static void destroy_range(T *, T *) {} /// Use move-assignment to move the range [I, E) onto the /// objects starting with "Dest". For PODs, this is just memcpy. template<typename It1, typename It2> static It2 move(It1 I, It1 E, It2 Dest) { return ::std::copy(I, E, Dest); } /// Use move-assignment to move the range [I, E) onto the objects ending at /// "Dest", moving objects in reverse order. template<typename It1, typename It2> static It2 move_backward(It1 I, It1 E, It2 Dest) { return ::std::copy_backward(I, E, Dest); } /// Move the range [I, E) onto the uninitialized memory /// starting with "Dest", constructing elements into it as needed. template<typename It1, typename It2> static void uninitialized_move(It1 I, It1 E, It2 Dest) { // Just do a copy. uninitialized_copy(I, E, Dest); } /// Copy the range [I, E) onto the uninitialized memory /// starting with "Dest", constructing elements into it as needed. template<typename It1, typename It2> static void uninitialized_copy(It1 I, It1 E, It2 Dest) { // Arbitrary iterator types; just use the basic implementation. std::uninitialized_copy(I, E, Dest); } /// Copy the range [I, E) onto the uninitialized memory /// starting with "Dest", constructing elements into it as needed. template <typename T1, typename T2> static void uninitialized_copy( T1 *I, T1 *E, T2 *Dest, typename std::enable_if<std::is_same<typename std::remove_const<T1>::type, T2>::value>::type * = nullptr) { // Use memcpy for PODs iterated by pointers (which includes SmallVector // iterators): std::uninitialized_copy optimizes to memmove, but we can // use memcpy here. Note that I and E are iterators and thus might be // invalid for memcpy if they are equal. if (I != E) memcpy(reinterpret_cast<void *>(Dest), I, (E - I) * sizeof(T)); } /// Double the size of the allocated memory, guaranteeing space for at /// least one more element or MinSize if specified. void grow(size_t MinSize = 0) { this->grow_pod(MinSize*sizeof(T), sizeof(T)); } public: void push_back(const T &Elt) { if (LLVM_UNLIKELY(this->EndX >= this->CapacityX)) this->grow(); memcpy(reinterpret_cast<void *>(this->end()), &Elt, sizeof(T)); this->setEnd(this->end()+1); } void pop_back() { this->setEnd(this->end()-1); } }; /// This class consists of common code factored out of the SmallVector class to /// reduce code duplication based on the SmallVector 'N' template parameter. template <typename T> class SmallVectorImpl : public SmallVectorTemplateBase<T, isPodLike<T>::value> { typedef SmallVectorTemplateBase<T, isPodLike<T>::value > SuperClass; SmallVectorImpl(const SmallVectorImpl&) = delete; public: typedef typename SuperClass::iterator iterator; typedef typename SuperClass::size_type size_type; protected: // Default ctor - Initialize to empty. explicit SmallVectorImpl(unsigned N) : SmallVectorTemplateBase<T, isPodLike<T>::value>(N*sizeof(T)) { } public: ~SmallVectorImpl() { // Subclass has already destructed this vector's elements. // If this wasn't grown from the inline copy, deallocate the old space. if (!this->isSmall()) delete[] (char*)this->begin(); // HLSL Change: Use overridable operator delete } void clear() { this->destroy_range(this->begin(), this->end()); this->EndX = this->BeginX; } void resize(size_type N) { if (N < this->size()) { this->destroy_range(this->begin()+N, this->end()); this->setEnd(this->begin()+N); } else if (N > this->size()) { if (this->capacity() < N) this->grow(N); for (auto I = this->end(), E = this->begin() + N; I != E; ++I) new (&*I) T(); this->setEnd(this->begin()+N); } } void resize(size_type N, const T &NV) { if (N < this->size()) { this->destroy_range(this->begin()+N, this->end()); this->setEnd(this->begin()+N); } else if (N > this->size()) { if (this->capacity() < N) this->grow(N); std::uninitialized_fill(this->end(), this->begin()+N, NV); this->setEnd(this->begin()+N); } } void reserve(size_type N) { if (this->capacity() < N) this->grow(N); } T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val() { T Result = ::std::move(this->back()); this->pop_back(); return Result; } void swap(SmallVectorImpl &RHS); /// Add the specified range to the end of the SmallVector. template<typename in_iter> void append(in_iter in_start, in_iter in_end) { size_type NumInputs = std::distance(in_start, in_end); // Grow allocated space if needed. if (NumInputs > size_type(this->capacity_ptr()-this->end())) this->grow(this->size()+NumInputs); // Copy the new elements over. this->uninitialized_copy(in_start, in_end, this->end()); this->setEnd(this->end() + NumInputs); } /// Add the specified range to the end of the SmallVector. void append(size_type NumInputs, const T &Elt) { // Grow allocated space if needed. if (NumInputs > size_type(this->capacity_ptr()-this->end())) this->grow(this->size()+NumInputs); // Copy the new elements over. std::uninitialized_fill_n(this->end(), NumInputs, Elt); this->setEnd(this->end() + NumInputs); } void append(std::initializer_list<T> IL) { append(IL.begin(), IL.end()); } void assign(size_type NumElts, const T &Elt) { clear(); if (this->capacity() < NumElts) this->grow(NumElts); this->setEnd(this->begin()+NumElts); std::uninitialized_fill(this->begin(), this->end(), Elt); } void assign(std::initializer_list<T> IL) { clear(); append(IL); } iterator erase(iterator I) { assert(I >= this->begin() && "Iterator to erase is out of bounds."); assert(I < this->end() && "Erasing at past-the-end iterator."); iterator N = I; // Shift all elts down one. this->move(I+1, this->end(), I); // Drop the last elt. this->pop_back(); return(N); } iterator erase(iterator S, iterator E) { assert(S >= this->begin() && "Range to erase is out of bounds."); assert(S <= E && "Trying to erase invalid range."); assert(E <= this->end() && "Trying to erase past the end."); iterator N = S; // Shift all elts down. iterator I = this->move(E, this->end(), S); // Drop the last elts. this->destroy_range(I, this->end()); this->setEnd(I); return(N); } iterator insert(iterator I, T &&Elt) { if (I == this->end()) { // Important special case for empty vector. this->push_back(::std::move(Elt)); return this->end()-1; } assert(I >= this->begin() && "Insertion iterator is out of bounds."); assert(I <= this->end() && "Inserting past the end of the vector."); if (this->EndX >= this->CapacityX) { size_t EltNo = I-this->begin(); this->grow(); I = this->begin()+EltNo; } ::new ((void*) this->end()) T(::std::move(this->back())); // Push everything else over. this->move_backward(I, this->end()-1, this->end()); this->setEnd(this->end()+1); // If we just moved the element we're inserting, be sure to update // the reference. T *EltPtr = &Elt; if (I <= EltPtr && EltPtr < this->EndX) ++EltPtr; *I = ::std::move(*EltPtr); return I; } iterator insert(iterator I, const T &Elt) { if (I == this->end()) { // Important special case for empty vector. this->push_back(Elt); return this->end()-1; } assert(I >= this->begin() && "Insertion iterator is out of bounds."); assert(I <= this->end() && "Inserting past the end of the vector."); if (this->EndX >= this->CapacityX) { size_t EltNo = I-this->begin(); this->grow(); I = this->begin()+EltNo; } ::new ((void*) this->end()) T(std::move(this->back())); // Push everything else over. this->move_backward(I, this->end()-1, this->end()); this->setEnd(this->end()+1); // If we just moved the element we're inserting, be sure to update // the reference. const T *EltPtr = &Elt; if (I <= EltPtr && EltPtr < this->EndX) ++EltPtr; *I = *EltPtr; return I; } iterator insert(iterator I, size_type NumToInsert, const T &Elt) { // Convert iterator to elt# to avoid invalidating iterator when we reserve() size_t InsertElt = I - this->begin(); if (I == this->end()) { // Important special case for empty vector. append(NumToInsert, Elt); return this->begin()+InsertElt; } assert(I >= this->begin() && "Insertion iterator is out of bounds."); assert(I <= this->end() && "Inserting past the end of the vector."); // Ensure there is enough space. reserve(this->size() + NumToInsert); // Uninvalidate the iterator. I = this->begin()+InsertElt; // If there are more elements between the insertion point and the end of the // range than there are being inserted, we can use a simple approach to // insertion. Since we already reserved space, we know that this won't // reallocate the vector. if (size_t(this->end()-I) >= NumToInsert) { T *OldEnd = this->end(); append(std::move_iterator<iterator>(this->end() - NumToInsert), std::move_iterator<iterator>(this->end())); // Copy the existing elements that get replaced. this->move_backward(I, OldEnd-NumToInsert, OldEnd); std::fill_n(I, NumToInsert, Elt); return I; } // Otherwise, we're inserting more elements than exist already, and we're // not inserting at the end. // Move over the elements that we're about to overwrite. T *OldEnd = this->end(); this->setEnd(this->end() + NumToInsert); size_t NumOverwritten = OldEnd-I; this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten); // Replace the overwritten part. std::fill_n(I, NumOverwritten, Elt); // Insert the non-overwritten middle part. std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt); return I; } template<typename ItTy> iterator insert(iterator I, ItTy From, ItTy To) { // Convert iterator to elt# to avoid invalidating iterator when we reserve() size_t InsertElt = I - this->begin(); if (I == this->end()) { // Important special case for empty vector. append(From, To); return this->begin()+InsertElt; } assert(I >= this->begin() && "Insertion iterator is out of bounds."); assert(I <= this->end() && "Inserting past the end of the vector."); size_t NumToInsert = std::distance(From, To); // Ensure there is enough space. reserve(this->size() + NumToInsert); // Uninvalidate the iterator. I = this->begin()+InsertElt; // If there are more elements between the insertion point and the end of the // range than there are being inserted, we can use a simple approach to // insertion. Since we already reserved space, we know that this won't // reallocate the vector. if (size_t(this->end()-I) >= NumToInsert) { T *OldEnd = this->end(); append(std::move_iterator<iterator>(this->end() - NumToInsert), std::move_iterator<iterator>(this->end())); // Copy the existing elements that get replaced. this->move_backward(I, OldEnd-NumToInsert, OldEnd); std::copy(From, To, I); return I; } // Otherwise, we're inserting more elements than exist already, and we're // not inserting at the end. // Move over the elements that we're about to overwrite. T *OldEnd = this->end(); this->setEnd(this->end() + NumToInsert); size_t NumOverwritten = OldEnd-I; this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten); // Replace the overwritten part. for (T *J = I; NumOverwritten > 0; --NumOverwritten) { *J = *From; ++J; ++From; } // Insert the non-overwritten middle part. this->uninitialized_copy(From, To, OldEnd); return I; } void insert(iterator I, std::initializer_list<T> IL) { insert(I, IL.begin(), IL.end()); } template <typename... ArgTypes> void emplace_back(ArgTypes &&... Args) { if (LLVM_UNLIKELY(this->EndX >= this->CapacityX)) this->grow(); ::new ((void *)this->end()) T(std::forward<ArgTypes>(Args)...); this->setEnd(this->end() + 1); } SmallVectorImpl &operator=(const SmallVectorImpl &RHS); SmallVectorImpl &operator=(SmallVectorImpl &&RHS); bool operator==(const SmallVectorImpl &RHS) const { if (this->size() != RHS.size()) return false; return std::equal(this->begin(), this->end(), RHS.begin()); } bool operator!=(const SmallVectorImpl &RHS) const { return !(*this == RHS); } bool operator<(const SmallVectorImpl &RHS) const { return std::lexicographical_compare(this->begin(), this->end(), RHS.begin(), RHS.end()); } /// Set the array size to \p N, which the current array must have enough /// capacity for. /// /// This does not construct or destroy any elements in the vector. /// /// Clients can use this in conjunction with capacity() to write past the end /// of the buffer when they know that more elements are available, and only /// update the size later. This avoids the cost of value initializing elements /// which will only be overwritten. void set_size(size_type N) { assert(N <= this->capacity()); this->setEnd(this->begin() + N); } }; template <typename T> void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) { if (this == &RHS) return; // We can only avoid copying elements if neither vector is small. if (!this->isSmall() && !RHS.isSmall()) { std::swap(this->BeginX, RHS.BeginX); std::swap(this->EndX, RHS.EndX); std::swap(this->CapacityX, RHS.CapacityX); return; } if (RHS.size() > this->capacity()) this->grow(RHS.size()); if (this->size() > RHS.capacity()) RHS.grow(this->size()); // Swap the shared elements. size_t NumShared = this->size(); if (NumShared > RHS.size()) NumShared = RHS.size(); for (size_type i = 0; i != NumShared; ++i) std::swap((*this)[i], RHS[i]); // Copy over the extra elts. if (this->size() > RHS.size()) { size_t EltDiff = this->size() - RHS.size(); this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end()); RHS.setEnd(RHS.end()+EltDiff); this->destroy_range(this->begin()+NumShared, this->end()); this->setEnd(this->begin()+NumShared); } else if (RHS.size() > this->size()) { size_t EltDiff = RHS.size() - this->size(); this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end()); this->setEnd(this->end() + EltDiff); this->destroy_range(RHS.begin()+NumShared, RHS.end()); RHS.setEnd(RHS.begin()+NumShared); } } template <typename T> SmallVectorImpl<T> &SmallVectorImpl<T>:: operator=(const SmallVectorImpl<T> &RHS) { // Avoid self-assignment. if (this == &RHS) return *this; // If we already have sufficient space, assign the common elements, then // destroy any excess. size_t RHSSize = RHS.size(); size_t CurSize = this->size(); if (CurSize >= RHSSize) { // Assign common elements. iterator NewEnd; if (RHSSize) NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin()); else NewEnd = this->begin(); // Destroy excess elements. this->destroy_range(NewEnd, this->end()); // Trim. this->setEnd(NewEnd); return *this; } // If we have to grow to have enough elements, destroy the current elements. // This allows us to avoid copying them during the grow. // FIXME: don't do this if they're efficiently moveable. if (this->capacity() < RHSSize) { // Destroy current elements. this->destroy_range(this->begin(), this->end()); this->setEnd(this->begin()); CurSize = 0; this->grow(RHSSize); } else if (CurSize) { // Otherwise, use assignment for the already-constructed elements. std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin()); } // Copy construct the new elements in place. this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(), this->begin()+CurSize); // Set end. this->setEnd(this->begin()+RHSSize); return *this; } template <typename T> SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) { // Avoid self-assignment. if (this == &RHS) return *this; // If the RHS isn't small, clear this vector and then steal its buffer. if (!RHS.isSmall()) { this->destroy_range(this->begin(), this->end()); if (!this->isSmall()) delete[] (char*)this->begin(); // HLSL Change: Use overridable operator delete this->BeginX = RHS.BeginX; this->EndX = RHS.EndX; this->CapacityX = RHS.CapacityX; RHS.resetToSmall(); return *this; } // If we already have sufficient space, assign the common elements, then // destroy any excess. size_t RHSSize = RHS.size(); size_t CurSize = this->size(); if (CurSize >= RHSSize) { // Assign common elements. iterator NewEnd = this->begin(); if (RHSSize) NewEnd = this->move(RHS.begin(), RHS.end(), NewEnd); // Destroy excess elements and trim the bounds. this->destroy_range(NewEnd, this->end()); this->setEnd(NewEnd); // Clear the RHS. RHS.clear(); return *this; } // If we have to grow to have enough elements, destroy the current elements. // This allows us to avoid copying them during the grow. // FIXME: this may not actually make any sense if we can efficiently move // elements. if (this->capacity() < RHSSize) { // Destroy current elements. this->destroy_range(this->begin(), this->end()); this->setEnd(this->begin()); CurSize = 0; this->grow(RHSSize); } else if (CurSize) { // Otherwise, use assignment for the already-constructed elements. this->move(RHS.begin(), RHS.begin()+CurSize, this->begin()); } // Move-construct the new elements in place. this->uninitialized_move(RHS.begin()+CurSize, RHS.end(), this->begin()+CurSize); // Set end. this->setEnd(this->begin()+RHSSize); RHS.clear(); return *this; } /// Storage for the SmallVector elements which aren't contained in /// SmallVectorTemplateCommon. There are 'N-1' elements here. The remaining '1' /// element is in the base class. This is specialized for the N=1 and N=0 cases /// to avoid allocating unnecessary storage. template <typename T, unsigned N> struct SmallVectorStorage { typename SmallVectorTemplateCommon<T>::U InlineElts[N - 1]; }; template <typename T> struct SmallVectorStorage<T, 1> {}; template <typename T> struct SmallVectorStorage<T, 0> {}; /// This is a 'vector' (really, a variable-sized array), optimized /// for the case when the array is small. It contains some number of elements /// in-place, which allows it to avoid heap allocation when the actual number of /// elements is below that threshold. This allows normal "small" cases to be /// fast without losing generality for large inputs. /// /// Note that this does not attempt to be exception safe. /// template <typename T, unsigned N> class SmallVector : public SmallVectorImpl<T> { /// Inline space for elements which aren't stored in the base class. SmallVectorStorage<T, N> Storage; public: SmallVector() : SmallVectorImpl<T>(N) { } ~SmallVector() { // Destroy the constructed elements in the vector. this->destroy_range(this->begin(), this->end()); } explicit SmallVector(size_t Size, const T &Value = T()) : SmallVectorImpl<T>(N) { this->assign(Size, Value); } template<typename ItTy> SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) { this->append(S, E); } template <typename RangeTy> explicit SmallVector(const llvm::iterator_range<RangeTy> R) : SmallVectorImpl<T>(N) { this->append(R.begin(), R.end()); } SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) { this->assign(IL); } SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) { if (!RHS.empty()) SmallVectorImpl<T>::operator=(RHS); } const SmallVector &operator=(const SmallVector &RHS) { SmallVectorImpl<T>::operator=(RHS); return *this; } SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) { if (!RHS.empty()) SmallVectorImpl<T>::operator=(::std::move(RHS)); } const SmallVector &operator=(SmallVector &&RHS) { SmallVectorImpl<T>::operator=(::std::move(RHS)); return *this; } SmallVector(SmallVectorImpl<T> &&RHS) : SmallVectorImpl<T>(N) { if (!RHS.empty()) SmallVectorImpl<T>::operator=(::std::move(RHS)); } const SmallVector &operator=(SmallVectorImpl<T> &&RHS) { SmallVectorImpl<T>::operator=(::std::move(RHS)); return *this; } const SmallVector &operator=(std::initializer_list<T> IL) { this->assign(IL); return *this; } }; template<typename T, unsigned N> static inline size_t capacity_in_bytes(const SmallVector<T, N> &X) { return X.capacity_in_bytes(); } } // End llvm namespace namespace std { /// Implement std::swap in terms of SmallVector swap. template<typename T> inline void swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) { LHS.swap(RHS); } /// Implement std::swap in terms of SmallVector swap. template<typename T, unsigned N> inline void swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) { LHS.swap(RHS); } } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ADT/DeltaAlgorithm.h
//===--- DeltaAlgorithm.h - A Set Minimization Algorithm -------*- C++ -*--===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_DELTAALGORITHM_H #define LLVM_ADT_DELTAALGORITHM_H #include <set> #include <vector> namespace llvm { /// DeltaAlgorithm - Implements the delta debugging algorithm (A. Zeller '99) /// for minimizing arbitrary sets using a predicate function. /// /// The result of the algorithm is a subset of the input change set which is /// guaranteed to satisfy the predicate, assuming that the input set did. For /// well formed predicates, the result set is guaranteed to be such that /// removing any single element would falsify the predicate. /// /// For best results the predicate function *should* (but need not) satisfy /// certain properties, in particular: /// (1) The predicate should return false on an empty set and true on the full /// set. /// (2) If the predicate returns true for a set of changes, it should return /// true for all supersets of that set. /// /// It is not an error to provide a predicate that does not satisfy these /// requirements, and the algorithm will generally produce reasonable /// results. However, it may run substantially more tests than with a good /// predicate. class DeltaAlgorithm { public: typedef unsigned change_ty; // FIXME: Use a decent data structure. typedef std::set<change_ty> changeset_ty; typedef std::vector<changeset_ty> changesetlist_ty; private: /// Cache of failed test results. Successful test results are never cached /// since we always reduce following a success. std::set<changeset_ty> FailedTestsCache; /// GetTestResult - Get the test result for the \p Changes from the /// cache, executing the test if necessary. /// /// \param Changes - The change set to test. /// \return - The test result. bool GetTestResult(const changeset_ty &Changes); /// Split - Partition a set of changes \p S into one or two subsets. void Split(const changeset_ty &S, changesetlist_ty &Res); /// Delta - Minimize a set of \p Changes which has been partioned into /// smaller sets, by attempting to remove individual subsets. changeset_ty Delta(const changeset_ty &Changes, const changesetlist_ty &Sets); /// Search - Search for a subset (or subsets) in \p Sets which can be /// removed from \p Changes while still satisfying the predicate. /// /// \param Res - On success, a subset of Changes which satisfies the /// predicate. /// \return - True on success. bool Search(const changeset_ty &Changes, const changesetlist_ty &Sets, changeset_ty &Res); protected: /// UpdatedSearchState - Callback used when the search state changes. virtual void UpdatedSearchState(const changeset_ty &Changes, const changesetlist_ty &Sets) {} /// ExecuteOneTest - Execute a single test predicate on the change set \p S. virtual bool ExecuteOneTest(const changeset_ty &S) = 0; DeltaAlgorithm& operator=(const DeltaAlgorithm&) = default; public: virtual ~DeltaAlgorithm(); /// Run - Minimize the set \p Changes by executing \see ExecuteOneTest() on /// subsets of changes and returning the smallest set which still satisfies /// the test predicate. changeset_ty Run(const changeset_ty &Changes); }; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ADT/TinyPtrVector.h
//===- llvm/ADT/TinyPtrVector.h - 'Normally tiny' vectors -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_TINYPTRVECTOR_H #define LLVM_ADT_TINYPTRVECTOR_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/PointerUnion.h" #include "llvm/ADT/SmallVector.h" namespace llvm { /// TinyPtrVector - This class is specialized for cases where there are /// normally 0 or 1 element in a vector, but is general enough to go beyond that /// when required. /// /// NOTE: This container doesn't allow you to store a null pointer into it. /// template <typename EltTy> class TinyPtrVector { public: typedef llvm::SmallVector<EltTy, 4> VecTy; typedef typename VecTy::value_type value_type; typedef llvm::PointerUnion<EltTy, VecTy *> PtrUnion; private: PtrUnion Val; public: TinyPtrVector() {} ~TinyPtrVector() { if (VecTy *V = Val.template dyn_cast<VecTy*>()) delete V; } TinyPtrVector(const TinyPtrVector &RHS) : Val(RHS.Val) { if (VecTy *V = Val.template dyn_cast<VecTy*>()) Val = new VecTy(*V); } TinyPtrVector &operator=(const TinyPtrVector &RHS) { if (this == &RHS) return *this; if (RHS.empty()) { this->clear(); return *this; } // Try to squeeze into the single slot. If it won't fit, allocate a copied // vector. if (Val.template is<EltTy>()) { if (RHS.size() == 1) Val = RHS.front(); else Val = new VecTy(*RHS.Val.template get<VecTy*>()); return *this; } // If we have a full vector allocated, try to re-use it. if (RHS.Val.template is<EltTy>()) { Val.template get<VecTy*>()->clear(); Val.template get<VecTy*>()->push_back(RHS.front()); } else { *Val.template get<VecTy*>() = *RHS.Val.template get<VecTy*>(); } return *this; } TinyPtrVector(TinyPtrVector &&RHS) : Val(RHS.Val) { RHS.Val = (EltTy)nullptr; } TinyPtrVector &operator=(TinyPtrVector &&RHS) { if (this == &RHS) return *this; if (RHS.empty()) { this->clear(); return *this; } // If this vector has been allocated on the heap, re-use it if cheap. If it // would require more copying, just delete it and we'll steal the other // side. if (VecTy *V = Val.template dyn_cast<VecTy*>()) { if (RHS.Val.template is<EltTy>()) { V->clear(); V->push_back(RHS.front()); return *this; } delete V; } Val = RHS.Val; RHS.Val = (EltTy)nullptr; return *this; } /// Constructor from an ArrayRef. /// /// This also is a constructor for individual array elements due to the single /// element constructor for ArrayRef. explicit TinyPtrVector(ArrayRef<EltTy> Elts) : Val(Elts.size() == 1 ? PtrUnion(Elts[0]) : PtrUnion(new VecTy(Elts.begin(), Elts.end()))) {} // implicit conversion operator to ArrayRef. operator ArrayRef<EltTy>() const { if (Val.isNull()) return None; if (Val.template is<EltTy>()) return *Val.getAddrOfPtr1(); return *Val.template get<VecTy*>(); } // implicit conversion operator to MutableArrayRef. operator MutableArrayRef<EltTy>() { if (Val.isNull()) return None; if (Val.template is<EltTy>()) return *Val.getAddrOfPtr1(); return *Val.template get<VecTy*>(); } bool empty() const { // This vector can be empty if it contains no element, or if it // contains a pointer to an empty vector. if (Val.isNull()) return true; if (VecTy *Vec = Val.template dyn_cast<VecTy*>()) return Vec->empty(); return false; } unsigned size() const { if (empty()) return 0; if (Val.template is<EltTy>()) return 1; return Val.template get<VecTy*>()->size(); } typedef const EltTy *const_iterator; typedef EltTy *iterator; iterator begin() { if (Val.template is<EltTy>()) return Val.getAddrOfPtr1(); return Val.template get<VecTy *>()->begin(); } iterator end() { if (Val.template is<EltTy>()) return begin() + (Val.isNull() ? 0 : 1); return Val.template get<VecTy *>()->end(); } const_iterator begin() const { return (const_iterator)const_cast<TinyPtrVector*>(this)->begin(); } const_iterator end() const { return (const_iterator)const_cast<TinyPtrVector*>(this)->end(); } EltTy operator[](unsigned i) const { assert(!Val.isNull() && "can't index into an empty vector"); if (EltTy V = Val.template dyn_cast<EltTy>()) { assert(i == 0 && "tinyvector index out of range"); return V; } assert(i < Val.template get<VecTy*>()->size() && "tinyvector index out of range"); return (*Val.template get<VecTy*>())[i]; } EltTy front() const { assert(!empty() && "vector empty"); if (EltTy V = Val.template dyn_cast<EltTy>()) return V; return Val.template get<VecTy*>()->front(); } EltTy back() const { assert(!empty() && "vector empty"); if (EltTy V = Val.template dyn_cast<EltTy>()) return V; return Val.template get<VecTy*>()->back(); } void push_back(EltTy NewVal) { assert(NewVal && "Can't add a null value"); // If we have nothing, add something. if (Val.isNull()) { Val = NewVal; return; } // If we have a single value, convert to a vector. if (EltTy V = Val.template dyn_cast<EltTy>()) { Val = new VecTy(); Val.template get<VecTy*>()->push_back(V); } // Add the new value, we know we have a vector. Val.template get<VecTy*>()->push_back(NewVal); } void pop_back() { // If we have a single value, convert to empty. if (Val.template is<EltTy>()) Val = (EltTy)nullptr; else if (VecTy *Vec = Val.template get<VecTy*>()) Vec->pop_back(); } void clear() { // If we have a single value, convert to empty. if (Val.template is<EltTy>()) { Val = (EltTy)nullptr; } else if (VecTy *Vec = Val.template dyn_cast<VecTy*>()) { // If we have a vector form, just clear it. Vec->clear(); } // Otherwise, we're already empty. } iterator erase(iterator I) { assert(I >= begin() && "Iterator to erase is out of bounds."); assert(I < end() && "Erasing at past-the-end iterator."); // If we have a single value, convert to empty. if (Val.template is<EltTy>()) { if (I == begin()) Val = (EltTy)nullptr; } else if (VecTy *Vec = Val.template dyn_cast<VecTy*>()) { // multiple items in a vector; just do the erase, there is no // benefit to collapsing back to a pointer return Vec->erase(I); } return end(); } iterator erase(iterator S, iterator E) { assert(S >= begin() && "Range to erase is out of bounds."); assert(S <= E && "Trying to erase invalid range."); assert(E <= end() && "Trying to erase past the end."); if (Val.template is<EltTy>()) { if (S == begin() && S != E) Val = (EltTy)nullptr; } else if (VecTy *Vec = Val.template dyn_cast<VecTy*>()) { return Vec->erase(S, E); } return end(); } iterator insert(iterator I, const EltTy &Elt) { assert(I >= this->begin() && "Insertion iterator is out of bounds."); assert(I <= this->end() && "Inserting past the end of the vector."); if (I == end()) { push_back(Elt); return std::prev(end()); } assert(!Val.isNull() && "Null value with non-end insert iterator."); if (EltTy V = Val.template dyn_cast<EltTy>()) { assert(I == begin()); Val = Elt; push_back(V); return begin(); } return Val.template get<VecTy*>()->insert(I, Elt); } template<typename ItTy> iterator insert(iterator I, ItTy From, ItTy To) { assert(I >= this->begin() && "Insertion iterator is out of bounds."); assert(I <= this->end() && "Inserting past the end of the vector."); if (From == To) return I; // If we have a single value, convert to a vector. ptrdiff_t Offset = I - begin(); if (Val.isNull()) { if (std::next(From) == To) { Val = *From; return begin(); } Val = new VecTy(); } else if (EltTy V = Val.template dyn_cast<EltTy>()) { Val = new VecTy(); Val.template get<VecTy*>()->push_back(V); } return Val.template get<VecTy*>()->insert(begin() + Offset, From, To); } }; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ADT/SmallSet.h
//===- llvm/ADT/SmallSet.h - 'Normally small' sets --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the SmallSet class. // //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_SMALLSET_H #define LLVM_ADT_SMALLSET_H #include "llvm/ADT/None.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include <set> namespace llvm { /// SmallSet - This maintains a set of unique values, optimizing for the case /// when the set is small (less than N). In this case, the set can be /// maintained with no mallocs. If the set gets large, we expand to using an /// std::set to maintain reasonable lookup times. /// /// Note that this set does not provide a way to iterate over members in the /// set. template <typename T, unsigned N, typename C = std::less<T> > class SmallSet { /// Use a SmallVector to hold the elements here (even though it will never /// reach its 'large' stage) to avoid calling the default ctors of elements /// we will never use. SmallVector<T, N> Vector; std::set<T, C> Set; typedef typename SmallVector<T, N>::const_iterator VIterator; typedef typename SmallVector<T, N>::iterator mutable_iterator; public: typedef size_t size_type; SmallSet() {} bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const { return Vector.empty() && Set.empty(); } size_type size() const { return isSmall() ? Vector.size() : Set.size(); } /// count - Return 1 if the element is in the set, 0 otherwise. size_type count(const T &V) const { if (isSmall()) { // Since the collection is small, just do a linear search. return vfind(V) == Vector.end() ? 0 : 1; } else { return Set.count(V); } } /// insert - Insert an element into the set if it isn't already there. /// Returns true if the element is inserted (it was not in the set before). /// The first value of the returned pair is unused and provided for /// partial compatibility with the standard library self-associative container /// concept. // FIXME: Add iterators that abstract over the small and large form, and then // return those here. std::pair<NoneType, bool> insert(const T &V) { if (!isSmall()) return std::make_pair(None, Set.insert(V).second); VIterator I = vfind(V); if (I != Vector.end()) // Don't reinsert if it already exists. return std::make_pair(None, false); if (Vector.size() < N) { Vector.push_back(V); return std::make_pair(None, true); } // Otherwise, grow from vector to set. while (!Vector.empty()) { Set.insert(Vector.back()); Vector.pop_back(); } Set.insert(V); return std::make_pair(None, true); } template <typename IterT> void insert(IterT I, IterT E) { for (; I != E; ++I) insert(*I); } bool erase(const T &V) { if (!isSmall()) return Set.erase(V); for (mutable_iterator I = Vector.begin(), E = Vector.end(); I != E; ++I) if (*I == V) { Vector.erase(I); return true; } return false; } void clear() { Vector.clear(); Set.clear(); } private: bool isSmall() const { return Set.empty(); } VIterator vfind(const T &V) const { for (VIterator I = Vector.begin(), E = Vector.end(); I != E; ++I) if (*I == V) return I; return Vector.end(); } }; /// If this set is of pointer values, transparently switch over to using /// SmallPtrSet for performance. template <typename PointeeType, unsigned N> class SmallSet<PointeeType*, N> : public SmallPtrSet<PointeeType*, N> {}; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ADT/Twine.h
//===-- Twine.h - Fast Temporary String Concatenation -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_TWINE_H #define LLVM_ADT_TWINE_H #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/ErrorHandling.h" #include <cassert> #include <string> namespace llvm { class raw_ostream; /// Twine - A lightweight data structure for efficiently representing the /// concatenation of temporary values as strings. /// /// A Twine is a kind of rope, it represents a concatenated string using a /// binary-tree, where the string is the preorder of the nodes. Since the /// Twine can be efficiently rendered into a buffer when its result is used, /// it avoids the cost of generating temporary values for intermediate string /// results -- particularly in cases when the Twine result is never /// required. By explicitly tracking the type of leaf nodes, we can also avoid /// the creation of temporary strings for conversions operations (such as /// appending an integer to a string). /// /// A Twine is not intended for use directly and should not be stored, its /// implementation relies on the ability to store pointers to temporary stack /// objects which may be deallocated at the end of a statement. Twines should /// only be used accepted as const references in arguments, when an API wishes /// to accept possibly-concatenated strings. /// /// Twines support a special 'null' value, which always concatenates to form /// itself, and renders as an empty string. This can be returned from APIs to /// effectively nullify any concatenations performed on the result. /// /// \b Implementation /// /// Given the nature of a Twine, it is not possible for the Twine's /// concatenation method to construct interior nodes; the result must be /// represented inside the returned value. For this reason a Twine object /// actually holds two values, the left- and right-hand sides of a /// concatenation. We also have nullary Twine objects, which are effectively /// sentinel values that represent empty strings. /// /// Thus, a Twine can effectively have zero, one, or two children. The \see /// isNullary(), \see isUnary(), and \see isBinary() predicates exist for /// testing the number of children. /// /// We maintain a number of invariants on Twine objects (FIXME: Why): /// - Nullary twines are always represented with their Kind on the left-hand /// side, and the Empty kind on the right-hand side. /// - Unary twines are always represented with the value on the left-hand /// side, and the Empty kind on the right-hand side. /// - If a Twine has another Twine as a child, that child should always be /// binary (otherwise it could have been folded into the parent). /// /// These invariants are check by \see isValid(). /// /// \b Efficiency Considerations /// /// The Twine is designed to yield efficient and small code for common /// situations. For this reason, the concat() method is inlined so that /// concatenations of leaf nodes can be optimized into stores directly into a /// single stack allocated object. /// /// In practice, not all compilers can be trusted to optimize concat() fully, /// so we provide two additional methods (and accompanying operator+ /// overloads) to guarantee that particularly important cases (cstring plus /// StringRef) codegen as desired. class Twine { /// NodeKind - Represent the type of an argument. enum NodeKind : unsigned char { /// An empty string; the result of concatenating anything with it is also /// empty. NullKind, /// The empty string. EmptyKind, /// A pointer to a Twine instance. TwineKind, /// A pointer to a C string instance. CStringKind, /// A pointer to an std::string instance. StdStringKind, /// A pointer to a StringRef instance. StringRefKind, /// A pointer to a SmallString instance. SmallStringKind, /// A char value reinterpreted as a pointer, to render as a character. CharKind, /// An unsigned int value reinterpreted as a pointer, to render as an /// unsigned decimal integer. DecUIKind, /// An int value reinterpreted as a pointer, to render as a signed /// decimal integer. DecIKind, /// A pointer to an unsigned long value, to render as an unsigned decimal /// integer. DecULKind, /// A pointer to a long value, to render as a signed decimal integer. DecLKind, /// A pointer to an unsigned long long value, to render as an unsigned /// decimal integer. DecULLKind, /// A pointer to a long long value, to render as a signed decimal integer. DecLLKind, /// A pointer to a uint64_t value, to render as an unsigned hexadecimal /// integer. UHexKind }; union Child { const Twine *twine; const char *cString; const std::string *stdString; const StringRef *stringRef; const SmallVectorImpl<char> *smallString; char character; unsigned int decUI; int decI; const unsigned long *decUL; const long *decL; const unsigned long long *decULL; const long long *decLL; const uint64_t *uHex; }; private: /// LHS - The prefix in the concatenation, which may be uninitialized for /// Null or Empty kinds. Child LHS; /// RHS - The suffix in the concatenation, which may be uninitialized for /// Null or Empty kinds. Child RHS; /// LHSKind - The NodeKind of the left hand side, \see getLHSKind(). NodeKind LHSKind; /// RHSKind - The NodeKind of the right hand side, \see getRHSKind(). NodeKind RHSKind; private: /// Construct a nullary twine; the kind must be NullKind or EmptyKind. explicit Twine(NodeKind Kind) : LHSKind(Kind), RHSKind(EmptyKind) { assert(isNullary() && "Invalid kind!"); } /// Construct a binary twine. explicit Twine(const Twine &LHS, const Twine &RHS) : LHSKind(TwineKind), RHSKind(TwineKind) { this->LHS.twine = &LHS; this->RHS.twine = &RHS; assert(isValid() && "Invalid twine!"); } /// Construct a twine from explicit values. explicit Twine(Child LHS, NodeKind LHSKind, Child RHS, NodeKind RHSKind) : LHS(LHS), RHS(RHS), LHSKind(LHSKind), RHSKind(RHSKind) { assert(isValid() && "Invalid twine!"); } /// Since the intended use of twines is as temporary objects, assignments /// when concatenating might cause undefined behavior or stack corruptions Twine &operator=(const Twine &Other) = delete; /// Check for the null twine. bool isNull() const { return getLHSKind() == NullKind; } /// Check for the empty twine. bool isEmpty() const { return getLHSKind() == EmptyKind; } /// Check if this is a nullary twine (null or empty). bool isNullary() const { return isNull() || isEmpty(); } /// Check if this is a unary twine. bool isUnary() const { return getRHSKind() == EmptyKind && !isNullary(); } /// Check if this is a binary twine. bool isBinary() const { return getLHSKind() != NullKind && getRHSKind() != EmptyKind; } /// Check if this is a valid twine (satisfying the invariants on /// order and number of arguments). bool isValid() const { // Nullary twines always have Empty on the RHS. if (isNullary() && getRHSKind() != EmptyKind) return false; // Null should never appear on the RHS. if (getRHSKind() == NullKind) return false; // The RHS cannot be non-empty if the LHS is empty. if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind) return false; // A twine child should always be binary. if (getLHSKind() == TwineKind && !LHS.twine->isBinary()) return false; if (getRHSKind() == TwineKind && !RHS.twine->isBinary()) return false; return true; } /// Get the NodeKind of the left-hand side. NodeKind getLHSKind() const { return LHSKind; } /// Get the NodeKind of the right-hand side. NodeKind getRHSKind() const { return RHSKind; } /// Print one child from a twine. void printOneChild(raw_ostream &OS, Child Ptr, NodeKind Kind) const; /// Print the representation of one child from a twine. void printOneChildRepr(raw_ostream &OS, Child Ptr, NodeKind Kind) const; public: /// @name Constructors /// @{ /// Construct from an empty string. /*implicit*/ Twine() : LHSKind(EmptyKind), RHSKind(EmptyKind) { assert(isValid() && "Invalid twine!"); } Twine(const Twine &) = default; /// Construct from a C string. /// /// We take care here to optimize "" into the empty twine -- this will be /// optimized out for string constants. This allows Twine arguments have /// default "" values, without introducing unnecessary string constants. /*implicit*/ Twine(const char *Str) : RHSKind(EmptyKind) { if (Str[0] != '\0') { LHS.cString = Str; LHSKind = CStringKind; } else LHSKind = EmptyKind; assert(isValid() && "Invalid twine!"); } /// Construct from an std::string. /*implicit*/ Twine(const std::string &Str) : LHSKind(StdStringKind), RHSKind(EmptyKind) { LHS.stdString = &Str; assert(isValid() && "Invalid twine!"); } /// Construct from a StringRef. /*implicit*/ Twine(const StringRef &Str) : LHSKind(StringRefKind), RHSKind(EmptyKind) { LHS.stringRef = &Str; assert(isValid() && "Invalid twine!"); } /// Construct from a SmallString. /*implicit*/ Twine(const SmallVectorImpl<char> &Str) : LHSKind(SmallStringKind), RHSKind(EmptyKind) { LHS.smallString = &Str; assert(isValid() && "Invalid twine!"); } /// Construct from a char. explicit Twine(char Val) : LHSKind(CharKind), RHSKind(EmptyKind) { LHS.character = Val; } /// Construct from a signed char. explicit Twine(signed char Val) : LHSKind(CharKind), RHSKind(EmptyKind) { LHS.character = static_cast<char>(Val); } /// Construct from an unsigned char. explicit Twine(unsigned char Val) : LHSKind(CharKind), RHSKind(EmptyKind) { LHS.character = static_cast<char>(Val); } /// Construct a twine to print \p Val as an unsigned decimal integer. explicit Twine(unsigned Val) : LHSKind(DecUIKind), RHSKind(EmptyKind) { LHS.decUI = Val; } /// Construct a twine to print \p Val as a signed decimal integer. explicit Twine(int Val) : LHSKind(DecIKind), RHSKind(EmptyKind) { LHS.decI = Val; } /// Construct a twine to print \p Val as an unsigned decimal integer. explicit Twine(const unsigned long &Val) : LHSKind(DecULKind), RHSKind(EmptyKind) { LHS.decUL = &Val; } /// Construct a twine to print \p Val as a signed decimal integer. explicit Twine(const long &Val) : LHSKind(DecLKind), RHSKind(EmptyKind) { LHS.decL = &Val; } /// Construct a twine to print \p Val as an unsigned decimal integer. explicit Twine(const unsigned long long &Val) : LHSKind(DecULLKind), RHSKind(EmptyKind) { LHS.decULL = &Val; } /// Construct a twine to print \p Val as a signed decimal integer. explicit Twine(const long long &Val) : LHSKind(DecLLKind), RHSKind(EmptyKind) { LHS.decLL = &Val; } // FIXME: Unfortunately, to make sure this is as efficient as possible we // need extra binary constructors from particular types. We can't rely on // the compiler to be smart enough to fold operator+()/concat() down to the // right thing. Yet. /// Construct as the concatenation of a C string and a StringRef. /*implicit*/ Twine(const char *LHS, const StringRef &RHS) : LHSKind(CStringKind), RHSKind(StringRefKind) { this->LHS.cString = LHS; this->RHS.stringRef = &RHS; assert(isValid() && "Invalid twine!"); } /// Construct as the concatenation of a StringRef and a C string. /*implicit*/ Twine(const StringRef &LHS, const char *RHS) : LHSKind(StringRefKind), RHSKind(CStringKind) { this->LHS.stringRef = &LHS; this->RHS.cString = RHS; assert(isValid() && "Invalid twine!"); } /// Create a 'null' string, which is an empty string that always /// concatenates to form another empty string. static Twine createNull() { return Twine(NullKind); } /// @} /// @name Numeric Conversions /// @{ // Construct a twine to print \p Val as an unsigned hexadecimal integer. static Twine utohexstr(const uint64_t &Val) { Child LHS, RHS; LHS.uHex = &Val; RHS.twine = nullptr; return Twine(LHS, UHexKind, RHS, EmptyKind); } /// @} /// @name Predicate Operations /// @{ /// Check if this twine is trivially empty; a false return value does not /// necessarily mean the twine is empty. bool isTriviallyEmpty() const { return isNullary(); } /// Return true if this twine can be dynamically accessed as a single /// StringRef value with getSingleStringRef(). bool isSingleStringRef() const { if (getRHSKind() != EmptyKind) return false; switch (getLHSKind()) { case EmptyKind: case CStringKind: case StdStringKind: case StringRefKind: case SmallStringKind: return true; default: return false; } } /// @} /// @name String Operations /// @{ Twine concat(const Twine &Suffix) const; /// @} /// @name Output & Conversion. /// @{ /// Return the twine contents as a std::string. std::string str() const; /// Append the concatenated string into the given SmallString or SmallVector. void toVector(SmallVectorImpl<char> &Out) const; /// This returns the twine as a single StringRef. This method is only valid /// if isSingleStringRef() is true. StringRef getSingleStringRef() const { assert(isSingleStringRef() &&"This cannot be had as a single stringref!"); switch (getLHSKind()) { default: llvm_unreachable("Out of sync with isSingleStringRef"); case EmptyKind: return StringRef(); case CStringKind: return StringRef(LHS.cString); case StdStringKind: return StringRef(*LHS.stdString); case StringRefKind: return *LHS.stringRef; case SmallStringKind: return StringRef(LHS.smallString->data(), LHS.smallString->size()); } } /// This returns the twine as a single StringRef if it can be /// represented as such. Otherwise the twine is written into the given /// SmallVector and a StringRef to the SmallVector's data is returned. StringRef toStringRef(SmallVectorImpl<char> &Out) const { if (isSingleStringRef()) return getSingleStringRef(); toVector(Out); return StringRef(Out.data(), Out.size()); } /// This returns the twine as a single null terminated StringRef if it /// can be represented as such. Otherwise the twine is written into the /// given SmallVector and a StringRef to the SmallVector's data is returned. /// /// The returned StringRef's size does not include the null terminator. StringRef toNullTerminatedStringRef(SmallVectorImpl<char> &Out) const; /// Write the concatenated string represented by this twine to the /// stream \p OS. void print(raw_ostream &OS) const; /// Dump the concatenated string represented by this twine to stderr. void dump() const; /// Write the representation of this twine to the stream \p OS. void printRepr(raw_ostream &OS) const; /// Dump the representation of this twine to stderr. void dumpRepr() const; /// @} }; /// @name Twine Inline Implementations /// @{ inline Twine Twine::concat(const Twine &Suffix) const { // Concatenation with null is null. if (isNull() || Suffix.isNull()) return Twine(NullKind); // Concatenation with empty yields the other side. if (isEmpty()) return Suffix; if (Suffix.isEmpty()) return *this; // Otherwise we need to create a new node, taking care to fold in unary // twines. Child NewLHS, NewRHS; NewLHS.twine = this; NewRHS.twine = &Suffix; NodeKind NewLHSKind = TwineKind, NewRHSKind = TwineKind; if (isUnary()) { NewLHS = LHS; NewLHSKind = getLHSKind(); } if (Suffix.isUnary()) { NewRHS = Suffix.LHS; NewRHSKind = Suffix.getLHSKind(); } return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind); } inline Twine operator+(const Twine &LHS, const Twine &RHS) { return LHS.concat(RHS); } /// Additional overload to guarantee simplified codegen; this is equivalent to /// concat(). inline Twine operator+(const char *LHS, const StringRef &RHS) { return Twine(LHS, RHS); } /// Additional overload to guarantee simplified codegen; this is equivalent to /// concat(). inline Twine operator+(const StringRef &LHS, const char *RHS) { return Twine(LHS, RHS); } inline raw_ostream &operator<<(raw_ostream &OS, const Twine &RHS) { RHS.print(OS); return OS; } /// @} } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ADT/ArrayRef.h
//===--- ArrayRef.h - Array Reference Wrapper -------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_ARRAYREF_H #define LLVM_ADT_ARRAYREF_H #include "llvm/ADT/None.h" #include "llvm/ADT/SmallVector.h" #include <vector> namespace llvm { /// ArrayRef - Represent a constant reference to an array (0 or more elements /// consecutively in memory), i.e. a start pointer and a length. It allows /// various APIs to take consecutive elements easily and conveniently. /// /// This class does not own the underlying data, it is expected to be used in /// situations where the data resides in some other buffer, whose lifetime /// extends past that of the ArrayRef. For this reason, it is not in general /// safe to store an ArrayRef. /// /// This is intended to be trivially copyable, so it should be passed by /// value. template<typename T> class ArrayRef { public: typedef const T *iterator; typedef const T *const_iterator; typedef size_t size_type; typedef std::reverse_iterator<iterator> reverse_iterator; private: /// The start of the array, in an external buffer. const T *Data; /// The number of elements. size_type Length; public: /// @name Constructors /// @{ /// Construct an empty ArrayRef. /*implicit*/ ArrayRef() : Data(nullptr), Length(0) {} /// Construct an empty ArrayRef from None. /*implicit*/ ArrayRef(NoneType) : Data(nullptr), Length(0) {} /// Construct an ArrayRef from a single element. /*implicit*/ ArrayRef(const T &OneElt) : Data(&OneElt), Length(1) {} /// Construct an ArrayRef from a pointer and length. /*implicit*/ ArrayRef(const T *data, size_t length) : Data(data), Length(length) {} /// Construct an ArrayRef from a range. ArrayRef(const T *begin, const T *end) : Data(begin), Length(end - begin) {} /// Construct an ArrayRef from a SmallVector. This is templated in order to /// avoid instantiating SmallVectorTemplateCommon<T> whenever we /// copy-construct an ArrayRef. template<typename U> /*implicit*/ ArrayRef(const SmallVectorTemplateCommon<T, U> &Vec) : Data(Vec.data()), Length(Vec.size()) { } /// Construct an ArrayRef from a std::vector. template<typename A> /*implicit*/ ArrayRef(const std::vector<T, A> &Vec) : Data(Vec.data()), Length(Vec.size()) {} /// Construct an ArrayRef from a C array. template <size_t N> /*implicit*/ LLVM_CONSTEXPR ArrayRef(const T (&Arr)[N]) : Data(Arr), Length(N) {} /// Construct an ArrayRef from a std::initializer_list. #if LLVM_GNUC_PREREQ(9, 0, 0) // Disable gcc's warning in this constructor as it generates an enormous amount // of messages. Anyone using ArrayRef should already be aware of the fact that // it does not do lifetime extension. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Winit-list-lifetime" #endif /*implicit*/ ArrayRef(const std::initializer_list<T> &Vec) : Data(Vec.begin() == Vec.end() ? (T*)0 : Vec.begin()), Length(Vec.size()) {} #if LLVM_GNUC_PREREQ(9, 0, 0) #pragma GCC diagnostic pop #endif /// Construct an ArrayRef<const T*> from ArrayRef<T*>. This uses SFINAE to /// ensure that only ArrayRefs of pointers can be converted. template <typename U> ArrayRef(const ArrayRef<U *> &A, typename std::enable_if< std::is_convertible<U *const *, T const *>::value>::type* = 0) : Data(A.data()), Length(A.size()) {} /// Construct an ArrayRef<const T*> from a SmallVector<T*>. This is /// templated in order to avoid instantiating SmallVectorTemplateCommon<T> /// whenever we copy-construct an ArrayRef. template<typename U, typename DummyT> /*implicit*/ ArrayRef(const SmallVectorTemplateCommon<U*, DummyT> &Vec, typename std::enable_if< std::is_convertible<U *const *, T const *>::value>::type* = 0) : Data(Vec.data()), Length(Vec.size()) { } /// Construct an ArrayRef<const T*> from std::vector<T*>. This uses SFINAE /// to ensure that only vectors of pointers can be converted. template<typename U, typename A> ArrayRef(const std::vector<U *, A> &Vec, typename std::enable_if< std::is_convertible<U *const *, T const *>::value>::type* = 0) : Data(Vec.data()), Length(Vec.size()) {} /// @} /// @name Simple Operations /// @{ iterator begin() const { return Data; } iterator end() const { return Data + Length; } reverse_iterator rbegin() const { return reverse_iterator(end()); } reverse_iterator rend() const { return reverse_iterator(begin()); } /// empty - Check if the array is empty. bool empty() const { return Length == 0; } const T *data() const { return Data; } /// size - Get the array size. size_t size() const { return Length; } /// front - Get the first element. const T &front() const { assert(!empty()); return Data[0]; } /// back - Get the last element. const T &back() const { assert(!empty()); return Data[Length-1]; } // copy - Allocate copy in Allocator and return ArrayRef<T> to it. template <typename Allocator> ArrayRef<T> copy(Allocator &A) { T *Buff = A.template Allocate<T>(Length); std::copy(begin(), end(), Buff); return ArrayRef<T>(Buff, Length); } /// equals - Check for element-wise equality. bool equals(ArrayRef RHS) const { if (Length != RHS.Length) return false; if (Length == 0) return true; return std::equal(begin(), end(), RHS.begin()); } /// slice(n) - Chop off the first N elements of the array. ArrayRef<T> slice(unsigned N) const { assert(N <= size() && "Invalid specifier"); return ArrayRef<T>(data()+N, size()-N); } /// slice(n, m) - Chop off the first N elements of the array, and keep M /// elements in the array. ArrayRef<T> slice(unsigned N, unsigned M) const { assert(N+M <= size() && "Invalid specifier"); return ArrayRef<T>(data()+N, M); } // \brief Drop the last \p N elements of the array. ArrayRef<T> drop_back(unsigned N = 1) const { assert(size() >= N && "Dropping more elements than exist"); return slice(0, size() - N); } /// @} /// @name Operator Overloads /// @{ const T &operator[](size_t Index) const { assert(Index < Length && "Invalid index!"); return Data[Index]; } /// @} /// @name Expensive Operations /// @{ std::vector<T> vec() const { return std::vector<T>(Data, Data+Length); } /// @} /// @name Conversion operators /// @{ operator std::vector<T>() const { return std::vector<T>(Data, Data+Length); } /// @} }; /// MutableArrayRef - Represent a mutable reference to an array (0 or more /// elements consecutively in memory), i.e. a start pointer and a length. It /// allows various APIs to take and modify consecutive elements easily and /// conveniently. /// /// This class does not own the underlying data, it is expected to be used in /// situations where the data resides in some other buffer, whose lifetime /// extends past that of the MutableArrayRef. For this reason, it is not in /// general safe to store a MutableArrayRef. /// /// This is intended to be trivially copyable, so it should be passed by /// value. template<typename T> class MutableArrayRef : public ArrayRef<T> { public: typedef T *iterator; typedef std::reverse_iterator<iterator> reverse_iterator; /// Construct an empty MutableArrayRef. /*implicit*/ MutableArrayRef() : ArrayRef<T>() {} /// Construct an empty MutableArrayRef from None. /*implicit*/ MutableArrayRef(NoneType) : ArrayRef<T>() {} /// Construct an MutableArrayRef from a single element. /*implicit*/ MutableArrayRef(T &OneElt) : ArrayRef<T>(OneElt) {} /// Construct an MutableArrayRef from a pointer and length. /*implicit*/ MutableArrayRef(T *data, size_t length) : ArrayRef<T>(data, length) {} /// Construct an MutableArrayRef from a range. MutableArrayRef(T *begin, T *end) : ArrayRef<T>(begin, end) {} /// Construct an MutableArrayRef from a SmallVector. /*implicit*/ MutableArrayRef(SmallVectorImpl<T> &Vec) : ArrayRef<T>(Vec) {} /// Construct a MutableArrayRef from a std::vector. /*implicit*/ MutableArrayRef(std::vector<T> &Vec) : ArrayRef<T>(Vec) {} /// Construct an MutableArrayRef from a C array. template <size_t N> /*implicit*/ LLVM_CONSTEXPR MutableArrayRef(T (&Arr)[N]) : ArrayRef<T>(Arr) {} T *data() const { return const_cast<T*>(ArrayRef<T>::data()); } iterator begin() const { return data(); } iterator end() const { return data() + this->size(); } reverse_iterator rbegin() const { return reverse_iterator(end()); } reverse_iterator rend() const { return reverse_iterator(begin()); } /// front - Get the first element. T &front() const { assert(!this->empty()); return data()[0]; } /// back - Get the last element. T &back() const { assert(!this->empty()); return data()[this->size()-1]; } /// slice(n) - Chop off the first N elements of the array. MutableArrayRef<T> slice(unsigned N) const { assert(N <= this->size() && "Invalid specifier"); return MutableArrayRef<T>(data()+N, this->size()-N); } /// slice(n, m) - Chop off the first N elements of the array, and keep M /// elements in the array. MutableArrayRef<T> slice(unsigned N, unsigned M) const { assert(N+M <= this->size() && "Invalid specifier"); return MutableArrayRef<T>(data()+N, M); } MutableArrayRef<T> drop_back(unsigned N) const { assert(this->size() >= N && "Dropping more elements than exist"); return slice(0, this->size() - N); } /// @} /// @name Operator Overloads /// @{ T &operator[](size_t Index) const { assert(Index < this->size() && "Invalid index!"); return data()[Index]; } }; /// @name ArrayRef Convenience constructors /// @{ /// Construct an ArrayRef from a single element. template<typename T> ArrayRef<T> makeArrayRef(const T &OneElt) { return OneElt; } /// Construct an ArrayRef from a pointer and length. template<typename T> ArrayRef<T> makeArrayRef(const T *data, size_t length) { return ArrayRef<T>(data, length); } /// Construct an ArrayRef from a range. template<typename T> ArrayRef<T> makeArrayRef(const T *begin, const T *end) { return ArrayRef<T>(begin, end); } /// Construct an ArrayRef from a SmallVector. template <typename T> ArrayRef<T> makeArrayRef(const SmallVectorImpl<T> &Vec) { return Vec; } /// Construct an ArrayRef from a SmallVector. template <typename T, unsigned N> ArrayRef<T> makeArrayRef(const SmallVector<T, N> &Vec) { return Vec; } /// Construct an ArrayRef from a std::vector. template<typename T> ArrayRef<T> makeArrayRef(const std::vector<T> &Vec) { return Vec; } /// Construct an ArrayRef from a C array. template<typename T, size_t N> ArrayRef<T> makeArrayRef(const T (&Arr)[N]) { return ArrayRef<T>(Arr); } /// @} /// @name ArrayRef Comparison Operators /// @{ template<typename T> inline bool operator==(ArrayRef<T> LHS, ArrayRef<T> RHS) { return LHS.equals(RHS); } template<typename T> inline bool operator!=(ArrayRef<T> LHS, ArrayRef<T> RHS) { return !(LHS == RHS); } /// @} // ArrayRefs can be treated like a POD type. template <typename T> struct isPodLike; template <typename T> struct isPodLike<ArrayRef<T> > { static const bool value = true; }; } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ADT/SmallString.h
//===- llvm/ADT/SmallString.h - 'Normally small' strings --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the SmallString class. // //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_SMALLSTRING_H #define LLVM_ADT_SMALLSTRING_H #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" namespace llvm { /// SmallString - A SmallString is just a SmallVector with methods and accessors /// that make it work better as a string (e.g. operator+ etc). template<unsigned InternalLen> class SmallString : public SmallVector<char, InternalLen> { public: /// Default ctor - Initialize to empty. SmallString() {} /// Initialize from a StringRef. SmallString(StringRef S) : SmallVector<char, InternalLen>(S.begin(), S.end()) {} /// Initialize with a range. template<typename ItTy> SmallString(ItTy S, ItTy E) : SmallVector<char, InternalLen>(S, E) {} // Note that in order to add new overloads for append & assign, we have to // duplicate the inherited versions so as not to inadvertently hide them. /// @} /// @name String Assignment /// @{ /// Assign from a repeated element. void assign(size_t NumElts, char Elt) { this->SmallVectorImpl<char>::assign(NumElts, Elt); } /// Assign from an iterator pair. template<typename in_iter> void assign(in_iter S, in_iter E) { this->clear(); SmallVectorImpl<char>::append(S, E); } /// Assign from a StringRef. void assign(StringRef RHS) { this->clear(); SmallVectorImpl<char>::append(RHS.begin(), RHS.end()); } /// Assign from a SmallVector. void assign(const SmallVectorImpl<char> &RHS) { this->clear(); SmallVectorImpl<char>::append(RHS.begin(), RHS.end()); } /// @} /// @name String Concatenation /// @{ /// Append from an iterator pair. template<typename in_iter> void append(in_iter S, in_iter E) { SmallVectorImpl<char>::append(S, E); } void append(size_t NumInputs, char Elt) { SmallVectorImpl<char>::append(NumInputs, Elt); } /// Append from a StringRef. void append(StringRef RHS) { SmallVectorImpl<char>::append(RHS.begin(), RHS.end()); } /// Append from a SmallVector. void append(const SmallVectorImpl<char> &RHS) { SmallVectorImpl<char>::append(RHS.begin(), RHS.end()); } /// @} /// @name String Comparison /// @{ /// Check for string equality. This is more efficient than compare() when /// the relative ordering of inequal strings isn't needed. bool equals(StringRef RHS) const { return str().equals(RHS); } /// Check for string equality, ignoring case. bool equals_lower(StringRef RHS) const { return str().equals_lower(RHS); } /// Compare two strings; the result is -1, 0, or 1 if this string is /// lexicographically less than, equal to, or greater than the \p RHS. int compare(StringRef RHS) const { return str().compare(RHS); } /// compare_lower - Compare two strings, ignoring case. int compare_lower(StringRef RHS) const { return str().compare_lower(RHS); } /// compare_numeric - Compare two strings, treating sequences of digits as /// numbers. int compare_numeric(StringRef RHS) const { return str().compare_numeric(RHS); } /// @} /// @name String Predicates /// @{ /// startswith - Check if this string starts with the given \p Prefix. bool startswith(StringRef Prefix) const { return str().startswith(Prefix); } /// endswith - Check if this string ends with the given \p Suffix. bool endswith(StringRef Suffix) const { return str().endswith(Suffix); } /// @} /// @name String Searching /// @{ /// find - Search for the first character \p C in the string. /// /// \return - The index of the first occurrence of \p C, or npos if not /// found. size_t find(char C, size_t From = 0) const { return str().find(C, From); } /// Search for the first string \p Str in the string. /// /// \returns The index of the first occurrence of \p Str, or npos if not /// found. size_t find(StringRef Str, size_t From = 0) const { return str().find(Str, From); } /// Search for the last character \p C in the string. /// /// \returns The index of the last occurrence of \p C, or npos if not /// found. size_t rfind(char C, size_t From = StringRef::npos) const { return str().rfind(C, From); } /// Search for the last string \p Str in the string. /// /// \returns The index of the last occurrence of \p Str, or npos if not /// found. size_t rfind(StringRef Str) const { return str().rfind(Str); } /// Find the first character in the string that is \p C, or npos if not /// found. Same as find. size_t find_first_of(char C, size_t From = 0) const { return str().find_first_of(C, From); } /// Find the first character in the string that is in \p Chars, or npos if /// not found. /// /// Complexity: O(size() + Chars.size()) size_t find_first_of(StringRef Chars, size_t From = 0) const { return str().find_first_of(Chars, From); } /// Find the first character in the string that is not \p C or npos if not /// found. size_t find_first_not_of(char C, size_t From = 0) const { return str().find_first_not_of(C, From); } /// Find the first character in the string that is not in the string /// \p Chars, or npos if not found. /// /// Complexity: O(size() + Chars.size()) size_t find_first_not_of(StringRef Chars, size_t From = 0) const { return str().find_first_not_of(Chars, From); } /// Find the last character in the string that is \p C, or npos if not /// found. size_t find_last_of(char C, size_t From = StringRef::npos) const { return str().find_last_of(C, From); } /// Find the last character in the string that is in \p C, or npos if not /// found. /// /// Complexity: O(size() + Chars.size()) size_t find_last_of( StringRef Chars, size_t From = StringRef::npos) const { return str().find_last_of(Chars, From); } /// @} /// @name Helpful Algorithms /// @{ /// Return the number of occurrences of \p C in the string. size_t count(char C) const { return str().count(C); } /// Return the number of non-overlapped occurrences of \p Str in the /// string. size_t count(StringRef Str) const { return str().count(Str); } /// @} /// @name Substring Operations /// @{ /// Return a reference to the substring from [Start, Start + N). /// /// \param Start The index of the starting character in the substring; if /// the index is npos or greater than the length of the string then the /// empty substring will be returned. /// /// \param N The number of characters to included in the substring. If \p N /// exceeds the number of characters remaining in the string, the string /// suffix (starting with \p Start) will be returned. StringRef substr(size_t Start, size_t N = StringRef::npos) const { return str().substr(Start, N); } /// Return a reference to the substring from [Start, End). /// /// \param Start The index of the starting character in the substring; if /// the index is npos or greater than the length of the string then the /// empty substring will be returned. /// /// \param End The index following the last character to include in the /// substring. If this is npos, or less than \p Start, or exceeds the /// number of characters remaining in the string, the string suffix /// (starting with \p Start) will be returned. StringRef slice(size_t Start, size_t End) const { return str().slice(Start, End); } // Extra methods. /// Explicit conversion to StringRef. StringRef str() const { return StringRef(this->begin(), this->size()); } // TODO: Make this const, if it's safe... const char* c_str() { this->push_back(0); this->pop_back(); return this->data(); } /// Implicit conversion to StringRef. operator StringRef() const { return str(); } // Extra operators. const SmallString &operator=(StringRef RHS) { this->clear(); return *this += RHS; } SmallString &operator+=(StringRef RHS) { this->append(RHS.begin(), RHS.end()); return *this; } SmallString &operator+=(char C) { this->push_back(C); return *this; } }; } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ADT/STLExtras.h
//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains some templates that are useful if you are working with the // STL at all. // // No library is required when using these functions. // //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_STLEXTRAS_H #define LLVM_ADT_STLEXTRAS_H #include "dxc/WinAdapter.h" // HLSL Change #include "llvm/Support/Compiler.h" #include <algorithm> // for std::all_of #include <cassert> #include <cstddef> // for std::size_t #include <cstdlib> // for qsort #include <functional> #include <iterator> #include <memory> #include <utility> // for std::pair #include "llvm/ADT/Optional.h" #include "llvm/ADT/iterator.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Support/Compiler.h" namespace llvm { namespace detail { template <typename RangeT> using IterOfRange = decltype(std::begin(std::declval<RangeT>())); } // End detail namespace //===----------------------------------------------------------------------===// // Extra additions to <functional> //===----------------------------------------------------------------------===// template<class Ty> struct identity { using argument_type = Ty; Ty &operator()(Ty &self) const { return self; } const Ty &operator()(const Ty &self) const { return self; } }; template<class Ty> struct less_ptr { bool operator()(const Ty* left, const Ty* right) const { return *left < *right; } }; template<class Ty> struct greater_ptr { bool operator()(const Ty* left, const Ty* right) const { return *right < *left; } }; /// An efficient, type-erasing, non-owning reference to a callable. This is /// intended for use as the type of a function parameter that is not used /// after the function in question returns. /// /// This class does not own the callable, so it is not in general safe to store /// a function_ref. template<typename Fn> class function_ref; template<typename Ret, typename ...Params> class function_ref<Ret(Params...)> { Ret (*callback)(intptr_t callable, Params ...params); intptr_t callable; template<typename Callable> static Ret callback_fn(intptr_t callable, Params ...params) { return (*reinterpret_cast<Callable*>(callable))( std::forward<Params>(params)...); } public: template <typename Callable> function_ref(Callable &&callable, typename std::enable_if< !std::is_same<typename std::remove_reference<Callable>::type, function_ref>::value>::type * = nullptr) : callback(callback_fn<typename std::remove_reference<Callable>::type>), callable(reinterpret_cast<intptr_t>(&callable)) {} Ret operator()(Params ...params) const { return callback(callable, std::forward<Params>(params)...); } }; // deleter - Very very very simple method that is used to invoke operator // delete on something. It is used like this: // // for_each(V.begin(), B.end(), deleter<Interval>); // template <class T> inline void deleter(T *Ptr) { delete Ptr; } //===----------------------------------------------------------------------===// // Extra additions to <iterator> //===----------------------------------------------------------------------===// // mapped_iterator - This is a simple iterator adapter that causes a function to // be dereferenced whenever operator* is invoked on the iterator. // template <class RootIt, class UnaryFunc> class mapped_iterator { RootIt current; UnaryFunc Fn; public: typedef typename std::iterator_traits<RootIt>::iterator_category iterator_category; typedef typename std::iterator_traits<RootIt>::difference_type difference_type; typedef decltype(std::declval<UnaryFunc>()(*std::declval<RootIt>())) value_type; typedef void pointer; //typedef typename UnaryFunc::result_type *pointer; typedef void reference; // Can't modify value returned by fn typedef RootIt iterator_type; inline const RootIt &getCurrent() const { return current; } inline const UnaryFunc &getFunc() const { return Fn; } inline explicit mapped_iterator(const RootIt &I, UnaryFunc F) : current(I), Fn(F) {} inline value_type operator*() const { // All this work to do this return Fn(*current); // little change } mapped_iterator &operator++() { ++current; return *this; } mapped_iterator &operator--() { --current; return *this; } mapped_iterator operator++(int) { mapped_iterator __tmp = *this; ++current; return __tmp; } mapped_iterator operator--(int) { mapped_iterator __tmp = *this; --current; return __tmp; } mapped_iterator operator+(difference_type n) const { return mapped_iterator(current + n, Fn); } mapped_iterator &operator+=(difference_type n) { current += n; return *this; } mapped_iterator operator-(difference_type n) const { return mapped_iterator(current - n, Fn); } mapped_iterator &operator-=(difference_type n) { current -= n; return *this; } reference operator[](difference_type n) const { return *(*this + n); } bool operator!=(const mapped_iterator &X) const { return !operator==(X); } bool operator==(const mapped_iterator &X) const { return current == X.current; } bool operator<(const mapped_iterator &X) const { return current < X.current; } difference_type operator-(const mapped_iterator &X) const { return current - X.current; } }; template <class Iterator, class Func> inline mapped_iterator<Iterator, Func> operator+(typename mapped_iterator<Iterator, Func>::difference_type N, const mapped_iterator<Iterator, Func> &X) { return mapped_iterator<Iterator, Func>(X.getCurrent() - N, X.getFunc()); } // map_iterator - Provide a convenient way to create mapped_iterators, just like // make_pair is useful for creating pairs... // template <class ItTy, class FuncTy> inline mapped_iterator<ItTy, FuncTy> map_iterator(const ItTy &I, FuncTy F) { return mapped_iterator<ItTy, FuncTy>(I, F); } /// Helper to determine if type T has a member called rbegin(). template <typename Ty> class has_rbegin_impl { typedef char yes[1]; typedef char no[2]; template <typename Inner> static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr); template <typename> static no& test(...); public: static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes); }; /// Metafunction to determine if T& or T has a member called rbegin(). template <typename Ty> struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> { }; // Returns an iterator_range over the given container which iterates in reverse. // Note that the container must have rbegin()/rend() methods for this to work. template <typename ContainerTy> auto reverse(ContainerTy &&C, typename std::enable_if<has_rbegin<ContainerTy>::value>::type * = nullptr) -> decltype(make_range(C.rbegin(), C.rend())) { return make_range(C.rbegin(), C.rend()); } // Returns a std::reverse_iterator wrapped around the given iterator. template <typename IteratorTy> std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) { return std::reverse_iterator<IteratorTy>(It); } // Returns an iterator_range over the given container which iterates in reverse. // Note that the container must have begin()/end() methods which return // bidirectional iterators for this to work. template <typename ContainerTy> auto reverse( ContainerTy &&C, typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr) -> decltype(make_range(make_reverse_iterator(std::end(C)), make_reverse_iterator(std::begin(C)))) { return make_range(make_reverse_iterator(std::end(C)), make_reverse_iterator(std::begin(C))); } /// An iterator adaptor that filters the elements of given inner iterators. /// /// The predicate parameter should be a callable object that accepts the wrapped /// iterator's reference type and returns a bool. When incrementing or /// decrementing the iterator, it will call the predicate on each element and /// skip any where it returns false. /// /// \code /// int A[] = { 1, 2, 3, 4 }; /// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; }); /// // R contains { 1, 3 }. /// \endcode template <typename WrappedIteratorT, typename PredicateT> class filter_iterator : public iterator_adaptor_base< filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT, typename std::common_type< std::forward_iterator_tag, typename std::iterator_traits< WrappedIteratorT>::iterator_category>::type> { using BaseT = iterator_adaptor_base< filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT, typename std::common_type< std::forward_iterator_tag, typename std::iterator_traits<WrappedIteratorT>::iterator_category>:: type>; struct PayloadType { WrappedIteratorT End; PredicateT Pred; }; Optional<PayloadType> Payload; void findNextValid() { assert(Payload && "Payload should be engaged when findNextValid is called"); while (this->I != Payload->End && !Payload->Pred(*this->I)) BaseT::operator++(); } // Construct the begin iterator. The begin iterator requires to know where end // is, so that it can properly stop when it hits end. filter_iterator(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred) : BaseT(std::move(Begin)), Payload(PayloadType{std::move(End), std::move(Pred)}) { findNextValid(); } // Construct the end iterator. It's not incrementable, so Payload doesn't // have to be engaged. filter_iterator(WrappedIteratorT End) : BaseT(End) {} public: using BaseT::operator++; filter_iterator &operator++() { BaseT::operator++(); findNextValid(); return *this; } template <typename RT, typename PT> friend iterator_range<filter_iterator<detail::IterOfRange<RT>, PT>> make_filter_range(RT &&, PT); }; /// Convenience function that takes a range of elements and a predicate, /// and return a new filter_iterator range. /// /// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the /// lifetime of that temporary is not kept by the returned range object, and the /// temporary is going to be dropped on the floor after the make_iterator_range /// full expression that contains this function call. template <typename RangeT, typename PredicateT> iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>> make_filter_range(RangeT &&Range, PredicateT Pred) { using FilterIteratorT = filter_iterator<detail::IterOfRange<RangeT>, PredicateT>; return make_range(FilterIteratorT(std::begin(std::forward<RangeT>(Range)), std::end(std::forward<RangeT>(Range)), std::move(Pred)), FilterIteratorT(std::end(std::forward<RangeT>(Range)))); } // forward declarations required by zip_shortest/zip_first template <typename R, class UnaryPredicate> bool all_of(R &&range, UnaryPredicate &&P); template <size_t... I> struct index_sequence; template <class... Ts> struct index_sequence_for; namespace detail { template <typename... Iters> class zip_first { public: typedef std::input_iterator_tag iterator_category; typedef std::tuple<decltype(*std::declval<Iters>())...> value_type; std::tuple<Iters...> iterators; private: template <size_t... Ns> value_type deres(index_sequence<Ns...>) { return value_type(*std::get<Ns>(iterators)...); } template <size_t... Ns> decltype(iterators) tup_inc(index_sequence<Ns...>) { return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...); } public: value_type operator*() { return deres(index_sequence_for<Iters...>{}); } void operator++() { iterators = tup_inc(index_sequence_for<Iters...>{}); } bool operator!=(const zip_first<Iters...> &other) const { return std::get<0>(iterators) != std::get<0>(other.iterators); } zip_first(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {} }; template <typename... Iters> class zip_shortest : public zip_first<Iters...> { template <size_t... Ns> bool test(const zip_first<Iters...> &other, index_sequence<Ns...>) const { return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) != std::get<Ns>(other.iterators)...}, identity<bool>{}); } public: bool operator!=(const zip_first<Iters...> &other) const { return test(other, index_sequence_for<Iters...>{}); } zip_shortest(Iters &&... ts) : zip_first<Iters...>(std::forward<Iters>(ts)...) {} }; template <template <typename...> class ItType, typename... Args> class zippy { public: typedef ItType<decltype(std::begin(std::declval<Args>()))...> iterator; private: std::tuple<Args...> ts; template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) { return iterator(std::begin(std::get<Ns>(ts))...); } template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) { return iterator(std::end(std::get<Ns>(ts))...); } public: iterator begin() { return begin_impl(index_sequence_for<Args...>{}); } iterator end() { return end_impl(index_sequence_for<Args...>{}); } zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {} }; } // End detail namespace /// zip iterator for two or more iteratable types. template <typename T, typename U, typename... Args> detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u, Args &&... args) { return detail::zippy<detail::zip_shortest, T, U, Args...>( std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); } /// zip iterator that, for the sake of efficiency, assumes the first iteratee to /// be the shortest. template <typename T, typename U, typename... Args> detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u, Args &&... args) { return detail::zippy<detail::zip_first, T, U, Args...>( std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); } //===----------------------------------------------------------------------===// // Extra additions to <utility> //===----------------------------------------------------------------------===// /// \brief Function object to check whether the first component of a std::pair /// compares less than the first component of another std::pair. struct less_first { template <typename T> bool operator()(const T &lhs, const T &rhs) const { return lhs.first < rhs.first; } }; /// \brief Function object to check whether the second component of a std::pair /// compares less than the second component of another std::pair. struct less_second { template <typename T> bool operator()(const T &lhs, const T &rhs) const { return lhs.second < rhs.second; } }; // A subset of N3658. More stuff can be added as-needed. /// \brief Represents a compile-time sequence of integers. template <class T, T... I> struct integer_sequence { typedef T value_type; static LLVM_CONSTEXPR size_t size() { return sizeof...(I); } }; /// \brief Alias for the common case of a sequence of size_ts. template <size_t... I> struct index_sequence : integer_sequence<std::size_t, I...> {}; template <std::size_t N, std::size_t... I> struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {}; template <std::size_t... I> struct build_index_impl<0, I...> : index_sequence<I...> {}; /// \brief Creates a compile-time integer sequence for a parameter pack. template <class... Ts> struct index_sequence_for : build_index_impl<sizeof...(Ts)> {}; //===----------------------------------------------------------------------===// // Extra additions for arrays //===----------------------------------------------------------------------===// /// Find the length of an array. template <class T, std::size_t N> LLVM_CONSTEXPR inline size_t array_lengthof(T (&)[N]) { return N; } /// Adapt std::less<T> for array_pod_sort. // HLSL Change: changed calling convention to __cdecl template<typename T> inline int __cdecl array_pod_sort_comparator(const void *P1, const void *P2) { if (std::less<T>()(*reinterpret_cast<const T*>(P1), *reinterpret_cast<const T*>(P2))) return -1; if (std::less<T>()(*reinterpret_cast<const T*>(P2), *reinterpret_cast<const T*>(P1))) return 1; return 0; } /// get_array_pod_sort_comparator - This is an internal helper function used to /// get type deduction of T right. // // HLSL Change: changed calling convention to __cdecl // HLSL Change: pulled this out into a typdef to make it easier to make change typedef int(__cdecl *llvm_cmp_func)(const void *, const void *); template<typename T> inline llvm_cmp_func get_array_pod_sort_comparator(const T &) { return array_pod_sort_comparator<T>; } /// array_pod_sort - This sorts an array with the specified start and end /// extent. This is just like std::sort, except that it calls qsort instead of /// using an inlined template. qsort is slightly slower than std::sort, but /// most sorts are not performance critical in LLVM and std::sort has to be /// template instantiated for each type, leading to significant measured code /// bloat. This function should generally be used instead of std::sort where /// possible. /// /// This function assumes that you have simple POD-like types that can be /// compared with std::less and can be moved with memcpy. If this isn't true, /// you should use std::sort. /// /// NOTE: If qsort_r were portable, we could allow a custom comparator and /// default to std::less. template<class IteratorTy> inline void array_pod_sort(IteratorTy Start, IteratorTy End) { // Don't inefficiently call qsort with one element or trigger undefined // behavior with an empty sequence. auto NElts = End - Start; if (NElts <= 1) return; qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start)); } // HLSL Change: changed calling convention of Compare to __cdecl template <class IteratorTy> inline void array_pod_sort( IteratorTy Start, IteratorTy End, int (__cdecl *Compare)( const typename std::iterator_traits<IteratorTy>::value_type *, const typename std::iterator_traits<IteratorTy>::value_type *)) { // Don't inefficiently call qsort with one element or trigger undefined // behavior with an empty sequence. auto NElts = End - Start; if (NElts <= 1) return; qsort(&*Start, NElts, sizeof(*Start), reinterpret_cast<int (__cdecl *)(const void *, const void *)>(Compare)); // HLSL Change - __cdecl } //===----------------------------------------------------------------------===// // Extra additions to <algorithm> //===----------------------------------------------------------------------===// /// For a container of pointers, deletes the pointers and then clears the /// container. template<typename Container> void DeleteContainerPointers(Container &C) { for (typename Container::iterator I = C.begin(), E = C.end(); I != E; ++I) delete *I; C.clear(); } /// In a container of pairs (usually a map) whose second element is a pointer, /// deletes the second elements and then clears the container. template<typename Container> void DeleteContainerSeconds(Container &C) { for (typename Container::iterator I = C.begin(), E = C.end(); I != E; ++I) delete I->second; C.clear(); } /// Provide wrappers to std::all_of which take ranges instead of having to pass /// being/end explicitly. template<typename R, class UnaryPredicate> bool all_of(R &&Range, UnaryPredicate &&P) { return std::all_of(Range.begin(), Range.end(), std::forward<UnaryPredicate>(P)); } //===----------------------------------------------------------------------===// // Extra additions to <memory> // // /////////////////////////////////////////////////////////////////////////////// // Implement make_unique according to N3656. /// \brief Constructs a `new T()` with the given args and returns a /// `unique_ptr<T>` which owns the object. /// /// Example: /// /// auto p = make_unique<int>(); /// auto p = make_unique<std::tuple<int, int>>(0, 1); template <class T, class... Args> typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type make_unique(Args &&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } /// \brief Constructs a `new T[n]` with the given args and returns a /// `unique_ptr<T[]>` which owns the object. /// /// \param n size of the new array. /// /// Example: /// /// auto p = make_unique<int[]>(2); // value-initializes the array with 0's. template <class T> typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0, std::unique_ptr<T>>::type make_unique(size_t n) { return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]()); } /// This function isn't used and is only here to provide better compile errors. template <class T, class... Args> typename std::enable_if<std::extent<T>::value != 0>::type make_unique(Args &&...) = delete; struct FreeDeleter { void operator()(void* v) { ::free(v); } }; template<typename First, typename Second> struct pair_hash { size_t operator()(const std::pair<First, Second> &P) const { return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second); } }; /// A functor like C++14's std::less<void> in its absence. struct less { template <typename A, typename B> bool operator()(A &&a, B &&b) const { return std::forward<A>(a) < std::forward<B>(b); } }; /// A functor like C++14's std::equal<void> in its absence. struct equal { template <typename A, typename B> bool operator()(A &&a, B &&b) const { return std::forward<A>(a) == std::forward<B>(b); } }; /// Binary functor that adapts to any other binary functor after dereferencing /// operands. template <typename T> struct deref { T func; // Could be further improved to cope with non-derivable functors and // non-binary functors (should be a variadic template member function // operator()). template <typename A, typename B> auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) { assert(lhs); assert(rhs); return func(*lhs, *rhs); } }; } // End llvm namespace #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ADT/Statistic.h
//===-- llvm/ADT/Statistic.h - Easy way to expose stats ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the 'Statistic' class, which is designed to be an easy way // to expose various metrics from passes. These statistics are printed at the // end of a run (from llvm_shutdown), when the -stats command line option is // passed on the command line. // // This is useful for reporting information like the number of instructions // simplified, optimized or removed by various transformations, like this: // // static Statistic NumInstsKilled("gcse", "Number of instructions killed"); // // Later, in the code: ++NumInstsKilled; // // NOTE: Statistics *must* be declared as global variables. // //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_STATISTIC_H #define LLVM_ADT_STATISTIC_H #include "llvm/Support/Atomic.h" #include "llvm/Support/Valgrind.h" namespace llvm { class raw_ostream; class Statistic { public: const char *Name; const char *Desc; volatile llvm::sys::cas_flag Value; bool Initialized; llvm::sys::cas_flag getValue() const { return Value; } const char *getName() const { return Name; } const char *getDesc() const { return Desc; } /// construct - This should only be called for non-global statistics. void construct(const char *name, const char *desc) { Name = name; Desc = desc; Value = 0; Initialized = false; } // Allow use of this class as the value itself. operator unsigned() const { return Value; } #if (!defined(NDEBUG) || defined(LLVM_ENABLE_STATS)) && 0 // HLSL Change - always disable, shouldn't do process-wide alloc in compile const Statistic &operator=(unsigned Val) { Value = Val; return init(); } const Statistic &operator++() { // FIXME: This function and all those that follow carefully use an // atomic operation to update the value safely in the presence of // concurrent accesses, but not to read the return value, so the // return value is not thread safe. sys::AtomicIncrement(&Value); return init(); } unsigned operator++(int) { init(); unsigned OldValue = Value; sys::AtomicIncrement(&Value); return OldValue; } const Statistic &operator--() { sys::AtomicDecrement(&Value); return init(); } unsigned operator--(int) { init(); unsigned OldValue = Value; sys::AtomicDecrement(&Value); return OldValue; } const Statistic &operator+=(const unsigned &V) { if (!V) return *this; sys::AtomicAdd(&Value, V); return init(); } const Statistic &operator-=(const unsigned &V) { if (!V) return *this; sys::AtomicAdd(&Value, -V); return init(); } const Statistic &operator*=(const unsigned &V) { sys::AtomicMul(&Value, V); return init(); } const Statistic &operator/=(const unsigned &V) { sys::AtomicDiv(&Value, V); return init(); } #else // Statistics are disabled in release builds. const Statistic &operator=(unsigned Val) { return *this; } const Statistic &operator++() { return *this; } unsigned operator++(int) { return 0; } const Statistic &operator--() { return *this; } unsigned operator--(int) { return 0; } const Statistic &operator+=(const unsigned &V) { return *this; } const Statistic &operator-=(const unsigned &V) { return *this; } const Statistic &operator*=(const unsigned &V) { return *this; } const Statistic &operator/=(const unsigned &V) { return *this; } #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_STATS) protected: Statistic &init() { bool tmp = Initialized; sys::MemoryFence(); if (!tmp) RegisterStatistic(); TsanHappensAfter(this); return *this; } void RegisterStatistic(); }; // STATISTIC - A macro to make definition of statistics really simple. This // automatically passes the DEBUG_TYPE of the file into the statistic. #define STATISTIC(VARNAME, DESC) \ static llvm::Statistic VARNAME = { DEBUG_TYPE, DESC, 0, 0 } /// \brief Enable the collection and printing of statistics. void EnableStatistics(); /// \brief Check if statistics are enabled. bool AreStatisticsEnabled(); /// \brief Print statistics to the file returned by CreateInfoOutputFile(). void PrintStatistics(); /// \brief Print statistics to the given output stream. void PrintStatistics(raw_ostream &OS); } // End llvm namespace #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ADT/ScopedHashTable.h
//===- ScopedHashTable.h - A simple scoped hash table ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements an efficient scoped hash table, which is useful for // things like dominator-based optimizations. This allows clients to do things // like this: // // ScopedHashTable<int, int> HT; // { // ScopedHashTableScope<int, int> Scope1(HT); // HT.insert(0, 0); // HT.insert(1, 1); // { // ScopedHashTableScope<int, int> Scope2(HT); // HT.insert(0, 42); // } // } // // Looking up the value for "0" in the Scope2 block will return 42. Looking // up the value for 0 before 42 is inserted or after Scope2 is popped will // return 0. // //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_SCOPEDHASHTABLE_H #define LLVM_ADT_SCOPEDHASHTABLE_H #include "llvm/ADT/DenseMap.h" #include "llvm/Support/Allocator.h" namespace llvm { template <typename K, typename V, typename KInfo = DenseMapInfo<K>, typename AllocatorTy = MallocAllocator> class ScopedHashTable; template <typename K, typename V> class ScopedHashTableVal { ScopedHashTableVal *NextInScope; ScopedHashTableVal *NextForKey; K Key; V Val; ScopedHashTableVal(const K &key, const V &val) : Key(key), Val(val) {} public: const K &getKey() const { return Key; } const V &getValue() const { return Val; } V &getValue() { return Val; } ScopedHashTableVal *getNextForKey() { return NextForKey; } const ScopedHashTableVal *getNextForKey() const { return NextForKey; } ScopedHashTableVal *getNextInScope() { return NextInScope; } template <typename AllocatorTy> static ScopedHashTableVal *Create(ScopedHashTableVal *nextInScope, ScopedHashTableVal *nextForKey, const K &key, const V &val, AllocatorTy &Allocator) { ScopedHashTableVal *New = Allocator.template Allocate<ScopedHashTableVal>(); // Set up the value. new (New) ScopedHashTableVal(key, val); New->NextInScope = nextInScope; New->NextForKey = nextForKey; return New; } template <typename AllocatorTy> void Destroy(AllocatorTy &Allocator) { // Free memory referenced by the item. this->~ScopedHashTableVal(); Allocator.Deallocate(this); } }; template <typename K, typename V, typename KInfo = DenseMapInfo<K>, typename AllocatorTy = MallocAllocator> class ScopedHashTableScope { /// HT - The hashtable that we are active for. ScopedHashTable<K, V, KInfo, AllocatorTy> &HT; /// PrevScope - This is the scope that we are shadowing in HT. ScopedHashTableScope *PrevScope; /// LastValInScope - This is the last value that was inserted for this scope /// or null if none have been inserted yet. ScopedHashTableVal<K, V> *LastValInScope; void operator=(ScopedHashTableScope&) = delete; ScopedHashTableScope(ScopedHashTableScope&) = delete; public: ScopedHashTableScope(ScopedHashTable<K, V, KInfo, AllocatorTy> &HT); ~ScopedHashTableScope(); ScopedHashTableScope *getParentScope() { return PrevScope; } const ScopedHashTableScope *getParentScope() const { return PrevScope; } private: friend class ScopedHashTable<K, V, KInfo, AllocatorTy>; ScopedHashTableVal<K, V> *getLastValInScope() { return LastValInScope; } void setLastValInScope(ScopedHashTableVal<K, V> *Val) { LastValInScope = Val; } }; template <typename K, typename V, typename KInfo = DenseMapInfo<K> > class ScopedHashTableIterator { ScopedHashTableVal<K, V> *Node; public: ScopedHashTableIterator(ScopedHashTableVal<K, V> *node) : Node(node) {} V &operator*() const { assert(Node && "Dereference end()"); return Node->getValue(); } V *operator->() const { return &Node->getValue(); } bool operator==(const ScopedHashTableIterator &RHS) const { return Node == RHS.Node; } bool operator!=(const ScopedHashTableIterator &RHS) const { return Node != RHS.Node; } inline ScopedHashTableIterator& operator++() { // Preincrement assert(Node && "incrementing past end()"); Node = Node->getNextForKey(); return *this; } ScopedHashTableIterator operator++(int) { // Postincrement ScopedHashTableIterator tmp = *this; ++*this; return tmp; } }; template <typename K, typename V, typename KInfo, typename AllocatorTy> class ScopedHashTable { public: /// ScopeTy - This is a helpful typedef that allows clients to get easy access /// to the name of the scope for this hash table. typedef ScopedHashTableScope<K, V, KInfo, AllocatorTy> ScopeTy; typedef unsigned size_type; private: typedef ScopedHashTableVal<K, V> ValTy; DenseMap<K, ValTy*, KInfo> TopLevelMap; ScopeTy *CurScope; AllocatorTy Allocator; ScopedHashTable(const ScopedHashTable&); // NOT YET IMPLEMENTED void operator=(const ScopedHashTable&); // NOT YET IMPLEMENTED friend class ScopedHashTableScope<K, V, KInfo, AllocatorTy>; public: ScopedHashTable() : CurScope(nullptr) {} ScopedHashTable(AllocatorTy A) : CurScope(0), Allocator(A) {} ~ScopedHashTable() { assert(!CurScope && TopLevelMap.empty() && "Scope imbalance!"); } /// Access to the allocator. AllocatorTy &getAllocator() { return Allocator; } const AllocatorTy &getAllocator() const { return Allocator; } /// Return 1 if the specified key is in the table, 0 otherwise. size_type count(const K &Key) const { return TopLevelMap.count(Key); } V lookup(const K &Key) { typename DenseMap<K, ValTy*, KInfo>::iterator I = TopLevelMap.find(Key); if (I != TopLevelMap.end()) return I->second->getValue(); return V(); } void insert(const K &Key, const V &Val) { insertIntoScope(CurScope, Key, Val); } typedef ScopedHashTableIterator<K, V, KInfo> iterator; iterator end() { return iterator(0); } iterator begin(const K &Key) { typename DenseMap<K, ValTy*, KInfo>::iterator I = TopLevelMap.find(Key); if (I == TopLevelMap.end()) return end(); return iterator(I->second); } ScopeTy *getCurScope() { return CurScope; } const ScopeTy *getCurScope() const { return CurScope; } /// insertIntoScope - This inserts the specified key/value at the specified /// (possibly not the current) scope. While it is ok to insert into a scope /// that isn't the current one, it isn't ok to insert *underneath* an existing /// value of the specified key. void insertIntoScope(ScopeTy *S, const K &Key, const V &Val) { assert(S && "No scope active!"); ScopedHashTableVal<K, V> *&KeyEntry = TopLevelMap[Key]; KeyEntry = ValTy::Create(S->getLastValInScope(), KeyEntry, Key, Val, Allocator); S->setLastValInScope(KeyEntry); } }; /// ScopedHashTableScope ctor - Install this as the current scope for the hash /// table. template <typename K, typename V, typename KInfo, typename Allocator> ScopedHashTableScope<K, V, KInfo, Allocator>:: ScopedHashTableScope(ScopedHashTable<K, V, KInfo, Allocator> &ht) : HT(ht) { PrevScope = HT.CurScope; HT.CurScope = this; LastValInScope = nullptr; } template <typename K, typename V, typename KInfo, typename Allocator> ScopedHashTableScope<K, V, KInfo, Allocator>::~ScopedHashTableScope() { assert(HT.CurScope == this && "Scope imbalance!"); HT.CurScope = PrevScope; // Pop and delete all values corresponding to this scope. while (ScopedHashTableVal<K, V> *ThisEntry = LastValInScope) { // Pop this value out of the TopLevelMap. if (!ThisEntry->getNextForKey()) { assert(HT.TopLevelMap[ThisEntry->getKey()] == ThisEntry && "Scope imbalance!"); HT.TopLevelMap.erase(ThisEntry->getKey()); } else { ScopedHashTableVal<K, V> *&KeyEntry = HT.TopLevelMap[ThisEntry->getKey()]; assert(KeyEntry == ThisEntry && "Scope imbalance!"); KeyEntry = ThisEntry->getNextForKey(); } // Pop this value out of the scope. LastValInScope = ThisEntry->getNextInScope(); // Delete this entry. ThisEntry->Destroy(HT.getAllocator()); } } } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ADT/DenseSet.h
//===- llvm/ADT/DenseSet.h - Dense probed hash table ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the DenseSet class. // //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_DENSESET_H #define LLVM_ADT_DENSESET_H #include "llvm/ADT/DenseMap.h" namespace llvm { namespace detail { struct DenseSetEmpty {}; // Use the empty base class trick so we can create a DenseMap where the buckets // contain only a single item. template <typename KeyT> class DenseSetPair : public DenseSetEmpty { KeyT key; public: KeyT &getFirst() { return key; } const KeyT &getFirst() const { return key; } DenseSetEmpty &getSecond() { return *this; } const DenseSetEmpty &getSecond() const { return *this; } }; } /// DenseSet - This implements a dense probed hash-table based set. template<typename ValueT, typename ValueInfoT = DenseMapInfo<ValueT> > class DenseSet { typedef DenseMap<ValueT, detail::DenseSetEmpty, ValueInfoT, detail::DenseSetPair<ValueT>> MapTy; static_assert(sizeof(typename MapTy::value_type) == sizeof(ValueT), "DenseMap buckets unexpectedly large!"); MapTy TheMap; public: typedef ValueT key_type; typedef ValueT value_type; typedef unsigned size_type; explicit DenseSet(unsigned NumInitBuckets = 0) : TheMap(NumInitBuckets) {} bool empty() const { return TheMap.empty(); } size_type size() const { return TheMap.size(); } size_t getMemorySize() const { return TheMap.getMemorySize(); } /// Grow the DenseSet so that it has at least Size buckets. Will not shrink /// the Size of the set. void resize(size_t Size) { TheMap.resize(Size); } void clear() { TheMap.clear(); } /// Return 1 if the specified key is in the set, 0 otherwise. size_type count(const ValueT &V) const { return TheMap.count(V); } bool erase(const ValueT &V) { return TheMap.erase(V); } void swap(DenseSet& RHS) { TheMap.swap(RHS.TheMap); } // Iterators. class Iterator { typename MapTy::iterator I; friend class DenseSet; public: typedef typename MapTy::iterator::difference_type difference_type; typedef ValueT value_type; typedef value_type *pointer; typedef value_type &reference; typedef std::forward_iterator_tag iterator_category; Iterator(const typename MapTy::iterator &i) : I(i) {} ValueT &operator*() { return I->getFirst(); } ValueT *operator->() { return &I->getFirst(); } Iterator& operator++() { ++I; return *this; } bool operator==(const Iterator& X) const { return I == X.I; } bool operator!=(const Iterator& X) const { return I != X.I; } }; class ConstIterator { typename MapTy::const_iterator I; friend class DenseSet; public: typedef typename MapTy::const_iterator::difference_type difference_type; typedef ValueT value_type; typedef value_type *pointer; typedef value_type &reference; typedef std::forward_iterator_tag iterator_category; ConstIterator(const typename MapTy::const_iterator &i) : I(i) {} const ValueT &operator*() { return I->getFirst(); } const ValueT *operator->() { return &I->getFirst(); } ConstIterator& operator++() { ++I; return *this; } bool operator==(const ConstIterator& X) const { return I == X.I; } bool operator!=(const ConstIterator& X) const { return I != X.I; } }; typedef Iterator iterator; typedef ConstIterator const_iterator; iterator begin() { return Iterator(TheMap.begin()); } iterator end() { return Iterator(TheMap.end()); } const_iterator begin() const { return ConstIterator(TheMap.begin()); } const_iterator end() const { return ConstIterator(TheMap.end()); } iterator find(const ValueT &V) { return Iterator(TheMap.find(V)); } /// Alternative version of find() which allows a different, and possibly less /// expensive, key type. /// The DenseMapInfo is responsible for supplying methods /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key type /// used. template <class LookupKeyT> iterator find_as(const LookupKeyT &Val) { return Iterator(TheMap.find_as(Val)); } template <class LookupKeyT> const_iterator find_as(const LookupKeyT &Val) const { return ConstIterator(TheMap.find_as(Val)); } void erase(Iterator I) { return TheMap.erase(I.I); } void erase(ConstIterator CI) { return TheMap.erase(CI.I); } std::pair<iterator, bool> insert(const ValueT &V) { detail::DenseSetEmpty Empty; return TheMap.insert(std::make_pair(V, Empty)); } // Range insertion of values. template<typename InputIt> void insert(InputIt I, InputIt E) { for (; I != E; ++I) insert(*I); } }; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/TableGen/StringToOffsetTable.h
//===- StringToOffsetTable.h - Emit a big concatenated string ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TABLEGEN_STRINGTOOFFSETTABLE_H #define LLVM_TABLEGEN_STRINGTOOFFSETTABLE_H #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/raw_ostream.h" #include <cctype> namespace llvm { /// StringToOffsetTable - This class uniques a bunch of nul-terminated strings /// and keeps track of their offset in a massive contiguous string allocation. /// It can then output this string blob and use indexes into the string to /// reference each piece. class StringToOffsetTable { StringMap<unsigned> StringOffset; std::string AggregateString; public: unsigned GetOrAddStringOffset(StringRef Str, bool appendZero = true) { auto IterBool = StringOffset.insert(std::make_pair(Str, AggregateString.size())); if (IterBool.second) { // Add the string to the aggregate if this is the first time found. AggregateString.append(Str.begin(), Str.end()); if (appendZero) AggregateString += '\0'; } return IterBool.first->second; } void EmitString(raw_ostream &O) { // Escape the string. SmallString<256> Str; raw_svector_ostream(Str).write_escaped(AggregateString); AggregateString = Str.str(); O << " \""; unsigned CharsPrinted = 0; for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) { if (CharsPrinted > 70) { O << "\"\n \""; CharsPrinted = 0; } O << AggregateString[i]; ++CharsPrinted; // Print escape sequences all together. if (AggregateString[i] != '\\') continue; assert(i+1 < AggregateString.size() && "Incomplete escape sequence!"); if (isdigit(AggregateString[i+1])) { assert(isdigit(AggregateString[i+2]) && isdigit(AggregateString[i+3]) && "Expected 3 digit octal escape!"); O << AggregateString[++i]; O << AggregateString[++i]; O << AggregateString[++i]; CharsPrinted += 3; } else { O << AggregateString[++i]; ++CharsPrinted; } } O << "\""; } }; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/TableGen/SetTheory.h
//===- SetTheory.h - Generate ordered sets from DAG expressions -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the SetTheory class that computes ordered sets of // Records from DAG expressions. Operators for standard set operations are // predefined, and it is possible to add special purpose set operators as well. // // The user may define named sets as Records of predefined classes. Set // expanders can be added to a SetTheory instance to teach it how to find the // elements of such a named set. // // These are the predefined operators. The argument lists can be individual // elements (defs), other sets (defs of expandable classes), lists, or DAG // expressions that are evaluated recursively. // // - (add S1, S2 ...) Union sets. This is also how sets are created from element // lists. // // - (sub S1, S2, ...) Set difference. Every element in S1 except for the // elements in S2, ... // // - (and S1, S2) Set intersection. Every element in S1 that is also in S2. // // - (shl S, N) Shift left. Remove the first N elements from S. // // - (trunc S, N) Truncate. The first N elements of S. // // - (rotl S, N) Rotate left. Same as (add (shl S, N), (trunc S, N)). // // - (rotr S, N) Rotate right. // // - (decimate S, N) Decimate S by picking every N'th element, starting with // the first one. For instance, (decimate S, 2) returns the even elements of // S. // // - (sequence "Format", From, To) Generate a sequence of defs with printf. // For instance, (sequence "R%u", 0, 3) -> [ R0, R1, R2, R3 ] // //===----------------------------------------------------------------------===// #ifndef LLVM_TABLEGEN_SETTHEORY_H #define LLVM_TABLEGEN_SETTHEORY_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/SMLoc.h" #include <map> #include <vector> namespace llvm { class DagInit; class Init; class Record; class SetTheory { public: typedef std::vector<Record*> RecVec; typedef SmallSetVector<Record*, 16> RecSet; /// Operator - A callback representing a DAG operator. class Operator { virtual void anchor(); public: virtual ~Operator() {} /// apply - Apply this operator to Expr's arguments and insert the result /// in Elts. virtual void apply(SetTheory&, DagInit *Expr, RecSet &Elts, ArrayRef<SMLoc> Loc) =0; }; /// Expander - A callback function that can transform a Record representing a /// set into a fully expanded list of elements. Expanders provide a way for /// users to define named sets that can be used in DAG expressions. class Expander { virtual void anchor(); public: virtual ~Expander() {} virtual void expand(SetTheory&, Record*, RecSet &Elts) =0; }; private: // Map set defs to their fully expanded contents. This serves as a memoization // cache and it makes it possible to return const references on queries. typedef std::map<Record*, RecVec> ExpandMap; ExpandMap Expansions; // Known DAG operators by name. StringMap<std::unique_ptr<Operator>> Operators; // Typed expanders by class name. StringMap<std::unique_ptr<Expander>> Expanders; public: /// Create a SetTheory instance with only the standard operators. SetTheory(); /// addExpander - Add an expander for Records with the named super class. void addExpander(StringRef ClassName, std::unique_ptr<Expander>); /// addFieldExpander - Add an expander for ClassName that simply evaluates /// FieldName in the Record to get the set elements. That is all that is /// needed for a class like: /// /// class Set<dag d> { /// dag Elts = d; /// } /// void addFieldExpander(StringRef ClassName, StringRef FieldName); /// addOperator - Add a DAG operator. void addOperator(StringRef Name, std::unique_ptr<Operator>); /// evaluate - Evaluate Expr and append the resulting set to Elts. void evaluate(Init *Expr, RecSet &Elts, ArrayRef<SMLoc> Loc); /// evaluate - Evaluate a sequence of Inits and append to Elts. template<typename Iter> void evaluate(Iter begin, Iter end, RecSet &Elts, ArrayRef<SMLoc> Loc) { while (begin != end) evaluate(*begin++, Elts, Loc); } /// expand - Expand a record into a set of elements if possible. Return a /// pointer to the expanded elements, or NULL if Set cannot be expanded /// further. const RecVec *expand(Record *Set); }; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/TableGen/TableGenBackend.h
//===- llvm/TableGen/TableGenBackend.h - Backend utilities ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Useful utilities for TableGen backends. // //===----------------------------------------------------------------------===// #ifndef LLVM_TABLEGEN_TABLEGENBACKEND_H #define LLVM_TABLEGEN_TABLEGENBACKEND_H namespace llvm { class StringRef; class raw_ostream; /// emitSourceFileHeader - Output an LLVM style file header to the specified /// raw_ostream. void emitSourceFileHeader(StringRef Desc, raw_ostream &OS); } // End llvm namespace #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/TableGen/StringMatcher.h
//===- StringMatcher.h - Generate a matcher for input strings ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the StringMatcher class. // //===----------------------------------------------------------------------===// #ifndef LLVM_TABLEGEN_STRINGMATCHER_H #define LLVM_TABLEGEN_STRINGMATCHER_H #include "llvm/ADT/StringRef.h" #include <string> #include <utility> #include <vector> namespace llvm { class raw_ostream; /// StringMatcher - Given a list of strings and code to execute when they match, /// output a simple switch tree to classify the input string. /// /// If a match is found, the code in Vals[i].second is executed; control must /// not exit this code fragment. If nothing matches, execution falls through. /// class StringMatcher { public: typedef std::pair<std::string, std::string> StringPair; private: StringRef StrVariableName; const std::vector<StringPair> &Matches; raw_ostream &OS; public: StringMatcher(StringRef strVariableName, const std::vector<StringPair> &matches, raw_ostream &os) : StrVariableName(strVariableName), Matches(matches), OS(os) {} void Emit(unsigned Indent = 0) const; private: bool EmitStringMatcherForChar(const std::vector<const StringPair*> &Matches, unsigned CharNo, unsigned IndentCount) const; }; } // end llvm namespace. #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/TableGen/Record.h
//===- llvm/TableGen/Record.h - Classes for Table Records -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the main TableGen data structures, including the TableGen // types, values, and high-level data structures. // //===----------------------------------------------------------------------===// #ifndef LLVM_TABLEGEN_RECORD_H #define LLVM_TABLEGEN_RECORD_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/Support/Casting.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/SMLoc.h" #include "llvm/Support/raw_ostream.h" #include <map> namespace llvm { class ListRecTy; struct MultiClass; class Record; class RecordVal; class RecordKeeper; //===----------------------------------------------------------------------===// // Type Classes //===----------------------------------------------------------------------===// class RecTy { public: /// \brief Subclass discriminator (for dyn_cast<> et al.) enum RecTyKind { BitRecTyKind, BitsRecTyKind, IntRecTyKind, StringRecTyKind, ListRecTyKind, DagRecTyKind, RecordRecTyKind }; private: RecTyKind Kind; std::unique_ptr<ListRecTy> ListTy; public: RecTyKind getRecTyKind() const { return Kind; } RecTy(RecTyKind K) : Kind(K) {} virtual ~RecTy() {} virtual std::string getAsString() const = 0; void print(raw_ostream &OS) const { OS << getAsString(); } void dump() const; /// typeIsConvertibleTo - Return true if all values of 'this' type can be /// converted to the specified type. virtual bool typeIsConvertibleTo(const RecTy *RHS) const; /// getListTy - Returns the type representing list<this>. ListRecTy *getListTy(); }; inline raw_ostream &operator<<(raw_ostream &OS, const RecTy &Ty) { Ty.print(OS); return OS; } /// BitRecTy - 'bit' - Represent a single bit /// class BitRecTy : public RecTy { static BitRecTy Shared; BitRecTy() : RecTy(BitRecTyKind) {} public: static bool classof(const RecTy *RT) { return RT->getRecTyKind() == BitRecTyKind; } static BitRecTy *get() { return &Shared; } std::string getAsString() const override { return "bit"; } bool typeIsConvertibleTo(const RecTy *RHS) const override; }; /// BitsRecTy - 'bits<n>' - Represent a fixed number of bits /// class BitsRecTy : public RecTy { unsigned Size; explicit BitsRecTy(unsigned Sz) : RecTy(BitsRecTyKind), Size(Sz) {} public: static bool classof(const RecTy *RT) { return RT->getRecTyKind() == BitsRecTyKind; } static BitsRecTy *get(unsigned Sz); unsigned getNumBits() const { return Size; } std::string getAsString() const override; bool typeIsConvertibleTo(const RecTy *RHS) const override; }; /// IntRecTy - 'int' - Represent an integer value of no particular size /// class IntRecTy : public RecTy { static IntRecTy Shared; IntRecTy() : RecTy(IntRecTyKind) {} public: static bool classof(const RecTy *RT) { return RT->getRecTyKind() == IntRecTyKind; } static IntRecTy *get() { return &Shared; } std::string getAsString() const override { return "int"; } bool typeIsConvertibleTo(const RecTy *RHS) const override; }; /// StringRecTy - 'string' - Represent an string value /// class StringRecTy : public RecTy { static StringRecTy Shared; StringRecTy() : RecTy(StringRecTyKind) {} public: static bool classof(const RecTy *RT) { return RT->getRecTyKind() == StringRecTyKind; } static StringRecTy *get() { return &Shared; } std::string getAsString() const override; }; /// ListRecTy - 'list<Ty>' - Represent a list of values, all of which must be of /// the specified type. /// class ListRecTy : public RecTy { RecTy *Ty; explicit ListRecTy(RecTy *T) : RecTy(ListRecTyKind), Ty(T) {} friend ListRecTy *RecTy::getListTy(); public: static bool classof(const RecTy *RT) { return RT->getRecTyKind() == ListRecTyKind; } static ListRecTy *get(RecTy *T) { return T->getListTy(); } RecTy *getElementType() const { return Ty; } std::string getAsString() const override; bool typeIsConvertibleTo(const RecTy *RHS) const override; }; /// DagRecTy - 'dag' - Represent a dag fragment /// class DagRecTy : public RecTy { static DagRecTy Shared; DagRecTy() : RecTy(DagRecTyKind) {} public: static bool classof(const RecTy *RT) { return RT->getRecTyKind() == DagRecTyKind; } static DagRecTy *get() { return &Shared; } std::string getAsString() const override; }; /// RecordRecTy - '[classname]' - Represent an instance of a class, such as: /// (R32 X = EAX). /// class RecordRecTy : public RecTy { Record *Rec; explicit RecordRecTy(Record *R) : RecTy(RecordRecTyKind), Rec(R) {} friend class Record; public: static bool classof(const RecTy *RT) { return RT->getRecTyKind() == RecordRecTyKind; } static RecordRecTy *get(Record *R); Record *getRecord() const { return Rec; } std::string getAsString() const override; bool typeIsConvertibleTo(const RecTy *RHS) const override; }; /// resolveTypes - Find a common type that T1 and T2 convert to. /// Return 0 if no such type exists. /// RecTy *resolveTypes(RecTy *T1, RecTy *T2); //===----------------------------------------------------------------------===// // Initializer Classes //===----------------------------------------------------------------------===// class Init { protected: /// \brief Discriminator enum (for isa<>, dyn_cast<>, et al.) /// /// This enum is laid out by a preorder traversal of the inheritance /// hierarchy, and does not contain an entry for abstract classes, as per /// the recommendation in docs/HowToSetUpLLVMStyleRTTI.rst. /// /// We also explicitly include "first" and "last" values for each /// interior node of the inheritance tree, to make it easier to read the /// corresponding classof(). /// /// We could pack these a bit tighter by not having the IK_FirstXXXInit /// and IK_LastXXXInit be their own values, but that would degrade /// readability for really no benefit. enum InitKind { IK_BitInit, IK_FirstTypedInit, IK_BitsInit, IK_DagInit, IK_DefInit, IK_FieldInit, IK_IntInit, IK_ListInit, IK_FirstOpInit, IK_BinOpInit, IK_TernOpInit, IK_UnOpInit, IK_LastOpInit, IK_StringInit, IK_VarInit, IK_VarListElementInit, IK_LastTypedInit, IK_UnsetInit, IK_VarBitInit }; private: const InitKind Kind; Init(const Init &) = delete; Init &operator=(const Init &) = delete; virtual void anchor(); public: InitKind getKind() const { return Kind; } protected: explicit Init(InitKind K) : Kind(K) {} public: virtual ~Init() {} /// isComplete - This virtual method should be overridden by values that may /// not be completely specified yet. virtual bool isComplete() const { return true; } /// print - Print out this value. void print(raw_ostream &OS) const { OS << getAsString(); } /// getAsString - Convert this value to a string form. virtual std::string getAsString() const = 0; /// getAsUnquotedString - Convert this value to a string form, /// without adding quote markers. This primaruly affects /// StringInits where we will not surround the string value with /// quotes. virtual std::string getAsUnquotedString() const { return getAsString(); } /// dump - Debugging method that may be called through a debugger, just /// invokes print on stderr. void dump() const; /// convertInitializerTo - This virtual function converts to the appropriate /// Init based on the passed in type. virtual Init *convertInitializerTo(RecTy *Ty) const = 0; /// convertInitializerBitRange - This method is used to implement the bitrange /// selection operator. Given an initializer, it selects the specified bits /// out, returning them as a new init of bits type. If it is not legal to use /// the bit subscript operator on this initializer, return null. /// virtual Init * convertInitializerBitRange(const std::vector<unsigned> &Bits) const { return nullptr; } /// convertInitListSlice - This method is used to implement the list slice /// selection operator. Given an initializer, it selects the specified list /// elements, returning them as a new init of list type. If it is not legal /// to take a slice of this, return null. /// virtual Init * convertInitListSlice(const std::vector<unsigned> &Elements) const { return nullptr; } /// getFieldType - This method is used to implement the FieldInit class. /// Implementors of this method should return the type of the named field if /// they are of record type. /// virtual RecTy *getFieldType(const std::string &FieldName) const { return nullptr; } /// getFieldInit - This method complements getFieldType to return the /// initializer for the specified field. If getFieldType returns non-null /// this method should return non-null, otherwise it returns null. /// virtual Init *getFieldInit(Record &R, const RecordVal *RV, const std::string &FieldName) const { return nullptr; } /// resolveReferences - This method is used by classes that refer to other /// variables which may not be defined at the time the expression is formed. /// If a value is set for the variable later, this method will be called on /// users of the value to allow the value to propagate out. /// virtual Init *resolveReferences(Record &R, const RecordVal *RV) const { return const_cast<Init *>(this); } /// getBit - This method is used to return the initializer for the specified /// bit. virtual Init *getBit(unsigned Bit) const = 0; /// getBitVar - This method is used to retrieve the initializer for bit /// reference. For non-VarBitInit, it simply returns itself. virtual Init *getBitVar() const { return const_cast<Init*>(this); } /// getBitNum - This method is used to retrieve the bit number of a bit /// reference. For non-VarBitInit, it simply returns 0. virtual unsigned getBitNum() const { return 0; } }; inline raw_ostream &operator<<(raw_ostream &OS, const Init &I) { I.print(OS); return OS; } /// TypedInit - This is the common super-class of types that have a specific, /// explicit, type. /// class TypedInit : public Init { RecTy *Ty; TypedInit(const TypedInit &Other) = delete; TypedInit &operator=(const TypedInit &Other) = delete; protected: explicit TypedInit(InitKind K, RecTy *T) : Init(K), Ty(T) {} ~TypedInit() { // If this is a DefInit we need to delete the RecordRecTy. if (getKind() == IK_DefInit) delete Ty; } public: static bool classof(const Init *I) { return I->getKind() >= IK_FirstTypedInit && I->getKind() <= IK_LastTypedInit; } RecTy *getType() const { return Ty; } Init *convertInitializerTo(RecTy *Ty) const override; Init * convertInitializerBitRange(const std::vector<unsigned> &Bits) const override; Init * convertInitListSlice(const std::vector<unsigned> &Elements) const override; /// getFieldType - This method is used to implement the FieldInit class. /// Implementors of this method should return the type of the named field if /// they are of record type. /// RecTy *getFieldType(const std::string &FieldName) const override; /// resolveListElementReference - This method is used to implement /// VarListElementInit::resolveReferences. If the list element is resolvable /// now, we return the resolved value, otherwise we return null. virtual Init *resolveListElementReference(Record &R, const RecordVal *RV, unsigned Elt) const = 0; }; /// UnsetInit - ? - Represents an uninitialized value /// class UnsetInit : public Init { UnsetInit() : Init(IK_UnsetInit) {} UnsetInit(const UnsetInit &) = delete; UnsetInit &operator=(const UnsetInit &Other) = delete; public: static bool classof(const Init *I) { return I->getKind() == IK_UnsetInit; } static UnsetInit *get(); Init *convertInitializerTo(RecTy *Ty) const override; Init *getBit(unsigned Bit) const override { return const_cast<UnsetInit*>(this); } bool isComplete() const override { return false; } std::string getAsString() const override { return "?"; } }; /// BitInit - true/false - Represent a concrete initializer for a bit. /// class BitInit : public Init { bool Value; explicit BitInit(bool V) : Init(IK_BitInit), Value(V) {} BitInit(const BitInit &Other) = delete; BitInit &operator=(BitInit &Other) = delete; public: static bool classof(const Init *I) { return I->getKind() == IK_BitInit; } static BitInit *get(bool V); bool getValue() const { return Value; } Init *convertInitializerTo(RecTy *Ty) const override; Init *getBit(unsigned Bit) const override { assert(Bit < 1 && "Bit index out of range!"); return const_cast<BitInit*>(this); } std::string getAsString() const override { return Value ? "1" : "0"; } }; /// BitsInit - { a, b, c } - Represents an initializer for a BitsRecTy value. /// It contains a vector of bits, whose size is determined by the type. /// class BitsInit : public TypedInit, public FoldingSetNode { std::vector<Init*> Bits; BitsInit(ArrayRef<Init *> Range) : TypedInit(IK_BitsInit, BitsRecTy::get(Range.size())), Bits(Range.begin(), Range.end()) {} BitsInit(const BitsInit &Other) = delete; BitsInit &operator=(const BitsInit &Other) = delete; public: static bool classof(const Init *I) { return I->getKind() == IK_BitsInit; } static BitsInit *get(ArrayRef<Init *> Range); void Profile(FoldingSetNodeID &ID) const; unsigned getNumBits() const { return Bits.size(); } Init *convertInitializerTo(RecTy *Ty) const override; Init * convertInitializerBitRange(const std::vector<unsigned> &Bits) const override; bool isComplete() const override { for (unsigned i = 0; i != getNumBits(); ++i) if (!getBit(i)->isComplete()) return false; return true; } bool allInComplete() const { for (unsigned i = 0; i != getNumBits(); ++i) if (getBit(i)->isComplete()) return false; return true; } std::string getAsString() const override; /// resolveListElementReference - This method is used to implement /// VarListElementInit::resolveReferences. If the list element is resolvable /// now, we return the resolved value, otherwise we return null. Init *resolveListElementReference(Record &R, const RecordVal *RV, unsigned Elt) const override { llvm_unreachable("Illegal element reference off bits<n>"); } Init *resolveReferences(Record &R, const RecordVal *RV) const override; Init *getBit(unsigned Bit) const override { assert(Bit < Bits.size() && "Bit index out of range!"); return Bits[Bit]; } }; /// IntInit - 7 - Represent an initialization by a literal integer value. /// class IntInit : public TypedInit { int64_t Value; explicit IntInit(int64_t V) : TypedInit(IK_IntInit, IntRecTy::get()), Value(V) {} IntInit(const IntInit &Other) = delete; IntInit &operator=(const IntInit &Other) = delete; public: static bool classof(const Init *I) { return I->getKind() == IK_IntInit; } static IntInit *get(int64_t V); int64_t getValue() const { return Value; } Init *convertInitializerTo(RecTy *Ty) const override; Init * convertInitializerBitRange(const std::vector<unsigned> &Bits) const override; std::string getAsString() const override; /// resolveListElementReference - This method is used to implement /// VarListElementInit::resolveReferences. If the list element is resolvable /// now, we return the resolved value, otherwise we return null. Init *resolveListElementReference(Record &R, const RecordVal *RV, unsigned Elt) const override { llvm_unreachable("Illegal element reference off int"); } Init *getBit(unsigned Bit) const override { return BitInit::get((Value & (1ULL << Bit)) != 0); } }; /// StringInit - "foo" - Represent an initialization by a string value. /// class StringInit : public TypedInit { std::string Value; explicit StringInit(const std::string &V) : TypedInit(IK_StringInit, StringRecTy::get()), Value(V) {} StringInit(const StringInit &Other) = delete; StringInit &operator=(const StringInit &Other) = delete; public: static bool classof(const Init *I) { return I->getKind() == IK_StringInit; } static StringInit *get(StringRef); const std::string &getValue() const { return Value; } Init *convertInitializerTo(RecTy *Ty) const override; std::string getAsString() const override { return "\"" + Value + "\""; } std::string getAsUnquotedString() const override { return Value; } /// resolveListElementReference - This method is used to implement /// VarListElementInit::resolveReferences. If the list element is resolvable /// now, we return the resolved value, otherwise we return null. Init *resolveListElementReference(Record &R, const RecordVal *RV, unsigned Elt) const override { llvm_unreachable("Illegal element reference off string"); } Init *getBit(unsigned Bit) const override { llvm_unreachable("Illegal bit reference off string"); } }; /// ListInit - [AL, AH, CL] - Represent a list of defs /// class ListInit : public TypedInit, public FoldingSetNode { std::vector<Init*> Values; public: typedef std::vector<Init*>::const_iterator const_iterator; private: explicit ListInit(ArrayRef<Init *> Range, RecTy *EltTy) : TypedInit(IK_ListInit, ListRecTy::get(EltTy)), Values(Range.begin(), Range.end()) {} ListInit(const ListInit &Other) = delete; ListInit &operator=(const ListInit &Other) = delete; public: static bool classof(const Init *I) { return I->getKind() == IK_ListInit; } static ListInit *get(ArrayRef<Init *> Range, RecTy *EltTy); void Profile(FoldingSetNodeID &ID) const; Init *getElement(unsigned i) const { assert(i < Values.size() && "List element index out of range!"); return Values[i]; } Record *getElementAsRecord(unsigned i) const; Init * convertInitListSlice(const std::vector<unsigned> &Elements) const override; Init *convertInitializerTo(RecTy *Ty) const override; /// resolveReferences - This method is used by classes that refer to other /// variables which may not be defined at the time they expression is formed. /// If a value is set for the variable later, this method will be called on /// users of the value to allow the value to propagate out. /// Init *resolveReferences(Record &R, const RecordVal *RV) const override; std::string getAsString() const override; ArrayRef<Init*> getValues() const { return Values; } const_iterator begin() const { return Values.begin(); } const_iterator end () const { return Values.end(); } size_t size () const { return Values.size(); } bool empty() const { return Values.empty(); } /// resolveListElementReference - This method is used to implement /// VarListElementInit::resolveReferences. If the list element is resolvable /// now, we return the resolved value, otherwise we return null. Init *resolveListElementReference(Record &R, const RecordVal *RV, unsigned Elt) const override; Init *getBit(unsigned Bit) const override { llvm_unreachable("Illegal bit reference off list"); } }; /// OpInit - Base class for operators /// class OpInit : public TypedInit { OpInit(const OpInit &Other) = delete; OpInit &operator=(OpInit &Other) = delete; protected: explicit OpInit(InitKind K, RecTy *Type) : TypedInit(K, Type) {} public: static bool classof(const Init *I) { return I->getKind() >= IK_FirstOpInit && I->getKind() <= IK_LastOpInit; } // Clone - Clone this operator, replacing arguments with the new list virtual OpInit *clone(std::vector<Init *> &Operands) const = 0; virtual unsigned getNumOperands() const = 0; virtual Init *getOperand(unsigned i) const = 0; // Fold - If possible, fold this to a simpler init. Return this if not // possible to fold. virtual Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const = 0; Init *resolveListElementReference(Record &R, const RecordVal *RV, unsigned Elt) const override; Init *getBit(unsigned Bit) const override; }; /// UnOpInit - !op (X) - Transform an init. /// class UnOpInit : public OpInit { public: enum UnaryOp { CAST, HEAD, TAIL, EMPTY }; private: UnaryOp Opc; Init *LHS; UnOpInit(UnaryOp opc, Init *lhs, RecTy *Type) : OpInit(IK_UnOpInit, Type), Opc(opc), LHS(lhs) {} UnOpInit(const UnOpInit &Other) = delete; UnOpInit &operator=(const UnOpInit &Other) = delete; public: static bool classof(const Init *I) { return I->getKind() == IK_UnOpInit; } static UnOpInit *get(UnaryOp opc, Init *lhs, RecTy *Type); // Clone - Clone this operator, replacing arguments with the new list OpInit *clone(std::vector<Init *> &Operands) const override { assert(Operands.size() == 1 && "Wrong number of operands for unary operation"); return UnOpInit::get(getOpcode(), *Operands.begin(), getType()); } unsigned getNumOperands() const override { return 1; } Init *getOperand(unsigned i) const override { assert(i == 0 && "Invalid operand id for unary operator"); return getOperand(); } UnaryOp getOpcode() const { return Opc; } Init *getOperand() const { return LHS; } // Fold - If possible, fold this to a simpler init. Return this if not // possible to fold. Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const override; Init *resolveReferences(Record &R, const RecordVal *RV) const override; std::string getAsString() const override; }; /// BinOpInit - !op (X, Y) - Combine two inits. /// class BinOpInit : public OpInit { public: enum BinaryOp { ADD, AND, SHL, SRA, SRL, LISTCONCAT, STRCONCAT, CONCAT, EQ }; private: BinaryOp Opc; Init *LHS, *RHS; BinOpInit(BinaryOp opc, Init *lhs, Init *rhs, RecTy *Type) : OpInit(IK_BinOpInit, Type), Opc(opc), LHS(lhs), RHS(rhs) {} BinOpInit(const BinOpInit &Other) = delete; BinOpInit &operator=(const BinOpInit &Other) = delete; public: static bool classof(const Init *I) { return I->getKind() == IK_BinOpInit; } static BinOpInit *get(BinaryOp opc, Init *lhs, Init *rhs, RecTy *Type); // Clone - Clone this operator, replacing arguments with the new list OpInit *clone(std::vector<Init *> &Operands) const override { assert(Operands.size() == 2 && "Wrong number of operands for binary operation"); return BinOpInit::get(getOpcode(), Operands[0], Operands[1], getType()); } unsigned getNumOperands() const override { return 2; } Init *getOperand(unsigned i) const override { switch (i) { default: llvm_unreachable("Invalid operand id for binary operator"); case 0: return getLHS(); case 1: return getRHS(); } } BinaryOp getOpcode() const { return Opc; } Init *getLHS() const { return LHS; } Init *getRHS() const { return RHS; } // Fold - If possible, fold this to a simpler init. Return this if not // possible to fold. Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const override; Init *resolveReferences(Record &R, const RecordVal *RV) const override; std::string getAsString() const override; }; /// TernOpInit - !op (X, Y, Z) - Combine two inits. /// class TernOpInit : public OpInit { public: enum TernaryOp { SUBST, FOREACH, IF }; private: TernaryOp Opc; Init *LHS, *MHS, *RHS; TernOpInit(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs, RecTy *Type) : OpInit(IK_TernOpInit, Type), Opc(opc), LHS(lhs), MHS(mhs), RHS(rhs) {} TernOpInit(const TernOpInit &Other) = delete; TernOpInit &operator=(const TernOpInit &Other) = delete; public: static bool classof(const Init *I) { return I->getKind() == IK_TernOpInit; } static TernOpInit *get(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs, RecTy *Type); // Clone - Clone this operator, replacing arguments with the new list OpInit *clone(std::vector<Init *> &Operands) const override { assert(Operands.size() == 3 && "Wrong number of operands for ternary operation"); return TernOpInit::get(getOpcode(), Operands[0], Operands[1], Operands[2], getType()); } unsigned getNumOperands() const override { return 3; } Init *getOperand(unsigned i) const override { switch (i) { default: llvm_unreachable("Invalid operand id for ternary operator"); case 0: return getLHS(); case 1: return getMHS(); case 2: return getRHS(); } } TernaryOp getOpcode() const { return Opc; } Init *getLHS() const { return LHS; } Init *getMHS() const { return MHS; } Init *getRHS() const { return RHS; } // Fold - If possible, fold this to a simpler init. Return this if not // possible to fold. Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const override; bool isComplete() const override { return false; } Init *resolveReferences(Record &R, const RecordVal *RV) const override; std::string getAsString() const override; }; /// VarInit - 'Opcode' - Represent a reference to an entire variable object. /// class VarInit : public TypedInit { Init *VarName; explicit VarInit(const std::string &VN, RecTy *T) : TypedInit(IK_VarInit, T), VarName(StringInit::get(VN)) {} explicit VarInit(Init *VN, RecTy *T) : TypedInit(IK_VarInit, T), VarName(VN) {} VarInit(const VarInit &Other) = delete; VarInit &operator=(const VarInit &Other) = delete; public: static bool classof(const Init *I) { return I->getKind() == IK_VarInit; } static VarInit *get(const std::string &VN, RecTy *T); static VarInit *get(Init *VN, RecTy *T); const std::string &getName() const; Init *getNameInit() const { return VarName; } std::string getNameInitAsString() const { return getNameInit()->getAsUnquotedString(); } Init *resolveListElementReference(Record &R, const RecordVal *RV, unsigned Elt) const override; RecTy *getFieldType(const std::string &FieldName) const override; Init *getFieldInit(Record &R, const RecordVal *RV, const std::string &FieldName) const override; /// resolveReferences - This method is used by classes that refer to other /// variables which may not be defined at the time they expression is formed. /// If a value is set for the variable later, this method will be called on /// users of the value to allow the value to propagate out. /// Init *resolveReferences(Record &R, const RecordVal *RV) const override; Init *getBit(unsigned Bit) const override; std::string getAsString() const override { return getName(); } }; /// VarBitInit - Opcode{0} - Represent access to one bit of a variable or field. /// class VarBitInit : public Init { TypedInit *TI; unsigned Bit; VarBitInit(TypedInit *T, unsigned B) : Init(IK_VarBitInit), TI(T), Bit(B) { assert(T->getType() && (isa<IntRecTy>(T->getType()) || (isa<BitsRecTy>(T->getType()) && cast<BitsRecTy>(T->getType())->getNumBits() > B)) && "Illegal VarBitInit expression!"); } VarBitInit(const VarBitInit &Other) = delete; VarBitInit &operator=(const VarBitInit &Other) = delete; public: static bool classof(const Init *I) { return I->getKind() == IK_VarBitInit; } static VarBitInit *get(TypedInit *T, unsigned B); Init *convertInitializerTo(RecTy *Ty) const override; Init *getBitVar() const override { return TI; } unsigned getBitNum() const override { return Bit; } std::string getAsString() const override; Init *resolveReferences(Record &R, const RecordVal *RV) const override; Init *getBit(unsigned B) const override { assert(B < 1 && "Bit index out of range!"); return const_cast<VarBitInit*>(this); } }; /// VarListElementInit - List[4] - Represent access to one element of a var or /// field. class VarListElementInit : public TypedInit { TypedInit *TI; unsigned Element; VarListElementInit(TypedInit *T, unsigned E) : TypedInit(IK_VarListElementInit, cast<ListRecTy>(T->getType())->getElementType()), TI(T), Element(E) { assert(T->getType() && isa<ListRecTy>(T->getType()) && "Illegal VarBitInit expression!"); } VarListElementInit(const VarListElementInit &Other) = delete; void operator=(const VarListElementInit &Other) = delete; public: static bool classof(const Init *I) { return I->getKind() == IK_VarListElementInit; } static VarListElementInit *get(TypedInit *T, unsigned E); TypedInit *getVariable() const { return TI; } unsigned getElementNum() const { return Element; } /// resolveListElementReference - This method is used to implement /// VarListElementInit::resolveReferences. If the list element is resolvable /// now, we return the resolved value, otherwise we return null. Init *resolveListElementReference(Record &R, const RecordVal *RV, unsigned Elt) const override; std::string getAsString() const override; Init *resolveReferences(Record &R, const RecordVal *RV) const override; Init *getBit(unsigned Bit) const override; }; /// DefInit - AL - Represent a reference to a 'def' in the description /// class DefInit : public TypedInit { Record *Def; DefInit(Record *D, RecordRecTy *T) : TypedInit(IK_DefInit, T), Def(D) {} friend class Record; DefInit(const DefInit &Other) = delete; DefInit &operator=(const DefInit &Other) = delete; public: static bool classof(const Init *I) { return I->getKind() == IK_DefInit; } static DefInit *get(Record*); Init *convertInitializerTo(RecTy *Ty) const override; Record *getDef() const { return Def; } //virtual Init *convertInitializerBitRange(const std::vector<unsigned> &Bits); RecTy *getFieldType(const std::string &FieldName) const override; Init *getFieldInit(Record &R, const RecordVal *RV, const std::string &FieldName) const override; std::string getAsString() const override; Init *getBit(unsigned Bit) const override { llvm_unreachable("Illegal bit reference off def"); } /// resolveListElementReference - This method is used to implement /// VarListElementInit::resolveReferences. If the list element is resolvable /// now, we return the resolved value, otherwise we return null. Init *resolveListElementReference(Record &R, const RecordVal *RV, unsigned Elt) const override { llvm_unreachable("Illegal element reference off def"); } }; /// FieldInit - X.Y - Represent a reference to a subfield of a variable /// class FieldInit : public TypedInit { Init *Rec; // Record we are referring to std::string FieldName; // Field we are accessing FieldInit(Init *R, const std::string &FN) : TypedInit(IK_FieldInit, R->getFieldType(FN)), Rec(R), FieldName(FN) { assert(getType() && "FieldInit with non-record type!"); } FieldInit(const FieldInit &Other) = delete; FieldInit &operator=(const FieldInit &Other) = delete; public: static bool classof(const Init *I) { return I->getKind() == IK_FieldInit; } static FieldInit *get(Init *R, const std::string &FN); Init *getBit(unsigned Bit) const override; Init *resolveListElementReference(Record &R, const RecordVal *RV, unsigned Elt) const override; Init *resolveReferences(Record &R, const RecordVal *RV) const override; std::string getAsString() const override { return Rec->getAsString() + "." + FieldName; } }; /// DagInit - (v a, b) - Represent a DAG tree value. DAG inits are required /// to have at least one value then a (possibly empty) list of arguments. Each /// argument can have a name associated with it. /// class DagInit : public TypedInit, public FoldingSetNode { Init *Val; std::string ValName; std::vector<Init*> Args; std::vector<std::string> ArgNames; DagInit(Init *V, const std::string &VN, ArrayRef<Init *> ArgRange, ArrayRef<std::string> NameRange) : TypedInit(IK_DagInit, DagRecTy::get()), Val(V), ValName(VN), Args(ArgRange.begin(), ArgRange.end()), ArgNames(NameRange.begin(), NameRange.end()) {} DagInit(const DagInit &Other) = delete; DagInit &operator=(const DagInit &Other) = delete; public: static bool classof(const Init *I) { return I->getKind() == IK_DagInit; } static DagInit *get(Init *V, const std::string &VN, ArrayRef<Init *> ArgRange, ArrayRef<std::string> NameRange); static DagInit *get(Init *V, const std::string &VN, const std::vector< std::pair<Init*, std::string> > &args); void Profile(FoldingSetNodeID &ID) const; Init *convertInitializerTo(RecTy *Ty) const override; Init *getOperator() const { return Val; } const std::string &getName() const { return ValName; } unsigned getNumArgs() const { return Args.size(); } Init *getArg(unsigned Num) const { assert(Num < Args.size() && "Arg number out of range!"); return Args[Num]; } const std::string &getArgName(unsigned Num) const { assert(Num < ArgNames.size() && "Arg number out of range!"); return ArgNames[Num]; } Init *resolveReferences(Record &R, const RecordVal *RV) const override; std::string getAsString() const override; typedef std::vector<Init*>::const_iterator const_arg_iterator; typedef std::vector<std::string>::const_iterator const_name_iterator; inline const_arg_iterator arg_begin() const { return Args.begin(); } inline const_arg_iterator arg_end () const { return Args.end(); } inline size_t arg_size () const { return Args.size(); } inline bool arg_empty() const { return Args.empty(); } inline const_name_iterator name_begin() const { return ArgNames.begin(); } inline const_name_iterator name_end () const { return ArgNames.end(); } inline size_t name_size () const { return ArgNames.size(); } inline bool name_empty() const { return ArgNames.empty(); } Init *getBit(unsigned Bit) const override { llvm_unreachable("Illegal bit reference off dag"); } Init *resolveListElementReference(Record &R, const RecordVal *RV, unsigned Elt) const override { llvm_unreachable("Illegal element reference off dag"); } }; //===----------------------------------------------------------------------===// // High-Level Classes // // /////////////////////////////////////////////////////////////////////////////// class RecordVal { PointerIntPair<Init *, 1, bool> NameAndPrefix; RecTy *Ty; Init *Value; public: RecordVal(Init *N, RecTy *T, bool P); RecordVal(const std::string &N, RecTy *T, bool P); const std::string &getName() const; const Init *getNameInit() const { return NameAndPrefix.getPointer(); } std::string getNameInitAsString() const { return getNameInit()->getAsUnquotedString(); } bool getPrefix() const { return NameAndPrefix.getInt(); } RecTy *getType() const { return Ty; } Init *getValue() const { return Value; } bool setValue(Init *V) { if (V) { Value = V->convertInitializerTo(Ty); return Value == nullptr; } Value = nullptr; return false; } void dump() const; void print(raw_ostream &OS, bool PrintSem = true) const; }; inline raw_ostream &operator<<(raw_ostream &OS, const RecordVal &RV) { RV.print(OS << " "); return OS; } class Record { static unsigned LastID; // Unique record ID. unsigned ID; Init *Name; // Location where record was instantiated, followed by the location of // multiclass prototypes used. SmallVector<SMLoc, 4> Locs; std::vector<Init *> TemplateArgs; std::vector<RecordVal> Values; std::vector<Record *> SuperClasses; std::vector<SMRange> SuperClassRanges; // Tracks Record instances. Not owned by Record. RecordKeeper &TrackedRecords; std::unique_ptr<DefInit> TheInit; bool IsAnonymous; // Class-instance values can be used by other defs. For example, Struct<i> // is used here as a template argument to another class: // // multiclass MultiClass<int i> { // def Def : Class<Struct<i>>; // // These need to get fully resolved before instantiating any other // definitions that use them (e.g. Def). However, inside a multiclass they // can't be immediately resolved so we mark them ResolveFirst to fully // resolve them later as soon as the multiclass is instantiated. bool ResolveFirst; void init(); void checkName(); public: // Constructs a record. explicit Record(Init *N, ArrayRef<SMLoc> locs, RecordKeeper &records, bool Anonymous = false) : ID(LastID++), Name(N), Locs(locs.begin(), locs.end()), TrackedRecords(records), IsAnonymous(Anonymous), ResolveFirst(false) { init(); } explicit Record(const std::string &N, ArrayRef<SMLoc> locs, RecordKeeper &records, bool Anonymous = false) : Record(StringInit::get(N), locs, records, Anonymous) {} // When copy-constructing a Record, we must still guarantee a globally unique // ID number. Don't copy TheInit either since it's owned by the original // record. All other fields can be copied normally. Record(const Record &O) : ID(LastID++), Name(O.Name), Locs(O.Locs), TemplateArgs(O.TemplateArgs), Values(O.Values), SuperClasses(O.SuperClasses), SuperClassRanges(O.SuperClassRanges), TrackedRecords(O.TrackedRecords), IsAnonymous(O.IsAnonymous), ResolveFirst(O.ResolveFirst) { } static unsigned getNewUID() { return LastID++; } unsigned getID() const { return ID; } const std::string &getName() const; Init *getNameInit() const { return Name; } const std::string getNameInitAsString() const { return getNameInit()->getAsUnquotedString(); } void setName(Init *Name); // Also updates RecordKeeper. void setName(const std::string &Name); // Also updates RecordKeeper. ArrayRef<SMLoc> getLoc() const { return Locs; } /// get the corresponding DefInit. DefInit *getDefInit(); ArrayRef<Init *> getTemplateArgs() const { return TemplateArgs; } ArrayRef<RecordVal> getValues() const { return Values; } ArrayRef<Record *> getSuperClasses() const { return SuperClasses; } ArrayRef<SMRange> getSuperClassRanges() const { return SuperClassRanges; } bool isTemplateArg(Init *Name) const { for (Init *TA : TemplateArgs) if (TA == Name) return true; return false; } bool isTemplateArg(StringRef Name) const { return isTemplateArg(StringInit::get(Name)); } const RecordVal *getValue(const Init *Name) const { for (const RecordVal &Val : Values) if (Val.getNameInit() == Name) return &Val; return nullptr; } const RecordVal *getValue(StringRef Name) const { return getValue(StringInit::get(Name)); } RecordVal *getValue(const Init *Name) { for (RecordVal &Val : Values) if (Val.getNameInit() == Name) return &Val; return nullptr; } RecordVal *getValue(StringRef Name) { return getValue(StringInit::get(Name)); } void addTemplateArg(Init *Name) { assert(!isTemplateArg(Name) && "Template arg already defined!"); TemplateArgs.push_back(Name); } void addTemplateArg(StringRef Name) { addTemplateArg(StringInit::get(Name)); } void addValue(const RecordVal &RV) { assert(getValue(RV.getNameInit()) == nullptr && "Value already added!"); Values.push_back(RV); if (Values.size() > 1) // Keep NAME at the end of the list. It makes record dumps a // bit prettier and allows TableGen tests to be written more // naturally. Tests can use CHECK-NEXT to look for Record // fields they expect to see after a def. They can't do that if // NAME is the first Record field. std::swap(Values[Values.size() - 2], Values[Values.size() - 1]); } void removeValue(Init *Name) { for (unsigned i = 0, e = Values.size(); i != e; ++i) if (Values[i].getNameInit() == Name) { Values.erase(Values.begin()+i); return; } llvm_unreachable("Cannot remove an entry that does not exist!"); } void removeValue(StringRef Name) { removeValue(StringInit::get(Name)); } bool isSubClassOf(const Record *R) const { for (const Record *SC : SuperClasses) if (SC == R) return true; return false; } bool isSubClassOf(StringRef Name) const { for (const Record *SC : SuperClasses) if (SC->getNameInitAsString() == Name) return true; return false; } void addSuperClass(Record *R, SMRange Range) { assert(!isSubClassOf(R) && "Already subclassing record!"); SuperClasses.push_back(R); SuperClassRanges.push_back(Range); } /// resolveReferences - If there are any field references that refer to fields /// that have been filled in, we can propagate the values now. /// void resolveReferences() { resolveReferencesTo(nullptr); } /// resolveReferencesTo - If anything in this record refers to RV, replace the /// reference to RV with the RHS of RV. If RV is null, we resolve all /// possible references. void resolveReferencesTo(const RecordVal *RV); RecordKeeper &getRecords() const { return TrackedRecords; } bool isAnonymous() const { return IsAnonymous; } bool isResolveFirst() const { return ResolveFirst; } void setResolveFirst(bool b) { ResolveFirst = b; } void dump() const; //===--------------------------------------------------------------------===// // High-level methods useful to tablegen back-ends // /// getValueInit - Return the initializer for a value with the specified name, /// or throw an exception if the field does not exist. /// Init *getValueInit(StringRef FieldName) const; /// Return true if the named field is unset. bool isValueUnset(StringRef FieldName) const { return isa<UnsetInit>(getValueInit(FieldName)); } /// getValueAsString - This method looks up the specified field and returns /// its value as a string, throwing an exception if the field does not exist /// or if the value is not a string. /// std::string getValueAsString(StringRef FieldName) const; /// getValueAsBitsInit - This method looks up the specified field and returns /// its value as a BitsInit, throwing an exception if the field does not exist /// or if the value is not the right type. /// BitsInit *getValueAsBitsInit(StringRef FieldName) const; /// getValueAsListInit - This method looks up the specified field and returns /// its value as a ListInit, throwing an exception if the field does not exist /// or if the value is not the right type. /// ListInit *getValueAsListInit(StringRef FieldName) const; /// getValueAsListOfDefs - This method looks up the specified field and /// returns its value as a vector of records, throwing an exception if the /// field does not exist or if the value is not the right type. /// std::vector<Record*> getValueAsListOfDefs(StringRef FieldName) const; /// getValueAsListOfInts - This method looks up the specified field and /// returns its value as a vector of integers, throwing an exception if the /// field does not exist or if the value is not the right type. /// std::vector<int64_t> getValueAsListOfInts(StringRef FieldName) const; /// getValueAsListOfStrings - This method looks up the specified field and /// returns its value as a vector of strings, throwing an exception if the /// field does not exist or if the value is not the right type. /// std::vector<std::string> getValueAsListOfStrings(StringRef FieldName) const; /// getValueAsDef - This method looks up the specified field and returns its /// value as a Record, throwing an exception if the field does not exist or if /// the value is not the right type. /// Record *getValueAsDef(StringRef FieldName) const; /// getValueAsBit - This method looks up the specified field and returns its /// value as a bit, throwing an exception if the field does not exist or if /// the value is not the right type. /// bool getValueAsBit(StringRef FieldName) const; /// getValueAsBitOrUnset - This method looks up the specified field and /// returns its value as a bit. If the field is unset, sets Unset to true and /// returns false. /// bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const; /// getValueAsInt - This method looks up the specified field and returns its /// value as an int64_t, throwing an exception if the field does not exist or /// if the value is not the right type. /// int64_t getValueAsInt(StringRef FieldName) const; /// getValueAsDag - This method looks up the specified field and returns its /// value as an Dag, throwing an exception if the field does not exist or if /// the value is not the right type. /// DagInit *getValueAsDag(StringRef FieldName) const; }; raw_ostream &operator<<(raw_ostream &OS, const Record &R); struct MultiClass { Record Rec; // Placeholder for template args and Name. typedef std::vector<std::unique_ptr<Record>> RecordVector; RecordVector DefPrototypes; void dump() const; MultiClass(const std::string &Name, SMLoc Loc, RecordKeeper &Records) : Rec(Name, Loc, Records) {} }; class RecordKeeper { typedef std::map<std::string, std::unique_ptr<Record>> RecordMap; RecordMap Classes, Defs; public: const RecordMap &getClasses() const { return Classes; } const RecordMap &getDefs() const { return Defs; } Record *getClass(const std::string &Name) const { auto I = Classes.find(Name); return I == Classes.end() ? nullptr : I->second.get(); } Record *getDef(const std::string &Name) const { auto I = Defs.find(Name); return I == Defs.end() ? nullptr : I->second.get(); } void addClass(std::unique_ptr<Record> R) { bool Ins = Classes.insert(std::make_pair(R->getName(), std::move(R))).second; (void)Ins; assert(Ins && "Class already exists"); } void addDef(std::unique_ptr<Record> R) { bool Ins = Defs.insert(std::make_pair(R->getName(), std::move(R))).second; (void)Ins; assert(Ins && "Record already exists"); } //===--------------------------------------------------------------------===// // High-level helper methods, useful for tablegen backends... /// getAllDerivedDefinitions - This method returns all concrete definitions /// that derive from the specified class name. If a class with the specified /// name does not exist, an exception is thrown. std::vector<Record*> getAllDerivedDefinitions(const std::string &ClassName) const; void dump() const; }; /// LessRecord - Sorting predicate to sort record pointers by name. /// struct LessRecord { bool operator()(const Record *Rec1, const Record *Rec2) const { return StringRef(Rec1->getName()).compare_numeric(Rec2->getName()) < 0; } }; /// LessRecordByID - Sorting predicate to sort record pointers by their /// unique ID. If you just need a deterministic order, use this, since it /// just compares two `unsigned`; the other sorting predicates require /// string manipulation. struct LessRecordByID { bool operator()(const Record *LHS, const Record *RHS) const { return LHS->getID() < RHS->getID(); } }; /// LessRecordFieldName - Sorting predicate to sort record pointers by their /// name field. /// struct LessRecordFieldName { bool operator()(const Record *Rec1, const Record *Rec2) const { return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name"); } }; struct LessRecordRegister { static bool ascii_isdigit(char x) { return x >= '0' && x <= '9'; } struct RecordParts { SmallVector<std::pair< bool, StringRef>, 4> Parts; RecordParts(StringRef Rec) { if (Rec.empty()) return; size_t Len = 0; const char *Start = Rec.data(); const char *Curr = Start; bool isDigitPart = ascii_isdigit(Curr[0]); for (size_t I = 0, E = Rec.size(); I != E; ++I, ++Len) { bool isDigit = ascii_isdigit(Curr[I]); if (isDigit != isDigitPart) { Parts.push_back(std::make_pair(isDigitPart, StringRef(Start, Len))); Len = 0; Start = &Curr[I]; isDigitPart = ascii_isdigit(Curr[I]); } } // Push the last part. Parts.push_back(std::make_pair(isDigitPart, StringRef(Start, Len))); } size_t size() { return Parts.size(); } std::pair<bool, StringRef> getPart(size_t i) { assert (i < Parts.size() && "Invalid idx!"); return Parts[i]; } }; bool operator()(const Record *Rec1, const Record *Rec2) const { RecordParts LHSParts(StringRef(Rec1->getName())); RecordParts RHSParts(StringRef(Rec2->getName())); size_t LHSNumParts = LHSParts.size(); size_t RHSNumParts = RHSParts.size(); assert (LHSNumParts && RHSNumParts && "Expected at least one part!"); if (LHSNumParts != RHSNumParts) return LHSNumParts < RHSNumParts; // We expect the registers to be of the form [_a-zA-z]+([0-9]*[_a-zA-Z]*)*. for (size_t I = 0, E = LHSNumParts; I < E; I+=2) { std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I); std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I); // Expect even part to always be alpha. assert (LHSPart.first == false && RHSPart.first == false && "Expected both parts to be alpha."); if (int Res = LHSPart.second.compare(RHSPart.second)) return Res < 0; } for (size_t I = 1, E = LHSNumParts; I < E; I+=2) { std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I); std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I); // Expect odd part to always be numeric. assert (LHSPart.first == true && RHSPart.first == true && "Expected both parts to be numeric."); if (LHSPart.second.size() != RHSPart.second.size()) return LHSPart.second.size() < RHSPart.second.size(); unsigned LHSVal, RHSVal; bool LHSFailed = LHSPart.second.getAsInteger(10, LHSVal); (void)LHSFailed; assert(!LHSFailed && "Unable to convert LHS to integer."); bool RHSFailed = RHSPart.second.getAsInteger(10, RHSVal); (void)RHSFailed; assert(!RHSFailed && "Unable to convert RHS to integer."); if (LHSVal != RHSVal) return LHSVal < RHSVal; } return LHSNumParts < RHSNumParts; } }; raw_ostream &operator<<(raw_ostream &OS, const RecordKeeper &RK); /// QualifyName - Return an Init with a qualifier prefix referring /// to CurRec's name. Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass, Init *Name, const std::string &Scoper); /// QualifyName - Return an Init with a qualifier prefix referring /// to CurRec's name. Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass, const std::string &Name, const std::string &Scoper); } // End llvm namespace #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/TableGen/Main.h
//===- llvm/TableGen/Main.h - tblgen entry point ----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares the common entry point for tblgen tools. // //===----------------------------------------------------------------------===// #ifndef LLVM_TABLEGEN_MAIN_H #define LLVM_TABLEGEN_MAIN_H // HLSL Change Begins #ifdef _WIN32 #include <sal.h> #else #include "dxc/WinAdapter.h" #endif // HLSL Change Ends namespace llvm { class RecordKeeper; class raw_ostream; /// \brief Perform the action using Records, and write output to OS. /// \returns true on error, false otherwise typedef bool TableGenMainFn(raw_ostream &OS, RecordKeeper &Records); int TableGenMain(char *argv0, TableGenMainFn *MainFn); } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/TableGen/Error.h
//===- llvm/TableGen/Error.h - tblgen error handling helpers ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains error handling helper routines to pretty-print diagnostic // messages from tblgen. // //===----------------------------------------------------------------------===// #ifndef LLVM_TABLEGEN_ERROR_H #define LLVM_TABLEGEN_ERROR_H #include "llvm/Support/SourceMgr.h" namespace llvm { void PrintWarning(ArrayRef<SMLoc> WarningLoc, const Twine &Msg); void PrintWarning(const char *Loc, const Twine &Msg); void PrintWarning(const Twine &Msg); void PrintError(ArrayRef<SMLoc> ErrorLoc, const Twine &Msg); void PrintError(const char *Loc, const Twine &Msg); void PrintError(const Twine &Msg); LLVM_ATTRIBUTE_NORETURN void PrintFatalError(const Twine &Msg); LLVM_ATTRIBUTE_NORETURN void PrintFatalError(ArrayRef<SMLoc> ErrorLoc, const Twine &Msg); extern SourceMgr SrcMgr; extern unsigned ErrorsPrinted; } // end namespace "llvm" #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/llvm-c/TargetMachine.h
/*===-- llvm-c/TargetMachine.h - Target Machine Library C Interface - C++ -*-=*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header declares the C interface to the Target and TargetMachine *| |* classes, which can be used to generate assembly or object files. *| |* *| |* Many exotic languages can interoperate with C code but have a harder time *| |* with C++ due to name mangling. So in addition to C, this interface enables *| |* tools written in such languages. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_TARGETMACHINE_H #define LLVM_C_TARGETMACHINE_H #include "llvm-c/Core.h" #include "llvm-c/Target.h" #ifdef __cplusplus extern "C" { #endif typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef; typedef struct LLVMTarget *LLVMTargetRef; typedef enum { LLVMCodeGenLevelNone, LLVMCodeGenLevelLess, LLVMCodeGenLevelDefault, LLVMCodeGenLevelAggressive } LLVMCodeGenOptLevel; typedef enum { LLVMRelocDefault, LLVMRelocStatic, LLVMRelocPIC, LLVMRelocDynamicNoPic } LLVMRelocMode; typedef enum { LLVMCodeModelDefault, LLVMCodeModelJITDefault, LLVMCodeModelSmall, LLVMCodeModelKernel, LLVMCodeModelMedium, LLVMCodeModelLarge } LLVMCodeModel; typedef enum { LLVMAssemblyFile, LLVMObjectFile } LLVMCodeGenFileType; /** Returns the first llvm::Target in the registered targets list. */ LLVMTargetRef LLVMGetFirstTarget(void); /** Returns the next llvm::Target given a previous one (or null if there's none) */ LLVMTargetRef LLVMGetNextTarget(LLVMTargetRef T); /*===-- Target ------------------------------------------------------------===*/ /** Finds the target corresponding to the given name and stores it in \p T. Returns 0 on success. */ LLVMTargetRef LLVMGetTargetFromName(const char *Name); /** Finds the target corresponding to the given triple and stores it in \p T. Returns 0 on success. Optionally returns any error in ErrorMessage. Use LLVMDisposeMessage to dispose the message. */ LLVMBool LLVMGetTargetFromTriple( const char* Triple, LLVMTargetRef *T, char **ErrorMessage); /** Returns the name of a target. See llvm::Target::getName */ const char *LLVMGetTargetName(LLVMTargetRef T); /** Returns the description of a target. See llvm::Target::getDescription */ const char *LLVMGetTargetDescription(LLVMTargetRef T); /** Returns if the target has a JIT */ LLVMBool LLVMTargetHasJIT(LLVMTargetRef T); /** Returns if the target has a TargetMachine associated */ LLVMBool LLVMTargetHasTargetMachine(LLVMTargetRef T); /** Returns if the target as an ASM backend (required for emitting output) */ LLVMBool LLVMTargetHasAsmBackend(LLVMTargetRef T); /*===-- Target Machine ----------------------------------------------------===*/ /** Creates a new llvm::TargetMachine. See llvm::Target::createTargetMachine */ LLVMTargetMachineRef LLVMCreateTargetMachine(LLVMTargetRef T, const char *Triple, const char *CPU, const char *Features, LLVMCodeGenOptLevel Level, LLVMRelocMode Reloc, LLVMCodeModel CodeModel); /** Dispose the LLVMTargetMachineRef instance generated by LLVMCreateTargetMachine. */ void LLVMDisposeTargetMachine(LLVMTargetMachineRef T); /** Returns the Target used in a TargetMachine */ LLVMTargetRef LLVMGetTargetMachineTarget(LLVMTargetMachineRef T); /** Returns the triple used creating this target machine. See llvm::TargetMachine::getTriple. The result needs to be disposed with LLVMDisposeMessage. */ char *LLVMGetTargetMachineTriple(LLVMTargetMachineRef T); /** Returns the cpu used creating this target machine. See llvm::TargetMachine::getCPU. The result needs to be disposed with LLVMDisposeMessage. */ char *LLVMGetTargetMachineCPU(LLVMTargetMachineRef T); /** Returns the feature string used creating this target machine. See llvm::TargetMachine::getFeatureString. The result needs to be disposed with LLVMDisposeMessage. */ char *LLVMGetTargetMachineFeatureString(LLVMTargetMachineRef T); /** Deprecated: use LLVMGetDataLayout(LLVMModuleRef M) instead. */ LLVMTargetDataRef LLVMGetTargetMachineData(LLVMTargetMachineRef T); /** Set the target machine's ASM verbosity. */ void LLVMSetTargetMachineAsmVerbosity(LLVMTargetMachineRef T, LLVMBool VerboseAsm); /** Emits an asm or object file for the given module to the filename. This wraps several c++ only classes (among them a file stream). Returns any error in ErrorMessage. Use LLVMDisposeMessage to dispose the message. */ LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M, char *Filename, LLVMCodeGenFileType codegen, char **ErrorMessage); /** Compile the LLVM IR stored in \p M and store the result in \p OutMemBuf. */ LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T, LLVMModuleRef M, LLVMCodeGenFileType codegen, char** ErrorMessage, LLVMMemoryBufferRef *OutMemBuf); /*===-- Triple ------------------------------------------------------------===*/ /** Get a triple for the host machine as a string. The result needs to be disposed with LLVMDisposeMessage. */ char* LLVMGetDefaultTargetTriple(void); /** Adds the target-specific analysis passes to the pass manager. */ void LLVMAddAnalysisPasses(LLVMTargetMachineRef T, LLVMPassManagerRef PM); #ifdef __cplusplus } #endif #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/llvm-c/Core.h
/*===-- llvm-c/Core.h - Core Library C Interface ------------------*- C -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header declares the C interface to libLLVMCore.a, which implements *| |* the LLVM intermediate representation. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_CORE_H #define LLVM_C_CORE_H #include "llvm-c/Support.h" #ifdef __cplusplus extern "C" { #endif /** * @defgroup LLVMC LLVM-C: C interface to LLVM * * This module exposes parts of the LLVM library as a C API. * * @{ */ /** * @defgroup LLVMCTransforms Transforms */ /** * @defgroup LLVMCCore Core * * This modules provide an interface to libLLVMCore, which implements * the LLVM intermediate representation as well as other related types * and utilities. * * LLVM uses a polymorphic type hierarchy which C cannot represent, therefore * parameters must be passed as base types. Despite the declared types, most * of the functions provided operate only on branches of the type hierarchy. * The declared parameter names are descriptive and specify which type is * required. Additionally, each type hierarchy is documented along with the * functions that operate upon it. For more detail, refer to LLVM's C++ code. * If in doubt, refer to Core.cpp, which performs parameter downcasts in the * form unwrap<RequiredType>(Param). * * Many exotic languages can interoperate with C code but have a harder time * with C++ due to name mangling. So in addition to C, this interface enables * tools written in such languages. * * @{ */ /** * @defgroup LLVMCCoreTypes Types and Enumerations * * @{ */ /* Opaque types. */ /** * The top-level container for all LLVM global data. See the LLVMContext class. */ typedef struct LLVMOpaqueContext *LLVMContextRef; /** * The top-level container for all other LLVM Intermediate Representation (IR) * objects. * * @see llvm::Module */ typedef struct LLVMOpaqueModule *LLVMModuleRef; /** * Each value in the LLVM IR has a type, an LLVMTypeRef. * * @see llvm::Type */ typedef struct LLVMOpaqueType *LLVMTypeRef; /** * Represents an individual value in LLVM IR. * * This models llvm::Value. */ typedef struct LLVMOpaqueValue *LLVMValueRef; /** * Represents a basic block of instructions in LLVM IR. * * This models llvm::BasicBlock. */ typedef struct LLVMOpaqueBasicBlock *LLVMBasicBlockRef; /** * Represents an LLVM basic block builder. * * This models llvm::IRBuilder. */ typedef struct LLVMOpaqueBuilder *LLVMBuilderRef; /** * Interface used to provide a module to JIT or interpreter. * This is now just a synonym for llvm::Module, but we have to keep using the * different type to keep binary compatibility. */ typedef struct LLVMOpaqueModuleProvider *LLVMModuleProviderRef; /** @see llvm::PassManagerBase */ typedef struct LLVMOpaquePassManager *LLVMPassManagerRef; /** @see llvm::PassRegistry */ typedef struct LLVMOpaquePassRegistry *LLVMPassRegistryRef; /** * Used to get the users and usees of a Value. * * @see llvm::Use */ typedef struct LLVMOpaqueUse *LLVMUseRef; /** * @see llvm::DiagnosticInfo */ typedef struct LLVMOpaqueDiagnosticInfo *LLVMDiagnosticInfoRef; typedef enum { LLVMZExtAttribute = 1<<0, LLVMSExtAttribute = 1<<1, LLVMNoReturnAttribute = 1<<2, LLVMInRegAttribute = 1<<3, LLVMStructRetAttribute = 1<<4, LLVMNoUnwindAttribute = 1<<5, LLVMNoAliasAttribute = 1<<6, LLVMByValAttribute = 1<<7, LLVMNestAttribute = 1<<8, LLVMReadNoneAttribute = 1<<9, LLVMReadOnlyAttribute = 1<<10, LLVMNoInlineAttribute = 1<<11, LLVMAlwaysInlineAttribute = 1<<12, LLVMOptimizeForSizeAttribute = 1<<13, LLVMStackProtectAttribute = 1<<14, LLVMStackProtectReqAttribute = 1<<15, LLVMAlignment = 31<<16, LLVMNoCaptureAttribute = 1<<21, LLVMNoRedZoneAttribute = 1<<22, LLVMNoImplicitFloatAttribute = 1<<23, LLVMNakedAttribute = 1<<24, LLVMInlineHintAttribute = 1<<25, LLVMStackAlignment = 7<<26, LLVMReturnsTwice = 1 << 29, LLVMUWTable = 1 << 30, LLVMNonLazyBind = 1 << 31 /* FIXME: These attributes are currently not included in the C API as a temporary measure until the API/ABI impact to the C API is understood and the path forward agreed upon. LLVMSanitizeAddressAttribute = 1ULL << 32, LLVMStackProtectStrongAttribute = 1ULL<<35, LLVMColdAttribute = 1ULL << 40, LLVMOptimizeNoneAttribute = 1ULL << 42, LLVMInAllocaAttribute = 1ULL << 43, LLVMNonNullAttribute = 1ULL << 44, LLVMJumpTableAttribute = 1ULL << 45, LLVMConvergentAttribute = 1ULL << 46, LLVMSafeStackAttribute = 1ULL << 47, */ } LLVMAttribute; typedef enum { /* Terminator Instructions */ LLVMRet = 1, LLVMBr = 2, LLVMSwitch = 3, LLVMIndirectBr = 4, LLVMInvoke = 5, /* removed 6 due to API changes */ LLVMUnreachable = 7, /* Standard Binary Operators */ LLVMAdd = 8, LLVMFAdd = 9, LLVMSub = 10, LLVMFSub = 11, LLVMMul = 12, LLVMFMul = 13, LLVMUDiv = 14, LLVMSDiv = 15, LLVMFDiv = 16, LLVMURem = 17, LLVMSRem = 18, LLVMFRem = 19, /* Logical Operators */ LLVMShl = 20, LLVMLShr = 21, LLVMAShr = 22, LLVMAnd = 23, LLVMOr = 24, LLVMXor = 25, /* Memory Operators */ LLVMAlloca = 26, LLVMLoad = 27, LLVMStore = 28, LLVMGetElementPtr = 29, /* Cast Operators */ LLVMTrunc = 30, LLVMZExt = 31, LLVMSExt = 32, LLVMFPToUI = 33, LLVMFPToSI = 34, LLVMUIToFP = 35, LLVMSIToFP = 36, LLVMFPTrunc = 37, LLVMFPExt = 38, LLVMPtrToInt = 39, LLVMIntToPtr = 40, LLVMBitCast = 41, LLVMAddrSpaceCast = 60, /* Other Operators */ LLVMICmp = 42, LLVMFCmp = 43, LLVMPHI = 44, LLVMCall = 45, LLVMSelect = 46, LLVMUserOp1 = 47, LLVMUserOp2 = 48, LLVMVAArg = 49, LLVMExtractElement = 50, LLVMInsertElement = 51, LLVMShuffleVector = 52, LLVMExtractValue = 53, LLVMInsertValue = 54, /* Atomic operators */ LLVMFence = 55, LLVMAtomicCmpXchg = 56, LLVMAtomicRMW = 57, /* Exception Handling Operators */ LLVMResume = 58, LLVMLandingPad = 59 } LLVMOpcode; typedef enum { LLVMVoidTypeKind, /**< type with no size */ LLVMHalfTypeKind, /**< 16 bit floating point type */ LLVMFloatTypeKind, /**< 32 bit floating point type */ LLVMDoubleTypeKind, /**< 64 bit floating point type */ LLVMX86_FP80TypeKind, /**< 80 bit floating point type (X87) */ LLVMFP128TypeKind, /**< 128 bit floating point type (112-bit mantissa)*/ LLVMPPC_FP128TypeKind, /**< 128 bit floating point type (two 64-bits) */ LLVMLabelTypeKind, /**< Labels */ LLVMIntegerTypeKind, /**< Arbitrary bit width integers */ LLVMFunctionTypeKind, /**< Functions */ LLVMStructTypeKind, /**< Structures */ LLVMArrayTypeKind, /**< Arrays */ LLVMPointerTypeKind, /**< Pointers */ LLVMVectorTypeKind, /**< SIMD 'packed' format, or other vector type */ LLVMMetadataTypeKind, /**< Metadata */ LLVMX86_MMXTypeKind /**< X86 MMX */ } LLVMTypeKind; typedef enum { LLVMExternalLinkage, /**< Externally visible function */ LLVMAvailableExternallyLinkage, LLVMLinkOnceAnyLinkage, /**< Keep one copy of function when linking (inline)*/ LLVMLinkOnceODRLinkage, /**< Same, but only replaced by something equivalent. */ LLVMLinkOnceODRAutoHideLinkage, /**< Obsolete */ LLVMWeakAnyLinkage, /**< Keep one copy of function when linking (weak) */ LLVMWeakODRLinkage, /**< Same, but only replaced by something equivalent. */ LLVMAppendingLinkage, /**< Special purpose, only applies to global arrays */ LLVMInternalLinkage, /**< Rename collisions when linking (static functions) */ LLVMPrivateLinkage, /**< Like Internal, but omit from symbol table */ LLVMDLLImportLinkage, /**< Obsolete */ LLVMDLLExportLinkage, /**< Obsolete */ LLVMExternalWeakLinkage,/**< ExternalWeak linkage description */ LLVMGhostLinkage, /**< Obsolete */ LLVMCommonLinkage, /**< Tentative definitions */ LLVMLinkerPrivateLinkage, /**< Like Private, but linker removes. */ LLVMLinkerPrivateWeakLinkage /**< Like LinkerPrivate, but is weak. */ } LLVMLinkage; typedef enum { LLVMDefaultVisibility, /**< The GV is visible */ LLVMHiddenVisibility, /**< The GV is hidden */ LLVMProtectedVisibility /**< The GV is protected */ } LLVMVisibility; typedef enum { LLVMDefaultStorageClass = 0, LLVMDLLImportStorageClass = 1, /**< Function to be imported from DLL. */ LLVMDLLExportStorageClass = 2 /**< Function to be accessible from DLL. */ } LLVMDLLStorageClass; typedef enum { LLVMCCallConv = 0, LLVMFastCallConv = 8, LLVMColdCallConv = 9, LLVMWebKitJSCallConv = 12, LLVMAnyRegCallConv = 13, LLVMX86StdcallCallConv = 64, LLVMX86FastcallCallConv = 65 } LLVMCallConv; typedef enum { LLVMIntEQ = 32, /**< equal */ LLVMIntNE, /**< not equal */ LLVMIntUGT, /**< unsigned greater than */ LLVMIntUGE, /**< unsigned greater or equal */ LLVMIntULT, /**< unsigned less than */ LLVMIntULE, /**< unsigned less or equal */ LLVMIntSGT, /**< signed greater than */ LLVMIntSGE, /**< signed greater or equal */ LLVMIntSLT, /**< signed less than */ LLVMIntSLE /**< signed less or equal */ } LLVMIntPredicate; typedef enum { LLVMRealPredicateFalse, /**< Always false (always folded) */ LLVMRealOEQ, /**< True if ordered and equal */ LLVMRealOGT, /**< True if ordered and greater than */ LLVMRealOGE, /**< True if ordered and greater than or equal */ LLVMRealOLT, /**< True if ordered and less than */ LLVMRealOLE, /**< True if ordered and less than or equal */ LLVMRealONE, /**< True if ordered and operands are unequal */ LLVMRealORD, /**< True if ordered (no nans) */ LLVMRealUNO, /**< True if unordered: isnan(X) | isnan(Y) */ LLVMRealUEQ, /**< True if unordered or equal */ LLVMRealUGT, /**< True if unordered or greater than */ LLVMRealUGE, /**< True if unordered, greater than, or equal */ LLVMRealULT, /**< True if unordered or less than */ LLVMRealULE, /**< True if unordered, less than, or equal */ LLVMRealUNE, /**< True if unordered or not equal */ LLVMRealPredicateTrue /**< Always true (always folded) */ } LLVMRealPredicate; typedef enum { LLVMLandingPadCatch, /**< A catch clause */ LLVMLandingPadFilter /**< A filter clause */ } LLVMLandingPadClauseTy; typedef enum { LLVMNotThreadLocal = 0, LLVMGeneralDynamicTLSModel, LLVMLocalDynamicTLSModel, LLVMInitialExecTLSModel, LLVMLocalExecTLSModel } LLVMThreadLocalMode; typedef enum { LLVMAtomicOrderingNotAtomic = 0, /**< A load or store which is not atomic */ LLVMAtomicOrderingUnordered = 1, /**< Lowest level of atomicity, guarantees somewhat sane results, lock free. */ LLVMAtomicOrderingMonotonic = 2, /**< guarantees that if you take all the operations affecting a specific address, a consistent ordering exists */ LLVMAtomicOrderingAcquire = 4, /**< Acquire provides a barrier of the sort necessary to acquire a lock to access other memory with normal loads and stores. */ LLVMAtomicOrderingRelease = 5, /**< Release is similar to Acquire, but with a barrier of the sort necessary to release a lock. */ LLVMAtomicOrderingAcquireRelease = 6, /**< provides both an Acquire and a Release barrier (for fences and operations which both read and write memory). */ LLVMAtomicOrderingSequentiallyConsistent = 7 /**< provides Acquire semantics for loads and Release semantics for stores. Additionally, it guarantees that a total ordering exists between all SequentiallyConsistent operations. */ } LLVMAtomicOrdering; typedef enum { LLVMAtomicRMWBinOpXchg, /**< Set the new value and return the one old */ LLVMAtomicRMWBinOpAdd, /**< Add a value and return the old one */ LLVMAtomicRMWBinOpSub, /**< Subtract a value and return the old one */ LLVMAtomicRMWBinOpAnd, /**< And a value and return the old one */ LLVMAtomicRMWBinOpNand, /**< Not-And a value and return the old one */ LLVMAtomicRMWBinOpOr, /**< OR a value and return the old one */ LLVMAtomicRMWBinOpXor, /**< Xor a value and return the old one */ LLVMAtomicRMWBinOpMax, /**< Sets the value if it's greater than the original using a signed comparison and return the old one */ LLVMAtomicRMWBinOpMin, /**< Sets the value if it's Smaller than the original using a signed comparison and return the old one */ LLVMAtomicRMWBinOpUMax, /**< Sets the value if it's greater than the original using an unsigned comparison and return the old one */ LLVMAtomicRMWBinOpUMin /**< Sets the value if it's greater than the original using an unsigned comparison and return the old one */ } LLVMAtomicRMWBinOp; typedef enum { LLVMDSError, LLVMDSWarning, LLVMDSRemark, LLVMDSNote } LLVMDiagnosticSeverity; /** * @} */ void LLVMInitializeCore(LLVMPassRegistryRef R); /** Deallocate and destroy all ManagedStatic variables. @see llvm::llvm_shutdown @see ManagedStatic */ void LLVMShutdown(void); /*===-- Error handling ----------------------------------------------------===*/ char *LLVMCreateMessage(const char *Message); void LLVMDisposeMessage(char *Message); typedef void (*LLVMFatalErrorHandler)(const char *Reason); /** * Install a fatal error handler. By default, if LLVM detects a fatal error, it * will call exit(1). This may not be appropriate in many contexts. For example, * doing exit(1) will bypass many crash reporting/tracing system tools. This * function allows you to install a callback that will be invoked prior to the * call to exit(1). */ void LLVMInstallFatalErrorHandler(LLVMFatalErrorHandler Handler); /** * Reset the fatal error handler. This resets LLVM's fatal error handling * behavior to the default. */ void LLVMResetFatalErrorHandler(void); /** * Enable LLVM's built-in stack trace code. This intercepts the OS's crash * signals and prints which component of LLVM you were in at the time if the * crash. */ void LLVMEnablePrettyStackTrace(void); /** * @defgroup LLVMCCoreContext Contexts * * Contexts are execution states for the core LLVM IR system. * * Most types are tied to a context instance. Multiple contexts can * exist simultaneously. A single context is not thread safe. However, * different contexts can execute on different threads simultaneously. * * @{ */ typedef void (*LLVMDiagnosticHandler)(LLVMDiagnosticInfoRef, void *); typedef void (*LLVMYieldCallback)(LLVMContextRef, void *); /** * Create a new context. * * Every call to this function should be paired with a call to * LLVMContextDispose() or the context will leak memory. */ LLVMContextRef LLVMContextCreate(void); /** * Obtain the global context instance. */ LLVMContextRef LLVMGetGlobalContext(void); /** * Set the diagnostic handler for this context. */ void LLVMContextSetDiagnosticHandler(LLVMContextRef C, LLVMDiagnosticHandler Handler, void *DiagnosticContext); /** * Set the yield callback function for this context. * * @see LLVMContext::setYieldCallback() */ void LLVMContextSetYieldCallback(LLVMContextRef C, LLVMYieldCallback Callback, void *OpaqueHandle); /** * Destroy a context instance. * * This should be called for every call to LLVMContextCreate() or memory * will be leaked. */ void LLVMContextDispose(LLVMContextRef C); /** * Return a string representation of the DiagnosticInfo. Use * LLVMDisposeMessage to free the string. * * @see DiagnosticInfo::print() */ char *LLVMGetDiagInfoDescription(LLVMDiagnosticInfoRef DI); /** * Return an enum LLVMDiagnosticSeverity. * * @see DiagnosticInfo::getSeverity() */ LLVMDiagnosticSeverity LLVMGetDiagInfoSeverity(LLVMDiagnosticInfoRef DI); unsigned LLVMGetMDKindIDInContext(LLVMContextRef C, const char* Name, unsigned SLen); unsigned LLVMGetMDKindID(const char* Name, unsigned SLen); /** * @} */ /** * @defgroup LLVMCCoreModule Modules * * Modules represent the top-level structure in an LLVM program. An LLVM * module is effectively a translation unit or a collection of * translation units merged together. * * @{ */ /** * Create a new, empty module in the global context. * * This is equivalent to calling LLVMModuleCreateWithNameInContext with * LLVMGetGlobalContext() as the context parameter. * * Every invocation should be paired with LLVMDisposeModule() or memory * will be leaked. */ LLVMModuleRef LLVMModuleCreateWithName(const char *ModuleID); /** * Create a new, empty module in a specific context. * * Every invocation should be paired with LLVMDisposeModule() or memory * will be leaked. */ LLVMModuleRef LLVMModuleCreateWithNameInContext(const char *ModuleID, LLVMContextRef C); /** * Return an exact copy of the specified module. */ LLVMModuleRef LLVMCloneModule(LLVMModuleRef M); /** * Destroy a module instance. * * This must be called for every created module or memory will be * leaked. */ void LLVMDisposeModule(LLVMModuleRef M); /** * Obtain the data layout for a module. * * @see Module::getDataLayout() */ const char *LLVMGetDataLayout(LLVMModuleRef M); /** * Set the data layout for a module. * * @see Module::setDataLayout() */ void LLVMSetDataLayout(LLVMModuleRef M, const char *Triple); /** * Obtain the target triple for a module. * * @see Module::getTargetTriple() */ const char *LLVMGetTarget(LLVMModuleRef M); /** * Set the target triple for a module. * * @see Module::setTargetTriple() */ void LLVMSetTarget(LLVMModuleRef M, const char *Triple); /** * Dump a representation of a module to stderr. * * @see Module::dump() */ void LLVMDumpModule(LLVMModuleRef M); /** * Print a representation of a module to a file. The ErrorMessage needs to be * disposed with LLVMDisposeMessage. Returns 0 on success, 1 otherwise. * * @see Module::print() */ LLVMBool LLVMPrintModuleToFile(LLVMModuleRef M, const char *Filename, char **ErrorMessage); /** * Return a string representation of the module. Use * LLVMDisposeMessage to free the string. * * @see Module::print() */ char *LLVMPrintModuleToString(LLVMModuleRef M); /** * Set inline assembly for a module. * * @see Module::setModuleInlineAsm() */ void LLVMSetModuleInlineAsm(LLVMModuleRef M, const char *Asm); /** * Obtain the context to which this module is associated. * * @see Module::getContext() */ LLVMContextRef LLVMGetModuleContext(LLVMModuleRef M); /** * Obtain a Type from a module by its registered name. */ LLVMTypeRef LLVMGetTypeByName(LLVMModuleRef M, const char *Name); /** * Obtain the number of operands for named metadata in a module. * * @see llvm::Module::getNamedMetadata() */ unsigned LLVMGetNamedMetadataNumOperands(LLVMModuleRef M, const char* name); /** * Obtain the named metadata operands for a module. * * The passed LLVMValueRef pointer should refer to an array of * LLVMValueRef at least LLVMGetNamedMetadataNumOperands long. This * array will be populated with the LLVMValueRef instances. Each * instance corresponds to a llvm::MDNode. * * @see llvm::Module::getNamedMetadata() * @see llvm::MDNode::getOperand() */ void LLVMGetNamedMetadataOperands(LLVMModuleRef M, const char* name, LLVMValueRef *Dest); /** * Add an operand to named metadata. * * @see llvm::Module::getNamedMetadata() * @see llvm::MDNode::addOperand() */ void LLVMAddNamedMetadataOperand(LLVMModuleRef M, const char* name, LLVMValueRef Val); /** * Add a function to a module under a specified name. * * @see llvm::Function::Create() */ LLVMValueRef LLVMAddFunction(LLVMModuleRef M, const char *Name, LLVMTypeRef FunctionTy); /** * Obtain a Function value from a Module by its name. * * The returned value corresponds to a llvm::Function value. * * @see llvm::Module::getFunction() */ LLVMValueRef LLVMGetNamedFunction(LLVMModuleRef M, const char *Name); /** * Obtain an iterator to the first Function in a Module. * * @see llvm::Module::begin() */ LLVMValueRef LLVMGetFirstFunction(LLVMModuleRef M); /** * Obtain an iterator to the last Function in a Module. * * @see llvm::Module::end() */ LLVMValueRef LLVMGetLastFunction(LLVMModuleRef M); /** * Advance a Function iterator to the next Function. * * Returns NULL if the iterator was already at the end and there are no more * functions. */ LLVMValueRef LLVMGetNextFunction(LLVMValueRef Fn); /** * Decrement a Function iterator to the previous Function. * * Returns NULL if the iterator was already at the beginning and there are * no previous functions. */ LLVMValueRef LLVMGetPreviousFunction(LLVMValueRef Fn); /** * @} */ /** * @defgroup LLVMCCoreType Types * * Types represent the type of a value. * * Types are associated with a context instance. The context internally * deduplicates types so there is only 1 instance of a specific type * alive at a time. In other words, a unique type is shared among all * consumers within a context. * * A Type in the C API corresponds to llvm::Type. * * Types have the following hierarchy: * * types: * integer type * real type * function type * sequence types: * array type * pointer type * vector type * void type * label type * opaque type * * @{ */ /** * Obtain the enumerated type of a Type instance. * * @see llvm::Type:getTypeID() */ LLVMTypeKind LLVMGetTypeKind(LLVMTypeRef Ty); /** * Whether the type has a known size. * * Things that don't have a size are abstract types, labels, and void.a * * @see llvm::Type::isSized() */ LLVMBool LLVMTypeIsSized(LLVMTypeRef Ty); /** * Obtain the context to which this type instance is associated. * * @see llvm::Type::getContext() */ LLVMContextRef LLVMGetTypeContext(LLVMTypeRef Ty); /** * Dump a representation of a type to stderr. * * @see llvm::Type::dump() */ void LLVMDumpType(LLVMTypeRef Val); /** * Return a string representation of the type. Use * LLVMDisposeMessage to free the string. * * @see llvm::Type::print() */ char *LLVMPrintTypeToString(LLVMTypeRef Val); /** * @defgroup LLVMCCoreTypeInt Integer Types * * Functions in this section operate on integer types. * * @{ */ /** * Obtain an integer type from a context with specified bit width. */ LLVMTypeRef LLVMInt1TypeInContext(LLVMContextRef C); LLVMTypeRef LLVMInt8TypeInContext(LLVMContextRef C); LLVMTypeRef LLVMInt16TypeInContext(LLVMContextRef C); LLVMTypeRef LLVMInt32TypeInContext(LLVMContextRef C); LLVMTypeRef LLVMInt64TypeInContext(LLVMContextRef C); LLVMTypeRef LLVMIntTypeInContext(LLVMContextRef C, unsigned NumBits); /** * Obtain an integer type from the global context with a specified bit * width. */ LLVMTypeRef LLVMInt1Type(void); LLVMTypeRef LLVMInt8Type(void); LLVMTypeRef LLVMInt16Type(void); LLVMTypeRef LLVMInt32Type(void); LLVMTypeRef LLVMInt64Type(void); LLVMTypeRef LLVMIntType(unsigned NumBits); unsigned LLVMGetIntTypeWidth(LLVMTypeRef IntegerTy); /** * @} */ /** * @defgroup LLVMCCoreTypeFloat Floating Point Types * * @{ */ /** * Obtain a 16-bit floating point type from a context. */ LLVMTypeRef LLVMHalfTypeInContext(LLVMContextRef C); /** * Obtain a 32-bit floating point type from a context. */ LLVMTypeRef LLVMFloatTypeInContext(LLVMContextRef C); /** * Obtain a 64-bit floating point type from a context. */ LLVMTypeRef LLVMDoubleTypeInContext(LLVMContextRef C); /** * Obtain a 80-bit floating point type (X87) from a context. */ LLVMTypeRef LLVMX86FP80TypeInContext(LLVMContextRef C); /** * Obtain a 128-bit floating point type (112-bit mantissa) from a * context. */ LLVMTypeRef LLVMFP128TypeInContext(LLVMContextRef C); /** * Obtain a 128-bit floating point type (two 64-bits) from a context. */ LLVMTypeRef LLVMPPCFP128TypeInContext(LLVMContextRef C); /** * Obtain a floating point type from the global context. * * These map to the functions in this group of the same name. */ LLVMTypeRef LLVMHalfType(void); LLVMTypeRef LLVMFloatType(void); LLVMTypeRef LLVMDoubleType(void); LLVMTypeRef LLVMX86FP80Type(void); LLVMTypeRef LLVMFP128Type(void); LLVMTypeRef LLVMPPCFP128Type(void); /** * @} */ /** * @defgroup LLVMCCoreTypeFunction Function Types * * @{ */ /** * Obtain a function type consisting of a specified signature. * * The function is defined as a tuple of a return Type, a list of * parameter types, and whether the function is variadic. */ LLVMTypeRef LLVMFunctionType(LLVMTypeRef ReturnType, LLVMTypeRef *ParamTypes, unsigned ParamCount, LLVMBool IsVarArg); /** * Returns whether a function type is variadic. */ LLVMBool LLVMIsFunctionVarArg(LLVMTypeRef FunctionTy); /** * Obtain the Type this function Type returns. */ LLVMTypeRef LLVMGetReturnType(LLVMTypeRef FunctionTy); /** * Obtain the number of parameters this function accepts. */ unsigned LLVMCountParamTypes(LLVMTypeRef FunctionTy); /** * Obtain the types of a function's parameters. * * The Dest parameter should point to a pre-allocated array of * LLVMTypeRef at least LLVMCountParamTypes() large. On return, the * first LLVMCountParamTypes() entries in the array will be populated * with LLVMTypeRef instances. * * @param FunctionTy The function type to operate on. * @param Dest Memory address of an array to be filled with result. */ void LLVMGetParamTypes(LLVMTypeRef FunctionTy, LLVMTypeRef *Dest); /** * @} */ /** * @defgroup LLVMCCoreTypeStruct Structure Types * * These functions relate to LLVMTypeRef instances. * * @see llvm::StructType * * @{ */ /** * Create a new structure type in a context. * * A structure is specified by a list of inner elements/types and * whether these can be packed together. * * @see llvm::StructType::create() */ LLVMTypeRef LLVMStructTypeInContext(LLVMContextRef C, LLVMTypeRef *ElementTypes, unsigned ElementCount, LLVMBool Packed); /** * Create a new structure type in the global context. * * @see llvm::StructType::create() */ LLVMTypeRef LLVMStructType(LLVMTypeRef *ElementTypes, unsigned ElementCount, LLVMBool Packed); /** * Create an empty structure in a context having a specified name. * * @see llvm::StructType::create() */ LLVMTypeRef LLVMStructCreateNamed(LLVMContextRef C, const char *Name); /** * Obtain the name of a structure. * * @see llvm::StructType::getName() */ const char *LLVMGetStructName(LLVMTypeRef Ty); /** * Set the contents of a structure type. * * @see llvm::StructType::setBody() */ void LLVMStructSetBody(LLVMTypeRef StructTy, LLVMTypeRef *ElementTypes, unsigned ElementCount, LLVMBool Packed); /** * Get the number of elements defined inside the structure. * * @see llvm::StructType::getNumElements() */ unsigned LLVMCountStructElementTypes(LLVMTypeRef StructTy); /** * Get the elements within a structure. * * The function is passed the address of a pre-allocated array of * LLVMTypeRef at least LLVMCountStructElementTypes() long. After * invocation, this array will be populated with the structure's * elements. The objects in the destination array will have a lifetime * of the structure type itself, which is the lifetime of the context it * is contained in. */ void LLVMGetStructElementTypes(LLVMTypeRef StructTy, LLVMTypeRef *Dest); /** * Get the type of the element at a given index in the structure. * * @see llvm::StructType::getTypeAtIndex() */ LLVMTypeRef LLVMStructGetTypeAtIndex(LLVMTypeRef StructTy, unsigned i); /** * Determine whether a structure is packed. * * @see llvm::StructType::isPacked() */ LLVMBool LLVMIsPackedStruct(LLVMTypeRef StructTy); /** * Determine whether a structure is opaque. * * @see llvm::StructType::isOpaque() */ LLVMBool LLVMIsOpaqueStruct(LLVMTypeRef StructTy); /** * @} */ /** * @defgroup LLVMCCoreTypeSequential Sequential Types * * Sequential types represents "arrays" of types. This is a super class * for array, vector, and pointer types. * * @{ */ /** * Obtain the type of elements within a sequential type. * * This works on array, vector, and pointer types. * * @see llvm::SequentialType::getElementType() */ LLVMTypeRef LLVMGetElementType(LLVMTypeRef Ty); /** * Create a fixed size array type that refers to a specific type. * * The created type will exist in the context that its element type * exists in. * * @see llvm::ArrayType::get() */ LLVMTypeRef LLVMArrayType(LLVMTypeRef ElementType, unsigned ElementCount); /** * Obtain the length of an array type. * * This only works on types that represent arrays. * * @see llvm::ArrayType::getNumElements() */ unsigned LLVMGetArrayLength(LLVMTypeRef ArrayTy); /** * Create a pointer type that points to a defined type. * * The created type will exist in the context that its pointee type * exists in. * * @see llvm::PointerType::get() */ LLVMTypeRef LLVMPointerType(LLVMTypeRef ElementType, unsigned AddressSpace); /** * Obtain the address space of a pointer type. * * This only works on types that represent pointers. * * @see llvm::PointerType::getAddressSpace() */ unsigned LLVMGetPointerAddressSpace(LLVMTypeRef PointerTy); /** * Create a vector type that contains a defined type and has a specific * number of elements. * * The created type will exist in the context thats its element type * exists in. * * @see llvm::VectorType::get() */ LLVMTypeRef LLVMVectorType(LLVMTypeRef ElementType, unsigned ElementCount); /** * Obtain the number of elements in a vector type. * * This only works on types that represent vectors. * * @see llvm::VectorType::getNumElements() */ unsigned LLVMGetVectorSize(LLVMTypeRef VectorTy); /** * @} */ /** * @defgroup LLVMCCoreTypeOther Other Types * * @{ */ /** * Create a void type in a context. */ LLVMTypeRef LLVMVoidTypeInContext(LLVMContextRef C); /** * Create a label type in a context. */ LLVMTypeRef LLVMLabelTypeInContext(LLVMContextRef C); /** * Create a X86 MMX type in a context. */ LLVMTypeRef LLVMX86MMXTypeInContext(LLVMContextRef C); /** * These are similar to the above functions except they operate on the * global context. */ LLVMTypeRef LLVMVoidType(void); LLVMTypeRef LLVMLabelType(void); LLVMTypeRef LLVMX86MMXType(void); /** * @} */ /** * @} */ /** * @defgroup LLVMCCoreValues Values * * The bulk of LLVM's object model consists of values, which comprise a very * rich type hierarchy. * * LLVMValueRef essentially represents llvm::Value. There is a rich * hierarchy of classes within this type. Depending on the instance * obtained, not all APIs are available. * * Callers can determine the type of an LLVMValueRef by calling the * LLVMIsA* family of functions (e.g. LLVMIsAArgument()). These * functions are defined by a macro, so it isn't obvious which are * available by looking at the Doxygen source code. Instead, look at the * source definition of LLVM_FOR_EACH_VALUE_SUBCLASS and note the list * of value names given. These value names also correspond to classes in * the llvm::Value hierarchy. * * @{ */ #define LLVM_FOR_EACH_VALUE_SUBCLASS(macro) \ macro(Argument) \ macro(BasicBlock) \ macro(InlineAsm) \ macro(User) \ macro(Constant) \ macro(BlockAddress) \ macro(ConstantAggregateZero) \ macro(ConstantArray) \ macro(ConstantDataSequential) \ macro(ConstantDataArray) \ macro(ConstantDataVector) \ macro(ConstantExpr) \ macro(ConstantFP) \ macro(ConstantInt) \ macro(ConstantPointerNull) \ macro(ConstantStruct) \ macro(ConstantVector) \ macro(GlobalValue) \ macro(GlobalAlias) \ macro(GlobalObject) \ macro(Function) \ macro(GlobalVariable) \ macro(UndefValue) \ macro(Instruction) \ macro(BinaryOperator) \ macro(CallInst) \ macro(IntrinsicInst) \ macro(DbgInfoIntrinsic) \ macro(DbgDeclareInst) \ macro(MemIntrinsic) \ macro(MemCpyInst) \ macro(MemMoveInst) \ macro(MemSetInst) \ macro(CmpInst) \ macro(FCmpInst) \ macro(ICmpInst) \ macro(ExtractElementInst) \ macro(GetElementPtrInst) \ macro(InsertElementInst) \ macro(InsertValueInst) \ macro(LandingPadInst) \ macro(PHINode) \ macro(SelectInst) \ macro(ShuffleVectorInst) \ macro(StoreInst) \ macro(TerminatorInst) \ macro(BranchInst) \ macro(IndirectBrInst) \ macro(InvokeInst) \ macro(ReturnInst) \ macro(SwitchInst) \ macro(UnreachableInst) \ macro(ResumeInst) \ macro(UnaryInstruction) \ macro(AllocaInst) \ macro(CastInst) \ macro(AddrSpaceCastInst) \ macro(BitCastInst) \ macro(FPExtInst) \ macro(FPToSIInst) \ macro(FPToUIInst) \ macro(FPTruncInst) \ macro(IntToPtrInst) \ macro(PtrToIntInst) \ macro(SExtInst) \ macro(SIToFPInst) \ macro(TruncInst) \ macro(UIToFPInst) \ macro(ZExtInst) \ macro(ExtractValueInst) \ macro(LoadInst) \ macro(VAArgInst) /** * @defgroup LLVMCCoreValueGeneral General APIs * * Functions in this section work on all LLVMValueRef instances, * regardless of their sub-type. They correspond to functions available * on llvm::Value. * * @{ */ /** * Obtain the type of a value. * * @see llvm::Value::getType() */ LLVMTypeRef LLVMTypeOf(LLVMValueRef Val); /** * Obtain the string name of a value. * * @see llvm::Value::getName() */ const char *LLVMGetValueName(LLVMValueRef Val); /** * Set the string name of a value. * * @see llvm::Value::setName() */ void LLVMSetValueName(LLVMValueRef Val, const char *Name); /** * Dump a representation of a value to stderr. * * @see llvm::Value::dump() */ void LLVMDumpValue(LLVMValueRef Val); /** * Return a string representation of the value. Use * LLVMDisposeMessage to free the string. * * @see llvm::Value::print() */ char *LLVMPrintValueToString(LLVMValueRef Val); /** * Replace all uses of a value with another one. * * @see llvm::Value::replaceAllUsesWith() */ void LLVMReplaceAllUsesWith(LLVMValueRef OldVal, LLVMValueRef NewVal); /** * Determine whether the specified constant instance is constant. */ LLVMBool LLVMIsConstant(LLVMValueRef Val); /** * Determine whether a value instance is undefined. */ LLVMBool LLVMIsUndef(LLVMValueRef Val); /** * Convert value instances between types. * * Internally, an LLVMValueRef is "pinned" to a specific type. This * series of functions allows you to cast an instance to a specific * type. * * If the cast is not valid for the specified type, NULL is returned. * * @see llvm::dyn_cast_or_null<> */ #define LLVM_DECLARE_VALUE_CAST(name) \ LLVMValueRef LLVMIsA##name(LLVMValueRef Val); LLVM_FOR_EACH_VALUE_SUBCLASS(LLVM_DECLARE_VALUE_CAST) LLVMValueRef LLVMIsAMDNode(LLVMValueRef Val); LLVMValueRef LLVMIsAMDString(LLVMValueRef Val); /** * @} */ /** * @defgroup LLVMCCoreValueUses Usage * * This module defines functions that allow you to inspect the uses of a * LLVMValueRef. * * It is possible to obtain an LLVMUseRef for any LLVMValueRef instance. * Each LLVMUseRef (which corresponds to a llvm::Use instance) holds a * llvm::User and llvm::Value. * * @{ */ /** * Obtain the first use of a value. * * Uses are obtained in an iterator fashion. First, call this function * to obtain a reference to the first use. Then, call LLVMGetNextUse() * on that instance and all subsequently obtained instances until * LLVMGetNextUse() returns NULL. * * @see llvm::Value::use_begin() */ LLVMUseRef LLVMGetFirstUse(LLVMValueRef Val); /** * Obtain the next use of a value. * * This effectively advances the iterator. It returns NULL if you are on * the final use and no more are available. */ LLVMUseRef LLVMGetNextUse(LLVMUseRef U); /** * Obtain the user value for a user. * * The returned value corresponds to a llvm::User type. * * @see llvm::Use::getUser() */ LLVMValueRef LLVMGetUser(LLVMUseRef U); /** * Obtain the value this use corresponds to. * * @see llvm::Use::get(). */ LLVMValueRef LLVMGetUsedValue(LLVMUseRef U); /** * @} */ /** * @defgroup LLVMCCoreValueUser User value * * Function in this group pertain to LLVMValueRef instances that descent * from llvm::User. This includes constants, instructions, and * operators. * * @{ */ /** * Obtain an operand at a specific index in a llvm::User value. * * @see llvm::User::getOperand() */ LLVMValueRef LLVMGetOperand(LLVMValueRef Val, unsigned Index); /** * Obtain the use of an operand at a specific index in a llvm::User value. * * @see llvm::User::getOperandUse() */ LLVMUseRef LLVMGetOperandUse(LLVMValueRef Val, unsigned Index); /** * Set an operand at a specific index in a llvm::User value. * * @see llvm::User::setOperand() */ void LLVMSetOperand(LLVMValueRef User, unsigned Index, LLVMValueRef Val); /** * Obtain the number of operands in a llvm::User value. * * @see llvm::User::getNumOperands() */ int LLVMGetNumOperands(LLVMValueRef Val); /** * @} */ /** * @defgroup LLVMCCoreValueConstant Constants * * This section contains APIs for interacting with LLVMValueRef that * correspond to llvm::Constant instances. * * These functions will work for any LLVMValueRef in the llvm::Constant * class hierarchy. * * @{ */ /** * Obtain a constant value referring to the null instance of a type. * * @see llvm::Constant::getNullValue() */ LLVMValueRef LLVMConstNull(LLVMTypeRef Ty); /* all zeroes */ /** * Obtain a constant value referring to the instance of a type * consisting of all ones. * * This is only valid for integer types. * * @see llvm::Constant::getAllOnesValue() */ LLVMValueRef LLVMConstAllOnes(LLVMTypeRef Ty); /** * Obtain a constant value referring to an undefined value of a type. * * @see llvm::UndefValue::get() */ LLVMValueRef LLVMGetUndef(LLVMTypeRef Ty); /** * Determine whether a value instance is null. * * @see llvm::Constant::isNullValue() */ LLVMBool LLVMIsNull(LLVMValueRef Val); /** * Obtain a constant that is a constant pointer pointing to NULL for a * specified type. */ LLVMValueRef LLVMConstPointerNull(LLVMTypeRef Ty); /** * @defgroup LLVMCCoreValueConstantScalar Scalar constants * * Functions in this group model LLVMValueRef instances that correspond * to constants referring to scalar types. * * For integer types, the LLVMTypeRef parameter should correspond to a * llvm::IntegerType instance and the returned LLVMValueRef will * correspond to a llvm::ConstantInt. * * For floating point types, the LLVMTypeRef returned corresponds to a * llvm::ConstantFP. * * @{ */ /** * Obtain a constant value for an integer type. * * The returned value corresponds to a llvm::ConstantInt. * * @see llvm::ConstantInt::get() * * @param IntTy Integer type to obtain value of. * @param N The value the returned instance should refer to. * @param SignExtend Whether to sign extend the produced value. */ LLVMValueRef LLVMConstInt(LLVMTypeRef IntTy, unsigned long long N, LLVMBool SignExtend); /** * Obtain a constant value for an integer of arbitrary precision. * * @see llvm::ConstantInt::get() */ LLVMValueRef LLVMConstIntOfArbitraryPrecision(LLVMTypeRef IntTy, unsigned NumWords, const uint64_t Words[]); /** * Obtain a constant value for an integer parsed from a string. * * A similar API, LLVMConstIntOfStringAndSize is also available. If the * string's length is available, it is preferred to call that function * instead. * * @see llvm::ConstantInt::get() */ LLVMValueRef LLVMConstIntOfString(LLVMTypeRef IntTy, const char *Text, uint8_t Radix); /** * Obtain a constant value for an integer parsed from a string with * specified length. * * @see llvm::ConstantInt::get() */ LLVMValueRef LLVMConstIntOfStringAndSize(LLVMTypeRef IntTy, const char *Text, unsigned SLen, uint8_t Radix); /** * Obtain a constant value referring to a double floating point value. */ LLVMValueRef LLVMConstReal(LLVMTypeRef RealTy, double N); /** * Obtain a constant for a floating point value parsed from a string. * * A similar API, LLVMConstRealOfStringAndSize is also available. It * should be used if the input string's length is known. */ LLVMValueRef LLVMConstRealOfString(LLVMTypeRef RealTy, const char *Text); /** * Obtain a constant for a floating point value parsed from a string. */ LLVMValueRef LLVMConstRealOfStringAndSize(LLVMTypeRef RealTy, const char *Text, unsigned SLen); /** * Obtain the zero extended value for an integer constant value. * * @see llvm::ConstantInt::getZExtValue() */ unsigned long long LLVMConstIntGetZExtValue(LLVMValueRef ConstantVal); /** * Obtain the sign extended value for an integer constant value. * * @see llvm::ConstantInt::getSExtValue() */ long long LLVMConstIntGetSExtValue(LLVMValueRef ConstantVal); /** * Obtain the double value for an floating point constant value. * losesInfo indicates if some precision was lost in the conversion. * * @see llvm::ConstantFP::getDoubleValue */ double LLVMConstRealGetDouble(LLVMValueRef ConstantVal, LLVMBool *losesInfo); /** * @} */ /** * @defgroup LLVMCCoreValueConstantComposite Composite Constants * * Functions in this group operate on composite constants. * * @{ */ /** * Create a ConstantDataSequential and initialize it with a string. * * @see llvm::ConstantDataArray::getString() */ LLVMValueRef LLVMConstStringInContext(LLVMContextRef C, const char *Str, unsigned Length, LLVMBool DontNullTerminate); /** * Create a ConstantDataSequential with string content in the global context. * * This is the same as LLVMConstStringInContext except it operates on the * global context. * * @see LLVMConstStringInContext() * @see llvm::ConstantDataArray::getString() */ LLVMValueRef LLVMConstString(const char *Str, unsigned Length, LLVMBool DontNullTerminate); /** * Returns true if the specified constant is an array of i8. * * @see ConstantDataSequential::getAsString() */ LLVMBool LLVMIsConstantString(LLVMValueRef c); /** * Get the given constant data sequential as a string. * * @see ConstantDataSequential::getAsString() */ const char *LLVMGetAsString(LLVMValueRef c, size_t* out); /** * Create an anonymous ConstantStruct with the specified values. * * @see llvm::ConstantStruct::getAnon() */ LLVMValueRef LLVMConstStructInContext(LLVMContextRef C, LLVMValueRef *ConstantVals, unsigned Count, LLVMBool Packed); /** * Create a ConstantStruct in the global Context. * * This is the same as LLVMConstStructInContext except it operates on the * global Context. * * @see LLVMConstStructInContext() */ LLVMValueRef LLVMConstStruct(LLVMValueRef *ConstantVals, unsigned Count, LLVMBool Packed); /** * Create a ConstantArray from values. * * @see llvm::ConstantArray::get() */ LLVMValueRef LLVMConstArray(LLVMTypeRef ElementTy, LLVMValueRef *ConstantVals, unsigned Length); /** * Create a non-anonymous ConstantStruct from values. * * @see llvm::ConstantStruct::get() */ LLVMValueRef LLVMConstNamedStruct(LLVMTypeRef StructTy, LLVMValueRef *ConstantVals, unsigned Count); /** * Get an element at specified index as a constant. * * @see ConstantDataSequential::getElementAsConstant() */ LLVMValueRef LLVMGetElementAsConstant(LLVMValueRef c, unsigned idx); /** * Create a ConstantVector from values. * * @see llvm::ConstantVector::get() */ LLVMValueRef LLVMConstVector(LLVMValueRef *ScalarConstantVals, unsigned Size); /** * @} */ /** * @defgroup LLVMCCoreValueConstantExpressions Constant Expressions * * Functions in this group correspond to APIs on llvm::ConstantExpr. * * @see llvm::ConstantExpr. * * @{ */ LLVMOpcode LLVMGetConstOpcode(LLVMValueRef ConstantVal); LLVMValueRef LLVMAlignOf(LLVMTypeRef Ty); LLVMValueRef LLVMSizeOf(LLVMTypeRef Ty); LLVMValueRef LLVMConstNeg(LLVMValueRef ConstantVal); LLVMValueRef LLVMConstNSWNeg(LLVMValueRef ConstantVal); LLVMValueRef LLVMConstNUWNeg(LLVMValueRef ConstantVal); LLVMValueRef LLVMConstFNeg(LLVMValueRef ConstantVal); LLVMValueRef LLVMConstNot(LLVMValueRef ConstantVal); LLVMValueRef LLVMConstAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstNSWAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstNUWAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstFAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstNSWSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstNUWSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstFSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstNSWMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstNUWMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstFMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstUDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstSDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstExactSDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstFDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstURem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstSRem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstFRem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstAnd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstOr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstXor(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstICmp(LLVMIntPredicate Predicate, LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstFCmp(LLVMRealPredicate Predicate, LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstShl(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstLShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstAShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant); LLVMValueRef LLVMConstGEP(LLVMValueRef ConstantVal, LLVMValueRef *ConstantIndices, unsigned NumIndices); LLVMValueRef LLVMConstInBoundsGEP(LLVMValueRef ConstantVal, LLVMValueRef *ConstantIndices, unsigned NumIndices); LLVMValueRef LLVMConstTrunc(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstSExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstZExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstFPTrunc(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstFPExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstUIToFP(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstSIToFP(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstFPToUI(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstFPToSI(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstPtrToInt(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstIntToPtr(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstBitCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstAddrSpaceCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstZExtOrBitCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstSExtOrBitCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstTruncOrBitCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstPointerCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstIntCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType, LLVMBool isSigned); LLVMValueRef LLVMConstFPCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType); LLVMValueRef LLVMConstSelect(LLVMValueRef ConstantCondition, LLVMValueRef ConstantIfTrue, LLVMValueRef ConstantIfFalse); LLVMValueRef LLVMConstExtractElement(LLVMValueRef VectorConstant, LLVMValueRef IndexConstant); LLVMValueRef LLVMConstInsertElement(LLVMValueRef VectorConstant, LLVMValueRef ElementValueConstant, LLVMValueRef IndexConstant); LLVMValueRef LLVMConstShuffleVector(LLVMValueRef VectorAConstant, LLVMValueRef VectorBConstant, LLVMValueRef MaskConstant); LLVMValueRef LLVMConstExtractValue(LLVMValueRef AggConstant, unsigned *IdxList, unsigned NumIdx); LLVMValueRef LLVMConstInsertValue(LLVMValueRef AggConstant, LLVMValueRef ElementValueConstant, unsigned *IdxList, unsigned NumIdx); LLVMValueRef LLVMConstInlineAsm(LLVMTypeRef Ty, const char *AsmString, const char *Constraints, LLVMBool HasSideEffects, LLVMBool IsAlignStack); LLVMValueRef LLVMBlockAddress(LLVMValueRef F, LLVMBasicBlockRef BB); /** * @} */ /** * @defgroup LLVMCCoreValueConstantGlobals Global Values * * This group contains functions that operate on global values. Functions in * this group relate to functions in the llvm::GlobalValue class tree. * * @see llvm::GlobalValue * * @{ */ LLVMModuleRef LLVMGetGlobalParent(LLVMValueRef Global); LLVMBool LLVMIsDeclaration(LLVMValueRef Global); LLVMLinkage LLVMGetLinkage(LLVMValueRef Global); void LLVMSetLinkage(LLVMValueRef Global, LLVMLinkage Linkage); const char *LLVMGetSection(LLVMValueRef Global); void LLVMSetSection(LLVMValueRef Global, const char *Section); LLVMVisibility LLVMGetVisibility(LLVMValueRef Global); void LLVMSetVisibility(LLVMValueRef Global, LLVMVisibility Viz); LLVMDLLStorageClass LLVMGetDLLStorageClass(LLVMValueRef Global); void LLVMSetDLLStorageClass(LLVMValueRef Global, LLVMDLLStorageClass Class); LLVMBool LLVMHasUnnamedAddr(LLVMValueRef Global); void LLVMSetUnnamedAddr(LLVMValueRef Global, LLVMBool HasUnnamedAddr); /** * @defgroup LLVMCCoreValueWithAlignment Values with alignment * * Functions in this group only apply to values with alignment, i.e. * global variables, load and store instructions. */ /** * Obtain the preferred alignment of the value. * @see llvm::AllocaInst::getAlignment() * @see llvm::LoadInst::getAlignment() * @see llvm::StoreInst::getAlignment() * @see llvm::GlobalValue::getAlignment() */ unsigned LLVMGetAlignment(LLVMValueRef V); /** * Set the preferred alignment of the value. * @see llvm::AllocaInst::setAlignment() * @see llvm::LoadInst::setAlignment() * @see llvm::StoreInst::setAlignment() * @see llvm::GlobalValue::setAlignment() */ void LLVMSetAlignment(LLVMValueRef V, unsigned Bytes); /** * @} */ /** * @defgroup LLVMCoreValueConstantGlobalVariable Global Variables * * This group contains functions that operate on global variable values. * * @see llvm::GlobalVariable * * @{ */ LLVMValueRef LLVMAddGlobal(LLVMModuleRef M, LLVMTypeRef Ty, const char *Name); LLVMValueRef LLVMAddGlobalInAddressSpace(LLVMModuleRef M, LLVMTypeRef Ty, const char *Name, unsigned AddressSpace); LLVMValueRef LLVMGetNamedGlobal(LLVMModuleRef M, const char *Name); LLVMValueRef LLVMGetFirstGlobal(LLVMModuleRef M); LLVMValueRef LLVMGetLastGlobal(LLVMModuleRef M); LLVMValueRef LLVMGetNextGlobal(LLVMValueRef GlobalVar); LLVMValueRef LLVMGetPreviousGlobal(LLVMValueRef GlobalVar); void LLVMDeleteGlobal(LLVMValueRef GlobalVar); LLVMValueRef LLVMGetInitializer(LLVMValueRef GlobalVar); void LLVMSetInitializer(LLVMValueRef GlobalVar, LLVMValueRef ConstantVal); LLVMBool LLVMIsThreadLocal(LLVMValueRef GlobalVar); void LLVMSetThreadLocal(LLVMValueRef GlobalVar, LLVMBool IsThreadLocal); LLVMBool LLVMIsGlobalConstant(LLVMValueRef GlobalVar); void LLVMSetGlobalConstant(LLVMValueRef GlobalVar, LLVMBool IsConstant); LLVMThreadLocalMode LLVMGetThreadLocalMode(LLVMValueRef GlobalVar); void LLVMSetThreadLocalMode(LLVMValueRef GlobalVar, LLVMThreadLocalMode Mode); LLVMBool LLVMIsExternallyInitialized(LLVMValueRef GlobalVar); void LLVMSetExternallyInitialized(LLVMValueRef GlobalVar, LLVMBool IsExtInit); /** * @} */ /** * @defgroup LLVMCoreValueConstantGlobalAlias Global Aliases * * This group contains function that operate on global alias values. * * @see llvm::GlobalAlias * * @{ */ LLVMValueRef LLVMAddAlias(LLVMModuleRef M, LLVMTypeRef Ty, LLVMValueRef Aliasee, const char *Name); /** * @} */ /** * @defgroup LLVMCCoreValueFunction Function values * * Functions in this group operate on LLVMValueRef instances that * correspond to llvm::Function instances. * * @see llvm::Function * * @{ */ /** * Remove a function from its containing module and deletes it. * * @see llvm::Function::eraseFromParent() */ void LLVMDeleteFunction(LLVMValueRef Fn); /** * Obtain the personality function attached to the function. * * @see llvm::Function::getPersonalityFn() */ LLVMValueRef LLVMGetPersonalityFn(LLVMValueRef Fn); /** * Set the personality function attached to the function. * * @see llvm::Function::setPersonalityFn() */ void LLVMSetPersonalityFn(LLVMValueRef Fn, LLVMValueRef PersonalityFn); /** * Obtain the ID number from a function instance. * * @see llvm::Function::getIntrinsicID() */ unsigned LLVMGetIntrinsicID(LLVMValueRef Fn); /** * Obtain the calling function of a function. * * The returned value corresponds to the LLVMCallConv enumeration. * * @see llvm::Function::getCallingConv() */ unsigned LLVMGetFunctionCallConv(LLVMValueRef Fn); /** * Set the calling convention of a function. * * @see llvm::Function::setCallingConv() * * @param Fn Function to operate on * @param CC LLVMCallConv to set calling convention to */ void LLVMSetFunctionCallConv(LLVMValueRef Fn, unsigned CC); /** * Obtain the name of the garbage collector to use during code * generation. * * @see llvm::Function::getGC() */ const char *LLVMGetGC(LLVMValueRef Fn); /** * Define the garbage collector to use during code generation. * * @see llvm::Function::setGC() */ void LLVMSetGC(LLVMValueRef Fn, const char *Name); /** * Add an attribute to a function. * * @see llvm::Function::addAttribute() */ void LLVMAddFunctionAttr(LLVMValueRef Fn, LLVMAttribute PA); /** * Add a target-dependent attribute to a fuction * @see llvm::AttrBuilder::addAttribute() */ void LLVMAddTargetDependentFunctionAttr(LLVMValueRef Fn, const char *A, const char *V); /** * Obtain an attribute from a function. * * @see llvm::Function::getAttributes() */ LLVMAttribute LLVMGetFunctionAttr(LLVMValueRef Fn); /** * Remove an attribute from a function. */ void LLVMRemoveFunctionAttr(LLVMValueRef Fn, LLVMAttribute PA); /** * @defgroup LLVMCCoreValueFunctionParameters Function Parameters * * Functions in this group relate to arguments/parameters on functions. * * Functions in this group expect LLVMValueRef instances that correspond * to llvm::Function instances. * * @{ */ /** * Obtain the number of parameters in a function. * * @see llvm::Function::arg_size() */ unsigned LLVMCountParams(LLVMValueRef Fn); /** * Obtain the parameters in a function. * * The takes a pointer to a pre-allocated array of LLVMValueRef that is * at least LLVMCountParams() long. This array will be filled with * LLVMValueRef instances which correspond to the parameters the * function receives. Each LLVMValueRef corresponds to a llvm::Argument * instance. * * @see llvm::Function::arg_begin() */ void LLVMGetParams(LLVMValueRef Fn, LLVMValueRef *Params); /** * Obtain the parameter at the specified index. * * Parameters are indexed from 0. * * @see llvm::Function::arg_begin() */ LLVMValueRef LLVMGetParam(LLVMValueRef Fn, unsigned Index); /** * Obtain the function to which this argument belongs. * * Unlike other functions in this group, this one takes an LLVMValueRef * that corresponds to a llvm::Attribute. * * The returned LLVMValueRef is the llvm::Function to which this * argument belongs. */ LLVMValueRef LLVMGetParamParent(LLVMValueRef Inst); /** * Obtain the first parameter to a function. * * @see llvm::Function::arg_begin() */ LLVMValueRef LLVMGetFirstParam(LLVMValueRef Fn); /** * Obtain the last parameter to a function. * * @see llvm::Function::arg_end() */ LLVMValueRef LLVMGetLastParam(LLVMValueRef Fn); /** * Obtain the next parameter to a function. * * This takes an LLVMValueRef obtained from LLVMGetFirstParam() (which is * actually a wrapped iterator) and obtains the next parameter from the * underlying iterator. */ LLVMValueRef LLVMGetNextParam(LLVMValueRef Arg); /** * Obtain the previous parameter to a function. * * This is the opposite of LLVMGetNextParam(). */ LLVMValueRef LLVMGetPreviousParam(LLVMValueRef Arg); /** * Add an attribute to a function argument. * * @see llvm::Argument::addAttr() */ void LLVMAddAttribute(LLVMValueRef Arg, LLVMAttribute PA); /** * Remove an attribute from a function argument. * * @see llvm::Argument::removeAttr() */ void LLVMRemoveAttribute(LLVMValueRef Arg, LLVMAttribute PA); /** * Get an attribute from a function argument. */ LLVMAttribute LLVMGetAttribute(LLVMValueRef Arg); /** * Set the alignment for a function parameter. * * @see llvm::Argument::addAttr() * @see llvm::AttrBuilder::addAlignmentAttr() */ void LLVMSetParamAlignment(LLVMValueRef Arg, unsigned align); /** * @} */ /** * @} */ /** * @} */ /** * @} */ /** * @defgroup LLVMCCoreValueMetadata Metadata * * @{ */ /** * Obtain a MDString value from a context. * * The returned instance corresponds to the llvm::MDString class. * * The instance is specified by string data of a specified length. The * string content is copied, so the backing memory can be freed after * this function returns. */ LLVMValueRef LLVMMDStringInContext(LLVMContextRef C, const char *Str, unsigned SLen); /** * Obtain a MDString value from the global context. */ LLVMValueRef LLVMMDString(const char *Str, unsigned SLen); /** * Obtain a MDNode value from a context. * * The returned value corresponds to the llvm::MDNode class. */ LLVMValueRef LLVMMDNodeInContext(LLVMContextRef C, LLVMValueRef *Vals, unsigned Count); /** * Obtain a MDNode value from the global context. */ LLVMValueRef LLVMMDNode(LLVMValueRef *Vals, unsigned Count); /** * Obtain the underlying string from a MDString value. * * @param V Instance to obtain string from. * @param Len Memory address which will hold length of returned string. * @return String data in MDString. */ const char *LLVMGetMDString(LLVMValueRef V, unsigned* Len); /** * Obtain the number of operands from an MDNode value. * * @param V MDNode to get number of operands from. * @return Number of operands of the MDNode. */ unsigned LLVMGetMDNodeNumOperands(LLVMValueRef V); /** * Obtain the given MDNode's operands. * * The passed LLVMValueRef pointer should point to enough memory to hold all of * the operands of the given MDNode (see LLVMGetMDNodeNumOperands) as * LLVMValueRefs. This memory will be populated with the LLVMValueRefs of the * MDNode's operands. * * @param V MDNode to get the operands from. * @param Dest Destination array for operands. */ void LLVMGetMDNodeOperands(LLVMValueRef V, LLVMValueRef *Dest); /** * @} */ /** * @defgroup LLVMCCoreValueBasicBlock Basic Block * * A basic block represents a single entry single exit section of code. * Basic blocks contain a list of instructions which form the body of * the block. * * Basic blocks belong to functions. They have the type of label. * * Basic blocks are themselves values. However, the C API models them as * LLVMBasicBlockRef. * * @see llvm::BasicBlock * * @{ */ /** * Convert a basic block instance to a value type. */ LLVMValueRef LLVMBasicBlockAsValue(LLVMBasicBlockRef BB); /** * Determine whether an LLVMValueRef is itself a basic block. */ LLVMBool LLVMValueIsBasicBlock(LLVMValueRef Val); /** * Convert an LLVMValueRef to an LLVMBasicBlockRef instance. */ LLVMBasicBlockRef LLVMValueAsBasicBlock(LLVMValueRef Val); /** * Obtain the function to which a basic block belongs. * * @see llvm::BasicBlock::getParent() */ LLVMValueRef LLVMGetBasicBlockParent(LLVMBasicBlockRef BB); /** * Obtain the terminator instruction for a basic block. * * If the basic block does not have a terminator (it is not well-formed * if it doesn't), then NULL is returned. * * The returned LLVMValueRef corresponds to a llvm::TerminatorInst. * * @see llvm::BasicBlock::getTerminator() */ LLVMValueRef LLVMGetBasicBlockTerminator(LLVMBasicBlockRef BB); /** * Obtain the number of basic blocks in a function. * * @param Fn Function value to operate on. */ unsigned LLVMCountBasicBlocks(LLVMValueRef Fn); /** * Obtain all of the basic blocks in a function. * * This operates on a function value. The BasicBlocks parameter is a * pointer to a pre-allocated array of LLVMBasicBlockRef of at least * LLVMCountBasicBlocks() in length. This array is populated with * LLVMBasicBlockRef instances. */ void LLVMGetBasicBlocks(LLVMValueRef Fn, LLVMBasicBlockRef *BasicBlocks); /** * Obtain the first basic block in a function. * * The returned basic block can be used as an iterator. You will likely * eventually call into LLVMGetNextBasicBlock() with it. * * @see llvm::Function::begin() */ LLVMBasicBlockRef LLVMGetFirstBasicBlock(LLVMValueRef Fn); /** * Obtain the last basic block in a function. * * @see llvm::Function::end() */ LLVMBasicBlockRef LLVMGetLastBasicBlock(LLVMValueRef Fn); /** * Advance a basic block iterator. */ LLVMBasicBlockRef LLVMGetNextBasicBlock(LLVMBasicBlockRef BB); /** * Go backwards in a basic block iterator. */ LLVMBasicBlockRef LLVMGetPreviousBasicBlock(LLVMBasicBlockRef BB); /** * Obtain the basic block that corresponds to the entry point of a * function. * * @see llvm::Function::getEntryBlock() */ LLVMBasicBlockRef LLVMGetEntryBasicBlock(LLVMValueRef Fn); /** * Append a basic block to the end of a function. * * @see llvm::BasicBlock::Create() */ LLVMBasicBlockRef LLVMAppendBasicBlockInContext(LLVMContextRef C, LLVMValueRef Fn, const char *Name); /** * Append a basic block to the end of a function using the global * context. * * @see llvm::BasicBlock::Create() */ LLVMBasicBlockRef LLVMAppendBasicBlock(LLVMValueRef Fn, const char *Name); /** * Insert a basic block in a function before another basic block. * * The function to add to is determined by the function of the * passed basic block. * * @see llvm::BasicBlock::Create() */ LLVMBasicBlockRef LLVMInsertBasicBlockInContext(LLVMContextRef C, LLVMBasicBlockRef BB, const char *Name); /** * Insert a basic block in a function using the global context. * * @see llvm::BasicBlock::Create() */ LLVMBasicBlockRef LLVMInsertBasicBlock(LLVMBasicBlockRef InsertBeforeBB, const char *Name); /** * Remove a basic block from a function and delete it. * * This deletes the basic block from its containing function and deletes * the basic block itself. * * @see llvm::BasicBlock::eraseFromParent() */ void LLVMDeleteBasicBlock(LLVMBasicBlockRef BB); /** * Remove a basic block from a function. * * This deletes the basic block from its containing function but keep * the basic block alive. * * @see llvm::BasicBlock::removeFromParent() */ void LLVMRemoveBasicBlockFromParent(LLVMBasicBlockRef BB); /** * Move a basic block to before another one. * * @see llvm::BasicBlock::moveBefore() */ void LLVMMoveBasicBlockBefore(LLVMBasicBlockRef BB, LLVMBasicBlockRef MovePos); /** * Move a basic block to after another one. * * @see llvm::BasicBlock::moveAfter() */ void LLVMMoveBasicBlockAfter(LLVMBasicBlockRef BB, LLVMBasicBlockRef MovePos); /** * Obtain the first instruction in a basic block. * * The returned LLVMValueRef corresponds to a llvm::Instruction * instance. */ LLVMValueRef LLVMGetFirstInstruction(LLVMBasicBlockRef BB); /** * Obtain the last instruction in a basic block. * * The returned LLVMValueRef corresponds to an LLVM:Instruction. */ LLVMValueRef LLVMGetLastInstruction(LLVMBasicBlockRef BB); /** * @} */ /** * @defgroup LLVMCCoreValueInstruction Instructions * * Functions in this group relate to the inspection and manipulation of * individual instructions. * * In the C++ API, an instruction is modeled by llvm::Instruction. This * class has a large number of descendents. llvm::Instruction is a * llvm::Value and in the C API, instructions are modeled by * LLVMValueRef. * * This group also contains sub-groups which operate on specific * llvm::Instruction types, e.g. llvm::CallInst. * * @{ */ /** * Determine whether an instruction has any metadata attached. */ int LLVMHasMetadata(LLVMValueRef Val); /** * Return metadata associated with an instruction value. */ LLVMValueRef LLVMGetMetadata(LLVMValueRef Val, unsigned KindID); /** * Set metadata associated with an instruction value. */ void LLVMSetMetadata(LLVMValueRef Val, unsigned KindID, LLVMValueRef Node); /** * Obtain the basic block to which an instruction belongs. * * @see llvm::Instruction::getParent() */ LLVMBasicBlockRef LLVMGetInstructionParent(LLVMValueRef Inst); /** * Obtain the instruction that occurs after the one specified. * * The next instruction will be from the same basic block. * * If this is the last instruction in a basic block, NULL will be * returned. */ LLVMValueRef LLVMGetNextInstruction(LLVMValueRef Inst); /** * Obtain the instruction that occurred before this one. * * If the instruction is the first instruction in a basic block, NULL * will be returned. */ LLVMValueRef LLVMGetPreviousInstruction(LLVMValueRef Inst); /** * Remove and delete an instruction. * * The instruction specified is removed from its containing building * block and then deleted. * * @see llvm::Instruction::eraseFromParent() */ void LLVMInstructionEraseFromParent(LLVMValueRef Inst); /** * Obtain the code opcode for an individual instruction. * * @see llvm::Instruction::getOpCode() */ LLVMOpcode LLVMGetInstructionOpcode(LLVMValueRef Inst); /** * Obtain the predicate of an instruction. * * This is only valid for instructions that correspond to llvm::ICmpInst * or llvm::ConstantExpr whose opcode is llvm::Instruction::ICmp. * * @see llvm::ICmpInst::getPredicate() */ LLVMIntPredicate LLVMGetICmpPredicate(LLVMValueRef Inst); /** * Obtain the float predicate of an instruction. * * This is only valid for instructions that correspond to llvm::FCmpInst * or llvm::ConstantExpr whose opcode is llvm::Instruction::FCmp. * * @see llvm::FCmpInst::getPredicate() */ LLVMRealPredicate LLVMGetFCmpPredicate(LLVMValueRef Inst); /** * Create a copy of 'this' instruction that is identical in all ways * except the following: * * The instruction has no parent * * The instruction has no name * * @see llvm::Instruction::clone() */ LLVMValueRef LLVMInstructionClone(LLVMValueRef Inst); /** * @defgroup LLVMCCoreValueInstructionCall Call Sites and Invocations * * Functions in this group apply to instructions that refer to call * sites and invocations. These correspond to C++ types in the * llvm::CallInst class tree. * * @{ */ /** * Set the calling convention for a call instruction. * * This expects an LLVMValueRef that corresponds to a llvm::CallInst or * llvm::InvokeInst. * * @see llvm::CallInst::setCallingConv() * @see llvm::InvokeInst::setCallingConv() */ void LLVMSetInstructionCallConv(LLVMValueRef Instr, unsigned CC); /** * Obtain the calling convention for a call instruction. * * This is the opposite of LLVMSetInstructionCallConv(). Reads its * usage. * * @see LLVMSetInstructionCallConv() */ unsigned LLVMGetInstructionCallConv(LLVMValueRef Instr); void LLVMAddInstrAttribute(LLVMValueRef Instr, unsigned index, LLVMAttribute); void LLVMRemoveInstrAttribute(LLVMValueRef Instr, unsigned index, LLVMAttribute); void LLVMSetInstrParamAlignment(LLVMValueRef Instr, unsigned index, unsigned align); /** * Obtain whether a call instruction is a tail call. * * This only works on llvm::CallInst instructions. * * @see llvm::CallInst::isTailCall() */ LLVMBool LLVMIsTailCall(LLVMValueRef CallInst); /** * Set whether a call instruction is a tail call. * * This only works on llvm::CallInst instructions. * * @see llvm::CallInst::setTailCall() */ void LLVMSetTailCall(LLVMValueRef CallInst, LLVMBool IsTailCall); /** * @} */ /** * @defgroup LLVMCCoreValueInstructionTerminator Terminators * * Functions in this group only apply to instructions that map to * llvm::TerminatorInst instances. * * @{ */ /** * Return the number of successors that this terminator has. * * @see llvm::TerminatorInst::getNumSuccessors */ unsigned LLVMGetNumSuccessors(LLVMValueRef Term); /** * Return the specified successor. * * @see llvm::TerminatorInst::getSuccessor */ LLVMBasicBlockRef LLVMGetSuccessor(LLVMValueRef Term, unsigned i); /** * Update the specified successor to point at the provided block. * * @see llvm::TerminatorInst::setSuccessor */ void LLVMSetSuccessor(LLVMValueRef Term, unsigned i, LLVMBasicBlockRef block); /** * Return if a branch is conditional. * * This only works on llvm::BranchInst instructions. * * @see llvm::BranchInst::isConditional */ LLVMBool LLVMIsConditional(LLVMValueRef Branch); /** * Return the condition of a branch instruction. * * This only works on llvm::BranchInst instructions. * * @see llvm::BranchInst::getCondition */ LLVMValueRef LLVMGetCondition(LLVMValueRef Branch); /** * Set the condition of a branch instruction. * * This only works on llvm::BranchInst instructions. * * @see llvm::BranchInst::setCondition */ void LLVMSetCondition(LLVMValueRef Branch, LLVMValueRef Cond); /** * Obtain the default destination basic block of a switch instruction. * * This only works on llvm::SwitchInst instructions. * * @see llvm::SwitchInst::getDefaultDest() */ LLVMBasicBlockRef LLVMGetSwitchDefaultDest(LLVMValueRef SwitchInstr); /** * @} */ /** * @defgroup LLVMCCoreValueInstructionPHINode PHI Nodes * * Functions in this group only apply to instructions that map to * llvm::PHINode instances. * * @{ */ /** * Add an incoming value to the end of a PHI list. */ void LLVMAddIncoming(LLVMValueRef PhiNode, LLVMValueRef *IncomingValues, LLVMBasicBlockRef *IncomingBlocks, unsigned Count); /** * Obtain the number of incoming basic blocks to a PHI node. */ unsigned LLVMCountIncoming(LLVMValueRef PhiNode); /** * Obtain an incoming value to a PHI node as an LLVMValueRef. */ LLVMValueRef LLVMGetIncomingValue(LLVMValueRef PhiNode, unsigned Index); /** * Obtain an incoming value to a PHI node as an LLVMBasicBlockRef. */ LLVMBasicBlockRef LLVMGetIncomingBlock(LLVMValueRef PhiNode, unsigned Index); /** * @} */ /** * @} */ /** * @} */ /** * @defgroup LLVMCCoreInstructionBuilder Instruction Builders * * An instruction builder represents a point within a basic block and is * the exclusive means of building instructions using the C interface. * * @{ */ LLVMBuilderRef LLVMCreateBuilderInContext(LLVMContextRef C); LLVMBuilderRef LLVMCreateBuilder(void); void LLVMPositionBuilder(LLVMBuilderRef Builder, LLVMBasicBlockRef Block, LLVMValueRef Instr); void LLVMPositionBuilderBefore(LLVMBuilderRef Builder, LLVMValueRef Instr); void LLVMPositionBuilderAtEnd(LLVMBuilderRef Builder, LLVMBasicBlockRef Block); LLVMBasicBlockRef LLVMGetInsertBlock(LLVMBuilderRef Builder); void LLVMClearInsertionPosition(LLVMBuilderRef Builder); void LLVMInsertIntoBuilder(LLVMBuilderRef Builder, LLVMValueRef Instr); void LLVMInsertIntoBuilderWithName(LLVMBuilderRef Builder, LLVMValueRef Instr, const char *Name); void LLVMDisposeBuilder(LLVMBuilderRef Builder); /* Metadata */ void LLVMSetCurrentDebugLocation(LLVMBuilderRef Builder, LLVMValueRef L); LLVMValueRef LLVMGetCurrentDebugLocation(LLVMBuilderRef Builder); void LLVMSetInstDebugLocation(LLVMBuilderRef Builder, LLVMValueRef Inst); /* Terminators */ LLVMValueRef LLVMBuildRetVoid(LLVMBuilderRef); LLVMValueRef LLVMBuildRet(LLVMBuilderRef, LLVMValueRef V); LLVMValueRef LLVMBuildAggregateRet(LLVMBuilderRef, LLVMValueRef *RetVals, unsigned N); LLVMValueRef LLVMBuildBr(LLVMBuilderRef, LLVMBasicBlockRef Dest); LLVMValueRef LLVMBuildCondBr(LLVMBuilderRef, LLVMValueRef If, LLVMBasicBlockRef Then, LLVMBasicBlockRef Else); LLVMValueRef LLVMBuildSwitch(LLVMBuilderRef, LLVMValueRef V, LLVMBasicBlockRef Else, unsigned NumCases); LLVMValueRef LLVMBuildIndirectBr(LLVMBuilderRef B, LLVMValueRef Addr, unsigned NumDests); LLVMValueRef LLVMBuildInvoke(LLVMBuilderRef, LLVMValueRef Fn, LLVMValueRef *Args, unsigned NumArgs, LLVMBasicBlockRef Then, LLVMBasicBlockRef Catch, const char *Name); LLVMValueRef LLVMBuildLandingPad(LLVMBuilderRef B, LLVMTypeRef Ty, unsigned NumClauses, const char *Name); LLVMValueRef LLVMBuildResume(LLVMBuilderRef B, LLVMValueRef Exn); LLVMValueRef LLVMBuildUnreachable(LLVMBuilderRef); /* Add a case to the switch instruction */ void LLVMAddCase(LLVMValueRef Switch, LLVMValueRef OnVal, LLVMBasicBlockRef Dest); /* Add a destination to the indirectbr instruction */ void LLVMAddDestination(LLVMValueRef IndirectBr, LLVMBasicBlockRef Dest); /* Add a catch or filter clause to the landingpad instruction */ void LLVMAddClause(LLVMValueRef LandingPad, LLVMValueRef ClauseVal); /* Set the 'cleanup' flag in the landingpad instruction */ void LLVMSetCleanup(LLVMValueRef LandingPad, LLVMBool Val); /* Arithmetic */ LLVMValueRef LLVMBuildAdd(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildNSWAdd(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildNUWAdd(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildFAdd(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildSub(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildNSWSub(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildNUWSub(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildFSub(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildMul(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildNSWMul(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildNUWMul(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildFMul(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildUDiv(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildSDiv(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildExactSDiv(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildFDiv(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildURem(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildSRem(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildFRem(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildShl(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildLShr(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildAShr(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildAnd(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildOr(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildXor(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildBinOp(LLVMBuilderRef B, LLVMOpcode Op, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildNeg(LLVMBuilderRef, LLVMValueRef V, const char *Name); LLVMValueRef LLVMBuildNSWNeg(LLVMBuilderRef B, LLVMValueRef V, const char *Name); LLVMValueRef LLVMBuildNUWNeg(LLVMBuilderRef B, LLVMValueRef V, const char *Name); LLVMValueRef LLVMBuildFNeg(LLVMBuilderRef, LLVMValueRef V, const char *Name); LLVMValueRef LLVMBuildNot(LLVMBuilderRef, LLVMValueRef V, const char *Name); /* Memory */ LLVMValueRef LLVMBuildMalloc(LLVMBuilderRef, LLVMTypeRef Ty, const char *Name); LLVMValueRef LLVMBuildArrayMalloc(LLVMBuilderRef, LLVMTypeRef Ty, LLVMValueRef Val, const char *Name); LLVMValueRef LLVMBuildAlloca(LLVMBuilderRef, LLVMTypeRef Ty, const char *Name); LLVMValueRef LLVMBuildArrayAlloca(LLVMBuilderRef, LLVMTypeRef Ty, LLVMValueRef Val, const char *Name); LLVMValueRef LLVMBuildFree(LLVMBuilderRef, LLVMValueRef PointerVal); LLVMValueRef LLVMBuildLoad(LLVMBuilderRef, LLVMValueRef PointerVal, const char *Name); LLVMValueRef LLVMBuildStore(LLVMBuilderRef, LLVMValueRef Val, LLVMValueRef Ptr); LLVMValueRef LLVMBuildGEP(LLVMBuilderRef B, LLVMValueRef Pointer, LLVMValueRef *Indices, unsigned NumIndices, const char *Name); LLVMValueRef LLVMBuildInBoundsGEP(LLVMBuilderRef B, LLVMValueRef Pointer, LLVMValueRef *Indices, unsigned NumIndices, const char *Name); LLVMValueRef LLVMBuildStructGEP(LLVMBuilderRef B, LLVMValueRef Pointer, unsigned Idx, const char *Name); LLVMValueRef LLVMBuildGlobalString(LLVMBuilderRef B, const char *Str, const char *Name); LLVMValueRef LLVMBuildGlobalStringPtr(LLVMBuilderRef B, const char *Str, const char *Name); LLVMBool LLVMGetVolatile(LLVMValueRef MemoryAccessInst); void LLVMSetVolatile(LLVMValueRef MemoryAccessInst, LLVMBool IsVolatile); /* Casts */ LLVMValueRef LLVMBuildTrunc(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildZExt(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildSExt(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildFPToUI(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildFPToSI(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildUIToFP(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildSIToFP(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildFPTrunc(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildFPExt(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildPtrToInt(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildIntToPtr(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildBitCast(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildAddrSpaceCast(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildZExtOrBitCast(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildSExtOrBitCast(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildTruncOrBitCast(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildCast(LLVMBuilderRef B, LLVMOpcode Op, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildPointerCast(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildIntCast(LLVMBuilderRef, LLVMValueRef Val, /*Signed cast!*/ LLVMTypeRef DestTy, const char *Name); LLVMValueRef LLVMBuildFPCast(LLVMBuilderRef, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name); /* Comparisons */ LLVMValueRef LLVMBuildICmp(LLVMBuilderRef, LLVMIntPredicate Op, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildFCmp(LLVMBuilderRef, LLVMRealPredicate Op, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); /* Miscellaneous instructions */ LLVMValueRef LLVMBuildPhi(LLVMBuilderRef, LLVMTypeRef Ty, const char *Name); LLVMValueRef LLVMBuildCall(LLVMBuilderRef, LLVMValueRef Fn, LLVMValueRef *Args, unsigned NumArgs, const char *Name); LLVMValueRef LLVMBuildSelect(LLVMBuilderRef, LLVMValueRef If, LLVMValueRef Then, LLVMValueRef Else, const char *Name); LLVMValueRef LLVMBuildVAArg(LLVMBuilderRef, LLVMValueRef List, LLVMTypeRef Ty, const char *Name); LLVMValueRef LLVMBuildExtractElement(LLVMBuilderRef, LLVMValueRef VecVal, LLVMValueRef Index, const char *Name); LLVMValueRef LLVMBuildInsertElement(LLVMBuilderRef, LLVMValueRef VecVal, LLVMValueRef EltVal, LLVMValueRef Index, const char *Name); LLVMValueRef LLVMBuildShuffleVector(LLVMBuilderRef, LLVMValueRef V1, LLVMValueRef V2, LLVMValueRef Mask, const char *Name); LLVMValueRef LLVMBuildExtractValue(LLVMBuilderRef, LLVMValueRef AggVal, unsigned Index, const char *Name); LLVMValueRef LLVMBuildInsertValue(LLVMBuilderRef, LLVMValueRef AggVal, LLVMValueRef EltVal, unsigned Index, const char *Name); LLVMValueRef LLVMBuildIsNull(LLVMBuilderRef, LLVMValueRef Val, const char *Name); LLVMValueRef LLVMBuildIsNotNull(LLVMBuilderRef, LLVMValueRef Val, const char *Name); LLVMValueRef LLVMBuildPtrDiff(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); LLVMValueRef LLVMBuildFence(LLVMBuilderRef B, LLVMAtomicOrdering ordering, LLVMBool singleThread, const char *Name); LLVMValueRef LLVMBuildAtomicRMW(LLVMBuilderRef B, LLVMAtomicRMWBinOp op, LLVMValueRef PTR, LLVMValueRef Val, LLVMAtomicOrdering ordering, LLVMBool singleThread); /** * @} */ /** * @defgroup LLVMCCoreModuleProvider Module Providers * * @{ */ /** * Changes the type of M so it can be passed to FunctionPassManagers and the * JIT. They take ModuleProviders for historical reasons. */ LLVMModuleProviderRef LLVMCreateModuleProviderForExistingModule(LLVMModuleRef M); /** * Destroys the module M. */ void LLVMDisposeModuleProvider(LLVMModuleProviderRef M); /** * @} */ /** * @defgroup LLVMCCoreMemoryBuffers Memory Buffers * * @{ */ LLVMBool LLVMCreateMemoryBufferWithContentsOfFile(const char *Path, LLVMMemoryBufferRef *OutMemBuf, char **OutMessage); LLVMBool LLVMCreateMemoryBufferWithSTDIN(LLVMMemoryBufferRef *OutMemBuf, char **OutMessage); LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRange(const char *InputData, size_t InputDataLength, const char *BufferName, LLVMBool RequiresNullTerminator); LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRangeCopy(const char *InputData, size_t InputDataLength, const char *BufferName); const char *LLVMGetBufferStart(LLVMMemoryBufferRef MemBuf); size_t LLVMGetBufferSize(LLVMMemoryBufferRef MemBuf); void LLVMDisposeMemoryBuffer(LLVMMemoryBufferRef MemBuf); /** * @} */ /** * @defgroup LLVMCCorePassRegistry Pass Registry * * @{ */ /** Return the global pass registry, for use with initialization functions. @see llvm::PassRegistry::getPassRegistry */ LLVMPassRegistryRef LLVMGetGlobalPassRegistry(void); /** * @} */ /** * @defgroup LLVMCCorePassManagers Pass Managers * * @{ */ /** Constructs a new whole-module pass pipeline. This type of pipeline is suitable for link-time optimization and whole-module transformations. @see llvm::PassManager::PassManager */ LLVMPassManagerRef LLVMCreatePassManager(void); /** Constructs a new function-by-function pass pipeline over the module provider. It does not take ownership of the module provider. This type of pipeline is suitable for code generation and JIT compilation tasks. @see llvm::FunctionPassManager::FunctionPassManager */ LLVMPassManagerRef LLVMCreateFunctionPassManagerForModule(LLVMModuleRef M); /** Deprecated: Use LLVMCreateFunctionPassManagerForModule instead. */ LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef MP); /** Initializes, executes on the provided module, and finalizes all of the passes scheduled in the pass manager. Returns 1 if any of the passes modified the module, 0 otherwise. @see llvm::PassManager::run(Module&) */ LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M); /** Initializes all of the function passes scheduled in the function pass manager. Returns 1 if any of the passes modified the module, 0 otherwise. @see llvm::FunctionPassManager::doInitialization */ LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM); /** Executes all of the function passes scheduled in the function pass manager on the provided function. Returns 1 if any of the passes modified the function, false otherwise. @see llvm::FunctionPassManager::run(Function&) */ LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F); /** Finalizes all of the function passes scheduled in in the function pass manager. Returns 1 if any of the passes modified the module, 0 otherwise. @see llvm::FunctionPassManager::doFinalization */ LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM); /** Frees the memory of a pass pipeline. For function pipelines, does not free the module provider. @see llvm::PassManagerBase::~PassManagerBase. */ void LLVMDisposePassManager(LLVMPassManagerRef PM); /** * @} */ /** * @defgroup LLVMCCoreThreading Threading * * Handle the structures needed to make LLVM safe for multithreading. * * @{ */ /** Deprecated: Multi-threading can only be enabled/disabled with the compile time define LLVM_ENABLE_THREADS. This function always returns LLVMIsMultithreaded(). */ LLVMBool LLVMStartMultithreaded(void); /** Deprecated: Multi-threading can only be enabled/disabled with the compile time define LLVM_ENABLE_THREADS. */ void LLVMStopMultithreaded(void); /** Check whether LLVM is executing in thread-safe mode or not. @see llvm::llvm_is_multithreaded */ LLVMBool LLVMIsMultithreaded(void); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* !defined(__cplusplus) */ #endif /* !defined(LLVM_C_CORE_H) */
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/llvm-c/ExecutionEngine.h
/*===-- llvm-c/ExecutionEngine.h - ExecutionEngine Lib C Iface --*- C++ -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header declares the C interface to libLLVMExecutionEngine.o, which *| |* implements various analyses of the LLVM IR. *| |* *| |* Many exotic languages can interoperate with C code but have a harder time *| |* with C++ due to name mangling. So in addition to C, this interface enables *| |* tools written in such languages. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_EXECUTIONENGINE_H #define LLVM_C_EXECUTIONENGINE_H #include "llvm-c/Core.h" #include "llvm-c/Target.h" #include "llvm-c/TargetMachine.h" #ifdef __cplusplus extern "C" { #endif /** * @defgroup LLVMCExecutionEngine Execution Engine * @ingroup LLVMC * * @{ */ void LLVMLinkInMCJIT(void); void LLVMLinkInInterpreter(void); typedef struct LLVMOpaqueGenericValue *LLVMGenericValueRef; typedef struct LLVMOpaqueExecutionEngine *LLVMExecutionEngineRef; typedef struct LLVMOpaqueMCJITMemoryManager *LLVMMCJITMemoryManagerRef; struct LLVMMCJITCompilerOptions { unsigned OptLevel; LLVMCodeModel CodeModel; LLVMBool NoFramePointerElim; LLVMBool EnableFastISel; LLVMMCJITMemoryManagerRef MCJMM; }; /*===-- Operations on generic values --------------------------------------===*/ LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty, unsigned long long N, LLVMBool IsSigned); LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P); LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef Ty, double N); unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef); unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenVal, LLVMBool IsSigned); void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal); double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal); void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal); /*===-- Operations on execution engines -----------------------------------===*/ LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE, LLVMModuleRef M, char **OutError); LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp, LLVMModuleRef M, char **OutError); LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M, unsigned OptLevel, char **OutError); void LLVMInitializeMCJITCompilerOptions( struct LLVMMCJITCompilerOptions *Options, size_t SizeOfOptions); /** * Create an MCJIT execution engine for a module, with the given options. It is * the responsibility of the caller to ensure that all fields in Options up to * the given SizeOfOptions are initialized. It is correct to pass a smaller * value of SizeOfOptions that omits some fields. The canonical way of using * this is: * * LLVMMCJITCompilerOptions options; * LLVMInitializeMCJITCompilerOptions(&options, sizeof(options)); * ... fill in those options you care about * LLVMCreateMCJITCompilerForModule(&jit, mod, &options, sizeof(options), * &error); * * Note that this is also correct, though possibly suboptimal: * * LLVMCreateMCJITCompilerForModule(&jit, mod, 0, 0, &error); */ LLVMBool LLVMCreateMCJITCompilerForModule( LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M, struct LLVMMCJITCompilerOptions *Options, size_t SizeOfOptions, char **OutError); /** Deprecated: Use LLVMCreateExecutionEngineForModule instead. */ LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE, LLVMModuleProviderRef MP, char **OutError); /** Deprecated: Use LLVMCreateInterpreterForModule instead. */ LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp, LLVMModuleProviderRef MP, char **OutError); /** Deprecated: Use LLVMCreateJITCompilerForModule instead. */ LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT, LLVMModuleProviderRef MP, unsigned OptLevel, char **OutError); void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE); void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE); void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE); int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F, unsigned ArgC, const char * const *ArgV, const char * const *EnvP); LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F, unsigned NumArgs, LLVMGenericValueRef *Args); void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F); void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M); /** Deprecated: Use LLVMAddModule instead. */ void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP); LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M, LLVMModuleRef *OutMod, char **OutError); /** Deprecated: Use LLVMRemoveModule instead. */ LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP, LLVMModuleRef *OutMod, char **OutError); LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name, LLVMValueRef *OutFn); void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE, LLVMValueRef Fn); LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE); LLVMTargetMachineRef LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE); void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global, void* Addr); void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global); uint64_t LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE, const char *Name); uint64_t LLVMGetFunctionAddress(LLVMExecutionEngineRef EE, const char *Name); /*===-- Operations on memory managers -------------------------------------===*/ typedef uint8_t *(*LLVMMemoryManagerAllocateCodeSectionCallback)( void *Opaque, uintptr_t Size, unsigned Alignment, unsigned SectionID, const char *SectionName); typedef uint8_t *(*LLVMMemoryManagerAllocateDataSectionCallback)( void *Opaque, uintptr_t Size, unsigned Alignment, unsigned SectionID, const char *SectionName, LLVMBool IsReadOnly); typedef LLVMBool (*LLVMMemoryManagerFinalizeMemoryCallback)( void *Opaque, char **ErrMsg); typedef void (*LLVMMemoryManagerDestroyCallback)(void *Opaque); /** * Create a simple custom MCJIT memory manager. This memory manager can * intercept allocations in a module-oblivious way. This will return NULL * if any of the passed functions are NULL. * * @param Opaque An opaque client object to pass back to the callbacks. * @param AllocateCodeSection Allocate a block of memory for executable code. * @param AllocateDataSection Allocate a block of memory for data. * @param FinalizeMemory Set page permissions and flush cache. Return 0 on * success, 1 on error. */ LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager( void *Opaque, LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection, LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection, LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory, LLVMMemoryManagerDestroyCallback Destroy); void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM); /** * @} */ #ifdef __cplusplus } #endif /* defined(__cplusplus) */ #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/llvm-c/Initialization.h
/*===-- llvm-c/Initialization.h - Initialization C Interface ------*- C -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header declares the C interface to LLVM initialization routines, *| |* which must be called before you can use the functionality provided by *| |* the corresponding LLVM library. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_INITIALIZATION_H #define LLVM_C_INITIALIZATION_H #include "llvm-c/Core.h" #ifdef __cplusplus extern "C" { #endif /** * @defgroup LLVMCInitialization Initialization Routines * @ingroup LLVMC * * This module contains routines used to initialize the LLVM system. * * @{ */ void LLVMInitializeCore(LLVMPassRegistryRef R); void LLVMInitializeTransformUtils(LLVMPassRegistryRef R); void LLVMInitializeScalarOpts(LLVMPassRegistryRef R); void LLVMInitializeObjCARCOpts(LLVMPassRegistryRef R); void LLVMInitializeVectorization(LLVMPassRegistryRef R); void LLVMInitializeInstCombine(LLVMPassRegistryRef R); void LLVMInitializeIPO(LLVMPassRegistryRef R); void LLVMInitializeInstrumentation(LLVMPassRegistryRef R); void LLVMInitializeAnalysis(LLVMPassRegistryRef R); void LLVMInitializeIPA(LLVMPassRegistryRef R); void LLVMInitializeCodeGen(LLVMPassRegistryRef R); void LLVMInitializeTarget(LLVMPassRegistryRef R); /** * @} */ #ifdef __cplusplus } #endif #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/llvm-c/Analysis.h
/*===-- llvm-c/Analysis.h - Analysis Library C Interface --------*- C++ -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header declares the C interface to libLLVMAnalysis.a, which *| |* implements various analyses of the LLVM IR. *| |* *| |* Many exotic languages can interoperate with C code but have a harder time *| |* with C++ due to name mangling. So in addition to C, this interface enables *| |* tools written in such languages. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_ANALYSIS_H #define LLVM_C_ANALYSIS_H #include "llvm-c/Core.h" #ifdef __cplusplus extern "C" { #endif /** * @defgroup LLVMCAnalysis Analysis * @ingroup LLVMC * * @{ */ typedef enum { LLVMAbortProcessAction, /* verifier will print to stderr and abort() */ LLVMPrintMessageAction, /* verifier will print to stderr and return 1 */ LLVMReturnStatusAction /* verifier will just return 1 */ } LLVMVerifierFailureAction; /* Verifies that a module is valid, taking the specified action if not. Optionally returns a human-readable description of any invalid constructs. OutMessage must be disposed with LLVMDisposeMessage. */ LLVMBool LLVMVerifyModule(LLVMModuleRef M, LLVMVerifierFailureAction Action, char **OutMessage); /* Verifies that a single function is valid, taking the specified action. Useful for debugging. */ LLVMBool LLVMVerifyFunction(LLVMValueRef Fn, LLVMVerifierFailureAction Action); /* Open up a ghostview window that displays the CFG of the current function. Useful for debugging. */ void LLVMViewFunctionCFG(LLVMValueRef Fn); void LLVMViewFunctionCFGOnly(LLVMValueRef Fn); /** * @} */ #ifdef __cplusplus } #endif #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/llvm-c/IRReader.h
/*===-- llvm-c/IRReader.h - IR Reader C Interface -----------------*- C -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This file defines the C interface to the IR Reader. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_IRREADER_H #define LLVM_C_IRREADER_H #include "llvm-c/Core.h" #ifdef __cplusplus extern "C" { #endif /** * Read LLVM IR from a memory buffer and convert it into an in-memory Module * object. Returns 0 on success. * Optionally returns a human-readable description of any errors that * occurred during parsing IR. OutMessage must be disposed with * LLVMDisposeMessage. * * @see llvm::ParseIR() */ LLVMBool LLVMParseIRInContext(LLVMContextRef ContextRef, LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM, char **OutMessage); #ifdef __cplusplus } #endif #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/llvm-c/Object.h
/*===-- llvm-c/Object.h - Object Lib C Iface --------------------*- C++ -*-===*/ /* */ /* The LLVM Compiler Infrastructure */ /* */ /* This file is distributed under the University of Illinois Open Source */ /* License. See LICENSE.TXT for details. */ /* */ /*===----------------------------------------------------------------------===*/ /* */ /* This header declares the C interface to libLLVMObject.a, which */ /* implements object file reading and writing. */ /* */ /* Many exotic languages can interoperate with C code but have a harder time */ /* with C++ due to name mangling. So in addition to C, this interface enables */ /* tools written in such languages. */ /* */ /*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_OBJECT_H #define LLVM_C_OBJECT_H #include "llvm-c/Core.h" #include "llvm/Config/llvm-config.h" #ifdef __cplusplus extern "C" { #endif /** * @defgroup LLVMCObject Object file reading and writing * @ingroup LLVMC * * @{ */ // Opaque type wrappers typedef struct LLVMOpaqueObjectFile *LLVMObjectFileRef; typedef struct LLVMOpaqueSectionIterator *LLVMSectionIteratorRef; typedef struct LLVMOpaqueSymbolIterator *LLVMSymbolIteratorRef; typedef struct LLVMOpaqueRelocationIterator *LLVMRelocationIteratorRef; // ObjectFile creation LLVMObjectFileRef LLVMCreateObjectFile(LLVMMemoryBufferRef MemBuf); void LLVMDisposeObjectFile(LLVMObjectFileRef ObjectFile); // ObjectFile Section iterators LLVMSectionIteratorRef LLVMGetSections(LLVMObjectFileRef ObjectFile); void LLVMDisposeSectionIterator(LLVMSectionIteratorRef SI); LLVMBool LLVMIsSectionIteratorAtEnd(LLVMObjectFileRef ObjectFile, LLVMSectionIteratorRef SI); void LLVMMoveToNextSection(LLVMSectionIteratorRef SI); void LLVMMoveToContainingSection(LLVMSectionIteratorRef Sect, LLVMSymbolIteratorRef Sym); // ObjectFile Symbol iterators LLVMSymbolIteratorRef LLVMGetSymbols(LLVMObjectFileRef ObjectFile); void LLVMDisposeSymbolIterator(LLVMSymbolIteratorRef SI); LLVMBool LLVMIsSymbolIteratorAtEnd(LLVMObjectFileRef ObjectFile, LLVMSymbolIteratorRef SI); void LLVMMoveToNextSymbol(LLVMSymbolIteratorRef SI); // SectionRef accessors const char *LLVMGetSectionName(LLVMSectionIteratorRef SI); uint64_t LLVMGetSectionSize(LLVMSectionIteratorRef SI); const char *LLVMGetSectionContents(LLVMSectionIteratorRef SI); uint64_t LLVMGetSectionAddress(LLVMSectionIteratorRef SI); LLVMBool LLVMGetSectionContainsSymbol(LLVMSectionIteratorRef SI, LLVMSymbolIteratorRef Sym); // Section Relocation iterators LLVMRelocationIteratorRef LLVMGetRelocations(LLVMSectionIteratorRef Section); void LLVMDisposeRelocationIterator(LLVMRelocationIteratorRef RI); LLVMBool LLVMIsRelocationIteratorAtEnd(LLVMSectionIteratorRef Section, LLVMRelocationIteratorRef RI); void LLVMMoveToNextRelocation(LLVMRelocationIteratorRef RI); // SymbolRef accessors const char *LLVMGetSymbolName(LLVMSymbolIteratorRef SI); uint64_t LLVMGetSymbolAddress(LLVMSymbolIteratorRef SI); uint64_t LLVMGetSymbolSize(LLVMSymbolIteratorRef SI); // RelocationRef accessors uint64_t LLVMGetRelocationOffset(LLVMRelocationIteratorRef RI); LLVMSymbolIteratorRef LLVMGetRelocationSymbol(LLVMRelocationIteratorRef RI); uint64_t LLVMGetRelocationType(LLVMRelocationIteratorRef RI); // NOTE: Caller takes ownership of returned string of the two // following functions. const char *LLVMGetRelocationTypeName(LLVMRelocationIteratorRef RI); const char *LLVMGetRelocationValueString(LLVMRelocationIteratorRef RI); /** * @} */ #ifdef __cplusplus } #endif /* defined(__cplusplus) */ #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/llvm-c/lto.h
/*===-- llvm-c/lto.h - LTO Public C Interface ---------------------*- C -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header provides public interface to an abstract link time optimization*| |* library. LLVM provides an implementation of this interface for use with *| |* llvm bitcode files. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_LTO_H #define LLVM_C_LTO_H #include <stddef.h> #include <sys/types.h> #ifndef __cplusplus #if !defined(_MSC_VER) #include <stdbool.h> typedef bool lto_bool_t; #else /* MSVC in particular does not have anything like _Bool or bool in C, but we can at least make sure the type is the same size. The implementation side will use C++ bool. */ typedef unsigned char lto_bool_t; #endif #else typedef bool lto_bool_t; #endif /** * @defgroup LLVMCLTO LTO * @ingroup LLVMC * * @{ */ #define LTO_API_VERSION 17 /** * \since prior to LTO_API_VERSION=3 */ typedef enum { LTO_SYMBOL_ALIGNMENT_MASK = 0x0000001F, /* log2 of alignment */ LTO_SYMBOL_PERMISSIONS_MASK = 0x000000E0, LTO_SYMBOL_PERMISSIONS_CODE = 0x000000A0, LTO_SYMBOL_PERMISSIONS_DATA = 0x000000C0, LTO_SYMBOL_PERMISSIONS_RODATA = 0x00000080, LTO_SYMBOL_DEFINITION_MASK = 0x00000700, LTO_SYMBOL_DEFINITION_REGULAR = 0x00000100, LTO_SYMBOL_DEFINITION_TENTATIVE = 0x00000200, LTO_SYMBOL_DEFINITION_WEAK = 0x00000300, LTO_SYMBOL_DEFINITION_UNDEFINED = 0x00000400, LTO_SYMBOL_DEFINITION_WEAKUNDEF = 0x00000500, LTO_SYMBOL_SCOPE_MASK = 0x00003800, LTO_SYMBOL_SCOPE_INTERNAL = 0x00000800, LTO_SYMBOL_SCOPE_HIDDEN = 0x00001000, LTO_SYMBOL_SCOPE_PROTECTED = 0x00002000, LTO_SYMBOL_SCOPE_DEFAULT = 0x00001800, LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN = 0x00002800, LTO_SYMBOL_COMDAT = 0x00004000, LTO_SYMBOL_ALIAS = 0x00008000 } lto_symbol_attributes; /** * \since prior to LTO_API_VERSION=3 */ typedef enum { LTO_DEBUG_MODEL_NONE = 0, LTO_DEBUG_MODEL_DWARF = 1 } lto_debug_model; /** * \since prior to LTO_API_VERSION=3 */ typedef enum { LTO_CODEGEN_PIC_MODEL_STATIC = 0, LTO_CODEGEN_PIC_MODEL_DYNAMIC = 1, LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC = 2, LTO_CODEGEN_PIC_MODEL_DEFAULT = 3 } lto_codegen_model; /** opaque reference to a loaded object module */ typedef struct LLVMOpaqueLTOModule *lto_module_t; /** opaque reference to a code generator */ typedef struct LLVMOpaqueLTOCodeGenerator *lto_code_gen_t; #ifdef __cplusplus extern "C" { #endif /** * Returns a printable string. * * \since prior to LTO_API_VERSION=3 */ extern const char* lto_get_version(void); /** * Returns the last error string or NULL if last operation was successful. * * \since prior to LTO_API_VERSION=3 */ extern const char* lto_get_error_message(void); /** * Checks if a file is a loadable object file. * * \since prior to LTO_API_VERSION=3 */ extern lto_bool_t lto_module_is_object_file(const char* path); /** * Checks if a file is a loadable object compiled for requested target. * * \since prior to LTO_API_VERSION=3 */ extern lto_bool_t lto_module_is_object_file_for_target(const char* path, const char* target_triple_prefix); /** * Checks if a buffer is a loadable object file. * * \since prior to LTO_API_VERSION=3 */ extern lto_bool_t lto_module_is_object_file_in_memory(const void* mem, size_t length); /** * Checks if a buffer is a loadable object compiled for requested target. * * \since prior to LTO_API_VERSION=3 */ extern lto_bool_t lto_module_is_object_file_in_memory_for_target(const void* mem, size_t length, const char* target_triple_prefix); /** * Loads an object file from disk. * Returns NULL on error (check lto_get_error_message() for details). * * \since prior to LTO_API_VERSION=3 */ extern lto_module_t lto_module_create(const char* path); /** * Loads an object file from memory. * Returns NULL on error (check lto_get_error_message() for details). * * \since prior to LTO_API_VERSION=3 */ extern lto_module_t lto_module_create_from_memory(const void* mem, size_t length); /** * Loads an object file from memory with an extra path argument. * Returns NULL on error (check lto_get_error_message() for details). * * \since LTO_API_VERSION=9 */ extern lto_module_t lto_module_create_from_memory_with_path(const void* mem, size_t length, const char *path); /** * \brief Loads an object file in its own context. * * Loads an object file in its own LLVMContext. This function call is * thread-safe. However, modules created this way should not be merged into an * lto_code_gen_t using \a lto_codegen_add_module(). * * Returns NULL on error (check lto_get_error_message() for details). * * \since LTO_API_VERSION=11 */ extern lto_module_t lto_module_create_in_local_context(const void *mem, size_t length, const char *path); /** * \brief Loads an object file in the codegen context. * * Loads an object file into the same context as \c cg. The module is safe to * add using \a lto_codegen_add_module(). * * Returns NULL on error (check lto_get_error_message() for details). * * \since LTO_API_VERSION=11 */ extern lto_module_t lto_module_create_in_codegen_context(const void *mem, size_t length, const char *path, lto_code_gen_t cg); /** * Loads an object file from disk. The seek point of fd is not preserved. * Returns NULL on error (check lto_get_error_message() for details). * * \since LTO_API_VERSION=5 */ extern lto_module_t lto_module_create_from_fd(int fd, const char *path, size_t file_size); /** * Loads an object file from disk. The seek point of fd is not preserved. * Returns NULL on error (check lto_get_error_message() for details). * * \since LTO_API_VERSION=5 */ extern lto_module_t lto_module_create_from_fd_at_offset(int fd, const char *path, size_t file_size, size_t map_size, off_t offset); /** * Frees all memory internally allocated by the module. * Upon return the lto_module_t is no longer valid. * * \since prior to LTO_API_VERSION=3 */ extern void lto_module_dispose(lto_module_t mod); /** * Returns triple string which the object module was compiled under. * * \since prior to LTO_API_VERSION=3 */ extern const char* lto_module_get_target_triple(lto_module_t mod); /** * Sets triple string with which the object will be codegened. * * \since LTO_API_VERSION=4 */ extern void lto_module_set_target_triple(lto_module_t mod, const char *triple); /** * Returns the number of symbols in the object module. * * \since prior to LTO_API_VERSION=3 */ extern unsigned int lto_module_get_num_symbols(lto_module_t mod); /** * Returns the name of the ith symbol in the object module. * * \since prior to LTO_API_VERSION=3 */ extern const char* lto_module_get_symbol_name(lto_module_t mod, unsigned int index); /** * Returns the attributes of the ith symbol in the object module. * * \since prior to LTO_API_VERSION=3 */ extern lto_symbol_attributes lto_module_get_symbol_attribute(lto_module_t mod, unsigned int index); /** * Returns the module's linker options. * * The linker options may consist of multiple flags. It is the linker's * responsibility to split the flags using a platform-specific mechanism. * * \since LTO_API_VERSION=16 */ extern const char* lto_module_get_linkeropts(lto_module_t mod); /** * Diagnostic severity. * * \since LTO_API_VERSION=7 */ typedef enum { LTO_DS_ERROR = 0, LTO_DS_WARNING = 1, LTO_DS_REMARK = 3, // Added in LTO_API_VERSION=10. LTO_DS_NOTE = 2 } lto_codegen_diagnostic_severity_t; /** * Diagnostic handler type. * \p severity defines the severity. * \p diag is the actual diagnostic. * The diagnostic is not prefixed by any of severity keyword, e.g., 'error: '. * \p ctxt is used to pass the context set with the diagnostic handler. * * \since LTO_API_VERSION=7 */ typedef void (*lto_diagnostic_handler_t)( lto_codegen_diagnostic_severity_t severity, const char *diag, void *ctxt); /** * Set a diagnostic handler and the related context (void *). * This is more general than lto_get_error_message, as the diagnostic handler * can be called at anytime within lto. * * \since LTO_API_VERSION=7 */ extern void lto_codegen_set_diagnostic_handler(lto_code_gen_t, lto_diagnostic_handler_t, void *); /** * Instantiates a code generator. * Returns NULL on error (check lto_get_error_message() for details). * * All modules added using \a lto_codegen_add_module() must have been created * in the same context as the codegen. * * \since prior to LTO_API_VERSION=3 */ extern lto_code_gen_t lto_codegen_create(void); /** * \brief Instantiate a code generator in its own context. * * Instantiates a code generator in its own context. Modules added via \a * lto_codegen_add_module() must have all been created in the same context, * using \a lto_module_create_in_codegen_context(). * * \since LTO_API_VERSION=11 */ extern lto_code_gen_t lto_codegen_create_in_local_context(void); /** * Frees all code generator and all memory it internally allocated. * Upon return the lto_code_gen_t is no longer valid. * * \since prior to LTO_API_VERSION=3 */ extern void lto_codegen_dispose(lto_code_gen_t); /** * Add an object module to the set of modules for which code will be generated. * Returns true on error (check lto_get_error_message() for details). * * \c cg and \c mod must both be in the same context. See \a * lto_codegen_create_in_local_context() and \a * lto_module_create_in_codegen_context(). * * \since prior to LTO_API_VERSION=3 */ extern lto_bool_t lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod); /** * Sets the object module for code generation. This will transfer the ownship of * the module to code generator. * * \c cg and \c mod must both be in the same context. * * \since LTO_API_VERSION=13 */ extern void lto_codegen_set_module(lto_code_gen_t cg, lto_module_t mod); /** * Sets if debug info should be generated. * Returns true on error (check lto_get_error_message() for details). * * \since prior to LTO_API_VERSION=3 */ extern lto_bool_t lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model); /** * Sets which PIC code model to generated. * Returns true on error (check lto_get_error_message() for details). * * \since prior to LTO_API_VERSION=3 */ extern lto_bool_t lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model); /** * Sets the cpu to generate code for. * * \since LTO_API_VERSION=4 */ extern void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu); /** * Sets the location of the assembler tool to run. If not set, libLTO * will use gcc to invoke the assembler. * * \since LTO_API_VERSION=3 */ extern void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char* path); /** * Sets extra arguments that libLTO should pass to the assembler. * * \since LTO_API_VERSION=4 */ extern void lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args, int nargs); /** * Adds to a list of all global symbols that must exist in the final generated * code. If a function is not listed there, it might be inlined into every usage * and optimized away. * * \since prior to LTO_API_VERSION=3 */ extern void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg, const char* symbol); /** * Writes a new object file at the specified path that contains the * merged contents of all modules added so far. * Returns true on error (check lto_get_error_message() for details). * * \since LTO_API_VERSION=5 */ extern lto_bool_t lto_codegen_write_merged_modules(lto_code_gen_t cg, const char* path); /** * Generates code for all added modules into one native object file. * This calls lto_codegen_optimize then lto_codegen_compile_optimized. * * On success returns a pointer to a generated mach-o/ELF buffer and * length set to the buffer size. The buffer is owned by the * lto_code_gen_t and will be freed when lto_codegen_dispose() * is called, or lto_codegen_compile() is called again. * On failure, returns NULL (check lto_get_error_message() for details). * * \since prior to LTO_API_VERSION=3 */ extern const void* lto_codegen_compile(lto_code_gen_t cg, size_t* length); /** * Generates code for all added modules into one native object file. * This calls lto_codegen_optimize then lto_codegen_compile_optimized (instead * of returning a generated mach-o/ELF buffer, it writes to a file). * * The name of the file is written to name. Returns true on error. * * \since LTO_API_VERSION=5 */ extern lto_bool_t lto_codegen_compile_to_file(lto_code_gen_t cg, const char** name); /** * Runs optimization for the merged module. Returns true on error. * * \since LTO_API_VERSION=12 */ extern lto_bool_t lto_codegen_optimize(lto_code_gen_t cg); /** * Generates code for the optimized merged module into one native object file. * It will not run any IR optimizations on the merged module. * * On success returns a pointer to a generated mach-o/ELF buffer and length set * to the buffer size. The buffer is owned by the lto_code_gen_t and will be * freed when lto_codegen_dispose() is called, or * lto_codegen_compile_optimized() is called again. On failure, returns NULL * (check lto_get_error_message() for details). * * \since LTO_API_VERSION=12 */ extern const void* lto_codegen_compile_optimized(lto_code_gen_t cg, size_t* length); /** * Returns the runtime API version. * * \since LTO_API_VERSION=12 */ extern unsigned int lto_api_version(void); /** * Sets options to help debug codegen bugs. * * \since prior to LTO_API_VERSION=3 */ extern void lto_codegen_debug_options(lto_code_gen_t cg, const char *); /** * Initializes LLVM disassemblers. * FIXME: This doesn't really belong here. * * \since LTO_API_VERSION=5 */ extern void lto_initialize_disassembler(void); /** * Sets if we should run internalize pass during optimization and code * generation. * * \since LTO_API_VERSION=14 */ extern void lto_codegen_set_should_internalize(lto_code_gen_t cg, lto_bool_t ShouldInternalize); /** * \brief Set whether to embed uselists in bitcode. * * Sets whether \a lto_codegen_write_merged_modules() should embed uselists in * output bitcode. This should be turned on for all -save-temps output. * * \since LTO_API_VERSION=15 */ extern void lto_codegen_set_should_embed_uselists(lto_code_gen_t cg, lto_bool_t ShouldEmbedUselists); #ifdef __cplusplus } #endif /** * @} */ #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/llvm-c/LinkTimeOptimizer.h
//===-- llvm/LinkTimeOptimizer.h - LTO Public C Interface -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header provides a C API to use the LLVM link time optimization // library. This is intended to be used by linkers which are C-only in // their implementation for performing LTO. // //===----------------------------------------------------------------------===// #ifndef LLVM_C_LINKTIMEOPTIMIZER_H #define LLVM_C_LINKTIMEOPTIMIZER_H #ifdef __cplusplus extern "C" { #endif /** * @defgroup LLVMCLinkTimeOptimizer Link Time Optimization * @ingroup LLVMC * * @{ */ /// This provides a dummy type for pointers to the LTO object. typedef void* llvm_lto_t; /// This provides a C-visible enumerator to manage status codes. /// This should map exactly onto the C++ enumerator LTOStatus. typedef enum llvm_lto_status { LLVM_LTO_UNKNOWN, LLVM_LTO_OPT_SUCCESS, LLVM_LTO_READ_SUCCESS, LLVM_LTO_READ_FAILURE, LLVM_LTO_WRITE_FAILURE, LLVM_LTO_NO_TARGET, LLVM_LTO_NO_WORK, LLVM_LTO_MODULE_MERGE_FAILURE, LLVM_LTO_ASM_FAILURE, // Added C-specific error codes LLVM_LTO_NULL_OBJECT } llvm_lto_status_t; /// This provides C interface to initialize link time optimizer. This allows /// linker to use dlopen() interface to dynamically load LinkTimeOptimizer. /// extern "C" helps, because dlopen() interface uses name to find the symbol. extern llvm_lto_t llvm_create_optimizer(void); extern void llvm_destroy_optimizer(llvm_lto_t lto); extern llvm_lto_status_t llvm_read_object_file (llvm_lto_t lto, const char* input_filename); extern llvm_lto_status_t llvm_optimize_modules (llvm_lto_t lto, const char* output_filename); /** * @} */ #ifdef __cplusplus } #endif #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/llvm-c/Support.h
/*===-- llvm-c/Support.h - Support C Interface --------------------*- C -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This file defines the C interface to the LLVM support library. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_SUPPORT_H #define LLVM_C_SUPPORT_H #include "llvm/Support/DataTypes.h" #ifdef __cplusplus extern "C" { #endif /** * @defgroup LLVMCSupportTypes Types and Enumerations * * @{ */ typedef int LLVMBool; /** * Used to pass regions of memory through LLVM interfaces. * * @see llvm::MemoryBuffer */ typedef struct LLVMOpaqueMemoryBuffer *LLVMMemoryBufferRef; /** * @} */ /** * This function permanently loads the dynamic library at the given path. * It is safe to call this function multiple times for the same library. * * @see sys::DynamicLibrary::LoadLibraryPermanently() */ LLVMBool LLVMLoadLibraryPermanently(const char* Filename); /** * This function parses the given arguments using the LLVM command line parser. * Note that the only stable thing about this function is its signature; you * cannot rely on any particular set of command line arguments being interpreted * the same way across LLVM versions. * * @see llvm::cl::ParseCommandLineOptions() */ void LLVMParseCommandLineOptions(int argc, const char *const *argv, const char *Overview); /** * This function will search through all previously loaded dynamic * libraries for the symbol \p symbolName. If it is found, the address of * that symbol is returned. If not, null is returned. * * @see sys::DynamicLibrary::SearchForAddressOfSymbol() */ void *LLVMSearchForAddressOfSymbol(const char *symbolName); /** * This functions permanently adds the symbol \p symbolName with the * value \p symbolValue. These symbols are searched before any * libraries. * * @see sys::DynamicLibrary::AddSymbol() */ void LLVMAddSymbol(const char *symbolName, void *symbolValue); #ifdef __cplusplus } #endif #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/llvm-c/Disassembler.h
/*===-- llvm-c/Disassembler.h - Disassembler Public C Interface ---*- C -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header provides a public interface to a disassembler library. *| |* LLVM provides an implementation of this interface. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_DISASSEMBLER_H #define LLVM_C_DISASSEMBLER_H #include "dxc/WinAdapter.h" // HLSL Change #include "llvm/Support/DataTypes.h" #include <stddef.h> /** * @defgroup LLVMCDisassembler Disassembler * @ingroup LLVMC * * @{ */ /** * An opaque reference to a disassembler context. */ typedef void *LLVMDisasmContextRef; /** * The type for the operand information call back function. This is called to * get the symbolic information for an operand of an instruction. Typically * this is from the relocation information, symbol table, etc. That block of * information is saved when the disassembler context is created and passed to * the call back in the DisInfo parameter. The instruction containing operand * is at the PC parameter. For some instruction sets, there can be more than * one operand with symbolic information. To determine the symbolic operand * information for each operand, the bytes for the specific operand in the * instruction are specified by the Offset parameter and its byte widith is the * size parameter. For instructions sets with fixed widths and one symbolic * operand per instruction, the Offset parameter will be zero and Size parameter * will be the instruction width. The information is returned in TagBuf and is * Triple specific with its specific information defined by the value of * TagType for that Triple. If symbolic information is returned the function * returns 1, otherwise it returns 0. */ typedef int (*LLVMOpInfoCallback)(void *DisInfo, uint64_t PC, uint64_t Offset, uint64_t Size, int TagType, void *TagBuf); /** * The initial support in LLVM MC for the most general form of a relocatable * expression is "AddSymbol - SubtractSymbol + Offset". For some Darwin targets * this full form is encoded in the relocation information so that AddSymbol and * SubtractSymbol can be link edited independent of each other. Many other * platforms only allow a relocatable expression of the form AddSymbol + Offset * to be encoded. * * The LLVMOpInfoCallback() for the TagType value of 1 uses the struct * LLVMOpInfo1. The value of the relocatable expression for the operand, * including any PC adjustment, is passed in to the call back in the Value * field. The symbolic information about the operand is returned using all * the fields of the structure with the Offset of the relocatable expression * returned in the Value field. It is possible that some symbols in the * relocatable expression were assembly temporary symbols, for example * "Ldata - LpicBase + constant", and only the Values of the symbols without * symbol names are present in the relocation information. The VariantKind * type is one of the Target specific #defines below and is used to print * operands like "_foo@GOT", ":lower16:_foo", etc. */ struct LLVMOpInfoSymbol1 { uint64_t Present; /* 1 if this symbol is present */ const char *Name; /* symbol name if not NULL */ uint64_t Value; /* symbol value if name is NULL */ }; struct LLVMOpInfo1 { struct LLVMOpInfoSymbol1 AddSymbol; struct LLVMOpInfoSymbol1 SubtractSymbol; uint64_t Value; uint64_t VariantKind; }; /** * The operand VariantKinds for symbolic disassembly. */ #define LLVMDisassembler_VariantKind_None 0 /* all targets */ /** * The ARM target VariantKinds. */ #define LLVMDisassembler_VariantKind_ARM_HI16 1 /* :upper16: */ #define LLVMDisassembler_VariantKind_ARM_LO16 2 /* :lower16: */ /** * The ARM64 target VariantKinds. */ #define LLVMDisassembler_VariantKind_ARM64_PAGE 1 /* @page */ #define LLVMDisassembler_VariantKind_ARM64_PAGEOFF 2 /* @pageoff */ #define LLVMDisassembler_VariantKind_ARM64_GOTPAGE 3 /* @gotpage */ #define LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF 4 /* @gotpageoff */ #define LLVMDisassembler_VariantKind_ARM64_TLVP 5 /* @tvlppage */ #define LLVMDisassembler_VariantKind_ARM64_TLVOFF 6 /* @tvlppageoff */ /** * The type for the symbol lookup function. This may be called by the * disassembler for things like adding a comment for a PC plus a constant * offset load instruction to use a symbol name instead of a load address value. * It is passed the block information is saved when the disassembler context is * created and the ReferenceValue to look up as a symbol. If no symbol is found * for the ReferenceValue NULL is returned. The ReferenceType of the * instruction is passed indirectly as is the PC of the instruction in * ReferencePC. If the output reference can be determined its type is returned * indirectly in ReferenceType along with ReferenceName if any, or that is set * to NULL. */ typedef const char *(*LLVMSymbolLookupCallback)(void *DisInfo, uint64_t ReferenceValue, uint64_t *ReferenceType, uint64_t ReferencePC, const char **ReferenceName); /** * The reference types on input and output. */ /* No input reference type or no output reference type. */ #define LLVMDisassembler_ReferenceType_InOut_None 0 /* The input reference is from a branch instruction. */ #define LLVMDisassembler_ReferenceType_In_Branch 1 /* The input reference is from a PC relative load instruction. */ #define LLVMDisassembler_ReferenceType_In_PCrel_Load 2 /* The input reference is from an ARM64::ADRP instruction. */ #define LLVMDisassembler_ReferenceType_In_ARM64_ADRP 0x100000001 /* The input reference is from an ARM64::ADDXri instruction. */ #define LLVMDisassembler_ReferenceType_In_ARM64_ADDXri 0x100000002 /* The input reference is from an ARM64::LDRXui instruction. */ #define LLVMDisassembler_ReferenceType_In_ARM64_LDRXui 0x100000003 /* The input reference is from an ARM64::LDRXl instruction. */ #define LLVMDisassembler_ReferenceType_In_ARM64_LDRXl 0x100000004 /* The input reference is from an ARM64::ADR instruction. */ #define LLVMDisassembler_ReferenceType_In_ARM64_ADR 0x100000005 /* The output reference is to as symbol stub. */ #define LLVMDisassembler_ReferenceType_Out_SymbolStub 1 /* The output reference is to a symbol address in a literal pool. */ #define LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr 2 /* The output reference is to a cstring address in a literal pool. */ #define LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr 3 /* The output reference is to a Objective-C CoreFoundation string. */ #define LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref 4 /* The output reference is to a Objective-C message. */ #define LLVMDisassembler_ReferenceType_Out_Objc_Message 5 /* The output reference is to a Objective-C message ref. */ #define LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref 6 /* The output reference is to a Objective-C selector ref. */ #define LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref 7 /* The output reference is to a Objective-C class ref. */ #define LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref 8 /* The output reference is to a C++ symbol name. */ #define LLVMDisassembler_ReferenceType_DeMangled_Name 9 #ifdef __cplusplus extern "C" { #endif /* !defined(__cplusplus) */ /** * Create a disassembler for the TripleName. Symbolic disassembly is supported * by passing a block of information in the DisInfo parameter and specifying the * TagType and callback functions as described above. These can all be passed * as NULL. If successful, this returns a disassembler context. If not, it * returns NULL. This function is equivalent to calling * LLVMCreateDisasmCPUFeatures() with an empty CPU name and feature set. */ LLVMDisasmContextRef LLVMCreateDisasm(const char *TripleName, void *DisInfo, int TagType, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp); /** * Create a disassembler for the TripleName and a specific CPU. Symbolic * disassembly is supported by passing a block of information in the DisInfo * parameter and specifying the TagType and callback functions as described * above. These can all be passed * as NULL. If successful, this returns a * disassembler context. If not, it returns NULL. This function is equivalent * to calling LLVMCreateDisasmCPUFeatures() with an empty feature set. */ LLVMDisasmContextRef LLVMCreateDisasmCPU(const char *Triple, const char *CPU, void *DisInfo, int TagType, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp); /** * Create a disassembler for the TripleName, a specific CPU and specific feature * string. Symbolic disassembly is supported by passing a block of information * in the DisInfo parameter and specifying the TagType and callback functions as * described above. These can all be passed * as NULL. If successful, this * returns a disassembler context. If not, it returns NULL. */ LLVMDisasmContextRef LLVMCreateDisasmCPUFeatures(const char *Triple, const char *CPU, const char *Features, void *DisInfo, int TagType, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp); /** * Set the disassembler's options. Returns 1 if it can set the Options and 0 * otherwise. */ int LLVMSetDisasmOptions(LLVMDisasmContextRef DC, uint64_t Options); /* The option to produce marked up assembly. */ #define LLVMDisassembler_Option_UseMarkup 1 /* The option to print immediates as hex. */ #define LLVMDisassembler_Option_PrintImmHex 2 /* The option use the other assembler printer variant */ #define LLVMDisassembler_Option_AsmPrinterVariant 4 /* The option to set comment on instructions */ #define LLVMDisassembler_Option_SetInstrComments 8 /* The option to print latency information alongside instructions */ #define LLVMDisassembler_Option_PrintLatency 16 /** * Dispose of a disassembler context. */ void LLVMDisasmDispose(LLVMDisasmContextRef DC); /** * Disassemble a single instruction using the disassembler context specified in * the parameter DC. The bytes of the instruction are specified in the * parameter Bytes, and contains at least BytesSize number of bytes. The * instruction is at the address specified by the PC parameter. If a valid * instruction can be disassembled, its string is returned indirectly in * OutString whose size is specified in the parameter OutStringSize. This * function returns the number of bytes in the instruction or zero if there was * no valid instruction. */ size_t LLVMDisasmInstruction(LLVMDisasmContextRef DC, uint8_t *Bytes, uint64_t BytesSize, uint64_t PC, char *OutString, size_t OutStringSize); /** * @} */ #ifdef __cplusplus } #endif /* !defined(__cplusplus) */ #endif /* !defined(LLVM_C_DISASSEMBLER_H) */
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/llvm-c/module.modulemap
module LLVM_C { umbrella "." module * { export * } }
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/llvm-c/BitReader.h
/*===-- llvm-c/BitReader.h - BitReader Library C Interface ------*- C++ -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header declares the C interface to libLLVMBitReader.a, which *| |* implements input of the LLVM bitcode format. *| |* *| |* Many exotic languages can interoperate with C code but have a harder time *| |* with C++ due to name mangling. So in addition to C, this interface enables *| |* tools written in such languages. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_BITREADER_H #define LLVM_C_BITREADER_H #include "llvm-c/Core.h" #ifdef __cplusplus extern "C" { #endif /** * @defgroup LLVMCBitReader Bit Reader * @ingroup LLVMC * * @{ */ /* Builds a module from the bitcode in the specified memory buffer, returning a reference to the module via the OutModule parameter. Returns 0 on success. Optionally returns a human-readable error message via OutMessage. */ LLVMBool LLVMParseBitcode(LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutModule, char **OutMessage); LLVMBool LLVMParseBitcodeInContext(LLVMContextRef ContextRef, LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutModule, char **OutMessage); /** Reads a module from the specified path, returning via the OutMP parameter a module provider which performs lazy deserialization. Returns 0 on success. Optionally returns a human-readable error message via OutMessage. */ LLVMBool LLVMGetBitcodeModuleInContext(LLVMContextRef ContextRef, LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM, char **OutMessage); LLVMBool LLVMGetBitcodeModule(LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM, char **OutMessage); /** Deprecated: Use LLVMGetBitcodeModuleInContext instead. */ LLVMBool LLVMGetBitcodeModuleProviderInContext(LLVMContextRef ContextRef, LLVMMemoryBufferRef MemBuf, LLVMModuleProviderRef *OutMP, char **OutMessage); /** Deprecated: Use LLVMGetBitcodeModule instead. */ LLVMBool LLVMGetBitcodeModuleProvider(LLVMMemoryBufferRef MemBuf, LLVMModuleProviderRef *OutMP, char **OutMessage); /** * @} */ #ifdef __cplusplus } #endif #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/llvm-c/Target.h
/*===-- llvm-c/Target.h - Target Lib C Iface --------------------*- C++ -*-===*/ /* */ /* The LLVM Compiler Infrastructure */ /* */ /* This file is distributed under the University of Illinois Open Source */ /* License. See LICENSE.TXT for details. */ /* */ /*===----------------------------------------------------------------------===*/ /* */ /* This header declares the C interface to libLLVMTarget.a, which */ /* implements target information. */ /* */ /* Many exotic languages can interoperate with C code but have a harder time */ /* with C++ due to name mangling. So in addition to C, this interface enables */ /* tools written in such languages. */ /* */ /*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_TARGET_H #define LLVM_C_TARGET_H #include "llvm-c/Core.h" #include "llvm/Config/llvm-config.h" #if defined(_MSC_VER) && !defined(inline) #define inline __inline #endif #ifdef __cplusplus extern "C" { #endif /** * @defgroup LLVMCTarget Target information * @ingroup LLVMC * * @{ */ enum LLVMByteOrdering { LLVMBigEndian, LLVMLittleEndian }; typedef struct LLVMOpaqueTargetData *LLVMTargetDataRef; typedef struct LLVMOpaqueTargetLibraryInfotData *LLVMTargetLibraryInfoRef; /* Declare all of the target-initialization functions that are available. */ #define LLVM_TARGET(TargetName) \ void LLVMInitialize##TargetName##TargetInfo(void); #include "llvm/Config/Targets.def" #undef LLVM_TARGET /* Explicit undef to make SWIG happier */ #define LLVM_TARGET(TargetName) void LLVMInitialize##TargetName##Target(void); #include "llvm/Config/Targets.def" #undef LLVM_TARGET /* Explicit undef to make SWIG happier */ #define LLVM_TARGET(TargetName) \ void LLVMInitialize##TargetName##TargetMC(void); #include "llvm/Config/Targets.def" #undef LLVM_TARGET /* Explicit undef to make SWIG happier */ /* Declare all of the available assembly printer initialization functions. */ #define LLVM_ASM_PRINTER(TargetName) \ void LLVMInitialize##TargetName##AsmPrinter(void); #include "llvm/Config/AsmPrinters.def" #undef LLVM_ASM_PRINTER /* Explicit undef to make SWIG happier */ /* Declare all of the available assembly parser initialization functions. */ #define LLVM_ASM_PARSER(TargetName) \ void LLVMInitialize##TargetName##AsmParser(void); #include "llvm/Config/AsmParsers.def" #undef LLVM_ASM_PARSER /* Explicit undef to make SWIG happier */ /* Declare all of the available disassembler initialization functions. */ #define LLVM_DISASSEMBLER(TargetName) \ void LLVMInitialize##TargetName##Disassembler(void); #include "llvm/Config/Disassemblers.def" #undef LLVM_DISASSEMBLER /* Explicit undef to make SWIG happier */ /** LLVMInitializeAllTargetInfos - The main program should call this function if it wants access to all available targets that LLVM is configured to support. */ static inline void LLVMInitializeAllTargetInfos(void) { #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetInfo(); #include "llvm/Config/Targets.def" #undef LLVM_TARGET /* Explicit undef to make SWIG happier */ } /** LLVMInitializeAllTargets - The main program should call this function if it wants to link in all available targets that LLVM is configured to support. */ static inline void LLVMInitializeAllTargets(void) { #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##Target(); #include "llvm/Config/Targets.def" #undef LLVM_TARGET /* Explicit undef to make SWIG happier */ } /** LLVMInitializeAllTargetMCs - The main program should call this function if it wants access to all available target MC that LLVM is configured to support. */ static inline void LLVMInitializeAllTargetMCs(void) { #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetMC(); #include "llvm/Config/Targets.def" #undef LLVM_TARGET /* Explicit undef to make SWIG happier */ } /** LLVMInitializeAllAsmPrinters - The main program should call this function if it wants all asm printers that LLVM is configured to support, to make them available via the TargetRegistry. */ static inline void LLVMInitializeAllAsmPrinters(void) { #define LLVM_ASM_PRINTER(TargetName) LLVMInitialize##TargetName##AsmPrinter(); #include "llvm/Config/AsmPrinters.def" #undef LLVM_ASM_PRINTER /* Explicit undef to make SWIG happier */ } /** LLVMInitializeAllAsmParsers - The main program should call this function if it wants all asm parsers that LLVM is configured to support, to make them available via the TargetRegistry. */ static inline void LLVMInitializeAllAsmParsers(void) { #define LLVM_ASM_PARSER(TargetName) LLVMInitialize##TargetName##AsmParser(); #include "llvm/Config/AsmParsers.def" #undef LLVM_ASM_PARSER /* Explicit undef to make SWIG happier */ } /** LLVMInitializeAllDisassemblers - The main program should call this function if it wants all disassemblers that LLVM is configured to support, to make them available via the TargetRegistry. */ static inline void LLVMInitializeAllDisassemblers(void) { #define LLVM_DISASSEMBLER(TargetName) \ LLVMInitialize##TargetName##Disassembler(); #include "llvm/Config/Disassemblers.def" #undef LLVM_DISASSEMBLER /* Explicit undef to make SWIG happier */ } /** LLVMInitializeNativeTarget - The main program should call this function to initialize the native target corresponding to the host. This is useful for JIT applications to ensure that the target gets linked in correctly. */ static inline LLVMBool LLVMInitializeNativeTarget(void) { /* If we have a native target, initialize it to ensure it is linked in. */ #ifdef LLVM_NATIVE_TARGET LLVM_NATIVE_TARGETINFO(); LLVM_NATIVE_TARGET(); LLVM_NATIVE_TARGETMC(); return 0; #else return 1; #endif } /** LLVMInitializeNativeTargetAsmParser - The main program should call this function to initialize the parser for the native target corresponding to the host. */ static inline LLVMBool LLVMInitializeNativeAsmParser(void) { #ifdef LLVM_NATIVE_ASMPARSER LLVM_NATIVE_ASMPARSER(); return 0; #else return 1; #endif } /** LLVMInitializeNativeTargetAsmPrinter - The main program should call this function to initialize the printer for the native target corresponding to the host. */ static inline LLVMBool LLVMInitializeNativeAsmPrinter(void) { #ifdef LLVM_NATIVE_ASMPRINTER LLVM_NATIVE_ASMPRINTER(); return 0; #else return 1; #endif } /** LLVMInitializeNativeTargetDisassembler - The main program should call this function to initialize the disassembler for the native target corresponding to the host. */ static inline LLVMBool LLVMInitializeNativeDisassembler(void) { #ifdef LLVM_NATIVE_DISASSEMBLER LLVM_NATIVE_DISASSEMBLER(); return 0; #else return 1; #endif } /*===-- Target Data -------------------------------------------------------===*/ /** Creates target data from a target layout string. See the constructor llvm::DataLayout::DataLayout. */ LLVMTargetDataRef LLVMCreateTargetData(const char *StringRep); /** Adds target data information to a pass manager. This does not take ownership of the target data. See the method llvm::PassManagerBase::add. */ void LLVMAddTargetData(LLVMTargetDataRef TD, LLVMPassManagerRef PM); /** Adds target library information to a pass manager. This does not take ownership of the target library info. See the method llvm::PassManagerBase::add. */ void LLVMAddTargetLibraryInfo(LLVMTargetLibraryInfoRef TLI, LLVMPassManagerRef PM); /** Converts target data to a target layout string. The string must be disposed with LLVMDisposeMessage. See the constructor llvm::DataLayout::DataLayout. */ char *LLVMCopyStringRepOfTargetData(LLVMTargetDataRef TD); /** Returns the byte order of a target, either LLVMBigEndian or LLVMLittleEndian. See the method llvm::DataLayout::isLittleEndian. */ enum LLVMByteOrdering LLVMByteOrder(LLVMTargetDataRef TD); /** Returns the pointer size in bytes for a target. See the method llvm::DataLayout::getPointerSize. */ unsigned LLVMPointerSize(LLVMTargetDataRef TD); /** Returns the pointer size in bytes for a target for a specified address space. See the method llvm::DataLayout::getPointerSize. */ unsigned LLVMPointerSizeForAS(LLVMTargetDataRef TD, unsigned AS); /** Returns the integer type that is the same size as a pointer on a target. See the method llvm::DataLayout::getIntPtrType. */ LLVMTypeRef LLVMIntPtrType(LLVMTargetDataRef TD); /** Returns the integer type that is the same size as a pointer on a target. This version allows the address space to be specified. See the method llvm::DataLayout::getIntPtrType. */ LLVMTypeRef LLVMIntPtrTypeForAS(LLVMTargetDataRef TD, unsigned AS); /** Returns the integer type that is the same size as a pointer on a target. See the method llvm::DataLayout::getIntPtrType. */ LLVMTypeRef LLVMIntPtrTypeInContext(LLVMContextRef C, LLVMTargetDataRef TD); /** Returns the integer type that is the same size as a pointer on a target. This version allows the address space to be specified. See the method llvm::DataLayout::getIntPtrType. */ LLVMTypeRef LLVMIntPtrTypeForASInContext(LLVMContextRef C, LLVMTargetDataRef TD, unsigned AS); /** Computes the size of a type in bytes for a target. See the method llvm::DataLayout::getTypeSizeInBits. */ unsigned long long LLVMSizeOfTypeInBits(LLVMTargetDataRef TD, LLVMTypeRef Ty); /** Computes the storage size of a type in bytes for a target. See the method llvm::DataLayout::getTypeStoreSize. */ unsigned long long LLVMStoreSizeOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty); /** Computes the ABI size of a type in bytes for a target. See the method llvm::DataLayout::getTypeAllocSize. */ unsigned long long LLVMABISizeOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty); /** Computes the ABI alignment of a type in bytes for a target. See the method llvm::DataLayout::getTypeABISize. */ unsigned LLVMABIAlignmentOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty); /** Computes the call frame alignment of a type in bytes for a target. See the method llvm::DataLayout::getTypeABISize. */ unsigned LLVMCallFrameAlignmentOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty); /** Computes the preferred alignment of a type in bytes for a target. See the method llvm::DataLayout::getTypeABISize. */ unsigned LLVMPreferredAlignmentOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty); /** Computes the preferred alignment of a global variable in bytes for a target. See the method llvm::DataLayout::getPreferredAlignment. */ unsigned LLVMPreferredAlignmentOfGlobal(LLVMTargetDataRef TD, LLVMValueRef GlobalVar); /** Computes the structure element that contains the byte offset for a target. See the method llvm::StructLayout::getElementContainingOffset. */ unsigned LLVMElementAtOffset(LLVMTargetDataRef TD, LLVMTypeRef StructTy, unsigned long long Offset); /** Computes the byte offset of the indexed struct element for a target. See the method llvm::StructLayout::getElementContainingOffset. */ unsigned long long LLVMOffsetOfElement(LLVMTargetDataRef TD, LLVMTypeRef StructTy, unsigned Element); /** Deallocates a TargetData. See the destructor llvm::DataLayout::~DataLayout. */ void LLVMDisposeTargetData(LLVMTargetDataRef TD); /** * @} */ #ifdef __cplusplus } #endif /* defined(__cplusplus) */ #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/llvm-c/BitWriter.h
/*===-- llvm-c/BitWriter.h - BitWriter Library C Interface ------*- C++ -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header declares the C interface to libLLVMBitWriter.a, which *| |* implements output of the LLVM bitcode format. *| |* *| |* Many exotic languages can interoperate with C code but have a harder time *| |* with C++ due to name mangling. So in addition to C, this interface enables *| |* tools written in such languages. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_BITWRITER_H #define LLVM_C_BITWRITER_H #include "llvm-c/Core.h" #ifdef __cplusplus extern "C" { #endif /** * @defgroup LLVMCBitWriter Bit Writer * @ingroup LLVMC * * @{ */ /*===-- Operations on modules ---------------------------------------------===*/ /** Writes a module to the specified path. Returns 0 on success. */ int LLVMWriteBitcodeToFile(LLVMModuleRef M, const char *Path); /** Writes a module to an open file descriptor. Returns 0 on success. */ int LLVMWriteBitcodeToFD(LLVMModuleRef M, int FD, int ShouldClose, int Unbuffered); /** Deprecated for LLVMWriteBitcodeToFD. Writes a module to an open file descriptor. Returns 0 on success. Closes the Handle. */ int LLVMWriteBitcodeToFileHandle(LLVMModuleRef M, int Handle); /** Writes a module to a new memory buffer and returns it. */ LLVMMemoryBufferRef LLVMWriteBitcodeToMemoryBuffer(LLVMModuleRef M); /** * @} */ #ifdef __cplusplus } #endif #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/llvm-c/Linker.h
/*===-- llvm-c/Linker.h - Module Linker C Interface -------------*- C++ -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This file defines the C interface to the module/file/archive linker. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_LINKER_H #define LLVM_C_LINKER_H #include "llvm-c/Core.h" #ifdef __cplusplus extern "C" { #endif /* This enum is provided for backwards-compatibility only. It has no effect. */ typedef enum { LLVMLinkerDestroySource = 0, /* This is the default behavior. */ LLVMLinkerPreserveSource_Removed = 1 /* This option has been deprecated and should not be used. */ } LLVMLinkerMode; /* Links the source module into the destination module, taking ownership * of the source module away from the caller. Optionally returns a * human-readable description of any errors that occurred in linking. * OutMessage must be disposed with LLVMDisposeMessage. The return value * is true if an error occurred, false otherwise. * * Note that the linker mode parameter \p Unused is no longer used, and has * no effect. */ LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src, LLVMLinkerMode Unused, char **OutMessage); #ifdef __cplusplus } #endif #endif
0
repos/DirectXShaderCompiler/include/llvm-c
repos/DirectXShaderCompiler/include/llvm-c/Transforms/Scalar.h
/*===-- Scalar.h - Scalar Transformation Library C Interface ----*- C++ -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header declares the C interface to libLLVMScalarOpts.a, which *| |* implements various scalar transformations of the LLVM IR. *| |* *| |* Many exotic languages can interoperate with C code but have a harder time *| |* with C++ due to name mangling. So in addition to C, this interface enables *| |* tools written in such languages. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_TRANSFORMS_SCALAR_H #define LLVM_C_TRANSFORMS_SCALAR_H #include "llvm-c/Core.h" #ifdef __cplusplus extern "C" { #endif /** * @defgroup LLVMCTransformsScalar Scalar transformations * @ingroup LLVMCTransforms * * @{ */ /** See llvm::createAggressiveDCEPass function. */ void LLVMAddAggressiveDCEPass(LLVMPassManagerRef PM); /** See llvm::createBitTrackingDCEPass function. */ void LLVMAddBitTrackingDCEPass(LLVMPassManagerRef PM); /** See llvm::createAlignmentFromAssumptionsPass function. */ void LLVMAddAlignmentFromAssumptionsPass(LLVMPassManagerRef PM); /** See llvm::createCFGSimplificationPass function. */ void LLVMAddCFGSimplificationPass(LLVMPassManagerRef PM); /** See llvm::createDeadStoreEliminationPass function. */ void LLVMAddDeadStoreEliminationPass(LLVMPassManagerRef PM); /** See llvm::createScalarizerPass function. */ void LLVMAddScalarizerPass(LLVMPassManagerRef PM); /** See llvm::createMergedLoadStoreMotionPass function. */ void LLVMAddMergedLoadStoreMotionPass(LLVMPassManagerRef PM); /** See llvm::createGVNPass function. */ void LLVMAddGVNPass(LLVMPassManagerRef PM); /** See llvm::createIndVarSimplifyPass function. */ void LLVMAddIndVarSimplifyPass(LLVMPassManagerRef PM); /** See llvm::createInstructionCombiningPass function. */ void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM); /** See llvm::createJumpThreadingPass function. */ void LLVMAddJumpThreadingPass(LLVMPassManagerRef PM); /** See llvm::createLICMPass function. */ void LLVMAddLICMPass(LLVMPassManagerRef PM); /** See llvm::createLoopDeletionPass function. */ void LLVMAddLoopDeletionPass(LLVMPassManagerRef PM); /** See llvm::createLoopIdiomPass function */ void LLVMAddLoopIdiomPass(LLVMPassManagerRef PM); /** See llvm::createLoopRotatePass function. */ void LLVMAddLoopRotatePass(LLVMPassManagerRef PM); /** See llvm::createLoopRerollPass function. */ void LLVMAddLoopRerollPass(LLVMPassManagerRef PM); /** See llvm::createLoopUnrollPass function. */ void LLVMAddLoopUnrollPass(LLVMPassManagerRef PM); /** See llvm::createLoopUnswitchPass function. */ void LLVMAddLoopUnswitchPass(LLVMPassManagerRef PM); /** See llvm::createMemCpyOptPass function. */ void LLVMAddMemCpyOptPass(LLVMPassManagerRef PM); /** See llvm::createPartiallyInlineLibCallsPass function. */ void LLVMAddPartiallyInlineLibCallsPass(LLVMPassManagerRef PM); /** See llvm::createLowerSwitchPass function. */ void LLVMAddLowerSwitchPass(LLVMPassManagerRef PM); /** See llvm::createPromoteMemoryToRegisterPass function. */ void LLVMAddPromoteMemoryToRegisterPass(LLVMPassManagerRef PM); /** See llvm::createReassociatePass function. */ void LLVMAddReassociatePass(LLVMPassManagerRef PM); /** See llvm::createSCCPPass function. */ void LLVMAddSCCPPass(LLVMPassManagerRef PM); /** See llvm::createScalarReplAggregatesPass function. */ void LLVMAddScalarReplAggregatesPass(LLVMPassManagerRef PM); /** See llvm::createScalarReplAggregatesPass function. */ void LLVMAddScalarReplAggregatesPassSSA(LLVMPassManagerRef PM); /** See llvm::createScalarReplAggregatesPass function. */ void LLVMAddScalarReplAggregatesPassWithThreshold(LLVMPassManagerRef PM, int Threshold); /** See llvm::createSimplifyLibCallsPass function. */ void LLVMAddSimplifyLibCallsPass(LLVMPassManagerRef PM); /** See llvm::createTailCallEliminationPass function. */ void LLVMAddTailCallEliminationPass(LLVMPassManagerRef PM); /** See llvm::createConstantPropagationPass function. */ void LLVMAddConstantPropagationPass(LLVMPassManagerRef PM); /** See llvm::demotePromoteMemoryToRegisterPass function. */ void LLVMAddDemoteMemoryToRegisterPass(LLVMPassManagerRef PM); /** See llvm::createVerifierPass function. */ void LLVMAddVerifierPass(LLVMPassManagerRef PM); /** See llvm::createCorrelatedValuePropagationPass function */ void LLVMAddCorrelatedValuePropagationPass(LLVMPassManagerRef PM); /** See llvm::createEarlyCSEPass function */ void LLVMAddEarlyCSEPass(LLVMPassManagerRef PM); /** See llvm::createLowerExpectIntrinsicPass function */ void LLVMAddLowerExpectIntrinsicPass(LLVMPassManagerRef PM); /** See llvm::createTypeBasedAliasAnalysisPass function */ void LLVMAddTypeBasedAliasAnalysisPass(LLVMPassManagerRef PM); /** See llvm::createScopedNoAliasAAPass function */ void LLVMAddScopedNoAliasAAPass(LLVMPassManagerRef PM); /** See llvm::createBasicAliasAnalysisPass function */ void LLVMAddBasicAliasAnalysisPass(LLVMPassManagerRef PM); /** * @} */ #ifdef __cplusplus } #endif /* defined(__cplusplus) */ #endif
0
repos/DirectXShaderCompiler/include/llvm-c
repos/DirectXShaderCompiler/include/llvm-c/Transforms/IPO.h
/*===-- IPO.h - Interprocedural Transformations C Interface -----*- C++ -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header declares the C interface to libLLVMIPO.a, which implements *| |* various interprocedural transformations of the LLVM IR. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_TRANSFORMS_IPO_H #define LLVM_C_TRANSFORMS_IPO_H #include "llvm-c/Core.h" #ifdef __cplusplus extern "C" { #endif /** * @defgroup LLVMCTransformsIPO Interprocedural transformations * @ingroup LLVMCTransforms * * @{ */ /** See llvm::createArgumentPromotionPass function. */ void LLVMAddArgumentPromotionPass(LLVMPassManagerRef PM); /** See llvm::createConstantMergePass function. */ void LLVMAddConstantMergePass(LLVMPassManagerRef PM); /** See llvm::createDeadArgEliminationPass function. */ void LLVMAddDeadArgEliminationPass(LLVMPassManagerRef PM); /** See llvm::createFunctionAttrsPass function. */ void LLVMAddFunctionAttrsPass(LLVMPassManagerRef PM); /** See llvm::createFunctionInliningPass function. */ void LLVMAddFunctionInliningPass(LLVMPassManagerRef PM); /** See llvm::createAlwaysInlinerPass function. */ void LLVMAddAlwaysInlinerPass(LLVMPassManagerRef PM); /** See llvm::createGlobalDCEPass function. */ void LLVMAddGlobalDCEPass(LLVMPassManagerRef PM); /** See llvm::createGlobalOptimizerPass function. */ void LLVMAddGlobalOptimizerPass(LLVMPassManagerRef PM); /** See llvm::createIPConstantPropagationPass function. */ void LLVMAddIPConstantPropagationPass(LLVMPassManagerRef PM); /** See llvm::createPruneEHPass function. */ void LLVMAddPruneEHPass(LLVMPassManagerRef PM); /** See llvm::createIPSCCPPass function. */ void LLVMAddIPSCCPPass(LLVMPassManagerRef PM); /** See llvm::createInternalizePass function. */ void LLVMAddInternalizePass(LLVMPassManagerRef, unsigned AllButMain); /** See llvm::createStripDeadPrototypesPass function. */ void LLVMAddStripDeadPrototypesPass(LLVMPassManagerRef PM); /** See llvm::createStripSymbolsPass function. */ void LLVMAddStripSymbolsPass(LLVMPassManagerRef PM); /** * @} */ #ifdef __cplusplus } #endif /* defined(__cplusplus) */ #endif
0
repos/DirectXShaderCompiler/include/llvm-c
repos/DirectXShaderCompiler/include/llvm-c/Transforms/PassManagerBuilder.h
/*===-- llvm-c/Transform/PassManagerBuilder.h - PMB C Interface ---*- C -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header declares the C interface to the PassManagerBuilder class. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_TRANSFORMS_PASSMANAGERBUILDER_H #define LLVM_C_TRANSFORMS_PASSMANAGERBUILDER_H #include "llvm-c/Core.h" typedef struct LLVMOpaquePassManagerBuilder *LLVMPassManagerBuilderRef; #ifdef __cplusplus extern "C" { #endif /** * @defgroup LLVMCTransformsPassManagerBuilder Pass manager builder * @ingroup LLVMCTransforms * * @{ */ /** See llvm::PassManagerBuilder. */ LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate(void); void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB); /** See llvm::PassManagerBuilder::OptLevel. */ void LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB, unsigned OptLevel); /** See llvm::PassManagerBuilder::SizeLevel. */ void LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB, unsigned SizeLevel); /** See llvm::PassManagerBuilder::DisableUnitAtATime. */ void LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB, LLVMBool Value); /** See llvm::PassManagerBuilder::DisableUnrollLoops. */ void LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB, LLVMBool Value); /** See llvm::PassManagerBuilder::DisableSimplifyLibCalls */ void LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB, LLVMBool Value); /** See llvm::PassManagerBuilder::Inliner. */ void LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB, unsigned Threshold); /** See llvm::PassManagerBuilder::populateFunctionPassManager. */ void LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB, LLVMPassManagerRef PM); /** See llvm::PassManagerBuilder::populateModulePassManager. */ void LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB, LLVMPassManagerRef PM); /** See llvm::PassManagerBuilder::populateLTOPassManager. */ void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB, LLVMPassManagerRef PM, LLVMBool Internalize, LLVMBool RunInliner); /** * @} */ #ifdef __cplusplus } #endif #endif
0
repos/DirectXShaderCompiler/include/llvm-c
repos/DirectXShaderCompiler/include/llvm-c/Transforms/Vectorize.h
/*===---------------------------Vectorize.h --------------------- -*- C -*-===*\ |*===----------- Vectorization Transformation Library C Interface ---------===*| |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header declares the C interface to libLLVMVectorize.a, which *| |* implements various vectorization transformations of the LLVM IR. *| |* *| |* Many exotic languages can interoperate with C code but have a harder time *| |* with C++ due to name mangling. So in addition to C, this interface enables *| |* tools written in such languages. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_C_TRANSFORMS_VECTORIZE_H #define LLVM_C_TRANSFORMS_VECTORIZE_H #include "llvm-c/Core.h" #ifdef __cplusplus extern "C" { #endif /** * @defgroup LLVMCTransformsVectorize Vectorization transformations * @ingroup LLVMCTransforms * * @{ */ /** See llvm::createBBVectorizePass function. */ void LLVMAddBBVectorizePass(LLVMPassManagerRef PM); /** See llvm::createLoopVectorizePass function. */ void LLVMAddLoopVectorizePass(LLVMPassManagerRef PM); /** See llvm::createSLPVectorizerPass function. */ void LLVMAddSLPVectorizePass(LLVMPassManagerRef PM); /** * @} */ #ifdef __cplusplus } #endif /* defined(__cplusplus) */ #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/dxc/dxcerrors.h
/////////////////////////////////////////////////////////////////////////////// // // // dxcerror.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides definition of error codes. // // // /////////////////////////////////////////////////////////////////////////////// #ifndef __DXC_ERRORS__ #define __DXC_ERRORS__ #ifndef FACILITY_GRAPHICS #define FACILITY_GRAPHICS 36 #endif #define DXC_EXCEPTION_CODE(name, status) \ static constexpr DWORD EXCEPTION_##name = \ (0xc0000000u | (FACILITY_GRAPHICS << 16) | \ (0xff00u | (status & 0xffu))); DXC_EXCEPTION_CODE(LOAD_LIBRARY_FAILED, 0x00u) DXC_EXCEPTION_CODE(NO_HMODULE, 0x01u) DXC_EXCEPTION_CODE(GET_PROC_FAILED, 0x02u) #undef DXC_EXCEPTION_CODE #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/dxc/dxcapi.h
/////////////////////////////////////////////////////////////////////////////// // // // dxcapi.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides declarations for the DirectX Compiler API entry point. // // // /////////////////////////////////////////////////////////////////////////////// #ifndef __DXC_API__ #define __DXC_API__ #ifdef _WIN32 #ifndef DXC_API_IMPORT #define DXC_API_IMPORT __declspec(dllimport) #endif #else #ifndef DXC_API_IMPORT #define DXC_API_IMPORT __attribute__((visibility("default"))) #endif #endif #ifdef _WIN32 #ifndef CROSS_PLATFORM_UUIDOF // Warning: This macro exists in WinAdapter.h as well #define CROSS_PLATFORM_UUIDOF(interface, spec) \ struct __declspec(uuid(spec)) interface; #endif #else #include "WinAdapter.h" #include <dlfcn.h> #endif struct IMalloc; struct IDxcIncludeHandler; /// \brief Typedef for DxcCreateInstance function pointer. /// /// This can be used with GetProcAddress to get the DxcCreateInstance function. typedef HRESULT(__stdcall *DxcCreateInstanceProc)(_In_ REFCLSID rclsid, _In_ REFIID riid, _Out_ LPVOID *ppv); /// \brief Typedef for DxcCreateInstance2 function pointer. /// /// This can be used with GetProcAddress to get the DxcCreateInstance2 function. typedef HRESULT(__stdcall *DxcCreateInstance2Proc)(_In_ IMalloc *pMalloc, _In_ REFCLSID rclsid, _In_ REFIID riid, _Out_ LPVOID *ppv); /// \brief Creates a single uninitialized object of the class associated with a /// specified CLSID. /// /// \param rclsid The CLSID associated with the data and code that will be used /// to create the object. /// /// \param riid A reference to the identifier of the interface to be used to /// communicate with the object. /// /// \param ppv Address of pointer variable that receives the interface pointer /// requested in riid. Upon successful return, *ppv contains the requested /// interface pointer. Upon failure, *ppv contains NULL. /// /// While this function is similar to CoCreateInstance, there is no COM /// involvement. extern "C" DXC_API_IMPORT HRESULT __stdcall DxcCreateInstance(_In_ REFCLSID rclsid, _In_ REFIID riid, _Out_ LPVOID *ppv); /// \brief Version of DxcCreateInstance that takes an IMalloc interface. /// /// This can be used to create an instance of the compiler with a custom memory /// allocator. extern "C" DXC_API_IMPORT HRESULT __stdcall DxcCreateInstance2(_In_ IMalloc *pMalloc, _In_ REFCLSID rclsid, _In_ REFIID riid, _Out_ LPVOID *ppv); // For convenience, equivalent definitions to CP_UTF8 and CP_UTF16. #define DXC_CP_UTF8 65001 #define DXC_CP_UTF16 1200 #define DXC_CP_UTF32 12000 // Use DXC_CP_ACP for: Binary; ANSI Text; Autodetect UTF with BOM #define DXC_CP_ACP 0 /// Codepage for "wide" characters - UTF16 on Windows, UTF32 on other platforms. #ifdef _WIN32 #define DXC_CP_WIDE DXC_CP_UTF16 #else #define DXC_CP_WIDE DXC_CP_UTF32 #endif /// Indicates that the shader hash was computed taking into account source /// information (-Zss). #define DXC_HASHFLAG_INCLUDES_SOURCE 1 /// Hash digest type for ShaderHash. typedef struct DxcShaderHash { UINT32 Flags; ///< DXC_HASHFLAG_* BYTE HashDigest[16]; ///< The hash digest } DxcShaderHash; #define DXC_FOURCC(ch0, ch1, ch2, ch3) \ ((UINT32)(UINT8)(ch0) | (UINT32)(UINT8)(ch1) << 8 | \ (UINT32)(UINT8)(ch2) << 16 | (UINT32)(UINT8)(ch3) << 24) #define DXC_PART_PDB DXC_FOURCC('I', 'L', 'D', 'B') #define DXC_PART_PDB_NAME DXC_FOURCC('I', 'L', 'D', 'N') #define DXC_PART_PRIVATE_DATA DXC_FOURCC('P', 'R', 'I', 'V') #define DXC_PART_ROOT_SIGNATURE DXC_FOURCC('R', 'T', 'S', '0') #define DXC_PART_DXIL DXC_FOURCC('D', 'X', 'I', 'L') #define DXC_PART_REFLECTION_DATA DXC_FOURCC('S', 'T', 'A', 'T') #define DXC_PART_SHADER_HASH DXC_FOURCC('H', 'A', 'S', 'H') #define DXC_PART_INPUT_SIGNATURE DXC_FOURCC('I', 'S', 'G', '1') #define DXC_PART_OUTPUT_SIGNATURE DXC_FOURCC('O', 'S', 'G', '1') #define DXC_PART_PATCH_CONSTANT_SIGNATURE DXC_FOURCC('P', 'S', 'G', '1') // Some option arguments are defined here for continuity with D3DCompile // interface. #define DXC_ARG_DEBUG L"-Zi" #define DXC_ARG_SKIP_VALIDATION L"-Vd" #define DXC_ARG_SKIP_OPTIMIZATIONS L"-Od" #define DXC_ARG_PACK_MATRIX_ROW_MAJOR L"-Zpr" #define DXC_ARG_PACK_MATRIX_COLUMN_MAJOR L"-Zpc" #define DXC_ARG_AVOID_FLOW_CONTROL L"-Gfa" #define DXC_ARG_PREFER_FLOW_CONTROL L"-Gfp" #define DXC_ARG_ENABLE_STRICTNESS L"-Ges" #define DXC_ARG_ENABLE_BACKWARDS_COMPATIBILITY L"-Gec" #define DXC_ARG_IEEE_STRICTNESS L"-Gis" #define DXC_ARG_OPTIMIZATION_LEVEL0 L"-O0" #define DXC_ARG_OPTIMIZATION_LEVEL1 L"-O1" #define DXC_ARG_OPTIMIZATION_LEVEL2 L"-O2" #define DXC_ARG_OPTIMIZATION_LEVEL3 L"-O3" #define DXC_ARG_WARNINGS_ARE_ERRORS L"-WX" #define DXC_ARG_RESOURCES_MAY_ALIAS L"-res_may_alias" #define DXC_ARG_ALL_RESOURCES_BOUND L"-all_resources_bound" #define DXC_ARG_DEBUG_NAME_FOR_SOURCE L"-Zss" #define DXC_ARG_DEBUG_NAME_FOR_BINARY L"-Zsb" CROSS_PLATFORM_UUIDOF(IDxcBlob, "8BA5FB08-5195-40e2-AC58-0D989C3A0102") /// \brief A sized buffer that can be passed in and out of DXC APIs. /// /// This is an alias of ID3D10Blob and ID3DBlob. struct IDxcBlob : public IUnknown { public: /// \brief Retrieves a pointer to the blob's data. virtual LPVOID STDMETHODCALLTYPE GetBufferPointer(void) = 0; /// \brief Retrieves the size, in bytes, of the blob's data. virtual SIZE_T STDMETHODCALLTYPE GetBufferSize(void) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcBlobEncoding, "7241d424-2646-4191-97c0-98e96e42fc68") /// \brief A blob that might have a known encoding. struct IDxcBlobEncoding : public IDxcBlob { public: /// \brief Retrieve the encoding for this blob. /// /// \param pKnown Pointer to a variable that will be set to TRUE if the /// encoding is known. /// /// \param pCodePage Pointer to variable that will be set to the encoding used /// for this blog. /// /// If the encoding is not known then pCodePage will be set to CP_ACP. virtual HRESULT STDMETHODCALLTYPE GetEncoding(_Out_ BOOL *pKnown, _Out_ UINT32 *pCodePage) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcBlobWide, "A3F84EAB-0FAA-497E-A39C-EE6ED60B2D84") /// \brief A blob containing a null-terminated wide string. /// /// This uses the native wide character encoding (utf16 on Windows, utf32 on /// Linux). /// /// The value returned by GetBufferSize() is the size of the buffer, in bytes, /// including the null-terminator. /// /// This interface is used to return output name strings DXC. Other string /// output blobs, such as errors/warnings, preprocessed HLSL, or other text are /// returned using encodings based on the -encoding option passed to the /// compiler. struct IDxcBlobWide : public IDxcBlobEncoding { public: /// \brief Retrieves a pointer to the string stored in this blob. virtual LPCWSTR STDMETHODCALLTYPE GetStringPointer(void) = 0; /// \brief Retrieves the length of the string stored in this blob, in /// characters, excluding the null-terminator. virtual SIZE_T STDMETHODCALLTYPE GetStringLength(void) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcBlobUtf8, "3DA636C9-BA71-4024-A301-30CBF125305B") /// \brief A blob containing a UTF-8 encoded string. /// /// The value returned by GetBufferSize() is the size of the buffer, in bytes, /// including the null-terminator. /// /// Depending on the -encoding option passed to the compiler, this interface is /// used to return string output blobs, such as errors/warnings, preprocessed /// HLSL, or other text. Output name strings always use IDxcBlobWide. struct IDxcBlobUtf8 : public IDxcBlobEncoding { public: /// \brief Retrieves a pointer to the string stored in this blob. virtual LPCSTR STDMETHODCALLTYPE GetStringPointer(void) = 0; /// \brief Retrieves the length of the string stored in this blob, in /// characters, excluding the null-terminator. virtual SIZE_T STDMETHODCALLTYPE GetStringLength(void) = 0; }; #ifdef _WIN32 /// IDxcBlobUtf16 is a legacy alias for IDxcBlobWide on Win32. typedef IDxcBlobWide IDxcBlobUtf16; #endif CROSS_PLATFORM_UUIDOF(IDxcIncludeHandler, "7f61fc7d-950d-467f-b3e3-3c02fb49187c") /// \brief Interface for handling include directives. /// /// This interface can be implemented to customize handling of include /// directives. /// /// Use IDxcUtils::CreateDefaultIncludeHandler to create a default /// implementation that reads include files from the filesystem. /// struct IDxcIncludeHandler : public IUnknown { /// \brief Load a source file to be included by the compiler. /// /// \param pFilename Candidate filename. /// /// \param ppIncludeSource Resultant source object for included file, nullptr /// if not found. virtual HRESULT STDMETHODCALLTYPE LoadSource(_In_z_ LPCWSTR pFilename, _COM_Outptr_result_maybenull_ IDxcBlob **ppIncludeSource) = 0; }; /// \brief Structure for supplying bytes or text input to Dxc APIs. typedef struct DxcBuffer { /// \brief Pointer to the start of the buffer. LPCVOID Ptr; /// \brief Size of the buffer in bytes. SIZE_T Size; /// \brief Encoding of the buffer. /// /// Use Encoding = 0 for non-text bytes, ANSI text, or unknown with BOM. UINT Encoding; } DxcText; /// \brief Structure for supplying defines to Dxc APIs. struct DxcDefine { LPCWSTR Name; ///< The define name. _Maybenull_ LPCWSTR Value; ///< Optional value for the define. }; CROSS_PLATFORM_UUIDOF(IDxcCompilerArgs, "73EFFE2A-70DC-45F8-9690-EFF64C02429D") /// \brief Interface for managing arguments passed to DXC. /// /// Use IDxcUtils::BuildArguments to create an instance of this interface. struct IDxcCompilerArgs : public IUnknown { /// \brief Retrieve the array of arguments. /// /// This can be passed directly to the pArguments parameter of the Compile() /// method. virtual LPCWSTR *STDMETHODCALLTYPE GetArguments() = 0; /// \brief Retrieve the number of arguments. /// /// This can be passed directly to the argCount parameter of the Compile() /// method. virtual UINT32 STDMETHODCALLTYPE GetCount() = 0; /// \brief Add additional arguments to this list of compiler arguments. virtual HRESULT STDMETHODCALLTYPE AddArguments( _In_opt_count_(argCount) LPCWSTR *pArguments, ///< Array of pointers to arguments to add. _In_ UINT32 argCount ///< Number of arguments to add. ) = 0; /// \brief Add additional UTF-8 encoded arguments to this list of compiler /// arguments. virtual HRESULT STDMETHODCALLTYPE AddArgumentsUTF8( _In_opt_count_(argCount) LPCSTR *pArguments, ///< Array of pointers to UTF-8 arguments to add. _In_ UINT32 argCount ///< Number of arguments to add. ) = 0; /// \brief Add additional defines to this list of compiler arguments. virtual HRESULT STDMETHODCALLTYPE AddDefines( _In_count_(defineCount) const DxcDefine *pDefines, ///< Array of defines. _In_ UINT32 defineCount ///< Number of defines. ) = 0; }; ////////////////////////// // Legacy Interfaces ///////////////////////// CROSS_PLATFORM_UUIDOF(IDxcLibrary, "e5204dc7-d18c-4c3c-bdfb-851673980fe7") /// \deprecated IDxcUtils replaces IDxcLibrary; please use IDxcUtils insted. struct IDxcLibrary : public IUnknown { /// \deprecated virtual HRESULT STDMETHODCALLTYPE SetMalloc(_In_opt_ IMalloc *pMalloc) = 0; /// \deprecated virtual HRESULT STDMETHODCALLTYPE CreateBlobFromBlob(_In_ IDxcBlob *pBlob, UINT32 offset, UINT32 length, _COM_Outptr_ IDxcBlob **ppResult) = 0; /// \deprecated virtual HRESULT STDMETHODCALLTYPE CreateBlobFromFile(_In_z_ LPCWSTR pFileName, _In_opt_ UINT32 *codePage, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; /// \deprecated virtual HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingFromPinned( _In_bytecount_(size) LPCVOID pText, UINT32 size, UINT32 codePage, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; /// \deprecated virtual HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingOnHeapCopy( _In_bytecount_(size) LPCVOID pText, UINT32 size, UINT32 codePage, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; /// \deprecated virtual HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingOnMalloc( _In_bytecount_(size) LPCVOID pText, IMalloc *pIMalloc, UINT32 size, UINT32 codePage, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; /// \deprecated virtual HRESULT STDMETHODCALLTYPE CreateIncludeHandler(_COM_Outptr_ IDxcIncludeHandler **ppResult) = 0; /// \deprecated virtual HRESULT STDMETHODCALLTYPE CreateStreamFromBlobReadOnly( _In_ IDxcBlob *pBlob, _COM_Outptr_ IStream **ppStream) = 0; /// \deprecated virtual HRESULT STDMETHODCALLTYPE GetBlobAsUtf8( _In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; // Renamed from GetBlobAsUtf16 to GetBlobAsWide /// \deprecated virtual HRESULT STDMETHODCALLTYPE GetBlobAsWide( _In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; #ifdef _WIN32 // Alias to GetBlobAsWide on Win32 /// \deprecated inline HRESULT GetBlobAsUtf16(_In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) { return this->GetBlobAsWide(pBlob, pBlobEncoding); } #endif }; CROSS_PLATFORM_UUIDOF(IDxcOperationResult, "CEDB484A-D4E9-445A-B991-CA21CA157DC2") /// \brief The results of a DXC operation. /// /// Note: IDxcResult replaces IDxcOperationResult and should be used wherever /// possible. struct IDxcOperationResult : public IUnknown { /// \brief Retrieve the overall status of the operation. virtual HRESULT STDMETHODCALLTYPE GetStatus(_Out_ HRESULT *pStatus) = 0; /// \brief Retrieve the primary output of the operation. /// /// This corresponds to: /// * DXC_OUT_OBJECT - Compile() with shader or library target /// * DXC_OUT_DISASSEMBLY - Disassemble() /// * DXC_OUT_HLSL - Compile() with -P /// * DXC_OUT_ROOT_SIGNATURE - Compile() with rootsig_* target virtual HRESULT STDMETHODCALLTYPE GetResult(_COM_Outptr_result_maybenull_ IDxcBlob **ppResult) = 0; /// \brief Retrieves the error buffer from the operation, if there is one. /// // This corresponds to calling IDxcResult::GetOutput() with DXC_OUT_ERRORS. virtual HRESULT STDMETHODCALLTYPE GetErrorBuffer(_COM_Outptr_result_maybenull_ IDxcBlobEncoding **ppErrors) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcCompiler, "8c210bf3-011f-4422-8d70-6f9acb8db617") /// \deprecated Please use IDxcCompiler3 instead. struct IDxcCompiler : public IUnknown { /// \brief Compile a single entry point to the target shader model. /// /// \deprecated Please use IDxcCompiler3::Compile() instead. virtual HRESULT STDMETHODCALLTYPE Compile( _In_ IDxcBlob *pSource, // Source text to compile. _In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in // errors and include handlers. _In_opt_z_ LPCWSTR pEntryPoint, // Entry point name. _In_z_ LPCWSTR pTargetProfile, // Shader profile to compile. _In_opt_count_(argCount) LPCWSTR *pArguments, // Array of pointers to arguments. _In_ UINT32 argCount, // Number of arguments. _In_count_(defineCount) const DxcDefine *pDefines, // Array of defines. _In_ UINT32 defineCount, // Number of defines. _In_opt_ IDxcIncludeHandler *pIncludeHandler, // User-provided interface to handle #include // directives (optional). _COM_Outptr_ IDxcOperationResult * *ppResult // Compiler output status, buffer, and errors. ) = 0; /// \brief Preprocess source text. /// /// \deprecated Please use IDxcCompiler3::Compile() with the "-P" argument /// instead. virtual HRESULT STDMETHODCALLTYPE Preprocess( _In_ IDxcBlob *pSource, // Source text to preprocess. _In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in // errors and include handlers. _In_opt_count_(argCount) LPCWSTR *pArguments, // Array of pointers to arguments. _In_ UINT32 argCount, // Number of arguments. _In_count_(defineCount) const DxcDefine *pDefines, // Array of defines. _In_ UINT32 defineCount, // Number of defines. _In_opt_ IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle #include // directives (optional). _COM_Outptr_ IDxcOperationResult * *ppResult // Preprocessor output status, buffer, and errors. ) = 0; /// \brief Disassemble a program. /// /// \deprecated Please use IDxcCompiler3::Disassemble() instead. virtual HRESULT STDMETHODCALLTYPE Disassemble( _In_ IDxcBlob *pSource, // Program to disassemble. _COM_Outptr_ IDxcBlobEncoding **ppDisassembly // Disassembly text. ) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcCompiler2, "A005A9D9-B8BB-4594-B5C9-0E633BEC4D37") /// \deprecated Please use IDxcCompiler3 instead. struct IDxcCompiler2 : public IDxcCompiler { /// \brief Compile a single entry point to the target shader model with debug /// information. /// /// \deprecated Please use IDxcCompiler3::Compile() instead. virtual HRESULT STDMETHODCALLTYPE CompileWithDebug( _In_ IDxcBlob *pSource, // Source text to compile. _In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in // errors and include handlers. _In_opt_z_ LPCWSTR pEntryPoint, // Entry point name. _In_z_ LPCWSTR pTargetProfile, // Shader profile to compile. _In_opt_count_(argCount) LPCWSTR *pArguments, // Array of pointers to arguments. _In_ UINT32 argCount, // Number of arguments. _In_count_(defineCount) const DxcDefine *pDefines, // Array of defines. _In_ UINT32 defineCount, // Number of defines. _In_opt_ IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle #include // directives (optional). _COM_Outptr_ IDxcOperationResult * *ppResult, // Compiler output status, buffer, and errors. _Outptr_opt_result_z_ LPWSTR *ppDebugBlobName, // Suggested file name for debug blob. Must be // CoTaskMemFree()'d. _COM_Outptr_opt_ IDxcBlob **ppDebugBlob // Debug blob. ) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcLinker, "F1B5BE2A-62DD-4327-A1C2-42AC1E1E78E6") /// \brief DXC linker interface. /// /// Use DxcCreateInstance with CLSID_DxcLinker to obtain an instance of this /// interface. struct IDxcLinker : public IUnknown { public: /// \brief Register a library with name to reference it later. virtual HRESULT RegisterLibrary(_In_opt_ LPCWSTR pLibName, ///< Name of the library. _In_ IDxcBlob *pLib ///< Library blob. ) = 0; /// \brief Links the shader and produces a shader blob that the Direct3D /// runtime can use. virtual HRESULT STDMETHODCALLTYPE Link( _In_opt_ LPCWSTR pEntryName, ///< Entry point name. _In_ LPCWSTR pTargetProfile, ///< shader profile to link. _In_count_(libCount) const LPCWSTR *pLibNames, ///< Array of library names to link. _In_ UINT32 libCount, ///< Number of libraries to link. _In_opt_count_(argCount) const LPCWSTR *pArguments, ///< Array of pointers to arguments. _In_ UINT32 argCount, ///< Number of arguments. _COM_Outptr_ IDxcOperationResult * *ppResult ///< Linker output status, buffer, and errors. ) = 0; }; ///////////////////////// // Latest interfaces. Please use these. //////////////////////// CROSS_PLATFORM_UUIDOF(IDxcUtils, "4605C4CB-2019-492A-ADA4-65F20BB7D67F") /// \brief Various utility functions for DXC. /// /// Use DxcCreateInstance with CLSID_DxcUtils to obtain an instance of this /// interface. /// /// IDxcUtils replaces IDxcLibrary. struct IDxcUtils : public IUnknown { /// \brief Create a sub-blob that holds a reference to the outer blob and /// points to its memory. /// /// \param pBlob The outer blob. /// /// \param offset The offset inside the outer blob. /// /// \param length The size, in bytes, of the buffer to reference from the /// output blob. /// /// \param ppResult Address of the pointer that receives a pointer to the /// newly created blob. virtual HRESULT STDMETHODCALLTYPE CreateBlobFromBlob(_In_ IDxcBlob *pBlob, UINT32 offset, UINT32 length, _COM_Outptr_ IDxcBlob **ppResult) = 0; // For codePage, use 0 (or DXC_CP_ACP) for raw binary or ANSI code page. /// \brief Create a blob referencing existing memory, with no copy. /// /// \param pData Pointer to buffer containing the contents of the new blob. /// /// \param size The size of the pData buffer, in bytes. /// /// \param codePage The code page to use if the blob contains text. Use /// DXC_CP_ACP for binary or ANSI code page. /// /// \param ppBlobEncoding Address of the pointer that receives a pointer to /// the newly created blob. /// /// The user must manage the memory lifetime separately. /// /// This replaces IDxcLibrary::CreateBlobWithEncodingFromPinned. virtual HRESULT STDMETHODCALLTYPE CreateBlobFromPinned( _In_bytecount_(size) LPCVOID pData, UINT32 size, UINT32 codePage, _COM_Outptr_ IDxcBlobEncoding **ppBlobEncoding) = 0; /// \brief Create a blob, taking ownership of memory allocated with the /// supplied allocator. /// /// \param pData Pointer to buffer containing the contents of the new blob. /// /// \param pIMalloc The memory allocator to use. /// /// \param size The size of thee pData buffer, in bytes. /// /// \param codePage The code page to use if the blob contains text. Use /// DXC_CP_ACP for binary or ANSI code page. /// /// \param ppBlobEncoding Address of the pointer that receives a pointer to /// the newly created blob. /// /// This replaces IDxcLibrary::CreateBlobWithEncodingOnMalloc. virtual HRESULT STDMETHODCALLTYPE MoveToBlob( _In_bytecount_(size) LPCVOID pData, IMalloc *pIMalloc, UINT32 size, UINT32 codePage, _COM_Outptr_ IDxcBlobEncoding **ppBlobEncoding) = 0; /// \brief Create a blob containing a copy of the existing data. /// /// \param pData Pointer to buffer containing the contents of the new blob. /// /// \param size The size of thee pData buffer, in bytes. /// /// \param codePage The code page to use if the blob contains text. Use /// DXC_CP_ACP for binary or ANSI code page. /// /// \param ppBlobEncoding Address of the pointer that receives a pointer to /// the newly created blob. /// /// The new blob and its contents are allocated with the current allocator. /// This replaces IDxcLibrary::CreateBlobWithEncodingOnHeapCopy. virtual HRESULT STDMETHODCALLTYPE CreateBlob(_In_bytecount_(size) LPCVOID pData, UINT32 size, UINT32 codePage, _COM_Outptr_ IDxcBlobEncoding **ppBlobEncoding) = 0; /// \brief Create a blob with data loaded from a file. /// /// \param pFileName The name of the file to load from. /// /// \param pCodePage Optional code page to use if the blob contains text. Pass /// NULL for binary data. /// /// \param ppBlobEncoding Address of the pointer that receives a pointer to /// the newly created blob. /// /// The new blob and its contents are allocated with the current allocator. /// This replaces IDxcLibrary::CreateBlobFromFile. virtual HRESULT STDMETHODCALLTYPE LoadFile(_In_z_ LPCWSTR pFileName, _In_opt_ UINT32 *pCodePage, _COM_Outptr_ IDxcBlobEncoding **ppBlobEncoding) = 0; /// \brief Create a stream that reads data from a blob. /// /// \param pBlob The blob to read from. /// /// \param ppStream Address of the pointer that receives a pointer to the /// newly created stream. virtual HRESULT STDMETHODCALLTYPE CreateReadOnlyStreamFromBlob( _In_ IDxcBlob *pBlob, _COM_Outptr_ IStream **ppStream) = 0; /// \brief Create default file-based include handler. /// /// \param ppResult Address of the pointer that receives a pointer to the /// newly created include handler. virtual HRESULT STDMETHODCALLTYPE CreateDefaultIncludeHandler(_COM_Outptr_ IDxcIncludeHandler **ppResult) = 0; /// \brief Convert or return matching encoded text blob as UTF-8. /// /// \param pBlob The blob to convert. /// /// \param ppBlobEncoding Address of the pointer that receives a pointer to /// the newly created blob. virtual HRESULT STDMETHODCALLTYPE GetBlobAsUtf8( _In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobUtf8 **ppBlobEncoding) = 0; /// \brief Convert or return matching encoded text blob as UTF-16. /// /// \param pBlob The blob to convert. /// /// \param ppBlobEncoding Address of the pointer that receives a pointer to /// the newly created blob. virtual HRESULT STDMETHODCALLTYPE GetBlobAsWide( _In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobWide **ppBlobEncoding) = 0; #ifdef _WIN32 /// \brief Convert or return matching encoded text blob as UTF-16. /// /// \param pBlob The blob to convert. /// /// \param ppBlobEncoding Address of the pointer that receives a pointer to /// the newly created blob. /// /// Alias to GetBlobAsWide on Win32. inline HRESULT GetBlobAsUtf16(_In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobWide **ppBlobEncoding) { return this->GetBlobAsWide(pBlob, ppBlobEncoding); } #endif /// \brief Retrieve a single part from a DXIL container. /// /// \param pShader The shader to retrieve the part from. /// /// \param DxcPart The part to retrieve (eg DXC_PART_ROOT_SIGNATURE). /// /// \param ppPartData Address of the pointer that receives a pointer to the /// part. /// /// \param pPartSizeInBytes Address of the pointer that receives the size of /// the part. /// /// The returned pointer points inside the buffer passed in pShader. virtual HRESULT STDMETHODCALLTYPE GetDxilContainerPart(_In_ const DxcBuffer *pShader, _In_ UINT32 DxcPart, _Outptr_result_nullonfailure_ void **ppPartData, _Out_ UINT32 *pPartSizeInBytes) = 0; /// \brief Create reflection interface from serialized DXIL container or the /// DXC_OUT_REFLECTION blob contents. /// /// \param pData The source data. /// /// \param iid The interface ID of the reflection interface to create. /// /// \param ppvReflection Address of the pointer that receives a pointer to the /// newly created reflection interface. /// /// Use this with interfaces such as ID3D12ShaderReflection. virtual HRESULT STDMETHODCALLTYPE CreateReflection( _In_ const DxcBuffer *pData, REFIID iid, void **ppvReflection) = 0; /// \brief Build arguments that can be passed to the Compile method. virtual HRESULT STDMETHODCALLTYPE BuildArguments( _In_opt_z_ LPCWSTR pSourceName, ///< Optional file name for pSource. Used ///< in errors and include handlers. _In_opt_z_ LPCWSTR pEntryPoint, ///< Entry point name (-E). _In_z_ LPCWSTR pTargetProfile, ///< Shader profile to compile (-T). _In_opt_count_(argCount) LPCWSTR *pArguments, ///< Array of pointers to arguments. _In_ UINT32 argCount, ///< Number of arguments. _In_count_(defineCount) const DxcDefine *pDefines, ///< Array of defines. _In_ UINT32 defineCount, ///< Number of defines. _COM_Outptr_ IDxcCompilerArgs * *ppArgs ///< Arguments you can use with Compile() method. ) = 0; /// \brief Retrieve the hash and contents of a shader PDB. /// /// \param pPDBBlob The blob containing the PDB. /// /// \param ppHash Address of the pointer that receives a pointer to the hash /// blob. /// /// \param ppContainer Address of the pointer that receives a pointer to the /// bloc containing the contents of the PDB. /// virtual HRESULT STDMETHODCALLTYPE GetPDBContents(_In_ IDxcBlob *pPDBBlob, _COM_Outptr_ IDxcBlob **ppHash, _COM_Outptr_ IDxcBlob **ppContainer) = 0; }; /// \brief Specifies the kind of output to retrieve from a IDxcResult. /// /// Note: text outputs returned from version 2 APIs are UTF-8 or UTF-16 based on /// the -encoding option passed to the compiler. typedef enum DXC_OUT_KIND { DXC_OUT_NONE = 0, ///< No output. DXC_OUT_OBJECT = 1, ///< IDxcBlob - Shader or library object. DXC_OUT_ERRORS = 2, ///< IDxcBlobUtf8 or IDxcBlobWide. DXC_OUT_PDB = 3, ///< IDxcBlob. DXC_OUT_SHADER_HASH = 4, ///< IDxcBlob - DxcShaderHash of shader or shader ///< with source info (-Zsb/-Zss). DXC_OUT_DISASSEMBLY = 5, ///< IDxcBlobUtf8 or IDxcBlobWide - from Disassemble. DXC_OUT_HLSL = 6, ///< IDxcBlobUtf8 or IDxcBlobWide - from Preprocessor or Rewriter. DXC_OUT_TEXT = 7, ///< IDxcBlobUtf8 or IDxcBlobWide - other text, such as ///< -ast-dump or -Odump. DXC_OUT_REFLECTION = 8, ///< IDxcBlob - RDAT part with reflection data. DXC_OUT_ROOT_SIGNATURE = 9, ///< IDxcBlob - Serialized root signature output. DXC_OUT_EXTRA_OUTPUTS = 10, ///< IDxcExtraOutputs - Extra outputs. DXC_OUT_REMARKS = 11, ///< IDxcBlobUtf8 or IDxcBlobWide - text directed at stdout. DXC_OUT_TIME_REPORT = 12, ///< IDxcBlobUtf8 or IDxcBlobWide - text directed at stdout. DXC_OUT_TIME_TRACE = 13, ///< IDxcBlobUtf8 or IDxcBlobWide - text directed at stdout. DXC_OUT_LAST = DXC_OUT_TIME_TRACE, ///< Last value for a counter. DXC_OUT_NUM_ENUMS, DXC_OUT_FORCE_DWORD = 0xFFFFFFFF } DXC_OUT_KIND; static_assert(DXC_OUT_NUM_ENUMS == DXC_OUT_LAST + 1, "DXC_OUT_* Enum added and last value not updated."); CROSS_PLATFORM_UUIDOF(IDxcResult, "58346CDA-DDE7-4497-9461-6F87AF5E0659") /// \brief Result of a DXC operation. /// /// DXC operations may have multiple outputs, such as a shader object and /// errors. This interface provides access to the outputs. struct IDxcResult : public IDxcOperationResult { /// \brief Determines whether or not this result has the specified output. /// /// \param dxcOutKind The kind of output to check for. virtual BOOL STDMETHODCALLTYPE HasOutput(_In_ DXC_OUT_KIND dxcOutKind) = 0; /// \brief Retrieves the specified output. /// /// \param dxcOutKind The kind of output to retrieve. /// /// \param iid The interface ID of the output interface. /// /// \param ppvObject Address of the pointer that receives a pointer to the /// output. /// /// \param ppOutputName Optional address of a pointer to receive the name /// blob, if there is one. virtual HRESULT STDMETHODCALLTYPE GetOutput(_In_ DXC_OUT_KIND dxcOutKind, _In_ REFIID iid, _COM_Outptr_opt_result_maybenull_ void **ppvObject, _COM_Outptr_opt_result_maybenull_ IDxcBlobWide **ppOutputName) = 0; /// \brief Retrieves the number of outputs available in this result. virtual UINT32 GetNumOutputs() = 0; /// \brief Retrieves the output kind at the specified index. virtual DXC_OUT_KIND GetOutputByIndex(UINT32 Index) = 0; /// \brief Retrieves the primary output kind for this result. /// /// See IDxcOperationResult::GetResult() for more information on the primary /// output kinds. virtual DXC_OUT_KIND PrimaryOutput() = 0; }; // Special names for extra output that should get written to specific streams. #define DXC_EXTRA_OUTPUT_NAME_STDOUT L"*stdout*" #define DXC_EXTRA_OUTPUT_NAME_STDERR L"*stderr*" CROSS_PLATFORM_UUIDOF(IDxcExtraOutputs, "319b37a2-a5c2-494a-a5de-4801b2faf989") /// \brief Additional outputs from a DXC operation. /// /// This can be used to obtain outputs that don't have an explicit DXC_OUT_KIND. /// Use DXC_OUT_EXTRA_OUTPUTS to obtain instances of this. struct IDxcExtraOutputs : public IUnknown { /// \brief Retrieves the number of outputs available virtual UINT32 STDMETHODCALLTYPE GetOutputCount() = 0; /// \brief Retrieves the specified output. /// /// \param uIndex The index of the output to retrieve. /// /// \param iid The interface ID of the output interface. /// /// \param ppvObject Optional address of the pointer that receives a pointer /// to the output if there is one. /// /// \param ppOutputType Optional address of the pointer that receives the /// output type name blob if there is one. /// /// \param ppOutputName Optional address of the pointer that receives the /// output name blob if there is one. virtual HRESULT STDMETHODCALLTYPE GetOutput(_In_ UINT32 uIndex, _In_ REFIID iid, _COM_Outptr_opt_result_maybenull_ void **ppvObject, _COM_Outptr_opt_result_maybenull_ IDxcBlobWide **ppOutputType, _COM_Outptr_opt_result_maybenull_ IDxcBlobWide **ppOutputName) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcCompiler3, "228B4687-5A6A-4730-900C-9702B2203F54") /// \brief Interface to the DirectX Shader Compiler. /// /// Use DxcCreateInstance with CLSID_DxcCompiler to obtain an instance of this /// interface. struct IDxcCompiler3 : public IUnknown { /// \brief Compile a shader. /// /// IDxcUtils::BuildArguments can be used to assist building the pArguments /// and argCount parameters. /// /// Depending on the arguments, this method can be used to: /// /// * Compile a single entry point to the target shader model, /// * Compile a library to a library target (-T lib_*) /// * Compile a root signature (-T rootsig_*), /// * Preprocess HLSL source (-P). virtual HRESULT STDMETHODCALLTYPE Compile( _In_ const DxcBuffer *pSource, ///< Source text to compile. _In_opt_count_(argCount) LPCWSTR *pArguments, ///< Array of pointers to arguments. _In_ UINT32 argCount, ///< Number of arguments. _In_opt_ IDxcIncludeHandler *pIncludeHandler, ///< user-provided interface to handle include ///< directives (optional). _In_ REFIID riid, ///< Interface ID for the result. _Out_ LPVOID *ppResult ///< IDxcResult: status, buffer, and errors. ) = 0; /// \brief Disassemble a program. virtual HRESULT STDMETHODCALLTYPE Disassemble( _In_ const DxcBuffer *pObject, ///< Program to disassemble: dxil container or bitcode. _In_ REFIID riid, ///< Interface ID for the result. _Out_ LPVOID *ppResult ///< IDxcResult: status, disassembly text, and errors. ) = 0; }; static const UINT32 DxcValidatorFlags_Default = 0; static const UINT32 DxcValidatorFlags_InPlaceEdit = 1; // Validator is allowed to update shader blob in-place. static const UINT32 DxcValidatorFlags_RootSignatureOnly = 2; static const UINT32 DxcValidatorFlags_ModuleOnly = 4; static const UINT32 DxcValidatorFlags_ValidMask = 0x7; CROSS_PLATFORM_UUIDOF(IDxcValidator, "A6E82BD2-1FD7-4826-9811-2857E797F49A") /// \brief Interface to DXC shader validator. /// /// Use DxcCreateInstance with CLSID_DxcValidator to obtain an instance of this. struct IDxcValidator : public IUnknown { /// \brief Validate a shader. virtual HRESULT STDMETHODCALLTYPE Validate( _In_ IDxcBlob *pShader, ///< Shader to validate. _In_ UINT32 Flags, ///< Validation flags. _COM_Outptr_ IDxcOperationResult * *ppResult ///< Validation output status, buffer, and errors. ) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcValidator2, "458e1fd1-b1b2-4750-a6e1-9c10f03bed92") /// \brief Interface to DXC shader validator. /// /// Use DxcCreateInstance with CLSID_DxcValidator to obtain an instance of this. struct IDxcValidator2 : public IDxcValidator { /// \brief Validate a shader with optional debug bitcode. virtual HRESULT STDMETHODCALLTYPE ValidateWithDebug( _In_ IDxcBlob *pShader, ///< Shader to validate. _In_ UINT32 Flags, ///< Validation flags. _In_opt_ DxcBuffer *pOptDebugBitcode, ///< Optional debug module bitcode ///< to provide line numbers. _COM_Outptr_ IDxcOperationResult * *ppResult ///< Validation output status, buffer, and errors. ) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcContainerBuilder, "334b1f50-2292-4b35-99a1-25588d8c17fe") /// \brief Interface to DXC container builder. /// /// Use DxcCreateInstance with CLSID_DxcContainerBuilder to obtain an instance /// of this. struct IDxcContainerBuilder : public IUnknown { /// \brief Load a DxilContainer to the builder. virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pDxilContainerHeader) = 0; /// \brief Add a part to the container. /// /// \param fourCC The part identifier (eg DXC_PART_PDB). /// /// \param pSource The source blob. virtual HRESULT STDMETHODCALLTYPE AddPart(_In_ UINT32 fourCC, _In_ IDxcBlob *pSource) = 0; /// \brief Remove a part from the container. /// /// \param fourCC The part identifier (eg DXC_PART_PDB). /// /// \return S_OK on success, DXC_E_MISSING_PART if the part was not found, or /// other standard HRESULT error code. virtual HRESULT STDMETHODCALLTYPE RemovePart(_In_ UINT32 fourCC) = 0; /// \brief Build the container. /// /// \param ppResult Pointer to variable to receive the result. virtual HRESULT STDMETHODCALLTYPE SerializeContainer(_Out_ IDxcOperationResult **ppResult) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcAssembler, "091f7a26-1c1f-4948-904b-e6e3a8a771d5") /// \brief Interface to DxcAssembler. /// /// Use DxcCreateInstance with CLSID_DxcAssembler to obtain an instance of this. struct IDxcAssembler : public IUnknown { /// \brief Assemble DXIL in LL or LLVM bitcode to DXIL container. virtual HRESULT STDMETHODCALLTYPE AssembleToContainer( _In_ IDxcBlob *pShader, ///< Shader to assemble. _COM_Outptr_ IDxcOperationResult * *ppResult ///< Assembly output status, buffer, and errors. ) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcContainerReflection, "d2c21b26-8350-4bdc-976a-331ce6f4c54c") /// \brief Interface to DxcContainerReflection. /// /// Use DxcCreateInstance with CLSID_DxcContainerReflection to obtain an /// instance of this. struct IDxcContainerReflection : public IUnknown { /// \brief Choose the container to perform reflection on /// /// \param pContainer The container to load. If null is passed then this /// instance will release any held resources. virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pContainer) = 0; /// \brief Retrieves the number of parts in the container. /// /// \param pResult Pointer to variable to receive the result. /// /// \return S_OK on success, E_NOT_VALID_STATE if a container has not been /// loaded using Load(), or other standard HRESULT error codes. virtual HRESULT STDMETHODCALLTYPE GetPartCount(_Out_ UINT32 *pResult) = 0; /// \brief Retrieve the kind of a specified part. /// /// \param idx The index of the part to retrieve the kind of. /// /// \param pResult Pointer to variable to receive the result. /// /// \return S_OK on success, E_NOT_VALID_STATE if a container has not been /// loaded using Load(), E_BOUND if idx is out of bounds, or other standard /// HRESULT error codes. virtual HRESULT STDMETHODCALLTYPE GetPartKind(UINT32 idx, _Out_ UINT32 *pResult) = 0; /// \brief Retrieve the content of a specified part. /// /// \param idx The index of the part to retrieve. /// /// \param ppResult Pointer to variable to receive the result. /// /// \return S_OK on success, E_NOT_VALID_STATE if a container has not been /// loaded using Load(), E_BOUND if idx is out of bounds, or other standard /// HRESULT error codes. virtual HRESULT STDMETHODCALLTYPE GetPartContent(UINT32 idx, _COM_Outptr_ IDxcBlob **ppResult) = 0; /// \brief Retrieve the index of the first part with the specified kind. /// /// \param kind The kind to search for. /// /// \param pResult Pointer to variable to receive the index of the matching /// part. /// /// \return S_OK on success, E_NOT_VALID_STATE if a container has not been /// loaded using Load(), HRESULT_FROM_WIN32(ERROR_NOT_FOUND) if there is no /// part with the specified kind, or other standard HRESULT error codes. virtual HRESULT STDMETHODCALLTYPE FindFirstPartKind(UINT32 kind, _Out_ UINT32 *pResult) = 0; /// \brief Retrieve the reflection interface for a specified part. /// /// \param idx The index of the part to retrieve the reflection interface of. /// /// \param iid The IID of the interface to retrieve. /// /// \param ppvObject Pointer to variable to receive the result. /// /// Use this with interfaces such as ID3D12ShaderReflection. /// /// \return S_OK on success, E_NOT_VALID_STATE if a container has not been /// loaded using Load(), E_BOUND if idx is out of bounds, or other standard /// HRESULT error codes. virtual HRESULT STDMETHODCALLTYPE GetPartReflection(UINT32 idx, REFIID iid, void **ppvObject) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcOptimizerPass, "AE2CD79F-CC22-453F-9B6B-B124E7A5204C") /// \brief An optimizer pass. /// /// Instances of this can be obtained via IDxcOptimizer::GetAvailablePass. struct IDxcOptimizerPass : public IUnknown { virtual HRESULT STDMETHODCALLTYPE GetOptionName(_COM_Outptr_ LPWSTR *ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetDescription(_COM_Outptr_ LPWSTR *ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetOptionArgCount(_Out_ UINT32 *pCount) = 0; virtual HRESULT STDMETHODCALLTYPE GetOptionArgName(UINT32 argIndex, _COM_Outptr_ LPWSTR *ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetOptionArgDescription(UINT32 argIndex, _COM_Outptr_ LPWSTR *ppResult) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcOptimizer, "25740E2E-9CBA-401B-9119-4FB42F39F270") /// \brief Interface to DxcOptimizer. /// /// Use DxcCreateInstance with CLSID_DxcOptimizer to obtain an instance of this. struct IDxcOptimizer : public IUnknown { virtual HRESULT STDMETHODCALLTYPE GetAvailablePassCount(_Out_ UINT32 *pCount) = 0; virtual HRESULT STDMETHODCALLTYPE GetAvailablePass(UINT32 index, _COM_Outptr_ IDxcOptimizerPass **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE RunOptimizer(IDxcBlob *pBlob, _In_count_(optionCount) LPCWSTR *ppOptions, UINT32 optionCount, _COM_Outptr_ IDxcBlob **pOutputModule, _COM_Outptr_opt_ IDxcBlobEncoding **ppOutputText) = 0; }; static const UINT32 DxcVersionInfoFlags_None = 0; static const UINT32 DxcVersionInfoFlags_Debug = 1; // Matches VS_FF_DEBUG static const UINT32 DxcVersionInfoFlags_Internal = 2; // Internal Validator (non-signing) CROSS_PLATFORM_UUIDOF(IDxcVersionInfo, "b04f5b50-2059-4f12-a8ff-a1e0cde1cc7e") /// \brief PDB Version information. /// /// Use IDxcPdbUtils2::GetVersionInfo to obtain an instance of this. struct IDxcVersionInfo : public IUnknown { virtual HRESULT STDMETHODCALLTYPE GetVersion(_Out_ UINT32 *pMajor, _Out_ UINT32 *pMinor) = 0; virtual HRESULT STDMETHODCALLTYPE GetFlags(_Out_ UINT32 *pFlags) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcVersionInfo2, "fb6904c4-42f0-4b62-9c46-983af7da7c83") /// \brief PDB Version Information. /// /// Use IDxcPdbUtils2::GetVersionInfo to obtain a IDxcVersionInfo interface, and /// then use QueryInterface to obtain an instance of this interface from it. struct IDxcVersionInfo2 : public IDxcVersionInfo { virtual HRESULT STDMETHODCALLTYPE GetCommitInfo( _Out_ UINT32 *pCommitCount, ///< The total number commits. _Outptr_result_z_ char **pCommitHash ///< The SHA of the latest commit. ///< Must be CoTaskMemFree()'d. ) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcVersionInfo3, "5e13e843-9d25-473c-9ad2-03b2d0b44b1e") /// \brief PDB Version Information. /// /// Use IDxcPdbUtils2::GetVersionInfo to obtain a IDxcVersionInfo interface, and /// then use QueryInterface to obtain an instance of this interface from it. struct IDxcVersionInfo3 : public IUnknown { virtual HRESULT STDMETHODCALLTYPE GetCustomVersionString( _Outptr_result_z_ char * *pVersionString ///< Custom version string for compiler. Must be ///< CoTaskMemFree()'d. ) = 0; }; struct DxcArgPair { const WCHAR *pName; const WCHAR *pValue; }; CROSS_PLATFORM_UUIDOF(IDxcPdbUtils, "E6C9647E-9D6A-4C3B-B94C-524B5A6C343D") /// \deprecated Please use IDxcPdbUtils2 instead. struct IDxcPdbUtils : public IUnknown { virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pPdbOrDxil) = 0; virtual HRESULT STDMETHODCALLTYPE GetSourceCount(_Out_ UINT32 *pCount) = 0; virtual HRESULT STDMETHODCALLTYPE GetSource(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobEncoding **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetSourceName(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetFlagCount(_Out_ UINT32 *pCount) = 0; virtual HRESULT STDMETHODCALLTYPE GetFlag(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetArgCount(_Out_ UINT32 *pCount) = 0; virtual HRESULT STDMETHODCALLTYPE GetArg(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetArgPairCount(_Out_ UINT32 *pCount) = 0; virtual HRESULT STDMETHODCALLTYPE GetArgPair(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pName, _Outptr_result_z_ BSTR *pValue) = 0; virtual HRESULT STDMETHODCALLTYPE GetDefineCount(_Out_ UINT32 *pCount) = 0; virtual HRESULT STDMETHODCALLTYPE GetDefine(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetTargetProfile(_Outptr_result_z_ BSTR *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetEntryPoint(_Outptr_result_z_ BSTR *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetMainFileName(_Outptr_result_z_ BSTR *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetHash(_COM_Outptr_ IDxcBlob **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetName(_Outptr_result_z_ BSTR *pResult) = 0; virtual BOOL STDMETHODCALLTYPE IsFullPDB() = 0; virtual HRESULT STDMETHODCALLTYPE GetFullPDB(_COM_Outptr_ IDxcBlob **ppFullPDB) = 0; virtual HRESULT STDMETHODCALLTYPE GetVersionInfo(_COM_Outptr_ IDxcVersionInfo **ppVersionInfo) = 0; virtual HRESULT STDMETHODCALLTYPE SetCompiler(_In_ IDxcCompiler3 *pCompiler) = 0; virtual HRESULT STDMETHODCALLTYPE CompileForFullPDB(_COM_Outptr_ IDxcResult **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE OverrideArgs(_In_ DxcArgPair *pArgPairs, UINT32 uNumArgPairs) = 0; virtual HRESULT STDMETHODCALLTYPE OverrideRootSignature(_In_ const WCHAR *pRootSignature) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcPdbUtils2, "4315D938-F369-4F93-95A2-252017CC3807") /// \brief DxcPdbUtils interface. /// /// Use DxcCreateInstance with CLSID_DxcPdbUtils to create an instance of this. struct IDxcPdbUtils2 : public IUnknown { virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pPdbOrDxil) = 0; virtual HRESULT STDMETHODCALLTYPE GetSourceCount(_Out_ UINT32 *pCount) = 0; virtual HRESULT STDMETHODCALLTYPE GetSource(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobEncoding **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetSourceName(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobWide **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetLibraryPDBCount(UINT32 *pCount) = 0; virtual HRESULT STDMETHODCALLTYPE GetLibraryPDB( _In_ UINT32 uIndex, _COM_Outptr_ IDxcPdbUtils2 **ppOutPdbUtils, _COM_Outptr_opt_result_maybenull_ IDxcBlobWide **ppLibraryName) = 0; virtual HRESULT STDMETHODCALLTYPE GetFlagCount(_Out_ UINT32 *pCount) = 0; virtual HRESULT STDMETHODCALLTYPE GetFlag(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobWide **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetArgCount(_Out_ UINT32 *pCount) = 0; virtual HRESULT STDMETHODCALLTYPE GetArg(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobWide **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetArgPairCount(_Out_ UINT32 *pCount) = 0; virtual HRESULT STDMETHODCALLTYPE GetArgPair( _In_ UINT32 uIndex, _COM_Outptr_result_maybenull_ IDxcBlobWide **ppName, _COM_Outptr_result_maybenull_ IDxcBlobWide **ppValue) = 0; virtual HRESULT STDMETHODCALLTYPE GetDefineCount(_Out_ UINT32 *pCount) = 0; virtual HRESULT STDMETHODCALLTYPE GetDefine(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobWide **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetTargetProfile(_COM_Outptr_result_maybenull_ IDxcBlobWide **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetEntryPoint(_COM_Outptr_result_maybenull_ IDxcBlobWide **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetMainFileName(_COM_Outptr_result_maybenull_ IDxcBlobWide **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetHash(_COM_Outptr_result_maybenull_ IDxcBlob **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetName(_COM_Outptr_result_maybenull_ IDxcBlobWide **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetVersionInfo( _COM_Outptr_result_maybenull_ IDxcVersionInfo **ppVersionInfo) = 0; virtual HRESULT STDMETHODCALLTYPE GetCustomToolchainID(_Out_ UINT32 *pID) = 0; virtual HRESULT STDMETHODCALLTYPE GetCustomToolchainData(_COM_Outptr_result_maybenull_ IDxcBlob **ppBlob) = 0; virtual HRESULT STDMETHODCALLTYPE GetWholeDxil(_COM_Outptr_result_maybenull_ IDxcBlob **ppResult) = 0; virtual BOOL STDMETHODCALLTYPE IsFullPDB() = 0; virtual BOOL STDMETHODCALLTYPE IsPDBRef() = 0; }; // Note: __declspec(selectany) requires 'extern' // On Linux __declspec(selectany) is removed and using 'extern' results in link // error. #ifdef _MSC_VER #define CLSID_SCOPE __declspec(selectany) extern #else #define CLSID_SCOPE #endif CLSID_SCOPE const CLSID CLSID_DxcCompiler = { 0x73e22d93, 0xe6ce, 0x47f3, {0xb5, 0xbf, 0xf0, 0x66, 0x4f, 0x39, 0xc1, 0xb0}}; // {EF6A8087-B0EA-4D56-9E45-D07E1A8B7806} CLSID_SCOPE const GUID CLSID_DxcLinker = { 0xef6a8087, 0xb0ea, 0x4d56, {0x9e, 0x45, 0xd0, 0x7e, 0x1a, 0x8b, 0x78, 0x6}}; // {CD1F6B73-2AB0-484D-8EDC-EBE7A43CA09F} CLSID_SCOPE const CLSID CLSID_DxcDiaDataSource = { 0xcd1f6b73, 0x2ab0, 0x484d, {0x8e, 0xdc, 0xeb, 0xe7, 0xa4, 0x3c, 0xa0, 0x9f}}; // {3E56AE82-224D-470F-A1A1-FE3016EE9F9D} CLSID_SCOPE const CLSID CLSID_DxcCompilerArgs = { 0x3e56ae82, 0x224d, 0x470f, {0xa1, 0xa1, 0xfe, 0x30, 0x16, 0xee, 0x9f, 0x9d}}; // {6245D6AF-66E0-48FD-80B4-4D271796748C} CLSID_SCOPE const GUID CLSID_DxcLibrary = { 0x6245d6af, 0x66e0, 0x48fd, {0x80, 0xb4, 0x4d, 0x27, 0x17, 0x96, 0x74, 0x8c}}; CLSID_SCOPE const GUID CLSID_DxcUtils = CLSID_DxcLibrary; // {8CA3E215-F728-4CF3-8CDD-88AF917587A1} CLSID_SCOPE const GUID CLSID_DxcValidator = { 0x8ca3e215, 0xf728, 0x4cf3, {0x8c, 0xdd, 0x88, 0xaf, 0x91, 0x75, 0x87, 0xa1}}; // {D728DB68-F903-4F80-94CD-DCCF76EC7151} CLSID_SCOPE const GUID CLSID_DxcAssembler = { 0xd728db68, 0xf903, 0x4f80, {0x94, 0xcd, 0xdc, 0xcf, 0x76, 0xec, 0x71, 0x51}}; // {b9f54489-55b8-400c-ba3a-1675e4728b91} CLSID_SCOPE const GUID CLSID_DxcContainerReflection = { 0xb9f54489, 0x55b8, 0x400c, {0xba, 0x3a, 0x16, 0x75, 0xe4, 0x72, 0x8b, 0x91}}; // {AE2CD79F-CC22-453F-9B6B-B124E7A5204C} CLSID_SCOPE const GUID CLSID_DxcOptimizer = { 0xae2cd79f, 0xcc22, 0x453f, {0x9b, 0x6b, 0xb1, 0x24, 0xe7, 0xa5, 0x20, 0x4c}}; // {94134294-411f-4574-b4d0-8741e25240d2} CLSID_SCOPE const GUID CLSID_DxcContainerBuilder = { 0x94134294, 0x411f, 0x4574, {0xb4, 0xd0, 0x87, 0x41, 0xe2, 0x52, 0x40, 0xd2}}; // {54621dfb-f2ce-457e-ae8c-ec355faeec7c} CLSID_SCOPE const GUID CLSID_DxcPdbUtils = { 0x54621dfb, 0xf2ce, 0x457e, {0xae, 0x8c, 0xec, 0x35, 0x5f, 0xae, 0xec, 0x7c}}; #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/dxc/dxctools.h
/////////////////////////////////////////////////////////////////////////////// // // // dxctools.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides declarations for the DirectX Compiler tooling components. // // // /////////////////////////////////////////////////////////////////////////////// #ifndef __DXC_TOOLS__ #define __DXC_TOOLS__ #include <dxc/dxcapi.h> enum RewriterOptionMask { Default = 0, SkipFunctionBody = 1, SkipStatic = 2, GlobalExternByDefault = 4, KeepUserMacro = 8, }; CROSS_PLATFORM_UUIDOF(IDxcRewriter, "c012115b-8893-4eb9-9c5a-111456ea1c45") struct IDxcRewriter : public IUnknown { virtual HRESULT STDMETHODCALLTYPE RemoveUnusedGlobals( IDxcBlobEncoding *pSource, LPCWSTR entryPoint, DxcDefine *pDefines, UINT32 defineCount, IDxcOperationResult **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE RewriteUnchanged(IDxcBlobEncoding *pSource, DxcDefine *pDefines, UINT32 defineCount, IDxcOperationResult **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE RewriteUnchangedWithInclude( IDxcBlobEncoding *pSource, // Optional file name for pSource. Used in errors and include handlers. LPCWSTR pSourceName, DxcDefine *pDefines, UINT32 defineCount, // user-provided interface to handle #include directives (optional) IDxcIncludeHandler *pIncludeHandler, UINT32 rewriteOption, IDxcOperationResult **ppResult) = 0; }; #ifdef _MSC_VER #define CLSID_SCOPE __declspec(selectany) extern #else #define CLSID_SCOPE #endif CLSID_SCOPE const CLSID CLSID_DxcRewriter = {/* b489b951-e07f-40b3-968d-93e124734da4 */ 0xb489b951, 0xe07f, 0x40b3, {0x96, 0x8d, 0x93, 0xe1, 0x24, 0x73, 0x4d, 0xa4}}; CROSS_PLATFORM_UUIDOF(IDxcRewriter2, "261afca1-0609-4ec6-a77f-d98c7035194e") struct IDxcRewriter2 : public IDxcRewriter { virtual HRESULT STDMETHODCALLTYPE RewriteWithOptions( IDxcBlobEncoding *pSource, // Optional file name for pSource. Used in errors and include handlers. LPCWSTR pSourceName, // Compiler arguments LPCWSTR *pArguments, UINT32 argCount, // Defines DxcDefine *pDefines, UINT32 defineCount, // user-provided interface to handle #include directives (optional) IDxcIncludeHandler *pIncludeHandler, IDxcOperationResult **ppResult) = 0; }; #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/dxc/config.h.cmake
/* Disable overriding memory allocators. */ #cmakedefine DXC_DISABLE_ALLOCATOR_OVERRIDES /* Generate a trap if an hlsl::Exception is thrown during code generation */ #cmakedefine DXC_CODEGEN_EXCEPTIONS_TRAP
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/dxc/dxcisense.h
/////////////////////////////////////////////////////////////////////////////// // // // dxcisense.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides declarations for the DirectX Compiler IntelliSense component. // // // /////////////////////////////////////////////////////////////////////////////// #ifndef __DXC_ISENSE__ #define __DXC_ISENSE__ #include "dxcapi.h" #ifndef _WIN32 #include "WinAdapter.h" #endif typedef enum DxcGlobalOptions { DxcGlobalOpt_None = 0x0, DxcGlobalOpt_ThreadBackgroundPriorityForIndexing = 0x1, DxcGlobalOpt_ThreadBackgroundPriorityForEditing = 0x2, DxcGlobalOpt_ThreadBackgroundPriorityForAll = DxcGlobalOpt_ThreadBackgroundPriorityForIndexing | DxcGlobalOpt_ThreadBackgroundPriorityForEditing } DxcGlobalOptions; typedef enum DxcTokenKind { DxcTokenKind_Punctuation = 0, // A token that contains some kind of punctuation. DxcTokenKind_Keyword = 1, // A language keyword. DxcTokenKind_Identifier = 2, // An identifier (that is not a keyword). DxcTokenKind_Literal = 3, // A numeric, string, or character literal. DxcTokenKind_Comment = 4, // A comment. DxcTokenKind_Unknown = 5, // An unknown token (possibly known to a future version). DxcTokenKind_BuiltInType = 6, // A built-in type like int, void or float3. } DxcTokenKind; typedef enum DxcTypeKind { DxcTypeKind_Invalid = 0, // Reprents an invalid type (e.g., where no type is available). DxcTypeKind_Unexposed = 1, // A type whose specific kind is not exposed via this interface. // Builtin types DxcTypeKind_Void = 2, DxcTypeKind_Bool = 3, DxcTypeKind_Char_U = 4, DxcTypeKind_UChar = 5, DxcTypeKind_Char16 = 6, DxcTypeKind_Char32 = 7, DxcTypeKind_UShort = 8, DxcTypeKind_UInt = 9, DxcTypeKind_ULong = 10, DxcTypeKind_ULongLong = 11, DxcTypeKind_UInt128 = 12, DxcTypeKind_Char_S = 13, DxcTypeKind_SChar = 14, DxcTypeKind_WChar = 15, DxcTypeKind_Short = 16, DxcTypeKind_Int = 17, DxcTypeKind_Long = 18, DxcTypeKind_LongLong = 19, DxcTypeKind_Int128 = 20, DxcTypeKind_Float = 21, DxcTypeKind_Double = 22, DxcTypeKind_LongDouble = 23, DxcTypeKind_NullPtr = 24, DxcTypeKind_Overload = 25, DxcTypeKind_Dependent = 26, DxcTypeKind_ObjCId = 27, DxcTypeKind_ObjCClass = 28, DxcTypeKind_ObjCSel = 29, DxcTypeKind_FirstBuiltin = DxcTypeKind_Void, DxcTypeKind_LastBuiltin = DxcTypeKind_ObjCSel, DxcTypeKind_Complex = 100, DxcTypeKind_Pointer = 101, DxcTypeKind_BlockPointer = 102, DxcTypeKind_LValueReference = 103, DxcTypeKind_RValueReference = 104, DxcTypeKind_Record = 105, DxcTypeKind_Enum = 106, DxcTypeKind_Typedef = 107, DxcTypeKind_ObjCInterface = 108, DxcTypeKind_ObjCObjectPointer = 109, DxcTypeKind_FunctionNoProto = 110, DxcTypeKind_FunctionProto = 111, DxcTypeKind_ConstantArray = 112, DxcTypeKind_Vector = 113, DxcTypeKind_IncompleteArray = 114, DxcTypeKind_VariableArray = 115, DxcTypeKind_DependentSizedArray = 116, DxcTypeKind_MemberPointer = 117 } DxcTypeKind; // Describes the severity of a particular diagnostic. typedef enum DxcDiagnosticSeverity { // A diagnostic that has been suppressed, e.g., by a command-line option. DxcDiagnostic_Ignored = 0, // This diagnostic is a note that should be attached to the previous // (non-note) diagnostic. DxcDiagnostic_Note = 1, // This diagnostic indicates suspicious code that may not be wrong. DxcDiagnostic_Warning = 2, // This diagnostic indicates that the code is ill-formed. DxcDiagnostic_Error = 3, // This diagnostic indicates that the code is ill-formed such that future // parser rec unlikely to produce useful results. DxcDiagnostic_Fatal = 4 } DxcDiagnosticSeverity; // Options to control the display of diagnostics. typedef enum DxcDiagnosticDisplayOptions { // Display the source-location information where the diagnostic was located. DxcDiagnostic_DisplaySourceLocation = 0x01, // If displaying the source-location information of the diagnostic, // also include the column number. DxcDiagnostic_DisplayColumn = 0x02, // If displaying the source-location information of the diagnostic, // also include information about source ranges in a machine-parsable format. DxcDiagnostic_DisplaySourceRanges = 0x04, // Display the option name associated with this diagnostic, if any. DxcDiagnostic_DisplayOption = 0x08, // Display the category number associated with this diagnostic, if any. DxcDiagnostic_DisplayCategoryId = 0x10, // Display the category name associated with this diagnostic, if any. DxcDiagnostic_DisplayCategoryName = 0x20, // Display the severity of the diagnostic message. DxcDiagnostic_DisplaySeverity = 0x200 } DxcDiagnosticDisplayOptions; typedef enum DxcTranslationUnitFlags { // Used to indicate that no special translation-unit options are needed. DxcTranslationUnitFlags_None = 0x0, // Used to indicate that the parser should construct a "detailed" // preprocessing record, including all macro definitions and instantiations. DxcTranslationUnitFlags_DetailedPreprocessingRecord = 0x01, // Used to indicate that the translation unit is incomplete. DxcTranslationUnitFlags_Incomplete = 0x02, // Used to indicate that the translation unit should be built with an // implicit precompiled header for the preamble. DxcTranslationUnitFlags_PrecompiledPreamble = 0x04, // Used to indicate that the translation unit should cache some // code-completion results with each reparse of the source file. DxcTranslationUnitFlags_CacheCompletionResults = 0x08, // Used to indicate that the translation unit will be serialized with // SaveTranslationUnit. DxcTranslationUnitFlags_ForSerialization = 0x10, // DEPRECATED DxcTranslationUnitFlags_CXXChainedPCH = 0x20, // Used to indicate that function/method bodies should be skipped while // parsing. DxcTranslationUnitFlags_SkipFunctionBodies = 0x40, // Used to indicate that brief documentation comments should be // included into the set of code completions returned from this translation // unit. DxcTranslationUnitFlags_IncludeBriefCommentsInCodeCompletion = 0x80, // Used to indicate that compilation should occur on the caller's thread. DxcTranslationUnitFlags_UseCallerThread = 0x800 } DxcTranslationUnitFlags; typedef enum DxcCursorFormatting { DxcCursorFormatting_Default = 0x0, // Default rules, language-insensitive formatting. DxcCursorFormatting_UseLanguageOptions = 0x1, // Language-sensitive formatting. DxcCursorFormatting_SuppressSpecifiers = 0x2, // Supresses type specifiers. DxcCursorFormatting_SuppressTagKeyword = 0x4, // Suppressed tag keyword (eg, 'class'). DxcCursorFormatting_IncludeNamespaceKeyword = 0x8, // Include namespace keyword. } DxcCursorFormatting; enum DxcCursorKind { /* Declarations */ DxcCursor_UnexposedDecl = 1, // A declaration whose specific kind is not exposed via this interface. DxcCursor_StructDecl = 2, // A C or C++ struct. DxcCursor_UnionDecl = 3, // A C or C++ union. DxcCursor_ClassDecl = 4, // A C++ class. DxcCursor_EnumDecl = 5, // An enumeration. DxcCursor_FieldDecl = 6, // A field (in C) or non-static data member (in C++) // in a struct, union, or C++ class. DxcCursor_EnumConstantDecl = 7, // An enumerator constant. DxcCursor_FunctionDecl = 8, // A function. DxcCursor_VarDecl = 9, // A variable. DxcCursor_ParmDecl = 10, // A function or method parameter. DxcCursor_ObjCInterfaceDecl = 11, // An Objective-C interface. DxcCursor_ObjCCategoryDecl = 12, // An Objective-C interface for a category. DxcCursor_ObjCProtocolDecl = 13, // An Objective-C protocol declaration. DxcCursor_ObjCPropertyDecl = 14, // An Objective-C property declaration. DxcCursor_ObjCIvarDecl = 15, // An Objective-C instance variable. DxcCursor_ObjCInstanceMethodDecl = 16, // An Objective-C instance method. DxcCursor_ObjCClassMethodDecl = 17, // An Objective-C class method. DxcCursor_ObjCImplementationDecl = 18, // An Objective-C \@implementation. DxcCursor_ObjCCategoryImplDecl = 19, // An Objective-C \@implementation for a category. DxcCursor_TypedefDecl = 20, // A typedef DxcCursor_CXXMethod = 21, // A C++ class method. DxcCursor_Namespace = 22, // A C++ namespace. DxcCursor_LinkageSpec = 23, // A linkage specification, e.g. 'extern "C"'. DxcCursor_Constructor = 24, // A C++ constructor. DxcCursor_Destructor = 25, // A C++ destructor. DxcCursor_ConversionFunction = 26, // A C++ conversion function. DxcCursor_TemplateTypeParameter = 27, // A C++ template type parameter. DxcCursor_NonTypeTemplateParameter = 28, // A C++ non-type template parameter. DxcCursor_TemplateTemplateParameter = 29, // A C++ template template parameter. DxcCursor_FunctionTemplate = 30, // A C++ function template. DxcCursor_ClassTemplate = 31, // A C++ class template. DxcCursor_ClassTemplatePartialSpecialization = 32, // A C++ class template partial specialization. DxcCursor_NamespaceAlias = 33, // A C++ namespace alias declaration. DxcCursor_UsingDirective = 34, // A C++ using directive. DxcCursor_UsingDeclaration = 35, // A C++ using declaration. DxcCursor_TypeAliasDecl = 36, // A C++ alias declaration DxcCursor_ObjCSynthesizeDecl = 37, // An Objective-C \@synthesize definition. DxcCursor_ObjCDynamicDecl = 38, // An Objective-C \@dynamic definition. DxcCursor_CXXAccessSpecifier = 39, // An access specifier. DxcCursor_FirstDecl = DxcCursor_UnexposedDecl, DxcCursor_LastDecl = DxcCursor_CXXAccessSpecifier, /* References */ DxcCursor_FirstRef = 40, /* Decl references */ DxcCursor_ObjCSuperClassRef = 40, DxcCursor_ObjCProtocolRef = 41, DxcCursor_ObjCClassRef = 42, /** * \brief A reference to a type declaration. * * A type reference occurs anywhere where a type is named but not * declared. For example, given: * * \code * typedef unsigned size_type; * size_type size; * \endcode * * The typedef is a declaration of size_type (DxcCursor_TypedefDecl), * while the type of the variable "size" is referenced. The cursor * referenced by the type of size is the typedef for size_type. */ DxcCursor_TypeRef = 43, // A reference to a type declaration. DxcCursor_CXXBaseSpecifier = 44, DxcCursor_TemplateRef = 45, // A reference to a class template, function template, template // template parameter, or class template partial specialization. DxcCursor_NamespaceRef = 46, // A reference to a namespace or namespace alias. DxcCursor_MemberRef = 47, // A reference to a member of a struct, union, or class that occurs in // some non-expression context, e.g., a designated initializer. /** * \brief A reference to a labeled statement. * * This cursor kind is used to describe the jump to "start_over" in the * goto statement in the following example: * * \code * start_over: * ++counter; * * goto start_over; * \endcode * * A label reference cursor refers to a label statement. */ DxcCursor_LabelRef = 48, // A reference to a labeled statement. // A reference to a set of overloaded functions or function templates // that has not yet been resolved to a specific function or function template. // // An overloaded declaration reference cursor occurs in C++ templates where // a dependent name refers to a function. DxcCursor_OverloadedDeclRef = 49, DxcCursor_VariableRef = 50, // A reference to a variable that occurs in some non-expression // context, e.g., a C++ lambda capture list. DxcCursor_LastRef = DxcCursor_VariableRef, /* Error conditions */ DxcCursor_FirstInvalid = 70, DxcCursor_InvalidFile = 70, DxcCursor_NoDeclFound = 71, DxcCursor_NotImplemented = 72, DxcCursor_InvalidCode = 73, DxcCursor_LastInvalid = DxcCursor_InvalidCode, /* Expressions */ DxcCursor_FirstExpr = 100, /** * \brief An expression whose specific kind is not exposed via this * interface. * * Unexposed expressions have the same operations as any other kind * of expression; one can extract their location information, * spelling, children, etc. However, the specific kind of the * expression is not reported. */ DxcCursor_UnexposedExpr = 100, // An expression whose specific kind is not // exposed via this interface. DxcCursor_DeclRefExpr = 101, // An expression that refers to some value declaration, such as a // function, varible, or enumerator. DxcCursor_MemberRefExpr = 102, // An expression that refers to a member of a struct, union, class, // Objective-C class, etc. DxcCursor_CallExpr = 103, // An expression that calls a function. DxcCursor_ObjCMessageExpr = 104, // An expression that sends a message to an // Objective-C object or class. DxcCursor_BlockExpr = 105, // An expression that represents a block literal. DxcCursor_IntegerLiteral = 106, // An integer literal. DxcCursor_FloatingLiteral = 107, // A floating point number literal. DxcCursor_ImaginaryLiteral = 108, // An imaginary number literal. DxcCursor_StringLiteral = 109, // A string literal. DxcCursor_CharacterLiteral = 110, // A character literal. DxcCursor_ParenExpr = 111, // A parenthesized expression, e.g. "(1)". This AST node is only // formed if full location information is requested. DxcCursor_UnaryOperator = 112, // This represents the unary-expression's // (except sizeof and alignof). DxcCursor_ArraySubscriptExpr = 113, // [C99 6.5.2.1] Array Subscripting. DxcCursor_BinaryOperator = 114, // A builtin binary operation expression such as "x + y" or "x <= y". DxcCursor_CompoundAssignOperator = 115, // Compound assignment such as "+=". DxcCursor_ConditionalOperator = 116, // The ?: ternary operator. DxcCursor_CStyleCastExpr = 117, // An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ // [expr.cast]), which uses the syntax (Type)expr, eg: (int)f. DxcCursor_CompoundLiteralExpr = 118, // [C99 6.5.2.5] DxcCursor_InitListExpr = 119, // Describes an C or C++ initializer list. DxcCursor_AddrLabelExpr = 120, // The GNU address of label extension, representing &&label. DxcCursor_StmtExpr = 121, // This is the GNU Statement Expression extension: ({int X=4; X;}) DxcCursor_GenericSelectionExpr = 122, // Represents a C11 generic selection. /** \brief Implements the GNU __null extension, which is a name for a null * pointer constant that has integral type (e.g., int or long) and is the same * size and alignment as a pointer. * * The __null extension is typically only used by system headers, which define * NULL as __null in C++ rather than using 0 (which is an integer that may not * match the size of a pointer). */ DxcCursor_GNUNullExpr = 123, DxcCursor_CXXStaticCastExpr = 124, // C++'s static_cast<> expression. DxcCursor_CXXDynamicCastExpr = 125, // C++'s dynamic_cast<> expression. DxcCursor_CXXReinterpretCastExpr = 126, // C++'s reinterpret_cast<> expression. DxcCursor_CXXConstCastExpr = 127, // C++'s const_cast<> expression. /** \brief Represents an explicit C++ type conversion that uses "functional" * notion (C++ [expr.type.conv]). * * Example: * \code * x = int(0.5); * \endcode */ DxcCursor_CXXFunctionalCastExpr = 128, DxcCursor_CXXTypeidExpr = 129, // A C++ typeid expression (C++ [expr.typeid]). DxcCursor_CXXBoolLiteralExpr = 130, // [C++ 2.13.5] C++ Boolean Literal. DxcCursor_CXXNullPtrLiteralExpr = 131, // [C++0x 2.14.7] C++ Pointer Literal. DxcCursor_CXXThisExpr = 132, // Represents the "this" expression in C++ DxcCursor_CXXThrowExpr = 133, // [C++ 15] C++ Throw Expression, both 'throw' // and 'throw' assignment-expression. DxcCursor_CXXNewExpr = 134, // A new expression for memory allocation and // constructor calls, e.g: "new CXXNewExpr(foo)". DxcCursor_CXXDeleteExpr = 135, // A delete expression for memory deallocation and destructor calls, // e.g. "delete[] pArray". DxcCursor_UnaryExpr = 136, // A unary expression. DxcCursor_ObjCStringLiteral = 137, // An Objective-C string literal i.e. @"foo". DxcCursor_ObjCEncodeExpr = 138, // An Objective-C \@encode expression. DxcCursor_ObjCSelectorExpr = 139, // An Objective-C \@selector expression. DxcCursor_ObjCProtocolExpr = 140, // An Objective-C \@protocol expression. /** \brief An Objective-C "bridged" cast expression, which casts between * Objective-C pointers and C pointers, transferring ownership in the process. * * \code * NSString *str = (__bridge_transfer NSString *)CFCreateString(); * \endcode */ DxcCursor_ObjCBridgedCastExpr = 141, /** \brief Represents a C++0x pack expansion that produces a sequence of * expressions. * * A pack expansion expression contains a pattern (which itself is an * expression) followed by an ellipsis. For example: * * \code * template<typename F, typename ...Types> * void forward(F f, Types &&...args) { * f(static_cast<Types&&>(args)...); * } * \endcode */ DxcCursor_PackExpansionExpr = 142, /** \brief Represents an expression that computes the length of a parameter * pack. * * \code * template<typename ...Types> * struct count { * static const unsigned value = sizeof...(Types); * }; * \endcode */ DxcCursor_SizeOfPackExpr = 143, /* \brief Represents a C++ lambda expression that produces a local function * object. * * \code * void abssort(float *x, unsigned N) { * std::sort(x, x + N, * [](float a, float b) { * return std::abs(a) < std::abs(b); * }); * } * \endcode */ DxcCursor_LambdaExpr = 144, DxcCursor_ObjCBoolLiteralExpr = 145, // Objective-c Boolean Literal. DxcCursor_ObjCSelfExpr = 146, // Represents the "self" expression in a ObjC method. DxcCursor_LastExpr = DxcCursor_ObjCSelfExpr, /* Statements */ DxcCursor_FirstStmt = 200, /** * \brief A statement whose specific kind is not exposed via this * interface. * * Unexposed statements have the same operations as any other kind of * statement; one can extract their location information, spelling, * children, etc. However, the specific kind of the statement is not * reported. */ DxcCursor_UnexposedStmt = 200, /** \brief A labelled statement in a function. * * This cursor kind is used to describe the "start_over:" label statement in * the following example: * * \code * start_over: * ++counter; * \endcode * */ DxcCursor_LabelStmt = 201, DxcCursor_CompoundStmt = 202, // A group of statements like { stmt stmt }. This cursor kind is used // to describe compound statements, e.g. function bodies. DxcCursor_CaseStmt = 203, // A case statement. DxcCursor_DefaultStmt = 204, // A default statement. DxcCursor_IfStmt = 205, // An if statement DxcCursor_SwitchStmt = 206, // A switch statement. DxcCursor_WhileStmt = 207, // A while statement. DxcCursor_DoStmt = 208, // A do statement. DxcCursor_ForStmt = 209, // A for statement. DxcCursor_GotoStmt = 210, // A goto statement. DxcCursor_IndirectGotoStmt = 211, // An indirect goto statement. DxcCursor_ContinueStmt = 212, // A continue statement. DxcCursor_BreakStmt = 213, // A break statement. DxcCursor_ReturnStmt = 214, // A return statement. DxcCursor_GCCAsmStmt = 215, // A GCC inline assembly statement extension. DxcCursor_AsmStmt = DxcCursor_GCCAsmStmt, DxcCursor_ObjCAtTryStmt = 216, // Objective-C's overall \@try-\@catch-\@finally statement. DxcCursor_ObjCAtCatchStmt = 217, // Objective-C's \@catch statement. DxcCursor_ObjCAtFinallyStmt = 218, // Objective-C's \@finally statement. DxcCursor_ObjCAtThrowStmt = 219, // Objective-C's \@throw statement. DxcCursor_ObjCAtSynchronizedStmt = 220, // Objective-C's \@synchronized statement. DxcCursor_ObjCAutoreleasePoolStmt = 221, // Objective-C's autorelease pool statement. DxcCursor_ObjCForCollectionStmt = 222, // Objective-C's collection statement. DxcCursor_CXXCatchStmt = 223, // C++'s catch statement. DxcCursor_CXXTryStmt = 224, // C++'s try statement. DxcCursor_CXXForRangeStmt = 225, // C++'s for (* : *) statement. DxcCursor_SEHTryStmt = 226, // Windows Structured Exception Handling's try statement. DxcCursor_SEHExceptStmt = 227, // Windows Structured Exception Handling's except statement. DxcCursor_SEHFinallyStmt = 228, // Windows Structured Exception Handling's finally statement. DxcCursor_MSAsmStmt = 229, // A MS inline assembly statement extension. DxcCursor_NullStmt = 230, // The null satement ";": C99 6.8.3p3. DxcCursor_DeclStmt = 231, // Adaptor class for mixing declarations with // statements and expressions. DxcCursor_OMPParallelDirective = 232, // OpenMP parallel directive. DxcCursor_OMPSimdDirective = 233, // OpenMP SIMD directive. DxcCursor_OMPForDirective = 234, // OpenMP for directive. DxcCursor_OMPSectionsDirective = 235, // OpenMP sections directive. DxcCursor_OMPSectionDirective = 236, // OpenMP section directive. DxcCursor_OMPSingleDirective = 237, // OpenMP single directive. DxcCursor_OMPParallelForDirective = 238, // OpenMP parallel for directive. DxcCursor_OMPParallelSectionsDirective = 239, // OpenMP parallel sections directive. DxcCursor_OMPTaskDirective = 240, // OpenMP task directive. DxcCursor_OMPMasterDirective = 241, // OpenMP master directive. DxcCursor_OMPCriticalDirective = 242, // OpenMP critical directive. DxcCursor_OMPTaskyieldDirective = 243, // OpenMP taskyield directive. DxcCursor_OMPBarrierDirective = 244, // OpenMP barrier directive. DxcCursor_OMPTaskwaitDirective = 245, // OpenMP taskwait directive. DxcCursor_OMPFlushDirective = 246, // OpenMP flush directive. DxcCursor_SEHLeaveStmt = 247, // Windows Structured Exception Handling's leave statement. DxcCursor_OMPOrderedDirective = 248, // OpenMP ordered directive. DxcCursor_OMPAtomicDirective = 249, // OpenMP atomic directive. DxcCursor_OMPForSimdDirective = 250, // OpenMP for SIMD directive. DxcCursor_OMPParallelForSimdDirective = 251, // OpenMP parallel for SIMD directive. DxcCursor_OMPTargetDirective = 252, // OpenMP target directive. DxcCursor_OMPTeamsDirective = 253, // OpenMP teams directive. DxcCursor_OMPTaskgroupDirective = 254, // OpenMP taskgroup directive. DxcCursor_OMPCancellationPointDirective = 255, // OpenMP cancellation point directive. DxcCursor_OMPCancelDirective = 256, // OpenMP cancel directive. DxcCursor_LastStmt = DxcCursor_OMPCancelDirective, DxcCursor_TranslationUnit = 300, // Cursor that represents the translation unit itself. /* Attributes */ DxcCursor_FirstAttr = 400, /** * \brief An attribute whose specific kind is not exposed via this * interface. */ DxcCursor_UnexposedAttr = 400, DxcCursor_IBActionAttr = 401, DxcCursor_IBOutletAttr = 402, DxcCursor_IBOutletCollectionAttr = 403, DxcCursor_CXXFinalAttr = 404, DxcCursor_CXXOverrideAttr = 405, DxcCursor_AnnotateAttr = 406, DxcCursor_AsmLabelAttr = 407, DxcCursor_PackedAttr = 408, DxcCursor_PureAttr = 409, DxcCursor_ConstAttr = 410, DxcCursor_NoDuplicateAttr = 411, DxcCursor_CUDAConstantAttr = 412, DxcCursor_CUDADeviceAttr = 413, DxcCursor_CUDAGlobalAttr = 414, DxcCursor_CUDAHostAttr = 415, DxcCursor_CUDASharedAttr = 416, DxcCursor_LastAttr = DxcCursor_CUDASharedAttr, /* Preprocessing */ DxcCursor_PreprocessingDirective = 500, DxcCursor_MacroDefinition = 501, DxcCursor_MacroExpansion = 502, DxcCursor_MacroInstantiation = DxcCursor_MacroExpansion, DxcCursor_InclusionDirective = 503, DxcCursor_FirstPreprocessing = DxcCursor_PreprocessingDirective, DxcCursor_LastPreprocessing = DxcCursor_InclusionDirective, /* Extra Declarations */ /** * \brief A module import declaration. */ DxcCursor_ModuleImportDecl = 600, DxcCursor_FirstExtraDecl = DxcCursor_ModuleImportDecl, DxcCursor_LastExtraDecl = DxcCursor_ModuleImportDecl }; enum DxcCursorKindFlags { DxcCursorKind_None = 0, DxcCursorKind_Declaration = 0x1, DxcCursorKind_Reference = 0x2, DxcCursorKind_Expression = 0x4, DxcCursorKind_Statement = 0x8, DxcCursorKind_Attribute = 0x10, DxcCursorKind_Invalid = 0x20, DxcCursorKind_TranslationUnit = 0x40, DxcCursorKind_Preprocessing = 0x80, DxcCursorKind_Unexposed = 0x100, }; enum DxcCodeCompleteFlags { DxcCodeCompleteFlags_None = 0, DxcCodeCompleteFlags_IncludeMacros = 0x1, DxcCodeCompleteFlags_IncludeCodePatterns = 0x2, DxcCodeCompleteFlags_IncludeBriefComments = 0x4, }; enum DxcCompletionChunkKind { DxcCompletionChunk_Optional = 0, DxcCompletionChunk_TypedText = 1, DxcCompletionChunk_Text = 2, DxcCompletionChunk_Placeholder = 3, DxcCompletionChunk_Informative = 4, DxcCompletionChunk_CurrentParameter = 5, DxcCompletionChunk_LeftParen = 6, DxcCompletionChunk_RightParen = 7, DxcCompletionChunk_LeftBracket = 8, DxcCompletionChunk_RightBracket = 9, DxcCompletionChunk_LeftBrace = 10, DxcCompletionChunk_RightBrace = 11, DxcCompletionChunk_LeftAngle = 12, DxcCompletionChunk_RightAngle = 13, DxcCompletionChunk_Comma = 14, DxcCompletionChunk_ResultType = 15, DxcCompletionChunk_Colon = 16, DxcCompletionChunk_SemiColon = 17, DxcCompletionChunk_Equal = 18, DxcCompletionChunk_HorizontalSpace = 19, DxcCompletionChunk_VerticalSpace = 20, }; struct IDxcCursor; struct IDxcDiagnostic; struct IDxcFile; struct IDxcInclusion; struct IDxcIntelliSense; struct IDxcIndex; struct IDxcSourceLocation; struct IDxcSourceRange; struct IDxcToken; struct IDxcTranslationUnit; struct IDxcType; struct IDxcUnsavedFile; struct IDxcCodeCompleteResults; struct IDxcCompletionResult; struct IDxcCompletionString; CROSS_PLATFORM_UUIDOF(IDxcCursor, "1467b985-288d-4d2a-80c1-ef89c42c40bc") struct IDxcCursor : public IUnknown { virtual HRESULT STDMETHODCALLTYPE GetExtent(_Outptr_result_nullonfailure_ IDxcSourceRange **pRange) = 0; virtual HRESULT STDMETHODCALLTYPE GetLocation(_Outptr_result_nullonfailure_ IDxcSourceLocation **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetKind(_Out_ DxcCursorKind *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetKindFlags(_Out_ DxcCursorKindFlags *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetSemanticParent(_Outptr_result_nullonfailure_ IDxcCursor **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetLexicalParent(_Outptr_result_nullonfailure_ IDxcCursor **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetCursorType(_Outptr_result_nullonfailure_ IDxcType **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetNumArguments(_Out_ int *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetArgumentAt( int index, _Outptr_result_nullonfailure_ IDxcCursor **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetReferencedCursor(_Outptr_result_nullonfailure_ IDxcCursor **pResult) = 0; /// <summary>For a cursor that is either a reference to or a declaration of /// some entity, retrieve a cursor that describes the definition of that /// entity.</summary> <remarks>Some entities can be declared multiple times /// within a translation unit, but only one of those declarations can also be /// a definition.</remarks> <returns>A cursor to the definition of this /// entity; nullptr if there is no definition in this translation /// unit.</returns> virtual HRESULT STDMETHODCALLTYPE GetDefinitionCursor(_Outptr_result_nullonfailure_ IDxcCursor **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE FindReferencesInFile(_In_ IDxcFile *file, unsigned skip, unsigned top, _Out_ unsigned *pResultLength, _Outptr_result_buffer_maybenull_(*pResultLength) IDxcCursor ***pResult) = 0; /// <summary>Gets the name for the entity references by the cursor, e.g. foo /// for an 'int foo' variable.</summary> virtual HRESULT STDMETHODCALLTYPE GetSpelling(_Outptr_result_maybenull_ LPSTR *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE IsEqualTo(_In_ IDxcCursor *other, _Out_ BOOL *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE IsNull(_Out_ BOOL *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE IsDefinition(_Out_ BOOL *pResult) = 0; /// <summary>Gets the display name for the cursor, including e.g. parameter /// types for a function.</summary> virtual HRESULT STDMETHODCALLTYPE GetDisplayName(_Out_ BSTR *pResult) = 0; /// <summary>Gets the qualified name for the symbol the cursor refers /// to.</summary> virtual HRESULT STDMETHODCALLTYPE GetQualifiedName( BOOL includeTemplateArgs, _Outptr_result_maybenull_ BSTR *pResult) = 0; /// <summary>Gets a name for the cursor, applying the specified formatting /// flags.</summary> virtual HRESULT STDMETHODCALLTYPE GetFormattedName(DxcCursorFormatting formatting, _Outptr_result_maybenull_ BSTR *pResult) = 0; /// <summary>Gets children in pResult up to top elements.</summary> virtual HRESULT STDMETHODCALLTYPE GetChildren(unsigned skip, unsigned top, _Out_ unsigned *pResultLength, _Outptr_result_buffer_maybenull_(*pResultLength) IDxcCursor ***pResult) = 0; /// <summary>Gets the cursor following a location within a compound /// cursor.</summary> virtual HRESULT STDMETHODCALLTYPE GetSnappedChild(_In_ IDxcSourceLocation *location, _Outptr_result_maybenull_ IDxcCursor **pResult) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcDiagnostic, "4f76b234-3659-4d33-99b0-3b0db994b564") struct IDxcDiagnostic : public IUnknown { virtual HRESULT STDMETHODCALLTYPE FormatDiagnostic(DxcDiagnosticDisplayOptions options, _Outptr_result_maybenull_ LPSTR *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetSeverity(_Out_ DxcDiagnosticSeverity *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetLocation(_Outptr_result_nullonfailure_ IDxcSourceLocation **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetSpelling(_Outptr_result_maybenull_ LPSTR *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetCategoryText(_Outptr_result_maybenull_ LPSTR *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetNumRanges(_Out_ unsigned *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetRangeAt(unsigned index, _Outptr_result_nullonfailure_ IDxcSourceRange **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetNumFixIts(_Out_ unsigned *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetFixItAt(unsigned index, _Outptr_result_nullonfailure_ IDxcSourceRange **pReplacementRange, _Outptr_result_maybenull_ LPSTR *pText) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcFile, "bb2fca9e-1478-47ba-b08c-2c502ada4895") struct IDxcFile : public IUnknown { /// <summary>Gets the file name for this file.</summary> virtual HRESULT STDMETHODCALLTYPE GetName(_Outptr_result_maybenull_ LPSTR *pResult) = 0; /// <summary>Checks whether this file is equal to the other specified /// file.</summary> virtual HRESULT STDMETHODCALLTYPE IsEqualTo(_In_ IDxcFile *other, _Out_ BOOL *pResult) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcInclusion, "0c364d65-df44-4412-888e-4e552fc5e3d6") struct IDxcInclusion : public IUnknown { virtual HRESULT STDMETHODCALLTYPE GetIncludedFile(_Outptr_result_nullonfailure_ IDxcFile **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetStackLength(_Out_ unsigned *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetStackItem(unsigned index, _Outptr_result_nullonfailure_ IDxcSourceLocation **pResult) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcIntelliSense, "b1f99513-46d6-4112-8169-dd0d6053f17d") struct IDxcIntelliSense : public IUnknown { virtual HRESULT STDMETHODCALLTYPE CreateIndex(_Outptr_result_nullonfailure_ IDxcIndex **index) = 0; virtual HRESULT STDMETHODCALLTYPE GetNullLocation( _Outptr_result_nullonfailure_ IDxcSourceLocation **location) = 0; virtual HRESULT STDMETHODCALLTYPE GetNullRange(_Outptr_result_nullonfailure_ IDxcSourceRange **location) = 0; virtual HRESULT STDMETHODCALLTYPE GetRange(_In_ IDxcSourceLocation *start, _In_ IDxcSourceLocation *end, _Outptr_result_nullonfailure_ IDxcSourceRange **location) = 0; virtual HRESULT STDMETHODCALLTYPE GetDefaultDiagnosticDisplayOptions( _Out_ DxcDiagnosticDisplayOptions *pValue) = 0; virtual HRESULT STDMETHODCALLTYPE GetDefaultEditingTUOptions(_Out_ DxcTranslationUnitFlags *pValue) = 0; virtual HRESULT STDMETHODCALLTYPE CreateUnsavedFile( _In_ LPCSTR fileName, _In_ LPCSTR contents, unsigned contentLength, _Outptr_result_nullonfailure_ IDxcUnsavedFile **pResult) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcIndex, "937824a0-7f5a-4815-9ba7-7fc0424f4173") struct IDxcIndex : public IUnknown { virtual HRESULT STDMETHODCALLTYPE SetGlobalOptions(DxcGlobalOptions options) = 0; virtual HRESULT STDMETHODCALLTYPE GetGlobalOptions(_Out_ DxcGlobalOptions *options) = 0; virtual HRESULT STDMETHODCALLTYPE ParseTranslationUnit( _In_z_ const char *source_filename, _In_count_(num_command_line_args) const char *const *command_line_args, int num_command_line_args, _In_count_(num_unsaved_files) IDxcUnsavedFile **unsaved_files, unsigned num_unsaved_files, DxcTranslationUnitFlags options, _Out_ IDxcTranslationUnit **pTranslationUnit) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcSourceLocation, "8e7ddf1c-d7d3-4d69-b286-85fccba1e0cf") struct IDxcSourceLocation : public IUnknown { virtual HRESULT STDMETHODCALLTYPE IsEqualTo(_In_ IDxcSourceLocation *other, _Out_ BOOL *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetSpellingLocation( _Outptr_opt_ IDxcFile **pFile, _Out_opt_ unsigned *pLine, _Out_opt_ unsigned *pCol, _Out_opt_ unsigned *pOffset) = 0; virtual HRESULT STDMETHODCALLTYPE IsNull(_Out_ BOOL *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetPresumedLocation(_Outptr_opt_ LPSTR *pFilename, _Out_opt_ unsigned *pLine, _Out_opt_ unsigned *pCol) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcSourceRange, "f1359b36-a53f-4e81-b514-b6b84122a13f") struct IDxcSourceRange : public IUnknown { virtual HRESULT STDMETHODCALLTYPE IsNull(_Out_ BOOL *pValue) = 0; virtual HRESULT STDMETHODCALLTYPE GetStart(_Out_ IDxcSourceLocation **pValue) = 0; virtual HRESULT STDMETHODCALLTYPE GetEnd(_Out_ IDxcSourceLocation **pValue) = 0; virtual HRESULT STDMETHODCALLTYPE GetOffsets(_Out_ unsigned *startOffset, _Out_ unsigned *endOffset) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcToken, "7f90b9ff-a275-4932-97d8-3cfd234482a2") struct IDxcToken : public IUnknown { virtual HRESULT STDMETHODCALLTYPE GetKind(_Out_ DxcTokenKind *pValue) = 0; virtual HRESULT STDMETHODCALLTYPE GetLocation(_Out_ IDxcSourceLocation **pValue) = 0; virtual HRESULT STDMETHODCALLTYPE GetExtent(_Out_ IDxcSourceRange **pValue) = 0; virtual HRESULT STDMETHODCALLTYPE GetSpelling(_Out_ LPSTR *pValue) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcTranslationUnit, "9677dee0-c0e5-46a1-8b40-3db3168be63d") struct IDxcTranslationUnit : public IUnknown { virtual HRESULT STDMETHODCALLTYPE GetCursor(_Out_ IDxcCursor **pCursor) = 0; virtual HRESULT STDMETHODCALLTYPE Tokenize(_In_ IDxcSourceRange *range, _Outptr_result_buffer_maybenull_(*pTokenCount) IDxcToken ***pTokens, _Out_ unsigned *pTokenCount) = 0; virtual HRESULT STDMETHODCALLTYPE GetLocation(_In_ IDxcFile *file, unsigned line, unsigned column, _Outptr_result_nullonfailure_ IDxcSourceLocation **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetNumDiagnostics(_Out_ unsigned *pValue) = 0; virtual HRESULT STDMETHODCALLTYPE GetDiagnostic(unsigned index, _Outptr_result_nullonfailure_ IDxcDiagnostic **pValue) = 0; virtual HRESULT STDMETHODCALLTYPE GetFile(_In_ const char *name, _Outptr_result_nullonfailure_ IDxcFile **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetFileName(_Outptr_result_maybenull_ LPSTR *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE Reparse(_In_count_(num_unsaved_files) IDxcUnsavedFile **unsaved_files, unsigned num_unsaved_files) = 0; virtual HRESULT STDMETHODCALLTYPE GetCursorForLocation(_In_ IDxcSourceLocation *location, _Outptr_result_nullonfailure_ IDxcCursor **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetLocationForOffset( _In_ IDxcFile *file, unsigned offset, _Outptr_result_nullonfailure_ IDxcSourceLocation **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetSkippedRanges( _In_ IDxcFile *file, _Out_ unsigned *pResultCount, _Outptr_result_buffer_(*pResultCount) IDxcSourceRange ***pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetDiagnosticDetails(unsigned index, DxcDiagnosticDisplayOptions options, _Out_ unsigned *errorCode, _Out_ unsigned *errorLine, _Out_ unsigned *errorColumn, _Out_ BSTR *errorFile, _Out_ unsigned *errorOffset, _Out_ unsigned *errorLength, _Out_ BSTR *errorMessage) = 0; virtual HRESULT STDMETHODCALLTYPE GetInclusionList( _Out_ unsigned *pResultCount, _Outptr_result_buffer_(*pResultCount) IDxcInclusion ***pResult) = 0; virtual HRESULT STDMETHODCALLTYPE CodeCompleteAt( _In_ const char *fileName, unsigned line, unsigned column, _In_ IDxcUnsavedFile **pUnsavedFiles, unsigned numUnsavedFiles, _In_ DxcCodeCompleteFlags options, _Outptr_result_nullonfailure_ IDxcCodeCompleteResults **pResult) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcType, "2ec912fd-b144-4a15-ad0d-1c5439c81e46") struct IDxcType : public IUnknown { virtual HRESULT STDMETHODCALLTYPE GetSpelling(_Outptr_result_z_ LPSTR *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE IsEqualTo(_In_ IDxcType *other, _Out_ BOOL *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetKind(_Out_ DxcTypeKind *pResult) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcUnsavedFile, "8ec00f98-07d0-4e60-9d7c-5a50b5b0017f") struct IDxcUnsavedFile : public IUnknown { virtual HRESULT STDMETHODCALLTYPE GetFileName(_Outptr_result_z_ LPSTR *pFileName) = 0; virtual HRESULT STDMETHODCALLTYPE GetContents(_Outptr_result_z_ LPSTR *pContents) = 0; virtual HRESULT STDMETHODCALLTYPE GetLength(_Out_ unsigned *pLength) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcCodeCompleteResults, "1E06466A-FD8B-45F3-A78F-8A3F76EBB552") struct IDxcCodeCompleteResults : public IUnknown { virtual HRESULT STDMETHODCALLTYPE GetNumResults(_Out_ unsigned *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetResultAt(unsigned index, _Outptr_result_nullonfailure_ IDxcCompletionResult **pResult) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcCompletionResult, "943C0588-22D0-4784-86FC-701F802AC2B6") struct IDxcCompletionResult : public IUnknown { virtual HRESULT STDMETHODCALLTYPE GetCursorKind(_Out_ DxcCursorKind *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetCompletionString( _Outptr_result_nullonfailure_ IDxcCompletionString **pResult) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcCompletionString, "06B51E0F-A605-4C69-A110-CD6E14B58EEC") struct IDxcCompletionString : public IUnknown { virtual HRESULT STDMETHODCALLTYPE GetNumCompletionChunks(_Out_ unsigned *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetCompletionChunkKind( unsigned chunkNumber, _Out_ DxcCompletionChunkKind *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetCompletionChunkText(unsigned chunkNumber, _Out_ LPSTR *pResult) = 0; }; // Fun fact: 'extern' is required because const is by default static in C++, so // CLSID_DxcIntelliSense is not visible externally (this is OK in C, since const // is not by default static in C) #ifdef _MSC_VER #define CLSID_SCOPE __declspec(selectany) extern #else #define CLSID_SCOPE #endif CLSID_SCOPE const CLSID CLSID_DxcIntelliSense = {/* 3047833c-d1c0-4b8e-9d40-102878605985 */ 0x3047833c, 0xd1c0, 0x4b8e, {0x9d, 0x40, 0x10, 0x28, 0x78, 0x60, 0x59, 0x85}}; #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/dxc/dxcpix.h
/////////////////////////////////////////////////////////////////////////////// // // // dxcpix.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides declarations for the DirectX Compiler API with pix debugging. // // // /////////////////////////////////////////////////////////////////////////////// #ifndef __DXC_PIX__ #define __DXC_PIX__ #include "dxc/dxcapi.h" #ifdef _WIN32 #include "objidl.h" #endif struct __declspec(uuid("199d8c13-d312-4197-a2c1-07a532999727")) IDxcPixType : public IUnknown { virtual STDMETHODIMP GetName(_Outptr_result_z_ BSTR *Name) = 0; virtual STDMETHODIMP GetSizeInBits(_Out_ DWORD *GetSizeInBits) = 0; virtual STDMETHODIMP UnAlias(_COM_Outptr_ IDxcPixType **ppBaseType) = 0; }; struct __declspec(uuid("d9df2c8b-2773-466d-9bc2-d848d8496bf6")) IDxcPixConstType : public IDxcPixType {}; struct __declspec(uuid("7bfca9c0-1ed0-429c-9dc2-c75597d821d2")) IDxcPixTypedefType : public IDxcPixType {}; struct __declspec(uuid("246e1652-ed2a-4ffc-a949-43bf63750ee5")) IDxcPixScalarType : public IDxcPixType {}; struct __declspec(uuid("9ba0d9d3-457b-426f-8019-9f3849982aa2")) IDxcPixArrayType : public IDxcPixType { virtual STDMETHODIMP GetNumElements(_Out_ DWORD *ppNumElements) = 0; virtual STDMETHODIMP GetIndexedType(_COM_Outptr_ IDxcPixType **ppElementType) = 0; virtual STDMETHODIMP GetElementType(_COM_Outptr_ IDxcPixType **ppElementType) = 0; }; struct __declspec(uuid("6c707d08-7995-4a84-bae5-e6d8291f3b78")) IDxcPixStructField0 : public IUnknown { virtual STDMETHODIMP GetName(_Outptr_result_z_ BSTR *Name) = 0; virtual STDMETHODIMP GetType(_COM_Outptr_ IDxcPixType **ppType) = 0; virtual STDMETHODIMP GetOffsetInBits(_Out_ DWORD *pOffsetInBits) = 0; }; struct __declspec(uuid("de45597c-5869-4f97-a77b-d6650b9a16cf")) IDxcPixStructField : public IUnknown { virtual STDMETHODIMP GetName(_Outptr_result_z_ BSTR *Name) = 0; virtual STDMETHODIMP GetType(_COM_Outptr_ IDxcPixType **ppType) = 0; virtual STDMETHODIMP GetOffsetInBits(_Out_ DWORD *pOffsetInBits) = 0; virtual STDMETHODIMP GetFieldSizeInBits(_Out_ DWORD *pFieldSizeInBits) = 0; }; struct __declspec(uuid("24c08c44-684b-4b1c-b41b-f8772383d074")) IDxcPixStructType : public IDxcPixType { virtual STDMETHODIMP GetNumFields(_Out_ DWORD *ppNumFields) = 0; virtual STDMETHODIMP GetFieldByIndex(DWORD dwIndex, _COM_Outptr_ IDxcPixStructField **ppField) = 0; virtual STDMETHODIMP GetFieldByName(_In_ LPCWSTR lpName, _COM_Outptr_ IDxcPixStructField **ppField) = 0; }; struct __declspec(uuid("7409f40c-dccb-41aa-bb42-1c95bbf7562f")) IDxcPixStructType2 : public IDxcPixStructType { virtual STDMETHODIMP GetBaseType(_COM_Outptr_ IDxcPixType **ppType) = 0; }; struct __declspec(uuid("74d522f5-16c4-40cb-867b-4b4149e3db0e")) IDxcPixDxilStorage : public IUnknown { virtual STDMETHODIMP AccessField(_In_ LPCWSTR Name, _COM_Outptr_ IDxcPixDxilStorage **ppResult) = 0; virtual STDMETHODIMP Index(_In_ DWORD Index, _COM_Outptr_ IDxcPixDxilStorage **ppResult) = 0; virtual STDMETHODIMP GetRegisterNumber(_Out_ DWORD *pRegNum) = 0; virtual STDMETHODIMP GetIsAlive() = 0; virtual STDMETHODIMP GetType(_COM_Outptr_ IDxcPixType **ppType) = 0; }; struct __declspec(uuid("2f954b30-61a7-4348-95b1-2db356a75cde")) IDxcPixVariable : public IUnknown { virtual STDMETHODIMP GetName(_Outptr_result_z_ BSTR *Name) = 0; virtual STDMETHODIMP GetType(_COM_Outptr_ IDxcPixType **ppType) = 0; virtual STDMETHODIMP GetStorage(_COM_Outptr_ IDxcPixDxilStorage **ppStorage) = 0; }; struct __declspec(uuid("c59d302f-34a2-4fe5-9646-32ce7a52d03f")) IDxcPixDxilLiveVariables : public IUnknown { virtual STDMETHODIMP GetCount(_Out_ DWORD *dwSize) = 0; virtual STDMETHODIMP GetVariableByIndex(_In_ DWORD Index, _COM_Outptr_ IDxcPixVariable **ppVariable) = 0; virtual STDMETHODIMP GetVariableByName(_In_ LPCWSTR Name, _COM_Outptr_ IDxcPixVariable **ppVariable) = 0; }; struct __declspec(uuid("eb71f85e-8542-44b5-87da-9d76045a1910")) IDxcPixDxilInstructionOffsets : public IUnknown { virtual STDMETHODIMP_(DWORD) GetCount() = 0; virtual STDMETHODIMP_(DWORD) GetOffsetByIndex(_In_ DWORD Index) = 0; }; struct __declspec(uuid("761c833d-e7b8-4624-80f8-3a3fb4146342")) IDxcPixDxilSourceLocations : public IUnknown { virtual STDMETHODIMP_(DWORD) GetCount() = 0; virtual STDMETHODIMP_(DWORD) GetLineNumberByIndex(_In_ DWORD Index) = 0; virtual STDMETHODIMP_(DWORD) GetColumnByIndex(_In_ DWORD Index) = 0; virtual STDMETHODIMP GetFileNameByIndex(_In_ DWORD Index, _Outptr_result_z_ BSTR *Name) = 0; }; struct __declspec(uuid("b875638e-108a-4d90-a53a-68d63773cb38")) IDxcPixDxilDebugInfo : public IUnknown { virtual STDMETHODIMP GetLiveVariablesAt( _In_ DWORD InstructionOffset, _COM_Outptr_ IDxcPixDxilLiveVariables **ppLiveVariables) = 0; virtual STDMETHODIMP IsVariableInRegister(_In_ DWORD InstructionOffset, _In_ const wchar_t *VariableName) = 0; virtual STDMETHODIMP GetFunctionName(_In_ DWORD InstructionOffset, _Outptr_result_z_ BSTR *ppFunctionName) = 0; virtual STDMETHODIMP GetStackDepth(_In_ DWORD InstructionOffset, _Out_ DWORD *StackDepth) = 0; virtual STDMETHODIMP InstructionOffsetsFromSourceLocation( _In_ const wchar_t *FileName, _In_ DWORD SourceLine, _In_ DWORD SourceColumn, _COM_Outptr_ IDxcPixDxilInstructionOffsets **ppOffsets) = 0; virtual STDMETHODIMP SourceLocationsFromInstructionOffset( _In_ DWORD InstructionOffset, _COM_Outptr_ IDxcPixDxilSourceLocations **ppSourceLocations) = 0; }; struct __declspec(uuid("61b16c95-8799-4ed8-bdb0-3b6c08a141b4")) IDxcPixCompilationInfo : public IUnknown { virtual STDMETHODIMP GetSourceFile(_In_ DWORD SourceFileOrdinal, _Outptr_result_z_ BSTR *pSourceName, _Outptr_result_z_ BSTR *pSourceContents) = 0; virtual STDMETHODIMP GetArguments(_Outptr_result_z_ BSTR *pArguments) = 0; virtual STDMETHODIMP GetMacroDefinitions(_Outptr_result_z_ BSTR *pMacroDefinitions) = 0; virtual STDMETHODIMP GetEntryPointFile(_Outptr_result_z_ BSTR *pEntryPointFile) = 0; virtual STDMETHODIMP GetHlslTarget(_Outptr_result_z_ BSTR *pHlslTarget) = 0; virtual STDMETHODIMP GetEntryPoint(_Outptr_result_z_ BSTR *pEntryPoint) = 0; }; struct __declspec(uuid("9c2a040d-8068-44ec-8c68-8bfef1b43789")) IDxcPixDxilDebugInfoFactory : public IUnknown { virtual STDMETHODIMP NewDxcPixDxilDebugInfo( _COM_Outptr_ IDxcPixDxilDebugInfo **ppDxilDebugInfo) = 0; virtual STDMETHODIMP NewDxcPixCompilationInfo( _COM_Outptr_ IDxcPixCompilationInfo **ppCompilationInfo) = 0; }; #ifndef CLSID_SCOPE #ifdef _MSC_VER #define CLSID_SCOPE __declspec(selectany) extern #else #define CLSID_SCOPE #endif #endif // !CLSID_SCOPE CLSID_SCOPE const CLSID CLSID_DxcPixDxilDebugger = {/* a712b622-5af7-4c77-a965-c83ac1a5d8bc */ 0xa712b622, 0x5af7, 0x4c77, {0xa9, 0x65, 0xc8, 0x3a, 0xc1, 0xa5, 0xd8, 0xbc}}; #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/dxc/dxcdxrfallbackcompiler.h
/////////////////////////////////////////////////////////////////////////////// // // // dxcapi.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides declarations for the DirectX Compiler API entry point. // // // /////////////////////////////////////////////////////////////////////////////// #ifndef __DXC_DXR_FALLBACK_COMPILER_API__ #define __DXC_DXR_FALLBACK_COMPILER_API__ #include "dxcapi.h" enum class ShaderType : unsigned int { Raygen, AnyHit, ClosestHit, Intersection, Miss, Callable, Lib, }; struct DxcShaderInfo { UINT32 Identifier; UINT32 StackSize; ShaderType Type; }; struct DxcShaderBytecode { LPBYTE pData; UINT32 Size; }; struct DxcExportDesc { LPCWSTR ExportToRename; LPCWSTR ExportName; }; struct __declspec(uuid("76bb3c85-006d-4b72-9e10-63cd97df57f0")) IDxcDxrFallbackCompiler : public IUnknown { // If set to true then shaders not listed in pShaderNames in Compile() but // called by shaders in pShaderNames are added to the final computer shader. // Otherwise these are considered errors. This is intended for testing // purposes. virtual HRESULT STDMETHODCALLTYPE SetFindCalledShaders(bool val) = 0; virtual HRESULT STDMETHODCALLTYPE SetDebugOutput(int val) = 0; virtual HRESULT STDMETHODCALLTYPE RenameAndLink( DxcShaderBytecode *pLibs, UINT32 libCount, DxcExportDesc *pExports, UINT32 ExportCount, IDxcOperationResult **ppResult) = 0; virtual HRESULT STDMETHODCALLTYPE PatchShaderBindingTables( const LPCWSTR pEntryName, DxcShaderBytecode *pShaderBytecode, void *pShaderInfo, IDxcOperationResult **ppResult) = 0; // Compiles libs together to create a raytracing compute shader. One of the // libs should be the fallback implementation lib that defines functions like // Fallback_TraceRay(), Fallback_ReportHit(), etc. Fallback_TraceRay() should // be one of the shader names so that it gets included in the compile. virtual HRESULT STDMETHODCALLTYPE Compile( DxcShaderBytecode *pLibs, // Array of libraries containing shaders UINT32 libCount, // Number of libraries containing shaders const LPCWSTR *pShaderNames, // Array of shader names to compile DxcShaderInfo *pShaderInfo, // Array of shaderInfo corresponding to pShaderNames UINT32 shaderCount, // Number of shaders to compile UINT32 maxAttributeSize, IDxcOperationResult * *ppResult // Compiler output status, buffer, and errors ) = 0; virtual HRESULT STDMETHODCALLTYPE Link( const LPCWSTR pEntryName, // Name of entry function, null if compiling a collection IDxcBlob **pLibs, // Array of libraries containing shaders UINT32 libCount, // Number of libraries containing shaders const LPCWSTR *pShaderNames, // Array of shader names to compile DxcShaderInfo *pShaderInfo, // Array of shaderInfo corresponding to pShaderNames UINT32 shaderCount, // Number of shaders to compile UINT32 maxAttributeSize, UINT32 stackSizeInBytes, // Continuation stack size. Use 0 for default. IDxcOperationResult * *ppResult // Compiler output status, buffer, and errors ) = 0; }; // Note: __declspec(selectany) requires 'extern' // On Linux __declspec(selectany) is removed and using 'extern' results in link // error. #ifdef _MSC_VER #define CLSID_SCOPE __declspec(selectany) extern #else #define CLSID_SCOPE #endif // {76bb3c85-006d-4b72-9e10-63cd97df57f0} CLSID_SCOPE const GUID CLSID_DxcDxrFallbackCompiler = { 0x76bb3c85, 0x006d, 0x4b72, {0x9e, 0x10, 0x63, 0xcd, 0x97, 0xdf, 0x57, 0xf0}}; typedef HRESULT(__stdcall *DxcCreateDxrFallbackCompilerProc)(REFCLSID rclsid, REFIID riid, LPVOID *ppv); #endif
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/dxc/HlslIntrinsicOp.h
// HlslIntrinsicOp.h - Generated by hctgen.py // DO NOT MODIFY!!! // Changes to this code are made in gen_intrin_main.txt #pragma once namespace hlsl { enum class IntrinsicOp { IOP_AcceptHitAndEndSearch, IOP_AddUint64, IOP_AllMemoryBarrier, IOP_AllMemoryBarrierWithGroupSync, IOP_AllocateRayQuery, IOP_Barrier, IOP_CallShader, IOP_CheckAccessFullyMapped, IOP_CreateResourceFromHeap, IOP_D3DCOLORtoUBYTE4, IOP_DeviceMemoryBarrier, IOP_DeviceMemoryBarrierWithGroupSync, IOP_DispatchMesh, IOP_DispatchRaysDimensions, IOP_DispatchRaysIndex, IOP_EvaluateAttributeAtSample, IOP_EvaluateAttributeCentroid, IOP_EvaluateAttributeSnapped, IOP_GeometryIndex, IOP_GetAttributeAtVertex, IOP_GetRemainingRecursionLevels, IOP_GetRenderTargetSampleCount, IOP_GetRenderTargetSamplePosition, IOP_GroupMemoryBarrier, IOP_GroupMemoryBarrierWithGroupSync, IOP_HitKind, IOP_IgnoreHit, IOP_InstanceID, IOP_InstanceIndex, IOP_InterlockedAdd, IOP_InterlockedAnd, IOP_InterlockedCompareExchange, IOP_InterlockedCompareExchangeFloatBitwise, IOP_InterlockedCompareStore, IOP_InterlockedCompareStoreFloatBitwise, IOP_InterlockedExchange, IOP_InterlockedMax, IOP_InterlockedMin, IOP_InterlockedOr, IOP_InterlockedXor, IOP_IsHelperLane, IOP_NonUniformResourceIndex, IOP_ObjectRayDirection, IOP_ObjectRayOrigin, IOP_ObjectToWorld, IOP_ObjectToWorld3x4, IOP_ObjectToWorld4x3, IOP_PrimitiveIndex, IOP_Process2DQuadTessFactorsAvg, IOP_Process2DQuadTessFactorsMax, IOP_Process2DQuadTessFactorsMin, IOP_ProcessIsolineTessFactors, IOP_ProcessQuadTessFactorsAvg, IOP_ProcessQuadTessFactorsMax, IOP_ProcessQuadTessFactorsMin, IOP_ProcessTriTessFactorsAvg, IOP_ProcessTriTessFactorsMax, IOP_ProcessTriTessFactorsMin, IOP_QuadAll, IOP_QuadAny, IOP_QuadReadAcrossDiagonal, IOP_QuadReadAcrossX, IOP_QuadReadAcrossY, IOP_QuadReadLaneAt, IOP_RayFlags, IOP_RayTCurrent, IOP_RayTMin, IOP_ReportHit, IOP_SetMeshOutputCounts, IOP_TraceRay, IOP_WaveActiveAllEqual, IOP_WaveActiveAllTrue, IOP_WaveActiveAnyTrue, IOP_WaveActiveBallot, IOP_WaveActiveBitAnd, IOP_WaveActiveBitOr, IOP_WaveActiveBitXor, IOP_WaveActiveCountBits, IOP_WaveActiveMax, IOP_WaveActiveMin, IOP_WaveActiveProduct, IOP_WaveActiveSum, IOP_WaveGetLaneCount, IOP_WaveGetLaneIndex, IOP_WaveIsFirstLane, IOP_WaveMatch, IOP_WaveMultiPrefixBitAnd, IOP_WaveMultiPrefixBitOr, IOP_WaveMultiPrefixBitXor, IOP_WaveMultiPrefixCountBits, IOP_WaveMultiPrefixProduct, IOP_WaveMultiPrefixSum, IOP_WavePrefixCountBits, IOP_WavePrefixProduct, IOP_WavePrefixSum, IOP_WaveReadLaneAt, IOP_WaveReadLaneFirst, IOP_WorldRayDirection, IOP_WorldRayOrigin, IOP_WorldToObject, IOP_WorldToObject3x4, IOP_WorldToObject4x3, IOP_abort, IOP_abs, IOP_acos, IOP_all, IOP_and, IOP_any, IOP_asdouble, IOP_asfloat, IOP_asfloat16, IOP_asin, IOP_asint, IOP_asint16, IOP_asuint, IOP_asuint16, IOP_atan, IOP_atan2, IOP_ceil, IOP_clamp, IOP_clip, IOP_cos, IOP_cosh, IOP_countbits, IOP_cross, IOP_ddx, IOP_ddx_coarse, IOP_ddx_fine, IOP_ddy, IOP_ddy_coarse, IOP_ddy_fine, IOP_degrees, IOP_determinant, IOP_distance, IOP_dot, IOP_dot2add, IOP_dot4add_i8packed, IOP_dot4add_u8packed, IOP_dst, IOP_exp, IOP_exp2, IOP_f16tof32, IOP_f32tof16, IOP_faceforward, IOP_firstbithigh, IOP_firstbitlow, IOP_floor, IOP_fma, IOP_fmod, IOP_frac, IOP_frexp, IOP_fwidth, IOP_isfinite, IOP_isinf, IOP_isnan, IOP_ldexp, IOP_length, IOP_lerp, IOP_lit, IOP_log, IOP_log10, IOP_log2, IOP_mad, IOP_max, IOP_min, IOP_modf, IOP_msad4, IOP_mul, IOP_normalize, IOP_or, IOP_pack_clamp_s8, IOP_pack_clamp_u8, IOP_pack_s8, IOP_pack_u8, IOP_pow, IOP_printf, IOP_radians, IOP_rcp, IOP_reflect, IOP_refract, IOP_reversebits, IOP_round, IOP_rsqrt, IOP_saturate, IOP_select, IOP_sign, IOP_sin, IOP_sincos, IOP_sinh, IOP_smoothstep, IOP_source_mark, IOP_sqrt, IOP_step, IOP_tan, IOP_tanh, IOP_tex1D, IOP_tex1Dbias, IOP_tex1Dgrad, IOP_tex1Dlod, IOP_tex1Dproj, IOP_tex2D, IOP_tex2Dbias, IOP_tex2Dgrad, IOP_tex2Dlod, IOP_tex2Dproj, IOP_tex3D, IOP_tex3Dbias, IOP_tex3Dgrad, IOP_tex3Dlod, IOP_tex3Dproj, IOP_texCUBE, IOP_texCUBEbias, IOP_texCUBEgrad, IOP_texCUBElod, IOP_texCUBEproj, IOP_transpose, IOP_trunc, IOP_unpack_s8s16, IOP_unpack_s8s32, IOP_unpack_u8u16, IOP_unpack_u8u32, #ifdef ENABLE_SPIRV_CODEGEN IOP_VkRawBufferLoad, #endif // ENABLE_SPIRV_CODEGEN #ifdef ENABLE_SPIRV_CODEGEN IOP_VkRawBufferStore, #endif // ENABLE_SPIRV_CODEGEN #ifdef ENABLE_SPIRV_CODEGEN IOP_VkReadClock, #endif // ENABLE_SPIRV_CODEGEN #ifdef ENABLE_SPIRV_CODEGEN IOP_Vkext_execution_mode, #endif // ENABLE_SPIRV_CODEGEN #ifdef ENABLE_SPIRV_CODEGEN IOP_Vkext_execution_mode_id, #endif // ENABLE_SPIRV_CODEGEN MOP_Append, MOP_RestartStrip, MOP_CalculateLevelOfDetail, MOP_CalculateLevelOfDetailUnclamped, MOP_GetDimensions, MOP_Load, MOP_Sample, MOP_SampleBias, MOP_SampleCmp, MOP_SampleCmpBias, MOP_SampleCmpGrad, MOP_SampleCmpLevel, MOP_SampleCmpLevelZero, MOP_SampleGrad, MOP_SampleLevel, MOP_Gather, MOP_GatherAlpha, MOP_GatherBlue, MOP_GatherCmp, MOP_GatherCmpAlpha, MOP_GatherCmpBlue, MOP_GatherCmpGreen, MOP_GatherCmpRed, MOP_GatherGreen, MOP_GatherRaw, MOP_GatherRed, MOP_GetSamplePosition, MOP_Load2, MOP_Load3, MOP_Load4, MOP_InterlockedAdd, MOP_InterlockedAdd64, MOP_InterlockedAnd, MOP_InterlockedAnd64, MOP_InterlockedCompareExchange, MOP_InterlockedCompareExchange64, MOP_InterlockedCompareExchangeFloatBitwise, MOP_InterlockedCompareStore, MOP_InterlockedCompareStore64, MOP_InterlockedCompareStoreFloatBitwise, MOP_InterlockedExchange, MOP_InterlockedExchange64, MOP_InterlockedExchangeFloat, MOP_InterlockedMax, MOP_InterlockedMax64, MOP_InterlockedMin, MOP_InterlockedMin64, MOP_InterlockedOr, MOP_InterlockedOr64, MOP_InterlockedXor, MOP_InterlockedXor64, MOP_Store, MOP_Store2, MOP_Store3, MOP_Store4, MOP_DecrementCounter, MOP_IncrementCounter, MOP_Consume, MOP_WriteSamplerFeedback, MOP_WriteSamplerFeedbackBias, MOP_WriteSamplerFeedbackGrad, MOP_WriteSamplerFeedbackLevel, MOP_Abort, MOP_CandidateGeometryIndex, MOP_CandidateInstanceContributionToHitGroupIndex, MOP_CandidateInstanceID, MOP_CandidateInstanceIndex, MOP_CandidateObjectRayDirection, MOP_CandidateObjectRayOrigin, MOP_CandidateObjectToWorld3x4, MOP_CandidateObjectToWorld4x3, MOP_CandidatePrimitiveIndex, MOP_CandidateProceduralPrimitiveNonOpaque, MOP_CandidateTriangleBarycentrics, MOP_CandidateTriangleFrontFace, MOP_CandidateTriangleRayT, MOP_CandidateType, MOP_CandidateWorldToObject3x4, MOP_CandidateWorldToObject4x3, MOP_CommitNonOpaqueTriangleHit, MOP_CommitProceduralPrimitiveHit, MOP_CommittedGeometryIndex, MOP_CommittedInstanceContributionToHitGroupIndex, MOP_CommittedInstanceID, MOP_CommittedInstanceIndex, MOP_CommittedObjectRayDirection, MOP_CommittedObjectRayOrigin, MOP_CommittedObjectToWorld3x4, MOP_CommittedObjectToWorld4x3, MOP_CommittedPrimitiveIndex, MOP_CommittedRayT, MOP_CommittedStatus, MOP_CommittedTriangleBarycentrics, MOP_CommittedTriangleFrontFace, MOP_CommittedWorldToObject3x4, MOP_CommittedWorldToObject4x3, MOP_Proceed, MOP_RayFlags, MOP_RayTMin, MOP_TraceRayInline, MOP_WorldRayDirection, MOP_WorldRayOrigin, MOP_Count, MOP_FinishedCrossGroupSharing, MOP_GetGroupNodeOutputRecords, MOP_GetThreadNodeOutputRecords, MOP_IsValid, MOP_GroupIncrementOutputCount, MOP_ThreadIncrementOutputCount, MOP_OutputComplete, #ifdef ENABLE_SPIRV_CODEGEN MOP_SubpassLoad, #endif // ENABLE_SPIRV_CODEGEN // unsigned IOP_InterlockedUMax, IOP_InterlockedUMin, IOP_WaveActiveUMax, IOP_WaveActiveUMin, IOP_WaveActiveUProduct, IOP_WaveActiveUSum, IOP_WaveMultiPrefixUProduct, IOP_WaveMultiPrefixUSum, IOP_WavePrefixUProduct, IOP_WavePrefixUSum, IOP_uabs, IOP_uclamp, IOP_ufirstbithigh, IOP_umad, IOP_umax, IOP_umin, IOP_umul, IOP_usign, MOP_InterlockedUMax, MOP_InterlockedUMin, Num_Intrinsics, }; inline bool HasUnsignedIntrinsicOpcode(IntrinsicOp opcode) { switch (opcode) { case IntrinsicOp::IOP_InterlockedMax: case IntrinsicOp::IOP_InterlockedMin: case IntrinsicOp::IOP_WaveActiveMax: case IntrinsicOp::IOP_WaveActiveMin: case IntrinsicOp::IOP_WaveActiveProduct: case IntrinsicOp::IOP_WaveActiveSum: case IntrinsicOp::IOP_WaveMultiPrefixProduct: case IntrinsicOp::IOP_WaveMultiPrefixSum: case IntrinsicOp::IOP_WavePrefixProduct: case IntrinsicOp::IOP_WavePrefixSum: case IntrinsicOp::IOP_abs: case IntrinsicOp::IOP_clamp: case IntrinsicOp::IOP_firstbithigh: case IntrinsicOp::IOP_mad: case IntrinsicOp::IOP_max: case IntrinsicOp::IOP_min: case IntrinsicOp::IOP_mul: case IntrinsicOp::IOP_sign: case IntrinsicOp::MOP_InterlockedMax: case IntrinsicOp::MOP_InterlockedMax64: case IntrinsicOp::MOP_InterlockedMin: case IntrinsicOp::MOP_InterlockedMin64: return true; default: return false; } } inline unsigned GetUnsignedIntrinsicOpcode(IntrinsicOp opcode) { switch (opcode) { case IntrinsicOp::IOP_InterlockedMax: return static_cast<unsigned>(IntrinsicOp::IOP_InterlockedUMax); case IntrinsicOp::IOP_InterlockedMin: return static_cast<unsigned>(IntrinsicOp::IOP_InterlockedUMin); case IntrinsicOp::IOP_WaveActiveMax: return static_cast<unsigned>(IntrinsicOp::IOP_WaveActiveUMax); case IntrinsicOp::IOP_WaveActiveMin: return static_cast<unsigned>(IntrinsicOp::IOP_WaveActiveUMin); case IntrinsicOp::IOP_WaveActiveProduct: return static_cast<unsigned>(IntrinsicOp::IOP_WaveActiveUProduct); case IntrinsicOp::IOP_WaveActiveSum: return static_cast<unsigned>(IntrinsicOp::IOP_WaveActiveUSum); case IntrinsicOp::IOP_WaveMultiPrefixProduct: return static_cast<unsigned>(IntrinsicOp::IOP_WaveMultiPrefixUProduct); case IntrinsicOp::IOP_WaveMultiPrefixSum: return static_cast<unsigned>(IntrinsicOp::IOP_WaveMultiPrefixUSum); case IntrinsicOp::IOP_WavePrefixProduct: return static_cast<unsigned>(IntrinsicOp::IOP_WavePrefixUProduct); case IntrinsicOp::IOP_WavePrefixSum: return static_cast<unsigned>(IntrinsicOp::IOP_WavePrefixUSum); case IntrinsicOp::IOP_abs: return static_cast<unsigned>(IntrinsicOp::IOP_uabs); case IntrinsicOp::IOP_clamp: return static_cast<unsigned>(IntrinsicOp::IOP_uclamp); case IntrinsicOp::IOP_firstbithigh: return static_cast<unsigned>(IntrinsicOp::IOP_ufirstbithigh); case IntrinsicOp::IOP_mad: return static_cast<unsigned>(IntrinsicOp::IOP_umad); case IntrinsicOp::IOP_max: return static_cast<unsigned>(IntrinsicOp::IOP_umax); case IntrinsicOp::IOP_min: return static_cast<unsigned>(IntrinsicOp::IOP_umin); case IntrinsicOp::IOP_mul: return static_cast<unsigned>(IntrinsicOp::IOP_umul); case IntrinsicOp::IOP_sign: return static_cast<unsigned>(IntrinsicOp::IOP_usign); case IntrinsicOp::MOP_InterlockedMax: return static_cast<unsigned>(IntrinsicOp::MOP_InterlockedUMax); case IntrinsicOp::MOP_InterlockedMax64: return static_cast<unsigned>(IntrinsicOp::MOP_InterlockedUMax); case IntrinsicOp::MOP_InterlockedMin: return static_cast<unsigned>(IntrinsicOp::MOP_InterlockedUMin); case IntrinsicOp::MOP_InterlockedMin64: return static_cast<unsigned>(IntrinsicOp::MOP_InterlockedUMin); default: return static_cast<unsigned>(opcode); } } } // namespace hlsl
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/dxc/WinAdapter.h
//===- WinAdapter.h - Windows Adapter for non-Windows platforms -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines Windows-specific types, macros, and SAL annotations used // in the codebase for non-Windows platforms. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_WIN_ADAPTER_H #define LLVM_SUPPORT_WIN_ADAPTER_H #ifndef _WIN32 #ifdef __cplusplus #include <atomic> #include <cassert> #include <climits> #include <cstring> #include <cwchar> #include <fstream> #include <stdarg.h> #include <stddef.h> #include <stdint.h> #include <string> #include <typeindex> #include <typeinfo> #include <vector> #endif // __cplusplus #define COM_NO_WINDOWS_H // needed to inform d3d headers that this isn't windows //===----------------------------------------------------------------------===// // // Begin: Macro Definitions // //===----------------------------------------------------------------------===// #define C_ASSERT(expr) static_assert((expr), "") #define ATLASSERT assert #define CoTaskMemAlloc malloc #define CoTaskMemFree free #define ARRAYSIZE(array) (sizeof(array) / sizeof(array[0])) #define _countof(a) (sizeof(a) / sizeof(*(a))) // If it is GCC, there is no UUID support and we must emulate it. #ifndef __clang__ #define __EMULATE_UUID 1 #endif // __clang__ #ifdef __EMULATE_UUID #define __declspec(x) #endif // __EMULATE_UUID #define DECLSPEC_SELECTANY #ifdef __EMULATE_UUID #define uuid(id) #endif // __EMULATE_UUID #define STDMETHODCALLTYPE #define STDMETHODIMP_(type) type STDMETHODCALLTYPE #define STDMETHODIMP STDMETHODIMP_(HRESULT) #define STDMETHOD_(type, name) virtual STDMETHODIMP_(type) name #define STDMETHOD(name) STDMETHOD_(HRESULT, name) #define EXTERN_C extern "C" #define UNREFERENCED_PARAMETER(P) (void)(P) #define RtlEqualMemory(Destination, Source, Length) \ (!memcmp((Destination), (Source), (Length))) #define RtlMoveMemory(Destination, Source, Length) \ memmove((Destination), (Source), (Length)) #define RtlCopyMemory(Destination, Source, Length) \ memcpy((Destination), (Source), (Length)) #define RtlFillMemory(Destination, Length, Fill) \ memset((Destination), (Fill), (Length)) #define RtlZeroMemory(Destination, Length) memset((Destination), 0, (Length)) #define MoveMemory RtlMoveMemory #define CopyMemory RtlCopyMemory #define FillMemory RtlFillMemory #define ZeroMemory RtlZeroMemory #define FALSE 0 #define TRUE 1 // We ignore the code page completely on Linux. #define GetConsoleOutputCP() 0 #define _HRESULT_TYPEDEF_(_sc) ((HRESULT)_sc) #define DISP_E_BADINDEX _HRESULT_TYPEDEF_(0x8002000BL) #define REGDB_E_CLASSNOTREG _HRESULT_TYPEDEF_(0x80040154L) // This is an unsafe conversion. If needed, we can later implement a safe // conversion that throws exceptions for overflow cases. #define UIntToInt(uint_arg, int_ptr_arg) *int_ptr_arg = uint_arg #define INVALID_HANDLE_VALUE ((HANDLE)(LONG_PTR)-1) // Use errno to implement {Get|Set}LastError #define GetLastError() errno #define SetLastError(ERR) errno = ERR // Map these errors to equivalent errnos. #define ERROR_SUCCESS 0L #define ERROR_ARITHMETIC_OVERFLOW EOVERFLOW #define ERROR_FILE_NOT_FOUND ENOENT #define ERROR_FUNCTION_NOT_CALLED ENOSYS #define ERROR_IO_DEVICE EIO #define ERROR_INSUFFICIENT_BUFFER ENOBUFS #define ERROR_INVALID_HANDLE EBADF #define ERROR_INVALID_PARAMETER EINVAL #define ERROR_OUT_OF_STRUCTURES ENOMEM #define ERROR_NOT_CAPABLE EPERM #define ERROR_NOT_FOUND ENOTSUP #define ERROR_UNHANDLED_EXCEPTION EBADF #define ERROR_BROKEN_PIPE EPIPE // Used by HRESULT <--> WIN32 error code conversion #define SEVERITY_ERROR 1 #define FACILITY_WIN32 7 #define HRESULT_CODE(hr) ((hr) & 0xFFFF) #define MAKE_HRESULT(severity, facility, code) \ ((HRESULT)(((unsigned long)(severity) << 31) | \ ((unsigned long)(facility) << 16) | ((unsigned long)(code)))) #define FILE_TYPE_UNKNOWN 0x0000 #define FILE_TYPE_DISK 0x0001 #define FILE_TYPE_CHAR 0x0002 #define FILE_TYPE_PIPE 0x0003 #define FILE_TYPE_REMOTE 0x8000 #define FILE_ATTRIBUTE_NORMAL 0x00000080 #define FILE_ATTRIBUTE_DIRECTORY 0x00000010 #define INVALID_FILE_ATTRIBUTES ((DWORD)-1) #define STDOUT_FILENO 1 #define STDERR_FILENO 2 // STGTY ENUMS #define STGTY_STORAGE 1 #define STGTY_STREAM 2 #define STGTY_LOCKBYTES 3 #define STGTY_PROPERTY 4 // Storage errors #define STG_E_INVALIDFUNCTION 1L #define STG_E_ACCESSDENIED 2L #define STREAM_SEEK_SET 0 #define STREAM_SEEK_CUR 1 #define STREAM_SEEK_END 2 #define HEAP_NO_SERIALIZE 0x1 #define HEAP_ZERO_MEMORY 0x8 #define MB_ERR_INVALID_CHARS 0x00000008 // error for invalid chars // File IO #define CREATE_ALWAYS 2 #define CREATE_NEW 1 #define OPEN_ALWAYS 4 #define OPEN_EXISTING 3 #define TRUNCATE_EXISTING 5 #define FILE_SHARE_DELETE 0x00000004 #define FILE_SHARE_READ 0x00000001 #define FILE_SHARE_WRITE 0x00000002 #define GENERIC_READ 0x80000000 #define GENERIC_WRITE 0x40000000 #define _atoi64 atoll #define sprintf_s snprintf #define _strdup strdup #define _strnicmp strnicmp #define vsnprintf_s vsnprintf #define strcat_s strcat #define strcpy_s(dst, n, src) strncpy(dst, src, n) #define _vscwprintf vwprintf #define vswprintf_s vswprintf #define swprintf_s swprintf #define StringCchCopyW(dst, n, src) wcsncpy(dst, src, n) #define OutputDebugStringW(msg) fputws(msg, stderr) #define OutputDebugStringA(msg) fputs(msg, stderr) #define OutputDebugFormatA(...) fprintf(stderr, __VA_ARGS__) // Event Tracing for Windows (ETW) provides application programmers the ability // to start and stop event tracing sessions, instrument an application to // provide trace events, and consume trace events. #define DxcEtw_DXCompilerCreateInstance_Start() #define DxcEtw_DXCompilerCreateInstance_Stop(hr) #define DxcEtw_DXCompilerCompile_Start() #define DxcEtw_DXCompilerCompile_Stop(hr) #define DxcEtw_DXCompilerDisassemble_Start() #define DxcEtw_DXCompilerDisassemble_Stop(hr) #define DxcEtw_DXCompilerPreprocess_Start() #define DxcEtw_DXCompilerPreprocess_Stop(hr) #define DxcEtw_DxcValidation_Start() #define DxcEtw_DxcValidation_Stop(hr) #define UInt32Add UIntAdd #define Int32ToUInt32 IntToUInt //===--------------------- HRESULT Related Macros -------------------------===// #define S_OK ((HRESULT)0L) #define S_FALSE ((HRESULT)1L) #define E_ABORT (HRESULT)0x80004004 #define E_ACCESSDENIED (HRESULT)0x80070005 #define E_BOUNDS (HRESULT)0x8000000B #define E_FAIL (HRESULT)0x80004005 #define E_HANDLE (HRESULT)0x80070006 #define E_INVALIDARG (HRESULT)0x80070057 #define E_NOINTERFACE (HRESULT)0x80004002 #define E_NOTIMPL (HRESULT)0x80004001 #define E_NOT_VALID_STATE (HRESULT)0x8007139F #define E_OUTOFMEMORY (HRESULT)0x8007000E #define E_POINTER (HRESULT)0x80004003 #define E_UNEXPECTED (HRESULT)0x8000FFFF #define SUCCEEDED(hr) (((HRESULT)(hr)) >= 0) #define FAILED(hr) (((HRESULT)(hr)) < 0) #define DXC_FAILED(hr) (((HRESULT)(hr)) < 0) #define HRESULT_FROM_WIN32(x) \ (HRESULT)(x) <= 0 ? (HRESULT)(x) \ : (HRESULT)(((x) & 0x0000FFFF) | (7 << 16) | 0x80000000) //===----------------------------------------------------------------------===// // // Begin: Disable SAL Annotations // //===----------------------------------------------------------------------===// #define _In_ #define _In_z_ #define _In_opt_ #define _In_opt_count_(size) #define _In_opt_z_ #define _In_count_(size) #define _In_bytecount_(size) #define _Out_ #define _Out_opt_ #define _Outptr_ #define _Outptr_opt_ #define _Outptr_result_z_ #define _Outptr_opt_result_z_ #define _Outptr_result_maybenull_ #define _Outptr_result_nullonfailure_ #define _Outptr_result_buffer_maybenull_(ptr) #define _Outptr_result_buffer_(ptr) #define _COM_Outptr_ #define _COM_Outptr_opt_ #define _COM_Outptr_result_maybenull_ #define _COM_Outptr_opt_result_maybenull_ #define THIS_ #define THIS #define PURE = 0 #define _Maybenull_ #define __debugbreak() // GCC produces erros on calling convention attributes. #ifdef __GNUC__ #define __cdecl #define __CRTDECL #define __stdcall #define __vectorcall #define __thiscall #define __fastcall #define __clrcall #endif // __GNUC__ //===----------------------------------------------------------------------===// // // Begin: Type Definitions // //===----------------------------------------------------------------------===// #ifdef __cplusplus typedef unsigned char BYTE, UINT8; typedef unsigned char *LPBYTE; typedef BYTE BOOLEAN; typedef BOOLEAN *PBOOLEAN; typedef bool BOOL; typedef BOOL *LPBOOL; typedef int INT; typedef long LONG; typedef unsigned int UINT; typedef unsigned long ULONG; typedef long long LONGLONG; typedef long long LONG_PTR; typedef unsigned long long ULONG_PTR; typedef unsigned long long ULONGLONG; typedef uint16_t WORD; typedef uint32_t DWORD; typedef DWORD *LPDWORD; typedef uint32_t UINT32; typedef uint64_t UINT64; typedef signed char INT8, *PINT8; typedef signed int INT32, *PINT32; typedef size_t SIZE_T; typedef const char *LPCSTR; typedef const char *PCSTR; typedef int errno_t; typedef wchar_t WCHAR; typedef wchar_t *LPWSTR; typedef wchar_t *PWCHAR; typedef const wchar_t *LPCWSTR; typedef const wchar_t *PCWSTR; typedef WCHAR OLECHAR; typedef OLECHAR *BSTR; typedef OLECHAR *LPOLESTR; typedef char *LPSTR; typedef void *LPVOID; typedef const void *LPCVOID; typedef std::nullptr_t nullptr_t; typedef signed int HRESULT; //===--------------------- Handle Types -----------------------------------===// typedef void *HANDLE; typedef void *RPC_IF_HANDLE; #define DECLARE_HANDLE(name) \ struct name##__ { \ int unused; \ }; \ typedef struct name##__ *name DECLARE_HANDLE(HINSTANCE); typedef void *HMODULE; #define STD_INPUT_HANDLE ((DWORD)-10) #define STD_OUTPUT_HANDLE ((DWORD)-11) #define STD_ERROR_HANDLE ((DWORD)-12) //===--------------------- ID Types and Macros for COM --------------------===// #ifdef __EMULATE_UUID struct GUID #else // __EMULATE_UUID // These specific definitions are required by clang -fms-extensions. typedef struct _GUID #endif // __EMULATE_UUID { uint32_t Data1; uint16_t Data2; uint16_t Data3; uint8_t Data4[8]; } #ifdef __EMULATE_UUID ; #else // __EMULATE_UUID GUID; #endif // __EMULATE_UUID typedef GUID CLSID; typedef const GUID &REFGUID; typedef const GUID &REFCLSID; typedef GUID IID; typedef IID *LPIID; typedef const IID &REFIID; inline bool IsEqualGUID(REFGUID rguid1, REFGUID rguid2) { // Optimization: if (&rguid1 == &rguid2) return true; return !memcmp(&rguid1, &rguid2, sizeof(GUID)); } inline bool operator==(REFGUID guidOne, REFGUID guidOther) { return !!IsEqualGUID(guidOne, guidOther); } inline bool operator!=(REFGUID guidOne, REFGUID guidOther) { return !(guidOne == guidOther); } inline bool IsEqualIID(REFIID riid1, REFIID riid2) { return IsEqualGUID(riid1, riid2); } inline bool IsEqualCLSID(REFCLSID rclsid1, REFCLSID rclsid2) { return IsEqualGUID(rclsid1, rclsid2); } //===--------------------- Struct Types -----------------------------------===// typedef struct _FILETIME { DWORD dwLowDateTime; DWORD dwHighDateTime; } FILETIME, *PFILETIME, *LPFILETIME; typedef struct _BY_HANDLE_FILE_INFORMATION { DWORD dwFileAttributes; FILETIME ftCreationTime; FILETIME ftLastAccessTime; FILETIME ftLastWriteTime; DWORD dwVolumeSerialNumber; DWORD nFileSizeHigh; DWORD nFileSizeLow; DWORD nNumberOfLinks; DWORD nFileIndexHigh; DWORD nFileIndexLow; } BY_HANDLE_FILE_INFORMATION, *PBY_HANDLE_FILE_INFORMATION, *LPBY_HANDLE_FILE_INFORMATION; typedef struct _WIN32_FIND_DATAW { DWORD dwFileAttributes; FILETIME ftCreationTime; FILETIME ftLastAccessTime; FILETIME ftLastWriteTime; DWORD nFileSizeHigh; DWORD nFileSizeLow; DWORD dwReserved0; DWORD dwReserved1; WCHAR cFileName[260]; WCHAR cAlternateFileName[14]; } WIN32_FIND_DATAW, *PWIN32_FIND_DATAW, *LPWIN32_FIND_DATAW; typedef union _LARGE_INTEGER { struct { DWORD LowPart; DWORD HighPart; } u; LONGLONG QuadPart; } LARGE_INTEGER; typedef LARGE_INTEGER *PLARGE_INTEGER; typedef union _ULARGE_INTEGER { struct { DWORD LowPart; DWORD HighPart; } u; ULONGLONG QuadPart; } ULARGE_INTEGER; typedef ULARGE_INTEGER *PULARGE_INTEGER; typedef struct tagSTATSTG { LPOLESTR pwcsName; DWORD type; ULARGE_INTEGER cbSize; FILETIME mtime; FILETIME ctime; FILETIME atime; DWORD grfMode; DWORD grfLocksSupported; CLSID clsid; DWORD grfStateBits; DWORD reserved; } STATSTG; enum tagSTATFLAG { STATFLAG_DEFAULT = 0, STATFLAG_NONAME = 1, STATFLAG_NOOPEN = 2 }; //===--------------------- UUID Related Macros ----------------------------===// #ifdef __EMULATE_UUID // The following macros are defined to facilitate the lack of 'uuid' on Linux. constexpr uint8_t nybble_from_hex(char c) { return ((c >= '0' && c <= '9') ? (c - '0') : ((c >= 'a' && c <= 'f') ? (c - 'a' + 10) : ((c >= 'A' && c <= 'F') ? (c - 'A' + 10) : /* Should be an error */ -1))); } constexpr uint8_t byte_from_hex(char c1, char c2) { return nybble_from_hex(c1) << 4 | nybble_from_hex(c2); } constexpr uint8_t byte_from_hexstr(const char str[2]) { return nybble_from_hex(str[0]) << 4 | nybble_from_hex(str[1]); } constexpr GUID guid_from_string(const char str[37]) { return GUID{static_cast<uint32_t>(byte_from_hexstr(str)) << 24 | static_cast<uint32_t>(byte_from_hexstr(str + 2)) << 16 | static_cast<uint32_t>(byte_from_hexstr(str + 4)) << 8 | byte_from_hexstr(str + 6), static_cast<uint16_t>( static_cast<uint16_t>(byte_from_hexstr(str + 9)) << 8 | byte_from_hexstr(str + 11)), static_cast<uint16_t>( static_cast<uint16_t>(byte_from_hexstr(str + 14)) << 8 | byte_from_hexstr(str + 16)), {byte_from_hexstr(str + 19), byte_from_hexstr(str + 21), byte_from_hexstr(str + 24), byte_from_hexstr(str + 26), byte_from_hexstr(str + 28), byte_from_hexstr(str + 30), byte_from_hexstr(str + 32), byte_from_hexstr(str + 34)}}; } template <typename interface> inline GUID __emulated_uuidof(); #define CROSS_PLATFORM_UUIDOF(interface, spec) \ struct interface; \ template <> inline GUID __emulated_uuidof<interface>() { \ static const IID _IID = guid_from_string(spec); \ return _IID; \ } #define __uuidof(T) __emulated_uuidof<typename std::decay<T>::type>() #define IID_PPV_ARGS(ppType) \ __uuidof(decltype(**(ppType))), reinterpret_cast<void **>(ppType) #else // __EMULATE_UUID #ifndef CROSS_PLATFORM_UUIDOF // Warning: This macro exists in dxcapi.h as well #define CROSS_PLATFORM_UUIDOF(interface, spec) \ struct __declspec(uuid(spec)) interface; #endif template <typename T> inline void **IID_PPV_ARGS_Helper(T **pp) { return reinterpret_cast<void **>(pp); } #define IID_PPV_ARGS(ppType) __uuidof(**(ppType)), IID_PPV_ARGS_Helper(ppType) #endif // __EMULATE_UUID // Needed for d3d headers, but fail to create actual interfaces #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ const GUID name = {l, w1, w2, {b1, b2, b3, b4, b5, b6, b7, b8}} #define DECLSPEC_UUID(x) #define MIDL_INTERFACE(x) struct DECLSPEC_UUID(x) #define DECLARE_INTERFACE(iface) struct iface #define DECLARE_INTERFACE_(iface, parent) DECLARE_INTERFACE(iface) : parent //===--------------------- COM Interfaces ---------------------------------===// CROSS_PLATFORM_UUIDOF(IUnknown, "00000000-0000-0000-C000-000000000046") struct IUnknown { IUnknown(){}; virtual HRESULT QueryInterface(REFIID riid, void **ppvObject) = 0; virtual ULONG AddRef() = 0; virtual ULONG Release() = 0; template <class Q> HRESULT QueryInterface(Q **pp) { return QueryInterface(__uuidof(Q), (void **)pp); } }; CROSS_PLATFORM_UUIDOF(INoMarshal, "ECC8691B-C1DB-4DC0-855E-65F6C551AF49") struct INoMarshal : public IUnknown {}; CROSS_PLATFORM_UUIDOF(IMalloc, "00000002-0000-0000-C000-000000000046") struct IMalloc : public IUnknown { virtual void *Alloc(SIZE_T size) = 0; virtual void *Realloc(void *ptr, SIZE_T size) = 0; virtual void Free(void *ptr) = 0; virtual SIZE_T GetSize(void *pv) = 0; virtual int DidAlloc(void *pv) = 0; virtual void HeapMinimize(void) = 0; }; CROSS_PLATFORM_UUIDOF(ISequentialStream, "0C733A30-2A1C-11CE-ADE5-00AA0044773D") struct ISequentialStream : public IUnknown { virtual HRESULT Read(void *pv, ULONG cb, ULONG *pcbRead) = 0; virtual HRESULT Write(const void *pv, ULONG cb, ULONG *pcbWritten) = 0; }; CROSS_PLATFORM_UUIDOF(IStream, "0000000c-0000-0000-C000-000000000046") struct IStream : public ISequentialStream { virtual HRESULT Seek(LARGE_INTEGER dlibMove, DWORD dwOrigin, ULARGE_INTEGER *plibNewPosition) = 0; virtual HRESULT SetSize(ULARGE_INTEGER libNewSize) = 0; virtual HRESULT CopyTo(IStream *pstm, ULARGE_INTEGER cb, ULARGE_INTEGER *pcbRead, ULARGE_INTEGER *pcbWritten) = 0; virtual HRESULT Commit(DWORD grfCommitFlags) = 0; virtual HRESULT Revert(void) = 0; virtual HRESULT LockRegion(ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType) = 0; virtual HRESULT UnlockRegion(ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType) = 0; virtual HRESULT Stat(STATSTG *pstatstg, DWORD grfStatFlag) = 0; virtual HRESULT Clone(IStream **ppstm) = 0; }; // These don't need stub implementations as they come from the DirectX Headers // They still need the __uuidof() though CROSS_PLATFORM_UUIDOF(ID3D12LibraryReflection, "8E349D19-54DB-4A56-9DC9-119D87BDB804") CROSS_PLATFORM_UUIDOF(ID3D12ShaderReflection, "5A58797D-A72C-478D-8BA2-EFC6B0EFE88E") //===--------------------- COM Pointer Types ------------------------------===// class CAllocator { public: static void *Reallocate(void *p, size_t nBytes) throw(); static void *Allocate(size_t nBytes) throw(); static void Free(void *p) throw(); }; template <class T> class CComPtrBase { protected: CComPtrBase() throw() { p = nullptr; } CComPtrBase(T *lp) throw() { p = lp; if (p != nullptr) p->AddRef(); } void Swap(CComPtrBase &other) { T *pTemp = p; p = other.p; other.p = pTemp; } public: ~CComPtrBase() throw() { if (p) { p->Release(); p = nullptr; } } operator T *() const throw() { return p; } T &operator*() const { return *p; } T *operator->() const { return p; } T **operator&() throw() { assert(p == nullptr); return &p; } bool operator!() const throw() { return (p == nullptr); } bool operator<(T *pT) const throw() { return p < pT; } bool operator!=(T *pT) const { return !operator==(pT); } bool operator==(T *pT) const throw() { return p == pT; } // Release the interface and set to nullptr void Release() throw() { T *pTemp = p; if (pTemp) { p = nullptr; pTemp->Release(); } } // Attach to an existing interface (does not AddRef) void Attach(T *p2) throw() { if (p) { ULONG ref = p->Release(); (void)(ref); // Attaching to the same object only works if duplicate references are // being coalesced. Otherwise re-attaching will cause the pointer to be // released and may cause a crash on a subsequent dereference. assert(ref != 0 || p2 != p); } p = p2; } // Detach the interface (does not Release) T *Detach() throw() { T *pt = p; p = nullptr; return pt; } HRESULT CopyTo(T **ppT) throw() { assert(ppT != nullptr); if (ppT == nullptr) return E_POINTER; *ppT = p; if (p) p->AddRef(); return S_OK; } template <class Q> HRESULT QueryInterface(Q **pp) const throw() { assert(pp != nullptr); return p->QueryInterface(__uuidof(Q), (void **)pp); } T *p; }; template <class T> class CComPtr : public CComPtrBase<T> { public: CComPtr() throw() {} CComPtr(T *lp) throw() : CComPtrBase<T>(lp) {} CComPtr(const CComPtr<T> &lp) throw() : CComPtrBase<T>(lp.p) {} T *operator=(T *lp) throw() { if (*this != lp) { CComPtr(lp).Swap(*this); } return *this; } inline bool IsEqualObject(IUnknown *pOther) throw() { if (this->p == nullptr && pOther == nullptr) return true; // They are both NULL objects if (this->p == nullptr || pOther == nullptr) return false; // One is NULL the other is not CComPtr<IUnknown> punk1; CComPtr<IUnknown> punk2; this->p->QueryInterface(__uuidof(IUnknown), (void **)&punk1); pOther->QueryInterface(__uuidof(IUnknown), (void **)&punk2); return punk1 == punk2; } void ComPtrAssign(IUnknown **pp, IUnknown *lp, REFIID riid) { IUnknown *pTemp = *pp; // takes ownership if (lp == nullptr || FAILED(lp->QueryInterface(riid, (void **)pp))) *pp = nullptr; if (pTemp) pTemp->Release(); } template <typename Q> T *operator=(const CComPtr<Q> &lp) throw() { if (!this->IsEqualObject(lp)) { ComPtrAssign((IUnknown **)&this->p, lp, __uuidof(T)); } return *this; } // NOTE: This conversion constructor is not part of the official CComPtr spec; // however, it is needed to convert CComPtr<Q> to CComPtr<T> where T derives // from Q on Clang. MSVC compiles this conversion as first a call to // CComPtr<Q>::operator T*, followed by CComPtr<T>(T*), but Clang fails to // compile with error: no viable conversion from 'CComPtr<Q>' to 'CComPtr<T>'. template <typename Q> CComPtr(const CComPtr<Q> &lp) throw() : CComPtrBase<T>(lp.p) {} T *operator=(const CComPtr<T> &lp) throw() { if (*this != lp) { CComPtr(lp).Swap(*this); } return *this; } CComPtr(CComPtr<T> &&lp) throw() : CComPtrBase<T>() { lp.Swap(*this); } T *operator=(CComPtr<T> &&lp) throw() { if (*this != lp) { CComPtr(static_cast<CComPtr &&>(lp)).Swap(*this); } return *this; } }; template <class T> class CSimpleArray : public std::vector<T> { public: bool Add(const T &t) { this->push_back(t); return true; } int GetSize() { return this->size(); } T *GetData() { return this->data(); } void RemoveAll() { this->clear(); } }; template <class T, class Allocator = CAllocator> class CHeapPtrBase { protected: CHeapPtrBase() throw() : m_pData(NULL) {} CHeapPtrBase(CHeapPtrBase<T, Allocator> &p) throw() { m_pData = p.Detach(); // Transfer ownership } explicit CHeapPtrBase(T *pData) throw() : m_pData(pData) {} public: ~CHeapPtrBase() throw() { Free(); } protected: CHeapPtrBase<T, Allocator> &operator=(CHeapPtrBase<T, Allocator> &p) throw() { if (m_pData != p.m_pData) Attach(p.Detach()); // Transfer ownership return *this; } public: operator T *() const throw() { return m_pData; } T *operator->() const throw() { assert(m_pData != NULL); return m_pData; } T **operator&() throw() { assert(m_pData == NULL); return &m_pData; } // Allocate a buffer with the given number of bytes bool AllocateBytes(size_t nBytes) throw() { assert(m_pData == NULL); m_pData = static_cast<T *>(Allocator::Allocate(nBytes * sizeof(char))); if (m_pData == NULL) return false; return true; } // Attach to an existing pointer (takes ownership) void Attach(T *pData) throw() { Allocator::Free(m_pData); m_pData = pData; } // Detach the pointer (releases ownership) T *Detach() throw() { T *pTemp = m_pData; m_pData = NULL; return pTemp; } // Free the memory pointed to, and set the pointer to NULL void Free() throw() { Allocator::Free(m_pData); m_pData = NULL; } // Reallocate the buffer to hold a given number of bytes bool ReallocateBytes(size_t nBytes) throw() { T *pNew; pNew = static_cast<T *>(Allocator::Reallocate(m_pData, nBytes * sizeof(char))); if (pNew == NULL) return false; m_pData = pNew; return true; } public: T *m_pData; }; template <typename T, class Allocator = CAllocator> class CHeapPtr : public CHeapPtrBase<T, Allocator> { public: CHeapPtr() throw() {} CHeapPtr(CHeapPtr<T, Allocator> &p) throw() : CHeapPtrBase<T, Allocator>(p) {} explicit CHeapPtr(T *p) throw() : CHeapPtrBase<T, Allocator>(p) {} CHeapPtr<T> &operator=(CHeapPtr<T, Allocator> &p) throw() { CHeapPtrBase<T, Allocator>::operator=(p); return *this; } // Allocate a buffer with the given number of elements bool Allocate(size_t nElements = 1) throw() { size_t nBytes = nElements * sizeof(T); return this->AllocateBytes(nBytes); } // Reallocate the buffer to hold a given number of elements bool Reallocate(size_t nElements) throw() { size_t nBytes = nElements * sizeof(T); return this->ReallocateBytes(nBytes); } }; #define CComHeapPtr CHeapPtr //===--------------------------- BSTR Allocation --------------------------===// void SysFreeString(BSTR bstrString); // Allocate string with length prefix BSTR SysAllocStringLen(const OLECHAR *strIn, UINT ui); //===--------------------------- BSTR Length ------------------------------===// unsigned int SysStringLen(const BSTR bstrString); //===--------------------- UTF-8 Related Types ----------------------------===// // Code Page #define CP_ACP 0 #define CP_UTF8 65001 // UTF-8 translation. // RAII style mechanism for setting/unsetting a locale for the specified Windows // codepage class ScopedLocale { const char *m_prevLocale; public: explicit ScopedLocale(uint32_t codePage) : m_prevLocale(setlocale(LC_ALL, nullptr)) { assert((codePage == CP_UTF8) && "Support for Linux only handles UTF8 code pages"); setlocale(LC_ALL, "en_US.UTF-8"); } ~ScopedLocale() { if (m_prevLocale != nullptr) { setlocale(LC_ALL, m_prevLocale); } } }; // The t_nBufferLength parameter is part of the published interface, but not // used here. template <int t_nBufferLength = 128> class CW2AEX { public: CW2AEX(LPCWSTR psz) { ScopedLocale locale(CP_UTF8); if (!psz) { m_psz = NULL; return; } int len = (wcslen(psz) + 1) * 4; m_psz = new char[len]; std::wcstombs(m_psz, psz, len); } ~CW2AEX() { delete[] m_psz; } operator LPSTR() const { return m_psz; } char *m_psz; }; typedef CW2AEX<> CW2A; // The t_nBufferLength parameter is part of the published interface, but not // used here. template <int t_nBufferLength = 128> class CA2WEX { public: CA2WEX(LPCSTR psz) { ScopedLocale locale(CP_UTF8); if (!psz) { m_psz = NULL; return; } int len = strlen(psz) + 1; m_psz = new wchar_t[len]; std::mbstowcs(m_psz, psz, len); } ~CA2WEX() { delete[] m_psz; } operator LPWSTR() const { return m_psz; } wchar_t *m_psz; }; typedef CA2WEX<> CA2W; //===--------- File IO Related Types ----------------===// class CHandle { public: CHandle(HANDLE h); ~CHandle(); operator HANDLE() const throw(); private: HANDLE m_h; }; ///////////////////////////////////////////////////////////////////////////// // CComBSTR class CComBSTR { public: BSTR m_str; CComBSTR() : m_str(nullptr){}; CComBSTR(int nSize, LPCWSTR sz); ~CComBSTR() throw() { SysFreeString(m_str); } unsigned int Length() const throw() { return SysStringLen(m_str); } operator BSTR() const throw() { return m_str; } bool operator==(const CComBSTR &bstrSrc) const throw(); BSTR *operator&() throw() { return &m_str; } BSTR Detach() throw() { BSTR s = m_str; m_str = NULL; return s; } void Empty() throw() { SysFreeString(m_str); m_str = NULL; } }; //===--------- Convert argv to wchar ----------------===// class WArgV { std::vector<std::wstring> WStringVector; std::vector<const wchar_t *> WCharPtrVector; public: WArgV(int argc, const char **argv); const wchar_t **argv() { return WCharPtrVector.data(); } }; #endif // __cplusplus #endif // _WIN32 #endif // LLVM_SUPPORT_WIN_ADAPTER_H
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/dxc/CMakeLists.txt
include(HCT) add_hlsl_hctgen(HLSLIntrinsicOp OUTPUT HlslIntrinsicOp.h) set(HLSL_TEST_DATA_DIR ${LLVM_SOURCE_DIR}/tools/clang/test/HLSL/) set(EXEC_TEST_DATA_DIR ${LLVM_SOURCE_DIR}/tools/clang/unittests/HLSLExec/) configure_file( ${LLVM_MAIN_INCLUDE_DIR}/dxc/Test/TestConfig.h.in ${LLVM_INCLUDE_DIR}/dxc/Test/TestConfig.h ) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/config.h.cmake ${LLVM_INCLUDE_DIR}/dxc/config.h ) add_subdirectory(DXIL) add_subdirectory(DxilContainer) add_subdirectory(Support) add_subdirectory(Tracing) set(DXC_PUBLIC_HEADERS ${CMAKE_CURRENT_BINARY_DIR}/config.h ${CMAKE_CURRENT_SOURCE_DIR}/dxcapi.h ${CMAKE_CURRENT_SOURCE_DIR}/dxcerrors.h ${CMAKE_CURRENT_SOURCE_DIR}/dxcisense.h) if (NOT WIN32) set(DXC_PLATFORM_PUBLIC_HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/WinAdapter.h) endif() # This target just needs to exist for the distribution build, it doesn't need to # actually build anything since the headers are static. add_custom_target(dxc-headers) install(FILES ${DXC_PUBLIC_HEADERS} ${DXC_PLATFORM_PUBLIC_HEADERS} DESTINATION include/dxc COMPONENT dxc-headers ) add_custom_target(install-dxc-headers DEPENDS dxc-headers COMMAND "${CMAKE_COMMAND}" -DCMAKE_INSTALL_COMPONENT=dxc-headers -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
0
repos/DirectXShaderCompiler/include
repos/DirectXShaderCompiler/include/dxc/dxcapi.internal.h
/////////////////////////////////////////////////////////////////////////////// // // // dxcapi.internal.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides non-public declarations for the DirectX Compiler component. // // // /////////////////////////////////////////////////////////////////////////////// #ifndef __DXC_API_INTERNAL__ #define __DXC_API_INTERNAL__ #include "dxcapi.h" /////////////////////////////////////////////////////////////////////////////// // Forward declarations. typedef struct ITextFont ITextFont; typedef struct IEnumSTATSTG IEnumSTATSTG; typedef struct ID3D10Blob ID3D10Blob; /////////////////////////////////////////////////////////////////////////////// // Intrinsic definitions. #define AR_QUAL_IN 0x0000000000000010ULL #define AR_QUAL_OUT 0x0000000000000020ULL #define AR_QUAL_REF 0x0000000000000040ULL #define AR_QUAL_CONST 0x0000000000000200ULL #define AR_QUAL_ROWMAJOR 0x0000000000000400ULL #define AR_QUAL_COLMAJOR 0x0000000000000800ULL #define AR_QUAL_GROUPSHARED 0x0000000000001000ULL #define AR_QUAL_IN_OUT (AR_QUAL_IN | AR_QUAL_OUT) static const BYTE INTRIN_TEMPLATE_FROM_TYPE = 0xff; static const BYTE INTRIN_TEMPLATE_VARARGS = 0xfe; static const BYTE INTRIN_TEMPLATE_FROM_FUNCTION = 0xfd; // Use this enumeration to describe allowed templates (layouts) in intrinsics. enum LEGAL_INTRINSIC_TEMPLATES { LITEMPLATE_VOID = 0, // No return type. LITEMPLATE_SCALAR = 1, // Scalar types. LITEMPLATE_VECTOR = 2, // Vector types (eg. float3). LITEMPLATE_MATRIX = 3, // Matrix types (eg. float3x3). LITEMPLATE_ANY = 4, // Any one of scalar, vector or matrix types (but not object). LITEMPLATE_OBJECT = 5, // Object types. LITEMPLATE_ARRAY = 6, // Scalar array. LITEMPLATE_COUNT = 7 }; // INTRIN_COMPTYPE_FROM_TYPE_ELT0 is for object method intrinsics to indicate // that the component type of the type is taken from the first subelement of the // object's template type; see for example Texture2D.Gather static const BYTE INTRIN_COMPTYPE_FROM_TYPE_ELT0 = 0xff; // INTRIN_COMPTYPE_FROM_NODEOUTPUT is for intrinsics to indicate that the // component type of the type is taken from the component type of the specified // argument type. See for example the intrinsics Get*NodeOutputRecords() static const BYTE INTRIN_COMPTYPE_FROM_NODEOUTPUT = 0xfe; enum LEGAL_INTRINSIC_COMPTYPES { LICOMPTYPE_VOID = 0, // void, used for function returns LICOMPTYPE_BOOL = 1, // bool LICOMPTYPE_INT = 2, // i32, int-literal LICOMPTYPE_UINT = 3, // u32, int-literal LICOMPTYPE_ANY_INT = 4, // i32, u32, i64, u64, int-literal LICOMPTYPE_ANY_INT32 = 5, // i32, u32, int-literal LICOMPTYPE_UINT_ONLY = 6, // u32, u64, int-literal; no casts allowed LICOMPTYPE_FLOAT = 7, // f32, partial-precision-f32, float-literal LICOMPTYPE_ANY_FLOAT = 8, // f32, partial-precision-f32, f64, float-literal, // min10-float, min16-float, half LICOMPTYPE_FLOAT_LIKE = 9, // f32, partial-precision-f32, float-literal, // min10-float, min16-float, half LICOMPTYPE_FLOAT_DOUBLE = 10, // f32, partial-precision-f32, f64, float-literal LICOMPTYPE_DOUBLE = 11, // f64, float-literal LICOMPTYPE_DOUBLE_ONLY = 12, // f64; no casts allowed LICOMPTYPE_NUMERIC = 13, // float-literal, f32, partial-precision-f32, f64, // min10-float, min16-float, int-literal, i32, u32, // min12-int, min16-int, min16-uint, i64, u64 LICOMPTYPE_NUMERIC32 = 14, // float-literal, f32, partial-precision-f32, int-literal, i32, u32 LICOMPTYPE_NUMERIC32_ONLY = 15, // float-literal, f32, partial-precision-f32, // int-literal, i32, u32; no casts allowed LICOMPTYPE_ANY = 16, // float-literal, f32, partial-precision-f32, f64, // min10-float, min16-float, int-literal, i32, u32, // min12-int, min16-int, min16-uint, bool, i64, u64 LICOMPTYPE_SAMPLER1D = 17, LICOMPTYPE_SAMPLER2D = 18, LICOMPTYPE_SAMPLER3D = 19, LICOMPTYPE_SAMPLERCUBE = 20, LICOMPTYPE_SAMPLERCMP = 21, LICOMPTYPE_SAMPLER = 22, LICOMPTYPE_STRING = 23, LICOMPTYPE_WAVE = 24, LICOMPTYPE_UINT64 = 25, // u64, int-literal LICOMPTYPE_FLOAT16 = 26, LICOMPTYPE_INT16 = 27, LICOMPTYPE_UINT16 = 28, LICOMPTYPE_NUMERIC16_ONLY = 29, LICOMPTYPE_RAYDESC = 30, LICOMPTYPE_ACCELERATION_STRUCT = 31, LICOMPTYPE_USER_DEFINED_TYPE = 32, LICOMPTYPE_TEXTURE2D = 33, LICOMPTYPE_TEXTURE2DARRAY = 34, LICOMPTYPE_RESOURCE = 35, LICOMPTYPE_INT32_ONLY = 36, LICOMPTYPE_INT64_ONLY = 37, LICOMPTYPE_ANY_INT64 = 38, LICOMPTYPE_FLOAT32_ONLY = 39, LICOMPTYPE_INT8_4PACKED = 40, LICOMPTYPE_UINT8_4PACKED = 41, LICOMPTYPE_ANY_INT16_OR_32 = 42, LICOMPTYPE_SINT16_OR_32_ONLY = 43, LICOMPTYPE_ANY_SAMPLER = 44, LICOMPTYPE_BYTEADDRESSBUFFER = 45, LICOMPTYPE_RWBYTEADDRESSBUFFER = 46, LICOMPTYPE_NODE_RECORD_OR_UAV = 47, LICOMPTYPE_ANY_NODE_OUTPUT_RECORD = 48, LICOMPTYPE_GROUP_NODE_OUTPUT_RECORDS = 49, LICOMPTYPE_THREAD_NODE_OUTPUT_RECORDS = 50, LICOMPTYPE_COUNT = 51 }; static const BYTE IA_SPECIAL_BASE = 0xf0; static const BYTE IA_R = 0xf0; static const BYTE IA_C = 0xf1; static const BYTE IA_R2 = 0xf2; static const BYTE IA_C2 = 0xf3; static const BYTE IA_SPECIAL_SLOTS = 4; struct HLSL_INTRINSIC_ARGUMENT { LPCSTR pName; // Name of the argument; the first argument has the function name. UINT64 qwUsage; // A combination of // AR_QUAL_IN|AR_QUAL_OUT|AR_QUAL_COLMAJOR|AR_QUAL_ROWMAJOR in // parameter tables; other values possible elsewhere. BYTE uTemplateId; // One of INTRIN_TEMPLATE_FROM_TYPE, INTRIN_TEMPLATE_VARARGS // or the argument # the template (layout) must match // (trivially itself). BYTE uLegalTemplates; // A LEGAL_INTRINSIC_TEMPLATES value for allowed // templates. BYTE uComponentTypeId; // INTRIN_COMPTYPE_FROM_TYPE_ELT0, or the argument # // the component (element type) must match (trivially // itself). BYTE uLegalComponentTypes; // A LEGAL_INTRINSIC_COMPTYPES value for allowed // components. BYTE uRows; // Required number of rows, or one of IA_R/IA_C/IA_R2/IA_C2 for // matching input constraints. BYTE uCols; // Required number of cols, or one of IA_R/IA_C/IA_R2/IA_C2 for // matching input constraints. }; struct HLSL_INTRINSIC { UINT Op; // Intrinsic Op ID BOOL bReadOnly; // Only read memory BOOL bReadNone; // Not read memory BOOL bIsWave; // Is a wave-sensitive op INT iOverloadParamIndex; // Parameter decide the overload type, -1 means ret // type UINT uNumArgs; // Count of arguments in pArgs. const HLSL_INTRINSIC_ARGUMENT *pArgs; // Pointer to first argument. }; /////////////////////////////////////////////////////////////////////////////// // Interfaces. CROSS_PLATFORM_UUIDOF(IDxcIntrinsicTable, "f0d4da3f-f863-4660-b8b4-dfd94ded6215") struct IDxcIntrinsicTable : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetTableName(LPCSTR *pTableName) = 0; virtual HRESULT STDMETHODCALLTYPE LookupIntrinsic(LPCWSTR typeName, LPCWSTR functionName, const HLSL_INTRINSIC **pIntrinsic, UINT64 *pLookupCookie) = 0; // Get the lowering strategy for an hlsl extension intrinsic. virtual HRESULT STDMETHODCALLTYPE GetLoweringStrategy(UINT opcode, LPCSTR *pStrategy) = 0; // Callback to support custom naming of hlsl extension intrinsic functions in // dxil. Return the empty string to get the default intrinsic name, which is // the mangled name of the high level intrinsic function. // // Overloaded intrinsics are supported by use of an overload place holder in // the name. The string "$o" in the name will be replaced by the return type // of the intrinsic. virtual HRESULT STDMETHODCALLTYPE GetIntrinsicName(UINT opcode, LPCSTR *pName) = 0; // Callback to support the 'dxil' lowering strategy. // Returns the dxil opcode that the intrinsic should use for lowering. virtual HRESULT STDMETHODCALLTYPE GetDxilOpCode(UINT opcode, UINT *pDxilOpcode) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcSemanticDefineValidator, "1d063e4f-515a-4d57-a12a-431f6a44cfb9") struct IDxcSemanticDefineValidator : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetSemanticDefineWarningsAndErrors( LPCSTR pName, LPCSTR pValue, IDxcBlobEncoding **ppWarningBlob, IDxcBlobEncoding **ppErrorBlob) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcLangExtensions, "282a56b4-3f56-4360-98c7-9ea04a752272") struct IDxcLangExtensions : public IUnknown { public: /// <summary> /// Registers the name of a preprocessor define that has semantic meaning /// and should be preserved for downstream consumers. /// </summary> virtual HRESULT STDMETHODCALLTYPE RegisterSemanticDefine(LPCWSTR name) = 0; /// <summary>Registers a name to exclude from semantic defines.</summary> virtual HRESULT STDMETHODCALLTYPE RegisterSemanticDefineExclusion(LPCWSTR name) = 0; /// <summary>Registers a definition for compilation.</summary> virtual HRESULT STDMETHODCALLTYPE RegisterDefine(LPCWSTR name) = 0; /// <summary>Registers a table of built-in intrinsics.</summary> virtual HRESULT STDMETHODCALLTYPE RegisterIntrinsicTable(IDxcIntrinsicTable *pTable) = 0; /// <summary>Sets an (optional) validator for parsed semantic /// defines.<summary> This provides a hook to check that the semantic defines /// present in the source contain valid data. One validator is used to /// validate all parsed semantic defines. virtual HRESULT STDMETHODCALLTYPE SetSemanticDefineValidator(IDxcSemanticDefineValidator *pValidator) = 0; /// <summary>Sets the name for the root metadata node used in DXIL to hold the /// semantic defines.</summary> virtual HRESULT STDMETHODCALLTYPE SetSemanticDefineMetaDataName(LPCSTR name) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcLangExtensions2, "2490C368-89EE-4491-A4B2-C6547B6C9381") struct IDxcLangExtensions2 : public IDxcLangExtensions { public: virtual HRESULT STDMETHODCALLTYPE SetTargetTriple(LPCSTR name) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcLangExtensions3, "A1B19880-FB1F-4920-9BC5-50356483BAC1") struct IDxcLangExtensions3 : public IDxcLangExtensions2 { public: /// Registers a semantic define which cannot be overriden using the flag /// -override-opt-semdefs virtual HRESULT STDMETHODCALLTYPE RegisterNonOptSemanticDefine(LPCWSTR name) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcSystemAccess, "454b764f-3549-475b-958c-a7a6fcd05fbc") struct IDxcSystemAccess : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE EnumFiles(LPCWSTR fileName, IEnumSTATSTG **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE OpenStorage(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, IUnknown **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE SetStorageTime( IUnknown *storage, const FILETIME *lpCreationTime, const FILETIME *lpLastAccessTime, const FILETIME *lpLastWriteTime) = 0; virtual HRESULT STDMETHODCALLTYPE GetFileInformationForStorage( IUnknown *storage, LPBY_HANDLE_FILE_INFORMATION lpFileInformation) = 0; virtual HRESULT STDMETHODCALLTYPE GetFileTypeForStorage(IUnknown *storage, DWORD *fileType) = 0; virtual HRESULT STDMETHODCALLTYPE CreateHardLinkInStorage(LPCWSTR lpFileName, LPCWSTR lpExistingFileName) = 0; virtual HRESULT STDMETHODCALLTYPE MoveStorage(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName, DWORD dwFlags) = 0; virtual HRESULT STDMETHODCALLTYPE GetFileAttributesForStorage(LPCWSTR lpFileName, DWORD *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE DeleteStorage(LPCWSTR lpFileName) = 0; virtual HRESULT STDMETHODCALLTYPE RemoveDirectoryStorage(LPCWSTR lpFileName) = 0; virtual HRESULT STDMETHODCALLTYPE CreateDirectoryStorage(LPCWSTR lpPathName) = 0; virtual HRESULT STDMETHODCALLTYPE GetCurrentDirectoryForStorage( DWORD nBufferLength, LPWSTR lpBuffer, DWORD *written) = 0; virtual HRESULT STDMETHODCALLTYPE GetMainModuleFileNameW(DWORD nBufferLength, LPWSTR lpBuffer, DWORD *written) = 0; virtual HRESULT STDMETHODCALLTYPE GetTempStoragePath(DWORD nBufferLength, LPWSTR lpBuffer, DWORD *written) = 0; virtual HRESULT STDMETHODCALLTYPE SupportsCreateSymbolicLink(BOOL *pResult) = 0; virtual HRESULT STDMETHODCALLTYPE CreateSymbolicLinkInStorage( LPCWSTR lpSymlinkFileName, LPCWSTR lpTargetFileName, DWORD dwFlags) = 0; virtual HRESULT STDMETHODCALLTYPE CreateStorageMapping( IUnknown *hFile, DWORD flProtect, DWORD dwMaximumSizeHigh, DWORD dwMaximumSizeLow, IUnknown **pResult) = 0; virtual HRESULT MapViewOfFile(IUnknown *hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow, SIZE_T dwNumberOfBytesToMap, ID3D10Blob **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE OpenStdStorage(int standardFD, IUnknown **pResult) = 0; virtual HRESULT STDMETHODCALLTYPE GetStreamDisplay(ITextFont **textFont, unsigned *columnCount) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcContainerEventsHandler, "e991ca8d-2045-413c-a8b8-788b2c06e14d") struct IDxcContainerEventsHandler : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE OnDxilContainerBuilt(IDxcBlob *pSource, IDxcBlob **ppTarget) = 0; }; CROSS_PLATFORM_UUIDOF(IDxcContainerEvent, "0cfc5058-342b-4ff2-83f7-04c12aad3d01") struct IDxcContainerEvent : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE RegisterDxilContainerEventHandler( IDxcContainerEventsHandler *pHandler, UINT64 *pCookie) = 0; virtual HRESULT STDMETHODCALLTYPE UnRegisterDxilContainerEventHandler(UINT64 cookie) = 0; }; #endif
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilContainer/DxilRDATParts.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilRDATParts.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "dxc/DxilContainer/DxilRuntimeReflection.h" #include "dxc/Support/WinIncludes.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/raw_ostream.h" #include <set> #include <string> #include <unordered_map> #include <vector> namespace hlsl { class RDATPart { public: virtual uint32_t GetPartSize() const { return 0; } virtual void Write(void *ptr) {} virtual RDAT::RuntimeDataPartType GetType() const { return RDAT::RuntimeDataPartType::Invalid; } virtual ~RDATPart() {} }; class StringBufferPart : public RDATPart { private: std::unordered_map<std::string, uint32_t> m_Map; std::vector<llvm::StringRef> m_List; size_t m_Size = 0; public: StringBufferPart() { // Always start string table with null so empty/null strings have offset of // zero Insert(""); } // returns the offset of the name inserted uint32_t Insert(llvm::StringRef str); RDAT::RuntimeDataPartType GetType() const { return RDAT::RuntimeDataPartType::StringBuffer; } uint32_t GetPartSize() const { return m_Size; } void Write(void *ptr); }; class IndexArraysPart : public RDATPart { private: std::vector<uint32_t> m_IndexBuffer; // Use m_IndexSet with CmpIndices to avoid duplicate index arrays struct CmpIndices { const IndexArraysPart &Table; CmpIndices(const IndexArraysPart &table) : Table(table) {} bool operator()(uint32_t left, uint32_t right) const { const uint32_t *pLeft = Table.m_IndexBuffer.data() + left; const uint32_t *pRight = Table.m_IndexBuffer.data() + right; if (*pLeft != *pRight) return (*pLeft < *pRight); uint32_t count = *pLeft; for (unsigned i = 0; i < count; i++) { ++pLeft; ++pRight; if (*pLeft != *pRight) return (*pLeft < *pRight); } return false; } }; std::set<uint32_t, CmpIndices> m_IndexSet; public: IndexArraysPart() : m_IndexBuffer(), m_IndexSet(*this) {} template <class iterator> uint32_t AddIndex(iterator begin, iterator end) { uint32_t newOffset = m_IndexBuffer.size(); m_IndexBuffer.push_back(0); // Size: update after insertion m_IndexBuffer.insert(m_IndexBuffer.end(), begin, end); m_IndexBuffer[newOffset] = (m_IndexBuffer.size() - newOffset) - 1; // Check for duplicate, return new offset if not duplicate auto insertResult = m_IndexSet.insert(newOffset); if (insertResult.second) return newOffset; // Otherwise it was a duplicate, so chop off the size and return the // original m_IndexBuffer.resize(newOffset); return *insertResult.first; } RDAT::RuntimeDataPartType GetType() const { return RDAT::RuntimeDataPartType::IndexArrays; } uint32_t GetPartSize() const { return sizeof(uint32_t) * m_IndexBuffer.size(); } void Write(void *ptr) { memcpy(ptr, m_IndexBuffer.data(), m_IndexBuffer.size() * sizeof(uint32_t)); } }; class RawBytesPart : public RDATPart { private: std::unordered_map<std::string, uint32_t> m_Map; std::vector<llvm::StringRef> m_List; size_t m_Size = 0; public: RawBytesPart() {} uint32_t Insert(const void *pData, size_t dataSize); RDAT::BytesRef InsertBytesRef(const void *pData, size_t dataSize) { RDAT::BytesRef ret = {}; ret.Offset = Insert(pData, dataSize); ret.Size = dataSize; return ret; } RDAT::RuntimeDataPartType GetType() const { return RDAT::RuntimeDataPartType::RawBytes; } uint32_t GetPartSize() const { return m_Size; } void Write(void *ptr); }; class RDATTable : public RDATPart { protected: // m_map is map of records to their index. // Used to alias identical records. std::unordered_map<std::string, uint32_t> m_map; std::vector<llvm::StringRef> m_rows; size_t m_RecordStride = 0; bool m_bDeduplicationEnabled = false; RDAT::RuntimeDataPartType m_Type = RDAT::RuntimeDataPartType::Invalid; uint32_t InsertImpl(const void *ptr, size_t size); public: virtual ~RDATTable() {} void SetType(RDAT::RuntimeDataPartType type) { m_Type = type; } RDAT::RuntimeDataPartType GetType() const { return m_Type; } void SetRecordStride(size_t RecordStride); size_t GetRecordStride() const { return m_RecordStride; } void SetDeduplication(bool bEnabled = true) { m_bDeduplicationEnabled = bEnabled; } uint32_t Count() { size_t count = m_rows.size(); return (count < UINT32_MAX) ? count : 0; } template <typename RecordType> uint32_t Insert(const RecordType &data) { return InsertImpl(&data, sizeof(RecordType)); } void Write(void *ptr); uint32_t GetPartSize() const; }; } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilContainer/RDAT_SubobjectTypes.inl
/////////////////////////////////////////////////////////////////////////////// // // // RDAT_SubobjectTypes.inl // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Defines types used in Dxil Library Runtime Data (RDAT). // // // /////////////////////////////////////////////////////////////////////////////// // clang-format off // Macro indentation makes this file easier to read, but clang-format flattens // everything. Turn off clang-format for this file. ////////////////////////////////////////////////////////////////////// // The following require validator version 1.4 and above. #ifdef DEF_RDAT_ENUMS // Nothing yet #endif // DEF_RDAT_ENUMS #ifdef DEF_DXIL_ENUMS RDAT_DXIL_ENUM_START(hlsl::DXIL::SubobjectKind, uint32_t) RDAT_ENUM_VALUE_NODEF(StateObjectConfig) RDAT_ENUM_VALUE_NODEF(GlobalRootSignature) RDAT_ENUM_VALUE_NODEF(LocalRootSignature) RDAT_ENUM_VALUE_NODEF(SubobjectToExportsAssociation) RDAT_ENUM_VALUE_NODEF(RaytracingShaderConfig) RDAT_ENUM_VALUE_NODEF(RaytracingPipelineConfig) RDAT_ENUM_VALUE_NODEF(HitGroup) RDAT_ENUM_VALUE_NODEF(RaytracingPipelineConfig1) // No need to define this here //RDAT_ENUM_VALUE_NODEF(NumKinds) #if DEF_RDAT_ENUMS == DEF_RDAT_DUMP_IMPL static_assert((unsigned)hlsl::DXIL::SubobjectKind::NumKinds == 13, "otherwise, RDAT_DXIL_ENUM definition needs updating"); #endif RDAT_ENUM_END() RDAT_DXIL_ENUM_START(hlsl::DXIL::StateObjectFlags, uint32_t) RDAT_ENUM_VALUE_NODEF(AllowLocalDependenciesOnExternalDefinitions) RDAT_ENUM_VALUE_NODEF(AllowExternalDependenciesOnLocalDefinitions) RDAT_ENUM_VALUE_NODEF(AllowStateObjectAdditions) // No need to define these masks here //RDAT_ENUM_VALUE_NODEF(ValidMask_1_4) //RDAT_ENUM_VALUE_NODEF(ValidMask) #if DEF_RDAT_ENUMS == DEF_RDAT_DUMP_IMPL static_assert((unsigned)hlsl::DXIL::StateObjectFlags::ValidMask == 0x7, "otherwise, RDAT_DXIL_ENUM definition needs updating"); #endif RDAT_ENUM_END() RDAT_DXIL_ENUM_START(hlsl::DXIL::HitGroupType, uint32_t) RDAT_ENUM_VALUE_NODEF(Triangle) RDAT_ENUM_VALUE_NODEF(ProceduralPrimitive) #if DEF_RDAT_ENUMS == DEF_RDAT_DUMP_IMPL static_assert((unsigned)hlsl::DXIL::HitGroupType::LastEntry == 2, "otherwise, RDAT_DXIL_ENUM definition needs updating"); #endif RDAT_ENUM_END() RDAT_DXIL_ENUM_START(hlsl::DXIL::RaytracingPipelineFlags, uint32_t) RDAT_ENUM_VALUE_NODEF(None) RDAT_ENUM_VALUE_NODEF(SkipTriangles) RDAT_ENUM_VALUE_NODEF(SkipProceduralPrimitives) // No need to define mask here // RDAT_ENUM_VALUE_NODEF(ValidMask) #if DEF_RDAT_ENUMS == DEF_RDAT_DUMP_IMPL static_assert((unsigned)hlsl::DXIL::RaytracingPipelineFlags::ValidMask == 0x300, "otherwise, RDAT_DXIL_ENUM definition needs updating"); #endif RDAT_ENUM_END() #endif // DEF_DXIL_ENUMS #ifdef DEF_RDAT_TYPES #define RECORD_TYPE StateObjectConfig_t RDAT_STRUCT(StateObjectConfig_t) RDAT_FLAGS(uint32_t, hlsl::DXIL::StateObjectFlags, Flags) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE RootSignature_t RDAT_STRUCT(RootSignature_t) RDAT_BYTES(Data) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE SubobjectToExportsAssociation_t RDAT_STRUCT(SubobjectToExportsAssociation_t) RDAT_STRING(Subobject) RDAT_STRING_ARRAY_REF(Exports) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE RaytracingShaderConfig_t RDAT_STRUCT(RaytracingShaderConfig_t) RDAT_VALUE(uint32_t, MaxPayloadSizeInBytes) RDAT_VALUE(uint32_t, MaxAttributeSizeInBytes) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE RaytracingPipelineConfig_t RDAT_STRUCT(RaytracingPipelineConfig_t) RDAT_VALUE(uint32_t, MaxTraceRecursionDepth) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE HitGroup_t RDAT_STRUCT(HitGroup_t) RDAT_ENUM(uint32_t, hlsl::DXIL::HitGroupType, Type) RDAT_STRING(AnyHit) RDAT_STRING(ClosestHit) RDAT_STRING(Intersection) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE RaytracingPipelineConfig1_t RDAT_STRUCT(RaytracingPipelineConfig1_t) RDAT_VALUE(uint32_t, MaxTraceRecursionDepth) RDAT_FLAGS(uint32_t, hlsl::DXIL::RaytracingPipelineFlags, Flags) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE RuntimeDataSubobjectInfo RDAT_STRUCT_TABLE(RuntimeDataSubobjectInfo, SubobjectTable) RDAT_ENUM(uint32_t, hlsl::DXIL::SubobjectKind, Kind) RDAT_STRING(Name) RDAT_UNION() RDAT_UNION_IF(StateObjectConfig, ((uint32_t)pRecord->Kind == (uint32_t)hlsl::DXIL::SubobjectKind::StateObjectConfig)) RDAT_RECORD_VALUE(StateObjectConfig_t, StateObjectConfig) RDAT_UNION_ELIF( RootSignature, ((uint32_t)pRecord->Kind == (uint32_t)hlsl::DXIL::SubobjectKind::GlobalRootSignature) || ((uint32_t)pRecord->Kind == (uint32_t)hlsl::DXIL::SubobjectKind::LocalRootSignature)) RDAT_RECORD_VALUE(RootSignature_t, RootSignature) RDAT_UNION_ELIF( SubobjectToExportsAssociation, ((uint32_t)pRecord->Kind == (uint32_t)hlsl::DXIL::SubobjectKind::SubobjectToExportsAssociation)) RDAT_RECORD_VALUE(SubobjectToExportsAssociation_t, SubobjectToExportsAssociation) RDAT_UNION_ELIF( RaytracingShaderConfig, ((uint32_t)pRecord->Kind == (uint32_t)hlsl::DXIL::SubobjectKind::RaytracingShaderConfig)) RDAT_RECORD_VALUE(RaytracingShaderConfig_t, RaytracingShaderConfig) RDAT_UNION_ELIF( RaytracingPipelineConfig, ((uint32_t)pRecord->Kind == (uint32_t)hlsl::DXIL::SubobjectKind::RaytracingPipelineConfig)) RDAT_RECORD_VALUE(RaytracingPipelineConfig_t, RaytracingPipelineConfig) RDAT_UNION_ELIF(HitGroup, ((uint32_t)pRecord->Kind == (uint32_t)hlsl::DXIL::SubobjectKind::HitGroup)) RDAT_RECORD_VALUE(HitGroup_t, HitGroup) RDAT_UNION_ELIF( RaytracingPipelineConfig1, ((uint32_t)pRecord->Kind == (uint32_t)hlsl::DXIL::SubobjectKind::RaytracingPipelineConfig1)) RDAT_RECORD_VALUE(RaytracingPipelineConfig1_t, RaytracingPipelineConfig1) RDAT_UNION_ENDIF() RDAT_UNION_END() // Note: this is how one could inject custom code into one of the definition // modes: #if DEF_RDAT_TYPES == DEF_RDAT_READER // Add custom code here that only gets added to the reader class definition #endif RDAT_STRUCT_END() #undef RECORD_TYPE #endif // DEF_RDAT_TYPES // clang-format on
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilContainer/DxcContainerBuilder.h
/////////////////////////////////////////////////////////////////////////////// // // // DxcContainerBuilder.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Implements the Dxil Container Builder // // // /////////////////////////////////////////////////////////////////////////////// #pragma once // Include Windows header early for DxilHash.h. #include "dxc/Support/Global.h" #include "dxc/Support/WinIncludes.h" #include "dxc/DxilContainer/DxilContainer.h" #include "dxc/DxilHash/DxilHash.h" #include "dxc/Support/microcom.h" #include "dxc/dxcapi.h" #include "llvm/ADT/SmallVector.h" using namespace hlsl; namespace hlsl { class AbstractMemoryStream; } class DxcContainerBuilder : public IDxcContainerBuilder { public: // Loads DxilContainer to the builder HRESULT STDMETHODCALLTYPE Load(IDxcBlob *pDxilContainerHeader) override; // Add the given part with fourCC HRESULT STDMETHODCALLTYPE AddPart(UINT32 fourCC, IDxcBlob *pSource) override; // Remove the part with fourCC HRESULT STDMETHODCALLTYPE RemovePart(UINT32 fourCC) override; // Builds a container of the given container builder state HRESULT STDMETHODCALLTYPE SerializeContainer(IDxcOperationResult **ppResult) override; DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_CTOR(DxcContainerBuilder) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) override { return DoBasicQueryInterface<IDxcContainerBuilder>(this, riid, ppvObject); } void Init(const char *warning = nullptr) { m_warning = warning; m_RequireValidation = false; m_HasPrivateData = false; m_HashFunction = nullptr; } protected: DXC_MICROCOM_TM_REF_FIELDS() private: class DxilPart { public: UINT32 m_fourCC; CComPtr<IDxcBlob> m_Blob; DxilPart(UINT32 fourCC, IDxcBlob *pSource) : m_fourCC(fourCC), m_Blob(pSource) {} }; typedef llvm::SmallVector<DxilPart, 8> PartList; PartList m_parts; CComPtr<IDxcBlob> m_pContainer; const char *m_warning; bool m_RequireValidation; bool m_HasPrivateData; // Function to compute hash when valid dxil container is built // This is nullptr if loaded container has invalid hash HASH_FUNCTION_PROTO *m_HashFunction; void DetermineHashFunctionFromContainerContents( const DxilContainerHeader *ContainerHeader); void HashAndUpdate(DxilContainerHeader *ContainerHeader); UINT32 ComputeContainerSize(); HRESULT UpdateContainerHeader(AbstractMemoryStream *pStream, uint32_t containerSize); HRESULT UpdateOffsetTable(AbstractMemoryStream *pStream); HRESULT UpdateParts(AbstractMemoryStream *pStream); void AddPart(DxilPart &&part); };
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilContainer/RDAT_Macros.inl
/////////////////////////////////////////////////////////////////////////////// // // // RDAT_Macros.inl // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Defines macros use to define types Dxil Library Runtime Data (RDAT). // // // /////////////////////////////////////////////////////////////////////////////// // Pay attention to alignment when organizing structures. // RDAT_STRING and *_REF types are always 4 bytes. // RDAT_BYTES is 2 * 4 bytes. // These are the modes set to DEF_RDAT_TYPES and/or DEF_RDAT_ENUMS that drive // macro expansion for types and enums which define the necessary declarations // and code. // While some of associated macros sets are not defined in this file, these // definitions allow custom paths in the type definition files in certain cases. // DEF_RDAT_TYPES and DEF_RDAT_ENUMS - define empty macros for anything not // already defined #define DEF_RDAT_DEFAULTS 1 // DEF_RDAT_TYPES - define structs with basic types, matching RDAT format #define DEF_RDAT_TYPES_BASIC_STRUCT 2 // DEF_RDAT_TYPES - define structs using helpers, matching RDAT format #define DEF_RDAT_TYPES_USE_HELPERS 3 // DEF_RDAT_TYPES and DEF_RDAT_ENUMS - write dump declarations #define DEF_RDAT_DUMP_DECL 4 // DEF_RDAT_TYPES and DEF_RDAT_ENUMS - write dump implementation #define DEF_RDAT_DUMP_IMPL 5 // DEF_RDAT_TYPES - define deserialized version using pointers instead of // offsets #define DEF_RDAT_TYPES_USE_POINTERS 6 // DEF_RDAT_ENUMS - declare enums with enum class #define DEF_RDAT_ENUM_CLASS 7 // DEF_RDAT_TYPES - define type traits #define DEF_RDAT_TRAITS 8 // DEF_RDAT_TYPES - forward declare type struct/class #define DEF_RDAT_TYPES_FORWARD_DECL 9 // DEF_RDAT_TYPES and DEF_RDAT_ENUMS - write reader classes #define DEF_RDAT_READER_DECL 10 // DEF_RDAT_TYPES and DEF_RDAT_ENUMS - write reader classes #define DEF_RDAT_READER_IMPL 11 // DEF_RDAT_TYPES and DEF_RDAT_ENUMS - define structural validation #define DEF_RDAT_STRUCT_VALIDATION 13 // clang-format off #define CLOSE_COMPOUND_DECL }; // clang-format on #define GLUE2(a, b) a##b #define GLUE(a, b) GLUE2(a, b) #ifdef DEF_RDAT_TYPES #if DEF_RDAT_TYPES == DEF_RDAT_TYPES_FORWARD_DECL #define RDAT_STRUCT(type) \ struct type; \ class type##_Reader; #define RDAT_STRUCT_DERIVED(type, base) RDAT_STRUCT(type) #define RDAT_WRAP_ARRAY(type, count, type_name) \ struct type_name { \ type arr[count]; \ }; #elif DEF_RDAT_TYPES == DEF_RDAT_TYPES_BASIC_STRUCT #define RDAT_STRUCT(type) struct type { #define RDAT_STRUCT_DERIVED(type, base) struct type : public base { #define RDAT_STRUCT_END() CLOSE_COMPOUND_DECL #define RDAT_UNION() union { #define RDAT_UNION_END() CLOSE_COMPOUND_DECL #define RDAT_RECORD_REF(type, name) uint32_t name; #define RDAT_RECORD_ARRAY_REF(type, name) uint32_t name; #define RDAT_RECORD_VALUE(type, name) type name; #define RDAT_STRING(name) uint32_t name; #define RDAT_STRING_ARRAY_REF(name) uint32_t name; #define RDAT_VALUE(type, name) type name; #define RDAT_INDEX_ARRAY_REF(name) uint32_t name; #define RDAT_ENUM(sTy, eTy, name) sTy name; #define RDAT_FLAGS(sTy, eTy, name) sTy name; #define RDAT_BYTES(name) \ uint32_t name; \ uint32_t name##_Size; \ name; #define RDAT_ARRAY_VALUE(type, count, type_name, name) type_name name; #elif DEF_RDAT_TYPES == DEF_RDAT_TYPES_USE_HELPERS #define RDAT_STRUCT(type) struct type { #define RDAT_STRUCT_DERIVED(type, base) struct type : public base { #define RDAT_STRUCT_END() CLOSE_COMPOUND_DECL #define RDAT_UNION() union { #define RDAT_UNION_END() CLOSE_COMPOUND_DECL #define RDAT_RECORD_REF(type, name) RecordRef<type> name; #define RDAT_RECORD_ARRAY_REF(type, name) RecordArrayRef<type> name; #define RDAT_RECORD_VALUE(type, name) struct type name; #define RDAT_STRING(name) RDATString name; #define RDAT_STRING_ARRAY_REF(name) RDATStringArray name; #define RDAT_VALUE(type, name) type name; #define RDAT_INDEX_ARRAY_REF(name) IndexArrayRef name; #define RDAT_ENUM(sTy, eTy, name) sTy name; #define RDAT_FLAGS(sTy, eTy, name) sTy name; #define RDAT_BYTES(name) hlsl::RDAT::BytesRef name; #define RDAT_ARRAY_VALUE(type, count, type_name, name) type_name name; #define RDAT_STRUCT_TABLE_DERIVED(type, base, table) \ template <> constexpr const char *RecordTraits<type>::TypeName(); \ template <> constexpr RecordTableIndex RecordTraits<type>::TableIndex(); \ template <> constexpr RuntimeDataPartType RecordTraits<type>::PartType(); \ template <> constexpr size_t RecordTraits<base>::DerivedRecordSize(); \ RDAT_STRUCT_DERIVED(type, base) #elif DEF_RDAT_TYPES == DEF_RDAT_READER_DECL #define RDAT_STRUCT(type) \ class type##_Reader : public RecordReader<type##_Reader> { \ public: \ typedef type RecordType; \ type##_Reader(const BaseRecordReader &reader); \ type##_Reader() : RecordReader<type##_Reader>() {} \ const RecordType *asRecord() const; \ const RecordType *operator->() const { return asRecord(); } #define RDAT_STRUCT_DERIVED(type, base) \ class type##_Reader : public base##_Reader { \ public: \ typedef type RecordType; \ type##_Reader(const BaseRecordReader &reader); \ type##_Reader(); \ const RecordType *asRecord() const; \ const RecordType *operator->() const { return asRecord(); } #define RDAT_STRUCT_END() CLOSE_COMPOUND_DECL #define RDAT_UNION_IF(name, expr) bool has##name() const; #define RDAT_UNION_ELIF(name, expr) RDAT_UNION_IF(name, expr) #define RDAT_RECORD_REF(type, name) type##_Reader get##name() const; #define RDAT_RECORD_ARRAY_REF(type, name) \ RecordArrayReader<type##_Reader> get##name() const; #define RDAT_RECORD_VALUE(type, name) type##_Reader get##name() const; #define RDAT_STRING(name) const char *get##name() const; #define RDAT_STRING_ARRAY_REF(name) StringArrayReader get##name() const; #define RDAT_VALUE(type, name) type get##name() const; #define RDAT_INDEX_ARRAY_REF(name) IndexTableReader::IndexRow get##name() const; #define RDAT_ENUM(sTy, eTy, name) eTy get##name() const; #define RDAT_FLAGS(sTy, eTy, name) sTy get##name() const; #define RDAT_BYTES(name) \ const void *get##name() const; \ uint32_t size##name() const; #define RDAT_ARRAY_VALUE(type, count, type_name, name) \ type_name get##name() const; #elif DEF_RDAT_TYPES == DEF_RDAT_READER_IMPL #define RDAT_STRUCT(type) \ type##_Reader::type##_Reader(const BaseRecordReader &reader) \ : RecordReader<type##_Reader>(reader) {} \ const type *type##_Reader::asRecord() const { \ return BaseRecordReader::asRecord<type>(); \ } #define RDAT_STRUCT_DERIVED(type, base) \ type##_Reader::type##_Reader(const BaseRecordReader &reader) \ : base##_Reader(reader) { \ if ((m_pContext || m_pRecord) && m_Size < sizeof(type)) \ InvalidateReader(); \ } \ type##_Reader::type##_Reader() : base##_Reader() {} \ const type *type##_Reader::asRecord() const { \ return BaseRecordReader::asRecord<type>(); \ } #define RDAT_STRUCT_TABLE(type, table) RDAT_STRUCT(type) #define RDAT_STRUCT_TABLE_DERIVED(type, base, table) \ RDAT_STRUCT_DERIVED(type, base) #define RDAT_UNION_IF(name, expr) \ bool GLUE(RECORD_TYPE, _Reader)::has##name() const { \ if (auto *pRecord = asRecord()) \ return !!(expr); \ return false; \ } #define RDAT_UNION_ELIF(name, expr) RDAT_UNION_IF(name, expr) #define RDAT_RECORD_REF(type, name) \ type##_Reader GLUE(RECORD_TYPE, _Reader)::get##name() const { \ return GetField_RecordRef<type##_Reader>(&(asRecord()->name)); \ } #define RDAT_RECORD_ARRAY_REF(type, name) \ RecordArrayReader<type##_Reader> GLUE(RECORD_TYPE, _Reader)::get##name() \ const { \ return GetField_RecordArrayRef<type##_Reader>(&(asRecord()->name)); \ } #define RDAT_RECORD_VALUE(type, name) \ type##_Reader GLUE(RECORD_TYPE, _Reader)::get##name() const { \ return GetField_RecordValue<type##_Reader>(&(asRecord()->name)); \ } #define RDAT_STRING(name) \ const char *GLUE(RECORD_TYPE, _Reader)::get##name() const { \ return GetField_String(&(asRecord()->name)); \ } #define RDAT_STRING_ARRAY_REF(name) \ StringArrayReader GLUE(RECORD_TYPE, _Reader)::get##name() const { \ return GetField_StringArray(&(asRecord()->name)); \ } #define RDAT_VALUE(type, name) \ type GLUE(RECORD_TYPE, _Reader)::get##name() const { \ return GetField_Value<type, type>(&(asRecord()->name)); \ } #define RDAT_INDEX_ARRAY_REF(name) \ IndexTableReader::IndexRow GLUE(RECORD_TYPE, _Reader)::get##name() const { \ return GetField_IndexArray(&(asRecord()->name)); \ } #define RDAT_ENUM(sTy, eTy, name) \ eTy GLUE(RECORD_TYPE, _Reader)::get##name() const { \ return GetField_Value<eTy, sTy>(&(asRecord()->name)); \ } #define RDAT_FLAGS(sTy, eTy, name) \ sTy GLUE(RECORD_TYPE, _Reader)::get##name() const { \ return GetField_Value<sTy, sTy>(&(asRecord()->name)); \ } #define RDAT_BYTES(name) \ const void *GLUE(RECORD_TYPE, _Reader)::get##name() const { \ return GetField_Bytes(&(asRecord()->name)); \ } \ uint32_t GLUE(RECORD_TYPE, _Reader)::size##name() const { \ return GetField_BytesSize(&(asRecord()->name)); \ } #define RDAT_ARRAY_VALUE(type, count, type_name, name) \ type_name GLUE(RECORD_TYPE, _Reader)::get##name() const { \ return GetField_Value<type_name, type_name>(&(asRecord()->name)); \ } #elif DEF_RDAT_TYPES == DEF_RDAT_STRUCT_VALIDATION #define RDAT_STRUCT(type) \ template <> \ bool ValidateRecord<type>(const RDATContext &ctx, const type *pRecord) { \ type##_Reader reader(BaseRecordReader( \ &ctx, (void *)pRecord, (uint32_t)RecordTraits<type>::RecordSize())); #define RDAT_STRUCT_DERIVED(type, base) RDAT_STRUCT(type) #define RDAT_STRUCT_END() \ return true; \ } #define RDAT_UNION_IF(name, expr) if (reader.has##name()) { #define RDAT_UNION_ELIF(name, expr) \ } \ else if (reader.has##name()) { #define RDAT_UNION_ENDIF() } #define RDAT_RECORD_REF(type, name) \ if (!ValidateRecordRef<type>(ctx, pRecord->name)) \ return false; #define RDAT_RECORD_ARRAY_REF(type, name) \ if (!ValidateRecordArrayRef<type>(ctx, pRecord->name)) \ return false; #define RDAT_RECORD_VALUE(type, name) \ if (!ValidateRecord<type>(ctx, &pRecord->name)) \ return false; #define RDAT_STRING(name) \ if (!ValidateStringRef(ctx, pRecord->name)) \ return false; #define RDAT_STRING_ARRAY_REF(name) \ if (!ValidateStringArrayRef(ctx, pRecord->name)) \ return false; #define RDAT_INDEX_ARRAY_REF(name) \ if (!ValidateIndexArrayRef(ctx, pRecord->name)) \ return false; #elif DEF_RDAT_TYPES == DEF_RDAT_DUMP_IMPL #define RDAT_STRUCT(type) \ template <> \ void RecordDumper<hlsl::RDAT::type>::Dump( \ const hlsl::RDAT::RDATContext &ctx, DumpContext &d) const { \ d.Indent(); \ const hlsl::RDAT::type *pRecord = this; \ type##_Reader reader(BaseRecordReader( \ &ctx, (void *)pRecord, (uint32_t)RecordTraits<type>::RecordSize())); #define RDAT_STRUCT_DERIVED(type, base) \ template <> \ const char *RecordRefDumper<hlsl::RDAT::base>::TypeNameDerived( \ const hlsl::RDAT::RDATContext &ctx) const { \ return TypeName<hlsl::RDAT::type>(ctx); \ } \ template <> \ void RecordRefDumper<hlsl::RDAT::base>::DumpDerived( \ const hlsl::RDAT::RDATContext &ctx, DumpContext &d) const { \ Dump<hlsl::RDAT::type>(ctx, d); \ } \ template <> \ void RecordDumper<hlsl::RDAT::type>::Dump( \ const hlsl::RDAT::RDATContext &ctx, DumpContext &d) const; \ template <> \ void DumpWithBase<hlsl::RDAT::type>(const hlsl::RDAT::RDATContext &ctx, \ DumpContext &d, \ const hlsl::RDAT::type *pRecord) { \ DumpWithBase<hlsl::RDAT::base>(ctx, d, pRecord); \ static_cast<const RecordDumper<hlsl::RDAT::type> *>(pRecord)->Dump(ctx, \ d); \ } \ RDAT_STRUCT(type) #define RDAT_STRUCT_END() \ d.Dedent(); \ } #define RDAT_UNION_IF(name, expr) if (reader.has##name()) { #define RDAT_UNION_ELIF(name, expr) \ } \ else if (reader.has##name()) { #define RDAT_UNION_ENDIF() } #define RDAT_RECORD_REF(type, name) DumpRecordRef(ctx, d, #type, #name, name); #define RDAT_RECORD_ARRAY_REF(type, name) \ DumpRecordArrayRef(ctx, d, #type, #name, name); #define RDAT_RECORD_VALUE(type, name) \ DumpRecordValue(ctx, d, #type, #name, &name); #define RDAT_STRING(name) \ d.WriteLn(#name ": ", QuotedStringValue(name.Get(ctx))); #define RDAT_STRING_ARRAY_REF(name) DumpStringArray(ctx, d, #name, name); #define RDAT_VALUE(type, name) d.WriteLn(#name ": ", name); #define RDAT_VALUE_HEX(type, name) \ d.WriteLn(#name ": ", std::hex, std::showbase, name); #define RDAT_INDEX_ARRAY_REF(name) DumpIndexArray(ctx, d, #name, name); #define RDAT_ENUM(sTy, eTy, name) d.DumpEnum<eTy>(#name, (eTy)name); #define RDAT_FLAGS(sTy, eTy, name) d.DumpFlags<eTy, sTy>(#name, name); #define RDAT_BYTES(name) DumpBytesRef(ctx, d, #name, name); #define RDAT_ARRAY_VALUE(type, count, type_name, name) \ DumpValueArray<type>(d, #name, #type, &name, count); #elif DEF_RDAT_TYPES == DEF_RDAT_TRAITS #define RDAT_STRUCT(type) \ template <> constexpr const char *RecordTraits<type>::TypeName() { \ return #type; \ } #define RDAT_STRUCT_DERIVED(type, base) RDAT_STRUCT(type) #define RDAT_STRUCT_TABLE(type, table) \ RDAT_STRUCT(type) \ template <> constexpr RecordTableIndex RecordTraits<type>::TableIndex() { \ return RecordTableIndex::table; \ } \ template <> constexpr RuntimeDataPartType RecordTraits<type>::PartType() { \ return RuntimeDataPartType::table; \ } #define RDAT_STRUCT_TABLE_DERIVED(type, base, table) \ RDAT_STRUCT_DERIVED(type, base) \ template <> constexpr RecordTableIndex RecordTraits<type>::TableIndex() { \ return RecordTableIndex::table; \ } \ template <> constexpr RuntimeDataPartType RecordTraits<type>::PartType() { \ return RuntimeDataPartType::table; \ } \ template <> constexpr size_t RecordTraits<base>::DerivedRecordSize() { \ return RecordTraits<type>::MaxRecordSize(); \ } #endif // DEF_RDAT_TYPES cases // Define any undefined macros to defaults #ifndef RDAT_STRUCT #define RDAT_STRUCT(type) #endif #ifndef RDAT_STRUCT_DERIVED #define RDAT_STRUCT_DERIVED(type, base) #endif #ifndef RDAT_STRUCT_TABLE #define RDAT_STRUCT_TABLE(type, table) RDAT_STRUCT(type) #endif #ifndef RDAT_STRUCT_TABLE_DERIVED #define RDAT_STRUCT_TABLE_DERIVED(type, base, table) \ RDAT_STRUCT_DERIVED(type, base) #endif #ifndef RDAT_STRUCT_END #define RDAT_STRUCT_END() #endif #ifndef RDAT_UNION #define RDAT_UNION() #endif #ifndef RDAT_UNION_IF #define RDAT_UNION_IF( \ name, expr) // In expr: 'this' is reader; pRecord is record struct #endif #ifndef RDAT_UNION_ELIF #define RDAT_UNION_ELIF( \ name, expr) // In expr: 'this' is reader; pRecord is record struct #endif #ifndef RDAT_UNION_ENDIF #define RDAT_UNION_ENDIF() #endif #ifndef RDAT_UNION_END #define RDAT_UNION_END() #endif #ifndef RDAT_RECORD_REF #define RDAT_RECORD_REF( \ type, name) // always use base record type in RDAT_RECORD_REF #endif #ifndef RDAT_RECORD_ARRAY_REF #define RDAT_RECORD_ARRAY_REF( \ type, name) // always use base record type in RDAT_RECORD_ARRAY_REF #endif #ifndef RDAT_RECORD_VALUE #define RDAT_RECORD_VALUE(type, name) #endif #ifndef RDAT_STRING #define RDAT_STRING(name) #endif #ifndef RDAT_STRING_ARRAY_REF #define RDAT_STRING_ARRAY_REF(name) #endif #ifndef RDAT_VALUE #define RDAT_VALUE(type, name) #endif #ifndef RDAT_VALUE_HEX #define RDAT_VALUE_HEX(type, name) RDAT_VALUE(type, name) #endif #ifndef RDAT_INDEX_ARRAY_REF #define RDAT_INDEX_ARRAY_REF(name) // ref to array of uint32_t values #endif #ifndef RDAT_ENUM #define RDAT_ENUM(sTy, eTy, name) #endif #ifndef RDAT_FLAGS #define RDAT_FLAGS(sTy, eTy, name) #endif #ifndef RDAT_BYTES #define RDAT_BYTES(name) #endif #ifndef RDAT_WRAP_ARRAY #define RDAT_WRAP_ARRAY(type, count, \ type_name) // define struct-wrapped array type here #endif #ifndef RDAT_ARRAY_VALUE #define RDAT_ARRAY_VALUE(type, count, type_name, \ name) // define struct-wrapped array member #endif #endif // DEF_RDAT_TYPES defined #if defined(DEF_RDAT_ENUMS) || defined(DEF_DXIL_ENUMS) #if DEF_RDAT_ENUMS == DEF_RDAT_ENUM_CLASS #define RDAT_ENUM_START(eTy, sTy) enum class eTy : sTy { // No RDAT_DXIL_ENUM_START, DXIL enums are defined elsewhere #define RDAT_ENUM_VALUE(name, value) name = value, #define RDAT_ENUM_VALUE_ALIAS(name, value) name = value, #define RDAT_ENUM_VALUE_NODEF(name) name, #define RDAT_ENUM_END() CLOSE_COMPOUND_DECL #elif DEF_RDAT_ENUMS == DEF_RDAT_DUMP_DECL #define RDAT_ENUM_START(eTy, sTy) const char *ToString(eTy e); #define RDAT_DXIL_ENUM_START(eTy, sTy) const char *ToString(eTy e); #elif DEF_RDAT_ENUMS == DEF_RDAT_DUMP_IMPL //#define RDAT_ENUM_START(eTy, sTy) \ // const char *ToString(eTy e) { \ // switch((sTy)e) { //#define RDAT_ENUM_VALUE(name, value) case value: return #name; #define RDAT_ENUM_START(eTy, sTy) \ const char *ToString(eTy e) { \ typedef eTy thisEnumTy; \ switch (e) { #define RDAT_DXIL_ENUM_START(eTy, sTy) \ const char *ToString(eTy e) { \ typedef eTy thisEnumTy; \ switch (e) { #define RDAT_ENUM_VALUE_NODEF(name) \ case thisEnumTy::name: \ return #name; #define RDAT_ENUM_VALUE(name, value) RDAT_ENUM_VALUE_NODEF(name) #define RDAT_ENUM_END() \ default: \ return nullptr; \ } \ } #endif // DEF_RDAT_ENUMS cases // Define any undefined macros to defaults #ifndef RDAT_ENUM_START #define RDAT_ENUM_START(eTy, sTy) #endif #ifndef RDAT_DXIL_ENUM_START #define RDAT_DXIL_ENUM_START(eTy, sTy) #endif #ifndef RDAT_ENUM_VALUE #define RDAT_ENUM_VALUE(name, value) // value only used during declaration #endif #ifndef RDAT_ENUM_VALUE_ALIAS #define RDAT_ENUM_VALUE_ALIAS(name, \ value) // secondary enum names that alias to the // same value as another name in the enum #endif #ifndef RDAT_ENUM_VALUE_NODEF #define RDAT_ENUM_VALUE_NODEF(name) // enum names that have no explicitly // defined value, or are defined elsewhere #endif #ifndef RDAT_ENUM_END #define RDAT_ENUM_END() #endif #endif // DEF_RDAT_ENUMS or DEF_DXIL_ENUMS defined #include "RDAT_LibraryTypes.inl" #include "RDAT_PdbInfoTypes.inl" #include "RDAT_SubobjectTypes.inl" #undef DEF_RDAT_TYPES #undef DEF_RDAT_ENUMS #undef DEF_DXIL_ENUMS #undef RDAT_STRUCT #undef RDAT_STRUCT_DERIVED #undef RDAT_STRUCT_TABLE #undef RDAT_STRUCT_TABLE_DERIVED #undef RDAT_STRUCT_END #undef RDAT_UNION #undef RDAT_UNION_IF #undef RDAT_UNION_ELIF #undef RDAT_UNION_ENDIF #undef RDAT_UNION_END #undef RDAT_RECORD_REF #undef RDAT_RECORD_ARRAY_REF #undef RDAT_RECORD_VALUE #undef RDAT_STRING #undef RDAT_STRING_ARRAY_REF #undef RDAT_VALUE #undef RDAT_VALUE_HEX #undef RDAT_INDEX_ARRAY_REF #undef RDAT_ENUM #undef RDAT_FLAGS #undef RDAT_BYTES #undef RDAT_WRAP_ARRAY #undef RDAT_ARRAY_VALUE #undef RDAT_ENUM_START #undef RDAT_DXIL_ENUM_START #undef RDAT_ENUM_VALUE #undef RDAT_ENUM_VALUE_ALIAS #undef RDAT_ENUM_VALUE_NODEF #undef RDAT_ENUM_END
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilContainer/RDAT_LibraryTypes.inl
/////////////////////////////////////////////////////////////////////////////// // // // RDAT_LibraryTypes.inl // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Defines types used in Dxil Library Runtime Data (RDAT). // // // /////////////////////////////////////////////////////////////////////////////// // clang-format off // Macro indentation makes this file easier to read, but clang-format flattens // everything. Turn off clang-format for this file. #ifdef DEF_RDAT_ENUMS RDAT_ENUM_START(DxilResourceFlag, uint32_t) RDAT_ENUM_VALUE(None, 0) RDAT_ENUM_VALUE(UAVGloballyCoherent, 1 << 0) RDAT_ENUM_VALUE(UAVCounter, 1 << 1) RDAT_ENUM_VALUE(UAVRasterizerOrderedView, 1 << 2) RDAT_ENUM_VALUE(DynamicIndexing, 1 << 3) RDAT_ENUM_VALUE(Atomics64Use, 1 << 4) RDAT_ENUM_END() RDAT_ENUM_START(DxilShaderStageFlags, uint32_t) RDAT_ENUM_VALUE(Pixel, (1 << (uint32_t)hlsl::DXIL::ShaderKind::Pixel)) RDAT_ENUM_VALUE(Vertex, (1 << (uint32_t)hlsl::DXIL::ShaderKind::Vertex)) RDAT_ENUM_VALUE(Geometry, (1 << (uint32_t)hlsl::DXIL::ShaderKind::Geometry)) RDAT_ENUM_VALUE(Hull, (1 << (uint32_t)hlsl::DXIL::ShaderKind::Hull)) RDAT_ENUM_VALUE(Domain, (1 << (uint32_t)hlsl::DXIL::ShaderKind::Domain)) RDAT_ENUM_VALUE(Compute, (1 << (uint32_t)hlsl::DXIL::ShaderKind::Compute)) RDAT_ENUM_VALUE(Library, (1 << (uint32_t)hlsl::DXIL::ShaderKind::Library)) RDAT_ENUM_VALUE(RayGeneration, (1 << (uint32_t)hlsl::DXIL::ShaderKind::RayGeneration)) RDAT_ENUM_VALUE(Intersection, (1 << (uint32_t)hlsl::DXIL::ShaderKind::Intersection)) RDAT_ENUM_VALUE(AnyHit, (1 << (uint32_t)hlsl::DXIL::ShaderKind::AnyHit)) RDAT_ENUM_VALUE(ClosestHit, (1 << (uint32_t)hlsl::DXIL::ShaderKind::ClosestHit)) RDAT_ENUM_VALUE(Miss, (1 << (uint32_t)hlsl::DXIL::ShaderKind::Miss)) RDAT_ENUM_VALUE(Callable, (1 << (uint32_t)hlsl::DXIL::ShaderKind::Callable)) RDAT_ENUM_VALUE(Mesh, (1 << (uint32_t)hlsl::DXIL::ShaderKind::Mesh)) RDAT_ENUM_VALUE(Amplification, (1 << (uint32_t)hlsl::DXIL::ShaderKind::Amplification)) RDAT_ENUM_VALUE(Node, (1 << (uint32_t)hlsl::DXIL::ShaderKind::Node)) RDAT_ENUM_END() // Low 32-bits of ShaderFeatureInfo from DFCC_FeatureInfo RDAT_ENUM_START(DxilFeatureInfo1, uint32_t) RDAT_ENUM_VALUE(Doubles, 0x0001) RDAT_ENUM_VALUE(ComputeShadersPlusRawAndStructuredBuffersViaShader4X, 0x0002) RDAT_ENUM_VALUE(UAVsAtEveryStage, 0x0004) RDAT_ENUM_VALUE(_64UAVs, 0x0008) RDAT_ENUM_VALUE(MinimumPrecision, 0x0010) RDAT_ENUM_VALUE(_11_1_DoubleExtensions, 0x0020) RDAT_ENUM_VALUE(_11_1_ShaderExtensions, 0x0040) RDAT_ENUM_VALUE(LEVEL9ComparisonFiltering, 0x0080) RDAT_ENUM_VALUE(TiledResources, 0x0100) RDAT_ENUM_VALUE(StencilRef, 0x0200) RDAT_ENUM_VALUE(InnerCoverage, 0x0400) RDAT_ENUM_VALUE(TypedUAVLoadAdditionalFormats, 0x0800) RDAT_ENUM_VALUE(ROVs, 0x1000) RDAT_ENUM_VALUE(ViewportAndRTArrayIndexFromAnyShaderFeedingRasterizer, 0x2000) RDAT_ENUM_VALUE(WaveOps, 0x4000) RDAT_ENUM_VALUE(Int64Ops, 0x8000) RDAT_ENUM_VALUE(ViewID, 0x10000) RDAT_ENUM_VALUE(Barycentrics, 0x20000) RDAT_ENUM_VALUE(NativeLowPrecision, 0x40000) RDAT_ENUM_VALUE(ShadingRate, 0x80000) RDAT_ENUM_VALUE(Raytracing_Tier_1_1, 0x100000) RDAT_ENUM_VALUE(SamplerFeedback, 0x200000) RDAT_ENUM_VALUE(AtomicInt64OnTypedResource, 0x400000) RDAT_ENUM_VALUE(AtomicInt64OnGroupShared, 0x800000) RDAT_ENUM_VALUE(DerivativesInMeshAndAmpShaders, 0x1000000) RDAT_ENUM_VALUE(ResourceDescriptorHeapIndexing, 0x2000000) RDAT_ENUM_VALUE(SamplerDescriptorHeapIndexing, 0x4000000) RDAT_ENUM_VALUE(Reserved, 0x8000000) RDAT_ENUM_VALUE(AtomicInt64OnHeapResource, 0x10000000) RDAT_ENUM_VALUE(AdvancedTextureOps, 0x20000000) RDAT_ENUM_VALUE(WriteableMSAATextures, 0x40000000) RDAT_ENUM_VALUE(SampleCmpGradientOrBias, 0x80000000) RDAT_ENUM_END() // High 32-bits of ShaderFeatureInfo from DFCC_FeatureInfo RDAT_ENUM_START(DxilFeatureInfo2, uint32_t) RDAT_ENUM_VALUE(ExtendedCommandInfo, 0x1) // OptFeatureInfo flags RDAT_ENUM_VALUE(Opt_UsesDerivatives, 0x100) RDAT_ENUM_VALUE(Opt_RequiresGroup, 0x200) #if DEF_RDAT_ENUMS == DEF_RDAT_DUMP_IMPL static_assert(DXIL::ShaderFeatureInfoCount == 33, "otherwise, RDAT_ENUM definition needs updating"); static_assert(DXIL::OptFeatureInfoCount == 2, "otherwise, RDAT_ENUM definition needs updating"); #endif RDAT_ENUM_END() #endif // DEF_RDAT_ENUMS #ifdef DEF_DXIL_ENUMS // Enums using RDAT_DXIL_ENUM_START use existing definitions of enums, rather // than redefining the enum locally. The definition here is mainly to // implement the ToString function. // A static_assert under DEF_RDAT_ENUMS == DEF_RDAT_DUMP_IMPL is used to // check one enum value that would change if the enum were to be updated, // making sure this definition is updated as well. RDAT_DXIL_ENUM_START(hlsl::DXIL::ResourceClass, uint32_t) RDAT_ENUM_VALUE_NODEF(SRV) RDAT_ENUM_VALUE_NODEF(UAV) RDAT_ENUM_VALUE_NODEF(CBuffer) RDAT_ENUM_VALUE_NODEF(Sampler) RDAT_ENUM_VALUE_NODEF(Invalid) #if DEF_RDAT_ENUMS == DEF_RDAT_DUMP_IMPL static_assert((unsigned)hlsl::DXIL::ResourceClass::Invalid == 4, "otherwise, RDAT_DXIL_ENUM definition needs updating"); #endif RDAT_ENUM_END() RDAT_DXIL_ENUM_START(hlsl::DXIL::ResourceKind, uint32_t) RDAT_ENUM_VALUE_NODEF(Invalid) RDAT_ENUM_VALUE_NODEF(Texture1D) RDAT_ENUM_VALUE_NODEF(Texture2D) RDAT_ENUM_VALUE_NODEF(Texture2DMS) RDAT_ENUM_VALUE_NODEF(Texture3D) RDAT_ENUM_VALUE_NODEF(TextureCube) RDAT_ENUM_VALUE_NODEF(Texture1DArray) RDAT_ENUM_VALUE_NODEF(Texture2DArray) RDAT_ENUM_VALUE_NODEF(Texture2DMSArray) RDAT_ENUM_VALUE_NODEF(TextureCubeArray) RDAT_ENUM_VALUE_NODEF(TypedBuffer) RDAT_ENUM_VALUE_NODEF(RawBuffer) RDAT_ENUM_VALUE_NODEF(StructuredBuffer) RDAT_ENUM_VALUE_NODEF(CBuffer) RDAT_ENUM_VALUE_NODEF(Sampler) RDAT_ENUM_VALUE_NODEF(TBuffer) RDAT_ENUM_VALUE_NODEF(RTAccelerationStructure) RDAT_ENUM_VALUE_NODEF(FeedbackTexture2D) RDAT_ENUM_VALUE_NODEF(FeedbackTexture2DArray) RDAT_ENUM_VALUE_NODEF(NumEntries) #if DEF_RDAT_ENUMS == DEF_RDAT_DUMP_IMPL static_assert((unsigned)hlsl::DXIL::ResourceKind::NumEntries == 19, "otherwise, RDAT_DXIL_ENUM definition needs updating"); #endif RDAT_ENUM_END() RDAT_DXIL_ENUM_START(hlsl::DXIL::ShaderKind, uint32_t) RDAT_ENUM_VALUE_NODEF(Pixel) RDAT_ENUM_VALUE_NODEF(Vertex) RDAT_ENUM_VALUE_NODEF(Geometry) RDAT_ENUM_VALUE_NODEF(Hull) RDAT_ENUM_VALUE_NODEF(Domain) RDAT_ENUM_VALUE_NODEF(Compute) RDAT_ENUM_VALUE_NODEF(Library) RDAT_ENUM_VALUE_NODEF(RayGeneration) RDAT_ENUM_VALUE_NODEF(Intersection) RDAT_ENUM_VALUE_NODEF(AnyHit) RDAT_ENUM_VALUE_NODEF(ClosestHit) RDAT_ENUM_VALUE_NODEF(Miss) RDAT_ENUM_VALUE_NODEF(Callable) RDAT_ENUM_VALUE_NODEF(Mesh) RDAT_ENUM_VALUE_NODEF(Amplification) RDAT_ENUM_VALUE_NODEF(Node) RDAT_ENUM_VALUE_NODEF(Invalid) #if DEF_RDAT_ENUMS == DEF_RDAT_DUMP_IMPL static_assert((unsigned)hlsl::DXIL::ShaderKind::Invalid == 16, "otherwise, RDAT_DXIL_ENUM definition needs updating"); #endif RDAT_ENUM_END() #endif // DEF_DXIL_ENUMS #ifdef DEF_RDAT_TYPES #define RECORD_TYPE RuntimeDataResourceInfo RDAT_STRUCT_TABLE(RuntimeDataResourceInfo, ResourceTable) RDAT_ENUM(uint32_t, hlsl::DXIL::ResourceClass, Class) RDAT_ENUM(uint32_t, hlsl::DXIL::ResourceKind, Kind) RDAT_VALUE(uint32_t, ID) RDAT_VALUE(uint32_t, Space) RDAT_VALUE(uint32_t, LowerBound) RDAT_VALUE(uint32_t, UpperBound) RDAT_STRING(Name) RDAT_FLAGS(uint32_t, DxilResourceFlag, Flags) RDAT_STRUCT_END() #undef RECORD_TYPE // ------------ RuntimeDataFunctionInfo ------------ #define RECORD_TYPE RuntimeDataFunctionInfo RDAT_STRUCT_TABLE(RuntimeDataFunctionInfo, FunctionTable) // full function name RDAT_STRING(Name) // unmangled function name RDAT_STRING(UnmangledName) // list of global resources used by this function RDAT_RECORD_ARRAY_REF(RuntimeDataResourceInfo, Resources) // list of external function names this function calls RDAT_STRING_ARRAY_REF(FunctionDependencies) // Shader type, or library function RDAT_ENUM(uint32_t, hlsl::DXIL::ShaderKind, ShaderKind) // Payload Size: // 1) any/closest hit or miss shader: payload size // 2) call shader: parameter size RDAT_VALUE(uint32_t, PayloadSizeInBytes) // attribute size for closest hit and any hit RDAT_VALUE(uint32_t, AttributeSizeInBytes) // first 32 bits of feature flag RDAT_FLAGS(uint32_t, hlsl::RDAT::DxilFeatureInfo1, FeatureInfo1) // second 32 bits of feature flag RDAT_FLAGS(uint32_t, hlsl::RDAT::DxilFeatureInfo2, FeatureInfo2) // valid shader stage flag. RDAT_FLAGS(uint32_t, hlsl::RDAT::DxilShaderStageFlags, ShaderStageFlag) // minimum shader target. RDAT_VALUE_HEX(uint32_t, MinShaderTarget) #if DEF_RDAT_TYPES == DEF_RDAT_TYPES_USE_HELPERS // void SetFeatureFlags(uint64_t flags) convenience method void SetFeatureFlags(uint64_t flags) { FeatureInfo1 = flags & 0xffffffff; FeatureInfo2 = (flags >> 32) & 0xffffffff; } #endif #if DEF_RDAT_TYPES == DEF_RDAT_READER_DECL // uint64_t GetFeatureFlags() convenience method uint64_t GetFeatureFlags() const; #elif DEF_RDAT_TYPES == DEF_RDAT_READER_IMPL // uint64_t GetFeatureFlags() convenience method uint64_t RuntimeDataFunctionInfo_Reader::GetFeatureFlags() const { return asRecord() ? (((uint64_t)asRecord()->FeatureInfo2 << 32) | (uint64_t)asRecord()->FeatureInfo1) : 0; } #endif RDAT_STRUCT_END() #undef RECORD_TYPE #endif // DEF_RDAT_TYPES ////////////////////////////////////////////////////////////////////// // The following require validator version 1.8 and above. // ------------ RuntimeDataFunctionInfo2 dependencies ------------ #ifdef DEF_RDAT_ENUMS RDAT_ENUM_START(DxilShaderFlags, uint32_t) RDAT_ENUM_VALUE(None, 0) RDAT_ENUM_VALUE(NodeProgramEntry, 1 << 0) // End of values supported by validator version 1.8 RDAT_ENUM_VALUE(OutputPositionPresent, 1 << 1) RDAT_ENUM_VALUE(DepthOutput, 1 << 2) RDAT_ENUM_VALUE(SampleFrequency, 1 << 3) RDAT_ENUM_VALUE(UsesViewID, 1 << 4) RDAT_ENUM_END() RDAT_ENUM_START(NodeFuncAttribKind, uint32_t) RDAT_ENUM_VALUE(None, 0) RDAT_ENUM_VALUE(ID, 1) RDAT_ENUM_VALUE(NumThreads, 2) RDAT_ENUM_VALUE(ShareInputOf, 3) RDAT_ENUM_VALUE(DispatchGrid, 4) RDAT_ENUM_VALUE(MaxRecursionDepth, 5) RDAT_ENUM_VALUE(LocalRootArgumentsTableIndex, 6) RDAT_ENUM_VALUE(MaxDispatchGrid, 7) RDAT_ENUM_VALUE(Reserved_MeshNodePreview1, 8) RDAT_ENUM_VALUE(Reserved_MeshNodePreview2, 9) RDAT_ENUM_VALUE_NODEF(LastValue) RDAT_ENUM_END() RDAT_ENUM_START(NodeAttribKind, uint32_t) RDAT_ENUM_VALUE(None, 0) RDAT_ENUM_VALUE(OutputID, 1) RDAT_ENUM_VALUE(MaxRecords, 2) RDAT_ENUM_VALUE(MaxRecordsSharedWith, 3) RDAT_ENUM_VALUE(RecordSizeInBytes, 4) RDAT_ENUM_VALUE(RecordDispatchGrid, 5) RDAT_ENUM_VALUE(OutputArraySize, 6) RDAT_ENUM_VALUE(AllowSparseNodes, 7) RDAT_ENUM_VALUE(RecordAlignmentInBytes, 8) RDAT_ENUM_VALUE_NODEF(LastValue) RDAT_ENUM_END() #endif // DEF_RDAT_ENUMS #ifdef DEF_DXIL_ENUMS RDAT_DXIL_ENUM_START(hlsl::DXIL::NodeIOKind, uint32_t) RDAT_ENUM_VALUE_NODEF(EmptyInput) RDAT_ENUM_VALUE_NODEF(NodeOutput) RDAT_ENUM_VALUE_NODEF(NodeOutputArray) RDAT_ENUM_VALUE_NODEF(EmptyOutput) RDAT_ENUM_VALUE_NODEF(EmptyOutputArray) RDAT_ENUM_VALUE_NODEF(DispatchNodeInputRecord) RDAT_ENUM_VALUE_NODEF(RWDispatchNodeInputRecord) RDAT_ENUM_VALUE_NODEF(GroupNodeInputRecords) RDAT_ENUM_VALUE_NODEF(RWGroupNodeInputRecords) RDAT_ENUM_VALUE_NODEF(ThreadNodeInputRecord) RDAT_ENUM_VALUE_NODEF(RWThreadNodeInputRecord) RDAT_ENUM_VALUE_NODEF(GroupNodeOutputRecords) RDAT_ENUM_VALUE_NODEF(ThreadNodeOutputRecords) RDAT_ENUM_VALUE_NODEF(Invalid) RDAT_ENUM_END() RDAT_DXIL_ENUM_START(hlsl::DXIL::NodeLaunchType, uint32_t) RDAT_ENUM_VALUE_NODEF(Invalid) RDAT_ENUM_VALUE_NODEF(Broadcasting) RDAT_ENUM_VALUE_NODEF(Coalescing) RDAT_ENUM_VALUE_NODEF(Thread) RDAT_ENUM_VALUE_NODEF(Reserved_Mesh) RDAT_ENUM_VALUE_NODEF(LastEntry) #if DEF_RDAT_ENUMS == DEF_RDAT_DUMP_IMPL static_assert((unsigned)hlsl::DXIL::NodeLaunchType::LastEntry == 5, "otherwise, RDAT_DXIL_ENUM definition needs updating"); #endif RDAT_ENUM_END() #endif // DEF_DXIL_ENUMS #ifdef DEF_RDAT_TYPES #define RECORD_TYPE RecordDispatchGrid RDAT_STRUCT(RecordDispatchGrid) RDAT_VALUE(uint16_t, ByteOffset) RDAT_VALUE(uint16_t, ComponentNumAndType) // 0:2 = NumComponents (0-3), 3:15 = // hlsl::DXIL::ComponentType enum #if DEF_RDAT_TYPES == DEF_RDAT_TYPES_USE_HELPERS uint8_t GetNumComponents() const { return (ComponentNumAndType & 0x3); } hlsl::DXIL::ComponentType GetComponentType() const { return (hlsl::DXIL::ComponentType)(ComponentNumAndType >> 2); } void SetNumComponents(uint8_t num) { ComponentNumAndType |= (num & 0x3); } void SetComponentType(hlsl::DXIL::ComponentType type) { ComponentNumAndType |= (((uint16_t)type) << 2); } #endif RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE NodeID RDAT_STRUCT_TABLE(NodeID, NodeIDTable) RDAT_STRING(Name) RDAT_VALUE(uint32_t, Index) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE NodeShaderFuncAttrib RDAT_STRUCT_TABLE(NodeShaderFuncAttrib, NodeShaderFuncAttribTable) RDAT_ENUM(uint32_t, hlsl::RDAT::NodeFuncAttribKind, AttribKind) RDAT_UNION() RDAT_UNION_IF(ID, getAttribKind() == hlsl::RDAT::NodeFuncAttribKind::ID) RDAT_RECORD_REF(NodeID, ID) RDAT_UNION_ELIF(NumThreads, getAttribKind() == hlsl::RDAT::NodeFuncAttribKind::NumThreads) RDAT_INDEX_ARRAY_REF(NumThreads) // ref to array of X, Y, Z. If < 3 // elements, default value is 1 RDAT_UNION_ELIF(SharedInput, getAttribKind() == hlsl::RDAT::NodeFuncAttribKind::ShareInputOf) RDAT_RECORD_REF(NodeID, ShareInputOf) RDAT_UNION_ELIF(DispatchGrid, getAttribKind() == hlsl::RDAT::NodeFuncAttribKind::DispatchGrid) RDAT_INDEX_ARRAY_REF(DispatchGrid) RDAT_UNION_ELIF(MaxRecursionDepth, getAttribKind() == hlsl::RDAT::NodeFuncAttribKind::MaxRecursionDepth) RDAT_VALUE(uint32_t, MaxRecursionDepth) RDAT_UNION_ELIF( LocalRootArgumentsTableIndex, getAttribKind() == hlsl::RDAT::NodeFuncAttribKind::LocalRootArgumentsTableIndex) RDAT_VALUE(uint32_t, LocalRootArgumentsTableIndex) RDAT_UNION_ELIF(MaxDispatchGrid, getAttribKind() == hlsl::RDAT::NodeFuncAttribKind::MaxDispatchGrid) RDAT_INDEX_ARRAY_REF(MaxDispatchGrid) RDAT_UNION_ENDIF() RDAT_UNION_END() RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE NodeShaderIOAttrib RDAT_STRUCT_TABLE(NodeShaderIOAttrib, NodeShaderIOAttribTable) RDAT_ENUM(uint32_t, hlsl::RDAT::NodeAttribKind, AttribKind) RDAT_UNION() RDAT_UNION_IF(ID, getAttribKind() == hlsl::RDAT::NodeAttribKind::OutputID) RDAT_RECORD_REF(NodeID, OutputID) RDAT_UNION_ELIF(MaxRecords, getAttribKind() == hlsl::RDAT::NodeAttribKind::MaxRecords) RDAT_VALUE(uint32_t, MaxRecords) RDAT_UNION_ELIF(MaxRecordsSharedWith, getAttribKind() == hlsl::RDAT::NodeAttribKind::MaxRecordsSharedWith) RDAT_VALUE(uint32_t, MaxRecordsSharedWith) RDAT_UNION_ELIF(RecordSizeInBytes, getAttribKind() == hlsl::RDAT::NodeAttribKind::RecordSizeInBytes) RDAT_VALUE(uint32_t, RecordSizeInBytes) RDAT_UNION_ELIF(RecordDispatchGrid, getAttribKind() == hlsl::RDAT::NodeAttribKind::RecordDispatchGrid) RDAT_RECORD_VALUE(RecordDispatchGrid, RecordDispatchGrid) RDAT_UNION_ELIF(OutputArraySize, getAttribKind() == hlsl::RDAT::NodeAttribKind::OutputArraySize) RDAT_VALUE(uint32_t, OutputArraySize) RDAT_UNION_ELIF(AllowSparseNodes, getAttribKind() == hlsl::RDAT::NodeAttribKind::AllowSparseNodes) RDAT_VALUE(uint32_t, AllowSparseNodes) RDAT_UNION_ELIF(RecordAlignmentInBytes, getAttribKind() == hlsl::RDAT::NodeAttribKind::RecordAlignmentInBytes) RDAT_VALUE(uint32_t, RecordAlignmentInBytes) RDAT_UNION_ENDIF() RDAT_UNION_END() RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE IONode RDAT_STRUCT_TABLE(IONode, IONodeTable) // Required field RDAT_VALUE(uint32_t, IOFlagsAndKind) // Optional fields RDAT_RECORD_ARRAY_REF(NodeShaderIOAttrib, Attribs) #if DEF_RDAT_TYPES == DEF_RDAT_TYPES_USE_HELPERS uint32_t GetIOFlags() const { return IOFlagsAndKind & (uint32_t)DXIL::NodeIOFlags::NodeFlagsMask; } hlsl::DXIL::NodeIOKind GetIOKind() const { return (hlsl::DXIL::NodeIOKind)(IOFlagsAndKind & (uint32_t)DXIL::NodeIOFlags::NodeIOKindMask); } void SetIOFlags(uint32_t flags) { IOFlagsAndKind |= flags; } void SetIOKind(hlsl::DXIL::NodeIOKind kind) { IOFlagsAndKind |= (uint32_t)kind; } #endif RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE NodeShaderInfo RDAT_STRUCT_TABLE(NodeShaderInfo, NodeShaderInfoTable) // Function Attributes RDAT_ENUM(uint32_t, hlsl::DXIL::NodeLaunchType, LaunchType) RDAT_VALUE(uint32_t, GroupSharedBytesUsed) RDAT_RECORD_ARRAY_REF(NodeShaderFuncAttrib, Attribs) RDAT_RECORD_ARRAY_REF(IONode, Outputs) RDAT_RECORD_ARRAY_REF(IONode, Inputs) RDAT_STRUCT_END() #undef RECORD_TYPE // ------------ RuntimeDataFunctionInfo2 ------------ #define RECORD_TYPE RuntimeDataFunctionInfo2 RDAT_STRUCT_TABLE_DERIVED(RuntimeDataFunctionInfo2, RuntimeDataFunctionInfo, FunctionTable) // 128 lanes is maximum that could be supported by HLSL RDAT_VALUE(uint8_t, MinimumExpectedWaveLaneCount) // 0 = none specified RDAT_VALUE(uint8_t, MaximumExpectedWaveLaneCount) // 0 = none specified RDAT_FLAGS(uint16_t, hlsl::RDAT::DxilShaderFlags, ShaderFlags) RDAT_UNION() RDAT_UNION_IF(RawShaderRef, (getShaderKind() == hlsl::DXIL::ShaderKind::Invalid)) RDAT_VALUE(uint32_t, RawShaderRef) RDAT_UNION_ELIF(Node, (getShaderKind() == hlsl::DXIL::ShaderKind::Node)) RDAT_RECORD_REF(NodeShaderInfo, Node) // End of values supported by validator version 1.8 RDAT_UNION_ELIF(VS, (getShaderKind() == hlsl::DXIL::ShaderKind::Vertex)) RDAT_RECORD_REF(VSInfo, VS) RDAT_UNION_ELIF(PS, (getShaderKind() == hlsl::DXIL::ShaderKind::Pixel)) RDAT_RECORD_REF(PSInfo, PS) RDAT_UNION_ELIF(HS, (getShaderKind() == hlsl::DXIL::ShaderKind::Hull)) RDAT_RECORD_REF(HSInfo, HS) RDAT_UNION_ELIF(DS, (getShaderKind() == hlsl::DXIL::ShaderKind::Domain)) RDAT_RECORD_REF(DSInfo, DS) RDAT_UNION_ELIF(GS, (getShaderKind() == hlsl::DXIL::ShaderKind::Geometry)) RDAT_RECORD_REF(GSInfo, GS) RDAT_UNION_ELIF(CS, (getShaderKind() == hlsl::DXIL::ShaderKind::Compute)) RDAT_RECORD_REF(CSInfo, CS) RDAT_UNION_ELIF(MS, (getShaderKind() == hlsl::DXIL::ShaderKind::Mesh)) RDAT_RECORD_REF(MSInfo, MS) RDAT_UNION_ELIF(AS, (getShaderKind() == hlsl::DXIL::ShaderKind::Amplification)) RDAT_RECORD_REF(ASInfo, AS) RDAT_UNION_ENDIF() RDAT_UNION_END() RDAT_STRUCT_END() #undef RECORD_TYPE #endif // DEF_RDAT_TYPES /////////////////////////////////////////////////////////////////////////////// // The following are experimental, and are not currently supported on any // validator version. #ifdef DEF_DXIL_ENUMS RDAT_DXIL_ENUM_START(hlsl::DXIL::SemanticKind, uint32_t) /* <py::lines('SemanticKind-ENUM')>hctdb_instrhelp.get_rdat_enum_decl("SemanticKind", nodef=True)</py>*/ // SemanticKind-ENUM:BEGIN RDAT_ENUM_VALUE_NODEF(Arbitrary) RDAT_ENUM_VALUE_NODEF(VertexID) RDAT_ENUM_VALUE_NODEF(InstanceID) RDAT_ENUM_VALUE_NODEF(Position) RDAT_ENUM_VALUE_NODEF(RenderTargetArrayIndex) RDAT_ENUM_VALUE_NODEF(ViewPortArrayIndex) RDAT_ENUM_VALUE_NODEF(ClipDistance) RDAT_ENUM_VALUE_NODEF(CullDistance) RDAT_ENUM_VALUE_NODEF(OutputControlPointID) RDAT_ENUM_VALUE_NODEF(DomainLocation) RDAT_ENUM_VALUE_NODEF(PrimitiveID) RDAT_ENUM_VALUE_NODEF(GSInstanceID) RDAT_ENUM_VALUE_NODEF(SampleIndex) RDAT_ENUM_VALUE_NODEF(IsFrontFace) RDAT_ENUM_VALUE_NODEF(Coverage) RDAT_ENUM_VALUE_NODEF(InnerCoverage) RDAT_ENUM_VALUE_NODEF(Target) RDAT_ENUM_VALUE_NODEF(Depth) RDAT_ENUM_VALUE_NODEF(DepthLessEqual) RDAT_ENUM_VALUE_NODEF(DepthGreaterEqual) RDAT_ENUM_VALUE_NODEF(StencilRef) RDAT_ENUM_VALUE_NODEF(DispatchThreadID) RDAT_ENUM_VALUE_NODEF(GroupID) RDAT_ENUM_VALUE_NODEF(GroupIndex) RDAT_ENUM_VALUE_NODEF(GroupThreadID) RDAT_ENUM_VALUE_NODEF(TessFactor) RDAT_ENUM_VALUE_NODEF(InsideTessFactor) RDAT_ENUM_VALUE_NODEF(ViewID) RDAT_ENUM_VALUE_NODEF(Barycentrics) RDAT_ENUM_VALUE_NODEF(ShadingRate) RDAT_ENUM_VALUE_NODEF(CullPrimitive) RDAT_ENUM_VALUE_NODEF(StartVertexLocation) RDAT_ENUM_VALUE_NODEF(StartInstanceLocation) RDAT_ENUM_VALUE_NODEF(Invalid) // SemanticKind-ENUM:END RDAT_ENUM_END() RDAT_DXIL_ENUM_START(hlsl::DXIL::ComponentType, uint32_t) RDAT_ENUM_VALUE_NODEF(Invalid) RDAT_ENUM_VALUE_NODEF(I1) RDAT_ENUM_VALUE_NODEF(I16) RDAT_ENUM_VALUE_NODEF(U16) RDAT_ENUM_VALUE_NODEF(I32) RDAT_ENUM_VALUE_NODEF(U32) RDAT_ENUM_VALUE_NODEF(I64) RDAT_ENUM_VALUE_NODEF(U64) RDAT_ENUM_VALUE_NODEF(F16) RDAT_ENUM_VALUE_NODEF(F32) RDAT_ENUM_VALUE_NODEF(F64) RDAT_ENUM_VALUE_NODEF(SNormF16) RDAT_ENUM_VALUE_NODEF(UNormF16) RDAT_ENUM_VALUE_NODEF(SNormF32) RDAT_ENUM_VALUE_NODEF(UNormF32) RDAT_ENUM_VALUE_NODEF(SNormF64) RDAT_ENUM_VALUE_NODEF(UNormF64) RDAT_ENUM_VALUE_NODEF(PackedS8x32) RDAT_ENUM_VALUE_NODEF(PackedU8x32) RDAT_ENUM_VALUE_NODEF(LastEntry) #if DEF_RDAT_ENUMS == DEF_RDAT_DUMP_IMPL static_assert((unsigned)hlsl::DXIL::ComponentType::LastEntry == 19, "otherwise, RDAT_DXIL_ENUM definition needs updating"); #endif RDAT_ENUM_END() RDAT_DXIL_ENUM_START(hlsl::DXIL::InterpolationMode, uint32_t) RDAT_ENUM_VALUE_NODEF(Undefined) RDAT_ENUM_VALUE_NODEF(Constant) RDAT_ENUM_VALUE_NODEF(Linear) RDAT_ENUM_VALUE_NODEF(LinearCentroid) RDAT_ENUM_VALUE_NODEF(LinearNoperspective) RDAT_ENUM_VALUE_NODEF(LinearNoperspectiveCentroid) RDAT_ENUM_VALUE_NODEF(LinearSample) RDAT_ENUM_VALUE_NODEF(LinearNoperspectiveSample) RDAT_ENUM_VALUE_NODEF(Invalid) #if DEF_RDAT_ENUMS == DEF_RDAT_DUMP_IMPL static_assert((unsigned)hlsl::DXIL::InterpolationMode::Invalid == 8, "otherwise, RDAT_DXIL_ENUM definition needs updating"); #endif RDAT_ENUM_END() #endif // DEF_DXIL_ENUMS #ifdef DEF_RDAT_TYPES #define RECORD_TYPE SignatureElement RDAT_STRUCT_TABLE(SignatureElement, SignatureElementTable) RDAT_STRING(SemanticName) RDAT_INDEX_ARRAY_REF(SemanticIndices) // Rows = SemanticIndices.Count() RDAT_ENUM(uint8_t, hlsl::DXIL::SemanticKind, SemanticKind) RDAT_ENUM(uint8_t, hlsl::DXIL::ComponentType, ComponentType) RDAT_ENUM(uint8_t, hlsl::DXIL::InterpolationMode, InterpolationMode) RDAT_VALUE( uint8_t, StartRow) // Starting row of packed location if allocated, otherwise 0xFF // TODO: use struct with bitfields or accessors for ColsAndStream and // UsageAndDynIndexMasks RDAT_VALUE(uint8_t, ColsAndStream) // 0:2 = (Cols-1) (0-3), 2:4 = StartCol // (0-3), 4:6 = OutputStream (0-3) RDAT_VALUE(uint8_t, UsageAndDynIndexMasks) // 0:4 = UsageMask, 4:8 = DynamicIndexMask #if DEF_RDAT_TYPES == DEF_RDAT_TYPES_USE_HELPERS uint8_t GetCols() const { return (ColsAndStream & 3) + 1; } uint8_t GetStartCol() const { return (ColsAndStream >> 2) & 3; } uint8_t GetOutputStream() const { return (ColsAndStream >> 4) & 3; } uint8_t GetUsageMask() const { return UsageAndDynIndexMasks & 0xF; } uint8_t GetDynamicIndexMask() const { return (UsageAndDynIndexMasks >> 4) & 0xF; } void SetCols(unsigned cols) { ColsAndStream &= ~3; ColsAndStream |= (cols - 1) & 3; } void SetStartCol(unsigned col) { ColsAndStream &= ~(3 << 2); ColsAndStream |= (col & 3) << 2; } void SetOutputStream(unsigned stream) { ColsAndStream &= ~(3 << 4); ColsAndStream |= (stream & 3) << 4; } void SetUsageMask(unsigned mask) { UsageAndDynIndexMasks &= ~0xF; UsageAndDynIndexMasks |= mask & 0xF; } void SetDynamicIndexMask(unsigned mask) { UsageAndDynIndexMasks &= ~(0xF << 4); UsageAndDynIndexMasks |= (mask & 0xF) << 4; } #endif RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE VSInfo RDAT_STRUCT_TABLE(VSInfo, VSInfoTable) RDAT_RECORD_ARRAY_REF(SignatureElement, SigInputElements) RDAT_RECORD_ARRAY_REF(SignatureElement, SigOutputElements) RDAT_BYTES(ViewIDOutputMask) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE PSInfo RDAT_STRUCT_TABLE(PSInfo, PSInfoTable) RDAT_RECORD_ARRAY_REF(SignatureElement, SigInputElements) RDAT_RECORD_ARRAY_REF(SignatureElement, SigOutputElements) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE HSInfo RDAT_STRUCT_TABLE(HSInfo, HSInfoTable) RDAT_RECORD_ARRAY_REF(SignatureElement, SigInputElements) RDAT_RECORD_ARRAY_REF(SignatureElement, SigOutputElements) RDAT_RECORD_ARRAY_REF(SignatureElement, SigPatchConstOutputElements) RDAT_BYTES(ViewIDOutputMask) RDAT_BYTES(ViewIDPatchConstOutputMask) RDAT_BYTES(InputToOutputMasks) RDAT_BYTES(InputToPatchConstOutputMasks) RDAT_VALUE(uint8_t, InputControlPointCount) RDAT_VALUE(uint8_t, OutputControlPointCount) RDAT_VALUE(uint8_t, TessellatorDomain) RDAT_VALUE(uint8_t, TessellatorOutputPrimitive) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE DSInfo RDAT_STRUCT_TABLE(DSInfo, DSInfoTable) RDAT_RECORD_ARRAY_REF(SignatureElement, SigInputElements) RDAT_RECORD_ARRAY_REF(SignatureElement, SigOutputElements) RDAT_RECORD_ARRAY_REF(SignatureElement, SigPatchConstInputElements) RDAT_BYTES(ViewIDOutputMask) RDAT_BYTES(InputToOutputMasks) RDAT_BYTES(PatchConstInputToOutputMasks) RDAT_VALUE(uint8_t, InputControlPointCount) RDAT_VALUE(uint8_t, TessellatorDomain) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE GSInfo RDAT_STRUCT_TABLE(GSInfo, GSInfoTable) RDAT_RECORD_ARRAY_REF(SignatureElement, SigInputElements) RDAT_RECORD_ARRAY_REF(SignatureElement, SigOutputElements) RDAT_BYTES(ViewIDOutputMask) RDAT_BYTES(InputToOutputMasks) RDAT_VALUE(uint8_t, InputPrimitive) RDAT_VALUE(uint8_t, OutputTopology) RDAT_VALUE(uint8_t, MaxVertexCount) RDAT_VALUE(uint8_t, OutputStreamMask) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE CSInfo RDAT_STRUCT_TABLE(CSInfo, CSInfoTable) RDAT_INDEX_ARRAY_REF(NumThreads) // ref to array of X, Y, Z. If < 3 elements, // default value is 1 RDAT_VALUE(uint32_t, GroupSharedBytesUsed) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE MSInfo RDAT_STRUCT_TABLE(MSInfo, MSInfoTable) RDAT_RECORD_ARRAY_REF(SignatureElement, SigOutputElements) RDAT_RECORD_ARRAY_REF(SignatureElement, SigPrimOutputElements) RDAT_BYTES(ViewIDOutputMask) RDAT_BYTES(ViewIDPrimOutputMask) RDAT_INDEX_ARRAY_REF(NumThreads) // ref to array of X, Y, Z. If < 3 elements, // default value is 1 RDAT_VALUE(uint32_t, GroupSharedBytesUsed) RDAT_VALUE(uint32_t, GroupSharedBytesDependentOnViewID) RDAT_VALUE(uint32_t, PayloadSizeInBytes) RDAT_VALUE(uint16_t, MaxOutputVertices) RDAT_VALUE(uint16_t, MaxOutputPrimitives) RDAT_VALUE(uint8_t, MeshOutputTopology) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE ASInfo RDAT_STRUCT_TABLE(ASInfo, ASInfoTable) RDAT_INDEX_ARRAY_REF(NumThreads) // ref to array of X, Y, Z. If < 3 elements, // default value is 1 RDAT_VALUE(uint32_t, GroupSharedBytesUsed) RDAT_VALUE(uint32_t, PayloadSizeInBytes) RDAT_STRUCT_END() #undef RECORD_TYPE #endif // DEF_RDAT_TYPES // clang-format on
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilContainer/DxilContainer.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilContainer.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides declarations for the DXIL container format. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #ifndef __DXC_CONTAINER__ #define __DXC_CONTAINER__ #include "dxc/DXIL/DxilConstants.h" #include "dxc/WinAdapter.h" #include <iterator> #include <stdint.h> struct IDxcContainerReflection; namespace hlsl { #pragma pack(push, 1) static const size_t DxilContainerHashSize = 16; static const uint16_t DxilContainerVersionMajor = 1; // Current major version static const uint16_t DxilContainerVersionMinor = 0; // Current minor version static const uint32_t DxilContainerMaxSize = 0x80000000; // Max size for container. /// Use this type to represent the hash for the full container. struct DxilContainerHash { uint8_t Digest[DxilContainerHashSize]; }; enum class DxilShaderHashFlags : uint32_t { None = 0, // No flags defined. IncludesSource = 1, // This flag indicates that the shader hash was computed // taking into account source information (-Zss) }; typedef struct DxilShaderHash { uint32_t Flags; // DxilShaderHashFlags uint8_t Digest[DxilContainerHashSize]; } DxilShaderHash; struct DxilContainerVersion { uint16_t Major; uint16_t Minor; }; /// Use this type to describe a DXIL container of parts. struct DxilContainerHeader { uint32_t HeaderFourCC; DxilContainerHash Hash; DxilContainerVersion Version; uint32_t ContainerSizeInBytes; // From start of this header uint32_t PartCount; // Structure is followed by uint32_t PartOffset[PartCount]; // The offset is to a DxilPartHeader. }; /// Use this type to describe the size and type of a DXIL container part. struct DxilPartHeader { uint32_t PartFourCC; // Four char code for part type. uint32_t PartSize; // Byte count for PartData. // Structure is followed by uint8_t PartData[PartSize]. }; #define DXIL_FOURCC(ch0, ch1, ch2, ch3) \ ((uint32_t)(uint8_t)(ch0) | (uint32_t)(uint8_t)(ch1) << 8 | \ (uint32_t)(uint8_t)(ch2) << 16 | (uint32_t)(uint8_t)(ch3) << 24) enum DxilFourCC { DFCC_Container = DXIL_FOURCC( 'D', 'X', 'B', 'C'), // for back-compat with tools that look for DXBC containers DFCC_ResourceDef = DXIL_FOURCC('R', 'D', 'E', 'F'), DFCC_InputSignature = DXIL_FOURCC('I', 'S', 'G', '1'), DFCC_OutputSignature = DXIL_FOURCC('O', 'S', 'G', '1'), DFCC_PatchConstantSignature = DXIL_FOURCC('P', 'S', 'G', '1'), DFCC_ShaderStatistics = DXIL_FOURCC('S', 'T', 'A', 'T'), DFCC_ShaderDebugInfoDXIL = DXIL_FOURCC('I', 'L', 'D', 'B'), DFCC_ShaderDebugName = DXIL_FOURCC('I', 'L', 'D', 'N'), DFCC_FeatureInfo = DXIL_FOURCC('S', 'F', 'I', '0'), DFCC_PrivateData = DXIL_FOURCC('P', 'R', 'I', 'V'), DFCC_RootSignature = DXIL_FOURCC('R', 'T', 'S', '0'), DFCC_DXIL = DXIL_FOURCC('D', 'X', 'I', 'L'), DFCC_PipelineStateValidation = DXIL_FOURCC('P', 'S', 'V', '0'), DFCC_RuntimeData = DXIL_FOURCC('R', 'D', 'A', 'T'), DFCC_ShaderHash = DXIL_FOURCC('H', 'A', 'S', 'H'), DFCC_ShaderSourceInfo = DXIL_FOURCC('S', 'R', 'C', 'I'), DFCC_ShaderPDBInfo = DXIL_FOURCC('P', 'D', 'B', 'I'), DFCC_CompilerVersion = DXIL_FOURCC('V', 'E', 'R', 'S'), }; #undef DXIL_FOURCC struct DxilShaderFeatureInfo { uint64_t FeatureFlags; }; // DXIL program information. struct DxilBitcodeHeader { uint32_t DxilMagic; // ACSII "DXIL". uint32_t DxilVersion; // DXIL version. uint32_t BitcodeOffset; // Offset to LLVM bitcode (from start of header). uint32_t BitcodeSize; // Size of LLVM bitcode. }; static const uint32_t DxilMagicValue = 0x4C495844; // 'DXIL' struct DxilProgramHeader { uint32_t ProgramVersion; /// Major and minor version, including type. uint32_t SizeInUint32; /// Size in uint32_t units including this header. DxilBitcodeHeader BitcodeHeader; /// Bitcode-specific header. // Followed by uint8_t[BitcodeHeader.BitcodeOffset] }; struct DxilProgramSignature { uint32_t ParamCount; uint32_t ParamOffset; }; enum class DxilProgramSigMinPrecision : uint32_t { Default = 0, Float16 = 1, Float2_8 = 2, Reserved = 3, SInt16 = 4, UInt16 = 5, Any16 = 0xf0, Any10 = 0xf1 }; // Corresponds to D3D_NAME and D3D10_SB_NAME enum class DxilProgramSigSemantic : uint32_t { Undefined = 0, Position = 1, ClipDistance = 2, CullDistance = 3, RenderTargetArrayIndex = 4, ViewPortArrayIndex = 5, VertexID = 6, PrimitiveID = 7, InstanceID = 8, IsFrontFace = 9, SampleIndex = 10, FinalQuadEdgeTessfactor = 11, FinalQuadInsideTessfactor = 12, FinalTriEdgeTessfactor = 13, FinalTriInsideTessfactor = 14, FinalLineDetailTessfactor = 15, FinalLineDensityTessfactor = 16, Barycentrics = 23, ShadingRate = 24, CullPrimitive = 25, Target = 64, Depth = 65, Coverage = 66, DepthGE = 67, DepthLE = 68, StencilRef = 69, InnerCoverage = 70, }; DxilProgramSigSemantic SemanticKindToSystemValue(DXIL::SemanticKind, DXIL::TessellatorDomain); enum class DxilProgramSigCompType : uint32_t { Unknown = 0, UInt32 = 1, SInt32 = 2, Float32 = 3, UInt16 = 4, SInt16 = 5, Float16 = 6, UInt64 = 7, SInt64 = 8, Float64 = 9, }; DxilProgramSigCompType CompTypeToSigCompType(DXIL::ComponentType, bool i1ToUnknownCompat); struct DxilProgramSignatureElement { uint32_t Stream; // Stream index (parameters must appear in non-decreasing // stream order) uint32_t SemanticName; // Offset to LPCSTR from start of DxilProgramSignature. uint32_t SemanticIndex; // Semantic Index DxilProgramSigSemantic SystemValue; // Semantic type. Similar to DxilSemantic::Kind, but a // serialized rather than processing rep. DxilProgramSigCompType CompType; // Type of bits. uint32_t Register; // Register Index (row index) uint8_t Mask; // Mask (column allocation) union // Unconditional cases useful for validation of shader linkage. { uint8_t NeverWrites_Mask; // For an output signature, the shader the // signature belongs to never writes the masked // components of the output register. uint8_t AlwaysReads_Mask; // For an input signature, the shader the // signature belongs to always reads the masked // components of the input register. }; uint16_t Pad; DxilProgramSigMinPrecision MinPrecision; // Minimum precision of input/output data }; // Easy to get this wrong. Earlier assertions can help determine static_assert(sizeof(DxilProgramSignatureElement) == 0x20, "else DxilProgramSignatureElement is misaligned"); struct DxilShaderDebugName { uint16_t Flags; // Reserved, must be set to zero. uint16_t NameLength; // Length of the debug name, without null terminator. // Followed by NameLength bytes of the UTF-8-encoded name. // Followed by a null terminator. // Followed by [0-3] zero bytes to align to a 4-byte boundary. }; static const size_t MinDxilShaderDebugNameSize = sizeof(DxilShaderDebugName) + 4; struct DxilCompilerVersion { uint16_t Major; uint16_t Minor; uint32_t VersionFlags; uint32_t CommitCount; uint32_t VersionStringListSizeInBytes; // Followed by VersionStringListSizeInBytes bytes, containing up to two // null-terminated strings, sequentially: // 1. CommitSha // 1. CustomVersionString // Followed by [0-3] zero bytes to align to a 4-byte boundary. }; // Source Info part has the following top level structure: // // DxilSourceInfo // // DxilSourceInfoSection // char Data[] // (0-3 zero bytes to align to a 4-byte boundary) // // DxilSourceInfoSection // char Data[] // (0-3 zero bytes to align to a 4-byte boundary) // // ... // // DxilSourceInfoSection // char Data[] // (0-3 zero bytes to align to a 4-byte boundary) // // Each DxilSourceInfoSection is followed by a blob of Data. // The each type of data has its own internal structure: // // ================ 1. Source Names ================================== // // DxilSourceInfo_SourceNames // // DxilSourceInfo_SourceNamesEntry // char Name[ NameSizeInBytes ] // (0-3 zero bytes to align to a 4-byte boundary) // // DxilSourceInfo_SourceNamesEntry // char Name[ NameSizeInBytes ] // (0-3 zero bytes to align to a 4-byte boundary) // // ... // // DxilSourceInfo_SourceNamesEntry // char Name[ NameSizeInBytes ] // (0-3 zero bytes to align to a 4-byte boundary) // // ================ 2. Source Contents ================================== // // DxilSourceInfo_SourceContents // char Entries[CompressedEntriesSizeInBytes] // // `Entries` may be compressed. Here is the uncompressed structure: // // DxilSourceInfo_SourcesContentsEntry // char Content[ ContentSizeInBytes ] // (0-3 zero bytes to align to a 4-byte boundary) // // DxilSourceInfo_SourcesContentsEntry // char Content[ ContentSizeInBytes ] // (0-3 zero bytes to align to a 4-byte boundary) // // ... // // DxilSourceInfo_SourcesContentsEntry // char Content[ ContentSizeInBytes ] // (0-3 zero bytes to align to a 4-byte boundary) // // ================ 3. Args ================================== // // DxilSourceInfo_Args // // char ArgName[]; char NullTerm; // char ArgValue[]; char NullTerm; // // char ArgName[]; char NullTerm; // char ArgValue[]; char NullTerm; // // ... // // char ArgName[]; char NullTerm; // char ArgValue[]; char NullTerm; // struct DxilSourceInfo { uint32_t AlignedSizeInBytes; // Total size of the contents including this header uint16_t Flags; // Reserved, must be set to zero. uint16_t SectionCount; // The number of sections in the source info. }; enum class DxilSourceInfoSectionType : uint16_t { SourceContents = 0, SourceNames = 1, Args = 2, }; struct DxilSourceInfoSection { uint32_t AlignedSizeInBytes; // Size of the section, including this header, // and the padding. Aligned to 4-byte boundary. uint16_t Flags; // Reserved, must be set to zero. DxilSourceInfoSectionType Type; // The type of data following this header. }; struct DxilSourceInfo_Args { uint32_t Flags; // Reserved, must be set to zero. uint32_t SizeInBytes; // Length of all argument pairs, including their null // terminators, not including this header. uint32_t Count; // Number of arguments. // Followed by `Count` argument pairs. // // For example, given the following arguments: // /T ps_6_0 -EMain -D MyDefine=1 /DMyOtherDefine=2 -Zi MyShader.hlsl // // The argument pair data becomes: // T\0ps_6_0\0 // E\0Main\0 // D\0MyDefine=1\0 // D\0MyOtherDefine=2\0 // Zi\0\0 // \0MyShader.hlsl\0 // }; struct DxilSourceInfo_SourceNames { uint32_t Flags; // Reserved, must be set to 0. uint32_t Count; // The number of data entries uint16_t EntriesSizeInBytes; // The total size of the data entries following // this header. // Followed by `Count` data entries with the header // DxilSourceInfo_SourceNamesEntry }; struct DxilSourceInfo_SourceNamesEntry { uint32_t AlignedSizeInBytes; // Size of the data including this header and // padding. Aligned to 4-byte boundary. uint32_t Flags; // Reserved, must be set to 0. uint32_t NameSizeInBytes; // Size of the file name, *including* the null // terminator. uint32_t ContentSizeInBytes; // Size of the file content, *including* the null // terminator. // Followed by NameSizeInBytes bytes of the UTF-8-encoded file name (including // null terminator). Followed by [0-3] zero bytes to align to a 4-byte // boundary. }; enum class DxilSourceInfo_SourceContentsCompressType : uint16_t { None, Zlib }; struct DxilSourceInfo_SourceContents { uint32_t AlignedSizeInBytes; // Size of the entry including this header. // Aligned to 4-byte boundary. uint16_t Flags; // Reserved, must be set to 0. DxilSourceInfo_SourceContentsCompressType CompressType; // The type of compression used to compress the data uint32_t EntriesSizeInBytes; // The size of the data entries following this header. uint32_t UncompressedEntriesSizeInBytes; // Total size of the data entries // when uncompressed. uint32_t Count; // The number of data entries // Followed by (compressed) `Count` data entries with the header // DxilSourceInfo_SourceContentsEntry }; struct DxilSourceInfo_SourceContentsEntry { uint32_t AlignedSizeInBytes; // Size of the entry including this header and // padding. Aligned to 4-byte boundary. uint32_t Flags; // Reserved, must be set to 0. uint32_t ContentSizeInBytes; // Size of the data following this header, // *including* the null terminator // Followed by ContentSizeInBytes bytes of the UTF-8-encoded content // (including null terminator). Followed by [0-3] zero bytes to align to a // 4-byte boundary. }; #pragma pack(pop) enum class DxilShaderPDBInfoVersion : uint16_t { Version_0 = 0, // At this point, the data is still subject to change. LatestPlus1, Latest = LatestPlus1 - 1 }; enum class DxilShaderPDBInfoCompressionType : uint16_t { Uncompressed, Zlib, }; // Header for generic PDB info. It's only found in the shader PDB and contains // all the information about shader's creation, such as compilation args, // shader sources, shader libraries, etc. // // This data part replaces DxilSourceInfo completely. Instead of using a custom // format, it uses the existing RDAT shader reflection format. See // include\dxc\DxilContainer\RDAT_PdbInfoTypes.inl for more information. // struct DxilShaderPDBInfo { DxilShaderPDBInfoVersion Version; DxilShaderPDBInfoCompressionType CompressionType; uint32_t SizeInBytes; uint32_t UncompressedSizeInBytes; }; /// Gets a part header by index. inline const DxilPartHeader * GetDxilContainerPart(const DxilContainerHeader *pHeader, uint32_t index) { const uint8_t *pLinearContainer = reinterpret_cast<const uint8_t *>(pHeader); const uint32_t *pPartOffsetTable = reinterpret_cast<const uint32_t *>(pHeader + 1); return reinterpret_cast<const DxilPartHeader *>(pLinearContainer + pPartOffsetTable[index]); } /// Gets a part header by index. inline DxilPartHeader *GetDxilContainerPart(DxilContainerHeader *pHeader, uint32_t index) { return const_cast<DxilPartHeader *>(GetDxilContainerPart( reinterpret_cast<const DxilContainerHeader *>(pHeader), index)); } /// Gets the part data from the header. inline const char *GetDxilPartData(const DxilPartHeader *pPart) { return reinterpret_cast<const char *>(pPart + 1); } /// Gets the part data from the header. inline char *GetDxilPartData(DxilPartHeader *pPart) { return reinterpret_cast<char *>(pPart + 1); } /// Gets a part header by fourCC DxilPartHeader *GetDxilPartByType(DxilContainerHeader *pHeader, DxilFourCC fourCC); /// Gets a part header by fourCC const DxilPartHeader *GetDxilPartByType(const DxilContainerHeader *pHeader, DxilFourCC fourCC); /// Returns valid DxilProgramHeader. nullptr if does not exist. DxilProgramHeader *GetDxilProgramHeader(DxilContainerHeader *pHeader, DxilFourCC fourCC); /// Returns valid DxilProgramHeader. nullptr if does not exist. const DxilProgramHeader * GetDxilProgramHeader(const DxilContainerHeader *pHeader, DxilFourCC fourCC); /// Initializes container with the specified values. void InitDxilContainer(DxilContainerHeader *pHeader, uint32_t partCount, uint32_t containerSizeInBytes); /// Checks whether pHeader claims by signature to be a DXIL container /// and the length is at least sizeof(DxilContainerHeader). const DxilContainerHeader *IsDxilContainerLike(const void *ptr, size_t length); DxilContainerHeader *IsDxilContainerLike(void *ptr, size_t length); /// Checks whether the DXIL container is valid and in-bounds. bool IsValidDxilContainer(const DxilContainerHeader *pHeader, size_t length); /// Use this type as a unary predicate functor. struct DxilPartIsType { uint32_t IsFourCC; DxilPartIsType(uint32_t FourCC) : IsFourCC(FourCC) {} bool operator()(const DxilPartHeader *pPart) const { return pPart->PartFourCC == IsFourCC; } }; /// Use this type as an iterator over the part headers. struct DxilPartIterator { using iterator_category = std::input_iterator_tag; using value_type = const DxilContainerHeader *; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; const DxilContainerHeader *pHeader; uint32_t index; DxilPartIterator(const DxilContainerHeader *h, uint32_t i) : pHeader(h), index(i) {} // increment DxilPartIterator &operator++() { ++index; return *this; } DxilPartIterator operator++(int) { DxilPartIterator result(pHeader, index); ++index; return result; } // input iterator - compare and deref bool operator==(const DxilPartIterator &other) const { return index == other.index && pHeader == other.pHeader; } bool operator!=(const DxilPartIterator &other) const { return index != other.index || pHeader != other.pHeader; } const DxilPartHeader *operator*() const { return GetDxilContainerPart(pHeader, index); } }; DxilPartIterator begin(const DxilContainerHeader *pHeader); DxilPartIterator end(const DxilContainerHeader *pHeader); inline bool IsValidDxilBitcodeHeader(const DxilBitcodeHeader *pHeader, uint32_t length) { return length > sizeof(DxilBitcodeHeader) && pHeader->BitcodeOffset + pHeader->BitcodeSize > pHeader->BitcodeOffset && length >= pHeader->BitcodeOffset + pHeader->BitcodeSize && pHeader->DxilMagic == DxilMagicValue; } inline void InitBitcodeHeader(DxilBitcodeHeader &header, uint32_t dxilVersion, uint32_t bitcodeSize) { header.DxilMagic = DxilMagicValue; header.DxilVersion = dxilVersion; header.BitcodeOffset = sizeof(DxilBitcodeHeader); header.BitcodeSize = bitcodeSize; } inline void GetDxilProgramBitcode(const DxilProgramHeader *pHeader, const char **pBitcode, uint32_t *pBitcodeLength) { *pBitcode = reinterpret_cast<const char *>(&pHeader->BitcodeHeader) + pHeader->BitcodeHeader.BitcodeOffset; *pBitcodeLength = pHeader->BitcodeHeader.BitcodeSize; } inline bool IsValidDxilProgramHeader(const DxilProgramHeader *pHeader, uint32_t length) { return length >= sizeof(DxilProgramHeader) && length >= (pHeader->SizeInUint32 * sizeof(uint32_t)) && IsValidDxilBitcodeHeader( &pHeader->BitcodeHeader, length - offsetof(DxilProgramHeader, BitcodeHeader)); } inline void InitProgramHeader(DxilProgramHeader &header, uint32_t shaderVersion, uint32_t dxilVersion, uint32_t bitcodeSize) { header.ProgramVersion = shaderVersion; header.SizeInUint32 = sizeof(DxilProgramHeader) / sizeof(uint32_t) + bitcodeSize / sizeof(uint32_t) + ((bitcodeSize % 4) ? 1 : 0); InitBitcodeHeader(header.BitcodeHeader, dxilVersion, bitcodeSize); } inline const char *GetDxilBitcodeData(const DxilProgramHeader *pHeader) { const DxilBitcodeHeader *pBCHdr = &(pHeader->BitcodeHeader); return (const char *)pBCHdr + pBCHdr->BitcodeOffset; } inline uint32_t GetDxilBitcodeSize(const DxilProgramHeader *pHeader) { return pHeader->BitcodeHeader.BitcodeSize; } /// Extract the shader type from the program version value. inline DXIL::ShaderKind GetVersionShaderType(uint32_t programVersion) { return (DXIL::ShaderKind)((programVersion & 0xffff0000) >> 16); } inline uint32_t GetVersionMajor(uint32_t programVersion) { return (programVersion & 0xf0) >> 4; } inline uint32_t GetVersionMinor(uint32_t programVersion) { return (programVersion & 0xf); } inline uint32_t EncodeVersion(DXIL::ShaderKind shaderType, uint32_t major, uint32_t minor) { return ((unsigned)shaderType << 16) | (major << 4) | minor; } inline bool IsDxilShaderDebugNameValid(const DxilPartHeader *pPart) { if (pPart->PartFourCC != DFCC_ShaderDebugName) return false; if (pPart->PartSize < MinDxilShaderDebugNameSize) return false; const DxilShaderDebugName *pDebugNameContent = reinterpret_cast<const DxilShaderDebugName *>(GetDxilPartData(pPart)); uint16_t ExpectedSize = sizeof(DxilShaderDebugName) + pDebugNameContent->NameLength + 1; if (ExpectedSize & 0x3) { ExpectedSize += 0x4; ExpectedSize &= ~(0x3); } if (pPart->PartSize != ExpectedSize) return false; return true; } inline bool GetDxilShaderDebugName(const DxilPartHeader *pDebugNamePart, const char **ppUtf8Name, uint16_t *pUtf8NameLen) { *ppUtf8Name = nullptr; if (!IsDxilShaderDebugNameValid(pDebugNamePart)) { return false; } const DxilShaderDebugName *pDebugNameContent = reinterpret_cast<const DxilShaderDebugName *>( GetDxilPartData(pDebugNamePart)); if (pUtf8NameLen) { *pUtf8NameLen = pDebugNameContent->NameLength; } *ppUtf8Name = (const char *)(pDebugNameContent + 1); return true; } enum class SerializeDxilFlags : uint32_t { None = 0, // No flags defined. IncludeDebugInfoPart = 1 << 0, // Include the debug info part in the container. IncludeDebugNamePart = 1 << 1, // Include the debug name part in the container. DebugNameDependOnSource = 1 << 2, // Make the debug name depend on source (and not just final module). StripReflectionFromDxilPart = 1 << 3, // Strip Reflection info from DXIL part. IncludeReflectionPart = 1 << 4, // Include reflection in STAT part. StripRootSignature = 1 << 5, // Strip Root Signature from main shader container. }; inline SerializeDxilFlags &operator|=(SerializeDxilFlags &l, const SerializeDxilFlags &r) { l = static_cast<SerializeDxilFlags>(static_cast<int>(l) | static_cast<int>(r)); return l; } inline SerializeDxilFlags &operator&=(SerializeDxilFlags &l, const SerializeDxilFlags &r) { l = static_cast<SerializeDxilFlags>(static_cast<int>(l) & static_cast<int>(r)); return l; } inline int operator&(SerializeDxilFlags l, SerializeDxilFlags r) { return static_cast<int>(l) & static_cast<int>(r); } inline SerializeDxilFlags operator~(SerializeDxilFlags l) { return static_cast<SerializeDxilFlags>(~static_cast<uint32_t>(l)); } void CreateDxcContainerReflection(IDxcContainerReflection **ppResult); // Converts uint32_t partKind to char array object. inline char *PartKindToCharArray(uint32_t partKind, char *pText) { pText[0] = (char)((partKind & 0x000000FF) >> 0); pText[1] = (char)((partKind & 0x0000FF00) >> 8); pText[2] = (char)((partKind & 0x00FF0000) >> 16); pText[3] = (char)((partKind & 0xFF000000) >> 24); pText[4] = '\0'; return pText; } inline size_t GetOffsetTableSize(uint32_t partCount) { return sizeof(uint32_t) * partCount; } // Compute total size of the dxil container from parts information inline size_t GetDxilContainerSizeFromParts(uint32_t partCount, uint32_t partsSize) { return partsSize + (uint32_t)sizeof(DxilContainerHeader) + GetOffsetTableSize(partCount) + (uint32_t)sizeof(DxilPartHeader) * partCount; } } // namespace hlsl #endif // __DXC_CONTAINER__
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilContainer/DxilRuntimeReflection.inl
/////////////////////////////////////////////////////////////////////////////// // // // DxilRuntimeReflection.inl // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Defines shader reflection for runtime usage. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxc/DxilContainer/DxilRuntimeReflection.h" #include <cwchar> #include <memory> #include <unordered_map> #include <vector> namespace hlsl { namespace RDAT { #define DEF_RDAT_TYPES DEF_RDAT_READER_IMPL #include "dxc/DxilContainer/RDAT_Macros.inl" struct ResourceKey { uint32_t Class, ID; ResourceKey(uint32_t Class, uint32_t ID) : Class(Class), ID(ID) {} bool operator==(const ResourceKey &other) const { return other.Class == Class && other.ID == ID; } }; // Size-checked reader // on overrun: throw buffer_overrun{}; // on overlap: throw buffer_overlap{}; class CheckedReader { const char *Ptr; size_t Size; size_t Offset; public: class exception : public std::exception {}; class buffer_overrun : public exception { public: buffer_overrun() noexcept {} virtual const char *what() const noexcept override { return ("buffer_overrun"); } }; class buffer_overlap : public exception { public: buffer_overlap() noexcept {} virtual const char *what() const noexcept override { return ("buffer_overlap"); } }; CheckedReader(const void *ptr, size_t size) : Ptr(reinterpret_cast<const char *>(ptr)), Size(size), Offset(0) {} void Reset(size_t offset = 0) { if (offset >= Size) throw buffer_overrun{}; Offset = offset; } // offset is absolute, ensure offset is >= current offset void Advance(size_t offset = 0) { if (offset < Offset) throw buffer_overlap{}; if (offset >= Size) throw buffer_overrun{}; Offset = offset; } void CheckBounds(size_t size) const { assert(Offset <= Size && "otherwise, offset larger than size"); if (size > Size - Offset) throw buffer_overrun{}; } template <typename T> const T *Cast(size_t size = 0) { if (0 == size) size = sizeof(T); CheckBounds(size); return reinterpret_cast<const T *>(Ptr + Offset); } template <typename T> const T &Read() { const size_t size = sizeof(T); const T *p = Cast<T>(size); Offset += size; return *p; } template <typename T> const T *ReadArray(size_t count = 1) { const size_t size = sizeof(T) * count; const T *p = Cast<T>(size); Offset += size; return p; } }; DxilRuntimeData::DxilRuntimeData() : DxilRuntimeData(nullptr, 0) {} DxilRuntimeData::DxilRuntimeData(const void *ptr, size_t size) { InitFromRDAT(ptr, size); } static void InitTable(RDATContext &ctx, CheckedReader &PR, RecordTableIndex tableIndex) { RuntimeDataTableHeader table = PR.Read<RuntimeDataTableHeader>(); size_t tableSize = table.RecordCount * table.RecordStride; ctx.Table(tableIndex) .Init(PR.ReadArray<char>(tableSize), table.RecordCount, table.RecordStride); } // initializing reader from RDAT. return true if no error has occured. bool DxilRuntimeData::InitFromRDAT(const void *pRDAT, size_t size) { if (pRDAT) { m_DataSize = size; try { CheckedReader Reader(pRDAT, size); RuntimeDataHeader RDATHeader = Reader.Read<RuntimeDataHeader>(); if (RDATHeader.Version < RDAT_Version_10) { return false; } const uint32_t *offsets = Reader.ReadArray<uint32_t>(RDATHeader.PartCount); for (uint32_t i = 0; i < RDATHeader.PartCount; ++i) { Reader.Advance(offsets[i]); RuntimeDataPartHeader part = Reader.Read<RuntimeDataPartHeader>(); CheckedReader PR(Reader.ReadArray<char>(part.Size), part.Size); switch (part.Type) { case RuntimeDataPartType::StringBuffer: { m_Context.StringBuffer.Init(PR.ReadArray<char>(part.Size), part.Size); break; } case RuntimeDataPartType::IndexArrays: { uint32_t count = part.Size / sizeof(uint32_t); m_Context.IndexTable.Init(PR.ReadArray<uint32_t>(count), count); break; } case RuntimeDataPartType::RawBytes: { m_Context.RawBytes.Init(PR.ReadArray<char>(part.Size), part.Size); break; } // Once per table. #define RDAT_STRUCT_TABLE(type, table) \ case RuntimeDataPartType::table: \ InitTable(m_Context, PR, RecordTableIndex::table); \ break; #define DEF_RDAT_TYPES DEF_RDAT_DEFAULTS #include "dxc/DxilContainer/RDAT_Macros.inl" default: continue; // Skip unrecognized parts } } #ifndef NDEBUG return Validate(); #else // NDEBUG return true; #endif // NDEBUG } catch (CheckedReader::exception e) { // TODO: error handling // throw hlsl::Exception(DXC_E_MALFORMED_CONTAINER, e.what()); return false; } } m_DataSize = 0; return false; } // TODO: Incorporate field names and report errors in error stream // TODO: Low-pri: Check other things like that all the index, string, // and binary buffer space is actually used. template <typename _RecordType> static bool ValidateRecordRef(const RDATContext &ctx, uint32_t id) { if (id == RDAT_NULL_REF) return true; // id should be a valid index into the appropriate table auto &table = ctx.Table(RecordTraits<_RecordType>::TableIndex()); if (id >= table.Count()) return false; return true; } static bool ValidateIndexArrayRef(const RDATContext &ctx, uint32_t id) { if (id == RDAT_NULL_REF) return true; uint32_t size = ctx.IndexTable.Count(); // check that id < size of index array if (id >= size) return false; // check that array size fits in remaining index space if (id + ctx.IndexTable.Data()[id] >= size) return false; return true; } template <typename _RecordType> static bool ValidateRecordArrayRef(const RDATContext &ctx, uint32_t id) { // Make sure index array is well-formed if (!ValidateIndexArrayRef(ctx, id)) return false; // Make sure each record id is a valid record ref in the table auto ids = ctx.IndexTable.getRow(id); for (unsigned i = 0; i < ids.Count(); i++) { if (!ValidateRecordRef<_RecordType>(ctx, ids.At(i))) return false; } return true; } static bool ValidateStringRef(const RDATContext &ctx, uint32_t id) { if (id == RDAT_NULL_REF) return true; uint32_t size = ctx.StringBuffer.Size(); if (id >= size) return false; return true; } static bool ValidateStringArrayRef(const RDATContext &ctx, uint32_t id) { if (id == RDAT_NULL_REF) return true; // Make sure index array is well-formed if (!ValidateIndexArrayRef(ctx, id)) return false; // Make sure each index is valid in string buffer auto ids = ctx.IndexTable.getRow(id); for (unsigned i = 0; i < ids.Count(); i++) { if (!ValidateStringRef(ctx, ids.At(i))) return false; } return true; } // Specialized for each record type template <typename _RecordType> bool ValidateRecord(const RDATContext &ctx, const _RecordType *pRecord) { return false; } #define DEF_RDAT_TYPES DEF_RDAT_STRUCT_VALIDATION #include "dxc/DxilContainer/RDAT_Macros.inl" // This class ensures that all versions of record to latest one supported by // table stride are validated class RecursiveRecordValidator { const hlsl::RDAT::RDATContext &m_Context; uint32_t m_RecordStride; public: RecursiveRecordValidator(const hlsl::RDAT::RDATContext &ctx, uint32_t recordStride) : m_Context(ctx), m_RecordStride(recordStride) {} template <typename _RecordType> bool Validate(const _RecordType *pRecord) const { if (pRecord && sizeof(_RecordType) <= m_RecordStride) { if (!ValidateRecord(m_Context, pRecord)) return false; return ValidateDerived<_RecordType>(pRecord); } return true; } // Specialized for base type to recurse into derived template <typename _RecordType> bool ValidateDerived(const _RecordType *) const { return true; } }; template <typename _RecordType> static bool ValidateRecordTable(RDATContext &ctx, RecordTableIndex tableIndex) { // iterate through records, bounds-checking all refs and index arrays auto &table = ctx.Table(tableIndex); for (unsigned i = 0; i < table.Count(); i++) { RecursiveRecordValidator(ctx, table.Stride()) .Validate<_RecordType>(table.Row<_RecordType>(i)); } return true; } bool DxilRuntimeData::Validate() { if (m_Context.StringBuffer.Size()) { if (m_Context.StringBuffer.Data()[m_Context.StringBuffer.Size() - 1] != 0) return false; } // Once per table. #define RDAT_STRUCT_TABLE(type, table) \ ValidateRecordTable<type>(m_Context, RecordTableIndex::table); // As an assumption of the way record types are versioned, derived record // types must always be larger than base record types. #define RDAT_STRUCT_DERIVED(type, base) \ static_assert(sizeof(type) > sizeof(base), \ "otherwise, derived record type " #type \ " is not larger than base record type " #base "."); #define DEF_RDAT_TYPES DEF_RDAT_DEFAULTS #include "dxc/DxilContainer/RDAT_Macros.inl" return true; } } // namespace RDAT } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilContainer/DxilContainerReader.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilContainerReader.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Helper class for reading from dxil container. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "dxc/DxilContainer/DxilContainer.h" #include "dxc/Support/Global.h" #include "dxc/Support/WinIncludes.h" #include "llvm/ADT/STLExtras.h" namespace hlsl { const uint32_t DXIL_CONTAINER_BLOB_NOT_FOUND = UINT_MAX; struct DxilContainerHeader; //============================================================================ // DxilContainerReader // // Parse a DXIL or DXBC Container that you provide as input. // // Basic usage: // (1) Call Load() // (2) Call various Get*() commands to retrieve information about the // container such as how many blobs are in it, the hash of the container, // the version #, and most importantly retrieve all of the Blobs. You can // retrieve blobs by searching for the FourCC, or enumerate through all of // them. Multiple blobs can even have the same FourCC, if you choose to // create the DXBC that way, and this parser will let you discover all of // them. // (3) You can parse a new container by calling Load() again, or just get rid // of the class. // class DxilContainerReader { public: DxilContainerReader() {} // Sets the container to be parsed, and does some // basic integrity checking, making sure the blob FourCCs // are all from the known list, and ensuring the version is: // Major = DXBC_MAJOR_VERSION // Minor = DXBC_MAJOR_VERSION // // Returns S_OK or E_FAIL HRESULT Load(const void *pContainer, uint32_t containerSizeInBytes); HRESULT GetVersion(DxilContainerVersion *pResult); HRESULT GetPartCount(uint32_t *pResult); HRESULT GetPartContent(uint32_t idx, const void **ppResult, uint32_t *pResultSize = nullptr); HRESULT GetPartFourCC(uint32_t idx, uint32_t *pResult); HRESULT FindFirstPartKind(uint32_t kind, uint32_t *pResult); private: const void *m_pContainer = nullptr; uint32_t m_uContainerSize = 0; const DxilContainerHeader *m_pHeader = nullptr; bool IsLoaded() const { return m_pHeader != nullptr; } }; } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilContainer/CMakeLists.txt
add_hlsl_hctgen(RDAT_LibraryTypes OUTPUT RDAT_LibraryTypes.inl CODE_TAG)
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilContainer/RDAT_PdbInfoTypes.inl
/////////////////////////////////////////////////////////////////////////////// // // // RDAT_PdbInfoTypes.inl // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Defines macros use to define types Dxil PDBInfo data. // // // /////////////////////////////////////////////////////////////////////////////// #ifdef DEF_RDAT_TYPES #define RECORD_TYPE DxilPdbInfoLibrary RDAT_STRUCT_TABLE(DxilPdbInfoLibrary, DxilPdbInfoLibraryTable) RDAT_STRING(Name) RDAT_BYTES(Data) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE DxilPdbInfoSource RDAT_STRUCT_TABLE(DxilPdbInfoSource, DxilPdbInfoSourceTable) RDAT_STRING(Name) RDAT_STRING(Content) RDAT_STRUCT_END() #undef RECORD_TYPE #define RECORD_TYPE DxilPdbInfo RDAT_STRUCT_TABLE(DxilPdbInfo, DxilPdbInfoTable) RDAT_RECORD_ARRAY_REF(DxilPdbInfoSource, Sources) RDAT_RECORD_ARRAY_REF(DxilPdbInfoLibrary, Libraries) RDAT_STRING_ARRAY_REF(ArgPairs) RDAT_BYTES(Hash) RDAT_STRING(PdbName) RDAT_VALUE(uint32_t, CustomToolchainId) RDAT_BYTES(CustomToolchainData) RDAT_BYTES(WholeDxil) RDAT_STRUCT_END() #undef RECORD_TYPE #endif // DEF_RDAT_TYPES
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilContainer/DxilRDATBuilder.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilRDATBuilder.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Helper type to build the RDAT data format. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "DxilRDATParts.h" #include <vector> namespace hlsl { // Like DXIL container, RDAT itself is a mini container that contains multiple // RDAT parts class DxilRDATBuilder { llvm::SmallVector<char, 1024> m_RDATBuffer; std::vector<std::unique_ptr<RDATPart>> m_Parts; StringBufferPart *m_pStringBufferPart = nullptr; IndexArraysPart *m_pIndexArraysPart = nullptr; RawBytesPart *m_pRawBytesPart = nullptr; RDATTable *m_pTables[(size_t)RDAT::RecordTableIndex::RecordTableCount] = {}; bool m_bRecordDeduplicationEnabled = true; template <typename T> T *GetOrAddPart(T **ptrStorage) { if (!*ptrStorage) { m_Parts.emplace_back(llvm::make_unique<T>()); *ptrStorage = reinterpret_cast<T *>(m_Parts.back().get()); } return *ptrStorage; } public: DxilRDATBuilder(bool allowRecordDuplication); template <typename T> RDATTable *GetOrAddTable() { RDATTable **tablePtr = &m_pTables[(size_t)RDAT::RecordTraits<T>::TableIndex()]; if (!*tablePtr) { m_Parts.emplace_back(llvm::make_unique<RDATTable>()); *tablePtr = reinterpret_cast<RDATTable *>(m_Parts.back().get()); (*tablePtr)->SetRecordStride(sizeof(T)); (*tablePtr)->SetType(RDAT::RecordTraits<T>::PartType()); (*tablePtr)->SetDeduplication(m_bRecordDeduplicationEnabled); } return *tablePtr; } template <typename T> uint32_t InsertRecord(const T &record) { return GetOrAddTable<T>()->Insert(record); } uint32_t InsertString(llvm::StringRef str) { return GetStringBufferPart().Insert(str); } hlsl::RDAT::BytesRef InsertBytesRef(const void *ptr, size_t size) { return GetRawBytesPart().InsertBytesRef(ptr, size); } hlsl::RDAT::BytesRef InsertBytesRef(llvm::StringRef data) { return GetRawBytesPart().InsertBytesRef(data.data(), data.size()); } template <typename T> uint32_t InsertArray(T begin, T end) { return GetIndexArraysPart().AddIndex(begin, end); } template <typename T> uint32_t InsertArray(T arr) { return InsertArray(arr.begin(), arr.end()); } StringBufferPart &GetStringBufferPart() { return *GetOrAddPart(&m_pStringBufferPart); } IndexArraysPart &GetIndexArraysPart() { return *GetOrAddPart(&m_pIndexArraysPart); } RawBytesPart &GetRawBytesPart() { return *GetOrAddPart(&m_pRawBytesPart); } struct SizeInfo { uint32_t sizeInBytes; uint32_t numParts; }; SizeInfo ComputeSize() const; uint32_t size() const { return ComputeSize().sizeInBytes; } llvm::StringRef FinalizeAndGetData(); }; } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilContainer/DxilRuntimeReflection.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilLibraryReflection.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Defines shader reflection for runtime usage. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "dxc/DXIL/DxilConstants.h" #include <cstddef> #define RDAT_NULL_REF ((uint32_t)0xFFFFFFFF) namespace hlsl { namespace RDAT { // Data Layout: // -start: // RuntimeDataHeader header; // uint32_t offsets[header.PartCount]; // - for each i in header.PartCount: // - at &header + offsets[i]: // RuntimeDataPartHeader part; // - if part.Type is a Table (Function or Resource): // RuntimeDataTableHeader table; // byte TableData[table.RecordCount][table.RecordStride]; // - else if part.Type is String: // byte UTF8Data[part.Size]; // - else if part.Type is Index: // uint32_t IndexData[part.Size / 4]; enum RuntimeDataVersion { // Cannot be mistaken for part count from prerelease version RDAT_Version_10 = 0x10, }; enum class RuntimeDataGroup : uint32_t { Core = 0, PdbInfo = 1, }; constexpr uint32_t RDAT_PART_ID_WITH_GROUP(RuntimeDataGroup group, uint32_t id) { return (((uint32_t)(group) << 16) | ((id)&0xFFFF)); } enum class RuntimeDataPartType : uint32_t { Invalid = 0, StringBuffer = 1, IndexArrays = 2, ResourceTable = 3, FunctionTable = 4, Last_1_3 = FunctionTable, RawBytes = 5, SubobjectTable = 6, Last_1_4 = SubobjectTable, NodeIDTable = 7, NodeShaderIOAttribTable = 8, NodeShaderFuncAttribTable = 9, IONodeTable = 10, NodeShaderInfoTable = 11, Last_1_8 = NodeShaderInfoTable, Reserved_MeshNodesPreviewInfoTable = 12, // Insert experimental here. SignatureElementTable, VSInfoTable, PSInfoTable, HSInfoTable, DSInfoTable, GSInfoTable, CSInfoTable, MSInfoTable, ASInfoTable, LastPlus1, LastExperimental = LastPlus1 - 1, DxilPdbInfoTable = RDAT_PART_ID_WITH_GROUP(RuntimeDataGroup::PdbInfo, 1), DxilPdbInfoSourceTable = RDAT_PART_ID_WITH_GROUP(RuntimeDataGroup::PdbInfo, 2), DxilPdbInfoLibraryTable = RDAT_PART_ID_WITH_GROUP(RuntimeDataGroup::PdbInfo, 3), }; inline RuntimeDataPartType MaxPartTypeForValVer(unsigned Major, unsigned Minor) { return DXIL::CompareVersions(Major, Minor, 1, 3) < 0 ? RuntimeDataPartType::Invalid // No RDAT before 1.3 : DXIL::CompareVersions(Major, Minor, 1, 4) < 0 ? RuntimeDataPartType::Last_1_3 : DXIL::CompareVersions(Major, Minor, 1, 8) < 0 ? RuntimeDataPartType::Last_1_4 : DXIL::CompareVersions(Major, Minor, 1, 8) == 0 ? RuntimeDataPartType::Last_1_8 : RuntimeDataPartType::LastExperimental; } enum class RecordTableIndex : unsigned { ResourceTable, FunctionTable, SubobjectTable, NodeIDTable, NodeShaderIOAttribTable, NodeShaderFuncAttribTable, IONodeTable, NodeShaderInfoTable, Reserved_MeshNodesPreviewInfoTable, DxilPdbInfoTable, DxilPdbInfoSourceTable, DxilPdbInfoLibraryTable, SignatureElementTable, VSInfoTable, PSInfoTable, HSInfoTable, DSInfoTable, GSInfoTable, CSInfoTable, MSInfoTable, ASInfoTable, RecordTableCount }; /////////////////////////////////////// // Header Structures struct RuntimeDataHeader { uint32_t Version; uint32_t PartCount; // Followed by uint32_t array of offsets to parts // offsets are relative to the beginning of this header // offsets must be 4-byte aligned // uint32_t offsets[]; }; struct RuntimeDataPartHeader { RuntimeDataPartType Type; uint32_t Size; // Not including this header. Must be 4-byte aligned. // Followed by part data // byte Data[ALIGN4(Size)]; }; // For tables of records, such as Function and Resource tables // Stride allows for extending records, with forward and backward compatibility struct RuntimeDataTableHeader { uint32_t RecordCount; uint32_t RecordStride; // Must be 4-byte aligned. // Followed by recordCount records of recordStride size // byte TableData[RecordCount * RecordStride]; }; /////////////////////////////////////// // Raw Reader Classes // General purpose strided table reader with casting Row() operation that // returns nullptr if stride is smaller than type, for record expansion. class TableReader { const char *m_table; uint32_t m_count; uint32_t m_stride; public: TableReader() : TableReader(nullptr, 0, 0) {} TableReader(const char *table, uint32_t count, uint32_t stride) : m_table(table), m_count(count), m_stride(stride) {} void Init(const char *table, uint32_t count, uint32_t stride) { m_table = table; m_count = count; m_stride = stride; } const char *Data() const { return m_table; } uint32_t Count() const { return m_count; } uint32_t Stride() const { return m_stride; } template <typename T> const T *Row(uint32_t index) const { if (Valid() && index < m_count && sizeof(T) <= m_stride) return reinterpret_cast<const T *>(m_table + (m_stride * index)); return nullptr; } bool Valid() const { return m_table && m_count && m_stride; } operator bool() { return Valid(); } }; // Index table is a sequence of rows, where each row has a count as a first // element followed by the count number of elements pre computing values class IndexTableReader { private: const uint32_t *m_table; uint32_t m_size; public: class IndexRow { private: const uint32_t *m_values; const uint32_t m_count; public: IndexRow() : m_values(nullptr), m_count(0) {} IndexRow(const uint32_t *values, uint32_t count) : m_values(values), m_count(count) {} uint32_t Count() const { return m_count; } uint32_t At(uint32_t i) const { return (m_values && i < m_count) ? m_values[i] : 0; } const uint32_t &operator[](uint32_t i) const { if (m_values && i < m_count) return m_values[i]; return m_values[0]; // If null, we should AV if value is read } bool empty() const { return !(m_values && m_count > 0); } operator bool() const { return !empty(); } }; IndexTableReader() : IndexTableReader(nullptr, 0) {} IndexTableReader(const uint32_t *table, uint32_t size) : m_table(table), m_size(size) {} void Init(const uint32_t *table, uint32_t size) { m_table = table; m_size = size; } IndexRow getRow(uint32_t i) const { if (Valid() && i < m_size - 1 && m_table[i] + i < m_size) { return IndexRow(&m_table[i] + 1, m_table[i]); } return {}; } const uint32_t *Data() const { return m_table; } uint32_t Count() const { return Valid() ? m_size : 0; } bool Valid() const { return m_table && m_size > 0; } operator bool() const { return Valid(); } }; class StringTableReader { const char *m_table = nullptr; uint32_t m_size = 0; public: void Init(const char *table, uint32_t size) { m_table = table; m_size = size; } const char *Get(uint32_t offset) const { (void)m_size; // avoid unused private warning if use above is ignored. return m_table + offset; } uint32_t Size() const { return m_size; } const char *Data() const { return m_table; } }; class RawBytesReader { const void *m_table; uint32_t m_size; public: RawBytesReader(const void *table, uint32_t size) : m_table(table), m_size(size) {} RawBytesReader() : RawBytesReader(nullptr, 0) {} void Init(const void *table, uint32_t size) { m_table = table; m_size = size; } uint32_t Size() const { return m_size; } const void *Get(uint32_t offset) const { return (const void *)(((const char *)m_table) + offset); } }; /////////////////////////////////////// // Record Traits template <typename _T> class RecordTraits { public: static constexpr const char *TypeName(); static constexpr RuntimeDataPartType PartType(); // If the following static assert is hit, it means a structure defined with // RDAT_STRUCT is being used in ref type, which requires the struct to have // a table and be defined with RDAT_STRUCT_TABLE instead. static constexpr RecordTableIndex TableIndex(); // RecordSize() is defined in order to allow for use of forward decl type in // RecordRef static constexpr size_t RecordSize() { return sizeof(_T); } static constexpr size_t MaxRecordSize() { return RecordTraits<_T>::DerivedRecordSize(); } static constexpr size_t DerivedRecordSize() { return sizeof(_T); } }; /////////////////////////////////////// // RDATContext struct RDATContext { StringTableReader StringBuffer; IndexTableReader IndexTable; RawBytesReader RawBytes; TableReader Tables[(unsigned)RecordTableIndex::RecordTableCount]; const TableReader &Table(RecordTableIndex idx) const { if (idx < RecordTableIndex::RecordTableCount) return Tables[(unsigned)idx]; return Tables[0]; // TODO: assert } TableReader &Table(RecordTableIndex idx) { return const_cast<TableReader &>(((const RDATContext *)this)->Table(idx)); } template <typename RecordType> const TableReader &Table() const { static_assert(RecordTraits<RecordType>::TableIndex() < RecordTableIndex::RecordTableCount, ""); return Table(RecordTraits<RecordType>::TableIndex()); } template <typename RecordType> TableReader &Table() { return const_cast<TableReader &>( ((const RDATContext *)this) ->Table(RecordTraits<RecordType>::TableIndex())); } }; /////////////////////////////////////// // Generic Reader Classes class BaseRecordReader { protected: const RDATContext *m_pContext = nullptr; const void *m_pRecord = nullptr; uint32_t m_Size = 0; template <typename _ReaderTy> const _ReaderTy asReader() const { if (*this && m_Size >= RecordTraits<typename _ReaderTy::RecordType>::RecordSize()) return _ReaderTy(*this); return {}; } template <typename _T> const _T *asRecord() const { return static_cast<const _T *>( (*this && m_Size >= RecordTraits<_T>::RecordSize()) ? m_pRecord : nullptr); } void InvalidateReader() { m_pContext = nullptr; m_pRecord = nullptr; m_Size = 0; } public: BaseRecordReader(const RDATContext *ctx, const void *record, uint32_t size) : m_pContext(ctx), m_pRecord(record), m_Size(size) {} BaseRecordReader() : BaseRecordReader(nullptr, nullptr, 0) {} // Is this a valid reader operator bool() const { return m_pContext != nullptr && m_pRecord != nullptr && m_Size != 0; } const RDATContext *GetContext() const { return m_pContext; } }; template <typename _ReaderTy> class RecordArrayReader { const RDATContext *m_pContext; const uint32_t m_IndexOffset; public: RecordArrayReader(const RDATContext *ctx, uint32_t indexOffset) : m_pContext(ctx), m_IndexOffset(indexOffset) { typedef typename _ReaderTy::RecordType RecordType; const TableReader &Table = m_pContext->Table<RecordType>(); // RecordArrays must be declared with the base record type, // with element reader upcast as necessary. if (Table.Stride() < RecordTraits<RecordType>::RecordSize()) InvalidateReader(); } RecordArrayReader() : RecordArrayReader(nullptr, 0) {} uint32_t Count() const { return *this ? m_pContext->IndexTable.getRow(m_IndexOffset).Count() : 0; } const _ReaderTy operator[](uint32_t idx) const { typedef typename _ReaderTy::RecordType RecordType; if (*this) { const TableReader &Table = m_pContext->Table<RecordType>(); return _ReaderTy(BaseRecordReader( m_pContext, (const void *)Table.Row<RecordType>( m_pContext->IndexTable.getRow(m_IndexOffset).At(idx)), Table.Stride())); } return {}; } // Is this a valid reader operator bool() const { return m_pContext != nullptr && m_IndexOffset < RDAT_NULL_REF; } void InvalidateReader() { m_pContext = nullptr; } const RDATContext *GetContext() const { return m_pContext; } }; class StringArrayReader { const RDATContext *m_pContext; const uint32_t m_IndexOffset; public: StringArrayReader(const RDATContext *pContext, uint32_t indexOffset) : m_pContext(pContext), m_IndexOffset(indexOffset) {} uint32_t Count() const { return *this ? m_pContext->IndexTable.getRow(m_IndexOffset).Count() : 0; } const char *operator[](uint32_t idx) const { return *this ? m_pContext->StringBuffer.Get( m_pContext->IndexTable.getRow(m_IndexOffset).At(idx)) : 0; } // Is this a valid reader operator bool() const { return m_pContext != nullptr && m_IndexOffset < RDAT_NULL_REF; } void InvalidateReader() { m_pContext = nullptr; } const RDATContext *GetContext() const { return m_pContext; } }; /////////////////////////////////////// // Field Helpers template <typename _T> struct RecordRef { uint32_t Index; template <typename RecordType = _T> const _T *Get(const RDATContext &ctx) const { return ctx.Table<_T>().template Row<RecordType>(Index); } RecordRef &operator=(uint32_t index) { Index = index; return *this; } operator uint32_t &() { return Index; } operator const uint32_t &() const { return Index; } uint32_t *operator&() { return &Index; } }; template <typename _T> struct RecordArrayRef { uint32_t Index; RecordArrayReader<_T> Get(const RDATContext &ctx) const { return RecordArrayReader<_T>(ctx.IndexTable, ctx.Table<_T>(), Index); } RecordArrayRef &operator=(uint32_t index) { Index = index; return *this; } operator uint32_t &() { return Index; } operator const uint32_t &() const { return Index; } uint32_t *operator&() { return &Index; } }; struct RDATString { uint32_t Offset; const char *Get(const RDATContext &ctx) const { return ctx.StringBuffer.Get(Offset); } RDATString &operator=(uint32_t offset) { Offset = offset; return *this; } operator uint32_t &() { return Offset; } operator const uint32_t &() const { return Offset; } uint32_t *operator&() { return &Offset; } }; struct RDATStringArray { uint32_t Index; StringArrayReader Get(const RDATContext &ctx) const { return StringArrayReader(&ctx, Index); } operator bool() const { return Index == 0 ? false : true; } RDATStringArray &operator=(uint32_t index) { Index = index; return *this; } operator uint32_t &() { return Index; } operator const uint32_t &() const { return Index; } uint32_t *operator&() { return &Index; } }; struct IndexArrayRef { uint32_t Index; IndexTableReader::IndexRow Get(const RDATContext &ctx) const { return ctx.IndexTable.getRow(Index); } IndexArrayRef &operator=(uint32_t index) { Index = index; return *this; } operator uint32_t &() { return Index; } operator const uint32_t &() const { return Index; } uint32_t *operator&() { return &Index; } }; struct BytesRef { uint32_t Offset; uint32_t Size; const void *GetBytes(const RDATContext &ctx) const { return ctx.RawBytes.Get(Offset); } template <typename _T> const _T *GetAs(const RDATContext &ctx) const { return (sizeof(_T) > Size) ? nullptr : reinterpret_cast<const _T *>(ctx.RawBytes.Get(Offset)); } uint32_t *operator&() { return &Offset; } }; struct BytesPtr { const void *Ptr = nullptr; uint32_t Size = 0; BytesPtr(const void *ptr, uint32_t size) : Ptr(ptr), Size(size) {} BytesPtr() : BytesPtr(nullptr, 0) {} template <typename _T> const _T *GetAs() const { return (sizeof(_T) > Size) ? nullptr : reinterpret_cast<const _T *>(Ptr); } }; /////////////////////////////////////// // Record Helpers template <typename _RecordReader> class RecordReader : public BaseRecordReader { public: typedef _RecordReader ThisReaderType; RecordReader(const BaseRecordReader &base) : BaseRecordReader(base) { typedef typename _RecordReader::RecordType RecordType; if ((m_pContext || m_pRecord) && m_Size < RecordTraits<RecordType>::RecordSize()) InvalidateReader(); } RecordReader() : BaseRecordReader() {} template <typename _ReaderType> _ReaderType as() { _ReaderType(*this); } protected: template <typename _FieldRecordReader> _FieldRecordReader GetField_RecordValue(const void *pField) const { if (*this) { return _FieldRecordReader(BaseRecordReader( m_pContext, pField, (uint32_t)RecordTraits< typename _FieldRecordReader::RecordType>::RecordSize())); } return {}; } template <typename _FieldRecordReader> _FieldRecordReader GetField_RecordRef(const void *pIndex) const { typedef typename _FieldRecordReader::RecordType RecordType; if (*this) { const TableReader &Table = m_pContext->Table<RecordType>(); return _FieldRecordReader(BaseRecordReader( m_pContext, (const void *)Table.Row<RecordType>(*(const uint32_t *)pIndex), Table.Stride())); } return {}; } template <typename _FieldRecordReader> RecordArrayReader<_FieldRecordReader> GetField_RecordArrayRef(const void *pIndex) const { if (*this) { return RecordArrayReader<_FieldRecordReader>(m_pContext, *(const uint32_t *)pIndex); } return {}; } template <typename _T, typename _StorageTy> _T GetField_Value(const _StorageTy *value) const { _T result = {}; if (*this) result = (_T)*value; return result; } IndexTableReader::IndexRow GetField_IndexArray(const void *pIndex) const { if (*this) { return m_pContext->IndexTable.getRow(*(const uint32_t *)pIndex); } return {}; } // Would use std::array, but don't want this header dependent on that. // Array reference syntax is almost enough reason to abandon C++!!! template <typename _T, size_t _ArraySize> decltype(auto) GetField_ValueArray(_T const (&value)[_ArraySize]) const { typedef _T ArrayType[_ArraySize]; if (*this) return value; return *(const ArrayType *)nullptr; } const char *GetField_String(const void *pIndex) const { return *this ? m_pContext->StringBuffer.Get(*(const uint32_t *)pIndex) : nullptr; } StringArrayReader GetField_StringArray(const void *pIndex) const { return *this ? StringArrayReader(m_pContext, *(const uint32_t *)pIndex) : StringArrayReader(nullptr, 0); } const void *GetField_Bytes(const void *pIndex) const { return *this ? m_pContext->RawBytes.Get(*(const uint32_t *)pIndex) : nullptr; } uint32_t GetField_BytesSize(const void *pIndex) const { return *this ? *(((const uint32_t *)pIndex) + 1) : 0; } }; template <typename _RecordReader> class RecordTableReader { const RDATContext *m_pContext; public: RecordTableReader(const RDATContext *pContext) : m_pContext(pContext) {} template <typename RecordReaderType = _RecordReader> RecordReaderType Row(uint32_t index) const { typedef typename _RecordReader::RecordType RecordType; const TableReader &Table = m_pContext->Table<RecordType>(); return RecordReaderType(BaseRecordReader( m_pContext, Table.Row<RecordType>(index), Table.Stride())); } uint32_t Count() const { return m_pContext->Table<typename _RecordReader::RecordType>().Count(); } uint32_t size() const { return Count(); } const _RecordReader operator[](uint32_t index) const { return Row(index); } operator bool() { return m_pContext && Count(); } }; ///////////////////////////// // All RDAT enums and types #define DEF_RDAT_ENUMS DEF_RDAT_ENUM_CLASS #define DEF_RDAT_TYPES DEF_RDAT_TYPES_FORWARD_DECL #include "dxc/DxilContainer/RDAT_Macros.inl" #define DEF_RDAT_TYPES DEF_RDAT_TYPES_USE_HELPERS #include "dxc/DxilContainer/RDAT_Macros.inl" #define DEF_RDAT_TYPES DEF_RDAT_TRAITS #include "dxc/DxilContainer/RDAT_Macros.inl" #define DEF_RDAT_TYPES DEF_RDAT_READER_DECL #include "dxc/DxilContainer/RDAT_Macros.inl" ///////////////////////////// ///////////////////////////// class DxilRuntimeData { private: RDATContext m_Context; size_t m_DataSize = 0; public: DxilRuntimeData(); DxilRuntimeData(const void *ptr, size_t size); // initializing reader from RDAT. return true if no error has occured. bool InitFromRDAT(const void *pRDAT, size_t size); // Make sure data is well formed. bool Validate(); size_t GetDataSize() const { return m_DataSize; } RDATContext &GetContext() { return m_Context; } const RDATContext &GetContext() const { return m_Context; } #define RDAT_STRUCT_TABLE(type, table) \ RecordTableReader<type##_Reader> Get##table() const { \ return RecordTableReader<type##_Reader>(&m_Context); \ } #define DEF_RDAT_TYPES DEF_RDAT_DEFAULTS #include "dxc/DxilContainer/RDAT_Macros.inl" }; } // namespace RDAT } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilContainer/DxilContainerAssembler.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilContainerAssembler.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Helpers for writing to dxil container. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "dxc/DxilContainer/DxilContainer.h" #include "llvm/ADT/StringRef.h" #include <functional> struct IDxcVersionInfo; struct IStream; class DxilPipelineStateValidation; namespace llvm { class Module; } namespace hlsl { class AbstractMemoryStream; class DxilModule; class RootSignatureHandle; class ShaderModel; namespace DXIL { enum class SignatureKind; } class DxilPartWriter { public: virtual ~DxilPartWriter() {} virtual uint32_t size() const = 0; virtual void write(AbstractMemoryStream *pStream) = 0; }; class DxilContainerWriter : public DxilPartWriter { public: typedef std::function<void(AbstractMemoryStream *)> WriteFn; virtual ~DxilContainerWriter() {} virtual void AddPart(uint32_t FourCC, uint32_t Size, WriteFn Write) = 0; }; DxilPartWriter *NewProgramSignatureWriter(const DxilModule &M, DXIL::SignatureKind Kind); DxilPartWriter *NewRootSignatureWriter(const RootSignatureHandle &S); DxilPartWriter *NewFeatureInfoWriter(const DxilModule &M); DxilPartWriter *NewPSVWriter(const DxilModule &M, uint32_t PSVVersion = UINT_MAX); // DxilModule is non-const because it caches per-function flag computations // used by both CollectShaderFlagsForModule and RDATWriter. DxilPartWriter *NewRDATWriter(DxilModule &M); DxilPartWriter *NewVersionWriter(IDxcVersionInfo *pVersionInfo); // Store serialized ViewID data from DxilModule to PipelineStateValidation. void StoreViewIDStateToPSV(const uint32_t *pInputData, unsigned InputSizeInUInts, DxilPipelineStateValidation &PSV); // Load ViewID state from PSV back to DxilModule view state vector. // Pass nullptr for pOutputData to compute and return needed OutputSizeInUInts. unsigned LoadViewIDStateFromPSV(unsigned *pOutputData, unsigned OutputSizeInUInts, const DxilPipelineStateValidation &PSV); // Unaligned is for matching container for validator version < 1.7. DxilContainerWriter *NewDxilContainerWriter(bool bUnaligned = false); // Set validator version to 0,0 (not validated) then re-emit as much reflection // metadata as possible. void ReEmitLatestReflectionData(llvm::Module *pReflectionM); // Strip functions and serialize module. void StripAndCreateReflectionStream( llvm::Module *pReflectionM, uint32_t *pReflectionPartSizeInBytes, AbstractMemoryStream **ppReflectionStreamOut); void WriteProgramPart(const hlsl::ShaderModel *pModel, AbstractMemoryStream *pModuleBitcode, IStream *pStream); void SerializeDxilContainerForModule( hlsl::DxilModule *pModule, AbstractMemoryStream *pModuleBitcode, IDxcVersionInfo *DXCVersionInfo, AbstractMemoryStream *pStream, llvm::StringRef DebugName, SerializeDxilFlags Flags, DxilShaderHash *pShaderHashOut = nullptr, AbstractMemoryStream *pReflectionStreamOut = nullptr, AbstractMemoryStream *pRootSigStreamOut = nullptr, void *pPrivateData = nullptr, size_t PrivateDataSize = 0); void SerializeDxilContainerForRootSignature( hlsl::RootSignatureHandle *pRootSigHandle, AbstractMemoryStream *pStream); } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilContainer/DxilPipelineStateValidation.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilPipelineStateValidation.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Defines data used by the D3D runtime for PSO validation. // // // /////////////////////////////////////////////////////////////////////////////// #ifndef __DXIL_PIPELINE_STATE_VALIDATION__H__ #define __DXIL_PIPELINE_STATE_VALIDATION__H__ #include "dxc/WinAdapter.h" #include <assert.h> #include <cstring> #include <stdint.h> namespace llvm { class raw_ostream; } // Don't include assert.h here. // Since this header is included from multiple environments, // it is necessary to define assert before this header is included. // #include <assert.h> #ifndef UINT_MAX #define UINT_MAX 0xffffffff #endif // How many dwords are required for mask with one bit per component, 4 // components per vector inline uint32_t PSVComputeMaskDwordsFromVectors(uint32_t Vectors) { return (Vectors + 7) >> 3; } inline uint32_t PSVComputeInputOutputTableDwords(uint32_t InputVectors, uint32_t OutputVectors) { return PSVComputeMaskDwordsFromVectors(OutputVectors) * InputVectors * 4; } #define PSVALIGN(ptr, alignbits) \ (((ptr) + ((1 << (alignbits)) - 1)) & ~((1 << (alignbits)) - 1)) #define PSVALIGN4(ptr) (((ptr) + 3) & ~3) #define PSV_GS_MAX_STREAMS 4 #ifndef NDEBUG #define PSV_RETB(exp) \ do { \ if (!(exp)) { \ assert(false && #exp); \ return false; \ } \ } while (0) #else // NDEBUG #define PSV_RETB(exp) \ do { \ if (!(exp)) { \ return false; \ } \ } while (0) #endif // NDEBUG struct VSInfo { char OutputPositionPresent; }; struct HSInfo { uint32_t InputControlPointCount; // max control points == 32 uint32_t OutputControlPointCount; // max control points == 32 uint32_t TessellatorDomain; // hlsl::DXIL::TessellatorDomain/D3D11_SB_TESSELLATOR_DOMAIN uint32_t TessellatorOutputPrimitive; // hlsl::DXIL::TessellatorOutputPrimitive/D3D11_SB_TESSELLATOR_OUTPUT_PRIMITIVE }; struct DSInfo { uint32_t InputControlPointCount; // max control points == 32 char OutputPositionPresent; uint32_t TessellatorDomain; // hlsl::DXIL::TessellatorDomain/D3D11_SB_TESSELLATOR_DOMAIN }; struct GSInfo { uint32_t InputPrimitive; // hlsl::DXIL::InputPrimitive/D3D10_SB_PRIMITIVE uint32_t OutputTopology; // hlsl::DXIL::PrimitiveTopology/D3D10_SB_PRIMITIVE_TOPOLOGY uint32_t OutputStreamMask; // max streams == 4 (PSV_GS_MAX_STREAMS) char OutputPositionPresent; }; struct PSInfo { char DepthOutput; char SampleFrequency; }; struct MSInfo { uint32_t GroupSharedBytesUsed; uint32_t GroupSharedBytesDependentOnViewID; uint32_t PayloadSizeInBytes; uint16_t MaxOutputVertices; uint16_t MaxOutputPrimitives; }; struct ASInfo { uint32_t PayloadSizeInBytes; }; struct MSInfo1 { uint8_t SigPrimVectors; // Primitive output for MS uint8_t MeshOutputTopology; }; // Versioning is additive and based on size struct PSVRuntimeInfo0 { union { VSInfo VS; HSInfo HS; DSInfo DS; GSInfo GS; PSInfo PS; MSInfo MS; ASInfo AS; }; uint32_t MinimumExpectedWaveLaneCount; // minimum lane count required, 0 if unused uint32_t MaximumExpectedWaveLaneCount; // maximum lane count required, // 0xffffffff if unused }; enum class PSVShaderKind : uint8_t // DXIL::ShaderKind { Pixel = 0, Vertex, Geometry, Hull, Domain, Compute, Library, RayGeneration, Intersection, AnyHit, ClosestHit, Miss, Callable, Mesh, Amplification, Node, Invalid, }; struct PSVRuntimeInfo1 : public PSVRuntimeInfo0 { uint8_t ShaderStage; // PSVShaderKind uint8_t UsesViewID; union { uint16_t MaxVertexCount; // MaxVertexCount for GS only (max 1024) uint8_t SigPatchConstOrPrimVectors; // Output for HS; Input for DS; // Primitive output for MS (overlaps // MS1::SigPrimVectors) struct MSInfo1 MS1; }; // PSVSignatureElement counts uint8_t SigInputElements; uint8_t SigOutputElements; uint8_t SigPatchConstOrPrimElements; // Number of packed vectors per signature uint8_t SigInputVectors; uint8_t SigOutputVectors[PSV_GS_MAX_STREAMS]; // Array for GS Stream Out Index }; struct PSVRuntimeInfo2 : public PSVRuntimeInfo1 { uint32_t NumThreadsX; uint32_t NumThreadsY; uint32_t NumThreadsZ; }; struct PSVRuntimeInfo3 : public PSVRuntimeInfo2 { uint32_t EntryFunctionName; }; enum class PSVResourceType { Invalid = 0, Sampler, CBV, SRVTyped, SRVRaw, SRVStructured, UAVTyped, UAVRaw, UAVStructured, UAVStructuredWithCounter, NumEntries }; enum class PSVResourceKind { Invalid = 0, Texture1D, Texture2D, Texture2DMS, Texture3D, TextureCube, Texture1DArray, Texture2DArray, Texture2DMSArray, TextureCubeArray, TypedBuffer, RawBuffer, StructuredBuffer, CBuffer, Sampler, TBuffer, RTAccelerationStructure, FeedbackTexture2D, FeedbackTexture2DArray, NumEntries }; enum class PSVResourceFlag { None = 0x00000000, UsedByAtomic64 = 0x00000001, }; // Table of null-terminated strings, overall size aligned to dword boundary, // last byte must be null struct PSVStringTable { const char *Table; uint32_t Size; PSVStringTable() : Table(nullptr), Size(0) {} PSVStringTable(const char *table, uint32_t size) : Table(table), Size(size) {} const char *Get(uint32_t offset) const { assert(offset < Size && Table && Table[Size - 1] == '\0'); return Table + offset; } }; // Versioning is additive and based on size struct PSVResourceBindInfo0 { uint32_t ResType; // PSVResourceType uint32_t Space; uint32_t LowerBound; uint32_t UpperBound; void Print(llvm::raw_ostream &O) const; }; struct PSVResourceBindInfo1 : public PSVResourceBindInfo0 { uint32_t ResKind; // PSVResourceKind uint32_t ResFlags; // special characteristics of the resource void Print(llvm::raw_ostream &O) const; }; // Helpers for output dependencies (ViewID and Input-Output tables) struct PSVComponentMask { uint32_t *Mask; uint32_t NumVectors; PSVComponentMask() : Mask(nullptr), NumVectors(0) {} PSVComponentMask(const PSVComponentMask &other) : Mask(other.Mask), NumVectors(other.NumVectors) {} PSVComponentMask(uint32_t *pMask, uint32_t outputVectors) : Mask(pMask), NumVectors(outputVectors) {} const PSVComponentMask &operator|=(const PSVComponentMask &other) { uint32_t dwords = PSVComputeMaskDwordsFromVectors( NumVectors < other.NumVectors ? NumVectors : other.NumVectors); for (uint32_t i = 0; i < dwords; ++i) { Mask[i] |= other.Mask[i]; } return *this; } bool Get(uint32_t ComponentIndex) const { if (ComponentIndex < NumVectors * 4) return (bool)(Mask[ComponentIndex >> 5] & (1 << (ComponentIndex & 0x1F))); return false; } void Set(uint32_t ComponentIndex) { if (ComponentIndex < NumVectors * 4) Mask[ComponentIndex >> 5] |= (1 << (ComponentIndex & 0x1F)); } void Clear(uint32_t ComponentIndex) { if (ComponentIndex < NumVectors * 4) Mask[ComponentIndex >> 5] &= ~(1 << (ComponentIndex & 0x1F)); } bool IsValid() const { return Mask != nullptr; } void Print(llvm::raw_ostream &, const char *, const char *) const; }; struct PSVDependencyTable { uint32_t *Table; uint32_t InputVectors; uint32_t OutputVectors; PSVDependencyTable() : Table(nullptr), InputVectors(0), OutputVectors(0) {} PSVDependencyTable(const PSVDependencyTable &other) : Table(other.Table), InputVectors(other.InputVectors), OutputVectors(other.OutputVectors) {} PSVDependencyTable(uint32_t *pTable, uint32_t inputVectors, uint32_t outputVectors) : Table(pTable), InputVectors(inputVectors), OutputVectors(outputVectors) {} PSVComponentMask GetMaskForInput(uint32_t inputComponentIndex) { return getMaskForInput(inputComponentIndex); } const PSVComponentMask GetMaskForInput(uint32_t inputComponentIndex) const { return getMaskForInput(inputComponentIndex); } bool IsValid() const { return Table != nullptr; } void Print(llvm::raw_ostream &, const char *, const char *) const; private: PSVComponentMask getMaskForInput(uint32_t inputComponentIndex) const { if (!Table || !InputVectors || !OutputVectors) return PSVComponentMask(); return PSVComponentMask( Table + (PSVComputeMaskDwordsFromVectors(OutputVectors) * inputComponentIndex), OutputVectors); } }; struct PSVString { uint32_t Offset; PSVString() : Offset(0) {} PSVString(uint32_t offset) : Offset(offset) {} const char *Get(const PSVStringTable &table) const { return table.Get(Offset); } }; struct PSVSemanticIndexTable { const uint32_t *Table; uint32_t Entries; PSVSemanticIndexTable() : Table(nullptr), Entries(0) {} PSVSemanticIndexTable(const uint32_t *table, uint32_t entries) : Table(table), Entries(entries) {} const uint32_t *Get(uint32_t offset) const { assert(offset < Entries && Table); return Table + offset; } }; struct PSVSemanticIndexes { uint32_t Offset; PSVSemanticIndexes() : Offset(0) {} PSVSemanticIndexes(uint32_t offset) : Offset(offset) {} const uint32_t *Get(const PSVSemanticIndexTable &table) const { return table.Get(Offset); } }; enum class PSVSemanticKind : uint8_t // DXIL::SemanticKind { Arbitrary, VertexID, InstanceID, Position, RenderTargetArrayIndex, ViewPortArrayIndex, ClipDistance, CullDistance, OutputControlPointID, DomainLocation, PrimitiveID, GSInstanceID, SampleIndex, IsFrontFace, Coverage, InnerCoverage, Target, Depth, DepthLessEqual, DepthGreaterEqual, StencilRef, DispatchThreadID, GroupID, GroupIndex, GroupThreadID, TessFactor, InsideTessFactor, ViewID, Barycentrics, ShadingRate, CullPrimitive, Invalid, }; struct PSVSignatureElement0 { uint32_t SemanticName; // Offset into StringTable uint32_t SemanticIndexes; // Offset into PSVSemanticIndexTable, count == Rows uint8_t Rows; // Number of rows this element occupies uint8_t StartRow; // Starting row of packing location if allocated uint8_t ColsAndStart; // 0:4 = Cols, 4:6 = StartCol, 6:7 == Allocated uint8_t SemanticKind; // PSVSemanticKind uint8_t ComponentType; // DxilProgramSigCompType uint8_t InterpolationMode; // DXIL::InterpolationMode or // D3D10_SB_INTERPOLATION_MODE uint8_t DynamicMaskAndStream; // 0:4 = DynamicIndexMask, 4:6 = OutputStream (0-3) uint8_t Reserved; }; // Provides convenient access to packed PSVSignatureElementN structure class PSVSignatureElement { private: const PSVStringTable &m_StringTable; const PSVSemanticIndexTable &m_SemanticIndexTable; const PSVSignatureElement0 *m_pElement0; public: PSVSignatureElement(const PSVStringTable &stringTable, const PSVSemanticIndexTable &semanticIndexTable, const PSVSignatureElement0 *pElement0) : m_StringTable(stringTable), m_SemanticIndexTable(semanticIndexTable), m_pElement0(pElement0) {} const char *GetSemanticName() const { return !m_pElement0 ? "" : m_StringTable.Get(m_pElement0->SemanticName); } const uint32_t *GetSemanticIndexes() const { return !m_pElement0 ? nullptr : m_SemanticIndexTable.Get(m_pElement0->SemanticIndexes); } uint32_t GetRows() const { return !m_pElement0 ? 0 : ((uint32_t)m_pElement0->Rows); } uint32_t GetCols() const { return !m_pElement0 ? 0 : ((uint32_t)m_pElement0->ColsAndStart & 0xF); } bool IsAllocated() const { return !m_pElement0 ? false : !!(m_pElement0->ColsAndStart & 0x40); } int32_t GetStartRow() const { return !m_pElement0 ? 0 : !IsAllocated() ? -1 : (int32_t)m_pElement0->StartRow; } int32_t GetStartCol() const { return !m_pElement0 ? 0 : !IsAllocated() ? -1 : (int32_t)((m_pElement0->ColsAndStart >> 4) & 0x3); } PSVSemanticKind GetSemanticKind() const { return !m_pElement0 ? (PSVSemanticKind)0 : (PSVSemanticKind)m_pElement0->SemanticKind; } uint32_t GetComponentType() const { return !m_pElement0 ? 0 : (uint32_t)m_pElement0->ComponentType; } uint32_t GetInterpolationMode() const { return !m_pElement0 ? 0 : (uint32_t)m_pElement0->InterpolationMode; } uint32_t GetOutputStream() const { return !m_pElement0 ? 0 : (uint32_t)(m_pElement0->DynamicMaskAndStream >> 4) & 0x3; } uint32_t GetDynamicIndexMask() const { return !m_pElement0 ? 0 : (uint32_t)m_pElement0->DynamicMaskAndStream & 0xF; } void Print(llvm::raw_ostream &O) const; }; #define MAX_PSV_VERSION 3 struct PSVInitInfo { PSVInitInfo(uint32_t psvVersion) : PSVVersion(psvVersion) {} uint32_t PSVVersion = 0; uint32_t ResourceCount = 0; PSVShaderKind ShaderStage = PSVShaderKind::Invalid; PSVStringTable StringTable; PSVSemanticIndexTable SemanticIndexTable; uint8_t UsesViewID = 0; uint8_t SigInputElements = 0; uint8_t SigOutputElements = 0; uint8_t SigPatchConstOrPrimElements = 0; uint8_t SigInputVectors = 0; uint8_t SigPatchConstOrPrimVectors = 0; uint8_t SigOutputVectors[PSV_GS_MAX_STREAMS] = {0, 0, 0, 0}; static_assert(MAX_PSV_VERSION == 3, "otherwise this needs updating."); uint32_t RuntimeInfoSize() const { switch (PSVVersion) { case 0: return sizeof(PSVRuntimeInfo0); case 1: return sizeof(PSVRuntimeInfo1); case 2: return sizeof(PSVRuntimeInfo2); default: break; } return sizeof(PSVRuntimeInfo3); } uint32_t ResourceBindInfoSize() const { if (PSVVersion < 2) return sizeof(PSVResourceBindInfo0); return sizeof(PSVResourceBindInfo1); } uint32_t SignatureElementSize() const { return sizeof(PSVSignatureElement0); } }; class DxilPipelineStateValidation { uint32_t m_uPSVRuntimeInfoSize = 0; PSVRuntimeInfo0 *m_pPSVRuntimeInfo0 = nullptr; PSVRuntimeInfo1 *m_pPSVRuntimeInfo1 = nullptr; PSVRuntimeInfo2 *m_pPSVRuntimeInfo2 = nullptr; PSVRuntimeInfo3 *m_pPSVRuntimeInfo3 = nullptr; uint32_t m_uResourceCount = 0; uint32_t m_uPSVResourceBindInfoSize = 0; void *m_pPSVResourceBindInfo = nullptr; PSVStringTable m_StringTable; PSVSemanticIndexTable m_SemanticIndexTable; uint32_t m_uPSVSignatureElementSize = 0; void *m_pSigInputElements = nullptr; void *m_pSigOutputElements = nullptr; void *m_pSigPatchConstOrPrimElements = nullptr; uint32_t *m_pViewIDOutputMask[PSV_GS_MAX_STREAMS] = {nullptr, nullptr, nullptr, nullptr}; uint32_t *m_pViewIDPCOrPrimOutputMask = nullptr; uint32_t *m_pInputToOutputTable[PSV_GS_MAX_STREAMS] = {nullptr, nullptr, nullptr, nullptr}; uint32_t *m_pInputToPCOutputTable = nullptr; uint32_t *m_pPCInputToOutputTable = nullptr; public: DxilPipelineStateValidation() {} enum class RWMode { Read, CalcSize, Write, }; class CheckedReaderWriter { private: char *Ptr; uint32_t Size; uint32_t Offset; RWMode Mode; public: CheckedReaderWriter(const void *ptr, uint32_t size, RWMode mode) : Ptr(reinterpret_cast<char *>(const_cast<void *>(ptr))), Size(mode == RWMode::CalcSize ? 0 : size), Offset(0), Mode(mode) {} uint32_t GetSize() { return Size; } RWMode GetMode() { return Mode; } // Return true if size fits in remaing buffer. bool CheckBounds(size_t size); // Increment Offset by size. Return false on error. bool IncrementPos(size_t size); // Cast and return true if it fits. template <typename _T> bool Cast(_T **ppPtr, size_t size); template <typename _T> bool Cast(_T **ppPtr); // Map* methods increment Offset. // Assign pointer, increment Offset, and return true if size fits. template <typename _T> bool MapPtr(_T **ppPtr, size_t size = 0); // Read value, increment Offset, and return true if value fits. template <typename _T> bool MapValue(_T *pValue, const _T init = {}); // Assign pointer, increment Offset, and return true if array fits. template <typename _T> bool MapArray(_T **ppPtr, size_t count, size_t eltSize); // template <> bool MapArray<void>(void **ppPtr, size_t count, size_t // eltSize); // Assign pointer, increment Offset, and return true if array fits. template <typename _T> bool MapArray(_T **ppPtr, size_t count = 1); void Clear(); }; // Assigned derived ptr to base if size large enough. template <typename _Base, typename _T> bool AssignDerived(_T **ppDerived, _Base *pBase, uint32_t size) { if ((size_t)size < sizeof(_T)) return false; // size not large enough for type *ppDerived = reinterpret_cast<_T *>(pBase); return true; } private: bool ReadOrWrite(const void *pBits, uint32_t *pSize, RWMode mode, const PSVInitInfo &initInfo = PSVInitInfo(MAX_PSV_VERSION)); public: bool InitFromPSV0(const void *pBits, uint32_t size) { return ReadOrWrite(pBits, &size, RWMode::Read); } // Initialize a new buffer // call with null pBuffer to get required size bool InitNew(uint32_t ResourceCount, void *pBuffer, uint32_t *pSize) { PSVInitInfo initInfo(0); initInfo.ResourceCount = ResourceCount; return InitNew(initInfo, pBuffer, pSize); } bool InitNew(const PSVInitInfo &initInfo, void *pBuffer, uint32_t *pSize) { RWMode Mode = nullptr != pBuffer ? RWMode::Write : RWMode::CalcSize; return ReadOrWrite(pBuffer, pSize, Mode, initInfo); } PSVRuntimeInfo0 *GetPSVRuntimeInfo0() const { return m_pPSVRuntimeInfo0; } PSVRuntimeInfo1 *GetPSVRuntimeInfo1() const { return m_pPSVRuntimeInfo1; } PSVRuntimeInfo2 *GetPSVRuntimeInfo2() const { return m_pPSVRuntimeInfo2; } PSVRuntimeInfo3 *GetPSVRuntimeInfo3() const { return m_pPSVRuntimeInfo3; } uint32_t GetBindCount() const { return m_uResourceCount; } template <typename _T> _T *GetRecord(void *pRecords, uint32_t recordSize, uint32_t numRecords, uint32_t index) const { if (pRecords && index < numRecords && sizeof(_T) <= recordSize) { assert((size_t)index * (size_t)recordSize <= UINT_MAX); return reinterpret_cast<_T *>(reinterpret_cast<uint8_t *>(pRecords) + (index * recordSize)); } return nullptr; } PSVResourceBindInfo0 *GetPSVResourceBindInfo0(uint32_t index) const { return GetRecord<PSVResourceBindInfo0>(m_pPSVResourceBindInfo, m_uPSVResourceBindInfoSize, m_uResourceCount, index); } PSVResourceBindInfo1 *GetPSVResourceBindInfo1(uint32_t index) const { return GetRecord<PSVResourceBindInfo1>(m_pPSVResourceBindInfo, m_uPSVResourceBindInfoSize, m_uResourceCount, index); } const PSVStringTable &GetStringTable() const { return m_StringTable; } const PSVSemanticIndexTable &GetSemanticIndexTable() const { return m_SemanticIndexTable; } // Signature element access uint32_t GetSigInputElements() const { if (m_pPSVRuntimeInfo1) return m_pPSVRuntimeInfo1->SigInputElements; return 0; } uint32_t GetSigOutputElements() const { if (m_pPSVRuntimeInfo1) return m_pPSVRuntimeInfo1->SigOutputElements; return 0; } uint32_t GetSigPatchConstOrPrimElements() const { if (m_pPSVRuntimeInfo1) return m_pPSVRuntimeInfo1->SigPatchConstOrPrimElements; return 0; } PSVSignatureElement0 *GetInputElement0(uint32_t index) const { return GetRecord<PSVSignatureElement0>( m_pSigInputElements, m_uPSVSignatureElementSize, m_pPSVRuntimeInfo1 ? m_pPSVRuntimeInfo1->SigInputElements : 0, index); } PSVSignatureElement0 *GetOutputElement0(uint32_t index) const { return GetRecord<PSVSignatureElement0>( m_pSigOutputElements, m_uPSVSignatureElementSize, m_pPSVRuntimeInfo1 ? m_pPSVRuntimeInfo1->SigOutputElements : 0, index); } PSVSignatureElement0 *GetPatchConstOrPrimElement0(uint32_t index) const { return GetRecord<PSVSignatureElement0>( m_pSigPatchConstOrPrimElements, m_uPSVSignatureElementSize, m_pPSVRuntimeInfo1 ? m_pPSVRuntimeInfo1->SigPatchConstOrPrimElements : 0, index); } // More convenient wrapper: PSVSignatureElement GetSignatureElement(PSVSignatureElement0 *pElement0) const { return PSVSignatureElement(m_StringTable, m_SemanticIndexTable, pElement0); } PSVShaderKind GetShaderKind() const { if (m_pPSVRuntimeInfo1 && m_pPSVRuntimeInfo1->ShaderStage < (uint8_t)PSVShaderKind::Invalid) return (PSVShaderKind)m_pPSVRuntimeInfo1->ShaderStage; return PSVShaderKind::Invalid; } bool IsVS() const { return GetShaderKind() == PSVShaderKind::Vertex; } bool IsHS() const { return GetShaderKind() == PSVShaderKind::Hull; } bool IsDS() const { return GetShaderKind() == PSVShaderKind::Domain; } bool IsGS() const { return GetShaderKind() == PSVShaderKind::Geometry; } bool IsPS() const { return GetShaderKind() == PSVShaderKind::Pixel; } bool IsCS() const { return GetShaderKind() == PSVShaderKind::Compute; } bool IsMS() const { return GetShaderKind() == PSVShaderKind::Mesh; } bool IsAS() const { return GetShaderKind() == PSVShaderKind::Amplification; } // ViewID dependencies PSVComponentMask GetViewIDOutputMask(unsigned streamIndex = 0) const { if (streamIndex >= PSV_GS_MAX_STREAMS || !m_pViewIDOutputMask[streamIndex] || !m_pPSVRuntimeInfo1 || !m_pPSVRuntimeInfo1->SigOutputVectors[streamIndex]) return PSVComponentMask(); return PSVComponentMask(m_pViewIDOutputMask[streamIndex], m_pPSVRuntimeInfo1->SigOutputVectors[streamIndex]); } PSVComponentMask GetViewIDPCOutputMask() const { if ((!IsHS() && !IsMS()) || !m_pViewIDPCOrPrimOutputMask || !m_pPSVRuntimeInfo1 || !m_pPSVRuntimeInfo1->SigPatchConstOrPrimVectors) return PSVComponentMask(); return PSVComponentMask(m_pViewIDPCOrPrimOutputMask, m_pPSVRuntimeInfo1->SigPatchConstOrPrimVectors); } // Input to Output dependencies PSVDependencyTable GetInputToOutputTable(unsigned streamIndex = 0) const { if (streamIndex < PSV_GS_MAX_STREAMS && m_pInputToOutputTable[streamIndex] && m_pPSVRuntimeInfo1) { return PSVDependencyTable( m_pInputToOutputTable[streamIndex], m_pPSVRuntimeInfo1->SigInputVectors, m_pPSVRuntimeInfo1->SigOutputVectors[streamIndex]); } return PSVDependencyTable(); } PSVDependencyTable GetInputToPCOutputTable() const { if (IsHS() && m_pInputToPCOutputTable && m_pPSVRuntimeInfo1) { return PSVDependencyTable(m_pInputToPCOutputTable, m_pPSVRuntimeInfo1->SigInputVectors, m_pPSVRuntimeInfo1->SigPatchConstOrPrimVectors); } return PSVDependencyTable(); } PSVDependencyTable GetPCInputToOutputTable() const { if (IsDS() && m_pPCInputToOutputTable && m_pPSVRuntimeInfo1) { return PSVDependencyTable(m_pPCInputToOutputTable, m_pPSVRuntimeInfo1->SigPatchConstOrPrimVectors, m_pPSVRuntimeInfo1->SigOutputVectors[0]); } return PSVDependencyTable(); } bool GetNumThreads(uint32_t *pNumThreadsX, uint32_t *pNumThreadsY, uint32_t *pNumThreadsZ) { if (m_pPSVRuntimeInfo2) { if (pNumThreadsX) *pNumThreadsX = m_pPSVRuntimeInfo2->NumThreadsX; if (pNumThreadsY) *pNumThreadsY = m_pPSVRuntimeInfo2->NumThreadsY; if (pNumThreadsZ) *pNumThreadsZ = m_pPSVRuntimeInfo2->NumThreadsZ; return true; } return false; } const char *GetEntryFunctionName() const { return m_pPSVRuntimeInfo3 ? m_StringTable.Get(m_pPSVRuntimeInfo3->EntryFunctionName) : ""; } void PrintPSVRuntimeInfo(llvm::raw_ostream &O, uint8_t ShaderKind, const char *Comment) const; void Print(llvm::raw_ostream &O, uint8_t ShaderKind) const; }; // Return true if size fits in remaing buffer. inline bool DxilPipelineStateValidation::CheckedReaderWriter::CheckBounds(size_t size) { if (Mode != RWMode::CalcSize) { PSV_RETB(size <= UINT_MAX); PSV_RETB(Offset <= Size); return (uint32_t)size <= Size - Offset; } return true; } // Increment Offset by size. Return false on error. inline bool DxilPipelineStateValidation::CheckedReaderWriter::IncrementPos(size_t size) { PSV_RETB(size <= UINT_MAX); uint32_t uSize = (uint32_t)size; if (Mode == RWMode::CalcSize) { PSV_RETB(uSize <= Size + uSize); Size += uSize; } PSV_RETB(CheckBounds(size)); Offset += uSize; return true; } // Cast and return true if it fits. template <typename _T> inline bool DxilPipelineStateValidation::CheckedReaderWriter::Cast(_T **ppPtr, size_t size) { PSV_RETB(CheckBounds(size)); if (Mode != RWMode::CalcSize) *ppPtr = reinterpret_cast<_T *>(Ptr + Offset); return true; } template <typename _T> inline bool DxilPipelineStateValidation::CheckedReaderWriter::Cast(_T **ppPtr) { return Cast(ppPtr, sizeof(_T)); } // Map* methods increment Offset. // Assign pointer, increment Offset, and return true if size fits. template <typename _T> inline bool DxilPipelineStateValidation::CheckedReaderWriter::MapPtr(_T **ppPtr, size_t size) { PSV_RETB(Cast(ppPtr, size)); PSV_RETB(IncrementPos(size)); return true; } // Read value, increment Offset, and return true if value fits. template <typename _T> inline bool DxilPipelineStateValidation::CheckedReaderWriter::MapValue(_T *pValue, const _T init) { _T *pPtr = nullptr; PSV_RETB(MapPtr(&pPtr, sizeof(_T))); switch (Mode) { case RWMode::Read: *pValue = *pPtr; break; case RWMode::CalcSize: *pValue = init; break; case RWMode::Write: *pPtr = *pValue = init; break; } return true; } // Assign pointer, increment Offset, and return true if array fits. template <typename _T> inline bool DxilPipelineStateValidation::CheckedReaderWriter::MapArray( _T **ppPtr, size_t count, size_t eltSize) { PSV_RETB(count <= UINT_MAX && eltSize <= UINT_MAX && eltSize >= sizeof(_T)); return count ? MapPtr(ppPtr, eltSize * count) : true; } // template <> bool MapArray<void>(void **ppPtr, size_t count, size_t eltSize); template <> inline bool DxilPipelineStateValidation::CheckedReaderWriter::MapArray<void>( void **ppPtr, size_t count, size_t eltSize) { PSV_RETB(count <= UINT_MAX && eltSize <= UINT_MAX && eltSize > 0); return count ? MapPtr(ppPtr, eltSize * count) : true; } // Assign pointer, increment Offset, and return true if array fits. template <typename _T> inline bool DxilPipelineStateValidation::CheckedReaderWriter::MapArray(_T **ppPtr, size_t count) { return count ? MapArray(ppPtr, count, sizeof(_T)) : true; } inline void DxilPipelineStateValidation::CheckedReaderWriter::Clear() { if (Mode == RWMode::Write) { memset(Ptr, 0, Size); } } // PSV0 blob part looks like: // uint32_t PSVRuntimeInfo_size // { PSVRuntimeInfoN structure } // uint32_t ResourceCount // If ResourceCount > 0: // uint32_t PSVResourceBindInfo_size // { PSVResourceBindInfoN structure } * ResourceCount // If PSVRuntimeInfo1: // uint32_t StringTableSize (dword aligned) // If StringTableSize: // { StringTableSize bytes, null terminated } // uint32_t SemanticIndexTableEntries (number of dwords) // If SemanticIndexTableEntries: // { semantic index } * SemanticIndexTableEntries // If SigInputElements || SigOutputElements || SigPatchConstOrPrimElements: // uint32_t PSVSignatureElement_size // { PSVSignatureElementN structure } * SigInputElements // { PSVSignatureElementN structure } * SigOutputElements // { PSVSignatureElementN structure } * SigPatchConstOrPrimElements // If (UsesViewID): // For (i : each stream index 0-3): // If (SigOutputVectors[i] non-zero): // { uint32_t * PSVComputeMaskDwordsFromVectors(SigOutputVectors[i]) } // - Outputs affected by ViewID as a bitmask // If (HS and SigPatchConstOrPrimVectors non-zero): // { uint32_t * // PSVComputeMaskDwordsFromVectors(SigPatchConstOrPrimVectors) } // - PCOutputs affected by ViewID as a bitmask // For (i : each stream index 0-3): // If (SigInputVectors and SigOutputVectors[i] non-zero): // { uint32_t * PSVComputeInputOutputTableDwords(SigInputVectors, // SigOutputVectors[i]) } // - Outputs affected by inputs as a table of bitmasks // If (HS and SigPatchConstOrPrimVectors and SigInputVectors non-zero): // { uint32_t * PSVComputeInputOutputTableDwords(SigInputVectors, // SigPatchConstOrPrimVectors) } // - Patch constant outputs affected by inputs as a table of bitmasks // If (DS and SigOutputVectors[0] and SigPatchConstOrPrimVectors non-zero): // { uint32_t * // PSVComputeInputOutputTableDwords(SigPatchConstOrPrimVectors, // SigOutputVectors[0]) } // - Outputs affected by patch constant inputs as a table of bitmasks // returns true if no errors occurred. inline bool DxilPipelineStateValidation::ReadOrWrite(const void *pBits, uint32_t *pSize, RWMode mode, const PSVInitInfo &initInfo) { PSV_RETB(pSize != nullptr); PSV_RETB(pBits != nullptr || mode == RWMode::CalcSize); PSV_RETB(initInfo.PSVVersion <= MAX_PSV_VERSION); CheckedReaderWriter rw(pBits, *pSize, mode); rw.Clear(); PSV_RETB(rw.MapValue(&m_uPSVRuntimeInfoSize, initInfo.RuntimeInfoSize())); PSV_RETB(rw.MapArray(&m_pPSVRuntimeInfo0, 1, m_uPSVRuntimeInfoSize)); AssignDerived(&m_pPSVRuntimeInfo1, m_pPSVRuntimeInfo0, m_uPSVRuntimeInfoSize); // failure ok AssignDerived(&m_pPSVRuntimeInfo2, m_pPSVRuntimeInfo0, m_uPSVRuntimeInfoSize); // failure ok AssignDerived(&m_pPSVRuntimeInfo3, m_pPSVRuntimeInfo0, m_uPSVRuntimeInfoSize); // failure ok // In RWMode::CalcSize, use temp runtime info to hold needed values from // initInfo PSVRuntimeInfo1 tempRuntimeInfo = {}; if (mode == RWMode::CalcSize && initInfo.PSVVersion > 0) { m_pPSVRuntimeInfo1 = &tempRuntimeInfo; } PSV_RETB(rw.MapValue(&m_uResourceCount, initInfo.ResourceCount)); if (m_uResourceCount > 0) { PSV_RETB(rw.MapValue(&m_uPSVResourceBindInfoSize, initInfo.ResourceBindInfoSize())); PSV_RETB(sizeof(PSVResourceBindInfo0) <= m_uPSVResourceBindInfoSize); PSV_RETB(rw.MapArray(&m_pPSVResourceBindInfo, m_uResourceCount, m_uPSVResourceBindInfoSize)); } if (m_pPSVRuntimeInfo1) { if (mode != RWMode::Read) { m_pPSVRuntimeInfo1->ShaderStage = (uint8_t)initInfo.ShaderStage; m_pPSVRuntimeInfo1->SigInputElements = initInfo.SigInputElements; m_pPSVRuntimeInfo1->SigOutputElements = initInfo.SigOutputElements; m_pPSVRuntimeInfo1->SigPatchConstOrPrimElements = initInfo.SigPatchConstOrPrimElements; m_pPSVRuntimeInfo1->UsesViewID = initInfo.UsesViewID; for (unsigned i = 0; i < PSV_GS_MAX_STREAMS; i++) { m_pPSVRuntimeInfo1->SigOutputVectors[i] = initInfo.SigOutputVectors[i]; } if (IsHS() || IsDS() || IsMS()) { m_pPSVRuntimeInfo1->SigPatchConstOrPrimVectors = initInfo.SigPatchConstOrPrimVectors; } m_pPSVRuntimeInfo1->SigInputVectors = initInfo.SigInputVectors; } PSV_RETB( rw.MapValue(&m_StringTable.Size, PSVALIGN4(initInfo.StringTable.Size))); PSV_RETB(PSVALIGN4(m_StringTable.Size) == m_StringTable.Size); if (m_StringTable.Size) { PSV_RETB(rw.MapArray(&m_StringTable.Table, m_StringTable.Size)); if (mode == RWMode::Write) { memcpy(const_cast<char *>(m_StringTable.Table), initInfo.StringTable.Table, initInfo.StringTable.Size); } } PSV_RETB(rw.MapValue(&m_SemanticIndexTable.Entries, initInfo.SemanticIndexTable.Entries)); if (m_SemanticIndexTable.Entries) { PSV_RETB(rw.MapArray(&m_SemanticIndexTable.Table, m_SemanticIndexTable.Entries)); if (mode == RWMode::Write) { memcpy(const_cast<uint32_t *>(m_SemanticIndexTable.Table), initInfo.SemanticIndexTable.Table, sizeof(uint32_t) * initInfo.SemanticIndexTable.Entries); } } // Dxil Signature Elements if (m_pPSVRuntimeInfo1->SigInputElements || m_pPSVRuntimeInfo1->SigOutputElements || m_pPSVRuntimeInfo1->SigPatchConstOrPrimElements) { PSV_RETB(rw.MapValue(&m_uPSVSignatureElementSize, initInfo.SignatureElementSize())); PSV_RETB(sizeof(PSVSignatureElement0) <= m_uPSVSignatureElementSize); if (m_pPSVRuntimeInfo1->SigInputElements) { PSV_RETB(rw.MapArray(&m_pSigInputElements, m_pPSVRuntimeInfo1->SigInputElements, m_uPSVSignatureElementSize)); } if (m_pPSVRuntimeInfo1->SigOutputElements) { PSV_RETB(rw.MapArray(&m_pSigOutputElements, m_pPSVRuntimeInfo1->SigOutputElements, m_uPSVSignatureElementSize)); } if (m_pPSVRuntimeInfo1->SigPatchConstOrPrimElements) { PSV_RETB(rw.MapArray(&m_pSigPatchConstOrPrimElements, m_pPSVRuntimeInfo1->SigPatchConstOrPrimElements, m_uPSVSignatureElementSize)); } } // ViewID dependencies if (m_pPSVRuntimeInfo1->UsesViewID) { for (unsigned i = 0; i < PSV_GS_MAX_STREAMS; i++) { if (m_pPSVRuntimeInfo1->SigOutputVectors[i]) { PSV_RETB(rw.MapArray(&m_pViewIDOutputMask[i], PSVComputeMaskDwordsFromVectors( m_pPSVRuntimeInfo1->SigOutputVectors[i]))); } if (!IsGS()) break; } if ((IsHS() || IsMS()) && m_pPSVRuntimeInfo1->SigPatchConstOrPrimVectors) { PSV_RETB( rw.MapArray(&m_pViewIDPCOrPrimOutputMask, PSVComputeMaskDwordsFromVectors( m_pPSVRuntimeInfo1->SigPatchConstOrPrimVectors))); } } // Input to Output dependencies for (unsigned i = 0; i < PSV_GS_MAX_STREAMS; i++) { if (!IsMS() && m_pPSVRuntimeInfo1->SigOutputVectors[i] > 0 && m_pPSVRuntimeInfo1->SigInputVectors > 0) { PSV_RETB(rw.MapArray(&m_pInputToOutputTable[i], PSVComputeInputOutputTableDwords( m_pPSVRuntimeInfo1->SigInputVectors, m_pPSVRuntimeInfo1->SigOutputVectors[i]))); } if (!IsGS()) break; } if (IsHS() && m_pPSVRuntimeInfo1->SigPatchConstOrPrimVectors > 0 && m_pPSVRuntimeInfo1->SigInputVectors > 0) { PSV_RETB( rw.MapArray(&m_pInputToPCOutputTable, PSVComputeInputOutputTableDwords( m_pPSVRuntimeInfo1->SigInputVectors, m_pPSVRuntimeInfo1->SigPatchConstOrPrimVectors))); } if (IsDS() && m_pPSVRuntimeInfo1->SigOutputVectors[0] > 0 && m_pPSVRuntimeInfo1->SigPatchConstOrPrimVectors > 0) { PSV_RETB(rw.MapArray(&m_pPCInputToOutputTable, PSVComputeInputOutputTableDwords( m_pPSVRuntimeInfo1->SigPatchConstOrPrimVectors, m_pPSVRuntimeInfo1->SigOutputVectors[0]))); } } if (mode == RWMode::CalcSize) { *pSize = rw.GetSize(); m_pPSVRuntimeInfo1 = nullptr; // clear ptr to tempRuntimeInfo } return true; } namespace hlsl { class DxilResourceBase; class DxilSignatureElement; class DxilModule; class ViewIDValidator { public: enum class Result { Success = 0, SuccessWithViewIDDependentTessFactor, InsufficientInputSpace, InsufficientOutputSpace, InsufficientPCSpace, MismatchedSignatures, MismatchedPCSignatures, InvalidUsage, InvalidPSVVersion, InvalidPSV, }; virtual ~ViewIDValidator() {} virtual Result ValidateStage(const DxilPipelineStateValidation &PSV, bool bFinalStage, bool bExpandInputOnly, unsigned &mismatchElementId) = 0; }; ViewIDValidator *NewViewIDValidator(unsigned viewIDCount, unsigned gsRastStreamIndex); void InitPSVResourceBinding(PSVResourceBindInfo0 *, PSVResourceBindInfo1 *, DxilResourceBase *); // Setup PSVSignatureElement0 with DxilSignatureElement. // Note that the SemanticName and SemanticIndexes are not done. void InitPSVSignatureElement(PSVSignatureElement0 &E, const DxilSignatureElement &SE, bool i1ToUnknownCompat); // Setup PSVRuntimeInfo* with DxilModule. // Note that the EntryFunctionName is not done. void InitPSVRuntimeInfo(PSVRuntimeInfo0 *pInfo, PSVRuntimeInfo1 *pInfo1, PSVRuntimeInfo2 *pInfo2, PSVRuntimeInfo3 *pInfo3, const DxilModule &DM); } // namespace hlsl #undef PSV_RETB #endif // __DXIL_PIPELINE_STATE_VALIDATION__H__
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxrFallback/DxrFallbackCompiler.h
#pragma once #include <map> #include <memory> #include <string> #include <vector> namespace llvm { class CallInst; class Function; class Module; class Type; } // namespace llvm // Combines DXIL raytracing shaders together into a compute shader. // // The incoming module should contain the following functions if the // corresponding intrinsic are called by the specified shaders, if called: // Fallback_TraceRay() // Fallback_Ignore() // Fallback_AcceptHitAndEndSearch() // Fallback_ReportHit() // // Fallback_TraceRay() will be called with the original arguments, substituting // the offset of the payload on the stack for the actual payload. // Fallback_TraceRay() will also be used to replace calls to TraceRayTest(). // // ReportHit() returns a boolean. But to handle the abort of the intersection // shader when AcceptHitAndEndSearch() is called we need a third return value. // Fallback_ReportHit() should return an integer < 0 for end search, 0 for // ignore, and > 0 for accept. // // The module should also contain a single call to Fallback_Scheduler() in the // entry shader for the raytracing compute shader. // // resizeStack() needs to be called after inlining everything in the compute // shader. // // Currently the main scheduling loop and the implementation for intrinsic // functions come from an internal runtime module. class DxrFallbackCompiler { public: typedef std::map<int, std::string> IntToFuncNameMap; // If findCalledShaders is true, then the list of shaderNames is expanded to // include shader functions (functions with attribute "exp-shader") that are // called by functions in shaderNames. Shader entry state IDs are still // returned only for those originally in shaderNames. findCalledShaders used // for testing. DxrFallbackCompiler(llvm::Module *mod, const std::vector<std::string> &shaderNames, unsigned maxAttributeSize, unsigned stackSizeInBytes, bool findCalledShaders = false); // 0 - no debug output // 1 - dump initial combined module, compiled module, and final linked module // 2 - dump intermediate stages of SFT to console // 3 - dump intermediate stages of SFT to file void setDebugOutputLevel(int val); // Returns the entry state id for each of shaderNames. The transformations // are performed in place on the module. void compile(std::vector<int> &shaderEntryStateIds, std::vector<unsigned int> &shaderStackSizes, IntToFuncNameMap *pCachedMap); void link(std::vector<int> &shaderEntryStateIds, std::vector<unsigned int> &shaderStackSizes, IntToFuncNameMap *pCachedMap); // TODO: Ideally we would run this after inlining everything at the end of // compile. Until we figure out to do this, we will call the function after // the final link. static void resizeStack(llvm::Function *F, unsigned stackSizeInBytes); private: typedef std::map<int, llvm::Function *> IntToFuncMap; typedef std::map<std::string, llvm::Function *> StringToFuncMap; llvm::Module *m_module = nullptr; const std::vector<std::string> &m_entryShaderNames; unsigned m_stackSizeInBytes = 0; unsigned m_maxAttributeSize = 0; bool m_findCalledShaders = false; int m_debugOutputLevel = 0; StringToFuncMap m_shaderMap; void initShaderMap(std::vector<std::string> &shaderNames); void linkRuntime(); void lowerAnyHitControlFlowFuncs(); void lowerReportHit(); void lowerTraceRay(llvm::Type *runtimeDataArgTy); void createStateFunctions(IntToFuncMap &stateFunctionMap, std::vector<int> &shaderEntryStateIds, std::vector<unsigned int> &shaderStackSizes, int baseStateId, const std::vector<std::string> &shaderNames, llvm::Type *runtimeDataArgTy); void createLaunchParams(llvm::Function *func); void createStack(llvm::Function *func); void createStateDispatch(llvm::Function *func, const IntToFuncMap &stateFunctionMap, llvm::Type *runtimeDataArgTy); void lowerIntrinsics(); llvm::Type *getRuntimeDataArgType(); llvm::Function *createDispatchFunction(const IntToFuncMap &stateFunctionMap, llvm::Type *runtimeDataArgTy); // These functions return calls only in shaders in m_shaderMap. std::vector<llvm::CallInst *> getCallsInShadersToFunction(const std::string &funcName); std::vector<llvm::CallInst *> getCallsInShadersToFunctionWithPrefix(const std::string &funcNamePrefix); };
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilHash/DxilHash.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilHash.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // // // DXBC/DXIL container hashing functions // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #define DXIL_CONTAINER_HASH_SIZE 16 // Prototype for hash computing function // pOutHash must always return a DXIL_CONTAINER_HASH_SIZE byte hash result. typedef void HASH_FUNCTION_PROTO(const BYTE *pData, UINT32 byteCount, BYTE *pOutHash); // ************************************************************************************** // **** DO NOT USE THESE ROUTINES TO PROVIDE FUNCTIONALITY THAT NEEDS TO BE // SECURE!!! *** // ************************************************************************************** // Derived from: RSA Data Security, Inc. M // D // 5 Message-Digest Algorithm // Computes a 128-bit hash of pData (size byteCount), returning 16 BYTE output void ComputeHashRetail(const BYTE *pData, UINT32 byteCount, BYTE *pOutHash); void ComputeHashDebug(const BYTE *pData, UINT32 byteCount, BYTE *pOutHash); // ************************************************************************************** // **** DO NOT USE THESE ROUTINES TO PROVIDE FUNCTIONALITY THAT NEEDS TO BE // SECURE!!! *** // **************************************************************************************
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/Test/WEXAdapter.h
#ifndef LLVM_CLANG_UNITTESTS_WEX_ADAPTER_H #define LLVM_CLANG_UNITTESTS_WEX_ADAPTER_H #ifndef _WIN32 #include <unistd.h> #include <wchar.h> #include "dxc/Support/WinFunctions.h" #include "dxc/WinAdapter.h" #include "gtest/gtest.h" #define MAX_PATH 260 // Concatinate two macro fragments #define CONCAT2(a, b) a##b #define CONCAT1(a, b) CONCAT2(a, b) #define CONCAT(a, b) CONCAT1(a, b) // Determine how many arguments are passed to NARG() up to 3 #define ARG_CT(_1, _2, _3, N, ...) N #define NARG(...) ARG_CT(__VA_ARGS__, 3, 2, 1, 0) // Call the appropriate arity macro based on number of arguments #define MACRO_N_(PREFIX, N, ...) CONCAT(PREFIX, N)(__VA_ARGS__) #define MACRO_N(PREFIX, ...) MACRO_N_(PREFIX, NARG(__VA_ARGS__), __VA_ARGS__) // Macros to convert TAEF macros to gtest equivalents // Single and double argument versions for optional failure messages #define VERIFY_SUCCEEDED_1(expr) EXPECT_TRUE(SUCCEEDED(expr)) #define VERIFY_SUCCEEDED_2(expr, msg) EXPECT_TRUE(SUCCEEDED(expr)) << msg #define VERIFY_SUCCEEDED(...) MACRO_N(VERIFY_SUCCEEDED_, __VA_ARGS__) #define VERIFY_FAILED_1(expr) EXPECT_FALSE(SUCCEEDED(expr)) #define VERIFY_FAILED_2(expr, msg) EXPECT_FALSE(SUCCEEDED(expr)) << msg #define VERIFY_FAILED(...) MACRO_N(VERIFY_FAILED_, __VA_ARGS__) #define VERIFY_ARE_EQUAL_2(A, B) EXPECT_EQ(A, B) #define VERIFY_ARE_EQUAL_3(A, B, msg) EXPECT_EQ(A, B) << msg #define VERIFY_ARE_EQUAL(...) MACRO_N(VERIFY_ARE_EQUAL_, __VA_ARGS__) #define VERIFY_ARE_NOT_EQUAL_2(A, B) EXPECT_NE(A, B) #define VERIFY_ARE_NOT_EQUAL_3(A, B, msg) EXPECT_NE(A, B) << msg #define VERIFY_ARE_NOT_EQUAL(...) MACRO_N(VERIFY_ARE_NOT_EQUAL_, __VA_ARGS__) #define VERIFY_IS_TRUE_1(expr) EXPECT_TRUE(expr) #define VERIFY_IS_TRUE_2(expr, msg) EXPECT_TRUE(expr) << msg #define VERIFY_IS_TRUE(...) MACRO_N(VERIFY_IS_TRUE_, __VA_ARGS__) #define VERIFY_IS_FALSE_1(expr) EXPECT_FALSE(expr) #define VERIFY_IS_FALSE_2(expr, msg) EXPECT_FALSE(expr) << msg #define VERIFY_IS_FALSE(...) MACRO_N(VERIFY_IS_FALSE_, __VA_ARGS__) #define VERIFY_IS_NULL_1(expr) EXPECT_EQ(nullptr, (expr)) #define VERIFY_IS_NULL_2(expr, msg) EXPECT_EQ(nullptr, (expr)) << msg #define VERIFY_IS_NULL(...) MACRO_N(VERIFY_IS_NULL_, __VA_ARGS__) #define VERIFY_IS_NOT_NULL_1(expr) EXPECT_NE(nullptr, (expr)) #define VERIFY_IS_NOT_NULL_2(expr, msg) EXPECT_NE(nullptr, (expr)) << msg #define VERIFY_IS_NOT_NULL(...) MACRO_N(VERIFY_IS_NOT_NULL_, __VA_ARGS__) #define VERIFY_IS_GREATER_THAN_OR_EQUAL(greater, less) EXPECT_GE(greater, less) #define VERIFY_IS_GREATER_THAN_2(greater, less) EXPECT_GT(greater, less) #define VERIFY_IS_GREATER_THAN_3(greater, less, msg) \ EXPECT_GT(greater, less) << msg #define VERIFY_IS_GREATER_THAN(...) \ MACRO_N(VERIFY_IS_GREATER_THAN_, __VA_ARGS__) #define VERIFY_IS_LESS_THAN_2(greater, less) EXPECT_LT(greater, less) #define VERIFY_IS_LESS_THAN_3(greater, less, msg) \ EXPECT_LT(greater, less) << msg #define VERIFY_IS_LESS_THAN(...) MACRO_N(VERIFY_IS_LESS_THAN_, __VA_ARGS__) #define VERIFY_WIN32_BOOL_SUCCEEDED_1(expr) EXPECT_TRUE(expr) #define VERIFY_WIN32_BOOL_SUCCEEDED_2(expr, msg) EXPECT_TRUE(expr) << msg #define VERIFY_WIN32_BOOL_SUCCEEDED(...) \ MACRO_N(VERIFY_WIN32_BOOL_SUCCEEDED_, __VA_ARGS__) #define VERIFY_FAIL(...) ADD_FAILURE() << __VA_ARGS__ "" #define TEST_CLASS_SETUP(method) \ bool method(); \ virtual void SetUp() { EXPECT_TRUE(method()); } #define TEST_CLASS_CLEANUP(method) \ bool method(); \ virtual void TearDown() { EXPECT_TRUE(method()); } #define BEGIN_TEST_CLASS(test) #define TEST_CLASS_PROPERTY(str1, str2) #define TEST_METHOD_PROPERTY(str1, str2) #define END_TEST_CLASS() #define TEST_METHOD(method) #define BEGIN_TEST_METHOD(method) #define END_TEST_METHOD() // gtest lacks any module setup/cleanup. These functions are called by the // main() function before and after tests are run. This approximates the // behavior. bool moduleSetup(); bool moduleTeardown(); #define MODULE_SETUP(method) \ bool method(); \ bool moduleSetup() { return method(); } #define MODULE_CLEANUP(method) \ bool method(); \ bool moduleTeardown() { return method(); } // No need to expand env vars on Unix platforms, so convert the slashes instead. inline DWORD ExpandEnvironmentStringsW(LPCWSTR lpSrc, LPWSTR lpDst, DWORD nSize) { unsigned i; bool wasSlash = false; for (i = 0; i < nSize && *lpSrc; i++, lpSrc++) { if (*lpSrc == L'\\' || *lpSrc == L'/') { if (!wasSlash) *lpDst++ = L'/'; wasSlash = true; } else { *lpDst++ = *lpSrc; wasSlash = false; } } *lpDst = L'\0'; return i; } typedef struct _LIST_ENTRY { struct _LIST_ENTRY *Flink; struct _LIST_ENTRY *Blink; } LIST_ENTRY, *PLIST_ENTRY, PRLIST_ENTRY; // Minimal implementation of the WEX namespace functions and classes // To either stub out or approximate behavior namespace WEX { namespace Common { class String : public std::wstring { public: String() = default; String(const wchar_t *S) : std::wstring(S) {} size_t GetLength() { return length(); } bool IsEmpty() { return empty(); } int CompareNoCase(std::wstring str) const { return -1; assert(!"unimplemented"); } operator const wchar_t *() { return c_str(); } const wchar_t *GetBuffer() { return *this; } wchar_t *Format(const wchar_t *fmt, ...) { static wchar_t msg[512]; va_list args; va_start(args, fmt); vswprintf(msg, 512, fmt, args); va_end(args); return msg; } }; } // namespace Common namespace TestExecution { enum class VerifyOutputSettings { LogOnlyFailures }; class SetVerifyOutput { public: SetVerifyOutput(VerifyOutputSettings) {} }; class DisableVerifyExceptions { public: DisableVerifyExceptions() {} }; namespace RuntimeParameters { HRESULT TryGetValue(const wchar_t *param, Common::String &retStr); } // namespace RuntimeParameters } // namespace TestExecution namespace Logging { namespace Log { inline void StartGroup(const wchar_t *name) { wprintf(L"BEGIN TEST(S): <%ls>\n", name); } inline void EndGroup(const wchar_t *name) { wprintf(L"END TEST(S): <%ls>\n", name); } inline void Comment(const wchar_t *msg) { fputws(msg, stdout); fputwc(L'\n', stdout); } inline void Error(const wchar_t *msg) { fputws(msg, stderr); fputwc(L'\n', stderr); ADD_FAILURE(); } } // namespace Log } // namespace Logging } // namespace WEX #endif // _WIN32 #endif // LLVM_CLANG_UNITTESTS_WEX_ADAPTER_H
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/Test/HlslTestUtils.h
/////////////////////////////////////////////////////////////////////////////// // // // HlslTestUtils.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides utility functions for HLSL tests. // // // /////////////////////////////////////////////////////////////////////////////// // *** THIS FILE CANNOT TAKE ANY LLVM DEPENDENCIES *** // #include <algorithm> #include <atomic> #include <cmath> #include <fstream> #include <sstream> #include <string> #include <vector> #ifdef _WIN32 // Disable -Wignored-qualifiers for WexTestClass.h. // For const size_t GetSize() const; in TestData.h. #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wignored-qualifiers" #endif #include "WexTestClass.h" #ifdef __clang__ #pragma clang diagnostic pop #endif #include <dxgiformat.h> #else #include "WEXAdapter.h" #include "dxc/Support/Global.h" // DXASSERT_LOCALVAR #endif #include "dxc/DXIL/DxilConstants.h" // DenormMode #ifdef _HLK_CONF #define DEFAULT_TEST_DIR L"" #define DEFAULT_EXEC_TEST_DIR DEFAULT_TEST_DIR #else #include "dxc/Test/TestConfig.h" #endif using namespace std; #ifndef HLSLDATAFILEPARAM #define HLSLDATAFILEPARAM L"HlslDataDir" #endif #ifndef FILECHECKDUMPDIRPARAM #define FILECHECKDUMPDIRPARAM L"FileCheckDumpDir" #endif // If TAEF verify macros are available, use them to alias other legacy // comparison macros that don't have a direct translation. // // Other common replacements are as follows. // // EXPECT_EQ -> VERIFY_ARE_EQUAL // ASSERT_EQ -> VERIFY_ARE_EQUAL // // Note that whether verification throws or continues depends on // preprocessor settings. #ifdef VERIFY_ARE_EQUAL #ifndef EXPECT_STREQ #define EXPECT_STREQ(a, b) VERIFY_ARE_EQUAL(0, strcmp(a, b)) #endif #define EXPECT_STREQW(a, b) VERIFY_ARE_EQUAL(0, wcscmp(a, b)) #define VERIFY_ARE_EQUAL_CMP(a, b, ...) VERIFY_IS_TRUE(a == b, __VA_ARGS__) #define VERIFY_ARE_EQUAL_STR(a, b) \ { \ const char *pTmpA = (a); \ const char *pTmpB = (b); \ if (0 != strcmp(pTmpA, pTmpB)) { \ CA2W conv(pTmpB); \ WEX::Logging::Log::Comment(conv); \ const char *pA = pTmpA; \ const char *pB = pTmpB; \ while (*pA == *pB) { \ pA++; \ pB++; \ } \ wchar_t diffMsg[32]; \ swprintf_s(diffMsg, _countof(diffMsg), L"diff at %u", \ (unsigned)(pA - pTmpA)); \ WEX::Logging::Log::Comment(diffMsg); \ } \ VERIFY_ARE_EQUAL(0, strcmp(pTmpA, pTmpB)); \ } #define VERIFY_ARE_EQUAL_WSTR(a, b) \ { \ if (0 != wcscmp(a, b)) { \ WEX::Logging::Log::Comment(b); \ } \ VERIFY_ARE_EQUAL(0, wcscmp(a, b)); \ } #ifndef ASSERT_EQ #define ASSERT_EQ(expected, actual) VERIFY_ARE_EQUAL(expected, actual) #endif #ifndef ASSERT_NE #define ASSERT_NE(expected, actual) VERIFY_ARE_NOT_EQUAL(expected, actual) #endif #ifndef TEST_F #define TEST_F(typeName, functionName) void typeName::functionName() #endif #define ASSERT_HRESULT_SUCCEEDED VERIFY_SUCCEEDED #ifndef EXPECT_EQ #define EXPECT_EQ(expected, actual) VERIFY_ARE_EQUAL(expected, actual) #endif #endif // VERIFY_ARE_EQUAL static constexpr char whitespaceChars[] = " \t\r\n"; static constexpr wchar_t wideWhitespaceChars[] = L" \t\r\n"; inline std::string strltrim(const std::string &value) { size_t first = value.find_first_not_of(whitespaceChars); return first == string::npos ? value : value.substr(first); } inline std::string strrtrim(const std::string &value) { size_t last = value.find_last_not_of(whitespaceChars); return last == string::npos ? value : value.substr(0, last + 1); } inline std::string strtrim(const std::string &value) { return strltrim(strrtrim(value)); } inline bool strstartswith(const std::string &value, const char *pattern) { for (size_t i = 0;; ++i) { if (pattern[i] == '\0') return true; if (i == value.size() || value[i] != pattern[i]) return false; } } inline std::vector<std::string> strtok(const std::string &value, const char *delimiters = whitespaceChars) { size_t searchOffset = 0; std::vector<std::string> tokens; while (searchOffset != value.size()) { size_t tokenStartIndex = value.find_first_not_of(delimiters, searchOffset); if (tokenStartIndex == std::string::npos) break; size_t tokenEndIndex = value.find_first_of(delimiters, tokenStartIndex); if (tokenEndIndex == std::string::npos) tokenEndIndex = value.size(); tokens.emplace_back( value.substr(tokenStartIndex, tokenEndIndex - tokenStartIndex)); searchOffset = tokenEndIndex; } return tokens; } inline std::vector<std::wstring> strtok(const std::wstring &value, const wchar_t *delimiters = wideWhitespaceChars) { size_t searchOffset = 0; std::vector<std::wstring> tokens; while (searchOffset != value.size()) { size_t tokenStartIndex = value.find_first_not_of(delimiters, searchOffset); if (tokenStartIndex == std::string::npos) break; size_t tokenEndIndex = value.find_first_of(delimiters, tokenStartIndex); if (tokenEndIndex == std::string::npos) tokenEndIndex = value.size(); tokens.emplace_back( value.substr(tokenStartIndex, tokenEndIndex - tokenStartIndex)); searchOffset = tokenEndIndex; } return tokens; } // strreplace will replace all instances of lookFors with replacements at the // same index. Will log an error if the string is not found, unless the first // character is ? marking it optional. inline void strreplace(const std::vector<std::string> &lookFors, const std::vector<std::string> &replacements, std::string &str) { for (unsigned i = 0; i < lookFors.size(); ++i) { bool bOptional = false; bool found = false; size_t pos = 0; LPCSTR pLookFor = lookFors[i].data(); size_t lookForLen = lookFors[i].size(); if (pLookFor[0] == '?') { bOptional = true; pLookFor++; lookForLen--; } if (!pLookFor || !*pLookFor) { continue; } for (;;) { pos = str.find(pLookFor, pos); if (pos == std::string::npos) break; found = true; // at least once str.replace(pos, lookForLen, replacements[i]); pos += replacements[i].size(); } if (!bOptional) { if (!found) { WEX::Logging::Log::Comment(WEX::Common::String().Format( L"String not found: '%S' in text:\r\n%.*S", pLookFor, (unsigned)str.size(), str.data())); } VERIFY_IS_TRUE(found); } } } namespace hlsl_test { inline std::wstring vFormatToWString(const wchar_t *fmt, va_list argptr) { std::wstring result; #ifdef _WIN32 int len = _vscwprintf(fmt, argptr); result.resize(len + 1); vswprintf_s((wchar_t *)result.data(), len + 1, fmt, argptr); #else wchar_t fmtOut[1000]; int len = vswprintf(fmtOut, 1000, fmt, argptr); DXASSERT_LOCALVAR(len, len >= 0, "Too long formatted string in vFormatToWstring"); result = fmtOut; #endif return result; } inline std::wstring FormatToWString(const wchar_t *fmt, ...) { va_list args; va_start(args, fmt); std::wstring result(vFormatToWString(fmt, args)); va_end(args); return result; } inline void LogCommentFmt(const wchar_t *fmt, ...) { va_list args; va_start(args, fmt); std::wstring buf(vFormatToWString(fmt, args)); va_end(args); WEX::Logging::Log::Comment(buf.data()); } inline void LogErrorFmt(const wchar_t *fmt, ...) { va_list args; va_start(args, fmt); std::wstring buf(vFormatToWString(fmt, args)); va_end(args); WEX::Logging::Log::Error(buf.data()); } inline std::wstring GetPathToHlslDataFile(const wchar_t *relative, LPCWSTR paramName = HLSLDATAFILEPARAM, LPCWSTR defaultDataDir = DEFAULT_TEST_DIR) { WEX::TestExecution::SetVerifyOutput verifySettings( WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures); WEX::Common::String HlslDataDirValue; if (std::wstring(paramName).compare(HLSLDATAFILEPARAM) != 0) { // Not fatal, for instance, FILECHECKDUMPDIRPARAM will dump files before // running FileCheck, so they can be compared run to run if (FAILED(WEX::TestExecution::RuntimeParameters::TryGetValue( paramName, HlslDataDirValue))) return std::wstring(); } else { if (FAILED(WEX::TestExecution::RuntimeParameters::TryGetValue( HLSLDATAFILEPARAM, HlslDataDirValue))) HlslDataDirValue = defaultDataDir; } wchar_t envPath[MAX_PATH]; wchar_t expanded[MAX_PATH]; swprintf_s(envPath, _countof(envPath), L"%ls\\%ls", reinterpret_cast<const wchar_t *>(HlslDataDirValue.GetBuffer()), relative); VERIFY_WIN32_BOOL_SUCCEEDED( ExpandEnvironmentStringsW(envPath, expanded, _countof(expanded))); return std::wstring(expanded); } inline bool PathLooksAbsolute(LPCWSTR name) { // Very simplified, only for the cases we care about in the test suite. #ifdef _WIN32 return name && *name && ((*name == L'\\') || (name[1] == L':')); #else return name && *name && (*name == L'/'); #endif } static bool HasRunLine(std::string &line) { const char *delimiters = " ;/"; auto lineelems = strtok(line, delimiters); return !lineelems.empty() && lineelems.front().compare("RUN:") == 0; } inline std::vector<std::string> GetRunLines(const LPCWSTR name) { const std::wstring path = PathLooksAbsolute(name) ? std::wstring(name) : hlsl_test::GetPathToHlslDataFile(name); #ifdef _WIN32 std::ifstream infile(path); #else std::ifstream infile((CW2A(path.c_str()))); #endif if (infile.fail() || infile.bad()) { std::wstring errMsg(L"Unable to read file "); errMsg += path; WEX::Logging::Log::Error(errMsg.c_str()); VERIFY_FAIL(); } std::vector<std::string> runlines; std::string line; constexpr size_t runlinesize = 300; while (std::getline(infile, line)) { if (!HasRunLine(line)) continue; char runline[runlinesize]; memset(runline, 0, runlinesize); memcpy(runline, line.c_str(), min(runlinesize, line.size())); runlines.emplace_back(runline); } return runlines; } inline std::string GetFirstLine(LPCWSTR name) { char firstLine[300]; memset(firstLine, 0, sizeof(firstLine)); const std::wstring path = PathLooksAbsolute(name) ? std::wstring(name) : hlsl_test::GetPathToHlslDataFile(name); #ifdef _WIN32 std::ifstream infile(path); #else std::ifstream infile((CW2A(path.c_str()))); #endif if (infile.bad()) { std::wstring errMsg(L"Unable to read file "); errMsg += path; WEX::Logging::Log::Error(errMsg.c_str()); VERIFY_FAIL(); } infile.getline(firstLine, _countof(firstLine)); return firstLine; } inline HANDLE CreateFileForReading(LPCWSTR path) { HANDLE sourceHandle = CreateFileW(path, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0); if (sourceHandle == INVALID_HANDLE_VALUE) { DWORD err = GetLastError(); std::wstring errorMessage( FormatToWString(L"Unable to open file '%s', err=%u", path, err) .c_str()); VERIFY_SUCCEEDED(HRESULT_FROM_WIN32(err), errorMessage.c_str()); } return sourceHandle; } inline HANDLE CreateNewFileForReadWrite(LPCWSTR path) { HANDLE sourceHandle = CreateFileW(path, GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0); if (sourceHandle == INVALID_HANDLE_VALUE) { DWORD err = GetLastError(); std::wstring errorMessage( FormatToWString(L"Unable to create file '%s', err=%u", path, err) .c_str()); VERIFY_SUCCEEDED(HRESULT_FROM_WIN32(err), errorMessage.c_str()); } return sourceHandle; } // Copy of Unicode::IsStarMatchT/IsStarMatchWide is included here to avoid the // dependency on DXC support libraries. template <typename TChar> inline static bool IsStarMatchT(const TChar *pMask, size_t maskLen, const TChar *pName, size_t nameLen, TChar star) { if (maskLen == 0 && nameLen == 0) { return true; } if (maskLen == 0 || nameLen == 0) { return false; } if (pMask[maskLen - 1] == star) { // Prefix match. if (maskLen == 1) { // For just '*', everything is a match. return true; } --maskLen; if (maskLen > nameLen) { // Mask is longer than name, can't be a match. return false; } return 0 == memcmp(pMask, pName, sizeof(TChar) * maskLen); } else { // Exact match. if (nameLen != maskLen) { return false; } return 0 == memcmp(pMask, pName, sizeof(TChar) * nameLen); } } inline bool IsStarMatchWide(const wchar_t *pMask, size_t maskLen, const wchar_t *pName, size_t nameLen) { return IsStarMatchT<wchar_t>(pMask, maskLen, pName, nameLen, L'*'); } inline bool GetTestParamBool(LPCWSTR name) { WEX::Common::String ParamValue; WEX::Common::String NameValue; if (FAILED(WEX::TestExecution::RuntimeParameters::TryGetValue(name, ParamValue))) { return false; } if (ParamValue.IsEmpty()) { return false; } if (0 == wcscmp(ParamValue, L"*")) { return true; } VERIFY_SUCCEEDED(WEX::TestExecution::RuntimeParameters::TryGetValue( L"TestName", NameValue)); if (NameValue.IsEmpty()) { return false; } return hlsl_test::IsStarMatchWide(ParamValue, ParamValue.GetLength(), NameValue, NameValue.GetLength()); } inline bool GetTestParamUseWARP(bool defaultVal) { WEX::Common::String AdapterValue; if (FAILED(WEX::TestExecution::RuntimeParameters::TryGetValue( L"Adapter", AdapterValue))) { return defaultVal; } if ((defaultVal && AdapterValue.IsEmpty()) || AdapterValue.CompareNoCase(L"WARP") == 0 || AdapterValue.CompareNoCase(L"Microsoft Basic Render Driver") == 0) { return true; } return false; } } // namespace hlsl_test #ifdef FP_SUBNORMAL inline bool isdenorm(float f) { return FP_SUBNORMAL == std::fpclassify(f); } #else inline bool isdenorm(float f) { return (std::numeric_limits<float>::denorm_min() <= f && f < std::numeric_limits<float>::min()) || (-std::numeric_limits<float>::min() < f && f <= -std::numeric_limits<float>::denorm_min()); } #endif // FP_SUBNORMAL inline float ifdenorm_flushf(float a) { return isdenorm(a) ? copysign(0.0f, a) : a; } inline bool ifdenorm_flushf_eq(float a, float b) { return ifdenorm_flushf(a) == ifdenorm_flushf(b); } static const uint16_t Float16NaN = 0xff80; static const uint16_t Float16PosInf = 0x7c00; static const uint16_t Float16NegInf = 0xfc00; static const uint16_t Float16PosDenorm = 0x0008; static const uint16_t Float16NegDenorm = 0x8008; static const uint16_t Float16PosZero = 0x0000; static const uint16_t Float16NegZero = 0x8000; inline bool GetSign(float x) { return std::signbit(x); } inline int GetMantissa(float x) { int bits = reinterpret_cast<int &>(x); return bits & 0x7fffff; } inline int GetExponent(float x) { int bits = reinterpret_cast<int &>(x); return (bits >> 23) & 0xff; } #define FLOAT16_BIT_SIGN 0x8000 #define FLOAT16_BIT_EXP 0x7c00 #define FLOAT16_BIT_MANTISSA 0x03ff #define FLOAT16_BIGGEST_DENORM FLOAT16_BIT_MANTISSA #define FLOAT16_BIGGEST_NORMAL 0x7bff inline bool isnanFloat16(uint16_t val) { return (val & FLOAT16_BIT_EXP) == FLOAT16_BIT_EXP && (val & FLOAT16_BIT_MANTISSA) != 0; } // These are defined in ShaderOpTest.cpp using DirectXPackedVector functions. uint16_t ConvertFloat32ToFloat16(float val) throw(); float ConvertFloat16ToFloat32(uint16_t val) throw(); inline bool CompareFloatULP( const float &fsrc, const float &fref, int ULPTolerance, hlsl::DXIL::Float32DenormMode mode = hlsl::DXIL::Float32DenormMode::Any) { if (fsrc == fref) { return true; } if (std::isnan(fsrc)) { return std::isnan(fref); } if (mode == hlsl::DXIL::Float32DenormMode::Any) { // If denorm expected, output can be sign preserved zero. Otherwise output // should pass the regular ulp testing. if (isdenorm(fref) && fsrc == 0 && std::signbit(fsrc) == std::signbit(fref)) return true; } // For FTZ or Preserve mode, we should get the expected number within // ULPTolerance for any operations. int diff = *((const DWORD *)&fsrc) - *((const DWORD *)&fref); unsigned int uDiff = diff < 0 ? -diff : diff; return uDiff <= (unsigned int)ULPTolerance; } inline bool CompareFloatEpsilon( const float &fsrc, const float &fref, float epsilon, hlsl::DXIL::Float32DenormMode mode = hlsl::DXIL::Float32DenormMode::Any) { if (fsrc == fref) { return true; } if (std::isnan(fsrc)) { return std::isnan(fref); } if (mode == hlsl::DXIL::Float32DenormMode::Any) { // If denorm expected, output can be sign preserved zero. Otherwise output // should pass the regular epsilon testing. if (isdenorm(fref) && fsrc == 0 && std::signbit(fsrc) == std::signbit(fref)) return true; } // For FTZ or Preserve mode, we should get the expected number within // epsilon for any operations. return fabsf(fsrc - fref) < epsilon; } // Compare using relative error (relative error < 2^{nRelativeExp}) inline bool CompareFloatRelativeEpsilon( const float &fsrc, const float &fref, int nRelativeExp, hlsl::DXIL::Float32DenormMode mode = hlsl::DXIL::Float32DenormMode::Any) { return CompareFloatULP(fsrc, fref, 23 - nRelativeExp, mode); } inline bool CompareHalfULP(const uint16_t &fsrc, const uint16_t &fref, float ULPTolerance) { if (fsrc == fref) return true; if (isnanFloat16(fsrc)) return isnanFloat16(fref); // 16-bit floating point numbers must preserve denorms int diff = fsrc - fref; unsigned int uDiff = diff < 0 ? -diff : diff; return uDiff <= (unsigned int)ULPTolerance; } inline bool CompareHalfEpsilon(const uint16_t &fsrc, const uint16_t &fref, float epsilon) { if (fsrc == fref) return true; if (isnanFloat16(fsrc)) return isnanFloat16(fref); float src_f32 = ConvertFloat16ToFloat32(fsrc); float ref_f32 = ConvertFloat16ToFloat32(fref); return std::abs(src_f32 - ref_f32) < epsilon; } inline bool CompareHalfRelativeEpsilon(const uint16_t &fsrc, const uint16_t &fref, int nRelativeExp) { return CompareHalfULP(fsrc, fref, (float)(10 - nRelativeExp)); } #ifdef _WIN32 // returns the number of bytes per pixel for a given dxgi format // add more cases if different format needed to copy back resources inline UINT GetByteSizeForFormat(DXGI_FORMAT value) { switch (value) { case DXGI_FORMAT_R32G32B32A32_TYPELESS: return 16; case DXGI_FORMAT_R32G32B32A32_FLOAT: return 16; case DXGI_FORMAT_R32G32B32A32_UINT: return 16; case DXGI_FORMAT_R32G32B32A32_SINT: return 16; case DXGI_FORMAT_R32G32B32_TYPELESS: return 12; case DXGI_FORMAT_R32G32B32_FLOAT: return 12; case DXGI_FORMAT_R32G32B32_UINT: return 12; case DXGI_FORMAT_R32G32B32_SINT: return 12; case DXGI_FORMAT_R16G16B16A16_TYPELESS: return 8; case DXGI_FORMAT_R16G16B16A16_FLOAT: return 8; case DXGI_FORMAT_R16G16B16A16_UNORM: return 8; case DXGI_FORMAT_R16G16B16A16_UINT: return 8; case DXGI_FORMAT_R16G16B16A16_SNORM: return 8; case DXGI_FORMAT_R16G16B16A16_SINT: return 8; case DXGI_FORMAT_R32G32_TYPELESS: return 8; case DXGI_FORMAT_R32G32_FLOAT: return 8; case DXGI_FORMAT_R32G32_UINT: return 8; case DXGI_FORMAT_R32G32_SINT: return 8; case DXGI_FORMAT_R32G8X24_TYPELESS: return 8; case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: return 4; case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: return 4; case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: return 4; case DXGI_FORMAT_R10G10B10A2_TYPELESS: return 4; case DXGI_FORMAT_R10G10B10A2_UNORM: return 4; case DXGI_FORMAT_R10G10B10A2_UINT: return 4; case DXGI_FORMAT_R11G11B10_FLOAT: return 4; case DXGI_FORMAT_R8G8B8A8_TYPELESS: return 4; case DXGI_FORMAT_R8G8B8A8_UNORM: return 4; case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return 4; case DXGI_FORMAT_R8G8B8A8_UINT: return 4; case DXGI_FORMAT_R8G8B8A8_SNORM: return 4; case DXGI_FORMAT_R8G8B8A8_SINT: return 4; case DXGI_FORMAT_R16G16_TYPELESS: return 4; case DXGI_FORMAT_R16G16_FLOAT: return 4; case DXGI_FORMAT_R16G16_UNORM: return 4; case DXGI_FORMAT_R16G16_UINT: return 4; case DXGI_FORMAT_R16G16_SNORM: return 4; case DXGI_FORMAT_R16G16_SINT: return 4; case DXGI_FORMAT_R32_TYPELESS: return 4; case DXGI_FORMAT_D32_FLOAT: return 4; case DXGI_FORMAT_R32_FLOAT: return 4; case DXGI_FORMAT_R32_UINT: return 4; case DXGI_FORMAT_R32_SINT: return 4; case DXGI_FORMAT_R24G8_TYPELESS: return 4; case DXGI_FORMAT_D24_UNORM_S8_UINT: return 4; case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: return 4; case DXGI_FORMAT_X24_TYPELESS_G8_UINT: return 4; case DXGI_FORMAT_R8G8_TYPELESS: return 2; case DXGI_FORMAT_R8G8_UNORM: return 2; case DXGI_FORMAT_R8G8_UINT: return 2; case DXGI_FORMAT_R8G8_SNORM: return 2; case DXGI_FORMAT_R8G8_SINT: return 2; case DXGI_FORMAT_R16_TYPELESS: return 2; case DXGI_FORMAT_R16_FLOAT: return 2; case DXGI_FORMAT_D16_UNORM: return 2; case DXGI_FORMAT_R16_UNORM: return 2; case DXGI_FORMAT_R16_UINT: return 2; case DXGI_FORMAT_R16_SNORM: return 2; case DXGI_FORMAT_R16_SINT: return 2; case DXGI_FORMAT_R8_TYPELESS: return 1; case DXGI_FORMAT_R8_UNORM: return 1; case DXGI_FORMAT_R8_UINT: return 1; case DXGI_FORMAT_R8_SNORM: return 1; case DXGI_FORMAT_R8_SINT: return 1; case DXGI_FORMAT_A8_UNORM: return 1; case DXGI_FORMAT_R1_UNORM: return 1; default: VERIFY_FAILED(E_INVALIDARG); return 0; } } #endif
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/Test/RDATDumper.h
/////////////////////////////////////////////////////////////////////////////// // // // RDATDumper.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Use this to dump DxilRuntimeData (RDAT) for testing. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "DumpContext.h" #include "dxc/Support/WinIncludes.h" namespace hlsl { using namespace RDAT; namespace dump { void DumpRuntimeData(const RDAT::DxilRuntimeData &RDAT, DumpContext &d); template <typename RecordType> void DumpRecordTable(const RDAT::RDATContext &ctx, DumpContext &d, const char *tableName, const RDAT::TableReader &table); template <typename RecordType> void DumpRecordTableEntry(const RDAT::RDATContext &ctx, DumpContext &d, uint32_t i); template <typename _RecordType> class RecordDumper : public _RecordType { public: void Dump(const hlsl::RDAT::RDATContext &ctx, DumpContext &d) const; }; // Dump record starting at base fields, ending at the type specified. // Specialized for derived records template <typename _RecordType> void DumpWithBase(const hlsl::RDAT::RDATContext &ctx, DumpContext &d, const _RecordType *pRecord) { static_cast<const RecordDumper<_RecordType> *>(pRecord)->Dump(ctx, d); } template <typename _RecordType> class RecordRefDumper : public hlsl::RDAT::RecordRef<_RecordType> { public: RecordRefDumper(uint32_t index) { this->Index = index; } template <typename _DumpTy = _RecordType> const char *TypeName(const hlsl::RDAT::RDATContext &ctx) const { if (const char *name = RecordRefDumper<_DumpTy>(this->Index).TypeNameDerived(ctx)) return name; RecordRef<_DumpTy> rr = {this->Index}; if (rr.Get(ctx)) return RecordTraits<_DumpTy>::TypeName(); return nullptr; } template <typename _DumpTy = _RecordType> void Dump(const hlsl::RDAT::RDATContext &ctx, DumpContext &d) const { RecordRefDumper<_DumpTy> rrDumper(this->Index); if (const _DumpTy *ptr = rrDumper.Get(ctx)) { static_cast<const RecordDumper<_DumpTy> *>(ptr)->Dump(ctx, d); rrDumper.DumpDerived(ctx, d); } } // Specialized for base type to recurse into derived const char *TypeNameDerived(const hlsl::RDAT::RDATContext &ctx) const { return nullptr; } void DumpDerived(const hlsl::RDAT::RDATContext &ctx, DumpContext &d) const {} }; template <typename _T> void DumpRecordValue(const hlsl::RDAT::RDATContext &ctx, DumpContext &d, const char *tyName, const char *memberName, const _T *memberPtr); template <typename _T> void DumpRecordRef(const hlsl::RDAT::RDATContext &ctx, DumpContext &d, const char *tyName, const char *memberName, hlsl::RDAT::RecordRef<_T> rr); template <typename _T> void DumpRecordArrayRef(const hlsl::RDAT::RDATContext &ctx, DumpContext &d, const char *tyName, const char *memberName, hlsl::RDAT::RecordArrayRef<_T> rar); void DumpStringArray(const hlsl::RDAT::RDATContext &ctx, DumpContext &d, const char *memberName, hlsl::RDAT::RDATStringArray sa); void DumpIndexArray(const hlsl::RDAT::RDATContext &ctx, DumpContext &d, const char *memberName, uint32_t index); void DumpBytesRef(const hlsl::RDAT::RDATContext &ctx, DumpContext &d, const char *memberName, hlsl::RDAT::BytesRef bytesRef); template <typename _T> void DumpValueArray(DumpContext &d, const char *memberName, const char *typeName, const void *valueArray, unsigned arraySize); } // namespace dump } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/Test/D3DReflectionStrings.h
/////////////////////////////////////////////////////////////////////////////// // // // D3DReflectionStrings.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Used to convert reflection data types into strings. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "dxc/WinAdapter.h" #include "dxc/DxilContainer/DxilRuntimeReflection.h" #include "dxc/Support/D3DReflection.h" namespace hlsl { using namespace RDAT; namespace dump { // ToString functions for D3D types LPCSTR ToString(D3D_CBUFFER_TYPE CBType); LPCSTR ToString(D3D_SHADER_INPUT_TYPE Type); LPCSTR ToString(D3D_RESOURCE_RETURN_TYPE ReturnType); LPCSTR ToString(D3D_SRV_DIMENSION Dimension); LPCSTR ToString(D3D_PRIMITIVE_TOPOLOGY GSOutputTopology); LPCSTR ToString(D3D_PRIMITIVE InputPrimitive); LPCSTR ToString(D3D_TESSELLATOR_OUTPUT_PRIMITIVE HSOutputPrimitive); LPCSTR ToString(D3D_TESSELLATOR_PARTITIONING HSPartitioning); LPCSTR ToString(D3D_TESSELLATOR_DOMAIN TessellatorDomain); LPCSTR ToString(D3D_SHADER_VARIABLE_CLASS Class); LPCSTR ToString(D3D_SHADER_VARIABLE_TYPE Type); LPCSTR ToString(D3D_SHADER_VARIABLE_FLAGS Flag); LPCSTR ToString(D3D_SHADER_INPUT_FLAGS Flag); LPCSTR ToString(D3D_SHADER_CBUFFER_FLAGS Flag); LPCSTR ToString(D3D_PARAMETER_FLAGS Flag); LPCSTR ToString(D3D_NAME Name); LPCSTR ToString(D3D_REGISTER_COMPONENT_TYPE CompTy); LPCSTR ToString(D3D_MIN_PRECISION MinPrec); LPCSTR CompMaskToString(unsigned CompMask); // These macros declare the ToString functions for DXC types #define DEF_RDAT_ENUMS DEF_RDAT_DUMP_DECL #define DEF_DXIL_ENUMS DEF_RDAT_DUMP_DECL #include "dxc/DxilContainer/RDAT_Macros.inl" } // namespace dump } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/Test/D3DReflectionDumper.h
/////////////////////////////////////////////////////////////////////////////// // // // D3DReflectionDumper.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Use this to dump D3D Reflection data for testing. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "DumpContext.h" #include "dxc/Support/Global.h" #include "dxc/Support/WinIncludes.h" namespace hlsl { namespace dump { class D3DReflectionDumper : public DumpContext { private: bool m_bCheckByName = false; const char *m_LastName = nullptr; void SetLastName(const char *Name = nullptr) { m_LastName = Name ? Name : "<nullptr>"; } public: D3DReflectionDumper(std::ostream &outStream) : DumpContext(outStream) {} void SetCheckByName(bool bCheckByName) { m_bCheckByName = bCheckByName; } void DumpShaderVersion(UINT Version); void DumpDefaultValue(LPCVOID pDefaultValue, UINT Size); void Dump(D3D12_SHADER_TYPE_DESC &tyDesc); void Dump(D3D12_SHADER_VARIABLE_DESC &varDesc); void Dump(D3D12_SHADER_BUFFER_DESC &Desc); void Dump(D3D12_SHADER_INPUT_BIND_DESC &resDesc); void Dump(D3D12_SIGNATURE_PARAMETER_DESC &elDesc); void Dump(D3D12_SHADER_DESC &Desc); void Dump(D3D12_FUNCTION_DESC &Desc); void Dump(D3D12_LIBRARY_DESC &Desc); void Dump(ID3D12ShaderReflectionType *pType); void Dump(ID3D12ShaderReflectionVariable *pVar); void Dump(ID3D12ShaderReflectionConstantBuffer *pCBReflection); void Dump(ID3D12ShaderReflection *pShaderReflection); void Dump(ID3D12FunctionReflection *pFunctionReflection); void Dump(ID3D12LibraryReflection *pLibraryReflection); }; } // namespace dump } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/Test/TestConfig.h.in
#define DEFAULT_TEST_DIR L"@HLSL_TEST_DATA_DIR@" #define DEFAULT_EXEC_TEST_DIR L"@EXEC_TEST_DATA_DIR@"
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/Test/CompilationResult.h
/////////////////////////////////////////////////////////////////////////////// // // // CompilationResult.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // This file provides a class to parse a translation unit and return the // // diagnostic results and AST tree. // // // /////////////////////////////////////////////////////////////////////////////// #include <algorithm> #include <atomic> #include <cassert> #include <iostream> #include <memory> #include <sstream> #include <string> #include <vector> #include "dxc/Support/WinIncludes.h" #include "dxc/Support/microcom.h" #include "dxc/Support/dxcapi.use.h" #include "dxc/dxcapi.h" #include "dxc/dxcisense.h" #include "llvm/Support/Atomic.h" inline HRESULT IFE(HRESULT hr) { if (FAILED(hr)) { throw std::runtime_error("COM call failed"); } return hr; } inline HRESULT GetFirstChildFromCursor(IDxcCursor *cursor, IDxcCursor **pResult) { HRESULT hr; IDxcCursor **children = nullptr; unsigned childrenCount; hr = cursor->GetChildren(0, 1, &childrenCount, &children); if (SUCCEEDED(hr) && childrenCount == 1) { *pResult = children[0]; } else { *pResult = nullptr; hr = E_FAIL; } CoTaskMemFree(children); return hr; } class TrivialDxcUnsavedFile : public IDxcUnsavedFile { private: DXC_MICROCOM_REF_FIELD(m_dwRef) LPCSTR m_fileName; LPCSTR m_contents; unsigned m_length; public: DXC_MICROCOM_ADDREF_RELEASE_IMPL(m_dwRef) TrivialDxcUnsavedFile(LPCSTR fileName, LPCSTR contents) : m_dwRef(0), m_fileName(fileName), m_contents(contents) { m_length = (unsigned)strlen(m_contents); } static HRESULT Create(LPCSTR fileName, LPCSTR contents, IDxcUnsavedFile **pResult) { CComPtr<TrivialDxcUnsavedFile> pNewValue = new TrivialDxcUnsavedFile(fileName, contents); return pNewValue.QueryInterface(pResult); } HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { if (ppvObject == nullptr) return E_POINTER; if (IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(INoMarshal)) || IsEqualIID(iid, __uuidof(IDxcUnsavedFile))) { *ppvObject = reinterpret_cast<IDxcUnsavedFile *>(this); reinterpret_cast<IDxcUnsavedFile *>(this)->AddRef(); return S_OK; } return E_NOINTERFACE; } HRESULT STDMETHODCALLTYPE GetFileName(LPSTR *pFileName) override { *pFileName = (LPSTR)CoTaskMemAlloc(1 + strlen(m_fileName)); strcpy(*pFileName, m_fileName); return S_OK; } HRESULT STDMETHODCALLTYPE GetContents(LPSTR *pContents) override { *pContents = (LPSTR)CoTaskMemAlloc(m_length + 1); memcpy(*pContents, m_contents, m_length + 1); return S_OK; } HRESULT STDMETHODCALLTYPE GetLength(unsigned *pLength) override { *pLength = m_length; return S_OK; } }; class HlslIntellisenseSupport : public dxc::DxcDllSupport { public: HlslIntellisenseSupport() {} HlslIntellisenseSupport(HlslIntellisenseSupport &&other) : dxc::DxcDllSupport(std::move(other)) {} HRESULT CreateIntellisense(IDxcIntelliSense **pResult) { return CreateInstance(CLSID_DxcIntelliSense, pResult); } }; /// Summary of the results of a clang compilation operation. class CompilationResult { private: // Keep Intellisense alive. std::shared_ptr<HlslIntellisenseSupport> IsenseSupport; /// The top-level Intellisense object. CComPtr<IDxcIntelliSense> Intellisense; /// The libclang index for the compilation operation. CComPtr<IDxcIndex> Index; /// The number of diagnostic messages emitted. unsigned NumDiagnostics; /// The number of diagnostic messages emitted that indicate errors. unsigned NumErrorDiagnostics; /// The diagnostic messages emitted. std::vector<std::string> DiagnosticMessages; /// The severity of diagnostic messages. std::vector<DxcDiagnosticSeverity> DiagnosticSeverities; // Hide the copy constructor. CompilationResult(const CompilationResult &); public: CompilationResult(std::shared_ptr<HlslIntellisenseSupport> support, IDxcIntelliSense *isense, IDxcIndex *index, IDxcTranslationUnit *tu) : IsenseSupport(support), Intellisense(isense), Index(index), NumErrorDiagnostics(0), TU(tu) { if (tu) { IFE(tu->GetNumDiagnostics(&NumDiagnostics)); } else { NumDiagnostics = 0; } DxcDiagnosticDisplayOptions diagnosticOptions; IFE(isense->GetDefaultDiagnosticDisplayOptions(&diagnosticOptions)); for (unsigned i = 0; i < NumDiagnostics; i++) { CComPtr<IDxcDiagnostic> diagnostic; IFE(tu->GetDiagnostic(i, &diagnostic)); LPSTR format; IFE(diagnostic->FormatDiagnostic(diagnosticOptions, &format)); DiagnosticMessages.push_back(std::string(format)); CoTaskMemFree(format); DxcDiagnosticSeverity severity; IFE(diagnostic->GetSeverity(&severity)); DiagnosticSeverities.push_back(severity); if (IsErrorSeverity(severity)) { NumErrorDiagnostics++; } } assert(NumErrorDiagnostics <= NumDiagnostics && "else counting code in loop is incorrect"); assert(DiagnosticMessages.size() == NumDiagnostics && "else some diagnostics have no message"); assert(DiagnosticSeverities.size() == NumDiagnostics && "else some diagnostics have no severity"); } CompilationResult(CompilationResult &&other) : IsenseSupport(std::move(other.IsenseSupport)) { // Allow move constructor. Intellisense = other.Intellisense; other.Intellisense = nullptr; Index = other.Index; other.Index = nullptr; TU = other.TU; other.TU = nullptr; NumDiagnostics = other.NumDiagnostics; NumErrorDiagnostics = other.NumErrorDiagnostics; DiagnosticMessages = std::move(other.DiagnosticMessages); DiagnosticSeverities = std::move(other.DiagnosticSeverities); } ~CompilationResult() { Dispose(); } /// The translation unit resulting from the compilation. CComPtr<IDxcTranslationUnit> TU; static const char *getDefaultFileName() { return "filename.hlsl"; } static std::shared_ptr<HlslIntellisenseSupport> DefaultHlslSupport; static std::shared_ptr<HlslIntellisenseSupport> GetHlslSupport() { if (DefaultHlslSupport.get() != nullptr) { return DefaultHlslSupport; } std::shared_ptr<HlslIntellisenseSupport> result = std::make_shared<HlslIntellisenseSupport>(); IFE(result->Initialize()); return result; } static CompilationResult CreateForProgramAndArgs(const char *text, size_t textLen, const char *commandLineArgs[], unsigned commandLineArgsCount, DxcTranslationUnitFlags *options = nullptr) { std::shared_ptr<HlslIntellisenseSupport> support(GetHlslSupport()); CComPtr<IDxcIntelliSense> isense; IFE(support->CreateIntellisense(&isense)); CComPtr<IDxcIndex> tuIndex; CComPtr<IDxcTranslationUnit> tu; const char *fileName = getDefaultFileName(); if (textLen == 0) textLen = strlen(text); IFE(isense->CreateIndex(&tuIndex)); CComPtr<IDxcUnsavedFile> unsavedFile; IFE(TrivialDxcUnsavedFile::Create(fileName, text, &unsavedFile)); DxcTranslationUnitFlags localOptions; if (options == nullptr) { IFE(isense->GetDefaultEditingTUOptions(&localOptions)); } else { localOptions = *options; } IFE(tuIndex->ParseTranslationUnit(fileName, commandLineArgs, commandLineArgsCount, &(unsavedFile.p), 1, localOptions, &tu)); return CompilationResult(support, isense.p, tuIndex.p, tu.p); } static CompilationResult CreateForProgram(const char *text, size_t textLen, DxcTranslationUnitFlags *options = nullptr) { const char *commandLineArgs[] = {"-c", "-ferror-limit=200"}; unsigned commandLineArgsCount = _countof(commandLineArgs); return CreateForProgramAndArgs(text, textLen, commandLineArgs, commandLineArgsCount, options); } static CompilationResult CreateForCommandLine(char *arguments, const char *fileName) { std::shared_ptr<HlslIntellisenseSupport> support(GetHlslSupport()); return CreateForCommandLine(arguments, fileName, support); } static CompilationResult CreateForCommandLine(char *arguments, const char *fileName, std::shared_ptr<HlslIntellisenseSupport> support) { CComPtr<IDxcIntelliSense> isense; IFE(support->CreateIntellisense(&isense)); CComPtr<IDxcIndex> tuIndex; CComPtr<IDxcTranslationUnit> tu; const char *commandLineArgs[32]; unsigned commandLineArgsCount = 0; char *nextArg = arguments; // Set a very high number of errors to avoid giving up too early. commandLineArgs[commandLineArgsCount++] = "-ferror-limit=2000"; // Turn on spell checking for compatibility. This produces error messages // that suggest corrected spellings. commandLineArgs[commandLineArgsCount++] = "-fspell-checking"; // Turn off color diagnostics to avoid control characters in diagnostic // stream. commandLineArgs[commandLineArgsCount++] = "-fno-color-diagnostics"; IFE(isense->CreateIndex(&tuIndex)); // Split command line arguments by spaces if (nextArg) { // skip leading spaces while (*nextArg == ' ') nextArg++; commandLineArgs[commandLineArgsCount++] = nextArg; while ((*nextArg != '\0')) { if (*nextArg == ' ') { *nextArg = 0; commandLineArgs[commandLineArgsCount++] = nextArg + 1; } nextArg++; } } DxcTranslationUnitFlags options; IFE(isense->GetDefaultEditingTUOptions(&options)); IFE(tuIndex->ParseTranslationUnit(fileName, commandLineArgs, commandLineArgsCount, nullptr, 0, options, &tu)); return CompilationResult(support, isense.p, tuIndex.p, tu.p); } bool IsTUAvailable() const { return TU != nullptr; } bool ParseSucceeded() const { return TU != nullptr && NumErrorDiagnostics == 0; } static bool IsErrorSeverity(DxcDiagnosticSeverity severity) { return (severity == DxcDiagnostic_Error || severity == DxcDiagnostic_Fatal); } /// Gets a string with all error messages concatenated, one per line. std::string GetTextForErrors() const { assert(DiagnosticMessages.size() == NumDiagnostics && "otherwise some diagnostics have no message"); assert(DiagnosticSeverities.size() == NumDiagnostics && "otherwise some diagnostics have no severity"); std::stringstream ostr; for (size_t i = 0; i < DiagnosticMessages.size(); i++) { if (IsErrorSeverity(DiagnosticSeverities[i])) { ostr << DiagnosticMessages[i] << '\n'; } } return ostr.str(); } /// Releases resources, including the translation unit AST. void Dispose() { TU = nullptr; Index = nullptr; Intellisense = nullptr; IsenseSupport = nullptr; } private: #if SUPPORTS_CURSOR_WALK struct CursorStringData { std::stringstream &ostr; std::vector<CXCursor> cursors; CursorStringData(std::stringstream &the_ostr) : ostr(the_ostr) {} }; static CXChildVisitResult AppendCursorStringCallback(CXCursor cursor, CXCursor parent, CXClientData client_data) { CursorStringData *d = (CursorStringData *)client_data; auto cursorsStart = std::begin(d->cursors); auto cursorsEnd = std::end(d->cursors); auto parentLocation = std::find(cursorsStart, cursorsEnd, parent); assert(parentLocation != cursorsEnd && "otherwise the parent was not visited previously"); AppendCursorString(cursor, parentLocation - cursorsStart, d->ostr); d->cursors.resize(1 + (parentLocation - cursorsStart)); d->cursors.push_back(cursor); return CXChildVisit_Recurse; } #endif static void AppendCursorString(IDxcCursor *cursor, size_t indent, std::stringstream &ostr) { if (indent > 0) { std::streamsize prior = ostr.width(); ostr.width(indent); ostr << ' '; ostr.width(prior); } CComPtr<IDxcType> type; DxcCursorKind kind; cursor->GetKind(&kind); cursor->GetCursorType(&type); switch (kind) { case DxcCursor_UnexposedDecl: ostr << "UnexposedDecl"; break; case DxcCursor_StructDecl: ostr << "StructDecl"; break; case DxcCursor_UnionDecl: ostr << "UnionDecl"; break; case DxcCursor_ClassDecl: ostr << "ClassDecl"; break; case DxcCursor_EnumDecl: ostr << "EnumDecl"; break; case DxcCursor_FieldDecl: ostr << "FieldDecl"; break; case DxcCursor_EnumConstantDecl: ostr << "EnumConstantDecl"; break; case DxcCursor_FunctionDecl: ostr << "FunctionDecl"; break; case DxcCursor_VarDecl: ostr << "VarDecl"; break; case DxcCursor_ParmDecl: ostr << "ParmDecl"; break; case DxcCursor_ObjCInterfaceDecl: ostr << "ObjCInterfaceDecl"; break; case DxcCursor_ObjCCategoryDecl: ostr << "ObjCCategoryDecl"; break; case DxcCursor_ObjCProtocolDecl: ostr << "ObjCProtocolDecl"; break; case DxcCursor_ObjCPropertyDecl: ostr << "ObjCPropertyDecl"; break; case DxcCursor_ObjCIvarDecl: ostr << "ObjCIvarDecl"; break; case DxcCursor_ObjCInstanceMethodDecl: ostr << "ObjCInstanceMethodDecl"; break; case DxcCursor_ObjCClassMethodDecl: ostr << "ObjCClassMethodDecl"; break; case DxcCursor_ObjCImplementationDecl: ostr << "ObjCImplementationDecl"; break; case DxcCursor_ObjCCategoryImplDecl: ostr << "ObjCCategoryImplDecl"; break; case DxcCursor_TypedefDecl: ostr << "TypedefDecl"; break; case DxcCursor_CXXMethod: ostr << "CXXMethod"; break; case DxcCursor_Namespace: ostr << "Namespace"; break; case DxcCursor_LinkageSpec: ostr << "LinkageSpec"; break; case DxcCursor_Constructor: ostr << "Constructor"; break; case DxcCursor_Destructor: ostr << "Destructor"; break; case DxcCursor_ConversionFunction: ostr << "ConversionFunction"; break; case DxcCursor_TemplateTypeParameter: ostr << "TemplateTypeParameter"; break; case DxcCursor_NonTypeTemplateParameter: ostr << "NonTypeTemplateParameter"; break; case DxcCursor_TemplateTemplateParameter: ostr << "TemplateTemplateParameter"; break; case DxcCursor_FunctionTemplate: ostr << "FunctionTemplate"; break; case DxcCursor_ClassTemplate: ostr << "ClassTemplate"; break; case DxcCursor_ClassTemplatePartialSpecialization: ostr << "ClassTemplatePartialSpecialization"; break; case DxcCursor_NamespaceAlias: ostr << "NamespaceAlias"; break; case DxcCursor_UsingDirective: ostr << "UsingDirective"; break; case DxcCursor_UsingDeclaration: ostr << "UsingDeclaration"; break; case DxcCursor_TypeAliasDecl: ostr << "TypeAliasDecl"; break; case DxcCursor_ObjCSynthesizeDecl: ostr << "ObjCSynthesizeDecl"; break; case DxcCursor_ObjCDynamicDecl: ostr << "ObjCDynamicDecl"; break; case DxcCursor_CXXAccessSpecifier: ostr << "CXXAccessSpecifier"; break; case DxcCursor_ObjCSuperClassRef: ostr << "ObjCSuperClassRef"; break; case DxcCursor_ObjCProtocolRef: ostr << "ObjCProtocolRef"; break; case DxcCursor_ObjCClassRef: ostr << "ObjCClassRef"; break; case DxcCursor_TypeRef: ostr << "TypeRef"; break; case DxcCursor_CXXBaseSpecifier: ostr << "CXXBaseSpecifier"; break; case DxcCursor_TemplateRef: ostr << "TemplateRef"; break; case DxcCursor_NamespaceRef: ostr << "NamespaceRef"; break; case DxcCursor_MemberRef: ostr << "MemberRef"; break; case DxcCursor_LabelRef: ostr << "LabelRef"; break; case DxcCursor_OverloadedDeclRef: ostr << "OverloadedDeclRef"; break; case DxcCursor_VariableRef: ostr << "VariableRef"; break; case DxcCursor_InvalidFile: ostr << "InvalidFile"; break; case DxcCursor_NoDeclFound: ostr << "NoDeclFound"; break; case DxcCursor_NotImplemented: ostr << "NotImplemented"; break; case DxcCursor_InvalidCode: ostr << "InvalidCode"; break; case DxcCursor_UnexposedExpr: ostr << "UnexposedExpr"; break; case DxcCursor_DeclRefExpr: ostr << "DeclRefExpr"; break; case DxcCursor_MemberRefExpr: ostr << "MemberRefExpr"; break; case DxcCursor_CallExpr: ostr << "CallExpr"; break; case DxcCursor_ObjCMessageExpr: ostr << "ObjCMessageExpr"; break; case DxcCursor_BlockExpr: ostr << "BlockExpr"; break; case DxcCursor_IntegerLiteral: ostr << "IntegerLiteral"; break; case DxcCursor_FloatingLiteral: ostr << "FloatingLiteral"; break; case DxcCursor_ImaginaryLiteral: ostr << "ImaginaryLiteral"; break; case DxcCursor_StringLiteral: ostr << "StringLiteral"; break; case DxcCursor_CharacterLiteral: ostr << "CharacterLiteral"; break; case DxcCursor_ParenExpr: ostr << "ParenExpr"; break; case DxcCursor_UnaryOperator: ostr << "UnaryOperator"; break; case DxcCursor_ArraySubscriptExpr: ostr << "ArraySubscriptExpr"; break; case DxcCursor_BinaryOperator: ostr << "BinaryOperator"; break; case DxcCursor_CompoundAssignOperator: ostr << "CompoundAssignOperator"; break; case DxcCursor_ConditionalOperator: ostr << "ConditionalOperator"; break; case DxcCursor_CStyleCastExpr: ostr << "CStyleCastExpr"; break; case DxcCursor_CompoundLiteralExpr: ostr << "CompoundLiteralExpr"; break; case DxcCursor_InitListExpr: ostr << "InitListExpr"; break; case DxcCursor_AddrLabelExpr: ostr << "AddrLabelExpr"; break; case DxcCursor_StmtExpr: ostr << "StmtExpr"; break; case DxcCursor_GenericSelectionExpr: ostr << "GenericSelectionExpr"; break; case DxcCursor_GNUNullExpr: ostr << "GNUNullExpr"; break; case DxcCursor_CXXStaticCastExpr: ostr << "CXXStaticCastExpr"; break; case DxcCursor_CXXDynamicCastExpr: ostr << "CXXDynamicCastExpr"; break; case DxcCursor_CXXReinterpretCastExpr: ostr << "CXXReinterpretCastExpr"; break; case DxcCursor_CXXConstCastExpr: ostr << "CXXConstCastExpr"; break; case DxcCursor_CXXFunctionalCastExpr: ostr << "CXXFunctionalCastExpr"; break; case DxcCursor_CXXTypeidExpr: ostr << "CXXTypeidExpr"; break; case DxcCursor_CXXBoolLiteralExpr: ostr << "CXXBoolLiteralExpr"; break; case DxcCursor_CXXNullPtrLiteralExpr: ostr << "CXXNullPtrLiteralExpr"; break; case DxcCursor_CXXThisExpr: ostr << "CXXThisExpr"; break; case DxcCursor_CXXThrowExpr: ostr << "CXXThrowExpr"; break; case DxcCursor_CXXNewExpr: ostr << "CXXNewExpr"; break; case DxcCursor_CXXDeleteExpr: ostr << "CXXDeleteExpr"; break; case DxcCursor_UnaryExpr: ostr << "UnaryExpr"; break; case DxcCursor_ObjCStringLiteral: ostr << "ObjCStringLiteral"; break; case DxcCursor_ObjCEncodeExpr: ostr << "ObjCEncodeExpr"; break; case DxcCursor_ObjCSelectorExpr: ostr << "ObjCSelectorExpr"; break; case DxcCursor_ObjCProtocolExpr: ostr << "ObjCProtocolExpr"; break; case DxcCursor_ObjCBridgedCastExpr: ostr << "ObjCBridgedCastExpr"; break; case DxcCursor_PackExpansionExpr: ostr << "PackExpansionExpr"; break; case DxcCursor_SizeOfPackExpr: ostr << "SizeOfPackExpr"; break; case DxcCursor_LambdaExpr: ostr << "LambdaExpr"; break; case DxcCursor_ObjCBoolLiteralExpr: ostr << "ObjCBoolLiteralExpr"; break; case DxcCursor_ObjCSelfExpr: ostr << "ObjCSelfExpr"; break; case DxcCursor_UnexposedStmt: ostr << "UnexposedStmt"; break; case DxcCursor_LabelStmt: ostr << "LabelStmt"; break; case DxcCursor_CompoundStmt: ostr << "CompoundStmt"; break; case DxcCursor_CaseStmt: ostr << "CaseStmt"; break; case DxcCursor_DefaultStmt: ostr << "DefaultStmt"; break; case DxcCursor_IfStmt: ostr << "IfStmt"; break; case DxcCursor_SwitchStmt: ostr << "SwitchStmt"; break; case DxcCursor_WhileStmt: ostr << "WhileStmt"; break; case DxcCursor_DoStmt: ostr << "DoStmt"; break; case DxcCursor_ForStmt: ostr << "ForStmt"; break; case DxcCursor_GotoStmt: ostr << "GotoStmt"; break; case DxcCursor_IndirectGotoStmt: ostr << "IndirectGotoStmt"; break; case DxcCursor_ContinueStmt: ostr << "ContinueStmt"; break; case DxcCursor_BreakStmt: ostr << "BreakStmt"; break; case DxcCursor_ReturnStmt: ostr << "ReturnStmt"; break; case DxcCursor_GCCAsmStmt: ostr << "GCCAsmStmt"; break; case DxcCursor_ObjCAtTryStmt: ostr << "ObjCAtTryStmt"; break; case DxcCursor_ObjCAtCatchStmt: ostr << "ObjCAtCatchStmt"; break; case DxcCursor_ObjCAtFinallyStmt: ostr << "ObjCAtFinallyStmt"; break; case DxcCursor_ObjCAtThrowStmt: ostr << "ObjCAtThrowStmt"; break; case DxcCursor_ObjCAtSynchronizedStmt: ostr << "ObjCAtSynchronizedStmt"; break; case DxcCursor_ObjCAutoreleasePoolStmt: ostr << "ObjCAutoreleasePoolStmt"; break; case DxcCursor_ObjCForCollectionStmt: ostr << "ObjCForCollectionStmt"; break; case DxcCursor_CXXCatchStmt: ostr << "CXXCatchStmt"; break; case DxcCursor_CXXTryStmt: ostr << "CXXTryStmt"; break; case DxcCursor_CXXForRangeStmt: ostr << "CXXForRangeStmt"; break; case DxcCursor_SEHTryStmt: ostr << "SEHTryStmt"; break; case DxcCursor_SEHExceptStmt: ostr << "SEHExceptStmt"; break; case DxcCursor_SEHFinallyStmt: ostr << "SEHFinallyStmt"; break; case DxcCursor_MSAsmStmt: ostr << "MSAsmStmt"; break; case DxcCursor_NullStmt: ostr << "NullStmt"; break; case DxcCursor_DeclStmt: ostr << "DeclStmt"; break; case DxcCursor_OMPParallelDirective: ostr << "OMPParallelDirective"; break; case DxcCursor_TranslationUnit: ostr << "TranslationUnit"; break; case DxcCursor_UnexposedAttr: ostr << "UnexposedAttr"; break; #if 0 CXCursor_IBActionAttr = 401, CXCursor_IBOutletAttr = 402, CXCursor_IBOutletCollectionAttr = 403, CXCursor_CXXFinalAttr = 404, CXCursor_CXXOverrideAttr = 405, CXCursor_AnnotateAttr = 406, CXCursor_AsmLabelAttr = 407, CXCursor_PackedAttr = 408, /* Preprocessing */ CXCursor_PreprocessingDirective = 500, CXCursor_MacroDefinition = 501, CXCursor_MacroExpansion = 502, CXCursor_InclusionDirective = 503, case CXCursor_FunctionDecl: break; case CXCursor_ClassDecl: ostr << "class decl"; break; case CXCursor_TranslationUnit: ostr << "translation unit"; break; #endif default: ostr << "unknown/unhandled cursor kind " << kind; break; } DxcTypeKind typeKind; if (type != nullptr && SUCCEEDED(type->GetKind(&typeKind)) && typeKind != DxcTypeKind_Invalid) { LPSTR name; type->GetSpelling(&name); ostr << " [type " << name << "]"; CoTaskMemFree(name); } ostr << '\n'; // Recurse. IDxcCursor **children = nullptr; unsigned childrenCount; cursor->GetChildren(0, 64, &childrenCount, &children); for (unsigned i = 0; i < childrenCount; i++) { AppendCursorString(children[i], indent + 1, ostr); children[i]->Release(); } CoTaskMemFree(children); } public: std::string BuildASTString() { if (TU == nullptr) { return "<failed to build - TU is null>"; } CComPtr<IDxcCursor> cursor; std::stringstream ostr; this->TU->GetCursor(&cursor); AppendCursorString(cursor, 0, ostr); return ostr.str(); } };
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/Test/HLSLTestData.h
/////////////////////////////////////////////////////////////////////////////// // // // HLSLTestData.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // This file provides declarations and sample data for unit tests. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once struct StorageClassDataItem { const char *Keyword; bool IsValid; }; const StorageClassDataItem StorageClassData[] = { {"inline", true}, {"extern", false}, {"", true}}; struct InOutParameterModifierDataItem { const char *Keyword; bool ActsAsReference; }; const InOutParameterModifierDataItem InOutParameterModifierData[] = { {"", false}, {"in", false}, {"inout", true}, {"out", true}};
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/Test/DumpContext.h
/////////////////////////////////////////////////////////////////////////////// // // // DumpContext.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Context for dumping structured data, enums, and flags for use in tests. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "dxc/Support/Global.h" #include "dxc/Test/D3DReflectionStrings.h" #include <iomanip> #include <ostream> #include <sstream> #include <string> #include <unordered_set> namespace hlsl { using namespace RDAT; namespace dump { template <typename _T> struct EnumValue { public: EnumValue(const _T &e) : eValue(e) {} _T eValue; }; template <typename _T, typename _StoreT = uint32_t> struct FlagsValue { public: FlagsValue(const _StoreT &f) : Flags(f) {} _StoreT Flags; }; struct QuotedStringValue { public: QuotedStringValue(const char *str) : Str(str) {} const char *Str; }; class DumpContext { private: std::ostream &m_out; unsigned m_indent = 0; std::unordered_set<size_t> m_visited; std::ostream &DoIndent() { return m_out << std::setfill(' ') << std::setw((m_indent > 16) ? 32 : m_indent * 2) << ""; } public: DumpContext(std::ostream &outStream) : m_out(outStream) {} void Indent() { if (m_indent < (1 << 30)) m_indent++; } void Dedent() { if (m_indent > 0) m_indent--; } template <typename _T> std::ostream &Write(_T t) { return Write(m_out, t); } template <typename _T, typename... Args> std::ostream &Write(_T t, Args... args) { return Write(Write(m_out, t), args...); } template <typename _T> std::ostream &Write(std::ostream &out, _T t) { return out << t; } template <typename _T, typename... Args> std::ostream &Write(std::ostream &out, _T t, Args... args) { return Write(Write(out, t), args...); } template <typename _T> std::ostream &WriteLn(_T t) { return Write(DoIndent(), t) << std::endl << std::resetiosflags(std::ios_base::basefield | std::ios_base::showbase); } template <typename _T, typename... Args> std::ostream &WriteLn(_T t, Args... args) { return Write(Write(DoIndent(), t), args...) << std::endl << std::resetiosflags(std::ios_base::basefield | std::ios_base::showbase); } template <typename _T> std::ostream &WriteEnumValue(_T eValue) { const char *szValue = ToString(eValue); if (szValue) return Write(szValue); else return Write("<unknown: ", std::hex, std::showbase, (UINT)eValue, ">"); } template <typename _T> void DumpEnum(const char *Name, _T eValue) { WriteLn(Name, ": ", EnumValue<_T>(eValue)); } template <typename _T, typename _StoreT = uint32_t> void DumpFlags(const char *Name, _StoreT Flags) { WriteLn(Name, ": ", FlagsValue<_T, _StoreT>(Flags)); } template <typename... Args> void Failure(Args... args) { WriteLn("Failed: ", args...); } // Return true if ptr has not yet been visited, prevents recursive dumping bool Visit(size_t value) { return m_visited.insert(value).second; } bool Visit(const void *ptr) { return ptr ? Visit((size_t)ptr) : false; } void VisitReset() { m_visited.clear(); } }; template <> inline std::ostream &DumpContext::Write<uint8_t>(std::ostream &out, uint8_t t) { return out << (unsigned)t; } // Copied from llvm/ADT/StringExtras.h inline char hexdigit(unsigned X, bool LowerCase = false) { const char HexChar = LowerCase ? 'a' : 'A'; return X < 10 ? '0' + X : HexChar + X - 10; } // Copied from lib/IR/AsmWriter.cpp // EscapedString - Print each character of the specified string, escaping // it if it is not printable or if it is an escape char. inline std::string EscapedString(const char *text) { std::ostringstream ss; size_t size = strlen(text); for (unsigned i = 0, e = size; i != e; ++i) { unsigned char C = text[i]; if (isprint(C) && C != '\\' && C != '"') ss << C; else ss << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F); } return ss.str(); } template <typename _T> std::ostream &operator<<(std::ostream &out, const EnumValue<_T> &obj) { if (const char *szValue = ToString(obj.eValue)) return out << szValue; else return out << "<unknown: " << std::hex << std::showbase << (UINT)obj.eValue << ">"; } template <typename _T, typename _StoreT> std::ostream &operator<<(std::ostream &out, const FlagsValue<_T, _StoreT> &obj) { _StoreT Flags = obj.Flags; if (!Flags) { const char *szValue = ToString((_T)0); if (szValue) return out << "0 (" << szValue << ")"; else return out << "0"; } uint32_t flag = 0; out << "("; while (Flags) { if (flag) out << " | "; flag = (Flags & ~(Flags - 1)); Flags ^= flag; out << EnumValue<_T>((_T)flag); } out << ")"; return out; } inline std::ostream &operator<<(std::ostream &out, const QuotedStringValue &obj) { if (!obj.Str) return out << "<null string pointer>"; return out << "\"" << EscapedString(obj.Str) << "\""; } } // namespace dump } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/Test/DxcTestUtils.h
/////////////////////////////////////////////////////////////////////////////// // // // DxcTestUtils.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // This file provides utility functions for testing dxc APIs. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "dxc/Support/WinIncludes.h" #include "dxc/Support/dxcapi.use.h" #include "dxc/dxcapi.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include <map> #include <string> #include <vector> namespace hlsl { namespace options { class DxcOpts; class MainArgs; } // namespace options } // namespace hlsl /// Use this class to run a FileCheck invocation in memory. class FileCheckForTest { public: FileCheckForTest(); std::string CheckFilename; /// File to check (defaults to stdin) std::string InputFilename; /// Prefix to use from check file (defaults to 'CHECK') std::vector<std::string> CheckPrefixes; /// Do not treat all horizontal whitespace as equivalent bool NoCanonicalizeWhiteSpace; /// Add an implicit negative check with this pattern to every /// positive check. This can be used to ensure that no instances of /// this pattern occur which are not matched by a positive pattern std::vector<std::string> ImplicitCheckNot; /// Allow the input file to be empty. This is useful when making /// checks that some error message does not occur, for example. bool AllowEmptyInput; /// VariableTable - This holds all the current filecheck variables. llvm::StringMap<std::string> VariableTable; /// String to read in place of standard input. std::string InputForStdin; /// Output stream. std::string test_outs; /// Output stream. std::string test_errs; int Run(); }; // wstring because most uses need UTF-16: IDxcResult output names, include // handler typedef std::map<std::wstring, CComPtr<IDxcBlob>> FileMap; // The result of running a single command in a run pipeline struct FileRunCommandResult { CComPtr<IDxcOperationResult> OpResult; // The operation result, if any. std::string StdOut; std::string StdErr; int ExitCode = 0; bool AbortPipeline = false; // True to prevent running subsequent commands static inline FileRunCommandResult Success() { FileRunCommandResult result; result.ExitCode = 0; return result; } static inline FileRunCommandResult Success(std::string StdOut) { FileRunCommandResult result; result.ExitCode = 0; result.StdOut = std::move(StdOut); return result; } static inline FileRunCommandResult Error(int ExitCode, std::string StdErr) { FileRunCommandResult result; result.ExitCode = ExitCode; result.StdErr = std::move(StdErr); return result; } static inline FileRunCommandResult Error(std::string StdErr) { return Error(1, StdErr); } }; typedef std::map<std::string, std::string> PluginToolsPaths; class FileRunCommandPart { public: FileRunCommandPart(const std::string &command, const std::string &arguments, LPCWSTR commandFileName); FileRunCommandPart(const FileRunCommandPart &) = default; FileRunCommandPart(FileRunCommandPart &&) = default; FileRunCommandResult Run(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior, PluginToolsPaths *pPluginToolsPaths = nullptr, LPCWSTR dumpName = nullptr); FileRunCommandResult RunHashTests(dxc::DxcDllSupport &DllSupport); FileRunCommandResult ReadOptsForDxc(hlsl::options::MainArgs &argStrings, hlsl::options::DxcOpts &Opts, unsigned flagsToInclude = 0); std::string Command; // Command to run, eg %dxc std::string Arguments; // Arguments to command LPCWSTR CommandFileName; // File name replacement for %s FileMap *pVFS = nullptr; // Files in virtual file system private: FileRunCommandResult RunFileChecker(const FileRunCommandResult *Prior, LPCWSTR dumpName = nullptr); FileRunCommandResult RunDxc(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior); FileRunCommandResult RunDxv(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior); FileRunCommandResult RunOpt(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior); FileRunCommandResult RunListParts(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior); FileRunCommandResult RunD3DReflect(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior); FileRunCommandResult RunDxr(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior); FileRunCommandResult RunLink(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior); FileRunCommandResult RunTee(const FileRunCommandResult *Prior); FileRunCommandResult RunXFail(const FileRunCommandResult *Prior); FileRunCommandResult RunDxilVer(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior); FileRunCommandResult RunDxcHashTest(dxc::DxcDllSupport &DllSupport); FileRunCommandResult RunFromPath(const std::string &path, const FileRunCommandResult *Prior); FileRunCommandResult RunFileCompareText(const FileRunCommandResult *Prior); #ifdef _WIN32 FileRunCommandResult RunFxc(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior); #endif void SubstituteFilenameVars(std::string &args); #ifdef _WIN32 bool ReadFileContentToString(HANDLE hFile, std::string &str); #endif }; void ParseCommandParts(LPCSTR commands, LPCWSTR fileName, std::vector<FileRunCommandPart> &parts); void ParseCommandPartsFromFile(LPCWSTR fileName, std::vector<FileRunCommandPart> &parts); class FileRunTestResult { public: std::string ErrorMessage; int RunResult = -1; static FileRunTestResult RunHashTestFromFileCommands(LPCWSTR fileName); static FileRunTestResult RunFromFileCommands(LPCWSTR fileName, PluginToolsPaths *pPluginToolsPaths = nullptr, LPCWSTR dumpName = nullptr); static FileRunTestResult RunFromFileCommands(LPCWSTR fileName, dxc::DxcDllSupport &dllSupport, PluginToolsPaths *pPluginToolsPaths = nullptr, LPCWSTR dumpName = nullptr); }; void AssembleToContainer(dxc::DxcDllSupport &dllSupport, IDxcBlob *pModule, IDxcBlob **pContainer); std::string BlobToUtf8(IDxcBlob *pBlob); std::wstring BlobToWide(IDxcBlob *pBlob); void CheckOperationSucceeded(IDxcOperationResult *pResult, IDxcBlob **ppBlob); bool CheckOperationResultMsgs(IDxcOperationResult *pResult, llvm::ArrayRef<LPCSTR> pErrorMsgs, bool maySucceedAnyway, bool bRegex); bool CheckOperationResultMsgs(IDxcOperationResult *pResult, const LPCSTR *pErrorMsgs, size_t errorMsgCount, bool maySucceedAnyway, bool bRegex); bool CheckMsgs(const LPCSTR pText, size_t TextCount, const LPCSTR *pErrorMsgs, size_t errorMsgCount, bool bRegex); bool CheckNotMsgs(const LPCSTR pText, size_t TextCount, const LPCSTR *pErrorMsgs, size_t errorMsgCount, bool bRegex); void GetDxilPart(dxc::DxcDllSupport &dllSupport, IDxcBlob *pProgram, IDxcBlob **pDxilPart); std::string DisassembleProgram(dxc::DxcDllSupport &dllSupport, IDxcBlob *pProgram); void SplitPassList(LPWSTR pPassesBuffer, std::vector<LPCWSTR> &passes); void MultiByteStringToBlob(dxc::DxcDllSupport &dllSupport, const std::string &val, UINT32 codePoint, IDxcBlob **ppBlob); void MultiByteStringToBlob(dxc::DxcDllSupport &dllSupport, const std::string &val, UINT32 codePoint, IDxcBlobEncoding **ppBlob); void Utf8ToBlob(dxc::DxcDllSupport &dllSupport, const std::string &val, IDxcBlob **ppBlob); void Utf8ToBlob(dxc::DxcDllSupport &dllSupport, const std::string &val, IDxcBlobEncoding **ppBlob); void Utf8ToBlob(dxc::DxcDllSupport &dllSupport, const char *pVal, IDxcBlobEncoding **ppBlob); void WideToBlob(dxc::DxcDllSupport &dllSupport, const std::wstring &val, IDxcBlob **ppBlob); void WideToBlob(dxc::DxcDllSupport &dllSupport, const std::wstring &val, IDxcBlobEncoding **ppBlob); void VerifyCompileOK(dxc::DxcDllSupport &dllSupport, LPCSTR pText, LPCWSTR pTargetProfile, LPCWSTR pArgs, IDxcBlob **ppResult); void VerifyCompileOK(dxc::DxcDllSupport &dllSupport, LPCSTR pText, LPCWSTR pTargetProfile, std::vector<LPCWSTR> &args, IDxcBlob **ppResult); HRESULT GetVersion(dxc::DxcDllSupport &DllSupport, REFCLSID clsid, unsigned &Major, unsigned &Minor); bool ParseTargetProfile(llvm::StringRef targetProfile, llvm::StringRef &outStage, unsigned &outMajor, unsigned &outMinor); class VersionSupportInfo { private: bool m_CompilerIsDebugBuild; public: bool m_InternalValidator; unsigned m_DxilMajor, m_DxilMinor; unsigned m_ValMajor, m_ValMinor; VersionSupportInfo(); // Initialize version info structure. TODO: add device shader model support void Initialize(dxc::DxcDllSupport &dllSupport); // Return true if IR sensitive test should be skipped, and log comment bool SkipIRSensitiveTest(); // Return true if test requiring DXIL of given version should be skipped, and // log comment bool SkipDxilVersion(unsigned major, unsigned minor); // Return true if out-of-memory test should be skipped, and log comment bool SkipOutOfMemoryTest(); };
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilValidation/DxilValidation.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilValidation.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // This file provides support for validating DXIL shaders. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "dxc/DXIL/DxilConstants.h" #include "dxc/Support/Global.h" #include "dxc/WinAdapter.h" #include <memory> namespace llvm { class Module; class LLVMContext; class raw_ostream; class DiagnosticPrinter; class DiagnosticInfo; } // namespace llvm namespace hlsl { void GetValidationVersion(unsigned *pMajor, unsigned *pMinor); // Validate the container parts, assuming supplied module is valid, loaded from // the container provided struct DxilContainerHeader; HRESULT ValidateDxilContainerParts(llvm::Module *pModule, llvm::Module *pDebugModule, const DxilContainerHeader *pContainer, uint32_t ContainerSize); // Loads module, validating load, but not module. HRESULT ValidateLoadModule(const char *pIL, uint32_t ILLength, std::unique_ptr<llvm::Module> &pModule, llvm::LLVMContext &Ctx, llvm::raw_ostream &DiagStream, unsigned bLazyLoad); // Loads module from container, validating load, but not module. HRESULT ValidateLoadModuleFromContainer( const void *pContainer, uint32_t ContainerSize, std::unique_ptr<llvm::Module> &pModule, std::unique_ptr<llvm::Module> &pDebugModule, llvm::LLVMContext &Ctx, llvm::LLVMContext &DbgCtx, llvm::raw_ostream &DiagStream); // Lazy loads module from container, validating load, but not module. HRESULT ValidateLoadModuleFromContainerLazy( const void *pContainer, uint32_t ContainerSize, std::unique_ptr<llvm::Module> &pModule, std::unique_ptr<llvm::Module> &pDebugModule, llvm::LLVMContext &Ctx, llvm::LLVMContext &DbgCtx, llvm::raw_ostream &DiagStream); // Load and validate Dxil module from bitcode. HRESULT ValidateDxilBitcode(const char *pIL, uint32_t ILLength, llvm::raw_ostream &DiagStream); // Full container validation, including ValidateDxilModule HRESULT ValidateDxilContainer(const void *pContainer, uint32_t ContainerSize, llvm::raw_ostream &DiagStream); // Full container validation, including ValidateDxilModule, with debug module HRESULT ValidateDxilContainer(const void *pContainer, uint32_t ContainerSize, llvm::Module *pDebugModule, llvm::raw_ostream &DiagStream); class PrintDiagnosticContext { private: llvm::DiagnosticPrinter &m_Printer; bool m_errorsFound; bool m_warningsFound; public: PrintDiagnosticContext(llvm::DiagnosticPrinter &printer); bool HasErrors() const; bool HasWarnings() const; void Handle(const llvm::DiagnosticInfo &DI); static void PrintDiagnosticHandler(const llvm::DiagnosticInfo &DI, void *Context); }; } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilCompression/DxilCompressionHelpers.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilCompressionHelpers.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// // // Helper wrapper functions for common buffer types. // // Calling ZlibCompressAppend on a buffer appends the compressed data to the // end. If at any point the compression fails, the buffer will be shrunk to // the original size. // #include "DxilCompression.h" #include "llvm/ADT/SmallVector.h" #include <vector> namespace hlsl { template <typename Buffer> ZlibResult ZlibCompressAppend(IMalloc *pMalloc, const void *pData, size_t dataSize, Buffer &outBuffer) { static_assert(sizeof(typename Buffer::value_type) == sizeof(uint8_t), "Cannot append to a non-byte-sized buffer."); // This helper resets the buffer to its original size in case of failure or // exception class RAIIResizer { Buffer &m_Buffer; size_t m_OriginalSize; bool m_Resize = true; public: RAIIResizer(Buffer &buffer) : m_Buffer(buffer), m_OriginalSize(buffer.size()) {} ~RAIIResizer() { if (m_Resize) { m_Buffer.resize(m_OriginalSize); } } void DoNotResize() { m_Resize = false; } }; RAIIResizer resizer(outBuffer); const size_t sizeBeforeCompress = outBuffer.size(); size_t compressedDataSize = 0; ZlibResult ret = ZlibCompress( pMalloc, pData, dataSize, &outBuffer, [](void *pUserData, size_t requiredSize) -> void * { Buffer *pBuffer = (Buffer *)pUserData; const size_t lastSize = pBuffer->size(); pBuffer->resize(pBuffer->size() + requiredSize); void *ptr = pBuffer->data() + lastSize; return ptr; }, &compressedDataSize); if (ret == ZlibResult::Success) { // Resize the buffer to what was actually added to the end. outBuffer.resize(sizeBeforeCompress + compressedDataSize); resizer.DoNotResize(); } return ret; } template ZlibResult ZlibCompressAppend<llvm::SmallVectorImpl<char>>( IMalloc *pMalloc, const void *pData, size_t dataSize, llvm::SmallVectorImpl<char> &outBuffer); template ZlibResult ZlibCompressAppend<llvm::SmallVectorImpl<uint8_t>>( IMalloc *pMalloc, const void *pData, size_t dataSize, llvm::SmallVectorImpl<uint8_t> &outBuffer); template ZlibResult ZlibCompressAppend<std::vector<char>>(IMalloc *pMalloc, const void *pData, size_t dataSize, std::vector<char> &outBuffer); template ZlibResult ZlibCompressAppend<std::vector<uint8_t>>(IMalloc *pMalloc, const void *pData, size_t dataSize, std::vector<uint8_t> &outBuffer); } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilCompression/DxilCompression.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilCompression.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// // // Helper wrapper functions for zlib deflate and inflate. Entirely // self-contained, only depends on IMalloc interface. // #pragma once #include <cstddef> struct IMalloc; namespace hlsl { enum class ZlibResult { Success = 0, InvalidData = 1, OutOfMemory = 2, }; ZlibResult ZlibDecompress(IMalloc *pMalloc, const void *pCompressedBuffer, size_t BufferSizeInBytes, void *pUncompressedBuffer, size_t UncompressedBufferSize); // // This is a user-provided callback function. The compression routine does // not need to know how the destination data is being managed. For example: // appending to an std::vector. // // During compression, the routine will call this callback to request the // amount of memory required for the next segment, and then write to it. // // See DxilCompressionHelpers for example of usage. // typedef void *ZlibCallbackFn(void *pUserData, size_t RequiredSize); ZlibResult ZlibCompress(IMalloc *pMalloc, const void *pData, size_t pDataSize, void *pUserData, ZlibCallbackFn *Callback, size_t *pOutCompressedSize); } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilRootSignature/DxilRootSignature.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilRootSignature.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // HLSL root signature parsing. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #ifndef __DXC_ROOTSIGNATURE__ #define __DXC_ROOTSIGNATURE__ #include <stdint.h> #include "dxc/DXIL/DxilConstants.h" #include "dxc/WinAdapter.h" struct IDxcBlob; struct IDxcBlobEncoding; namespace llvm { class raw_ostream; } namespace hlsl { // Forward declarations. struct DxilDescriptorRange; struct DxilDescriptorRange1; struct DxilRootConstants; struct DxilRootDescriptor; struct DxilRootDescriptor1; struct DxilRootDescriptorTable; struct DxilRootDescriptorTable1; struct DxilRootParameter; struct DxilRootParameter1; struct DxilRootSignatureDesc; struct DxilRootSignatureDesc1; struct DxilStaticSamplerDesc; struct DxilVersionedRootSignatureDesc; // Constant values. static const uint32_t DxilDescriptorRangeOffsetAppend = 0xffffffff; static const uint32_t DxilSystemReservedRegisterSpaceValuesStart = 0xfffffff0; static const uint32_t DxilSystemReservedRegisterSpaceValuesEnd = 0xffffffff; #define DxilMipLodBiaxMax (15.99f) #define DxilMipLodBiaxMin (-16.0f) #define DxilFloat32Max (3.402823466e+38f) static const uint32_t DxilMipLodFractionalBitCount = 8; static const uint32_t DxilMapAnisotropy = 16; // Enumerations and flags. enum class DxilComparisonFunc : unsigned { Never = 1, Less = 2, Equal = 3, LessEqual = 4, Greater = 5, NotEqual = 6, GreaterEqual = 7, Always = 8 }; enum class DxilDescriptorRangeFlags : unsigned { None = 0, DescriptorsVolatile = 0x1, DataVolatile = 0x2, DataStaticWhileSetAtExecute = 0x4, DataStatic = 0x8, DescriptorsStaticKeepingBufferBoundsChecks = 0x10000, ValidFlags = 0x1000f, ValidSamplerFlags = DescriptorsVolatile }; enum class DxilDescriptorRangeType : unsigned { SRV = 0, UAV = 1, CBV = 2, Sampler = 3, MaxValue = 3 }; enum class DxilRootDescriptorFlags : unsigned { None = 0, DataVolatile = 0x2, DataStaticWhileSetAtExecute = 0x4, DataStatic = 0x8, ValidFlags = 0xe }; enum class DxilRootSignatureVersion { Version_1 = 1, Version_1_0 = 1, Version_1_1 = 2 }; enum class DxilRootSignatureCompilationFlags { None = 0x0, LocalRootSignature = 0x1, GlobalRootSignature = 0x2, }; enum class DxilRootSignatureFlags : uint32_t { None = 0, AllowInputAssemblerInputLayout = 0x1, DenyVertexShaderRootAccess = 0x2, DenyHullShaderRootAccess = 0x4, DenyDomainShaderRootAccess = 0x8, DenyGeometryShaderRootAccess = 0x10, DenyPixelShaderRootAccess = 0x20, AllowStreamOutput = 0x40, LocalRootSignature = 0x80, DenyAmplificationShaderRootAccess = 0x100, DenyMeshShaderRootAccess = 0x200, CBVSRVUAVHeapDirectlyIndexed = 0x400, SamplerHeapDirectlyIndexed = 0x800, AllowLowTierReservedHwCbLimit = 0x80000000, ValidFlags = 0x80000fff }; enum class DxilRootParameterType { DescriptorTable = 0, Constants32Bit = 1, CBV = 2, SRV = 3, UAV = 4, MaxValue = 4 }; enum class DxilFilter { // TODO: make these names consistent with code convention MIN_MAG_MIP_POINT = 0, MIN_MAG_POINT_MIP_LINEAR = 0x1, MIN_POINT_MAG_LINEAR_MIP_POINT = 0x4, MIN_POINT_MAG_MIP_LINEAR = 0x5, MIN_LINEAR_MAG_MIP_POINT = 0x10, MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x11, MIN_MAG_LINEAR_MIP_POINT = 0x14, MIN_MAG_MIP_LINEAR = 0x15, ANISOTROPIC = 0x55, COMPARISON_MIN_MAG_MIP_POINT = 0x80, COMPARISON_MIN_MAG_POINT_MIP_LINEAR = 0x81, COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x84, COMPARISON_MIN_POINT_MAG_MIP_LINEAR = 0x85, COMPARISON_MIN_LINEAR_MAG_MIP_POINT = 0x90, COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x91, COMPARISON_MIN_MAG_LINEAR_MIP_POINT = 0x94, COMPARISON_MIN_MAG_MIP_LINEAR = 0x95, COMPARISON_ANISOTROPIC = 0xd5, MINIMUM_MIN_MAG_MIP_POINT = 0x100, MINIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x101, MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x104, MINIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x105, MINIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x110, MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x111, MINIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x114, MINIMUM_MIN_MAG_MIP_LINEAR = 0x115, MINIMUM_ANISOTROPIC = 0x155, MAXIMUM_MIN_MAG_MIP_POINT = 0x180, MAXIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x181, MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x184, MAXIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x185, MAXIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x190, MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x191, MAXIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x194, MAXIMUM_MIN_MAG_MIP_LINEAR = 0x195, MAXIMUM_ANISOTROPIC = 0x1d5 }; enum class DxilShaderVisibility { All = 0, Vertex = 1, Hull = 2, Domain = 3, Geometry = 4, Pixel = 5, Amplification = 6, Mesh = 7, MaxValue = 7 }; enum class DxilStaticBorderColor { TransparentBlack = 0, OpaqueBlack = 1, OpaqueWhite = 2, OpaqueBlackUint = 3, OpaqueWhiteUint = 4 }; enum class DxilTextureAddressMode { Wrap = 1, Mirror = 2, Clamp = 3, Border = 4, MirrorOnce = 5 }; // Structure definitions for serialized structures. #pragma pack(push, 1) struct DxilContainerRootDescriptor1 { uint32_t ShaderRegister; uint32_t RegisterSpace; uint32_t Flags; }; struct DxilContainerDescriptorRange { uint32_t RangeType; uint32_t NumDescriptors; uint32_t BaseShaderRegister; uint32_t RegisterSpace; uint32_t OffsetInDescriptorsFromTableStart; }; struct DxilContainerDescriptorRange1 { uint32_t RangeType; uint32_t NumDescriptors; uint32_t BaseShaderRegister; uint32_t RegisterSpace; uint32_t Flags; uint32_t OffsetInDescriptorsFromTableStart; }; struct DxilContainerRootDescriptorTable { uint32_t NumDescriptorRanges; uint32_t DescriptorRangesOffset; }; struct DxilContainerRootParameter { uint32_t ParameterType; uint32_t ShaderVisibility; uint32_t PayloadOffset; }; struct DxilContainerRootSignatureDesc { uint32_t Version; uint32_t NumParameters; uint32_t RootParametersOffset; uint32_t NumStaticSamplers; uint32_t StaticSamplersOffset; uint32_t Flags; }; #pragma pack(pop) // Structure definitions for in-memory structures. struct DxilDescriptorRange { DxilDescriptorRangeType RangeType; uint32_t NumDescriptors; uint32_t BaseShaderRegister; uint32_t RegisterSpace; uint32_t OffsetInDescriptorsFromTableStart; }; struct DxilRootDescriptorTable { uint32_t NumDescriptorRanges; DxilDescriptorRange *pDescriptorRanges; }; struct DxilRootConstants { uint32_t ShaderRegister; uint32_t RegisterSpace; uint32_t Num32BitValues; }; struct DxilRootDescriptor { uint32_t ShaderRegister; uint32_t RegisterSpace; }; struct DxilRootDescriptor1 { uint32_t ShaderRegister; uint32_t RegisterSpace; DxilRootDescriptorFlags Flags; }; struct DxilRootParameter { DxilRootParameterType ParameterType; union { DxilRootDescriptorTable DescriptorTable; DxilRootConstants Constants; DxilRootDescriptor Descriptor; }; DxilShaderVisibility ShaderVisibility; }; struct DxilDescriptorRange1 { DxilDescriptorRangeType RangeType; uint32_t NumDescriptors; uint32_t BaseShaderRegister; uint32_t RegisterSpace; DxilDescriptorRangeFlags Flags; uint32_t OffsetInDescriptorsFromTableStart; }; struct DxilRootDescriptorTable1 { uint32_t NumDescriptorRanges; DxilDescriptorRange1 *pDescriptorRanges; }; struct DxilRootParameter1 { DxilRootParameterType ParameterType; union { DxilRootDescriptorTable1 DescriptorTable; DxilRootConstants Constants; DxilRootDescriptor1 Descriptor; }; DxilShaderVisibility ShaderVisibility; }; struct DxilRootSignatureDesc { uint32_t NumParameters; DxilRootParameter *pParameters; uint32_t NumStaticSamplers; DxilStaticSamplerDesc *pStaticSamplers; DxilRootSignatureFlags Flags; }; struct DxilStaticSamplerDesc { DxilFilter Filter; DxilTextureAddressMode AddressU; DxilTextureAddressMode AddressV; DxilTextureAddressMode AddressW; float MipLODBias; uint32_t MaxAnisotropy; DxilComparisonFunc ComparisonFunc; DxilStaticBorderColor BorderColor; float MinLOD; float MaxLOD; uint32_t ShaderRegister; uint32_t RegisterSpace; DxilShaderVisibility ShaderVisibility; }; struct DxilRootSignatureDesc1 { uint32_t NumParameters; DxilRootParameter1 *pParameters; uint32_t NumStaticSamplers; DxilStaticSamplerDesc *pStaticSamplers; DxilRootSignatureFlags Flags; }; struct DxilVersionedRootSignatureDesc { DxilRootSignatureVersion Version; union { DxilRootSignatureDesc Desc_1_0; DxilRootSignatureDesc1 Desc_1_1; }; }; void printRootSignature(const DxilVersionedRootSignatureDesc &RS, llvm::raw_ostream &os); // Use this class to represent a root signature that may be in memory or // serialized. There is just enough API surface to help callers not take a // dependency on Windows headers. class RootSignatureHandle { private: const DxilVersionedRootSignatureDesc *m_pDesc; IDxcBlob *m_pSerialized; public: RootSignatureHandle() : m_pDesc(nullptr), m_pSerialized(nullptr) {} RootSignatureHandle(const RootSignatureHandle &) = delete; RootSignatureHandle(RootSignatureHandle &&other); ~RootSignatureHandle() { Clear(); } bool IsEmpty() const { return m_pDesc == nullptr && m_pSerialized == nullptr; } IDxcBlob *GetSerialized() const { return m_pSerialized; } const uint8_t *GetSerializedBytes() const; unsigned GetSerializedSize() const; void Assign(const DxilVersionedRootSignatureDesc *pDesc, IDxcBlob *pSerialized); void Clear(); void LoadSerialized(const uint8_t *pData, uint32_t length); void EnsureSerializedAvailable(); void Deserialize(); const DxilVersionedRootSignatureDesc *GetDesc() const { return m_pDesc; } }; void DeleteRootSignature(const DxilVersionedRootSignatureDesc *pRootSignature); // Careful to delete: returns the original root signature, if conversion is not // required. void ConvertRootSignature( const DxilVersionedRootSignatureDesc *pRootSignatureIn, DxilRootSignatureVersion RootSignatureVersionOut, const DxilVersionedRootSignatureDesc **ppRootSignatureOut); void SerializeRootSignature( const DxilVersionedRootSignatureDesc *pRootSignature, IDxcBlob **ppBlob, IDxcBlobEncoding **ppErrorBlob, bool bAllowReservedRegisterSpace); void DeserializeRootSignature( const void *pSrcData, uint32_t SrcDataSizeInBytes, const DxilVersionedRootSignatureDesc **ppRootSignature); // Takes PSV - pipeline state validation data, not shader container. bool VerifyRootSignatureWithShaderPSV( const DxilVersionedRootSignatureDesc *pDesc, DXIL::ShaderKind ShaderKind, const void *pPSVData, uint32_t PSVSize, llvm::raw_ostream &DiagStream); // standalone verification bool VerifyRootSignature(const DxilVersionedRootSignatureDesc *pDesc, llvm::raw_ostream &DiagStream, bool bAllowReservedRegisterSpace); class DxilVersionedRootSignature { DxilVersionedRootSignatureDesc *m_pRootSignature; public: // Non-copyable: DxilVersionedRootSignature(DxilVersionedRootSignature const &) = delete; DxilVersionedRootSignature const & operator=(DxilVersionedRootSignature const &) = delete; // but movable: DxilVersionedRootSignature(DxilVersionedRootSignature &&) = default; DxilVersionedRootSignature & operator=(DxilVersionedRootSignature &&) = default; DxilVersionedRootSignature() : m_pRootSignature(nullptr) {} explicit DxilVersionedRootSignature( const DxilVersionedRootSignatureDesc *pRootSignature) : m_pRootSignature( const_cast<DxilVersionedRootSignatureDesc *>(pRootSignature)) {} ~DxilVersionedRootSignature() { DeleteRootSignature(m_pRootSignature); } const DxilVersionedRootSignatureDesc *operator->() const { return m_pRootSignature; } const DxilVersionedRootSignatureDesc **get_address_of() { if (m_pRootSignature != nullptr) return nullptr; // You're probably about to leak... return const_cast<const DxilVersionedRootSignatureDesc **>( &m_pRootSignature); } const DxilVersionedRootSignatureDesc *get() const { return m_pRootSignature; } DxilVersionedRootSignatureDesc *get_mutable() const { return m_pRootSignature; } }; } // namespace hlsl #endif // __DXC_ROOTSIGNATURE__
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxilPdbInfo/DxilPdbInfoWriter.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilPdbInfoWriter.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// // // Helper for writing a valid hlsl::DxilShaderPDBInfo part // #pragma once #include "dxc/Support/Global.h" #include <vector> struct IMalloc; namespace hlsl { HRESULT WritePdbInfoPart(IMalloc *pMalloc, const void *pUncompressedPdbInfoData, size_t size, std::vector<char> *outBuffer); }
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/DxcBindingTable/DxcBindingTable.h
/////////////////////////////////////////////////////////////////////////////// // // // DxcBindingTable.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "dxc/DXIL/DxilConstants.h" #include "llvm/ADT/StringRef.h" #include <map> #include <string> namespace llvm { class raw_ostream; class Module; } // namespace llvm namespace hlsl { class DxilModule; } namespace hlsl { struct DxcBindingTable { typedef std::pair<std::string, hlsl::DXIL::ResourceClass> Key; struct Entry { unsigned index = UINT_MAX; unsigned space = UINT_MAX; }; std::map<Key, Entry> entries; }; bool ParseBindingTable(llvm::StringRef fileName, llvm::StringRef content, llvm::raw_ostream &errors, DxcBindingTable *outTable); void WriteBindingTableToMetadata(llvm::Module &M, const DxcBindingTable &table); void ApplyBindingTableFromMetadata(hlsl::DxilModule &DM); } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/Tracing/CMakeLists.txt
# Copyright (C) Microsoft Corporation. All rights reserved. # This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. # Generate ETW instrumentation. # Create the header in a temporary file and only update when necessary, # to avoid invalidating targets that depend on it. add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/tmpdxcetw.h COMMAND mc -r ${CMAKE_CURRENT_BINARY_DIR} -h ${CMAKE_CURRENT_BINARY_DIR} -p DxcEtw_ -um -z tmpdxcetw ${CMAKE_CURRENT_SOURCE_DIR}/dxcetw.man DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/dxcetw.man COMMENT "Building instrumentation manifest ..." ) add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/dxcetw.h COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_BINARY_DIR}/tmpdxcetw.h ${CMAKE_CURRENT_BINARY_DIR}/dxcetw.h COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_BINARY_DIR}/tmpdxcetw.rc ${CMAKE_CURRENT_BINARY_DIR}/dxcetw.rc COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_BINARY_DIR}/tmpdxcetwTEMP.bin ${CMAKE_CURRENT_BINARY_DIR}/dxcetwTEMP.bin COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_BINARY_DIR}/tmpdxcetw_MSG00001.bin ${CMAKE_CURRENT_BINARY_DIR}/MSG00001.bin DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/tmpdxcetw.h COMMENT "Updating instrumentation manifest ..." ) set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/dxcetw.h PROPERTIES GENERATED 1) set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/dxcetw.rc PROPERTIES GENERATED 1) set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/dxcetwTEMP.bin PROPERTIES GENERATED 1) set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/MSG00001.bin PROPERTIES GENERATED 1) add_custom_target(DxcEtw DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/dxcetw.h SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/dxcetw.man ) # Not quite tablegen, but close enough. set_target_properties(DxcEtw PROPERTIES FOLDER "Tablegenning")
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/HLSL/HLMatrixLowerHelper.h
/////////////////////////////////////////////////////////////////////////////// // // // HLMatrixLowerHelper.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // This file provides helper functions to lower high level matrix. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "llvm/IR/IRBuilder.h" namespace llvm { class Type; class Value; template <typename T> class ArrayRef; } // namespace llvm namespace hlsl { class DxilFieldAnnotation; class DxilTypeSystem; namespace HLMatrixLower { llvm::Value *BuildVector(llvm::Type *EltTy, llvm::ArrayRef<llvm::Value *> elts, llvm::IRBuilder<> &Builder); } // namespace HLMatrixLower } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/HLSL/DxilFallbackLayerPass.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilFallbackLayerPass.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // This file provides passes used by the Ray Tracing Fallback Layer // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "llvm/Pass.h" namespace llvm { ModulePass *createDxilUpdateMetadataPass(); ModulePass *createDxilPatchShaderRecordBindingsPass(); void initializeDxilUpdateMetadataPass(llvm::PassRegistry &); void initializeDxilPatchShaderRecordBindingsPass(llvm::PassRegistry &); } // namespace llvm
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/HLSL/DxilSignatureAllocator.inl
/////////////////////////////////////////////////////////////////////////////// // // // DxilSignatureAllocator.inl // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// //#include "dxc/Support/Global.h" // for DXASSERT //#include "dxc/HLSL/DxilSignatureAllocator.h" using std::sort; // #include <algorithm> using std::unique_ptr; // #include <memory> using std::vector; // #include <vector> namespace hlsl { //------------------------------------------------------------------------------ // // DxilSignatureAllocator methods. // uint8_t DxilSignatureAllocator::GetElementFlags(const PackElement *SE) { uint8_t flags = 0; DXIL::SemanticInterpretationKind interpretation = SE->GetInterpretation(); switch (interpretation) { case DXIL::SemanticInterpretationKind::Arb: flags |= kEFArbitrary; break; case DXIL::SemanticInterpretationKind::SV: flags |= kEFSV; break; case DXIL::SemanticInterpretationKind::SGV: flags |= kEFSGV; break; case DXIL::SemanticInterpretationKind::TessFactor: flags |= kEFTessFactor; break; case DXIL::SemanticInterpretationKind::ClipCull: flags |= kEFClipCull; break; default: DXASSERT(false, "otherwise, unexpected interpretation for allocated element"); } return flags; } // The following two functions enforce the rules of component ordering when // packing different kinds of elements into the same register. // given element flags, return element flags that conflict when placed to the // left of the element uint8_t DxilSignatureAllocator::GetConflictFlagsLeft(uint8_t flags) { uint8_t conflicts = 0; if (flags & kEFArbitrary) conflicts |= kEFSGV | kEFSV | kEFTessFactor | kEFClipCull; if (flags & kEFSV) conflicts |= kEFSGV; if (flags & kEFTessFactor) conflicts |= kEFSGV; if (flags & kEFClipCull) conflicts |= kEFSGV; return conflicts; } // given element flags, return element flags that conflict when placed to the // right of the element uint8_t DxilSignatureAllocator::GetConflictFlagsRight(uint8_t flags) { uint8_t conflicts = 0; if (flags & kEFSGV) conflicts |= kEFArbitrary | kEFSV | kEFTessFactor | kEFClipCull; if (flags & kEFSV) conflicts |= kEFArbitrary; if (flags & kEFTessFactor) conflicts |= kEFArbitrary; if (flags & kEFClipCull) conflicts |= kEFArbitrary; return conflicts; } DxilSignatureAllocator::PackedRegister::PackedRegister() : Interp(DXIL::InterpolationMode::Undefined), IndexFlags(0), IndexingFixed(0), DataWidth(DXIL::SignatureDataWidth::Undefined) { for (unsigned i = 0; i < 4; ++i) Flags[i] = 0; } DxilSignatureAllocator::ConflictType DxilSignatureAllocator::PackedRegister::DetectRowConflict( uint8_t flags, uint8_t indexFlags, DXIL::InterpolationMode interp, unsigned width, DXIL::SignatureDataWidth dataWidth) { // indexing already present, and element incompatible with indexing if (IndexFlags && (flags & kEFConflictsWithIndexed)) return kConflictsWithIndexed; // indexing cannot be changed, and element indexing is incompatible when // merged if (IndexingFixed && (indexFlags | IndexFlags) != IndexFlags) return kConflictsWithIndexed; if ((flags & kEFTessFactor) && (indexFlags | IndexFlags) != indexFlags) return kConflictsWithIndexedTessFactor; if (Interp != DXIL::InterpolationMode::Undefined && Interp != interp) return kConflictsWithInterpolationMode; if (DataWidth != DXIL::SignatureDataWidth::Undefined && DataWidth != dataWidth) return kConflictDataWidth; unsigned freeWidth = 0; for (unsigned i = 0; i < 4; ++i) { if ((Flags[i] & kEFOccupied) || (Flags[i] & flags)) freeWidth = 0; else ++freeWidth; if (width <= freeWidth) break; } if (width > freeWidth) return kInsufficientFreeComponents; return kNoConflict; } DxilSignatureAllocator::ConflictType DxilSignatureAllocator::PackedRegister::DetectColConflict(uint8_t flags, unsigned col, unsigned width) { if (col + width > 4) return kConflictFit; flags |= kEFOccupied; for (unsigned i = col; i < col + width; ++i) { if (flags & Flags[i]) { if (Flags[i] & kEFOccupied) return kOverlapElement; else return kIllegalComponentOrder; } } return kNoConflict; } void DxilSignatureAllocator::PackedRegister::PlaceElement( uint8_t flags, uint8_t indexFlags, DXIL::InterpolationMode interp, unsigned col, unsigned width, DXIL::SignatureDataWidth dataWidth) { // Assume no conflicts (DetectRowConflict and DetectColConflict both return // 0). Interp = interp; IndexFlags |= indexFlags; DataWidth = dataWidth; if ((flags & kEFConflictsWithIndexed) || (flags & kEFTessFactor)) { DXASSERT(indexFlags == IndexFlags, "otherwise, bug in DetectRowConflict checking index flags"); IndexingFixed = 1; } uint8_t conflictLeft = GetConflictFlagsLeft(flags); uint8_t conflictRight = GetConflictFlagsRight(flags); for (unsigned i = 0; i < 4; ++i) { if ((Flags[i] & kEFOccupied) == 0) { if (i < col) Flags[i] |= conflictLeft; else if (i < col + width) Flags[i] = kEFOccupied | flags; else Flags[i] |= conflictRight; } } } DxilSignatureAllocator::DxilSignatureAllocator(unsigned numRegisters, bool useMinPrecision) : m_bIgnoreIndexing(false), m_bUseMinPrecision(useMinPrecision) { m_Registers.resize(numRegisters); } DxilSignatureAllocator::ConflictType DxilSignatureAllocator::DetectRowConflict(const PackElement *SE, unsigned row) { unsigned rows = SE->GetRows(); if (rows + row > m_Registers.size()) return kConflictFit; unsigned cols = SE->GetCols(); DXIL::InterpolationMode interp = SE->GetInterpolationMode(); uint8_t flags = GetElementFlags(SE); for (unsigned i = 0; i < rows; ++i) { uint8_t indexFlags = m_bIgnoreIndexing ? 0 : GetIndexFlags(i, rows); ConflictType conflict = m_Registers[row + i].DetectRowConflict( flags, indexFlags, interp, cols, SE->GetDataBitWidth()); if (conflict) return conflict; } return kNoConflict; } DxilSignatureAllocator::ConflictType DxilSignatureAllocator::DetectColConflict(const PackElement *SE, unsigned row, unsigned col) { unsigned rows = SE->GetRows(); unsigned cols = SE->GetCols(); uint8_t flags = GetElementFlags(SE); for (unsigned i = 0; i < rows; ++i) { ConflictType conflict = m_Registers[row + i].DetectColConflict(flags, col, cols); if (conflict) return conflict; } return kNoConflict; } void DxilSignatureAllocator::PlaceElement(const PackElement *SE, unsigned row, unsigned col) { // Assume no conflicts (DetectRowConflict and DetectColConflict both return // 0). unsigned rows = SE->GetRows(); unsigned cols = SE->GetCols(); DXIL::InterpolationMode interp = SE->GetInterpolationMode(); uint8_t flags = GetElementFlags(SE); for (unsigned i = 0; i < rows; ++i) { uint8_t indexFlags = m_bIgnoreIndexing ? 0 : GetIndexFlags(i, rows); m_Registers[row + i].PlaceElement(flags, indexFlags, interp, col, cols, SE->GetDataBitWidth()); } } namespace { template <typename T> int cmp(T a, T b) { if (a < b) return -1; if (b < a) return 1; return 0; } int CmpElements(const DxilSignatureAllocator::PackElement *left, const DxilSignatureAllocator::PackElement *right) { unsigned result; result = cmp((unsigned)left->GetInterpolationMode(), (unsigned)right->GetInterpolationMode()); if (result) return result; result = -cmp(left->GetRows(), right->GetRows()); if (result) return result; result = -cmp(left->GetCols(), right->GetCols()); if (result) return result; result = cmp(left->GetID(), right->GetID()); if (result) return result; return 0; } struct { bool operator()(const DxilSignatureAllocator::PackElement *left, const DxilSignatureAllocator::PackElement *right) { return CmpElements(left, right) < 0; } } CmpElementsLess; } // anonymous namespace unsigned DxilSignatureAllocator::FindNext(unsigned &foundRow, unsigned &foundCol, PackElement *SE, unsigned startRow, unsigned numRows, unsigned startCol) { unsigned rows = SE->GetRows(); if (rows > numRows) return 0; // element will not fit unsigned cols = SE->GetCols(); DXASSERT_NOMSG(startCol + cols <= 4); for (unsigned row = startRow; row <= (startRow + numRows - rows); ++row) { if (DetectRowConflict(SE, row)) continue; for (unsigned col = startCol; col <= 4 - cols; ++col) { if (DetectColConflict(SE, row, col)) continue; foundRow = row; foundCol = col; return row + rows; } } return 0; } unsigned DxilSignatureAllocator::PackNext(PackElement *SE, unsigned startRow, unsigned numRows, unsigned startCol) { unsigned row, col; unsigned rowsUsed = FindNext(row, col, SE, startRow, numRows, startCol); if (rowsUsed) { PlaceElement(SE, row, col); SE->SetLocation(row, col); } return rowsUsed; } unsigned DxilSignatureAllocator::PackGreedy(std::vector<PackElement *> elements, unsigned startRow, unsigned numRows, unsigned startCol) { // Allocation failures should be caught by IsFullyAllocated() unsigned rowsUsed = 0; for (auto &SE : elements) { rowsUsed = std::max(rowsUsed, PackNext(SE, startRow, numRows, startCol)); } return rowsUsed; } static_assert(DXIL::kMaxClipOrCullDistanceElementCount == 2, "code here assumes this is 2"); unsigned DxilSignatureAllocator::PackOptimized(std::vector<PackElement *> elements, unsigned startRow, unsigned numRows) { unsigned rowsUsed = 0; // Clip/Cull needs special handling due to limitations unique to these. // Otherwise, packer could easily pack across too many registers in available // gaps. // The rules are special/weird: // - for interpolation mode, clip must be linear or linearCentroid, while // cull may be anything // - both have a maximum of 8 components shared between them // - you can have a combined maximum of two registers declared with clip or // cull SV's // other SV rules still apply: // - X no indexing allowed X - This rule has been changed to allow indexing // - cannot come before arbitrary values in same register // Strategy for dealing with these with rows == 1 for all elements: // - attempt to pack these into a two register allocator // - if this fails, some constraint is blocking, or declaration order is // preventing good packing for example: 2, 1, 2, 3 - total 8 components // and packable, but if greedily packed, it will fail Packing largest to // smallest would solve this. // - track components used for each register and create temp elements for // allocation tests // - iterate rows and look for a viable location for each temp element // When found, allocate original sub-elements associated with temp element. // If one or more clip/cull elements have rows > 1: // - walk through each pair of adjacent rows, initializing a temp two-row // allocator with existing contents and trying to pack all elements into // the remaining space. // - when successful, do real allocation into these rows. // Packing overview // - pack 4-component elements first // - pack indexed tessfactors to the right // - pack arbitrary elements // - pack system value elements // - pack clip/cull // - pack SGV elements // ========== // Group elements std::vector<PackElement *> clipcullElements, clipcullElementsByRow[DXIL::kMaxClipOrCullDistanceElementCount], vec4Elements, arbElements, svElements, sgvElements, indexedtessElements; for (auto &SE : elements) { // Clear any existing allocation if (SE->IsAllocated()) { SE->ClearLocation(); } switch (SE->GetInterpretation()) { case DXIL::SemanticInterpretationKind::Arb: if (SE->GetCols() == 4) vec4Elements.push_back(SE); else arbElements.push_back(SE); break; case DXIL::SemanticInterpretationKind::ClipCull: clipcullElements.push_back(SE); break; case DXIL::SemanticInterpretationKind::SV: if (SE->GetCols() == 4) vec4Elements.push_back(SE); else svElements.push_back(SE); break; case DXIL::SemanticInterpretationKind::SGV: sgvElements.push_back(SE); break; case DXIL::SemanticInterpretationKind::TessFactor: if (SE->GetRows() > 1) indexedtessElements.push_back(SE); else svElements.push_back(SE); break; default: DXASSERT(false, "otherwise, unexpected interpretation for allocated element"); } } // ========== // Allocate 4-component elements if (!vec4Elements.empty()) { std::sort(vec4Elements.begin(), vec4Elements.end(), CmpElementsLess); rowsUsed = std::max(rowsUsed, PackGreedy(vec4Elements, startRow, numRows)); startRow = std::max(startRow, rowsUsed); } // ========== // Allocate indexed tessfactors in rightmost column if (!indexedtessElements.empty()) { std::sort(indexedtessElements.begin(), indexedtessElements.end(), CmpElementsLess); rowsUsed = std::max(rowsUsed, PackGreedy(indexedtessElements, startRow, numRows, 3)); } // ========== // Allocate arbitrary if (!arbElements.empty()) { std::sort(arbElements.begin(), arbElements.end(), CmpElementsLess); rowsUsed = std::max(rowsUsed, PackGreedy(arbElements, startRow, numRows)); } // ========== // Allocate system values if (!svElements.empty()) { std::sort(svElements.begin(), svElements.end(), CmpElementsLess); rowsUsed = std::max(rowsUsed, PackGreedy(svElements, startRow, numRows)); } // ========== // Allocate clip/cull std::sort(clipcullElements.begin(), clipcullElements.end(), CmpElementsLess); unsigned numClipCullComponents = 0; unsigned clipCullMultiRowCols = 0; for (auto &SE : clipcullElements) { numClipCullComponents += SE->GetRows() * SE->GetCols(); if (SE->GetRows() > 1) { clipCullMultiRowCols += SE->GetCols(); } } if (0 == clipCullMultiRowCols) { // Preallocate clip/cull elements into two rows and allocate independently DxilSignatureAllocator clipcullAllocator( DXIL::kMaxClipOrCullDistanceElementCount, m_bUseMinPrecision); unsigned clipcullRegUsed = clipcullAllocator.PackGreedy( clipcullElements, 0, DXIL::kMaxClipOrCullDistanceElementCount); unsigned clipcullComponentsByRow[DXIL::kMaxClipOrCullDistanceElementCount] = {0, 0}; for (auto &SE : clipcullElements) { if (!SE->IsAllocated()) { continue; } unsigned row = SE->GetStartRow(); DXASSERT_NOMSG(row < clipcullRegUsed); clipcullElementsByRow[row].push_back(SE); clipcullComponentsByRow[row] += SE->GetCols(); // Deallocate element, to be allocated later: SE->ClearLocation(); } // Allocate rows independently // Init temp elements, used to find compatible spaces for subsets: DummyElement clipcullTempElements[DXIL::kMaxClipOrCullDistanceElementCount]; for (unsigned row = 0; row < clipcullRegUsed; ++row) { DXASSERT_NOMSG(!clipcullElementsByRow[row].empty()); clipcullTempElements[row].kind = clipcullElementsByRow[row][0]->GetKind(); clipcullTempElements[row].interpolation = clipcullElementsByRow[row][0]->GetInterpolationMode(); clipcullTempElements[row].interpretation = clipcullElementsByRow[row][0]->GetInterpretation(); clipcullTempElements[row].dataBitWidth = clipcullElementsByRow[row][0]->GetDataBitWidth(); clipcullTempElements[row].rows = 1; clipcullTempElements[row].cols = clipcullComponentsByRow[row]; } for (unsigned i = 0; i < clipcullRegUsed; ++i) { bool bAllocated = false; unsigned cols = clipcullComponentsByRow[i]; for (unsigned row = startRow; row < startRow + numRows; ++row) { if (DetectRowConflict(&clipcullTempElements[i], row)) continue; for (unsigned col = 0; col <= 4 - cols; ++col) { if (DetectColConflict(&clipcullTempElements[i], row, col)) continue; for (auto &SE : clipcullElementsByRow[i]) { PlaceElement(SE, row, col); SE->SetLocation(row, col); col += SE->GetCols(); } bAllocated = true; if (rowsUsed < row + 1) rowsUsed = row + 1; break; } if (bAllocated) break; } } } else if (numRows > 1) { // Multi-row clip/cull element found, test allocation at each pair of // rows. If location found, allocate the elements. for (unsigned i = 0; i < numRows - 1; ++i) { unsigned row = startRow + i; // Use temp allocator with copy of rows to test locations DxilSignatureAllocator clipcullAllocator( DXIL::kMaxClipOrCullDistanceElementCount, m_bUseMinPrecision); clipcullAllocator.m_Registers[0] = m_Registers[row]; clipcullAllocator.m_Registers[1] = m_Registers[row + 1]; clipcullAllocator.PackGreedy(clipcullElements, 0, DXIL::kMaxClipOrCullDistanceElementCount, 0); bool bFullyAllocated = true; for (auto &SE : clipcullElements) { bFullyAllocated &= SE->IsAllocated(); if (!bFullyAllocated) break; } // Clear temp allocations for (auto &SE : clipcullElements) SE->ClearLocation(); if (bFullyAllocated) { // Found a spot, do real allocation PackGreedy(clipcullElements, row, DXIL::kMaxClipOrCullDistanceElementCount); #ifndef NDEBUG for (auto &SE : clipcullElements) { bFullyAllocated &= SE->IsAllocated(); if (!bFullyAllocated) break; } DXASSERT(bFullyAllocated, "otherwise, clip/cull allocation failed when " "predicted to succeed."); #endif break; } } } // ========== // Allocate system generated values if (!sgvElements.empty()) { std::sort(sgvElements.begin(), sgvElements.end(), CmpElementsLess); rowsUsed = std::max(rowsUsed, PackGreedy(sgvElements, startRow, numRows)); } return rowsUsed; } unsigned DxilSignatureAllocator::PackPrefixStable(std::vector<PackElement *> elements, unsigned startRow, unsigned numRows) { unsigned rowsUsed = 0; // Special handling for prefix-stable clip/cull arguments // - basically, do not pack with anything else to maximize chance to pack into // two register limit // - this is complicated by multi-row clip/cull elements, which force // allocation adjacency, // but PrefixStable does not know in advance if this will be the case. unsigned clipcullRegUsed = 0; bool clipcullIndexed = false; DxilSignatureAllocator clipcullAllocator( DXIL::kMaxClipOrCullDistanceElementCount, m_bUseMinPrecision); DummyElement clipcullTempElements[DXIL::kMaxClipOrCullDistanceElementCount]; for (auto &SE : elements) { // Clear any existing allocation if (SE->IsAllocated()) { SE->ClearLocation(); } switch (SE->GetInterpretation()) { case DXIL::SemanticInterpretationKind::Arb: case DXIL::SemanticInterpretationKind::SGV: break; case DXIL::SemanticInterpretationKind::SV: break; case DXIL::SemanticInterpretationKind::ClipCull: { unsigned row, col; unsigned used = clipcullAllocator.FindNext( row, col, SE, 0, DXIL::kMaxClipOrCullDistanceElementCount); if (!used) continue; if (SE->GetRows() > 1 && !clipcullIndexed) { // If two rows already allocated, they must be adjacent to // pack indexed elements. if (clipcullRegUsed == DXIL::kMaxClipOrCullDistanceElementCount && clipcullTempElements[0].row + 1 != clipcullTempElements[1].row) continue; clipcullIndexed = true; } // If necessary, allocate placeholder element to reserve space in // signature: if (used > clipcullRegUsed) { auto &DE = clipcullTempElements[clipcullRegUsed]; DE.kind = SE->GetKind(); DE.interpolation = SE->GetInterpolationMode(); DE.interpretation = SE->GetInterpretation(); DE.dataBitWidth = SE->GetDataBitWidth(); DE.rows = 1; DE.cols = 4; if (clipcullIndexed) { // Either allocate one 2-row placeholder element, or allocate on // adjacent row. if (clipcullRegUsed < 1) { // Allocate one element with 2 rows DE.rows = DXIL::kMaxClipOrCullDistanceElementCount; rowsUsed = std::max(rowsUsed, PackNext(&DE, startRow, numRows)); if (!DE.IsAllocated()) continue; // Init second placeholder element to next row because it's used to // adjust element locations starting on that row. clipcullTempElements[1] = DE; clipcullTempElements[1].row = DE.row + 1; clipcullTempElements[1].rows = 1; } else { DXASSERT_NOMSG(clipcullRegUsed == 1); // Make sure additional element can be placed just after other // element, otherwise fail to allocate this element. rowsUsed = std::max(rowsUsed, PackNext(&DE, clipcullTempElements[0].row + 1, clipcullTempElements[0].row + 2)); if (!DE.IsAllocated()) continue; } clipcullRegUsed = DXIL::kMaxClipOrCullDistanceElementCount; } else { // allocate placeholder element, reserving new row(s) rowsUsed = std::max(rowsUsed, PackNext(&DE, startRow, numRows)); if (!DE.IsAllocated()) continue; clipcullRegUsed = used; } } // Place element in temp allocator and adjust row for signature clipcullAllocator.PlaceElement(SE, row, col); SE->SetLocation(clipcullTempElements[row].GetStartRow(), col); continue; } break; case DXIL::SemanticInterpretationKind::TessFactor: if (SE->GetRows() > 1) { // Maximize opportunity for packing while preserving prefix-stable // property rowsUsed = std::max(rowsUsed, PackNext(SE, startRow, numRows, 3)); continue; } break; default: DXASSERT(false, "otherwise, unexpected interpretation for allocated element"); } rowsUsed = std::max(rowsUsed, PackNext(SE, startRow, numRows)); } return rowsUsed; } } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/HLSL/DxilNoops.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilNoops.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "llvm/ADT/StringRef.h" namespace llvm { class Instruction; } namespace hlsl { static const llvm::StringRef kNoopName = "dx.noop"; static const llvm::StringRef kPreservePrefix = "dx.preserve."; static const llvm::StringRef kNothingName = "dx.nothing.a"; static const llvm::StringRef kPreserveName = "dx.preserve.value.a"; bool IsPreserveRelatedValue(llvm::Instruction *I); bool IsPreserve(llvm::Instruction *S); bool IsNop(llvm::Instruction *I); } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/HLSL/DxilLinker.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilLinker.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Representation of HLSL Linker. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "dxc/HLSL/DxilExportMap.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/ErrorOr.h" #include <memory> #include <unordered_map> #include <unordered_set> namespace llvm { class Function; class GlobalVariable; class Constant; class Module; class LLVMContext; } // namespace llvm namespace hlsl { class DxilModule; class DxilResourceBase; // Linker for DxilModule. class DxilLinker { public: virtual ~DxilLinker() {} static DxilLinker *CreateLinker(llvm::LLVMContext &Ctx, unsigned valMajor, unsigned valMinor); void SetValidatorVersion(unsigned valMajor, unsigned valMinor) { m_valMajor = valMajor, m_valMinor = valMinor; } virtual bool HasLibNameRegistered(llvm::StringRef name) = 0; virtual bool RegisterLib(llvm::StringRef name, std::unique_ptr<llvm::Module> pModule, std::unique_ptr<llvm::Module> pDebugModule) = 0; virtual bool AttachLib(llvm::StringRef name) = 0; virtual bool DetachLib(llvm::StringRef name) = 0; virtual void DetachAll() = 0; virtual std::unique_ptr<llvm::Module> Link(llvm::StringRef entry, llvm::StringRef profile, dxilutil::ExportMap &exportMap) = 0; protected: DxilLinker(llvm::LLVMContext &Ctx, unsigned valMajor, unsigned valMinor) : m_ctx(Ctx), m_valMajor(valMajor), m_valMinor(valMinor) {} llvm::LLVMContext &m_ctx; unsigned m_valMajor, m_valMinor; }; } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/HLSL/ControlDependence.h
/////////////////////////////////////////////////////////////////////////////// // // // ComputeViewIdSets.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Computes control dependence relation for a function. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Dominators.h" #include <unordered_map> #include <unordered_set> namespace llvm { class Function; class raw_ostream; } // namespace llvm namespace hlsl { using BasicBlockSet = std::unordered_set<llvm::BasicBlock *>; using PostDomRelationType = llvm::DominatorTreeBase<llvm::BasicBlock>; class ControlDependence { public: void Compute(llvm::Function *F, PostDomRelationType &PostDomRel); void Clear(); const BasicBlockSet &GetCDBlocks(llvm::BasicBlock *pBB) const; void print(llvm::raw_ostream &OS); void dump(); private: using BasicBlockVector = std::vector<llvm::BasicBlock *>; using ControlDependenceType = std::unordered_map<llvm::BasicBlock *, BasicBlockSet>; llvm::Function *m_pFunc; ControlDependenceType m_ControlDependence; BasicBlockSet m_EmptyBBSet; llvm::BasicBlock *GetIPostDom(PostDomRelationType &PostDomRel, llvm::BasicBlock *pBB); void ComputeRevTopOrderRec(PostDomRelationType &PostDomRel, llvm::BasicBlock *pBB, BasicBlockVector &RevTopOrder, BasicBlockSet &VisitedBBs); }; } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/HLSL/DxilSpanAllocator.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilSpanAllocator.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Allocator for resources or other things that span a range of space // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "dxc/Support/Global.h" #include <map> #include <set> namespace hlsl { template <typename T_index, typename T_element> class SpanAllocator { public: struct Span { Span(const T_element *element, T_index start, T_index end) : element(element), start(start), end(end) { DXASSERT_NOMSG(!(end < start)); } const T_element *element; T_index start, end; // inclusive bool operator<(const Span &other) const { return end < other.start; } }; typedef std::set<Span> SpanSet; public: SpanAllocator(T_index Min, T_index Max) : m_Min(Min), m_Max(Max), m_FirstFree(Min), m_Unbounded(nullptr), m_AllocationFull(false) { DXASSERT_NOMSG(Min <= Max); } T_index GetMin() { return m_Min; } T_index GetMax() { return m_Max; } T_index GetFirstFree() { return m_FirstFree; } bool IsFull() { return m_AllocationFull; } void SetUnbounded(const T_element *element) { m_Unbounded = element; } const T_element *GetUnbounded() const { return m_Unbounded; } const SpanSet &GetSpans() const { return m_Spans; } // Find size gap starting at pos, updating pos, and returning true if // successful bool Find(T_index size, T_index &pos, T_index align = 1) { DXASSERT_NOMSG(size); if (size - 1 > m_Max - m_Min) return false; if (pos < m_FirstFree) pos = m_FirstFree; if (!UpdatePos(pos, size, align)) return false; T_index end = pos + (size - 1); auto next = m_Spans.lower_bound(Span(nullptr, pos, end)); if (next == m_Spans.end() || end < next->start) return true; // it fits here return Find(size, next, pos, align); } // Finds the farthest position at which an element could be allocated. bool FindForUnbounded(T_index &pos, T_index align = 1) { if (m_Spans.empty()) { pos = m_Min; return UpdatePos(pos, /*size*/ 1, align); } pos = m_Spans.crbegin()->end; return IncPos(pos, /*inc*/ 1, /*size*/ 1, align); } // allocate element size in first available space, returns false on failure bool Allocate(const T_element *element, T_index size, T_index &pos, T_index align = 1) { DXASSERT_NOMSG(size); if (size - 1 > m_Max - m_Min) return false; if (m_AllocationFull) return false; pos = m_FirstFree; if (!UpdatePos(pos, size, align)) return false; auto result = m_Spans.emplace(element, pos, pos + (size - 1)); if (result.second) { AdvanceFirstFree(result.first); return true; } // Collision, find a gap from iterator if (!Find(size, result.first, pos, align)) return false; result = m_Spans.emplace(element, pos, pos + (size - 1)); return result.second; } bool AllocateUnbounded(const T_element *element, T_index &pos, T_index align = 1) { if (m_AllocationFull) return false; if (m_Spans.empty()) { pos = m_Min; if (!UpdatePos(pos, /*size*/ 1, align)) return false; } else { // This will allocate after the last span auto it = m_Spans.end(); --it; // find last span DXASSERT_NOMSG(it != m_Spans.end()); pos = it->end; if (!IncPos(pos, /*inc*/ 1, /*size*/ 1, align)) return false; } const T_element *conflict = Insert(element, pos, m_Max); DXASSERT_NOMSG(!conflict); if (!conflict) SetUnbounded(element); return !conflict; } // Insert at specific location, returning conflicting element on collision const T_element *Insert(const T_element *element, T_index start, T_index end) { DXASSERT_NOMSG(m_Min <= start && start <= end && end <= m_Max); auto result = m_Spans.emplace(element, start, end); if (!result.second) return result.first->element; AdvanceFirstFree(result.first); return nullptr; } // Insert at specific location, overwriting anything previously there, // losing their element pointer, but conserving the spans they represented. void ForceInsertAndClobber(const T_element *element, T_index start, T_index end) { DXASSERT_NOMSG(m_Min <= start && start <= end && end <= m_Max); for (;;) { auto result = m_Spans.emplace(element, start, end); if (result.second) break; // Delete the spans we overlap with, but make sure our new span covers // what they covered. start = std::min(result.first->start, start); end = std::max(result.first->end, end); m_Spans.erase(result.first); } } private: // Find size gap starting at iterator, updating pos, and returning true if // successful bool Find(T_index size, typename SpanSet::const_iterator it, T_index &pos, T_index align = 1) { pos = it->end; if (!IncPos(pos, /*inc*/ 1, size, align)) return false; for (++it; it != m_Spans.end() && (it->start < pos || it->start - pos < size); ++it) { pos = it->end; if (!IncPos(pos, /*inc*/ 1, size, align)) return false; } return true; } // Advance m_FirstFree if it's in span void AdvanceFirstFree(typename SpanSet::const_iterator it) { if (it->start <= m_FirstFree && m_FirstFree <= it->end) { for (; it != m_Spans.end();) { if (it->end >= m_Max) { m_AllocationFull = true; break; } m_FirstFree = it->end + 1; ++it; if (it != m_Spans.end() && m_FirstFree < it->start) break; } } } T_index Align(T_index pos, T_index align) { T_index rem = (1 < align) ? pos % align : 0; return rem ? pos + (align - rem) : pos; } bool IncPos(T_index &pos, T_index inc = 1, T_index size = 1, T_index align = 1) { DXASSERT_NOMSG(inc > 0); if (pos + inc < pos) return false; // overflow pos += inc; return UpdatePos(pos, size, align); } bool UpdatePos(T_index &pos, T_index size = 1, T_index align = 1) { if ((size - 1) > m_Max - m_Min || pos < m_Min || pos > m_Max - (size - 1)) return false; T_index aligned = Align(pos, align); if (aligned < pos || aligned > m_Max - (size - 1)) return false; // overflow on alignment, or won't fit pos = aligned; return true; } private: SpanSet m_Spans; T_index m_Min, m_Max, m_FirstFree; const T_element *m_Unbounded; bool m_AllocationFull; }; template <typename T_index, typename T_element> class SpacesAllocator { public: typedef SpanAllocator<T_index, T_element> Allocator; typedef std::map<T_index, Allocator> AllocatorMap; Allocator &Get(T_index SpaceID) { auto it = m_Allocators.find(SpaceID); if (it != m_Allocators.end()) return it->second; auto result = m_Allocators.emplace(SpaceID, Allocator(0, UINT_MAX)); DXASSERT(result.second, "Failed to allocate new Allocator"); return result.first->second; } private: AllocatorMap m_Allocators; }; } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/HLSL/HLOperationLower.h
/////////////////////////////////////////////////////////////////////////////// // // // HLOperationLower.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Lower functions to lower HL operations to DXIL operations. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include <unordered_set> namespace llvm { class Instruction; class Function; } // namespace llvm namespace hlsl { class HLModule; class DxilResourceBase; class HLSLExtensionsCodegenHelper; void TranslateBuiltinOperations( HLModule &HLM, HLSLExtensionsCodegenHelper *extCodegenHelper, std::unordered_set<llvm::Instruction *> &UpdateCounterSet); void LowerRecordAccessToGetNodeRecordPtr(HLModule &HLM); } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/HLSL/HLUtil.h
/////////////////////////////////////////////////////////////////////////////// // // // HLUtil.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // HL helper functions. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "llvm/ADT/SetVector.h" namespace llvm { class Function; class Value; class MemCpyInst; } // namespace llvm namespace hlsl { class DxilTypeSystem; namespace hlutil { struct PointerStatus { /// Keep track of what stores to the pointer look like. enum class StoredType { /// There is no store to this pointer. It can thus be marked constant. NotStored, /// This ptr is a global, and is stored to, but the only thing stored is the /// constant it /// was initialized with. This is only tracked for scalar globals. InitializerStored, /// This ptr is stored to, but only its initializer and one other value /// is ever stored to it. If this global isStoredOnce, we track the value /// stored to it in StoredOnceValue below. This is only tracked for scalar /// globals. StoredOnce, /// This ptr is only assigned by a memcpy. MemcopyDestOnce, /// This ptr is stored to by multiple values or something else that we /// cannot track. Stored } storedType; /// Keep track of what loaded from the pointer look like. enum class LoadedType { /// There is no load to this pointer. It can thus be marked constant. NotLoaded, /// This ptr is only used by a memcpy. MemcopySrcOnce, /// This ptr is loaded to by multiple instructions or something else that we /// cannot track. Loaded } loadedType; /// If only one value (besides the initializer constant) is ever stored to /// this global, keep track of what value it is. llvm::Value *StoredOnceValue; /// Memcpy which this ptr is used. llvm::SetVector<llvm::MemCpyInst *> memcpySet; /// Memcpy which use this ptr as dest. llvm::MemCpyInst *StoringMemcpy; /// Memcpy which use this ptr as src. llvm::MemCpyInst *LoadingMemcpy; /// These start out null/false. When the first accessing function is noticed, /// it is recorded. When a second different accessing function is noticed, /// HasMultipleAccessingFunctions is set to true. const llvm::Function *AccessingFunction; bool HasMultipleAccessingFunctions; /// Size of the ptr. unsigned Size; llvm::Value *Ptr; // Just check load store. bool bLoadStoreOnly; void analyze(DxilTypeSystem &typeSys, bool bStructElt); PointerStatus(llvm::Value *ptr, unsigned size, bool bLdStOnly); void MarkAsStored(); void MarkAsLoaded(); bool HasStored(); bool HasLoaded(); }; } // namespace hlutil } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/HLSL/DxilConvergentName.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilConvergentName.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Expose helper function name to avoid link issue with spirv. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once namespace hlsl { static const char *kConvergentFunctionPrefix = "dxil.convergent.marker."; }
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/HLSL/HLResource.h
/////////////////////////////////////////////////////////////////////////////// // // // HLResource.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Representation of HLSL SRVs and UAVs in high-level DX IR. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "dxc/DXIL/DxilResource.h" namespace hlsl { /// Use this class to represent an HLSL resource (SRV/UAV) in HLDXIR. class HLResource : public DxilResource { public: // QQQ // TODO: this does not belong here. QQQ // static Kind KeywordToKind(const std::string &keyword); HLResource(); }; } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/HLSL/ComputeViewIdState.h
/////////////////////////////////////////////////////////////////////////////// // // // ComputeViewIdState.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Computes output registers dependent on ViewID. // // Computes sets of input registers on which output registers depend. // // Computes which input/output shapes are dynamically indexed. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "dxc/HLSL/ControlDependence.h" #include "llvm/Pass.h" #include "llvm/Support/GenericDomTree.h" #include <bitset> #include <map> #include <memory> #include <set> #include <unordered_map> #include <unordered_set> namespace llvm { class Module; class Function; class BasicBlock; class Instruction; class ReturnInst; class Value; class PHINode; class AnalysisUsage; class CallGraph; class CallGraphNode; class ModulePass; class raw_ostream; } // namespace llvm namespace hlsl { class DxilModule; class DxilSignature; class DxilSignatureElement; struct DxilViewIdStateData { static const unsigned kNumComps = 4; static const unsigned kMaxSigScalars = 32 * 4; using OutputsDependentOnViewIdType = std::bitset<kMaxSigScalars>; using InputsContributingToOutputType = std::map<unsigned, std::set<unsigned>>; static const unsigned kNumStreams = 4; unsigned m_NumInputSigScalars = 0; unsigned m_NumOutputSigScalars[kNumStreams] = {0, 0, 0, 0}; unsigned m_NumPCOrPrimSigScalars = 0; // Set of scalar outputs dependent on ViewID. OutputsDependentOnViewIdType m_OutputsDependentOnViewId[kNumStreams]; OutputsDependentOnViewIdType m_PCOrPrimOutputsDependentOnViewId; // Set of scalar inputs contributing to computation of scalar outputs. InputsContributingToOutputType m_InputsContributingToOutputs[kNumStreams]; InputsContributingToOutputType m_InputsContributingToPCOrPrimOutputs; // HS PC and MS Prim only. InputsContributingToOutputType m_PCInputsContributingToOutputs; // DS only. bool m_bUsesViewId = false; }; class DxilViewIdState : public DxilViewIdStateData { static const unsigned kNumComps = 4; static const unsigned kMaxSigScalars = 32 * 4; public: using OutputsDependentOnViewIdType = std::bitset<kMaxSigScalars>; using InputsContributingToOutputType = std::map<unsigned, std::set<unsigned>>; DxilViewIdState(DxilModule *pDxilModule); unsigned getNumInputSigScalars() const; unsigned getNumOutputSigScalars(unsigned StreamId) const; unsigned getNumPCSigScalars() const; const OutputsDependentOnViewIdType & getOutputsDependentOnViewId(unsigned StreamId) const; const OutputsDependentOnViewIdType &getPCOutputsDependentOnViewId() const; const InputsContributingToOutputType & getInputsContributingToOutputs(unsigned StreamId) const; const InputsContributingToOutputType & getInputsContributingToPCOutputs() const; const InputsContributingToOutputType & getPCInputsContributingToOutputs() const; void Serialize(); const std::vector<unsigned> &GetSerialized(); const std::vector<unsigned> & GetSerialized() const; // returns previously serialized data void Deserialize(const unsigned *pData, unsigned DataSizeInUINTs); void PrintSets(llvm::raw_ostream &OS); private: DxilModule *m_pModule; // Serialized form. std::vector<unsigned> m_SerializedState; void Clear(); }; } // namespace hlsl namespace llvm { void initializeComputeViewIdStatePass(llvm::PassRegistry &); llvm::ModulePass *createComputeViewIdStatePass(); } // namespace llvm
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/HLSL/DxilPoisonValues.h
/////////////////////////////////////////////////////////////////////////////// // // // DxilPoisonValues.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Allows insertion of poisoned values with error messages that get // // cleaned up late in the compiler. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "llvm/IR/DebugLoc.h" namespace llvm { class Instruction; class Type; class Value; class Module; } // namespace llvm namespace hlsl { // Create a special dx.poison.* instruction with debug location and an error // message. The reason for this is certain invalid code is allowed in the code // as long as it is removed by optimization at the end of compilation. We only // want to emit the error for real if we are sure the code with the problem is // in the final DXIL. // // This "emits" an error message with the specified type. If by the end the // compilation it is still used, then FinalizePoisonValues will emit the correct // error for real. llvm::Value *CreatePoisonValue(llvm::Type *ty, const llvm::Twine &errMsg, llvm::DebugLoc DL, llvm::Instruction *InsertPt); // If there's any dx.poison.* values present in the module, emit them. Returns // true M was modified in any way. bool FinalizePoisonValues(llvm::Module &M); } // namespace hlsl
0
repos/DirectXShaderCompiler/include/dxc
repos/DirectXShaderCompiler/include/dxc/HLSL/HLOperations.h
/////////////////////////////////////////////////////////////////////////////// // // // HLOperations.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Implentation of High Level DXIL operations. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "llvm/IR/IRBuilder.h" #include <string> namespace llvm { class Argument; template <typename T> class ArrayRef; class AttributeSet; class CallInst; class Function; class FunctionType; class Module; class StringRef; class Type; class Value; } // namespace llvm namespace hlsl { enum class HLOpcodeGroup { NotHL, HLExtIntrinsic, HLIntrinsic, HLCast, HLInit, HLBinOp, HLUnOp, HLSubscript, HLMatLoadStore, HLSelect, HLCreateHandle, // FIXME: Change the way these groups are being proliferated/used for each // new generated op. // Suggestion: Add an opcode and reuse CreateHandle/AnnotateHandle groups, and // add an IndexHandle group. HLCreateNodeOutputHandle, HLIndexNodeHandle, HLCreateNodeInputRecordHandle, HLAnnotateHandle, HLAnnotateNodeHandle, HLAnnotateNodeRecordHandle, NumOfHLOps }; enum class HLBinaryOpcode { Invalid, Mul, Div, Rem, Add, Sub, Shl, Shr, LT, GT, LE, GE, EQ, NE, And, Xor, Or, LAnd, LOr, UDiv, URem, UShr, ULT, UGT, ULE, UGE, NumOfBO, }; enum class HLUnaryOpcode { Invalid, PostInc, PostDec, PreInc, PreDec, Plus, Minus, Not, LNot, NumOfUO, }; enum class HLSubscriptOpcode { DefaultSubscript, ColMatSubscript, RowMatSubscript, ColMatElement, RowMatElement, DoubleSubscript, CBufferSubscript, VectorSubscript, // Only for bool vector, other vector type will use GEP // directly. }; enum class HLCastOpcode { DefaultCast, UnsignedUnsignedCast, FromUnsignedCast, ToUnsignedCast, ColMatrixToVecCast, RowMatrixToVecCast, ColMatrixToRowMatrix, RowMatrixToColMatrix, HandleToResCast, HandleToNodeOutputCast, NodeOutputToHandleCast, HandleToNodeRecordCast, NodeRecordToHandleCast, }; enum class HLMatLoadStoreOpcode { ColMatLoad, ColMatStore, RowMatLoad, RowMatStore, }; extern const char *const HLPrefix; HLOpcodeGroup GetHLOpcodeGroup(llvm::Function *F); HLOpcodeGroup GetHLOpcodeGroupByName(const llvm::Function *F); llvm::StringRef GetHLOpcodeGroupNameByAttr(llvm::Function *F); llvm::StringRef GetHLLowerStrategy(llvm::Function *F); unsigned GetHLOpcode(const llvm::CallInst *CI); unsigned GetRowMajorOpcode(HLOpcodeGroup group, unsigned opcode); void SetHLLowerStrategy(llvm::Function *F, llvm::StringRef S); void SetHLWaveSensitive(llvm::Function *F); bool IsHLWaveSensitive(llvm::Function *F); // For intrinsic opcode. unsigned GetUnsignedOpcode(unsigned opcode); // For HLBinaryOpcode. bool HasUnsignedOpcode(HLBinaryOpcode opcode); HLBinaryOpcode GetUnsignedOpcode(HLBinaryOpcode opcode); llvm::StringRef GetHLOpcodeGroupName(HLOpcodeGroup op); namespace HLOperandIndex { // Opcode parameter. const unsigned kOpcodeIdx = 0; // Used to initialize values that have no valid index in the HL overload. const unsigned kInvalidIdx = UINT32_MAX; // Matrix store. const unsigned kMatStoreDstPtrOpIdx = 1; const unsigned kMatStoreValOpIdx = 2; // Matrix load. const unsigned kMatLoadPtrOpIdx = 1; // Normal subscipts. const unsigned kSubscriptObjectOpIdx = 1; const unsigned kSubscriptIndexOpIdx = 2; // Double subscripts. const unsigned kDoubleSubscriptMipLevelOpIdx = 3; // Matrix subscripts. const unsigned kMatSubscriptMatOpIdx = 1; const unsigned kMatSubscriptSubOpIdx = 2; // Matrix init. const unsigned kMatArrayInitMatOpIdx = 1; const unsigned kMatArrayInitFirstArgOpIdx = 2; // Array Init. const unsigned kArrayInitPtrOpIdx = 1; const unsigned kArrayInitFirstArgOpIdx = 2; // Normal Init. const unsigned kInitFirstArgOpIdx = 1; // Unary operators. const unsigned kUnaryOpSrc0Idx = 1; // Binary operators. const unsigned kBinaryOpSrc0Idx = 1; const unsigned kBinaryOpSrc1Idx = 2; // Trinary operators. const unsigned kTrinaryOpSrc0Idx = 1; const unsigned kTrinaryOpSrc1Idx = 2; const unsigned kTrinaryOpSrc2Idx = 3; // Interlocked. const unsigned kInterlockedDestOpIndex = 1; const unsigned kInterlockedValueOpIndex = 2; const unsigned kInterlockedOriginalValueOpIndex = 3; // Interlocked method const unsigned kInterlockedMethodValueOpIndex = 3; // InterlockedCompareExchange. const unsigned kInterlockedCmpDestOpIndex = 1; const unsigned kInterlockedCmpCompareValueOpIndex = 2; const unsigned kInterlockedCmpValueOpIndex = 3; const unsigned kInterlockedCmpOriginalValueOpIndex = 4; // Lerp. const unsigned kLerpOpXIdx = 1; const unsigned kLerpOpYIdx = 2; const unsigned kLerpOpSIdx = 3; // ProcessTessFactorIsoline. const unsigned kProcessTessFactorRawDetailFactor = 1; const unsigned kProcessTessFactorRawDensityFactor = 2; const unsigned kProcessTessFactorRoundedDetailFactor = 3; const unsigned kProcessTessFactorRoundedDensityFactor = 4; // ProcessTessFactor. const unsigned kProcessTessFactorRawEdgeFactor = 1; const unsigned kProcessTessFactorInsideScale = 2; const unsigned kProcessTessFactorRoundedEdgeFactor = 3; const unsigned kProcessTessFactorRoundedInsideFactor = 4; const unsigned kProcessTessFactorUnRoundedInsideFactor = 5; // Reflect. const unsigned kReflectOpIIdx = 1; const unsigned kReflectOpNIdx = 2; // Refract const unsigned kRefractOpIIdx = 1; const unsigned kRefractOpNIdx = 2; const unsigned kRefractOpEtaIdx = 3; // SmoothStep. const unsigned kSmoothStepOpMinIdx = 1; const unsigned kSmoothStepOpMaxIdx = 2; const unsigned kSmoothStepOpXIdx = 3; // Clamp const unsigned kClampOpXIdx = 1; const unsigned kClampOpMinIdx = 2; const unsigned kClampOpMaxIdx = 3; // Object functions. const unsigned kHandleOpIdx = 1; // Store. const unsigned kStoreOffsetOpIdx = 2; const unsigned kStoreValOpIdx = 3; // Load. const unsigned kBufLoadAddrOpIdx = 2; const unsigned kBufLoadStatusOpIdx = 3; const unsigned kRWTexLoadStatusOpIdx = 3; const unsigned kTexLoadOffsetOpIdx = 3; const unsigned kTexLoadStatusOpIdx = 4; // Load for Texture2DMS const unsigned kTex2DMSLoadSampleIdxOpIdx = 3; const unsigned kTex2DMSLoadOffsetOpIdx = 4; const unsigned kTex2DMSLoadStatusOpIdx = 5; // mips.Operator. const unsigned kMipLoadAddrOpIdx = 3; const unsigned kMipLoadOffsetOpIdx = 4; const unsigned kMipLoadStatusOpIdx = 5; // Sample. const unsigned kSampleSamplerArgIndex = 2; const unsigned kSampleCoordArgIndex = 3; const unsigned kSampleOffsetArgIndex = 4; const unsigned kSampleClampArgIndex = 5; const unsigned kSampleStatusArgIndex = 6; // SampleG. const unsigned kSampleGDDXArgIndex = 4; const unsigned kSampleGDDYArgIndex = 5; const unsigned kSampleGOffsetArgIndex = 6; const unsigned kSampleGClampArgIndex = 7; const unsigned kSampleGStatusArgIndex = 8; // SampleCmp. const unsigned kSampleCmpCmpValArgIndex = 4; const unsigned kSampleCmpOffsetArgIndex = 5; const unsigned kSampleCmpClampArgIndex = 6; const unsigned kSampleCmpStatusArgIndex = 7; // SampleCmpBias. const unsigned kSampleCmpBCmpValArgIndex = 4; const unsigned kSampleCmpBBiasArgIndex = 5; const unsigned kSampleCmpBOffsetArgIndex = 6; const unsigned kSampleCmpBClampArgIndex = 7; const unsigned kSampleCmpBStatusArgIndex = 8; // SampleCmpGrad. const unsigned kSampleCmpGCmpValArgIndex = 4; const unsigned kSampleCmpGDDXArgIndex = 5; const unsigned kSampleCmpGDDYArgIndex = 6; const unsigned kSampleCmpGOffsetArgIndex = 7; const unsigned kSampleCmpGClampArgIndex = 8; const unsigned kSampleCmpGStatusArgIndex = 9; // SampleBias. const unsigned kSampleBBiasArgIndex = 4; const unsigned kSampleBOffsetArgIndex = 5; const unsigned kSampleBClampArgIndex = 6; const unsigned kSampleBStatusArgIndex = 7; // SampleLevel. const unsigned kSampleLLevelArgIndex = 4; const unsigned kSampleLOffsetArgIndex = 5; const unsigned kSampleLStatusArgIndex = 6; // SampleCmpLevel // the rest are the same as SampleCmp const unsigned kSampleCmpLLevelArgIndex = 5; const unsigned kSampleCmpLOffsetArgIndex = 6; // SampleCmpLevelZero. const unsigned kSampleCmpLZCmpValArgIndex = 4; const unsigned kSampleCmpLZOffsetArgIndex = 5; const unsigned kSampleCmpLZStatusArgIndex = 6; // Gather. const unsigned kGatherSamplerArgIndex = 2; const unsigned kGatherCoordArgIndex = 3; const unsigned kGatherOffsetArgIndex = 4; const unsigned kGatherStatusArgIndex = 5; const unsigned kGatherSampleOffsetArgIndex = 5; const unsigned kGatherStatusWithSampleOffsetArgIndex = 8; const unsigned kGatherCubeStatusArgIndex = 4; // GatherCmp. const unsigned kGatherCmpCmpValArgIndex = 4; const unsigned kGatherCmpOffsetArgIndex = 5; const unsigned kGatherCmpStatusArgIndex = 6; const unsigned kGatherCmpSampleOffsetArgIndex = 6; const unsigned kGatherCmpStatusWithSampleOffsetArgIndex = 9; const unsigned kGatherCmpCubeStatusArgIndex = 5; // WriteSamplerFeedback. const unsigned kWriteSamplerFeedbackSampledArgIndex = 2; const unsigned kWriteSamplerFeedbackSamplerArgIndex = 3; const unsigned kWriteSamplerFeedbackCoordArgIndex = 4; const unsigned kWriteSamplerFeedbackBias_BiasArgIndex = 5; const unsigned kWriteSamplerFeedbackLevel_LodArgIndex = 5; const unsigned kWriteSamplerFeedbackGrad_DdxArgIndex = 5; const unsigned kWriteSamplerFeedbackGrad_DdyArgIndex = 6; const unsigned kWriteSamplerFeedback_ClampArgIndex = 5; const unsigned kWriteSamplerFeedbackBias_ClampArgIndex = 6; const unsigned kWriteSamplerFeedbackGrad_ClampArgIndex = 7; // StreamAppend. const unsigned kStreamAppendStreamOpIndex = 1; const unsigned kStreamAppendDataOpIndex = 2; // Append. const unsigned kAppendValOpIndex = 2; // Interlocked. const unsigned kObjectInterlockedDestOpIndex = 2; const unsigned kObjectInterlockedValueOpIndex = 3; const unsigned kObjectInterlockedOriginalValueOpIndex = 4; // InterlockedCompareExchange. const unsigned kObjectInterlockedCmpDestOpIndex = 2; const unsigned kObjectInterlockedCmpCompareValueOpIndex = 3; const unsigned kObjectInterlockedCmpValueOpIndex = 4; const unsigned kObjectInterlockedCmpOriginalValueOpIndex = 5; // GetSamplePosition. const unsigned kGetSamplePositionSampleIdxOpIndex = 2; // GetDimensions. const unsigned kGetDimensionsMipLevelOpIndex = 2; const unsigned kGetDimensionsMipWidthOpIndex = 3; const unsigned kGetDimensionsNoMipWidthOpIndex = 2; // WaveAllEqual. const unsigned kWaveAllEqualValueOpIdx = 1; // CreateHandle. const unsigned kCreateHandleResourceOpIdx = 1; const unsigned kCreateHandleIndexOpIdx = 2; // Only for array of cbuffer. // Annotate(Node)(Record)Handle. const unsigned kAnnotateHandleResourcePropertiesOpIdx = 2; const unsigned kAnnotateHandleResourceTypeOpIdx = 3; // TraceRay. const unsigned kTraceRayRayDescOpIdx = 7; const unsigned kTraceRayPayLoadOpIdx = 8; // CallShader. const unsigned kCallShaderPayloadOpIdx = 2; // TraceRayInline. const unsigned kTraceRayInlineRayDescOpIdx = 5; // ReportIntersection. const unsigned kReportIntersectionAttributeOpIdx = 3; // DispatchMesh const unsigned kDispatchMeshOpThreadX = 1; const unsigned kDispatchMeshOpThreadY = 2; const unsigned kDispatchMeshOpThreadZ = 3; const unsigned kDispatchMeshOpPayload = 4; // Work Graph const unsigned kIncrementOutputCountCountIdx = 2; const unsigned kBarrierMemoryTypeFlagsOpIdx = 1; const unsigned kBarrierSemanticFlagsOpIdx = 2; // Node Handles const unsigned kAllocateRecordNumRecordsIdx = 2; const unsigned kNodeOutputMetadataIDIdx = 1; const unsigned kIndexNodeHandleArrayIDIdx = 2; const unsigned kNodeInputRecordMetadataIDIdx = 1; const unsigned kNodeHandleToResCastOpIdx = 1; const unsigned kAnnotateNodeHandleNodePropIdx = 2; const unsigned kAnnotateNodeRecordHandleNodeRecordPropIdx = 2; } // namespace HLOperandIndex llvm::Function *GetOrCreateHLFunction(llvm::Module &M, llvm::FunctionType *funcTy, HLOpcodeGroup group, unsigned opcode); llvm::Function *GetOrCreateHLFunction(llvm::Module &M, llvm::FunctionType *funcTy, HLOpcodeGroup group, llvm::StringRef *groupName, llvm::StringRef *fnName, unsigned opcode); llvm::Function *GetOrCreateHLFunction(llvm::Module &M, llvm::FunctionType *funcTy, HLOpcodeGroup group, unsigned opcode, const llvm::AttributeSet &attribs); llvm::Function *GetOrCreateHLFunction(llvm::Module &M, llvm::FunctionType *funcTy, HLOpcodeGroup group, llvm::StringRef *groupName, llvm::StringRef *fnName, unsigned opcode, const llvm::AttributeSet &attribs); llvm::Function *GetOrCreateHLFunctionWithBody(llvm::Module &M, llvm::FunctionType *funcTy, HLOpcodeGroup group, unsigned opcode, llvm::StringRef name); llvm::Value *callHLFunction(llvm::Module &Module, HLOpcodeGroup OpcodeGroup, unsigned Opcode, llvm::Type *RetTy, llvm::ArrayRef<llvm::Value *> Args, const llvm::AttributeSet &attribs, llvm::IRBuilder<> &Builder); llvm::Value *callHLFunction(llvm::Module &Module, HLOpcodeGroup OpcodeGroup, unsigned Opcode, llvm::Type *RetTy, llvm::ArrayRef<llvm::Value *> Args, llvm::IRBuilder<> &Builder); } // namespace hlsl