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