1193323Sed//===-- llvm/Target/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file describes how to lower LLVM code to machine code.  This has two
11193323Sed// main components:
12193323Sed//
13193323Sed//  1. Which ValueTypes are natively supported by the target.
14193323Sed//  2. Which operations are supported for supported ValueTypes.
15193323Sed//  3. Cost thresholds for alternative implementations of certain operations.
16193323Sed//
17193323Sed// In addition it has a few other components, like information about FP
18193323Sed// immediates.
19193323Sed//
20193323Sed//===----------------------------------------------------------------------===//
21193323Sed
22193323Sed#ifndef LLVM_TARGET_TARGETLOWERING_H
23193323Sed#define LLVM_TARGET_TARGETLOWERING_H
24193323Sed
25243830Sdim#include "llvm/ADT/DenseMap.h"
26249423Sdim#include "llvm/CodeGen/DAGCombine.h"
27249423Sdim#include "llvm/CodeGen/RuntimeLibcalls.h"
28249423Sdim#include "llvm/CodeGen/SelectionDAGNodes.h"
29249423Sdim#include "llvm/IR/Attributes.h"
30249423Sdim#include "llvm/IR/CallingConv.h"
31249423Sdim#include "llvm/IR/InlineAsm.h"
32239462Sdim#include "llvm/Support/CallSite.h"
33194612Sed#include "llvm/Support/DebugLoc.h"
34210299Sed#include "llvm/Target/TargetCallingConv.h"
35193323Sed#include "llvm/Target/TargetMachine.h"
36193323Sed#include <climits>
37193323Sed#include <map>
38193323Sed#include <vector>
39193323Sed
40193323Sednamespace llvm {
41193323Sed  class CallInst;
42221345Sdim  class CCState;
43193323Sed  class FastISel;
44210299Sed  class FunctionLoweringInfo;
45218893Sdim  class ImmutableCallSite;
46234353Sdim  class IntrinsicInst;
47193323Sed  class MachineBasicBlock;
48193323Sed  class MachineFunction;
49193323Sed  class MachineInstr;
50203954Srdivacky  class MachineJumpTableInfo;
51203954Srdivacky  class MCContext;
52203954Srdivacky  class MCExpr;
53218893Sdim  template<typename T> class SmallVectorImpl;
54243830Sdim  class DataLayout;
55193323Sed  class TargetRegisterClass;
56239462Sdim  class TargetLibraryInfo;
57198090Srdivacky  class TargetLoweringObjectFile;
58193323Sed  class Value;
59193323Sed
60234353Sdim  namespace Sched {
61234353Sdim    enum Preference {
62234353Sdim      None,             // No preference
63234353Sdim      Source,           // Follow source order.
64234353Sdim      RegPressure,      // Scheduling for lowest register pressure.
65234353Sdim      Hybrid,           // Scheduling for both latency and register pressure.
66234353Sdim      ILP,              // Scheduling for ILP in low register pressure mode.
67234353Sdim      VLIW              // Scheduling for VLIW targets.
68193323Sed    };
69193323Sed  }
70193323Sed
71249423Sdim/// TargetLoweringBase - This base class for TargetLowering contains the
72249423Sdim/// SelectionDAG-independent parts that can be used from the rest of CodeGen.
73249423Sdimclass TargetLoweringBase {
74249423Sdim  TargetLoweringBase(const TargetLoweringBase&) LLVM_DELETED_FUNCTION;
75249423Sdim  void operator=(const TargetLoweringBase&) LLVM_DELETED_FUNCTION;
76193323Sed
77193323Sedpublic:
78193323Sed  /// LegalizeAction - This enum indicates whether operations are valid for a
79193323Sed  /// target, and if not, what action should be used to make them valid.
80193323Sed  enum LegalizeAction {
81193323Sed    Legal,      // The target natively supports this operation.
82193323Sed    Promote,    // This operation should be executed in a larger type.
83193323Sed    Expand,     // Try to expand this to other ops, otherwise use a libcall.
84193323Sed    Custom      // Use the LowerOperation hook to implement custom lowering.
85193323Sed  };
86193323Sed
87234353Sdim  /// LegalizeTypeAction - This enum indicates whether a types are legal for a
88223017Sdim  /// target, and if not, what action should be used to make them valid.
89223017Sdim  enum LegalizeTypeAction {
90223017Sdim    TypeLegal,           // The target natively supports this type.
91223017Sdim    TypePromoteInteger,  // Replace this integer with a larger one.
92223017Sdim    TypeExpandInteger,   // Split this integer into two of half the size.
93223017Sdim    TypeSoftenFloat,     // Convert this float to a same size integer type.
94223017Sdim    TypeExpandFloat,     // Split this float into two of half the size.
95223017Sdim    TypeScalarizeVector, // Replace this one-element vector with its element.
96223017Sdim    TypeSplitVector,     // Split this vector into two of half the size.
97223017Sdim    TypeWidenVector      // This vector should be widened into a larger vector.
98223017Sdim  };
99223017Sdim
100243830Sdim  /// LegalizeKind holds the legalization kind that needs to happen to EVT
101243830Sdim  /// in order to type-legalize it.
102243830Sdim  typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind;
103243830Sdim
104193323Sed  enum BooleanContent { // How the target represents true/false values.
105193323Sed    UndefinedBooleanContent,    // Only bit 0 counts, the rest can hold garbage.
106193323Sed    ZeroOrOneBooleanContent,        // All bits zero except for bit 0.
107193323Sed    ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
108193323Sed  };
109193323Sed
110243830Sdim  enum SelectSupportKind {
111243830Sdim    ScalarValSelect,      // The target supports scalar selects (ex: cmov).
112243830Sdim    ScalarCondVectorVal,  // The target supports selects with a scalar condition
113243830Sdim                          // and vector values (ex: cmov).
114243830Sdim    VectorMaskSelect      // The target supports vector selects with a vector
115243830Sdim                          // mask (ex: x86 blends).
116243830Sdim  };
117243830Sdim
118226633Sdim  static ISD::NodeType getExtendForContent(BooleanContent Content) {
119226633Sdim    switch (Content) {
120226633Sdim    case UndefinedBooleanContent:
121226633Sdim      // Extend by adding rubbish bits.
122226633Sdim      return ISD::ANY_EXTEND;
123226633Sdim    case ZeroOrOneBooleanContent:
124226633Sdim      // Extend by adding zero bits.
125226633Sdim      return ISD::ZERO_EXTEND;
126226633Sdim    case ZeroOrNegativeOneBooleanContent:
127226633Sdim      // Extend by copying the sign bit.
128226633Sdim      return ISD::SIGN_EXTEND;
129226633Sdim    }
130234353Sdim    llvm_unreachable("Invalid content kind");
131226633Sdim  }
132226633Sdim
133198090Srdivacky  /// NOTE: The constructor takes ownership of TLOF.
134249423Sdim  explicit TargetLoweringBase(const TargetMachine &TM,
135249423Sdim                              const TargetLoweringObjectFile *TLOF);
136249423Sdim  virtual ~TargetLoweringBase();
137193323Sed
138251662Sdimprotected:
139251662Sdim  /// \brief Initialize all of the actions to default values.
140251662Sdim  void initActions();
141251662Sdim
142251662Sdimpublic:
143207618Srdivacky  const TargetMachine &getTargetMachine() const { return TM; }
144243830Sdim  const DataLayout *getDataLayout() const { return TD; }
145207618Srdivacky  const TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; }
146193323Sed
147193323Sed  bool isBigEndian() const { return !IsLittleEndian; }
148193323Sed  bool isLittleEndian() const { return IsLittleEndian; }
149243830Sdim  // Return the pointer type for the given address space, defaults to
150243830Sdim  // the pointer type from the data layout.
151243830Sdim  // FIXME: The default needs to be removed once all the code is updated.
152243830Sdim  virtual MVT getPointerTy(uint32_t AS = 0) const { return PointerTy; }
153249423Sdim  virtual MVT getScalarShiftAmountTy(EVT LHSTy) const;
154193323Sed
155249423Sdim  EVT getShiftAmountTy(EVT LHSTy) const;
156249423Sdim
157193323Sed  /// isSelectExpensive - Return true if the select operation is expensive for
158193323Sed  /// this target.
159193323Sed  bool isSelectExpensive() const { return SelectIsExpensive; }
160210299Sed
161243830Sdim  virtual bool isSelectSupported(SelectSupportKind kind) const { return true; }
162243830Sdim
163249423Sdim  /// shouldSplitVectorElementType - Return true if a vector of the given type
164249423Sdim  /// should be split (TypeSplitVector) instead of promoted
165249423Sdim  /// (TypePromoteInteger) during type legalization.
166249423Sdim  virtual bool shouldSplitVectorElementType(EVT VT) const { return false; }
167249423Sdim
168193323Sed  /// isIntDivCheap() - Return true if integer divide is usually cheaper than
169193323Sed  /// a sequence of several shifts, adds, and multiplies for this target.
170193323Sed  bool isIntDivCheap() const { return IntDivIsCheap; }
171193323Sed
172243830Sdim  /// isSlowDivBypassed - Returns true if target has indicated at least one
173243830Sdim  /// type should be bypassed.
174243830Sdim  bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
175243830Sdim
176243830Sdim  /// getBypassSlowDivTypes - Returns map of slow types for division or
177243830Sdim  /// remainder with corresponding fast types
178243830Sdim  const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
179243830Sdim    return BypassSlowDivWidths;
180243830Sdim  }
181243830Sdim
182193323Sed  /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
183193323Sed  /// srl/add/sra.
184193323Sed  bool isPow2DivCheap() const { return Pow2DivIsCheap; }
185193323Sed
186218893Sdim  /// isJumpExpensive() - Return true if Flow Control is an expensive operation
187218893Sdim  /// that should be avoided.
188218893Sdim  bool isJumpExpensive() const { return JumpIsExpensive; }
189218893Sdim
190239462Sdim  /// isPredictableSelectExpensive - Return true if selects are only cheaper
191239462Sdim  /// than branches if the branch is unlikely to be predicted right.
192239462Sdim  bool isPredictableSelectExpensive() const {
193249423Sdim    return PredictableSelectIsExpensive;
194239462Sdim  }
195239462Sdim
196193323Sed  /// getSetCCResultType - Return the ValueType of the result of SETCC
197193323Sed  /// operations.  Also used to obtain the target's preferred type for
198193323Sed  /// the condition operand of SELECT and BRCOND nodes.  In the case of
199193323Sed  /// BRCOND the argument passed is MVT::Other since there are no other
200193323Sed  /// operands to get a type hint from.
201226633Sdim  virtual EVT getSetCCResultType(EVT VT) const;
202193323Sed
203210299Sed  /// getCmpLibcallReturnType - Return the ValueType for comparison
204201360Srdivacky  /// libcalls. Comparions libcalls include floating point comparion calls,
205201360Srdivacky  /// and Ordered/Unordered check calls on floating point numbers.
206210299Sed  virtual
207201360Srdivacky  MVT::SimpleValueType getCmpLibcallReturnType() const;
208201360Srdivacky
209193323Sed  /// getBooleanContents - For targets without i1 registers, this gives the
210193323Sed  /// nature of the high-bits of boolean values held in types wider than i1.
211193323Sed  /// "Boolean values" are special true/false values produced by nodes like
212193323Sed  /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
213193323Sed  /// Not to be confused with general values promoted from i1.
214226633Sdim  /// Some cpus distinguish between vectors of boolean and scalars; the isVec
215226633Sdim  /// parameter selects between the two kinds.  For example on X86 a scalar
216226633Sdim  /// boolean should be zero extended from i1, while the elements of a vector
217226633Sdim  /// of booleans should be sign extended from i1.
218226633Sdim  BooleanContent getBooleanContents(bool isVec) const {
219226633Sdim    return isVec ? BooleanVectorContents : BooleanContents;
220226633Sdim  }
221193323Sed
222193323Sed  /// getSchedulingPreference - Return target scheduling preference.
223208599Srdivacky  Sched::Preference getSchedulingPreference() const {
224193323Sed    return SchedPreferenceInfo;
225193323Sed  }
226193323Sed
227208599Srdivacky  /// getSchedulingPreference - Some scheduler, e.g. hybrid, can switch to
228208599Srdivacky  /// different scheduling heuristics for different nodes. This function returns
229208599Srdivacky  /// the preference (or none) for the given node.
230226633Sdim  virtual Sched::Preference getSchedulingPreference(SDNode *) const {
231208599Srdivacky    return Sched::None;
232208599Srdivacky  }
233208599Srdivacky
234193323Sed  /// getRegClassFor - Return the register class that should be used for the
235208599Srdivacky  /// specified value type.
236249423Sdim  virtual const TargetRegisterClass *getRegClassFor(MVT VT) const {
237249423Sdim    const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
238193323Sed    assert(RC && "This value type is not natively supported!");
239193323Sed    return RC;
240193323Sed  }
241193323Sed
242212904Sdim  /// getRepRegClassFor - Return the 'representative' register class for the
243212904Sdim  /// specified value type. The 'representative' register class is the largest
244212904Sdim  /// legal super-reg register class for the register class of the value type.
245212904Sdim  /// For example, on i386 the rep register class for i8, i16, and i32 are GR32;
246212904Sdim  /// while the rep register class is GR64 on x86_64.
247249423Sdim  virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
248249423Sdim    const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
249212904Sdim    return RC;
250212904Sdim  }
251212904Sdim
252212904Sdim  /// getRepRegClassCostFor - Return the cost of the 'representative' register
253212904Sdim  /// class for the specified value type.
254249423Sdim  virtual uint8_t getRepRegClassCostFor(MVT VT) const {
255249423Sdim    return RepRegClassCostForVT[VT.SimpleTy];
256212904Sdim  }
257212904Sdim
258193323Sed  /// isTypeLegal - Return true if the target has native support for the
259193323Sed  /// specified value type.  This means that it has a register that directly
260193323Sed  /// holds it without promotions or expansions.
261198090Srdivacky  bool isTypeLegal(EVT VT) const {
262193323Sed    assert(!VT.isSimple() ||
263198090Srdivacky           (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
264198090Srdivacky    return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != 0;
265193323Sed  }
266193323Sed
267193323Sed  class ValueTypeActionImpl {
268223017Sdim    /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
269208599Srdivacky    /// that indicates how instruction selection should deal with the type.
270208599Srdivacky    uint8_t ValueTypeActions[MVT::LAST_VALUETYPE];
271219077Sdim
272193323Sed  public:
273193323Sed    ValueTypeActionImpl() {
274207618Srdivacky      std::fill(ValueTypeActions, array_endof(ValueTypeActions), 0);
275193323Sed    }
276219077Sdim
277223017Sdim    LegalizeTypeAction getTypeAction(MVT VT) const {
278223017Sdim      return (LegalizeTypeAction)ValueTypeActions[VT.SimpleTy];
279193323Sed    }
280219077Sdim
281249423Sdim    void setTypeAction(MVT VT, LegalizeTypeAction Action) {
282249423Sdim      unsigned I = VT.SimpleTy;
283208599Srdivacky      ValueTypeActions[I] = Action;
284193323Sed    }
285193323Sed  };
286210299Sed
287193323Sed  const ValueTypeActionImpl &getValueTypeActions() const {
288193323Sed    return ValueTypeActions;
289193323Sed  }
290193323Sed
291193323Sed  /// getTypeAction - Return how we should legalize values of this type, either
292193323Sed  /// it is already legal (return 'Legal') or we need to promote it to a larger
293193323Sed  /// type (return 'Promote'), or we need to expand it into multiple registers
294193323Sed  /// of smaller integer type (return 'Expand').  'Custom' is not an option.
295223017Sdim  LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
296223017Sdim    return getTypeConversion(Context, VT).first;
297193323Sed  }
298223017Sdim  LegalizeTypeAction getTypeAction(MVT VT) const {
299212904Sdim    return ValueTypeActions.getTypeAction(VT);
300212904Sdim  }
301219077Sdim
302193323Sed  /// getTypeToTransformTo - For types supported by the target, this is an
303193323Sed  /// identity function.  For types that must be promoted to larger types, this
304193323Sed  /// returns the larger type to promote to.  For integer types that are larger
305193323Sed  /// than the largest integer register, this contains one step in the expansion
306193323Sed  /// to get to the smaller register. For illegal floating point types, this
307193323Sed  /// returns the integer type to transform to.
308198090Srdivacky  EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
309223017Sdim    return getTypeConversion(Context, VT).second;
310193323Sed  }
311193323Sed
312193323Sed  /// getTypeToExpandTo - For types supported by the target, this is an
313193323Sed  /// identity function.  For types that must be expanded (i.e. integer types
314193323Sed  /// that are larger than the largest integer register or illegal floating
315193323Sed  /// point types), this returns the largest legal type it will be expanded to.
316198090Srdivacky  EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
317193323Sed    assert(!VT.isVector());
318193323Sed    while (true) {
319223017Sdim      switch (getTypeAction(Context, VT)) {
320226633Sdim      case TypeLegal:
321193323Sed        return VT;
322226633Sdim      case TypeExpandInteger:
323198090Srdivacky        VT = getTypeToTransformTo(Context, VT);
324193323Sed        break;
325193323Sed      default:
326234353Sdim        llvm_unreachable("Type is not legal nor is it to be expanded!");
327193323Sed      }
328193323Sed    }
329193323Sed  }
330193323Sed
331193323Sed  /// getVectorTypeBreakdown - Vector types are broken down into some number of
332198090Srdivacky  /// legal first class types.  For example, EVT::v8f32 maps to 2 EVT::v4f32
333198090Srdivacky  /// with Altivec or SSE1, or 8 promoted EVT::f64 values with the X86 FP stack.
334198090Srdivacky  /// Similarly, EVT::v2i64 turns into 4 EVT::i32 values with both PPC and X86.
335193323Sed  ///
336193323Sed  /// This method returns the number of registers needed, and the VT for each
337193323Sed  /// register.  It also returns the VT and quantity of the intermediate values
338193323Sed  /// before they are promoted/expanded.
339193323Sed  ///
340198090Srdivacky  unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
341198090Srdivacky                                  EVT &IntermediateVT,
342193323Sed                                  unsigned &NumIntermediates,
343249423Sdim                                  MVT &RegisterVT) const;
344193323Sed
345193323Sed  /// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the
346193323Sed  /// intrinsic will need to map to a MemIntrinsicNode (touches memory). If
347193323Sed  /// this is the case, it returns true and store the intrinsic
348193323Sed  /// information into the IntrinsicInfo that was passed to the function.
349210299Sed  struct IntrinsicInfo {
350193323Sed    unsigned     opc;         // target opcode
351198090Srdivacky    EVT          memVT;       // memory VT
352193323Sed    const Value* ptrVal;      // value representing memory location
353210299Sed    int          offset;      // offset off of ptrVal
354193323Sed    unsigned     align;       // alignment
355193323Sed    bool         vol;         // is volatile?
356193323Sed    bool         readMem;     // reads memory?
357193323Sed    bool         writeMem;    // writes memory?
358205407Srdivacky  };
359193323Sed
360226633Sdim  virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
361226633Sdim                                  unsigned /*Intrinsic*/) const {
362193323Sed    return false;
363193323Sed  }
364193323Sed
365198892Srdivacky  /// isFPImmLegal - Returns true if the target can instruction select the
366198892Srdivacky  /// specified FP immediate natively. If false, the legalizer will materialize
367198892Srdivacky  /// the FP immediate as a load from a constant pool.
368226633Sdim  virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
369198892Srdivacky    return false;
370193323Sed  }
371210299Sed
372193323Sed  /// isShuffleMaskLegal - Targets can use this to indicate that they only
373193323Sed  /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
374193323Sed  /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
375193323Sed  /// are assumed to be legal.
376226633Sdim  virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
377226633Sdim                                  EVT /*VT*/) const {
378193323Sed    return true;
379193323Sed  }
380193323Sed
381203954Srdivacky  /// canOpTrap - Returns true if the operation can trap for the value type.
382203954Srdivacky  /// VT must be a legal type. By default, we optimistically assume most
383203954Srdivacky  /// operations don't trap except for divide and remainder.
384203954Srdivacky  virtual bool canOpTrap(unsigned Op, EVT VT) const;
385203954Srdivacky
386193323Sed  /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
387193323Sed  /// used by Targets can use this to indicate if there is a suitable
388193323Sed  /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
389193323Sed  /// pool entry.
390226633Sdim  virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
391226633Sdim                                      EVT /*VT*/) const {
392193323Sed    return false;
393193323Sed  }
394193323Sed
395193323Sed  /// getOperationAction - Return how this operation should be treated: either
396193323Sed  /// it is legal, needs to be promoted to a larger size, needs to be
397193323Sed  /// expanded to some other code sequence, or the target has a custom expander
398193323Sed  /// for it.
399198090Srdivacky  LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
400193323Sed    if (VT.isExtended()) return Expand;
401239462Sdim    // If a target-specific SDNode requires legalization, require the target
402239462Sdim    // to provide custom legalization for it.
403239462Sdim    if (Op > array_lengthof(OpActions[0])) return Custom;
404198090Srdivacky    unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
405208599Srdivacky    return (LegalizeAction)OpActions[I][Op];
406193323Sed  }
407193323Sed
408193323Sed  /// isOperationLegalOrCustom - Return true if the specified operation is
409193323Sed  /// legal on this target or can be made legal with custom lowering. This
410193323Sed  /// is used to help guide high-level lowering decisions.
411198090Srdivacky  bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
412193323Sed    return (VT == MVT::Other || isTypeLegal(VT)) &&
413193323Sed      (getOperationAction(Op, VT) == Legal ||
414193323Sed       getOperationAction(Op, VT) == Custom);
415193323Sed  }
416193323Sed
417249423Sdim  /// isOperationLegalOrPromote - Return true if the specified operation is
418249423Sdim  /// legal on this target or can be made legal using promotion. This
419249423Sdim  /// is used to help guide high-level lowering decisions.
420249423Sdim  bool isOperationLegalOrPromote(unsigned Op, EVT VT) const {
421249423Sdim    return (VT == MVT::Other || isTypeLegal(VT)) &&
422249423Sdim      (getOperationAction(Op, VT) == Legal ||
423249423Sdim       getOperationAction(Op, VT) == Promote);
424249423Sdim  }
425249423Sdim
426243830Sdim  /// isOperationExpand - Return true if the specified operation is illegal on
427243830Sdim  /// this target or unlikely to be made legal with custom lowering. This is
428243830Sdim  /// used to help guide high-level lowering decisions.
429243830Sdim  bool isOperationExpand(unsigned Op, EVT VT) const {
430243830Sdim    return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
431243830Sdim  }
432243830Sdim
433193323Sed  /// isOperationLegal - Return true if the specified operation is legal on this
434193323Sed  /// target.
435198090Srdivacky  bool isOperationLegal(unsigned Op, EVT VT) const {
436193323Sed    return (VT == MVT::Other || isTypeLegal(VT)) &&
437193323Sed           getOperationAction(Op, VT) == Legal;
438193323Sed  }
439193323Sed
440193323Sed  /// getLoadExtAction - Return how this load with extension should be treated:
441193323Sed  /// either it is legal, needs to be promoted to a larger size, needs to be
442193323Sed  /// expanded to some other code sequence, or the target has a custom expander
443193323Sed  /// for it.
444249423Sdim  LegalizeAction getLoadExtAction(unsigned ExtType, MVT VT) const {
445249423Sdim    assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
446193323Sed           "Table isn't big enough!");
447249423Sdim    return (LegalizeAction)LoadExtActions[VT.SimpleTy][ExtType];
448193323Sed  }
449193323Sed
450193323Sed  /// isLoadExtLegal - Return true if the specified load with extension is legal
451193323Sed  /// on this target.
452208599Srdivacky  bool isLoadExtLegal(unsigned ExtType, EVT VT) const {
453249423Sdim    return VT.isSimple() &&
454249423Sdim      getLoadExtAction(ExtType, VT.getSimpleVT()) == Legal;
455193323Sed  }
456193323Sed
457193323Sed  /// getTruncStoreAction - Return how this store with truncation should be
458193323Sed  /// treated: either it is legal, needs to be promoted to a larger size, needs
459193323Sed  /// to be expanded to some other code sequence, or the target has a custom
460193323Sed  /// expander for it.
461249423Sdim  LegalizeAction getTruncStoreAction(MVT ValVT, MVT MemVT) const {
462249423Sdim    assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
463193323Sed           "Table isn't big enough!");
464249423Sdim    return (LegalizeAction)TruncStoreActions[ValVT.SimpleTy]
465249423Sdim                                            [MemVT.SimpleTy];
466193323Sed  }
467193323Sed
468193323Sed  /// isTruncStoreLegal - Return true if the specified store with truncation is
469193323Sed  /// legal on this target.
470198090Srdivacky  bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
471193323Sed    return isTypeLegal(ValVT) && MemVT.isSimple() &&
472249423Sdim      getTruncStoreAction(ValVT.getSimpleVT(), MemVT.getSimpleVT()) == Legal;
473193323Sed  }
474193323Sed
475193323Sed  /// getIndexedLoadAction - Return how the indexed load should be treated:
476193323Sed  /// either it is legal, needs to be promoted to a larger size, needs to be
477193323Sed  /// expanded to some other code sequence, or the target has a custom expander
478193323Sed  /// for it.
479193323Sed  LegalizeAction
480249423Sdim  getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
481249423Sdim    assert(IdxMode < ISD::LAST_INDEXED_MODE && VT < MVT::LAST_VALUETYPE &&
482193323Sed           "Table isn't big enough!");
483249423Sdim    unsigned Ty = (unsigned)VT.SimpleTy;
484208599Srdivacky    return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
485193323Sed  }
486193323Sed
487193323Sed  /// isIndexedLoadLegal - Return true if the specified indexed load is legal
488193323Sed  /// on this target.
489198090Srdivacky  bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
490193323Sed    return VT.isSimple() &&
491249423Sdim      (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
492249423Sdim       getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
493193323Sed  }
494193323Sed
495193323Sed  /// getIndexedStoreAction - Return how the indexed store should be treated:
496193323Sed  /// either it is legal, needs to be promoted to a larger size, needs to be
497193323Sed  /// expanded to some other code sequence, or the target has a custom expander
498193323Sed  /// for it.
499193323Sed  LegalizeAction
500249423Sdim  getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
501249423Sdim    assert(IdxMode < ISD::LAST_INDEXED_MODE && VT < MVT::LAST_VALUETYPE &&
502193323Sed           "Table isn't big enough!");
503249423Sdim    unsigned Ty = (unsigned)VT.SimpleTy;
504208599Srdivacky    return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
505210299Sed  }
506193323Sed
507193323Sed  /// isIndexedStoreLegal - Return true if the specified indexed load is legal
508193323Sed  /// on this target.
509198090Srdivacky  bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
510193323Sed    return VT.isSimple() &&
511249423Sdim      (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
512249423Sdim       getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
513193323Sed  }
514193323Sed
515193323Sed  /// getCondCodeAction - Return how the condition code should be treated:
516193323Sed  /// either it is legal, needs to be expanded to some other code sequence,
517193323Sed  /// or the target has a custom expander for it.
518193323Sed  LegalizeAction
519249423Sdim  getCondCodeAction(ISD::CondCode CC, MVT VT) const {
520193323Sed    assert((unsigned)CC < array_lengthof(CondCodeActions) &&
521249423Sdim           (unsigned)VT.SimpleTy < sizeof(CondCodeActions[0])*4 &&
522193323Sed           "Table isn't big enough!");
523243830Sdim    /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 64bit
524243830Sdim    /// value and the upper 27 bits index into the second dimension of the
525243830Sdim    /// array to select what 64bit value to use.
526193323Sed    LegalizeAction Action = (LegalizeAction)
527249423Sdim      ((CondCodeActions[CC][VT.SimpleTy >> 5] >> (2*(VT.SimpleTy & 0x1F))) & 3);
528193323Sed    assert(Action != Promote && "Can't promote condition code!");
529193323Sed    return Action;
530193323Sed  }
531193323Sed
532193323Sed  /// isCondCodeLegal - Return true if the specified condition code is legal
533193323Sed  /// on this target.
534249423Sdim  bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
535249423Sdim    return
536249423Sdim      getCondCodeAction(CC, VT) == Legal ||
537249423Sdim      getCondCodeAction(CC, VT) == Custom;
538193323Sed  }
539193323Sed
540193323Sed
541193323Sed  /// getTypeToPromoteTo - If the action for this operation is to promote, this
542193323Sed  /// method returns the ValueType to promote to.
543249423Sdim  MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
544193323Sed    assert(getOperationAction(Op, VT) == Promote &&
545193323Sed           "This operation isn't promoted!");
546193323Sed
547193323Sed    // See if this has an explicit type specified.
548193323Sed    std::map<std::pair<unsigned, MVT::SimpleValueType>,
549193323Sed             MVT::SimpleValueType>::const_iterator PTTI =
550249423Sdim      PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
551193323Sed    if (PTTI != PromoteToType.end()) return PTTI->second;
552193323Sed
553193323Sed    assert((VT.isInteger() || VT.isFloatingPoint()) &&
554193323Sed           "Cannot autopromote this type, add it with AddPromotedToType.");
555210299Sed
556249423Sdim    MVT NVT = VT;
557193323Sed    do {
558249423Sdim      NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
559193323Sed      assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
560193323Sed             "Didn't find type to promote to!");
561193323Sed    } while (!isTypeLegal(NVT) ||
562193323Sed              getOperationAction(Op, NVT) == Promote);
563193323Sed    return NVT;
564193323Sed  }
565193323Sed
566198090Srdivacky  /// getValueType - Return the EVT corresponding to this LLVM type.
567193323Sed  /// This is fixed by the LLVM operations except for the pointer size.  If
568198090Srdivacky  /// AllowUnknown is true, this will return MVT::Other for types with no EVT
569193323Sed  /// counterpart (e.g. structs), otherwise it will assert.
570226633Sdim  EVT getValueType(Type *Ty, bool AllowUnknown = false) const {
571234353Sdim    // Lower scalar pointers to native pointer types.
572234353Sdim    if (Ty->isPointerTy()) return PointerTy;
573234353Sdim
574234353Sdim    if (Ty->isVectorTy()) {
575234353Sdim      VectorType *VTy = cast<VectorType>(Ty);
576234353Sdim      Type *Elm = VTy->getElementType();
577234353Sdim      // Lower vectors of pointers to native pointer types.
578234353Sdim      if (Elm->isPointerTy())
579234353Sdim        Elm = EVT(PointerTy).getTypeForEVT(Ty->getContext());
580234353Sdim      return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
581234353Sdim                       VTy->getNumElements());
582234353Sdim    }
583234353Sdim    return EVT::getEVT(Ty, AllowUnknown);
584193323Sed  }
585193323Sed
586249423Sdim  /// Return the MVT corresponding to this LLVM type. See getValueType.
587249423Sdim  MVT getSimpleValueType(Type *Ty, bool AllowUnknown = false) const {
588249423Sdim    return getValueType(Ty, AllowUnknown).getSimpleVT();
589249423Sdim  }
590249423Sdim
591193323Sed  /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
592193323Sed  /// function arguments in the caller parameter area.  This is the actual
593193323Sed  /// alignment, not its logarithm.
594226633Sdim  virtual unsigned getByValTypeAlignment(Type *Ty) const;
595210299Sed
596193323Sed  /// getRegisterType - Return the type of registers that this ValueType will
597193323Sed  /// eventually require.
598249423Sdim  MVT getRegisterType(MVT VT) const {
599198090Srdivacky    assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
600198090Srdivacky    return RegisterTypeForVT[VT.SimpleTy];
601198090Srdivacky  }
602210299Sed
603198090Srdivacky  /// getRegisterType - Return the type of registers that this ValueType will
604198090Srdivacky  /// eventually require.
605249423Sdim  MVT getRegisterType(LLVMContext &Context, EVT VT) const {
606193323Sed    if (VT.isSimple()) {
607198090Srdivacky      assert((unsigned)VT.getSimpleVT().SimpleTy <
608198090Srdivacky                array_lengthof(RegisterTypeForVT));
609198090Srdivacky      return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
610193323Sed    }
611193323Sed    if (VT.isVector()) {
612249423Sdim      EVT VT1;
613249423Sdim      MVT RegisterVT;
614193323Sed      unsigned NumIntermediates;
615198090Srdivacky      (void)getVectorTypeBreakdown(Context, VT, VT1,
616198090Srdivacky                                   NumIntermediates, RegisterVT);
617193323Sed      return RegisterVT;
618193323Sed    }
619193323Sed    if (VT.isInteger()) {
620198090Srdivacky      return getRegisterType(Context, getTypeToTransformTo(Context, VT));
621193323Sed    }
622234353Sdim    llvm_unreachable("Unsupported extended type!");
623193323Sed  }
624193323Sed
625193323Sed  /// getNumRegisters - Return the number of registers that this ValueType will
626193323Sed  /// eventually require.  This is one for any types promoted to live in larger
627193323Sed  /// registers, but may be more than one for types (like i64) that are split
628193323Sed  /// into pieces.  For types like i140, which are first promoted then expanded,
629193323Sed  /// it is the number of registers needed to hold all the bits of the original
630193323Sed  /// type.  For an i140 on a 32 bit machine this means 5 registers.
631198090Srdivacky  unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
632193323Sed    if (VT.isSimple()) {
633198090Srdivacky      assert((unsigned)VT.getSimpleVT().SimpleTy <
634198090Srdivacky                array_lengthof(NumRegistersForVT));
635198090Srdivacky      return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
636193323Sed    }
637193323Sed    if (VT.isVector()) {
638249423Sdim      EVT VT1;
639249423Sdim      MVT VT2;
640193323Sed      unsigned NumIntermediates;
641198090Srdivacky      return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
642193323Sed    }
643193323Sed    if (VT.isInteger()) {
644193323Sed      unsigned BitWidth = VT.getSizeInBits();
645198090Srdivacky      unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
646193323Sed      return (BitWidth + RegWidth - 1) / RegWidth;
647193323Sed    }
648234353Sdim    llvm_unreachable("Unsupported extended type!");
649193323Sed  }
650193323Sed
651193323Sed  /// ShouldShrinkFPConstant - If true, then instruction selection should
652193323Sed  /// seek to shrink the FP constant of the specified type to a smaller type
653193323Sed  /// in order to save space and / or reduce runtime.
654226633Sdim  virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
655193323Sed
656193323Sed  /// hasTargetDAGCombine - If true, the target has custom DAG combine
657193323Sed  /// transformations that it can perform for the specified node.
658193323Sed  bool hasTargetDAGCombine(ISD::NodeType NT) const {
659193323Sed    assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
660193323Sed    return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
661193323Sed  }
662193323Sed
663193323Sed  /// This function returns the maximum number of store operations permitted
664193323Sed  /// to replace a call to llvm.memset. The value is set by the target at the
665218893Sdim  /// performance threshold for such a replacement. If OptSize is true,
666218893Sdim  /// return the limit for functions that have OptSize attribute.
667193323Sed  /// @brief Get maximum # of store operations permitted for llvm.memset
668218893Sdim  unsigned getMaxStoresPerMemset(bool OptSize) const {
669249423Sdim    return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
670218893Sdim  }
671193323Sed
672193323Sed  /// This function returns the maximum number of store operations permitted
673193323Sed  /// to replace a call to llvm.memcpy. The value is set by the target at the
674218893Sdim  /// performance threshold for such a replacement. If OptSize is true,
675218893Sdim  /// return the limit for functions that have OptSize attribute.
676193323Sed  /// @brief Get maximum # of store operations permitted for llvm.memcpy
677218893Sdim  unsigned getMaxStoresPerMemcpy(bool OptSize) const {
678249423Sdim    return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
679218893Sdim  }
680193323Sed
681193323Sed  /// This function returns the maximum number of store operations permitted
682193323Sed  /// to replace a call to llvm.memmove. The value is set by the target at the
683218893Sdim  /// performance threshold for such a replacement. If OptSize is true,
684218893Sdim  /// return the limit for functions that have OptSize attribute.
685193323Sed  /// @brief Get maximum # of store operations permitted for llvm.memmove
686218893Sdim  unsigned getMaxStoresPerMemmove(bool OptSize) const {
687249423Sdim    return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
688218893Sdim  }
689193323Sed
690193323Sed  /// This function returns true if the target allows unaligned memory accesses.
691249423Sdim  /// of the specified type. If true, it also returns whether the unaligned
692249423Sdim  /// memory access is "fast" in the second argument by reference. This is used,
693249423Sdim  /// for example, in situations where an array copy/move/set is  converted to a
694249423Sdim  /// sequence of store operations. It's use helps to ensure that such
695249423Sdim  /// replacements don't generate code that causes an alignment error  (trap) on
696249423Sdim  /// the target machine.
697193323Sed  /// @brief Determine if the target supports unaligned memory accesses.
698249423Sdim  virtual bool allowsUnalignedMemoryAccesses(EVT, bool *Fast = 0) const {
699198090Srdivacky    return false;
700193323Sed  }
701193323Sed
702193323Sed  /// getOptimalMemOpType - Returns the target specific optimal type for load
703206124Srdivacky  /// and store operations as a result of memset, memcpy, and memmove
704206124Srdivacky  /// lowering. If DstAlign is zero that means it's safe to destination
705206124Srdivacky  /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
706206124Srdivacky  /// means there isn't a need to check it against alignment requirement,
707249423Sdim  /// probably because the source does not need to be loaded. If 'IsMemset' is
708249423Sdim  /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
709249423Sdim  /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
710249423Sdim  /// source is constant so it does not need to be loaded.
711207618Srdivacky  /// It returns EVT::Other if the type should be determined using generic
712207618Srdivacky  /// target-independent logic.
713226633Sdim  virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
714226633Sdim                                  unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
715249423Sdim                                  bool /*IsMemset*/,
716249423Sdim                                  bool /*ZeroMemset*/,
717226633Sdim                                  bool /*MemcpyStrSrc*/,
718226633Sdim                                  MachineFunction &/*MF*/) const {
719204961Srdivacky    return MVT::Other;
720193323Sed  }
721210299Sed
722249423Sdim  /// isSafeMemOpType - Returns true if it's safe to use load / store of the
723249423Sdim  /// specified type to expand memcpy / memset inline. This is mostly true
724249423Sdim  /// for all types except for some special cases. For example, on X86
725249423Sdim  /// targets without SSE2 f64 load / store are done with fldl / fstpl which
726249423Sdim  /// also does type conversion. Note the specified type doesn't have to be
727249423Sdim  /// legal as the hook is used before type legalization.
728249423Sdim  virtual bool isSafeMemOpType(MVT VT) const {
729249423Sdim    return true;
730249423Sdim  }
731249423Sdim
732193323Sed  /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
733193323Sed  /// to implement llvm.setjmp.
734193323Sed  bool usesUnderscoreSetJmp() const {
735193323Sed    return UseUnderscoreSetJmp;
736193323Sed  }
737193323Sed
738193323Sed  /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
739193323Sed  /// to implement llvm.longjmp.
740193323Sed  bool usesUnderscoreLongJmp() const {
741193323Sed    return UseUnderscoreLongJmp;
742193323Sed  }
743193323Sed
744239462Sdim  /// supportJumpTables - return whether the target can generate code for
745239462Sdim  /// jump tables.
746239462Sdim  bool supportJumpTables() const {
747239462Sdim    return SupportJumpTables;
748239462Sdim  }
749239462Sdim
750243830Sdim  /// getMinimumJumpTableEntries - return integer threshold on number of
751243830Sdim  /// blocks to use jump tables rather than if sequence.
752243830Sdim  int getMinimumJumpTableEntries() const {
753243830Sdim    return MinimumJumpTableEntries;
754243830Sdim  }
755243830Sdim
756193323Sed  /// getStackPointerRegisterToSaveRestore - If a physical register, this
757193323Sed  /// specifies the register that llvm.savestack/llvm.restorestack should save
758193323Sed  /// and restore.
759193323Sed  unsigned getStackPointerRegisterToSaveRestore() const {
760193323Sed    return StackPointerRegisterToSaveRestore;
761193323Sed  }
762193323Sed
763234353Sdim  /// getExceptionPointerRegister - If a physical register, this returns
764193323Sed  /// the register that receives the exception address on entry to a landing
765193323Sed  /// pad.
766234353Sdim  unsigned getExceptionPointerRegister() const {
767193323Sed    return ExceptionPointerRegister;
768193323Sed  }
769193323Sed
770193323Sed  /// getExceptionSelectorRegister - If a physical register, this returns
771193323Sed  /// the register that receives the exception typeid on entry to a landing
772193323Sed  /// pad.
773193323Sed  unsigned getExceptionSelectorRegister() const {
774193323Sed    return ExceptionSelectorRegister;
775193323Sed  }
776193323Sed
777193323Sed  /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
778193323Sed  /// set, the default is 200)
779193323Sed  unsigned getJumpBufSize() const {
780193323Sed    return JumpBufSize;
781193323Sed  }
782193323Sed
783193323Sed  /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
784193323Sed  /// (if never set, the default is 0)
785193323Sed  unsigned getJumpBufAlignment() const {
786193323Sed    return JumpBufAlignment;
787193323Sed  }
788193323Sed
789210299Sed  /// getMinStackArgumentAlignment - return the minimum stack alignment of an
790210299Sed  /// argument.
791210299Sed  unsigned getMinStackArgumentAlignment() const {
792210299Sed    return MinStackArgumentAlignment;
793193323Sed  }
794193323Sed
795223017Sdim  /// getMinFunctionAlignment - return the minimum function alignment.
796223017Sdim  ///
797223017Sdim  unsigned getMinFunctionAlignment() const {
798223017Sdim    return MinFunctionAlignment;
799223017Sdim  }
800223017Sdim
801223017Sdim  /// getPrefFunctionAlignment - return the preferred function alignment.
802223017Sdim  ///
803223017Sdim  unsigned getPrefFunctionAlignment() const {
804223017Sdim    return PrefFunctionAlignment;
805223017Sdim  }
806223017Sdim
807193323Sed  /// getPrefLoopAlignment - return the preferred loop alignment.
808193323Sed  ///
809193323Sed  unsigned getPrefLoopAlignment() const {
810193323Sed    return PrefLoopAlignment;
811193323Sed  }
812210299Sed
813226633Sdim  /// getInsertFencesFor - return whether the DAG builder should automatically
814226633Sdim  /// insert fences and reduce ordering for atomics.
815226633Sdim  ///
816226633Sdim  bool getInsertFencesForAtomic() const {
817226633Sdim    return InsertFencesForAtomic;
818226633Sdim  }
819226633Sdim
820210299Sed  /// getStackCookieLocation - Return true if the target stores stack
821210299Sed  /// protector cookies at a fixed offset in some non-standard address
822210299Sed  /// space, and populates the address space and offset as
823210299Sed  /// appropriate.
824226633Sdim  virtual bool getStackCookieLocation(unsigned &/*AddressSpace*/,
825226633Sdim                                      unsigned &/*Offset*/) const {
826210299Sed    return false;
827210299Sed  }
828210299Sed
829212904Sdim  /// getMaximalGlobalOffset - Returns the maximal possible offset which can be
830212904Sdim  /// used for loads / stores from the global.
831212904Sdim  virtual unsigned getMaximalGlobalOffset() const {
832212904Sdim    return 0;
833212904Sdim  }
834212904Sdim
835193323Sed  //===--------------------------------------------------------------------===//
836249423Sdim  /// \name Helpers for TargetTransformInfo implementations
837249423Sdim  /// @{
838210299Sed
839249423Sdim  /// Get the ISD node that corresponds to the Instruction class opcode.
840249423Sdim  int InstructionOpcodeToISD(unsigned Opcode) const;
841193323Sed
842249423Sdim  /// Estimate the cost of type-legalization and the legalized type.
843249423Sdim  std::pair<unsigned, MVT> getTypeLegalizationCost(Type *Ty) const;
844207618Srdivacky
845249423Sdim  /// @}
846210299Sed
847193323Sed  //===--------------------------------------------------------------------===//
848193323Sed  // TargetLowering Configuration Methods - These methods should be invoked by
849193323Sed  // the derived class constructor to configure this object for the target.
850193323Sed  //
851193323Sed
852251662Sdim  /// \brief Reset the operation actions based on target options.
853251662Sdim  virtual void resetOperationActions() {}
854251662Sdim
855193323Sedprotected:
856193323Sed  /// setBooleanContents - Specify how the target extends the result of a
857193323Sed  /// boolean value from i1 to a wider type.  See getBooleanContents.
858193323Sed  void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
859226633Sdim  /// setBooleanVectorContents - Specify how the target extends the result
860226633Sdim  /// of a vector boolean value from a vector of i1 to a wider type.  See
861226633Sdim  /// getBooleanContents.
862226633Sdim  void setBooleanVectorContents(BooleanContent Ty) {
863226633Sdim    BooleanVectorContents = Ty;
864226633Sdim  }
865193323Sed
866193323Sed  /// setSchedulingPreference - Specify the target scheduling preference.
867208599Srdivacky  void setSchedulingPreference(Sched::Preference Pref) {
868193323Sed    SchedPreferenceInfo = Pref;
869193323Sed  }
870193323Sed
871193323Sed  /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
872193323Sed  /// use _setjmp to implement llvm.setjmp or the non _ version.
873193323Sed  /// Defaults to false.
874193323Sed  void setUseUnderscoreSetJmp(bool Val) {
875193323Sed    UseUnderscoreSetJmp = Val;
876193323Sed  }
877193323Sed
878193323Sed  /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
879193323Sed  /// use _longjmp to implement llvm.longjmp or the non _ version.
880193323Sed  /// Defaults to false.
881193323Sed  void setUseUnderscoreLongJmp(bool Val) {
882193323Sed    UseUnderscoreLongJmp = Val;
883193323Sed  }
884193323Sed
885239462Sdim  /// setSupportJumpTables - Indicate whether the target can generate code for
886239462Sdim  /// jump tables.
887239462Sdim  void setSupportJumpTables(bool Val) {
888239462Sdim    SupportJumpTables = Val;
889239462Sdim  }
890239462Sdim
891243830Sdim  /// setMinimumJumpTableEntries - Indicate the number of blocks to generate
892243830Sdim  /// jump tables rather than if sequence.
893243830Sdim  void setMinimumJumpTableEntries(int Val) {
894243830Sdim    MinimumJumpTableEntries = Val;
895243830Sdim  }
896243830Sdim
897193323Sed  /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
898193323Sed  /// specifies the register that llvm.savestack/llvm.restorestack should save
899193323Sed  /// and restore.
900193323Sed  void setStackPointerRegisterToSaveRestore(unsigned R) {
901193323Sed    StackPointerRegisterToSaveRestore = R;
902193323Sed  }
903210299Sed
904193323Sed  /// setExceptionPointerRegister - If set to a physical register, this sets
905193323Sed  /// the register that receives the exception address on entry to a landing
906193323Sed  /// pad.
907193323Sed  void setExceptionPointerRegister(unsigned R) {
908193323Sed    ExceptionPointerRegister = R;
909193323Sed  }
910193323Sed
911193323Sed  /// setExceptionSelectorRegister - If set to a physical register, this sets
912193323Sed  /// the register that receives the exception typeid on entry to a landing
913193323Sed  /// pad.
914193323Sed  void setExceptionSelectorRegister(unsigned R) {
915193323Sed    ExceptionSelectorRegister = R;
916193323Sed  }
917193323Sed
918193323Sed  /// SelectIsExpensive - Tells the code generator not to expand operations
919193323Sed  /// into sequences that use the select operations if possible.
920219077Sdim  void setSelectIsExpensive(bool isExpensive = true) {
921219077Sdim    SelectIsExpensive = isExpensive;
922218893Sdim  }
923193323Sed
924219077Sdim  /// JumpIsExpensive - Tells the code generator not to expand sequence of
925221345Sdim  /// operations into a separate sequences that increases the amount of
926218893Sdim  /// flow control.
927218893Sdim  void setJumpIsExpensive(bool isExpensive = true) {
928218893Sdim    JumpIsExpensive = isExpensive;
929218893Sdim  }
930218893Sdim
931193323Sed  /// setIntDivIsCheap - Tells the code generator that integer divide is
932193323Sed  /// expensive, and if possible, should be replaced by an alternate sequence
933193323Sed  /// of instructions not containing an integer divide.
934193323Sed  void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
935210299Sed
936243830Sdim  /// addBypassSlowDiv - Tells the code generator which bitwidths to bypass.
937243830Sdim  void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
938243830Sdim    BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
939243830Sdim  }
940243830Sdim
941193323Sed  /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
942193323Sed  /// srl/add/sra for a signed divide by power of two, and let the target handle
943193323Sed  /// it.
944193323Sed  void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
945210299Sed
946193323Sed  /// addRegisterClass - Add the specified register class as an available
947193323Sed  /// regclass for the specified value type.  This indicates the selector can
948193323Sed  /// handle values of that class natively.
949249423Sdim  void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
950249423Sdim    assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
951193323Sed    AvailableRegClasses.push_back(std::make_pair(VT, RC));
952249423Sdim    RegClassForVT[VT.SimpleTy] = RC;
953193323Sed  }
954193323Sed
955251662Sdim  /// clearRegisterClasses - Remove all register classes.
956249423Sdim  void clearRegisterClasses() {
957251662Sdim    memset(RegClassForVT, 0,MVT::LAST_VALUETYPE * sizeof(TargetRegisterClass*));
958251662Sdim
959249423Sdim    AvailableRegClasses.clear();
960249423Sdim  }
961249423Sdim
962251662Sdim  /// \brief Remove all operation actions.
963251662Sdim  void clearOperationActions() {
964251662Sdim  }
965251662Sdim
966212904Sdim  /// findRepresentativeClass - Return the largest legal super-reg register class
967212904Sdim  /// of the register class for the specified type and its associated "cost".
968212904Sdim  virtual std::pair<const TargetRegisterClass*, uint8_t>
969249423Sdim  findRepresentativeClass(MVT VT) const;
970212904Sdim
971193323Sed  /// computeRegisterProperties - Once all of the register classes are added,
972193323Sed  /// this allows us to compute derived properties we expose.
973193323Sed  void computeRegisterProperties();
974193323Sed
975193323Sed  /// setOperationAction - Indicate that the specified operation does not work
976193323Sed  /// with the specified type and indicate what to do about it.
977193323Sed  void setOperationAction(unsigned Op, MVT VT,
978193323Sed                          LegalizeAction Action) {
979208599Srdivacky    assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
980208599Srdivacky    OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action;
981193323Sed  }
982210299Sed
983193323Sed  /// setLoadExtAction - Indicate that the specified load with extension does
984206083Srdivacky  /// not work with the specified type and indicate what to do about it.
985193323Sed  void setLoadExtAction(unsigned ExtType, MVT VT,
986208599Srdivacky                        LegalizeAction Action) {
987218893Sdim    assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
988193323Sed           "Table isn't big enough!");
989208599Srdivacky    LoadExtActions[VT.SimpleTy][ExtType] = (uint8_t)Action;
990193323Sed  }
991210299Sed
992193323Sed  /// setTruncStoreAction - Indicate that the specified truncating store does
993206083Srdivacky  /// not work with the specified type and indicate what to do about it.
994193323Sed  void setTruncStoreAction(MVT ValVT, MVT MemVT,
995193323Sed                           LegalizeAction Action) {
996218893Sdim    assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
997193323Sed           "Table isn't big enough!");
998208599Srdivacky    TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action;
999193323Sed  }
1000193323Sed
1001193323Sed  /// setIndexedLoadAction - Indicate that the specified indexed load does or
1002206083Srdivacky  /// does not work with the specified type and indicate what to do abort
1003193323Sed  /// it. NOTE: All indexed mode loads are initialized to Expand in
1004193323Sed  /// TargetLowering.cpp
1005193323Sed  void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1006193323Sed                            LegalizeAction Action) {
1007218893Sdim    assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1008218893Sdim           (unsigned)Action < 0xf && "Table isn't big enough!");
1009208599Srdivacky    // Load action are kept in the upper half.
1010208599Srdivacky    IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1011208599Srdivacky    IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1012193323Sed  }
1013210299Sed
1014193323Sed  /// setIndexedStoreAction - Indicate that the specified indexed store does or
1015206083Srdivacky  /// does not work with the specified type and indicate what to do about
1016193323Sed  /// it. NOTE: All indexed mode stores are initialized to Expand in
1017193323Sed  /// TargetLowering.cpp
1018193323Sed  void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1019193323Sed                             LegalizeAction Action) {
1020218893Sdim    assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1021218893Sdim           (unsigned)Action < 0xf && "Table isn't big enough!");
1022208599Srdivacky    // Store action are kept in the lower half.
1023208599Srdivacky    IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1024208599Srdivacky    IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1025193323Sed  }
1026210299Sed
1027193323Sed  /// setCondCodeAction - Indicate that the specified condition code is or isn't
1028193323Sed  /// supported on the target and indicate what to do about it.
1029198090Srdivacky  void setCondCodeAction(ISD::CondCode CC, MVT VT,
1030198090Srdivacky                         LegalizeAction Action) {
1031218893Sdim    assert(VT < MVT::LAST_VALUETYPE &&
1032193323Sed           (unsigned)CC < array_lengthof(CondCodeActions) &&
1033193323Sed           "Table isn't big enough!");
1034243830Sdim    /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 64bit
1035243830Sdim    /// value and the upper 27 bits index into the second dimension of the
1036243830Sdim    /// array to select what 64bit value to use.
1037243830Sdim    CondCodeActions[(unsigned)CC][VT.SimpleTy >> 5]
1038243830Sdim      &= ~(uint64_t(3UL)  << (VT.SimpleTy & 0x1F)*2);
1039243830Sdim    CondCodeActions[(unsigned)CC][VT.SimpleTy >> 5]
1040243830Sdim      |= (uint64_t)Action << (VT.SimpleTy & 0x1F)*2;
1041193323Sed  }
1042193323Sed
1043193323Sed  /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
1044193323Sed  /// promotion code defaults to trying a larger integer/fp until it can find
1045193323Sed  /// one that works.  If that default is insufficient, this method can be used
1046193323Sed  /// by the target to override the default.
1047193323Sed  void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1048198090Srdivacky    PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1049193323Sed  }
1050193323Sed
1051193323Sed  /// setTargetDAGCombine - Targets should invoke this method for each target
1052193323Sed  /// independent node that they want to provide a custom DAG combiner for by
1053193323Sed  /// implementing the PerformDAGCombine virtual method.
1054193323Sed  void setTargetDAGCombine(ISD::NodeType NT) {
1055193323Sed    assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1056193323Sed    TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1057193323Sed  }
1058210299Sed
1059193323Sed  /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
1060193323Sed  /// bytes); default is 200
1061193323Sed  void setJumpBufSize(unsigned Size) {
1062193323Sed    JumpBufSize = Size;
1063193323Sed  }
1064193323Sed
1065193323Sed  /// setJumpBufAlignment - Set the target's required jmp_buf buffer
1066193323Sed  /// alignment (in bytes); default is 0
1067193323Sed  void setJumpBufAlignment(unsigned Align) {
1068193323Sed    JumpBufAlignment = Align;
1069193323Sed  }
1070193323Sed
1071234353Sdim  /// setMinFunctionAlignment - Set the target's minimum function alignment (in
1072234353Sdim  /// log2(bytes))
1073223017Sdim  void setMinFunctionAlignment(unsigned Align) {
1074223017Sdim    MinFunctionAlignment = Align;
1075223017Sdim  }
1076223017Sdim
1077223017Sdim  /// setPrefFunctionAlignment - Set the target's preferred function alignment.
1078223017Sdim  /// This should be set if there is a performance benefit to
1079234353Sdim  /// higher-than-minimum alignment (in log2(bytes))
1080223017Sdim  void setPrefFunctionAlignment(unsigned Align) {
1081223017Sdim    PrefFunctionAlignment = Align;
1082223017Sdim  }
1083223017Sdim
1084193323Sed  /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
1085193323Sed  /// alignment is zero, it means the target does not care about loop alignment.
1086234353Sdim  /// The alignment is specified in log2(bytes).
1087193323Sed  void setPrefLoopAlignment(unsigned Align) {
1088193323Sed    PrefLoopAlignment = Align;
1089193323Sed  }
1090210299Sed
1091210299Sed  /// setMinStackArgumentAlignment - Set the minimum stack alignment of an
1092234353Sdim  /// argument (in log2(bytes)).
1093210299Sed  void setMinStackArgumentAlignment(unsigned Align) {
1094210299Sed    MinStackArgumentAlignment = Align;
1095210299Sed  }
1096210299Sed
1097239462Sdim  /// setInsertFencesForAtomic - Set if the DAG builder should
1098226633Sdim  /// automatically insert fences and reduce the order of atomic memory
1099226633Sdim  /// operations to Monotonic.
1100226633Sdim  void setInsertFencesForAtomic(bool fence) {
1101226633Sdim    InsertFencesForAtomic = fence;
1102226633Sdim  }
1103226633Sdim
1104193323Sedpublic:
1105193323Sed  //===--------------------------------------------------------------------===//
1106193323Sed  // Addressing mode description hooks (used by LSR etc).
1107193323Sed  //
1108193323Sed
1109234353Sdim  /// GetAddrModeArguments - CodeGenPrepare sinks address calculations into the
1110234353Sdim  /// same BB as Load/Store instructions reading the address.  This allows as
1111234353Sdim  /// much computation as possible to be done in the address mode for that
1112234353Sdim  /// operand.  This hook lets targets also pass back when this should be done
1113234353Sdim  /// on intrinsics which load/store.
1114234353Sdim  virtual bool GetAddrModeArguments(IntrinsicInst *I,
1115234353Sdim                                    SmallVectorImpl<Value*> &Ops,
1116234353Sdim                                    Type *&AccessTy) const {
1117234353Sdim    return false;
1118234353Sdim  }
1119234353Sdim
1120249423Sdim  /// AddrMode - This represents an addressing mode of:
1121249423Sdim  ///    BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1122249423Sdim  /// If BaseGV is null,  there is no BaseGV.
1123249423Sdim  /// If BaseOffs is zero, there is no base offset.
1124249423Sdim  /// If HasBaseReg is false, there is no base register.
1125249423Sdim  /// If Scale is zero, there is no ScaleReg.  Scale of 1 indicates a reg with
1126249423Sdim  /// no scale.
1127249423Sdim  ///
1128249423Sdim  struct AddrMode {
1129249423Sdim    GlobalValue *BaseGV;
1130249423Sdim    int64_t      BaseOffs;
1131249423Sdim    bool         HasBaseReg;
1132249423Sdim    int64_t      Scale;
1133249423Sdim    AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1134249423Sdim  };
1135249423Sdim
1136193323Sed  /// isLegalAddressingMode - Return true if the addressing mode represented by
1137193323Sed  /// AM is legal for this target, for a load/store of the specified type.
1138193323Sed  /// The type may be VoidTy, in which case only return true if the addressing
1139193323Sed  /// mode is legal for a load/store of any legal type.
1140193323Sed  /// TODO: Handle pre/postinc as well.
1141226633Sdim  virtual bool isLegalAddressingMode(const AddrMode &AM, Type *Ty) const;
1142193323Sed
1143226633Sdim  /// isLegalICmpImmediate - Return true if the specified immediate is legal
1144226633Sdim  /// icmp immediate, that is the target has icmp instructions which can compare
1145226633Sdim  /// a register against the immediate without having to materialize the
1146226633Sdim  /// immediate into a register.
1147226633Sdim  virtual bool isLegalICmpImmediate(int64_t) const {
1148226633Sdim    return true;
1149226633Sdim  }
1150226633Sdim
1151226633Sdim  /// isLegalAddImmediate - Return true if the specified immediate is legal
1152226633Sdim  /// add immediate, that is the target has add instructions which can add
1153226633Sdim  /// a register with the immediate without having to materialize the
1154226633Sdim  /// immediate into a register.
1155226633Sdim  virtual bool isLegalAddImmediate(int64_t) const {
1156226633Sdim    return true;
1157226633Sdim  }
1158226633Sdim
1159193323Sed  /// isTruncateFree - Return true if it's free to truncate a value of
1160193323Sed  /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1161193323Sed  /// register EAX to i16 by referencing its sub-register AX.
1162226633Sdim  virtual bool isTruncateFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1163193323Sed    return false;
1164193323Sed  }
1165193323Sed
1166226633Sdim  virtual bool isTruncateFree(EVT /*VT1*/, EVT /*VT2*/) const {
1167193323Sed    return false;
1168193323Sed  }
1169193323Sed
1170193323Sed  /// isZExtFree - Return true if any actual instruction that defines a
1171202375Srdivacky  /// value of type Ty1 implicitly zero-extends the value to Ty2 in the result
1172193323Sed  /// register. This does not necessarily include registers defined in
1173193323Sed  /// unknown ways, such as incoming arguments, or copies from unknown
1174193323Sed  /// virtual registers. Also, if isTruncateFree(Ty2, Ty1) is true, this
1175193323Sed  /// does not necessarily apply to truncate instructions. e.g. on x86-64,
1176193323Sed  /// all instructions that define 32-bit values implicit zero-extend the
1177193323Sed  /// result out to 64 bits.
1178226633Sdim  virtual bool isZExtFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1179193323Sed    return false;
1180193323Sed  }
1181193323Sed
1182226633Sdim  virtual bool isZExtFree(EVT /*VT1*/, EVT /*VT2*/) const {
1183193323Sed    return false;
1184193323Sed  }
1185193323Sed
1186249423Sdim  /// isZExtFree - Return true if zero-extending the specific node Val to type
1187249423Sdim  /// VT2 is free (either because it's implicitly zero-extended such as ARM
1188249423Sdim  /// ldrb / ldrh or because it's folded such as X86 zero-extending loads).
1189249423Sdim  virtual bool isZExtFree(SDValue Val, EVT VT2) const {
1190249423Sdim    return isZExtFree(Val.getValueType(), VT2);
1191249423Sdim  }
1192249423Sdim
1193234353Sdim  /// isFNegFree - Return true if an fneg operation is free to the point where
1194234353Sdim  /// it is never worthwhile to replace it with a bitwise operation.
1195234353Sdim  virtual bool isFNegFree(EVT) const {
1196234353Sdim    return false;
1197234353Sdim  }
1198234353Sdim
1199234353Sdim  /// isFAbsFree - Return true if an fneg operation is free to the point where
1200234353Sdim  /// it is never worthwhile to replace it with a bitwise operation.
1201234353Sdim  virtual bool isFAbsFree(EVT) const {
1202234353Sdim    return false;
1203234353Sdim  }
1204234353Sdim
1205239462Sdim  /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
1206239462Sdim  /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
1207239462Sdim  /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
1208239462Sdim  /// is expanded to mul + add.
1209239462Sdim  virtual bool isFMAFasterThanMulAndAdd(EVT) const {
1210239462Sdim    return false;
1211239462Sdim  }
1212239462Sdim
1213193323Sed  /// isNarrowingProfitable - Return true if it's profitable to narrow
1214193323Sed  /// operations of type VT1 to VT2. e.g. on x86, it's profitable to narrow
1215193323Sed  /// from i32 to i8 but not from i32 to i16.
1216226633Sdim  virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
1217193323Sed    return false;
1218193323Sed  }
1219193323Sed
1220193323Sed  //===--------------------------------------------------------------------===//
1221193323Sed  // Runtime Library hooks
1222193323Sed  //
1223193323Sed
1224193323Sed  /// setLibcallName - Rename the default libcall routine name for the specified
1225193323Sed  /// libcall.
1226193323Sed  void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1227193323Sed    LibcallRoutineNames[Call] = Name;
1228193323Sed  }
1229193323Sed
1230193323Sed  /// getLibcallName - Get the libcall routine name for the specified libcall.
1231193323Sed  ///
1232193323Sed  const char *getLibcallName(RTLIB::Libcall Call) const {
1233193323Sed    return LibcallRoutineNames[Call];
1234193323Sed  }
1235193323Sed
1236193323Sed  /// setCmpLibcallCC - Override the default CondCode to be used to test the
1237193323Sed  /// result of the comparison libcall against zero.
1238193323Sed  void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1239193323Sed    CmpLibcallCCs[Call] = CC;
1240193323Sed  }
1241193323Sed
1242193323Sed  /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1243193323Sed  /// the comparison libcall against zero.
1244193323Sed  ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1245193323Sed    return CmpLibcallCCs[Call];
1246193323Sed  }
1247193323Sed
1248198090Srdivacky  /// setLibcallCallingConv - Set the CallingConv that should be used for the
1249198090Srdivacky  /// specified libcall.
1250198090Srdivacky  void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
1251198090Srdivacky    LibcallCallingConvs[Call] = CC;
1252198090Srdivacky  }
1253210299Sed
1254198090Srdivacky  /// getLibcallCallingConv - Get the CallingConv that should be used for the
1255198090Srdivacky  /// specified libcall.
1256198090Srdivacky  CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
1257198090Srdivacky    return LibcallCallingConvs[Call];
1258198090Srdivacky  }
1259198090Srdivacky
1260193323Sedprivate:
1261207618Srdivacky  const TargetMachine &TM;
1262243830Sdim  const DataLayout *TD;
1263207618Srdivacky  const TargetLoweringObjectFile &TLOF;
1264193323Sed
1265243830Sdim  /// PointerTy - The type to use for pointers for the default address space,
1266243830Sdim  /// usually i32 or i64.
1267193323Sed  ///
1268193323Sed  MVT PointerTy;
1269193323Sed
1270193323Sed  /// IsLittleEndian - True if this is a little endian target.
1271193323Sed  ///
1272193323Sed  bool IsLittleEndian;
1273193323Sed
1274193323Sed  /// SelectIsExpensive - Tells the code generator not to expand operations
1275193323Sed  /// into sequences that use the select operations if possible.
1276193323Sed  bool SelectIsExpensive;
1277193323Sed
1278193323Sed  /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1279193323Sed  /// constants into a sequence of muls, adds, and shifts.  This is a hack until
1280193323Sed  /// a real cost model is in place.  If we ever optimize for size, this will be
1281193323Sed  /// set to true unconditionally.
1282193323Sed  bool IntDivIsCheap;
1283210299Sed
1284243830Sdim  /// BypassSlowDivMap - Tells the code generator to bypass slow divide or
1285243830Sdim  /// remainder instructions. For example, BypassSlowDivWidths[32,8] tells the
1286243830Sdim  /// code generator to bypass 32-bit integer div/rem with an 8-bit unsigned
1287243830Sdim  /// integer div/rem when the operands are positive and less than 256.
1288243830Sdim  DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
1289243830Sdim
1290193323Sed  /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1291193323Sed  /// srl/add/sra for a signed divide by power of two, and let the target handle
1292193323Sed  /// it.
1293193323Sed  bool Pow2DivIsCheap;
1294210299Sed
1295218893Sdim  /// JumpIsExpensive - Tells the code generator that it shouldn't generate
1296218893Sdim  /// extra flow control instructions and should attempt to combine flow
1297218893Sdim  /// control instructions via predication.
1298218893Sdim  bool JumpIsExpensive;
1299218893Sdim
1300193323Sed  /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1301193323Sed  /// llvm.setjmp.  Defaults to false.
1302193323Sed  bool UseUnderscoreSetJmp;
1303193323Sed
1304193323Sed  /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1305193323Sed  /// llvm.longjmp.  Defaults to false.
1306193323Sed  bool UseUnderscoreLongJmp;
1307193323Sed
1308239462Sdim  /// SupportJumpTables - Whether the target can generate code for jumptables.
1309239462Sdim  /// If it's not true, then each jumptable must be lowered into if-then-else's.
1310239462Sdim  bool SupportJumpTables;
1311239462Sdim
1312243830Sdim  /// MinimumJumpTableEntries - Number of blocks threshold to use jump tables.
1313243830Sdim  int MinimumJumpTableEntries;
1314243830Sdim
1315193323Sed  /// BooleanContents - Information about the contents of the high-bits in
1316193323Sed  /// boolean values held in a type wider than i1.  See getBooleanContents.
1317193323Sed  BooleanContent BooleanContents;
1318226633Sdim  /// BooleanVectorContents - Information about the contents of the high-bits
1319226633Sdim  /// in boolean vector values when the element type is wider than i1.  See
1320226633Sdim  /// getBooleanContents.
1321226633Sdim  BooleanContent BooleanVectorContents;
1322193323Sed
1323193323Sed  /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1324193323Sed  /// total cycles or lowest register usage.
1325208599Srdivacky  Sched::Preference SchedPreferenceInfo;
1326210299Sed
1327193323Sed  /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1328193323Sed  unsigned JumpBufSize;
1329210299Sed
1330193323Sed  /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1331193323Sed  /// buffers
1332193323Sed  unsigned JumpBufAlignment;
1333193323Sed
1334210299Sed  /// MinStackArgumentAlignment - The minimum alignment that any argument
1335210299Sed  /// on the stack needs to have.
1336210299Sed  ///
1337210299Sed  unsigned MinStackArgumentAlignment;
1338193323Sed
1339223017Sdim  /// MinFunctionAlignment - The minimum function alignment (used when
1340223017Sdim  /// optimizing for size, and to prevent explicitly provided alignment
1341223017Sdim  /// from leading to incorrect code).
1342193323Sed  ///
1343223017Sdim  unsigned MinFunctionAlignment;
1344223017Sdim
1345223017Sdim  /// PrefFunctionAlignment - The preferred function alignment (used when
1346223017Sdim  /// alignment unspecified and optimizing for speed).
1347223017Sdim  ///
1348223017Sdim  unsigned PrefFunctionAlignment;
1349223017Sdim
1350223017Sdim  /// PrefLoopAlignment - The preferred loop alignment.
1351223017Sdim  ///
1352193323Sed  unsigned PrefLoopAlignment;
1353193323Sed
1354226633Sdim  /// InsertFencesForAtomic - Whether the DAG builder should automatically
1355226633Sdim  /// insert fences and reduce ordering for atomics.  (This will be set for
1356226633Sdim  /// for most architectures with weak memory ordering.)
1357226633Sdim  bool InsertFencesForAtomic;
1358226633Sdim
1359193323Sed  /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1360193323Sed  /// specifies the register that llvm.savestack/llvm.restorestack should save
1361193323Sed  /// and restore.
1362193323Sed  unsigned StackPointerRegisterToSaveRestore;
1363193323Sed
1364193323Sed  /// ExceptionPointerRegister - If set to a physical register, this specifies
1365193323Sed  /// the register that receives the exception address on entry to a landing
1366193323Sed  /// pad.
1367193323Sed  unsigned ExceptionPointerRegister;
1368193323Sed
1369193323Sed  /// ExceptionSelectorRegister - If set to a physical register, this specifies
1370193323Sed  /// the register that receives the exception typeid on entry to a landing
1371193323Sed  /// pad.
1372193323Sed  unsigned ExceptionSelectorRegister;
1373193323Sed
1374193323Sed  /// RegClassForVT - This indicates the default register class to use for
1375193323Sed  /// each ValueType the target supports natively.
1376234353Sdim  const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1377193323Sed  unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1378249423Sdim  MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1379193323Sed
1380212904Sdim  /// RepRegClassForVT - This indicates the "representative" register class to
1381212904Sdim  /// use for each ValueType the target supports natively. This information is
1382212904Sdim  /// used by the scheduler to track register pressure. By default, the
1383212904Sdim  /// representative register class is the largest legal super-reg register
1384212904Sdim  /// class of the register class of the specified type. e.g. On x86, i8, i16,
1385212904Sdim  /// and i32's representative class would be GR32.
1386212904Sdim  const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
1387212904Sdim
1388212904Sdim  /// RepRegClassCostForVT - This indicates the "cost" of the "representative"
1389212904Sdim  /// register class for each ValueType. The cost is used by the scheduler to
1390212904Sdim  /// approximate register pressure.
1391212904Sdim  uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
1392212904Sdim
1393193323Sed  /// TransformToType - For any value types we are promoting or expanding, this
1394193323Sed  /// contains the value type that we are changing to.  For Expanded types, this
1395193323Sed  /// contains one step of the expand (e.g. i64 -> i32), even if there are
1396193323Sed  /// multiple steps required (e.g. i64 -> i16).  For types natively supported
1397193323Sed  /// by the system, this holds the same type (e.g. i32 -> i32).
1398249423Sdim  MVT TransformToType[MVT::LAST_VALUETYPE];
1399193323Sed
1400193323Sed  /// OpActions - For each operation and each value type, keep a LegalizeAction
1401193323Sed  /// that indicates how instruction selection should deal with the operation.
1402193323Sed  /// Most operations are Legal (aka, supported natively by the target), but
1403193323Sed  /// operations that are not should be described.  Note that operations on
1404193323Sed  /// non-legal value types are not described here.
1405208599Srdivacky  uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
1406210299Sed
1407208599Srdivacky  /// LoadExtActions - For each load extension type and each value type,
1408193323Sed  /// keep a LegalizeAction that indicates how instruction selection should deal
1409208599Srdivacky  /// with a load of a specific value type and extension type.
1410208599Srdivacky  uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE];
1411210299Sed
1412208599Srdivacky  /// TruncStoreActions - For each value type pair keep a LegalizeAction that
1413208599Srdivacky  /// indicates whether a truncating store of a specific value type and
1414208599Srdivacky  /// truncating type is legal.
1415208599Srdivacky  uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
1416193323Sed
1417194178Sed  /// IndexedModeActions - For each indexed mode and each value type,
1418194178Sed  /// keep a pair of LegalizeAction that indicates how instruction
1419208599Srdivacky  /// selection should deal with the load / store.  The first dimension is the
1420208599Srdivacky  /// value_type for the reference. The second dimension represents the various
1421208599Srdivacky  /// modes for load store.
1422208599Srdivacky  uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
1423210299Sed
1424193323Sed  /// CondCodeActions - For each condition code (ISD::CondCode) keep a
1425193323Sed  /// LegalizeAction that indicates how instruction selection should
1426193323Sed  /// deal with the condition code.
1427243830Sdim  /// Because each CC action takes up 2 bits, we need to have the array size
1428243830Sdim  /// be large enough to fit all of the value types. This can be done by
1429243830Sdim  /// dividing the MVT::LAST_VALUETYPE by 32 and adding one.
1430243830Sdim  uint64_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE / 32) + 1];
1431193323Sed
1432193323Sed  ValueTypeActionImpl ValueTypeActions;
1433193323Sed
1434243830Sdimpublic:
1435223017Sdim  LegalizeKind
1436223017Sdim  getTypeConversion(LLVMContext &Context, EVT VT) const {
1437223017Sdim    // If this is a simple type, use the ComputeRegisterProp mechanism.
1438223017Sdim    if (VT.isSimple()) {
1439249423Sdim      MVT SVT = VT.getSimpleVT();
1440249423Sdim      assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
1441249423Sdim      MVT NVT = TransformToType[SVT.SimpleTy];
1442249423Sdim      LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
1443223017Sdim
1444223017Sdim      assert(
1445249423Sdim        (LA == TypeLegal ||
1446249423Sdim         ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)
1447223017Sdim         && "Promote may not follow Expand or Promote");
1448223017Sdim
1449243830Sdim      if (LA == TypeSplitVector)
1450249423Sdim        return LegalizeKind(LA, EVT::getVectorVT(Context,
1451249423Sdim                                                 SVT.getVectorElementType(),
1452249423Sdim                                                 SVT.getVectorNumElements()/2));
1453249423Sdim      if (LA == TypeScalarizeVector)
1454249423Sdim        return LegalizeKind(LA, SVT.getVectorElementType());
1455223017Sdim      return LegalizeKind(LA, NVT);
1456223017Sdim    }
1457223017Sdim
1458223017Sdim    // Handle Extended Scalar Types.
1459223017Sdim    if (!VT.isVector()) {
1460223017Sdim      assert(VT.isInteger() && "Float types must be simple");
1461223017Sdim      unsigned BitSize = VT.getSizeInBits();
1462223017Sdim      // First promote to a power-of-two size, then expand if necessary.
1463223017Sdim      if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
1464223017Sdim        EVT NVT = VT.getRoundIntegerType(Context);
1465223017Sdim        assert(NVT != VT && "Unable to round integer VT");
1466223017Sdim        LegalizeKind NextStep = getTypeConversion(Context, NVT);
1467223017Sdim        // Avoid multi-step promotion.
1468223017Sdim        if (NextStep.first == TypePromoteInteger) return NextStep;
1469223017Sdim        // Return rounded integer type.
1470223017Sdim        return LegalizeKind(TypePromoteInteger, NVT);
1471223017Sdim      }
1472223017Sdim
1473223017Sdim      return LegalizeKind(TypeExpandInteger,
1474223017Sdim                          EVT::getIntegerVT(Context, VT.getSizeInBits()/2));
1475223017Sdim    }
1476223017Sdim
1477223017Sdim    // Handle vector types.
1478223017Sdim    unsigned NumElts = VT.getVectorNumElements();
1479223017Sdim    EVT EltVT = VT.getVectorElementType();
1480223017Sdim
1481223017Sdim    // Vectors with only one element are always scalarized.
1482223017Sdim    if (NumElts == 1)
1483223017Sdim      return LegalizeKind(TypeScalarizeVector, EltVT);
1484223017Sdim
1485239462Sdim    // Try to widen vector elements until a legal type is found.
1486239462Sdim    if (EltVT.isInteger()) {
1487223017Sdim      // Vectors with a number of elements that is not a power of two are always
1488223017Sdim      // widened, for example <3 x float> -> <4 x float>.
1489223017Sdim      if (!VT.isPow2VectorType()) {
1490223017Sdim        NumElts = (unsigned)NextPowerOf2(NumElts);
1491223017Sdim        EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
1492223017Sdim        return LegalizeKind(TypeWidenVector, NVT);
1493223017Sdim      }
1494223017Sdim
1495223017Sdim      // Examine the element type.
1496223017Sdim      LegalizeKind LK = getTypeConversion(Context, EltVT);
1497223017Sdim
1498223017Sdim      // If type is to be expanded, split the vector.
1499223017Sdim      //  <4 x i140> -> <2 x i140>
1500223017Sdim      if (LK.first == TypeExpandInteger)
1501223017Sdim        return LegalizeKind(TypeSplitVector,
1502223017Sdim                            EVT::getVectorVT(Context, EltVT, NumElts / 2));
1503223017Sdim
1504223017Sdim      // Promote the integer element types until a legal vector type is found
1505223017Sdim      // or until the element integer type is too big. If a legal type was not
1506223017Sdim      // found, fallback to the usual mechanism of widening/splitting the
1507223017Sdim      // vector.
1508251662Sdim      EVT OldEltVT = EltVT;
1509223017Sdim      while (1) {
1510223017Sdim        // Increase the bitwidth of the element to the next pow-of-two
1511223017Sdim        // (which is greater than 8 bits).
1512223017Sdim        EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()
1513223017Sdim                                 ).getRoundIntegerType(Context);
1514223017Sdim
1515223017Sdim        // Stop trying when getting a non-simple element type.
1516223017Sdim        // Note that vector elements may be greater than legal vector element
1517223017Sdim        // types. Example: X86 XMM registers hold 64bit element on 32bit systems.
1518223017Sdim        if (!EltVT.isSimple()) break;
1519223017Sdim
1520223017Sdim        // Build a new vector type and check if it is legal.
1521223017Sdim        MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1522223017Sdim        // Found a legal promoted vector type.
1523224145Sdim        if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
1524223017Sdim          return LegalizeKind(TypePromoteInteger,
1525223017Sdim                              EVT::getVectorVT(Context, EltVT, NumElts));
1526223017Sdim      }
1527251662Sdim
1528251662Sdim      // Reset the type to the unexpanded type if we did not find a legal vector
1529251662Sdim      // type with a promoted vector element type.
1530251662Sdim      EltVT = OldEltVT;
1531223017Sdim    }
1532223017Sdim
1533223017Sdim    // Try to widen the vector until a legal type is found.
1534223017Sdim    // If there is no wider legal type, split the vector.
1535223017Sdim    while (1) {
1536223017Sdim      // Round up to the next power of 2.
1537223017Sdim      NumElts = (unsigned)NextPowerOf2(NumElts);
1538223017Sdim
1539223017Sdim      // If there is no simple vector type with this many elements then there
1540223017Sdim      // cannot be a larger legal vector type.  Note that this assumes that
1541223017Sdim      // there are no skipped intermediate vector types in the simple types.
1542224145Sdim      if (!EltVT.isSimple()) break;
1543223017Sdim      MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1544223017Sdim      if (LargerVector == MVT()) break;
1545223017Sdim
1546223017Sdim      // If this type is legal then widen the vector.
1547223017Sdim      if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
1548223017Sdim        return LegalizeKind(TypeWidenVector, LargerVector);
1549223017Sdim    }
1550223017Sdim
1551223017Sdim    // Widen odd vectors to next power of two.
1552223017Sdim    if (!VT.isPow2VectorType()) {
1553223017Sdim      EVT NVT = VT.getPow2VectorType(Context);
1554223017Sdim      return LegalizeKind(TypeWidenVector, NVT);
1555223017Sdim    }
1556223017Sdim
1557223017Sdim    // Vectors with illegal element types are expanded.
1558223017Sdim    EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
1559223017Sdim    return LegalizeKind(TypeSplitVector, NVT);
1560223017Sdim  }
1561223017Sdim
1562243830Sdimprivate:
1563249423Sdim  std::vector<std::pair<MVT, const TargetRegisterClass*> > AvailableRegClasses;
1564193323Sed
1565193323Sed  /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
1566193323Sed  /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
1567193323Sed  /// which sets a bit in this array.
1568193323Sed  unsigned char
1569193323Sed  TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
1570210299Sed
1571193323Sed  /// PromoteToType - For operations that must be promoted to a specific type,
1572193323Sed  /// this holds the destination type.  This map should be sparse, so don't hold
1573193323Sed  /// it as an array.
1574193323Sed  ///
1575193323Sed  /// Targets add entries to this map with AddPromotedToType(..), clients access
1576193323Sed  /// this with getTypeToPromoteTo(..).
1577193323Sed  std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1578193323Sed    PromoteToType;
1579193323Sed
1580193323Sed  /// LibcallRoutineNames - Stores the name each libcall.
1581193323Sed  ///
1582193323Sed  const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1583193323Sed
1584193323Sed  /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
1585193323Sed  /// of each of the comparison libcall against zero.
1586193323Sed  ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1587193323Sed
1588198090Srdivacky  /// LibcallCallingConvs - Stores the CallingConv that should be used for each
1589198090Srdivacky  /// libcall.
1590198090Srdivacky  CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
1591198090Srdivacky
1592193323Sedprotected:
1593193323Sed  /// When lowering \@llvm.memset this field specifies the maximum number of
1594193323Sed  /// store operations that may be substituted for the call to memset. Targets
1595193323Sed  /// must set this value based on the cost threshold for that target. Targets
1596193323Sed  /// should assume that the memset will be done using as many of the largest
1597193323Sed  /// store operations first, followed by smaller ones, if necessary, per
1598193323Sed  /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1599193323Sed  /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1600193323Sed  /// store.  This only applies to setting a constant array of a constant size.
1601193323Sed  /// @brief Specify maximum number of store instructions per memset call.
1602249423Sdim  unsigned MaxStoresPerMemset;
1603193323Sed
1604218893Sdim  /// Maximum number of stores operations that may be substituted for the call
1605218893Sdim  /// to memset, used for functions with OptSize attribute.
1606249423Sdim  unsigned MaxStoresPerMemsetOptSize;
1607218893Sdim
1608193323Sed  /// When lowering \@llvm.memcpy this field specifies the maximum number of
1609193323Sed  /// store operations that may be substituted for a call to memcpy. Targets
1610193323Sed  /// must set this value based on the cost threshold for that target. Targets
1611193323Sed  /// should assume that the memcpy will be done using as many of the largest
1612193323Sed  /// store operations first, followed by smaller ones, if necessary, per
1613193323Sed  /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1614193323Sed  /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1615193323Sed  /// and one 1-byte store. This only applies to copying a constant array of
1616193323Sed  /// constant size.
1617193323Sed  /// @brief Specify maximum bytes of store instructions per memcpy call.
1618249423Sdim  unsigned MaxStoresPerMemcpy;
1619193323Sed
1620218893Sdim  /// Maximum number of store operations that may be substituted for a call
1621218893Sdim  /// to memcpy, used for functions with OptSize attribute.
1622249423Sdim  unsigned MaxStoresPerMemcpyOptSize;
1623218893Sdim
1624193323Sed  /// When lowering \@llvm.memmove this field specifies the maximum number of
1625193323Sed  /// store instructions that may be substituted for a call to memmove. Targets
1626193323Sed  /// must set this value based on the cost threshold for that target. Targets
1627193323Sed  /// should assume that the memmove will be done using as many of the largest
1628193323Sed  /// store operations first, followed by smaller ones, if necessary, per
1629193323Sed  /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1630193323Sed  /// with 8-bit alignment would result in nine 1-byte stores.  This only
1631193323Sed  /// applies to copying a constant array of constant size.
1632193323Sed  /// @brief Specify maximum bytes of store instructions per memmove call.
1633249423Sdim  unsigned MaxStoresPerMemmove;
1634193323Sed
1635218893Sdim  /// Maximum number of store instructions that may be substituted for a call
1636218893Sdim  /// to memmove, used for functions with OpSize attribute.
1637249423Sdim  unsigned MaxStoresPerMemmoveOptSize;
1638218893Sdim
1639249423Sdim  /// PredictableSelectIsExpensive - Tells the code generator that select is
1640239462Sdim  /// more expensive than a branch if the branch is usually predicted right.
1641249423Sdim  bool PredictableSelectIsExpensive;
1642239462Sdim
1643249423Sdimprotected:
1644212904Sdim  /// isLegalRC - Return true if the value types that can be represented by the
1645212904Sdim  /// specified register class are all legal.
1646212904Sdim  bool isLegalRC(const TargetRegisterClass *RC) const;
1647193323Sed};
1648210299Sed
1649249423Sdim//===----------------------------------------------------------------------===//
1650249423Sdim/// TargetLowering - This class defines information used to lower LLVM code to
1651249423Sdim/// legal SelectionDAG operators that the target instruction selector can accept
1652249423Sdim/// natively.
1653249423Sdim///
1654249423Sdim/// This class also defines callbacks that targets must implement to lower
1655249423Sdim/// target-specific constructs to SelectionDAG operators.
1656249423Sdim///
1657249423Sdimclass TargetLowering : public TargetLoweringBase {
1658249423Sdim  TargetLowering(const TargetLowering&) LLVM_DELETED_FUNCTION;
1659249423Sdim  void operator=(const TargetLowering&) LLVM_DELETED_FUNCTION;
1660249423Sdim
1661249423Sdimpublic:
1662249423Sdim  /// NOTE: The constructor takes ownership of TLOF.
1663249423Sdim  explicit TargetLowering(const TargetMachine &TM,
1664249423Sdim                          const TargetLoweringObjectFile *TLOF);
1665249423Sdim
1666249423Sdim  /// getPreIndexedAddressParts - returns true by value, base pointer and
1667249423Sdim  /// offset pointer and addressing mode by reference if the node's address
1668249423Sdim  /// can be legally represented as pre-indexed load / store address.
1669249423Sdim  virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
1670249423Sdim                                         SDValue &/*Offset*/,
1671249423Sdim                                         ISD::MemIndexedMode &/*AM*/,
1672249423Sdim                                         SelectionDAG &/*DAG*/) const {
1673249423Sdim    return false;
1674249423Sdim  }
1675249423Sdim
1676249423Sdim  /// getPostIndexedAddressParts - returns true by value, base pointer and
1677249423Sdim  /// offset pointer and addressing mode by reference if this node can be
1678249423Sdim  /// combined with a load / store to form a post-indexed load / store.
1679249423Sdim  virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
1680249423Sdim                                          SDValue &/*Base*/, SDValue &/*Offset*/,
1681249423Sdim                                          ISD::MemIndexedMode &/*AM*/,
1682249423Sdim                                          SelectionDAG &/*DAG*/) const {
1683249423Sdim    return false;
1684249423Sdim  }
1685249423Sdim
1686249423Sdim  /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1687249423Sdim  /// current function.  The returned value is a member of the
1688249423Sdim  /// MachineJumpTableInfo::JTEntryKind enum.
1689249423Sdim  virtual unsigned getJumpTableEncoding() const;
1690249423Sdim
1691249423Sdim  virtual const MCExpr *
1692249423Sdim  LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
1693249423Sdim                            const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
1694249423Sdim                            MCContext &/*Ctx*/) const {
1695249423Sdim    llvm_unreachable("Need to implement this hook if target has custom JTIs");
1696249423Sdim  }
1697249423Sdim
1698249423Sdim  /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1699249423Sdim  /// jumptable.
1700249423Sdim  virtual SDValue getPICJumpTableRelocBase(SDValue Table,
1701249423Sdim                                           SelectionDAG &DAG) const;
1702249423Sdim
1703249423Sdim  /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1704249423Sdim  /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1705249423Sdim  /// MCExpr.
1706249423Sdim  virtual const MCExpr *
1707249423Sdim  getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
1708249423Sdim                               unsigned JTI, MCContext &Ctx) const;
1709249423Sdim
1710249423Sdim  /// isOffsetFoldingLegal - Return true if folding a constant offset
1711249423Sdim  /// with the given GlobalAddress is legal.  It is frequently not legal in
1712249423Sdim  /// PIC relocation models.
1713249423Sdim  virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
1714249423Sdim
1715249423Sdim  bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
1716249423Sdim                            SDValue &Chain) const;
1717249423Sdim
1718249423Sdim  void softenSetCCOperands(SelectionDAG &DAG, EVT VT,
1719249423Sdim                           SDValue &NewLHS, SDValue &NewRHS,
1720249423Sdim                           ISD::CondCode &CCCode, DebugLoc DL) const;
1721249423Sdim
1722249423Sdim  SDValue makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
1723249423Sdim                      const SDValue *Ops, unsigned NumOps,
1724249423Sdim                      bool isSigned, DebugLoc dl) const;
1725249423Sdim
1726249423Sdim  //===--------------------------------------------------------------------===//
1727249423Sdim  // TargetLowering Optimization Methods
1728249423Sdim  //
1729249423Sdim
1730249423Sdim  /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
1731249423Sdim  /// SDValues for returning information from TargetLowering to its clients
1732249423Sdim  /// that want to combine
1733249423Sdim  struct TargetLoweringOpt {
1734249423Sdim    SelectionDAG &DAG;
1735249423Sdim    bool LegalTys;
1736249423Sdim    bool LegalOps;
1737249423Sdim    SDValue Old;
1738249423Sdim    SDValue New;
1739249423Sdim
1740249423Sdim    explicit TargetLoweringOpt(SelectionDAG &InDAG,
1741249423Sdim                               bool LT, bool LO) :
1742249423Sdim      DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
1743249423Sdim
1744249423Sdim    bool LegalTypes() const { return LegalTys; }
1745249423Sdim    bool LegalOperations() const { return LegalOps; }
1746249423Sdim
1747249423Sdim    bool CombineTo(SDValue O, SDValue N) {
1748249423Sdim      Old = O;
1749249423Sdim      New = N;
1750249423Sdim      return true;
1751249423Sdim    }
1752249423Sdim
1753249423Sdim    /// ShrinkDemandedConstant - Check to see if the specified operand of the
1754249423Sdim    /// specified instruction is a constant integer.  If so, check to see if
1755249423Sdim    /// there are any bits set in the constant that are not demanded.  If so,
1756249423Sdim    /// shrink the constant and return true.
1757249423Sdim    bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
1758249423Sdim
1759249423Sdim    /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
1760249423Sdim    /// casts are free.  This uses isZExtFree and ZERO_EXTEND for the widening
1761249423Sdim    /// cast, but it could be generalized for targets with other types of
1762249423Sdim    /// implicit widening casts.
1763249423Sdim    bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
1764249423Sdim                          DebugLoc dl);
1765249423Sdim  };
1766249423Sdim
1767249423Sdim  /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
1768249423Sdim  /// DemandedMask bits of the result of Op are ever used downstream.  If we can
1769249423Sdim  /// use this information to simplify Op, create a new simplified DAG node and
1770249423Sdim  /// return true, returning the original and new nodes in Old and New.
1771249423Sdim  /// Otherwise, analyze the expression and return a mask of KnownOne and
1772249423Sdim  /// KnownZero bits for the expression (used to simplify the caller).
1773249423Sdim  /// The KnownZero/One bits may only be accurate for those bits in the
1774249423Sdim  /// DemandedMask.
1775249423Sdim  bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
1776249423Sdim                            APInt &KnownZero, APInt &KnownOne,
1777249423Sdim                            TargetLoweringOpt &TLO, unsigned Depth = 0) const;
1778249423Sdim
1779249423Sdim  /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
1780249423Sdim  /// Mask are known to be either zero or one and return them in the
1781249423Sdim  /// KnownZero/KnownOne bitsets.
1782249423Sdim  virtual void computeMaskedBitsForTargetNode(const SDValue Op,
1783249423Sdim                                              APInt &KnownZero,
1784249423Sdim                                              APInt &KnownOne,
1785249423Sdim                                              const SelectionDAG &DAG,
1786249423Sdim                                              unsigned Depth = 0) const;
1787249423Sdim
1788249423Sdim  /// ComputeNumSignBitsForTargetNode - This method can be implemented by
1789249423Sdim  /// targets that want to expose additional information about sign bits to the
1790249423Sdim  /// DAG Combiner.
1791249423Sdim  virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
1792249423Sdim                                                   unsigned Depth = 0) const;
1793249423Sdim
1794249423Sdim  struct DAGCombinerInfo {
1795249423Sdim    void *DC;  // The DAG Combiner object.
1796249423Sdim    CombineLevel Level;
1797249423Sdim    bool CalledByLegalizer;
1798249423Sdim  public:
1799249423Sdim    SelectionDAG &DAG;
1800249423Sdim
1801249423Sdim    DAGCombinerInfo(SelectionDAG &dag, CombineLevel level,  bool cl, void *dc)
1802249423Sdim      : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
1803249423Sdim
1804249423Sdim    bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
1805249423Sdim    bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
1806249423Sdim    bool isAfterLegalizeVectorOps() const {
1807249423Sdim      return Level == AfterLegalizeDAG;
1808249423Sdim    }
1809249423Sdim    CombineLevel getDAGCombineLevel() { return Level; }
1810249423Sdim    bool isCalledByLegalizer() const { return CalledByLegalizer; }
1811249423Sdim
1812249423Sdim    void AddToWorklist(SDNode *N);
1813249423Sdim    void RemoveFromWorklist(SDNode *N);
1814249423Sdim    SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
1815249423Sdim                      bool AddTo = true);
1816249423Sdim    SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
1817249423Sdim    SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
1818249423Sdim
1819249423Sdim    void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
1820249423Sdim  };
1821249423Sdim
1822249423Sdim  /// SimplifySetCC - Try to simplify a setcc built with the specified operands
1823249423Sdim  /// and cc. If it is unable to simplify it, return a null SDValue.
1824249423Sdim  SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1825249423Sdim                          ISD::CondCode Cond, bool foldBooleans,
1826249423Sdim                          DAGCombinerInfo &DCI, DebugLoc dl) const;
1827249423Sdim
1828249423Sdim  /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
1829249423Sdim  /// node is a GlobalAddress + offset.
1830249423Sdim  virtual bool
1831249423Sdim  isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
1832249423Sdim
1833249423Sdim  /// PerformDAGCombine - This method will be invoked for all target nodes and
1834249423Sdim  /// for any target-independent nodes that the target has registered with
1835249423Sdim  /// invoke it for.
1836249423Sdim  ///
1837249423Sdim  /// The semantics are as follows:
1838249423Sdim  /// Return Value:
1839249423Sdim  ///   SDValue.Val == 0   - No change was made
1840249423Sdim  ///   SDValue.Val == N   - N was replaced, is dead, and is already handled.
1841249423Sdim  ///   otherwise          - N should be replaced by the returned Operand.
1842249423Sdim  ///
1843249423Sdim  /// In addition, methods provided by DAGCombinerInfo may be used to perform
1844249423Sdim  /// more complex transformations.
1845249423Sdim  ///
1846249423Sdim  virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
1847249423Sdim
1848249423Sdim  /// isTypeDesirableForOp - Return true if the target has native support for
1849249423Sdim  /// the specified value type and it is 'desirable' to use the type for the
1850249423Sdim  /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
1851249423Sdim  /// instruction encodings are longer and some i16 instructions are slow.
1852249423Sdim  virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
1853249423Sdim    // By default, assume all legal types are desirable.
1854249423Sdim    return isTypeLegal(VT);
1855249423Sdim  }
1856249423Sdim
1857249423Sdim  /// isDesirableToPromoteOp - Return true if it is profitable for dag combiner
1858249423Sdim  /// to transform a floating point op of specified opcode to a equivalent op of
1859249423Sdim  /// an integer type. e.g. f32 load -> i32 load can be profitable on ARM.
1860249423Sdim  virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
1861249423Sdim                                                 EVT /*VT*/) const {
1862249423Sdim    return false;
1863249423Sdim  }
1864249423Sdim
1865249423Sdim  /// IsDesirableToPromoteOp - This method query the target whether it is
1866249423Sdim  /// beneficial for dag combiner to promote the specified node. If true, it
1867249423Sdim  /// should return the desired promotion type by reference.
1868249423Sdim  virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
1869249423Sdim    return false;
1870249423Sdim  }
1871249423Sdim
1872249423Sdim  //===--------------------------------------------------------------------===//
1873249423Sdim  // Lowering methods - These methods must be implemented by targets so that
1874249423Sdim  // the SelectionDAGBuilder code knows how to lower these.
1875249423Sdim  //
1876249423Sdim
1877249423Sdim  /// LowerFormalArguments - This hook must be implemented to lower the
1878249423Sdim  /// incoming (formal) arguments, described by the Ins array, into the
1879249423Sdim  /// specified DAG. The implementation should fill in the InVals array
1880249423Sdim  /// with legal-type argument values, and return the resulting token
1881249423Sdim  /// chain value.
1882249423Sdim  ///
1883249423Sdim  virtual SDValue
1884249423Sdim    LowerFormalArguments(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1885249423Sdim                         bool /*isVarArg*/,
1886249423Sdim                         const SmallVectorImpl<ISD::InputArg> &/*Ins*/,
1887249423Sdim                         DebugLoc /*dl*/, SelectionDAG &/*DAG*/,
1888249423Sdim                         SmallVectorImpl<SDValue> &/*InVals*/) const {
1889249423Sdim    llvm_unreachable("Not Implemented");
1890249423Sdim  }
1891249423Sdim
1892249423Sdim  struct ArgListEntry {
1893249423Sdim    SDValue Node;
1894249423Sdim    Type* Ty;
1895251662Sdim    bool isSExt     : 1;
1896251662Sdim    bool isZExt     : 1;
1897251662Sdim    bool isInReg    : 1;
1898251662Sdim    bool isSRet     : 1;
1899251662Sdim    bool isNest     : 1;
1900251662Sdim    bool isByVal    : 1;
1901251662Sdim    bool isReturned : 1;
1902249423Sdim    uint16_t Alignment;
1903249423Sdim
1904249423Sdim    ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1905251662Sdim      isSRet(false), isNest(false), isByVal(false), isReturned(false),
1906251662Sdim      Alignment(0) { }
1907249423Sdim  };
1908249423Sdim  typedef std::vector<ArgListEntry> ArgListTy;
1909249423Sdim
1910249423Sdim  /// CallLoweringInfo - This structure contains all information that is
1911249423Sdim  /// necessary for lowering calls. It is passed to TLI::LowerCallTo when the
1912249423Sdim  /// SelectionDAG builder needs to lower a call, and targets will see this
1913249423Sdim  /// struct in their LowerCall implementation.
1914249423Sdim  struct CallLoweringInfo {
1915249423Sdim    SDValue Chain;
1916249423Sdim    Type *RetTy;
1917249423Sdim    bool RetSExt           : 1;
1918249423Sdim    bool RetZExt           : 1;
1919249423Sdim    bool IsVarArg          : 1;
1920249423Sdim    bool IsInReg           : 1;
1921249423Sdim    bool DoesNotReturn     : 1;
1922249423Sdim    bool IsReturnValueUsed : 1;
1923249423Sdim
1924249423Sdim    // IsTailCall should be modified by implementations of
1925249423Sdim    // TargetLowering::LowerCall that perform tail call conversions.
1926249423Sdim    bool IsTailCall;
1927249423Sdim
1928249423Sdim    unsigned NumFixedArgs;
1929249423Sdim    CallingConv::ID CallConv;
1930249423Sdim    SDValue Callee;
1931249423Sdim    ArgListTy &Args;
1932249423Sdim    SelectionDAG &DAG;
1933249423Sdim    DebugLoc DL;
1934249423Sdim    ImmutableCallSite *CS;
1935249423Sdim    SmallVector<ISD::OutputArg, 32> Outs;
1936249423Sdim    SmallVector<SDValue, 32> OutVals;
1937249423Sdim    SmallVector<ISD::InputArg, 32> Ins;
1938249423Sdim
1939249423Sdim
1940249423Sdim    /// CallLoweringInfo - Constructs a call lowering context based on the
1941249423Sdim    /// ImmutableCallSite \p cs.
1942249423Sdim    CallLoweringInfo(SDValue chain, Type *retTy,
1943249423Sdim                     FunctionType *FTy, bool isTailCall, SDValue callee,
1944249423Sdim                     ArgListTy &args, SelectionDAG &dag, DebugLoc dl,
1945249423Sdim                     ImmutableCallSite &cs)
1946249423Sdim    : Chain(chain), RetTy(retTy), RetSExt(cs.paramHasAttr(0, Attribute::SExt)),
1947249423Sdim      RetZExt(cs.paramHasAttr(0, Attribute::ZExt)), IsVarArg(FTy->isVarArg()),
1948249423Sdim      IsInReg(cs.paramHasAttr(0, Attribute::InReg)),
1949249423Sdim      DoesNotReturn(cs.doesNotReturn()),
1950249423Sdim      IsReturnValueUsed(!cs.getInstruction()->use_empty()),
1951249423Sdim      IsTailCall(isTailCall), NumFixedArgs(FTy->getNumParams()),
1952249423Sdim      CallConv(cs.getCallingConv()), Callee(callee), Args(args), DAG(dag),
1953249423Sdim      DL(dl), CS(&cs) {}
1954249423Sdim
1955249423Sdim    /// CallLoweringInfo - Constructs a call lowering context based on the
1956249423Sdim    /// provided call information.
1957249423Sdim    CallLoweringInfo(SDValue chain, Type *retTy, bool retSExt, bool retZExt,
1958249423Sdim                     bool isVarArg, bool isInReg, unsigned numFixedArgs,
1959249423Sdim                     CallingConv::ID callConv, bool isTailCall,
1960249423Sdim                     bool doesNotReturn, bool isReturnValueUsed, SDValue callee,
1961249423Sdim                     ArgListTy &args, SelectionDAG &dag, DebugLoc dl)
1962249423Sdim    : Chain(chain), RetTy(retTy), RetSExt(retSExt), RetZExt(retZExt),
1963249423Sdim      IsVarArg(isVarArg), IsInReg(isInReg), DoesNotReturn(doesNotReturn),
1964249423Sdim      IsReturnValueUsed(isReturnValueUsed), IsTailCall(isTailCall),
1965249423Sdim      NumFixedArgs(numFixedArgs), CallConv(callConv), Callee(callee),
1966249423Sdim      Args(args), DAG(dag), DL(dl), CS(NULL) {}
1967249423Sdim  };
1968249423Sdim
1969249423Sdim  /// LowerCallTo - This function lowers an abstract call to a function into an
1970249423Sdim  /// actual call.  This returns a pair of operands.  The first element is the
1971249423Sdim  /// return value for the function (if RetTy is not VoidTy).  The second
1972249423Sdim  /// element is the outgoing token chain. It calls LowerCall to do the actual
1973249423Sdim  /// lowering.
1974249423Sdim  std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
1975249423Sdim
1976249423Sdim  /// LowerCall - This hook must be implemented to lower calls into the
1977249423Sdim  /// the specified DAG. The outgoing arguments to the call are described
1978249423Sdim  /// by the Outs array, and the values to be returned by the call are
1979249423Sdim  /// described by the Ins array. The implementation should fill in the
1980249423Sdim  /// InVals array with legal-type return values from the call, and return
1981249423Sdim  /// the resulting token chain value.
1982249423Sdim  virtual SDValue
1983249423Sdim    LowerCall(CallLoweringInfo &/*CLI*/,
1984249423Sdim              SmallVectorImpl<SDValue> &/*InVals*/) const {
1985249423Sdim    llvm_unreachable("Not Implemented");
1986249423Sdim  }
1987249423Sdim
1988249423Sdim  /// HandleByVal - Target-specific cleanup for formal ByVal parameters.
1989249423Sdim  virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
1990249423Sdim
1991249423Sdim  /// CanLowerReturn - This hook should be implemented to check whether the
1992249423Sdim  /// return values described by the Outs array can fit into the return
1993249423Sdim  /// registers.  If false is returned, an sret-demotion is performed.
1994249423Sdim  ///
1995249423Sdim  virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
1996249423Sdim                              MachineFunction &/*MF*/, bool /*isVarArg*/,
1997249423Sdim               const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
1998249423Sdim               LLVMContext &/*Context*/) const
1999249423Sdim  {
2000249423Sdim    // Return true by default to get preexisting behavior.
2001249423Sdim    return true;
2002249423Sdim  }
2003249423Sdim
2004249423Sdim  /// LowerReturn - This hook must be implemented to lower outgoing
2005249423Sdim  /// return values, described by the Outs array, into the specified
2006249423Sdim  /// DAG. The implementation should return the resulting token chain
2007249423Sdim  /// value.
2008249423Sdim  ///
2009249423Sdim  virtual SDValue
2010249423Sdim    LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
2011249423Sdim                bool /*isVarArg*/,
2012249423Sdim                const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
2013249423Sdim                const SmallVectorImpl<SDValue> &/*OutVals*/,
2014249423Sdim                DebugLoc /*dl*/, SelectionDAG &/*DAG*/) const {
2015249423Sdim    llvm_unreachable("Not Implemented");
2016249423Sdim  }
2017249423Sdim
2018249423Sdim  /// isUsedByReturnOnly - Return true if result of the specified node is used
2019249423Sdim  /// by a return node only. It also compute and return the input chain for the
2020249423Sdim  /// tail call.
2021249423Sdim  /// This is used to determine whether it is possible
2022249423Sdim  /// to codegen a libcall as tail call at legalization time.
2023249423Sdim  virtual bool isUsedByReturnOnly(SDNode *, SDValue &Chain) const {
2024249423Sdim    return false;
2025249423Sdim  }
2026249423Sdim
2027249423Sdim  /// mayBeEmittedAsTailCall - Return true if the target may be able emit the
2028249423Sdim  /// call instruction as a tail call. This is used by optimization passes to
2029249423Sdim  /// determine if it's profitable to duplicate return instructions to enable
2030249423Sdim  /// tailcall optimization.
2031249423Sdim  virtual bool mayBeEmittedAsTailCall(CallInst *) const {
2032249423Sdim    return false;
2033249423Sdim  }
2034249423Sdim
2035249423Sdim  /// getTypeForExtArgOrReturn - Return the type that should be used to zero or
2036249423Sdim  /// sign extend a zeroext/signext integer argument or return value.
2037249423Sdim  /// FIXME: Most C calling convention requires the return type to be promoted,
2038249423Sdim  /// but this is not true all the time, e.g. i1 on x86-64. It is also not
2039249423Sdim  /// necessary for non-C calling conventions. The frontend should handle this
2040249423Sdim  /// and include all of the necessary information.
2041249423Sdim  virtual MVT getTypeForExtArgOrReturn(MVT VT,
2042249423Sdim                                       ISD::NodeType /*ExtendKind*/) const {
2043249423Sdim    MVT MinVT = getRegisterType(MVT::i32);
2044249423Sdim    return VT.bitsLT(MinVT) ? MinVT : VT;
2045249423Sdim  }
2046249423Sdim
2047249423Sdim  /// LowerOperationWrapper - This callback is invoked by the type legalizer
2048249423Sdim  /// to legalize nodes with an illegal operand type but legal result types.
2049249423Sdim  /// It replaces the LowerOperation callback in the type Legalizer.
2050249423Sdim  /// The reason we can not do away with LowerOperation entirely is that
2051249423Sdim  /// LegalizeDAG isn't yet ready to use this callback.
2052249423Sdim  /// TODO: Consider merging with ReplaceNodeResults.
2053249423Sdim
2054249423Sdim  /// The target places new result values for the node in Results (their number
2055249423Sdim  /// and types must exactly match those of the original return values of
2056249423Sdim  /// the node), or leaves Results empty, which indicates that the node is not
2057249423Sdim  /// to be custom lowered after all.
2058249423Sdim  /// The default implementation calls LowerOperation.
2059249423Sdim  virtual void LowerOperationWrapper(SDNode *N,
2060249423Sdim                                     SmallVectorImpl<SDValue> &Results,
2061249423Sdim                                     SelectionDAG &DAG) const;
2062249423Sdim
2063249423Sdim  /// LowerOperation - This callback is invoked for operations that are
2064249423Sdim  /// unsupported by the target, which are registered to use 'custom' lowering,
2065249423Sdim  /// and whose defined values are all legal.
2066249423Sdim  /// If the target has no operations that require custom lowering, it need not
2067249423Sdim  /// implement this.  The default implementation of this aborts.
2068249423Sdim  virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
2069249423Sdim
2070249423Sdim  /// ReplaceNodeResults - This callback is invoked when a node result type is
2071249423Sdim  /// illegal for the target, and the operation was registered to use 'custom'
2072249423Sdim  /// lowering for that result type.  The target places new result values for
2073249423Sdim  /// the node in Results (their number and types must exactly match those of
2074249423Sdim  /// the original return values of the node), or leaves Results empty, which
2075249423Sdim  /// indicates that the node is not to be custom lowered after all.
2076249423Sdim  ///
2077249423Sdim  /// If the target has no operations that require custom lowering, it need not
2078249423Sdim  /// implement this.  The default implementation aborts.
2079249423Sdim  virtual void ReplaceNodeResults(SDNode * /*N*/,
2080249423Sdim                                  SmallVectorImpl<SDValue> &/*Results*/,
2081249423Sdim                                  SelectionDAG &/*DAG*/) const {
2082249423Sdim    llvm_unreachable("ReplaceNodeResults not implemented for this target!");
2083249423Sdim  }
2084249423Sdim
2085249423Sdim  /// getTargetNodeName() - This method returns the name of a target specific
2086249423Sdim  /// DAG node.
2087249423Sdim  virtual const char *getTargetNodeName(unsigned Opcode) const;
2088249423Sdim
2089249423Sdim  /// createFastISel - This method returns a target specific FastISel object,
2090249423Sdim  /// or null if the target does not support "fast" ISel.
2091249423Sdim  virtual FastISel *createFastISel(FunctionLoweringInfo &,
2092249423Sdim                                   const TargetLibraryInfo *) const {
2093249423Sdim    return 0;
2094249423Sdim  }
2095249423Sdim
2096249423Sdim  //===--------------------------------------------------------------------===//
2097249423Sdim  // Inline Asm Support hooks
2098249423Sdim  //
2099249423Sdim
2100249423Sdim  /// ExpandInlineAsm - This hook allows the target to expand an inline asm
2101249423Sdim  /// call to be explicit llvm code if it wants to.  This is useful for
2102249423Sdim  /// turning simple inline asms into LLVM intrinsics, which gives the
2103249423Sdim  /// compiler more information about the behavior of the code.
2104249423Sdim  virtual bool ExpandInlineAsm(CallInst *) const {
2105249423Sdim    return false;
2106249423Sdim  }
2107249423Sdim
2108249423Sdim  enum ConstraintType {
2109249423Sdim    C_Register,            // Constraint represents specific register(s).
2110249423Sdim    C_RegisterClass,       // Constraint represents any of register(s) in class.
2111249423Sdim    C_Memory,              // Memory constraint.
2112249423Sdim    C_Other,               // Something else.
2113249423Sdim    C_Unknown              // Unsupported constraint.
2114249423Sdim  };
2115249423Sdim
2116249423Sdim  enum ConstraintWeight {
2117249423Sdim    // Generic weights.
2118249423Sdim    CW_Invalid  = -1,     // No match.
2119249423Sdim    CW_Okay     = 0,      // Acceptable.
2120249423Sdim    CW_Good     = 1,      // Good weight.
2121249423Sdim    CW_Better   = 2,      // Better weight.
2122249423Sdim    CW_Best     = 3,      // Best weight.
2123249423Sdim
2124249423Sdim    // Well-known weights.
2125249423Sdim    CW_SpecificReg  = CW_Okay,    // Specific register operands.
2126249423Sdim    CW_Register     = CW_Good,    // Register operands.
2127249423Sdim    CW_Memory       = CW_Better,  // Memory operands.
2128249423Sdim    CW_Constant     = CW_Best,    // Constant operand.
2129249423Sdim    CW_Default      = CW_Okay     // Default or don't know type.
2130249423Sdim  };
2131249423Sdim
2132249423Sdim  /// AsmOperandInfo - This contains information for each constraint that we are
2133249423Sdim  /// lowering.
2134249423Sdim  struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
2135249423Sdim    /// ConstraintCode - This contains the actual string for the code, like "m".
2136249423Sdim    /// TargetLowering picks the 'best' code from ConstraintInfo::Codes that
2137249423Sdim    /// most closely matches the operand.
2138249423Sdim    std::string ConstraintCode;
2139249423Sdim
2140249423Sdim    /// ConstraintType - Information about the constraint code, e.g. Register,
2141249423Sdim    /// RegisterClass, Memory, Other, Unknown.
2142249423Sdim    TargetLowering::ConstraintType ConstraintType;
2143249423Sdim
2144249423Sdim    /// CallOperandval - If this is the result output operand or a
2145249423Sdim    /// clobber, this is null, otherwise it is the incoming operand to the
2146249423Sdim    /// CallInst.  This gets modified as the asm is processed.
2147249423Sdim    Value *CallOperandVal;
2148249423Sdim
2149249423Sdim    /// ConstraintVT - The ValueType for the operand value.
2150249423Sdim    MVT ConstraintVT;
2151249423Sdim
2152249423Sdim    /// isMatchingInputConstraint - Return true of this is an input operand that
2153249423Sdim    /// is a matching constraint like "4".
2154249423Sdim    bool isMatchingInputConstraint() const;
2155249423Sdim
2156249423Sdim    /// getMatchedOperand - If this is an input matching constraint, this method
2157249423Sdim    /// returns the output operand it matches.
2158249423Sdim    unsigned getMatchedOperand() const;
2159249423Sdim
2160249423Sdim    /// Copy constructor for copying from an AsmOperandInfo.
2161249423Sdim    AsmOperandInfo(const AsmOperandInfo &info)
2162249423Sdim      : InlineAsm::ConstraintInfo(info),
2163249423Sdim        ConstraintCode(info.ConstraintCode),
2164249423Sdim        ConstraintType(info.ConstraintType),
2165249423Sdim        CallOperandVal(info.CallOperandVal),
2166249423Sdim        ConstraintVT(info.ConstraintVT) {
2167249423Sdim    }
2168249423Sdim
2169249423Sdim    /// Copy constructor for copying from a ConstraintInfo.
2170249423Sdim    AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
2171249423Sdim      : InlineAsm::ConstraintInfo(info),
2172249423Sdim        ConstraintType(TargetLowering::C_Unknown),
2173249423Sdim        CallOperandVal(0), ConstraintVT(MVT::Other) {
2174249423Sdim    }
2175249423Sdim  };
2176249423Sdim
2177249423Sdim  typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
2178249423Sdim
2179249423Sdim  /// ParseConstraints - Split up the constraint string from the inline
2180249423Sdim  /// assembly value into the specific constraints and their prefixes,
2181249423Sdim  /// and also tie in the associated operand values.
2182249423Sdim  /// If this returns an empty vector, and if the constraint string itself
2183249423Sdim  /// isn't empty, there was an error parsing.
2184249423Sdim  virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const;
2185249423Sdim
2186249423Sdim  /// Examine constraint type and operand type and determine a weight value.
2187249423Sdim  /// The operand object must already have been set up with the operand type.
2188249423Sdim  virtual ConstraintWeight getMultipleConstraintMatchWeight(
2189249423Sdim      AsmOperandInfo &info, int maIndex) const;
2190249423Sdim
2191249423Sdim  /// Examine constraint string and operand type and determine a weight value.
2192249423Sdim  /// The operand object must already have been set up with the operand type.
2193249423Sdim  virtual ConstraintWeight getSingleConstraintMatchWeight(
2194249423Sdim      AsmOperandInfo &info, const char *constraint) const;
2195249423Sdim
2196249423Sdim  /// ComputeConstraintToUse - Determines the constraint code and constraint
2197249423Sdim  /// type to use for the specific AsmOperandInfo, setting
2198249423Sdim  /// OpInfo.ConstraintCode and OpInfo.ConstraintType.  If the actual operand
2199249423Sdim  /// being passed in is available, it can be passed in as Op, otherwise an
2200249423Sdim  /// empty SDValue can be passed.
2201249423Sdim  virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2202249423Sdim                                      SDValue Op,
2203249423Sdim                                      SelectionDAG *DAG = 0) const;
2204249423Sdim
2205249423Sdim  /// getConstraintType - Given a constraint, return the type of constraint it
2206249423Sdim  /// is for this target.
2207249423Sdim  virtual ConstraintType getConstraintType(const std::string &Constraint) const;
2208249423Sdim
2209249423Sdim  /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
2210249423Sdim  /// {edx}), return the register number and the register class for the
2211249423Sdim  /// register.
2212249423Sdim  ///
2213249423Sdim  /// Given a register class constraint, like 'r', if this corresponds directly
2214249423Sdim  /// to an LLVM register class, return a register of 0 and the register class
2215249423Sdim  /// pointer.
2216249423Sdim  ///
2217249423Sdim  /// This should only be used for C_Register constraints.  On error,
2218249423Sdim  /// this returns a register number of 0 and a null register class pointer..
2219249423Sdim  virtual std::pair<unsigned, const TargetRegisterClass*>
2220249423Sdim    getRegForInlineAsmConstraint(const std::string &Constraint,
2221249423Sdim                                 EVT VT) const;
2222249423Sdim
2223249423Sdim  /// LowerXConstraint - try to replace an X constraint, which matches anything,
2224249423Sdim  /// with another that has more specific requirements based on the type of the
2225249423Sdim  /// corresponding operand.  This returns null if there is no replacement to
2226249423Sdim  /// make.
2227249423Sdim  virtual const char *LowerXConstraint(EVT ConstraintVT) const;
2228249423Sdim
2229249423Sdim  /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2230249423Sdim  /// vector.  If it is invalid, don't add anything to Ops.
2231249423Sdim  virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
2232249423Sdim                                            std::vector<SDValue> &Ops,
2233249423Sdim                                            SelectionDAG &DAG) const;
2234249423Sdim
2235249423Sdim  //===--------------------------------------------------------------------===//
2236249423Sdim  // Div utility functions
2237249423Sdim  //
2238249423Sdim  SDValue BuildExactSDIV(SDValue Op1, SDValue Op2, DebugLoc dl,
2239249423Sdim                         SelectionDAG &DAG) const;
2240249423Sdim  SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2241249423Sdim                      std::vector<SDNode*> *Created) const;
2242249423Sdim  SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2243249423Sdim                      std::vector<SDNode*> *Created) const;
2244249423Sdim
2245249423Sdim  //===--------------------------------------------------------------------===//
2246249423Sdim  // Instruction Emitting Hooks
2247249423Sdim  //
2248249423Sdim
2249249423Sdim  // EmitInstrWithCustomInserter - This method should be implemented by targets
2250249423Sdim  // that mark instructions with the 'usesCustomInserter' flag.  These
2251249423Sdim  // instructions are special in various ways, which require special support to
2252249423Sdim  // insert.  The specified MachineInstr is created but not inserted into any
2253249423Sdim  // basic blocks, and this method is called to expand it into a sequence of
2254249423Sdim  // instructions, potentially also creating new basic blocks and control flow.
2255249423Sdim  virtual MachineBasicBlock *
2256249423Sdim    EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const;
2257249423Sdim
2258249423Sdim  /// AdjustInstrPostInstrSelection - This method should be implemented by
2259249423Sdim  /// targets that mark instructions with the 'hasPostISelHook' flag. These
2260249423Sdim  /// instructions must be adjusted after instruction selection by target hooks.
2261249423Sdim  /// e.g. To fill in optional defs for ARM 's' setting instructions.
2262249423Sdim  virtual void
2263249423Sdim  AdjustInstrPostInstrSelection(MachineInstr *MI, SDNode *Node) const;
2264249423Sdim};
2265249423Sdim
2266210299Sed/// GetReturnInfo - Given an LLVM IR type and return type attributes,
2267210299Sed/// compute the return value EVTs and flags, and optionally also
2268210299Sed/// the offsets, if the return value is being lowered to memory.
2269249423Sdimvoid GetReturnInfo(Type* ReturnType, AttributeSet attr,
2270210299Sed                   SmallVectorImpl<ISD::OutputArg> &Outs,
2271239462Sdim                   const TargetLowering &TLI);
2272210299Sed
2273193323Sed} // end llvm namespace
2274193323Sed
2275193323Sed#endif
2276