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 TargetLoweringObjectFile;
59 None, // No preference
60 Source, // Follow source order.
61 RegPressure, // Scheduling for lowest register pressure.
62 Hybrid, // Scheduling for both latency and register pressure.
63 ILP, // Scheduling for ILP in low register pressure mode.
64 VLIW // Scheduling for VLIW targets.
69 //===----------------------------------------------------------------------===//
70 /// TargetLowering - This class defines information used to lower LLVM code to
71 /// legal SelectionDAG operators that the target instruction selector can accept
74 /// This class also defines callbacks that targets must implement to lower
75 /// target-specific constructs to SelectionDAG operators.
77 class TargetLowering {
78 TargetLowering(const TargetLowering&); // DO NOT IMPLEMENT
79 void operator=(const TargetLowering&); // DO NOT IMPLEMENT
81 /// LegalizeAction - This enum indicates whether operations are valid for a
82 /// target, and if not, what action should be used to make them valid.
84 Legal, // The target natively supports this operation.
85 Promote, // This operation should be executed in a larger type.
86 Expand, // Try to expand this to other ops, otherwise use a libcall.
87 Custom // Use the LowerOperation hook to implement custom lowering.
90 /// LegalizeTypeAction - This enum indicates whether a types are legal for a
91 /// target, and if not, what action should be used to make them valid.
92 enum LegalizeTypeAction {
93 TypeLegal, // The target natively supports this type.
94 TypePromoteInteger, // Replace this integer with a larger one.
95 TypeExpandInteger, // Split this integer into two of half the size.
96 TypeSoftenFloat, // Convert this float to a same size integer type.
97 TypeExpandFloat, // Split this float into two of half the size.
98 TypeScalarizeVector, // Replace this one-element vector with its element.
99 TypeSplitVector, // Split this vector into two of half the size.
100 TypeWidenVector // This vector should be widened into a larger vector.
103 enum BooleanContent { // How the target represents true/false values.
104 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
105 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
106 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
109 static ISD::NodeType getExtendForContent(BooleanContent Content) {
111 case UndefinedBooleanContent:
112 // Extend by adding rubbish bits.
113 return ISD::ANY_EXTEND;
114 case ZeroOrOneBooleanContent:
115 // Extend by adding zero bits.
116 return ISD::ZERO_EXTEND;
117 case ZeroOrNegativeOneBooleanContent:
118 // Extend by copying the sign bit.
119 return ISD::SIGN_EXTEND;
121 llvm_unreachable("Invalid content kind");
124 /// NOTE: The constructor takes ownership of TLOF.
125 explicit TargetLowering(const TargetMachine &TM,
126 const TargetLoweringObjectFile *TLOF);
127 virtual ~TargetLowering();
129 const TargetMachine &getTargetMachine() const { return TM; }
130 const TargetData *getTargetData() const { return TD; }
131 const TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; }
133 bool isBigEndian() const { return !IsLittleEndian; }
134 bool isLittleEndian() const { return IsLittleEndian; }
135 MVT getPointerTy() const { return PointerTy; }
136 virtual MVT getShiftAmountTy(EVT LHSTy) const;
138 /// isSelectExpensive - Return true if the select operation is expensive for
140 bool isSelectExpensive() const { return SelectIsExpensive; }
142 /// isIntDivCheap() - Return true if integer divide is usually cheaper than
143 /// a sequence of several shifts, adds, and multiplies for this target.
144 bool isIntDivCheap() const { return IntDivIsCheap; }
146 /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
148 bool isPow2DivCheap() const { return Pow2DivIsCheap; }
150 /// isJumpExpensive() - Return true if Flow Control is an expensive operation
151 /// that should be avoided.
152 bool isJumpExpensive() const { return JumpIsExpensive; }
154 /// isPredictableSelectExpensive - Return true if selects are only cheaper
155 /// than branches if the branch is unlikely to be predicted right.
156 bool isPredictableSelectExpensive() const {
157 return predictableSelectIsExpensive;
160 /// getSetCCResultType - Return the ValueType of the result of SETCC
161 /// operations. Also used to obtain the target's preferred type for
162 /// the condition operand of SELECT and BRCOND nodes. In the case of
163 /// BRCOND the argument passed is MVT::Other since there are no other
164 /// operands to get a type hint from.
165 virtual EVT getSetCCResultType(EVT VT) const;
167 /// getCmpLibcallReturnType - Return the ValueType for comparison
168 /// libcalls. Comparions libcalls include floating point comparion calls,
169 /// and Ordered/Unordered check calls on floating point numbers.
171 MVT::SimpleValueType getCmpLibcallReturnType() const;
173 /// getBooleanContents - For targets without i1 registers, this gives the
174 /// nature of the high-bits of boolean values held in types wider than i1.
175 /// "Boolean values" are special true/false values produced by nodes like
176 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
177 /// Not to be confused with general values promoted from i1.
178 /// Some cpus distinguish between vectors of boolean and scalars; the isVec
179 /// parameter selects between the two kinds. For example on X86 a scalar
180 /// boolean should be zero extended from i1, while the elements of a vector
181 /// of booleans should be sign extended from i1.
182 BooleanContent getBooleanContents(bool isVec) const {
183 return isVec ? BooleanVectorContents : BooleanContents;
186 /// getSchedulingPreference - Return target scheduling preference.
187 Sched::Preference getSchedulingPreference() const {
188 return SchedPreferenceInfo;
191 /// getSchedulingPreference - Some scheduler, e.g. hybrid, can switch to
192 /// different scheduling heuristics for different nodes. This function returns
193 /// the preference (or none) for the given node.
194 virtual Sched::Preference getSchedulingPreference(SDNode *) const {
198 /// getRegClassFor - Return the register class that should be used for the
199 /// specified value type.
200 virtual const TargetRegisterClass *getRegClassFor(EVT VT) const {
201 assert(VT.isSimple() && "getRegClassFor called on illegal type!");
202 const TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT().SimpleTy];
203 assert(RC && "This value type is not natively supported!");
207 /// getRepRegClassFor - Return the 'representative' register class for the
208 /// specified value type. The 'representative' register class is the largest
209 /// legal super-reg register class for the register class of the value type.
210 /// For example, on i386 the rep register class for i8, i16, and i32 are GR32;
211 /// while the rep register class is GR64 on x86_64.
212 virtual const TargetRegisterClass *getRepRegClassFor(EVT VT) const {
213 assert(VT.isSimple() && "getRepRegClassFor called on illegal type!");
214 const TargetRegisterClass *RC = RepRegClassForVT[VT.getSimpleVT().SimpleTy];
218 /// getRepRegClassCostFor - Return the cost of the 'representative' register
219 /// class for the specified value type.
220 virtual uint8_t getRepRegClassCostFor(EVT VT) const {
221 assert(VT.isSimple() && "getRepRegClassCostFor called on illegal type!");
222 return RepRegClassCostForVT[VT.getSimpleVT().SimpleTy];
225 /// isTypeLegal - Return true if the target has native support for the
226 /// specified value type. This means that it has a register that directly
227 /// holds it without promotions or expansions.
228 bool isTypeLegal(EVT VT) const {
229 assert(!VT.isSimple() ||
230 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
231 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != 0;
234 class ValueTypeActionImpl {
235 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
236 /// that indicates how instruction selection should deal with the type.
237 uint8_t ValueTypeActions[MVT::LAST_VALUETYPE];
240 ValueTypeActionImpl() {
241 std::fill(ValueTypeActions, array_endof(ValueTypeActions), 0);
244 LegalizeTypeAction getTypeAction(MVT VT) const {
245 return (LegalizeTypeAction)ValueTypeActions[VT.SimpleTy];
248 void setTypeAction(EVT VT, LegalizeTypeAction Action) {
249 unsigned I = VT.getSimpleVT().SimpleTy;
250 ValueTypeActions[I] = Action;
254 const ValueTypeActionImpl &getValueTypeActions() const {
255 return ValueTypeActions;
258 /// getTypeAction - Return how we should legalize values of this type, either
259 /// it is already legal (return 'Legal') or we need to promote it to a larger
260 /// type (return 'Promote'), or we need to expand it into multiple registers
261 /// of smaller integer type (return 'Expand'). 'Custom' is not an option.
262 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
263 return getTypeConversion(Context, VT).first;
265 LegalizeTypeAction getTypeAction(MVT VT) const {
266 return ValueTypeActions.getTypeAction(VT);
269 /// getTypeToTransformTo - For types supported by the target, this is an
270 /// identity function. For types that must be promoted to larger types, this
271 /// returns the larger type to promote to. For integer types that are larger
272 /// than the largest integer register, this contains one step in the expansion
273 /// to get to the smaller register. For illegal floating point types, this
274 /// returns the integer type to transform to.
275 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
276 return getTypeConversion(Context, VT).second;
279 /// getTypeToExpandTo - For types supported by the target, this is an
280 /// identity function. For types that must be expanded (i.e. integer types
281 /// that are larger than the largest integer register or illegal floating
282 /// point types), this returns the largest legal type it will be expanded to.
283 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
284 assert(!VT.isVector());
286 switch (getTypeAction(Context, VT)) {
289 case TypeExpandInteger:
290 VT = getTypeToTransformTo(Context, VT);
293 llvm_unreachable("Type is not legal nor is it to be expanded!");
298 /// getVectorTypeBreakdown - Vector types are broken down into some number of
299 /// legal first class types. For example, EVT::v8f32 maps to 2 EVT::v4f32
300 /// with Altivec or SSE1, or 8 promoted EVT::f64 values with the X86 FP stack.
301 /// Similarly, EVT::v2i64 turns into 4 EVT::i32 values with both PPC and X86.
303 /// This method returns the number of registers needed, and the VT for each
304 /// register. It also returns the VT and quantity of the intermediate values
305 /// before they are promoted/expanded.
307 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
309 unsigned &NumIntermediates,
310 EVT &RegisterVT) const;
312 /// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the
313 /// intrinsic will need to map to a MemIntrinsicNode (touches memory). If
314 /// this is the case, it returns true and store the intrinsic
315 /// information into the IntrinsicInfo that was passed to the function.
316 struct IntrinsicInfo {
317 unsigned opc; // target opcode
318 EVT memVT; // memory VT
319 const Value* ptrVal; // value representing memory location
320 int offset; // offset off of ptrVal
321 unsigned align; // alignment
322 bool vol; // is volatile?
323 bool readMem; // reads memory?
324 bool writeMem; // writes memory?
327 virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
328 unsigned /*Intrinsic*/) const {
332 /// isFPImmLegal - Returns true if the target can instruction select the
333 /// specified FP immediate natively. If false, the legalizer will materialize
334 /// the FP immediate as a load from a constant pool.
335 virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
339 /// isShuffleMaskLegal - Targets can use this to indicate that they only
340 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
341 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
342 /// are assumed to be legal.
343 virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
348 /// canOpTrap - Returns true if the operation can trap for the value type.
349 /// VT must be a legal type. By default, we optimistically assume most
350 /// operations don't trap except for divide and remainder.
351 virtual bool canOpTrap(unsigned Op, EVT VT) const;
353 /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
354 /// used by Targets can use this to indicate if there is a suitable
355 /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
357 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
362 /// getOperationAction - Return how this operation should be treated: either
363 /// it is legal, needs to be promoted to a larger size, needs to be
364 /// expanded to some other code sequence, or the target has a custom expander
366 LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
367 if (VT.isExtended()) return Expand;
368 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
369 unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
370 return (LegalizeAction)OpActions[I][Op];
373 /// isOperationLegalOrCustom - Return true if the specified operation is
374 /// legal on this target or can be made legal with custom lowering. This
375 /// is used to help guide high-level lowering decisions.
376 bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
377 return (VT == MVT::Other || isTypeLegal(VT)) &&
378 (getOperationAction(Op, VT) == Legal ||
379 getOperationAction(Op, VT) == Custom);
382 /// isOperationLegal - Return true if the specified operation is legal on this
384 bool isOperationLegal(unsigned Op, EVT VT) const {
385 return (VT == MVT::Other || isTypeLegal(VT)) &&
386 getOperationAction(Op, VT) == Legal;
389 /// getLoadExtAction - Return how this load with extension should be treated:
390 /// either it is legal, needs to be promoted to a larger size, needs to be
391 /// expanded to some other code sequence, or the target has a custom expander
393 LegalizeAction getLoadExtAction(unsigned ExtType, EVT VT) const {
394 assert(ExtType < ISD::LAST_LOADEXT_TYPE &&
395 VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
396 "Table isn't big enough!");
397 return (LegalizeAction)LoadExtActions[VT.getSimpleVT().SimpleTy][ExtType];
400 /// isLoadExtLegal - Return true if the specified load with extension is legal
402 bool isLoadExtLegal(unsigned ExtType, EVT VT) const {
403 return VT.isSimple() && getLoadExtAction(ExtType, VT) == Legal;
406 /// getTruncStoreAction - Return how this store with truncation should be
407 /// treated: either it is legal, needs to be promoted to a larger size, needs
408 /// to be expanded to some other code sequence, or the target has a custom
410 LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
411 assert(ValVT.getSimpleVT() < MVT::LAST_VALUETYPE &&
412 MemVT.getSimpleVT() < MVT::LAST_VALUETYPE &&
413 "Table isn't big enough!");
414 return (LegalizeAction)TruncStoreActions[ValVT.getSimpleVT().SimpleTy]
415 [MemVT.getSimpleVT().SimpleTy];
418 /// isTruncStoreLegal - Return true if the specified store with truncation is
419 /// legal on this target.
420 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
421 return isTypeLegal(ValVT) && MemVT.isSimple() &&
422 getTruncStoreAction(ValVT, MemVT) == Legal;
425 /// getIndexedLoadAction - Return how the indexed load should be treated:
426 /// either it is legal, needs to be promoted to a larger size, needs to be
427 /// expanded to some other code sequence, or the target has a custom expander
430 getIndexedLoadAction(unsigned IdxMode, EVT VT) const {
431 assert(IdxMode < ISD::LAST_INDEXED_MODE &&
432 VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
433 "Table isn't big enough!");
434 unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy;
435 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
438 /// isIndexedLoadLegal - Return true if the specified indexed load is legal
440 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
441 return VT.isSimple() &&
442 (getIndexedLoadAction(IdxMode, VT) == Legal ||
443 getIndexedLoadAction(IdxMode, VT) == Custom);
446 /// getIndexedStoreAction - Return how the indexed store should be treated:
447 /// either it is legal, needs to be promoted to a larger size, needs to be
448 /// expanded to some other code sequence, or the target has a custom expander
451 getIndexedStoreAction(unsigned IdxMode, EVT VT) const {
452 assert(IdxMode < ISD::LAST_INDEXED_MODE &&
453 VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
454 "Table isn't big enough!");
455 unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy;
456 return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
459 /// isIndexedStoreLegal - Return true if the specified indexed load is legal
461 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
462 return VT.isSimple() &&
463 (getIndexedStoreAction(IdxMode, VT) == Legal ||
464 getIndexedStoreAction(IdxMode, VT) == Custom);
467 /// getCondCodeAction - Return how the condition code should be treated:
468 /// either it is legal, needs to be expanded to some other code sequence,
469 /// or the target has a custom expander for it.
471 getCondCodeAction(ISD::CondCode CC, EVT VT) const {
472 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
473 (unsigned)VT.getSimpleVT().SimpleTy < sizeof(CondCodeActions[0])*4 &&
474 "Table isn't big enough!");
475 LegalizeAction Action = (LegalizeAction)
476 ((CondCodeActions[CC] >> (2*VT.getSimpleVT().SimpleTy)) & 3);
477 assert(Action != Promote && "Can't promote condition code!");
481 /// isCondCodeLegal - Return true if the specified condition code is legal
483 bool isCondCodeLegal(ISD::CondCode CC, EVT VT) const {
484 return getCondCodeAction(CC, VT) == Legal ||
485 getCondCodeAction(CC, VT) == Custom;
489 /// getTypeToPromoteTo - If the action for this operation is to promote, this
490 /// method returns the ValueType to promote to.
491 EVT getTypeToPromoteTo(unsigned Op, EVT VT) const {
492 assert(getOperationAction(Op, VT) == Promote &&
493 "This operation isn't promoted!");
495 // See if this has an explicit type specified.
496 std::map<std::pair<unsigned, MVT::SimpleValueType>,
497 MVT::SimpleValueType>::const_iterator PTTI =
498 PromoteToType.find(std::make_pair(Op, VT.getSimpleVT().SimpleTy));
499 if (PTTI != PromoteToType.end()) return PTTI->second;
501 assert((VT.isInteger() || VT.isFloatingPoint()) &&
502 "Cannot autopromote this type, add it with AddPromotedToType.");
506 NVT = (MVT::SimpleValueType)(NVT.getSimpleVT().SimpleTy+1);
507 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
508 "Didn't find type to promote to!");
509 } while (!isTypeLegal(NVT) ||
510 getOperationAction(Op, NVT) == Promote);
514 /// getValueType - Return the EVT corresponding to this LLVM type.
515 /// This is fixed by the LLVM operations except for the pointer size. If
516 /// AllowUnknown is true, this will return MVT::Other for types with no EVT
517 /// counterpart (e.g. structs), otherwise it will assert.
518 EVT getValueType(Type *Ty, bool AllowUnknown = false) const {
519 // Lower scalar pointers to native pointer types.
520 if (Ty->isPointerTy()) return PointerTy;
522 if (Ty->isVectorTy()) {
523 VectorType *VTy = cast<VectorType>(Ty);
524 Type *Elm = VTy->getElementType();
525 // Lower vectors of pointers to native pointer types.
526 if (Elm->isPointerTy())
527 Elm = EVT(PointerTy).getTypeForEVT(Ty->getContext());
528 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
529 VTy->getNumElements());
531 return EVT::getEVT(Ty, AllowUnknown);
534 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
535 /// function arguments in the caller parameter area. This is the actual
536 /// alignment, not its logarithm.
537 virtual unsigned getByValTypeAlignment(Type *Ty) const;
539 /// getRegisterType - Return the type of registers that this ValueType will
540 /// eventually require.
541 EVT getRegisterType(MVT VT) const {
542 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
543 return RegisterTypeForVT[VT.SimpleTy];
546 /// getRegisterType - Return the type of registers that this ValueType will
547 /// eventually require.
548 EVT getRegisterType(LLVMContext &Context, EVT VT) const {
550 assert((unsigned)VT.getSimpleVT().SimpleTy <
551 array_lengthof(RegisterTypeForVT));
552 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
556 unsigned NumIntermediates;
557 (void)getVectorTypeBreakdown(Context, VT, VT1,
558 NumIntermediates, RegisterVT);
561 if (VT.isInteger()) {
562 return getRegisterType(Context, getTypeToTransformTo(Context, VT));
564 llvm_unreachable("Unsupported extended type!");
567 /// getNumRegisters - Return the number of registers that this ValueType will
568 /// eventually require. This is one for any types promoted to live in larger
569 /// registers, but may be more than one for types (like i64) that are split
570 /// into pieces. For types like i140, which are first promoted then expanded,
571 /// it is the number of registers needed to hold all the bits of the original
572 /// type. For an i140 on a 32 bit machine this means 5 registers.
573 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
575 assert((unsigned)VT.getSimpleVT().SimpleTy <
576 array_lengthof(NumRegistersForVT));
577 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
581 unsigned NumIntermediates;
582 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
584 if (VT.isInteger()) {
585 unsigned BitWidth = VT.getSizeInBits();
586 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
587 return (BitWidth + RegWidth - 1) / RegWidth;
589 llvm_unreachable("Unsupported extended type!");
592 /// ShouldShrinkFPConstant - If true, then instruction selection should
593 /// seek to shrink the FP constant of the specified type to a smaller type
594 /// in order to save space and / or reduce runtime.
595 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
597 /// hasTargetDAGCombine - If true, the target has custom DAG combine
598 /// transformations that it can perform for the specified node.
599 bool hasTargetDAGCombine(ISD::NodeType NT) const {
600 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
601 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
604 /// This function returns the maximum number of store operations permitted
605 /// to replace a call to llvm.memset. The value is set by the target at the
606 /// performance threshold for such a replacement. If OptSize is true,
607 /// return the limit for functions that have OptSize attribute.
608 /// @brief Get maximum # of store operations permitted for llvm.memset
609 unsigned getMaxStoresPerMemset(bool OptSize) const {
610 return OptSize ? maxStoresPerMemsetOptSize : maxStoresPerMemset;
613 /// This function returns the maximum number of store operations permitted
614 /// to replace a call to llvm.memcpy. The value is set by the target at the
615 /// performance threshold for such a replacement. If OptSize is true,
616 /// return the limit for functions that have OptSize attribute.
617 /// @brief Get maximum # of store operations permitted for llvm.memcpy
618 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
619 return OptSize ? maxStoresPerMemcpyOptSize : maxStoresPerMemcpy;
622 /// This function returns the maximum number of store operations permitted
623 /// to replace a call to llvm.memmove. The value is set by the target at the
624 /// performance threshold for such a replacement. If OptSize is true,
625 /// return the limit for functions that have OptSize attribute.
626 /// @brief Get maximum # of store operations permitted for llvm.memmove
627 unsigned getMaxStoresPerMemmove(bool OptSize) const {
628 return OptSize ? maxStoresPerMemmoveOptSize : maxStoresPerMemmove;
631 /// This function returns true if the target allows unaligned memory accesses.
632 /// of the specified type. This is used, for example, in situations where an
633 /// array copy/move/set is converted to a sequence of store operations. It's
634 /// use helps to ensure that such replacements don't generate code that causes
635 /// an alignment error (trap) on the target machine.
636 /// @brief Determine if the target supports unaligned memory accesses.
637 virtual bool allowsUnalignedMemoryAccesses(EVT) const {
641 /// This function returns true if the target would benefit from code placement
643 /// @brief Determine if the target should perform code placement optimization.
644 bool shouldOptimizeCodePlacement() const {
645 return benefitFromCodePlacementOpt;
648 /// getOptimalMemOpType - Returns the target specific optimal type for load
649 /// and store operations as a result of memset, memcpy, and memmove
650 /// lowering. If DstAlign is zero that means it's safe to destination
651 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
652 /// means there isn't a need to check it against alignment requirement,
653 /// probably because the source does not need to be loaded. If
654 /// 'IsZeroVal' is true, that means it's safe to return a
655 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
656 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
657 /// constant so it does not need to be loaded.
658 /// It returns EVT::Other if the type should be determined using generic
659 /// target-independent logic.
660 virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
661 unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
663 bool /*MemcpyStrSrc*/,
664 MachineFunction &/*MF*/) const {
668 /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
669 /// to implement llvm.setjmp.
670 bool usesUnderscoreSetJmp() const {
671 return UseUnderscoreSetJmp;
674 /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
675 /// to implement llvm.longjmp.
676 bool usesUnderscoreLongJmp() const {
677 return UseUnderscoreLongJmp;
680 /// getStackPointerRegisterToSaveRestore - If a physical register, this
681 /// specifies the register that llvm.savestack/llvm.restorestack should save
683 unsigned getStackPointerRegisterToSaveRestore() const {
684 return StackPointerRegisterToSaveRestore;
687 /// getExceptionPointerRegister - If a physical register, this returns
688 /// the register that receives the exception address on entry to a landing
690 unsigned getExceptionPointerRegister() const {
691 return ExceptionPointerRegister;
694 /// getExceptionSelectorRegister - If a physical register, this returns
695 /// the register that receives the exception typeid on entry to a landing
697 unsigned getExceptionSelectorRegister() const {
698 return ExceptionSelectorRegister;
701 /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
702 /// set, the default is 200)
703 unsigned getJumpBufSize() const {
707 /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
708 /// (if never set, the default is 0)
709 unsigned getJumpBufAlignment() const {
710 return JumpBufAlignment;
713 /// getMinStackArgumentAlignment - return the minimum stack alignment of an
715 unsigned getMinStackArgumentAlignment() const {
716 return MinStackArgumentAlignment;
719 /// getMinFunctionAlignment - return the minimum function alignment.
721 unsigned getMinFunctionAlignment() const {
722 return MinFunctionAlignment;
725 /// getPrefFunctionAlignment - return the preferred function alignment.
727 unsigned getPrefFunctionAlignment() const {
728 return PrefFunctionAlignment;
731 /// getPrefLoopAlignment - return the preferred loop alignment.
733 unsigned getPrefLoopAlignment() const {
734 return PrefLoopAlignment;
737 /// getShouldFoldAtomicFences - return whether the combiner should fold
738 /// fence MEMBARRIER instructions into the atomic intrinsic instructions.
740 bool getShouldFoldAtomicFences() const {
741 return ShouldFoldAtomicFences;
744 /// getInsertFencesFor - return whether the DAG builder should automatically
745 /// insert fences and reduce ordering for atomics.
747 bool getInsertFencesForAtomic() const {
748 return InsertFencesForAtomic;
751 /// getPreIndexedAddressParts - returns true by value, base pointer and
752 /// offset pointer and addressing mode by reference if the node's address
753 /// can be legally represented as pre-indexed load / store address.
754 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
756 ISD::MemIndexedMode &/*AM*/,
757 SelectionDAG &/*DAG*/) const {
761 /// getPostIndexedAddressParts - returns true by value, base pointer and
762 /// offset pointer and addressing mode by reference if this node can be
763 /// combined with a load / store to form a post-indexed load / store.
764 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
765 SDValue &/*Base*/, SDValue &/*Offset*/,
766 ISD::MemIndexedMode &/*AM*/,
767 SelectionDAG &/*DAG*/) const {
771 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
772 /// current function. The returned value is a member of the
773 /// MachineJumpTableInfo::JTEntryKind enum.
774 virtual unsigned getJumpTableEncoding() const;
776 virtual const MCExpr *
777 LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
778 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
779 MCContext &/*Ctx*/) const {
780 llvm_unreachable("Need to implement this hook if target has custom JTIs");
783 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
785 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
786 SelectionDAG &DAG) const;
788 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
789 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
791 virtual const MCExpr *
792 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
793 unsigned JTI, MCContext &Ctx) const;
795 /// isOffsetFoldingLegal - Return true if folding a constant offset
796 /// with the given GlobalAddress is legal. It is frequently not legal in
797 /// PIC relocation models.
798 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
800 /// getStackCookieLocation - Return true if the target stores stack
801 /// protector cookies at a fixed offset in some non-standard address
802 /// space, and populates the address space and offset as
804 virtual bool getStackCookieLocation(unsigned &/*AddressSpace*/,
805 unsigned &/*Offset*/) const {
809 /// getMaximalGlobalOffset - Returns the maximal possible offset which can be
810 /// used for loads / stores from the global.
811 virtual unsigned getMaximalGlobalOffset() const {
815 //===--------------------------------------------------------------------===//
816 // TargetLowering Optimization Methods
819 /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
820 /// SDValues for returning information from TargetLowering to its clients
821 /// that want to combine
822 struct TargetLoweringOpt {
829 explicit TargetLoweringOpt(SelectionDAG &InDAG,
831 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
833 bool LegalTypes() const { return LegalTys; }
834 bool LegalOperations() const { return LegalOps; }
836 bool CombineTo(SDValue O, SDValue N) {
842 /// ShrinkDemandedConstant - Check to see if the specified operand of the
843 /// specified instruction is a constant integer. If so, check to see if
844 /// there are any bits set in the constant that are not demanded. If so,
845 /// shrink the constant and return true.
846 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
848 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
849 /// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening
850 /// cast, but it could be generalized for targets with other types of
851 /// implicit widening casts.
852 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
856 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
857 /// DemandedMask bits of the result of Op are ever used downstream. If we can
858 /// use this information to simplify Op, create a new simplified DAG node and
859 /// return true, returning the original and new nodes in Old and New.
860 /// Otherwise, analyze the expression and return a mask of KnownOne and
861 /// KnownZero bits for the expression (used to simplify the caller).
862 /// The KnownZero/One bits may only be accurate for those bits in the
864 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
865 APInt &KnownZero, APInt &KnownOne,
866 TargetLoweringOpt &TLO, unsigned Depth = 0) const;
868 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
869 /// Mask are known to be either zero or one and return them in the
870 /// KnownZero/KnownOne bitsets.
871 virtual void computeMaskedBitsForTargetNode(const SDValue Op,
874 const SelectionDAG &DAG,
875 unsigned Depth = 0) const;
877 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
878 /// targets that want to expose additional information about sign bits to the
880 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
881 unsigned Depth = 0) const;
883 struct DAGCombinerInfo {
884 void *DC; // The DAG Combiner object.
886 bool BeforeLegalizeOps;
887 bool CalledByLegalizer;
891 DAGCombinerInfo(SelectionDAG &dag, bool bl, bool blo, bool cl, void *dc)
892 : DC(dc), BeforeLegalize(bl), BeforeLegalizeOps(blo),
893 CalledByLegalizer(cl), DAG(dag) {}
895 bool isBeforeLegalize() const { return BeforeLegalize; }
896 bool isBeforeLegalizeOps() const { return BeforeLegalizeOps; }
897 bool isCalledByLegalizer() const { return CalledByLegalizer; }
899 void AddToWorklist(SDNode *N);
900 void RemoveFromWorklist(SDNode *N);
901 SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
903 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
904 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
906 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
909 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
910 /// and cc. If it is unable to simplify it, return a null SDValue.
911 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
912 ISD::CondCode Cond, bool foldBooleans,
913 DAGCombinerInfo &DCI, DebugLoc dl) const;
915 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
916 /// node is a GlobalAddress + offset.
918 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
920 /// PerformDAGCombine - This method will be invoked for all target nodes and
921 /// for any target-independent nodes that the target has registered with
924 /// The semantics are as follows:
926 /// SDValue.Val == 0 - No change was made
927 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
928 /// otherwise - N should be replaced by the returned Operand.
930 /// In addition, methods provided by DAGCombinerInfo may be used to perform
931 /// more complex transformations.
933 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
935 /// isTypeDesirableForOp - Return true if the target has native support for
936 /// the specified value type and it is 'desirable' to use the type for the
937 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
938 /// instruction encodings are longer and some i16 instructions are slow.
939 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
940 // By default, assume all legal types are desirable.
941 return isTypeLegal(VT);
944 /// isDesirableToPromoteOp - Return true if it is profitable for dag combiner
945 /// to transform a floating point op of specified opcode to a equivalent op of
946 /// an integer type. e.g. f32 load -> i32 load can be profitable on ARM.
947 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
952 /// IsDesirableToPromoteOp - This method query the target whether it is
953 /// beneficial for dag combiner to promote the specified node. If true, it
954 /// should return the desired promotion type by reference.
955 virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
959 //===--------------------------------------------------------------------===//
960 // TargetLowering Configuration Methods - These methods should be invoked by
961 // the derived class constructor to configure this object for the target.
965 /// setBooleanContents - Specify how the target extends the result of a
966 /// boolean value from i1 to a wider type. See getBooleanContents.
967 void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
968 /// setBooleanVectorContents - Specify how the target extends the result
969 /// of a vector boolean value from a vector of i1 to a wider type. See
970 /// getBooleanContents.
971 void setBooleanVectorContents(BooleanContent Ty) {
972 BooleanVectorContents = Ty;
975 /// setSchedulingPreference - Specify the target scheduling preference.
976 void setSchedulingPreference(Sched::Preference Pref) {
977 SchedPreferenceInfo = Pref;
980 /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
981 /// use _setjmp to implement llvm.setjmp or the non _ version.
982 /// Defaults to false.
983 void setUseUnderscoreSetJmp(bool Val) {
984 UseUnderscoreSetJmp = Val;
987 /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
988 /// use _longjmp to implement llvm.longjmp or the non _ version.
989 /// Defaults to false.
990 void setUseUnderscoreLongJmp(bool Val) {
991 UseUnderscoreLongJmp = Val;
994 /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
995 /// specifies the register that llvm.savestack/llvm.restorestack should save
997 void setStackPointerRegisterToSaveRestore(unsigned R) {
998 StackPointerRegisterToSaveRestore = R;
1001 /// setExceptionPointerRegister - If set to a physical register, this sets
1002 /// the register that receives the exception address on entry to a landing
1004 void setExceptionPointerRegister(unsigned R) {
1005 ExceptionPointerRegister = R;
1008 /// setExceptionSelectorRegister - If set to a physical register, this sets
1009 /// the register that receives the exception typeid on entry to a landing
1011 void setExceptionSelectorRegister(unsigned R) {
1012 ExceptionSelectorRegister = R;
1015 /// SelectIsExpensive - Tells the code generator not to expand operations
1016 /// into sequences that use the select operations if possible.
1017 void setSelectIsExpensive(bool isExpensive = true) {
1018 SelectIsExpensive = isExpensive;
1021 /// JumpIsExpensive - Tells the code generator not to expand sequence of
1022 /// operations into a separate sequences that increases the amount of
1024 void setJumpIsExpensive(bool isExpensive = true) {
1025 JumpIsExpensive = isExpensive;
1028 /// setIntDivIsCheap - Tells the code generator that integer divide is
1029 /// expensive, and if possible, should be replaced by an alternate sequence
1030 /// of instructions not containing an integer divide.
1031 void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
1033 /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
1034 /// srl/add/sra for a signed divide by power of two, and let the target handle
1036 void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
1038 /// addRegisterClass - Add the specified register class as an available
1039 /// regclass for the specified value type. This indicates the selector can
1040 /// handle values of that class natively.
1041 void addRegisterClass(EVT VT, const TargetRegisterClass *RC) {
1042 assert((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
1043 AvailableRegClasses.push_back(std::make_pair(VT, RC));
1044 RegClassForVT[VT.getSimpleVT().SimpleTy] = RC;
1047 /// findRepresentativeClass - Return the largest legal super-reg register class
1048 /// of the register class for the specified type and its associated "cost".
1049 virtual std::pair<const TargetRegisterClass*, uint8_t>
1050 findRepresentativeClass(EVT VT) const;
1052 /// computeRegisterProperties - Once all of the register classes are added,
1053 /// this allows us to compute derived properties we expose.
1054 void computeRegisterProperties();
1056 /// setOperationAction - Indicate that the specified operation does not work
1057 /// with the specified type and indicate what to do about it.
1058 void setOperationAction(unsigned Op, MVT VT,
1059 LegalizeAction Action) {
1060 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
1061 OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action;
1064 /// setLoadExtAction - Indicate that the specified load with extension does
1065 /// not work with the specified type and indicate what to do about it.
1066 void setLoadExtAction(unsigned ExtType, MVT VT,
1067 LegalizeAction Action) {
1068 assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
1069 "Table isn't big enough!");
1070 LoadExtActions[VT.SimpleTy][ExtType] = (uint8_t)Action;
1073 /// setTruncStoreAction - Indicate that the specified truncating store does
1074 /// not work with the specified type and indicate what to do about it.
1075 void setTruncStoreAction(MVT ValVT, MVT MemVT,
1076 LegalizeAction Action) {
1077 assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
1078 "Table isn't big enough!");
1079 TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action;
1082 /// setIndexedLoadAction - Indicate that the specified indexed load does or
1083 /// does not work with the specified type and indicate what to do abort
1084 /// it. NOTE: All indexed mode loads are initialized to Expand in
1085 /// TargetLowering.cpp
1086 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1087 LegalizeAction Action) {
1088 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1089 (unsigned)Action < 0xf && "Table isn't big enough!");
1090 // Load action are kept in the upper half.
1091 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1092 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1095 /// setIndexedStoreAction - Indicate that the specified indexed store does or
1096 /// does not work with the specified type and indicate what to do about
1097 /// it. NOTE: All indexed mode stores are initialized to Expand in
1098 /// TargetLowering.cpp
1099 void setIndexedStoreAction(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 // Store action are kept in the lower half.
1104 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1105 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1108 /// setCondCodeAction - Indicate that the specified condition code is or isn't
1109 /// supported on the target and indicate what to do about it.
1110 void setCondCodeAction(ISD::CondCode CC, MVT VT,
1111 LegalizeAction Action) {
1112 assert(VT < MVT::LAST_VALUETYPE &&
1113 (unsigned)CC < array_lengthof(CondCodeActions) &&
1114 "Table isn't big enough!");
1115 CondCodeActions[(unsigned)CC] &= ~(uint64_t(3UL) << VT.SimpleTy*2);
1116 CondCodeActions[(unsigned)CC] |= (uint64_t)Action << VT.SimpleTy*2;
1119 /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
1120 /// promotion code defaults to trying a larger integer/fp until it can find
1121 /// one that works. If that default is insufficient, this method can be used
1122 /// by the target to override the default.
1123 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1124 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1127 /// setTargetDAGCombine - Targets should invoke this method for each target
1128 /// independent node that they want to provide a custom DAG combiner for by
1129 /// implementing the PerformDAGCombine virtual method.
1130 void setTargetDAGCombine(ISD::NodeType NT) {
1131 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1132 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1135 /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
1136 /// bytes); default is 200
1137 void setJumpBufSize(unsigned Size) {
1141 /// setJumpBufAlignment - Set the target's required jmp_buf buffer
1142 /// alignment (in bytes); default is 0
1143 void setJumpBufAlignment(unsigned Align) {
1144 JumpBufAlignment = Align;
1147 /// setMinFunctionAlignment - Set the target's minimum function alignment (in
1149 void setMinFunctionAlignment(unsigned Align) {
1150 MinFunctionAlignment = Align;
1153 /// setPrefFunctionAlignment - Set the target's preferred function alignment.
1154 /// This should be set if there is a performance benefit to
1155 /// higher-than-minimum alignment (in log2(bytes))
1156 void setPrefFunctionAlignment(unsigned Align) {
1157 PrefFunctionAlignment = Align;
1160 /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
1161 /// alignment is zero, it means the target does not care about loop alignment.
1162 /// The alignment is specified in log2(bytes).
1163 void setPrefLoopAlignment(unsigned Align) {
1164 PrefLoopAlignment = Align;
1167 /// setMinStackArgumentAlignment - Set the minimum stack alignment of an
1168 /// argument (in log2(bytes)).
1169 void setMinStackArgumentAlignment(unsigned Align) {
1170 MinStackArgumentAlignment = Align;
1173 /// setShouldFoldAtomicFences - Set if the target's implementation of the
1174 /// atomic operation intrinsics includes locking. Default is false.
1175 void setShouldFoldAtomicFences(bool fold) {
1176 ShouldFoldAtomicFences = fold;
1179 /// setInsertFencesForAtomic - Set if the the DAG builder should
1180 /// automatically insert fences and reduce the order of atomic memory
1181 /// operations to Monotonic.
1182 void setInsertFencesForAtomic(bool fence) {
1183 InsertFencesForAtomic = fence;
1187 //===--------------------------------------------------------------------===//
1188 // Lowering methods - These methods must be implemented by targets so that
1189 // the SelectionDAGLowering code knows how to lower these.
1192 /// LowerFormalArguments - This hook must be implemented to lower the
1193 /// incoming (formal) arguments, described by the Ins array, into the
1194 /// specified DAG. The implementation should fill in the InVals array
1195 /// with legal-type argument values, and return the resulting token
1199 LowerFormalArguments(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1201 const SmallVectorImpl<ISD::InputArg> &/*Ins*/,
1202 DebugLoc /*dl*/, SelectionDAG &/*DAG*/,
1203 SmallVectorImpl<SDValue> &/*InVals*/) const {
1204 llvm_unreachable("Not Implemented");
1207 struct ArgListEntry {
1218 ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1219 isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
1221 typedef std::vector<ArgListEntry> ArgListTy;
1223 /// CallLoweringInfo - This structure contains all information that is
1224 /// necessary for lowering calls. It is passed to TLI::LowerCallTo when the
1225 /// SelectionDAG builder needs to lower a call, and targets will see this
1226 /// struct in their LowerCall implementation.
1227 struct CallLoweringInfo {
1234 bool DoesNotReturn : 1;
1235 bool IsReturnValueUsed : 1;
1237 // IsTailCall should be modified by implementations of
1238 // TargetLowering::LowerCall that perform tail call conversions.
1241 unsigned NumFixedArgs;
1242 CallingConv::ID CallConv;
1247 ImmutableCallSite *CS;
1248 SmallVector<ISD::OutputArg, 32> Outs;
1249 SmallVector<SDValue, 32> OutVals;
1250 SmallVector<ISD::InputArg, 32> Ins;
1253 /// CallLoweringInfo - Constructs a call lowering context based on the
1254 /// ImmutableCallSite \p cs.
1255 CallLoweringInfo(SDValue chain, Type *retTy,
1256 FunctionType *FTy, bool isTailCall, SDValue callee,
1257 ArgListTy &args, SelectionDAG &dag, DebugLoc dl,
1258 ImmutableCallSite &cs)
1259 : Chain(chain), RetTy(retTy), RetSExt(cs.paramHasAttr(0, Attribute::SExt)),
1260 RetZExt(cs.paramHasAttr(0, Attribute::ZExt)), IsVarArg(FTy->isVarArg()),
1261 IsInReg(cs.paramHasAttr(0, Attribute::InReg)),
1262 DoesNotReturn(cs.doesNotReturn()),
1263 IsReturnValueUsed(!cs.getInstruction()->use_empty()),
1264 IsTailCall(isTailCall), NumFixedArgs(FTy->getNumParams()),
1265 CallConv(cs.getCallingConv()), Callee(callee), Args(args), DAG(dag),
1268 /// CallLoweringInfo - Constructs a call lowering context based on the
1269 /// provided call information.
1270 CallLoweringInfo(SDValue chain, Type *retTy, bool retSExt, bool retZExt,
1271 bool isVarArg, bool isInReg, unsigned numFixedArgs,
1272 CallingConv::ID callConv, bool isTailCall,
1273 bool doesNotReturn, bool isReturnValueUsed, SDValue callee,
1274 ArgListTy &args, SelectionDAG &dag, DebugLoc dl)
1275 : Chain(chain), RetTy(retTy), RetSExt(retSExt), RetZExt(retZExt),
1276 IsVarArg(isVarArg), IsInReg(isInReg), DoesNotReturn(doesNotReturn),
1277 IsReturnValueUsed(isReturnValueUsed), IsTailCall(isTailCall),
1278 NumFixedArgs(numFixedArgs), CallConv(callConv), Callee(callee),
1279 Args(args), DAG(dag), DL(dl), CS(NULL) {}
1282 /// LowerCallTo - This function lowers an abstract call to a function into an
1283 /// actual call. This returns a pair of operands. The first element is the
1284 /// return value for the function (if RetTy is not VoidTy). The second
1285 /// element is the outgoing token chain. It calls LowerCall to do the actual
1287 std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
1289 /// LowerCall - This hook must be implemented to lower calls into the
1290 /// the specified DAG. The outgoing arguments to the call are described
1291 /// by the Outs array, and the values to be returned by the call are
1292 /// described by the Ins array. The implementation should fill in the
1293 /// InVals array with legal-type return values from the call, and return
1294 /// the resulting token chain value.
1296 LowerCall(CallLoweringInfo &/*CLI*/,
1297 SmallVectorImpl<SDValue> &/*InVals*/) const {
1298 llvm_unreachable("Not Implemented");
1301 /// HandleByVal - Target-specific cleanup for formal ByVal parameters.
1302 virtual void HandleByVal(CCState *, unsigned &) const {}
1304 /// CanLowerReturn - This hook should be implemented to check whether the
1305 /// return values described by the Outs array can fit into the return
1306 /// registers. If false is returned, an sret-demotion is performed.
1308 virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
1309 MachineFunction &/*MF*/, bool /*isVarArg*/,
1310 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
1311 LLVMContext &/*Context*/) const
1313 // Return true by default to get preexisting behavior.
1317 /// LowerReturn - This hook must be implemented to lower outgoing
1318 /// return values, described by the Outs array, into the specified
1319 /// DAG. The implementation should return the resulting token chain
1323 LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1325 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
1326 const SmallVectorImpl<SDValue> &/*OutVals*/,
1327 DebugLoc /*dl*/, SelectionDAG &/*DAG*/) const {
1328 llvm_unreachable("Not Implemented");
1331 /// isUsedByReturnOnly - Return true if result of the specified node is used
1332 /// by a return node only. It also compute and return the input chain for the
1334 /// This is used to determine whether it is possible
1335 /// to codegen a libcall as tail call at legalization time.
1336 virtual bool isUsedByReturnOnly(SDNode *, SDValue &Chain) const {
1340 /// mayBeEmittedAsTailCall - Return true if the target may be able emit the
1341 /// call instruction as a tail call. This is used by optimization passes to
1342 /// determine if it's profitable to duplicate return instructions to enable
1343 /// tailcall optimization.
1344 virtual bool mayBeEmittedAsTailCall(CallInst *) const {
1348 /// getTypeForExtArgOrReturn - Return the type that should be used to zero or
1349 /// sign extend a zeroext/signext integer argument or return value.
1350 /// FIXME: Most C calling convention requires the return type to be promoted,
1351 /// but this is not true all the time, e.g. i1 on x86-64. It is also not
1352 /// necessary for non-C calling conventions. The frontend should handle this
1353 /// and include all of the necessary information.
1354 virtual EVT getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1355 ISD::NodeType /*ExtendKind*/) const {
1356 EVT MinVT = getRegisterType(Context, MVT::i32);
1357 return VT.bitsLT(MinVT) ? MinVT : VT;
1360 /// LowerOperationWrapper - This callback is invoked by the type legalizer
1361 /// to legalize nodes with an illegal operand type but legal result types.
1362 /// It replaces the LowerOperation callback in the type Legalizer.
1363 /// The reason we can not do away with LowerOperation entirely is that
1364 /// LegalizeDAG isn't yet ready to use this callback.
1365 /// TODO: Consider merging with ReplaceNodeResults.
1367 /// The target places new result values for the node in Results (their number
1368 /// and types must exactly match those of the original return values of
1369 /// the node), or leaves Results empty, which indicates that the node is not
1370 /// to be custom lowered after all.
1371 /// The default implementation calls LowerOperation.
1372 virtual void LowerOperationWrapper(SDNode *N,
1373 SmallVectorImpl<SDValue> &Results,
1374 SelectionDAG &DAG) const;
1376 /// LowerOperation - This callback is invoked for operations that are
1377 /// unsupported by the target, which are registered to use 'custom' lowering,
1378 /// and whose defined values are all legal.
1379 /// If the target has no operations that require custom lowering, it need not
1380 /// implement this. The default implementation of this aborts.
1381 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
1383 /// ReplaceNodeResults - This callback is invoked when a node result type is
1384 /// illegal for the target, and the operation was registered to use 'custom'
1385 /// lowering for that result type. The target places new result values for
1386 /// the node in Results (their number and types must exactly match those of
1387 /// the original return values of the node), or leaves Results empty, which
1388 /// indicates that the node is not to be custom lowered after all.
1390 /// If the target has no operations that require custom lowering, it need not
1391 /// implement this. The default implementation aborts.
1392 virtual void ReplaceNodeResults(SDNode * /*N*/,
1393 SmallVectorImpl<SDValue> &/*Results*/,
1394 SelectionDAG &/*DAG*/) const {
1395 llvm_unreachable("ReplaceNodeResults not implemented for this target!");
1398 /// getTargetNodeName() - This method returns the name of a target specific
1400 virtual const char *getTargetNodeName(unsigned Opcode) const;
1402 /// createFastISel - This method returns a target specific FastISel object,
1403 /// or null if the target does not support "fast" ISel.
1404 virtual FastISel *createFastISel(FunctionLoweringInfo &) const {
1408 //===--------------------------------------------------------------------===//
1409 // Inline Asm Support hooks
1412 /// ExpandInlineAsm - This hook allows the target to expand an inline asm
1413 /// call to be explicit llvm code if it wants to. This is useful for
1414 /// turning simple inline asms into LLVM intrinsics, which gives the
1415 /// compiler more information about the behavior of the code.
1416 virtual bool ExpandInlineAsm(CallInst *) const {
1420 enum ConstraintType {
1421 C_Register, // Constraint represents specific register(s).
1422 C_RegisterClass, // Constraint represents any of register(s) in class.
1423 C_Memory, // Memory constraint.
1424 C_Other, // Something else.
1425 C_Unknown // Unsupported constraint.
1428 enum ConstraintWeight {
1430 CW_Invalid = -1, // No match.
1431 CW_Okay = 0, // Acceptable.
1432 CW_Good = 1, // Good weight.
1433 CW_Better = 2, // Better weight.
1434 CW_Best = 3, // Best weight.
1436 // Well-known weights.
1437 CW_SpecificReg = CW_Okay, // Specific register operands.
1438 CW_Register = CW_Good, // Register operands.
1439 CW_Memory = CW_Better, // Memory operands.
1440 CW_Constant = CW_Best, // Constant operand.
1441 CW_Default = CW_Okay // Default or don't know type.
1444 /// AsmOperandInfo - This contains information for each constraint that we are
1446 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
1447 /// ConstraintCode - This contains the actual string for the code, like "m".
1448 /// TargetLowering picks the 'best' code from ConstraintInfo::Codes that
1449 /// most closely matches the operand.
1450 std::string ConstraintCode;
1452 /// ConstraintType - Information about the constraint code, e.g. Register,
1453 /// RegisterClass, Memory, Other, Unknown.
1454 TargetLowering::ConstraintType ConstraintType;
1456 /// CallOperandval - If this is the result output operand or a
1457 /// clobber, this is null, otherwise it is the incoming operand to the
1458 /// CallInst. This gets modified as the asm is processed.
1459 Value *CallOperandVal;
1461 /// ConstraintVT - The ValueType for the operand value.
1464 /// isMatchingInputConstraint - Return true of this is an input operand that
1465 /// is a matching constraint like "4".
1466 bool isMatchingInputConstraint() const;
1468 /// getMatchedOperand - If this is an input matching constraint, this method
1469 /// returns the output operand it matches.
1470 unsigned getMatchedOperand() const;
1472 /// Copy constructor for copying from an AsmOperandInfo.
1473 AsmOperandInfo(const AsmOperandInfo &info)
1474 : InlineAsm::ConstraintInfo(info),
1475 ConstraintCode(info.ConstraintCode),
1476 ConstraintType(info.ConstraintType),
1477 CallOperandVal(info.CallOperandVal),
1478 ConstraintVT(info.ConstraintVT) {
1481 /// Copy constructor for copying from a ConstraintInfo.
1482 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
1483 : InlineAsm::ConstraintInfo(info),
1484 ConstraintType(TargetLowering::C_Unknown),
1485 CallOperandVal(0), ConstraintVT(MVT::Other) {
1489 typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
1491 /// ParseConstraints - Split up the constraint string from the inline
1492 /// assembly value into the specific constraints and their prefixes,
1493 /// and also tie in the associated operand values.
1494 /// If this returns an empty vector, and if the constraint string itself
1495 /// isn't empty, there was an error parsing.
1496 virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const;
1498 /// Examine constraint type and operand type and determine a weight value.
1499 /// The operand object must already have been set up with the operand type.
1500 virtual ConstraintWeight getMultipleConstraintMatchWeight(
1501 AsmOperandInfo &info, int maIndex) const;
1503 /// Examine constraint string and operand type and determine a weight value.
1504 /// The operand object must already have been set up with the operand type.
1505 virtual ConstraintWeight getSingleConstraintMatchWeight(
1506 AsmOperandInfo &info, const char *constraint) const;
1508 /// ComputeConstraintToUse - Determines the constraint code and constraint
1509 /// type to use for the specific AsmOperandInfo, setting
1510 /// OpInfo.ConstraintCode and OpInfo.ConstraintType. If the actual operand
1511 /// being passed in is available, it can be passed in as Op, otherwise an
1512 /// empty SDValue can be passed.
1513 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
1515 SelectionDAG *DAG = 0) const;
1517 /// getConstraintType - Given a constraint, return the type of constraint it
1518 /// is for this target.
1519 virtual ConstraintType getConstraintType(const std::string &Constraint) const;
1521 /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
1522 /// {edx}), return the register number and the register class for the
1525 /// Given a register class constraint, like 'r', if this corresponds directly
1526 /// to an LLVM register class, return a register of 0 and the register class
1529 /// This should only be used for C_Register constraints. On error,
1530 /// this returns a register number of 0 and a null register class pointer..
1531 virtual std::pair<unsigned, const TargetRegisterClass*>
1532 getRegForInlineAsmConstraint(const std::string &Constraint,
1535 /// LowerXConstraint - try to replace an X constraint, which matches anything,
1536 /// with another that has more specific requirements based on the type of the
1537 /// corresponding operand. This returns null if there is no replacement to
1539 virtual const char *LowerXConstraint(EVT ConstraintVT) const;
1541 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1542 /// vector. If it is invalid, don't add anything to Ops.
1543 virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
1544 std::vector<SDValue> &Ops,
1545 SelectionDAG &DAG) const;
1547 //===--------------------------------------------------------------------===//
1548 // Instruction Emitting Hooks
1551 // EmitInstrWithCustomInserter - This method should be implemented by targets
1552 // that mark instructions with the 'usesCustomInserter' flag. These
1553 // instructions are special in various ways, which require special support to
1554 // insert. The specified MachineInstr is created but not inserted into any
1555 // basic blocks, and this method is called to expand it into a sequence of
1556 // instructions, potentially also creating new basic blocks and control flow.
1557 virtual MachineBasicBlock *
1558 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const;
1560 /// AdjustInstrPostInstrSelection - This method should be implemented by
1561 /// targets that mark instructions with the 'hasPostISelHook' flag. These
1562 /// instructions must be adjusted after instruction selection by target hooks.
1563 /// e.g. To fill in optional defs for ARM 's' setting instructions.
1565 AdjustInstrPostInstrSelection(MachineInstr *MI, SDNode *Node) const;
1567 //===--------------------------------------------------------------------===//
1568 // Addressing mode description hooks (used by LSR etc).
1571 /// AddrMode - This represents an addressing mode of:
1572 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1573 /// If BaseGV is null, there is no BaseGV.
1574 /// If BaseOffs is zero, there is no base offset.
1575 /// If HasBaseReg is false, there is no base register.
1576 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1580 GlobalValue *BaseGV;
1584 AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1587 /// GetAddrModeArguments - CodeGenPrepare sinks address calculations into the
1588 /// same BB as Load/Store instructions reading the address. This allows as
1589 /// much computation as possible to be done in the address mode for that
1590 /// operand. This hook lets targets also pass back when this should be done
1591 /// on intrinsics which load/store.
1592 virtual bool GetAddrModeArguments(IntrinsicInst *I,
1593 SmallVectorImpl<Value*> &Ops,
1594 Type *&AccessTy) const {
1598 /// isLegalAddressingMode - Return true if the addressing mode represented by
1599 /// AM is legal for this target, for a load/store of the specified type.
1600 /// The type may be VoidTy, in which case only return true if the addressing
1601 /// mode is legal for a load/store of any legal type.
1602 /// TODO: Handle pre/postinc as well.
1603 virtual bool isLegalAddressingMode(const AddrMode &AM, Type *Ty) const;
1605 /// isLegalICmpImmediate - Return true if the specified immediate is legal
1606 /// icmp immediate, that is the target has icmp instructions which can compare
1607 /// a register against the immediate without having to materialize the
1608 /// immediate into a register.
1609 virtual bool isLegalICmpImmediate(int64_t) const {
1613 /// isLegalAddImmediate - Return true if the specified immediate is legal
1614 /// add immediate, that is the target has add instructions which can add
1615 /// a register with the immediate without having to materialize the
1616 /// immediate into a register.
1617 virtual bool isLegalAddImmediate(int64_t) const {
1621 /// isTruncateFree - Return true if it's free to truncate a value of
1622 /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1623 /// register EAX to i16 by referencing its sub-register AX.
1624 virtual bool isTruncateFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1628 virtual bool isTruncateFree(EVT /*VT1*/, EVT /*VT2*/) const {
1632 /// isZExtFree - Return true if any actual instruction that defines a
1633 /// value of type Ty1 implicitly zero-extends the value to Ty2 in the result
1634 /// register. This does not necessarily include registers defined in
1635 /// unknown ways, such as incoming arguments, or copies from unknown
1636 /// virtual registers. Also, if isTruncateFree(Ty2, Ty1) is true, this
1637 /// does not necessarily apply to truncate instructions. e.g. on x86-64,
1638 /// all instructions that define 32-bit values implicit zero-extend the
1639 /// result out to 64 bits.
1640 virtual bool isZExtFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1644 virtual bool isZExtFree(EVT /*VT1*/, EVT /*VT2*/) const {
1648 /// isFNegFree - Return true if an fneg operation is free to the point where
1649 /// it is never worthwhile to replace it with a bitwise operation.
1650 virtual bool isFNegFree(EVT) const {
1654 /// isFAbsFree - Return true if an fneg operation is free to the point where
1655 /// it is never worthwhile to replace it with a bitwise operation.
1656 virtual bool isFAbsFree(EVT) const {
1660 /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
1661 /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
1662 /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
1663 /// is expanded to mul + add.
1664 virtual bool isFMAFasterThanMulAndAdd(EVT) const {
1668 /// isNarrowingProfitable - Return true if it's profitable to narrow
1669 /// operations of type VT1 to VT2. e.g. on x86, it's profitable to narrow
1670 /// from i32 to i8 but not from i32 to i16.
1671 virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
1675 //===--------------------------------------------------------------------===//
1676 // Div utility functions
1678 SDValue BuildExactSDIV(SDValue Op1, SDValue Op2, DebugLoc dl,
1679 SelectionDAG &DAG) const;
1680 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
1681 std::vector<SDNode*>* Created) const;
1682 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
1683 std::vector<SDNode*>* Created) const;
1686 //===--------------------------------------------------------------------===//
1687 // Runtime Library hooks
1690 /// setLibcallName - Rename the default libcall routine name for the specified
1692 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1693 LibcallRoutineNames[Call] = Name;
1696 /// getLibcallName - Get the libcall routine name for the specified libcall.
1698 const char *getLibcallName(RTLIB::Libcall Call) const {
1699 return LibcallRoutineNames[Call];
1702 /// setCmpLibcallCC - Override the default CondCode to be used to test the
1703 /// result of the comparison libcall against zero.
1704 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1705 CmpLibcallCCs[Call] = CC;
1708 /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1709 /// the comparison libcall against zero.
1710 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1711 return CmpLibcallCCs[Call];
1714 /// setLibcallCallingConv - Set the CallingConv that should be used for the
1715 /// specified libcall.
1716 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
1717 LibcallCallingConvs[Call] = CC;
1720 /// getLibcallCallingConv - Get the CallingConv that should be used for the
1721 /// specified libcall.
1722 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
1723 return LibcallCallingConvs[Call];
1727 const TargetMachine &TM;
1728 const TargetData *TD;
1729 const TargetLoweringObjectFile &TLOF;
1731 /// PointerTy - The type to use for pointers, usually i32 or i64.
1735 /// IsLittleEndian - True if this is a little endian target.
1737 bool IsLittleEndian;
1739 /// SelectIsExpensive - Tells the code generator not to expand operations
1740 /// into sequences that use the select operations if possible.
1741 bool SelectIsExpensive;
1743 /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1744 /// constants into a sequence of muls, adds, and shifts. This is a hack until
1745 /// a real cost model is in place. If we ever optimize for size, this will be
1746 /// set to true unconditionally.
1749 /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1750 /// srl/add/sra for a signed divide by power of two, and let the target handle
1752 bool Pow2DivIsCheap;
1754 /// JumpIsExpensive - Tells the code generator that it shouldn't generate
1755 /// extra flow control instructions and should attempt to combine flow
1756 /// control instructions via predication.
1757 bool JumpIsExpensive;
1759 /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1760 /// llvm.setjmp. Defaults to false.
1761 bool UseUnderscoreSetJmp;
1763 /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1764 /// llvm.longjmp. Defaults to false.
1765 bool UseUnderscoreLongJmp;
1767 /// BooleanContents - Information about the contents of the high-bits in
1768 /// boolean values held in a type wider than i1. See getBooleanContents.
1769 BooleanContent BooleanContents;
1770 /// BooleanVectorContents - Information about the contents of the high-bits
1771 /// in boolean vector values when the element type is wider than i1. See
1772 /// getBooleanContents.
1773 BooleanContent BooleanVectorContents;
1775 /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1776 /// total cycles or lowest register usage.
1777 Sched::Preference SchedPreferenceInfo;
1779 /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1780 unsigned JumpBufSize;
1782 /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1784 unsigned JumpBufAlignment;
1786 /// MinStackArgumentAlignment - The minimum alignment that any argument
1787 /// on the stack needs to have.
1789 unsigned MinStackArgumentAlignment;
1791 /// MinFunctionAlignment - The minimum function alignment (used when
1792 /// optimizing for size, and to prevent explicitly provided alignment
1793 /// from leading to incorrect code).
1795 unsigned MinFunctionAlignment;
1797 /// PrefFunctionAlignment - The preferred function alignment (used when
1798 /// alignment unspecified and optimizing for speed).
1800 unsigned PrefFunctionAlignment;
1802 /// PrefLoopAlignment - The preferred loop alignment.
1804 unsigned PrefLoopAlignment;
1806 /// ShouldFoldAtomicFences - Whether fencing MEMBARRIER instructions should
1807 /// be folded into the enclosed atomic intrinsic instruction by the
1809 bool ShouldFoldAtomicFences;
1811 /// InsertFencesForAtomic - Whether the DAG builder should automatically
1812 /// insert fences and reduce ordering for atomics. (This will be set for
1813 /// for most architectures with weak memory ordering.)
1814 bool InsertFencesForAtomic;
1816 /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1817 /// specifies the register that llvm.savestack/llvm.restorestack should save
1819 unsigned StackPointerRegisterToSaveRestore;
1821 /// ExceptionPointerRegister - If set to a physical register, this specifies
1822 /// the register that receives the exception address on entry to a landing
1824 unsigned ExceptionPointerRegister;
1826 /// ExceptionSelectorRegister - If set to a physical register, this specifies
1827 /// the register that receives the exception typeid on entry to a landing
1829 unsigned ExceptionSelectorRegister;
1831 /// RegClassForVT - This indicates the default register class to use for
1832 /// each ValueType the target supports natively.
1833 const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1834 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1835 EVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1837 /// RepRegClassForVT - This indicates the "representative" register class to
1838 /// use for each ValueType the target supports natively. This information is
1839 /// used by the scheduler to track register pressure. By default, the
1840 /// representative register class is the largest legal super-reg register
1841 /// class of the register class of the specified type. e.g. On x86, i8, i16,
1842 /// and i32's representative class would be GR32.
1843 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
1845 /// RepRegClassCostForVT - This indicates the "cost" of the "representative"
1846 /// register class for each ValueType. The cost is used by the scheduler to
1847 /// approximate register pressure.
1848 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
1850 /// TransformToType - For any value types we are promoting or expanding, this
1851 /// contains the value type that we are changing to. For Expanded types, this
1852 /// contains one step of the expand (e.g. i64 -> i32), even if there are
1853 /// multiple steps required (e.g. i64 -> i16). For types natively supported
1854 /// by the system, this holds the same type (e.g. i32 -> i32).
1855 EVT TransformToType[MVT::LAST_VALUETYPE];
1857 /// OpActions - For each operation and each value type, keep a LegalizeAction
1858 /// that indicates how instruction selection should deal with the operation.
1859 /// Most operations are Legal (aka, supported natively by the target), but
1860 /// operations that are not should be described. Note that operations on
1861 /// non-legal value types are not described here.
1862 uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
1864 /// LoadExtActions - For each load extension type and each value type,
1865 /// keep a LegalizeAction that indicates how instruction selection should deal
1866 /// with a load of a specific value type and extension type.
1867 uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE];
1869 /// TruncStoreActions - For each value type pair keep a LegalizeAction that
1870 /// indicates whether a truncating store of a specific value type and
1871 /// truncating type is legal.
1872 uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
1874 /// IndexedModeActions - For each indexed mode and each value type,
1875 /// keep a pair of LegalizeAction that indicates how instruction
1876 /// selection should deal with the load / store. The first dimension is the
1877 /// value_type for the reference. The second dimension represents the various
1878 /// modes for load store.
1879 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
1881 /// CondCodeActions - For each condition code (ISD::CondCode) keep a
1882 /// LegalizeAction that indicates how instruction selection should
1883 /// deal with the condition code.
1884 uint64_t CondCodeActions[ISD::SETCC_INVALID];
1886 ValueTypeActionImpl ValueTypeActions;
1888 typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind;
1891 getTypeConversion(LLVMContext &Context, EVT VT) const {
1892 // If this is a simple type, use the ComputeRegisterProp mechanism.
1893 if (VT.isSimple()) {
1894 assert((unsigned)VT.getSimpleVT().SimpleTy <
1895 array_lengthof(TransformToType));
1896 EVT NVT = TransformToType[VT.getSimpleVT().SimpleTy];
1897 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(VT.getSimpleVT());
1900 (!(NVT.isSimple() && LA != TypeLegal) ||
1901 ValueTypeActions.getTypeAction(NVT.getSimpleVT()) != TypePromoteInteger)
1902 && "Promote may not follow Expand or Promote");
1904 return LegalizeKind(LA, NVT);
1907 // Handle Extended Scalar Types.
1908 if (!VT.isVector()) {
1909 assert(VT.isInteger() && "Float types must be simple");
1910 unsigned BitSize = VT.getSizeInBits();
1911 // First promote to a power-of-two size, then expand if necessary.
1912 if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
1913 EVT NVT = VT.getRoundIntegerType(Context);
1914 assert(NVT != VT && "Unable to round integer VT");
1915 LegalizeKind NextStep = getTypeConversion(Context, NVT);
1916 // Avoid multi-step promotion.
1917 if (NextStep.first == TypePromoteInteger) return NextStep;
1918 // Return rounded integer type.
1919 return LegalizeKind(TypePromoteInteger, NVT);
1922 return LegalizeKind(TypeExpandInteger,
1923 EVT::getIntegerVT(Context, VT.getSizeInBits()/2));
1926 // Handle vector types.
1927 unsigned NumElts = VT.getVectorNumElements();
1928 EVT EltVT = VT.getVectorElementType();
1930 // Vectors with only one element are always scalarized.
1932 return LegalizeKind(TypeScalarizeVector, EltVT);
1934 // Try to widen vector elements until a legal type is found.
1935 if (EltVT.isInteger()) {
1936 // Vectors with a number of elements that is not a power of two are always
1937 // widened, for example <3 x float> -> <4 x float>.
1938 if (!VT.isPow2VectorType()) {
1939 NumElts = (unsigned)NextPowerOf2(NumElts);
1940 EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
1941 return LegalizeKind(TypeWidenVector, NVT);
1944 // Examine the element type.
1945 LegalizeKind LK = getTypeConversion(Context, EltVT);
1947 // If type is to be expanded, split the vector.
1948 // <4 x i140> -> <2 x i140>
1949 if (LK.first == TypeExpandInteger)
1950 return LegalizeKind(TypeSplitVector,
1951 EVT::getVectorVT(Context, EltVT, NumElts / 2));
1953 // Promote the integer element types until a legal vector type is found
1954 // or until the element integer type is too big. If a legal type was not
1955 // found, fallback to the usual mechanism of widening/splitting the
1958 // Increase the bitwidth of the element to the next pow-of-two
1959 // (which is greater than 8 bits).
1960 EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()
1961 ).getRoundIntegerType(Context);
1963 // Stop trying when getting a non-simple element type.
1964 // Note that vector elements may be greater than legal vector element
1965 // types. Example: X86 XMM registers hold 64bit element on 32bit systems.
1966 if (!EltVT.isSimple()) break;
1968 // Build a new vector type and check if it is legal.
1969 MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1970 // Found a legal promoted vector type.
1971 if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
1972 return LegalizeKind(TypePromoteInteger,
1973 EVT::getVectorVT(Context, EltVT, NumElts));
1977 // Try to widen the vector until a legal type is found.
1978 // If there is no wider legal type, split the vector.
1980 // Round up to the next power of 2.
1981 NumElts = (unsigned)NextPowerOf2(NumElts);
1983 // If there is no simple vector type with this many elements then there
1984 // cannot be a larger legal vector type. Note that this assumes that
1985 // there are no skipped intermediate vector types in the simple types.
1986 if (!EltVT.isSimple()) break;
1987 MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1988 if (LargerVector == MVT()) break;
1990 // If this type is legal then widen the vector.
1991 if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
1992 return LegalizeKind(TypeWidenVector, LargerVector);
1995 // Widen odd vectors to next power of two.
1996 if (!VT.isPow2VectorType()) {
1997 EVT NVT = VT.getPow2VectorType(Context);
1998 return LegalizeKind(TypeWidenVector, NVT);
2001 // Vectors with illegal element types are expanded.
2002 EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
2003 return LegalizeKind(TypeSplitVector, NVT);
2006 std::vector<std::pair<EVT, const TargetRegisterClass*> > AvailableRegClasses;
2008 /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
2009 /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
2010 /// which sets a bit in this array.
2012 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
2014 /// PromoteToType - For operations that must be promoted to a specific type,
2015 /// this holds the destination type. This map should be sparse, so don't hold
2018 /// Targets add entries to this map with AddPromotedToType(..), clients access
2019 /// this with getTypeToPromoteTo(..).
2020 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
2023 /// LibcallRoutineNames - Stores the name each libcall.
2025 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
2027 /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
2028 /// of each of the comparison libcall against zero.
2029 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
2031 /// LibcallCallingConvs - Stores the CallingConv that should be used for each
2033 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
2036 /// When lowering \@llvm.memset this field specifies the maximum number of
2037 /// store operations that may be substituted for the call to memset. Targets
2038 /// must set this value based on the cost threshold for that target. Targets
2039 /// should assume that the memset will be done using as many of the largest
2040 /// store operations first, followed by smaller ones, if necessary, per
2041 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
2042 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
2043 /// store. This only applies to setting a constant array of a constant size.
2044 /// @brief Specify maximum number of store instructions per memset call.
2045 unsigned maxStoresPerMemset;
2047 /// Maximum number of stores operations that may be substituted for the call
2048 /// to memset, used for functions with OptSize attribute.
2049 unsigned maxStoresPerMemsetOptSize;
2051 /// When lowering \@llvm.memcpy this field specifies the maximum number of
2052 /// store operations that may be substituted for a call to memcpy. Targets
2053 /// must set this value based on the cost threshold for that target. Targets
2054 /// should assume that the memcpy will be done using as many of the largest
2055 /// store operations first, followed by smaller ones, if necessary, per
2056 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
2057 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
2058 /// and one 1-byte store. This only applies to copying a constant array of
2060 /// @brief Specify maximum bytes of store instructions per memcpy call.
2061 unsigned maxStoresPerMemcpy;
2063 /// Maximum number of store operations that may be substituted for a call
2064 /// to memcpy, used for functions with OptSize attribute.
2065 unsigned maxStoresPerMemcpyOptSize;
2067 /// When lowering \@llvm.memmove this field specifies the maximum number of
2068 /// store instructions that may be substituted for a call to memmove. Targets
2069 /// must set this value based on the cost threshold for that target. Targets
2070 /// should assume that the memmove will be done using as many of the largest
2071 /// store operations first, followed by smaller ones, if necessary, per
2072 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
2073 /// with 8-bit alignment would result in nine 1-byte stores. This only
2074 /// applies to copying a constant array of constant size.
2075 /// @brief Specify maximum bytes of store instructions per memmove call.
2076 unsigned maxStoresPerMemmove;
2078 /// Maximum number of store instructions that may be substituted for a call
2079 /// to memmove, used for functions with OpSize attribute.
2080 unsigned maxStoresPerMemmoveOptSize;
2082 /// This field specifies whether the target can benefit from code placement
2084 bool benefitFromCodePlacementOpt;
2086 /// predictableSelectIsExpensive - Tells the code generator that select is
2087 /// more expensive than a branch if the branch is usually predicted right.
2088 bool predictableSelectIsExpensive;
2091 /// isLegalRC - Return true if the value types that can be represented by the
2092 /// specified register class are all legal.
2093 bool isLegalRC(const TargetRegisterClass *RC) const;
2096 /// GetReturnInfo - Given an LLVM IR type and return type attributes,
2097 /// compute the return value EVTs and flags, and optionally also
2098 /// the offsets, if the return value is being lowered to memory.
2099 void GetReturnInfo(Type* ReturnType, Attributes attr,
2100 SmallVectorImpl<ISD::OutputArg> &Outs,
2101 const TargetLowering &TLI);
2103 } // end llvm namespace