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