0ebf1d505497dd747d5deba91190d240016ba802
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Type.h"
26 #include "llvm/CodeGen/SelectionDAGNodes.h"
27 #include <map>
28
29 namespace llvm {
30   class Value;
31   class Function;
32   class TargetMachine;
33   class TargetData;
34   class TargetRegisterClass;
35   class SDNode;
36   class SDOperand;
37   class SelectionDAG;
38   class MachineBasicBlock;
39   class MachineInstr;
40
41 //===----------------------------------------------------------------------===//
42 /// TargetLowering - This class defines information used to lower LLVM code to
43 /// legal SelectionDAG operators that the target instruction selector can accept
44 /// natively.
45 ///
46 /// This class also defines callbacks that targets must implement to lower
47 /// target-specific constructs to SelectionDAG operators.
48 ///
49 class TargetLowering {
50 public:
51   /// LegalizeAction - This enum indicates whether operations are valid for a
52   /// target, and if not, what action should be used to make them valid.
53   enum LegalizeAction {
54     Legal,      // The target natively supports this operation.
55     Promote,    // This operation should be executed in a larger type.
56     Expand,     // Try to expand this to other ops, otherwise use a libcall.
57     Custom      // Use the LowerOperation hook to implement custom lowering.
58   };
59
60   enum OutOfRangeShiftAmount {
61     Undefined,  // Oversized shift amounts are undefined (default).
62     Mask,       // Shift amounts are auto masked (anded) to value size.
63     Extend      // Oversized shift pulls in zeros or sign bits.
64   };
65
66   enum SetCCResultValue {
67     UndefinedSetCCResult,          // SetCC returns a garbage/unknown extend.
68     ZeroOrOneSetCCResult,          // SetCC returns a zero extended result.
69     ZeroOrNegativeOneSetCCResult   // SetCC returns a sign extended result.
70   };
71
72   enum SchedPreference {
73     SchedulingForLatency,          // Scheduling for shortest total latency.
74     SchedulingForRegPressure       // Scheduling for lowest register pressure.
75   };
76
77   TargetLowering(TargetMachine &TM);
78   virtual ~TargetLowering();
79
80   TargetMachine &getTargetMachine() const { return TM; }
81   const TargetData *getTargetData() const { return TD; }
82
83   bool isLittleEndian() const { return IsLittleEndian; }
84   MVT::ValueType getPointerTy() const { return PointerTy; }
85   MVT::ValueType getShiftAmountTy() const { return ShiftAmountTy; }
86   OutOfRangeShiftAmount getShiftAmountFlavor() const {return ShiftAmtHandling; }
87
88   /// usesGlobalOffsetTable - Return true if this target uses a GOT for PIC
89   /// codegen.
90   bool usesGlobalOffsetTable() const { return UsesGlobalOffsetTable; }
91   
92   /// isSetCCExpensive - Return true if the setcc operation is expensive for
93   /// this target.
94   bool isSetCCExpensive() const { return SetCCIsExpensive; }
95   
96   /// isIntDivCheap() - Return true if integer divide is usually cheaper than
97   /// a sequence of several shifts, adds, and multiplies for this target.
98   bool isIntDivCheap() const { return IntDivIsCheap; }
99
100   /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
101   /// srl/add/sra.
102   bool isPow2DivCheap() const { return Pow2DivIsCheap; }
103   
104   /// getSetCCResultTy - Return the ValueType of the result of setcc operations.
105   ///
106   MVT::ValueType getSetCCResultTy() const { return SetCCResultTy; }
107
108   /// getSetCCResultContents - For targets without boolean registers, this flag
109   /// returns information about the contents of the high-bits in the setcc
110   /// result register.
111   SetCCResultValue getSetCCResultContents() const { return SetCCResultContents;}
112
113   /// getSchedulingPreference - Return target scheduling preference.
114   SchedPreference getSchedulingPreference() const {
115     return SchedPreferenceInfo;
116   }
117
118   /// getRegClassFor - Return the register class that should be used for the
119   /// specified value type.  This may only be called on legal types.
120   TargetRegisterClass *getRegClassFor(MVT::ValueType VT) const {
121     TargetRegisterClass *RC = RegClassForVT[VT];
122     assert(RC && "This value type is not natively supported!");
123     return RC;
124   }
125   
126   /// isTypeLegal - Return true if the target has native support for the
127   /// specified value type.  This means that it has a register that directly
128   /// holds it without promotions or expansions.
129   bool isTypeLegal(MVT::ValueType VT) const {
130     return RegClassForVT[VT] != 0;
131   }
132
133   class ValueTypeActionImpl {
134     /// ValueTypeActions - This is a bitvector that contains two bits for each
135     /// value type, where the two bits correspond to the LegalizeAction enum.
136     /// This can be queried with "getTypeAction(VT)".
137     uint32_t ValueTypeActions[2];
138   public:
139     ValueTypeActionImpl() {
140       ValueTypeActions[0] = ValueTypeActions[1] = 0;
141     }
142     ValueTypeActionImpl(const ValueTypeActionImpl &RHS) {
143       ValueTypeActions[0] = RHS.ValueTypeActions[0];
144       ValueTypeActions[1] = RHS.ValueTypeActions[1];
145     }
146     
147     LegalizeAction getTypeAction(MVT::ValueType VT) const {
148       return (LegalizeAction)((ValueTypeActions[VT>>4] >> ((2*VT) & 31)) & 3);
149     }
150     void setTypeAction(MVT::ValueType VT, LegalizeAction Action) {
151       assert(unsigned(VT >> 4) < 
152              sizeof(ValueTypeActions)/sizeof(ValueTypeActions[0]));
153       ValueTypeActions[VT>>4] |= Action << ((VT*2) & 31);
154     }
155   };
156   
157   const ValueTypeActionImpl &getValueTypeActions() const {
158     return ValueTypeActions;
159   }
160   
161   /// getTypeAction - Return how we should legalize values of this type, either
162   /// it is already legal (return 'Legal') or we need to promote it to a larger
163   /// type (return 'Promote'), or we need to expand it into multiple registers
164   /// of smaller integer type (return 'Expand').  'Custom' is not an option.
165   LegalizeAction getTypeAction(MVT::ValueType VT) const {
166     return ValueTypeActions.getTypeAction(VT);
167   }
168
169   /// getTypeToTransformTo - For types supported by the target, this is an
170   /// identity function.  For types that must be promoted to larger types, this
171   /// returns the larger type to promote to.  For types that are larger than the
172   /// largest integer register, this contains one step in the expansion to get
173   /// to the smaller register.
174   MVT::ValueType getTypeToTransformTo(MVT::ValueType VT) const {
175     return TransformToType[VT];
176   }
177   
178   /// getPackedTypeBreakdown - Packed types are broken down into some number of
179   /// legal first class types.  For example, <8 x float> maps to 2 MVT::v4f32
180   /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
181   /// Similarly, <2 x long> turns into 4 MVT::i32 values with both PPC and X86.
182   ///
183   /// This method returns the number of registers needed, and the VT for each
184   /// register.  It also returns the VT of the PackedType elements before they
185   /// are promoted/expanded.
186   ///
187   unsigned getPackedTypeBreakdown(const PackedType *PTy, 
188                                   MVT::ValueType &PTyElementVT,
189                                   MVT::ValueType &PTyLegalElementVT) const;
190   
191   typedef std::vector<double>::const_iterator legal_fpimm_iterator;
192   legal_fpimm_iterator legal_fpimm_begin() const {
193     return LegalFPImmediates.begin();
194   }
195   legal_fpimm_iterator legal_fpimm_end() const {
196     return LegalFPImmediates.end();
197   }
198   
199   /// isShuffleMaskLegal - Targets can use this to indicate that they only
200   /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
201   /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
202   /// are assumed to be legal.
203   virtual bool isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
204     return true;
205   }
206
207   /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
208   /// used by Targets can use this to indicate if there is a suitable
209   /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
210   /// pool entry.
211   virtual bool isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
212                                       MVT::ValueType EVT,
213                                       SelectionDAG &DAG) const {
214     return false;
215   }
216
217   /// getOperationAction - Return how this operation should be treated: either
218   /// it is legal, needs to be promoted to a larger size, needs to be
219   /// expanded to some other code sequence, or the target has a custom expander
220   /// for it.
221   LegalizeAction getOperationAction(unsigned Op, MVT::ValueType VT) const {
222     return (LegalizeAction)((OpActions[Op] >> (2*VT)) & 3);
223   }
224   
225   /// isOperationLegal - Return true if the specified operation is legal on this
226   /// target.
227   bool isOperationLegal(unsigned Op, MVT::ValueType VT) const {
228     return getOperationAction(Op, VT) == Legal ||
229            getOperationAction(Op, VT) == Custom;
230   }
231   
232   /// getLoadXAction - Return how this load with extension should be treated:
233   /// either it is legal, needs to be promoted to a larger size, needs to be
234   /// expanded to some other code sequence, or the target has a custom expander
235   /// for it.
236   LegalizeAction getLoadXAction(unsigned LType, MVT::ValueType VT) const {
237     return (LegalizeAction)((LoadXActions[LType] >> (2*VT)) & 3);
238   }
239   
240   /// isLoadXLegal - Return true if the specified load with extension is legal
241   /// on this target.
242   bool isLoadXLegal(unsigned LType, MVT::ValueType VT) const {
243     return getLoadXAction(LType, VT) == Legal ||
244            getLoadXAction(LType, VT) == Custom;
245   }
246   
247   /// getStoreXAction - Return how this store with truncation should be treated:
248   /// either it is legal, needs to be promoted to a larger size, needs to be
249   /// expanded to some other code sequence, or the target has a custom expander
250   /// for it.
251   LegalizeAction getStoreXAction(MVT::ValueType VT) const {
252     return (LegalizeAction)((StoreXActions >> (2*VT)) & 3);
253   }
254   
255   /// isStoreXLegal - Return true if the specified store with truncation is
256   /// legal on this target.
257   bool isStoreXLegal(MVT::ValueType VT) const {
258     return getStoreXAction(VT) == Legal || getStoreXAction(VT) == Custom;
259   }
260
261   /// getTypeToPromoteTo - If the action for this operation is to promote, this
262   /// method returns the ValueType to promote to.
263   MVT::ValueType getTypeToPromoteTo(unsigned Op, MVT::ValueType VT) const {
264     assert(getOperationAction(Op, VT) == Promote &&
265            "This operation isn't promoted!");
266
267     // See if this has an explicit type specified.
268     std::map<std::pair<unsigned, MVT::ValueType>, 
269              MVT::ValueType>::const_iterator PTTI =
270       PromoteToType.find(std::make_pair(Op, VT));
271     if (PTTI != PromoteToType.end()) return PTTI->second;
272     
273     assert((MVT::isInteger(VT) || MVT::isFloatingPoint(VT)) &&
274            "Cannot autopromote this type, add it with AddPromotedToType.");
275     
276     MVT::ValueType NVT = VT;
277     do {
278       NVT = (MVT::ValueType)(NVT+1);
279       assert(MVT::isInteger(NVT) == MVT::isInteger(VT) && NVT != MVT::isVoid &&
280              "Didn't find type to promote to!");
281     } while (!isTypeLegal(NVT) ||
282               getOperationAction(Op, NVT) == Promote);
283     return NVT;
284   }
285
286   /// getValueType - Return the MVT::ValueType corresponding to this LLVM type.
287   /// This is fixed by the LLVM operations except for the pointer size.
288   MVT::ValueType getValueType(const Type *Ty) const {
289     switch (Ty->getTypeID()) {
290     default: assert(0 && "Unknown type!");
291     case Type::VoidTyID:    return MVT::isVoid;
292     case Type::BoolTyID:    return MVT::i1;
293     case Type::UByteTyID:
294     case Type::SByteTyID:   return MVT::i8;
295     case Type::ShortTyID:
296     case Type::UShortTyID:  return MVT::i16;
297     case Type::IntTyID:
298     case Type::UIntTyID:    return MVT::i32;
299     case Type::LongTyID:
300     case Type::ULongTyID:   return MVT::i64;
301     case Type::FloatTyID:   return MVT::f32;
302     case Type::DoubleTyID:  return MVT::f64;
303     case Type::PointerTyID: return PointerTy;
304     case Type::PackedTyID:  return MVT::Vector;
305     }
306   }
307
308   /// getNumElements - Return the number of registers that this ValueType will
309   /// eventually require.  This is always one for all non-integer types, is
310   /// one for any types promoted to live in larger registers, but may be more
311   /// than one for types (like i64) that are split into pieces.
312   unsigned getNumElements(MVT::ValueType VT) const {
313     return NumElementsForVT[VT];
314   }
315   
316   /// hasTargetDAGCombine - If true, the target has custom DAG combine
317   /// transformations that it can perform for the specified node.
318   bool hasTargetDAGCombine(ISD::NodeType NT) const {
319     return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
320   }
321
322   /// This function returns the maximum number of store operations permitted
323   /// to replace a call to llvm.memset. The value is set by the target at the
324   /// performance threshold for such a replacement.
325   /// @brief Get maximum # of store operations permitted for llvm.memset
326   unsigned getMaxStoresPerMemset() const { return maxStoresPerMemset; }
327
328   /// This function returns the maximum number of store operations permitted
329   /// to replace a call to llvm.memcpy. The value is set by the target at the
330   /// performance threshold for such a replacement.
331   /// @brief Get maximum # of store operations permitted for llvm.memcpy
332   unsigned getMaxStoresPerMemcpy() const { return maxStoresPerMemcpy; }
333
334   /// This function returns the maximum number of store operations permitted
335   /// to replace a call to llvm.memmove. The value is set by the target at the
336   /// performance threshold for such a replacement.
337   /// @brief Get maximum # of store operations permitted for llvm.memmove
338   unsigned getMaxStoresPerMemmove() const { return maxStoresPerMemmove; }
339
340   /// This function returns true if the target allows unaligned memory accesses.
341   /// This is used, for example, in situations where an array copy/move/set is 
342   /// converted to a sequence of store operations. It's use helps to ensure that
343   /// such replacements don't generate code that causes an alignment error 
344   /// (trap) on the target machine. 
345   /// @brief Determine if the target supports unaligned memory accesses.
346   bool allowsUnalignedMemoryAccesses() const {
347     return allowUnalignedMemoryAccesses;
348   }
349   
350   /// usesUnderscoreSetJmpLongJmp - Determine if we should use _setjmp or setjmp
351   /// to implement llvm.setjmp.
352   bool usesUnderscoreSetJmpLongJmp() const {
353     return UseUnderscoreSetJmpLongJmp;
354   }
355   
356   /// getStackPointerRegisterToSaveRestore - If a physical register, this
357   /// specifies the register that llvm.savestack/llvm.restorestack should save
358   /// and restore.
359   unsigned getStackPointerRegisterToSaveRestore() const {
360     return StackPointerRegisterToSaveRestore;
361   }
362
363   /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
364   /// set, the default is 200)
365   unsigned getJumpBufSize() const {
366     return JumpBufSize;
367   }
368
369   /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
370   /// (if never set, the default is 0)
371   unsigned getJumpBufAlignment() const {
372     return JumpBufAlignment;
373   }
374
375   /// getLegalPreIndexedAddressBase - returns true by value, base pointer and
376   /// offset pointer and addressing mode by reference if the node's address
377   /// can be legally represented as pre-indexed load / store address.
378   virtual bool getLegalPreIndexedAddressBase(SDNode *N, SDOperand &Base,
379                                              SDOperand &Offset,
380                                              ISD::MemOpAddrMode &AM,
381                                              SelectionDAG &DAG) {
382     return false;
383   }
384   
385   //===--------------------------------------------------------------------===//
386   // TargetLowering Optimization Methods
387   //
388   
389   /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
390   /// SDOperands for returning information from TargetLowering to its clients
391   /// that want to combine 
392   struct TargetLoweringOpt {
393     SelectionDAG &DAG;
394     SDOperand Old;
395     SDOperand New;
396
397     TargetLoweringOpt(SelectionDAG &InDAG) : DAG(InDAG) {}
398     
399     bool CombineTo(SDOperand O, SDOperand N) { 
400       Old = O; 
401       New = N; 
402       return true;
403     }
404     
405     /// ShrinkDemandedConstant - Check to see if the specified operand of the 
406     /// specified instruction is a constant integer.  If so, check to see if there
407     /// are any bits set in the constant that are not demanded.  If so, shrink the
408     /// constant and return true.
409     bool ShrinkDemandedConstant(SDOperand Op, uint64_t Demanded);
410   };
411                                                 
412   /// MaskedValueIsZero - Return true if 'Op & Mask' is known to be zero.  We
413   /// use this predicate to simplify operations downstream.  Op and Mask are
414   /// known to be the same type.
415   bool MaskedValueIsZero(SDOperand Op, uint64_t Mask, unsigned Depth = 0)
416     const;
417   
418   /// ComputeMaskedBits - Determine which of the bits specified in Mask are
419   /// known to be either zero or one and return them in the KnownZero/KnownOne
420   /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
421   /// processing.  Targets can implement the computeMaskedBitsForTargetNode 
422   /// method, to allow target nodes to be understood.
423   void ComputeMaskedBits(SDOperand Op, uint64_t Mask, uint64_t &KnownZero,
424                          uint64_t &KnownOne, unsigned Depth = 0) const;
425     
426   /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
427   /// DemandedMask bits of the result of Op are ever used downstream.  If we can
428   /// use this information to simplify Op, create a new simplified DAG node and
429   /// return true, returning the original and new nodes in Old and New. 
430   /// Otherwise, analyze the expression and return a mask of KnownOne and 
431   /// KnownZero bits for the expression (used to simplify the caller).  
432   /// The KnownZero/One bits may only be accurate for those bits in the 
433   /// DemandedMask.
434   bool SimplifyDemandedBits(SDOperand Op, uint64_t DemandedMask, 
435                             uint64_t &KnownZero, uint64_t &KnownOne,
436                             TargetLoweringOpt &TLO, unsigned Depth = 0) const;
437   
438   /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
439   /// Mask are known to be either zero or one and return them in the 
440   /// KnownZero/KnownOne bitsets.
441   virtual void computeMaskedBitsForTargetNode(const SDOperand Op,
442                                               uint64_t Mask,
443                                               uint64_t &KnownZero, 
444                                               uint64_t &KnownOne,
445                                               unsigned Depth = 0) const;
446
447   /// ComputeNumSignBits - Return the number of times the sign bit of the
448   /// register is replicated into the other bits.  We know that at least 1 bit
449   /// is always equal to the sign bit (itself), but other cases can give us
450   /// information.  For example, immediately after an "SRA X, 2", we know that
451   /// the top 3 bits are all equal to each other, so we return 3.
452   unsigned ComputeNumSignBits(SDOperand Op, unsigned Depth = 0) const;
453   
454   /// ComputeNumSignBitsForTargetNode - This method can be implemented by
455   /// targets that want to expose additional information about sign bits to the
456   /// DAG Combiner.
457   virtual unsigned ComputeNumSignBitsForTargetNode(SDOperand Op,
458                                                    unsigned Depth = 0) const;
459   
460   struct DAGCombinerInfo {
461     void *DC;  // The DAG Combiner object.
462     bool BeforeLegalize;
463   public:
464     SelectionDAG &DAG;
465     
466     DAGCombinerInfo(SelectionDAG &dag, bool bl, void *dc)
467       : DC(dc), BeforeLegalize(bl), DAG(dag) {}
468     
469     bool isBeforeLegalize() const { return BeforeLegalize; }
470     
471     void AddToWorklist(SDNode *N);
472     SDOperand CombineTo(SDNode *N, const std::vector<SDOperand> &To);
473     SDOperand CombineTo(SDNode *N, SDOperand Res);
474     SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1);
475   };
476
477   /// PerformDAGCombine - This method will be invoked for all target nodes and
478   /// for any target-independent nodes that the target has registered with
479   /// invoke it for.
480   ///
481   /// The semantics are as follows:
482   /// Return Value:
483   ///   SDOperand.Val == 0   - No change was made
484   ///   SDOperand.Val == N   - N was replaced, is dead, and is already handled.
485   ///   otherwise            - N should be replaced by the returned Operand.
486   ///
487   /// In addition, methods provided by DAGCombinerInfo may be used to perform
488   /// more complex transformations.
489   ///
490   virtual SDOperand PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
491   
492   //===--------------------------------------------------------------------===//
493   // TargetLowering Configuration Methods - These methods should be invoked by
494   // the derived class constructor to configure this object for the target.
495   //
496
497 protected:
498   /// setUsesGlobalOffsetTable - Specify that this target does or doesn't use a
499   /// GOT for PC-relative code.
500   void setUsesGlobalOffsetTable(bool V) { UsesGlobalOffsetTable = V; }
501
502   /// setShiftAmountType - Describe the type that should be used for shift
503   /// amounts.  This type defaults to the pointer type.
504   void setShiftAmountType(MVT::ValueType VT) { ShiftAmountTy = VT; }
505
506   /// setSetCCResultType - Describe the type that shoudl be used as the result
507   /// of a setcc operation.  This defaults to the pointer type.
508   void setSetCCResultType(MVT::ValueType VT) { SetCCResultTy = VT; }
509
510   /// setSetCCResultContents - Specify how the target extends the result of a
511   /// setcc operation in a register.
512   void setSetCCResultContents(SetCCResultValue Ty) { SetCCResultContents = Ty; }
513
514   /// setSchedulingPreference - Specify the target scheduling preference.
515   void setSchedulingPreference(SchedPreference Pref) {
516     SchedPreferenceInfo = Pref;
517   }
518
519   /// setShiftAmountFlavor - Describe how the target handles out of range shift
520   /// amounts.
521   void setShiftAmountFlavor(OutOfRangeShiftAmount OORSA) {
522     ShiftAmtHandling = OORSA;
523   }
524
525   /// setUseUnderscoreSetJmpLongJmp - Indicate whether this target prefers to
526   /// use _setjmp and _longjmp to or implement llvm.setjmp/llvm.longjmp or
527   /// the non _ versions.  Defaults to false.
528   void setUseUnderscoreSetJmpLongJmp(bool Val) {
529     UseUnderscoreSetJmpLongJmp = Val;
530   }
531   
532   /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
533   /// specifies the register that llvm.savestack/llvm.restorestack should save
534   /// and restore.
535   void setStackPointerRegisterToSaveRestore(unsigned R) {
536     StackPointerRegisterToSaveRestore = R;
537   }
538   
539   /// setSetCCIxExpensive - This is a short term hack for targets that codegen
540   /// setcc as a conditional branch.  This encourages the code generator to fold
541   /// setcc operations into other operations if possible.
542   void setSetCCIsExpensive() { SetCCIsExpensive = true; }
543
544   /// setIntDivIsCheap - Tells the code generator that integer divide is
545   /// expensive, and if possible, should be replaced by an alternate sequence
546   /// of instructions not containing an integer divide.
547   void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
548   
549   /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
550   /// srl/add/sra for a signed divide by power of two, and let the target handle
551   /// it.
552   void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
553   
554   /// addRegisterClass - Add the specified register class as an available
555   /// regclass for the specified value type.  This indicates the selector can
556   /// handle values of that class natively.
557   void addRegisterClass(MVT::ValueType VT, TargetRegisterClass *RC) {
558     AvailableRegClasses.push_back(std::make_pair(VT, RC));
559     RegClassForVT[VT] = RC;
560   }
561
562   /// computeRegisterProperties - Once all of the register classes are added,
563   /// this allows us to compute derived properties we expose.
564   void computeRegisterProperties();
565
566   /// setOperationAction - Indicate that the specified operation does not work
567   /// with the specified type and indicate what to do about it.
568   void setOperationAction(unsigned Op, MVT::ValueType VT,
569                           LegalizeAction Action) {
570     assert(VT < 32 && Op < sizeof(OpActions)/sizeof(OpActions[0]) &&
571            "Table isn't big enough!");
572     OpActions[Op] &= ~(uint64_t(3UL) << VT*2);
573     OpActions[Op] |= (uint64_t)Action << VT*2;
574   }
575   
576   /// setLoadXAction - Indicate that the specified load with extension does not
577   /// work with the with specified type and indicate what to do about it.
578   void setLoadXAction(unsigned ExtType, MVT::ValueType VT,
579                       LegalizeAction Action) {
580     assert(VT < 32 && ExtType < sizeof(LoadXActions)/sizeof(LoadXActions[0]) &&
581            "Table isn't big enough!");
582     LoadXActions[ExtType] &= ~(uint64_t(3UL) << VT*2);
583     LoadXActions[ExtType] |= (uint64_t)Action << VT*2;
584   }
585   
586   /// setStoreXAction - Indicate that the specified store with truncation does
587   /// not work with the with specified type and indicate what to do about it.
588   void setStoreXAction(MVT::ValueType VT, LegalizeAction Action) {
589     assert(VT < 32 && "Table isn't big enough!");
590     StoreXActions &= ~(uint64_t(3UL) << VT*2);
591     StoreXActions |= (uint64_t)Action << VT*2;
592   }
593
594   /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
595   /// promotion code defaults to trying a larger integer/fp until it can find
596   /// one that works.  If that default is insufficient, this method can be used
597   /// by the target to override the default.
598   void AddPromotedToType(unsigned Opc, MVT::ValueType OrigVT, 
599                          MVT::ValueType DestVT) {
600     PromoteToType[std::make_pair(Opc, OrigVT)] = DestVT;
601   }
602
603   /// addLegalFPImmediate - Indicate that this target can instruction select
604   /// the specified FP immediate natively.
605   void addLegalFPImmediate(double Imm) {
606     LegalFPImmediates.push_back(Imm);
607   }
608
609   /// setTargetDAGCombine - Targets should invoke this method for each target
610   /// independent node that they want to provide a custom DAG combiner for by
611   /// implementing the PerformDAGCombine virtual method.
612   void setTargetDAGCombine(ISD::NodeType NT) {
613     TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
614   }
615   
616   /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
617   /// bytes); default is 200
618   void setJumpBufSize(unsigned Size) {
619     JumpBufSize = Size;
620   }
621
622   /// setJumpBufAlignment - Set the target's required jmp_buf buffer
623   /// alignment (in bytes); default is 0
624   void setJumpBufAlignment(unsigned Align) {
625     JumpBufAlignment = Align;
626   }
627   
628 public:
629
630   //===--------------------------------------------------------------------===//
631   // Lowering methods - These methods must be implemented by targets so that
632   // the SelectionDAGLowering code knows how to lower these.
633   //
634
635   /// LowerArguments - This hook must be implemented to indicate how we should
636   /// lower the arguments for the specified function, into the specified DAG.
637   virtual std::vector<SDOperand>
638   LowerArguments(Function &F, SelectionDAG &DAG);
639
640   /// LowerCallTo - This hook lowers an abstract call to a function into an
641   /// actual call.  This returns a pair of operands.  The first element is the
642   /// return value for the function (if RetTy is not VoidTy).  The second
643   /// element is the outgoing token chain.
644   typedef std::vector<std::pair<SDOperand, const Type*> > ArgListTy;
645   virtual std::pair<SDOperand, SDOperand>
646   LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
647               unsigned CallingConv, bool isTailCall, SDOperand Callee,
648               ArgListTy &Args, SelectionDAG &DAG);
649
650   /// LowerFrameReturnAddress - This hook lowers a call to llvm.returnaddress or
651   /// llvm.frameaddress (depending on the value of the first argument).  The
652   /// return values are the result pointer and the resultant token chain.  If
653   /// not implemented, both of these intrinsics will return null.
654   virtual std::pair<SDOperand, SDOperand>
655   LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
656                           SelectionDAG &DAG);
657
658   /// LowerOperation - This callback is invoked for operations that are 
659   /// unsupported by the target, which are registered to use 'custom' lowering,
660   /// and whose defined values are all legal.
661   /// If the target has no operations that require custom lowering, it need not
662   /// implement this.  The default implementation of this aborts.
663   virtual SDOperand LowerOperation(SDOperand Op, SelectionDAG &DAG);
664
665   /// CustomPromoteOperation - This callback is invoked for operations that are
666   /// unsupported by the target, are registered to use 'custom' lowering, and
667   /// whose type needs to be promoted.
668   virtual SDOperand CustomPromoteOperation(SDOperand Op, SelectionDAG &DAG);
669   
670   /// getTargetNodeName() - This method returns the name of a target specific
671   /// DAG node.
672   virtual const char *getTargetNodeName(unsigned Opcode) const;
673
674   //===--------------------------------------------------------------------===//
675   // Inline Asm Support hooks
676   //
677   
678   enum ConstraintType {
679     C_Register,            // Constraint represents a single register.
680     C_RegisterClass,       // Constraint represents one or more registers.
681     C_Memory,              // Memory constraint.
682     C_Other,               // Something else.
683     C_Unknown              // Unsupported constraint.
684   };
685   
686   /// getConstraintType - Given a constraint letter, return the type of
687   /// constraint it is for this target.
688   virtual ConstraintType getConstraintType(char ConstraintLetter) const;
689   
690   
691   /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
692   /// return a list of registers that can be used to satisfy the constraint.
693   /// This should only be used for C_RegisterClass constraints.
694   virtual std::vector<unsigned> 
695   getRegClassForInlineAsmConstraint(const std::string &Constraint,
696                                     MVT::ValueType VT) const;
697
698   /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
699   /// {edx}), return the register number and the register class for the
700   /// register.
701   ///
702   /// Given a register class constraint, like 'r', if this corresponds directly
703   /// to an LLVM register class, return a register of 0 and the register class
704   /// pointer.
705   ///
706   /// This should only be used for C_Register constraints.  On error,
707   /// this returns a register number of 0 and a null register class pointer..
708   virtual std::pair<unsigned, const TargetRegisterClass*> 
709     getRegForInlineAsmConstraint(const std::string &Constraint,
710                                  MVT::ValueType VT) const;
711   
712   
713   /// isOperandValidForConstraint - Return the specified operand (possibly
714   /// modified) if the specified SDOperand is valid for the specified target
715   /// constraint letter, otherwise return null.
716   virtual SDOperand 
717     isOperandValidForConstraint(SDOperand Op, char ConstraintLetter,
718                                 SelectionDAG &DAG);
719   
720   //===--------------------------------------------------------------------===//
721   // Scheduler hooks
722   //
723   
724   // InsertAtEndOfBasicBlock - This method should be implemented by targets that
725   // mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
726   // instructions are special in various ways, which require special support to
727   // insert.  The specified MachineInstr is created but not inserted into any
728   // basic blocks, and the scheduler passes ownership of it to this method.
729   virtual MachineBasicBlock *InsertAtEndOfBasicBlock(MachineInstr *MI,
730                                                      MachineBasicBlock *MBB);
731
732   //===--------------------------------------------------------------------===//
733   // Loop Strength Reduction hooks
734   //
735   
736   /// isLegalAddressImmediate - Return true if the integer value or GlobalValue
737   /// can be used as the offset of the target addressing mode.
738   virtual bool isLegalAddressImmediate(int64_t V) const;
739   virtual bool isLegalAddressImmediate(GlobalValue *GV) const;
740
741   typedef std::vector<unsigned>::const_iterator legal_am_scale_iterator;
742   legal_am_scale_iterator legal_am_scale_begin() const {
743     return LegalAddressScales.begin();
744   }
745   legal_am_scale_iterator legal_am_scale_end() const {
746     return LegalAddressScales.end();
747   }
748
749   //===--------------------------------------------------------------------===//
750   // Div utility functions
751   //
752   SDOperand BuildSDIV(SDNode *N, SelectionDAG &DAG, 
753                       std::vector<SDNode*>* Created) const;
754   SDOperand BuildUDIV(SDNode *N, SelectionDAG &DAG, 
755                       std::vector<SDNode*>* Created) const;
756
757
758 protected:
759   /// addLegalAddressScale - Add a integer (> 1) value which can be used as
760   /// scale in the target addressing mode. Note: the ordering matters so the
761   /// least efficient ones should be entered first.
762   void addLegalAddressScale(unsigned Scale) {
763     LegalAddressScales.push_back(Scale);
764   }
765
766 private:
767   std::vector<unsigned> LegalAddressScales;
768   
769   TargetMachine &TM;
770   const TargetData *TD;
771
772   /// IsLittleEndian - True if this is a little endian target.
773   ///
774   bool IsLittleEndian;
775
776   /// PointerTy - The type to use for pointers, usually i32 or i64.
777   ///
778   MVT::ValueType PointerTy;
779
780   /// UsesGlobalOffsetTable - True if this target uses a GOT for PIC codegen.
781   ///
782   bool UsesGlobalOffsetTable;
783   
784   /// ShiftAmountTy - The type to use for shift amounts, usually i8 or whatever
785   /// PointerTy is.
786   MVT::ValueType ShiftAmountTy;
787
788   OutOfRangeShiftAmount ShiftAmtHandling;
789
790   /// SetCCIsExpensive - This is a short term hack for targets that codegen
791   /// setcc as a conditional branch.  This encourages the code generator to fold
792   /// setcc operations into other operations if possible.
793   bool SetCCIsExpensive;
794
795   /// IntDivIsCheap - Tells the code generator not to expand integer divides by
796   /// constants into a sequence of muls, adds, and shifts.  This is a hack until
797   /// a real cost model is in place.  If we ever optimize for size, this will be
798   /// set to true unconditionally.
799   bool IntDivIsCheap;
800   
801   /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
802   /// srl/add/sra for a signed divide by power of two, and let the target handle
803   /// it.
804   bool Pow2DivIsCheap;
805   
806   /// SetCCResultTy - The type that SetCC operations use.  This defaults to the
807   /// PointerTy.
808   MVT::ValueType SetCCResultTy;
809
810   /// SetCCResultContents - Information about the contents of the high-bits in
811   /// the result of a setcc comparison operation.
812   SetCCResultValue SetCCResultContents;
813
814   /// SchedPreferenceInfo - The target scheduling preference: shortest possible
815   /// total cycles or lowest register usage.
816   SchedPreference SchedPreferenceInfo;
817   
818   /// UseUnderscoreSetJmpLongJmp - This target prefers to use _setjmp and
819   /// _longjmp to implement llvm.setjmp/llvm.longjmp.  Defaults to false.
820   bool UseUnderscoreSetJmpLongJmp;
821   
822   /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
823   unsigned JumpBufSize;
824   
825   /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
826   /// buffers
827   unsigned JumpBufAlignment;
828   
829   /// StackPointerRegisterToSaveRestore - If set to a physical register, this
830   /// specifies the register that llvm.savestack/llvm.restorestack should save
831   /// and restore.
832   unsigned StackPointerRegisterToSaveRestore;
833
834   /// RegClassForVT - This indicates the default register class to use for
835   /// each ValueType the target supports natively.
836   TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
837   unsigned char NumElementsForVT[MVT::LAST_VALUETYPE];
838
839   /// TransformToType - For any value types we are promoting or expanding, this
840   /// contains the value type that we are changing to.  For Expanded types, this
841   /// contains one step of the expand (e.g. i64 -> i32), even if there are
842   /// multiple steps required (e.g. i64 -> i16).  For types natively supported
843   /// by the system, this holds the same type (e.g. i32 -> i32).
844   MVT::ValueType TransformToType[MVT::LAST_VALUETYPE];
845
846   /// OpActions - For each operation and each value type, keep a LegalizeAction
847   /// that indicates how instruction selection should deal with the operation.
848   /// Most operations are Legal (aka, supported natively by the target), but
849   /// operations that are not should be described.  Note that operations on
850   /// non-legal value types are not described here.
851   uint64_t OpActions[156];
852   
853   /// LoadXActions - For each load of load extension type and each value type,
854   /// keep a LegalizeAction that indicates how instruction selection should deal
855   /// with the load.
856   uint64_t LoadXActions[ISD::LAST_LOADX_TYPE];
857   
858   /// StoreXActions - For each store with truncation of each value type, keep a
859   /// LegalizeAction that indicates how instruction selection should deal with
860   /// the store.
861   uint64_t StoreXActions;
862   
863   ValueTypeActionImpl ValueTypeActions;
864
865   std::vector<double> LegalFPImmediates;
866
867   std::vector<std::pair<MVT::ValueType,
868                         TargetRegisterClass*> > AvailableRegClasses;
869
870   /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
871   /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
872   /// which sets a bit in this array.
873   unsigned char TargetDAGCombineArray[156/(sizeof(unsigned char)*8)];
874   
875   /// PromoteToType - For operations that must be promoted to a specific type,
876   /// this holds the destination type.  This map should be sparse, so don't hold
877   /// it as an array.
878   ///
879   /// Targets add entries to this map with AddPromotedToType(..), clients access
880   /// this with getTypeToPromoteTo(..).
881   std::map<std::pair<unsigned, MVT::ValueType>, MVT::ValueType> PromoteToType;
882   
883 protected:
884   /// When lowering %llvm.memset this field specifies the maximum number of
885   /// store operations that may be substituted for the call to memset. Targets
886   /// must set this value based on the cost threshold for that target. Targets
887   /// should assume that the memset will be done using as many of the largest
888   /// store operations first, followed by smaller ones, if necessary, per
889   /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
890   /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
891   /// store.  This only applies to setting a constant array of a constant size.
892   /// @brief Specify maximum number of store instructions per memset call.
893   unsigned maxStoresPerMemset;
894
895   /// When lowering %llvm.memcpy this field specifies the maximum number of
896   /// store operations that may be substituted for a call to memcpy. Targets
897   /// must set this value based on the cost threshold for that target. Targets
898   /// should assume that the memcpy will be done using as many of the largest
899   /// store operations first, followed by smaller ones, if necessary, per
900   /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
901   /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
902   /// and one 1-byte store. This only applies to copying a constant array of
903   /// constant size.
904   /// @brief Specify maximum bytes of store instructions per memcpy call.
905   unsigned maxStoresPerMemcpy;
906
907   /// When lowering %llvm.memmove this field specifies the maximum number of
908   /// store instructions that may be substituted for a call to memmove. Targets
909   /// must set this value based on the cost threshold for that target. Targets
910   /// should assume that the memmove will be done using as many of the largest
911   /// store operations first, followed by smaller ones, if necessary, per
912   /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
913   /// with 8-bit alignment would result in nine 1-byte stores.  This only
914   /// applies to copying a constant array of constant size.
915   /// @brief Specify maximum bytes of store instructions per memmove call.
916   unsigned maxStoresPerMemmove;
917
918   /// This field specifies whether the target machine permits unaligned memory
919   /// accesses.  This is used, for example, to determine the size of store 
920   /// operations when copying small arrays and other similar tasks.
921   /// @brief Indicate whether the target permits unaligned memory accesses.
922   bool allowUnalignedMemoryAccesses;
923 };
924 } // end llvm namespace
925
926 #endif