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/STLExtras.h"
32 #include "llvm/CodeGen/DebugLoc.h"
42 class MachineBasicBlock;
43 class MachineFunction;
44 class MachineFrameInfo;
46 class MachineModuleInfo;
53 class TargetRegisterClass;
54 class TargetSubtarget;
57 //===----------------------------------------------------------------------===//
58 /// TargetLowering - This class defines information used to lower LLVM code to
59 /// legal SelectionDAG operators that the target instruction selector can accept
62 /// This class also defines callbacks that targets must implement to lower
63 /// target-specific constructs to SelectionDAG operators.
65 class TargetLowering {
67 /// LegalizeAction - This enum indicates whether operations are valid for a
68 /// target, and if not, what action should be used to make them valid.
70 Legal, // The target natively supports this operation.
71 Promote, // This operation should be executed in a larger type.
72 Expand, // Try to expand this to other ops, otherwise use a libcall.
73 Custom // Use the LowerOperation hook to implement custom lowering.
76 enum OutOfRangeShiftAmount {
77 Undefined, // Oversized shift amounts are undefined (default).
78 Mask, // Shift amounts are auto masked (anded) to value size.
79 Extend // Oversized shift pulls in zeros or sign bits.
82 enum BooleanContent { // How the target represents true/false values.
83 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
84 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
85 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
88 enum SchedPreference {
89 SchedulingForLatency, // Scheduling for shortest total latency.
90 SchedulingForRegPressure // Scheduling for lowest register pressure.
93 explicit TargetLowering(TargetMachine &TM);
94 virtual ~TargetLowering();
96 TargetMachine &getTargetMachine() const { return TM; }
97 const TargetData *getTargetData() const { return TD; }
99 bool isBigEndian() const { return !IsLittleEndian; }
100 bool isLittleEndian() const { return IsLittleEndian; }
101 MVT getPointerTy() const { return PointerTy; }
102 MVT getShiftAmountTy() const { return ShiftAmountTy; }
103 OutOfRangeShiftAmount getShiftAmountFlavor() const {return ShiftAmtHandling; }
105 /// usesGlobalOffsetTable - Return true if this target uses a GOT for PIC
107 bool usesGlobalOffsetTable() const { return UsesGlobalOffsetTable; }
109 /// isSelectExpensive - Return true if the select operation is expensive for
111 bool isSelectExpensive() const { return SelectIsExpensive; }
113 /// isIntDivCheap() - Return true if integer divide is usually cheaper than
114 /// a sequence of several shifts, adds, and multiplies for this target.
115 bool isIntDivCheap() const { return IntDivIsCheap; }
117 /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
119 bool isPow2DivCheap() const { return Pow2DivIsCheap; }
121 /// getSetCCResultType - Return the ValueType of the result of SETCC
122 /// operations. Also used to obtain the target's preferred type for
123 /// the condition operand of SELECT and BRCOND nodes. In the case of
124 /// BRCOND the argument passed is MVT::Other since there are no other
125 /// operands to get a type hint from.
126 virtual MVT getSetCCResultType(MVT VT) const;
128 /// getBooleanContents - For targets without i1 registers, this gives the
129 /// nature of the high-bits of boolean values held in types wider than i1.
130 /// "Boolean values" are special true/false values produced by nodes like
131 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
132 /// Not to be confused with general values promoted from i1.
133 BooleanContent getBooleanContents() const { return BooleanContents;}
135 /// getSchedulingPreference - Return target scheduling preference.
136 SchedPreference getSchedulingPreference() const {
137 return SchedPreferenceInfo;
140 /// getRegClassFor - Return the register class that should be used for the
141 /// specified value type. This may only be called on legal types.
142 TargetRegisterClass *getRegClassFor(MVT VT) const {
143 assert((unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
144 TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT()];
145 assert(RC && "This value type is not natively supported!");
149 /// isTypeLegal - Return true if the target has native support for the
150 /// specified value type. This means that it has a register that directly
151 /// holds it without promotions or expansions.
152 bool isTypeLegal(MVT VT) const {
153 assert(!VT.isSimple() ||
154 (unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
155 return VT.isSimple() && RegClassForVT[VT.getSimpleVT()] != 0;
158 class ValueTypeActionImpl {
159 /// ValueTypeActions - This is a bitvector that contains two bits for each
160 /// value type, where the two bits correspond to the LegalizeAction enum.
161 /// This can be queried with "getTypeAction(VT)".
162 uint32_t ValueTypeActions[2];
164 ValueTypeActionImpl() {
165 ValueTypeActions[0] = ValueTypeActions[1] = 0;
167 ValueTypeActionImpl(const ValueTypeActionImpl &RHS) {
168 ValueTypeActions[0] = RHS.ValueTypeActions[0];
169 ValueTypeActions[1] = RHS.ValueTypeActions[1];
172 LegalizeAction getTypeAction(MVT VT) const {
173 if (VT.isExtended()) {
175 return VT.isPow2VectorType() ? Expand : Promote;
178 // First promote to a power-of-two size, then expand if necessary.
179 return VT == VT.getRoundIntegerType() ? Expand : Promote;
180 assert(0 && "Unsupported extended type!");
183 unsigned I = VT.getSimpleVT();
184 assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
185 return (LegalizeAction)((ValueTypeActions[I>>4] >> ((2*I) & 31)) & 3);
187 void setTypeAction(MVT VT, LegalizeAction Action) {
188 unsigned I = VT.getSimpleVT();
189 assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
190 ValueTypeActions[I>>4] |= Action << ((I*2) & 31);
194 const ValueTypeActionImpl &getValueTypeActions() const {
195 return ValueTypeActions;
198 /// getTypeAction - Return how we should legalize values of this type, either
199 /// it is already legal (return 'Legal') or we need to promote it to a larger
200 /// type (return 'Promote'), or we need to expand it into multiple registers
201 /// of smaller integer type (return 'Expand'). 'Custom' is not an option.
202 LegalizeAction getTypeAction(MVT VT) const {
203 return ValueTypeActions.getTypeAction(VT);
206 /// getTypeToTransformTo - For types supported by the target, this is an
207 /// identity function. For types that must be promoted to larger types, this
208 /// returns the larger type to promote to. For integer types that are larger
209 /// than the largest integer register, this contains one step in the expansion
210 /// to get to the smaller register. For illegal floating point types, this
211 /// returns the integer type to transform to.
212 MVT getTypeToTransformTo(MVT VT) const {
214 assert((unsigned)VT.getSimpleVT() < array_lengthof(TransformToType));
215 MVT NVT = TransformToType[VT.getSimpleVT()];
216 assert(getTypeAction(NVT) != Promote &&
217 "Promote may not follow Expand or Promote");
222 MVT NVT = VT.getPow2VectorType();
224 // Vector length is a power of 2 - split to half the size.
225 unsigned NumElts = VT.getVectorNumElements();
226 MVT EltVT = VT.getVectorElementType();
227 return (NumElts == 1) ? EltVT : MVT::getVectorVT(EltVT, NumElts / 2);
229 // Promote to a power of two size, avoiding multi-step promotion.
230 return getTypeAction(NVT) == Promote ? getTypeToTransformTo(NVT) : NVT;
231 } else if (VT.isInteger()) {
232 MVT NVT = VT.getRoundIntegerType();
234 // Size is a power of two - expand to half the size.
235 return MVT::getIntegerVT(VT.getSizeInBits() / 2);
237 // Promote to a power of two size, avoiding multi-step promotion.
238 return getTypeAction(NVT) == Promote ? getTypeToTransformTo(NVT) : NVT;
240 assert(0 && "Unsupported extended type!");
241 return MVT(); // Not reached
244 /// getTypeToExpandTo - For types supported by the target, this is an
245 /// identity function. For types that must be expanded (i.e. integer types
246 /// that are larger than the largest integer register or illegal floating
247 /// point types), this returns the largest legal type it will be expanded to.
248 MVT getTypeToExpandTo(MVT VT) const {
249 assert(!VT.isVector());
251 switch (getTypeAction(VT)) {
255 VT = getTypeToTransformTo(VT);
258 assert(false && "Type is not legal nor is it to be expanded!");
265 /// getVectorTypeBreakdown - Vector types are broken down into some number of
266 /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
267 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
268 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
270 /// This method returns the number of registers needed, and the VT for each
271 /// register. It also returns the VT and quantity of the intermediate values
272 /// before they are promoted/expanded.
274 unsigned getVectorTypeBreakdown(MVT VT,
276 unsigned &NumIntermediates,
277 MVT &RegisterVT) const;
279 /// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the
280 /// intrinsic will need to map to a MemIntrinsicNode (touches memory). If
281 /// this is the case, it returns true and store the intrinsic
282 /// information into the IntrinsicInfo that was passed to the function.
283 typedef struct IntrinsicInfo {
284 unsigned opc; // target opcode
285 MVT memVT; // memory VT
286 const Value* ptrVal; // value representing memory location
287 int offset; // offset off of ptrVal
288 unsigned align; // alignment
289 bool vol; // is volatile?
290 bool readMem; // reads memory?
291 bool writeMem; // writes memory?
294 virtual bool getTgtMemIntrinsic(IntrinsicInfo& Info,
295 CallInst &I, unsigned Intrinsic) {
299 /// getWidenVectorType: given a vector type, returns the type to widen to
300 /// (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
301 /// If there is no vector type that we want to widen to, returns MVT::Other
302 /// When and were to widen is target dependent based on the cost of
303 /// scalarizing vs using the wider vector type.
304 virtual MVT getWidenVectorType(MVT VT) const;
306 typedef std::vector<APFloat>::const_iterator legal_fpimm_iterator;
307 legal_fpimm_iterator legal_fpimm_begin() const {
308 return LegalFPImmediates.begin();
310 legal_fpimm_iterator legal_fpimm_end() const {
311 return LegalFPImmediates.end();
314 /// isShuffleMaskLegal - Targets can use this to indicate that they only
315 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
316 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
317 /// are assumed to be legal.
318 virtual bool isShuffleMaskLegal(SDValue Mask, MVT VT) const {
322 /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
323 /// used by Targets can use this to indicate if there is a suitable
324 /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
326 virtual bool isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
328 SelectionDAG &DAG) const {
332 /// getOperationAction - Return how this operation should be treated: either
333 /// it is legal, needs to be promoted to a larger size, needs to be
334 /// expanded to some other code sequence, or the target has a custom expander
336 LegalizeAction getOperationAction(unsigned Op, MVT VT) const {
337 if (VT.isExtended()) return Expand;
338 assert(Op < array_lengthof(OpActions) &&
339 (unsigned)VT.getSimpleVT() < sizeof(OpActions[0])*4 &&
340 "Table isn't big enough!");
341 return (LegalizeAction)((OpActions[Op] >> (2*VT.getSimpleVT())) & 3);
344 /// isOperationLegalOrCustom - Return true if the specified operation is
345 /// legal on this target or can be made legal with custom lowering. This
346 /// is used to help guide high-level lowering decisions.
347 bool isOperationLegalOrCustom(unsigned Op, MVT VT) const {
348 return (VT == MVT::Other || isTypeLegal(VT)) &&
349 (getOperationAction(Op, VT) == Legal ||
350 getOperationAction(Op, VT) == Custom);
353 /// isOperationLegal - Return true if the specified operation is legal on this
355 bool isOperationLegal(unsigned Op, MVT VT) const {
356 return (VT == MVT::Other || isTypeLegal(VT)) &&
357 getOperationAction(Op, VT) == Legal;
360 /// getLoadExtAction - Return how this load with extension should be treated:
361 /// either it is legal, needs to be promoted to a larger size, needs to be
362 /// expanded to some other code sequence, or the target has a custom expander
364 LegalizeAction getLoadExtAction(unsigned LType, MVT VT) const {
365 assert(LType < array_lengthof(LoadExtActions) &&
366 (unsigned)VT.getSimpleVT() < sizeof(LoadExtActions[0])*4 &&
367 "Table isn't big enough!");
368 return (LegalizeAction)((LoadExtActions[LType] >> (2*VT.getSimpleVT())) & 3);
371 /// isLoadExtLegal - Return true if the specified load with extension is legal
373 bool isLoadExtLegal(unsigned LType, MVT VT) const {
374 return VT.isSimple() &&
375 (getLoadExtAction(LType, VT) == Legal ||
376 getLoadExtAction(LType, VT) == Custom);
379 /// getTruncStoreAction - Return how this store with truncation should be
380 /// treated: either it is legal, needs to be promoted to a larger size, needs
381 /// to be expanded to some other code sequence, or the target has a custom
383 LegalizeAction getTruncStoreAction(MVT ValVT,
385 assert((unsigned)ValVT.getSimpleVT() < array_lengthof(TruncStoreActions) &&
386 (unsigned)MemVT.getSimpleVT() < sizeof(TruncStoreActions[0])*4 &&
387 "Table isn't big enough!");
388 return (LegalizeAction)((TruncStoreActions[ValVT.getSimpleVT()] >>
389 (2*MemVT.getSimpleVT())) & 3);
392 /// isTruncStoreLegal - Return true if the specified store with truncation is
393 /// legal on this target.
394 bool isTruncStoreLegal(MVT ValVT, MVT MemVT) const {
395 return isTypeLegal(ValVT) && MemVT.isSimple() &&
396 (getTruncStoreAction(ValVT, MemVT) == Legal ||
397 getTruncStoreAction(ValVT, MemVT) == Custom);
400 /// getIndexedLoadAction - Return how the indexed load should be treated:
401 /// either it is legal, needs to be promoted to a larger size, needs to be
402 /// expanded to some other code sequence, or the target has a custom expander
405 getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
406 assert(IdxMode < array_lengthof(IndexedModeActions[0]) &&
407 (unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[0][0])*4 &&
408 "Table isn't big enough!");
409 return (LegalizeAction)((IndexedModeActions[0][IdxMode] >>
410 (2*VT.getSimpleVT())) & 3);
413 /// isIndexedLoadLegal - Return true if the specified indexed load is legal
415 bool isIndexedLoadLegal(unsigned IdxMode, MVT VT) const {
416 return VT.isSimple() &&
417 (getIndexedLoadAction(IdxMode, VT) == Legal ||
418 getIndexedLoadAction(IdxMode, VT) == Custom);
421 /// getIndexedStoreAction - Return how the indexed store should be treated:
422 /// either it is legal, needs to be promoted to a larger size, needs to be
423 /// expanded to some other code sequence, or the target has a custom expander
426 getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
427 assert(IdxMode < array_lengthof(IndexedModeActions[1]) &&
428 (unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[1][0])*4 &&
429 "Table isn't big enough!");
430 return (LegalizeAction)((IndexedModeActions[1][IdxMode] >>
431 (2*VT.getSimpleVT())) & 3);
434 /// isIndexedStoreLegal - Return true if the specified indexed load is legal
436 bool isIndexedStoreLegal(unsigned IdxMode, MVT VT) const {
437 return VT.isSimple() &&
438 (getIndexedStoreAction(IdxMode, VT) == Legal ||
439 getIndexedStoreAction(IdxMode, VT) == Custom);
442 /// getConvertAction - Return how the conversion should be treated:
443 /// either it is legal, needs to be promoted to a larger size, needs to be
444 /// expanded to some other code sequence, or the target has a custom expander
447 getConvertAction(MVT FromVT, MVT ToVT) const {
448 assert((unsigned)FromVT.getSimpleVT() < array_lengthof(ConvertActions) &&
449 (unsigned)ToVT.getSimpleVT() < sizeof(ConvertActions[0])*4 &&
450 "Table isn't big enough!");
451 return (LegalizeAction)((ConvertActions[FromVT.getSimpleVT()] >>
452 (2*ToVT.getSimpleVT())) & 3);
455 /// isConvertLegal - Return true if the specified conversion is legal
457 bool isConvertLegal(MVT FromVT, MVT ToVT) const {
458 return isTypeLegal(FromVT) && isTypeLegal(ToVT) &&
459 (getConvertAction(FromVT, ToVT) == Legal ||
460 getConvertAction(FromVT, ToVT) == Custom);
463 /// getCondCodeAction - Return how the condition code should be treated:
464 /// either it is legal, needs to be expanded to some other code sequence,
465 /// or the target has a custom expander for it.
467 getCondCodeAction(ISD::CondCode CC, MVT VT) const {
468 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
469 (unsigned)VT.getSimpleVT() < sizeof(CondCodeActions[0])*4 &&
470 "Table isn't big enough!");
471 LegalizeAction Action = (LegalizeAction)
472 ((CondCodeActions[CC] >> (2*VT.getSimpleVT())) & 3);
473 assert(Action != Promote && "Can't promote condition code!");
477 /// isCondCodeLegal - Return true if the specified condition code is legal
479 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
480 return getCondCodeAction(CC, VT) == Legal ||
481 getCondCodeAction(CC, VT) == Custom;
485 /// getTypeToPromoteTo - If the action for this operation is to promote, this
486 /// method returns the ValueType to promote to.
487 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
488 assert(getOperationAction(Op, VT) == Promote &&
489 "This operation isn't promoted!");
491 // See if this has an explicit type specified.
492 std::map<std::pair<unsigned, MVT::SimpleValueType>,
493 MVT::SimpleValueType>::const_iterator PTTI =
494 PromoteToType.find(std::make_pair(Op, VT.getSimpleVT()));
495 if (PTTI != PromoteToType.end()) return PTTI->second;
497 assert((VT.isInteger() || VT.isFloatingPoint()) &&
498 "Cannot autopromote this type, add it with AddPromotedToType.");
502 NVT = (MVT::SimpleValueType)(NVT.getSimpleVT()+1);
503 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
504 "Didn't find type to promote to!");
505 } while (!isTypeLegal(NVT) ||
506 getOperationAction(Op, NVT) == Promote);
510 /// getValueType - Return the MVT corresponding to this LLVM type.
511 /// This is fixed by the LLVM operations except for the pointer size. If
512 /// AllowUnknown is true, this will return MVT::Other for types with no MVT
513 /// counterpart (e.g. structs), otherwise it will assert.
514 MVT getValueType(const Type *Ty, bool AllowUnknown = false) const {
515 MVT VT = MVT::getMVT(Ty, AllowUnknown);
516 return VT == MVT::iPTR ? PointerTy : VT;
519 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
520 /// function arguments in the caller parameter area. This is the actual
521 /// alignment, not its logarithm.
522 virtual unsigned getByValTypeAlignment(const Type *Ty) const;
524 /// getRegisterType - Return the type of registers that this ValueType will
525 /// eventually require.
526 MVT getRegisterType(MVT VT) const {
528 assert((unsigned)VT.getSimpleVT() < array_lengthof(RegisterTypeForVT));
529 return RegisterTypeForVT[VT.getSimpleVT()];
533 unsigned NumIntermediates;
534 (void)getVectorTypeBreakdown(VT, VT1, NumIntermediates, RegisterVT);
537 if (VT.isInteger()) {
538 return getRegisterType(getTypeToTransformTo(VT));
540 assert(0 && "Unsupported extended type!");
541 return MVT(); // Not reached
544 /// getNumRegisters - Return the number of registers that this ValueType will
545 /// eventually require. This is one for any types promoted to live in larger
546 /// registers, but may be more than one for types (like i64) that are split
547 /// into pieces. For types like i140, which are first promoted then expanded,
548 /// it is the number of registers needed to hold all the bits of the original
549 /// type. For an i140 on a 32 bit machine this means 5 registers.
550 unsigned getNumRegisters(MVT VT) const {
552 assert((unsigned)VT.getSimpleVT() < array_lengthof(NumRegistersForVT));
553 return NumRegistersForVT[VT.getSimpleVT()];
557 unsigned NumIntermediates;
558 return getVectorTypeBreakdown(VT, VT1, NumIntermediates, VT2);
560 if (VT.isInteger()) {
561 unsigned BitWidth = VT.getSizeInBits();
562 unsigned RegWidth = getRegisterType(VT).getSizeInBits();
563 return (BitWidth + RegWidth - 1) / RegWidth;
565 assert(0 && "Unsupported extended type!");
566 return 0; // Not reached
569 /// ShouldShrinkFPConstant - If true, then instruction selection should
570 /// seek to shrink the FP constant of the specified type to a smaller type
571 /// in order to save space and / or reduce runtime.
572 virtual bool ShouldShrinkFPConstant(MVT VT) const { return true; }
574 /// hasTargetDAGCombine - If true, the target has custom DAG combine
575 /// transformations that it can perform for the specified node.
576 bool hasTargetDAGCombine(ISD::NodeType NT) const {
577 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
578 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
581 /// This function returns the maximum number of store operations permitted
582 /// to replace a call to llvm.memset. The value is set by the target at the
583 /// performance threshold for such a replacement.
584 /// @brief Get maximum # of store operations permitted for llvm.memset
585 unsigned getMaxStoresPerMemset() const { return maxStoresPerMemset; }
587 /// This function returns the maximum number of store operations permitted
588 /// to replace a call to llvm.memcpy. The value is set by the target at the
589 /// performance threshold for such a replacement.
590 /// @brief Get maximum # of store operations permitted for llvm.memcpy
591 unsigned getMaxStoresPerMemcpy() const { return maxStoresPerMemcpy; }
593 /// This function returns the maximum number of store operations permitted
594 /// to replace a call to llvm.memmove. 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.memmove
597 unsigned getMaxStoresPerMemmove() const { return maxStoresPerMemmove; }
599 /// This function returns true if the target allows unaligned memory accesses.
600 /// This is used, for example, in situations where an array copy/move/set is
601 /// converted to a sequence of store operations. It's use helps to ensure that
602 /// such replacements don't generate code that causes an alignment error
603 /// (trap) on the target machine.
604 /// @brief Determine if the target supports unaligned memory accesses.
605 bool allowsUnalignedMemoryAccesses() const {
606 return allowUnalignedMemoryAccesses;
609 /// getOptimalMemOpType - Returns the target specific optimal type for load
610 /// and store operations as a result of memset, memcpy, and memmove lowering.
611 /// It returns MVT::iAny if SelectionDAG should be responsible for
613 virtual MVT getOptimalMemOpType(uint64_t Size, unsigned Align,
614 bool isSrcConst, bool isSrcStr) const {
618 /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
619 /// to implement llvm.setjmp.
620 bool usesUnderscoreSetJmp() const {
621 return UseUnderscoreSetJmp;
624 /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
625 /// to implement llvm.longjmp.
626 bool usesUnderscoreLongJmp() const {
627 return UseUnderscoreLongJmp;
630 /// getStackPointerRegisterToSaveRestore - If a physical register, this
631 /// specifies the register that llvm.savestack/llvm.restorestack should save
633 unsigned getStackPointerRegisterToSaveRestore() const {
634 return StackPointerRegisterToSaveRestore;
637 /// getExceptionAddressRegister - If a physical register, this returns
638 /// the register that receives the exception address on entry to a landing
640 unsigned getExceptionAddressRegister() const {
641 return ExceptionPointerRegister;
644 /// getExceptionSelectorRegister - If a physical register, this returns
645 /// the register that receives the exception typeid on entry to a landing
647 unsigned getExceptionSelectorRegister() const {
648 return ExceptionSelectorRegister;
651 /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
652 /// set, the default is 200)
653 unsigned getJumpBufSize() const {
657 /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
658 /// (if never set, the default is 0)
659 unsigned getJumpBufAlignment() const {
660 return JumpBufAlignment;
663 /// getIfCvtBlockLimit - returns the target specific if-conversion block size
664 /// limit. Any block whose size is greater should not be predicated.
665 unsigned getIfCvtBlockSizeLimit() const {
666 return IfCvtBlockSizeLimit;
669 /// getIfCvtDupBlockLimit - returns the target specific size limit for a
670 /// block to be considered for duplication. Any block whose size is greater
671 /// should not be duplicated to facilitate its predication.
672 unsigned getIfCvtDupBlockSizeLimit() const {
673 return IfCvtDupBlockSizeLimit;
676 /// getPrefLoopAlignment - return the preferred loop alignment.
678 unsigned getPrefLoopAlignment() const {
679 return PrefLoopAlignment;
682 /// getPreIndexedAddressParts - returns true by value, base pointer and
683 /// offset pointer and addressing mode by reference if the node's address
684 /// can be legally represented as pre-indexed load / store address.
685 virtual bool getPreIndexedAddressParts(SDNode *N, SDValue &Base,
687 ISD::MemIndexedMode &AM,
688 SelectionDAG &DAG) const {
692 /// getPostIndexedAddressParts - returns true by value, base pointer and
693 /// offset pointer and addressing mode by reference if this node can be
694 /// combined with a load / store to form a post-indexed load / store.
695 virtual bool getPostIndexedAddressParts(SDNode *N, SDNode *Op,
696 SDValue &Base, SDValue &Offset,
697 ISD::MemIndexedMode &AM,
698 SelectionDAG &DAG) const {
702 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
704 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
705 SelectionDAG &DAG) const;
707 /// isOffsetFoldingLegal - Return true if folding a constant offset
708 /// with the given GlobalAddress is legal. It is frequently not legal in
709 /// PIC relocation models.
710 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
712 //===--------------------------------------------------------------------===//
713 // TargetLowering Optimization Methods
716 /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
717 /// SDValues for returning information from TargetLowering to its clients
718 /// that want to combine
719 struct TargetLoweringOpt {
724 explicit TargetLoweringOpt(SelectionDAG &InDAG) : DAG(InDAG) {}
726 bool CombineTo(SDValue O, SDValue N) {
732 /// ShrinkDemandedConstant - Check to see if the specified operand of the
733 /// specified instruction is a constant integer. If so, check to see if
734 /// there are any bits set in the constant that are not demanded. If so,
735 /// shrink the constant and return true.
736 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
739 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
740 /// DemandedMask bits of the result of Op are ever used downstream. If we can
741 /// use this information to simplify Op, create a new simplified DAG node and
742 /// return true, returning the original and new nodes in Old and New.
743 /// Otherwise, analyze the expression and return a mask of KnownOne and
744 /// KnownZero bits for the expression (used to simplify the caller).
745 /// The KnownZero/One bits may only be accurate for those bits in the
747 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
748 APInt &KnownZero, APInt &KnownOne,
749 TargetLoweringOpt &TLO, unsigned Depth = 0) const;
751 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
752 /// Mask are known to be either zero or one and return them in the
753 /// KnownZero/KnownOne bitsets.
754 virtual void computeMaskedBitsForTargetNode(const SDValue Op,
758 const SelectionDAG &DAG,
759 unsigned Depth = 0) const;
761 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
762 /// targets that want to expose additional information about sign bits to the
764 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
765 unsigned Depth = 0) const;
767 struct DAGCombinerInfo {
768 void *DC; // The DAG Combiner object.
770 bool CalledByLegalizer;
774 DAGCombinerInfo(SelectionDAG &dag, bool bl, bool cl, void *dc)
775 : DC(dc), BeforeLegalize(bl), CalledByLegalizer(cl), DAG(dag) {}
777 bool isBeforeLegalize() const { return BeforeLegalize; }
778 bool isCalledByLegalizer() const { return CalledByLegalizer; }
780 void AddToWorklist(SDNode *N);
781 SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To);
782 SDValue CombineTo(SDNode *N, SDValue Res);
783 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1);
785 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
788 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
789 /// and cc. If it is unable to simplify it, return a null SDValue.
790 SDValue SimplifySetCC(MVT VT, SDValue N0, SDValue N1,
791 ISD::CondCode Cond, bool foldBooleans,
792 DAGCombinerInfo &DCI, DebugLoc dl) const;
794 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
795 /// node is a GlobalAddress + offset.
797 isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) const;
799 /// isConsecutiveLoad - Return true if LD (which must be a LoadSDNode) is
800 /// loading 'Bytes' bytes from a location that is 'Dist' units away from the
801 /// location that the 'Base' load is loading from.
802 bool isConsecutiveLoad(SDNode *LD, SDNode *Base, unsigned Bytes, int Dist,
803 const MachineFrameInfo *MFI) const;
805 /// PerformDAGCombine - This method will be invoked for all target nodes and
806 /// for any target-independent nodes that the target has registered with
809 /// The semantics are as follows:
811 /// SDValue.Val == 0 - No change was made
812 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
813 /// otherwise - N should be replaced by the returned Operand.
815 /// In addition, methods provided by DAGCombinerInfo may be used to perform
816 /// more complex transformations.
818 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
820 //===--------------------------------------------------------------------===//
821 // TargetLowering Configuration Methods - These methods should be invoked by
822 // the derived class constructor to configure this object for the target.
826 /// setUsesGlobalOffsetTable - Specify that this target does or doesn't use a
827 /// GOT for PC-relative code.
828 void setUsesGlobalOffsetTable(bool V) { UsesGlobalOffsetTable = V; }
830 /// setShiftAmountType - Describe the type that should be used for shift
831 /// amounts. This type defaults to the pointer type.
832 void setShiftAmountType(MVT VT) { ShiftAmountTy = VT; }
834 /// setBooleanContents - Specify how the target extends the result of a
835 /// boolean value from i1 to a wider type. See getBooleanContents.
836 void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
838 /// setSchedulingPreference - Specify the target scheduling preference.
839 void setSchedulingPreference(SchedPreference Pref) {
840 SchedPreferenceInfo = Pref;
843 /// setShiftAmountFlavor - Describe how the target handles out of range shift
845 void setShiftAmountFlavor(OutOfRangeShiftAmount OORSA) {
846 ShiftAmtHandling = OORSA;
849 /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
850 /// use _setjmp to implement llvm.setjmp or the non _ version.
851 /// Defaults to false.
852 void setUseUnderscoreSetJmp(bool Val) {
853 UseUnderscoreSetJmp = Val;
856 /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
857 /// use _longjmp to implement llvm.longjmp or the non _ version.
858 /// Defaults to false.
859 void setUseUnderscoreLongJmp(bool Val) {
860 UseUnderscoreLongJmp = Val;
863 /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
864 /// specifies the register that llvm.savestack/llvm.restorestack should save
866 void setStackPointerRegisterToSaveRestore(unsigned R) {
867 StackPointerRegisterToSaveRestore = R;
870 /// setExceptionPointerRegister - If set to a physical register, this sets
871 /// the register that receives the exception address on entry to a landing
873 void setExceptionPointerRegister(unsigned R) {
874 ExceptionPointerRegister = R;
877 /// setExceptionSelectorRegister - If set to a physical register, this sets
878 /// the register that receives the exception typeid on entry to a landing
880 void setExceptionSelectorRegister(unsigned R) {
881 ExceptionSelectorRegister = R;
884 /// SelectIsExpensive - Tells the code generator not to expand operations
885 /// into sequences that use the select operations if possible.
886 void setSelectIsExpensive() { SelectIsExpensive = true; }
888 /// setIntDivIsCheap - Tells the code generator that integer divide is
889 /// expensive, and if possible, should be replaced by an alternate sequence
890 /// of instructions not containing an integer divide.
891 void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
893 /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
894 /// srl/add/sra for a signed divide by power of two, and let the target handle
896 void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
898 /// addRegisterClass - Add the specified register class as an available
899 /// regclass for the specified value type. This indicates the selector can
900 /// handle values of that class natively.
901 void addRegisterClass(MVT VT, TargetRegisterClass *RC) {
902 assert((unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
903 AvailableRegClasses.push_back(std::make_pair(VT, RC));
904 RegClassForVT[VT.getSimpleVT()] = RC;
907 /// computeRegisterProperties - Once all of the register classes are added,
908 /// this allows us to compute derived properties we expose.
909 void computeRegisterProperties();
911 /// setOperationAction - Indicate that the specified operation does not work
912 /// with the specified type and indicate what to do about it.
913 void setOperationAction(unsigned Op, MVT VT,
914 LegalizeAction Action) {
915 assert((unsigned)VT.getSimpleVT() < sizeof(OpActions[0])*4 &&
916 Op < array_lengthof(OpActions) && "Table isn't big enough!");
917 OpActions[Op] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
918 OpActions[Op] |= (uint64_t)Action << VT.getSimpleVT()*2;
921 /// setLoadExtAction - Indicate that the specified load with extension does
922 /// not work with the with specified type and indicate what to do about it.
923 void setLoadExtAction(unsigned ExtType, MVT VT,
924 LegalizeAction Action) {
925 assert((unsigned)VT.getSimpleVT() < sizeof(LoadExtActions[0])*4 &&
926 ExtType < array_lengthof(LoadExtActions) &&
927 "Table isn't big enough!");
928 LoadExtActions[ExtType] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
929 LoadExtActions[ExtType] |= (uint64_t)Action << VT.getSimpleVT()*2;
932 /// setTruncStoreAction - Indicate that the specified truncating store does
933 /// not work with the with specified type and indicate what to do about it.
934 void setTruncStoreAction(MVT ValVT, MVT MemVT,
935 LegalizeAction Action) {
936 assert((unsigned)ValVT.getSimpleVT() < array_lengthof(TruncStoreActions) &&
937 (unsigned)MemVT.getSimpleVT() < sizeof(TruncStoreActions[0])*4 &&
938 "Table isn't big enough!");
939 TruncStoreActions[ValVT.getSimpleVT()] &= ~(uint64_t(3UL) <<
940 MemVT.getSimpleVT()*2);
941 TruncStoreActions[ValVT.getSimpleVT()] |= (uint64_t)Action <<
942 MemVT.getSimpleVT()*2;
945 /// setIndexedLoadAction - Indicate that the specified indexed load does or
946 /// does not work with the with specified type and indicate what to do abort
947 /// it. NOTE: All indexed mode loads are initialized to Expand in
948 /// TargetLowering.cpp
949 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
950 LegalizeAction Action) {
951 assert((unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[0])*4 &&
952 IdxMode < array_lengthof(IndexedModeActions[0]) &&
953 "Table isn't big enough!");
954 IndexedModeActions[0][IdxMode] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
955 IndexedModeActions[0][IdxMode] |= (uint64_t)Action << VT.getSimpleVT()*2;
958 /// setIndexedStoreAction - Indicate that the specified indexed store does or
959 /// does not work with the with specified type and indicate what to do about
960 /// it. NOTE: All indexed mode stores are initialized to Expand in
961 /// TargetLowering.cpp
962 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
963 LegalizeAction Action) {
964 assert((unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[1][0])*4 &&
965 IdxMode < array_lengthof(IndexedModeActions[1]) &&
966 "Table isn't big enough!");
967 IndexedModeActions[1][IdxMode] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
968 IndexedModeActions[1][IdxMode] |= (uint64_t)Action << VT.getSimpleVT()*2;
971 /// setConvertAction - Indicate that the specified conversion does or does
972 /// not work with the with specified type and indicate what to do about it.
973 void setConvertAction(MVT FromVT, MVT ToVT,
974 LegalizeAction Action) {
975 assert((unsigned)FromVT.getSimpleVT() < array_lengthof(ConvertActions) &&
976 (unsigned)ToVT.getSimpleVT() < sizeof(ConvertActions[0])*4 &&
977 "Table isn't big enough!");
978 ConvertActions[FromVT.getSimpleVT()] &= ~(uint64_t(3UL) <<
979 ToVT.getSimpleVT()*2);
980 ConvertActions[FromVT.getSimpleVT()] |= (uint64_t)Action <<
981 ToVT.getSimpleVT()*2;
984 /// setCondCodeAction - Indicate that the specified condition code is or isn't
985 /// supported on the target and indicate what to do about it.
986 void setCondCodeAction(ISD::CondCode CC, MVT VT, LegalizeAction Action) {
987 assert((unsigned)VT.getSimpleVT() < sizeof(CondCodeActions[0])*4 &&
988 (unsigned)CC < array_lengthof(CondCodeActions) &&
989 "Table isn't big enough!");
990 CondCodeActions[(unsigned)CC] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
991 CondCodeActions[(unsigned)CC] |= (uint64_t)Action << VT.getSimpleVT()*2;
994 /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
995 /// promotion code defaults to trying a larger integer/fp until it can find
996 /// one that works. If that default is insufficient, this method can be used
997 /// by the target to override the default.
998 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
999 PromoteToType[std::make_pair(Opc, OrigVT.getSimpleVT())] =
1000 DestVT.getSimpleVT();
1003 /// addLegalFPImmediate - Indicate that this target can instruction select
1004 /// the specified FP immediate natively.
1005 void addLegalFPImmediate(const APFloat& Imm) {
1006 LegalFPImmediates.push_back(Imm);
1009 /// setTargetDAGCombine - Targets should invoke this method for each target
1010 /// independent node that they want to provide a custom DAG combiner for by
1011 /// implementing the PerformDAGCombine virtual method.
1012 void setTargetDAGCombine(ISD::NodeType NT) {
1013 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1014 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1017 /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
1018 /// bytes); default is 200
1019 void setJumpBufSize(unsigned Size) {
1023 /// setJumpBufAlignment - Set the target's required jmp_buf buffer
1024 /// alignment (in bytes); default is 0
1025 void setJumpBufAlignment(unsigned Align) {
1026 JumpBufAlignment = Align;
1029 /// setIfCvtBlockSizeLimit - Set the target's if-conversion block size
1030 /// limit (in number of instructions); default is 2.
1031 void setIfCvtBlockSizeLimit(unsigned Limit) {
1032 IfCvtBlockSizeLimit = Limit;
1035 /// setIfCvtDupBlockSizeLimit - Set the target's block size limit (in number
1036 /// of instructions) to be considered for code duplication during
1037 /// if-conversion; default is 2.
1038 void setIfCvtDupBlockSizeLimit(unsigned Limit) {
1039 IfCvtDupBlockSizeLimit = Limit;
1042 /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
1043 /// alignment is zero, it means the target does not care about loop alignment.
1044 void setPrefLoopAlignment(unsigned Align) {
1045 PrefLoopAlignment = Align;
1050 virtual const TargetSubtarget *getSubtarget() {
1051 assert(0 && "Not Implemented");
1052 return NULL; // this is here to silence compiler errors
1054 //===--------------------------------------------------------------------===//
1055 // Lowering methods - These methods must be implemented by targets so that
1056 // the SelectionDAGLowering code knows how to lower these.
1059 /// LowerArguments - This hook must be implemented to indicate how we should
1060 /// lower the arguments for the specified function, into the specified DAG.
1062 LowerArguments(Function &F, SelectionDAG &DAG,
1063 SmallVectorImpl<SDValue>& ArgValues, DebugLoc dl);
1065 /// LowerCallTo - This hook lowers an abstract call to a function into an
1066 /// actual call. This returns a pair of operands. The first element is the
1067 /// return value for the function (if RetTy is not VoidTy). The second
1068 /// element is the outgoing token chain.
1069 struct ArgListEntry {
1080 ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1081 isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
1083 typedef std::vector<ArgListEntry> ArgListTy;
1084 virtual std::pair<SDValue, SDValue>
1085 LowerCallTo(SDValue Chain, const Type *RetTy, bool RetSExt, bool RetZExt,
1086 bool isVarArg, bool isInreg, unsigned CallingConv,
1087 bool isTailCall, SDValue Callee, ArgListTy &Args,
1088 SelectionDAG &DAG, DebugLoc dl);
1090 /// EmitTargetCodeForMemcpy - Emit target-specific code that performs a
1091 /// memcpy. This can be used by targets to provide code sequences for cases
1092 /// that don't fit the target's parameters for simple loads/stores and can be
1093 /// more efficient than using a library call. This function can return a null
1094 /// SDValue if the target declines to use custom code and a different
1095 /// lowering strategy should be used.
1097 /// If AlwaysInline is true, the size is constant and the target should not
1098 /// emit any calls and is strongly encouraged to attempt to emit inline code
1099 /// even if it is beyond the usual threshold because this intrinsic is being
1100 /// expanded in a place where calls are not feasible (e.g. within the prologue
1101 /// for another call). If the target chooses to decline an AlwaysInline
1102 /// request here, legalize will resort to using simple loads and stores.
1104 EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
1106 SDValue Op1, SDValue Op2,
1107 SDValue Op3, unsigned Align,
1109 const Value *DstSV, uint64_t DstOff,
1110 const Value *SrcSV, uint64_t SrcOff) {
1114 /// EmitTargetCodeForMemmove - Emit target-specific code that performs a
1115 /// memmove. This can be used by targets to provide code sequences for cases
1116 /// that don't fit the target's parameters for simple loads/stores and can be
1117 /// more efficient than using a library call. This function can return a null
1118 /// SDValue if the target declines to use custom code and a different
1119 /// lowering strategy should be used.
1121 EmitTargetCodeForMemmove(SelectionDAG &DAG, DebugLoc dl,
1123 SDValue Op1, SDValue Op2,
1124 SDValue Op3, unsigned Align,
1125 const Value *DstSV, uint64_t DstOff,
1126 const Value *SrcSV, uint64_t SrcOff) {
1130 /// EmitTargetCodeForMemset - Emit target-specific code that performs a
1131 /// memset. This can be used by targets to provide code sequences for cases
1132 /// that don't fit the target's parameters for simple stores and can be more
1133 /// efficient than using a library call. This function can return a null
1134 /// SDValue if the target declines to use custom code and a different
1135 /// lowering strategy should be used.
1137 EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
1139 SDValue Op1, SDValue Op2,
1140 SDValue Op3, unsigned Align,
1141 const Value *DstSV, uint64_t DstOff) {
1145 /// LowerOperationWrapper - This callback is invoked by the type legalizer
1146 /// to legalize nodes with an illegal operand type but legal result types.
1147 /// It replaces the LowerOperation callback in the type Legalizer.
1148 /// The reason we can not do away with LowerOperation entirely is that
1149 /// LegalizeDAG isn't yet ready to use this callback.
1150 /// TODO: Consider merging with ReplaceNodeResults.
1152 /// The target places new result values for the node in Results (their number
1153 /// and types must exactly match those of the original return values of
1154 /// the node), or leaves Results empty, which indicates that the node is not
1155 /// to be custom lowered after all.
1156 /// The default implementation calls LowerOperation.
1157 virtual void LowerOperationWrapper(SDNode *N,
1158 SmallVectorImpl<SDValue> &Results,
1161 /// LowerOperation - This callback is invoked for operations that are
1162 /// unsupported by the target, which are registered to use 'custom' lowering,
1163 /// and whose defined values are all legal.
1164 /// If the target has no operations that require custom lowering, it need not
1165 /// implement this. The default implementation of this aborts.
1166 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG);
1168 /// ReplaceNodeResults - This callback is invoked when a node result type is
1169 /// illegal for the target, and the operation was registered to use 'custom'
1170 /// lowering for that result type. The target places new result values for
1171 /// the node in Results (their number and types must exactly match those of
1172 /// the original return values of the node), or leaves Results empty, which
1173 /// indicates that the node is not to be custom lowered after all.
1175 /// If the target has no operations that require custom lowering, it need not
1176 /// implement this. The default implementation aborts.
1177 virtual void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
1178 SelectionDAG &DAG) {
1179 assert(0 && "ReplaceNodeResults not implemented for this target!");
1182 /// IsEligibleForTailCallOptimization - Check whether the call is eligible for
1183 /// tail call optimization. Targets which want to do tail call optimization
1184 /// should override this function.
1185 virtual bool IsEligibleForTailCallOptimization(CallSDNode *Call,
1187 SelectionDAG &DAG) const {
1191 /// CheckTailCallReturnConstraints - Check whether CALL node immediatly
1192 /// preceeds the RET node and whether the return uses the result of the node
1193 /// or is a void return. This function can be used by the target to determine
1194 /// eligiblity of tail call optimization.
1195 static bool CheckTailCallReturnConstraints(CallSDNode *TheCall, SDValue Ret) {
1196 unsigned NumOps = Ret.getNumOperands();
1198 (Ret.getOperand(0) == SDValue(TheCall,1) ||
1199 Ret.getOperand(0) == SDValue(TheCall,0))) ||
1201 Ret.getOperand(0) == SDValue(TheCall,
1202 TheCall->getNumValues()-1) &&
1203 Ret.getOperand(1) == SDValue(TheCall,0)))
1208 /// GetPossiblePreceedingTailCall - Get preceeding TailCallNodeOpCode node if
1209 /// it exists. Skip a possible ISD::TokenFactor.
1210 static SDValue GetPossiblePreceedingTailCall(SDValue Chain,
1211 unsigned TailCallNodeOpCode) {
1212 if (Chain.getOpcode() == TailCallNodeOpCode) {
1214 } else if (Chain.getOpcode() == ISD::TokenFactor) {
1215 if (Chain.getNumOperands() &&
1216 Chain.getOperand(0).getOpcode() == TailCallNodeOpCode)
1217 return Chain.getOperand(0);
1222 /// getTargetNodeName() - This method returns the name of a target specific
1224 virtual const char *getTargetNodeName(unsigned Opcode) const;
1226 /// createFastISel - This method returns a target specific FastISel object,
1227 /// or null if the target does not support "fast" ISel.
1229 createFastISel(MachineFunction &,
1230 MachineModuleInfo *, DwarfWriter *,
1231 DenseMap<const Value *, unsigned> &,
1232 DenseMap<const BasicBlock *, MachineBasicBlock *> &,
1233 DenseMap<const AllocaInst *, int> &
1235 , SmallSet<Instruction*, 8> &CatchInfoLost
1241 //===--------------------------------------------------------------------===//
1242 // Inline Asm Support hooks
1245 enum ConstraintType {
1246 C_Register, // Constraint represents specific register(s).
1247 C_RegisterClass, // Constraint represents any of register(s) in class.
1248 C_Memory, // Memory constraint.
1249 C_Other, // Something else.
1250 C_Unknown // Unsupported constraint.
1253 /// AsmOperandInfo - This contains information for each constraint that we are
1255 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
1256 /// ConstraintCode - This contains the actual string for the code, like "m".
1257 /// TargetLowering picks the 'best' code from ConstraintInfo::Codes that
1258 /// most closely matches the operand.
1259 std::string ConstraintCode;
1261 /// ConstraintType - Information about the constraint code, e.g. Register,
1262 /// RegisterClass, Memory, Other, Unknown.
1263 TargetLowering::ConstraintType ConstraintType;
1265 /// CallOperandval - If this is the result output operand or a
1266 /// clobber, this is null, otherwise it is the incoming operand to the
1267 /// CallInst. This gets modified as the asm is processed.
1268 Value *CallOperandVal;
1270 /// ConstraintVT - The ValueType for the operand value.
1273 /// isMatchingInputConstraint - Return true of this is an input operand that
1274 /// is a matching constraint like "4".
1275 bool isMatchingInputConstraint() const;
1277 /// getMatchedOperand - If this is an input matching constraint, this method
1278 /// returns the output operand it matches.
1279 unsigned getMatchedOperand() const;
1281 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
1282 : InlineAsm::ConstraintInfo(info),
1283 ConstraintType(TargetLowering::C_Unknown),
1284 CallOperandVal(0), ConstraintVT(MVT::Other) {
1288 /// ComputeConstraintToUse - Determines the constraint code and constraint
1289 /// type to use for the specific AsmOperandInfo, setting
1290 /// OpInfo.ConstraintCode and OpInfo.ConstraintType. If the actual operand
1291 /// being passed in is available, it can be passed in as Op, otherwise an
1292 /// empty SDValue can be passed. If hasMemory is true it means one of the asm
1293 /// constraint of the inline asm instruction being processed is 'm'.
1294 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
1297 SelectionDAG *DAG = 0) const;
1299 /// getConstraintType - Given a constraint, return the type of constraint it
1300 /// is for this target.
1301 virtual ConstraintType getConstraintType(const std::string &Constraint) const;
1303 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1304 /// return a list of registers that can be used to satisfy the constraint.
1305 /// This should only be used for C_RegisterClass constraints.
1306 virtual std::vector<unsigned>
1307 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1310 /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
1311 /// {edx}), return the register number and the register class for the
1314 /// Given a register class constraint, like 'r', if this corresponds directly
1315 /// to an LLVM register class, return a register of 0 and the register class
1318 /// This should only be used for C_Register constraints. On error,
1319 /// this returns a register number of 0 and a null register class pointer..
1320 virtual std::pair<unsigned, const TargetRegisterClass*>
1321 getRegForInlineAsmConstraint(const std::string &Constraint,
1324 /// LowerXConstraint - try to replace an X constraint, which matches anything,
1325 /// with another that has more specific requirements based on the type of the
1326 /// corresponding operand. This returns null if there is no replacement to
1328 virtual const char *LowerXConstraint(MVT ConstraintVT) const;
1330 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1331 /// vector. If it is invalid, don't add anything to Ops. If hasMemory is true
1332 /// it means one of the asm constraint of the inline asm instruction being
1333 /// processed is 'm'.
1334 virtual void LowerAsmOperandForConstraint(SDValue Op, char ConstraintLetter,
1336 std::vector<SDValue> &Ops,
1337 SelectionDAG &DAG) const;
1339 //===--------------------------------------------------------------------===//
1343 // EmitInstrWithCustomInserter - This method should be implemented by targets
1344 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1345 // instructions are special in various ways, which require special support to
1346 // insert. The specified MachineInstr is created but not inserted into any
1347 // basic blocks, and the scheduler passes ownership of it to this method.
1348 virtual MachineBasicBlock *EmitInstrWithCustomInserter(MachineInstr *MI,
1349 MachineBasicBlock *MBB) const;
1351 //===--------------------------------------------------------------------===//
1352 // Addressing mode description hooks (used by LSR etc).
1355 /// AddrMode - This represents an addressing mode of:
1356 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1357 /// If BaseGV is null, there is no BaseGV.
1358 /// If BaseOffs is zero, there is no base offset.
1359 /// If HasBaseReg is false, there is no base register.
1360 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1364 GlobalValue *BaseGV;
1368 AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1371 /// isLegalAddressingMode - Return true if the addressing mode represented by
1372 /// AM is legal for this target, for a load/store of the specified type.
1373 /// TODO: Handle pre/postinc as well.
1374 virtual bool isLegalAddressingMode(const AddrMode &AM, const Type *Ty) const;
1376 /// isTruncateFree - Return true if it's free to truncate a value of
1377 /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1378 /// register EAX to i16 by referencing its sub-register AX.
1379 virtual bool isTruncateFree(const Type *Ty1, const Type *Ty2) const {
1383 virtual bool isTruncateFree(MVT VT1, MVT VT2) const {
1387 //===--------------------------------------------------------------------===//
1388 // Div utility functions
1390 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG,
1391 std::vector<SDNode*>* Created) const;
1392 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG,
1393 std::vector<SDNode*>* Created) const;
1396 //===--------------------------------------------------------------------===//
1397 // Runtime Library hooks
1400 /// setLibcallName - Rename the default libcall routine name for the specified
1402 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1403 LibcallRoutineNames[Call] = Name;
1406 /// getLibcallName - Get the libcall routine name for the specified libcall.
1408 const char *getLibcallName(RTLIB::Libcall Call) const {
1409 return LibcallRoutineNames[Call];
1412 /// setCmpLibcallCC - Override the default CondCode to be used to test the
1413 /// result of the comparison libcall against zero.
1414 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1415 CmpLibcallCCs[Call] = CC;
1418 /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1419 /// the comparison libcall against zero.
1420 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1421 return CmpLibcallCCs[Call];
1426 const TargetData *TD;
1428 /// PointerTy - The type to use for pointers, usually i32 or i64.
1432 /// IsLittleEndian - True if this is a little endian target.
1434 bool IsLittleEndian;
1436 /// UsesGlobalOffsetTable - True if this target uses a GOT for PIC codegen.
1438 bool UsesGlobalOffsetTable;
1440 /// SelectIsExpensive - Tells the code generator not to expand operations
1441 /// into sequences that use the select operations if possible.
1442 bool SelectIsExpensive;
1444 /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1445 /// constants into a sequence of muls, adds, and shifts. This is a hack until
1446 /// a real cost model is in place. If we ever optimize for size, this will be
1447 /// set to true unconditionally.
1450 /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1451 /// srl/add/sra for a signed divide by power of two, and let the target handle
1453 bool Pow2DivIsCheap;
1455 /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1456 /// llvm.setjmp. Defaults to false.
1457 bool UseUnderscoreSetJmp;
1459 /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1460 /// llvm.longjmp. Defaults to false.
1461 bool UseUnderscoreLongJmp;
1463 /// ShiftAmountTy - The type to use for shift amounts, usually i8 or whatever
1467 OutOfRangeShiftAmount ShiftAmtHandling;
1469 /// BooleanContents - Information about the contents of the high-bits in
1470 /// boolean values held in a type wider than i1. See getBooleanContents.
1471 BooleanContent BooleanContents;
1473 /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1474 /// total cycles or lowest register usage.
1475 SchedPreference SchedPreferenceInfo;
1477 /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1478 unsigned JumpBufSize;
1480 /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1482 unsigned JumpBufAlignment;
1484 /// IfCvtBlockSizeLimit - The maximum allowed size for a block to be
1486 unsigned IfCvtBlockSizeLimit;
1488 /// IfCvtDupBlockSizeLimit - The maximum allowed size for a block to be
1489 /// duplicated during if-conversion.
1490 unsigned IfCvtDupBlockSizeLimit;
1492 /// PrefLoopAlignment - The perferred loop alignment.
1494 unsigned PrefLoopAlignment;
1496 /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1497 /// specifies the register that llvm.savestack/llvm.restorestack should save
1499 unsigned StackPointerRegisterToSaveRestore;
1501 /// ExceptionPointerRegister - If set to a physical register, this specifies
1502 /// the register that receives the exception address on entry to a landing
1504 unsigned ExceptionPointerRegister;
1506 /// ExceptionSelectorRegister - If set to a physical register, this specifies
1507 /// the register that receives the exception typeid on entry to a landing
1509 unsigned ExceptionSelectorRegister;
1511 /// RegClassForVT - This indicates the default register class to use for
1512 /// each ValueType the target supports natively.
1513 TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1514 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1515 MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1517 /// TransformToType - For any value types we are promoting or expanding, this
1518 /// contains the value type that we are changing to. For Expanded types, this
1519 /// contains one step of the expand (e.g. i64 -> i32), even if there are
1520 /// multiple steps required (e.g. i64 -> i16). For types natively supported
1521 /// by the system, this holds the same type (e.g. i32 -> i32).
1522 MVT TransformToType[MVT::LAST_VALUETYPE];
1524 /// OpActions - For each operation and each value type, keep a LegalizeAction
1525 /// that indicates how instruction selection should deal with the operation.
1526 /// Most operations are Legal (aka, supported natively by the target), but
1527 /// operations that are not should be described. Note that operations on
1528 /// non-legal value types are not described here.
1529 uint64_t OpActions[ISD::BUILTIN_OP_END];
1531 /// LoadExtActions - For each load of load extension type and each value type,
1532 /// keep a LegalizeAction that indicates how instruction selection should deal
1534 uint64_t LoadExtActions[ISD::LAST_LOADEXT_TYPE];
1536 /// TruncStoreActions - For each truncating store, keep a LegalizeAction that
1537 /// indicates how instruction selection should deal with the store.
1538 uint64_t TruncStoreActions[MVT::LAST_VALUETYPE];
1540 /// IndexedModeActions - For each indexed mode and each value type, keep a
1541 /// pair of LegalizeAction that indicates how instruction selection should
1542 /// deal with the load / store.
1543 uint64_t IndexedModeActions[2][ISD::LAST_INDEXED_MODE];
1545 /// ConvertActions - For each conversion from source type to destination type,
1546 /// keep a LegalizeAction that indicates how instruction selection should
1547 /// deal with the conversion.
1548 /// Currently, this is used only for floating->floating conversions
1549 /// (FP_EXTEND and FP_ROUND).
1550 uint64_t ConvertActions[MVT::LAST_VALUETYPE];
1552 /// CondCodeActions - For each condition code (ISD::CondCode) keep a
1553 /// LegalizeAction that indicates how instruction selection should
1554 /// deal with the condition code.
1555 uint64_t CondCodeActions[ISD::SETCC_INVALID];
1557 ValueTypeActionImpl ValueTypeActions;
1559 std::vector<APFloat> LegalFPImmediates;
1561 std::vector<std::pair<MVT, TargetRegisterClass*> > AvailableRegClasses;
1563 /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
1564 /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
1565 /// which sets a bit in this array.
1567 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
1569 /// PromoteToType - For operations that must be promoted to a specific type,
1570 /// this holds the destination type. This map should be sparse, so don't hold
1573 /// Targets add entries to this map with AddPromotedToType(..), clients access
1574 /// this with getTypeToPromoteTo(..).
1575 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1578 /// LibcallRoutineNames - Stores the name each libcall.
1580 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1582 /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
1583 /// of each of the comparison libcall against zero.
1584 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1587 /// When lowering @llvm.memset this field specifies the maximum number of
1588 /// store operations that may be substituted for the call to memset. Targets
1589 /// must set this value based on the cost threshold for that target. Targets
1590 /// should assume that the memset will be done using as many of the largest
1591 /// store operations first, followed by smaller ones, if necessary, per
1592 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1593 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1594 /// store. This only applies to setting a constant array of a constant size.
1595 /// @brief Specify maximum number of store instructions per memset call.
1596 unsigned maxStoresPerMemset;
1598 /// When lowering @llvm.memcpy this field specifies the maximum number of
1599 /// store operations that may be substituted for a call to memcpy. Targets
1600 /// must set this value based on the cost threshold for that target. Targets
1601 /// should assume that the memcpy will be done using as many of the largest
1602 /// store operations first, followed by smaller ones, if necessary, per
1603 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1604 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1605 /// and one 1-byte store. This only applies to copying a constant array of
1607 /// @brief Specify maximum bytes of store instructions per memcpy call.
1608 unsigned maxStoresPerMemcpy;
1610 /// When lowering @llvm.memmove this field specifies the maximum number of
1611 /// store instructions that may be substituted for a call to memmove. Targets
1612 /// must set this value based on the cost threshold for that target. Targets
1613 /// should assume that the memmove will be done using as many of the largest
1614 /// store operations first, followed by smaller ones, if necessary, per
1615 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1616 /// with 8-bit alignment would result in nine 1-byte stores. This only
1617 /// applies to copying a constant array of constant size.
1618 /// @brief Specify maximum bytes of store instructions per memmove call.
1619 unsigned maxStoresPerMemmove;
1621 /// This field specifies whether the target machine permits unaligned memory
1622 /// accesses. This is used, for example, to determine the size of store
1623 /// operations when copying small arrays and other similar tasks.
1624 /// @brief Indicate whether the target permits unaligned memory accesses.
1625 bool allowUnalignedMemoryAccesses;
1627 } // end llvm namespace