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