5875d130dbb8311ea6717c6c25087c36af362422
[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/Constants.h"
26 #include "llvm/InlineAsm.h"
27 #include "llvm/CodeGen/SelectionDAGNodes.h"
28 #include "llvm/CodeGen/RuntimeLibcalls.h"
29 #include "llvm/ADT/APFloat.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include <map>
32 #include <vector>
33
34 namespace llvm {
35   class Function;
36   class MachineBasicBlock;
37   class MachineFrameInfo;
38   class MachineInstr;
39   class SDNode;
40   class SDOperand;
41   class SelectionDAG;
42   class TargetData;
43   class TargetMachine;
44   class TargetRegisterClass;
45   class TargetSubtarget;
46   class Value;
47   class VectorType;
48
49 //===----------------------------------------------------------------------===//
50 /// TargetLowering - This class defines information used to lower LLVM code to
51 /// legal SelectionDAG operators that the target instruction selector can accept
52 /// natively.
53 ///
54 /// This class also defines callbacks that targets must implement to lower
55 /// target-specific constructs to SelectionDAG operators.
56 ///
57 class TargetLowering {
58 public:
59   /// LegalizeAction - This enum indicates whether operations are valid for a
60   /// target, and if not, what action should be used to make them valid.
61   enum LegalizeAction {
62     Legal,      // The target natively supports this operation.
63     Promote,    // This operation should be executed in a larger type.
64     Expand,     // Try to expand this to other ops, otherwise use a libcall.
65     Custom      // Use the LowerOperation hook to implement custom lowering.
66   };
67
68   enum OutOfRangeShiftAmount {
69     Undefined,  // Oversized shift amounts are undefined (default).
70     Mask,       // Shift amounts are auto masked (anded) to value size.
71     Extend      // Oversized shift pulls in zeros or sign bits.
72   };
73
74   enum SetCCResultValue {
75     UndefinedSetCCResult,          // SetCC returns a garbage/unknown extend.
76     ZeroOrOneSetCCResult,          // SetCC returns a zero extended result.
77     ZeroOrNegativeOneSetCCResult   // SetCC returns a sign extended result.
78   };
79
80   enum SchedPreference {
81     SchedulingForLatency,          // Scheduling for shortest total latency.
82     SchedulingForRegPressure       // Scheduling for lowest register pressure.
83   };
84
85   explicit TargetLowering(TargetMachine &TM);
86   virtual ~TargetLowering();
87
88   TargetMachine &getTargetMachine() const { return TM; }
89   const TargetData *getTargetData() const { return TD; }
90
91   bool isBigEndian() const { return !IsLittleEndian; }
92   bool isLittleEndian() const { return IsLittleEndian; }
93   MVT getPointerTy() const { return PointerTy; }
94   MVT getShiftAmountTy() const { return ShiftAmountTy; }
95   OutOfRangeShiftAmount getShiftAmountFlavor() const {return ShiftAmtHandling; }
96
97   /// usesGlobalOffsetTable - Return true if this target uses a GOT for PIC
98   /// codegen.
99   bool usesGlobalOffsetTable() const { return UsesGlobalOffsetTable; }
100
101   /// isSelectExpensive - Return true if the select operation is expensive for
102   /// this target.
103   bool isSelectExpensive() const { return SelectIsExpensive; }
104   
105   /// isIntDivCheap() - Return true if integer divide is usually cheaper than
106   /// a sequence of several shifts, adds, and multiplies for this target.
107   bool isIntDivCheap() const { return IntDivIsCheap; }
108
109   /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
110   /// srl/add/sra.
111   bool isPow2DivCheap() const { return Pow2DivIsCheap; }
112
113   /// getSetCCResultType - Return the ValueType of the result of setcc
114   /// operations.
115   virtual MVT getSetCCResultType(const SDOperand &) const;
116
117   /// getSetCCResultContents - For targets without boolean registers, this flag
118   /// returns information about the contents of the high-bits in the setcc
119   /// result register.
120   SetCCResultValue getSetCCResultContents() const { return SetCCResultContents;}
121
122   /// getSchedulingPreference - Return target scheduling preference.
123   SchedPreference getSchedulingPreference() const {
124     return SchedPreferenceInfo;
125   }
126
127   /// getRegClassFor - Return the register class that should be used for the
128   /// specified value type.  This may only be called on legal types.
129   TargetRegisterClass *getRegClassFor(MVT VT) const {
130     assert((unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
131     TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT()];
132     assert(RC && "This value type is not natively supported!");
133     return RC;
134   }
135   
136   /// isTypeLegal - Return true if the target has native support for the
137   /// specified value type.  This means that it has a register that directly
138   /// holds it without promotions or expansions.
139   bool isTypeLegal(MVT VT) const {
140     assert(!VT.isSimple() ||
141            (unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
142     return VT.isSimple() && RegClassForVT[VT.getSimpleVT()] != 0;
143   }
144
145   class ValueTypeActionImpl {
146     /// ValueTypeActions - This is a bitvector that contains two bits for each
147     /// value type, where the two bits correspond to the LegalizeAction enum.
148     /// This can be queried with "getTypeAction(VT)".
149     uint32_t ValueTypeActions[2];
150   public:
151     ValueTypeActionImpl() {
152       ValueTypeActions[0] = ValueTypeActions[1] = 0;
153     }
154     ValueTypeActionImpl(const ValueTypeActionImpl &RHS) {
155       ValueTypeActions[0] = RHS.ValueTypeActions[0];
156       ValueTypeActions[1] = RHS.ValueTypeActions[1];
157     }
158     
159     LegalizeAction getTypeAction(MVT VT) const {
160       if (VT.isExtended()) {
161         if (VT.isVector()) return Expand;
162         if (VT.isInteger())
163           // First promote to a power-of-two size, then expand if necessary.
164           return VT == VT.getRoundIntegerType() ? Expand : Promote;
165         assert(0 && "Unsupported extended type!");
166         return Legal;
167       }
168       unsigned I = VT.getSimpleVT();
169       assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
170       return (LegalizeAction)((ValueTypeActions[I>>4] >> ((2*I) & 31)) & 3);
171     }
172     void setTypeAction(MVT VT, LegalizeAction Action) {
173       unsigned I = VT.getSimpleVT();
174       assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
175       ValueTypeActions[I>>4] |= Action << ((I*2) & 31);
176     }
177   };
178   
179   const ValueTypeActionImpl &getValueTypeActions() const {
180     return ValueTypeActions;
181   }
182   
183   /// getTypeAction - Return how we should legalize values of this type, either
184   /// it is already legal (return 'Legal') or we need to promote it to a larger
185   /// type (return 'Promote'), or we need to expand it into multiple registers
186   /// of smaller integer type (return 'Expand').  'Custom' is not an option.
187   LegalizeAction getTypeAction(MVT VT) const {
188     return ValueTypeActions.getTypeAction(VT);
189   }
190
191   /// getTypeToTransformTo - For types supported by the target, this is an
192   /// identity function.  For types that must be promoted to larger types, this
193   /// returns the larger type to promote to.  For integer types that are larger
194   /// than the largest integer register, this contains one step in the expansion
195   /// to get to the smaller register. For illegal floating point types, this
196   /// returns the integer type to transform to.
197   MVT getTypeToTransformTo(MVT VT) const {
198     if (VT.isSimple()) {
199       assert((unsigned)VT.getSimpleVT() < array_lengthof(TransformToType));
200       MVT NVT = TransformToType[VT.getSimpleVT()];
201       assert(getTypeAction(NVT) != Promote &&
202              "Promote may not follow Expand or Promote");
203       return NVT;
204     }
205
206     if (VT.isVector())
207       return MVT::getVectorVT(VT.getVectorElementType(),
208                               VT.getVectorNumElements() / 2);
209     if (VT.isInteger()) {
210       MVT NVT = VT.getRoundIntegerType();
211       if (NVT == VT)
212         // Size is a power of two - expand to half the size.
213         return MVT::getIntegerVT(VT.getSizeInBits() / 2);
214       else
215         // Promote to a power of two size, avoiding multi-step promotion.
216         return getTypeAction(NVT) == Promote ? getTypeToTransformTo(NVT) : NVT;
217     }
218     assert(0 && "Unsupported extended type!");
219     return MVT(); // Not reached
220   }
221
222   /// getTypeToExpandTo - For types supported by the target, this is an
223   /// identity function.  For types that must be expanded (i.e. integer types
224   /// that are larger than the largest integer register or illegal floating
225   /// point types), this returns the largest legal type it will be expanded to.
226   MVT getTypeToExpandTo(MVT VT) const {
227     assert(!VT.isVector());
228     while (true) {
229       switch (getTypeAction(VT)) {
230       case Legal:
231         return VT;
232       case Expand:
233         VT = getTypeToTransformTo(VT);
234         break;
235       default:
236         assert(false && "Type is not legal nor is it to be expanded!");
237         return VT;
238       }
239     }
240     return VT;
241   }
242
243   /// getVectorTypeBreakdown - Vector types are broken down into some number of
244   /// legal first class types.  For example, MVT::v8f32 maps to 2 MVT::v4f32
245   /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
246   /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
247   ///
248   /// This method returns the number of registers needed, and the VT for each
249   /// register.  It also returns the VT and quantity of the intermediate values
250   /// before they are promoted/expanded.
251   ///
252   unsigned getVectorTypeBreakdown(MVT VT,
253                                   MVT &IntermediateVT,
254                                   unsigned &NumIntermediates,
255                                   MVT &RegisterVT) const;
256   
257   typedef std::vector<APFloat>::const_iterator legal_fpimm_iterator;
258   legal_fpimm_iterator legal_fpimm_begin() const {
259     return LegalFPImmediates.begin();
260   }
261   legal_fpimm_iterator legal_fpimm_end() const {
262     return LegalFPImmediates.end();
263   }
264   
265   /// isShuffleMaskLegal - Targets can use this to indicate that they only
266   /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
267   /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
268   /// are assumed to be legal.
269   virtual bool isShuffleMaskLegal(SDOperand Mask, MVT VT) const {
270     return true;
271   }
272
273   /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
274   /// used by Targets can use this to indicate if there is a suitable
275   /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
276   /// pool entry.
277   virtual bool isVectorClearMaskLegal(const std::vector<SDOperand> &BVOps,
278                                       MVT EVT,
279                                       SelectionDAG &DAG) const {
280     return false;
281   }
282
283   /// getOperationAction - Return how this operation should be treated: either
284   /// it is legal, needs to be promoted to a larger size, needs to be
285   /// expanded to some other code sequence, or the target has a custom expander
286   /// for it.
287   LegalizeAction getOperationAction(unsigned Op, MVT VT) const {
288     if (VT.isExtended()) return Expand;
289     assert(Op < array_lengthof(OpActions) &&
290            (unsigned)VT.getSimpleVT() < sizeof(OpActions[0])*4 &&
291            "Table isn't big enough!");
292     return (LegalizeAction)((OpActions[Op] >> (2*VT.getSimpleVT())) & 3);
293   }
294   
295   /// isOperationLegal - Return true if the specified operation is legal on this
296   /// target.
297   bool isOperationLegal(unsigned Op, MVT VT) const {
298     return VT.isSimple() &&
299       (getOperationAction(Op, VT) == Legal ||
300        getOperationAction(Op, VT) == Custom);
301   }
302   
303   /// getLoadXAction - Return how this load with extension should be treated:
304   /// either it is legal, needs to be promoted to a larger size, needs to be
305   /// expanded to some other code sequence, or the target has a custom expander
306   /// for it.
307   LegalizeAction getLoadXAction(unsigned LType, MVT VT) const {
308     assert(LType < array_lengthof(LoadXActions) &&
309            (unsigned)VT.getSimpleVT() < sizeof(LoadXActions[0])*4 &&
310            "Table isn't big enough!");
311     return (LegalizeAction)((LoadXActions[LType] >> (2*VT.getSimpleVT())) & 3);
312   }
313
314   /// isLoadXLegal - Return true if the specified load with extension is legal
315   /// on this target.
316   bool isLoadXLegal(unsigned LType, MVT VT) const {
317     return VT.isSimple() &&
318       (getLoadXAction(LType, VT) == Legal ||
319        getLoadXAction(LType, VT) == Custom);
320   }
321
322   /// getTruncStoreAction - Return how this store with truncation should be
323   /// treated: either it is legal, needs to be promoted to a larger size, needs
324   /// to be expanded to some other code sequence, or the target has a custom
325   /// expander for it.
326   LegalizeAction getTruncStoreAction(MVT ValVT,
327                                      MVT MemVT) const {
328     assert((unsigned)ValVT.getSimpleVT() < array_lengthof(TruncStoreActions) &&
329            (unsigned)MemVT.getSimpleVT() < sizeof(TruncStoreActions[0])*4 &&
330            "Table isn't big enough!");
331     return (LegalizeAction)((TruncStoreActions[ValVT.getSimpleVT()] >>
332                              (2*MemVT.getSimpleVT())) & 3);
333   }
334
335   /// isTruncStoreLegal - Return true if the specified store with truncation is
336   /// legal on this target.
337   bool isTruncStoreLegal(MVT ValVT, MVT MemVT) const {
338     return MemVT.isSimple() &&
339       (getTruncStoreAction(ValVT, MemVT) == Legal ||
340        getTruncStoreAction(ValVT, MemVT) == Custom);
341   }
342
343   /// getIndexedLoadAction - Return how the indexed load should be treated:
344   /// either it is legal, needs to be promoted to a larger size, needs to be
345   /// expanded to some other code sequence, or the target has a custom expander
346   /// for it.
347   LegalizeAction
348   getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
349     assert(IdxMode < array_lengthof(IndexedModeActions[0]) &&
350            (unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[0][0])*4 &&
351            "Table isn't big enough!");
352     return (LegalizeAction)((IndexedModeActions[0][IdxMode] >>
353                              (2*VT.getSimpleVT())) & 3);
354   }
355
356   /// isIndexedLoadLegal - Return true if the specified indexed load is legal
357   /// on this target.
358   bool isIndexedLoadLegal(unsigned IdxMode, MVT VT) const {
359     return VT.isSimple() &&
360       (getIndexedLoadAction(IdxMode, VT) == Legal ||
361        getIndexedLoadAction(IdxMode, VT) == Custom);
362   }
363
364   /// getIndexedStoreAction - Return how the indexed store should be treated:
365   /// either it is legal, needs to be promoted to a larger size, needs to be
366   /// expanded to some other code sequence, or the target has a custom expander
367   /// for it.
368   LegalizeAction
369   getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
370     assert(IdxMode < array_lengthof(IndexedModeActions[1]) &&
371            (unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[1][0])*4 &&
372            "Table isn't big enough!");
373     return (LegalizeAction)((IndexedModeActions[1][IdxMode] >>
374                              (2*VT.getSimpleVT())) & 3);
375   }  
376   
377   /// isIndexedStoreLegal - Return true if the specified indexed load is legal
378   /// on this target.
379   bool isIndexedStoreLegal(unsigned IdxMode, MVT VT) const {
380     return VT.isSimple() &&
381       (getIndexedStoreAction(IdxMode, VT) == Legal ||
382        getIndexedStoreAction(IdxMode, VT) == Custom);
383   }
384
385   /// getConvertAction - Return how the conversion should be treated:
386   /// either it is legal, needs to be promoted to a larger size, needs to be
387   /// expanded to some other code sequence, or the target has a custom expander
388   /// for it.
389   LegalizeAction
390   getConvertAction(MVT FromVT, MVT ToVT) const {
391     assert((unsigned)FromVT.getSimpleVT() < array_lengthof(ConvertActions) &&
392            (unsigned)ToVT.getSimpleVT() < sizeof(ConvertActions[0])*4 &&
393            "Table isn't big enough!");
394     return (LegalizeAction)((ConvertActions[FromVT.getSimpleVT()] >>
395                              (2*ToVT.getSimpleVT())) & 3);
396   }
397
398   /// isConvertLegal - Return true if the specified conversion is legal
399   /// on this target.
400   bool isConvertLegal(MVT FromVT, MVT ToVT) const {
401     return FromVT.isSimple() && ToVT.isSimple() &&
402       (getConvertAction(FromVT, ToVT) == Legal ||
403        getConvertAction(FromVT, ToVT) == Custom);
404   }
405
406   /// getTypeToPromoteTo - If the action for this operation is to promote, this
407   /// method returns the ValueType to promote to.
408   MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
409     assert(getOperationAction(Op, VT) == Promote &&
410            "This operation isn't promoted!");
411
412     // See if this has an explicit type specified.
413     std::map<std::pair<unsigned, MVT::SimpleValueType>,
414              MVT::SimpleValueType>::const_iterator PTTI =
415       PromoteToType.find(std::make_pair(Op, VT.getSimpleVT()));
416     if (PTTI != PromoteToType.end()) return PTTI->second;
417
418     assert((VT.isInteger() || VT.isFloatingPoint()) &&
419            "Cannot autopromote this type, add it with AddPromotedToType.");
420     
421     MVT NVT = VT;
422     do {
423       NVT = (MVT::SimpleValueType)(NVT.getSimpleVT()+1);
424       assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
425              "Didn't find type to promote to!");
426     } while (!isTypeLegal(NVT) ||
427               getOperationAction(Op, NVT) == Promote);
428     return NVT;
429   }
430
431   /// getValueType - Return the MVT corresponding to this LLVM type.
432   /// This is fixed by the LLVM operations except for the pointer size.  If
433   /// AllowUnknown is true, this will return MVT::Other for types with no MVT
434   /// counterpart (e.g. structs), otherwise it will assert.
435   MVT getValueType(const Type *Ty, bool AllowUnknown = false) const {
436     MVT VT = MVT::getMVT(Ty, AllowUnknown);
437     return VT == MVT::iPTR ? PointerTy : VT;
438   }
439
440   /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
441   /// function arguments in the caller parameter area.  This is the actual
442   /// alignment, not its logarithm.
443   virtual unsigned getByValTypeAlignment(const Type *Ty) const;
444   
445   /// getRegisterType - Return the type of registers that this ValueType will
446   /// eventually require.
447   MVT getRegisterType(MVT VT) const {
448     if (VT.isSimple()) {
449       assert((unsigned)VT.getSimpleVT() < array_lengthof(RegisterTypeForVT));
450       return RegisterTypeForVT[VT.getSimpleVT()];
451     }
452     if (VT.isVector()) {
453       MVT VT1, RegisterVT;
454       unsigned NumIntermediates;
455       (void)getVectorTypeBreakdown(VT, VT1, NumIntermediates, RegisterVT);
456       return RegisterVT;
457     }
458     if (VT.isInteger()) {
459       return getRegisterType(getTypeToTransformTo(VT));
460     }
461     assert(0 && "Unsupported extended type!");
462     return MVT(); // Not reached
463   }
464
465   /// getNumRegisters - Return the number of registers that this ValueType will
466   /// eventually require.  This is one for any types promoted to live in larger
467   /// registers, but may be more than one for types (like i64) that are split
468   /// into pieces.  For types like i140, which are first promoted then expanded,
469   /// it is the number of registers needed to hold all the bits of the original
470   /// type.  For an i140 on a 32 bit machine this means 5 registers.
471   unsigned getNumRegisters(MVT VT) const {
472     if (VT.isSimple()) {
473       assert((unsigned)VT.getSimpleVT() < array_lengthof(NumRegistersForVT));
474       return NumRegistersForVT[VT.getSimpleVT()];
475     }
476     if (VT.isVector()) {
477       MVT VT1, VT2;
478       unsigned NumIntermediates;
479       return getVectorTypeBreakdown(VT, VT1, NumIntermediates, VT2);
480     }
481     if (VT.isInteger()) {
482       unsigned BitWidth = VT.getSizeInBits();
483       unsigned RegWidth = getRegisterType(VT).getSizeInBits();
484       return (BitWidth + RegWidth - 1) / RegWidth;
485     }
486     assert(0 && "Unsupported extended type!");
487     return 0; // Not reached
488   }
489
490   /// ShouldShrinkFPConstant - If true, then instruction selection should
491   /// seek to shrink the FP constant of the specified type to a smaller type
492   /// in order to save space and / or reduce runtime.
493   virtual bool ShouldShrinkFPConstant(MVT VT) const { return true; }
494
495   /// hasTargetDAGCombine - If true, the target has custom DAG combine
496   /// transformations that it can perform for the specified node.
497   bool hasTargetDAGCombine(ISD::NodeType NT) const {
498     assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
499     return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
500   }
501
502   /// This function returns the maximum number of store operations permitted
503   /// to replace a call to llvm.memset. The value is set by the target at the
504   /// performance threshold for such a replacement.
505   /// @brief Get maximum # of store operations permitted for llvm.memset
506   unsigned getMaxStoresPerMemset() const { return maxStoresPerMemset; }
507
508   /// This function returns the maximum number of store operations permitted
509   /// to replace a call to llvm.memcpy. The value is set by the target at the
510   /// performance threshold for such a replacement.
511   /// @brief Get maximum # of store operations permitted for llvm.memcpy
512   unsigned getMaxStoresPerMemcpy() const { return maxStoresPerMemcpy; }
513
514   /// This function returns the maximum number of store operations permitted
515   /// to replace a call to llvm.memmove. The value is set by the target at the
516   /// performance threshold for such a replacement.
517   /// @brief Get maximum # of store operations permitted for llvm.memmove
518   unsigned getMaxStoresPerMemmove() const { return maxStoresPerMemmove; }
519
520   /// This function returns true if the target allows unaligned memory accesses.
521   /// This is used, for example, in situations where an array copy/move/set is 
522   /// converted to a sequence of store operations. It's use helps to ensure that
523   /// such replacements don't generate code that causes an alignment error 
524   /// (trap) on the target machine. 
525   /// @brief Determine if the target supports unaligned memory accesses.
526   bool allowsUnalignedMemoryAccesses() const {
527     return allowUnalignedMemoryAccesses;
528   }
529
530   /// getOptimalMemOpType - Returns the target specific optimal type for load
531   /// and store operations as a result of memset, memcpy, and memmove lowering.
532   /// It returns MVT::iAny if SelectionDAG should be responsible for
533   /// determining it.
534   virtual MVT getOptimalMemOpType(uint64_t Size, unsigned Align,
535                                   bool isSrcConst, bool isSrcStr) const {
536     return MVT::iAny;
537   }
538   
539   /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
540   /// to implement llvm.setjmp.
541   bool usesUnderscoreSetJmp() const {
542     return UseUnderscoreSetJmp;
543   }
544
545   /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
546   /// to implement llvm.longjmp.
547   bool usesUnderscoreLongJmp() const {
548     return UseUnderscoreLongJmp;
549   }
550
551   /// getStackPointerRegisterToSaveRestore - If a physical register, this
552   /// specifies the register that llvm.savestack/llvm.restorestack should save
553   /// and restore.
554   unsigned getStackPointerRegisterToSaveRestore() const {
555     return StackPointerRegisterToSaveRestore;
556   }
557
558   /// getExceptionAddressRegister - If a physical register, this returns
559   /// the register that receives the exception address on entry to a landing
560   /// pad.
561   unsigned getExceptionAddressRegister() const {
562     return ExceptionPointerRegister;
563   }
564
565   /// getExceptionSelectorRegister - If a physical register, this returns
566   /// the register that receives the exception typeid on entry to a landing
567   /// pad.
568   unsigned getExceptionSelectorRegister() const {
569     return ExceptionSelectorRegister;
570   }
571
572   /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
573   /// set, the default is 200)
574   unsigned getJumpBufSize() const {
575     return JumpBufSize;
576   }
577
578   /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
579   /// (if never set, the default is 0)
580   unsigned getJumpBufAlignment() const {
581     return JumpBufAlignment;
582   }
583
584   /// getIfCvtBlockLimit - returns the target specific if-conversion block size
585   /// limit. Any block whose size is greater should not be predicated.
586   unsigned getIfCvtBlockSizeLimit() const {
587     return IfCvtBlockSizeLimit;
588   }
589
590   /// getIfCvtDupBlockLimit - returns the target specific size limit for a
591   /// block to be considered for duplication. Any block whose size is greater
592   /// should not be duplicated to facilitate its predication.
593   unsigned getIfCvtDupBlockSizeLimit() const {
594     return IfCvtDupBlockSizeLimit;
595   }
596
597   /// getPrefLoopAlignment - return the preferred loop alignment.
598   ///
599   unsigned getPrefLoopAlignment() const {
600     return PrefLoopAlignment;
601   }
602   
603   /// getPreIndexedAddressParts - returns true by value, base pointer and
604   /// offset pointer and addressing mode by reference if the node's address
605   /// can be legally represented as pre-indexed load / store address.
606   virtual bool getPreIndexedAddressParts(SDNode *N, SDOperand &Base,
607                                          SDOperand &Offset,
608                                          ISD::MemIndexedMode &AM,
609                                          SelectionDAG &DAG) {
610     return false;
611   }
612   
613   /// getPostIndexedAddressParts - returns true by value, base pointer and
614   /// offset pointer and addressing mode by reference if this node can be
615   /// combined with a load / store to form a post-indexed load / store.
616   virtual bool getPostIndexedAddressParts(SDNode *N, SDNode *Op,
617                                           SDOperand &Base, SDOperand &Offset,
618                                           ISD::MemIndexedMode &AM,
619                                           SelectionDAG &DAG) {
620     return false;
621   }
622   
623   /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
624   /// jumptable.
625   virtual SDOperand getPICJumpTableRelocBase(SDOperand Table,
626                                              SelectionDAG &DAG) const;
627
628   //===--------------------------------------------------------------------===//
629   // TargetLowering Optimization Methods
630   //
631   
632   /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
633   /// SDOperands for returning information from TargetLowering to its clients
634   /// that want to combine 
635   struct TargetLoweringOpt {
636     SelectionDAG &DAG;
637     bool AfterLegalize;
638     SDOperand Old;
639     SDOperand New;
640
641     explicit TargetLoweringOpt(SelectionDAG &InDAG, bool afterLegalize)
642       : DAG(InDAG), AfterLegalize(afterLegalize) {}
643     
644     bool CombineTo(SDOperand O, SDOperand N) { 
645       Old = O; 
646       New = N; 
647       return true;
648     }
649     
650     /// ShrinkDemandedConstant - Check to see if the specified operand of the 
651     /// specified instruction is a constant integer.  If so, check to see if
652     /// there are any bits set in the constant that are not demanded.  If so,
653     /// shrink the constant and return true.
654     bool ShrinkDemandedConstant(SDOperand Op, const APInt &Demanded);
655   };
656                                                 
657   /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
658   /// DemandedMask bits of the result of Op are ever used downstream.  If we can
659   /// use this information to simplify Op, create a new simplified DAG node and
660   /// return true, returning the original and new nodes in Old and New. 
661   /// Otherwise, analyze the expression and return a mask of KnownOne and 
662   /// KnownZero bits for the expression (used to simplify the caller).  
663   /// The KnownZero/One bits may only be accurate for those bits in the 
664   /// DemandedMask.
665   bool SimplifyDemandedBits(SDOperand Op, const APInt &DemandedMask, 
666                             APInt &KnownZero, APInt &KnownOne,
667                             TargetLoweringOpt &TLO, unsigned Depth = 0) const;
668   
669   /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
670   /// Mask are known to be either zero or one and return them in the 
671   /// KnownZero/KnownOne bitsets.
672   virtual void computeMaskedBitsForTargetNode(const SDOperand Op,
673                                               const APInt &Mask,
674                                               APInt &KnownZero, 
675                                               APInt &KnownOne,
676                                               const SelectionDAG &DAG,
677                                               unsigned Depth = 0) const;
678
679   /// ComputeNumSignBitsForTargetNode - This method can be implemented by
680   /// targets that want to expose additional information about sign bits to the
681   /// DAG Combiner.
682   virtual unsigned ComputeNumSignBitsForTargetNode(SDOperand Op,
683                                                    unsigned Depth = 0) const;
684   
685   struct DAGCombinerInfo {
686     void *DC;  // The DAG Combiner object.
687     bool BeforeLegalize;
688     bool CalledByLegalizer;
689   public:
690     SelectionDAG &DAG;
691     
692     DAGCombinerInfo(SelectionDAG &dag, bool bl, bool cl, void *dc)
693       : DC(dc), BeforeLegalize(bl), CalledByLegalizer(cl), DAG(dag) {}
694     
695     bool isBeforeLegalize() const { return BeforeLegalize; }
696     bool isCalledByLegalizer() const { return CalledByLegalizer; }
697     
698     void AddToWorklist(SDNode *N);
699     SDOperand CombineTo(SDNode *N, const std::vector<SDOperand> &To);
700     SDOperand CombineTo(SDNode *N, SDOperand Res);
701     SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1);
702   };
703
704   /// SimplifySetCC - Try to simplify a setcc built with the specified operands 
705   /// and cc. If it is unable to simplify it, return a null SDOperand.
706   SDOperand SimplifySetCC(MVT VT, SDOperand N0, SDOperand N1,
707                           ISD::CondCode Cond, bool foldBooleans,
708                           DAGCombinerInfo &DCI) const;
709
710   /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
711   /// node is a GlobalAddress + offset.
712   virtual bool
713   isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) const;
714
715   /// isConsecutiveLoad - Return true if LD (which must be a LoadSDNode) is
716   /// loading 'Bytes' bytes from a location that is 'Dist' units away from the
717   /// location that the 'Base' load is loading from.
718   bool isConsecutiveLoad(SDNode *LD, SDNode *Base, unsigned Bytes, int Dist,
719                          const MachineFrameInfo *MFI) const;
720
721   /// PerformDAGCombine - This method will be invoked for all target nodes and
722   /// for any target-independent nodes that the target has registered with
723   /// invoke it for.
724   ///
725   /// The semantics are as follows:
726   /// Return Value:
727   ///   SDOperand.Val == 0   - No change was made
728   ///   SDOperand.Val == N   - N was replaced, is dead, and is already handled.
729   ///   otherwise            - N should be replaced by the returned Operand.
730   ///
731   /// In addition, methods provided by DAGCombinerInfo may be used to perform
732   /// more complex transformations.
733   ///
734   virtual SDOperand PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
735   
736   //===--------------------------------------------------------------------===//
737   // TargetLowering Configuration Methods - These methods should be invoked by
738   // the derived class constructor to configure this object for the target.
739   //
740
741 protected:
742   /// setUsesGlobalOffsetTable - Specify that this target does or doesn't use a
743   /// GOT for PC-relative code.
744   void setUsesGlobalOffsetTable(bool V) { UsesGlobalOffsetTable = V; }
745
746   /// setShiftAmountType - Describe the type that should be used for shift
747   /// amounts.  This type defaults to the pointer type.
748   void setShiftAmountType(MVT VT) { ShiftAmountTy = VT; }
749
750   /// setSetCCResultContents - Specify how the target extends the result of a
751   /// setcc operation in a register.
752   void setSetCCResultContents(SetCCResultValue Ty) { SetCCResultContents = Ty; }
753
754   /// setSchedulingPreference - Specify the target scheduling preference.
755   void setSchedulingPreference(SchedPreference Pref) {
756     SchedPreferenceInfo = Pref;
757   }
758
759   /// setShiftAmountFlavor - Describe how the target handles out of range shift
760   /// amounts.
761   void setShiftAmountFlavor(OutOfRangeShiftAmount OORSA) {
762     ShiftAmtHandling = OORSA;
763   }
764
765   /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
766   /// use _setjmp to implement llvm.setjmp or the non _ version.
767   /// Defaults to false.
768   void setUseUnderscoreSetJmp(bool Val) {
769     UseUnderscoreSetJmp = Val;
770   }
771
772   /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
773   /// use _longjmp to implement llvm.longjmp or the non _ version.
774   /// Defaults to false.
775   void setUseUnderscoreLongJmp(bool Val) {
776     UseUnderscoreLongJmp = Val;
777   }
778
779   /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
780   /// specifies the register that llvm.savestack/llvm.restorestack should save
781   /// and restore.
782   void setStackPointerRegisterToSaveRestore(unsigned R) {
783     StackPointerRegisterToSaveRestore = R;
784   }
785   
786   /// setExceptionPointerRegister - If set to a physical register, this sets
787   /// the register that receives the exception address on entry to a landing
788   /// pad.
789   void setExceptionPointerRegister(unsigned R) {
790     ExceptionPointerRegister = R;
791   }
792
793   /// setExceptionSelectorRegister - If set to a physical register, this sets
794   /// the register that receives the exception typeid on entry to a landing
795   /// pad.
796   void setExceptionSelectorRegister(unsigned R) {
797     ExceptionSelectorRegister = R;
798   }
799
800   /// SelectIsExpensive - Tells the code generator not to expand operations
801   /// into sequences that use the select operations if possible.
802   void setSelectIsExpensive() { SelectIsExpensive = true; }
803
804   /// setIntDivIsCheap - Tells the code generator that integer divide is
805   /// expensive, and if possible, should be replaced by an alternate sequence
806   /// of instructions not containing an integer divide.
807   void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
808   
809   /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
810   /// srl/add/sra for a signed divide by power of two, and let the target handle
811   /// it.
812   void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
813   
814   /// addRegisterClass - Add the specified register class as an available
815   /// regclass for the specified value type.  This indicates the selector can
816   /// handle values of that class natively.
817   void addRegisterClass(MVT VT, TargetRegisterClass *RC) {
818     assert((unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
819     AvailableRegClasses.push_back(std::make_pair(VT, RC));
820     RegClassForVT[VT.getSimpleVT()] = RC;
821   }
822
823   /// computeRegisterProperties - Once all of the register classes are added,
824   /// this allows us to compute derived properties we expose.
825   void computeRegisterProperties();
826
827   /// setOperationAction - Indicate that the specified operation does not work
828   /// with the specified type and indicate what to do about it.
829   void setOperationAction(unsigned Op, MVT VT,
830                           LegalizeAction Action) {
831     assert((unsigned)VT.getSimpleVT() < sizeof(OpActions[0])*4 &&
832            Op < array_lengthof(OpActions) && "Table isn't big enough!");
833     OpActions[Op] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
834     OpActions[Op] |= (uint64_t)Action << VT.getSimpleVT()*2;
835   }
836   
837   /// setLoadXAction - Indicate that the specified load with extension does not
838   /// work with the with specified type and indicate what to do about it.
839   void setLoadXAction(unsigned ExtType, MVT VT,
840                       LegalizeAction Action) {
841     assert((unsigned)VT.getSimpleVT() < sizeof(LoadXActions[0])*4 &&
842            ExtType < array_lengthof(LoadXActions) &&
843            "Table isn't big enough!");
844     LoadXActions[ExtType] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
845     LoadXActions[ExtType] |= (uint64_t)Action << VT.getSimpleVT()*2;
846   }
847   
848   /// setTruncStoreAction - Indicate that the specified truncating store does
849   /// not work with the with specified type and indicate what to do about it.
850   void setTruncStoreAction(MVT ValVT, MVT MemVT,
851                            LegalizeAction Action) {
852     assert((unsigned)ValVT.getSimpleVT() < array_lengthof(TruncStoreActions) &&
853            (unsigned)MemVT.getSimpleVT() < sizeof(TruncStoreActions[0])*4 &&
854            "Table isn't big enough!");
855     TruncStoreActions[ValVT.getSimpleVT()] &= ~(uint64_t(3UL) <<
856                                                 MemVT.getSimpleVT()*2);
857     TruncStoreActions[ValVT.getSimpleVT()] |= (uint64_t)Action <<
858       MemVT.getSimpleVT()*2;
859   }
860
861   /// setIndexedLoadAction - Indicate that the specified indexed load does or
862   /// does not work with the with specified type and indicate what to do abort
863   /// it. NOTE: All indexed mode loads are initialized to Expand in
864   /// TargetLowering.cpp
865   void setIndexedLoadAction(unsigned IdxMode, MVT VT,
866                             LegalizeAction Action) {
867     assert((unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[0])*4 &&
868            IdxMode < array_lengthof(IndexedModeActions[0]) &&
869            "Table isn't big enough!");
870     IndexedModeActions[0][IdxMode] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
871     IndexedModeActions[0][IdxMode] |= (uint64_t)Action << VT.getSimpleVT()*2;
872   }
873   
874   /// setIndexedStoreAction - Indicate that the specified indexed store does or
875   /// does not work with the with specified type and indicate what to do about
876   /// it. NOTE: All indexed mode stores are initialized to Expand in
877   /// TargetLowering.cpp
878   void setIndexedStoreAction(unsigned IdxMode, MVT VT,
879                              LegalizeAction Action) {
880     assert((unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[1][0])*4 &&
881            IdxMode < array_lengthof(IndexedModeActions[1]) &&
882            "Table isn't big enough!");
883     IndexedModeActions[1][IdxMode] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
884     IndexedModeActions[1][IdxMode] |= (uint64_t)Action << VT.getSimpleVT()*2;
885   }
886   
887   /// setConvertAction - Indicate that the specified conversion does or does
888   /// not work with the with specified type and indicate what to do about it.
889   void setConvertAction(MVT FromVT, MVT ToVT,
890                         LegalizeAction Action) {
891     assert((unsigned)FromVT.getSimpleVT() < array_lengthof(ConvertActions) &&
892            (unsigned)ToVT.getSimpleVT() < sizeof(ConvertActions[0])*4 &&
893            "Table isn't big enough!");
894     ConvertActions[FromVT.getSimpleVT()] &= ~(uint64_t(3UL) <<
895                                               ToVT.getSimpleVT()*2);
896     ConvertActions[FromVT.getSimpleVT()] |= (uint64_t)Action <<
897       ToVT.getSimpleVT()*2;
898   }
899
900   /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
901   /// promotion code defaults to trying a larger integer/fp until it can find
902   /// one that works.  If that default is insufficient, this method can be used
903   /// by the target to override the default.
904   void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
905     PromoteToType[std::make_pair(Opc, OrigVT.getSimpleVT())] =
906       DestVT.getSimpleVT();
907   }
908
909   /// addLegalFPImmediate - Indicate that this target can instruction select
910   /// the specified FP immediate natively.
911   void addLegalFPImmediate(const APFloat& Imm) {
912     LegalFPImmediates.push_back(Imm);
913   }
914
915   /// setTargetDAGCombine - Targets should invoke this method for each target
916   /// independent node that they want to provide a custom DAG combiner for by
917   /// implementing the PerformDAGCombine virtual method.
918   void setTargetDAGCombine(ISD::NodeType NT) {
919     assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
920     TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
921   }
922   
923   /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
924   /// bytes); default is 200
925   void setJumpBufSize(unsigned Size) {
926     JumpBufSize = Size;
927   }
928
929   /// setJumpBufAlignment - Set the target's required jmp_buf buffer
930   /// alignment (in bytes); default is 0
931   void setJumpBufAlignment(unsigned Align) {
932     JumpBufAlignment = Align;
933   }
934
935   /// setIfCvtBlockSizeLimit - Set the target's if-conversion block size
936   /// limit (in number of instructions); default is 2.
937   void setIfCvtBlockSizeLimit(unsigned Limit) {
938     IfCvtBlockSizeLimit = Limit;
939   }
940   
941   /// setIfCvtDupBlockSizeLimit - Set the target's block size limit (in number
942   /// of instructions) to be considered for code duplication during
943   /// if-conversion; default is 2.
944   void setIfCvtDupBlockSizeLimit(unsigned Limit) {
945     IfCvtDupBlockSizeLimit = Limit;
946   }
947
948   /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
949   /// alignment is zero, it means the target does not care about loop alignment.
950   void setPrefLoopAlignment(unsigned Align) {
951     PrefLoopAlignment = Align;
952   }
953   
954 public:
955
956   virtual const TargetSubtarget *getSubtarget() {
957     assert(0 && "Not Implemented");
958     return NULL;    // this is here to silence compiler errors
959   }
960   //===--------------------------------------------------------------------===//
961   // Lowering methods - These methods must be implemented by targets so that
962   // the SelectionDAGLowering code knows how to lower these.
963   //
964
965   /// LowerArguments - This hook must be implemented to indicate how we should
966   /// lower the arguments for the specified function, into the specified DAG.
967   virtual std::vector<SDOperand>
968   LowerArguments(Function &F, SelectionDAG &DAG);
969
970   /// LowerCallTo - This hook lowers an abstract call to a function into an
971   /// actual call.  This returns a pair of operands.  The first element is the
972   /// return value for the function (if RetTy is not VoidTy).  The second
973   /// element is the outgoing token chain.
974   struct ArgListEntry {
975     SDOperand Node;
976     const Type* Ty;
977     bool isSExt;
978     bool isZExt;
979     bool isInReg;
980     bool isSRet;
981     bool isNest;
982     bool isByVal;
983     uint16_t Alignment;
984
985     ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
986       isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
987   };
988   typedef std::vector<ArgListEntry> ArgListTy;
989   virtual std::pair<SDOperand, SDOperand>
990   LowerCallTo(SDOperand Chain, const Type *RetTy, bool RetSExt, bool RetZExt,
991               bool isVarArg, unsigned CallingConv, bool isTailCall,
992               SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG);
993
994
995   /// EmitTargetCodeForMemcpy - Emit target-specific code that performs a
996   /// memcpy. This can be used by targets to provide code sequences for cases
997   /// that don't fit the target's parameters for simple loads/stores and can be
998   /// more efficient than using a library call. This function can return a null
999   /// SDOperand if the target declines to use custom code and a different
1000   /// lowering strategy should be used.
1001   /// 
1002   /// If AlwaysInline is true, the size is constant and the target should not
1003   /// emit any calls and is strongly encouraged to attempt to emit inline code
1004   /// even if it is beyond the usual threshold because this intrinsic is being
1005   /// expanded in a place where calls are not feasible (e.g. within the prologue
1006   /// for another call). If the target chooses to decline an AlwaysInline
1007   /// request here, legalize will resort to using simple loads and stores.
1008   virtual SDOperand
1009   EmitTargetCodeForMemcpy(SelectionDAG &DAG,
1010                           SDOperand Chain,
1011                           SDOperand Op1, SDOperand Op2,
1012                           SDOperand Op3, unsigned Align,
1013                           bool AlwaysInline,
1014                           const Value *DstSV, uint64_t DstOff,
1015                           const Value *SrcSV, uint64_t SrcOff) {
1016     return SDOperand();
1017   }
1018
1019   /// EmitTargetCodeForMemmove - Emit target-specific code that performs a
1020   /// memmove. This can be used by targets to provide code sequences for cases
1021   /// that don't fit the target's parameters for simple loads/stores and can be
1022   /// more efficient than using a library call. This function can return a null
1023   /// SDOperand if the target declines to use custom code and a different
1024   /// lowering strategy should be used.
1025   virtual SDOperand
1026   EmitTargetCodeForMemmove(SelectionDAG &DAG,
1027                            SDOperand Chain,
1028                            SDOperand Op1, SDOperand Op2,
1029                            SDOperand Op3, unsigned Align,
1030                            const Value *DstSV, uint64_t DstOff,
1031                            const Value *SrcSV, uint64_t SrcOff) {
1032     return SDOperand();
1033   }
1034
1035   /// EmitTargetCodeForMemset - Emit target-specific code that performs a
1036   /// memset. This can be used by targets to provide code sequences for cases
1037   /// that don't fit the target's parameters for simple stores and can be more
1038   /// efficient than using a library call. This function can return a null
1039   /// SDOperand if the target declines to use custom code and a different
1040   /// lowering strategy should be used.
1041   virtual SDOperand
1042   EmitTargetCodeForMemset(SelectionDAG &DAG,
1043                           SDOperand Chain,
1044                           SDOperand Op1, SDOperand Op2,
1045                           SDOperand Op3, unsigned Align,
1046                           const Value *DstSV, uint64_t DstOff) {
1047     return SDOperand();
1048   }
1049
1050   /// LowerOperation - This callback is invoked for operations that are 
1051   /// unsupported by the target, which are registered to use 'custom' lowering,
1052   /// and whose defined values are all legal.
1053   /// If the target has no operations that require custom lowering, it need not
1054   /// implement this.  The default implementation of this aborts.
1055   virtual SDOperand LowerOperation(SDOperand Op, SelectionDAG &DAG);
1056
1057   /// ExpandOperationResult - This callback is invoked for operations that are 
1058   /// unsupported by the target, which are registered to use 'custom' lowering,
1059   /// and whose result type needs to be expanded.  This must return a node whose
1060   /// results precisely match the results of the input node.  This typically
1061   /// involves a MERGE_VALUES node and/or BUILD_PAIR.
1062   ///
1063   /// If the target has no operations that require custom lowering, it need not
1064   /// implement this.  The default implementation of this aborts.
1065   virtual SDNode *ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
1066     assert(0 && "ExpandOperationResult not implemented for this target!");
1067     return 0;
1068   }
1069   
1070   /// IsEligibleForTailCallOptimization - Check whether the call is eligible for
1071   /// tail call optimization. Targets which want to do tail call optimization
1072   /// should override this function. 
1073   virtual bool IsEligibleForTailCallOptimization(SDOperand Call, 
1074                                                  SDOperand Ret, 
1075                                                  SelectionDAG &DAG) const {
1076     return false;
1077   }
1078
1079   /// CheckTailCallReturnConstraints - Check whether CALL node immediatly
1080   /// preceeds the RET node and whether the return uses the result of the node
1081   /// or is a void return. This function can be used by the target to determine
1082   /// eligiblity of tail call optimization.
1083   static bool CheckTailCallReturnConstraints(SDOperand Call, SDOperand Ret) {
1084     unsigned NumOps = Ret.getNumOperands();
1085     if ((NumOps == 1 &&
1086        (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1087         Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1088       (NumOps > 1 &&
1089        Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1090        Ret.getOperand(1) == SDOperand(Call.Val,0)))
1091       return true;
1092     return false;
1093   }
1094
1095   /// GetPossiblePreceedingTailCall - Get preceeding TailCallNodeOpCode node if
1096   /// it exists skip possible ISD:TokenFactor.
1097   static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain,
1098                                                  unsigned TailCallNodeOpCode) {
1099     if (Chain.getOpcode() == TailCallNodeOpCode) {
1100       return Chain;
1101     } else if (Chain.getOpcode() == ISD::TokenFactor) {
1102       if (Chain.getNumOperands() &&
1103           Chain.getOperand(0).getOpcode() == TailCallNodeOpCode)
1104         return Chain.getOperand(0);
1105     }
1106     return Chain;
1107   }
1108
1109   /// CustomPromoteOperation - This callback is invoked for operations that are
1110   /// unsupported by the target, are registered to use 'custom' lowering, and
1111   /// whose type needs to be promoted.
1112   virtual SDOperand CustomPromoteOperation(SDOperand Op, SelectionDAG &DAG);
1113   
1114   /// getTargetNodeName() - This method returns the name of a target specific
1115   /// DAG node.
1116   virtual const char *getTargetNodeName(unsigned Opcode) const;
1117
1118   //===--------------------------------------------------------------------===//
1119   // Inline Asm Support hooks
1120   //
1121   
1122   enum ConstraintType {
1123     C_Register,            // Constraint represents a single register.
1124     C_RegisterClass,       // Constraint represents one or more registers.
1125     C_Memory,              // Memory constraint.
1126     C_Other,               // Something else.
1127     C_Unknown              // Unsupported constraint.
1128   };
1129   
1130   /// AsmOperandInfo - This contains information for each constraint that we are
1131   /// lowering.
1132   struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
1133     /// ConstraintCode - This contains the actual string for the code, like "m".
1134     std::string ConstraintCode;
1135
1136     /// ConstraintType - Information about the constraint code, e.g. Register,
1137     /// RegisterClass, Memory, Other, Unknown.
1138     TargetLowering::ConstraintType ConstraintType;
1139   
1140     /// CallOperandval - If this is the result output operand or a
1141     /// clobber, this is null, otherwise it is the incoming operand to the
1142     /// CallInst.  This gets modified as the asm is processed.
1143     Value *CallOperandVal;
1144   
1145     /// ConstraintVT - The ValueType for the operand value.
1146     MVT ConstraintVT;
1147   
1148     AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
1149       : InlineAsm::ConstraintInfo(info), 
1150         ConstraintType(TargetLowering::C_Unknown),
1151         CallOperandVal(0), ConstraintVT(MVT::Other) {
1152     }
1153   };
1154
1155   /// ComputeConstraintToUse - Determines the constraint code and constraint
1156   /// type to use for the specific AsmOperandInfo, setting
1157   /// OpInfo.ConstraintCode and OpInfo.ConstraintType.  If the actual operand
1158   /// being passed in is available, it can be passed in as Op, otherwise an
1159   /// empty SDOperand can be passed.
1160   virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
1161                                       SDOperand Op,
1162                                       SelectionDAG *DAG = 0) const;
1163   
1164   /// getConstraintType - Given a constraint, return the type of constraint it
1165   /// is for this target.
1166   virtual ConstraintType getConstraintType(const std::string &Constraint) const;
1167   
1168   /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1169   /// return a list of registers that can be used to satisfy the constraint.
1170   /// This should only be used for C_RegisterClass constraints.
1171   virtual std::vector<unsigned> 
1172   getRegClassForInlineAsmConstraint(const std::string &Constraint,
1173                                     MVT VT) const;
1174
1175   /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
1176   /// {edx}), return the register number and the register class for the
1177   /// register.
1178   ///
1179   /// Given a register class constraint, like 'r', if this corresponds directly
1180   /// to an LLVM register class, return a register of 0 and the register class
1181   /// pointer.
1182   ///
1183   /// This should only be used for C_Register constraints.  On error,
1184   /// this returns a register number of 0 and a null register class pointer..
1185   virtual std::pair<unsigned, const TargetRegisterClass*> 
1186     getRegForInlineAsmConstraint(const std::string &Constraint,
1187                                  MVT VT) const;
1188   
1189   /// LowerXConstraint - try to replace an X constraint, which matches anything,
1190   /// with another that has more specific requirements based on the type of the
1191   /// corresponding operand.  This returns null if there is no replacement to
1192   /// make.
1193   virtual const char *LowerXConstraint(MVT ConstraintVT) const;
1194   
1195   /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1196   /// vector.  If it is invalid, don't add anything to Ops.
1197   virtual void LowerAsmOperandForConstraint(SDOperand Op, char ConstraintLetter,
1198                                             std::vector<SDOperand> &Ops,
1199                                             SelectionDAG &DAG) const;
1200   
1201   //===--------------------------------------------------------------------===//
1202   // Scheduler hooks
1203   //
1204   
1205   // EmitInstrWithCustomInserter - This method should be implemented by targets
1206   // that mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
1207   // instructions are special in various ways, which require special support to
1208   // insert.  The specified MachineInstr is created but not inserted into any
1209   // basic blocks, and the scheduler passes ownership of it to this method.
1210   virtual MachineBasicBlock *EmitInstrWithCustomInserter(MachineInstr *MI,
1211                                                         MachineBasicBlock *MBB);
1212
1213   //===--------------------------------------------------------------------===//
1214   // Addressing mode description hooks (used by LSR etc).
1215   //
1216
1217   /// AddrMode - This represents an addressing mode of:
1218   ///    BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1219   /// If BaseGV is null,  there is no BaseGV.
1220   /// If BaseOffs is zero, there is no base offset.
1221   /// If HasBaseReg is false, there is no base register.
1222   /// If Scale is zero, there is no ScaleReg.  Scale of 1 indicates a reg with
1223   /// no scale.
1224   ///
1225   struct AddrMode {
1226     GlobalValue *BaseGV;
1227     int64_t      BaseOffs;
1228     bool         HasBaseReg;
1229     int64_t      Scale;
1230     AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1231   };
1232   
1233   /// isLegalAddressingMode - Return true if the addressing mode represented by
1234   /// AM is legal for this target, for a load/store of the specified type.
1235   /// TODO: Handle pre/postinc as well.
1236   virtual bool isLegalAddressingMode(const AddrMode &AM, const Type *Ty) const;
1237
1238   /// isTruncateFree - Return true if it's free to truncate a value of
1239   /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1240   /// register EAX to i16 by referencing its sub-register AX.
1241   virtual bool isTruncateFree(const Type *Ty1, const Type *Ty2) const {
1242     return false;
1243   }
1244
1245   virtual bool isTruncateFree(MVT VT1, MVT VT2) const {
1246     return false;
1247   }
1248   
1249   //===--------------------------------------------------------------------===//
1250   // Div utility functions
1251   //
1252   SDOperand BuildSDIV(SDNode *N, SelectionDAG &DAG, 
1253                       std::vector<SDNode*>* Created) const;
1254   SDOperand BuildUDIV(SDNode *N, SelectionDAG &DAG, 
1255                       std::vector<SDNode*>* Created) const;
1256
1257
1258   //===--------------------------------------------------------------------===//
1259   // Runtime Library hooks
1260   //
1261
1262   /// setLibcallName - Rename the default libcall routine name for the specified
1263   /// libcall.
1264   void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1265     LibcallRoutineNames[Call] = Name;
1266   }
1267
1268   /// getLibcallName - Get the libcall routine name for the specified libcall.
1269   ///
1270   const char *getLibcallName(RTLIB::Libcall Call) const {
1271     return LibcallRoutineNames[Call];
1272   }
1273
1274   /// setCmpLibcallCC - Override the default CondCode to be used to test the
1275   /// result of the comparison libcall against zero.
1276   void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1277     CmpLibcallCCs[Call] = CC;
1278   }
1279
1280   /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1281   /// the comparison libcall against zero.
1282   ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1283     return CmpLibcallCCs[Call];
1284   }
1285
1286 private:
1287   TargetMachine &TM;
1288   const TargetData *TD;
1289
1290   /// IsLittleEndian - True if this is a little endian target.
1291   ///
1292   bool IsLittleEndian;
1293
1294   /// PointerTy - The type to use for pointers, usually i32 or i64.
1295   ///
1296   MVT PointerTy;
1297
1298   /// UsesGlobalOffsetTable - True if this target uses a GOT for PIC codegen.
1299   ///
1300   bool UsesGlobalOffsetTable;
1301   
1302   /// ShiftAmountTy - The type to use for shift amounts, usually i8 or whatever
1303   /// PointerTy is.
1304   MVT ShiftAmountTy;
1305
1306   OutOfRangeShiftAmount ShiftAmtHandling;
1307
1308   /// SelectIsExpensive - Tells the code generator not to expand operations
1309   /// into sequences that use the select operations if possible.
1310   bool SelectIsExpensive;
1311
1312   /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1313   /// constants into a sequence of muls, adds, and shifts.  This is a hack until
1314   /// a real cost model is in place.  If we ever optimize for size, this will be
1315   /// set to true unconditionally.
1316   bool IntDivIsCheap;
1317   
1318   /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1319   /// srl/add/sra for a signed divide by power of two, and let the target handle
1320   /// it.
1321   bool Pow2DivIsCheap;
1322   
1323   /// SetCCResultContents - Information about the contents of the high-bits in
1324   /// the result of a setcc comparison operation.
1325   SetCCResultValue SetCCResultContents;
1326
1327   /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1328   /// total cycles or lowest register usage.
1329   SchedPreference SchedPreferenceInfo;
1330   
1331   /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1332   /// llvm.setjmp.  Defaults to false.
1333   bool UseUnderscoreSetJmp;
1334
1335   /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1336   /// llvm.longjmp.  Defaults to false.
1337   bool UseUnderscoreLongJmp;
1338
1339   /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1340   unsigned JumpBufSize;
1341   
1342   /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1343   /// buffers
1344   unsigned JumpBufAlignment;
1345
1346   /// IfCvtBlockSizeLimit - The maximum allowed size for a block to be
1347   /// if-converted.
1348   unsigned IfCvtBlockSizeLimit;
1349   
1350   /// IfCvtDupBlockSizeLimit - The maximum allowed size for a block to be
1351   /// duplicated during if-conversion.
1352   unsigned IfCvtDupBlockSizeLimit;
1353
1354   /// PrefLoopAlignment - The perferred loop alignment.
1355   ///
1356   unsigned PrefLoopAlignment;
1357
1358   /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1359   /// specifies the register that llvm.savestack/llvm.restorestack should save
1360   /// and restore.
1361   unsigned StackPointerRegisterToSaveRestore;
1362
1363   /// ExceptionPointerRegister - If set to a physical register, this specifies
1364   /// the register that receives the exception address on entry to a landing
1365   /// pad.
1366   unsigned ExceptionPointerRegister;
1367
1368   /// ExceptionSelectorRegister - If set to a physical register, this specifies
1369   /// the register that receives the exception typeid on entry to a landing
1370   /// pad.
1371   unsigned ExceptionSelectorRegister;
1372
1373   /// RegClassForVT - This indicates the default register class to use for
1374   /// each ValueType the target supports natively.
1375   TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1376   unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1377   MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1378
1379   /// TransformToType - For any value types we are promoting or expanding, this
1380   /// contains the value type that we are changing to.  For Expanded types, this
1381   /// contains one step of the expand (e.g. i64 -> i32), even if there are
1382   /// multiple steps required (e.g. i64 -> i16).  For types natively supported
1383   /// by the system, this holds the same type (e.g. i32 -> i32).
1384   MVT TransformToType[MVT::LAST_VALUETYPE];
1385
1386   // Defines the capacity of the TargetLowering::OpActions table
1387   static const int OpActionsCapacity = 176;
1388
1389   /// OpActions - For each operation and each value type, keep a LegalizeAction
1390   /// that indicates how instruction selection should deal with the operation.
1391   /// Most operations are Legal (aka, supported natively by the target), but
1392   /// operations that are not should be described.  Note that operations on
1393   /// non-legal value types are not described here.
1394   uint64_t OpActions[OpActionsCapacity];
1395   
1396   /// LoadXActions - For each load of load extension type and each value type,
1397   /// keep a LegalizeAction that indicates how instruction selection should deal
1398   /// with the load.
1399   uint64_t LoadXActions[ISD::LAST_LOADX_TYPE];
1400   
1401   /// TruncStoreActions - For each truncating store, keep a LegalizeAction that
1402   /// indicates how instruction selection should deal with the store.
1403   uint64_t TruncStoreActions[MVT::LAST_VALUETYPE];
1404
1405   /// IndexedModeActions - For each indexed mode and each value type, keep a
1406   /// pair of LegalizeAction that indicates how instruction selection should
1407   /// deal with the load / store.
1408   uint64_t IndexedModeActions[2][ISD::LAST_INDEXED_MODE];
1409   
1410   /// ConvertActions - For each conversion from source type to destination type,
1411   /// keep a LegalizeAction that indicates how instruction selection should
1412   /// deal with the conversion.
1413   /// Currently, this is used only for floating->floating conversions
1414   /// (FP_EXTEND and FP_ROUND).
1415   uint64_t ConvertActions[MVT::LAST_VALUETYPE];
1416
1417   ValueTypeActionImpl ValueTypeActions;
1418
1419   std::vector<APFloat> LegalFPImmediates;
1420
1421   std::vector<std::pair<MVT, TargetRegisterClass*> > AvailableRegClasses;
1422
1423   /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
1424   /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
1425   /// which sets a bit in this array.
1426   unsigned char
1427   TargetDAGCombineArray[OpActionsCapacity/(sizeof(unsigned char)*8)];
1428   
1429   /// PromoteToType - For operations that must be promoted to a specific type,
1430   /// this holds the destination type.  This map should be sparse, so don't hold
1431   /// it as an array.
1432   ///
1433   /// Targets add entries to this map with AddPromotedToType(..), clients access
1434   /// this with getTypeToPromoteTo(..).
1435   std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1436     PromoteToType;
1437
1438   /// LibcallRoutineNames - Stores the name each libcall.
1439   ///
1440   const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1441
1442   /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
1443   /// of each of the comparison libcall against zero.
1444   ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1445
1446 protected:
1447   /// When lowering %llvm.memset this field specifies the maximum number of
1448   /// store operations that may be substituted for the call to memset. Targets
1449   /// must set this value based on the cost threshold for that target. Targets
1450   /// should assume that the memset will be done using as many of the largest
1451   /// store operations first, followed by smaller ones, if necessary, per
1452   /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1453   /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1454   /// store.  This only applies to setting a constant array of a constant size.
1455   /// @brief Specify maximum number of store instructions per memset call.
1456   unsigned maxStoresPerMemset;
1457
1458   /// When lowering %llvm.memcpy this field specifies the maximum number of
1459   /// store operations that may be substituted for a call to memcpy. Targets
1460   /// must set this value based on the cost threshold for that target. Targets
1461   /// should assume that the memcpy will be done using as many of the largest
1462   /// store operations first, followed by smaller ones, if necessary, per
1463   /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1464   /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1465   /// and one 1-byte store. This only applies to copying a constant array of
1466   /// constant size.
1467   /// @brief Specify maximum bytes of store instructions per memcpy call.
1468   unsigned maxStoresPerMemcpy;
1469
1470   /// When lowering %llvm.memmove this field specifies the maximum number of
1471   /// store instructions that may be substituted for a call to memmove. Targets
1472   /// must set this value based on the cost threshold for that target. Targets
1473   /// should assume that the memmove will be done using as many of the largest
1474   /// store operations first, followed by smaller ones, if necessary, per
1475   /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1476   /// with 8-bit alignment would result in nine 1-byte stores.  This only
1477   /// applies to copying a constant array of constant size.
1478   /// @brief Specify maximum bytes of store instructions per memmove call.
1479   unsigned maxStoresPerMemmove;
1480
1481   /// This field specifies whether the target machine permits unaligned memory
1482   /// accesses.  This is used, for example, to determine the size of store 
1483   /// operations when copying small arrays and other similar tasks.
1484   /// @brief Indicate whether the target permits unaligned memory accesses.
1485   bool allowUnalignedMemoryAccesses;
1486 };
1487 } // end llvm namespace
1488
1489 #endif