1 //===-- llvm/Target/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file describes how to lower LLVM code to machine code. This has two
13 // 1. Which ValueTypes are natively supported by the target.
14 // 2. Which operations are supported for supported ValueTypes.
15 // 3. Cost thresholds for alternative implementations of certain operations.
17 // In addition it has a few other components, like information about FP
20 //===----------------------------------------------------------------------===//
22 #ifndef LLVM_TARGET_TARGETLOWERING_H
23 #define LLVM_TARGET_TARGETLOWERING_H
25 #include "llvm/CallingConv.h"
26 #include "llvm/InlineAsm.h"
27 #include "llvm/Attributes.h"
28 #include "llvm/Support/CallSite.h"
29 #include "llvm/CodeGen/SelectionDAGNodes.h"
30 #include "llvm/CodeGen/RuntimeLibcalls.h"
31 #include "llvm/Support/DebugLoc.h"
32 #include "llvm/Target/TargetCallingConv.h"
33 #include "llvm/Target/TargetMachine.h"
42 class FunctionLoweringInfo;
43 class ImmutableCallSite;
45 class MachineBasicBlock;
46 class MachineFunction;
48 class MachineJumpTableInfo;
51 template<typename T> class SmallVectorImpl;
53 class TargetRegisterClass;
54 class TargetLibraryInfo;
55 class TargetLoweringObjectFile;
60 None, // No preference
61 Source, // Follow source order.
62 RegPressure, // Scheduling for lowest register pressure.
63 Hybrid, // Scheduling for both latency and register pressure.
64 ILP, // Scheduling for ILP in low register pressure mode.
65 VLIW // Scheduling for VLIW targets.
70 //===----------------------------------------------------------------------===//
71 /// TargetLowering - This class defines information used to lower LLVM code to
72 /// legal SelectionDAG operators that the target instruction selector can accept
75 /// This class also defines callbacks that targets must implement to lower
76 /// target-specific constructs to SelectionDAG operators.
78 class TargetLowering {
79 TargetLowering(const TargetLowering&); // DO NOT IMPLEMENT
80 void operator=(const TargetLowering&); // DO NOT IMPLEMENT
82 /// LegalizeAction - This enum indicates whether operations are valid for a
83 /// target, and if not, what action should be used to make them valid.
85 Legal, // The target natively supports this operation.
86 Promote, // This operation should be executed in a larger type.
87 Expand, // Try to expand this to other ops, otherwise use a libcall.
88 Custom // Use the LowerOperation hook to implement custom lowering.
91 /// LegalizeTypeAction - This enum indicates whether a types are legal for a
92 /// target, and if not, what action should be used to make them valid.
93 enum LegalizeTypeAction {
94 TypeLegal, // The target natively supports this type.
95 TypePromoteInteger, // Replace this integer with a larger one.
96 TypeExpandInteger, // Split this integer into two of half the size.
97 TypeSoftenFloat, // Convert this float to a same size integer type.
98 TypeExpandFloat, // Split this float into two of half the size.
99 TypeScalarizeVector, // Replace this one-element vector with its element.
100 TypeSplitVector, // Split this vector into two of half the size.
101 TypeWidenVector // This vector should be widened into a larger vector.
104 enum BooleanContent { // How the target represents true/false values.
105 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
106 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
107 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
110 static ISD::NodeType getExtendForContent(BooleanContent Content) {
112 case UndefinedBooleanContent:
113 // Extend by adding rubbish bits.
114 return ISD::ANY_EXTEND;
115 case ZeroOrOneBooleanContent:
116 // Extend by adding zero bits.
117 return ISD::ZERO_EXTEND;
118 case ZeroOrNegativeOneBooleanContent:
119 // Extend by copying the sign bit.
120 return ISD::SIGN_EXTEND;
122 llvm_unreachable("Invalid content kind");
125 /// NOTE: The constructor takes ownership of TLOF.
126 explicit TargetLowering(const TargetMachine &TM,
127 const TargetLoweringObjectFile *TLOF);
128 virtual ~TargetLowering();
130 const TargetMachine &getTargetMachine() const { return TM; }
131 const TargetData *getTargetData() const { return TD; }
132 const TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; }
134 bool isBigEndian() const { return !IsLittleEndian; }
135 bool isLittleEndian() const { return IsLittleEndian; }
136 MVT getPointerTy() const { return PointerTy; }
137 virtual MVT getShiftAmountTy(EVT LHSTy) const;
139 /// isSelectExpensive - Return true if the select operation is expensive for
141 bool isSelectExpensive() const { return SelectIsExpensive; }
143 /// isIntDivCheap() - Return true if integer divide is usually cheaper than
144 /// a sequence of several shifts, adds, and multiplies for this target.
145 bool isIntDivCheap() const { return IntDivIsCheap; }
147 /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
149 bool isPow2DivCheap() const { return Pow2DivIsCheap; }
151 /// isJumpExpensive() - Return true if Flow Control is an expensive operation
152 /// that should be avoided.
153 bool isJumpExpensive() const { return JumpIsExpensive; }
155 /// isPredictableSelectExpensive - Return true if selects are only cheaper
156 /// than branches if the branch is unlikely to be predicted right.
157 bool isPredictableSelectExpensive() const {
158 return predictableSelectIsExpensive;
161 /// getSetCCResultType - Return the ValueType of the result of SETCC
162 /// operations. Also used to obtain the target's preferred type for
163 /// the condition operand of SELECT and BRCOND nodes. In the case of
164 /// BRCOND the argument passed is MVT::Other since there are no other
165 /// operands to get a type hint from.
166 virtual EVT getSetCCResultType(EVT VT) const;
168 /// getCmpLibcallReturnType - Return the ValueType for comparison
169 /// libcalls. Comparions libcalls include floating point comparion calls,
170 /// and Ordered/Unordered check calls on floating point numbers.
172 MVT::SimpleValueType getCmpLibcallReturnType() const;
174 /// getBooleanContents - For targets without i1 registers, this gives the
175 /// nature of the high-bits of boolean values held in types wider than i1.
176 /// "Boolean values" are special true/false values produced by nodes like
177 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
178 /// Not to be confused with general values promoted from i1.
179 /// Some cpus distinguish between vectors of boolean and scalars; the isVec
180 /// parameter selects between the two kinds. For example on X86 a scalar
181 /// boolean should be zero extended from i1, while the elements of a vector
182 /// of booleans should be sign extended from i1.
183 BooleanContent getBooleanContents(bool isVec) const {
184 return isVec ? BooleanVectorContents : BooleanContents;
187 /// getSchedulingPreference - Return target scheduling preference.
188 Sched::Preference getSchedulingPreference() const {
189 return SchedPreferenceInfo;
192 /// getSchedulingPreference - Some scheduler, e.g. hybrid, can switch to
193 /// different scheduling heuristics for different nodes. This function returns
194 /// the preference (or none) for the given node.
195 virtual Sched::Preference getSchedulingPreference(SDNode *) const {
199 /// getRegClassFor - Return the register class that should be used for the
200 /// specified value type.
201 virtual const TargetRegisterClass *getRegClassFor(EVT VT) const {
202 assert(VT.isSimple() && "getRegClassFor called on illegal type!");
203 const TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT().SimpleTy];
204 assert(RC && "This value type is not natively supported!");
208 /// getRepRegClassFor - Return the 'representative' register class for the
209 /// specified value type. The 'representative' register class is the largest
210 /// legal super-reg register class for the register class of the value type.
211 /// For example, on i386 the rep register class for i8, i16, and i32 are GR32;
212 /// while the rep register class is GR64 on x86_64.
213 virtual const TargetRegisterClass *getRepRegClassFor(EVT VT) const {
214 assert(VT.isSimple() && "getRepRegClassFor called on illegal type!");
215 const TargetRegisterClass *RC = RepRegClassForVT[VT.getSimpleVT().SimpleTy];
219 /// getRepRegClassCostFor - Return the cost of the 'representative' register
220 /// class for the specified value type.
221 virtual uint8_t getRepRegClassCostFor(EVT VT) const {
222 assert(VT.isSimple() && "getRepRegClassCostFor called on illegal type!");
223 return RepRegClassCostForVT[VT.getSimpleVT().SimpleTy];
226 /// isTypeLegal - Return true if the target has native support for the
227 /// specified value type. This means that it has a register that directly
228 /// holds it without promotions or expansions.
229 bool isTypeLegal(EVT VT) const {
230 assert(!VT.isSimple() ||
231 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
232 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != 0;
235 class ValueTypeActionImpl {
236 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
237 /// that indicates how instruction selection should deal with the type.
238 uint8_t ValueTypeActions[MVT::LAST_VALUETYPE];
241 ValueTypeActionImpl() {
242 std::fill(ValueTypeActions, array_endof(ValueTypeActions), 0);
245 LegalizeTypeAction getTypeAction(MVT VT) const {
246 return (LegalizeTypeAction)ValueTypeActions[VT.SimpleTy];
249 void setTypeAction(EVT VT, LegalizeTypeAction Action) {
250 unsigned I = VT.getSimpleVT().SimpleTy;
251 ValueTypeActions[I] = Action;
255 const ValueTypeActionImpl &getValueTypeActions() const {
256 return ValueTypeActions;
259 /// getTypeAction - Return how we should legalize values of this type, either
260 /// it is already legal (return 'Legal') or we need to promote it to a larger
261 /// type (return 'Promote'), or we need to expand it into multiple registers
262 /// of smaller integer type (return 'Expand'). 'Custom' is not an option.
263 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
264 return getTypeConversion(Context, VT).first;
266 LegalizeTypeAction getTypeAction(MVT VT) const {
267 return ValueTypeActions.getTypeAction(VT);
270 /// getTypeToTransformTo - For types supported by the target, this is an
271 /// identity function. For types that must be promoted to larger types, this
272 /// returns the larger type to promote to. For integer types that are larger
273 /// than the largest integer register, this contains one step in the expansion
274 /// to get to the smaller register. For illegal floating point types, this
275 /// returns the integer type to transform to.
276 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
277 return getTypeConversion(Context, VT).second;
280 /// getTypeToExpandTo - For types supported by the target, this is an
281 /// identity function. For types that must be expanded (i.e. integer types
282 /// that are larger than the largest integer register or illegal floating
283 /// point types), this returns the largest legal type it will be expanded to.
284 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
285 assert(!VT.isVector());
287 switch (getTypeAction(Context, VT)) {
290 case TypeExpandInteger:
291 VT = getTypeToTransformTo(Context, VT);
294 llvm_unreachable("Type is not legal nor is it to be expanded!");
299 /// getVectorTypeBreakdown - Vector types are broken down into some number of
300 /// legal first class types. For example, EVT::v8f32 maps to 2 EVT::v4f32
301 /// with Altivec or SSE1, or 8 promoted EVT::f64 values with the X86 FP stack.
302 /// Similarly, EVT::v2i64 turns into 4 EVT::i32 values with both PPC and X86.
304 /// This method returns the number of registers needed, and the VT for each
305 /// register. It also returns the VT and quantity of the intermediate values
306 /// before they are promoted/expanded.
308 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
310 unsigned &NumIntermediates,
311 EVT &RegisterVT) const;
313 /// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the
314 /// intrinsic will need to map to a MemIntrinsicNode (touches memory). If
315 /// this is the case, it returns true and store the intrinsic
316 /// information into the IntrinsicInfo that was passed to the function.
317 struct IntrinsicInfo {
318 unsigned opc; // target opcode
319 EVT memVT; // memory VT
320 const Value* ptrVal; // value representing memory location
321 int offset; // offset off of ptrVal
322 unsigned align; // alignment
323 bool vol; // is volatile?
324 bool readMem; // reads memory?
325 bool writeMem; // writes memory?
328 virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
329 unsigned /*Intrinsic*/) const {
333 /// isFPImmLegal - Returns true if the target can instruction select the
334 /// specified FP immediate natively. If false, the legalizer will materialize
335 /// the FP immediate as a load from a constant pool.
336 virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
340 /// isShuffleMaskLegal - Targets can use this to indicate that they only
341 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
342 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
343 /// are assumed to be legal.
344 virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
349 /// canOpTrap - Returns true if the operation can trap for the value type.
350 /// VT must be a legal type. By default, we optimistically assume most
351 /// operations don't trap except for divide and remainder.
352 virtual bool canOpTrap(unsigned Op, EVT VT) const;
354 /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
355 /// used by Targets can use this to indicate if there is a suitable
356 /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
358 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
363 /// getOperationAction - Return how this operation should be treated: either
364 /// it is legal, needs to be promoted to a larger size, needs to be
365 /// expanded to some other code sequence, or the target has a custom expander
367 LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
368 if (VT.isExtended()) return Expand;
369 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
370 unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
371 return (LegalizeAction)OpActions[I][Op];
374 /// isOperationLegalOrCustom - Return true if the specified operation is
375 /// legal on this target or can be made legal with custom lowering. This
376 /// is used to help guide high-level lowering decisions.
377 bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
378 return (VT == MVT::Other || isTypeLegal(VT)) &&
379 (getOperationAction(Op, VT) == Legal ||
380 getOperationAction(Op, VT) == Custom);
383 /// isOperationLegal - Return true if the specified operation is legal on this
385 bool isOperationLegal(unsigned Op, EVT VT) const {
386 return (VT == MVT::Other || isTypeLegal(VT)) &&
387 getOperationAction(Op, VT) == Legal;
390 /// getLoadExtAction - Return how this load with extension should be treated:
391 /// either it is legal, needs to be promoted to a larger size, needs to be
392 /// expanded to some other code sequence, or the target has a custom expander
394 LegalizeAction getLoadExtAction(unsigned ExtType, EVT VT) const {
395 assert(ExtType < ISD::LAST_LOADEXT_TYPE &&
396 VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
397 "Table isn't big enough!");
398 return (LegalizeAction)LoadExtActions[VT.getSimpleVT().SimpleTy][ExtType];
401 /// isLoadExtLegal - Return true if the specified load with extension is legal
403 bool isLoadExtLegal(unsigned ExtType, EVT VT) const {
404 return VT.isSimple() && getLoadExtAction(ExtType, VT) == Legal;
407 /// getTruncStoreAction - Return how this store with truncation should be
408 /// treated: either it is legal, needs to be promoted to a larger size, needs
409 /// to be expanded to some other code sequence, or the target has a custom
411 LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
412 assert(ValVT.getSimpleVT() < MVT::LAST_VALUETYPE &&
413 MemVT.getSimpleVT() < MVT::LAST_VALUETYPE &&
414 "Table isn't big enough!");
415 return (LegalizeAction)TruncStoreActions[ValVT.getSimpleVT().SimpleTy]
416 [MemVT.getSimpleVT().SimpleTy];
419 /// isTruncStoreLegal - Return true if the specified store with truncation is
420 /// legal on this target.
421 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
422 return isTypeLegal(ValVT) && MemVT.isSimple() &&
423 getTruncStoreAction(ValVT, MemVT) == Legal;
426 /// getIndexedLoadAction - Return how the indexed load should be treated:
427 /// either it is legal, needs to be promoted to a larger size, needs to be
428 /// expanded to some other code sequence, or the target has a custom expander
431 getIndexedLoadAction(unsigned IdxMode, EVT VT) const {
432 assert(IdxMode < ISD::LAST_INDEXED_MODE &&
433 VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
434 "Table isn't big enough!");
435 unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy;
436 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
439 /// isIndexedLoadLegal - Return true if the specified indexed load is legal
441 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
442 return VT.isSimple() &&
443 (getIndexedLoadAction(IdxMode, VT) == Legal ||
444 getIndexedLoadAction(IdxMode, VT) == Custom);
447 /// getIndexedStoreAction - Return how the indexed store should be treated:
448 /// either it is legal, needs to be promoted to a larger size, needs to be
449 /// expanded to some other code sequence, or the target has a custom expander
452 getIndexedStoreAction(unsigned IdxMode, EVT VT) const {
453 assert(IdxMode < ISD::LAST_INDEXED_MODE &&
454 VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
455 "Table isn't big enough!");
456 unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy;
457 return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
460 /// isIndexedStoreLegal - Return true if the specified indexed load is legal
462 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
463 return VT.isSimple() &&
464 (getIndexedStoreAction(IdxMode, VT) == Legal ||
465 getIndexedStoreAction(IdxMode, VT) == Custom);
468 /// getCondCodeAction - Return how the condition code should be treated:
469 /// either it is legal, needs to be expanded to some other code sequence,
470 /// or the target has a custom expander for it.
472 getCondCodeAction(ISD::CondCode CC, EVT VT) const {
473 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
474 (unsigned)VT.getSimpleVT().SimpleTy < sizeof(CondCodeActions[0])*4 &&
475 "Table isn't big enough!");
476 LegalizeAction Action = (LegalizeAction)
477 ((CondCodeActions[CC] >> (2*VT.getSimpleVT().SimpleTy)) & 3);
478 assert(Action != Promote && "Can't promote condition code!");
482 /// isCondCodeLegal - Return true if the specified condition code is legal
484 bool isCondCodeLegal(ISD::CondCode CC, EVT VT) const {
485 return getCondCodeAction(CC, VT) == Legal ||
486 getCondCodeAction(CC, VT) == Custom;
490 /// getTypeToPromoteTo - If the action for this operation is to promote, this
491 /// method returns the ValueType to promote to.
492 EVT getTypeToPromoteTo(unsigned Op, EVT VT) const {
493 assert(getOperationAction(Op, VT) == Promote &&
494 "This operation isn't promoted!");
496 // See if this has an explicit type specified.
497 std::map<std::pair<unsigned, MVT::SimpleValueType>,
498 MVT::SimpleValueType>::const_iterator PTTI =
499 PromoteToType.find(std::make_pair(Op, VT.getSimpleVT().SimpleTy));
500 if (PTTI != PromoteToType.end()) return PTTI->second;
502 assert((VT.isInteger() || VT.isFloatingPoint()) &&
503 "Cannot autopromote this type, add it with AddPromotedToType.");
507 NVT = (MVT::SimpleValueType)(NVT.getSimpleVT().SimpleTy+1);
508 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
509 "Didn't find type to promote to!");
510 } while (!isTypeLegal(NVT) ||
511 getOperationAction(Op, NVT) == Promote);
515 /// getValueType - Return the EVT corresponding to this LLVM type.
516 /// This is fixed by the LLVM operations except for the pointer size. If
517 /// AllowUnknown is true, this will return MVT::Other for types with no EVT
518 /// counterpart (e.g. structs), otherwise it will assert.
519 EVT getValueType(Type *Ty, bool AllowUnknown = false) const {
520 // Lower scalar pointers to native pointer types.
521 if (Ty->isPointerTy()) return PointerTy;
523 if (Ty->isVectorTy()) {
524 VectorType *VTy = cast<VectorType>(Ty);
525 Type *Elm = VTy->getElementType();
526 // Lower vectors of pointers to native pointer types.
527 if (Elm->isPointerTy())
528 Elm = EVT(PointerTy).getTypeForEVT(Ty->getContext());
529 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
530 VTy->getNumElements());
532 return EVT::getEVT(Ty, AllowUnknown);
535 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
536 /// function arguments in the caller parameter area. This is the actual
537 /// alignment, not its logarithm.
538 virtual unsigned getByValTypeAlignment(Type *Ty) const;
540 /// getRegisterType - Return the type of registers that this ValueType will
541 /// eventually require.
542 EVT getRegisterType(MVT VT) const {
543 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
544 return RegisterTypeForVT[VT.SimpleTy];
547 /// getRegisterType - Return the type of registers that this ValueType will
548 /// eventually require.
549 EVT getRegisterType(LLVMContext &Context, EVT VT) const {
551 assert((unsigned)VT.getSimpleVT().SimpleTy <
552 array_lengthof(RegisterTypeForVT));
553 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
557 unsigned NumIntermediates;
558 (void)getVectorTypeBreakdown(Context, VT, VT1,
559 NumIntermediates, RegisterVT);
562 if (VT.isInteger()) {
563 return getRegisterType(Context, getTypeToTransformTo(Context, VT));
565 llvm_unreachable("Unsupported extended type!");
568 /// getNumRegisters - Return the number of registers that this ValueType will
569 /// eventually require. This is one for any types promoted to live in larger
570 /// registers, but may be more than one for types (like i64) that are split
571 /// into pieces. For types like i140, which are first promoted then expanded,
572 /// it is the number of registers needed to hold all the bits of the original
573 /// type. For an i140 on a 32 bit machine this means 5 registers.
574 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
576 assert((unsigned)VT.getSimpleVT().SimpleTy <
577 array_lengthof(NumRegistersForVT));
578 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
582 unsigned NumIntermediates;
583 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
585 if (VT.isInteger()) {
586 unsigned BitWidth = VT.getSizeInBits();
587 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
588 return (BitWidth + RegWidth - 1) / RegWidth;
590 llvm_unreachable("Unsupported extended type!");
593 /// ShouldShrinkFPConstant - If true, then instruction selection should
594 /// seek to shrink the FP constant of the specified type to a smaller type
595 /// in order to save space and / or reduce runtime.
596 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
598 /// hasTargetDAGCombine - If true, the target has custom DAG combine
599 /// transformations that it can perform for the specified node.
600 bool hasTargetDAGCombine(ISD::NodeType NT) const {
601 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
602 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
605 /// This function returns the maximum number of store operations permitted
606 /// to replace a call to llvm.memset. The value is set by the target at the
607 /// performance threshold for such a replacement. If OptSize is true,
608 /// return the limit for functions that have OptSize attribute.
609 /// @brief Get maximum # of store operations permitted for llvm.memset
610 unsigned getMaxStoresPerMemset(bool OptSize) const {
611 return OptSize ? maxStoresPerMemsetOptSize : maxStoresPerMemset;
614 /// This function returns the maximum number of store operations permitted
615 /// to replace a call to llvm.memcpy. The value is set by the target at the
616 /// performance threshold for such a replacement. If OptSize is true,
617 /// return the limit for functions that have OptSize attribute.
618 /// @brief Get maximum # of store operations permitted for llvm.memcpy
619 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
620 return OptSize ? maxStoresPerMemcpyOptSize : maxStoresPerMemcpy;
623 /// This function returns the maximum number of store operations permitted
624 /// to replace a call to llvm.memmove. The value is set by the target at the
625 /// performance threshold for such a replacement. If OptSize is true,
626 /// return the limit for functions that have OptSize attribute.
627 /// @brief Get maximum # of store operations permitted for llvm.memmove
628 unsigned getMaxStoresPerMemmove(bool OptSize) const {
629 return OptSize ? maxStoresPerMemmoveOptSize : maxStoresPerMemmove;
632 /// This function returns true if the target allows unaligned memory accesses.
633 /// of the specified type. This is used, for example, in situations where an
634 /// array copy/move/set is converted to a sequence of store operations. It's
635 /// use helps to ensure that such replacements don't generate code that causes
636 /// an alignment error (trap) on the target machine.
637 /// @brief Determine if the target supports unaligned memory accesses.
638 virtual bool allowsUnalignedMemoryAccesses(EVT) const {
642 /// This function returns true if the target would benefit from code placement
644 /// @brief Determine if the target should perform code placement optimization.
645 bool shouldOptimizeCodePlacement() const {
646 return benefitFromCodePlacementOpt;
649 /// getOptimalMemOpType - Returns the target specific optimal type for load
650 /// and store operations as a result of memset, memcpy, and memmove
651 /// lowering. If DstAlign is zero that means it's safe to destination
652 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
653 /// means there isn't a need to check it against alignment requirement,
654 /// probably because the source does not need to be loaded. If
655 /// 'IsZeroVal' is true, that means it's safe to return a
656 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
657 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
658 /// constant so it does not need to be loaded.
659 /// It returns EVT::Other if the type should be determined using generic
660 /// target-independent logic.
661 virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
662 unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
664 bool /*MemcpyStrSrc*/,
665 MachineFunction &/*MF*/) const {
669 /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
670 /// to implement llvm.setjmp.
671 bool usesUnderscoreSetJmp() const {
672 return UseUnderscoreSetJmp;
675 /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
676 /// to implement llvm.longjmp.
677 bool usesUnderscoreLongJmp() const {
678 return UseUnderscoreLongJmp;
681 /// supportJumpTables - return whether the target can generate code for
683 bool supportJumpTables() const {
684 return SupportJumpTables;
687 /// getStackPointerRegisterToSaveRestore - If a physical register, this
688 /// specifies the register that llvm.savestack/llvm.restorestack should save
690 unsigned getStackPointerRegisterToSaveRestore() const {
691 return StackPointerRegisterToSaveRestore;
694 /// getExceptionPointerRegister - If a physical register, this returns
695 /// the register that receives the exception address on entry to a landing
697 unsigned getExceptionPointerRegister() const {
698 return ExceptionPointerRegister;
701 /// getExceptionSelectorRegister - If a physical register, this returns
702 /// the register that receives the exception typeid on entry to a landing
704 unsigned getExceptionSelectorRegister() const {
705 return ExceptionSelectorRegister;
708 /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
709 /// set, the default is 200)
710 unsigned getJumpBufSize() const {
714 /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
715 /// (if never set, the default is 0)
716 unsigned getJumpBufAlignment() const {
717 return JumpBufAlignment;
720 /// getMinStackArgumentAlignment - return the minimum stack alignment of an
722 unsigned getMinStackArgumentAlignment() const {
723 return MinStackArgumentAlignment;
726 /// getMinFunctionAlignment - return the minimum function alignment.
728 unsigned getMinFunctionAlignment() const {
729 return MinFunctionAlignment;
732 /// getPrefFunctionAlignment - return the preferred function alignment.
734 unsigned getPrefFunctionAlignment() const {
735 return PrefFunctionAlignment;
738 /// getPrefLoopAlignment - return the preferred loop alignment.
740 unsigned getPrefLoopAlignment() const {
741 return PrefLoopAlignment;
744 /// getShouldFoldAtomicFences - return whether the combiner should fold
745 /// fence MEMBARRIER instructions into the atomic intrinsic instructions.
747 bool getShouldFoldAtomicFences() const {
748 return ShouldFoldAtomicFences;
751 /// getInsertFencesFor - return whether the DAG builder should automatically
752 /// insert fences and reduce ordering for atomics.
754 bool getInsertFencesForAtomic() const {
755 return InsertFencesForAtomic;
758 /// getPreIndexedAddressParts - returns true by value, base pointer and
759 /// offset pointer and addressing mode by reference if the node's address
760 /// can be legally represented as pre-indexed load / store address.
761 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
763 ISD::MemIndexedMode &/*AM*/,
764 SelectionDAG &/*DAG*/) const {
768 /// getPostIndexedAddressParts - returns true by value, base pointer and
769 /// offset pointer and addressing mode by reference if this node can be
770 /// combined with a load / store to form a post-indexed load / store.
771 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
772 SDValue &/*Base*/, SDValue &/*Offset*/,
773 ISD::MemIndexedMode &/*AM*/,
774 SelectionDAG &/*DAG*/) const {
778 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
779 /// current function. The returned value is a member of the
780 /// MachineJumpTableInfo::JTEntryKind enum.
781 virtual unsigned getJumpTableEncoding() const;
783 virtual const MCExpr *
784 LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
785 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
786 MCContext &/*Ctx*/) const {
787 llvm_unreachable("Need to implement this hook if target has custom JTIs");
790 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
792 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
793 SelectionDAG &DAG) const;
795 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
796 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
798 virtual const MCExpr *
799 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
800 unsigned JTI, MCContext &Ctx) const;
802 /// isOffsetFoldingLegal - Return true if folding a constant offset
803 /// with the given GlobalAddress is legal. It is frequently not legal in
804 /// PIC relocation models.
805 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
807 /// getStackCookieLocation - Return true if the target stores stack
808 /// protector cookies at a fixed offset in some non-standard address
809 /// space, and populates the address space and offset as
811 virtual bool getStackCookieLocation(unsigned &/*AddressSpace*/,
812 unsigned &/*Offset*/) const {
816 /// getMaximalGlobalOffset - Returns the maximal possible offset which can be
817 /// used for loads / stores from the global.
818 virtual unsigned getMaximalGlobalOffset() const {
822 //===--------------------------------------------------------------------===//
823 // TargetLowering Optimization Methods
826 /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
827 /// SDValues for returning information from TargetLowering to its clients
828 /// that want to combine
829 struct TargetLoweringOpt {
836 explicit TargetLoweringOpt(SelectionDAG &InDAG,
838 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
840 bool LegalTypes() const { return LegalTys; }
841 bool LegalOperations() const { return LegalOps; }
843 bool CombineTo(SDValue O, SDValue N) {
849 /// ShrinkDemandedConstant - Check to see if the specified operand of the
850 /// specified instruction is a constant integer. If so, check to see if
851 /// there are any bits set in the constant that are not demanded. If so,
852 /// shrink the constant and return true.
853 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
855 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
856 /// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening
857 /// cast, but it could be generalized for targets with other types of
858 /// implicit widening casts.
859 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
863 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
864 /// DemandedMask bits of the result of Op are ever used downstream. If we can
865 /// use this information to simplify Op, create a new simplified DAG node and
866 /// return true, returning the original and new nodes in Old and New.
867 /// Otherwise, analyze the expression and return a mask of KnownOne and
868 /// KnownZero bits for the expression (used to simplify the caller).
869 /// The KnownZero/One bits may only be accurate for those bits in the
871 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
872 APInt &KnownZero, APInt &KnownOne,
873 TargetLoweringOpt &TLO, unsigned Depth = 0) const;
875 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
876 /// Mask are known to be either zero or one and return them in the
877 /// KnownZero/KnownOne bitsets.
878 virtual void computeMaskedBitsForTargetNode(const SDValue Op,
881 const SelectionDAG &DAG,
882 unsigned Depth = 0) const;
884 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
885 /// targets that want to expose additional information about sign bits to the
887 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
888 unsigned Depth = 0) const;
890 struct DAGCombinerInfo {
891 void *DC; // The DAG Combiner object.
893 bool BeforeLegalizeOps;
894 bool CalledByLegalizer;
898 DAGCombinerInfo(SelectionDAG &dag, bool bl, bool blo, bool cl, void *dc)
899 : DC(dc), BeforeLegalize(bl), BeforeLegalizeOps(blo),
900 CalledByLegalizer(cl), DAG(dag) {}
902 bool isBeforeLegalize() const { return BeforeLegalize; }
903 bool isBeforeLegalizeOps() const { return BeforeLegalizeOps; }
904 bool isCalledByLegalizer() const { return CalledByLegalizer; }
906 void AddToWorklist(SDNode *N);
907 void RemoveFromWorklist(SDNode *N);
908 SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
910 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
911 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
913 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
916 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
917 /// and cc. If it is unable to simplify it, return a null SDValue.
918 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
919 ISD::CondCode Cond, bool foldBooleans,
920 DAGCombinerInfo &DCI, DebugLoc dl) const;
922 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
923 /// node is a GlobalAddress + offset.
925 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
927 /// PerformDAGCombine - This method will be invoked for all target nodes and
928 /// for any target-independent nodes that the target has registered with
931 /// The semantics are as follows:
933 /// SDValue.Val == 0 - No change was made
934 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
935 /// otherwise - N should be replaced by the returned Operand.
937 /// In addition, methods provided by DAGCombinerInfo may be used to perform
938 /// more complex transformations.
940 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
942 /// isTypeDesirableForOp - Return true if the target has native support for
943 /// the specified value type and it is 'desirable' to use the type for the
944 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
945 /// instruction encodings are longer and some i16 instructions are slow.
946 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
947 // By default, assume all legal types are desirable.
948 return isTypeLegal(VT);
951 /// isDesirableToPromoteOp - Return true if it is profitable for dag combiner
952 /// to transform a floating point op of specified opcode to a equivalent op of
953 /// an integer type. e.g. f32 load -> i32 load can be profitable on ARM.
954 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
959 /// IsDesirableToPromoteOp - This method query the target whether it is
960 /// beneficial for dag combiner to promote the specified node. If true, it
961 /// should return the desired promotion type by reference.
962 virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
966 //===--------------------------------------------------------------------===//
967 // TargetLowering Configuration Methods - These methods should be invoked by
968 // the derived class constructor to configure this object for the target.
972 /// setBooleanContents - Specify how the target extends the result of a
973 /// boolean value from i1 to a wider type. See getBooleanContents.
974 void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
975 /// setBooleanVectorContents - Specify how the target extends the result
976 /// of a vector boolean value from a vector of i1 to a wider type. See
977 /// getBooleanContents.
978 void setBooleanVectorContents(BooleanContent Ty) {
979 BooleanVectorContents = Ty;
982 /// setSchedulingPreference - Specify the target scheduling preference.
983 void setSchedulingPreference(Sched::Preference Pref) {
984 SchedPreferenceInfo = Pref;
987 /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
988 /// use _setjmp to implement llvm.setjmp or the non _ version.
989 /// Defaults to false.
990 void setUseUnderscoreSetJmp(bool Val) {
991 UseUnderscoreSetJmp = Val;
994 /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
995 /// use _longjmp to implement llvm.longjmp or the non _ version.
996 /// Defaults to false.
997 void setUseUnderscoreLongJmp(bool Val) {
998 UseUnderscoreLongJmp = Val;
1001 /// setSupportJumpTables - Indicate whether the target can generate code for
1003 void setSupportJumpTables(bool Val) {
1004 SupportJumpTables = Val;
1007 /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
1008 /// specifies the register that llvm.savestack/llvm.restorestack should save
1010 void setStackPointerRegisterToSaveRestore(unsigned R) {
1011 StackPointerRegisterToSaveRestore = R;
1014 /// setExceptionPointerRegister - If set to a physical register, this sets
1015 /// the register that receives the exception address on entry to a landing
1017 void setExceptionPointerRegister(unsigned R) {
1018 ExceptionPointerRegister = R;
1021 /// setExceptionSelectorRegister - If set to a physical register, this sets
1022 /// the register that receives the exception typeid on entry to a landing
1024 void setExceptionSelectorRegister(unsigned R) {
1025 ExceptionSelectorRegister = R;
1028 /// SelectIsExpensive - Tells the code generator not to expand operations
1029 /// into sequences that use the select operations if possible.
1030 void setSelectIsExpensive(bool isExpensive = true) {
1031 SelectIsExpensive = isExpensive;
1034 /// JumpIsExpensive - Tells the code generator not to expand sequence of
1035 /// operations into a separate sequences that increases the amount of
1037 void setJumpIsExpensive(bool isExpensive = true) {
1038 JumpIsExpensive = isExpensive;
1041 /// setIntDivIsCheap - Tells the code generator that integer divide is
1042 /// expensive, and if possible, should be replaced by an alternate sequence
1043 /// of instructions not containing an integer divide.
1044 void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
1046 /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
1047 /// srl/add/sra for a signed divide by power of two, and let the target handle
1049 void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
1051 /// addRegisterClass - Add the specified register class as an available
1052 /// regclass for the specified value type. This indicates the selector can
1053 /// handle values of that class natively.
1054 void addRegisterClass(EVT VT, const TargetRegisterClass *RC) {
1055 assert((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
1056 AvailableRegClasses.push_back(std::make_pair(VT, RC));
1057 RegClassForVT[VT.getSimpleVT().SimpleTy] = RC;
1060 /// findRepresentativeClass - Return the largest legal super-reg register class
1061 /// of the register class for the specified type and its associated "cost".
1062 virtual std::pair<const TargetRegisterClass*, uint8_t>
1063 findRepresentativeClass(EVT VT) const;
1065 /// computeRegisterProperties - Once all of the register classes are added,
1066 /// this allows us to compute derived properties we expose.
1067 void computeRegisterProperties();
1069 /// setOperationAction - Indicate that the specified operation does not work
1070 /// with the specified type and indicate what to do about it.
1071 void setOperationAction(unsigned Op, MVT VT,
1072 LegalizeAction Action) {
1073 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
1074 OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action;
1077 /// setLoadExtAction - Indicate that the specified load with extension does
1078 /// not work with the specified type and indicate what to do about it.
1079 void setLoadExtAction(unsigned ExtType, MVT VT,
1080 LegalizeAction Action) {
1081 assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
1082 "Table isn't big enough!");
1083 LoadExtActions[VT.SimpleTy][ExtType] = (uint8_t)Action;
1086 /// setTruncStoreAction - Indicate that the specified truncating store does
1087 /// not work with the specified type and indicate what to do about it.
1088 void setTruncStoreAction(MVT ValVT, MVT MemVT,
1089 LegalizeAction Action) {
1090 assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
1091 "Table isn't big enough!");
1092 TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action;
1095 /// setIndexedLoadAction - Indicate that the specified indexed load does or
1096 /// does not work with the specified type and indicate what to do abort
1097 /// it. NOTE: All indexed mode loads are initialized to Expand in
1098 /// TargetLowering.cpp
1099 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1100 LegalizeAction Action) {
1101 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1102 (unsigned)Action < 0xf && "Table isn't big enough!");
1103 // Load action are kept in the upper half.
1104 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1105 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1108 /// setIndexedStoreAction - Indicate that the specified indexed store does or
1109 /// does not work with the specified type and indicate what to do about
1110 /// it. NOTE: All indexed mode stores are initialized to Expand in
1111 /// TargetLowering.cpp
1112 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1113 LegalizeAction Action) {
1114 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1115 (unsigned)Action < 0xf && "Table isn't big enough!");
1116 // Store action are kept in the lower half.
1117 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1118 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1121 /// setCondCodeAction - Indicate that the specified condition code is or isn't
1122 /// supported on the target and indicate what to do about it.
1123 void setCondCodeAction(ISD::CondCode CC, MVT VT,
1124 LegalizeAction Action) {
1125 assert(VT < MVT::LAST_VALUETYPE &&
1126 (unsigned)CC < array_lengthof(CondCodeActions) &&
1127 "Table isn't big enough!");
1128 CondCodeActions[(unsigned)CC] &= ~(uint64_t(3UL) << VT.SimpleTy*2);
1129 CondCodeActions[(unsigned)CC] |= (uint64_t)Action << VT.SimpleTy*2;
1132 /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
1133 /// promotion code defaults to trying a larger integer/fp until it can find
1134 /// one that works. If that default is insufficient, this method can be used
1135 /// by the target to override the default.
1136 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1137 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1140 /// setTargetDAGCombine - Targets should invoke this method for each target
1141 /// independent node that they want to provide a custom DAG combiner for by
1142 /// implementing the PerformDAGCombine virtual method.
1143 void setTargetDAGCombine(ISD::NodeType NT) {
1144 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1145 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1148 /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
1149 /// bytes); default is 200
1150 void setJumpBufSize(unsigned Size) {
1154 /// setJumpBufAlignment - Set the target's required jmp_buf buffer
1155 /// alignment (in bytes); default is 0
1156 void setJumpBufAlignment(unsigned Align) {
1157 JumpBufAlignment = Align;
1160 /// setMinFunctionAlignment - Set the target's minimum function alignment (in
1162 void setMinFunctionAlignment(unsigned Align) {
1163 MinFunctionAlignment = Align;
1166 /// setPrefFunctionAlignment - Set the target's preferred function alignment.
1167 /// This should be set if there is a performance benefit to
1168 /// higher-than-minimum alignment (in log2(bytes))
1169 void setPrefFunctionAlignment(unsigned Align) {
1170 PrefFunctionAlignment = Align;
1173 /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
1174 /// alignment is zero, it means the target does not care about loop alignment.
1175 /// The alignment is specified in log2(bytes).
1176 void setPrefLoopAlignment(unsigned Align) {
1177 PrefLoopAlignment = Align;
1180 /// setMinStackArgumentAlignment - Set the minimum stack alignment of an
1181 /// argument (in log2(bytes)).
1182 void setMinStackArgumentAlignment(unsigned Align) {
1183 MinStackArgumentAlignment = Align;
1186 /// setShouldFoldAtomicFences - Set if the target's implementation of the
1187 /// atomic operation intrinsics includes locking. Default is false.
1188 void setShouldFoldAtomicFences(bool fold) {
1189 ShouldFoldAtomicFences = fold;
1192 /// setInsertFencesForAtomic - Set if the DAG builder should
1193 /// automatically insert fences and reduce the order of atomic memory
1194 /// operations to Monotonic.
1195 void setInsertFencesForAtomic(bool fence) {
1196 InsertFencesForAtomic = fence;
1200 //===--------------------------------------------------------------------===//
1201 // Lowering methods - These methods must be implemented by targets so that
1202 // the SelectionDAGLowering code knows how to lower these.
1205 /// LowerFormalArguments - This hook must be implemented to lower the
1206 /// incoming (formal) arguments, described by the Ins array, into the
1207 /// specified DAG. The implementation should fill in the InVals array
1208 /// with legal-type argument values, and return the resulting token
1212 LowerFormalArguments(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1214 const SmallVectorImpl<ISD::InputArg> &/*Ins*/,
1215 DebugLoc /*dl*/, SelectionDAG &/*DAG*/,
1216 SmallVectorImpl<SDValue> &/*InVals*/) const {
1217 llvm_unreachable("Not Implemented");
1220 struct ArgListEntry {
1231 ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1232 isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
1234 typedef std::vector<ArgListEntry> ArgListTy;
1236 /// CallLoweringInfo - This structure contains all information that is
1237 /// necessary for lowering calls. It is passed to TLI::LowerCallTo when the
1238 /// SelectionDAG builder needs to lower a call, and targets will see this
1239 /// struct in their LowerCall implementation.
1240 struct CallLoweringInfo {
1247 bool DoesNotReturn : 1;
1248 bool IsReturnValueUsed : 1;
1250 // IsTailCall should be modified by implementations of
1251 // TargetLowering::LowerCall that perform tail call conversions.
1254 unsigned NumFixedArgs;
1255 CallingConv::ID CallConv;
1260 ImmutableCallSite *CS;
1261 SmallVector<ISD::OutputArg, 32> Outs;
1262 SmallVector<SDValue, 32> OutVals;
1263 SmallVector<ISD::InputArg, 32> Ins;
1266 /// CallLoweringInfo - Constructs a call lowering context based on the
1267 /// ImmutableCallSite \p cs.
1268 CallLoweringInfo(SDValue chain, Type *retTy,
1269 FunctionType *FTy, bool isTailCall, SDValue callee,
1270 ArgListTy &args, SelectionDAG &dag, DebugLoc dl,
1271 ImmutableCallSite &cs)
1272 : Chain(chain), RetTy(retTy), RetSExt(cs.paramHasAttr(0, Attribute::SExt)),
1273 RetZExt(cs.paramHasAttr(0, Attribute::ZExt)), IsVarArg(FTy->isVarArg()),
1274 IsInReg(cs.paramHasAttr(0, Attribute::InReg)),
1275 DoesNotReturn(cs.doesNotReturn()),
1276 IsReturnValueUsed(!cs.getInstruction()->use_empty()),
1277 IsTailCall(isTailCall), NumFixedArgs(FTy->getNumParams()),
1278 CallConv(cs.getCallingConv()), Callee(callee), Args(args), DAG(dag),
1281 /// CallLoweringInfo - Constructs a call lowering context based on the
1282 /// provided call information.
1283 CallLoweringInfo(SDValue chain, Type *retTy, bool retSExt, bool retZExt,
1284 bool isVarArg, bool isInReg, unsigned numFixedArgs,
1285 CallingConv::ID callConv, bool isTailCall,
1286 bool doesNotReturn, bool isReturnValueUsed, SDValue callee,
1287 ArgListTy &args, SelectionDAG &dag, DebugLoc dl)
1288 : Chain(chain), RetTy(retTy), RetSExt(retSExt), RetZExt(retZExt),
1289 IsVarArg(isVarArg), IsInReg(isInReg), DoesNotReturn(doesNotReturn),
1290 IsReturnValueUsed(isReturnValueUsed), IsTailCall(isTailCall),
1291 NumFixedArgs(numFixedArgs), CallConv(callConv), Callee(callee),
1292 Args(args), DAG(dag), DL(dl), CS(NULL) {}
1295 /// LowerCallTo - This function lowers an abstract call to a function into an
1296 /// actual call. This returns a pair of operands. The first element is the
1297 /// return value for the function (if RetTy is not VoidTy). The second
1298 /// element is the outgoing token chain. It calls LowerCall to do the actual
1300 std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
1302 /// LowerCall - This hook must be implemented to lower calls into the
1303 /// the specified DAG. The outgoing arguments to the call are described
1304 /// by the Outs array, and the values to be returned by the call are
1305 /// described by the Ins array. The implementation should fill in the
1306 /// InVals array with legal-type return values from the call, and return
1307 /// the resulting token chain value.
1309 LowerCall(CallLoweringInfo &/*CLI*/,
1310 SmallVectorImpl<SDValue> &/*InVals*/) const {
1311 llvm_unreachable("Not Implemented");
1314 /// HandleByVal - Target-specific cleanup for formal ByVal parameters.
1315 virtual void HandleByVal(CCState *, unsigned &) const {}
1317 /// CanLowerReturn - This hook should be implemented to check whether the
1318 /// return values described by the Outs array can fit into the return
1319 /// registers. If false is returned, an sret-demotion is performed.
1321 virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
1322 MachineFunction &/*MF*/, bool /*isVarArg*/,
1323 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
1324 LLVMContext &/*Context*/) const
1326 // Return true by default to get preexisting behavior.
1330 /// LowerReturn - This hook must be implemented to lower outgoing
1331 /// return values, described by the Outs array, into the specified
1332 /// DAG. The implementation should return the resulting token chain
1336 LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1338 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
1339 const SmallVectorImpl<SDValue> &/*OutVals*/,
1340 DebugLoc /*dl*/, SelectionDAG &/*DAG*/) const {
1341 llvm_unreachable("Not Implemented");
1344 /// isUsedByReturnOnly - Return true if result of the specified node is used
1345 /// by a return node only. It also compute and return the input chain for the
1347 /// This is used to determine whether it is possible
1348 /// to codegen a libcall as tail call at legalization time.
1349 virtual bool isUsedByReturnOnly(SDNode *, SDValue &Chain) const {
1353 /// mayBeEmittedAsTailCall - Return true if the target may be able emit the
1354 /// call instruction as a tail call. This is used by optimization passes to
1355 /// determine if it's profitable to duplicate return instructions to enable
1356 /// tailcall optimization.
1357 virtual bool mayBeEmittedAsTailCall(CallInst *) const {
1361 /// getTypeForExtArgOrReturn - Return the type that should be used to zero or
1362 /// sign extend a zeroext/signext integer argument or return value.
1363 /// FIXME: Most C calling convention requires the return type to be promoted,
1364 /// but this is not true all the time, e.g. i1 on x86-64. It is also not
1365 /// necessary for non-C calling conventions. The frontend should handle this
1366 /// and include all of the necessary information.
1367 virtual EVT getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1368 ISD::NodeType /*ExtendKind*/) const {
1369 EVT MinVT = getRegisterType(Context, MVT::i32);
1370 return VT.bitsLT(MinVT) ? MinVT : VT;
1373 /// LowerOperationWrapper - This callback is invoked by the type legalizer
1374 /// to legalize nodes with an illegal operand type but legal result types.
1375 /// It replaces the LowerOperation callback in the type Legalizer.
1376 /// The reason we can not do away with LowerOperation entirely is that
1377 /// LegalizeDAG isn't yet ready to use this callback.
1378 /// TODO: Consider merging with ReplaceNodeResults.
1380 /// The target places new result values for the node in Results (their number
1381 /// and types must exactly match those of the original return values of
1382 /// the node), or leaves Results empty, which indicates that the node is not
1383 /// to be custom lowered after all.
1384 /// The default implementation calls LowerOperation.
1385 virtual void LowerOperationWrapper(SDNode *N,
1386 SmallVectorImpl<SDValue> &Results,
1387 SelectionDAG &DAG) const;
1389 /// LowerOperation - This callback is invoked for operations that are
1390 /// unsupported by the target, which are registered to use 'custom' lowering,
1391 /// and whose defined values are all legal.
1392 /// If the target has no operations that require custom lowering, it need not
1393 /// implement this. The default implementation of this aborts.
1394 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
1396 /// ReplaceNodeResults - This callback is invoked when a node result type is
1397 /// illegal for the target, and the operation was registered to use 'custom'
1398 /// lowering for that result type. The target places new result values for
1399 /// the node in Results (their number and types must exactly match those of
1400 /// the original return values of the node), or leaves Results empty, which
1401 /// indicates that the node is not to be custom lowered after all.
1403 /// If the target has no operations that require custom lowering, it need not
1404 /// implement this. The default implementation aborts.
1405 virtual void ReplaceNodeResults(SDNode * /*N*/,
1406 SmallVectorImpl<SDValue> &/*Results*/,
1407 SelectionDAG &/*DAG*/) const {
1408 llvm_unreachable("ReplaceNodeResults not implemented for this target!");
1411 /// getTargetNodeName() - This method returns the name of a target specific
1413 virtual const char *getTargetNodeName(unsigned Opcode) const;
1415 /// createFastISel - This method returns a target specific FastISel object,
1416 /// or null if the target does not support "fast" ISel.
1417 virtual FastISel *createFastISel(FunctionLoweringInfo &,
1418 const TargetLibraryInfo *) const {
1422 //===--------------------------------------------------------------------===//
1423 // Inline Asm Support hooks
1426 /// ExpandInlineAsm - This hook allows the target to expand an inline asm
1427 /// call to be explicit llvm code if it wants to. This is useful for
1428 /// turning simple inline asms into LLVM intrinsics, which gives the
1429 /// compiler more information about the behavior of the code.
1430 virtual bool ExpandInlineAsm(CallInst *) const {
1434 enum ConstraintType {
1435 C_Register, // Constraint represents specific register(s).
1436 C_RegisterClass, // Constraint represents any of register(s) in class.
1437 C_Memory, // Memory constraint.
1438 C_Other, // Something else.
1439 C_Unknown // Unsupported constraint.
1442 enum ConstraintWeight {
1444 CW_Invalid = -1, // No match.
1445 CW_Okay = 0, // Acceptable.
1446 CW_Good = 1, // Good weight.
1447 CW_Better = 2, // Better weight.
1448 CW_Best = 3, // Best weight.
1450 // Well-known weights.
1451 CW_SpecificReg = CW_Okay, // Specific register operands.
1452 CW_Register = CW_Good, // Register operands.
1453 CW_Memory = CW_Better, // Memory operands.
1454 CW_Constant = CW_Best, // Constant operand.
1455 CW_Default = CW_Okay // Default or don't know type.
1458 /// AsmOperandInfo - This contains information for each constraint that we are
1460 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
1461 /// ConstraintCode - This contains the actual string for the code, like "m".
1462 /// TargetLowering picks the 'best' code from ConstraintInfo::Codes that
1463 /// most closely matches the operand.
1464 std::string ConstraintCode;
1466 /// ConstraintType - Information about the constraint code, e.g. Register,
1467 /// RegisterClass, Memory, Other, Unknown.
1468 TargetLowering::ConstraintType ConstraintType;
1470 /// CallOperandval - If this is the result output operand or a
1471 /// clobber, this is null, otherwise it is the incoming operand to the
1472 /// CallInst. This gets modified as the asm is processed.
1473 Value *CallOperandVal;
1475 /// ConstraintVT - The ValueType for the operand value.
1478 /// isMatchingInputConstraint - Return true of this is an input operand that
1479 /// is a matching constraint like "4".
1480 bool isMatchingInputConstraint() const;
1482 /// getMatchedOperand - If this is an input matching constraint, this method
1483 /// returns the output operand it matches.
1484 unsigned getMatchedOperand() const;
1486 /// Copy constructor for copying from an AsmOperandInfo.
1487 AsmOperandInfo(const AsmOperandInfo &info)
1488 : InlineAsm::ConstraintInfo(info),
1489 ConstraintCode(info.ConstraintCode),
1490 ConstraintType(info.ConstraintType),
1491 CallOperandVal(info.CallOperandVal),
1492 ConstraintVT(info.ConstraintVT) {
1495 /// Copy constructor for copying from a ConstraintInfo.
1496 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
1497 : InlineAsm::ConstraintInfo(info),
1498 ConstraintType(TargetLowering::C_Unknown),
1499 CallOperandVal(0), ConstraintVT(MVT::Other) {
1503 typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
1505 /// ParseConstraints - Split up the constraint string from the inline
1506 /// assembly value into the specific constraints and their prefixes,
1507 /// and also tie in the associated operand values.
1508 /// If this returns an empty vector, and if the constraint string itself
1509 /// isn't empty, there was an error parsing.
1510 virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const;
1512 /// Examine constraint type and operand type and determine a weight value.
1513 /// The operand object must already have been set up with the operand type.
1514 virtual ConstraintWeight getMultipleConstraintMatchWeight(
1515 AsmOperandInfo &info, int maIndex) const;
1517 /// Examine constraint string and operand type and determine a weight value.
1518 /// The operand object must already have been set up with the operand type.
1519 virtual ConstraintWeight getSingleConstraintMatchWeight(
1520 AsmOperandInfo &info, const char *constraint) const;
1522 /// ComputeConstraintToUse - Determines the constraint code and constraint
1523 /// type to use for the specific AsmOperandInfo, setting
1524 /// OpInfo.ConstraintCode and OpInfo.ConstraintType. If the actual operand
1525 /// being passed in is available, it can be passed in as Op, otherwise an
1526 /// empty SDValue can be passed.
1527 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
1529 SelectionDAG *DAG = 0) const;
1531 /// getConstraintType - Given a constraint, return the type of constraint it
1532 /// is for this target.
1533 virtual ConstraintType getConstraintType(const std::string &Constraint) const;
1535 /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
1536 /// {edx}), return the register number and the register class for the
1539 /// Given a register class constraint, like 'r', if this corresponds directly
1540 /// to an LLVM register class, return a register of 0 and the register class
1543 /// This should only be used for C_Register constraints. On error,
1544 /// this returns a register number of 0 and a null register class pointer..
1545 virtual std::pair<unsigned, const TargetRegisterClass*>
1546 getRegForInlineAsmConstraint(const std::string &Constraint,
1549 /// LowerXConstraint - try to replace an X constraint, which matches anything,
1550 /// with another that has more specific requirements based on the type of the
1551 /// corresponding operand. This returns null if there is no replacement to
1553 virtual const char *LowerXConstraint(EVT ConstraintVT) const;
1555 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1556 /// vector. If it is invalid, don't add anything to Ops.
1557 virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
1558 std::vector<SDValue> &Ops,
1559 SelectionDAG &DAG) const;
1561 //===--------------------------------------------------------------------===//
1562 // Instruction Emitting Hooks
1565 // EmitInstrWithCustomInserter - This method should be implemented by targets
1566 // that mark instructions with the 'usesCustomInserter' flag. These
1567 // instructions are special in various ways, which require special support to
1568 // insert. The specified MachineInstr is created but not inserted into any
1569 // basic blocks, and this method is called to expand it into a sequence of
1570 // instructions, potentially also creating new basic blocks and control flow.
1571 virtual MachineBasicBlock *
1572 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const;
1574 /// AdjustInstrPostInstrSelection - This method should be implemented by
1575 /// targets that mark instructions with the 'hasPostISelHook' flag. These
1576 /// instructions must be adjusted after instruction selection by target hooks.
1577 /// e.g. To fill in optional defs for ARM 's' setting instructions.
1579 AdjustInstrPostInstrSelection(MachineInstr *MI, SDNode *Node) const;
1581 //===--------------------------------------------------------------------===//
1582 // Addressing mode description hooks (used by LSR etc).
1585 /// AddrMode - This represents an addressing mode of:
1586 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1587 /// If BaseGV is null, there is no BaseGV.
1588 /// If BaseOffs is zero, there is no base offset.
1589 /// If HasBaseReg is false, there is no base register.
1590 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1594 GlobalValue *BaseGV;
1598 AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1601 /// GetAddrModeArguments - CodeGenPrepare sinks address calculations into the
1602 /// same BB as Load/Store instructions reading the address. This allows as
1603 /// much computation as possible to be done in the address mode for that
1604 /// operand. This hook lets targets also pass back when this should be done
1605 /// on intrinsics which load/store.
1606 virtual bool GetAddrModeArguments(IntrinsicInst *I,
1607 SmallVectorImpl<Value*> &Ops,
1608 Type *&AccessTy) const {
1612 /// isLegalAddressingMode - Return true if the addressing mode represented by
1613 /// AM is legal for this target, for a load/store of the specified type.
1614 /// The type may be VoidTy, in which case only return true if the addressing
1615 /// mode is legal for a load/store of any legal type.
1616 /// TODO: Handle pre/postinc as well.
1617 virtual bool isLegalAddressingMode(const AddrMode &AM, Type *Ty) const;
1619 /// isLegalICmpImmediate - Return true if the specified immediate is legal
1620 /// icmp immediate, that is the target has icmp instructions which can compare
1621 /// a register against the immediate without having to materialize the
1622 /// immediate into a register.
1623 virtual bool isLegalICmpImmediate(int64_t) const {
1627 /// isLegalAddImmediate - Return true if the specified immediate is legal
1628 /// add immediate, that is the target has add instructions which can add
1629 /// a register with the immediate without having to materialize the
1630 /// immediate into a register.
1631 virtual bool isLegalAddImmediate(int64_t) const {
1635 /// isTruncateFree - Return true if it's free to truncate a value of
1636 /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1637 /// register EAX to i16 by referencing its sub-register AX.
1638 virtual bool isTruncateFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1642 virtual bool isTruncateFree(EVT /*VT1*/, EVT /*VT2*/) const {
1646 /// isZExtFree - Return true if any actual instruction that defines a
1647 /// value of type Ty1 implicitly zero-extends the value to Ty2 in the result
1648 /// register. This does not necessarily include registers defined in
1649 /// unknown ways, such as incoming arguments, or copies from unknown
1650 /// virtual registers. Also, if isTruncateFree(Ty2, Ty1) is true, this
1651 /// does not necessarily apply to truncate instructions. e.g. on x86-64,
1652 /// all instructions that define 32-bit values implicit zero-extend the
1653 /// result out to 64 bits.
1654 virtual bool isZExtFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1658 virtual bool isZExtFree(EVT /*VT1*/, EVT /*VT2*/) const {
1662 /// isFNegFree - Return true if an fneg operation is free to the point where
1663 /// it is never worthwhile to replace it with a bitwise operation.
1664 virtual bool isFNegFree(EVT) const {
1668 /// isFAbsFree - Return true if an fneg operation is free to the point where
1669 /// it is never worthwhile to replace it with a bitwise operation.
1670 virtual bool isFAbsFree(EVT) const {
1674 /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
1675 /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
1676 /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
1677 /// is expanded to mul + add.
1678 virtual bool isFMAFasterThanMulAndAdd(EVT) const {
1682 /// isNarrowingProfitable - Return true if it's profitable to narrow
1683 /// operations of type VT1 to VT2. e.g. on x86, it's profitable to narrow
1684 /// from i32 to i8 but not from i32 to i16.
1685 virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
1689 //===--------------------------------------------------------------------===//
1690 // Div utility functions
1692 SDValue BuildExactSDIV(SDValue Op1, SDValue Op2, DebugLoc dl,
1693 SelectionDAG &DAG) const;
1694 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
1695 std::vector<SDNode*>* Created) const;
1696 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
1697 std::vector<SDNode*>* Created) const;
1700 //===--------------------------------------------------------------------===//
1701 // Runtime Library hooks
1704 /// setLibcallName - Rename the default libcall routine name for the specified
1706 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1707 LibcallRoutineNames[Call] = Name;
1710 /// getLibcallName - Get the libcall routine name for the specified libcall.
1712 const char *getLibcallName(RTLIB::Libcall Call) const {
1713 return LibcallRoutineNames[Call];
1716 /// setCmpLibcallCC - Override the default CondCode to be used to test the
1717 /// result of the comparison libcall against zero.
1718 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1719 CmpLibcallCCs[Call] = CC;
1722 /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1723 /// the comparison libcall against zero.
1724 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1725 return CmpLibcallCCs[Call];
1728 /// setLibcallCallingConv - Set the CallingConv that should be used for the
1729 /// specified libcall.
1730 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
1731 LibcallCallingConvs[Call] = CC;
1734 /// getLibcallCallingConv - Get the CallingConv that should be used for the
1735 /// specified libcall.
1736 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
1737 return LibcallCallingConvs[Call];
1741 const TargetMachine &TM;
1742 const TargetData *TD;
1743 const TargetLoweringObjectFile &TLOF;
1745 /// PointerTy - The type to use for pointers, usually i32 or i64.
1749 /// IsLittleEndian - True if this is a little endian target.
1751 bool IsLittleEndian;
1753 /// SelectIsExpensive - Tells the code generator not to expand operations
1754 /// into sequences that use the select operations if possible.
1755 bool SelectIsExpensive;
1757 /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1758 /// constants into a sequence of muls, adds, and shifts. This is a hack until
1759 /// a real cost model is in place. If we ever optimize for size, this will be
1760 /// set to true unconditionally.
1763 /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1764 /// srl/add/sra for a signed divide by power of two, and let the target handle
1766 bool Pow2DivIsCheap;
1768 /// JumpIsExpensive - Tells the code generator that it shouldn't generate
1769 /// extra flow control instructions and should attempt to combine flow
1770 /// control instructions via predication.
1771 bool JumpIsExpensive;
1773 /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1774 /// llvm.setjmp. Defaults to false.
1775 bool UseUnderscoreSetJmp;
1777 /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1778 /// llvm.longjmp. Defaults to false.
1779 bool UseUnderscoreLongJmp;
1781 /// SupportJumpTables - Whether the target can generate code for jumptables.
1782 /// If it's not true, then each jumptable must be lowered into if-then-else's.
1783 bool SupportJumpTables;
1785 /// BooleanContents - Information about the contents of the high-bits in
1786 /// boolean values held in a type wider than i1. See getBooleanContents.
1787 BooleanContent BooleanContents;
1788 /// BooleanVectorContents - Information about the contents of the high-bits
1789 /// in boolean vector values when the element type is wider than i1. See
1790 /// getBooleanContents.
1791 BooleanContent BooleanVectorContents;
1793 /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1794 /// total cycles or lowest register usage.
1795 Sched::Preference SchedPreferenceInfo;
1797 /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1798 unsigned JumpBufSize;
1800 /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1802 unsigned JumpBufAlignment;
1804 /// MinStackArgumentAlignment - The minimum alignment that any argument
1805 /// on the stack needs to have.
1807 unsigned MinStackArgumentAlignment;
1809 /// MinFunctionAlignment - The minimum function alignment (used when
1810 /// optimizing for size, and to prevent explicitly provided alignment
1811 /// from leading to incorrect code).
1813 unsigned MinFunctionAlignment;
1815 /// PrefFunctionAlignment - The preferred function alignment (used when
1816 /// alignment unspecified and optimizing for speed).
1818 unsigned PrefFunctionAlignment;
1820 /// PrefLoopAlignment - The preferred loop alignment.
1822 unsigned PrefLoopAlignment;
1824 /// ShouldFoldAtomicFences - Whether fencing MEMBARRIER instructions should
1825 /// be folded into the enclosed atomic intrinsic instruction by the
1827 bool ShouldFoldAtomicFences;
1829 /// InsertFencesForAtomic - Whether the DAG builder should automatically
1830 /// insert fences and reduce ordering for atomics. (This will be set for
1831 /// for most architectures with weak memory ordering.)
1832 bool InsertFencesForAtomic;
1834 /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1835 /// specifies the register that llvm.savestack/llvm.restorestack should save
1837 unsigned StackPointerRegisterToSaveRestore;
1839 /// ExceptionPointerRegister - If set to a physical register, this specifies
1840 /// the register that receives the exception address on entry to a landing
1842 unsigned ExceptionPointerRegister;
1844 /// ExceptionSelectorRegister - If set to a physical register, this specifies
1845 /// the register that receives the exception typeid on entry to a landing
1847 unsigned ExceptionSelectorRegister;
1849 /// RegClassForVT - This indicates the default register class to use for
1850 /// each ValueType the target supports natively.
1851 const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1852 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1853 EVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1855 /// RepRegClassForVT - This indicates the "representative" register class to
1856 /// use for each ValueType the target supports natively. This information is
1857 /// used by the scheduler to track register pressure. By default, the
1858 /// representative register class is the largest legal super-reg register
1859 /// class of the register class of the specified type. e.g. On x86, i8, i16,
1860 /// and i32's representative class would be GR32.
1861 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
1863 /// RepRegClassCostForVT - This indicates the "cost" of the "representative"
1864 /// register class for each ValueType. The cost is used by the scheduler to
1865 /// approximate register pressure.
1866 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
1868 /// TransformToType - For any value types we are promoting or expanding, this
1869 /// contains the value type that we are changing to. For Expanded types, this
1870 /// contains one step of the expand (e.g. i64 -> i32), even if there are
1871 /// multiple steps required (e.g. i64 -> i16). For types natively supported
1872 /// by the system, this holds the same type (e.g. i32 -> i32).
1873 EVT TransformToType[MVT::LAST_VALUETYPE];
1875 /// OpActions - For each operation and each value type, keep a LegalizeAction
1876 /// that indicates how instruction selection should deal with the operation.
1877 /// Most operations are Legal (aka, supported natively by the target), but
1878 /// operations that are not should be described. Note that operations on
1879 /// non-legal value types are not described here.
1880 uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
1882 /// LoadExtActions - For each load extension type and each value type,
1883 /// keep a LegalizeAction that indicates how instruction selection should deal
1884 /// with a load of a specific value type and extension type.
1885 uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE];
1887 /// TruncStoreActions - For each value type pair keep a LegalizeAction that
1888 /// indicates whether a truncating store of a specific value type and
1889 /// truncating type is legal.
1890 uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
1892 /// IndexedModeActions - For each indexed mode and each value type,
1893 /// keep a pair of LegalizeAction that indicates how instruction
1894 /// selection should deal with the load / store. The first dimension is the
1895 /// value_type for the reference. The second dimension represents the various
1896 /// modes for load store.
1897 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
1899 /// CondCodeActions - For each condition code (ISD::CondCode) keep a
1900 /// LegalizeAction that indicates how instruction selection should
1901 /// deal with the condition code.
1902 uint64_t CondCodeActions[ISD::SETCC_INVALID];
1904 ValueTypeActionImpl ValueTypeActions;
1906 typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind;
1909 getTypeConversion(LLVMContext &Context, EVT VT) const {
1910 // If this is a simple type, use the ComputeRegisterProp mechanism.
1911 if (VT.isSimple()) {
1912 assert((unsigned)VT.getSimpleVT().SimpleTy <
1913 array_lengthof(TransformToType));
1914 EVT NVT = TransformToType[VT.getSimpleVT().SimpleTy];
1915 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(VT.getSimpleVT());
1918 (!(NVT.isSimple() && LA != TypeLegal) ||
1919 ValueTypeActions.getTypeAction(NVT.getSimpleVT()) != TypePromoteInteger)
1920 && "Promote may not follow Expand or Promote");
1922 return LegalizeKind(LA, NVT);
1925 // Handle Extended Scalar Types.
1926 if (!VT.isVector()) {
1927 assert(VT.isInteger() && "Float types must be simple");
1928 unsigned BitSize = VT.getSizeInBits();
1929 // First promote to a power-of-two size, then expand if necessary.
1930 if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
1931 EVT NVT = VT.getRoundIntegerType(Context);
1932 assert(NVT != VT && "Unable to round integer VT");
1933 LegalizeKind NextStep = getTypeConversion(Context, NVT);
1934 // Avoid multi-step promotion.
1935 if (NextStep.first == TypePromoteInteger) return NextStep;
1936 // Return rounded integer type.
1937 return LegalizeKind(TypePromoteInteger, NVT);
1940 return LegalizeKind(TypeExpandInteger,
1941 EVT::getIntegerVT(Context, VT.getSizeInBits()/2));
1944 // Handle vector types.
1945 unsigned NumElts = VT.getVectorNumElements();
1946 EVT EltVT = VT.getVectorElementType();
1948 // Vectors with only one element are always scalarized.
1950 return LegalizeKind(TypeScalarizeVector, EltVT);
1952 // Try to widen vector elements until a legal type is found.
1953 if (EltVT.isInteger()) {
1954 // Vectors with a number of elements that is not a power of two are always
1955 // widened, for example <3 x float> -> <4 x float>.
1956 if (!VT.isPow2VectorType()) {
1957 NumElts = (unsigned)NextPowerOf2(NumElts);
1958 EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
1959 return LegalizeKind(TypeWidenVector, NVT);
1962 // Examine the element type.
1963 LegalizeKind LK = getTypeConversion(Context, EltVT);
1965 // If type is to be expanded, split the vector.
1966 // <4 x i140> -> <2 x i140>
1967 if (LK.first == TypeExpandInteger)
1968 return LegalizeKind(TypeSplitVector,
1969 EVT::getVectorVT(Context, EltVT, NumElts / 2));
1971 // Promote the integer element types until a legal vector type is found
1972 // or until the element integer type is too big. If a legal type was not
1973 // found, fallback to the usual mechanism of widening/splitting the
1976 // Increase the bitwidth of the element to the next pow-of-two
1977 // (which is greater than 8 bits).
1978 EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()
1979 ).getRoundIntegerType(Context);
1981 // Stop trying when getting a non-simple element type.
1982 // Note that vector elements may be greater than legal vector element
1983 // types. Example: X86 XMM registers hold 64bit element on 32bit systems.
1984 if (!EltVT.isSimple()) break;
1986 // Build a new vector type and check if it is legal.
1987 MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1988 // Found a legal promoted vector type.
1989 if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
1990 return LegalizeKind(TypePromoteInteger,
1991 EVT::getVectorVT(Context, EltVT, NumElts));
1995 // Try to widen the vector until a legal type is found.
1996 // If there is no wider legal type, split the vector.
1998 // Round up to the next power of 2.
1999 NumElts = (unsigned)NextPowerOf2(NumElts);
2001 // If there is no simple vector type with this many elements then there
2002 // cannot be a larger legal vector type. Note that this assumes that
2003 // there are no skipped intermediate vector types in the simple types.
2004 if (!EltVT.isSimple()) break;
2005 MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
2006 if (LargerVector == MVT()) break;
2008 // If this type is legal then widen the vector.
2009 if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
2010 return LegalizeKind(TypeWidenVector, LargerVector);
2013 // Widen odd vectors to next power of two.
2014 if (!VT.isPow2VectorType()) {
2015 EVT NVT = VT.getPow2VectorType(Context);
2016 return LegalizeKind(TypeWidenVector, NVT);
2019 // Vectors with illegal element types are expanded.
2020 EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
2021 return LegalizeKind(TypeSplitVector, NVT);
2024 std::vector<std::pair<EVT, const TargetRegisterClass*> > AvailableRegClasses;
2026 /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
2027 /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
2028 /// which sets a bit in this array.
2030 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
2032 /// PromoteToType - For operations that must be promoted to a specific type,
2033 /// this holds the destination type. This map should be sparse, so don't hold
2036 /// Targets add entries to this map with AddPromotedToType(..), clients access
2037 /// this with getTypeToPromoteTo(..).
2038 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
2041 /// LibcallRoutineNames - Stores the name each libcall.
2043 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
2045 /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
2046 /// of each of the comparison libcall against zero.
2047 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
2049 /// LibcallCallingConvs - Stores the CallingConv that should be used for each
2051 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
2054 /// When lowering \@llvm.memset this field specifies the maximum number of
2055 /// store operations that may be substituted for the call to memset. Targets
2056 /// must set this value based on the cost threshold for that target. Targets
2057 /// should assume that the memset will be done using as many of the largest
2058 /// store operations first, followed by smaller ones, if necessary, per
2059 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
2060 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
2061 /// store. This only applies to setting a constant array of a constant size.
2062 /// @brief Specify maximum number of store instructions per memset call.
2063 unsigned maxStoresPerMemset;
2065 /// Maximum number of stores operations that may be substituted for the call
2066 /// to memset, used for functions with OptSize attribute.
2067 unsigned maxStoresPerMemsetOptSize;
2069 /// When lowering \@llvm.memcpy this field specifies the maximum number of
2070 /// store operations that may be substituted for a call to memcpy. Targets
2071 /// must set this value based on the cost threshold for that target. Targets
2072 /// should assume that the memcpy will be done using as many of the largest
2073 /// store operations first, followed by smaller ones, if necessary, per
2074 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
2075 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
2076 /// and one 1-byte store. This only applies to copying a constant array of
2078 /// @brief Specify maximum bytes of store instructions per memcpy call.
2079 unsigned maxStoresPerMemcpy;
2081 /// Maximum number of store operations that may be substituted for a call
2082 /// to memcpy, used for functions with OptSize attribute.
2083 unsigned maxStoresPerMemcpyOptSize;
2085 /// When lowering \@llvm.memmove this field specifies the maximum number of
2086 /// store instructions that may be substituted for a call to memmove. Targets
2087 /// must set this value based on the cost threshold for that target. Targets
2088 /// should assume that the memmove will be done using as many of the largest
2089 /// store operations first, followed by smaller ones, if necessary, per
2090 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
2091 /// with 8-bit alignment would result in nine 1-byte stores. This only
2092 /// applies to copying a constant array of constant size.
2093 /// @brief Specify maximum bytes of store instructions per memmove call.
2094 unsigned maxStoresPerMemmove;
2096 /// Maximum number of store instructions that may be substituted for a call
2097 /// to memmove, used for functions with OpSize attribute.
2098 unsigned maxStoresPerMemmoveOptSize;
2100 /// This field specifies whether the target can benefit from code placement
2102 bool benefitFromCodePlacementOpt;
2104 /// predictableSelectIsExpensive - Tells the code generator that select is
2105 /// more expensive than a branch if the branch is usually predicted right.
2106 bool predictableSelectIsExpensive;
2109 /// isLegalRC - Return true if the value types that can be represented by the
2110 /// specified register class are all legal.
2111 bool isLegalRC(const TargetRegisterClass *RC) const;
2114 /// GetReturnInfo - Given an LLVM IR type and return type attributes,
2115 /// compute the return value EVTs and flags, and optionally also
2116 /// the offsets, if the return value is being lowered to memory.
2117 void GetReturnInfo(Type* ReturnType, Attributes attr,
2118 SmallVectorImpl<ISD::OutputArg> &Outs,
2119 const TargetLowering &TLI);
2121 } // end llvm namespace