1 //===- CodeGenDAGPatterns.h - Read DAG patterns from .td file ---*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the CodeGenDAGPatterns class, which is used to read and
11 // represent the patterns present in a .td file for instructions.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_UTILS_TABLEGEN_CODEGENDAGPATTERNS_H
16 #define LLVM_UTILS_TABLEGEN_CODEGENDAGPATTERNS_H
17 
18 #include "CodeGenHwModes.h"
19 #include "CodeGenIntrinsics.h"
20 #include "CodeGenTarget.h"
21 #include "SDNodeProperties.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringSet.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/MathExtras.h"
27 #include <algorithm>
28 #include <array>
29 #include <functional>
30 #include <map>
31 #include <set>
32 #include <vector>
33 
34 namespace llvm {
35 
36 class Record;
37 class Init;
38 class ListInit;
39 class DagInit;
40 class SDNodeInfo;
41 class TreePattern;
42 class TreePatternNode;
43 class CodeGenDAGPatterns;
44 class ComplexPattern;
45 
46 /// Shared pointer for TreePatternNode.
47 using TreePatternNodePtr = std::shared_ptr<TreePatternNode>;
48 
49 /// This represents a set of MVTs. Since the underlying type for the MVT
50 /// is uint8_t, there are at most 256 values. To reduce the number of memory
51 /// allocations and deallocations, represent the set as a sequence of bits.
52 /// To reduce the allocations even further, make MachineValueTypeSet own
53 /// the storage and use std::array as the bit container.
54 struct MachineValueTypeSet {
55   static_assert(std::is_same<std::underlying_type<MVT::SimpleValueType>::type,
56                              uint8_t>::value,
57                 "Change uint8_t here to the SimpleValueType's type");
58   static unsigned constexpr Capacity = std::numeric_limits<uint8_t>::max()+1;
59   using WordType = uint64_t;
60   static unsigned constexpr WordWidth = CHAR_BIT*sizeof(WordType);
61   static unsigned constexpr NumWords = Capacity/WordWidth;
62   static_assert(NumWords*WordWidth == Capacity,
63                 "Capacity should be a multiple of WordWidth");
64 
65   LLVM_ATTRIBUTE_ALWAYS_INLINE
66   MachineValueTypeSet() {
67     clear();
68   }
69 
70   LLVM_ATTRIBUTE_ALWAYS_INLINE
71   unsigned size() const {
72     unsigned Count = 0;
73     for (WordType W : Words)
74       Count += countPopulation(W);
75     return Count;
76   }
77   LLVM_ATTRIBUTE_ALWAYS_INLINE
78   void clear() {
79     std::memset(Words.data(), 0, NumWords*sizeof(WordType));
80   }
81   LLVM_ATTRIBUTE_ALWAYS_INLINE
82   bool empty() const {
83     for (WordType W : Words)
84       if (W != 0)
85         return false;
86     return true;
87   }
88   LLVM_ATTRIBUTE_ALWAYS_INLINE
89   unsigned count(MVT T) const {
90     return (Words[T.SimpleTy / WordWidth] >> (T.SimpleTy % WordWidth)) & 1;
91   }
92   std::pair<MachineValueTypeSet&,bool> insert(MVT T) {
93     bool V = count(T.SimpleTy);
94     Words[T.SimpleTy / WordWidth] |= WordType(1) << (T.SimpleTy % WordWidth);
95     return {*this, V};
96   }
97   MachineValueTypeSet &insert(const MachineValueTypeSet &S) {
98     for (unsigned i = 0; i != NumWords; ++i)
99       Words[i] |= S.Words[i];
100     return *this;
101   }
102   LLVM_ATTRIBUTE_ALWAYS_INLINE
103   void erase(MVT T) {
104     Words[T.SimpleTy / WordWidth] &= ~(WordType(1) << (T.SimpleTy % WordWidth));
105   }
106 
107   struct const_iterator {
108     // Some implementations of the C++ library require these traits to be
109     // defined.
110     using iterator_category = std::forward_iterator_tag;
111     using value_type = MVT;
112     using difference_type = ptrdiff_t;
113     using pointer = const MVT*;
114     using reference = const MVT&;
115 
116     LLVM_ATTRIBUTE_ALWAYS_INLINE
117     MVT operator*() const {
118       assert(Pos != Capacity);
119       return MVT::SimpleValueType(Pos);
120     }
121     LLVM_ATTRIBUTE_ALWAYS_INLINE
122     const_iterator(const MachineValueTypeSet *S, bool End) : Set(S) {
123       Pos = End ? Capacity : find_from_pos(0);
124     }
125     LLVM_ATTRIBUTE_ALWAYS_INLINE
126     const_iterator &operator++() {
127       assert(Pos != Capacity);
128       Pos = find_from_pos(Pos+1);
129       return *this;
130     }
131 
132     LLVM_ATTRIBUTE_ALWAYS_INLINE
133     bool operator==(const const_iterator &It) const {
134       return Set == It.Set && Pos == It.Pos;
135     }
136     LLVM_ATTRIBUTE_ALWAYS_INLINE
137     bool operator!=(const const_iterator &It) const {
138       return !operator==(It);
139     }
140 
141   private:
142     unsigned find_from_pos(unsigned P) const {
143       unsigned SkipWords = P / WordWidth;
144       unsigned SkipBits = P % WordWidth;
145       unsigned Count = SkipWords * WordWidth;
146 
147       // If P is in the middle of a word, process it manually here, because
148       // the trailing bits need to be masked off to use findFirstSet.
149       if (SkipBits != 0) {
150         WordType W = Set->Words[SkipWords];
151         W &= maskLeadingOnes<WordType>(WordWidth-SkipBits);
152         if (W != 0)
153           return Count + findFirstSet(W);
154         Count += WordWidth;
155         SkipWords++;
156       }
157 
158       for (unsigned i = SkipWords; i != NumWords; ++i) {
159         WordType W = Set->Words[i];
160         if (W != 0)
161           return Count + findFirstSet(W);
162         Count += WordWidth;
163       }
164       return Capacity;
165     }
166 
167     const MachineValueTypeSet *Set;
168     unsigned Pos;
169   };
170 
171   LLVM_ATTRIBUTE_ALWAYS_INLINE
172   const_iterator begin() const { return const_iterator(this, false); }
173   LLVM_ATTRIBUTE_ALWAYS_INLINE
174   const_iterator end()   const { return const_iterator(this, true); }
175 
176   LLVM_ATTRIBUTE_ALWAYS_INLINE
177   bool operator==(const MachineValueTypeSet &S) const {
178     return Words == S.Words;
179   }
180   LLVM_ATTRIBUTE_ALWAYS_INLINE
181   bool operator!=(const MachineValueTypeSet &S) const {
182     return !operator==(S);
183   }
184 
185 private:
186   friend struct const_iterator;
187   std::array<WordType,NumWords> Words;
188 };
189 
190 struct TypeSetByHwMode : public InfoByHwMode<MachineValueTypeSet> {
191   using SetType = MachineValueTypeSet;
192 
193   TypeSetByHwMode() = default;
194   TypeSetByHwMode(const TypeSetByHwMode &VTS) = default;
195   TypeSetByHwMode(MVT::SimpleValueType VT)
196     : TypeSetByHwMode(ValueTypeByHwMode(VT)) {}
197   TypeSetByHwMode(ValueTypeByHwMode VT)
198     : TypeSetByHwMode(ArrayRef<ValueTypeByHwMode>(&VT, 1)) {}
199   TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList);
200 
201   SetType &getOrCreate(unsigned Mode) {
202     if (hasMode(Mode))
203       return get(Mode);
204     return Map.insert({Mode,SetType()}).first->second;
205   }
206 
207   bool isValueTypeByHwMode(bool AllowEmpty) const;
208   ValueTypeByHwMode getValueTypeByHwMode() const;
209 
210   LLVM_ATTRIBUTE_ALWAYS_INLINE
211   bool isMachineValueType() const {
212     return isDefaultOnly() && Map.begin()->second.size() == 1;
213   }
214 
215   LLVM_ATTRIBUTE_ALWAYS_INLINE
216   MVT getMachineValueType() const {
217     assert(isMachineValueType());
218     return *Map.begin()->second.begin();
219   }
220 
221   bool isPossible() const;
222 
223   LLVM_ATTRIBUTE_ALWAYS_INLINE
224   bool isDefaultOnly() const {
225     return Map.size() == 1 && Map.begin()->first == DefaultMode;
226   }
227 
228   bool insert(const ValueTypeByHwMode &VVT);
229   bool constrain(const TypeSetByHwMode &VTS);
230   template <typename Predicate> bool constrain(Predicate P);
231   template <typename Predicate>
232   bool assign_if(const TypeSetByHwMode &VTS, Predicate P);
233 
234   void writeToStream(raw_ostream &OS) const;
235   static void writeToStream(const SetType &S, raw_ostream &OS);
236 
237   bool operator==(const TypeSetByHwMode &VTS) const;
238   bool operator!=(const TypeSetByHwMode &VTS) const { return !(*this == VTS); }
239 
240   void dump() const;
241   bool validate() const;
242 
243 private:
244   /// Intersect two sets. Return true if anything has changed.
245   bool intersect(SetType &Out, const SetType &In);
246 };
247 
248 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T);
249 
250 struct TypeInfer {
251   TypeInfer(TreePattern &T) : TP(T), ForceMode(0) {}
252 
253   bool isConcrete(const TypeSetByHwMode &VTS, bool AllowEmpty) const {
254     return VTS.isValueTypeByHwMode(AllowEmpty);
255   }
256   ValueTypeByHwMode getConcrete(const TypeSetByHwMode &VTS,
257                                 bool AllowEmpty) const {
258     assert(VTS.isValueTypeByHwMode(AllowEmpty));
259     return VTS.getValueTypeByHwMode();
260   }
261 
262   /// The protocol in the following functions (Merge*, force*, Enforce*,
263   /// expand*) is to return "true" if a change has been made, "false"
264   /// otherwise.
265 
266   bool MergeInTypeInfo(TypeSetByHwMode &Out, const TypeSetByHwMode &In);
267   bool MergeInTypeInfo(TypeSetByHwMode &Out, MVT::SimpleValueType InVT) {
268     return MergeInTypeInfo(Out, TypeSetByHwMode(InVT));
269   }
270   bool MergeInTypeInfo(TypeSetByHwMode &Out, ValueTypeByHwMode InVT) {
271     return MergeInTypeInfo(Out, TypeSetByHwMode(InVT));
272   }
273 
274   /// Reduce the set \p Out to have at most one element for each mode.
275   bool forceArbitrary(TypeSetByHwMode &Out);
276 
277   /// The following four functions ensure that upon return the set \p Out
278   /// will only contain types of the specified kind: integer, floating-point,
279   /// scalar, or vector.
280   /// If \p Out is empty, all legal types of the specified kind will be added
281   /// to it. Otherwise, all types that are not of the specified kind will be
282   /// removed from \p Out.
283   bool EnforceInteger(TypeSetByHwMode &Out);
284   bool EnforceFloatingPoint(TypeSetByHwMode &Out);
285   bool EnforceScalar(TypeSetByHwMode &Out);
286   bool EnforceVector(TypeSetByHwMode &Out);
287 
288   /// If \p Out is empty, fill it with all legal types. Otherwise, leave it
289   /// unchanged.
290   bool EnforceAny(TypeSetByHwMode &Out);
291   /// Make sure that for each type in \p Small, there exists a larger type
292   /// in \p Big.
293   bool EnforceSmallerThan(TypeSetByHwMode &Small, TypeSetByHwMode &Big);
294   /// 1. Ensure that for each type T in \p Vec, T is a vector type, and that
295   ///    for each type U in \p Elem, U is a scalar type.
296   /// 2. Ensure that for each (scalar) type U in \p Elem, there exists a
297   ///    (vector) type T in \p Vec, such that U is the element type of T.
298   bool EnforceVectorEltTypeIs(TypeSetByHwMode &Vec, TypeSetByHwMode &Elem);
299   bool EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
300                               const ValueTypeByHwMode &VVT);
301   /// Ensure that for each type T in \p Sub, T is a vector type, and there
302   /// exists a type U in \p Vec such that U is a vector type with the same
303   /// element type as T and at least as many elements as T.
304   bool EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
305                                     TypeSetByHwMode &Sub);
306   /// 1. Ensure that \p V has a scalar type iff \p W has a scalar type.
307   /// 2. Ensure that for each vector type T in \p V, there exists a vector
308   ///    type U in \p W, such that T and U have the same number of elements.
309   /// 3. Ensure that for each vector type U in \p W, there exists a vector
310   ///    type T in \p V, such that T and U have the same number of elements
311   ///    (reverse of 2).
312   bool EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W);
313   /// 1. Ensure that for each type T in \p A, there exists a type U in \p B,
314   ///    such that T and U have equal size in bits.
315   /// 2. Ensure that for each type U in \p B, there exists a type T in \p A
316   ///    such that T and U have equal size in bits (reverse of 1).
317   bool EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B);
318 
319   /// For each overloaded type (i.e. of form *Any), replace it with the
320   /// corresponding subset of legal, specific types.
321   void expandOverloads(TypeSetByHwMode &VTS);
322   void expandOverloads(TypeSetByHwMode::SetType &Out,
323                        const TypeSetByHwMode::SetType &Legal);
324 
325   struct ValidateOnExit {
326     ValidateOnExit(TypeSetByHwMode &T, TypeInfer &TI) : Infer(TI), VTS(T) {}
327   #ifndef NDEBUG
328     ~ValidateOnExit();
329   #else
330     ~ValidateOnExit() {}  // Empty destructor with NDEBUG.
331   #endif
332     TypeInfer &Infer;
333     TypeSetByHwMode &VTS;
334   };
335 
336   TreePattern &TP;
337   unsigned ForceMode;     // Mode to use when set.
338   bool CodeGen = false;   // Set during generation of matcher code.
339 
340 private:
341   TypeSetByHwMode getLegalTypes();
342 
343   /// Cached legal types.
344   bool LegalTypesCached = false;
345   TypeSetByHwMode::SetType LegalCache = {};
346 };
347 
348 /// Set type used to track multiply used variables in patterns
349 typedef StringSet<> MultipleUseVarSet;
350 
351 /// SDTypeConstraint - This is a discriminated union of constraints,
352 /// corresponding to the SDTypeConstraint tablegen class in Target.td.
353 struct SDTypeConstraint {
354   SDTypeConstraint(Record *R, const CodeGenHwModes &CGH);
355 
356   unsigned OperandNo;   // The operand # this constraint applies to.
357   enum {
358     SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisVec, SDTCisSameAs,
359     SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisEltOfVec,
360     SDTCisSubVecOfVec, SDTCVecEltisVT, SDTCisSameNumEltsAs, SDTCisSameSizeAs
361   } ConstraintType;
362 
363   union {   // The discriminated union.
364     struct {
365       unsigned OtherOperandNum;
366     } SDTCisSameAs_Info;
367     struct {
368       unsigned OtherOperandNum;
369     } SDTCisVTSmallerThanOp_Info;
370     struct {
371       unsigned BigOperandNum;
372     } SDTCisOpSmallerThanOp_Info;
373     struct {
374       unsigned OtherOperandNum;
375     } SDTCisEltOfVec_Info;
376     struct {
377       unsigned OtherOperandNum;
378     } SDTCisSubVecOfVec_Info;
379     struct {
380       unsigned OtherOperandNum;
381     } SDTCisSameNumEltsAs_Info;
382     struct {
383       unsigned OtherOperandNum;
384     } SDTCisSameSizeAs_Info;
385   } x;
386 
387   // The VT for SDTCisVT and SDTCVecEltisVT.
388   // Must not be in the union because it has a non-trivial destructor.
389   ValueTypeByHwMode VVT;
390 
391   /// ApplyTypeConstraint - Given a node in a pattern, apply this type
392   /// constraint to the nodes operands.  This returns true if it makes a
393   /// change, false otherwise.  If a type contradiction is found, an error
394   /// is flagged.
395   bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
396                            TreePattern &TP) const;
397 };
398 
399 /// SDNodeInfo - One of these records is created for each SDNode instance in
400 /// the target .td file.  This represents the various dag nodes we will be
401 /// processing.
402 class SDNodeInfo {
403   Record *Def;
404   StringRef EnumName;
405   StringRef SDClassName;
406   unsigned Properties;
407   unsigned NumResults;
408   int NumOperands;
409   std::vector<SDTypeConstraint> TypeConstraints;
410 public:
411   // Parse the specified record.
412   SDNodeInfo(Record *R, const CodeGenHwModes &CGH);
413 
414   unsigned getNumResults() const { return NumResults; }
415 
416   /// getNumOperands - This is the number of operands required or -1 if
417   /// variadic.
418   int getNumOperands() const { return NumOperands; }
419   Record *getRecord() const { return Def; }
420   StringRef getEnumName() const { return EnumName; }
421   StringRef getSDClassName() const { return SDClassName; }
422 
423   const std::vector<SDTypeConstraint> &getTypeConstraints() const {
424     return TypeConstraints;
425   }
426 
427   /// getKnownType - If the type constraints on this node imply a fixed type
428   /// (e.g. all stores return void, etc), then return it as an
429   /// MVT::SimpleValueType.  Otherwise, return MVT::Other.
430   MVT::SimpleValueType getKnownType(unsigned ResNo) const;
431 
432   /// hasProperty - Return true if this node has the specified property.
433   ///
434   bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
435 
436   /// ApplyTypeConstraints - Given a node in a pattern, apply the type
437   /// constraints for this node to the operands of the node.  This returns
438   /// true if it makes a change, false otherwise.  If a type contradiction is
439   /// found, an error is flagged.
440   bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const;
441 };
442 
443 /// TreePredicateFn - This is an abstraction that represents the predicates on
444 /// a PatFrag node.  This is a simple one-word wrapper around a pointer to
445 /// provide nice accessors.
446 class TreePredicateFn {
447   /// PatFragRec - This is the TreePattern for the PatFrag that we
448   /// originally came from.
449   TreePattern *PatFragRec;
450 public:
451   /// TreePredicateFn constructor.  Here 'N' is a subclass of PatFrag.
452   TreePredicateFn(TreePattern *N);
453 
454 
455   TreePattern *getOrigPatFragRecord() const { return PatFragRec; }
456 
457   /// isAlwaysTrue - Return true if this is a noop predicate.
458   bool isAlwaysTrue() const;
459 
460   bool isImmediatePattern() const { return hasImmCode(); }
461 
462   /// getImmediatePredicateCode - Return the code that evaluates this pattern if
463   /// this is an immediate predicate.  It is an error to call this on a
464   /// non-immediate pattern.
465   std::string getImmediatePredicateCode() const {
466     std::string Result = getImmCode();
467     assert(!Result.empty() && "Isn't an immediate pattern!");
468     return Result;
469   }
470 
471   bool operator==(const TreePredicateFn &RHS) const {
472     return PatFragRec == RHS.PatFragRec;
473   }
474 
475   bool operator!=(const TreePredicateFn &RHS) const { return !(*this == RHS); }
476 
477   /// Return the name to use in the generated code to reference this, this is
478   /// "Predicate_foo" if from a pattern fragment "foo".
479   std::string getFnName() const;
480 
481   /// getCodeToRunOnSDNode - Return the code for the function body that
482   /// evaluates this predicate.  The argument is expected to be in "Node",
483   /// not N.  This handles casting and conversion to a concrete node type as
484   /// appropriate.
485   std::string getCodeToRunOnSDNode() const;
486 
487   /// Get the data type of the argument to getImmediatePredicateCode().
488   StringRef getImmType() const;
489 
490   /// Get a string that describes the type returned by getImmType() but is
491   /// usable as part of an identifier.
492   StringRef getImmTypeIdentifier() const;
493 
494   // Is the desired predefined predicate for a load?
495   bool isLoad() const;
496   // Is the desired predefined predicate for a store?
497   bool isStore() const;
498   // Is the desired predefined predicate for an atomic?
499   bool isAtomic() const;
500 
501   /// Is this predicate the predefined unindexed load predicate?
502   /// Is this predicate the predefined unindexed store predicate?
503   bool isUnindexed() const;
504   /// Is this predicate the predefined non-extending load predicate?
505   bool isNonExtLoad() const;
506   /// Is this predicate the predefined any-extend load predicate?
507   bool isAnyExtLoad() const;
508   /// Is this predicate the predefined sign-extend load predicate?
509   bool isSignExtLoad() const;
510   /// Is this predicate the predefined zero-extend load predicate?
511   bool isZeroExtLoad() const;
512   /// Is this predicate the predefined non-truncating store predicate?
513   bool isNonTruncStore() const;
514   /// Is this predicate the predefined truncating store predicate?
515   bool isTruncStore() const;
516 
517   /// Is this predicate the predefined monotonic atomic predicate?
518   bool isAtomicOrderingMonotonic() const;
519   /// Is this predicate the predefined acquire atomic predicate?
520   bool isAtomicOrderingAcquire() const;
521   /// Is this predicate the predefined release atomic predicate?
522   bool isAtomicOrderingRelease() const;
523   /// Is this predicate the predefined acquire-release atomic predicate?
524   bool isAtomicOrderingAcquireRelease() const;
525   /// Is this predicate the predefined sequentially consistent atomic predicate?
526   bool isAtomicOrderingSequentiallyConsistent() const;
527 
528   /// Is this predicate the predefined acquire-or-stronger atomic predicate?
529   bool isAtomicOrderingAcquireOrStronger() const;
530   /// Is this predicate the predefined weaker-than-acquire atomic predicate?
531   bool isAtomicOrderingWeakerThanAcquire() const;
532 
533   /// Is this predicate the predefined release-or-stronger atomic predicate?
534   bool isAtomicOrderingReleaseOrStronger() const;
535   /// Is this predicate the predefined weaker-than-release atomic predicate?
536   bool isAtomicOrderingWeakerThanRelease() const;
537 
538   /// If non-null, indicates that this predicate is a predefined memory VT
539   /// predicate for a load/store and returns the ValueType record for the memory VT.
540   Record *getMemoryVT() const;
541   /// If non-null, indicates that this predicate is a predefined memory VT
542   /// predicate (checking only the scalar type) for load/store and returns the
543   /// ValueType record for the memory VT.
544   Record *getScalarMemoryVT() const;
545 
546 private:
547   bool hasPredCode() const;
548   bool hasImmCode() const;
549   std::string getPredCode() const;
550   std::string getImmCode() const;
551   bool immCodeUsesAPInt() const;
552   bool immCodeUsesAPFloat() const;
553 
554   bool isPredefinedPredicateEqualTo(StringRef Field, bool Value) const;
555 };
556 
557 
558 class TreePatternNode {
559   /// The type of each node result.  Before and during type inference, each
560   /// result may be a set of possible types.  After (successful) type inference,
561   /// each is a single concrete type.
562   std::vector<TypeSetByHwMode> Types;
563 
564   /// Operator - The Record for the operator if this is an interior node (not
565   /// a leaf).
566   Record *Operator;
567 
568   /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
569   ///
570   Init *Val;
571 
572   /// Name - The name given to this node with the :$foo notation.
573   ///
574   std::string Name;
575 
576   /// PredicateFns - The predicate functions to execute on this node to check
577   /// for a match.  If this list is empty, no predicate is involved.
578   std::vector<TreePredicateFn> PredicateFns;
579 
580   /// TransformFn - The transformation function to execute on this node before
581   /// it can be substituted into the resulting instruction on a pattern match.
582   Record *TransformFn;
583 
584   std::vector<TreePatternNodePtr> Children;
585 
586 public:
587   TreePatternNode(Record *Op, std::vector<TreePatternNodePtr> &Ch,
588                   unsigned NumResults)
589       : Operator(Op), Val(nullptr), TransformFn(nullptr), Children(Ch) {
590     Types.resize(NumResults);
591   }
592   TreePatternNode(Init *val, unsigned NumResults)    // leaf ctor
593     : Operator(nullptr), Val(val), TransformFn(nullptr) {
594     Types.resize(NumResults);
595   }
596 
597   bool hasName() const { return !Name.empty(); }
598   const std::string &getName() const { return Name; }
599   void setName(StringRef N) { Name.assign(N.begin(), N.end()); }
600 
601   bool isLeaf() const { return Val != nullptr; }
602 
603   // Type accessors.
604   unsigned getNumTypes() const { return Types.size(); }
605   ValueTypeByHwMode getType(unsigned ResNo) const {
606     return Types[ResNo].getValueTypeByHwMode();
607   }
608   const std::vector<TypeSetByHwMode> &getExtTypes() const { return Types; }
609   const TypeSetByHwMode &getExtType(unsigned ResNo) const {
610     return Types[ResNo];
611   }
612   TypeSetByHwMode &getExtType(unsigned ResNo) { return Types[ResNo]; }
613   void setType(unsigned ResNo, const TypeSetByHwMode &T) { Types[ResNo] = T; }
614   MVT::SimpleValueType getSimpleType(unsigned ResNo) const {
615     return Types[ResNo].getMachineValueType().SimpleTy;
616   }
617 
618   bool hasConcreteType(unsigned ResNo) const {
619     return Types[ResNo].isValueTypeByHwMode(false);
620   }
621   bool isTypeCompletelyUnknown(unsigned ResNo, TreePattern &TP) const {
622     return Types[ResNo].empty();
623   }
624 
625   Init *getLeafValue() const { assert(isLeaf()); return Val; }
626   Record *getOperator() const { assert(!isLeaf()); return Operator; }
627 
628   unsigned getNumChildren() const { return Children.size(); }
629   TreePatternNode *getChild(unsigned N) const { return Children[N].get(); }
630   const TreePatternNodePtr &getChildShared(unsigned N) const {
631     return Children[N];
632   }
633   void setChild(unsigned i, TreePatternNodePtr N) { Children[i] = N; }
634 
635   /// hasChild - Return true if N is any of our children.
636   bool hasChild(const TreePatternNode *N) const {
637     for (unsigned i = 0, e = Children.size(); i != e; ++i)
638       if (Children[i].get() == N)
639         return true;
640     return false;
641   }
642 
643   bool hasProperTypeByHwMode() const;
644   bool hasPossibleType() const;
645   bool setDefaultMode(unsigned Mode);
646 
647   bool hasAnyPredicate() const { return !PredicateFns.empty(); }
648 
649   const std::vector<TreePredicateFn> &getPredicateFns() const {
650     return PredicateFns;
651   }
652   void clearPredicateFns() { PredicateFns.clear(); }
653   void setPredicateFns(const std::vector<TreePredicateFn> &Fns) {
654     assert(PredicateFns.empty() && "Overwriting non-empty predicate list!");
655     PredicateFns = Fns;
656   }
657   void addPredicateFn(const TreePredicateFn &Fn) {
658     assert(!Fn.isAlwaysTrue() && "Empty predicate string!");
659     if (!is_contained(PredicateFns, Fn))
660       PredicateFns.push_back(Fn);
661   }
662 
663   Record *getTransformFn() const { return TransformFn; }
664   void setTransformFn(Record *Fn) { TransformFn = Fn; }
665 
666   /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
667   /// CodeGenIntrinsic information for it, otherwise return a null pointer.
668   const CodeGenIntrinsic *getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const;
669 
670   /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
671   /// return the ComplexPattern information, otherwise return null.
672   const ComplexPattern *
673   getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const;
674 
675   /// Returns the number of MachineInstr operands that would be produced by this
676   /// node if it mapped directly to an output Instruction's
677   /// operand. ComplexPattern specifies this explicitly; MIOperandInfo gives it
678   /// for Operands; otherwise 1.
679   unsigned getNumMIResults(const CodeGenDAGPatterns &CGP) const;
680 
681   /// NodeHasProperty - Return true if this node has the specified property.
682   bool NodeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const;
683 
684   /// TreeHasProperty - Return true if any node in this tree has the specified
685   /// property.
686   bool TreeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const;
687 
688   /// isCommutativeIntrinsic - Return true if the node is an intrinsic which is
689   /// marked isCommutative.
690   bool isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const;
691 
692   void print(raw_ostream &OS) const;
693   void dump() const;
694 
695 public:   // Higher level manipulation routines.
696 
697   /// clone - Return a new copy of this tree.
698   ///
699   TreePatternNodePtr clone() const;
700 
701   /// RemoveAllTypes - Recursively strip all the types of this tree.
702   void RemoveAllTypes();
703 
704   /// isIsomorphicTo - Return true if this node is recursively isomorphic to
705   /// the specified node.  For this comparison, all of the state of the node
706   /// is considered, except for the assigned name.  Nodes with differing names
707   /// that are otherwise identical are considered isomorphic.
708   bool isIsomorphicTo(const TreePatternNode *N,
709                       const MultipleUseVarSet &DepVars) const;
710 
711   /// SubstituteFormalArguments - Replace the formal arguments in this tree
712   /// with actual values specified by ArgMap.
713   void
714   SubstituteFormalArguments(std::map<std::string, TreePatternNodePtr> &ArgMap);
715 
716   /// InlinePatternFragments - If this pattern refers to any pattern
717   /// fragments, inline them into place, giving us a pattern without any
718   /// PatFrag references.
719   TreePatternNodePtr InlinePatternFragments(TreePatternNodePtr T,
720                                             TreePattern &TP);
721 
722   /// ApplyTypeConstraints - Apply all of the type constraints relevant to
723   /// this node and its children in the tree.  This returns true if it makes a
724   /// change, false otherwise.  If a type contradiction is found, flag an error.
725   bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
726 
727   /// UpdateNodeType - Set the node type of N to VT if VT contains
728   /// information.  If N already contains a conflicting type, then flag an
729   /// error.  This returns true if any information was updated.
730   ///
731   bool UpdateNodeType(unsigned ResNo, const TypeSetByHwMode &InTy,
732                       TreePattern &TP);
733   bool UpdateNodeType(unsigned ResNo, MVT::SimpleValueType InTy,
734                       TreePattern &TP);
735   bool UpdateNodeType(unsigned ResNo, ValueTypeByHwMode InTy,
736                       TreePattern &TP);
737 
738   // Update node type with types inferred from an instruction operand or result
739   // def from the ins/outs lists.
740   // Return true if the type changed.
741   bool UpdateNodeTypeFromInst(unsigned ResNo, Record *Operand, TreePattern &TP);
742 
743   /// ContainsUnresolvedType - Return true if this tree contains any
744   /// unresolved types.
745   bool ContainsUnresolvedType(TreePattern &TP) const;
746 
747   /// canPatternMatch - If it is impossible for this pattern to match on this
748   /// target, fill in Reason and return false.  Otherwise, return true.
749   bool canPatternMatch(std::string &Reason, const CodeGenDAGPatterns &CDP);
750 };
751 
752 inline raw_ostream &operator<<(raw_ostream &OS, const TreePatternNode &TPN) {
753   TPN.print(OS);
754   return OS;
755 }
756 
757 
758 /// TreePattern - Represent a pattern, used for instructions, pattern
759 /// fragments, etc.
760 ///
761 class TreePattern {
762   /// Trees - The list of pattern trees which corresponds to this pattern.
763   /// Note that PatFrag's only have a single tree.
764   ///
765   std::vector<TreePatternNodePtr> Trees;
766 
767   /// NamedNodes - This is all of the nodes that have names in the trees in this
768   /// pattern.
769   StringMap<SmallVector<TreePatternNode *, 1>> NamedNodes;
770 
771   /// TheRecord - The actual TableGen record corresponding to this pattern.
772   ///
773   Record *TheRecord;
774 
775   /// Args - This is a list of all of the arguments to this pattern (for
776   /// PatFrag patterns), which are the 'node' markers in this pattern.
777   std::vector<std::string> Args;
778 
779   /// CDP - the top-level object coordinating this madness.
780   ///
781   CodeGenDAGPatterns &CDP;
782 
783   /// isInputPattern - True if this is an input pattern, something to match.
784   /// False if this is an output pattern, something to emit.
785   bool isInputPattern;
786 
787   /// hasError - True if the currently processed nodes have unresolvable types
788   /// or other non-fatal errors
789   bool HasError;
790 
791   /// It's important that the usage of operands in ComplexPatterns is
792   /// consistent: each named operand can be defined by at most one
793   /// ComplexPattern. This records the ComplexPattern instance and the operand
794   /// number for each operand encountered in a ComplexPattern to aid in that
795   /// check.
796   StringMap<std::pair<Record *, unsigned>> ComplexPatternOperands;
797 
798   TypeInfer Infer;
799 
800 public:
801 
802   /// TreePattern constructor - Parse the specified DagInits into the
803   /// current record.
804   TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
805               CodeGenDAGPatterns &ise);
806   TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
807               CodeGenDAGPatterns &ise);
808   TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
809               CodeGenDAGPatterns &ise);
810 
811   /// getTrees - Return the tree patterns which corresponds to this pattern.
812   ///
813   const std::vector<TreePatternNodePtr> &getTrees() const { return Trees; }
814   unsigned getNumTrees() const { return Trees.size(); }
815   const TreePatternNodePtr &getTree(unsigned i) const { return Trees[i]; }
816   void setTree(unsigned i, TreePatternNodePtr Tree) { Trees[i] = Tree; }
817   TreePatternNodePtr getOnlyTree() const {
818     assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
819     return Trees[0];
820   }
821 
822   const StringMap<SmallVector<TreePatternNode *, 1>> &getNamedNodesMap() {
823     if (NamedNodes.empty())
824       ComputeNamedNodes();
825     return NamedNodes;
826   }
827 
828   /// getRecord - Return the actual TableGen record corresponding to this
829   /// pattern.
830   ///
831   Record *getRecord() const { return TheRecord; }
832 
833   unsigned getNumArgs() const { return Args.size(); }
834   const std::string &getArgName(unsigned i) const {
835     assert(i < Args.size() && "Argument reference out of range!");
836     return Args[i];
837   }
838   std::vector<std::string> &getArgList() { return Args; }
839 
840   CodeGenDAGPatterns &getDAGPatterns() const { return CDP; }
841 
842   /// InlinePatternFragments - If this pattern refers to any pattern
843   /// fragments, inline them into place, giving us a pattern without any
844   /// PatFrag references.
845   void InlinePatternFragments() {
846     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
847       Trees[i] = Trees[i]->InlinePatternFragments(Trees[i], *this);
848   }
849 
850   /// InferAllTypes - Infer/propagate as many types throughout the expression
851   /// patterns as possible.  Return true if all types are inferred, false
852   /// otherwise.  Bail out if a type contradiction is found.
853   bool InferAllTypes(
854       const StringMap<SmallVector<TreePatternNode *, 1>> *NamedTypes = nullptr);
855 
856   /// error - If this is the first error in the current resolution step,
857   /// print it and set the error flag.  Otherwise, continue silently.
858   void error(const Twine &Msg);
859   bool hasError() const {
860     return HasError;
861   }
862   void resetError() {
863     HasError = false;
864   }
865 
866   TypeInfer &getInfer() { return Infer; }
867 
868   void print(raw_ostream &OS) const;
869   void dump() const;
870 
871 private:
872   TreePatternNodePtr ParseTreePattern(Init *DI, StringRef OpName);
873   void ComputeNamedNodes();
874   void ComputeNamedNodes(TreePatternNode *N);
875 };
876 
877 
878 inline bool TreePatternNode::UpdateNodeType(unsigned ResNo,
879                                             const TypeSetByHwMode &InTy,
880                                             TreePattern &TP) {
881   TypeSetByHwMode VTS(InTy);
882   TP.getInfer().expandOverloads(VTS);
883   return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS);
884 }
885 
886 inline bool TreePatternNode::UpdateNodeType(unsigned ResNo,
887                                             MVT::SimpleValueType InTy,
888                                             TreePattern &TP) {
889   TypeSetByHwMode VTS(InTy);
890   TP.getInfer().expandOverloads(VTS);
891   return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS);
892 }
893 
894 inline bool TreePatternNode::UpdateNodeType(unsigned ResNo,
895                                             ValueTypeByHwMode InTy,
896                                             TreePattern &TP) {
897   TypeSetByHwMode VTS(InTy);
898   TP.getInfer().expandOverloads(VTS);
899   return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS);
900 }
901 
902 
903 /// DAGDefaultOperand - One of these is created for each OperandWithDefaultOps
904 /// that has a set ExecuteAlways / DefaultOps field.
905 struct DAGDefaultOperand {
906   std::vector<TreePatternNodePtr> DefaultOps;
907 };
908 
909 class DAGInstruction {
910   TreePattern *Pattern;
911   std::vector<Record*> Results;
912   std::vector<Record*> Operands;
913   std::vector<Record*> ImpResults;
914   TreePatternNodePtr ResultPattern;
915 
916 public:
917   DAGInstruction(TreePattern *TP,
918                  const std::vector<Record*> &results,
919                  const std::vector<Record*> &operands,
920                  const std::vector<Record*> &impresults)
921     : Pattern(TP), Results(results), Operands(operands),
922       ImpResults(impresults), ResultPattern(nullptr) {}
923 
924   TreePattern *getPattern() const { return Pattern; }
925   unsigned getNumResults() const { return Results.size(); }
926   unsigned getNumOperands() const { return Operands.size(); }
927   unsigned getNumImpResults() const { return ImpResults.size(); }
928   const std::vector<Record*>& getImpResults() const { return ImpResults; }
929 
930   void setResultPattern(TreePatternNodePtr R) { ResultPattern = R; }
931 
932   Record *getResult(unsigned RN) const {
933     assert(RN < Results.size());
934     return Results[RN];
935   }
936 
937   Record *getOperand(unsigned ON) const {
938     assert(ON < Operands.size());
939     return Operands[ON];
940   }
941 
942   Record *getImpResult(unsigned RN) const {
943     assert(RN < ImpResults.size());
944     return ImpResults[RN];
945   }
946 
947   TreePatternNodePtr getResultPattern() const { return ResultPattern; }
948 };
949 
950 /// This class represents a condition that has to be satisfied for a pattern
951 /// to be tried. It is a generalization of a class "Pattern" from Target.td:
952 /// in addition to the Target.td's predicates, this class can also represent
953 /// conditions associated with HW modes. Both types will eventually become
954 /// strings containing C++ code to be executed, the difference is in how
955 /// these strings are generated.
956 class Predicate {
957 public:
958   Predicate(Record *R, bool C = true) : Def(R), IfCond(C), IsHwMode(false) {
959     assert(R->isSubClassOf("Predicate") &&
960            "Predicate objects should only be created for records derived"
961            "from Predicate class");
962   }
963   Predicate(StringRef FS, bool C = true) : Def(nullptr), Features(FS.str()),
964     IfCond(C), IsHwMode(true) {}
965 
966   /// Return a string which contains the C++ condition code that will serve
967   /// as a predicate during instruction selection.
968   std::string getCondString() const {
969     // The string will excute in a subclass of SelectionDAGISel.
970     // Cast to std::string explicitly to avoid ambiguity with StringRef.
971     std::string C = IsHwMode
972         ? std::string("MF->getSubtarget().checkFeatures(\"" + Features + "\")")
973         : std::string(Def->getValueAsString("CondString"));
974     return IfCond ? C : "!("+C+')';
975   }
976   bool operator==(const Predicate &P) const {
977     return IfCond == P.IfCond && IsHwMode == P.IsHwMode && Def == P.Def;
978   }
979   bool operator<(const Predicate &P) const {
980     if (IsHwMode != P.IsHwMode)
981       return IsHwMode < P.IsHwMode;
982     assert(!Def == !P.Def && "Inconsistency between Def and IsHwMode");
983     if (IfCond != P.IfCond)
984       return IfCond < P.IfCond;
985     if (Def)
986       return LessRecord()(Def, P.Def);
987     return Features < P.Features;
988   }
989   Record *Def;            ///< Predicate definition from .td file, null for
990                           ///< HW modes.
991   std::string Features;   ///< Feature string for HW mode.
992   bool IfCond;            ///< The boolean value that the condition has to
993                           ///< evaluate to for this predicate to be true.
994   bool IsHwMode;          ///< Does this predicate correspond to a HW mode?
995 };
996 
997 /// PatternToMatch - Used by CodeGenDAGPatterns to keep tab of patterns
998 /// processed to produce isel.
999 class PatternToMatch {
1000 public:
1001   PatternToMatch(Record *srcrecord, const std::vector<Predicate> &preds,
1002                  TreePatternNodePtr src, TreePatternNodePtr dst,
1003                  const std::vector<Record *> &dstregs, int complexity,
1004                  unsigned uid, unsigned setmode = 0)
1005       : SrcRecord(srcrecord), SrcPattern(src), DstPattern(dst),
1006         Predicates(preds), Dstregs(std::move(dstregs)),
1007         AddedComplexity(complexity), ID(uid), ForceMode(setmode) {}
1008 
1009   PatternToMatch(Record *srcrecord, std::vector<Predicate> &&preds,
1010                  TreePatternNodePtr src, TreePatternNodePtr dst,
1011                  std::vector<Record *> &&dstregs, int complexity, unsigned uid,
1012                  unsigned setmode = 0)
1013       : SrcRecord(srcrecord), SrcPattern(src), DstPattern(dst),
1014         Predicates(preds), Dstregs(std::move(dstregs)),
1015         AddedComplexity(complexity), ID(uid), ForceMode(setmode) {}
1016 
1017   Record          *SrcRecord;   // Originating Record for the pattern.
1018   TreePatternNodePtr SrcPattern;      // Source pattern to match.
1019   TreePatternNodePtr DstPattern;      // Resulting pattern.
1020   std::vector<Predicate> Predicates;  // Top level predicate conditions
1021                                       // to match.
1022   std::vector<Record*> Dstregs; // Physical register defs being matched.
1023   int              AddedComplexity; // Add to matching pattern complexity.
1024   unsigned         ID;          // Unique ID for the record.
1025   unsigned         ForceMode;   // Force this mode in type inference when set.
1026 
1027   Record          *getSrcRecord()  const { return SrcRecord; }
1028   TreePatternNode *getSrcPattern() const { return SrcPattern.get(); }
1029   TreePatternNodePtr getSrcPatternShared() const { return SrcPattern; }
1030   TreePatternNode *getDstPattern() const { return DstPattern.get(); }
1031   TreePatternNodePtr getDstPatternShared() const { return DstPattern; }
1032   const std::vector<Record*> &getDstRegs() const { return Dstregs; }
1033   int         getAddedComplexity() const { return AddedComplexity; }
1034   const std::vector<Predicate> &getPredicates() const { return Predicates; }
1035 
1036   std::string getPredicateCheck() const;
1037 
1038   /// Compute the complexity metric for the input pattern.  This roughly
1039   /// corresponds to the number of nodes that are covered.
1040   int getPatternComplexity(const CodeGenDAGPatterns &CGP) const;
1041 };
1042 
1043 class CodeGenDAGPatterns {
1044   RecordKeeper &Records;
1045   CodeGenTarget Target;
1046   CodeGenIntrinsicTable Intrinsics;
1047   CodeGenIntrinsicTable TgtIntrinsics;
1048 
1049   std::map<Record*, SDNodeInfo, LessRecordByID> SDNodes;
1050   std::map<Record*, std::pair<Record*, std::string>, LessRecordByID>
1051       SDNodeXForms;
1052   std::map<Record*, ComplexPattern, LessRecordByID> ComplexPatterns;
1053   std::map<Record *, std::unique_ptr<TreePattern>, LessRecordByID>
1054       PatternFragments;
1055   std::map<Record*, DAGDefaultOperand, LessRecordByID> DefaultOperands;
1056   std::map<Record*, DAGInstruction, LessRecordByID> Instructions;
1057 
1058   // Specific SDNode definitions:
1059   Record *intrinsic_void_sdnode;
1060   Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode;
1061 
1062   /// PatternsToMatch - All of the things we are matching on the DAG.  The first
1063   /// value is the pattern to match, the second pattern is the result to
1064   /// emit.
1065   std::vector<PatternToMatch> PatternsToMatch;
1066 
1067   TypeSetByHwMode LegalVTS;
1068 
1069   using PatternRewriterFn = std::function<void (TreePattern *)>;
1070   PatternRewriterFn PatternRewriter;
1071 
1072 public:
1073   CodeGenDAGPatterns(RecordKeeper &R,
1074                      PatternRewriterFn PatternRewriter = nullptr);
1075 
1076   CodeGenTarget &getTargetInfo() { return Target; }
1077   const CodeGenTarget &getTargetInfo() const { return Target; }
1078   const TypeSetByHwMode &getLegalTypes() const { return LegalVTS; }
1079 
1080   Record *getSDNodeNamed(const std::string &Name) const;
1081 
1082   const SDNodeInfo &getSDNodeInfo(Record *R) const {
1083     auto F = SDNodes.find(R);
1084     assert(F != SDNodes.end() && "Unknown node!");
1085     return F->second;
1086   }
1087 
1088   // Node transformation lookups.
1089   typedef std::pair<Record*, std::string> NodeXForm;
1090   const NodeXForm &getSDNodeTransform(Record *R) const {
1091     auto F = SDNodeXForms.find(R);
1092     assert(F != SDNodeXForms.end() && "Invalid transform!");
1093     return F->second;
1094   }
1095 
1096   typedef std::map<Record*, NodeXForm, LessRecordByID>::const_iterator
1097           nx_iterator;
1098   nx_iterator nx_begin() const { return SDNodeXForms.begin(); }
1099   nx_iterator nx_end() const { return SDNodeXForms.end(); }
1100 
1101 
1102   const ComplexPattern &getComplexPattern(Record *R) const {
1103     auto F = ComplexPatterns.find(R);
1104     assert(F != ComplexPatterns.end() && "Unknown addressing mode!");
1105     return F->second;
1106   }
1107 
1108   const CodeGenIntrinsic &getIntrinsic(Record *R) const {
1109     for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
1110       if (Intrinsics[i].TheDef == R) return Intrinsics[i];
1111     for (unsigned i = 0, e = TgtIntrinsics.size(); i != e; ++i)
1112       if (TgtIntrinsics[i].TheDef == R) return TgtIntrinsics[i];
1113     llvm_unreachable("Unknown intrinsic!");
1114   }
1115 
1116   const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const {
1117     if (IID-1 < Intrinsics.size())
1118       return Intrinsics[IID-1];
1119     if (IID-Intrinsics.size()-1 < TgtIntrinsics.size())
1120       return TgtIntrinsics[IID-Intrinsics.size()-1];
1121     llvm_unreachable("Bad intrinsic ID!");
1122   }
1123 
1124   unsigned getIntrinsicID(Record *R) const {
1125     for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
1126       if (Intrinsics[i].TheDef == R) return i;
1127     for (unsigned i = 0, e = TgtIntrinsics.size(); i != e; ++i)
1128       if (TgtIntrinsics[i].TheDef == R) return i + Intrinsics.size();
1129     llvm_unreachable("Unknown intrinsic!");
1130   }
1131 
1132   const DAGDefaultOperand &getDefaultOperand(Record *R) const {
1133     auto F = DefaultOperands.find(R);
1134     assert(F != DefaultOperands.end() &&"Isn't an analyzed default operand!");
1135     return F->second;
1136   }
1137 
1138   // Pattern Fragment information.
1139   TreePattern *getPatternFragment(Record *R) const {
1140     auto F = PatternFragments.find(R);
1141     assert(F != PatternFragments.end() && "Invalid pattern fragment request!");
1142     return F->second.get();
1143   }
1144   TreePattern *getPatternFragmentIfRead(Record *R) const {
1145     auto F = PatternFragments.find(R);
1146     if (F == PatternFragments.end())
1147       return nullptr;
1148     return F->second.get();
1149   }
1150 
1151   typedef std::map<Record *, std::unique_ptr<TreePattern>,
1152                    LessRecordByID>::const_iterator pf_iterator;
1153   pf_iterator pf_begin() const { return PatternFragments.begin(); }
1154   pf_iterator pf_end() const { return PatternFragments.end(); }
1155   iterator_range<pf_iterator> ptfs() const { return PatternFragments; }
1156 
1157   // Patterns to match information.
1158   typedef std::vector<PatternToMatch>::const_iterator ptm_iterator;
1159   ptm_iterator ptm_begin() const { return PatternsToMatch.begin(); }
1160   ptm_iterator ptm_end() const { return PatternsToMatch.end(); }
1161   iterator_range<ptm_iterator> ptms() const { return PatternsToMatch; }
1162 
1163   /// Parse the Pattern for an instruction, and insert the result in DAGInsts.
1164   typedef std::map<Record*, DAGInstruction, LessRecordByID> DAGInstMap;
1165   const DAGInstruction &parseInstructionPattern(
1166       CodeGenInstruction &CGI, ListInit *Pattern,
1167       DAGInstMap &DAGInsts);
1168 
1169   const DAGInstruction &getInstruction(Record *R) const {
1170     auto F = Instructions.find(R);
1171     assert(F != Instructions.end() && "Unknown instruction!");
1172     return F->second;
1173   }
1174 
1175   Record *get_intrinsic_void_sdnode() const {
1176     return intrinsic_void_sdnode;
1177   }
1178   Record *get_intrinsic_w_chain_sdnode() const {
1179     return intrinsic_w_chain_sdnode;
1180   }
1181   Record *get_intrinsic_wo_chain_sdnode() const {
1182     return intrinsic_wo_chain_sdnode;
1183   }
1184 
1185   bool hasTargetIntrinsics() { return !TgtIntrinsics.empty(); }
1186 
1187 private:
1188   void ParseNodeInfo();
1189   void ParseNodeTransforms();
1190   void ParseComplexPatterns();
1191   void ParsePatternFragments(bool OutFrags = false);
1192   void ParseDefaultOperands();
1193   void ParseInstructions();
1194   void ParsePatterns();
1195   void ExpandHwModeBasedTypes();
1196   void InferInstructionFlags();
1197   void GenerateVariants();
1198   void VerifyInstructionFlags();
1199 
1200   std::vector<Predicate> makePredList(ListInit *L);
1201 
1202   void AddPatternToMatch(TreePattern *Pattern, PatternToMatch &&PTM);
1203   void FindPatternInputsAndOutputs(
1204       TreePattern *I, TreePatternNodePtr Pat,
1205       std::map<std::string, TreePatternNodePtr> &InstInputs,
1206       std::map<std::string, TreePatternNodePtr> &InstResults,
1207       std::vector<Record *> &InstImpResults);
1208 };
1209 
1210 
1211 inline bool SDNodeInfo::ApplyTypeConstraints(TreePatternNode *N,
1212                                              TreePattern &TP) const {
1213     bool MadeChange = false;
1214     for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
1215       MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
1216     return MadeChange;
1217   }
1218 
1219 } // end namespace llvm
1220 
1221 #endif
1222