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