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