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