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