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"
41 class MachineBasicBlock;
42 class MachineFunction;
43 class MachineFrameInfo;
45 class MachineModuleInfo;
52 class TargetRegisterClass;
53 class TargetSubtarget;
56 //===----------------------------------------------------------------------===//
57 /// TargetLowering - This class defines information used to lower LLVM code to
58 /// legal SelectionDAG operators that the target instruction selector can accept
61 /// This class also defines callbacks that targets must implement to lower
62 /// target-specific constructs to SelectionDAG operators.
64 class TargetLowering {
66 /// LegalizeAction - This enum indicates whether operations are valid for a
67 /// target, and if not, what action should be used to make them valid.
69 Legal, // The target natively supports this operation.
70 Promote, // This operation should be executed in a larger type.
71 Expand, // Try to expand this to other ops, otherwise use a libcall.
72 Custom // Use the LowerOperation hook to implement custom lowering.
75 enum OutOfRangeShiftAmount {
76 Undefined, // Oversized shift amounts are undefined (default).
77 Mask, // Shift amounts are auto masked (anded) to value size.
78 Extend // Oversized shift pulls in zeros or sign bits.
81 enum BooleanContent { // How the target represents true/false values.
82 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
83 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
84 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
87 enum SchedPreference {
88 SchedulingForLatency, // Scheduling for shortest total latency.
89 SchedulingForRegPressure // Scheduling for lowest register pressure.
92 explicit TargetLowering(TargetMachine &TM);
93 virtual ~TargetLowering();
95 TargetMachine &getTargetMachine() const { return TM; }
96 const TargetData *getTargetData() const { return TD; }
98 bool isBigEndian() const { return !IsLittleEndian; }
99 bool isLittleEndian() const { return IsLittleEndian; }
100 MVT getPointerTy() const { return PointerTy; }
101 MVT getShiftAmountTy() const { return ShiftAmountTy; }
102 OutOfRangeShiftAmount getShiftAmountFlavor() const {return ShiftAmtHandling; }
104 /// usesGlobalOffsetTable - Return true if this target uses a GOT for PIC
106 bool usesGlobalOffsetTable() const { return UsesGlobalOffsetTable; }
108 /// isSelectExpensive - Return true if the select operation is expensive for
110 bool isSelectExpensive() const { return SelectIsExpensive; }
112 /// isIntDivCheap() - Return true if integer divide is usually cheaper than
113 /// a sequence of several shifts, adds, and multiplies for this target.
114 bool isIntDivCheap() const { return IntDivIsCheap; }
116 /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
118 bool isPow2DivCheap() const { return Pow2DivIsCheap; }
120 /// getSetCCResultType - Return the ValueType of the result of SETCC
121 /// operations. Also used to obtain the target's preferred type for
122 /// the condition operand of SELECT and BRCOND nodes. In the case of
123 /// BRCOND the argument passed is MVT::Other since there are no other
124 /// operands to get a type hint from.
125 virtual MVT getSetCCResultType(MVT VT) const;
127 /// getBooleanContents - For targets without i1 registers, this gives the
128 /// nature of the high-bits of boolean values held in types wider than i1.
129 /// "Boolean values" are special true/false values produced by nodes like
130 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
131 /// Not to be confused with general values promoted from i1.
132 BooleanContent getBooleanContents() const { return BooleanContents;}
134 /// getSchedulingPreference - Return target scheduling preference.
135 SchedPreference getSchedulingPreference() const {
136 return SchedPreferenceInfo;
139 /// getRegClassFor - Return the register class that should be used for the
140 /// specified value type. This may only be called on legal types.
141 TargetRegisterClass *getRegClassFor(MVT VT) const {
142 assert((unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
143 TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT()];
144 assert(RC && "This value type is not natively supported!");
148 /// isTypeLegal - Return true if the target has native support for the
149 /// specified value type. This means that it has a register that directly
150 /// holds it without promotions or expansions.
151 bool isTypeLegal(MVT VT) const {
152 assert(!VT.isSimple() ||
153 (unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
154 return VT.isSimple() && RegClassForVT[VT.getSimpleVT()] != 0;
157 class ValueTypeActionImpl {
158 /// ValueTypeActions - This is a bitvector that contains two bits for each
159 /// value type, where the two bits correspond to the LegalizeAction enum.
160 /// This can be queried with "getTypeAction(VT)".
161 uint32_t ValueTypeActions[2];
163 ValueTypeActionImpl() {
164 ValueTypeActions[0] = ValueTypeActions[1] = 0;
166 ValueTypeActionImpl(const ValueTypeActionImpl &RHS) {
167 ValueTypeActions[0] = RHS.ValueTypeActions[0];
168 ValueTypeActions[1] = RHS.ValueTypeActions[1];
171 LegalizeAction getTypeAction(MVT VT) const {
172 if (VT.isExtended()) {
174 return VT.isPow2VectorType() ? Expand : Promote;
177 // First promote to a power-of-two size, then expand if necessary.
178 return VT == VT.getRoundIntegerType() ? Expand : Promote;
179 assert(0 && "Unsupported extended type!");
182 unsigned I = VT.getSimpleVT();
183 assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
184 return (LegalizeAction)((ValueTypeActions[I>>4] >> ((2*I) & 31)) & 3);
186 void setTypeAction(MVT VT, LegalizeAction Action) {
187 unsigned I = VT.getSimpleVT();
188 assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
189 ValueTypeActions[I>>4] |= Action << ((I*2) & 31);
193 const ValueTypeActionImpl &getValueTypeActions() const {
194 return ValueTypeActions;
197 /// getTypeAction - Return how we should legalize values of this type, either
198 /// it is already legal (return 'Legal') or we need to promote it to a larger
199 /// type (return 'Promote'), or we need to expand it into multiple registers
200 /// of smaller integer type (return 'Expand'). 'Custom' is not an option.
201 LegalizeAction getTypeAction(MVT VT) const {
202 return ValueTypeActions.getTypeAction(VT);
205 /// getTypeToTransformTo - For types supported by the target, this is an
206 /// identity function. For types that must be promoted to larger types, this
207 /// returns the larger type to promote to. For integer types that are larger
208 /// than the largest integer register, this contains one step in the expansion
209 /// to get to the smaller register. For illegal floating point types, this
210 /// returns the integer type to transform to.
211 MVT getTypeToTransformTo(MVT VT) const {
213 assert((unsigned)VT.getSimpleVT() < array_lengthof(TransformToType));
214 MVT NVT = TransformToType[VT.getSimpleVT()];
215 assert(getTypeAction(NVT) != Promote &&
216 "Promote may not follow Expand or Promote");
221 MVT NVT = VT.getPow2VectorType();
223 // Vector length is a power of 2 - split to half the size.
224 unsigned NumElts = VT.getVectorNumElements();
225 MVT EltVT = VT.getVectorElementType();
226 return (NumElts == 1) ? EltVT : MVT::getVectorVT(EltVT, NumElts / 2);
228 // Promote to a power of two size, avoiding multi-step promotion.
229 return getTypeAction(NVT) == Promote ? getTypeToTransformTo(NVT) : NVT;
230 } else if (VT.isInteger()) {
231 MVT NVT = VT.getRoundIntegerType();
233 // Size is a power of two - expand to half the size.
234 return MVT::getIntegerVT(VT.getSizeInBits() / 2);
236 // Promote to a power of two size, avoiding multi-step promotion.
237 return getTypeAction(NVT) == Promote ? getTypeToTransformTo(NVT) : NVT;
239 assert(0 && "Unsupported extended type!");
240 return MVT(); // Not reached
243 /// getTypeToExpandTo - For types supported by the target, this is an
244 /// identity function. For types that must be expanded (i.e. integer types
245 /// that are larger than the largest integer register or illegal floating
246 /// point types), this returns the largest legal type it will be expanded to.
247 MVT getTypeToExpandTo(MVT VT) const {
248 assert(!VT.isVector());
250 switch (getTypeAction(VT)) {
254 VT = getTypeToTransformTo(VT);
257 assert(false && "Type is not legal nor is it to be expanded!");
264 /// getVectorTypeBreakdown - Vector types are broken down into some number of
265 /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
266 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
267 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
269 /// This method returns the number of registers needed, and the VT for each
270 /// register. It also returns the VT and quantity of the intermediate values
271 /// before they are promoted/expanded.
273 unsigned getVectorTypeBreakdown(MVT VT,
275 unsigned &NumIntermediates,
276 MVT &RegisterVT) const;
278 /// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the
279 /// intrinsic will need to map to a MemIntrinsicNode (touches memory). If
280 /// this is the case, it returns true and store the intrinsic
281 /// information into the IntrinsicInfo that was passed to the function.
282 typedef struct IntrinsicInfo {
283 unsigned opc; // target opcode
284 MVT memVT; // memory VT
285 const Value* ptrVal; // value representing memory location
286 int offset; // offset off of ptrVal
287 unsigned align; // alignment
288 bool vol; // is volatile?
289 bool readMem; // reads memory?
290 bool writeMem; // writes memory?
293 virtual bool getTgtMemIntrinsic(IntrinsicInfo& Info,
294 CallInst &I, unsigned Intrinsic) {
298 /// getWidenVectorType: given a vector type, returns the type to widen to
299 /// (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
300 /// If there is no vector type that we want to widen to, returns MVT::Other
301 /// When and were to widen is target dependent based on the cost of
302 /// scalarizing vs using the wider vector type.
303 virtual MVT getWidenVectorType(MVT VT) const;
305 typedef std::vector<APFloat>::const_iterator legal_fpimm_iterator;
306 legal_fpimm_iterator legal_fpimm_begin() const {
307 return LegalFPImmediates.begin();
309 legal_fpimm_iterator legal_fpimm_end() const {
310 return LegalFPImmediates.end();
313 /// isShuffleMaskLegal - Targets can use this to indicate that they only
314 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
315 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
316 /// are assumed to be legal.
317 virtual bool isShuffleMaskLegal(SDValue Mask, MVT VT) const {
321 /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
322 /// used by Targets can use this to indicate if there is a suitable
323 /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
325 virtual bool isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
327 SelectionDAG &DAG) const {
331 /// getOperationAction - Return how this operation should be treated: either
332 /// it is legal, needs to be promoted to a larger size, needs to be
333 /// expanded to some other code sequence, or the target has a custom expander
335 LegalizeAction getOperationAction(unsigned Op, MVT VT) const {
336 if (VT.isExtended()) return Expand;
337 assert(Op < array_lengthof(OpActions) &&
338 (unsigned)VT.getSimpleVT() < sizeof(OpActions[0])*4 &&
339 "Table isn't big enough!");
340 return (LegalizeAction)((OpActions[Op] >> (2*VT.getSimpleVT())) & 3);
343 /// isOperationLegalOrCustom - Return true if the specified operation is
344 /// legal on this target or can be made legal with custom lowering. This
345 /// is used to help guide high-level lowering decisions.
346 bool isOperationLegalOrCustom(unsigned Op, MVT VT) const {
347 return (VT == MVT::Other || isTypeLegal(VT)) &&
348 (getOperationAction(Op, VT) == Legal ||
349 getOperationAction(Op, VT) == Custom);
352 /// isOperationLegal - Return true if the specified operation is legal on this
354 bool isOperationLegal(unsigned Op, MVT VT) const {
355 return (VT == MVT::Other || isTypeLegal(VT)) &&
356 getOperationAction(Op, VT) == Legal;
359 /// getLoadExtAction - Return how this load with extension should be treated:
360 /// either it is legal, needs to be promoted to a larger size, needs to be
361 /// expanded to some other code sequence, or the target has a custom expander
363 LegalizeAction getLoadExtAction(unsigned LType, MVT VT) const {
364 assert(LType < array_lengthof(LoadExtActions) &&
365 (unsigned)VT.getSimpleVT() < sizeof(LoadExtActions[0])*4 &&
366 "Table isn't big enough!");
367 return (LegalizeAction)((LoadExtActions[LType] >> (2*VT.getSimpleVT())) & 3);
370 /// isLoadExtLegal - Return true if the specified load with extension is legal
372 bool isLoadExtLegal(unsigned LType, MVT VT) const {
373 return VT.isSimple() &&
374 (getLoadExtAction(LType, VT) == Legal ||
375 getLoadExtAction(LType, VT) == Custom);
378 /// getTruncStoreAction - Return how this store with truncation should be
379 /// treated: either it is legal, needs to be promoted to a larger size, needs
380 /// to be expanded to some other code sequence, or the target has a custom
382 LegalizeAction getTruncStoreAction(MVT ValVT,
384 assert((unsigned)ValVT.getSimpleVT() < array_lengthof(TruncStoreActions) &&
385 (unsigned)MemVT.getSimpleVT() < sizeof(TruncStoreActions[0])*4 &&
386 "Table isn't big enough!");
387 return (LegalizeAction)((TruncStoreActions[ValVT.getSimpleVT()] >>
388 (2*MemVT.getSimpleVT())) & 3);
391 /// isTruncStoreLegal - Return true if the specified store with truncation is
392 /// legal on this target.
393 bool isTruncStoreLegal(MVT ValVT, MVT MemVT) const {
394 return isTypeLegal(ValVT) && MemVT.isSimple() &&
395 (getTruncStoreAction(ValVT, MemVT) == Legal ||
396 getTruncStoreAction(ValVT, MemVT) == Custom);
399 /// getIndexedLoadAction - Return how the indexed load should be treated:
400 /// either it is legal, needs to be promoted to a larger size, needs to be
401 /// expanded to some other code sequence, or the target has a custom expander
404 getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
405 assert(IdxMode < array_lengthof(IndexedModeActions[0]) &&
406 (unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[0][0])*4 &&
407 "Table isn't big enough!");
408 return (LegalizeAction)((IndexedModeActions[0][IdxMode] >>
409 (2*VT.getSimpleVT())) & 3);
412 /// isIndexedLoadLegal - Return true if the specified indexed load is legal
414 bool isIndexedLoadLegal(unsigned IdxMode, MVT VT) const {
415 return VT.isSimple() &&
416 (getIndexedLoadAction(IdxMode, VT) == Legal ||
417 getIndexedLoadAction(IdxMode, VT) == Custom);
420 /// getIndexedStoreAction - Return how the indexed store should be treated:
421 /// either it is legal, needs to be promoted to a larger size, needs to be
422 /// expanded to some other code sequence, or the target has a custom expander
425 getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
426 assert(IdxMode < array_lengthof(IndexedModeActions[1]) &&
427 (unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[1][0])*4 &&
428 "Table isn't big enough!");
429 return (LegalizeAction)((IndexedModeActions[1][IdxMode] >>
430 (2*VT.getSimpleVT())) & 3);
433 /// isIndexedStoreLegal - Return true if the specified indexed load is legal
435 bool isIndexedStoreLegal(unsigned IdxMode, MVT VT) const {
436 return VT.isSimple() &&
437 (getIndexedStoreAction(IdxMode, VT) == Legal ||
438 getIndexedStoreAction(IdxMode, VT) == Custom);
441 /// getConvertAction - Return how the conversion should be treated:
442 /// either it is legal, needs to be promoted to a larger size, needs to be
443 /// expanded to some other code sequence, or the target has a custom expander
446 getConvertAction(MVT FromVT, MVT ToVT) const {
447 assert((unsigned)FromVT.getSimpleVT() < array_lengthof(ConvertActions) &&
448 (unsigned)ToVT.getSimpleVT() < sizeof(ConvertActions[0])*4 &&
449 "Table isn't big enough!");
450 return (LegalizeAction)((ConvertActions[FromVT.getSimpleVT()] >>
451 (2*ToVT.getSimpleVT())) & 3);
454 /// isConvertLegal - Return true if the specified conversion is legal
456 bool isConvertLegal(MVT FromVT, MVT ToVT) const {
457 return isTypeLegal(FromVT) && isTypeLegal(ToVT) &&
458 (getConvertAction(FromVT, ToVT) == Legal ||
459 getConvertAction(FromVT, ToVT) == Custom);
462 /// getCondCodeAction - Return how the condition code should be treated:
463 /// either it is legal, needs to be expanded to some other code sequence,
464 /// or the target has a custom expander for it.
466 getCondCodeAction(ISD::CondCode CC, MVT VT) const {
467 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
468 (unsigned)VT.getSimpleVT() < sizeof(CondCodeActions[0])*4 &&
469 "Table isn't big enough!");
470 LegalizeAction Action = (LegalizeAction)
471 ((CondCodeActions[CC] >> (2*VT.getSimpleVT())) & 3);
472 assert(Action != Promote && "Can't promote condition code!");
476 /// isCondCodeLegal - Return true if the specified condition code is legal
478 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
479 return getCondCodeAction(CC, VT) == Legal ||
480 getCondCodeAction(CC, VT) == Custom;
484 /// getTypeToPromoteTo - If the action for this operation is to promote, this
485 /// method returns the ValueType to promote to.
486 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
487 assert(getOperationAction(Op, VT) == Promote &&
488 "This operation isn't promoted!");
490 // See if this has an explicit type specified.
491 std::map<std::pair<unsigned, MVT::SimpleValueType>,
492 MVT::SimpleValueType>::const_iterator PTTI =
493 PromoteToType.find(std::make_pair(Op, VT.getSimpleVT()));
494 if (PTTI != PromoteToType.end()) return PTTI->second;
496 assert((VT.isInteger() || VT.isFloatingPoint()) &&
497 "Cannot autopromote this type, add it with AddPromotedToType.");
501 NVT = (MVT::SimpleValueType)(NVT.getSimpleVT()+1);
502 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
503 "Didn't find type to promote to!");
504 } while (!isTypeLegal(NVT) ||
505 getOperationAction(Op, NVT) == Promote);
509 /// getValueType - Return the MVT corresponding to this LLVM type.
510 /// This is fixed by the LLVM operations except for the pointer size. If
511 /// AllowUnknown is true, this will return MVT::Other for types with no MVT
512 /// counterpart (e.g. structs), otherwise it will assert.
513 MVT getValueType(const Type *Ty, bool AllowUnknown = false) const {
514 MVT VT = MVT::getMVT(Ty, AllowUnknown);
515 return VT == MVT::iPTR ? PointerTy : VT;
518 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
519 /// function arguments in the caller parameter area. This is the actual
520 /// alignment, not its logarithm.
521 virtual unsigned getByValTypeAlignment(const Type *Ty) const;
523 /// getRegisterType - Return the type of registers that this ValueType will
524 /// eventually require.
525 MVT getRegisterType(MVT VT) const {
527 assert((unsigned)VT.getSimpleVT() < array_lengthof(RegisterTypeForVT));
528 return RegisterTypeForVT[VT.getSimpleVT()];
532 unsigned NumIntermediates;
533 (void)getVectorTypeBreakdown(VT, VT1, NumIntermediates, RegisterVT);
536 if (VT.isInteger()) {
537 return getRegisterType(getTypeToTransformTo(VT));
539 assert(0 && "Unsupported extended type!");
540 return MVT(); // Not reached
543 /// getNumRegisters - Return the number of registers that this ValueType will
544 /// eventually require. This is one for any types promoted to live in larger
545 /// registers, but may be more than one for types (like i64) that are split
546 /// into pieces. For types like i140, which are first promoted then expanded,
547 /// it is the number of registers needed to hold all the bits of the original
548 /// type. For an i140 on a 32 bit machine this means 5 registers.
549 unsigned getNumRegisters(MVT VT) const {
551 assert((unsigned)VT.getSimpleVT() < array_lengthof(NumRegistersForVT));
552 return NumRegistersForVT[VT.getSimpleVT()];
556 unsigned NumIntermediates;
557 return getVectorTypeBreakdown(VT, VT1, NumIntermediates, VT2);
559 if (VT.isInteger()) {
560 unsigned BitWidth = VT.getSizeInBits();
561 unsigned RegWidth = getRegisterType(VT).getSizeInBits();
562 return (BitWidth + RegWidth - 1) / RegWidth;
564 assert(0 && "Unsupported extended type!");
565 return 0; // Not reached
568 /// ShouldShrinkFPConstant - If true, then instruction selection should
569 /// seek to shrink the FP constant of the specified type to a smaller type
570 /// in order to save space and / or reduce runtime.
571 virtual bool ShouldShrinkFPConstant(MVT VT) const { return true; }
573 /// hasTargetDAGCombine - If true, the target has custom DAG combine
574 /// transformations that it can perform for the specified node.
575 bool hasTargetDAGCombine(ISD::NodeType NT) const {
576 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
577 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
580 /// This function returns the maximum number of store operations permitted
581 /// to replace a call to llvm.memset. The value is set by the target at the
582 /// performance threshold for such a replacement.
583 /// @brief Get maximum # of store operations permitted for llvm.memset
584 unsigned getMaxStoresPerMemset() const { return maxStoresPerMemset; }
586 /// This function returns the maximum number of store operations permitted
587 /// to replace a call to llvm.memcpy. The value is set by the target at the
588 /// performance threshold for such a replacement.
589 /// @brief Get maximum # of store operations permitted for llvm.memcpy
590 unsigned getMaxStoresPerMemcpy() const { return maxStoresPerMemcpy; }
592 /// This function returns the maximum number of store operations permitted
593 /// to replace a call to llvm.memmove. The value is set by the target at the
594 /// performance threshold for such a replacement.
595 /// @brief Get maximum # of store operations permitted for llvm.memmove
596 unsigned getMaxStoresPerMemmove() const { return maxStoresPerMemmove; }
598 /// This function returns true if the target allows unaligned memory accesses.
599 /// This is used, for example, in situations where an array copy/move/set is
600 /// converted to a sequence of store operations. It's use helps to ensure that
601 /// such replacements don't generate code that causes an alignment error
602 /// (trap) on the target machine.
603 /// @brief Determine if the target supports unaligned memory accesses.
604 bool allowsUnalignedMemoryAccesses() const {
605 return allowUnalignedMemoryAccesses;
608 /// getOptimalMemOpType - Returns the target specific optimal type for load
609 /// and store operations as a result of memset, memcpy, and memmove lowering.
610 /// It returns MVT::iAny if SelectionDAG should be responsible for
612 virtual MVT getOptimalMemOpType(uint64_t Size, unsigned Align,
613 bool isSrcConst, bool isSrcStr) const {
617 /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
618 /// to implement llvm.setjmp.
619 bool usesUnderscoreSetJmp() const {
620 return UseUnderscoreSetJmp;
623 /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
624 /// to implement llvm.longjmp.
625 bool usesUnderscoreLongJmp() const {
626 return UseUnderscoreLongJmp;
629 /// getStackPointerRegisterToSaveRestore - If a physical register, this
630 /// specifies the register that llvm.savestack/llvm.restorestack should save
632 unsigned getStackPointerRegisterToSaveRestore() const {
633 return StackPointerRegisterToSaveRestore;
636 /// getExceptionAddressRegister - If a physical register, this returns
637 /// the register that receives the exception address on entry to a landing
639 unsigned getExceptionAddressRegister() const {
640 return ExceptionPointerRegister;
643 /// getExceptionSelectorRegister - If a physical register, this returns
644 /// the register that receives the exception typeid on entry to a landing
646 unsigned getExceptionSelectorRegister() const {
647 return ExceptionSelectorRegister;
650 /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
651 /// set, the default is 200)
652 unsigned getJumpBufSize() const {
656 /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
657 /// (if never set, the default is 0)
658 unsigned getJumpBufAlignment() const {
659 return JumpBufAlignment;
662 /// getIfCvtBlockLimit - returns the target specific if-conversion block size
663 /// limit. Any block whose size is greater should not be predicated.
664 unsigned getIfCvtBlockSizeLimit() const {
665 return IfCvtBlockSizeLimit;
668 /// getIfCvtDupBlockLimit - returns the target specific size limit for a
669 /// block to be considered for duplication. Any block whose size is greater
670 /// should not be duplicated to facilitate its predication.
671 unsigned getIfCvtDupBlockSizeLimit() const {
672 return IfCvtDupBlockSizeLimit;
675 /// getPrefLoopAlignment - return the preferred loop alignment.
677 unsigned getPrefLoopAlignment() const {
678 return PrefLoopAlignment;
681 /// getPreIndexedAddressParts - returns true by value, base pointer and
682 /// offset pointer and addressing mode by reference if the node's address
683 /// can be legally represented as pre-indexed load / store address.
684 virtual bool getPreIndexedAddressParts(SDNode *N, SDValue &Base,
686 ISD::MemIndexedMode &AM,
687 SelectionDAG &DAG) const {
691 /// getPostIndexedAddressParts - returns true by value, base pointer and
692 /// offset pointer and addressing mode by reference if this node can be
693 /// combined with a load / store to form a post-indexed load / store.
694 virtual bool getPostIndexedAddressParts(SDNode *N, SDNode *Op,
695 SDValue &Base, SDValue &Offset,
696 ISD::MemIndexedMode &AM,
697 SelectionDAG &DAG) const {
701 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
703 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
704 SelectionDAG &DAG) const;
706 /// isOffsetFoldingLegal - Return true if folding a constant offset
707 /// with the given GlobalAddress is legal. It is frequently not legal in
708 /// PIC relocation models.
709 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
711 //===--------------------------------------------------------------------===//
712 // TargetLowering Optimization Methods
715 /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
716 /// SDValues for returning information from TargetLowering to its clients
717 /// that want to combine
718 struct TargetLoweringOpt {
723 explicit TargetLoweringOpt(SelectionDAG &InDAG) : DAG(InDAG) {}
725 bool CombineTo(SDValue O, SDValue N) {
731 /// ShrinkDemandedConstant - Check to see if the specified operand of the
732 /// specified instruction is a constant integer. If so, check to see if
733 /// there are any bits set in the constant that are not demanded. If so,
734 /// shrink the constant and return true.
735 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
738 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
739 /// DemandedMask bits of the result of Op are ever used downstream. If we can
740 /// use this information to simplify Op, create a new simplified DAG node and
741 /// return true, returning the original and new nodes in Old and New.
742 /// Otherwise, analyze the expression and return a mask of KnownOne and
743 /// KnownZero bits for the expression (used to simplify the caller).
744 /// The KnownZero/One bits may only be accurate for those bits in the
746 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
747 APInt &KnownZero, APInt &KnownOne,
748 TargetLoweringOpt &TLO, unsigned Depth = 0) const;
750 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
751 /// Mask are known to be either zero or one and return them in the
752 /// KnownZero/KnownOne bitsets.
753 virtual void computeMaskedBitsForTargetNode(const SDValue Op,
757 const SelectionDAG &DAG,
758 unsigned Depth = 0) const;
760 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
761 /// targets that want to expose additional information about sign bits to the
763 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
764 unsigned Depth = 0) const;
766 struct DAGCombinerInfo {
767 void *DC; // The DAG Combiner object.
769 bool CalledByLegalizer;
773 DAGCombinerInfo(SelectionDAG &dag, bool bl, bool cl, void *dc)
774 : DC(dc), BeforeLegalize(bl), CalledByLegalizer(cl), DAG(dag) {}
776 bool isBeforeLegalize() const { return BeforeLegalize; }
777 bool isCalledByLegalizer() const { return CalledByLegalizer; }
779 void AddToWorklist(SDNode *N);
780 SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To);
781 SDValue CombineTo(SDNode *N, SDValue Res);
782 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1);
784 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
787 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
788 /// and cc. If it is unable to simplify it, return a null SDValue.
789 SDValue SimplifySetCC(MVT VT, SDValue N0, SDValue N1,
790 ISD::CondCode Cond, bool foldBooleans,
791 DAGCombinerInfo &DCI) const;
793 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
794 /// node is a GlobalAddress + offset.
796 isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) const;
798 /// isConsecutiveLoad - Return true if LD (which must be a LoadSDNode) is
799 /// loading 'Bytes' bytes from a location that is 'Dist' units away from the
800 /// location that the 'Base' load is loading from.
801 bool isConsecutiveLoad(SDNode *LD, SDNode *Base, unsigned Bytes, int Dist,
802 const MachineFrameInfo *MFI) const;
804 /// PerformDAGCombine - This method will be invoked for all target nodes and
805 /// for any target-independent nodes that the target has registered with
808 /// The semantics are as follows:
810 /// SDValue.Val == 0 - No change was made
811 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
812 /// otherwise - N should be replaced by the returned Operand.
814 /// In addition, methods provided by DAGCombinerInfo may be used to perform
815 /// more complex transformations.
817 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
819 //===--------------------------------------------------------------------===//
820 // TargetLowering Configuration Methods - These methods should be invoked by
821 // the derived class constructor to configure this object for the target.
825 /// setUsesGlobalOffsetTable - Specify that this target does or doesn't use a
826 /// GOT for PC-relative code.
827 void setUsesGlobalOffsetTable(bool V) { UsesGlobalOffsetTable = V; }
829 /// setShiftAmountType - Describe the type that should be used for shift
830 /// amounts. This type defaults to the pointer type.
831 void setShiftAmountType(MVT VT) { ShiftAmountTy = VT; }
833 /// setBooleanContents - Specify how the target extends the result of a
834 /// boolean value from i1 to a wider type. See getBooleanContents.
835 void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
837 /// setSchedulingPreference - Specify the target scheduling preference.
838 void setSchedulingPreference(SchedPreference Pref) {
839 SchedPreferenceInfo = Pref;
842 /// setShiftAmountFlavor - Describe how the target handles out of range shift
844 void setShiftAmountFlavor(OutOfRangeShiftAmount OORSA) {
845 ShiftAmtHandling = OORSA;
848 /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
849 /// use _setjmp to implement llvm.setjmp or the non _ version.
850 /// Defaults to false.
851 void setUseUnderscoreSetJmp(bool Val) {
852 UseUnderscoreSetJmp = Val;
855 /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
856 /// use _longjmp to implement llvm.longjmp or the non _ version.
857 /// Defaults to false.
858 void setUseUnderscoreLongJmp(bool Val) {
859 UseUnderscoreLongJmp = Val;
862 /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
863 /// specifies the register that llvm.savestack/llvm.restorestack should save
865 void setStackPointerRegisterToSaveRestore(unsigned R) {
866 StackPointerRegisterToSaveRestore = R;
869 /// setExceptionPointerRegister - If set to a physical register, this sets
870 /// the register that receives the exception address on entry to a landing
872 void setExceptionPointerRegister(unsigned R) {
873 ExceptionPointerRegister = R;
876 /// setExceptionSelectorRegister - If set to a physical register, this sets
877 /// the register that receives the exception typeid on entry to a landing
879 void setExceptionSelectorRegister(unsigned R) {
880 ExceptionSelectorRegister = R;
883 /// SelectIsExpensive - Tells the code generator not to expand operations
884 /// into sequences that use the select operations if possible.
885 void setSelectIsExpensive() { SelectIsExpensive = true; }
887 /// setIntDivIsCheap - Tells the code generator that integer divide is
888 /// expensive, and if possible, should be replaced by an alternate sequence
889 /// of instructions not containing an integer divide.
890 void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
892 /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
893 /// srl/add/sra for a signed divide by power of two, and let the target handle
895 void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
897 /// addRegisterClass - Add the specified register class as an available
898 /// regclass for the specified value type. This indicates the selector can
899 /// handle values of that class natively.
900 void addRegisterClass(MVT VT, TargetRegisterClass *RC) {
901 assert((unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
902 AvailableRegClasses.push_back(std::make_pair(VT, RC));
903 RegClassForVT[VT.getSimpleVT()] = RC;
906 /// computeRegisterProperties - Once all of the register classes are added,
907 /// this allows us to compute derived properties we expose.
908 void computeRegisterProperties();
910 /// setOperationAction - Indicate that the specified operation does not work
911 /// with the specified type and indicate what to do about it.
912 void setOperationAction(unsigned Op, MVT VT,
913 LegalizeAction Action) {
914 assert((unsigned)VT.getSimpleVT() < sizeof(OpActions[0])*4 &&
915 Op < array_lengthof(OpActions) && "Table isn't big enough!");
916 OpActions[Op] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
917 OpActions[Op] |= (uint64_t)Action << VT.getSimpleVT()*2;
920 /// setLoadExtAction - Indicate that the specified load with extension does
921 /// not work with the with specified type and indicate what to do about it.
922 void setLoadExtAction(unsigned ExtType, MVT VT,
923 LegalizeAction Action) {
924 assert((unsigned)VT.getSimpleVT() < sizeof(LoadExtActions[0])*4 &&
925 ExtType < array_lengthof(LoadExtActions) &&
926 "Table isn't big enough!");
927 LoadExtActions[ExtType] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
928 LoadExtActions[ExtType] |= (uint64_t)Action << VT.getSimpleVT()*2;
931 /// setTruncStoreAction - Indicate that the specified truncating store does
932 /// not work with the with specified type and indicate what to do about it.
933 void setTruncStoreAction(MVT ValVT, MVT MemVT,
934 LegalizeAction Action) {
935 assert((unsigned)ValVT.getSimpleVT() < array_lengthof(TruncStoreActions) &&
936 (unsigned)MemVT.getSimpleVT() < sizeof(TruncStoreActions[0])*4 &&
937 "Table isn't big enough!");
938 TruncStoreActions[ValVT.getSimpleVT()] &= ~(uint64_t(3UL) <<
939 MemVT.getSimpleVT()*2);
940 TruncStoreActions[ValVT.getSimpleVT()] |= (uint64_t)Action <<
941 MemVT.getSimpleVT()*2;
944 /// setIndexedLoadAction - Indicate that the specified indexed load does or
945 /// does not work with the with specified type and indicate what to do abort
946 /// it. NOTE: All indexed mode loads are initialized to Expand in
947 /// TargetLowering.cpp
948 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
949 LegalizeAction Action) {
950 assert((unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[0])*4 &&
951 IdxMode < array_lengthof(IndexedModeActions[0]) &&
952 "Table isn't big enough!");
953 IndexedModeActions[0][IdxMode] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
954 IndexedModeActions[0][IdxMode] |= (uint64_t)Action << VT.getSimpleVT()*2;
957 /// setIndexedStoreAction - Indicate that the specified indexed store does or
958 /// does not work with the with specified type and indicate what to do about
959 /// it. NOTE: All indexed mode stores are initialized to Expand in
960 /// TargetLowering.cpp
961 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
962 LegalizeAction Action) {
963 assert((unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[1][0])*4 &&
964 IdxMode < array_lengthof(IndexedModeActions[1]) &&
965 "Table isn't big enough!");
966 IndexedModeActions[1][IdxMode] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
967 IndexedModeActions[1][IdxMode] |= (uint64_t)Action << VT.getSimpleVT()*2;
970 /// setConvertAction - Indicate that the specified conversion does or does
971 /// not work with the with specified type and indicate what to do about it.
972 void setConvertAction(MVT FromVT, MVT ToVT,
973 LegalizeAction Action) {
974 assert((unsigned)FromVT.getSimpleVT() < array_lengthof(ConvertActions) &&
975 (unsigned)ToVT.getSimpleVT() < sizeof(ConvertActions[0])*4 &&
976 "Table isn't big enough!");
977 ConvertActions[FromVT.getSimpleVT()] &= ~(uint64_t(3UL) <<
978 ToVT.getSimpleVT()*2);
979 ConvertActions[FromVT.getSimpleVT()] |= (uint64_t)Action <<
980 ToVT.getSimpleVT()*2;
983 /// setCondCodeAction - Indicate that the specified condition code is or isn't
984 /// supported on the target and indicate what to do about it.
985 void setCondCodeAction(ISD::CondCode CC, MVT VT, LegalizeAction Action) {
986 assert((unsigned)VT.getSimpleVT() < sizeof(CondCodeActions[0])*4 &&
987 (unsigned)CC < array_lengthof(CondCodeActions) &&
988 "Table isn't big enough!");
989 CondCodeActions[(unsigned)CC] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
990 CondCodeActions[(unsigned)CC] |= (uint64_t)Action << VT.getSimpleVT()*2;
993 /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
994 /// promotion code defaults to trying a larger integer/fp until it can find
995 /// one that works. If that default is insufficient, this method can be used
996 /// by the target to override the default.
997 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
998 PromoteToType[std::make_pair(Opc, OrigVT.getSimpleVT())] =
999 DestVT.getSimpleVT();
1002 /// addLegalFPImmediate - Indicate that this target can instruction select
1003 /// the specified FP immediate natively.
1004 void addLegalFPImmediate(const APFloat& Imm) {
1005 LegalFPImmediates.push_back(Imm);
1008 /// setTargetDAGCombine - Targets should invoke this method for each target
1009 /// independent node that they want to provide a custom DAG combiner for by
1010 /// implementing the PerformDAGCombine virtual method.
1011 void setTargetDAGCombine(ISD::NodeType NT) {
1012 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1013 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1016 /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
1017 /// bytes); default is 200
1018 void setJumpBufSize(unsigned Size) {
1022 /// setJumpBufAlignment - Set the target's required jmp_buf buffer
1023 /// alignment (in bytes); default is 0
1024 void setJumpBufAlignment(unsigned Align) {
1025 JumpBufAlignment = Align;
1028 /// setIfCvtBlockSizeLimit - Set the target's if-conversion block size
1029 /// limit (in number of instructions); default is 2.
1030 void setIfCvtBlockSizeLimit(unsigned Limit) {
1031 IfCvtBlockSizeLimit = Limit;
1034 /// setIfCvtDupBlockSizeLimit - Set the target's block size limit (in number
1035 /// of instructions) to be considered for code duplication during
1036 /// if-conversion; default is 2.
1037 void setIfCvtDupBlockSizeLimit(unsigned Limit) {
1038 IfCvtDupBlockSizeLimit = Limit;
1041 /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
1042 /// alignment is zero, it means the target does not care about loop alignment.
1043 void setPrefLoopAlignment(unsigned Align) {
1044 PrefLoopAlignment = Align;
1049 virtual const TargetSubtarget *getSubtarget() {
1050 assert(0 && "Not Implemented");
1051 return NULL; // this is here to silence compiler errors
1053 //===--------------------------------------------------------------------===//
1054 // Lowering methods - These methods must be implemented by targets so that
1055 // the SelectionDAGLowering code knows how to lower these.
1058 /// LowerArguments - This hook must be implemented to indicate how we should
1059 /// lower the arguments for the specified function, into the specified DAG.
1061 LowerArguments(Function &F, SelectionDAG &DAG,
1062 SmallVectorImpl<SDValue>& ArgValues);
1064 /// LowerCallTo - This hook lowers an abstract call to a function into an
1065 /// actual call. This returns a pair of operands. The first element is the
1066 /// return value for the function (if RetTy is not VoidTy). The second
1067 /// element is the outgoing token chain.
1068 struct ArgListEntry {
1079 ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1080 isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
1082 typedef std::vector<ArgListEntry> ArgListTy;
1083 virtual std::pair<SDValue, SDValue>
1084 LowerCallTo(SDValue Chain, const Type *RetTy, bool RetSExt, bool RetZExt,
1085 bool isVarArg, bool isInreg, unsigned CallingConv,
1086 bool isTailCall, SDValue Callee, ArgListTy &Args,
1089 /// EmitTargetCodeForMemcpy - Emit target-specific code that performs a
1090 /// memcpy. This can be used by targets to provide code sequences for cases
1091 /// that don't fit the target's parameters for simple loads/stores and can be
1092 /// more efficient than using a library call. This function can return a null
1093 /// SDValue if the target declines to use custom code and a different
1094 /// lowering strategy should be used.
1096 /// If AlwaysInline is true, the size is constant and the target should not
1097 /// emit any calls and is strongly encouraged to attempt to emit inline code
1098 /// even if it is beyond the usual threshold because this intrinsic is being
1099 /// expanded in a place where calls are not feasible (e.g. within the prologue
1100 /// for another call). If the target chooses to decline an AlwaysInline
1101 /// request here, legalize will resort to using simple loads and stores.
1103 EmitTargetCodeForMemcpy(SelectionDAG &DAG,
1105 SDValue Op1, SDValue Op2,
1106 SDValue Op3, unsigned Align,
1108 const Value *DstSV, uint64_t DstOff,
1109 const Value *SrcSV, uint64_t SrcOff) {
1113 /// EmitTargetCodeForMemmove - Emit target-specific code that performs a
1114 /// memmove. This can be used by targets to provide code sequences for cases
1115 /// that don't fit the target's parameters for simple loads/stores and can be
1116 /// more efficient than using a library call. This function can return a null
1117 /// SDValue if the target declines to use custom code and a different
1118 /// lowering strategy should be used.
1120 EmitTargetCodeForMemmove(SelectionDAG &DAG,
1122 SDValue Op1, SDValue Op2,
1123 SDValue Op3, unsigned Align,
1124 const Value *DstSV, uint64_t DstOff,
1125 const Value *SrcSV, uint64_t SrcOff) {
1129 /// EmitTargetCodeForMemset - Emit target-specific code that performs a
1130 /// memset. This can be used by targets to provide code sequences for cases
1131 /// that don't fit the target's parameters for simple stores and can be more
1132 /// efficient than using a library call. This function can return a null
1133 /// SDValue if the target declines to use custom code and a different
1134 /// lowering strategy should be used.
1136 EmitTargetCodeForMemset(SelectionDAG &DAG,
1138 SDValue Op1, SDValue Op2,
1139 SDValue Op3, unsigned Align,
1140 const Value *DstSV, uint64_t DstOff) {
1144 /// LowerOperationWrapper - This callback is invoked by the type legalizer
1145 /// to legalize nodes with an illegal operand type but legal result types.
1146 /// It replaces the LowerOperation callback in the type Legalizer.
1147 /// The reason we can not do away with LowerOperation entirely is that
1148 /// LegalizeDAG isn't yet ready to use this callback.
1149 /// TODO: Consider merging with ReplaceNodeResults.
1151 /// The target places new result values for the node in Results (their number
1152 /// and types must exactly match those of the original return values of
1153 /// the node), or leaves Results empty, which indicates that the node is not
1154 /// to be custom lowered after all.
1155 /// The default implementation calls LowerOperation.
1156 virtual void LowerOperationWrapper(SDNode *N,
1157 SmallVectorImpl<SDValue> &Results,
1160 /// LowerOperation - This callback is invoked for operations that are
1161 /// unsupported by the target, which are registered to use 'custom' lowering,
1162 /// and whose defined values are all legal.
1163 /// If the target has no operations that require custom lowering, it need not
1164 /// implement this. The default implementation of this aborts.
1165 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG);
1167 /// ReplaceNodeResults - This callback is invoked when a node result type is
1168 /// illegal for the target, and the operation was registered to use 'custom'
1169 /// lowering for that result type. The target places new result values for
1170 /// the node in Results (their number and types must exactly match those of
1171 /// the original return values of the node), or leaves Results empty, which
1172 /// indicates that the node is not to be custom lowered after all.
1174 /// If the target has no operations that require custom lowering, it need not
1175 /// implement this. The default implementation aborts.
1176 virtual void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
1177 SelectionDAG &DAG) {
1178 assert(0 && "ReplaceNodeResults not implemented for this target!");
1181 /// IsEligibleForTailCallOptimization - Check whether the call is eligible for
1182 /// tail call optimization. Targets which want to do tail call optimization
1183 /// should override this function.
1184 virtual bool IsEligibleForTailCallOptimization(CallSDNode *Call,
1186 SelectionDAG &DAG) const {
1190 /// CheckTailCallReturnConstraints - Check whether CALL node immediatly
1191 /// preceeds the RET node and whether the return uses the result of the node
1192 /// or is a void return. This function can be used by the target to determine
1193 /// eligiblity of tail call optimization.
1194 static bool CheckTailCallReturnConstraints(CallSDNode *TheCall, SDValue Ret) {
1195 unsigned NumOps = Ret.getNumOperands();
1197 (Ret.getOperand(0) == SDValue(TheCall,1) ||
1198 Ret.getOperand(0) == SDValue(TheCall,0))) ||
1200 Ret.getOperand(0) == SDValue(TheCall,
1201 TheCall->getNumValues()-1) &&
1202 Ret.getOperand(1) == SDValue(TheCall,0)))
1207 /// GetPossiblePreceedingTailCall - Get preceeding TailCallNodeOpCode node if
1208 /// it exists. Skip a possible ISD::TokenFactor.
1209 static SDValue GetPossiblePreceedingTailCall(SDValue Chain,
1210 unsigned TailCallNodeOpCode) {
1211 if (Chain.getOpcode() == TailCallNodeOpCode) {
1213 } else if (Chain.getOpcode() == ISD::TokenFactor) {
1214 if (Chain.getNumOperands() &&
1215 Chain.getOperand(0).getOpcode() == TailCallNodeOpCode)
1216 return Chain.getOperand(0);
1221 /// getTargetNodeName() - This method returns the name of a target specific
1223 virtual const char *getTargetNodeName(unsigned Opcode) const;
1225 /// createFastISel - This method returns a target specific FastISel object,
1226 /// or null if the target does not support "fast" ISel.
1228 createFastISel(MachineFunction &,
1229 MachineModuleInfo *, DwarfWriter *,
1230 DenseMap<const Value *, unsigned> &,
1231 DenseMap<const BasicBlock *, MachineBasicBlock *> &,
1232 DenseMap<const AllocaInst *, int> &
1234 , SmallSet<Instruction*, 8> &CatchInfoLost
1240 //===--------------------------------------------------------------------===//
1241 // Inline Asm Support hooks
1244 enum ConstraintType {
1245 C_Register, // Constraint represents specific register(s).
1246 C_RegisterClass, // Constraint represents any of register(s) in class.
1247 C_Memory, // Memory constraint.
1248 C_Other, // Something else.
1249 C_Unknown // Unsupported constraint.
1252 /// AsmOperandInfo - This contains information for each constraint that we are
1254 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
1255 /// ConstraintCode - This contains the actual string for the code, like "m".
1256 /// TargetLowering picks the 'best' code from ConstraintInfo::Codes that
1257 /// most closely matches the operand.
1258 std::string ConstraintCode;
1260 /// ConstraintType - Information about the constraint code, e.g. Register,
1261 /// RegisterClass, Memory, Other, Unknown.
1262 TargetLowering::ConstraintType ConstraintType;
1264 /// CallOperandval - If this is the result output operand or a
1265 /// clobber, this is null, otherwise it is the incoming operand to the
1266 /// CallInst. This gets modified as the asm is processed.
1267 Value *CallOperandVal;
1269 /// ConstraintVT - The ValueType for the operand value.
1272 /// isMatchingInputConstraint - Return true of this is an input operand that
1273 /// is a matching constraint like "4".
1274 bool isMatchingInputConstraint() const;
1276 /// getMatchedOperand - If this is an input matching constraint, this method
1277 /// returns the output operand it matches.
1278 unsigned getMatchedOperand() const;
1280 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
1281 : InlineAsm::ConstraintInfo(info),
1282 ConstraintType(TargetLowering::C_Unknown),
1283 CallOperandVal(0), ConstraintVT(MVT::Other) {
1287 /// ComputeConstraintToUse - Determines the constraint code and constraint
1288 /// type to use for the specific AsmOperandInfo, setting
1289 /// OpInfo.ConstraintCode and OpInfo.ConstraintType. If the actual operand
1290 /// being passed in is available, it can be passed in as Op, otherwise an
1291 /// empty SDValue can be passed. If hasMemory is true it means one of the asm
1292 /// constraint of the inline asm instruction being processed is 'm'.
1293 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
1296 SelectionDAG *DAG = 0) const;
1298 /// getConstraintType - Given a constraint, return the type of constraint it
1299 /// is for this target.
1300 virtual ConstraintType getConstraintType(const std::string &Constraint) const;
1302 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1303 /// return a list of registers that can be used to satisfy the constraint.
1304 /// This should only be used for C_RegisterClass constraints.
1305 virtual std::vector<unsigned>
1306 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1309 /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
1310 /// {edx}), return the register number and the register class for the
1313 /// Given a register class constraint, like 'r', if this corresponds directly
1314 /// to an LLVM register class, return a register of 0 and the register class
1317 /// This should only be used for C_Register constraints. On error,
1318 /// this returns a register number of 0 and a null register class pointer..
1319 virtual std::pair<unsigned, const TargetRegisterClass*>
1320 getRegForInlineAsmConstraint(const std::string &Constraint,
1323 /// LowerXConstraint - try to replace an X constraint, which matches anything,
1324 /// with another that has more specific requirements based on the type of the
1325 /// corresponding operand. This returns null if there is no replacement to
1327 virtual const char *LowerXConstraint(MVT ConstraintVT) const;
1329 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1330 /// vector. If it is invalid, don't add anything to Ops. If hasMemory is true
1331 /// it means one of the asm constraint of the inline asm instruction being
1332 /// processed is 'm'.
1333 virtual void LowerAsmOperandForConstraint(SDValue Op, char ConstraintLetter,
1335 std::vector<SDValue> &Ops,
1336 SelectionDAG &DAG) const;
1338 //===--------------------------------------------------------------------===//
1342 // EmitInstrWithCustomInserter - This method should be implemented by targets
1343 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1344 // instructions are special in various ways, which require special support to
1345 // insert. The specified MachineInstr is created but not inserted into any
1346 // basic blocks, and the scheduler passes ownership of it to this method.
1347 virtual MachineBasicBlock *EmitInstrWithCustomInserter(MachineInstr *MI,
1348 MachineBasicBlock *MBB);
1350 //===--------------------------------------------------------------------===//
1351 // Addressing mode description hooks (used by LSR etc).
1354 /// AddrMode - This represents an addressing mode of:
1355 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1356 /// If BaseGV is null, there is no BaseGV.
1357 /// If BaseOffs is zero, there is no base offset.
1358 /// If HasBaseReg is false, there is no base register.
1359 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1363 GlobalValue *BaseGV;
1367 AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1370 /// isLegalAddressingMode - Return true if the addressing mode represented by
1371 /// AM is legal for this target, for a load/store of the specified type.
1372 /// TODO: Handle pre/postinc as well.
1373 virtual bool isLegalAddressingMode(const AddrMode &AM, const Type *Ty) const;
1375 /// isTruncateFree - Return true if it's free to truncate a value of
1376 /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1377 /// register EAX to i16 by referencing its sub-register AX.
1378 virtual bool isTruncateFree(const Type *Ty1, const Type *Ty2) const {
1382 virtual bool isTruncateFree(MVT VT1, MVT VT2) const {
1386 //===--------------------------------------------------------------------===//
1387 // Div utility functions
1389 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG,
1390 std::vector<SDNode*>* Created) const;
1391 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG,
1392 std::vector<SDNode*>* Created) const;
1395 //===--------------------------------------------------------------------===//
1396 // Runtime Library hooks
1399 /// setLibcallName - Rename the default libcall routine name for the specified
1401 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1402 LibcallRoutineNames[Call] = Name;
1405 /// getLibcallName - Get the libcall routine name for the specified libcall.
1407 const char *getLibcallName(RTLIB::Libcall Call) const {
1408 return LibcallRoutineNames[Call];
1411 /// setCmpLibcallCC - Override the default CondCode to be used to test the
1412 /// result of the comparison libcall against zero.
1413 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1414 CmpLibcallCCs[Call] = CC;
1417 /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1418 /// the comparison libcall against zero.
1419 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1420 return CmpLibcallCCs[Call];
1425 const TargetData *TD;
1427 /// PointerTy - The type to use for pointers, usually i32 or i64.
1431 /// IsLittleEndian - True if this is a little endian target.
1433 bool IsLittleEndian;
1435 /// UsesGlobalOffsetTable - True if this target uses a GOT for PIC codegen.
1437 bool UsesGlobalOffsetTable;
1439 /// SelectIsExpensive - Tells the code generator not to expand operations
1440 /// into sequences that use the select operations if possible.
1441 bool SelectIsExpensive;
1443 /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1444 /// constants into a sequence of muls, adds, and shifts. This is a hack until
1445 /// a real cost model is in place. If we ever optimize for size, this will be
1446 /// set to true unconditionally.
1449 /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1450 /// srl/add/sra for a signed divide by power of two, and let the target handle
1452 bool Pow2DivIsCheap;
1454 /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1455 /// llvm.setjmp. Defaults to false.
1456 bool UseUnderscoreSetJmp;
1458 /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1459 /// llvm.longjmp. Defaults to false.
1460 bool UseUnderscoreLongJmp;
1462 /// ShiftAmountTy - The type to use for shift amounts, usually i8 or whatever
1466 OutOfRangeShiftAmount ShiftAmtHandling;
1468 /// BooleanContents - Information about the contents of the high-bits in
1469 /// boolean values held in a type wider than i1. See getBooleanContents.
1470 BooleanContent BooleanContents;
1472 /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1473 /// total cycles or lowest register usage.
1474 SchedPreference SchedPreferenceInfo;
1476 /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1477 unsigned JumpBufSize;
1479 /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1481 unsigned JumpBufAlignment;
1483 /// IfCvtBlockSizeLimit - The maximum allowed size for a block to be
1485 unsigned IfCvtBlockSizeLimit;
1487 /// IfCvtDupBlockSizeLimit - The maximum allowed size for a block to be
1488 /// duplicated during if-conversion.
1489 unsigned IfCvtDupBlockSizeLimit;
1491 /// PrefLoopAlignment - The perferred loop alignment.
1493 unsigned PrefLoopAlignment;
1495 /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1496 /// specifies the register that llvm.savestack/llvm.restorestack should save
1498 unsigned StackPointerRegisterToSaveRestore;
1500 /// ExceptionPointerRegister - If set to a physical register, this specifies
1501 /// the register that receives the exception address on entry to a landing
1503 unsigned ExceptionPointerRegister;
1505 /// ExceptionSelectorRegister - If set to a physical register, this specifies
1506 /// the register that receives the exception typeid on entry to a landing
1508 unsigned ExceptionSelectorRegister;
1510 /// RegClassForVT - This indicates the default register class to use for
1511 /// each ValueType the target supports natively.
1512 TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1513 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1514 MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1516 /// TransformToType - For any value types we are promoting or expanding, this
1517 /// contains the value type that we are changing to. For Expanded types, this
1518 /// contains one step of the expand (e.g. i64 -> i32), even if there are
1519 /// multiple steps required (e.g. i64 -> i16). For types natively supported
1520 /// by the system, this holds the same type (e.g. i32 -> i32).
1521 MVT TransformToType[MVT::LAST_VALUETYPE];
1523 /// OpActions - For each operation and each value type, keep a LegalizeAction
1524 /// that indicates how instruction selection should deal with the operation.
1525 /// Most operations are Legal (aka, supported natively by the target), but
1526 /// operations that are not should be described. Note that operations on
1527 /// non-legal value types are not described here.
1528 uint64_t OpActions[ISD::BUILTIN_OP_END];
1530 /// LoadExtActions - For each load of load extension type and each value type,
1531 /// keep a LegalizeAction that indicates how instruction selection should deal
1533 uint64_t LoadExtActions[ISD::LAST_LOADEXT_TYPE];
1535 /// TruncStoreActions - For each truncating store, keep a LegalizeAction that
1536 /// indicates how instruction selection should deal with the store.
1537 uint64_t TruncStoreActions[MVT::LAST_VALUETYPE];
1539 /// IndexedModeActions - For each indexed mode and each value type, keep a
1540 /// pair of LegalizeAction that indicates how instruction selection should
1541 /// deal with the load / store.
1542 uint64_t IndexedModeActions[2][ISD::LAST_INDEXED_MODE];
1544 /// ConvertActions - For each conversion from source type to destination type,
1545 /// keep a LegalizeAction that indicates how instruction selection should
1546 /// deal with the conversion.
1547 /// Currently, this is used only for floating->floating conversions
1548 /// (FP_EXTEND and FP_ROUND).
1549 uint64_t ConvertActions[MVT::LAST_VALUETYPE];
1551 /// CondCodeActions - For each condition code (ISD::CondCode) keep a
1552 /// LegalizeAction that indicates how instruction selection should
1553 /// deal with the condition code.
1554 uint64_t CondCodeActions[ISD::SETCC_INVALID];
1556 ValueTypeActionImpl ValueTypeActions;
1558 std::vector<APFloat> LegalFPImmediates;
1560 std::vector<std::pair<MVT, TargetRegisterClass*> > AvailableRegClasses;
1562 /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
1563 /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
1564 /// which sets a bit in this array.
1566 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
1568 /// PromoteToType - For operations that must be promoted to a specific type,
1569 /// this holds the destination type. This map should be sparse, so don't hold
1572 /// Targets add entries to this map with AddPromotedToType(..), clients access
1573 /// this with getTypeToPromoteTo(..).
1574 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1577 /// LibcallRoutineNames - Stores the name each libcall.
1579 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1581 /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
1582 /// of each of the comparison libcall against zero.
1583 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1586 /// When lowering @llvm.memset this field specifies the maximum number of
1587 /// store operations that may be substituted for the call to memset. Targets
1588 /// must set this value based on the cost threshold for that target. Targets
1589 /// should assume that the memset will be done using as many of the largest
1590 /// store operations first, followed by smaller ones, if necessary, per
1591 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1592 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1593 /// store. This only applies to setting a constant array of a constant size.
1594 /// @brief Specify maximum number of store instructions per memset call.
1595 unsigned maxStoresPerMemset;
1597 /// When lowering @llvm.memcpy this field specifies the maximum number of
1598 /// store operations that may be substituted for a call to memcpy. Targets
1599 /// must set this value based on the cost threshold for that target. Targets
1600 /// should assume that the memcpy will be done using as many of the largest
1601 /// store operations first, followed by smaller ones, if necessary, per
1602 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1603 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1604 /// and one 1-byte store. This only applies to copying a constant array of
1606 /// @brief Specify maximum bytes of store instructions per memcpy call.
1607 unsigned maxStoresPerMemcpy;
1609 /// When lowering @llvm.memmove this field specifies the maximum number of
1610 /// store instructions that may be substituted for a call to memmove. Targets
1611 /// must set this value based on the cost threshold for that target. Targets
1612 /// should assume that the memmove will be done using as many of the largest
1613 /// store operations first, followed by smaller ones, if necessary, per
1614 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1615 /// with 8-bit alignment would result in nine 1-byte stores. This only
1616 /// applies to copying a constant array of constant size.
1617 /// @brief Specify maximum bytes of store instructions per memmove call.
1618 unsigned maxStoresPerMemmove;
1620 /// This field specifies whether the target machine permits unaligned memory
1621 /// accesses. This is used, for example, to determine the size of store
1622 /// operations when copying small arrays and other similar tasks.
1623 /// @brief Indicate whether the target permits unaligned memory accesses.
1624 bool allowUnalignedMemoryAccesses;
1626 } // end llvm namespace