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