Add a hook
[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/ValueTypes.h"
27 #include <vector>
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
39 //===----------------------------------------------------------------------===//
40 /// TargetLowering - This class defines information used to lower LLVM code to
41 /// legal SelectionDAG operators that the target instruction selector can accept
42 /// natively.
43 ///
44 /// This class also defines callbacks that targets must implement to lower
45 /// target-specific constructs to SelectionDAG operators.
46 ///
47 class TargetLowering {
48 public:
49   /// LegalizeAction - This enum indicates whether operations are valid for a
50   /// target, and if not, what action should be used to make them valid.
51   enum LegalizeAction {
52     Legal,      // The target natively supports this operation.
53     Promote,    // This operation should be executed in a larger type.
54     Expand,     // Try to expand this to other ops, otherwise use a libcall.
55     Custom,     // Use the LowerOperation hook to implement custom lowering.
56   };
57
58   enum OutOfRangeShiftAmount {
59     Undefined,  // Oversized shift amounts are undefined (default).
60     Mask,       // Shift amounts are auto masked (anded) to value size.
61     Extend,     // Oversized shift pulls in zeros or sign bits.
62   };
63
64   enum SetCCResultValue {
65     UndefinedSetCCResult,          // SetCC returns a garbage/unknown extend.
66     ZeroOrOneSetCCResult,          // SetCC returns a zero extended result.
67     ZeroOrNegativeOneSetCCResult,  // SetCC returns a sign extended result.
68   };
69
70   TargetLowering(TargetMachine &TM);
71   virtual ~TargetLowering();
72
73   TargetMachine &getTargetMachine() const { return TM; }
74   const TargetData &getTargetData() const { return TD; }
75
76   bool isLittleEndian() const { return IsLittleEndian; }
77   MVT::ValueType getPointerTy() const { return PointerTy; }
78   MVT::ValueType getShiftAmountTy() const { return ShiftAmountTy; }
79   OutOfRangeShiftAmount getShiftAmountFlavor() const {return ShiftAmtHandling; }
80
81   /// isSetCCExpensive - Return true if the setcc operation is expensive for
82   /// this target.
83   bool isSetCCExpensive() const { return SetCCIsExpensive; }
84
85   /// getSetCCResultTy - Return the ValueType of the result of setcc operations.
86   ///
87   MVT::ValueType getSetCCResultTy() const { return SetCCResultTy; }
88
89   /// getSetCCResultContents - For targets without boolean registers, this flag
90   /// returns information about the contents of the high-bits in the setcc
91   /// result register.
92   SetCCResultValue getSetCCResultContents() const { return SetCCResultContents;}
93
94   /// getRegClassFor - Return the register class that should be used for the
95   /// specified value type.  This may only be called on legal types.
96   TargetRegisterClass *getRegClassFor(MVT::ValueType VT) const {
97     TargetRegisterClass *RC = RegClassForVT[VT];
98     assert(RC && "This value type is not natively supported!");
99     return RC;
100   }
101
102   /// isTypeLegal - Return true if the target has native support for the
103   /// specified value type.  This means that it has a register that directly
104   /// holds it without promotions or expansions.
105   bool isTypeLegal(MVT::ValueType VT) const {
106     return RegClassForVT[VT] != 0;
107   }
108
109   /// getTypeAction - Return how we should legalize values of this type, either
110   /// it is already legal (return 'Legal') or we need to promote it to a larger
111   /// type (return 'Promote'), or we need to expand it into multiple registers
112   /// of smaller integer type (return 'Expand').  'Custom' is not an option.
113   LegalizeAction getTypeAction(MVT::ValueType VT) const {
114     return (LegalizeAction)((ValueTypeActions >> (2*VT)) & 3);
115   }
116   unsigned getValueTypeActions() const { return ValueTypeActions; }
117
118   /// getTypeToTransformTo - For types supported by the target, this is an
119   /// identity function.  For types that must be promoted to larger types, this
120   /// returns the larger type to promote to.  For types that are larger than the
121   /// largest integer register, this contains one step in the expansion to get
122   /// to the smaller register.
123   MVT::ValueType getTypeToTransformTo(MVT::ValueType VT) const {
124     return TransformToType[VT];
125   }
126
127   typedef std::vector<double>::const_iterator legal_fpimm_iterator;
128   legal_fpimm_iterator legal_fpimm_begin() const {
129     return LegalFPImmediates.begin();
130   }
131   legal_fpimm_iterator legal_fpimm_end() const {
132     return LegalFPImmediates.end();
133   }
134
135   /// getOperationAction - Return how this operation should be treated: either
136   /// it is legal, needs to be promoted to a larger size, needs to be
137   /// expanded to some other code sequence, or the target has a custom expander
138   /// for it.
139   LegalizeAction getOperationAction(unsigned Op, MVT::ValueType VT) const {
140     return (LegalizeAction)((OpActions[Op] >> (2*VT)) & 3);
141   }
142   
143   /// isOperationLegal - Return true if the specified operation is legal on this
144   /// target.
145   bool isOperationLegal(unsigned Op, MVT::ValueType VT) const {
146     return getOperationAction(Op, VT) == Legal;
147   }
148
149   /// getTypeToPromoteTo - If the action for this operation is to promote, this
150   /// method returns the ValueType to promote to.
151   MVT::ValueType getTypeToPromoteTo(unsigned Op, MVT::ValueType VT) const {
152     assert(getOperationAction(Op, VT) == Promote &&
153            "This operation isn't promoted!");
154     MVT::ValueType NVT = VT;
155     do {
156       NVT = (MVT::ValueType)(NVT+1);
157       assert(MVT::isInteger(NVT) == MVT::isInteger(VT) && NVT != MVT::isVoid &&
158              "Didn't find type to promote to!");
159     } while (!isTypeLegal(NVT) ||
160               getOperationAction(Op, NVT) == Promote);
161     return NVT;
162   }
163
164   /// getValueType - Return the MVT::ValueType corresponding to this LLVM type.
165   /// This is fixed by the LLVM operations except for the pointer size.
166   MVT::ValueType getValueType(const Type *Ty) const {
167     switch (Ty->getTypeID()) {
168     default: assert(0 && "Unknown type!");
169     case Type::VoidTyID:    return MVT::isVoid;
170     case Type::BoolTyID:    return MVT::i1;
171     case Type::UByteTyID:
172     case Type::SByteTyID:   return MVT::i8;
173     case Type::ShortTyID:
174     case Type::UShortTyID:  return MVT::i16;
175     case Type::IntTyID:
176     case Type::UIntTyID:    return MVT::i32;
177     case Type::LongTyID:
178     case Type::ULongTyID:   return MVT::i64;
179     case Type::FloatTyID:   return MVT::f32;
180     case Type::DoubleTyID:  return MVT::f64;
181     case Type::PointerTyID: return PointerTy;
182     }
183   }
184
185   /// getNumElements - Return the number of registers that this ValueType will
186   /// eventually require.  This is always one for all non-integer types, is
187   /// one for any types promoted to live in larger registers, but may be more
188   /// than one for types (like i64) that are split into pieces.
189   unsigned getNumElements(MVT::ValueType VT) const {
190     return NumElementsForVT[VT];
191   }
192
193   /// This function returns the maximum number of store operations permitted
194   /// to replace a call to llvm.memset. The value is set by the target at the
195   /// performance threshold for such a replacement.
196   /// @brief Get maximum # of store operations permitted for llvm.memset
197   unsigned getMaxStoresPerMemSet() const { return maxStoresPerMemSet; }
198
199   /// This function returns the maximum number of store operations permitted
200   /// to replace a call to llvm.memcpy. The value is set by the target at the
201   /// performance threshold for such a replacement.
202   /// @brief Get maximum # of store operations permitted for llvm.memcpy
203   unsigned getMaxStoresPerMemCpy() const { return maxStoresPerMemCpy; }
204
205   /// This function returns the maximum number of store operations permitted
206   /// to replace a call to llvm.memmove. The value is set by the target at the
207   /// performance threshold for such a replacement.
208   /// @brief Get maximum # of store operations permitted for llvm.memmove
209   unsigned getMaxStoresPerMemMove() const { return maxStoresPerMemMove; }
210
211   /// This function returns true if the target allows unaligned stores. This is
212   /// used in situations where an array copy/move/set is converted to a sequence
213   /// of store operations. It ensures that such replacements don't generate
214   /// code that causes an alignment error (trap) on the target machine.
215   /// @brief Determine if the target supports unaligned stores.
216   bool allowsUnalignedStores() const { return allowUnalignedStores; }
217
218   //===--------------------------------------------------------------------===//
219   // TargetLowering Configuration Methods - These methods should be invoked by
220   // the derived class constructor to configure this object for the target.
221   //
222
223 protected:
224
225   /// setShiftAmountType - Describe the type that should be used for shift
226   /// amounts.  This type defaults to the pointer type.
227   void setShiftAmountType(MVT::ValueType VT) { ShiftAmountTy = VT; }
228
229   /// setSetCCResultType - Describe the type that shoudl be used as the result
230   /// of a setcc operation.  This defaults to the pointer type.
231   void setSetCCResultType(MVT::ValueType VT) { SetCCResultTy = VT; }
232
233   /// setSetCCResultContents - Specify how the target extends the result of a
234   /// setcc operation in a register.
235   void setSetCCResultContents(SetCCResultValue Ty) { SetCCResultContents = Ty; }
236
237   /// setShiftAmountFlavor - Describe how the target handles out of range shift
238   /// amounts.
239   void setShiftAmountFlavor(OutOfRangeShiftAmount OORSA) {
240     ShiftAmtHandling = OORSA;
241   }
242
243   /// setSetCCIxExpensive - This is a short term hack for targets that codegen
244   /// setcc as a conditional branch.  This encourages the code generator to fold
245   /// setcc operations into other operations if possible.
246   void setSetCCIsExpensive() { SetCCIsExpensive = true; }
247
248   /// addRegisterClass - Add the specified register class as an available
249   /// regclass for the specified value type.  This indicates the selector can
250   /// handle values of that class natively.
251   void addRegisterClass(MVT::ValueType VT, TargetRegisterClass *RC) {
252     AvailableRegClasses.push_back(std::make_pair(VT, RC));
253     RegClassForVT[VT] = RC;
254   }
255
256   /// computeRegisterProperties - Once all of the register classes are added,
257   /// this allows us to compute derived properties we expose.
258   void computeRegisterProperties();
259
260   /// setOperationAction - Indicate that the specified operation does not work
261   /// with the specified type and indicate what to do about it.
262   void setOperationAction(unsigned Op, MVT::ValueType VT,
263                           LegalizeAction Action) {
264     assert(VT < 16 && Op < sizeof(OpActions)/sizeof(OpActions[0]) &&
265            "Table isn't big enough!");
266     OpActions[Op] |= Action << VT*2;
267   }
268
269   /// addLegalFPImmediate - Indicate that this target can instruction select
270   /// the specified FP immediate natively.
271   void addLegalFPImmediate(double Imm) {
272     LegalFPImmediates.push_back(Imm);
273   }
274
275 public:
276
277   //===--------------------------------------------------------------------===//
278   // Lowering methods - These methods must be implemented by targets so that
279   // the SelectionDAGLowering code knows how to lower these.
280   //
281
282   /// LowerArguments - This hook must be implemented to indicate how we should
283   /// lower the arguments for the specified function, into the specified DAG.
284   virtual std::vector<SDOperand>
285   LowerArguments(Function &F, SelectionDAG &DAG) = 0;
286
287   /// LowerCallTo - This hook lowers an abstract call to a function into an
288   /// actual call.  This returns a pair of operands.  The first element is the
289   /// return value for the function (if RetTy is not VoidTy).  The second
290   /// element is the outgoing token chain.
291   typedef std::vector<std::pair<SDOperand, const Type*> > ArgListTy;
292   virtual std::pair<SDOperand, SDOperand>
293   LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
294               unsigned CallingConv, bool isTailCall, SDOperand Callee,
295               ArgListTy &Args, SelectionDAG &DAG) = 0;
296
297   /// LowerVAStart - This lowers the llvm.va_start intrinsic.  If not
298   /// implemented, this method prints a message and aborts.  This method should
299   /// return the modified chain value.  Note that VAListPtr* correspond to the
300   /// llvm.va_start operand.
301   virtual SDOperand LowerVAStart(SDOperand Chain, SDOperand VAListP,
302                                  Value *VAListV, SelectionDAG &DAG);
303
304   /// LowerVAEnd - This lowers llvm.va_end and returns the resultant chain.  If
305   /// not implemented, this defaults to a noop.
306   virtual SDOperand LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
307                                SelectionDAG &DAG);
308
309   /// LowerVACopy - This lowers llvm.va_copy and returns the resultant chain.
310   /// If not implemented, this defaults to loading a pointer from the input and
311   /// storing it to the output.
312   virtual SDOperand LowerVACopy(SDOperand Chain, SDOperand SrcP, Value *SrcV,
313                                 SDOperand DestP, Value *DestV,
314                                 SelectionDAG &DAG);
315
316   /// LowerVAArg - This lowers the vaarg instruction.  If not implemented, this
317   /// prints a message and aborts.
318   virtual std::pair<SDOperand,SDOperand>
319   LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
320              const Type *ArgTy, SelectionDAG &DAG);
321
322   /// LowerFrameReturnAddress - This hook lowers a call to llvm.returnaddress or
323   /// llvm.frameaddress (depending on the value of the first argument).  The
324   /// return values are the result pointer and the resultant token chain.  If
325   /// not implemented, both of these intrinsics will return null.
326   virtual std::pair<SDOperand, SDOperand>
327   LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
328                           SelectionDAG &DAG);
329
330   /// LowerOperation - For operations that are unsupported by the target, and
331   /// which are registered to use 'custom' lowering.  This callback is invoked.
332   /// If the target has no operations that require custom lowering, it need not
333   /// implement this.  The default implementation of this aborts.
334   virtual SDOperand LowerOperation(SDOperand Op, SelectionDAG &DAG);
335
336   //===--------------------------------------------------------------------===//
337   // Scheduler hooks
338   //
339   
340   // InsertAtEndOfBasicBlock - This method should be implemented by targets that
341   // mark instructions with the 'usesCustomDAGSChedInserter' flag.  These
342   // instructions are special in various ways, which require special support to
343   // insert.  The specified MachineInstr is created but not inserted into any
344   // basic blocks, and the scheduler passes ownership of it to this method.
345   virtual MachineBasicBlock *InsertAtEndOfBasicBlock(MachineInstr *MI,
346                                                      MachineBasicBlock *MBB);
347
348 private:
349   TargetMachine &TM;
350   const TargetData &TD;
351
352   /// IsLittleEndian - True if this is a little endian target.
353   ///
354   bool IsLittleEndian;
355
356   /// PointerTy - The type to use for pointers, usually i32 or i64.
357   ///
358   MVT::ValueType PointerTy;
359
360   /// ShiftAmountTy - The type to use for shift amounts, usually i8 or whatever
361   /// PointerTy is.
362   MVT::ValueType ShiftAmountTy;
363
364   OutOfRangeShiftAmount ShiftAmtHandling;
365
366   /// SetCCIsExpensive - This is a short term hack for targets that codegen
367   /// setcc as a conditional branch.  This encourages the code generator to fold
368   /// setcc operations into other operations if possible.
369   bool SetCCIsExpensive;
370
371   /// SetCCResultTy - The type that SetCC operations use.  This defaults to the
372   /// PointerTy.
373   MVT::ValueType SetCCResultTy;
374
375   /// SetCCResultContents - Information about the contents of the high-bits in
376   /// the result of a setcc comparison operation.
377   SetCCResultValue SetCCResultContents;
378
379   /// RegClassForVT - This indicates the default register class to use for
380   /// each ValueType the target supports natively.
381   TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
382   unsigned char NumElementsForVT[MVT::LAST_VALUETYPE];
383
384   /// ValueTypeActions - This is a bitvector that contains two bits for each
385   /// value type, where the two bits correspond to the LegalizeAction enum.
386   /// This can be queried with "getTypeAction(VT)".
387   unsigned ValueTypeActions;
388
389   /// TransformToType - For any value types we are promoting or expanding, this
390   /// contains the value type that we are changing to.  For Expanded types, this
391   /// contains one step of the expand (e.g. i64 -> i32), even if there are
392   /// multiple steps required (e.g. i64 -> i16).  For types natively supported
393   /// by the system, this holds the same type (e.g. i32 -> i32).
394   MVT::ValueType TransformToType[MVT::LAST_VALUETYPE];
395
396   /// OpActions - For each operation and each value type, keep a LegalizeAction
397   /// that indicates how instruction selection should deal with the operation.
398   /// Most operations are Legal (aka, supported natively by the target), but
399   /// operations that are not should be described.  Note that operations on
400   /// non-legal value types are not described here.
401   unsigned OpActions[128];
402
403   std::vector<double> LegalFPImmediates;
404
405   std::vector<std::pair<MVT::ValueType,
406                         TargetRegisterClass*> > AvailableRegClasses;
407
408 protected:
409   /// When lowering %llvm.memset this field specifies the maximum number of
410   /// store operations that may be substituted for the call to memset. Targets
411   /// must set this value based on the cost threshold for that target. Targets
412   /// should assume that the memset will be done using as many of the largest
413   /// store operations first, followed by smaller ones, if necessary, per
414   /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
415   /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
416   /// store.  This only applies to setting a constant array of a constant size.
417   /// @brief Specify maximum number of store instructions per memset call.
418   unsigned maxStoresPerMemSet;
419
420   /// When lowering %llvm.memcpy this field specifies the maximum number of
421   /// store operations that may be substituted for a call to memcpy. Targets
422   /// must set this value based on the cost threshold for that target. Targets
423   /// should assume that the memcpy will be done using as many of the largest
424   /// store operations first, followed by smaller ones, if necessary, per
425   /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
426   /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
427   /// and one 1-byte store. This only applies to copying a constant array of
428   /// constant size.
429   /// @brief Specify maximum bytes of store instructions per memcpy call.
430   unsigned maxStoresPerMemCpy;
431
432   /// When lowering %llvm.memmove this field specifies the maximum number of
433   /// store instructions that may be substituted for a call to memmove. Targets
434   /// must set this value based on the cost threshold for that target. Targets
435   /// should assume that the memmove will be done using as many of the largest
436   /// store operations first, followed by smaller ones, if necessary, per
437   /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
438   /// with 8-bit alignment would result in nine 1-byte stores.  This only
439   /// applies to copying a constant array of constant size.
440   /// @brief Specify maximum bytes of store instructions per memmove call.
441   unsigned maxStoresPerMemMove;
442
443   /// This field specifies whether the target machine permits unaligned stores.
444   /// This is used to determine the size of store operations for copying
445   /// small arrays and other similar tasks.
446   /// @brief Indicate whether the target machine permits unaligned stores.
447   bool allowUnalignedStores;
448 };
449 } // end llvm namespace
450
451 #endif