• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- llvm/Target/TargetLowering.h - Target Lowering Info -----*- 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 /// \file
11 /// This file describes how to lower LLVM code to machine code.  This has two
12 /// main components:
13 ///
14 ///  1. Which ValueTypes are natively supported by the target.
15 ///  2. Which operations are supported for supported ValueTypes.
16 ///  3. Cost thresholds for alternative implementations of certain operations.
17 ///
18 /// In addition it has a few other components, like information about FP
19 /// immediates.
20 ///
21 //===----------------------------------------------------------------------===//
22 
23 #ifndef LLVM_TARGET_TARGETLOWERING_H
24 #define LLVM_TARGET_TARGETLOWERING_H
25 
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/CodeGen/DAGCombine.h"
28 #include "llvm/CodeGen/RuntimeLibcalls.h"
29 #include "llvm/CodeGen/SelectionDAGNodes.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/Support/CallSite.h"
34 #include "llvm/Target/TargetCallingConv.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include <climits>
37 #include <map>
38 #include <vector>
39 
40 namespace llvm {
41   class CallInst;
42   class CCState;
43   class FastISel;
44   class FunctionLoweringInfo;
45   class ImmutableCallSite;
46   class IntrinsicInst;
47   class MachineBasicBlock;
48   class MachineFunction;
49   class MachineInstr;
50   class MachineJumpTableInfo;
51   class MCContext;
52   class MCExpr;
53   template<typename T> class SmallVectorImpl;
54   class DataLayout;
55   class TargetRegisterClass;
56   class TargetLibraryInfo;
57   class TargetLoweringObjectFile;
58   class Value;
59 
60   namespace Sched {
61     enum Preference {
62       None,             // No preference
63       Source,           // Follow source order.
64       RegPressure,      // Scheduling for lowest register pressure.
65       Hybrid,           // Scheduling for both latency and register pressure.
66       ILP,              // Scheduling for ILP in low register pressure mode.
67       VLIW              // Scheduling for VLIW targets.
68     };
69   }
70 
71 /// This base class for TargetLowering contains the SelectionDAG-independent
72 /// parts that can be used from the rest of CodeGen.
73 class TargetLoweringBase {
74   TargetLoweringBase(const TargetLoweringBase&) LLVM_DELETED_FUNCTION;
75   void operator=(const TargetLoweringBase&) LLVM_DELETED_FUNCTION;
76 
77 public:
78   /// This enum indicates whether operations are valid for a target, and if not,
79   /// what action should be used to make them valid.
80   enum LegalizeAction {
81     Legal,      // The target natively supports this operation.
82     Promote,    // This operation should be executed in a larger type.
83     Expand,     // Try to expand this to other ops, otherwise use a libcall.
84     Custom      // Use the LowerOperation hook to implement custom lowering.
85   };
86 
87   /// This enum indicates whether a types are legal for a target, and if not,
88   /// what action should be used to make them valid.
89   enum LegalizeTypeAction {
90     TypeLegal,           // The target natively supports this type.
91     TypePromoteInteger,  // Replace this integer with a larger one.
92     TypeExpandInteger,   // Split this integer into two of half the size.
93     TypeSoftenFloat,     // Convert this float to a same size integer type.
94     TypeExpandFloat,     // Split this float into two of half the size.
95     TypeScalarizeVector, // Replace this one-element vector with its element.
96     TypeSplitVector,     // Split this vector into two of half the size.
97     TypeWidenVector      // This vector should be widened into a larger vector.
98   };
99 
100   /// LegalizeKind holds the legalization kind that needs to happen to EVT
101   /// in order to type-legalize it.
102   typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind;
103 
104   /// Enum that describes how the target represents true/false values.
105   enum BooleanContent {
106     UndefinedBooleanContent,    // Only bit 0 counts, the rest can hold garbage.
107     ZeroOrOneBooleanContent,        // All bits zero except for bit 0.
108     ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
109   };
110 
111   /// Enum that describes what type of support for selects the target has.
112   enum SelectSupportKind {
113     ScalarValSelect,      // The target supports scalar selects (ex: cmov).
114     ScalarCondVectorVal,  // The target supports selects with a scalar condition
115                           // and vector values (ex: cmov).
116     VectorMaskSelect      // The target supports vector selects with a vector
117                           // mask (ex: x86 blends).
118   };
119 
getExtendForContent(BooleanContent Content)120   static ISD::NodeType getExtendForContent(BooleanContent Content) {
121     switch (Content) {
122     case UndefinedBooleanContent:
123       // Extend by adding rubbish bits.
124       return ISD::ANY_EXTEND;
125     case ZeroOrOneBooleanContent:
126       // Extend by adding zero bits.
127       return ISD::ZERO_EXTEND;
128     case ZeroOrNegativeOneBooleanContent:
129       // Extend by copying the sign bit.
130       return ISD::SIGN_EXTEND;
131     }
132     llvm_unreachable("Invalid content kind");
133   }
134 
135   /// NOTE: The constructor takes ownership of TLOF.
136   explicit TargetLoweringBase(const TargetMachine &TM,
137                               const TargetLoweringObjectFile *TLOF);
138   virtual ~TargetLoweringBase();
139 
140 protected:
141   /// \brief Initialize all of the actions to default values.
142   void initActions();
143 
144 public:
getTargetMachine()145   const TargetMachine &getTargetMachine() const { return TM; }
getDataLayout()146   const DataLayout *getDataLayout() const { return TD; }
getObjFileLowering()147   const TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; }
148 
isBigEndian()149   bool isBigEndian() const { return !IsLittleEndian; }
isLittleEndian()150   bool isLittleEndian() const { return IsLittleEndian; }
151   // Return the pointer type for the given address space, defaults to
152   // the pointer type from the data layout.
153   // FIXME: The default needs to be removed once all the code is updated.
154   virtual MVT getPointerTy(uint32_t /*AS*/ = 0) const { return PointerTy; }
155   virtual MVT getScalarShiftAmountTy(EVT LHSTy) const;
156 
157   EVT getShiftAmountTy(EVT LHSTy) const;
158 
159   /// Returns the type to be used for the index operand of:
160   /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
161   /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
getVectorIdxTy()162   virtual MVT getVectorIdxTy() const {
163     return getPointerTy();
164   }
165 
166   /// Return true if the select operation is expensive for this target.
isSelectExpensive()167   bool isSelectExpensive() const { return SelectIsExpensive; }
168 
isSelectSupported(SelectSupportKind)169   virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
170     return true;
171   }
172 
173   /// Return true if a vector of the given type should be split
174   /// (TypeSplitVector) instead of promoted (TypePromoteInteger) during type
175   /// legalization.
shouldSplitVectorElementType(EVT)176   virtual bool shouldSplitVectorElementType(EVT /*VT*/) const { return false; }
177 
178   /// Return true if integer divide is usually cheaper than a sequence of
179   /// several shifts, adds, and multiplies for this target.
isIntDivCheap()180   bool isIntDivCheap() const { return IntDivIsCheap; }
181 
182   /// Returns true if target has indicated at least one type should be bypassed.
isSlowDivBypassed()183   bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
184 
185   /// Returns map of slow types for division or remainder with corresponding
186   /// fast types
getBypassSlowDivWidths()187   const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
188     return BypassSlowDivWidths;
189   }
190 
191   /// Return true if pow2 div is cheaper than a chain of srl/add/sra.
isPow2DivCheap()192   bool isPow2DivCheap() const { return Pow2DivIsCheap; }
193 
194   /// Return true if Flow Control is an expensive operation that should be
195   /// avoided.
isJumpExpensive()196   bool isJumpExpensive() const { return JumpIsExpensive; }
197 
198   /// Return true if selects are only cheaper than branches if the branch is
199   /// unlikely to be predicted right.
isPredictableSelectExpensive()200   bool isPredictableSelectExpensive() const {
201     return PredictableSelectIsExpensive;
202   }
203 
204   /// Return the ValueType of the result of SETCC operations.  Also used to
205   /// obtain the target's preferred type for the condition operand of SELECT and
206   /// BRCOND nodes.  In the case of BRCOND the argument passed is MVT::Other
207   /// since there are no other operands to get a type hint from.
208   virtual EVT getSetCCResultType(LLVMContext &Context, EVT VT) const;
209 
210   /// Return the ValueType for comparison libcalls. Comparions libcalls include
211   /// floating point comparion calls, and Ordered/Unordered check calls on
212   /// floating point numbers.
213   virtual
214   MVT::SimpleValueType getCmpLibcallReturnType() const;
215 
216   /// For targets without i1 registers, this gives the nature of the high-bits
217   /// of boolean values held in types wider than i1.
218   ///
219   /// "Boolean values" are special true/false values produced by nodes like
220   /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
221   /// Not to be confused with general values promoted from i1.  Some cpus
222   /// distinguish between vectors of boolean and scalars; the isVec parameter
223   /// selects between the two kinds.  For example on X86 a scalar boolean should
224   /// be zero extended from i1, while the elements of a vector of booleans
225   /// should be sign extended from i1.
getBooleanContents(bool isVec)226   BooleanContent getBooleanContents(bool isVec) const {
227     return isVec ? BooleanVectorContents : BooleanContents;
228   }
229 
230   /// Return target scheduling preference.
getSchedulingPreference()231   Sched::Preference getSchedulingPreference() const {
232     return SchedPreferenceInfo;
233   }
234 
235   /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
236   /// for different nodes. This function returns the preference (or none) for
237   /// the given node.
getSchedulingPreference(SDNode *)238   virtual Sched::Preference getSchedulingPreference(SDNode *) const {
239     return Sched::None;
240   }
241 
242   /// Return the register class that should be used for the specified value
243   /// type.
getRegClassFor(MVT VT)244   virtual const TargetRegisterClass *getRegClassFor(MVT VT) const {
245     const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
246     assert(RC && "This value type is not natively supported!");
247     return RC;
248   }
249 
250   /// Return the 'representative' register class for the specified value
251   /// type.
252   ///
253   /// The 'representative' register class is the largest legal super-reg
254   /// register class for the register class of the value type.  For example, on
255   /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
256   /// register class is GR64 on x86_64.
getRepRegClassFor(MVT VT)257   virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
258     const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
259     return RC;
260   }
261 
262   /// Return the cost of the 'representative' register class for the specified
263   /// value type.
getRepRegClassCostFor(MVT VT)264   virtual uint8_t getRepRegClassCostFor(MVT VT) const {
265     return RepRegClassCostForVT[VT.SimpleTy];
266   }
267 
268   /// Return true if the target has native support for the specified value type.
269   /// This means that it has a register that directly holds it without
270   /// promotions or expansions.
isTypeLegal(EVT VT)271   bool isTypeLegal(EVT VT) const {
272     assert(!VT.isSimple() ||
273            (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
274     return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != 0;
275   }
276 
277   class ValueTypeActionImpl {
278     /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
279     /// that indicates how instruction selection should deal with the type.
280     uint8_t ValueTypeActions[MVT::LAST_VALUETYPE];
281 
282   public:
ValueTypeActionImpl()283     ValueTypeActionImpl() {
284       std::fill(ValueTypeActions, array_endof(ValueTypeActions), 0);
285     }
286 
getTypeAction(MVT VT)287     LegalizeTypeAction getTypeAction(MVT VT) const {
288       return (LegalizeTypeAction)ValueTypeActions[VT.SimpleTy];
289     }
290 
setTypeAction(MVT VT,LegalizeTypeAction Action)291     void setTypeAction(MVT VT, LegalizeTypeAction Action) {
292       unsigned I = VT.SimpleTy;
293       ValueTypeActions[I] = Action;
294     }
295   };
296 
getValueTypeActions()297   const ValueTypeActionImpl &getValueTypeActions() const {
298     return ValueTypeActions;
299   }
300 
301   /// Return how we should legalize values of this type, either it is already
302   /// legal (return 'Legal') or we need to promote it to a larger type (return
303   /// 'Promote'), or we need to expand it into multiple registers of smaller
304   /// integer type (return 'Expand').  'Custom' is not an option.
getTypeAction(LLVMContext & Context,EVT VT)305   LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
306     return getTypeConversion(Context, VT).first;
307   }
getTypeAction(MVT VT)308   LegalizeTypeAction getTypeAction(MVT VT) const {
309     return ValueTypeActions.getTypeAction(VT);
310   }
311 
312   /// For types supported by the target, this is an identity function.  For
313   /// types that must be promoted to larger types, this returns the larger type
314   /// to promote to.  For integer types that are larger than the largest integer
315   /// register, this contains one step in the expansion to get to the smaller
316   /// register. For illegal floating point types, this returns the integer type
317   /// to transform to.
getTypeToTransformTo(LLVMContext & Context,EVT VT)318   EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
319     return getTypeConversion(Context, VT).second;
320   }
321 
322   /// For types supported by the target, this is an identity function.  For
323   /// types that must be expanded (i.e. integer types that are larger than the
324   /// largest integer register or illegal floating point types), this returns
325   /// the largest legal type it will be expanded to.
getTypeToExpandTo(LLVMContext & Context,EVT VT)326   EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
327     assert(!VT.isVector());
328     while (true) {
329       switch (getTypeAction(Context, VT)) {
330       case TypeLegal:
331         return VT;
332       case TypeExpandInteger:
333         VT = getTypeToTransformTo(Context, VT);
334         break;
335       default:
336         llvm_unreachable("Type is not legal nor is it to be expanded!");
337       }
338     }
339   }
340 
341   /// Vector types are broken down into some number of legal first class types.
342   /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
343   /// promoted EVT::f64 values with the X86 FP stack.  Similarly, EVT::v2i64
344   /// turns into 4 EVT::i32 values with both PPC and X86.
345   ///
346   /// This method returns the number of registers needed, and the VT for each
347   /// register.  It also returns the VT and quantity of the intermediate values
348   /// before they are promoted/expanded.
349   unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
350                                   EVT &IntermediateVT,
351                                   unsigned &NumIntermediates,
352                                   MVT &RegisterVT) const;
353 
354   struct IntrinsicInfo {
355     unsigned     opc;         // target opcode
356     EVT          memVT;       // memory VT
357     const Value* ptrVal;      // value representing memory location
358     int          offset;      // offset off of ptrVal
359     unsigned     align;       // alignment
360     bool         vol;         // is volatile?
361     bool         readMem;     // reads memory?
362     bool         writeMem;    // writes memory?
363   };
364 
365   /// Given an intrinsic, checks if on the target the intrinsic will need to map
366   /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
367   /// true and store the intrinsic information into the IntrinsicInfo that was
368   /// passed to the function.
getTgtMemIntrinsic(IntrinsicInfo &,const CallInst &,unsigned)369   virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
370                                   unsigned /*Intrinsic*/) const {
371     return false;
372   }
373 
374   /// Returns true if the target can instruction select the specified FP
375   /// immediate natively. If false, the legalizer will materialize the FP
376   /// immediate as a load from a constant pool.
isFPImmLegal(const APFloat &,EVT)377   virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
378     return false;
379   }
380 
381   /// Targets can use this to indicate that they only support *some*
382   /// VECTOR_SHUFFLE operations, those with specific masks.  By default, if a
383   /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
384   /// legal.
isShuffleMaskLegal(const SmallVectorImpl<int> &,EVT)385   virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
386                                   EVT /*VT*/) const {
387     return true;
388   }
389 
390   /// Returns true if the operation can trap for the value type.
391   ///
392   /// VT must be a legal type. By default, we optimistically assume most
393   /// operations don't trap except for divide and remainder.
394   virtual bool canOpTrap(unsigned Op, EVT VT) const;
395 
396   /// Similar to isShuffleMaskLegal. This is used by Targets can use this to
397   /// indicate if there is a suitable VECTOR_SHUFFLE that can be used to replace
398   /// a VAND with a constant pool entry.
isVectorClearMaskLegal(const SmallVectorImpl<int> &,EVT)399   virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
400                                       EVT /*VT*/) const {
401     return false;
402   }
403 
404   /// Return how this operation should be treated: either it is legal, needs to
405   /// be promoted to a larger size, needs to be expanded to some other code
406   /// sequence, or the target has a custom expander for it.
getOperationAction(unsigned Op,EVT VT)407   LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
408     if (VT.isExtended()) return Expand;
409     // If a target-specific SDNode requires legalization, require the target
410     // to provide custom legalization for it.
411     if (Op > array_lengthof(OpActions[0])) return Custom;
412     unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
413     return (LegalizeAction)OpActions[I][Op];
414   }
415 
416   /// Return true if the specified operation is legal on this target or can be
417   /// made legal with custom lowering. This is used to help guide high-level
418   /// lowering decisions.
isOperationLegalOrCustom(unsigned Op,EVT VT)419   bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
420     return (VT == MVT::Other || isTypeLegal(VT)) &&
421       (getOperationAction(Op, VT) == Legal ||
422        getOperationAction(Op, VT) == Custom);
423   }
424 
425   /// Return true if the specified operation is legal on this target or can be
426   /// made legal using promotion. This is used to help guide high-level lowering
427   /// decisions.
isOperationLegalOrPromote(unsigned Op,EVT VT)428   bool isOperationLegalOrPromote(unsigned Op, EVT VT) const {
429     return (VT == MVT::Other || isTypeLegal(VT)) &&
430       (getOperationAction(Op, VT) == Legal ||
431        getOperationAction(Op, VT) == Promote);
432   }
433 
434   /// Return true if the specified operation is illegal on this target or
435   /// unlikely to be made legal with custom lowering. This is used to help guide
436   /// high-level lowering decisions.
isOperationExpand(unsigned Op,EVT VT)437   bool isOperationExpand(unsigned Op, EVT VT) const {
438     return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
439   }
440 
441   /// Return true if the specified operation is legal on this target.
isOperationLegal(unsigned Op,EVT VT)442   bool isOperationLegal(unsigned Op, EVT VT) const {
443     return (VT == MVT::Other || isTypeLegal(VT)) &&
444            getOperationAction(Op, VT) == Legal;
445   }
446 
447   /// Return how this load with extension should be treated: either it is legal,
448   /// needs to be promoted to a larger size, needs to be expanded to some other
449   /// code sequence, or the target has a custom expander for it.
getLoadExtAction(unsigned ExtType,MVT VT)450   LegalizeAction getLoadExtAction(unsigned ExtType, MVT VT) const {
451     assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
452            "Table isn't big enough!");
453     return (LegalizeAction)LoadExtActions[VT.SimpleTy][ExtType];
454   }
455 
456   /// Return true if the specified load with extension is legal on this target.
isLoadExtLegal(unsigned ExtType,EVT VT)457   bool isLoadExtLegal(unsigned ExtType, EVT VT) const {
458     return VT.isSimple() &&
459       getLoadExtAction(ExtType, VT.getSimpleVT()) == Legal;
460   }
461 
462   /// Return how this store with truncation should be treated: either it is
463   /// legal, needs to be promoted to a larger size, needs to be expanded to some
464   /// other code sequence, or the target has a custom expander for it.
getTruncStoreAction(MVT ValVT,MVT MemVT)465   LegalizeAction getTruncStoreAction(MVT ValVT, MVT MemVT) const {
466     assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
467            "Table isn't big enough!");
468     return (LegalizeAction)TruncStoreActions[ValVT.SimpleTy]
469                                             [MemVT.SimpleTy];
470   }
471 
472   /// Return true if the specified store with truncation is legal on this
473   /// target.
isTruncStoreLegal(EVT ValVT,EVT MemVT)474   bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
475     return isTypeLegal(ValVT) && MemVT.isSimple() &&
476       getTruncStoreAction(ValVT.getSimpleVT(), MemVT.getSimpleVT()) == Legal;
477   }
478 
479   /// Return how the indexed load should be treated: either it is legal, needs
480   /// to be promoted to a larger size, needs to be expanded to some other code
481   /// sequence, or the target has a custom expander for it.
482   LegalizeAction
getIndexedLoadAction(unsigned IdxMode,MVT VT)483   getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
484     assert(IdxMode < ISD::LAST_INDEXED_MODE && VT < MVT::LAST_VALUETYPE &&
485            "Table isn't big enough!");
486     unsigned Ty = (unsigned)VT.SimpleTy;
487     return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
488   }
489 
490   /// Return true if the specified indexed load is legal on this target.
isIndexedLoadLegal(unsigned IdxMode,EVT VT)491   bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
492     return VT.isSimple() &&
493       (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
494        getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
495   }
496 
497   /// Return how the indexed store should be treated: either it is legal, needs
498   /// to be promoted to a larger size, needs to be expanded to some other code
499   /// sequence, or the target has a custom expander for it.
500   LegalizeAction
getIndexedStoreAction(unsigned IdxMode,MVT VT)501   getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
502     assert(IdxMode < ISD::LAST_INDEXED_MODE && VT < MVT::LAST_VALUETYPE &&
503            "Table isn't big enough!");
504     unsigned Ty = (unsigned)VT.SimpleTy;
505     return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
506   }
507 
508   /// Return true if the specified indexed load is legal on this target.
isIndexedStoreLegal(unsigned IdxMode,EVT VT)509   bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
510     return VT.isSimple() &&
511       (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
512        getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
513   }
514 
515   /// Return how the condition code should be treated: either it is legal, needs
516   /// to be expanded to some other code sequence, or the target has a custom
517   /// expander for it.
518   LegalizeAction
getCondCodeAction(ISD::CondCode CC,MVT VT)519   getCondCodeAction(ISD::CondCode CC, MVT VT) const {
520     assert((unsigned)CC < array_lengthof(CondCodeActions) &&
521            (unsigned)VT.SimpleTy < sizeof(CondCodeActions[0])*4 &&
522            "Table isn't big enough!");
523     /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 64bit
524     /// value and the upper 27 bits index into the second dimension of the
525     /// array to select what 64bit value to use.
526     LegalizeAction Action = (LegalizeAction)
527       ((CondCodeActions[CC][VT.SimpleTy >> 5] >> (2*(VT.SimpleTy & 0x1F))) & 3);
528     assert(Action != Promote && "Can't promote condition code!");
529     return Action;
530   }
531 
532   /// Return true if the specified condition code is legal on this target.
isCondCodeLegal(ISD::CondCode CC,MVT VT)533   bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
534     return
535       getCondCodeAction(CC, VT) == Legal ||
536       getCondCodeAction(CC, VT) == Custom;
537   }
538 
539 
540   /// If the action for this operation is to promote, this method returns the
541   /// ValueType to promote to.
getTypeToPromoteTo(unsigned Op,MVT VT)542   MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
543     assert(getOperationAction(Op, VT) == Promote &&
544            "This operation isn't promoted!");
545 
546     // See if this has an explicit type specified.
547     std::map<std::pair<unsigned, MVT::SimpleValueType>,
548              MVT::SimpleValueType>::const_iterator PTTI =
549       PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
550     if (PTTI != PromoteToType.end()) return PTTI->second;
551 
552     assert((VT.isInteger() || VT.isFloatingPoint()) &&
553            "Cannot autopromote this type, add it with AddPromotedToType.");
554 
555     MVT NVT = VT;
556     do {
557       NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
558       assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
559              "Didn't find type to promote to!");
560     } while (!isTypeLegal(NVT) ||
561               getOperationAction(Op, NVT) == Promote);
562     return NVT;
563   }
564 
565   /// Return the EVT corresponding to this LLVM type.  This is fixed by the LLVM
566   /// operations except for the pointer size.  If AllowUnknown is true, this
567   /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
568   /// otherwise it will assert.
569   EVT getValueType(Type *Ty, bool AllowUnknown = false) const {
570     // Lower scalar pointers to native pointer types.
571     if (Ty->isPointerTy()) return PointerTy;
572 
573     if (Ty->isVectorTy()) {
574       VectorType *VTy = cast<VectorType>(Ty);
575       Type *Elm = VTy->getElementType();
576       // Lower vectors of pointers to native pointer types.
577       if (Elm->isPointerTy())
578         Elm = EVT(PointerTy).getTypeForEVT(Ty->getContext());
579       return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
580                        VTy->getNumElements());
581     }
582     return EVT::getEVT(Ty, AllowUnknown);
583   }
584 
585   /// Return the MVT corresponding to this LLVM type. See getValueType.
586   MVT getSimpleValueType(Type *Ty, bool AllowUnknown = false) const {
587     return getValueType(Ty, AllowUnknown).getSimpleVT();
588   }
589 
590   /// Return the desired alignment for ByVal aggregate function arguments in the
591   /// caller parameter area.  This is the actual alignment, not its logarithm.
592   virtual unsigned getByValTypeAlignment(Type *Ty) const;
593 
594   /// Return the type of registers that this ValueType will eventually require.
getRegisterType(MVT VT)595   MVT getRegisterType(MVT VT) const {
596     assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
597     return RegisterTypeForVT[VT.SimpleTy];
598   }
599 
600   /// Return the type of registers that this ValueType will eventually require.
getRegisterType(LLVMContext & Context,EVT VT)601   MVT getRegisterType(LLVMContext &Context, EVT VT) const {
602     if (VT.isSimple()) {
603       assert((unsigned)VT.getSimpleVT().SimpleTy <
604                 array_lengthof(RegisterTypeForVT));
605       return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
606     }
607     if (VT.isVector()) {
608       EVT VT1;
609       MVT RegisterVT;
610       unsigned NumIntermediates;
611       (void)getVectorTypeBreakdown(Context, VT, VT1,
612                                    NumIntermediates, RegisterVT);
613       return RegisterVT;
614     }
615     if (VT.isInteger()) {
616       return getRegisterType(Context, getTypeToTransformTo(Context, VT));
617     }
618     llvm_unreachable("Unsupported extended type!");
619   }
620 
621   /// Return the number of registers that this ValueType will eventually
622   /// require.
623   ///
624   /// This is one for any types promoted to live in larger registers, but may be
625   /// more than one for types (like i64) that are split into pieces.  For types
626   /// like i140, which are first promoted then expanded, it is the number of
627   /// registers needed to hold all the bits of the original type.  For an i140
628   /// on a 32 bit machine this means 5 registers.
getNumRegisters(LLVMContext & Context,EVT VT)629   unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
630     if (VT.isSimple()) {
631       assert((unsigned)VT.getSimpleVT().SimpleTy <
632                 array_lengthof(NumRegistersForVT));
633       return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
634     }
635     if (VT.isVector()) {
636       EVT VT1;
637       MVT VT2;
638       unsigned NumIntermediates;
639       return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
640     }
641     if (VT.isInteger()) {
642       unsigned BitWidth = VT.getSizeInBits();
643       unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
644       return (BitWidth + RegWidth - 1) / RegWidth;
645     }
646     llvm_unreachable("Unsupported extended type!");
647   }
648 
649   /// If true, then instruction selection should seek to shrink the FP constant
650   /// of the specified type to a smaller type in order to save space and / or
651   /// reduce runtime.
ShouldShrinkFPConstant(EVT)652   virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
653 
654   /// If true, the target has custom DAG combine transformations that it can
655   /// perform for the specified node.
hasTargetDAGCombine(ISD::NodeType NT)656   bool hasTargetDAGCombine(ISD::NodeType NT) const {
657     assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
658     return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
659   }
660 
661   /// \brief Get maximum # of store operations permitted for llvm.memset
662   ///
663   /// This function returns the maximum number of store operations permitted
664   /// to replace a call to llvm.memset. The value is set by the target at the
665   /// performance threshold for such a replacement. If OptSize is true,
666   /// return the limit for functions that have OptSize attribute.
getMaxStoresPerMemset(bool OptSize)667   unsigned getMaxStoresPerMemset(bool OptSize) const {
668     return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
669   }
670 
671   /// \brief Get maximum # of store operations permitted for llvm.memcpy
672   ///
673   /// This function returns the maximum number of store operations permitted
674   /// to replace a call to llvm.memcpy. The value is set by the target at the
675   /// performance threshold for such a replacement. If OptSize is true,
676   /// return the limit for functions that have OptSize attribute.
getMaxStoresPerMemcpy(bool OptSize)677   unsigned getMaxStoresPerMemcpy(bool OptSize) const {
678     return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
679   }
680 
681   /// \brief Get maximum # of store operations permitted for llvm.memmove
682   ///
683   /// This function returns the maximum number of store operations permitted
684   /// to replace a call to llvm.memmove. The value is set by the target at the
685   /// performance threshold for such a replacement. If OptSize is true,
686   /// return the limit for functions that have OptSize attribute.
getMaxStoresPerMemmove(bool OptSize)687   unsigned getMaxStoresPerMemmove(bool OptSize) const {
688     return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
689   }
690 
691   /// \brief Determine if the target supports unaligned memory accesses.
692   ///
693   /// This function returns true if the target allows unaligned memory accesses.
694   /// of the specified type. If true, it also returns whether the unaligned
695   /// memory access is "fast" in the second argument by reference. This is used,
696   /// for example, in situations where an array copy/move/set is converted to a
697   /// sequence of store operations. It's use helps to ensure that such
698   /// replacements don't generate code that causes an alignment error (trap) on
699   /// the target machine.
700   virtual bool allowsUnalignedMemoryAccesses(EVT, bool * /*Fast*/ = 0) const {
701     return false;
702   }
703 
704   /// Returns the target specific optimal type for load and store operations as
705   /// a result of memset, memcpy, and memmove lowering.
706   ///
707   /// If DstAlign is zero that means it's safe to destination alignment can
708   /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
709   /// a need to check it against alignment requirement, probably because the
710   /// source does not need to be loaded. If 'IsMemset' is true, that means it's
711   /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
712   /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
713   /// does not need to be loaded.  It returns EVT::Other if the type should be
714   /// determined using generic target-independent logic.
getOptimalMemOpType(uint64_t,unsigned,unsigned,bool,bool,bool,MachineFunction &)715   virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
716                                   unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
717                                   bool /*IsMemset*/,
718                                   bool /*ZeroMemset*/,
719                                   bool /*MemcpyStrSrc*/,
720                                   MachineFunction &/*MF*/) const {
721     return MVT::Other;
722   }
723 
724   /// Returns true if it's safe to use load / store of the specified type to
725   /// expand memcpy / memset inline.
726   ///
727   /// This is mostly true for all types except for some special cases. For
728   /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
729   /// fstpl which also does type conversion. Note the specified type doesn't
730   /// have to be legal as the hook is used before type legalization.
isSafeMemOpType(MVT)731   virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
732 
733   /// Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
usesUnderscoreSetJmp()734   bool usesUnderscoreSetJmp() const {
735     return UseUnderscoreSetJmp;
736   }
737 
738   /// Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
usesUnderscoreLongJmp()739   bool usesUnderscoreLongJmp() const {
740     return UseUnderscoreLongJmp;
741   }
742 
743   /// Return whether the target can generate code for jump tables.
supportJumpTables()744   bool supportJumpTables() const {
745     return SupportJumpTables;
746   }
747 
748   /// Return integer threshold on number of blocks to use jump tables rather
749   /// than if sequence.
getMinimumJumpTableEntries()750   int getMinimumJumpTableEntries() const {
751     return MinimumJumpTableEntries;
752   }
753 
754   /// If a physical register, this specifies the register that
755   /// llvm.savestack/llvm.restorestack should save and restore.
getStackPointerRegisterToSaveRestore()756   unsigned getStackPointerRegisterToSaveRestore() const {
757     return StackPointerRegisterToSaveRestore;
758   }
759 
760   /// If a physical register, this returns the register that receives the
761   /// exception address on entry to a landing pad.
getExceptionPointerRegister()762   unsigned getExceptionPointerRegister() const {
763     return ExceptionPointerRegister;
764   }
765 
766   /// If a physical register, this returns the register that receives the
767   /// exception typeid on entry to a landing pad.
getExceptionSelectorRegister()768   unsigned getExceptionSelectorRegister() const {
769     return ExceptionSelectorRegister;
770   }
771 
772   /// Returns the target's jmp_buf size in bytes (if never set, the default is
773   /// 200)
getJumpBufSize()774   unsigned getJumpBufSize() const {
775     return JumpBufSize;
776   }
777 
778   /// Returns the target's jmp_buf alignment in bytes (if never set, the default
779   /// is 0)
getJumpBufAlignment()780   unsigned getJumpBufAlignment() const {
781     return JumpBufAlignment;
782   }
783 
784   /// Return the minimum stack alignment of an argument.
getMinStackArgumentAlignment()785   unsigned getMinStackArgumentAlignment() const {
786     return MinStackArgumentAlignment;
787   }
788 
789   /// Return the minimum function alignment.
getMinFunctionAlignment()790   unsigned getMinFunctionAlignment() const {
791     return MinFunctionAlignment;
792   }
793 
794   /// Return the preferred function alignment.
getPrefFunctionAlignment()795   unsigned getPrefFunctionAlignment() const {
796     return PrefFunctionAlignment;
797   }
798 
799   /// Return the preferred loop alignment.
getPrefLoopAlignment()800   unsigned getPrefLoopAlignment() const {
801     return PrefLoopAlignment;
802   }
803 
804   /// Return whether the DAG builder should automatically insert fences and
805   /// reduce ordering for atomics.
getInsertFencesForAtomic()806   bool getInsertFencesForAtomic() const {
807     return InsertFencesForAtomic;
808   }
809 
810   /// Return true if the target stores stack protector cookies at a fixed offset
811   /// in some non-standard address space, and populates the address space and
812   /// offset as appropriate.
getStackCookieLocation(unsigned &,unsigned &)813   virtual bool getStackCookieLocation(unsigned &/*AddressSpace*/,
814                                       unsigned &/*Offset*/) const {
815     return false;
816   }
817 
818   /// Returns the maximal possible offset which can be used for loads / stores
819   /// from the global.
getMaximalGlobalOffset()820   virtual unsigned getMaximalGlobalOffset() const {
821     return 0;
822   }
823 
824   //===--------------------------------------------------------------------===//
825   /// \name Helpers for TargetTransformInfo implementations
826   /// @{
827 
828   /// Get the ISD node that corresponds to the Instruction class opcode.
829   int InstructionOpcodeToISD(unsigned Opcode) const;
830 
831   /// Estimate the cost of type-legalization and the legalized type.
832   std::pair<unsigned, MVT> getTypeLegalizationCost(Type *Ty) const;
833 
834   /// @}
835 
836   //===--------------------------------------------------------------------===//
837   // TargetLowering Configuration Methods - These methods should be invoked by
838   // the derived class constructor to configure this object for the target.
839   //
840 
841   /// \brief Reset the operation actions based on target options.
resetOperationActions()842   virtual void resetOperationActions() {}
843 
844 protected:
845   /// Specify how the target extends the result of a boolean value from i1 to a
846   /// wider type.  See getBooleanContents.
setBooleanContents(BooleanContent Ty)847   void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
848 
849   /// Specify how the target extends the result of a vector boolean value from a
850   /// vector of i1 to a wider type.  See getBooleanContents.
setBooleanVectorContents(BooleanContent Ty)851   void setBooleanVectorContents(BooleanContent Ty) {
852     BooleanVectorContents = Ty;
853   }
854 
855   /// Specify the target scheduling preference.
setSchedulingPreference(Sched::Preference Pref)856   void setSchedulingPreference(Sched::Preference Pref) {
857     SchedPreferenceInfo = Pref;
858   }
859 
860   /// Indicate whether this target prefers to use _setjmp to implement
861   /// llvm.setjmp or the non _ version.  Defaults to false.
setUseUnderscoreSetJmp(bool Val)862   void setUseUnderscoreSetJmp(bool Val) {
863     UseUnderscoreSetJmp = Val;
864   }
865 
866   /// Indicate whether this target prefers to use _longjmp to implement
867   /// llvm.longjmp or the non _ version.  Defaults to false.
setUseUnderscoreLongJmp(bool Val)868   void setUseUnderscoreLongJmp(bool Val) {
869     UseUnderscoreLongJmp = Val;
870   }
871 
872   /// Indicate whether the target can generate code for jump tables.
setSupportJumpTables(bool Val)873   void setSupportJumpTables(bool Val) {
874     SupportJumpTables = Val;
875   }
876 
877   /// Indicate the number of blocks to generate jump tables rather than if
878   /// sequence.
setMinimumJumpTableEntries(int Val)879   void setMinimumJumpTableEntries(int Val) {
880     MinimumJumpTableEntries = Val;
881   }
882 
883   /// If set to a physical register, this specifies the register that
884   /// llvm.savestack/llvm.restorestack should save and restore.
setStackPointerRegisterToSaveRestore(unsigned R)885   void setStackPointerRegisterToSaveRestore(unsigned R) {
886     StackPointerRegisterToSaveRestore = R;
887   }
888 
889   /// If set to a physical register, this sets the register that receives the
890   /// exception address on entry to a landing pad.
setExceptionPointerRegister(unsigned R)891   void setExceptionPointerRegister(unsigned R) {
892     ExceptionPointerRegister = R;
893   }
894 
895   /// If set to a physical register, this sets the register that receives the
896   /// exception typeid on entry to a landing pad.
setExceptionSelectorRegister(unsigned R)897   void setExceptionSelectorRegister(unsigned R) {
898     ExceptionSelectorRegister = R;
899   }
900 
901   /// Tells the code generator not to expand operations into sequences that use
902   /// the select operations if possible.
903   void setSelectIsExpensive(bool isExpensive = true) {
904     SelectIsExpensive = isExpensive;
905   }
906 
907   /// Tells the code generator not to expand sequence of operations into a
908   /// separate sequences that increases the amount of flow control.
909   void setJumpIsExpensive(bool isExpensive = true) {
910     JumpIsExpensive = isExpensive;
911   }
912 
913   /// Tells the code generator that integer divide is expensive, and if
914   /// possible, should be replaced by an alternate sequence of instructions not
915   /// containing an integer divide.
916   void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
917 
918   /// Tells the code generator which bitwidths to bypass.
addBypassSlowDiv(unsigned int SlowBitWidth,unsigned int FastBitWidth)919   void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
920     BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
921   }
922 
923   /// Tells the code generator that it shouldn't generate srl/add/sra for a
924   /// signed divide by power of two, and let the target handle it.
925   void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
926 
927   /// Add the specified register class as an available regclass for the
928   /// specified value type. This indicates the selector can handle values of
929   /// that class natively.
addRegisterClass(MVT VT,const TargetRegisterClass * RC)930   void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
931     assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
932     AvailableRegClasses.push_back(std::make_pair(VT, RC));
933     RegClassForVT[VT.SimpleTy] = RC;
934   }
935 
936   /// Remove all register classes.
clearRegisterClasses()937   void clearRegisterClasses() {
938     memset(RegClassForVT, 0,MVT::LAST_VALUETYPE * sizeof(TargetRegisterClass*));
939 
940     AvailableRegClasses.clear();
941   }
942 
943   /// \brief Remove all operation actions.
clearOperationActions()944   void clearOperationActions() {
945   }
946 
947   /// Return the largest legal super-reg register class of the register class
948   /// for the specified type and its associated "cost".
949   virtual std::pair<const TargetRegisterClass*, uint8_t>
950   findRepresentativeClass(MVT VT) const;
951 
952   /// Once all of the register classes are added, this allows us to compute
953   /// derived properties we expose.
954   void computeRegisterProperties();
955 
956   /// Indicate that the specified operation does not work with the specified
957   /// type and indicate what to do about it.
setOperationAction(unsigned Op,MVT VT,LegalizeAction Action)958   void setOperationAction(unsigned Op, MVT VT,
959                           LegalizeAction Action) {
960     assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
961     OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action;
962   }
963 
964   /// Indicate that the specified load with extension does not work with the
965   /// specified type and indicate what to do about it.
setLoadExtAction(unsigned ExtType,MVT VT,LegalizeAction Action)966   void setLoadExtAction(unsigned ExtType, MVT VT,
967                         LegalizeAction Action) {
968     assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
969            "Table isn't big enough!");
970     LoadExtActions[VT.SimpleTy][ExtType] = (uint8_t)Action;
971   }
972 
973   /// Indicate that the specified truncating store does not work with the
974   /// specified type and indicate what to do about it.
setTruncStoreAction(MVT ValVT,MVT MemVT,LegalizeAction Action)975   void setTruncStoreAction(MVT ValVT, MVT MemVT,
976                            LegalizeAction Action) {
977     assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
978            "Table isn't big enough!");
979     TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action;
980   }
981 
982   /// Indicate that the specified indexed load does or does not work with the
983   /// specified type and indicate what to do abort it.
984   ///
985   /// NOTE: All indexed mode loads are initialized to Expand in
986   /// TargetLowering.cpp
setIndexedLoadAction(unsigned IdxMode,MVT VT,LegalizeAction Action)987   void setIndexedLoadAction(unsigned IdxMode, MVT VT,
988                             LegalizeAction Action) {
989     assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
990            (unsigned)Action < 0xf && "Table isn't big enough!");
991     // Load action are kept in the upper half.
992     IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
993     IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
994   }
995 
996   /// Indicate that the specified indexed store does or does not work with the
997   /// specified type and indicate what to do about it.
998   ///
999   /// NOTE: All indexed mode stores are initialized to Expand in
1000   /// TargetLowering.cpp
setIndexedStoreAction(unsigned IdxMode,MVT VT,LegalizeAction Action)1001   void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1002                              LegalizeAction Action) {
1003     assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1004            (unsigned)Action < 0xf && "Table isn't big enough!");
1005     // Store action are kept in the lower half.
1006     IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1007     IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1008   }
1009 
1010   /// Indicate that the specified condition code is or isn't supported on the
1011   /// target and indicate what to do about it.
setCondCodeAction(ISD::CondCode CC,MVT VT,LegalizeAction Action)1012   void setCondCodeAction(ISD::CondCode CC, MVT VT,
1013                          LegalizeAction Action) {
1014     assert(VT < MVT::LAST_VALUETYPE &&
1015            (unsigned)CC < array_lengthof(CondCodeActions) &&
1016            "Table isn't big enough!");
1017     /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 64bit
1018     /// value and the upper 27 bits index into the second dimension of the
1019     /// array to select what 64bit value to use.
1020     CondCodeActions[(unsigned)CC][VT.SimpleTy >> 5]
1021       &= ~(uint64_t(3UL)  << (VT.SimpleTy & 0x1F)*2);
1022     CondCodeActions[(unsigned)CC][VT.SimpleTy >> 5]
1023       |= (uint64_t)Action << (VT.SimpleTy & 0x1F)*2;
1024   }
1025 
1026   /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
1027   /// to trying a larger integer/fp until it can find one that works. If that
1028   /// default is insufficient, this method can be used by the target to override
1029   /// the default.
AddPromotedToType(unsigned Opc,MVT OrigVT,MVT DestVT)1030   void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1031     PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1032   }
1033 
1034   /// Targets should invoke this method for each target independent node that
1035   /// they want to provide a custom DAG combiner for by implementing the
1036   /// PerformDAGCombine virtual method.
setTargetDAGCombine(ISD::NodeType NT)1037   void setTargetDAGCombine(ISD::NodeType NT) {
1038     assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1039     TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1040   }
1041 
1042   /// Set the target's required jmp_buf buffer size (in bytes); default is 200
setJumpBufSize(unsigned Size)1043   void setJumpBufSize(unsigned Size) {
1044     JumpBufSize = Size;
1045   }
1046 
1047   /// Set the target's required jmp_buf buffer alignment (in bytes); default is
1048   /// 0
setJumpBufAlignment(unsigned Align)1049   void setJumpBufAlignment(unsigned Align) {
1050     JumpBufAlignment = Align;
1051   }
1052 
1053   /// Set the target's minimum function alignment (in log2(bytes))
setMinFunctionAlignment(unsigned Align)1054   void setMinFunctionAlignment(unsigned Align) {
1055     MinFunctionAlignment = Align;
1056   }
1057 
1058   /// Set the target's preferred function alignment.  This should be set if
1059   /// there is a performance benefit to higher-than-minimum alignment (in
1060   /// log2(bytes))
setPrefFunctionAlignment(unsigned Align)1061   void setPrefFunctionAlignment(unsigned Align) {
1062     PrefFunctionAlignment = Align;
1063   }
1064 
1065   /// Set the target's preferred loop alignment. Default alignment is zero, it
1066   /// means the target does not care about loop alignment.  The alignment is
1067   /// specified in log2(bytes).
setPrefLoopAlignment(unsigned Align)1068   void setPrefLoopAlignment(unsigned Align) {
1069     PrefLoopAlignment = Align;
1070   }
1071 
1072   /// Set the minimum stack alignment of an argument (in log2(bytes)).
setMinStackArgumentAlignment(unsigned Align)1073   void setMinStackArgumentAlignment(unsigned Align) {
1074     MinStackArgumentAlignment = Align;
1075   }
1076 
1077   /// Set if the DAG builder should automatically insert fences and reduce the
1078   /// order of atomic memory operations to Monotonic.
setInsertFencesForAtomic(bool fence)1079   void setInsertFencesForAtomic(bool fence) {
1080     InsertFencesForAtomic = fence;
1081   }
1082 
1083 public:
1084   //===--------------------------------------------------------------------===//
1085   // Addressing mode description hooks (used by LSR etc).
1086   //
1087 
1088   /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
1089   /// instructions reading the address. This allows as much computation as
1090   /// possible to be done in the address mode for that operand. This hook lets
1091   /// targets also pass back when this should be done on intrinsics which
1092   /// load/store.
GetAddrModeArguments(IntrinsicInst *,SmallVectorImpl<Value * > &,Type * &)1093   virtual bool GetAddrModeArguments(IntrinsicInst * /*I*/,
1094                                     SmallVectorImpl<Value*> &/*Ops*/,
1095                                     Type *&/*AccessTy*/) const {
1096     return false;
1097   }
1098 
1099   /// This represents an addressing mode of:
1100   ///    BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1101   /// If BaseGV is null,  there is no BaseGV.
1102   /// If BaseOffs is zero, there is no base offset.
1103   /// If HasBaseReg is false, there is no base register.
1104   /// If Scale is zero, there is no ScaleReg.  Scale of 1 indicates a reg with
1105   /// no scale.
1106   struct AddrMode {
1107     GlobalValue *BaseGV;
1108     int64_t      BaseOffs;
1109     bool         HasBaseReg;
1110     int64_t      Scale;
AddrModeAddrMode1111     AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1112   };
1113 
1114   /// Return true if the addressing mode represented by AM is legal for this
1115   /// target, for a load/store of the specified type.
1116   ///
1117   /// The type may be VoidTy, in which case only return true if the addressing
1118   /// mode is legal for a load/store of any legal type.  TODO: Handle
1119   /// pre/postinc as well.
1120   virtual bool isLegalAddressingMode(const AddrMode &AM, Type *Ty) const;
1121 
1122   /// \brief Return the cost of the scaling factor used in the addressing mode
1123   /// represented by AM for this target, for a load/store of the specified type.
1124   ///
1125   /// If the AM is supported, the return value must be >= 0.
1126   /// If the AM is not supported, it returns a negative value.
1127   /// TODO: Handle pre/postinc as well.
getScalingFactorCost(const AddrMode & AM,Type * Ty)1128   virtual int getScalingFactorCost(const AddrMode &AM, Type *Ty) const {
1129     // Default: assume that any scaling factor used in a legal AM is free.
1130     if (isLegalAddressingMode(AM, Ty)) return 0;
1131     return -1;
1132   }
1133 
1134   /// Return true if the specified immediate is legal icmp immediate, that is
1135   /// the target has icmp instructions which can compare a register against the
1136   /// immediate without having to materialize the immediate into a register.
isLegalICmpImmediate(int64_t)1137   virtual bool isLegalICmpImmediate(int64_t) const {
1138     return true;
1139   }
1140 
1141   /// Return true if the specified immediate is legal add immediate, that is the
1142   /// target has add instructions which can add a register with the immediate
1143   /// without having to materialize the immediate into a register.
isLegalAddImmediate(int64_t)1144   virtual bool isLegalAddImmediate(int64_t) const {
1145     return true;
1146   }
1147 
1148   /// Return true if it's free to truncate a value of type Ty1 to type
1149   /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
1150   /// by referencing its sub-register AX.
isTruncateFree(Type *,Type *)1151   virtual bool isTruncateFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1152     return false;
1153   }
1154 
1155   /// Return true if a truncation from Ty1 to Ty2 is permitted when deciding
1156   /// whether a call is in tail position. Typically this means that both results
1157   /// would be assigned to the same register or stack slot, but it could mean
1158   /// the target performs adequate checks of its own before proceeding with the
1159   /// tail call.
allowTruncateForTailCall(Type *,Type *)1160   virtual bool allowTruncateForTailCall(Type * /*Ty1*/, Type * /*Ty2*/) const {
1161     return false;
1162   }
1163 
isTruncateFree(EVT,EVT)1164   virtual bool isTruncateFree(EVT /*VT1*/, EVT /*VT2*/) const {
1165     return false;
1166   }
1167 
1168   /// Return true if any actual instruction that defines a value of type Ty1
1169   /// implicitly zero-extends the value to Ty2 in the result register.
1170   ///
1171   /// This does not necessarily include registers defined in unknown ways, such
1172   /// as incoming arguments, or copies from unknown virtual registers. Also, if
1173   /// isTruncateFree(Ty2, Ty1) is true, this does not necessarily apply to
1174   /// truncate instructions. e.g. on x86-64, all instructions that define 32-bit
1175   /// values implicit zero-extend the result out to 64 bits.
isZExtFree(Type *,Type *)1176   virtual bool isZExtFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1177     return false;
1178   }
1179 
isZExtFree(EVT,EVT)1180   virtual bool isZExtFree(EVT /*VT1*/, EVT /*VT2*/) const {
1181     return false;
1182   }
1183 
1184   /// Return true if zero-extending the specific node Val to type VT2 is free
1185   /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
1186   /// because it's folded such as X86 zero-extending loads).
isZExtFree(SDValue Val,EVT VT2)1187   virtual bool isZExtFree(SDValue Val, EVT VT2) const {
1188     return isZExtFree(Val.getValueType(), VT2);
1189   }
1190 
1191   /// Return true if an fneg operation is free to the point where it is never
1192   /// worthwhile to replace it with a bitwise operation.
isFNegFree(EVT VT)1193   virtual bool isFNegFree(EVT VT) const {
1194     assert(VT.isFloatingPoint());
1195     return false;
1196   }
1197 
1198   /// Return true if an fabs operation is free to the point where it is never
1199   /// worthwhile to replace it with a bitwise operation.
isFAbsFree(EVT VT)1200   virtual bool isFAbsFree(EVT VT) const {
1201     assert(VT.isFloatingPoint());
1202     return false;
1203   }
1204 
1205   /// Return true if an FMA operation is faster than a pair of fmul and fadd
1206   /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
1207   /// returns true, otherwise fmuladd is expanded to fmul + fadd.
1208   ///
1209   /// NOTE: This may be called before legalization on types for which FMAs are
1210   /// not legal, but should return true if those types will eventually legalize
1211   /// to types that support FMAs. After legalization, it will only be called on
1212   /// types that support FMAs (via Legal or Custom actions)
isFMAFasterThanFMulAndFAdd(EVT)1213   virtual bool isFMAFasterThanFMulAndFAdd(EVT) const {
1214     return false;
1215   }
1216 
1217   /// Return true if it's profitable to narrow operations of type VT1 to
1218   /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
1219   /// i32 to i16.
isNarrowingProfitable(EVT,EVT)1220   virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
1221     return false;
1222   }
1223 
1224   //===--------------------------------------------------------------------===//
1225   // Runtime Library hooks
1226   //
1227 
1228   /// Rename the default libcall routine name for the specified libcall.
setLibcallName(RTLIB::Libcall Call,const char * Name)1229   void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1230     LibcallRoutineNames[Call] = Name;
1231   }
1232 
1233   /// Get the libcall routine name for the specified libcall.
getLibcallName(RTLIB::Libcall Call)1234   const char *getLibcallName(RTLIB::Libcall Call) const {
1235     return LibcallRoutineNames[Call];
1236   }
1237 
1238   /// Override the default CondCode to be used to test the result of the
1239   /// comparison libcall against zero.
setCmpLibcallCC(RTLIB::Libcall Call,ISD::CondCode CC)1240   void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1241     CmpLibcallCCs[Call] = CC;
1242   }
1243 
1244   /// Get the CondCode that's to be used to test the result of the comparison
1245   /// libcall against zero.
getCmpLibcallCC(RTLIB::Libcall Call)1246   ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1247     return CmpLibcallCCs[Call];
1248   }
1249 
1250   /// Set the CallingConv that should be used for the specified libcall.
setLibcallCallingConv(RTLIB::Libcall Call,CallingConv::ID CC)1251   void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
1252     LibcallCallingConvs[Call] = CC;
1253   }
1254 
1255   /// Get the CallingConv that should be used for the specified libcall.
getLibcallCallingConv(RTLIB::Libcall Call)1256   CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
1257     return LibcallCallingConvs[Call];
1258   }
1259 
1260 private:
1261   const TargetMachine &TM;
1262   const DataLayout *TD;
1263   const TargetLoweringObjectFile &TLOF;
1264 
1265   /// The type to use for pointers for the default address space, usually i32 or
1266   /// i64.
1267   MVT PointerTy;
1268 
1269   /// True if this is a little endian target.
1270   bool IsLittleEndian;
1271 
1272   /// Tells the code generator not to expand operations into sequences that use
1273   /// the select operations if possible.
1274   bool SelectIsExpensive;
1275 
1276   /// Tells the code generator not to expand integer divides by constants into a
1277   /// sequence of muls, adds, and shifts.  This is a hack until a real cost
1278   /// model is in place.  If we ever optimize for size, this will be set to true
1279   /// unconditionally.
1280   bool IntDivIsCheap;
1281 
1282   /// Tells the code generator to bypass slow divide or remainder
1283   /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
1284   /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
1285   /// div/rem when the operands are positive and less than 256.
1286   DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
1287 
1288   /// Tells the code generator that it shouldn't generate srl/add/sra for a
1289   /// signed divide by power of two, and let the target handle it.
1290   bool Pow2DivIsCheap;
1291 
1292   /// Tells the code generator that it shouldn't generate extra flow control
1293   /// instructions and should attempt to combine flow control instructions via
1294   /// predication.
1295   bool JumpIsExpensive;
1296 
1297   /// This target prefers to use _setjmp to implement llvm.setjmp.
1298   ///
1299   /// Defaults to false.
1300   bool UseUnderscoreSetJmp;
1301 
1302   /// This target prefers to use _longjmp to implement llvm.longjmp.
1303   ///
1304   /// Defaults to false.
1305   bool UseUnderscoreLongJmp;
1306 
1307   /// Whether the target can generate code for jumptables.  If it's not true,
1308   /// then each jumptable must be lowered into if-then-else's.
1309   bool SupportJumpTables;
1310 
1311   /// Number of blocks threshold to use jump tables.
1312   int MinimumJumpTableEntries;
1313 
1314   /// Information about the contents of the high-bits in boolean values held in
1315   /// a type wider than i1. See getBooleanContents.
1316   BooleanContent BooleanContents;
1317 
1318   /// Information about the contents of the high-bits in boolean vector values
1319   /// when the element type is wider than i1. See getBooleanContents.
1320   BooleanContent BooleanVectorContents;
1321 
1322   /// The target scheduling preference: shortest possible total cycles or lowest
1323   /// register usage.
1324   Sched::Preference SchedPreferenceInfo;
1325 
1326   /// The size, in bytes, of the target's jmp_buf buffers
1327   unsigned JumpBufSize;
1328 
1329   /// The alignment, in bytes, of the target's jmp_buf buffers
1330   unsigned JumpBufAlignment;
1331 
1332   /// The minimum alignment that any argument on the stack needs to have.
1333   unsigned MinStackArgumentAlignment;
1334 
1335   /// The minimum function alignment (used when optimizing for size, and to
1336   /// prevent explicitly provided alignment from leading to incorrect code).
1337   unsigned MinFunctionAlignment;
1338 
1339   /// The preferred function alignment (used when alignment unspecified and
1340   /// optimizing for speed).
1341   unsigned PrefFunctionAlignment;
1342 
1343   /// The preferred loop alignment.
1344   unsigned PrefLoopAlignment;
1345 
1346   /// Whether the DAG builder should automatically insert fences and reduce
1347   /// ordering for atomics.  (This will be set for for most architectures with
1348   /// weak memory ordering.)
1349   bool InsertFencesForAtomic;
1350 
1351   /// If set to a physical register, this specifies the register that
1352   /// llvm.savestack/llvm.restorestack should save and restore.
1353   unsigned StackPointerRegisterToSaveRestore;
1354 
1355   /// If set to a physical register, this specifies the register that receives
1356   /// the exception address on entry to a landing pad.
1357   unsigned ExceptionPointerRegister;
1358 
1359   /// If set to a physical register, this specifies the register that receives
1360   /// the exception typeid on entry to a landing pad.
1361   unsigned ExceptionSelectorRegister;
1362 
1363   /// This indicates the default register class to use for each ValueType the
1364   /// target supports natively.
1365   const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1366   unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1367   MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1368 
1369   /// This indicates the "representative" register class to use for each
1370   /// ValueType the target supports natively. This information is used by the
1371   /// scheduler to track register pressure. By default, the representative
1372   /// register class is the largest legal super-reg register class of the
1373   /// register class of the specified type. e.g. On x86, i8, i16, and i32's
1374   /// representative class would be GR32.
1375   const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
1376 
1377   /// This indicates the "cost" of the "representative" register class for each
1378   /// ValueType. The cost is used by the scheduler to approximate register
1379   /// pressure.
1380   uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
1381 
1382   /// For any value types we are promoting or expanding, this contains the value
1383   /// type that we are changing to.  For Expanded types, this contains one step
1384   /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
1385   /// (e.g. i64 -> i16).  For types natively supported by the system, this holds
1386   /// the same type (e.g. i32 -> i32).
1387   MVT TransformToType[MVT::LAST_VALUETYPE];
1388 
1389   /// For each operation and each value type, keep a LegalizeAction that
1390   /// indicates how instruction selection should deal with the operation.  Most
1391   /// operations are Legal (aka, supported natively by the target), but
1392   /// operations that are not should be described.  Note that operations on
1393   /// non-legal value types are not described here.
1394   uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
1395 
1396   /// For each load extension type and each value type, keep a LegalizeAction
1397   /// that indicates how instruction selection should deal with a load of a
1398   /// specific value type and extension type.
1399   uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE];
1400 
1401   /// For each value type pair keep a LegalizeAction that indicates whether a
1402   /// truncating store of a specific value type and truncating type is legal.
1403   uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
1404 
1405   /// For each indexed mode and each value type, keep a pair of LegalizeAction
1406   /// that indicates how instruction selection should deal with the load /
1407   /// store.
1408   ///
1409   /// The first dimension is the value_type for the reference. The second
1410   /// dimension represents the various modes for load store.
1411   uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
1412 
1413   /// For each condition code (ISD::CondCode) keep a LegalizeAction that
1414   /// indicates how instruction selection should deal with the condition code.
1415   ///
1416   /// Because each CC action takes up 2 bits, we need to have the array size be
1417   /// large enough to fit all of the value types. This can be done by dividing
1418   /// the MVT::LAST_VALUETYPE by 32 and adding one.
1419   uint64_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE / 32) + 1];
1420 
1421   ValueTypeActionImpl ValueTypeActions;
1422 
1423 public:
1424   LegalizeKind
getTypeConversion(LLVMContext & Context,EVT VT)1425   getTypeConversion(LLVMContext &Context, EVT VT) const {
1426     // If this is a simple type, use the ComputeRegisterProp mechanism.
1427     if (VT.isSimple()) {
1428       MVT SVT = VT.getSimpleVT();
1429       assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
1430       MVT NVT = TransformToType[SVT.SimpleTy];
1431       LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
1432 
1433       assert(
1434         (LA == TypeLegal ||
1435          ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)
1436          && "Promote may not follow Expand or Promote");
1437 
1438       if (LA == TypeSplitVector)
1439         return LegalizeKind(LA, EVT::getVectorVT(Context,
1440                                                  SVT.getVectorElementType(),
1441                                                  SVT.getVectorNumElements()/2));
1442       if (LA == TypeScalarizeVector)
1443         return LegalizeKind(LA, SVT.getVectorElementType());
1444       return LegalizeKind(LA, NVT);
1445     }
1446 
1447     // Handle Extended Scalar Types.
1448     if (!VT.isVector()) {
1449       assert(VT.isInteger() && "Float types must be simple");
1450       unsigned BitSize = VT.getSizeInBits();
1451       // First promote to a power-of-two size, then expand if necessary.
1452       if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
1453         EVT NVT = VT.getRoundIntegerType(Context);
1454         assert(NVT != VT && "Unable to round integer VT");
1455         LegalizeKind NextStep = getTypeConversion(Context, NVT);
1456         // Avoid multi-step promotion.
1457         if (NextStep.first == TypePromoteInteger) return NextStep;
1458         // Return rounded integer type.
1459         return LegalizeKind(TypePromoteInteger, NVT);
1460       }
1461 
1462       return LegalizeKind(TypeExpandInteger,
1463                           EVT::getIntegerVT(Context, VT.getSizeInBits()/2));
1464     }
1465 
1466     // Handle vector types.
1467     unsigned NumElts = VT.getVectorNumElements();
1468     EVT EltVT = VT.getVectorElementType();
1469 
1470     // Vectors with only one element are always scalarized.
1471     if (NumElts == 1)
1472       return LegalizeKind(TypeScalarizeVector, EltVT);
1473 
1474     // Try to widen vector elements until a legal type is found.
1475     if (EltVT.isInteger()) {
1476       // Vectors with a number of elements that is not a power of two are always
1477       // widened, for example <3 x float> -> <4 x float>.
1478       if (!VT.isPow2VectorType()) {
1479         NumElts = (unsigned)NextPowerOf2(NumElts);
1480         EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
1481         return LegalizeKind(TypeWidenVector, NVT);
1482       }
1483 
1484       // Examine the element type.
1485       LegalizeKind LK = getTypeConversion(Context, EltVT);
1486 
1487       // If type is to be expanded, split the vector.
1488       //  <4 x i140> -> <2 x i140>
1489       if (LK.first == TypeExpandInteger)
1490         return LegalizeKind(TypeSplitVector,
1491                             EVT::getVectorVT(Context, EltVT, NumElts / 2));
1492 
1493       // Promote the integer element types until a legal vector type is found
1494       // or until the element integer type is too big. If a legal type was not
1495       // found, fallback to the usual mechanism of widening/splitting the
1496       // vector.
1497       EVT OldEltVT = EltVT;
1498       while (1) {
1499         // Increase the bitwidth of the element to the next pow-of-two
1500         // (which is greater than 8 bits).
1501         EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()
1502                                  ).getRoundIntegerType(Context);
1503 
1504         // Stop trying when getting a non-simple element type.
1505         // Note that vector elements may be greater than legal vector element
1506         // types. Example: X86 XMM registers hold 64bit element on 32bit systems.
1507         if (!EltVT.isSimple()) break;
1508 
1509         // Build a new vector type and check if it is legal.
1510         MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1511         // Found a legal promoted vector type.
1512         if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
1513           return LegalizeKind(TypePromoteInteger,
1514                               EVT::getVectorVT(Context, EltVT, NumElts));
1515       }
1516 
1517       // Reset the type to the unexpanded type if we did not find a legal vector
1518       // type with a promoted vector element type.
1519       EltVT = OldEltVT;
1520     }
1521 
1522     // Try to widen the vector until a legal type is found.
1523     // If there is no wider legal type, split the vector.
1524     while (1) {
1525       // Round up to the next power of 2.
1526       NumElts = (unsigned)NextPowerOf2(NumElts);
1527 
1528       // If there is no simple vector type with this many elements then there
1529       // cannot be a larger legal vector type.  Note that this assumes that
1530       // there are no skipped intermediate vector types in the simple types.
1531       if (!EltVT.isSimple()) break;
1532       MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1533       if (LargerVector == MVT()) break;
1534 
1535       // If this type is legal then widen the vector.
1536       if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
1537         return LegalizeKind(TypeWidenVector, LargerVector);
1538     }
1539 
1540     // Widen odd vectors to next power of two.
1541     if (!VT.isPow2VectorType()) {
1542       EVT NVT = VT.getPow2VectorType(Context);
1543       return LegalizeKind(TypeWidenVector, NVT);
1544     }
1545 
1546     // Vectors with illegal element types are expanded.
1547     EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
1548     return LegalizeKind(TypeSplitVector, NVT);
1549   }
1550 
1551 private:
1552   std::vector<std::pair<MVT, const TargetRegisterClass*> > AvailableRegClasses;
1553 
1554   /// Targets can specify ISD nodes that they would like PerformDAGCombine
1555   /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
1556   /// array.
1557   unsigned char
1558   TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
1559 
1560   /// For operations that must be promoted to a specific type, this holds the
1561   /// destination type.  This map should be sparse, so don't hold it as an
1562   /// array.
1563   ///
1564   /// Targets add entries to this map with AddPromotedToType(..), clients access
1565   /// this with getTypeToPromoteTo(..).
1566   std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1567     PromoteToType;
1568 
1569   /// Stores the name each libcall.
1570   const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1571 
1572   /// The ISD::CondCode that should be used to test the result of each of the
1573   /// comparison libcall against zero.
1574   ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1575 
1576   /// Stores the CallingConv that should be used for each libcall.
1577   CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
1578 
1579 protected:
1580   /// \brief Specify maximum number of store instructions per memset call.
1581   ///
1582   /// When lowering \@llvm.memset this field specifies the maximum number of
1583   /// store operations that may be substituted for the call to memset. Targets
1584   /// must set this value based on the cost threshold for that target. Targets
1585   /// should assume that the memset will be done using as many of the largest
1586   /// store operations first, followed by smaller ones, if necessary, per
1587   /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1588   /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1589   /// store.  This only applies to setting a constant array of a constant size.
1590   unsigned MaxStoresPerMemset;
1591 
1592   /// Maximum number of stores operations that may be substituted for the call
1593   /// to memset, used for functions with OptSize attribute.
1594   unsigned MaxStoresPerMemsetOptSize;
1595 
1596   /// \brief Specify maximum bytes of store instructions per memcpy call.
1597   ///
1598   /// When lowering \@llvm.memcpy this field specifies the maximum number of
1599   /// store operations that may be substituted for a call to memcpy. Targets
1600   /// must set this value based on the cost threshold for that target. Targets
1601   /// should assume that the memcpy will be done using as many of the largest
1602   /// store operations first, followed by smaller ones, if necessary, per
1603   /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1604   /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1605   /// and one 1-byte store. This only applies to copying a constant array of
1606   /// constant size.
1607   unsigned MaxStoresPerMemcpy;
1608 
1609   /// Maximum number of store operations that may be substituted for a call to
1610   /// memcpy, used for functions with OptSize attribute.
1611   unsigned MaxStoresPerMemcpyOptSize;
1612 
1613   /// \brief Specify maximum bytes of store instructions per memmove call.
1614   ///
1615   /// When lowering \@llvm.memmove this field specifies the maximum number of
1616   /// store instructions that may be substituted for a call to memmove. Targets
1617   /// must set this value based on the cost threshold for that target. Targets
1618   /// should assume that the memmove will be done using as many of the largest
1619   /// store operations first, followed by smaller ones, if necessary, per
1620   /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1621   /// with 8-bit alignment would result in nine 1-byte stores.  This only
1622   /// applies to copying a constant array of constant size.
1623   unsigned MaxStoresPerMemmove;
1624 
1625   /// Maximum number of store instructions that may be substituted for a call to
1626   /// memmove, used for functions with OpSize attribute.
1627   unsigned MaxStoresPerMemmoveOptSize;
1628 
1629   /// Tells the code generator that select is more expensive than a branch if
1630   /// the branch is usually predicted right.
1631   bool PredictableSelectIsExpensive;
1632 
1633 protected:
1634   /// Return true if the value types that can be represented by the specified
1635   /// register class are all legal.
1636   bool isLegalRC(const TargetRegisterClass *RC) const;
1637 };
1638 
1639 /// This class defines information used to lower LLVM code to legal SelectionDAG
1640 /// operators that the target instruction selector can accept natively.
1641 ///
1642 /// This class also defines callbacks that targets must implement to lower
1643 /// target-specific constructs to SelectionDAG operators.
1644 class TargetLowering : public TargetLoweringBase {
1645   TargetLowering(const TargetLowering&) LLVM_DELETED_FUNCTION;
1646   void operator=(const TargetLowering&) LLVM_DELETED_FUNCTION;
1647 
1648 public:
1649   /// NOTE: The constructor takes ownership of TLOF.
1650   explicit TargetLowering(const TargetMachine &TM,
1651                           const TargetLoweringObjectFile *TLOF);
1652 
1653   /// Returns true by value, base pointer and offset pointer and addressing mode
1654   /// by reference if the node's address can be legally represented as
1655   /// pre-indexed load / store address.
getPreIndexedAddressParts(SDNode *,SDValue &,SDValue &,ISD::MemIndexedMode &,SelectionDAG &)1656   virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
1657                                          SDValue &/*Offset*/,
1658                                          ISD::MemIndexedMode &/*AM*/,
1659                                          SelectionDAG &/*DAG*/) const {
1660     return false;
1661   }
1662 
1663   /// Returns true by value, base pointer and offset pointer and addressing mode
1664   /// by reference if this node can be combined with a load / store to form a
1665   /// post-indexed load / store.
getPostIndexedAddressParts(SDNode *,SDNode *,SDValue &,SDValue &,ISD::MemIndexedMode &,SelectionDAG &)1666   virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
1667                                           SDValue &/*Base*/, SDValue &/*Offset*/,
1668                                           ISD::MemIndexedMode &/*AM*/,
1669                                           SelectionDAG &/*DAG*/) const {
1670     return false;
1671   }
1672 
1673   /// Return the entry encoding for a jump table in the current function.  The
1674   /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
1675   virtual unsigned getJumpTableEncoding() const;
1676 
1677   virtual const MCExpr *
LowerCustomJumpTableEntry(const MachineJumpTableInfo *,const MachineBasicBlock *,unsigned,MCContext &)1678   LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
1679                             const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
1680                             MCContext &/*Ctx*/) const {
1681     llvm_unreachable("Need to implement this hook if target has custom JTIs");
1682   }
1683 
1684   /// Returns relocation base for the given PIC jumptable.
1685   virtual SDValue getPICJumpTableRelocBase(SDValue Table,
1686                                            SelectionDAG &DAG) const;
1687 
1688   /// This returns the relocation base for the given PIC jumptable, the same as
1689   /// getPICJumpTableRelocBase, but as an MCExpr.
1690   virtual const MCExpr *
1691   getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
1692                                unsigned JTI, MCContext &Ctx) const;
1693 
1694   /// Return true if folding a constant offset with the given GlobalAddress is
1695   /// legal.  It is frequently not legal in PIC relocation models.
1696   virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
1697 
1698   bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
1699                             SDValue &Chain) const;
1700 
1701   void softenSetCCOperands(SelectionDAG &DAG, EVT VT,
1702                            SDValue &NewLHS, SDValue &NewRHS,
1703                            ISD::CondCode &CCCode, SDLoc DL) const;
1704 
1705   SDValue makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
1706                       const SDValue *Ops, unsigned NumOps,
1707                       bool isSigned, SDLoc dl) const;
1708 
1709   //===--------------------------------------------------------------------===//
1710   // TargetLowering Optimization Methods
1711   //
1712 
1713   /// A convenience struct that encapsulates a DAG, and two SDValues for
1714   /// returning information from TargetLowering to its clients that want to
1715   /// combine.
1716   struct TargetLoweringOpt {
1717     SelectionDAG &DAG;
1718     bool LegalTys;
1719     bool LegalOps;
1720     SDValue Old;
1721     SDValue New;
1722 
TargetLoweringOptTargetLoweringOpt1723     explicit TargetLoweringOpt(SelectionDAG &InDAG,
1724                                bool LT, bool LO) :
1725       DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
1726 
LegalTypesTargetLoweringOpt1727     bool LegalTypes() const { return LegalTys; }
LegalOperationsTargetLoweringOpt1728     bool LegalOperations() const { return LegalOps; }
1729 
CombineToTargetLoweringOpt1730     bool CombineTo(SDValue O, SDValue N) {
1731       Old = O;
1732       New = N;
1733       return true;
1734     }
1735 
1736     /// Check to see if the specified operand of the specified instruction is a
1737     /// constant integer.  If so, check to see if there are any bits set in the
1738     /// constant that are not demanded.  If so, shrink the constant and return
1739     /// true.
1740     bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
1741 
1742     /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.  This
1743     /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
1744     /// generalized for targets with other types of implicit widening casts.
1745     bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
1746                           SDLoc dl);
1747   };
1748 
1749   /// Look at Op.  At this point, we know that only the DemandedMask bits of the
1750   /// result of Op are ever used downstream.  If we can use this information to
1751   /// simplify Op, create a new simplified DAG node and return true, returning
1752   /// the original and new nodes in Old and New.  Otherwise, analyze the
1753   /// expression and return a mask of KnownOne and KnownZero bits for the
1754   /// expression (used to simplify the caller).  The KnownZero/One bits may only
1755   /// be accurate for those bits in the DemandedMask.
1756   bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
1757                             APInt &KnownZero, APInt &KnownOne,
1758                             TargetLoweringOpt &TLO, unsigned Depth = 0) const;
1759 
1760   /// Determine which of the bits specified in Mask are known to be either zero
1761   /// or one and return them in the KnownZero/KnownOne bitsets.
1762   virtual void computeMaskedBitsForTargetNode(const SDValue Op,
1763                                               APInt &KnownZero,
1764                                               APInt &KnownOne,
1765                                               const SelectionDAG &DAG,
1766                                               unsigned Depth = 0) const;
1767 
1768   /// This method can be implemented by targets that want to expose additional
1769   /// information about sign bits to the DAG Combiner.
1770   virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
1771                                                    unsigned Depth = 0) const;
1772 
1773   struct DAGCombinerInfo {
1774     void *DC;  // The DAG Combiner object.
1775     CombineLevel Level;
1776     bool CalledByLegalizer;
1777   public:
1778     SelectionDAG &DAG;
1779 
DAGCombinerInfoDAGCombinerInfo1780     DAGCombinerInfo(SelectionDAG &dag, CombineLevel level,  bool cl, void *dc)
1781       : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
1782 
isBeforeLegalizeDAGCombinerInfo1783     bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
isBeforeLegalizeOpsDAGCombinerInfo1784     bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
isAfterLegalizeVectorOpsDAGCombinerInfo1785     bool isAfterLegalizeVectorOps() const {
1786       return Level == AfterLegalizeDAG;
1787     }
getDAGCombineLevelDAGCombinerInfo1788     CombineLevel getDAGCombineLevel() { return Level; }
isCalledByLegalizerDAGCombinerInfo1789     bool isCalledByLegalizer() const { return CalledByLegalizer; }
1790 
1791     void AddToWorklist(SDNode *N);
1792     void RemoveFromWorklist(SDNode *N);
1793     SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
1794                       bool AddTo = true);
1795     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
1796     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
1797 
1798     void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
1799   };
1800 
1801   /// Try to simplify a setcc built with the specified operands and cc. If it is
1802   /// unable to simplify it, return a null SDValue.
1803   SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1804                           ISD::CondCode Cond, bool foldBooleans,
1805                           DAGCombinerInfo &DCI, SDLoc dl) const;
1806 
1807   /// Returns true (and the GlobalValue and the offset) if the node is a
1808   /// GlobalAddress + offset.
1809   virtual bool
1810   isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
1811 
1812   /// This method will be invoked for all target nodes and for any
1813   /// target-independent nodes that the target has registered with invoke it
1814   /// for.
1815   ///
1816   /// The semantics are as follows:
1817   /// Return Value:
1818   ///   SDValue.Val == 0   - No change was made
1819   ///   SDValue.Val == N   - N was replaced, is dead, and is already handled.
1820   ///   otherwise          - N should be replaced by the returned Operand.
1821   ///
1822   /// In addition, methods provided by DAGCombinerInfo may be used to perform
1823   /// more complex transformations.
1824   ///
1825   virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
1826 
1827   /// Return true if the target has native support for the specified value type
1828   /// and it is 'desirable' to use the type for the given node type. e.g. On x86
1829   /// i16 is legal, but undesirable since i16 instruction encodings are longer
1830   /// and some i16 instructions are slow.
isTypeDesirableForOp(unsigned,EVT VT)1831   virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
1832     // By default, assume all legal types are desirable.
1833     return isTypeLegal(VT);
1834   }
1835 
1836   /// Return true if it is profitable for dag combiner to transform a floating
1837   /// point op of specified opcode to a equivalent op of an integer
1838   /// type. e.g. f32 load -> i32 load can be profitable on ARM.
isDesirableToTransformToIntegerOp(unsigned,EVT)1839   virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
1840                                                  EVT /*VT*/) const {
1841     return false;
1842   }
1843 
1844   /// This method query the target whether it is beneficial for dag combiner to
1845   /// promote the specified node. If true, it should return the desired
1846   /// promotion type by reference.
IsDesirableToPromoteOp(SDValue,EVT &)1847   virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
1848     return false;
1849   }
1850 
1851   //===--------------------------------------------------------------------===//
1852   // Lowering methods - These methods must be implemented by targets so that
1853   // the SelectionDAGBuilder code knows how to lower these.
1854   //
1855 
1856   /// This hook must be implemented to lower the incoming (formal) arguments,
1857   /// described by the Ins array, into the specified DAG. The implementation
1858   /// should fill in the InVals array with legal-type argument values, and
1859   /// return the resulting token chain value.
1860   ///
1861   virtual SDValue
LowerFormalArguments(SDValue,CallingConv::ID,bool,const SmallVectorImpl<ISD::InputArg> &,SDLoc,SelectionDAG &,SmallVectorImpl<SDValue> &)1862     LowerFormalArguments(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1863                          bool /*isVarArg*/,
1864                          const SmallVectorImpl<ISD::InputArg> &/*Ins*/,
1865                          SDLoc /*dl*/, SelectionDAG &/*DAG*/,
1866                          SmallVectorImpl<SDValue> &/*InVals*/) const {
1867     llvm_unreachable("Not Implemented");
1868   }
1869 
1870   struct ArgListEntry {
1871     SDValue Node;
1872     Type* Ty;
1873     bool isSExt     : 1;
1874     bool isZExt     : 1;
1875     bool isInReg    : 1;
1876     bool isSRet     : 1;
1877     bool isNest     : 1;
1878     bool isByVal    : 1;
1879     bool isReturned : 1;
1880     uint16_t Alignment;
1881 
ArgListEntryArgListEntry1882     ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1883       isSRet(false), isNest(false), isByVal(false), isReturned(false),
1884       Alignment(0) { }
1885   };
1886   typedef std::vector<ArgListEntry> ArgListTy;
1887 
1888   /// This structure contains all information that is necessary for lowering
1889   /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
1890   /// needs to lower a call, and targets will see this struct in their LowerCall
1891   /// implementation.
1892   struct CallLoweringInfo {
1893     SDValue Chain;
1894     Type *RetTy;
1895     bool RetSExt           : 1;
1896     bool RetZExt           : 1;
1897     bool IsVarArg          : 1;
1898     bool IsInReg           : 1;
1899     bool DoesNotReturn     : 1;
1900     bool IsReturnValueUsed : 1;
1901 
1902     // IsTailCall should be modified by implementations of
1903     // TargetLowering::LowerCall that perform tail call conversions.
1904     bool IsTailCall;
1905 
1906     unsigned NumFixedArgs;
1907     CallingConv::ID CallConv;
1908     SDValue Callee;
1909     ArgListTy &Args;
1910     SelectionDAG &DAG;
1911     SDLoc DL;
1912     ImmutableCallSite *CS;
1913     SmallVector<ISD::OutputArg, 32> Outs;
1914     SmallVector<SDValue, 32> OutVals;
1915     SmallVector<ISD::InputArg, 32> Ins;
1916 
1917 
1918     /// Constructs a call lowering context based on the ImmutableCallSite \p cs.
CallLoweringInfoCallLoweringInfo1919     CallLoweringInfo(SDValue chain, Type *retTy,
1920                      FunctionType *FTy, bool isTailCall, SDValue callee,
1921                      ArgListTy &args, SelectionDAG &dag, SDLoc dl,
1922                      ImmutableCallSite &cs)
1923     : Chain(chain), RetTy(retTy), RetSExt(cs.paramHasAttr(0, Attribute::SExt)),
1924       RetZExt(cs.paramHasAttr(0, Attribute::ZExt)), IsVarArg(FTy->isVarArg()),
1925       IsInReg(cs.paramHasAttr(0, Attribute::InReg)),
1926       DoesNotReturn(cs.doesNotReturn()),
1927       IsReturnValueUsed(!cs.getInstruction()->use_empty()),
1928       IsTailCall(isTailCall), NumFixedArgs(FTy->getNumParams()),
1929       CallConv(cs.getCallingConv()), Callee(callee), Args(args), DAG(dag),
1930       DL(dl), CS(&cs) {}
1931 
1932     /// Constructs a call lowering context based on the provided call
1933     /// information.
CallLoweringInfoCallLoweringInfo1934     CallLoweringInfo(SDValue chain, Type *retTy, bool retSExt, bool retZExt,
1935                      bool isVarArg, bool isInReg, unsigned numFixedArgs,
1936                      CallingConv::ID callConv, bool isTailCall,
1937                      bool doesNotReturn, bool isReturnValueUsed, SDValue callee,
1938                      ArgListTy &args, SelectionDAG &dag, SDLoc dl)
1939     : Chain(chain), RetTy(retTy), RetSExt(retSExt), RetZExt(retZExt),
1940       IsVarArg(isVarArg), IsInReg(isInReg), DoesNotReturn(doesNotReturn),
1941       IsReturnValueUsed(isReturnValueUsed), IsTailCall(isTailCall),
1942       NumFixedArgs(numFixedArgs), CallConv(callConv), Callee(callee),
1943       Args(args), DAG(dag), DL(dl), CS(NULL) {}
1944   };
1945 
1946   /// This function lowers an abstract call to a function into an actual call.
1947   /// This returns a pair of operands.  The first element is the return value
1948   /// for the function (if RetTy is not VoidTy).  The second element is the
1949   /// outgoing token chain. It calls LowerCall to do the actual lowering.
1950   std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
1951 
1952   /// This hook must be implemented to lower calls into the the specified
1953   /// DAG. The outgoing arguments to the call are described by the Outs array,
1954   /// and the values to be returned by the call are described by the Ins
1955   /// array. The implementation should fill in the InVals array with legal-type
1956   /// return values from the call, and return the resulting token chain value.
1957   virtual SDValue
LowerCall(CallLoweringInfo &,SmallVectorImpl<SDValue> &)1958     LowerCall(CallLoweringInfo &/*CLI*/,
1959               SmallVectorImpl<SDValue> &/*InVals*/) const {
1960     llvm_unreachable("Not Implemented");
1961   }
1962 
1963   /// Target-specific cleanup for formal ByVal parameters.
HandleByVal(CCState *,unsigned &,unsigned)1964   virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
1965 
1966   /// This hook should be implemented to check whether the return values
1967   /// described by the Outs array can fit into the return registers.  If false
1968   /// is returned, an sret-demotion is performed.
CanLowerReturn(CallingConv::ID,MachineFunction &,bool,const SmallVectorImpl<ISD::OutputArg> &,LLVMContext &)1969   virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
1970                               MachineFunction &/*MF*/, bool /*isVarArg*/,
1971                const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
1972                LLVMContext &/*Context*/) const
1973   {
1974     // Return true by default to get preexisting behavior.
1975     return true;
1976   }
1977 
1978   /// This hook must be implemented to lower outgoing return values, described
1979   /// by the Outs array, into the specified DAG. The implementation should
1980   /// return the resulting token chain value.
1981   virtual SDValue
LowerReturn(SDValue,CallingConv::ID,bool,const SmallVectorImpl<ISD::OutputArg> &,const SmallVectorImpl<SDValue> &,SDLoc,SelectionDAG &)1982     LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1983                 bool /*isVarArg*/,
1984                 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
1985                 const SmallVectorImpl<SDValue> &/*OutVals*/,
1986                 SDLoc /*dl*/, SelectionDAG &/*DAG*/) const {
1987     llvm_unreachable("Not Implemented");
1988   }
1989 
1990   /// Return true if result of the specified node is used by a return node
1991   /// only. It also compute and return the input chain for the tail call.
1992   ///
1993   /// This is used to determine whether it is possible to codegen a libcall as
1994   /// tail call at legalization time.
isUsedByReturnOnly(SDNode *,SDValue &)1995   virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
1996     return false;
1997   }
1998 
1999   /// Return true if the target may be able emit the call instruction as a tail
2000   /// call. This is used by optimization passes to determine if it's profitable
2001   /// to duplicate return instructions to enable tailcall optimization.
mayBeEmittedAsTailCall(CallInst *)2002   virtual bool mayBeEmittedAsTailCall(CallInst *) const {
2003     return false;
2004   }
2005 
2006   /// Return the type that should be used to zero or sign extend a
2007   /// zeroext/signext integer argument or return value.  FIXME: Most C calling
2008   /// convention requires the return type to be promoted, but this is not true
2009   /// all the time, e.g. i1 on x86-64. It is also not necessary for non-C
2010   /// calling conventions. The frontend should handle this and include all of
2011   /// the necessary information.
getTypeForExtArgOrReturn(MVT VT,ISD::NodeType)2012   virtual MVT getTypeForExtArgOrReturn(MVT VT,
2013                                        ISD::NodeType /*ExtendKind*/) const {
2014     MVT MinVT = getRegisterType(MVT::i32);
2015     return VT.bitsLT(MinVT) ? MinVT : VT;
2016   }
2017 
2018   /// This callback is invoked by the type legalizer to legalize nodes with an
2019   /// illegal operand type but legal result types.  It replaces the
2020   /// LowerOperation callback in the type Legalizer.  The reason we can not do
2021   /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
2022   /// use this callback.
2023   ///
2024   /// TODO: Consider merging with ReplaceNodeResults.
2025   ///
2026   /// The target places new result values for the node in Results (their number
2027   /// and types must exactly match those of the original return values of
2028   /// the node), or leaves Results empty, which indicates that the node is not
2029   /// to be custom lowered after all.
2030   /// The default implementation calls LowerOperation.
2031   virtual void LowerOperationWrapper(SDNode *N,
2032                                      SmallVectorImpl<SDValue> &Results,
2033                                      SelectionDAG &DAG) const;
2034 
2035   /// This callback is invoked for operations that are unsupported by the
2036   /// target, which are registered to use 'custom' lowering, and whose defined
2037   /// values are all legal.  If the target has no operations that require custom
2038   /// lowering, it need not implement this.  The default implementation of this
2039   /// aborts.
2040   virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
2041 
2042   /// This callback is invoked when a node result type is illegal for the
2043   /// target, and the operation was registered to use 'custom' lowering for that
2044   /// result type.  The target places new result values for the node in Results
2045   /// (their number and types must exactly match those of the original return
2046   /// values of the node), or leaves Results empty, which indicates that the
2047   /// node is not to be custom lowered after all.
2048   ///
2049   /// If the target has no operations that require custom lowering, it need not
2050   /// implement this.  The default implementation aborts.
ReplaceNodeResults(SDNode *,SmallVectorImpl<SDValue> &,SelectionDAG &)2051   virtual void ReplaceNodeResults(SDNode * /*N*/,
2052                                   SmallVectorImpl<SDValue> &/*Results*/,
2053                                   SelectionDAG &/*DAG*/) const {
2054     llvm_unreachable("ReplaceNodeResults not implemented for this target!");
2055   }
2056 
2057   /// This method returns the name of a target specific DAG node.
2058   virtual const char *getTargetNodeName(unsigned Opcode) const;
2059 
2060   /// This method returns a target specific FastISel object, or null if the
2061   /// target does not support "fast" ISel.
createFastISel(FunctionLoweringInfo &,const TargetLibraryInfo *)2062   virtual FastISel *createFastISel(FunctionLoweringInfo &,
2063                                    const TargetLibraryInfo *) const {
2064     return 0;
2065   }
2066 
2067   //===--------------------------------------------------------------------===//
2068   // Inline Asm Support hooks
2069   //
2070 
2071   /// This hook allows the target to expand an inline asm call to be explicit
2072   /// llvm code if it wants to.  This is useful for turning simple inline asms
2073   /// into LLVM intrinsics, which gives the compiler more information about the
2074   /// behavior of the code.
ExpandInlineAsm(CallInst *)2075   virtual bool ExpandInlineAsm(CallInst *) const {
2076     return false;
2077   }
2078 
2079   enum ConstraintType {
2080     C_Register,            // Constraint represents specific register(s).
2081     C_RegisterClass,       // Constraint represents any of register(s) in class.
2082     C_Memory,              // Memory constraint.
2083     C_Other,               // Something else.
2084     C_Unknown              // Unsupported constraint.
2085   };
2086 
2087   enum ConstraintWeight {
2088     // Generic weights.
2089     CW_Invalid  = -1,     // No match.
2090     CW_Okay     = 0,      // Acceptable.
2091     CW_Good     = 1,      // Good weight.
2092     CW_Better   = 2,      // Better weight.
2093     CW_Best     = 3,      // Best weight.
2094 
2095     // Well-known weights.
2096     CW_SpecificReg  = CW_Okay,    // Specific register operands.
2097     CW_Register     = CW_Good,    // Register operands.
2098     CW_Memory       = CW_Better,  // Memory operands.
2099     CW_Constant     = CW_Best,    // Constant operand.
2100     CW_Default      = CW_Okay     // Default or don't know type.
2101   };
2102 
2103   /// This contains information for each constraint that we are lowering.
2104   struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
2105     /// This contains the actual string for the code, like "m".  TargetLowering
2106     /// picks the 'best' code from ConstraintInfo::Codes that most closely
2107     /// matches the operand.
2108     std::string ConstraintCode;
2109 
2110     /// Information about the constraint code, e.g. Register, RegisterClass,
2111     /// Memory, Other, Unknown.
2112     TargetLowering::ConstraintType ConstraintType;
2113 
2114     /// If this is the result output operand or a clobber, this is null,
2115     /// otherwise it is the incoming operand to the CallInst.  This gets
2116     /// modified as the asm is processed.
2117     Value *CallOperandVal;
2118 
2119     /// The ValueType for the operand value.
2120     MVT ConstraintVT;
2121 
2122     /// Return true of this is an input operand that is a matching constraint
2123     /// like "4".
2124     bool isMatchingInputConstraint() const;
2125 
2126     /// If this is an input matching constraint, this method returns the output
2127     /// operand it matches.
2128     unsigned getMatchedOperand() const;
2129 
2130     /// Copy constructor for copying from an AsmOperandInfo.
AsmOperandInfoAsmOperandInfo2131     AsmOperandInfo(const AsmOperandInfo &info)
2132       : InlineAsm::ConstraintInfo(info),
2133         ConstraintCode(info.ConstraintCode),
2134         ConstraintType(info.ConstraintType),
2135         CallOperandVal(info.CallOperandVal),
2136         ConstraintVT(info.ConstraintVT) {
2137     }
2138 
2139     /// Copy constructor for copying from a ConstraintInfo.
AsmOperandInfoAsmOperandInfo2140     AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
2141       : InlineAsm::ConstraintInfo(info),
2142         ConstraintType(TargetLowering::C_Unknown),
2143         CallOperandVal(0), ConstraintVT(MVT::Other) {
2144     }
2145   };
2146 
2147   typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
2148 
2149   /// Split up the constraint string from the inline assembly value into the
2150   /// specific constraints and their prefixes, and also tie in the associated
2151   /// operand values.  If this returns an empty vector, and if the constraint
2152   /// string itself isn't empty, there was an error parsing.
2153   virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const;
2154 
2155   /// Examine constraint type and operand type and determine a weight value.
2156   /// The operand object must already have been set up with the operand type.
2157   virtual ConstraintWeight getMultipleConstraintMatchWeight(
2158       AsmOperandInfo &info, int maIndex) const;
2159 
2160   /// Examine constraint string and operand type and determine a weight value.
2161   /// The operand object must already have been set up with the operand type.
2162   virtual ConstraintWeight getSingleConstraintMatchWeight(
2163       AsmOperandInfo &info, const char *constraint) const;
2164 
2165   /// Determines the constraint code and constraint type to use for the specific
2166   /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
2167   /// If the actual operand being passed in is available, it can be passed in as
2168   /// Op, otherwise an empty SDValue can be passed.
2169   virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2170                                       SDValue Op,
2171                                       SelectionDAG *DAG = 0) const;
2172 
2173   /// Given a constraint, return the type of constraint it is for this target.
2174   virtual ConstraintType getConstraintType(const std::string &Constraint) const;
2175 
2176   /// Given a physical register constraint (e.g.  {edx}), return the register
2177   /// number and the register class for the register.
2178   ///
2179   /// Given a register class constraint, like 'r', if this corresponds directly
2180   /// to an LLVM register class, return a register of 0 and the register class
2181   /// pointer.
2182   ///
2183   /// This should only be used for C_Register constraints.  On error, this
2184   /// returns a register number of 0 and a null register class pointer..
2185   virtual std::pair<unsigned, const TargetRegisterClass*>
2186     getRegForInlineAsmConstraint(const std::string &Constraint,
2187                                  MVT VT) const;
2188 
2189   /// Try to replace an X constraint, which matches anything, with another that
2190   /// has more specific requirements based on the type of the corresponding
2191   /// operand.  This returns null if there is no replacement to make.
2192   virtual const char *LowerXConstraint(EVT ConstraintVT) const;
2193 
2194   /// Lower the specified operand into the Ops vector.  If it is invalid, don't
2195   /// add anything to Ops.
2196   virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
2197                                             std::vector<SDValue> &Ops,
2198                                             SelectionDAG &DAG) const;
2199 
2200   //===--------------------------------------------------------------------===//
2201   // Div utility functions
2202   //
2203   SDValue BuildExactSDIV(SDValue Op1, SDValue Op2, SDLoc dl,
2204                          SelectionDAG &DAG) const;
2205   SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2206                       std::vector<SDNode*> *Created) const;
2207   SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2208                       std::vector<SDNode*> *Created) const;
2209 
2210   //===--------------------------------------------------------------------===//
2211   // Instruction Emitting Hooks
2212   //
2213 
2214   // This method should be implemented by targets that mark instructions with
2215   // the 'usesCustomInserter' flag.  These instructions are special in various
2216   // ways, which require special support to insert.  The specified MachineInstr
2217   // is created but not inserted into any basic blocks, and this method is
2218   // called to expand it into a sequence of instructions, potentially also
2219   // creating new basic blocks and control flow.
2220   virtual MachineBasicBlock *
2221     EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const;
2222 
2223   /// This method should be implemented by targets that mark instructions with
2224   /// the 'hasPostISelHook' flag. These instructions must be adjusted after
2225   /// instruction selection by target hooks.  e.g. To fill in optional defs for
2226   /// ARM 's' setting instructions.
2227   virtual void
2228   AdjustInstrPostInstrSelection(MachineInstr *MI, SDNode *Node) const;
2229 };
2230 
2231 /// Given an LLVM IR type and return type attributes, compute the return value
2232 /// EVTs and flags, and optionally also the offsets, if the return value is
2233 /// being lowered to memory.
2234 void GetReturnInfo(Type* ReturnType, AttributeSet attr,
2235                    SmallVectorImpl<ISD::OutputArg> &Outs,
2236                    const TargetLowering &TLI);
2237 
2238 } // end llvm namespace
2239 
2240 #endif
2241