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