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/InlineAsm.h"
26 #include "llvm/CodeGen/SelectionDAGNodes.h"
27 #include "llvm/CodeGen/RuntimeLibcalls.h"
28 #include "llvm/ADT/APFloat.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/DebugLoc.h"
34 #include "llvm/Target/TargetMachine.h"
44 class MachineBasicBlock;
45 class MachineFunction;
46 class MachineFrameInfo;
48 class MachineModuleInfo;
55 class TargetRegisterClass;
56 class TargetSubtarget;
59 // FIXME: should this be here?
68 TLSModel::Model getTLSModel(const GlobalValue *GV, Reloc::Model reloc);
71 //===----------------------------------------------------------------------===//
72 /// TargetLowering - This class defines information used to lower LLVM code to
73 /// legal SelectionDAG operators that the target instruction selector can accept
76 /// This class also defines callbacks that targets must implement to lower
77 /// target-specific constructs to SelectionDAG operators.
79 class TargetLowering {
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 enum BooleanContent { // How the target represents true/false values.
91 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
92 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
93 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
96 enum SchedPreference {
97 SchedulingForLatency, // Scheduling for shortest total latency.
98 SchedulingForRegPressure // Scheduling for lowest register pressure.
101 explicit TargetLowering(TargetMachine &TM);
102 virtual ~TargetLowering();
104 TargetMachine &getTargetMachine() const { return TM; }
105 const TargetData *getTargetData() const { return TD; }
107 bool isBigEndian() const { return !IsLittleEndian; }
108 bool isLittleEndian() const { return IsLittleEndian; }
109 MVT getPointerTy() const { return PointerTy; }
110 MVT getShiftAmountTy() const { return ShiftAmountTy; }
112 /// usesGlobalOffsetTable - Return true if this target uses a GOT for PIC
114 bool usesGlobalOffsetTable() const { return UsesGlobalOffsetTable; }
116 /// isSelectExpensive - Return true if the select operation is expensive for
118 bool isSelectExpensive() const { return SelectIsExpensive; }
120 /// isIntDivCheap() - Return true if integer divide is usually cheaper than
121 /// a sequence of several shifts, adds, and multiplies for this target.
122 bool isIntDivCheap() const { return IntDivIsCheap; }
124 /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
126 bool isPow2DivCheap() const { return Pow2DivIsCheap; }
128 /// getSetCCResultType - Return the ValueType of the result of SETCC
129 /// operations. Also used to obtain the target's preferred type for
130 /// the condition operand of SELECT and BRCOND nodes. In the case of
131 /// BRCOND the argument passed is MVT::Other since there are no other
132 /// operands to get a type hint from.
133 virtual MVT getSetCCResultType(MVT VT) const;
135 /// getBooleanContents - For targets without i1 registers, this gives the
136 /// nature of the high-bits of boolean values held in types wider than i1.
137 /// "Boolean values" are special true/false values produced by nodes like
138 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
139 /// Not to be confused with general values promoted from i1.
140 BooleanContent getBooleanContents() const { return BooleanContents;}
142 /// getSchedulingPreference - Return target scheduling preference.
143 SchedPreference getSchedulingPreference() const {
144 return SchedPreferenceInfo;
147 /// getRegClassFor - Return the register class that should be used for the
148 /// specified value type. This may only be called on legal types.
149 TargetRegisterClass *getRegClassFor(MVT VT) const {
150 assert((unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
151 TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT()];
152 assert(RC && "This value type is not natively supported!");
156 /// isTypeLegal - Return true if the target has native support for the
157 /// specified value type. This means that it has a register that directly
158 /// holds it without promotions or expansions.
159 bool isTypeLegal(MVT VT) const {
160 assert(!VT.isSimple() ||
161 (unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
162 return VT.isSimple() && RegClassForVT[VT.getSimpleVT()] != 0;
165 class ValueTypeActionImpl {
166 /// ValueTypeActions - This is a bitvector that contains two bits for each
167 /// value type, where the two bits correspond to the LegalizeAction enum.
168 /// This can be queried with "getTypeAction(VT)".
169 /// dimension by (MVT::MAX_ALLOWED_VALUETYPE/32) * 2
170 uint32_t ValueTypeActions[(MVT::MAX_ALLOWED_VALUETYPE/32)*2];
172 ValueTypeActionImpl() {
173 ValueTypeActions[0] = ValueTypeActions[1] = 0;
174 ValueTypeActions[2] = ValueTypeActions[3] = 0;
176 ValueTypeActionImpl(const ValueTypeActionImpl &RHS) {
177 ValueTypeActions[0] = RHS.ValueTypeActions[0];
178 ValueTypeActions[1] = RHS.ValueTypeActions[1];
179 ValueTypeActions[2] = RHS.ValueTypeActions[2];
180 ValueTypeActions[3] = RHS.ValueTypeActions[3];
183 LegalizeAction getTypeAction(MVT VT) const {
184 if (VT.isExtended()) {
186 return VT.isPow2VectorType() ? Expand : Promote;
189 // First promote to a power-of-two size, then expand if necessary.
190 return VT == VT.getRoundIntegerType() ? Expand : Promote;
191 assert(0 && "Unsupported extended type!");
194 unsigned I = VT.getSimpleVT();
195 assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
196 return (LegalizeAction)((ValueTypeActions[I>>4] >> ((2*I) & 31)) & 3);
198 void setTypeAction(MVT VT, LegalizeAction Action) {
199 unsigned I = VT.getSimpleVT();
200 assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
201 ValueTypeActions[I>>4] |= Action << ((I*2) & 31);
205 const ValueTypeActionImpl &getValueTypeActions() const {
206 return ValueTypeActions;
209 /// getTypeAction - Return how we should legalize values of this type, either
210 /// it is already legal (return 'Legal') or we need to promote it to a larger
211 /// type (return 'Promote'), or we need to expand it into multiple registers
212 /// of smaller integer type (return 'Expand'). 'Custom' is not an option.
213 LegalizeAction getTypeAction(MVT VT) const {
214 return ValueTypeActions.getTypeAction(VT);
217 /// getTypeToTransformTo - For types supported by the target, this is an
218 /// identity function. For types that must be promoted to larger types, this
219 /// returns the larger type to promote to. For integer types that are larger
220 /// than the largest integer register, this contains one step in the expansion
221 /// to get to the smaller register. For illegal floating point types, this
222 /// returns the integer type to transform to.
223 MVT getTypeToTransformTo(MVT VT) const {
225 assert((unsigned)VT.getSimpleVT() < array_lengthof(TransformToType));
226 MVT NVT = TransformToType[VT.getSimpleVT()];
227 assert(getTypeAction(NVT) != Promote &&
228 "Promote may not follow Expand or Promote");
233 MVT NVT = VT.getPow2VectorType();
235 // Vector length is a power of 2 - split to half the size.
236 unsigned NumElts = VT.getVectorNumElements();
237 MVT EltVT = VT.getVectorElementType();
238 return (NumElts == 1) ? EltVT : MVT::getVectorVT(EltVT, NumElts / 2);
240 // Promote to a power of two size, avoiding multi-step promotion.
241 return getTypeAction(NVT) == Promote ? getTypeToTransformTo(NVT) : NVT;
242 } else if (VT.isInteger()) {
243 MVT NVT = VT.getRoundIntegerType();
245 // Size is a power of two - expand to half the size.
246 return MVT::getIntegerVT(VT.getSizeInBits() / 2);
248 // Promote to a power of two size, avoiding multi-step promotion.
249 return getTypeAction(NVT) == Promote ? getTypeToTransformTo(NVT) : NVT;
251 assert(0 && "Unsupported extended type!");
252 return MVT(MVT::Other); // Not reached
255 /// getTypeToExpandTo - For types supported by the target, this is an
256 /// identity function. For types that must be expanded (i.e. integer types
257 /// that are larger than the largest integer register or illegal floating
258 /// point types), this returns the largest legal type it will be expanded to.
259 MVT getTypeToExpandTo(MVT VT) const {
260 assert(!VT.isVector());
262 switch (getTypeAction(VT)) {
266 VT = getTypeToTransformTo(VT);
269 assert(false && "Type is not legal nor is it to be expanded!");
276 /// getVectorTypeBreakdown - Vector types are broken down into some number of
277 /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
278 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
279 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
281 /// This method returns the number of registers needed, and the VT for each
282 /// register. It also returns the VT and quantity of the intermediate values
283 /// before they are promoted/expanded.
285 unsigned getVectorTypeBreakdown(MVT VT,
287 unsigned &NumIntermediates,
288 MVT &RegisterVT) const;
290 /// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the
291 /// intrinsic will need to map to a MemIntrinsicNode (touches memory). If
292 /// this is the case, it returns true and store the intrinsic
293 /// information into the IntrinsicInfo that was passed to the function.
294 typedef struct IntrinsicInfo {
295 unsigned opc; // target opcode
296 MVT memVT; // memory VT
297 const Value* ptrVal; // value representing memory location
298 int offset; // offset off of ptrVal
299 unsigned align; // alignment
300 bool vol; // is volatile?
301 bool readMem; // reads memory?
302 bool writeMem; // writes memory?
305 virtual bool getTgtMemIntrinsic(IntrinsicInfo& Info,
306 CallInst &I, unsigned Intrinsic) {
310 /// getWidenVectorType: given a vector type, returns the type to widen to
311 /// (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
312 /// If there is no vector type that we want to widen to, returns MVT::Other
313 /// When and were to widen is target dependent based on the cost of
314 /// scalarizing vs using the wider vector type.
315 virtual MVT getWidenVectorType(MVT VT) const;
317 typedef std::vector<APFloat>::const_iterator legal_fpimm_iterator;
318 legal_fpimm_iterator legal_fpimm_begin() const {
319 return LegalFPImmediates.begin();
321 legal_fpimm_iterator legal_fpimm_end() const {
322 return LegalFPImmediates.end();
325 /// isShuffleMaskLegal - Targets can use this to indicate that they only
326 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
327 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
328 /// are assumed to be legal.
329 virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &Mask,
334 /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
335 /// used by Targets can use this to indicate if there is a suitable
336 /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
338 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
343 /// getOperationAction - Return how this operation should be treated: either
344 /// it is legal, needs to be promoted to a larger size, needs to be
345 /// expanded to some other code sequence, or the target has a custom expander
347 LegalizeAction getOperationAction(unsigned Op, MVT VT) const {
348 if (VT.isExtended()) return Expand;
349 assert(Op < array_lengthof(OpActions[0]) &&
350 (unsigned)VT.getSimpleVT() < sizeof(OpActions[0][0])*8 &&
351 "Table isn't big enough!");
352 unsigned I = (unsigned) VT.getSimpleVT();
355 return (LegalizeAction)((OpActions[I][Op] >> (J*2) ) & 3);
358 /// isOperationLegalOrCustom - Return true if the specified operation is
359 /// legal on this target or can be made legal with custom lowering. This
360 /// is used to help guide high-level lowering decisions.
361 bool isOperationLegalOrCustom(unsigned Op, MVT VT) const {
362 return (VT == MVT::Other || isTypeLegal(VT)) &&
363 (getOperationAction(Op, VT) == Legal ||
364 getOperationAction(Op, VT) == Custom);
367 /// isOperationLegal - Return true if the specified operation is legal on this
369 bool isOperationLegal(unsigned Op, MVT VT) const {
370 return (VT == MVT::Other || isTypeLegal(VT)) &&
371 getOperationAction(Op, VT) == Legal;
374 /// getLoadExtAction - Return how this load with extension should be treated:
375 /// either it is legal, needs to be promoted to a larger size, needs to be
376 /// expanded to some other code sequence, or the target has a custom expander
378 LegalizeAction getLoadExtAction(unsigned LType, MVT VT) const {
379 assert(LType < array_lengthof(LoadExtActions) &&
380 (unsigned)VT.getSimpleVT() < sizeof(LoadExtActions[0])*4 &&
381 "Table isn't big enough!");
382 return (LegalizeAction)((LoadExtActions[LType] >> (2*VT.getSimpleVT())) & 3);
385 /// isLoadExtLegal - Return true if the specified load with extension is legal
387 bool isLoadExtLegal(unsigned LType, MVT VT) const {
388 return VT.isSimple() &&
389 (getLoadExtAction(LType, VT) == Legal ||
390 getLoadExtAction(LType, VT) == Custom);
393 /// getTruncStoreAction - Return how this store with truncation should be
394 /// treated: either it is legal, needs to be promoted to a larger size, needs
395 /// to be expanded to some other code sequence, or the target has a custom
397 LegalizeAction getTruncStoreAction(MVT ValVT,
399 assert((unsigned)ValVT.getSimpleVT() < array_lengthof(TruncStoreActions) &&
400 (unsigned)MemVT.getSimpleVT() < sizeof(TruncStoreActions[0])*4 &&
401 "Table isn't big enough!");
402 return (LegalizeAction)((TruncStoreActions[ValVT.getSimpleVT()] >>
403 (2*MemVT.getSimpleVT())) & 3);
406 /// isTruncStoreLegal - Return true if the specified store with truncation is
407 /// legal on this target.
408 bool isTruncStoreLegal(MVT ValVT, MVT MemVT) const {
409 return isTypeLegal(ValVT) && MemVT.isSimple() &&
410 (getTruncStoreAction(ValVT, MemVT) == Legal ||
411 getTruncStoreAction(ValVT, MemVT) == Custom);
414 /// getIndexedLoadAction - Return how the indexed load should be treated:
415 /// either it is legal, needs to be promoted to a larger size, needs to be
416 /// expanded to some other code sequence, or the target has a custom expander
419 getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
420 assert( IdxMode < array_lengthof(IndexedModeActions[0][0]) &&
421 ((unsigned)VT.getSimpleVT()) < MVT::LAST_VALUETYPE &&
422 "Table isn't big enough!");
423 return (LegalizeAction)((IndexedModeActions[(unsigned)VT.getSimpleVT()][0][IdxMode]));
426 /// isIndexedLoadLegal - Return true if the specified indexed load is legal
428 bool isIndexedLoadLegal(unsigned IdxMode, MVT VT) const {
429 return VT.isSimple() &&
430 (getIndexedLoadAction(IdxMode, VT) == Legal ||
431 getIndexedLoadAction(IdxMode, VT) == Custom);
434 /// getIndexedStoreAction - Return how the indexed store should be treated:
435 /// either it is legal, needs to be promoted to a larger size, needs to be
436 /// expanded to some other code sequence, or the target has a custom expander
439 getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
440 assert(IdxMode < array_lengthof(IndexedModeActions[0][1]) &&
441 (unsigned)VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
442 "Table isn't big enough!");
443 return (LegalizeAction)((IndexedModeActions[(unsigned)VT.getSimpleVT()][1][IdxMode]));
446 /// isIndexedStoreLegal - Return true if the specified indexed load is legal
448 bool isIndexedStoreLegal(unsigned IdxMode, MVT VT) const {
449 return VT.isSimple() &&
450 (getIndexedStoreAction(IdxMode, VT) == Legal ||
451 getIndexedStoreAction(IdxMode, VT) == Custom);
454 /// getConvertAction - Return how the conversion should be treated:
455 /// either it is legal, needs to be promoted to a larger size, needs to be
456 /// expanded to some other code sequence, or the target has a custom expander
459 getConvertAction(MVT FromVT, MVT ToVT) const {
460 assert((unsigned)FromVT.getSimpleVT() < array_lengthof(ConvertActions) &&
461 (unsigned)ToVT.getSimpleVT() < sizeof(ConvertActions[0])*4 &&
462 "Table isn't big enough!");
463 return (LegalizeAction)((ConvertActions[FromVT.getSimpleVT()] >>
464 (2*ToVT.getSimpleVT())) & 3);
467 /// isConvertLegal - Return true if the specified conversion is legal
469 bool isConvertLegal(MVT FromVT, MVT ToVT) const {
470 return isTypeLegal(FromVT) && isTypeLegal(ToVT) &&
471 (getConvertAction(FromVT, ToVT) == Legal ||
472 getConvertAction(FromVT, ToVT) == Custom);
475 /// getCondCodeAction - Return how the condition code should be treated:
476 /// either it is legal, needs to be expanded to some other code sequence,
477 /// or the target has a custom expander for it.
479 getCondCodeAction(ISD::CondCode CC, MVT VT) const {
480 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
481 (unsigned)VT.getSimpleVT() < sizeof(CondCodeActions[0])*4 &&
482 "Table isn't big enough!");
483 LegalizeAction Action = (LegalizeAction)
484 ((CondCodeActions[CC] >> (2*VT.getSimpleVT())) & 3);
485 assert(Action != Promote && "Can't promote condition code!");
489 /// isCondCodeLegal - Return true if the specified condition code is legal
491 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
492 return getCondCodeAction(CC, VT) == Legal ||
493 getCondCodeAction(CC, VT) == Custom;
497 /// getTypeToPromoteTo - If the action for this operation is to promote, this
498 /// method returns the ValueType to promote to.
499 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
500 assert(getOperationAction(Op, VT) == Promote &&
501 "This operation isn't promoted!");
503 // See if this has an explicit type specified.
504 std::map<std::pair<unsigned, MVT::SimpleValueType>,
505 MVT::SimpleValueType>::const_iterator PTTI =
506 PromoteToType.find(std::make_pair(Op, VT.getSimpleVT()));
507 if (PTTI != PromoteToType.end()) return PTTI->second;
509 assert((VT.isInteger() || VT.isFloatingPoint()) &&
510 "Cannot autopromote this type, add it with AddPromotedToType.");
514 NVT = (MVT::SimpleValueType)(NVT.getSimpleVT()+1);
515 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
516 "Didn't find type to promote to!");
517 } while (!isTypeLegal(NVT) ||
518 getOperationAction(Op, NVT) == Promote);
522 /// getValueType - Return the MVT corresponding to this LLVM type.
523 /// This is fixed by the LLVM operations except for the pointer size. If
524 /// AllowUnknown is true, this will return MVT::Other for types with no MVT
525 /// counterpart (e.g. structs), otherwise it will assert.
526 MVT getValueType(const Type *Ty, bool AllowUnknown = false) const {
527 MVT VT = MVT::getMVT(Ty, AllowUnknown);
528 return VT == MVT::iPTR ? PointerTy : VT;
531 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
532 /// function arguments in the caller parameter area. This is the actual
533 /// alignment, not its logarithm.
534 virtual unsigned getByValTypeAlignment(const Type *Ty) const;
536 /// getRegisterType - Return the type of registers that this ValueType will
537 /// eventually require.
538 MVT getRegisterType(MVT VT) const {
540 assert((unsigned)VT.getSimpleVT() < array_lengthof(RegisterTypeForVT));
541 return RegisterTypeForVT[VT.getSimpleVT()];
545 unsigned NumIntermediates;
546 (void)getVectorTypeBreakdown(VT, VT1, NumIntermediates, RegisterVT);
549 if (VT.isInteger()) {
550 return getRegisterType(getTypeToTransformTo(VT));
552 assert(0 && "Unsupported extended type!");
553 return MVT(MVT::Other); // Not reached
556 /// getNumRegisters - Return the number of registers that this ValueType will
557 /// eventually require. This is one for any types promoted to live in larger
558 /// registers, but may be more than one for types (like i64) that are split
559 /// into pieces. For types like i140, which are first promoted then expanded,
560 /// it is the number of registers needed to hold all the bits of the original
561 /// type. For an i140 on a 32 bit machine this means 5 registers.
562 unsigned getNumRegisters(MVT VT) const {
564 assert((unsigned)VT.getSimpleVT() < array_lengthof(NumRegistersForVT));
565 return NumRegistersForVT[VT.getSimpleVT()];
569 unsigned NumIntermediates;
570 return getVectorTypeBreakdown(VT, VT1, NumIntermediates, VT2);
572 if (VT.isInteger()) {
573 unsigned BitWidth = VT.getSizeInBits();
574 unsigned RegWidth = getRegisterType(VT).getSizeInBits();
575 return (BitWidth + RegWidth - 1) / RegWidth;
577 assert(0 && "Unsupported extended type!");
578 return 0; // Not reached
581 /// ShouldShrinkFPConstant - If true, then instruction selection should
582 /// seek to shrink the FP constant of the specified type to a smaller type
583 /// in order to save space and / or reduce runtime.
584 virtual bool ShouldShrinkFPConstant(MVT VT) const { return true; }
586 /// hasTargetDAGCombine - If true, the target has custom DAG combine
587 /// transformations that it can perform for the specified node.
588 bool hasTargetDAGCombine(ISD::NodeType NT) const {
589 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
590 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
593 /// This function returns the maximum number of store operations permitted
594 /// to replace a call to llvm.memset. The value is set by the target at the
595 /// performance threshold for such a replacement.
596 /// @brief Get maximum # of store operations permitted for llvm.memset
597 unsigned getMaxStoresPerMemset() const { return maxStoresPerMemset; }
599 /// This function returns the maximum number of store operations permitted
600 /// to replace a call to llvm.memcpy. The value is set by the target at the
601 /// performance threshold for such a replacement.
602 /// @brief Get maximum # of store operations permitted for llvm.memcpy
603 unsigned getMaxStoresPerMemcpy() const { return maxStoresPerMemcpy; }
605 /// This function returns the maximum number of store operations permitted
606 /// to replace a call to llvm.memmove. The value is set by the target at the
607 /// performance threshold for such a replacement.
608 /// @brief Get maximum # of store operations permitted for llvm.memmove
609 unsigned getMaxStoresPerMemmove() const { return maxStoresPerMemmove; }
611 /// This function returns true if the target allows unaligned memory accesses.
612 /// This is used, for example, in situations where an array copy/move/set is
613 /// converted to a sequence of store operations. It's use helps to ensure that
614 /// such replacements don't generate code that causes an alignment error
615 /// (trap) on the target machine.
616 /// @brief Determine if the target supports unaligned memory accesses.
617 bool allowsUnalignedMemoryAccesses() const {
618 return allowUnalignedMemoryAccesses;
621 /// This function returns true if the target would benefit from code placement
623 /// @brief Determine if the target should perform code placement optimization.
624 bool shouldOptimizeCodePlacement() const {
625 return benefitFromCodePlacementOpt;
628 /// getOptimalMemOpType - Returns the target specific optimal type for load
629 /// and store operations as a result of memset, memcpy, and memmove lowering.
630 /// It returns MVT::iAny if SelectionDAG should be responsible for
632 virtual MVT getOptimalMemOpType(uint64_t Size, unsigned Align,
633 bool isSrcConst, bool isSrcStr,
634 SelectionDAG &DAG) const {
638 /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
639 /// to implement llvm.setjmp.
640 bool usesUnderscoreSetJmp() const {
641 return UseUnderscoreSetJmp;
644 /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
645 /// to implement llvm.longjmp.
646 bool usesUnderscoreLongJmp() const {
647 return UseUnderscoreLongJmp;
650 /// getStackPointerRegisterToSaveRestore - If a physical register, this
651 /// specifies the register that llvm.savestack/llvm.restorestack should save
653 unsigned getStackPointerRegisterToSaveRestore() const {
654 return StackPointerRegisterToSaveRestore;
657 /// getExceptionAddressRegister - If a physical register, this returns
658 /// the register that receives the exception address on entry to a landing
660 unsigned getExceptionAddressRegister() const {
661 return ExceptionPointerRegister;
664 /// getExceptionSelectorRegister - If a physical register, this returns
665 /// the register that receives the exception typeid on entry to a landing
667 unsigned getExceptionSelectorRegister() const {
668 return ExceptionSelectorRegister;
671 /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
672 /// set, the default is 200)
673 unsigned getJumpBufSize() const {
677 /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
678 /// (if never set, the default is 0)
679 unsigned getJumpBufAlignment() const {
680 return JumpBufAlignment;
683 /// getIfCvtBlockLimit - returns the target specific if-conversion block size
684 /// limit. Any block whose size is greater should not be predicated.
685 unsigned getIfCvtBlockSizeLimit() const {
686 return IfCvtBlockSizeLimit;
689 /// getIfCvtDupBlockLimit - returns the target specific size limit for a
690 /// block to be considered for duplication. Any block whose size is greater
691 /// should not be duplicated to facilitate its predication.
692 unsigned getIfCvtDupBlockSizeLimit() const {
693 return IfCvtDupBlockSizeLimit;
696 /// getPrefLoopAlignment - return the preferred loop alignment.
698 unsigned getPrefLoopAlignment() const {
699 return PrefLoopAlignment;
702 /// getPreIndexedAddressParts - returns true by value, base pointer and
703 /// offset pointer and addressing mode by reference if the node's address
704 /// can be legally represented as pre-indexed load / store address.
705 virtual bool getPreIndexedAddressParts(SDNode *N, SDValue &Base,
707 ISD::MemIndexedMode &AM,
708 SelectionDAG &DAG) const {
712 /// getPostIndexedAddressParts - returns true by value, base pointer and
713 /// offset pointer and addressing mode by reference if this node can be
714 /// combined with a load / store to form a post-indexed load / store.
715 virtual bool getPostIndexedAddressParts(SDNode *N, SDNode *Op,
716 SDValue &Base, SDValue &Offset,
717 ISD::MemIndexedMode &AM,
718 SelectionDAG &DAG) const {
722 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
724 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
725 SelectionDAG &DAG) const;
727 /// isOffsetFoldingLegal - Return true if folding a constant offset
728 /// with the given GlobalAddress is legal. It is frequently not legal in
729 /// PIC relocation models.
730 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
732 /// getFunctionAlignment - Return the Log2 alignment of this function.
733 virtual unsigned getFunctionAlignment(const Function *) const = 0;
735 //===--------------------------------------------------------------------===//
736 // TargetLowering Optimization Methods
739 /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
740 /// SDValues for returning information from TargetLowering to its clients
741 /// that want to combine
742 struct TargetLoweringOpt {
747 explicit TargetLoweringOpt(SelectionDAG &InDAG) : DAG(InDAG) {}
749 bool CombineTo(SDValue O, SDValue N) {
755 /// ShrinkDemandedConstant - Check to see if the specified operand of the
756 /// specified instruction is a constant integer. If so, check to see if
757 /// there are any bits set in the constant that are not demanded. If so,
758 /// shrink the constant and return true.
759 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
761 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
762 /// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening
763 /// cast, but it could be generalized for targets with other types of
764 /// implicit widening casts.
765 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
769 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
770 /// DemandedMask bits of the result of Op are ever used downstream. If we can
771 /// use this information to simplify Op, create a new simplified DAG node and
772 /// return true, returning the original and new nodes in Old and New.
773 /// Otherwise, analyze the expression and return a mask of KnownOne and
774 /// KnownZero bits for the expression (used to simplify the caller).
775 /// The KnownZero/One bits may only be accurate for those bits in the
777 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
778 APInt &KnownZero, APInt &KnownOne,
779 TargetLoweringOpt &TLO, unsigned Depth = 0) const;
781 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
782 /// Mask are known to be either zero or one and return them in the
783 /// KnownZero/KnownOne bitsets.
784 virtual void computeMaskedBitsForTargetNode(const SDValue Op,
788 const SelectionDAG &DAG,
789 unsigned Depth = 0) const;
791 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
792 /// targets that want to expose additional information about sign bits to the
794 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
795 unsigned Depth = 0) const;
797 struct DAGCombinerInfo {
798 void *DC; // The DAG Combiner object.
800 bool CalledByLegalizer;
804 DAGCombinerInfo(SelectionDAG &dag, bool bl, bool cl, void *dc)
805 : DC(dc), BeforeLegalize(bl), CalledByLegalizer(cl), DAG(dag) {}
807 bool isBeforeLegalize() const { return BeforeLegalize; }
808 bool isCalledByLegalizer() const { return CalledByLegalizer; }
810 void AddToWorklist(SDNode *N);
811 SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
813 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
814 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
816 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
819 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
820 /// and cc. If it is unable to simplify it, return a null SDValue.
821 SDValue SimplifySetCC(MVT VT, SDValue N0, SDValue N1,
822 ISD::CondCode Cond, bool foldBooleans,
823 DAGCombinerInfo &DCI, DebugLoc dl) const;
825 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
826 /// node is a GlobalAddress + offset.
828 isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) const;
830 /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
831 /// location that is 'Dist' units away from the location that the 'Base' load
833 bool isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base, unsigned Bytes,
834 int Dist, const MachineFrameInfo *MFI) const;
836 /// PerformDAGCombine - This method will be invoked for all target nodes and
837 /// for any target-independent nodes that the target has registered with
840 /// The semantics are as follows:
842 /// SDValue.Val == 0 - No change was made
843 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
844 /// otherwise - N should be replaced by the returned Operand.
846 /// In addition, methods provided by DAGCombinerInfo may be used to perform
847 /// more complex transformations.
849 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
851 //===--------------------------------------------------------------------===//
852 // TargetLowering Configuration Methods - These methods should be invoked by
853 // the derived class constructor to configure this object for the target.
857 /// setUsesGlobalOffsetTable - Specify that this target does or doesn't use a
858 /// GOT for PC-relative code.
859 void setUsesGlobalOffsetTable(bool V) { UsesGlobalOffsetTable = V; }
861 /// setShiftAmountType - Describe the type that should be used for shift
862 /// amounts. This type defaults to the pointer type.
863 void setShiftAmountType(MVT VT) { ShiftAmountTy = VT; }
865 /// setBooleanContents - Specify how the target extends the result of a
866 /// boolean value from i1 to a wider type. See getBooleanContents.
867 void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
869 /// setSchedulingPreference - Specify the target scheduling preference.
870 void setSchedulingPreference(SchedPreference Pref) {
871 SchedPreferenceInfo = Pref;
874 /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
875 /// use _setjmp to implement llvm.setjmp or the non _ version.
876 /// Defaults to false.
877 void setUseUnderscoreSetJmp(bool Val) {
878 UseUnderscoreSetJmp = Val;
881 /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
882 /// use _longjmp to implement llvm.longjmp or the non _ version.
883 /// Defaults to false.
884 void setUseUnderscoreLongJmp(bool Val) {
885 UseUnderscoreLongJmp = Val;
888 /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
889 /// specifies the register that llvm.savestack/llvm.restorestack should save
891 void setStackPointerRegisterToSaveRestore(unsigned R) {
892 StackPointerRegisterToSaveRestore = R;
895 /// setExceptionPointerRegister - If set to a physical register, this sets
896 /// the register that receives the exception address on entry to a landing
898 void setExceptionPointerRegister(unsigned R) {
899 ExceptionPointerRegister = R;
902 /// setExceptionSelectorRegister - If set to a physical register, this sets
903 /// the register that receives the exception typeid on entry to a landing
905 void setExceptionSelectorRegister(unsigned R) {
906 ExceptionSelectorRegister = R;
909 /// SelectIsExpensive - Tells the code generator not to expand operations
910 /// into sequences that use the select operations if possible.
911 void setSelectIsExpensive() { SelectIsExpensive = true; }
913 /// setIntDivIsCheap - Tells the code generator that integer divide is
914 /// expensive, and if possible, should be replaced by an alternate sequence
915 /// of instructions not containing an integer divide.
916 void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
918 /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
919 /// srl/add/sra for a signed divide by power of two, and let the target handle
921 void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
923 /// addRegisterClass - Add the specified register class as an available
924 /// regclass for the specified value type. This indicates the selector can
925 /// handle values of that class natively.
926 void addRegisterClass(MVT VT, TargetRegisterClass *RC) {
927 assert((unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
928 AvailableRegClasses.push_back(std::make_pair(VT, RC));
929 RegClassForVT[VT.getSimpleVT()] = RC;
932 /// computeRegisterProperties - Once all of the register classes are added,
933 /// this allows us to compute derived properties we expose.
934 void computeRegisterProperties();
936 /// setOperationAction - Indicate that the specified operation does not work
937 /// with the specified type and indicate what to do about it.
938 void setOperationAction(unsigned Op, MVT VT,
939 LegalizeAction Action) {
940 assert((unsigned)VT.getSimpleVT() < sizeof(OpActions[0][0])*8 &&
941 Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
942 unsigned I = (unsigned) VT.getSimpleVT();
945 OpActions[I][Op] &= ~(uint64_t(3UL) << (J*2));
946 OpActions[I][Op] |= (uint64_t)Action << (J*2);
949 /// setLoadExtAction - Indicate that the specified load with extension does
950 /// not work with the with specified type and indicate what to do about it.
951 void setLoadExtAction(unsigned ExtType, MVT VT,
952 LegalizeAction Action) {
953 assert((unsigned)VT.getSimpleVT() < sizeof(LoadExtActions[0])*4 &&
954 ExtType < array_lengthof(LoadExtActions) &&
955 "Table isn't big enough!");
956 LoadExtActions[ExtType] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
957 LoadExtActions[ExtType] |= (uint64_t)Action << VT.getSimpleVT()*2;
960 /// setTruncStoreAction - Indicate that the specified truncating store does
961 /// not work with the with specified type and indicate what to do about it.
962 void setTruncStoreAction(MVT ValVT, MVT MemVT,
963 LegalizeAction Action) {
964 assert((unsigned)ValVT.getSimpleVT() < array_lengthof(TruncStoreActions) &&
965 (unsigned)MemVT.getSimpleVT() < sizeof(TruncStoreActions[0])*4 &&
966 "Table isn't big enough!");
967 TruncStoreActions[ValVT.getSimpleVT()] &= ~(uint64_t(3UL) <<
968 MemVT.getSimpleVT()*2);
969 TruncStoreActions[ValVT.getSimpleVT()] |= (uint64_t)Action <<
970 MemVT.getSimpleVT()*2;
973 /// setIndexedLoadAction - Indicate that the specified indexed load does or
974 /// does not work with the with specified type and indicate what to do abort
975 /// it. NOTE: All indexed mode loads are initialized to Expand in
976 /// TargetLowering.cpp
977 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
978 LegalizeAction Action) {
979 assert((unsigned)VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
980 IdxMode < array_lengthof(IndexedModeActions[0][0]) &&
981 "Table isn't big enough!");
982 IndexedModeActions[(unsigned)VT.getSimpleVT()][0][IdxMode] = (uint8_t)Action;
985 /// setIndexedStoreAction - Indicate that the specified indexed store does or
986 /// does not work with the with specified type and indicate what to do about
987 /// it. NOTE: All indexed mode stores are initialized to Expand in
988 /// TargetLowering.cpp
989 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
990 LegalizeAction Action) {
991 assert((unsigned)VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
992 IdxMode < array_lengthof(IndexedModeActions[0][1] ) &&
993 "Table isn't big enough!");
994 IndexedModeActions[(unsigned)VT.getSimpleVT()][1][IdxMode] = (uint8_t)Action;
997 /// setConvertAction - Indicate that the specified conversion does or does
998 /// not work with the with specified type and indicate what to do about it.
999 void setConvertAction(MVT FromVT, MVT ToVT,
1000 LegalizeAction Action) {
1001 assert((unsigned)FromVT.getSimpleVT() < array_lengthof(ConvertActions) &&
1002 (unsigned)ToVT.getSimpleVT() < sizeof(ConvertActions[0])*4 &&
1003 "Table isn't big enough!");
1004 ConvertActions[FromVT.getSimpleVT()] &= ~(uint64_t(3UL) <<
1005 ToVT.getSimpleVT()*2);
1006 ConvertActions[FromVT.getSimpleVT()] |= (uint64_t)Action <<
1007 ToVT.getSimpleVT()*2;
1010 /// setCondCodeAction - Indicate that the specified condition code is or isn't
1011 /// supported on the target and indicate what to do about it.
1012 void setCondCodeAction(ISD::CondCode CC, MVT VT, LegalizeAction Action) {
1013 assert((unsigned)VT.getSimpleVT() < sizeof(CondCodeActions[0])*4 &&
1014 (unsigned)CC < array_lengthof(CondCodeActions) &&
1015 "Table isn't big enough!");
1016 CondCodeActions[(unsigned)CC] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
1017 CondCodeActions[(unsigned)CC] |= (uint64_t)Action << VT.getSimpleVT()*2;
1020 /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
1021 /// promotion code defaults to trying a larger integer/fp until it can find
1022 /// one that works. If that default is insufficient, this method can be used
1023 /// by the target to override the default.
1024 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1025 PromoteToType[std::make_pair(Opc, OrigVT.getSimpleVT())] =
1026 DestVT.getSimpleVT();
1029 /// addLegalFPImmediate - Indicate that this target can instruction select
1030 /// the specified FP immediate natively.
1031 void addLegalFPImmediate(const APFloat& Imm) {
1032 LegalFPImmediates.push_back(Imm);
1035 /// setTargetDAGCombine - Targets should invoke this method for each target
1036 /// independent node that they want to provide a custom DAG combiner for by
1037 /// implementing the PerformDAGCombine virtual method.
1038 void setTargetDAGCombine(ISD::NodeType NT) {
1039 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1040 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1043 /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
1044 /// bytes); default is 200
1045 void setJumpBufSize(unsigned Size) {
1049 /// setJumpBufAlignment - Set the target's required jmp_buf buffer
1050 /// alignment (in bytes); default is 0
1051 void setJumpBufAlignment(unsigned Align) {
1052 JumpBufAlignment = Align;
1055 /// setIfCvtBlockSizeLimit - Set the target's if-conversion block size
1056 /// limit (in number of instructions); default is 2.
1057 void setIfCvtBlockSizeLimit(unsigned Limit) {
1058 IfCvtBlockSizeLimit = Limit;
1061 /// setIfCvtDupBlockSizeLimit - Set the target's block size limit (in number
1062 /// of instructions) to be considered for code duplication during
1063 /// if-conversion; default is 2.
1064 void setIfCvtDupBlockSizeLimit(unsigned Limit) {
1065 IfCvtDupBlockSizeLimit = Limit;
1068 /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
1069 /// alignment is zero, it means the target does not care about loop alignment.
1070 void setPrefLoopAlignment(unsigned Align) {
1071 PrefLoopAlignment = Align;
1076 virtual const TargetSubtarget *getSubtarget() {
1077 assert(0 && "Not Implemented");
1078 return NULL; // this is here to silence compiler errors
1080 //===--------------------------------------------------------------------===//
1081 // Lowering methods - These methods must be implemented by targets so that
1082 // the SelectionDAGLowering code knows how to lower these.
1085 /// LowerArguments - This hook must be implemented to indicate how we should
1086 /// lower the arguments for the specified function, into the specified DAG.
1088 LowerArguments(Function &F, SelectionDAG &DAG,
1089 SmallVectorImpl<SDValue>& ArgValues, DebugLoc dl);
1091 /// LowerCallTo - This hook lowers an abstract call to a function into an
1092 /// actual call. This returns a pair of operands. The first element is the
1093 /// return value for the function (if RetTy is not VoidTy). The second
1094 /// element is the outgoing token chain.
1095 struct ArgListEntry {
1106 ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1107 isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
1109 typedef std::vector<ArgListEntry> ArgListTy;
1110 virtual std::pair<SDValue, SDValue>
1111 LowerCallTo(SDValue Chain, const Type *RetTy, bool RetSExt, bool RetZExt,
1112 bool isVarArg, bool isInreg, unsigned NumFixedArgs,
1113 unsigned CallingConv, bool isTailCall, SDValue Callee,
1114 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl);
1116 /// EmitTargetCodeForMemcpy - Emit target-specific code that performs a
1117 /// memcpy. This can be used by targets to provide code sequences for cases
1118 /// that don't fit the target's parameters for simple loads/stores and can be
1119 /// more efficient than using a library call. This function can return a null
1120 /// SDValue if the target declines to use custom code and a different
1121 /// lowering strategy should be used.
1123 /// If AlwaysInline is true, the size is constant and the target should not
1124 /// emit any calls and is strongly encouraged to attempt to emit inline code
1125 /// even if it is beyond the usual threshold because this intrinsic is being
1126 /// expanded in a place where calls are not feasible (e.g. within the prologue
1127 /// for another call). If the target chooses to decline an AlwaysInline
1128 /// request here, legalize will resort to using simple loads and stores.
1130 EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
1132 SDValue Op1, SDValue Op2,
1133 SDValue Op3, unsigned Align,
1135 const Value *DstSV, uint64_t DstOff,
1136 const Value *SrcSV, uint64_t SrcOff) {
1140 /// EmitTargetCodeForMemmove - Emit target-specific code that performs a
1141 /// memmove. This can be used by targets to provide code sequences for cases
1142 /// that don't fit the target's parameters for simple loads/stores and can be
1143 /// more efficient than using a library call. This function can return a null
1144 /// SDValue if the target declines to use custom code and a different
1145 /// lowering strategy should be used.
1147 EmitTargetCodeForMemmove(SelectionDAG &DAG, DebugLoc dl,
1149 SDValue Op1, SDValue Op2,
1150 SDValue Op3, unsigned Align,
1151 const Value *DstSV, uint64_t DstOff,
1152 const Value *SrcSV, uint64_t SrcOff) {
1156 /// EmitTargetCodeForMemset - Emit target-specific code that performs a
1157 /// memset. This can be used by targets to provide code sequences for cases
1158 /// that don't fit the target's parameters for simple stores and can be more
1159 /// efficient than using a library call. This function can return a null
1160 /// SDValue if the target declines to use custom code and a different
1161 /// lowering strategy should be used.
1163 EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
1165 SDValue Op1, SDValue Op2,
1166 SDValue Op3, unsigned Align,
1167 const Value *DstSV, uint64_t DstOff) {
1171 /// LowerOperationWrapper - This callback is invoked by the type legalizer
1172 /// to legalize nodes with an illegal operand type but legal result types.
1173 /// It replaces the LowerOperation callback in the type Legalizer.
1174 /// The reason we can not do away with LowerOperation entirely is that
1175 /// LegalizeDAG isn't yet ready to use this callback.
1176 /// TODO: Consider merging with ReplaceNodeResults.
1178 /// The target places new result values for the node in Results (their number
1179 /// and types must exactly match those of the original return values of
1180 /// the node), or leaves Results empty, which indicates that the node is not
1181 /// to be custom lowered after all.
1182 /// The default implementation calls LowerOperation.
1183 virtual void LowerOperationWrapper(SDNode *N,
1184 SmallVectorImpl<SDValue> &Results,
1187 /// LowerOperation - This callback is invoked for operations that are
1188 /// unsupported by the target, which are registered to use 'custom' lowering,
1189 /// and whose defined values are all legal.
1190 /// If the target has no operations that require custom lowering, it need not
1191 /// implement this. The default implementation of this aborts.
1192 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG);
1194 /// ReplaceNodeResults - This callback is invoked when a node result type is
1195 /// illegal for the target, and the operation was registered to use 'custom'
1196 /// lowering for that result type. The target places new result values for
1197 /// the node in Results (their number and types must exactly match those of
1198 /// the original return values of the node), or leaves Results empty, which
1199 /// indicates that the node is not to be custom lowered after all.
1201 /// If the target has no operations that require custom lowering, it need not
1202 /// implement this. The default implementation aborts.
1203 virtual void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
1204 SelectionDAG &DAG) {
1205 assert(0 && "ReplaceNodeResults not implemented for this target!");
1208 /// IsEligibleForTailCallOptimization - Check whether the call is eligible for
1209 /// tail call optimization. Targets which want to do tail call optimization
1210 /// should override this function.
1211 virtual bool IsEligibleForTailCallOptimization(CallSDNode *Call,
1213 SelectionDAG &DAG) const {
1217 /// CheckTailCallReturnConstraints - Check whether CALL node immediatly
1218 /// preceeds the RET node and whether the return uses the result of the node
1219 /// or is a void return. This function can be used by the target to determine
1220 /// eligiblity of tail call optimization.
1221 static bool CheckTailCallReturnConstraints(CallSDNode *TheCall, SDValue Ret);
1223 /// GetPossiblePreceedingTailCall - Get preceeding TailCallNodeOpCode node if
1224 /// it exists. Skip a possible ISD::TokenFactor.
1225 static SDValue GetPossiblePreceedingTailCall(SDValue Chain,
1226 unsigned TailCallNodeOpCode) {
1227 if (Chain.getOpcode() == TailCallNodeOpCode) {
1229 } else if (Chain.getOpcode() == ISD::TokenFactor) {
1230 if (Chain.getNumOperands() &&
1231 Chain.getOperand(0).getOpcode() == TailCallNodeOpCode)
1232 return Chain.getOperand(0);
1237 /// getTargetNodeName() - This method returns the name of a target specific
1239 virtual const char *getTargetNodeName(unsigned Opcode) const;
1241 /// createFastISel - This method returns a target specific FastISel object,
1242 /// or null if the target does not support "fast" ISel.
1244 createFastISel(MachineFunction &,
1245 MachineModuleInfo *, DwarfWriter *,
1246 DenseMap<const Value *, unsigned> &,
1247 DenseMap<const BasicBlock *, MachineBasicBlock *> &,
1248 DenseMap<const AllocaInst *, int> &
1250 , SmallSet<Instruction*, 8> &CatchInfoLost
1256 //===--------------------------------------------------------------------===//
1257 // Inline Asm Support hooks
1260 /// ExpandInlineAsm - This hook allows the target to expand an inline asm
1261 /// call to be explicit llvm code if it wants to. This is useful for
1262 /// turning simple inline asms into LLVM intrinsics, which gives the
1263 /// compiler more information about the behavior of the code.
1264 virtual bool ExpandInlineAsm(CallInst *CI) const {
1268 enum ConstraintType {
1269 C_Register, // Constraint represents specific register(s).
1270 C_RegisterClass, // Constraint represents any of register(s) in class.
1271 C_Memory, // Memory constraint.
1272 C_Other, // Something else.
1273 C_Unknown // Unsupported constraint.
1276 /// AsmOperandInfo - This contains information for each constraint that we are
1278 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
1279 /// ConstraintCode - This contains the actual string for the code, like "m".
1280 /// TargetLowering picks the 'best' code from ConstraintInfo::Codes that
1281 /// most closely matches the operand.
1282 std::string ConstraintCode;
1284 /// ConstraintType - Information about the constraint code, e.g. Register,
1285 /// RegisterClass, Memory, Other, Unknown.
1286 TargetLowering::ConstraintType ConstraintType;
1288 /// CallOperandval - If this is the result output operand or a
1289 /// clobber, this is null, otherwise it is the incoming operand to the
1290 /// CallInst. This gets modified as the asm is processed.
1291 Value *CallOperandVal;
1293 /// ConstraintVT - The ValueType for the operand value.
1296 /// isMatchingInputConstraint - Return true of this is an input operand that
1297 /// is a matching constraint like "4".
1298 bool isMatchingInputConstraint() const;
1300 /// getMatchedOperand - If this is an input matching constraint, this method
1301 /// returns the output operand it matches.
1302 unsigned getMatchedOperand() const;
1304 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
1305 : InlineAsm::ConstraintInfo(info),
1306 ConstraintType(TargetLowering::C_Unknown),
1307 CallOperandVal(0), ConstraintVT(MVT::Other) {
1311 /// ComputeConstraintToUse - Determines the constraint code and constraint
1312 /// type to use for the specific AsmOperandInfo, setting
1313 /// OpInfo.ConstraintCode and OpInfo.ConstraintType. If the actual operand
1314 /// being passed in is available, it can be passed in as Op, otherwise an
1315 /// empty SDValue can be passed. If hasMemory is true it means one of the asm
1316 /// constraint of the inline asm instruction being processed is 'm'.
1317 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
1320 SelectionDAG *DAG = 0) const;
1322 /// getConstraintType - Given a constraint, return the type of constraint it
1323 /// is for this target.
1324 virtual ConstraintType getConstraintType(const std::string &Constraint) const;
1326 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1327 /// return a list of registers that can be used to satisfy the constraint.
1328 /// This should only be used for C_RegisterClass constraints.
1329 virtual std::vector<unsigned>
1330 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1333 /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
1334 /// {edx}), return the register number and the register class for the
1337 /// Given a register class constraint, like 'r', if this corresponds directly
1338 /// to an LLVM register class, return a register of 0 and the register class
1341 /// This should only be used for C_Register constraints. On error,
1342 /// this returns a register number of 0 and a null register class pointer..
1343 virtual std::pair<unsigned, const TargetRegisterClass*>
1344 getRegForInlineAsmConstraint(const std::string &Constraint,
1347 /// LowerXConstraint - try to replace an X constraint, which matches anything,
1348 /// with another that has more specific requirements based on the type of the
1349 /// corresponding operand. This returns null if there is no replacement to
1351 virtual const char *LowerXConstraint(MVT ConstraintVT) const;
1353 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1354 /// vector. If it is invalid, don't add anything to Ops. If hasMemory is true
1355 /// it means one of the asm constraint of the inline asm instruction being
1356 /// processed is 'm'.
1357 virtual void LowerAsmOperandForConstraint(SDValue Op, char ConstraintLetter,
1359 std::vector<SDValue> &Ops,
1360 SelectionDAG &DAG) const;
1362 //===--------------------------------------------------------------------===//
1366 // EmitInstrWithCustomInserter - This method should be implemented by targets
1367 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1368 // instructions are special in various ways, which require special support to
1369 // insert. The specified MachineInstr is created but not inserted into any
1370 // basic blocks, and the scheduler passes ownership of it to this method.
1371 virtual MachineBasicBlock *EmitInstrWithCustomInserter(MachineInstr *MI,
1372 MachineBasicBlock *MBB) const;
1374 //===--------------------------------------------------------------------===//
1375 // Addressing mode description hooks (used by LSR etc).
1378 /// AddrMode - This represents an addressing mode of:
1379 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1380 /// If BaseGV is null, there is no BaseGV.
1381 /// If BaseOffs is zero, there is no base offset.
1382 /// If HasBaseReg is false, there is no base register.
1383 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1387 GlobalValue *BaseGV;
1391 AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1394 /// isLegalAddressingMode - Return true if the addressing mode represented by
1395 /// AM is legal for this target, for a load/store of the specified type.
1396 /// The type may be VoidTy, in which case only return true if the addressing
1397 /// mode is legal for a load/store of any legal type.
1398 /// TODO: Handle pre/postinc as well.
1399 virtual bool isLegalAddressingMode(const AddrMode &AM, const Type *Ty) const;
1401 /// isTruncateFree - Return true if it's free to truncate a value of
1402 /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1403 /// register EAX to i16 by referencing its sub-register AX.
1404 virtual bool isTruncateFree(const Type *Ty1, const Type *Ty2) const {
1408 virtual bool isTruncateFree(MVT VT1, MVT VT2) const {
1412 /// isZExtFree - Return true if any actual instruction that defines a
1413 /// value of type Ty1 implicit zero-extends the value to Ty2 in the result
1414 /// register. This does not necessarily include registers defined in
1415 /// unknown ways, such as incoming arguments, or copies from unknown
1416 /// virtual registers. Also, if isTruncateFree(Ty2, Ty1) is true, this
1417 /// does not necessarily apply to truncate instructions. e.g. on x86-64,
1418 /// all instructions that define 32-bit values implicit zero-extend the
1419 /// result out to 64 bits.
1420 virtual bool isZExtFree(const Type *Ty1, const Type *Ty2) const {
1424 virtual bool isZExtFree(MVT VT1, MVT VT2) const {
1428 /// isNarrowingProfitable - Return true if it's profitable to narrow
1429 /// operations of type VT1 to VT2. e.g. on x86, it's profitable to narrow
1430 /// from i32 to i8 but not from i32 to i16.
1431 virtual bool isNarrowingProfitable(MVT VT1, MVT VT2) const {
1435 //===--------------------------------------------------------------------===//
1436 // Div utility functions
1438 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG,
1439 std::vector<SDNode*>* Created) const;
1440 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG,
1441 std::vector<SDNode*>* Created) const;
1444 //===--------------------------------------------------------------------===//
1445 // Runtime Library hooks
1448 /// setLibcallName - Rename the default libcall routine name for the specified
1450 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1451 LibcallRoutineNames[Call] = Name;
1454 /// getLibcallName - Get the libcall routine name for the specified libcall.
1456 const char *getLibcallName(RTLIB::Libcall Call) const {
1457 return LibcallRoutineNames[Call];
1460 /// setCmpLibcallCC - Override the default CondCode to be used to test the
1461 /// result of the comparison libcall against zero.
1462 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1463 CmpLibcallCCs[Call] = CC;
1466 /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1467 /// the comparison libcall against zero.
1468 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1469 return CmpLibcallCCs[Call];
1474 const TargetData *TD;
1476 /// PointerTy - The type to use for pointers, usually i32 or i64.
1480 /// IsLittleEndian - True if this is a little endian target.
1482 bool IsLittleEndian;
1484 /// UsesGlobalOffsetTable - True if this target uses a GOT for PIC codegen.
1486 bool UsesGlobalOffsetTable;
1488 /// SelectIsExpensive - Tells the code generator not to expand operations
1489 /// into sequences that use the select operations if possible.
1490 bool SelectIsExpensive;
1492 /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1493 /// constants into a sequence of muls, adds, and shifts. This is a hack until
1494 /// a real cost model is in place. If we ever optimize for size, this will be
1495 /// set to true unconditionally.
1498 /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1499 /// srl/add/sra for a signed divide by power of two, and let the target handle
1501 bool Pow2DivIsCheap;
1503 /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1504 /// llvm.setjmp. Defaults to false.
1505 bool UseUnderscoreSetJmp;
1507 /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1508 /// llvm.longjmp. Defaults to false.
1509 bool UseUnderscoreLongJmp;
1511 /// ShiftAmountTy - The type to use for shift amounts, usually i8 or whatever
1515 /// BooleanContents - Information about the contents of the high-bits in
1516 /// boolean values held in a type wider than i1. See getBooleanContents.
1517 BooleanContent BooleanContents;
1519 /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1520 /// total cycles or lowest register usage.
1521 SchedPreference SchedPreferenceInfo;
1523 /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1524 unsigned JumpBufSize;
1526 /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1528 unsigned JumpBufAlignment;
1530 /// IfCvtBlockSizeLimit - The maximum allowed size for a block to be
1532 unsigned IfCvtBlockSizeLimit;
1534 /// IfCvtDupBlockSizeLimit - The maximum allowed size for a block to be
1535 /// duplicated during if-conversion.
1536 unsigned IfCvtDupBlockSizeLimit;
1538 /// PrefLoopAlignment - The perferred loop alignment.
1540 unsigned PrefLoopAlignment;
1542 /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1543 /// specifies the register that llvm.savestack/llvm.restorestack should save
1545 unsigned StackPointerRegisterToSaveRestore;
1547 /// ExceptionPointerRegister - If set to a physical register, this specifies
1548 /// the register that receives the exception address on entry to a landing
1550 unsigned ExceptionPointerRegister;
1552 /// ExceptionSelectorRegister - If set to a physical register, this specifies
1553 /// the register that receives the exception typeid on entry to a landing
1555 unsigned ExceptionSelectorRegister;
1557 /// RegClassForVT - This indicates the default register class to use for
1558 /// each ValueType the target supports natively.
1559 TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1560 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1561 MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1563 /// TransformToType - For any value types we are promoting or expanding, this
1564 /// contains the value type that we are changing to. For Expanded types, this
1565 /// contains one step of the expand (e.g. i64 -> i32), even if there are
1566 /// multiple steps required (e.g. i64 -> i16). For types natively supported
1567 /// by the system, this holds the same type (e.g. i32 -> i32).
1568 MVT TransformToType[MVT::LAST_VALUETYPE];
1570 /// OpActions - For each operation and each value type, keep a LegalizeAction
1571 /// that indicates how instruction selection should deal with the operation.
1572 /// Most operations are Legal (aka, supported natively by the target), but
1573 /// operations that are not should be described. Note that operations on
1574 /// non-legal value types are not described here.
1575 /// This array is accessed using VT.getSimpleVT(), so it is subject to
1576 /// the MVT::MAX_ALLOWED_VALUETYPE * 2 bits.
1577 uint64_t OpActions[MVT::MAX_ALLOWED_VALUETYPE/(sizeof(uint64_t)*4)][ISD::BUILTIN_OP_END];
1579 /// LoadExtActions - For each load of load extension type and each value type,
1580 /// keep a LegalizeAction that indicates how instruction selection should deal
1582 uint64_t LoadExtActions[ISD::LAST_LOADEXT_TYPE];
1584 /// TruncStoreActions - For each truncating store, keep a LegalizeAction that
1585 /// indicates how instruction selection should deal with the store.
1586 uint64_t TruncStoreActions[MVT::LAST_VALUETYPE];
1588 /// IndexedModeActions - For each indexed mode and each value type,
1589 /// keep a pair of LegalizeAction that indicates how instruction
1590 /// selection should deal with the load / store. The first
1591 /// dimension is now the value_type for the reference. The second
1592 /// dimension is the load [0] vs. store[1]. The third dimension
1593 /// represents the various modes for load store.
1594 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][2][ISD::LAST_INDEXED_MODE];
1596 /// ConvertActions - For each conversion from source type to destination type,
1597 /// keep a LegalizeAction that indicates how instruction selection should
1598 /// deal with the conversion.
1599 /// Currently, this is used only for floating->floating conversions
1600 /// (FP_EXTEND and FP_ROUND).
1601 uint64_t ConvertActions[MVT::LAST_VALUETYPE];
1603 /// CondCodeActions - For each condition code (ISD::CondCode) keep a
1604 /// LegalizeAction that indicates how instruction selection should
1605 /// deal with the condition code.
1606 uint64_t CondCodeActions[ISD::SETCC_INVALID];
1608 ValueTypeActionImpl ValueTypeActions;
1610 std::vector<APFloat> LegalFPImmediates;
1612 std::vector<std::pair<MVT, TargetRegisterClass*> > AvailableRegClasses;
1614 /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
1615 /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
1616 /// which sets a bit in this array.
1618 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
1620 /// PromoteToType - For operations that must be promoted to a specific type,
1621 /// this holds the destination type. This map should be sparse, so don't hold
1624 /// Targets add entries to this map with AddPromotedToType(..), clients access
1625 /// this with getTypeToPromoteTo(..).
1626 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1629 /// LibcallRoutineNames - Stores the name each libcall.
1631 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1633 /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
1634 /// of each of the comparison libcall against zero.
1635 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1638 /// When lowering \@llvm.memset this field specifies the maximum number of
1639 /// store operations that may be substituted for the call to memset. Targets
1640 /// must set this value based on the cost threshold for that target. Targets
1641 /// should assume that the memset will be done using as many of the largest
1642 /// store operations first, followed by smaller ones, if necessary, per
1643 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1644 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1645 /// store. This only applies to setting a constant array of a constant size.
1646 /// @brief Specify maximum number of store instructions per memset call.
1647 unsigned maxStoresPerMemset;
1649 /// When lowering \@llvm.memcpy this field specifies the maximum number of
1650 /// store operations that may be substituted for a call to memcpy. Targets
1651 /// must set this value based on the cost threshold for that target. Targets
1652 /// should assume that the memcpy will be done using as many of the largest
1653 /// store operations first, followed by smaller ones, if necessary, per
1654 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1655 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1656 /// and one 1-byte store. This only applies to copying a constant array of
1658 /// @brief Specify maximum bytes of store instructions per memcpy call.
1659 unsigned maxStoresPerMemcpy;
1661 /// When lowering \@llvm.memmove this field specifies the maximum number of
1662 /// store instructions that may be substituted for a call to memmove. Targets
1663 /// must set this value based on the cost threshold for that target. Targets
1664 /// should assume that the memmove will be done using as many of the largest
1665 /// store operations first, followed by smaller ones, if necessary, per
1666 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1667 /// with 8-bit alignment would result in nine 1-byte stores. This only
1668 /// applies to copying a constant array of constant size.
1669 /// @brief Specify maximum bytes of store instructions per memmove call.
1670 unsigned maxStoresPerMemmove;
1672 /// This field specifies whether the target machine permits unaligned memory
1673 /// accesses. This is used, for example, to determine the size of store
1674 /// operations when copying small arrays and other similar tasks.
1675 /// @brief Indicate whether the target permits unaligned memory accesses.
1676 bool allowUnalignedMemoryAccesses;
1678 /// This field specifies whether the target can benefit from code placement
1680 bool benefitFromCodePlacementOpt;
1682 } // end llvm namespace