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