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