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