TargetLowering.h revision aec038fa8418d21755e22ff749969bddd4428da9
1//===-- llvm/Target/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// 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/CallingConv.h"
26#include "llvm/InlineAsm.h"
27#include "llvm/Attributes.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/CodeGen/SelectionDAGNodes.h"
30#include "llvm/CodeGen/RuntimeLibcalls.h"
31#include "llvm/Support/DebugLoc.h"
32#include "llvm/Target/TargetCallingConv.h"
33#include "llvm/Target/TargetMachine.h"
34#include <climits>
35#include <map>
36#include <vector>
37
38namespace llvm {
39  class AllocaInst;
40  class APFloat;
41  class CallInst;
42  class CCState;
43  class Function;
44  class FastISel;
45  class FunctionLoweringInfo;
46  class ImmutableCallSite;
47  class MachineBasicBlock;
48  class MachineFunction;
49  class MachineFrameInfo;
50  class MachineInstr;
51  class MachineJumpTableInfo;
52  class MCContext;
53  class MCExpr;
54  class SDNode;
55  class SDValue;
56  class SelectionDAG;
57  template<typename T> class SmallVectorImpl;
58  class TargetData;
59  class TargetMachine;
60  class TargetRegisterClass;
61  class TargetLoweringObjectFile;
62  class Value;
63
64  // FIXME: should this be here?
65  namespace TLSModel {
66    enum Model {
67      GeneralDynamic,
68      LocalDynamic,
69      InitialExec,
70      LocalExec
71    };
72  }
73  TLSModel::Model getTLSModel(const GlobalValue *GV, Reloc::Model reloc);
74
75
76//===----------------------------------------------------------------------===//
77/// TargetLowering - This class defines information used to lower LLVM code to
78/// legal SelectionDAG operators that the target instruction selector can accept
79/// natively.
80///
81/// This class also defines callbacks that targets must implement to lower
82/// target-specific constructs to SelectionDAG operators.
83///
84class TargetLowering {
85  TargetLowering(const TargetLowering&);  // DO NOT IMPLEMENT
86  void operator=(const TargetLowering&);  // DO NOT IMPLEMENT
87public:
88  /// LegalizeAction - This enum indicates whether operations are valid for a
89  /// target, and if not, what action should be used to make them valid.
90  enum LegalizeAction {
91    Legal,      // The target natively supports this operation.
92    Promote,    // This operation should be executed in a larger type.
93    Expand,     // Try to expand this to other ops, otherwise use a libcall.
94    Custom      // Use the LowerOperation hook to implement custom lowering.
95  };
96
97  enum BooleanContent { // How the target represents true/false values.
98    UndefinedBooleanContent,    // Only bit 0 counts, the rest can hold garbage.
99    ZeroOrOneBooleanContent,        // All bits zero except for bit 0.
100    ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
101  };
102
103  /// NOTE: The constructor takes ownership of TLOF.
104  explicit TargetLowering(const TargetMachine &TM,
105                          const TargetLoweringObjectFile *TLOF);
106  virtual ~TargetLowering();
107
108  const TargetMachine &getTargetMachine() const { return TM; }
109  const TargetData *getTargetData() const { return TD; }
110  const TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; }
111
112  bool isBigEndian() const { return !IsLittleEndian; }
113  bool isLittleEndian() const { return IsLittleEndian; }
114  MVT getPointerTy() const { return PointerTy; }
115  virtual MVT getShiftAmountTy(EVT LHSTy) const;
116
117  /// isSelectExpensive - Return true if the select operation is expensive for
118  /// this target.
119  bool isSelectExpensive() const { return SelectIsExpensive; }
120
121  /// isIntDivCheap() - Return true if integer divide is usually cheaper than
122  /// a sequence of several shifts, adds, and multiplies for this target.
123  bool isIntDivCheap() const { return IntDivIsCheap; }
124
125  /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
126  /// srl/add/sra.
127  bool isPow2DivCheap() const { return Pow2DivIsCheap; }
128
129  /// isJumpExpensive() - Return true if Flow Control is an expensive operation
130  /// that should be avoided.
131  bool isJumpExpensive() const { return JumpIsExpensive; }
132
133  /// getSetCCResultType - Return the ValueType of the result of SETCC
134  /// operations.  Also used to obtain the target's preferred type for
135  /// the condition operand of SELECT and BRCOND nodes.  In the case of
136  /// BRCOND the argument passed is MVT::Other since there are no other
137  /// operands to get a type hint from.
138  virtual
139  MVT::SimpleValueType getSetCCResultType(EVT VT) const;
140
141  /// getCmpLibcallReturnType - Return the ValueType for comparison
142  /// libcalls. Comparions libcalls include floating point comparion calls,
143  /// and Ordered/Unordered check calls on floating point numbers.
144  virtual
145  MVT::SimpleValueType getCmpLibcallReturnType() const;
146
147  /// getBooleanContents - For targets without i1 registers, this gives the
148  /// nature of the high-bits of boolean values held in types wider than i1.
149  /// "Boolean values" are special true/false values produced by nodes like
150  /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
151  /// Not to be confused with general values promoted from i1.
152  BooleanContent getBooleanContents() const { return BooleanContents;}
153
154  /// getSchedulingPreference - Return target scheduling preference.
155  Sched::Preference getSchedulingPreference() const {
156    return SchedPreferenceInfo;
157  }
158
159  /// getSchedulingPreference - Some scheduler, e.g. hybrid, can switch to
160  /// different scheduling heuristics for different nodes. This function returns
161  /// the preference (or none) for the given node.
162  virtual Sched::Preference getSchedulingPreference(SDNode *N) const {
163    return Sched::None;
164  }
165
166  /// getRegClassFor - Return the register class that should be used for the
167  /// specified value type.
168  virtual TargetRegisterClass *getRegClassFor(EVT VT) const {
169    assert(VT.isSimple() && "getRegClassFor called on illegal type!");
170    TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT().SimpleTy];
171    assert(RC && "This value type is not natively supported!");
172    return RC;
173  }
174
175  /// getRepRegClassFor - Return the 'representative' register class for the
176  /// specified value type. The 'representative' register class is the largest
177  /// legal super-reg register class for the register class of the value type.
178  /// For example, on i386 the rep register class for i8, i16, and i32 are GR32;
179  /// while the rep register class is GR64 on x86_64.
180  virtual const TargetRegisterClass *getRepRegClassFor(EVT VT) const {
181    assert(VT.isSimple() && "getRepRegClassFor called on illegal type!");
182    const TargetRegisterClass *RC = RepRegClassForVT[VT.getSimpleVT().SimpleTy];
183    return RC;
184  }
185
186  /// getRepRegClassCostFor - Return the cost of the 'representative' register
187  /// class for the specified value type.
188  virtual uint8_t getRepRegClassCostFor(EVT VT) const {
189    assert(VT.isSimple() && "getRepRegClassCostFor called on illegal type!");
190    return RepRegClassCostForVT[VT.getSimpleVT().SimpleTy];
191  }
192
193  /// isTypeLegal - Return true if the target has native support for the
194  /// specified value type.  This means that it has a register that directly
195  /// holds it without promotions or expansions.
196  bool isTypeLegal(EVT VT) const {
197    assert(!VT.isSimple() ||
198           (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
199    return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != 0;
200  }
201
202  class ValueTypeActionImpl {
203    /// ValueTypeActions - For each value type, keep a LegalizeAction enum
204    /// that indicates how instruction selection should deal with the type.
205    uint8_t ValueTypeActions[MVT::LAST_VALUETYPE];
206
207    LegalizeAction getExtendedTypeAction(EVT VT) const {
208      // Handle non-vector integers.
209      if (!VT.isVector()) {
210        assert(VT.isInteger() && "Unsupported extended type!");
211        unsigned BitSize = VT.getSizeInBits();
212        // First promote to a power-of-two size, then expand if necessary.
213        if (BitSize < 8 || !isPowerOf2_32(BitSize))
214          return Promote;
215        return Expand;
216      }
217
218      // Vectors with only one element are always scalarized.
219      if (VT.getVectorNumElements() == 1)
220        return Expand;
221
222      // Vectors with a number of elements that is not a power of two are always
223      // widened, for example <3 x float> -> <4 x float>.
224      if (!VT.isPow2VectorType())
225        return Promote;
226
227      // Vectors with a crazy element type are always expanded, for example
228      // <4 x i2> is expanded into two vectors of type <2 x i2>.
229      if (!VT.getVectorElementType().isSimple())
230        return Expand;
231
232      // If this type is smaller than a legal vector type then widen it,
233      // otherwise expand it.  E.g. <2 x float> -> <4 x float>.
234      MVT EltType = VT.getVectorElementType().getSimpleVT();
235      unsigned NumElts = VT.getVectorNumElements();
236      while (1) {
237        // Round up to the next power of 2.
238        NumElts = (unsigned)NextPowerOf2(NumElts);
239
240        // If there is no simple vector type with this many elements then there
241        // cannot be a larger legal vector type.  Note that this assumes that
242        // there are no skipped intermediate vector types in the simple types.
243        MVT LargerVector = MVT::getVectorVT(EltType, NumElts);
244        if (LargerVector == MVT())
245          return Expand;
246
247        // If this type is legal then widen the vector.
248        if (getTypeAction(LargerVector) == Legal)
249          return Promote;
250      }
251    }
252  public:
253    ValueTypeActionImpl() {
254      std::fill(ValueTypeActions, array_endof(ValueTypeActions), 0);
255    }
256
257    LegalizeAction getTypeAction(EVT VT) const {
258      if (!VT.isExtended())
259        return getTypeAction(VT.getSimpleVT());
260      return getExtendedTypeAction(VT);
261    }
262
263    LegalizeAction getTypeAction(MVT VT) const {
264      return (LegalizeAction)ValueTypeActions[VT.SimpleTy];
265    }
266
267    void setTypeAction(EVT VT, LegalizeAction Action) {
268      unsigned I = VT.getSimpleVT().SimpleTy;
269      ValueTypeActions[I] = Action;
270    }
271  };
272
273  const ValueTypeActionImpl &getValueTypeActions() const {
274    return ValueTypeActions;
275  }
276
277  /// getTypeAction - Return how we should legalize values of this type, either
278  /// it is already legal (return 'Legal') or we need to promote it to a larger
279  /// type (return 'Promote'), or we need to expand it into multiple registers
280  /// of smaller integer type (return 'Expand').  'Custom' is not an option.
281  LegalizeAction getTypeAction(EVT VT) const {
282    return ValueTypeActions.getTypeAction(VT);
283  }
284  LegalizeAction getTypeAction(MVT VT) const {
285    return ValueTypeActions.getTypeAction(VT);
286  }
287
288  /// getTypeToTransformTo - For types supported by the target, this is an
289  /// identity function.  For types that must be promoted to larger types, this
290  /// returns the larger type to promote to.  For integer types that are larger
291  /// than the largest integer register, this contains one step in the expansion
292  /// to get to the smaller register. For illegal floating point types, this
293  /// returns the integer type to transform to.
294  EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
295    if (VT.isSimple()) {
296      assert((unsigned)VT.getSimpleVT().SimpleTy <
297             array_lengthof(TransformToType));
298      EVT NVT = TransformToType[VT.getSimpleVT().SimpleTy];
299      assert(getTypeAction(NVT) != Promote &&
300             "Promote may not follow Expand or Promote");
301      return NVT;
302    }
303
304    if (VT.isVector()) {
305      EVT NVT = VT.getPow2VectorType(Context);
306      if (NVT == VT) {
307        // Vector length is a power of 2 - split to half the size.
308        unsigned NumElts = VT.getVectorNumElements();
309        EVT EltVT = VT.getVectorElementType();
310        return (NumElts == 1) ?
311          EltVT : EVT::getVectorVT(Context, EltVT, NumElts / 2);
312      }
313      // Promote to a power of two size, avoiding multi-step promotion.
314      return getTypeAction(NVT) == Promote ?
315        getTypeToTransformTo(Context, NVT) : NVT;
316    } else if (VT.isInteger()) {
317      EVT NVT = VT.getRoundIntegerType(Context);
318      if (NVT == VT)      // Size is a power of two - expand to half the size.
319        return EVT::getIntegerVT(Context, VT.getSizeInBits() / 2);
320
321      // Promote to a power of two size, avoiding multi-step promotion.
322      return getTypeAction(NVT) == Promote ?
323        getTypeToTransformTo(Context, NVT) : NVT;
324    }
325    assert(0 && "Unsupported extended type!");
326    return MVT(MVT::Other); // Not reached
327  }
328
329  /// getTypeToExpandTo - For types supported by the target, this is an
330  /// identity function.  For types that must be expanded (i.e. integer types
331  /// that are larger than the largest integer register or illegal floating
332  /// point types), this returns the largest legal type it will be expanded to.
333  EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
334    assert(!VT.isVector());
335    while (true) {
336      switch (getTypeAction(VT)) {
337      case Legal:
338        return VT;
339      case Expand:
340        VT = getTypeToTransformTo(Context, VT);
341        break;
342      default:
343        assert(false && "Type is not legal nor is it to be expanded!");
344        return VT;
345      }
346    }
347    return VT;
348  }
349
350  /// getVectorTypeBreakdown - Vector types are broken down into some number of
351  /// legal first class types.  For example, EVT::v8f32 maps to 2 EVT::v4f32
352  /// with Altivec or SSE1, or 8 promoted EVT::f64 values with the X86 FP stack.
353  /// Similarly, EVT::v2i64 turns into 4 EVT::i32 values with both PPC and X86.
354  ///
355  /// This method returns the number of registers needed, and the VT for each
356  /// register.  It also returns the VT and quantity of the intermediate values
357  /// before they are promoted/expanded.
358  ///
359  unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
360                                  EVT &IntermediateVT,
361                                  unsigned &NumIntermediates,
362                                  EVT &RegisterVT) const;
363
364  /// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the
365  /// intrinsic will need to map to a MemIntrinsicNode (touches memory). If
366  /// this is the case, it returns true and store the intrinsic
367  /// information into the IntrinsicInfo that was passed to the function.
368  struct IntrinsicInfo {
369    unsigned     opc;         // target opcode
370    EVT          memVT;       // memory VT
371    const Value* ptrVal;      // value representing memory location
372    int          offset;      // offset off of ptrVal
373    unsigned     align;       // alignment
374    bool         vol;         // is volatile?
375    bool         readMem;     // reads memory?
376    bool         writeMem;    // writes memory?
377  };
378
379  virtual bool getTgtMemIntrinsic(IntrinsicInfo &Info,
380                                  const CallInst &I, unsigned Intrinsic) const {
381    return false;
382  }
383
384  /// isFPImmLegal - Returns true if the target can instruction select the
385  /// specified FP immediate natively. If false, the legalizer will materialize
386  /// the FP immediate as a load from a constant pool.
387  virtual bool isFPImmLegal(const APFloat &Imm, EVT VT) const {
388    return false;
389  }
390
391  /// isShuffleMaskLegal - Targets can use this to indicate that they only
392  /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
393  /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
394  /// are assumed to be legal.
395  virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &Mask,
396                                  EVT VT) const {
397    return true;
398  }
399
400  /// canOpTrap - Returns true if the operation can trap for the value type.
401  /// VT must be a legal type. By default, we optimistically assume most
402  /// operations don't trap except for divide and remainder.
403  virtual bool canOpTrap(unsigned Op, EVT VT) const;
404
405  /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
406  /// used by Targets can use this to indicate if there is a suitable
407  /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
408  /// pool entry.
409  virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
410                                      EVT VT) const {
411    return false;
412  }
413
414  /// getOperationAction - Return how this operation should be treated: either
415  /// it is legal, needs to be promoted to a larger size, needs to be
416  /// expanded to some other code sequence, or the target has a custom expander
417  /// for it.
418  LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
419    if (VT.isExtended()) return Expand;
420    assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
421    unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
422    return (LegalizeAction)OpActions[I][Op];
423  }
424
425  /// isOperationLegalOrCustom - Return true if the specified operation is
426  /// legal on this target or can be made legal with custom lowering. This
427  /// is used to help guide high-level lowering decisions.
428  bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
429    return (VT == MVT::Other || isTypeLegal(VT)) &&
430      (getOperationAction(Op, VT) == Legal ||
431       getOperationAction(Op, VT) == Custom);
432  }
433
434  /// isOperationLegal - Return true if the specified operation is legal on this
435  /// target.
436  bool isOperationLegal(unsigned Op, EVT VT) const {
437    return (VT == MVT::Other || isTypeLegal(VT)) &&
438           getOperationAction(Op, VT) == Legal;
439  }
440
441  /// getLoadExtAction - Return how this load with extension should be treated:
442  /// either it is legal, needs to be promoted to a larger size, needs to be
443  /// expanded to some other code sequence, or the target has a custom expander
444  /// for it.
445  LegalizeAction getLoadExtAction(unsigned ExtType, EVT VT) const {
446    assert(ExtType < ISD::LAST_LOADEXT_TYPE &&
447           VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
448           "Table isn't big enough!");
449    return (LegalizeAction)LoadExtActions[VT.getSimpleVT().SimpleTy][ExtType];
450  }
451
452  /// isLoadExtLegal - Return true if the specified load with extension is legal
453  /// on this target.
454  bool isLoadExtLegal(unsigned ExtType, EVT VT) const {
455    return VT.isSimple() &&
456      (getLoadExtAction(ExtType, VT) == Legal ||
457       getLoadExtAction(ExtType, VT) == Custom);
458  }
459
460  /// getTruncStoreAction - Return how this store with truncation should be
461  /// treated: either it is legal, needs to be promoted to a larger size, needs
462  /// to be expanded to some other code sequence, or the target has a custom
463  /// expander for it.
464  LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
465    assert(ValVT.getSimpleVT() < MVT::LAST_VALUETYPE &&
466           MemVT.getSimpleVT() < MVT::LAST_VALUETYPE &&
467           "Table isn't big enough!");
468    return (LegalizeAction)TruncStoreActions[ValVT.getSimpleVT().SimpleTy]
469                                            [MemVT.getSimpleVT().SimpleTy];
470  }
471
472  /// isTruncStoreLegal - Return true if the specified store with truncation is
473  /// legal on this target.
474  bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
475    return isTypeLegal(ValVT) && MemVT.isSimple() &&
476      (getTruncStoreAction(ValVT, MemVT) == Legal ||
477       getTruncStoreAction(ValVT, MemVT) == Custom);
478  }
479
480  /// getIndexedLoadAction - Return how the indexed load should be treated:
481  /// either it is legal, needs to be promoted to a larger size, needs to be
482  /// expanded to some other code sequence, or the target has a custom expander
483  /// for it.
484  LegalizeAction
485  getIndexedLoadAction(unsigned IdxMode, EVT VT) const {
486    assert(IdxMode < ISD::LAST_INDEXED_MODE &&
487           VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
488           "Table isn't big enough!");
489    unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy;
490    return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
491  }
492
493  /// isIndexedLoadLegal - Return true if the specified indexed load is legal
494  /// on this target.
495  bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
496    return VT.isSimple() &&
497      (getIndexedLoadAction(IdxMode, VT) == Legal ||
498       getIndexedLoadAction(IdxMode, VT) == Custom);
499  }
500
501  /// getIndexedStoreAction - Return how the indexed store should be treated:
502  /// either it is legal, needs to be promoted to a larger size, needs to be
503  /// expanded to some other code sequence, or the target has a custom expander
504  /// for it.
505  LegalizeAction
506  getIndexedStoreAction(unsigned IdxMode, EVT VT) const {
507    assert(IdxMode < ISD::LAST_INDEXED_MODE &&
508           VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
509           "Table isn't big enough!");
510    unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy;
511    return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
512  }
513
514  /// isIndexedStoreLegal - Return true if the specified indexed load is legal
515  /// on this target.
516  bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
517    return VT.isSimple() &&
518      (getIndexedStoreAction(IdxMode, VT) == Legal ||
519       getIndexedStoreAction(IdxMode, VT) == Custom);
520  }
521
522  /// getCondCodeAction - Return how the condition code should be treated:
523  /// either it is legal, needs to be expanded to some other code sequence,
524  /// or the target has a custom expander for it.
525  LegalizeAction
526  getCondCodeAction(ISD::CondCode CC, EVT VT) const {
527    assert((unsigned)CC < array_lengthof(CondCodeActions) &&
528           (unsigned)VT.getSimpleVT().SimpleTy < sizeof(CondCodeActions[0])*4 &&
529           "Table isn't big enough!");
530    LegalizeAction Action = (LegalizeAction)
531      ((CondCodeActions[CC] >> (2*VT.getSimpleVT().SimpleTy)) & 3);
532    assert(Action != Promote && "Can't promote condition code!");
533    return Action;
534  }
535
536  /// isCondCodeLegal - Return true if the specified condition code is legal
537  /// on this target.
538  bool isCondCodeLegal(ISD::CondCode CC, EVT VT) const {
539    return getCondCodeAction(CC, VT) == Legal ||
540           getCondCodeAction(CC, VT) == Custom;
541  }
542
543
544  /// getTypeToPromoteTo - If the action for this operation is to promote, this
545  /// method returns the ValueType to promote to.
546  EVT getTypeToPromoteTo(unsigned Op, EVT VT) const {
547    assert(getOperationAction(Op, VT) == Promote &&
548           "This operation isn't promoted!");
549
550    // See if this has an explicit type specified.
551    std::map<std::pair<unsigned, MVT::SimpleValueType>,
552             MVT::SimpleValueType>::const_iterator PTTI =
553      PromoteToType.find(std::make_pair(Op, VT.getSimpleVT().SimpleTy));
554    if (PTTI != PromoteToType.end()) return PTTI->second;
555
556    assert((VT.isInteger() || VT.isFloatingPoint()) &&
557           "Cannot autopromote this type, add it with AddPromotedToType.");
558
559    EVT NVT = VT;
560    do {
561      NVT = (MVT::SimpleValueType)(NVT.getSimpleVT().SimpleTy+1);
562      assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
563             "Didn't find type to promote to!");
564    } while (!isTypeLegal(NVT) ||
565              getOperationAction(Op, NVT) == Promote);
566    return NVT;
567  }
568
569  /// getValueType - Return the EVT corresponding to this LLVM type.
570  /// This is fixed by the LLVM operations except for the pointer size.  If
571  /// AllowUnknown is true, this will return MVT::Other for types with no EVT
572  /// counterpart (e.g. structs), otherwise it will assert.
573  EVT getValueType(const Type *Ty, bool AllowUnknown = false) const {
574    EVT VT = EVT::getEVT(Ty, AllowUnknown);
575    return VT == MVT::iPTR ? PointerTy : VT;
576  }
577
578  /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
579  /// function arguments in the caller parameter area.  This is the actual
580  /// alignment, not its logarithm.
581  virtual unsigned getByValTypeAlignment(const Type *Ty) const;
582
583  /// getRegisterType - Return the type of registers that this ValueType will
584  /// eventually require.
585  EVT getRegisterType(MVT VT) const {
586    assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
587    return RegisterTypeForVT[VT.SimpleTy];
588  }
589
590  /// getRegisterType - Return the type of registers that this ValueType will
591  /// eventually require.
592  EVT getRegisterType(LLVMContext &Context, EVT VT) const {
593    if (VT.isSimple()) {
594      assert((unsigned)VT.getSimpleVT().SimpleTy <
595                array_lengthof(RegisterTypeForVT));
596      return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
597    }
598    if (VT.isVector()) {
599      EVT VT1, RegisterVT;
600      unsigned NumIntermediates;
601      (void)getVectorTypeBreakdown(Context, VT, VT1,
602                                   NumIntermediates, RegisterVT);
603      return RegisterVT;
604    }
605    if (VT.isInteger()) {
606      return getRegisterType(Context, getTypeToTransformTo(Context, VT));
607    }
608    assert(0 && "Unsupported extended type!");
609    return EVT(MVT::Other); // Not reached
610  }
611
612  /// getNumRegisters - Return the number of registers that this ValueType will
613  /// eventually require.  This is one for any types promoted to live in larger
614  /// registers, but may be more than one for types (like i64) that are split
615  /// into pieces.  For types like i140, which are first promoted then expanded,
616  /// it is the number of registers needed to hold all the bits of the original
617  /// type.  For an i140 on a 32 bit machine this means 5 registers.
618  unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
619    if (VT.isSimple()) {
620      assert((unsigned)VT.getSimpleVT().SimpleTy <
621                array_lengthof(NumRegistersForVT));
622      return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
623    }
624    if (VT.isVector()) {
625      EVT VT1, VT2;
626      unsigned NumIntermediates;
627      return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
628    }
629    if (VT.isInteger()) {
630      unsigned BitWidth = VT.getSizeInBits();
631      unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
632      return (BitWidth + RegWidth - 1) / RegWidth;
633    }
634    assert(0 && "Unsupported extended type!");
635    return 0; // Not reached
636  }
637
638  /// ShouldShrinkFPConstant - If true, then instruction selection should
639  /// seek to shrink the FP constant of the specified type to a smaller type
640  /// in order to save space and / or reduce runtime.
641  virtual bool ShouldShrinkFPConstant(EVT VT) const { return true; }
642
643  /// hasTargetDAGCombine - If true, the target has custom DAG combine
644  /// transformations that it can perform for the specified node.
645  bool hasTargetDAGCombine(ISD::NodeType NT) const {
646    assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
647    return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
648  }
649
650  /// This function returns the maximum number of store operations permitted
651  /// to replace a call to llvm.memset. The value is set by the target at the
652  /// performance threshold for such a replacement. If OptSize is true,
653  /// return the limit for functions that have OptSize attribute.
654  /// @brief Get maximum # of store operations permitted for llvm.memset
655  unsigned getMaxStoresPerMemset(bool OptSize) const {
656    return OptSize ? maxStoresPerMemsetOptSize : maxStoresPerMemset;
657  }
658
659  /// This function returns the maximum number of store operations permitted
660  /// to replace a call to llvm.memcpy. The value is set by the target at the
661  /// performance threshold for such a replacement. If OptSize is true,
662  /// return the limit for functions that have OptSize attribute.
663  /// @brief Get maximum # of store operations permitted for llvm.memcpy
664  unsigned getMaxStoresPerMemcpy(bool OptSize) const {
665    return OptSize ? maxStoresPerMemcpyOptSize : maxStoresPerMemcpy;
666  }
667
668  /// This function returns the maximum number of store operations permitted
669  /// to replace a call to llvm.memmove. The value is set by the target at the
670  /// performance threshold for such a replacement. If OptSize is true,
671  /// return the limit for functions that have OptSize attribute.
672  /// @brief Get maximum # of store operations permitted for llvm.memmove
673  unsigned getMaxStoresPerMemmove(bool OptSize) const {
674    return OptSize ? maxStoresPerMemmoveOptSize : maxStoresPerMemmove;
675  }
676
677  /// This function returns true if the target allows unaligned memory accesses.
678  /// of the specified type. This is used, for example, in situations where an
679  /// array copy/move/set is  converted to a sequence of store operations. It's
680  /// use helps to ensure that such replacements don't generate code that causes
681  /// an alignment error  (trap) on the target machine.
682  /// @brief Determine if the target supports unaligned memory accesses.
683  virtual bool allowsUnalignedMemoryAccesses(EVT VT) const {
684    return false;
685  }
686
687  /// This function returns true if the target would benefit from code placement
688  /// optimization.
689  /// @brief Determine if the target should perform code placement optimization.
690  bool shouldOptimizeCodePlacement() const {
691    return benefitFromCodePlacementOpt;
692  }
693
694  /// getOptimalMemOpType - Returns the target specific optimal type for load
695  /// and store operations as a result of memset, memcpy, and memmove
696  /// lowering. If DstAlign is zero that means it's safe to destination
697  /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
698  /// means there isn't a need to check it against alignment requirement,
699  /// probably because the source does not need to be loaded. If
700  /// 'NonScalarIntSafe' is true, that means it's safe to return a
701  /// non-scalar-integer type, e.g. empty string source, constant, or loaded
702  /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
703  /// constant so it does not need to be loaded.
704  /// It returns EVT::Other if the type should be determined using generic
705  /// target-independent logic.
706  virtual EVT getOptimalMemOpType(uint64_t Size,
707                                  unsigned DstAlign, unsigned SrcAlign,
708                                  bool NonScalarIntSafe, bool MemcpyStrSrc,
709                                  MachineFunction &MF) const {
710    return MVT::Other;
711  }
712
713  /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
714  /// to implement llvm.setjmp.
715  bool usesUnderscoreSetJmp() const {
716    return UseUnderscoreSetJmp;
717  }
718
719  /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
720  /// to implement llvm.longjmp.
721  bool usesUnderscoreLongJmp() const {
722    return UseUnderscoreLongJmp;
723  }
724
725  /// getStackPointerRegisterToSaveRestore - If a physical register, this
726  /// specifies the register that llvm.savestack/llvm.restorestack should save
727  /// and restore.
728  unsigned getStackPointerRegisterToSaveRestore() const {
729    return StackPointerRegisterToSaveRestore;
730  }
731
732  /// getExceptionAddressRegister - If a physical register, this returns
733  /// the register that receives the exception address on entry to a landing
734  /// pad.
735  unsigned getExceptionAddressRegister() const {
736    return ExceptionPointerRegister;
737  }
738
739  /// getExceptionSelectorRegister - If a physical register, this returns
740  /// the register that receives the exception typeid on entry to a landing
741  /// pad.
742  unsigned getExceptionSelectorRegister() const {
743    return ExceptionSelectorRegister;
744  }
745
746  /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
747  /// set, the default is 200)
748  unsigned getJumpBufSize() const {
749    return JumpBufSize;
750  }
751
752  /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
753  /// (if never set, the default is 0)
754  unsigned getJumpBufAlignment() const {
755    return JumpBufAlignment;
756  }
757
758  /// getMinStackArgumentAlignment - return the minimum stack alignment of an
759  /// argument.
760  unsigned getMinStackArgumentAlignment() const {
761    return MinStackArgumentAlignment;
762  }
763
764  /// getMinFunctionAlignment - return the minimum function alignment.
765  ///
766  unsigned getMinFunctionAlignment() const {
767    return MinFunctionAlignment;
768  }
769
770  /// getPrefFunctionAlignment - return the preferred function alignment.
771  ///
772  unsigned getPrefFunctionAlignment() const {
773    return PrefFunctionAlignment;
774  }
775
776  /// getPrefLoopAlignment - return the preferred loop alignment.
777  ///
778  unsigned getPrefLoopAlignment() const {
779    return PrefLoopAlignment;
780  }
781
782  /// getShouldFoldAtomicFences - return whether the combiner should fold
783  /// fence MEMBARRIER instructions into the atomic intrinsic instructions.
784  ///
785  bool getShouldFoldAtomicFences() const {
786    return ShouldFoldAtomicFences;
787  }
788
789  /// getPreIndexedAddressParts - returns true by value, base pointer and
790  /// offset pointer and addressing mode by reference if the node's address
791  /// can be legally represented as pre-indexed load / store address.
792  virtual bool getPreIndexedAddressParts(SDNode *N, SDValue &Base,
793                                         SDValue &Offset,
794                                         ISD::MemIndexedMode &AM,
795                                         SelectionDAG &DAG) const {
796    return false;
797  }
798
799  /// getPostIndexedAddressParts - returns true by value, base pointer and
800  /// offset pointer and addressing mode by reference if this node can be
801  /// combined with a load / store to form a post-indexed load / store.
802  virtual bool getPostIndexedAddressParts(SDNode *N, SDNode *Op,
803                                          SDValue &Base, SDValue &Offset,
804                                          ISD::MemIndexedMode &AM,
805                                          SelectionDAG &DAG) const {
806    return false;
807  }
808
809  /// getJumpTableEncoding - Return the entry encoding for a jump table in the
810  /// current function.  The returned value is a member of the
811  /// MachineJumpTableInfo::JTEntryKind enum.
812  virtual unsigned getJumpTableEncoding() const;
813
814  virtual const MCExpr *
815  LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
816                            const MachineBasicBlock *MBB, unsigned uid,
817                            MCContext &Ctx) const {
818    assert(0 && "Need to implement this hook if target has custom JTIs");
819    return 0;
820  }
821
822  /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
823  /// jumptable.
824  virtual SDValue getPICJumpTableRelocBase(SDValue Table,
825                                           SelectionDAG &DAG) const;
826
827  /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
828  /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
829  /// MCExpr.
830  virtual const MCExpr *
831  getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
832                               unsigned JTI, MCContext &Ctx) const;
833
834  /// isOffsetFoldingLegal - Return true if folding a constant offset
835  /// with the given GlobalAddress is legal.  It is frequently not legal in
836  /// PIC relocation models.
837  virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
838
839  /// getStackCookieLocation - Return true if the target stores stack
840  /// protector cookies at a fixed offset in some non-standard address
841  /// space, and populates the address space and offset as
842  /// appropriate.
843  virtual bool getStackCookieLocation(unsigned &AddressSpace, unsigned &Offset) const {
844    return false;
845  }
846
847  /// getMaximalGlobalOffset - Returns the maximal possible offset which can be
848  /// used for loads / stores from the global.
849  virtual unsigned getMaximalGlobalOffset() const {
850    return 0;
851  }
852
853  //===--------------------------------------------------------------------===//
854  // TargetLowering Optimization Methods
855  //
856
857  /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
858  /// SDValues for returning information from TargetLowering to its clients
859  /// that want to combine
860  struct TargetLoweringOpt {
861    SelectionDAG &DAG;
862    bool LegalTys;
863    bool LegalOps;
864    SDValue Old;
865    SDValue New;
866
867    explicit TargetLoweringOpt(SelectionDAG &InDAG,
868                               bool LT, bool LO) :
869      DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
870
871    bool LegalTypes() const { return LegalTys; }
872    bool LegalOperations() const { return LegalOps; }
873
874    bool CombineTo(SDValue O, SDValue N) {
875      Old = O;
876      New = N;
877      return true;
878    }
879
880    /// ShrinkDemandedConstant - Check to see if the specified operand of the
881    /// specified instruction is a constant integer.  If so, check to see if
882    /// there are any bits set in the constant that are not demanded.  If so,
883    /// shrink the constant and return true.
884    bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
885
886    /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
887    /// casts are free.  This uses isZExtFree and ZERO_EXTEND for the widening
888    /// cast, but it could be generalized for targets with other types of
889    /// implicit widening casts.
890    bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
891                          DebugLoc dl);
892  };
893
894  /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
895  /// DemandedMask bits of the result of Op are ever used downstream.  If we can
896  /// use this information to simplify Op, create a new simplified DAG node and
897  /// return true, returning the original and new nodes in Old and New.
898  /// Otherwise, analyze the expression and return a mask of KnownOne and
899  /// KnownZero bits for the expression (used to simplify the caller).
900  /// The KnownZero/One bits may only be accurate for those bits in the
901  /// DemandedMask.
902  bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
903                            APInt &KnownZero, APInt &KnownOne,
904                            TargetLoweringOpt &TLO, unsigned Depth = 0) const;
905
906  /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
907  /// Mask are known to be either zero or one and return them in the
908  /// KnownZero/KnownOne bitsets.
909  virtual void computeMaskedBitsForTargetNode(const SDValue Op,
910                                              const APInt &Mask,
911                                              APInt &KnownZero,
912                                              APInt &KnownOne,
913                                              const SelectionDAG &DAG,
914                                              unsigned Depth = 0) const;
915
916  /// ComputeNumSignBitsForTargetNode - This method can be implemented by
917  /// targets that want to expose additional information about sign bits to the
918  /// DAG Combiner.
919  virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
920                                                   unsigned Depth = 0) const;
921
922  struct DAGCombinerInfo {
923    void *DC;  // The DAG Combiner object.
924    bool BeforeLegalize;
925    bool BeforeLegalizeOps;
926    bool CalledByLegalizer;
927  public:
928    SelectionDAG &DAG;
929
930    DAGCombinerInfo(SelectionDAG &dag, bool bl, bool blo, bool cl, void *dc)
931      : DC(dc), BeforeLegalize(bl), BeforeLegalizeOps(blo),
932        CalledByLegalizer(cl), DAG(dag) {}
933
934    bool isBeforeLegalize() const { return BeforeLegalize; }
935    bool isBeforeLegalizeOps() const { return BeforeLegalizeOps; }
936    bool isCalledByLegalizer() const { return CalledByLegalizer; }
937
938    void AddToWorklist(SDNode *N);
939    void RemoveFromWorklist(SDNode *N);
940    SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
941                      bool AddTo = true);
942    SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
943    SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
944
945    void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
946  };
947
948  /// SimplifySetCC - Try to simplify a setcc built with the specified operands
949  /// and cc. If it is unable to simplify it, return a null SDValue.
950  SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
951                          ISD::CondCode Cond, bool foldBooleans,
952                          DAGCombinerInfo &DCI, DebugLoc dl) const;
953
954  /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
955  /// node is a GlobalAddress + offset.
956  virtual bool
957  isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
958
959  /// PerformDAGCombine - This method will be invoked for all target nodes and
960  /// for any target-independent nodes that the target has registered with
961  /// invoke it for.
962  ///
963  /// The semantics are as follows:
964  /// Return Value:
965  ///   SDValue.Val == 0   - No change was made
966  ///   SDValue.Val == N   - N was replaced, is dead, and is already handled.
967  ///   otherwise          - N should be replaced by the returned Operand.
968  ///
969  /// In addition, methods provided by DAGCombinerInfo may be used to perform
970  /// more complex transformations.
971  ///
972  virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
973
974  /// isTypeDesirableForOp - Return true if the target has native support for
975  /// the specified value type and it is 'desirable' to use the type for the
976  /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
977  /// instruction encodings are longer and some i16 instructions are slow.
978  virtual bool isTypeDesirableForOp(unsigned Opc, EVT VT) const {
979    // By default, assume all legal types are desirable.
980    return isTypeLegal(VT);
981  }
982
983  /// isDesirableToPromoteOp - Return true if it is profitable for dag combiner
984  /// to transform a floating point op of specified opcode to a equivalent op of
985  /// an integer type. e.g. f32 load -> i32 load can be profitable on ARM.
986  virtual bool isDesirableToTransformToIntegerOp(unsigned Opc, EVT VT) const {
987    return false;
988  }
989
990  /// IsDesirableToPromoteOp - This method query the target whether it is
991  /// beneficial for dag combiner to promote the specified node. If true, it
992  /// should return the desired promotion type by reference.
993  virtual bool IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
994    return false;
995  }
996
997  //===--------------------------------------------------------------------===//
998  // TargetLowering Configuration Methods - These methods should be invoked by
999  // the derived class constructor to configure this object for the target.
1000  //
1001
1002protected:
1003  /// setBooleanContents - Specify how the target extends the result of a
1004  /// boolean value from i1 to a wider type.  See getBooleanContents.
1005  void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
1006
1007  /// setSchedulingPreference - Specify the target scheduling preference.
1008  void setSchedulingPreference(Sched::Preference Pref) {
1009    SchedPreferenceInfo = Pref;
1010  }
1011
1012  /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
1013  /// use _setjmp to implement llvm.setjmp or the non _ version.
1014  /// Defaults to false.
1015  void setUseUnderscoreSetJmp(bool Val) {
1016    UseUnderscoreSetJmp = Val;
1017  }
1018
1019  /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
1020  /// use _longjmp to implement llvm.longjmp or the non _ version.
1021  /// Defaults to false.
1022  void setUseUnderscoreLongJmp(bool Val) {
1023    UseUnderscoreLongJmp = Val;
1024  }
1025
1026  /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
1027  /// specifies the register that llvm.savestack/llvm.restorestack should save
1028  /// and restore.
1029  void setStackPointerRegisterToSaveRestore(unsigned R) {
1030    StackPointerRegisterToSaveRestore = R;
1031  }
1032
1033  /// setExceptionPointerRegister - If set to a physical register, this sets
1034  /// the register that receives the exception address on entry to a landing
1035  /// pad.
1036  void setExceptionPointerRegister(unsigned R) {
1037    ExceptionPointerRegister = R;
1038  }
1039
1040  /// setExceptionSelectorRegister - If set to a physical register, this sets
1041  /// the register that receives the exception typeid on entry to a landing
1042  /// pad.
1043  void setExceptionSelectorRegister(unsigned R) {
1044    ExceptionSelectorRegister = R;
1045  }
1046
1047  /// SelectIsExpensive - Tells the code generator not to expand operations
1048  /// into sequences that use the select operations if possible.
1049  void setSelectIsExpensive(bool isExpensive = true) {
1050    SelectIsExpensive = isExpensive;
1051  }
1052
1053  /// JumpIsExpensive - Tells the code generator not to expand sequence of
1054  /// operations into a separate sequences that increases the amount of
1055  /// flow control.
1056  void setJumpIsExpensive(bool isExpensive = true) {
1057    JumpIsExpensive = isExpensive;
1058  }
1059
1060  /// setIntDivIsCheap - Tells the code generator that integer divide is
1061  /// expensive, and if possible, should be replaced by an alternate sequence
1062  /// of instructions not containing an integer divide.
1063  void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
1064
1065  /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
1066  /// srl/add/sra for a signed divide by power of two, and let the target handle
1067  /// it.
1068  void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
1069
1070  /// addRegisterClass - Add the specified register class as an available
1071  /// regclass for the specified value type.  This indicates the selector can
1072  /// handle values of that class natively.
1073  void addRegisterClass(EVT VT, TargetRegisterClass *RC) {
1074    assert((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
1075    AvailableRegClasses.push_back(std::make_pair(VT, RC));
1076    RegClassForVT[VT.getSimpleVT().SimpleTy] = RC;
1077  }
1078
1079  /// findRepresentativeClass - Return the largest legal super-reg register class
1080  /// of the register class for the specified type and its associated "cost".
1081  virtual std::pair<const TargetRegisterClass*, uint8_t>
1082  findRepresentativeClass(EVT VT) const;
1083
1084  /// computeRegisterProperties - Once all of the register classes are added,
1085  /// this allows us to compute derived properties we expose.
1086  void computeRegisterProperties();
1087
1088  /// setOperationAction - Indicate that the specified operation does not work
1089  /// with the specified type and indicate what to do about it.
1090  void setOperationAction(unsigned Op, MVT VT,
1091                          LegalizeAction Action) {
1092    assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
1093    OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action;
1094  }
1095
1096  /// setLoadExtAction - Indicate that the specified load with extension does
1097  /// not work with the specified type and indicate what to do about it.
1098  void setLoadExtAction(unsigned ExtType, MVT VT,
1099                        LegalizeAction Action) {
1100    assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
1101           "Table isn't big enough!");
1102    LoadExtActions[VT.SimpleTy][ExtType] = (uint8_t)Action;
1103  }
1104
1105  /// setTruncStoreAction - Indicate that the specified truncating store does
1106  /// not work with the specified type and indicate what to do about it.
1107  void setTruncStoreAction(MVT ValVT, MVT MemVT,
1108                           LegalizeAction Action) {
1109    assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
1110           "Table isn't big enough!");
1111    TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action;
1112  }
1113
1114  /// setIndexedLoadAction - Indicate that the specified indexed load does or
1115  /// does not work with the specified type and indicate what to do abort
1116  /// it. NOTE: All indexed mode loads are initialized to Expand in
1117  /// TargetLowering.cpp
1118  void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1119                            LegalizeAction Action) {
1120    assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1121           (unsigned)Action < 0xf && "Table isn't big enough!");
1122    // Load action are kept in the upper half.
1123    IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1124    IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1125  }
1126
1127  /// setIndexedStoreAction - Indicate that the specified indexed store does or
1128  /// does not work with the specified type and indicate what to do about
1129  /// it. NOTE: All indexed mode stores are initialized to Expand in
1130  /// TargetLowering.cpp
1131  void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1132                             LegalizeAction Action) {
1133    assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1134           (unsigned)Action < 0xf && "Table isn't big enough!");
1135    // Store action are kept in the lower half.
1136    IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1137    IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1138  }
1139
1140  /// setCondCodeAction - Indicate that the specified condition code is or isn't
1141  /// supported on the target and indicate what to do about it.
1142  void setCondCodeAction(ISD::CondCode CC, MVT VT,
1143                         LegalizeAction Action) {
1144    assert(VT < MVT::LAST_VALUETYPE &&
1145           (unsigned)CC < array_lengthof(CondCodeActions) &&
1146           "Table isn't big enough!");
1147    CondCodeActions[(unsigned)CC] &= ~(uint64_t(3UL)  << VT.SimpleTy*2);
1148    CondCodeActions[(unsigned)CC] |= (uint64_t)Action << VT.SimpleTy*2;
1149  }
1150
1151  /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
1152  /// promotion code defaults to trying a larger integer/fp until it can find
1153  /// one that works.  If that default is insufficient, this method can be used
1154  /// by the target to override the default.
1155  void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1156    PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1157  }
1158
1159  /// setTargetDAGCombine - Targets should invoke this method for each target
1160  /// independent node that they want to provide a custom DAG combiner for by
1161  /// implementing the PerformDAGCombine virtual method.
1162  void setTargetDAGCombine(ISD::NodeType NT) {
1163    assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1164    TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1165  }
1166
1167  /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
1168  /// bytes); default is 200
1169  void setJumpBufSize(unsigned Size) {
1170    JumpBufSize = Size;
1171  }
1172
1173  /// setJumpBufAlignment - Set the target's required jmp_buf buffer
1174  /// alignment (in bytes); default is 0
1175  void setJumpBufAlignment(unsigned Align) {
1176    JumpBufAlignment = Align;
1177  }
1178
1179  /// setMinFunctionAlignment - Set the target's minimum function alignment.
1180  void setMinFunctionAlignment(unsigned Align) {
1181    MinFunctionAlignment = Align;
1182  }
1183
1184  /// setPrefFunctionAlignment - Set the target's preferred function alignment.
1185  /// This should be set if there is a performance benefit to
1186  /// higher-than-minimum alignment
1187  void setPrefFunctionAlignment(unsigned Align) {
1188    PrefFunctionAlignment = Align;
1189  }
1190
1191  /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
1192  /// alignment is zero, it means the target does not care about loop alignment.
1193  void setPrefLoopAlignment(unsigned Align) {
1194    PrefLoopAlignment = Align;
1195  }
1196
1197  /// setMinStackArgumentAlignment - Set the minimum stack alignment of an
1198  /// argument.
1199  void setMinStackArgumentAlignment(unsigned Align) {
1200    MinStackArgumentAlignment = Align;
1201  }
1202
1203  /// setShouldFoldAtomicFences - Set if the target's implementation of the
1204  /// atomic operation intrinsics includes locking. Default is false.
1205  void setShouldFoldAtomicFences(bool fold) {
1206    ShouldFoldAtomicFences = fold;
1207  }
1208
1209public:
1210  //===--------------------------------------------------------------------===//
1211  // Lowering methods - These methods must be implemented by targets so that
1212  // the SelectionDAGLowering code knows how to lower these.
1213  //
1214
1215  /// LowerFormalArguments - This hook must be implemented to lower the
1216  /// incoming (formal) arguments, described by the Ins array, into the
1217  /// specified DAG. The implementation should fill in the InVals array
1218  /// with legal-type argument values, and return the resulting token
1219  /// chain value.
1220  ///
1221  virtual SDValue
1222    LowerFormalArguments(SDValue Chain,
1223                         CallingConv::ID CallConv, bool isVarArg,
1224                         const SmallVectorImpl<ISD::InputArg> &Ins,
1225                         DebugLoc dl, SelectionDAG &DAG,
1226                         SmallVectorImpl<SDValue> &InVals) const {
1227    assert(0 && "Not Implemented");
1228    return SDValue();    // this is here to silence compiler errors
1229  }
1230
1231  /// LowerCallTo - This function lowers an abstract call to a function into an
1232  /// actual call.  This returns a pair of operands.  The first element is the
1233  /// return value for the function (if RetTy is not VoidTy).  The second
1234  /// element is the outgoing token chain. It calls LowerCall to do the actual
1235  /// lowering.
1236  struct ArgListEntry {
1237    SDValue Node;
1238    const Type* Ty;
1239    bool isSExt  : 1;
1240    bool isZExt  : 1;
1241    bool isInReg : 1;
1242    bool isSRet  : 1;
1243    bool isNest  : 1;
1244    bool isByVal : 1;
1245    uint16_t Alignment;
1246
1247    ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1248      isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
1249  };
1250  typedef std::vector<ArgListEntry> ArgListTy;
1251  std::pair<SDValue, SDValue>
1252  LowerCallTo(SDValue Chain, const Type *RetTy, bool RetSExt, bool RetZExt,
1253              bool isVarArg, bool isInreg, unsigned NumFixedArgs,
1254              CallingConv::ID CallConv, bool isTailCall,
1255              bool isReturnValueUsed, SDValue Callee, ArgListTy &Args,
1256              SelectionDAG &DAG, DebugLoc dl) const;
1257
1258  /// LowerCall - This hook must be implemented to lower calls into the
1259  /// the specified DAG. The outgoing arguments to the call are described
1260  /// by the Outs array, and the values to be returned by the call are
1261  /// described by the Ins array. The implementation should fill in the
1262  /// InVals array with legal-type return values from the call, and return
1263  /// the resulting token chain value.
1264  virtual SDValue
1265    LowerCall(SDValue Chain, SDValue Callee,
1266              CallingConv::ID CallConv, bool isVarArg, bool &isTailCall,
1267              const SmallVectorImpl<ISD::OutputArg> &Outs,
1268              const SmallVectorImpl<SDValue> &OutVals,
1269              const SmallVectorImpl<ISD::InputArg> &Ins,
1270              DebugLoc dl, SelectionDAG &DAG,
1271              SmallVectorImpl<SDValue> &InVals) const {
1272    assert(0 && "Not Implemented");
1273    return SDValue();    // this is here to silence compiler errors
1274  }
1275
1276  /// HandleByVal - Target-specific cleanup for formal ByVal parameters.
1277  virtual void HandleByVal(CCState *, unsigned &) const {}
1278
1279  /// CanLowerReturn - This hook should be implemented to check whether the
1280  /// return values described by the Outs array can fit into the return
1281  /// registers.  If false is returned, an sret-demotion is performed.
1282  ///
1283  virtual bool CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1284               const SmallVectorImpl<ISD::OutputArg> &Outs,
1285               LLVMContext &Context) const
1286  {
1287    // Return true by default to get preexisting behavior.
1288    return true;
1289  }
1290
1291  /// LowerReturn - This hook must be implemented to lower outgoing
1292  /// return values, described by the Outs array, into the specified
1293  /// DAG. The implementation should return the resulting token chain
1294  /// value.
1295  ///
1296  virtual SDValue
1297    LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1298                const SmallVectorImpl<ISD::OutputArg> &Outs,
1299                const SmallVectorImpl<SDValue> &OutVals,
1300                DebugLoc dl, SelectionDAG &DAG) const {
1301    assert(0 && "Not Implemented");
1302    return SDValue();    // this is here to silence compiler errors
1303  }
1304
1305  /// isUsedByReturnOnly - Return true if result of the specified node is used
1306  /// by a return node only. This is used to determine whether it is possible
1307  /// to codegen a libcall as tail call at legalization time.
1308  virtual bool isUsedByReturnOnly(SDNode *N) const {
1309    return false;
1310  }
1311
1312  /// mayBeEmittedAsTailCall - Return true if the target may be able emit the
1313  /// call instruction as a tail call. This is used by optimization passes to
1314  /// determine if it's profitable to duplicate return instructions to enable
1315  /// tailcall optimization.
1316  virtual bool mayBeEmittedAsTailCall(CallInst *CI) const {
1317    return false;
1318  }
1319
1320  /// getTypeForExtArgOrReturn - Return the type that should be used to zero or
1321  /// sign extend a zeroext/signext integer argument or return value.
1322  /// FIXME: Most C calling convention requires the return type to be promoted,
1323  /// but this is not true all the time, e.g. i1 on x86-64. It is also not
1324  /// necessary for non-C calling conventions. The frontend should handle this
1325  /// and include all of the necessary information.
1326  virtual EVT getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1327                                       ISD::NodeType ExtendKind) const {
1328    EVT MinVT = getRegisterType(Context, MVT::i32);
1329    return VT.bitsLT(MinVT) ? MinVT : VT;
1330  }
1331
1332  /// LowerOperationWrapper - This callback is invoked by the type legalizer
1333  /// to legalize nodes with an illegal operand type but legal result types.
1334  /// It replaces the LowerOperation callback in the type Legalizer.
1335  /// The reason we can not do away with LowerOperation entirely is that
1336  /// LegalizeDAG isn't yet ready to use this callback.
1337  /// TODO: Consider merging with ReplaceNodeResults.
1338
1339  /// The target places new result values for the node in Results (their number
1340  /// and types must exactly match those of the original return values of
1341  /// the node), or leaves Results empty, which indicates that the node is not
1342  /// to be custom lowered after all.
1343  /// The default implementation calls LowerOperation.
1344  virtual void LowerOperationWrapper(SDNode *N,
1345                                     SmallVectorImpl<SDValue> &Results,
1346                                     SelectionDAG &DAG) const;
1347
1348  /// LowerOperation - This callback is invoked for operations that are
1349  /// unsupported by the target, which are registered to use 'custom' lowering,
1350  /// and whose defined values are all legal.
1351  /// If the target has no operations that require custom lowering, it need not
1352  /// implement this.  The default implementation of this aborts.
1353  virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
1354
1355  /// ReplaceNodeResults - This callback is invoked when a node result type is
1356  /// illegal for the target, and the operation was registered to use 'custom'
1357  /// lowering for that result type.  The target places new result values for
1358  /// the node in Results (their number and types must exactly match those of
1359  /// the original return values of the node), or leaves Results empty, which
1360  /// indicates that the node is not to be custom lowered after all.
1361  ///
1362  /// If the target has no operations that require custom lowering, it need not
1363  /// implement this.  The default implementation aborts.
1364  virtual void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
1365                                  SelectionDAG &DAG) const {
1366    assert(0 && "ReplaceNodeResults not implemented for this target!");
1367  }
1368
1369  /// getTargetNodeName() - This method returns the name of a target specific
1370  /// DAG node.
1371  virtual const char *getTargetNodeName(unsigned Opcode) const;
1372
1373  /// createFastISel - This method returns a target specific FastISel object,
1374  /// or null if the target does not support "fast" ISel.
1375  virtual FastISel *createFastISel(FunctionLoweringInfo &funcInfo) const {
1376    return 0;
1377  }
1378
1379  //===--------------------------------------------------------------------===//
1380  // Inline Asm Support hooks
1381  //
1382
1383  /// ExpandInlineAsm - This hook allows the target to expand an inline asm
1384  /// call to be explicit llvm code if it wants to.  This is useful for
1385  /// turning simple inline asms into LLVM intrinsics, which gives the
1386  /// compiler more information about the behavior of the code.
1387  virtual bool ExpandInlineAsm(CallInst *CI) const {
1388    return false;
1389  }
1390
1391  enum ConstraintType {
1392    C_Register,            // Constraint represents specific register(s).
1393    C_RegisterClass,       // Constraint represents any of register(s) in class.
1394    C_Memory,              // Memory constraint.
1395    C_Other,               // Something else.
1396    C_Unknown              // Unsupported constraint.
1397  };
1398
1399  enum ConstraintWeight {
1400    // Generic weights.
1401    CW_Invalid  = -1,     // No match.
1402    CW_Okay     = 0,      // Acceptable.
1403    CW_Good     = 1,      // Good weight.
1404    CW_Better   = 2,      // Better weight.
1405    CW_Best     = 3,      // Best weight.
1406
1407    // Well-known weights.
1408    CW_SpecificReg  = CW_Okay,    // Specific register operands.
1409    CW_Register     = CW_Good,    // Register operands.
1410    CW_Memory       = CW_Better,  // Memory operands.
1411    CW_Constant     = CW_Best,    // Constant operand.
1412    CW_Default      = CW_Okay     // Default or don't know type.
1413  };
1414
1415  /// AsmOperandInfo - This contains information for each constraint that we are
1416  /// lowering.
1417  struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
1418    /// ConstraintCode - This contains the actual string for the code, like "m".
1419    /// TargetLowering picks the 'best' code from ConstraintInfo::Codes that
1420    /// most closely matches the operand.
1421    std::string ConstraintCode;
1422
1423    /// ConstraintType - Information about the constraint code, e.g. Register,
1424    /// RegisterClass, Memory, Other, Unknown.
1425    TargetLowering::ConstraintType ConstraintType;
1426
1427    /// CallOperandval - If this is the result output operand or a
1428    /// clobber, this is null, otherwise it is the incoming operand to the
1429    /// CallInst.  This gets modified as the asm is processed.
1430    Value *CallOperandVal;
1431
1432    /// ConstraintVT - The ValueType for the operand value.
1433    EVT ConstraintVT;
1434
1435    /// isMatchingInputConstraint - Return true of this is an input operand that
1436    /// is a matching constraint like "4".
1437    bool isMatchingInputConstraint() const;
1438
1439    /// getMatchedOperand - If this is an input matching constraint, this method
1440    /// returns the output operand it matches.
1441    unsigned getMatchedOperand() const;
1442
1443    /// Copy constructor for copying from an AsmOperandInfo.
1444    AsmOperandInfo(const AsmOperandInfo &info)
1445      : InlineAsm::ConstraintInfo(info),
1446        ConstraintCode(info.ConstraintCode),
1447        ConstraintType(info.ConstraintType),
1448        CallOperandVal(info.CallOperandVal),
1449        ConstraintVT(info.ConstraintVT) {
1450    }
1451
1452    /// Copy constructor for copying from a ConstraintInfo.
1453    AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
1454      : InlineAsm::ConstraintInfo(info),
1455        ConstraintType(TargetLowering::C_Unknown),
1456        CallOperandVal(0), ConstraintVT(MVT::Other) {
1457    }
1458  };
1459
1460  typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
1461
1462  /// ParseConstraints - Split up the constraint string from the inline
1463  /// assembly value into the specific constraints and their prefixes,
1464  /// and also tie in the associated operand values.
1465  /// If this returns an empty vector, and if the constraint string itself
1466  /// isn't empty, there was an error parsing.
1467  virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const;
1468
1469  /// Examine constraint type and operand type and determine a weight value.
1470  /// The operand object must already have been set up with the operand type.
1471  virtual ConstraintWeight getMultipleConstraintMatchWeight(
1472      AsmOperandInfo &info, int maIndex) const;
1473
1474  /// Examine constraint string and operand type and determine a weight value.
1475  /// The operand object must already have been set up with the operand type.
1476  virtual ConstraintWeight getSingleConstraintMatchWeight(
1477      AsmOperandInfo &info, const char *constraint) const;
1478
1479  /// ComputeConstraintToUse - Determines the constraint code and constraint
1480  /// type to use for the specific AsmOperandInfo, setting
1481  /// OpInfo.ConstraintCode and OpInfo.ConstraintType.  If the actual operand
1482  /// being passed in is available, it can be passed in as Op, otherwise an
1483  /// empty SDValue can be passed.
1484  virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
1485                                      SDValue Op,
1486                                      SelectionDAG *DAG = 0) const;
1487
1488  /// getConstraintType - Given a constraint, return the type of constraint it
1489  /// is for this target.
1490  virtual ConstraintType getConstraintType(const std::string &Constraint) const;
1491
1492  /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1493  /// return a list of registers that can be used to satisfy the constraint.
1494  /// This should only be used for C_RegisterClass constraints.
1495  virtual std::vector<unsigned>
1496  getRegClassForInlineAsmConstraint(const std::string &Constraint,
1497                                    EVT VT) const;
1498
1499  /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
1500  /// {edx}), return the register number and the register class for the
1501  /// register.
1502  ///
1503  /// Given a register class constraint, like 'r', if this corresponds directly
1504  /// to an LLVM register class, return a register of 0 and the register class
1505  /// pointer.
1506  ///
1507  /// This should only be used for C_Register constraints.  On error,
1508  /// this returns a register number of 0 and a null register class pointer..
1509  virtual std::pair<unsigned, const TargetRegisterClass*>
1510    getRegForInlineAsmConstraint(const std::string &Constraint,
1511                                 EVT VT) const;
1512
1513  /// LowerXConstraint - try to replace an X constraint, which matches anything,
1514  /// with another that has more specific requirements based on the type of the
1515  /// corresponding operand.  This returns null if there is no replacement to
1516  /// make.
1517  virtual const char *LowerXConstraint(EVT ConstraintVT) const;
1518
1519  /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1520  /// vector.  If it is invalid, don't add anything to Ops.
1521  virtual void LowerAsmOperandForConstraint(SDValue Op, char ConstraintLetter,
1522                                            std::vector<SDValue> &Ops,
1523                                            SelectionDAG &DAG) const;
1524
1525  //===--------------------------------------------------------------------===//
1526  // Instruction Emitting Hooks
1527  //
1528
1529  // EmitInstrWithCustomInserter - This method should be implemented by targets
1530  // that mark instructions with the 'usesCustomInserter' flag.  These
1531  // instructions are special in various ways, which require special support to
1532  // insert.  The specified MachineInstr is created but not inserted into any
1533  // basic blocks, and this method is called to expand it into a sequence of
1534  // instructions, potentially also creating new basic blocks and control flow.
1535  virtual MachineBasicBlock *
1536    EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const;
1537
1538  //===--------------------------------------------------------------------===//
1539  // Addressing mode description hooks (used by LSR etc).
1540  //
1541
1542  /// AddrMode - This represents an addressing mode of:
1543  ///    BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1544  /// If BaseGV is null,  there is no BaseGV.
1545  /// If BaseOffs is zero, there is no base offset.
1546  /// If HasBaseReg is false, there is no base register.
1547  /// If Scale is zero, there is no ScaleReg.  Scale of 1 indicates a reg with
1548  /// no scale.
1549  ///
1550  struct AddrMode {
1551    GlobalValue *BaseGV;
1552    int64_t      BaseOffs;
1553    bool         HasBaseReg;
1554    int64_t      Scale;
1555    AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1556  };
1557
1558  /// isLegalAddressingMode - Return true if the addressing mode represented by
1559  /// AM is legal for this target, for a load/store of the specified type.
1560  /// The type may be VoidTy, in which case only return true if the addressing
1561  /// mode is legal for a load/store of any legal type.
1562  /// TODO: Handle pre/postinc as well.
1563  virtual bool isLegalAddressingMode(const AddrMode &AM, const Type *Ty) const;
1564
1565  /// isTruncateFree - Return true if it's free to truncate a value of
1566  /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1567  /// register EAX to i16 by referencing its sub-register AX.
1568  virtual bool isTruncateFree(const Type *Ty1, const Type *Ty2) const {
1569    return false;
1570  }
1571
1572  virtual bool isTruncateFree(EVT VT1, EVT VT2) const {
1573    return false;
1574  }
1575
1576  /// isZExtFree - Return true if any actual instruction that defines a
1577  /// value of type Ty1 implicitly zero-extends the value to Ty2 in the result
1578  /// register. This does not necessarily include registers defined in
1579  /// unknown ways, such as incoming arguments, or copies from unknown
1580  /// virtual registers. Also, if isTruncateFree(Ty2, Ty1) is true, this
1581  /// does not necessarily apply to truncate instructions. e.g. on x86-64,
1582  /// all instructions that define 32-bit values implicit zero-extend the
1583  /// result out to 64 bits.
1584  virtual bool isZExtFree(const Type *Ty1, const Type *Ty2) const {
1585    return false;
1586  }
1587
1588  virtual bool isZExtFree(EVT VT1, EVT VT2) const {
1589    return false;
1590  }
1591
1592  /// isNarrowingProfitable - Return true if it's profitable to narrow
1593  /// operations of type VT1 to VT2. e.g. on x86, it's profitable to narrow
1594  /// from i32 to i8 but not from i32 to i16.
1595  virtual bool isNarrowingProfitable(EVT VT1, EVT VT2) const {
1596    return false;
1597  }
1598
1599  /// isLegalICmpImmediate - Return true if the specified immediate is legal
1600  /// icmp immediate, that is the target has icmp instructions which can compare
1601  /// a register against the immediate without having to materialize the
1602  /// immediate into a register.
1603  virtual bool isLegalICmpImmediate(int64_t Imm) const {
1604    return true;
1605  }
1606
1607  /// isLegalAddImmediate - Return true if the specified immediate is legal
1608  /// add immediate, that is the target has add instructions which can add
1609  /// a register with the immediate without having to materialize the
1610  /// immediate into a register.
1611  virtual bool isLegalAddImmediate(int64_t Imm) const {
1612    return true;
1613  }
1614
1615  //===--------------------------------------------------------------------===//
1616  // Div utility functions
1617  //
1618  SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG,
1619                      std::vector<SDNode*>* Created) const;
1620  SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG,
1621                      std::vector<SDNode*>* Created) const;
1622
1623
1624  //===--------------------------------------------------------------------===//
1625  // Runtime Library hooks
1626  //
1627
1628  /// setLibcallName - Rename the default libcall routine name for the specified
1629  /// libcall.
1630  void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1631    LibcallRoutineNames[Call] = Name;
1632  }
1633
1634  /// getLibcallName - Get the libcall routine name for the specified libcall.
1635  ///
1636  const char *getLibcallName(RTLIB::Libcall Call) const {
1637    return LibcallRoutineNames[Call];
1638  }
1639
1640  /// setCmpLibcallCC - Override the default CondCode to be used to test the
1641  /// result of the comparison libcall against zero.
1642  void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1643    CmpLibcallCCs[Call] = CC;
1644  }
1645
1646  /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1647  /// the comparison libcall against zero.
1648  ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1649    return CmpLibcallCCs[Call];
1650  }
1651
1652  /// setLibcallCallingConv - Set the CallingConv that should be used for the
1653  /// specified libcall.
1654  void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
1655    LibcallCallingConvs[Call] = CC;
1656  }
1657
1658  /// getLibcallCallingConv - Get the CallingConv that should be used for the
1659  /// specified libcall.
1660  CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
1661    return LibcallCallingConvs[Call];
1662  }
1663
1664private:
1665  const TargetMachine &TM;
1666  const TargetData *TD;
1667  const TargetLoweringObjectFile &TLOF;
1668
1669  /// PointerTy - The type to use for pointers, usually i32 or i64.
1670  ///
1671  MVT PointerTy;
1672
1673  /// IsLittleEndian - True if this is a little endian target.
1674  ///
1675  bool IsLittleEndian;
1676
1677  /// SelectIsExpensive - Tells the code generator not to expand operations
1678  /// into sequences that use the select operations if possible.
1679  bool SelectIsExpensive;
1680
1681  /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1682  /// constants into a sequence of muls, adds, and shifts.  This is a hack until
1683  /// a real cost model is in place.  If we ever optimize for size, this will be
1684  /// set to true unconditionally.
1685  bool IntDivIsCheap;
1686
1687  /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1688  /// srl/add/sra for a signed divide by power of two, and let the target handle
1689  /// it.
1690  bool Pow2DivIsCheap;
1691
1692  /// JumpIsExpensive - Tells the code generator that it shouldn't generate
1693  /// extra flow control instructions and should attempt to combine flow
1694  /// control instructions via predication.
1695  bool JumpIsExpensive;
1696
1697  /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1698  /// llvm.setjmp.  Defaults to false.
1699  bool UseUnderscoreSetJmp;
1700
1701  /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1702  /// llvm.longjmp.  Defaults to false.
1703  bool UseUnderscoreLongJmp;
1704
1705  /// BooleanContents - Information about the contents of the high-bits in
1706  /// boolean values held in a type wider than i1.  See getBooleanContents.
1707  BooleanContent BooleanContents;
1708
1709  /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1710  /// total cycles or lowest register usage.
1711  Sched::Preference SchedPreferenceInfo;
1712
1713  /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1714  unsigned JumpBufSize;
1715
1716  /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1717  /// buffers
1718  unsigned JumpBufAlignment;
1719
1720  /// MinStackArgumentAlignment - The minimum alignment that any argument
1721  /// on the stack needs to have.
1722  ///
1723  unsigned MinStackArgumentAlignment;
1724
1725  /// MinFunctionAlignment - The minimum function alignment (used when
1726  /// optimizing for size, and to prevent explicitly provided alignment
1727  /// from leading to incorrect code).
1728  ///
1729  unsigned MinFunctionAlignment;
1730
1731  /// PrefFunctionAlignment - The preferred function alignment (used when
1732  /// alignment unspecified and optimizing for speed).
1733  ///
1734  unsigned PrefFunctionAlignment;
1735
1736  /// PrefLoopAlignment - The preferred loop alignment.
1737  ///
1738  unsigned PrefLoopAlignment;
1739
1740  /// ShouldFoldAtomicFences - Whether fencing MEMBARRIER instructions should
1741  /// be folded into the enclosed atomic intrinsic instruction by the
1742  /// combiner.
1743  bool ShouldFoldAtomicFences;
1744
1745  /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1746  /// specifies the register that llvm.savestack/llvm.restorestack should save
1747  /// and restore.
1748  unsigned StackPointerRegisterToSaveRestore;
1749
1750  /// ExceptionPointerRegister - If set to a physical register, this specifies
1751  /// the register that receives the exception address on entry to a landing
1752  /// pad.
1753  unsigned ExceptionPointerRegister;
1754
1755  /// ExceptionSelectorRegister - If set to a physical register, this specifies
1756  /// the register that receives the exception typeid on entry to a landing
1757  /// pad.
1758  unsigned ExceptionSelectorRegister;
1759
1760  /// RegClassForVT - This indicates the default register class to use for
1761  /// each ValueType the target supports natively.
1762  TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1763  unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1764  EVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1765
1766  /// RepRegClassForVT - This indicates the "representative" register class to
1767  /// use for each ValueType the target supports natively. This information is
1768  /// used by the scheduler to track register pressure. By default, the
1769  /// representative register class is the largest legal super-reg register
1770  /// class of the register class of the specified type. e.g. On x86, i8, i16,
1771  /// and i32's representative class would be GR32.
1772  const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
1773
1774  /// RepRegClassCostForVT - This indicates the "cost" of the "representative"
1775  /// register class for each ValueType. The cost is used by the scheduler to
1776  /// approximate register pressure.
1777  uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
1778
1779  /// TransformToType - For any value types we are promoting or expanding, this
1780  /// contains the value type that we are changing to.  For Expanded types, this
1781  /// contains one step of the expand (e.g. i64 -> i32), even if there are
1782  /// multiple steps required (e.g. i64 -> i16).  For types natively supported
1783  /// by the system, this holds the same type (e.g. i32 -> i32).
1784  EVT TransformToType[MVT::LAST_VALUETYPE];
1785
1786  /// OpActions - For each operation and each value type, keep a LegalizeAction
1787  /// that indicates how instruction selection should deal with the operation.
1788  /// Most operations are Legal (aka, supported natively by the target), but
1789  /// operations that are not should be described.  Note that operations on
1790  /// non-legal value types are not described here.
1791  uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
1792
1793  /// LoadExtActions - For each load extension type and each value type,
1794  /// keep a LegalizeAction that indicates how instruction selection should deal
1795  /// with a load of a specific value type and extension type.
1796  uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE];
1797
1798  /// TruncStoreActions - For each value type pair keep a LegalizeAction that
1799  /// indicates whether a truncating store of a specific value type and
1800  /// truncating type is legal.
1801  uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
1802
1803  /// IndexedModeActions - For each indexed mode and each value type,
1804  /// keep a pair of LegalizeAction that indicates how instruction
1805  /// selection should deal with the load / store.  The first dimension is the
1806  /// value_type for the reference. The second dimension represents the various
1807  /// modes for load store.
1808  uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
1809
1810  /// CondCodeActions - For each condition code (ISD::CondCode) keep a
1811  /// LegalizeAction that indicates how instruction selection should
1812  /// deal with the condition code.
1813  uint64_t CondCodeActions[ISD::SETCC_INVALID];
1814
1815  ValueTypeActionImpl ValueTypeActions;
1816
1817  std::vector<std::pair<EVT, TargetRegisterClass*> > AvailableRegClasses;
1818
1819  /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
1820  /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
1821  /// which sets a bit in this array.
1822  unsigned char
1823  TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
1824
1825  /// PromoteToType - For operations that must be promoted to a specific type,
1826  /// this holds the destination type.  This map should be sparse, so don't hold
1827  /// it as an array.
1828  ///
1829  /// Targets add entries to this map with AddPromotedToType(..), clients access
1830  /// this with getTypeToPromoteTo(..).
1831  std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1832    PromoteToType;
1833
1834  /// LibcallRoutineNames - Stores the name each libcall.
1835  ///
1836  const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1837
1838  /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
1839  /// of each of the comparison libcall against zero.
1840  ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1841
1842  /// LibcallCallingConvs - Stores the CallingConv that should be used for each
1843  /// libcall.
1844  CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
1845
1846protected:
1847  /// When lowering \@llvm.memset this field specifies the maximum number of
1848  /// store operations that may be substituted for the call to memset. Targets
1849  /// must set this value based on the cost threshold for that target. Targets
1850  /// should assume that the memset will be done using as many of the largest
1851  /// store operations first, followed by smaller ones, if necessary, per
1852  /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1853  /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1854  /// store.  This only applies to setting a constant array of a constant size.
1855  /// @brief Specify maximum number of store instructions per memset call.
1856  unsigned maxStoresPerMemset;
1857
1858  /// Maximum number of stores operations that may be substituted for the call
1859  /// to memset, used for functions with OptSize attribute.
1860  unsigned maxStoresPerMemsetOptSize;
1861
1862  /// When lowering \@llvm.memcpy this field specifies the maximum number of
1863  /// store operations that may be substituted for a call to memcpy. Targets
1864  /// must set this value based on the cost threshold for that target. Targets
1865  /// should assume that the memcpy will be done using as many of the largest
1866  /// store operations first, followed by smaller ones, if necessary, per
1867  /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1868  /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1869  /// and one 1-byte store. This only applies to copying a constant array of
1870  /// constant size.
1871  /// @brief Specify maximum bytes of store instructions per memcpy call.
1872  unsigned maxStoresPerMemcpy;
1873
1874  /// Maximum number of store operations that may be substituted for a call
1875  /// to memcpy, used for functions with OptSize attribute.
1876  unsigned maxStoresPerMemcpyOptSize;
1877
1878  /// When lowering \@llvm.memmove this field specifies the maximum number of
1879  /// store instructions that may be substituted for a call to memmove. Targets
1880  /// must set this value based on the cost threshold for that target. Targets
1881  /// should assume that the memmove will be done using as many of the largest
1882  /// store operations first, followed by smaller ones, if necessary, per
1883  /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1884  /// with 8-bit alignment would result in nine 1-byte stores.  This only
1885  /// applies to copying a constant array of constant size.
1886  /// @brief Specify maximum bytes of store instructions per memmove call.
1887  unsigned maxStoresPerMemmove;
1888
1889  /// Maximum number of store instructions that may be substituted for a call
1890  /// to memmove, used for functions with OpSize attribute.
1891  unsigned maxStoresPerMemmoveOptSize;
1892
1893  /// This field specifies whether the target can benefit from code placement
1894  /// optimization.
1895  bool benefitFromCodePlacementOpt;
1896
1897private:
1898  /// isLegalRC - Return true if the value types that can be represented by the
1899  /// specified register class are all legal.
1900  bool isLegalRC(const TargetRegisterClass *RC) const;
1901
1902  /// hasLegalSuperRegRegClasses - Return true if the specified register class
1903  /// has one or more super-reg register classes that are legal.
1904  bool hasLegalSuperRegRegClasses(const TargetRegisterClass *RC) const;
1905};
1906
1907/// GetReturnInfo - Given an LLVM IR type and return type attributes,
1908/// compute the return value EVTs and flags, and optionally also
1909/// the offsets, if the return value is being lowered to memory.
1910void GetReturnInfo(const Type* ReturnType, Attributes attr,
1911                   SmallVectorImpl<ISD::OutputArg> &Outs,
1912                   const TargetLowering &TLI,
1913                   SmallVectorImpl<uint64_t> *Offsets = 0);
1914
1915} // end llvm namespace
1916
1917#endif
1918