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