OSDN Git Service

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