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