1 //===-- llvm/Target/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file describes how to lower LLVM code to machine code. This has two
13 // 1. Which ValueTypes are natively supported by the target.
14 // 2. Which operations are supported for supported ValueTypes.
15 // 3. Cost thresholds for alternative implementations of certain operations.
17 // In addition it has a few other components, like information about FP
20 //===----------------------------------------------------------------------===//
22 #ifndef LLVM_TARGET_TARGETLOWERING_H
23 #define LLVM_TARGET_TARGETLOWERING_H
25 #include "llvm/InlineAsm.h"
26 #include "llvm/CodeGen/SelectionDAGNodes.h"
27 #include "llvm/CodeGen/RuntimeLibcalls.h"
28 #include "llvm/ADT/APFloat.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/DebugLoc.h"
34 #include "llvm/Target/TargetMachine.h"
44 class MachineBasicBlock;
45 class MachineFunction;
46 class MachineFrameInfo;
48 class MachineModuleInfo;
55 class TargetRegisterClass;
56 class TargetSubtarget;
57 class TargetLoweringObjectFile;
60 // FIXME: should this be here?
69 TLSModel::Model getTLSModel(const GlobalValue *GV, Reloc::Model reloc);
72 //===----------------------------------------------------------------------===//
73 /// TargetLowering - This class defines information used to lower LLVM code to
74 /// legal SelectionDAG operators that the target instruction selector can accept
77 /// This class also defines callbacks that targets must implement to lower
78 /// target-specific constructs to SelectionDAG operators.
80 class TargetLowering {
81 TargetLowering(const TargetLowering&); // DO NOT IMPLEMENT
82 void operator=(const TargetLowering&); // DO NOT IMPLEMENT
84 /// LegalizeAction - This enum indicates whether operations are valid for a
85 /// target, and if not, what action should be used to make them valid.
87 Legal, // The target natively supports this operation.
88 Promote, // This operation should be executed in a larger type.
89 Expand, // Try to expand this to other ops, otherwise use a libcall.
90 Custom // Use the LowerOperation hook to implement custom lowering.
93 enum BooleanContent { // How the target represents true/false values.
94 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
95 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
96 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
99 enum SchedPreference {
100 SchedulingForLatency, // Scheduling for shortest total latency.
101 SchedulingForRegPressure // Scheduling for lowest register pressure.
104 /// NOTE: The constructor takes ownership of TLOF.
105 explicit TargetLowering(TargetMachine &TM, TargetLoweringObjectFile *TLOF);
106 virtual ~TargetLowering();
108 TargetMachine &getTargetMachine() const { return TM; }
109 const TargetData *getTargetData() const { return TD; }
110 const TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; }
112 bool isBigEndian() const { return !IsLittleEndian; }
113 bool isLittleEndian() const { return IsLittleEndian; }
114 MVT getPointerTy() const { return PointerTy; }
115 MVT getShiftAmountTy() const { return ShiftAmountTy; }
117 /// usesGlobalOffsetTable - Return true if this target uses a GOT for PIC
119 bool usesGlobalOffsetTable() const { return UsesGlobalOffsetTable; }
121 /// isSelectExpensive - Return true if the select operation is expensive for
123 bool isSelectExpensive() const { return SelectIsExpensive; }
125 /// isIntDivCheap() - Return true if integer divide is usually cheaper than
126 /// a sequence of several shifts, adds, and multiplies for this target.
127 bool isIntDivCheap() const { return IntDivIsCheap; }
129 /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
131 bool isPow2DivCheap() const { return Pow2DivIsCheap; }
133 /// getSetCCResultType - Return the ValueType of the result of SETCC
134 /// operations. Also used to obtain the target's preferred type for
135 /// the condition operand of SELECT and BRCOND nodes. In the case of
136 /// BRCOND the argument passed is MVT::Other since there are no other
137 /// operands to get a type hint from.
138 virtual MVT getSetCCResultType(MVT VT) const;
140 /// getBooleanContents - For targets without i1 registers, this gives the
141 /// nature of the high-bits of boolean values held in types wider than i1.
142 /// "Boolean values" are special true/false values produced by nodes like
143 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
144 /// Not to be confused with general values promoted from i1.
145 BooleanContent getBooleanContents() const { return BooleanContents;}
147 /// getSchedulingPreference - Return target scheduling preference.
148 SchedPreference getSchedulingPreference() const {
149 return SchedPreferenceInfo;
152 /// getRegClassFor - Return the register class that should be used for the
153 /// specified value type. This may only be called on legal types.
154 TargetRegisterClass *getRegClassFor(MVT VT) const {
155 assert((unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
156 TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT()];
157 assert(RC && "This value type is not natively supported!");
161 /// isTypeLegal - Return true if the target has native support for the
162 /// specified value type. This means that it has a register that directly
163 /// holds it without promotions or expansions.
164 bool isTypeLegal(MVT VT) const {
165 assert(!VT.isSimple() ||
166 (unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
167 return VT.isSimple() && RegClassForVT[VT.getSimpleVT()] != 0;
170 class ValueTypeActionImpl {
171 /// ValueTypeActions - This is a bitvector that contains two bits for each
172 /// value type, where the two bits correspond to the LegalizeAction enum.
173 /// This can be queried with "getTypeAction(VT)".
174 /// dimension by (MVT::MAX_ALLOWED_VALUETYPE/32) * 2
175 uint32_t ValueTypeActions[(MVT::MAX_ALLOWED_VALUETYPE/32)*2];
177 ValueTypeActionImpl() {
178 ValueTypeActions[0] = ValueTypeActions[1] = 0;
179 ValueTypeActions[2] = ValueTypeActions[3] = 0;
181 ValueTypeActionImpl(const ValueTypeActionImpl &RHS) {
182 ValueTypeActions[0] = RHS.ValueTypeActions[0];
183 ValueTypeActions[1] = RHS.ValueTypeActions[1];
184 ValueTypeActions[2] = RHS.ValueTypeActions[2];
185 ValueTypeActions[3] = RHS.ValueTypeActions[3];
188 LegalizeAction getTypeAction(MVT VT) const {
189 if (VT.isExtended()) {
191 return VT.isPow2VectorType() ? Expand : Promote;
194 // First promote to a power-of-two size, then expand if necessary.
195 return VT == VT.getRoundIntegerType() ? Expand : Promote;
196 assert(0 && "Unsupported extended type!");
199 unsigned I = VT.getSimpleVT();
200 assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
201 return (LegalizeAction)((ValueTypeActions[I>>4] >> ((2*I) & 31)) & 3);
203 void setTypeAction(MVT VT, LegalizeAction Action) {
204 unsigned I = VT.getSimpleVT();
205 assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
206 ValueTypeActions[I>>4] |= Action << ((I*2) & 31);
210 const ValueTypeActionImpl &getValueTypeActions() const {
211 return ValueTypeActions;
214 /// getTypeAction - Return how we should legalize values of this type, either
215 /// it is already legal (return 'Legal') or we need to promote it to a larger
216 /// type (return 'Promote'), or we need to expand it into multiple registers
217 /// of smaller integer type (return 'Expand'). 'Custom' is not an option.
218 LegalizeAction getTypeAction(MVT VT) const {
219 return ValueTypeActions.getTypeAction(VT);
222 /// getTypeToTransformTo - For types supported by the target, this is an
223 /// identity function. For types that must be promoted to larger types, this
224 /// returns the larger type to promote to. For integer types that are larger
225 /// than the largest integer register, this contains one step in the expansion
226 /// to get to the smaller register. For illegal floating point types, this
227 /// returns the integer type to transform to.
228 MVT getTypeToTransformTo(MVT VT) const {
230 assert((unsigned)VT.getSimpleVT() < array_lengthof(TransformToType));
231 MVT NVT = TransformToType[VT.getSimpleVT()];
232 assert(getTypeAction(NVT) != Promote &&
233 "Promote may not follow Expand or Promote");
238 MVT NVT = VT.getPow2VectorType();
240 // Vector length is a power of 2 - split to half the size.
241 unsigned NumElts = VT.getVectorNumElements();
242 MVT EltVT = VT.getVectorElementType();
243 return (NumElts == 1) ? EltVT : MVT::getVectorVT(EltVT, NumElts / 2);
245 // Promote to a power of two size, avoiding multi-step promotion.
246 return getTypeAction(NVT) == Promote ? getTypeToTransformTo(NVT) : NVT;
247 } else if (VT.isInteger()) {
248 MVT NVT = VT.getRoundIntegerType();
250 // Size is a power of two - expand to half the size.
251 return MVT::getIntegerVT(VT.getSizeInBits() / 2);
253 // Promote to a power of two size, avoiding multi-step promotion.
254 return getTypeAction(NVT) == Promote ? getTypeToTransformTo(NVT) : NVT;
256 assert(0 && "Unsupported extended type!");
257 return MVT(MVT::Other); // Not reached
260 /// getTypeToExpandTo - For types supported by the target, this is an
261 /// identity function. For types that must be expanded (i.e. integer types
262 /// that are larger than the largest integer register or illegal floating
263 /// point types), this returns the largest legal type it will be expanded to.
264 MVT getTypeToExpandTo(MVT VT) const {
265 assert(!VT.isVector());
267 switch (getTypeAction(VT)) {
271 VT = getTypeToTransformTo(VT);
274 assert(false && "Type is not legal nor is it to be expanded!");
281 /// getVectorTypeBreakdown - Vector types are broken down into some number of
282 /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
283 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
284 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
286 /// This method returns the number of registers needed, and the VT for each
287 /// register. It also returns the VT and quantity of the intermediate values
288 /// before they are promoted/expanded.
290 unsigned getVectorTypeBreakdown(MVT VT,
292 unsigned &NumIntermediates,
293 MVT &RegisterVT) const;
295 /// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the
296 /// intrinsic will need to map to a MemIntrinsicNode (touches memory). If
297 /// this is the case, it returns true and store the intrinsic
298 /// information into the IntrinsicInfo that was passed to the function.
299 typedef struct IntrinsicInfo {
300 unsigned opc; // target opcode
301 MVT memVT; // memory VT
302 const Value* ptrVal; // value representing memory location
303 int offset; // offset off of ptrVal
304 unsigned align; // alignment
305 bool vol; // is volatile?
306 bool readMem; // reads memory?
307 bool writeMem; // writes memory?
310 virtual bool getTgtMemIntrinsic(IntrinsicInfo& Info,
311 CallInst &I, unsigned Intrinsic) {
315 /// getWidenVectorType: given a vector type, returns the type to widen to
316 /// (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
317 /// If there is no vector type that we want to widen to, returns MVT::Other
318 /// When and were to widen is target dependent based on the cost of
319 /// scalarizing vs using the wider vector type.
320 virtual MVT getWidenVectorType(MVT VT) const;
322 typedef std::vector<APFloat>::const_iterator legal_fpimm_iterator;
323 legal_fpimm_iterator legal_fpimm_begin() const {
324 return LegalFPImmediates.begin();
326 legal_fpimm_iterator legal_fpimm_end() const {
327 return LegalFPImmediates.end();
330 /// isShuffleMaskLegal - Targets can use this to indicate that they only
331 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
332 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
333 /// are assumed to be legal.
334 virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &Mask,
339 /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
340 /// used by Targets can use this to indicate if there is a suitable
341 /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
343 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
348 /// getOperationAction - Return how this operation should be treated: either
349 /// it is legal, needs to be promoted to a larger size, needs to be
350 /// expanded to some other code sequence, or the target has a custom expander
352 LegalizeAction getOperationAction(unsigned Op, MVT VT) const {
353 if (VT.isExtended()) return Expand;
354 assert(Op < array_lengthof(OpActions[0]) &&
355 (unsigned)VT.getSimpleVT() < sizeof(OpActions[0][0])*8 &&
356 "Table isn't big enough!");
357 unsigned I = (unsigned) VT.getSimpleVT();
360 return (LegalizeAction)((OpActions[I][Op] >> (J*2) ) & 3);
363 /// isOperationLegalOrCustom - Return true if the specified operation is
364 /// legal on this target or can be made legal with custom lowering. This
365 /// is used to help guide high-level lowering decisions.
366 bool isOperationLegalOrCustom(unsigned Op, MVT VT) const {
367 return (VT == MVT::Other || isTypeLegal(VT)) &&
368 (getOperationAction(Op, VT) == Legal ||
369 getOperationAction(Op, VT) == Custom);
372 /// isOperationLegal - Return true if the specified operation is legal on this
374 bool isOperationLegal(unsigned Op, MVT VT) const {
375 return (VT == MVT::Other || isTypeLegal(VT)) &&
376 getOperationAction(Op, VT) == Legal;
379 /// getLoadExtAction - Return how this load with extension should be treated:
380 /// either it is legal, needs to be promoted to a larger size, needs to be
381 /// expanded to some other code sequence, or the target has a custom expander
383 LegalizeAction getLoadExtAction(unsigned LType, MVT VT) const {
384 assert(LType < array_lengthof(LoadExtActions) &&
385 (unsigned)VT.getSimpleVT() < sizeof(LoadExtActions[0])*4 &&
386 "Table isn't big enough!");
387 return (LegalizeAction)((LoadExtActions[LType] >> (2*VT.getSimpleVT())) & 3);
390 /// isLoadExtLegal - Return true if the specified load with extension is legal
392 bool isLoadExtLegal(unsigned LType, MVT VT) const {
393 return VT.isSimple() &&
394 (getLoadExtAction(LType, VT) == Legal ||
395 getLoadExtAction(LType, VT) == Custom);
398 /// getTruncStoreAction - Return how this store with truncation should be
399 /// treated: either it is legal, needs to be promoted to a larger size, needs
400 /// to be expanded to some other code sequence, or the target has a custom
402 LegalizeAction getTruncStoreAction(MVT ValVT,
404 assert((unsigned)ValVT.getSimpleVT() < array_lengthof(TruncStoreActions) &&
405 (unsigned)MemVT.getSimpleVT() < sizeof(TruncStoreActions[0])*4 &&
406 "Table isn't big enough!");
407 return (LegalizeAction)((TruncStoreActions[ValVT.getSimpleVT()] >>
408 (2*MemVT.getSimpleVT())) & 3);
411 /// isTruncStoreLegal - Return true if the specified store with truncation is
412 /// legal on this target.
413 bool isTruncStoreLegal(MVT ValVT, MVT MemVT) const {
414 return isTypeLegal(ValVT) && MemVT.isSimple() &&
415 (getTruncStoreAction(ValVT, MemVT) == Legal ||
416 getTruncStoreAction(ValVT, MemVT) == Custom);
419 /// getIndexedLoadAction - Return how the indexed load should be treated:
420 /// either it is legal, needs to be promoted to a larger size, needs to be
421 /// expanded to some other code sequence, or the target has a custom expander
424 getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
425 assert( IdxMode < array_lengthof(IndexedModeActions[0][0]) &&
426 ((unsigned)VT.getSimpleVT()) < MVT::LAST_VALUETYPE &&
427 "Table isn't big enough!");
428 return (LegalizeAction)((IndexedModeActions[(unsigned)VT.getSimpleVT()][0][IdxMode]));
431 /// isIndexedLoadLegal - Return true if the specified indexed load is legal
433 bool isIndexedLoadLegal(unsigned IdxMode, MVT VT) const {
434 return VT.isSimple() &&
435 (getIndexedLoadAction(IdxMode, VT) == Legal ||
436 getIndexedLoadAction(IdxMode, VT) == Custom);
439 /// getIndexedStoreAction - Return how the indexed store should be treated:
440 /// either it is legal, needs to be promoted to a larger size, needs to be
441 /// expanded to some other code sequence, or the target has a custom expander
444 getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
445 assert(IdxMode < array_lengthof(IndexedModeActions[0][1]) &&
446 (unsigned)VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
447 "Table isn't big enough!");
448 return (LegalizeAction)((IndexedModeActions[(unsigned)VT.getSimpleVT()][1][IdxMode]));
451 /// isIndexedStoreLegal - Return true if the specified indexed load is legal
453 bool isIndexedStoreLegal(unsigned IdxMode, MVT VT) const {
454 return VT.isSimple() &&
455 (getIndexedStoreAction(IdxMode, VT) == Legal ||
456 getIndexedStoreAction(IdxMode, VT) == Custom);
459 /// getConvertAction - Return how the conversion should be treated:
460 /// either it is legal, needs to be promoted to a larger size, needs to be
461 /// expanded to some other code sequence, or the target has a custom expander
464 getConvertAction(MVT FromVT, MVT ToVT) const {
465 assert((unsigned)FromVT.getSimpleVT() < array_lengthof(ConvertActions) &&
466 (unsigned)ToVT.getSimpleVT() < sizeof(ConvertActions[0])*4 &&
467 "Table isn't big enough!");
468 return (LegalizeAction)((ConvertActions[FromVT.getSimpleVT()] >>
469 (2*ToVT.getSimpleVT())) & 3);
472 /// isConvertLegal - Return true if the specified conversion is legal
474 bool isConvertLegal(MVT FromVT, MVT ToVT) const {
475 return isTypeLegal(FromVT) && isTypeLegal(ToVT) &&
476 (getConvertAction(FromVT, ToVT) == Legal ||
477 getConvertAction(FromVT, ToVT) == Custom);
480 /// getCondCodeAction - Return how the condition code should be treated:
481 /// either it is legal, needs to be expanded to some other code sequence,
482 /// or the target has a custom expander for it.
484 getCondCodeAction(ISD::CondCode CC, MVT VT) const {
485 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
486 (unsigned)VT.getSimpleVT() < sizeof(CondCodeActions[0])*4 &&
487 "Table isn't big enough!");
488 LegalizeAction Action = (LegalizeAction)
489 ((CondCodeActions[CC] >> (2*VT.getSimpleVT())) & 3);
490 assert(Action != Promote && "Can't promote condition code!");
494 /// isCondCodeLegal - Return true if the specified condition code is legal
496 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
497 return getCondCodeAction(CC, VT) == Legal ||
498 getCondCodeAction(CC, VT) == Custom;
502 /// getTypeToPromoteTo - If the action for this operation is to promote, this
503 /// method returns the ValueType to promote to.
504 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
505 assert(getOperationAction(Op, VT) == Promote &&
506 "This operation isn't promoted!");
508 // See if this has an explicit type specified.
509 std::map<std::pair<unsigned, MVT::SimpleValueType>,
510 MVT::SimpleValueType>::const_iterator PTTI =
511 PromoteToType.find(std::make_pair(Op, VT.getSimpleVT()));
512 if (PTTI != PromoteToType.end()) return PTTI->second;
514 assert((VT.isInteger() || VT.isFloatingPoint()) &&
515 "Cannot autopromote this type, add it with AddPromotedToType.");
519 NVT = (MVT::SimpleValueType)(NVT.getSimpleVT()+1);
520 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
521 "Didn't find type to promote to!");
522 } while (!isTypeLegal(NVT) ||
523 getOperationAction(Op, NVT) == Promote);
527 /// getValueType - Return the MVT corresponding to this LLVM type.
528 /// This is fixed by the LLVM operations except for the pointer size. If
529 /// AllowUnknown is true, this will return MVT::Other for types with no MVT
530 /// counterpart (e.g. structs), otherwise it will assert.
531 MVT getValueType(const Type *Ty, bool AllowUnknown = false) const {
532 MVT VT = MVT::getMVT(Ty, AllowUnknown);
533 return VT == MVT::iPTR ? PointerTy : VT;
536 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
537 /// function arguments in the caller parameter area. This is the actual
538 /// alignment, not its logarithm.
539 virtual unsigned getByValTypeAlignment(const Type *Ty) const;
541 /// getRegisterType - Return the type of registers that this ValueType will
542 /// eventually require.
543 MVT getRegisterType(MVT VT) const {
545 assert((unsigned)VT.getSimpleVT() < array_lengthof(RegisterTypeForVT));
546 return RegisterTypeForVT[VT.getSimpleVT()];
550 unsigned NumIntermediates;
551 (void)getVectorTypeBreakdown(VT, VT1, NumIntermediates, RegisterVT);
554 if (VT.isInteger()) {
555 return getRegisterType(getTypeToTransformTo(VT));
557 assert(0 && "Unsupported extended type!");
558 return MVT(MVT::Other); // Not reached
561 /// getNumRegisters - Return the number of registers that this ValueType will
562 /// eventually require. This is one for any types promoted to live in larger
563 /// registers, but may be more than one for types (like i64) that are split
564 /// into pieces. For types like i140, which are first promoted then expanded,
565 /// it is the number of registers needed to hold all the bits of the original
566 /// type. For an i140 on a 32 bit machine this means 5 registers.
567 unsigned getNumRegisters(MVT VT) const {
569 assert((unsigned)VT.getSimpleVT() < array_lengthof(NumRegistersForVT));
570 return NumRegistersForVT[VT.getSimpleVT()];
574 unsigned NumIntermediates;
575 return getVectorTypeBreakdown(VT, VT1, NumIntermediates, VT2);
577 if (VT.isInteger()) {
578 unsigned BitWidth = VT.getSizeInBits();
579 unsigned RegWidth = getRegisterType(VT).getSizeInBits();
580 return (BitWidth + RegWidth - 1) / RegWidth;
582 assert(0 && "Unsupported extended type!");
583 return 0; // Not reached
586 /// ShouldShrinkFPConstant - If true, then instruction selection should
587 /// seek to shrink the FP constant of the specified type to a smaller type
588 /// in order to save space and / or reduce runtime.
589 virtual bool ShouldShrinkFPConstant(MVT VT) const { return true; }
591 /// hasTargetDAGCombine - If true, the target has custom DAG combine
592 /// transformations that it can perform for the specified node.
593 bool hasTargetDAGCombine(ISD::NodeType NT) const {
594 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
595 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
598 /// This function returns the maximum number of store operations permitted
599 /// to replace a call to llvm.memset. The value is set by the target at the
600 /// performance threshold for such a replacement.
601 /// @brief Get maximum # of store operations permitted for llvm.memset
602 unsigned getMaxStoresPerMemset() const { return maxStoresPerMemset; }
604 /// This function returns the maximum number of store operations permitted
605 /// to replace a call to llvm.memcpy. The value is set by the target at the
606 /// performance threshold for such a replacement.
607 /// @brief Get maximum # of store operations permitted for llvm.memcpy
608 unsigned getMaxStoresPerMemcpy() const { return maxStoresPerMemcpy; }
610 /// This function returns the maximum number of store operations permitted
611 /// to replace a call to llvm.memmove. The value is set by the target at the
612 /// performance threshold for such a replacement.
613 /// @brief Get maximum # of store operations permitted for llvm.memmove
614 unsigned getMaxStoresPerMemmove() const { return maxStoresPerMemmove; }
616 /// This function returns true if the target allows unaligned memory accesses.
617 /// This is used, for example, in situations where an array copy/move/set is
618 /// converted to a sequence of store operations. It's use helps to ensure that
619 /// such replacements don't generate code that causes an alignment error
620 /// (trap) on the target machine.
621 /// @brief Determine if the target supports unaligned memory accesses.
622 bool allowsUnalignedMemoryAccesses() const {
623 return allowUnalignedMemoryAccesses;
626 /// This function returns true if the target would benefit from code placement
628 /// @brief Determine if the target should perform code placement optimization.
629 bool shouldOptimizeCodePlacement() const {
630 return benefitFromCodePlacementOpt;
633 /// getOptimalMemOpType - Returns the target specific optimal type for load
634 /// and store operations as a result of memset, memcpy, and memmove lowering.
635 /// It returns MVT::iAny if SelectionDAG should be responsible for
637 virtual MVT getOptimalMemOpType(uint64_t Size, unsigned Align,
638 bool isSrcConst, bool isSrcStr,
639 SelectionDAG &DAG) const {
643 /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
644 /// to implement llvm.setjmp.
645 bool usesUnderscoreSetJmp() const {
646 return UseUnderscoreSetJmp;
649 /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
650 /// to implement llvm.longjmp.
651 bool usesUnderscoreLongJmp() const {
652 return UseUnderscoreLongJmp;
655 /// getStackPointerRegisterToSaveRestore - If a physical register, this
656 /// specifies the register that llvm.savestack/llvm.restorestack should save
658 unsigned getStackPointerRegisterToSaveRestore() const {
659 return StackPointerRegisterToSaveRestore;
662 /// getExceptionAddressRegister - If a physical register, this returns
663 /// the register that receives the exception address on entry to a landing
665 unsigned getExceptionAddressRegister() const {
666 return ExceptionPointerRegister;
669 /// getExceptionSelectorRegister - If a physical register, this returns
670 /// the register that receives the exception typeid on entry to a landing
672 unsigned getExceptionSelectorRegister() const {
673 return ExceptionSelectorRegister;
676 /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
677 /// set, the default is 200)
678 unsigned getJumpBufSize() const {
682 /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
683 /// (if never set, the default is 0)
684 unsigned getJumpBufAlignment() const {
685 return JumpBufAlignment;
688 /// getIfCvtBlockLimit - returns the target specific if-conversion block size
689 /// limit. Any block whose size is greater should not be predicated.
690 unsigned getIfCvtBlockSizeLimit() const {
691 return IfCvtBlockSizeLimit;
694 /// getIfCvtDupBlockLimit - returns the target specific size limit for a
695 /// block to be considered for duplication. Any block whose size is greater
696 /// should not be duplicated to facilitate its predication.
697 unsigned getIfCvtDupBlockSizeLimit() const {
698 return IfCvtDupBlockSizeLimit;
701 /// getPrefLoopAlignment - return the preferred loop alignment.
703 unsigned getPrefLoopAlignment() const {
704 return PrefLoopAlignment;
707 /// getPreIndexedAddressParts - returns true by value, base pointer and
708 /// offset pointer and addressing mode by reference if the node's address
709 /// can be legally represented as pre-indexed load / store address.
710 virtual bool getPreIndexedAddressParts(SDNode *N, SDValue &Base,
712 ISD::MemIndexedMode &AM,
713 SelectionDAG &DAG) const {
717 /// getPostIndexedAddressParts - returns true by value, base pointer and
718 /// offset pointer and addressing mode by reference if this node can be
719 /// combined with a load / store to form a post-indexed load / store.
720 virtual bool getPostIndexedAddressParts(SDNode *N, SDNode *Op,
721 SDValue &Base, SDValue &Offset,
722 ISD::MemIndexedMode &AM,
723 SelectionDAG &DAG) const {
727 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
729 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
730 SelectionDAG &DAG) const;
732 /// isOffsetFoldingLegal - Return true if folding a constant offset
733 /// with the given GlobalAddress is legal. It is frequently not legal in
734 /// PIC relocation models.
735 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
737 /// getFunctionAlignment - Return the Log2 alignment of this function.
738 virtual unsigned getFunctionAlignment(const Function *) const = 0;
740 //===--------------------------------------------------------------------===//
741 // TargetLowering Optimization Methods
744 /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
745 /// SDValues for returning information from TargetLowering to its clients
746 /// that want to combine
747 struct TargetLoweringOpt {
752 explicit TargetLoweringOpt(SelectionDAG &InDAG) : DAG(InDAG) {}
754 bool CombineTo(SDValue O, SDValue N) {
760 /// ShrinkDemandedConstant - Check to see if the specified operand of the
761 /// specified instruction is a constant integer. If so, check to see if
762 /// there are any bits set in the constant that are not demanded. If so,
763 /// shrink the constant and return true.
764 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
766 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
767 /// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening
768 /// cast, but it could be generalized for targets with other types of
769 /// implicit widening casts.
770 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
774 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
775 /// DemandedMask bits of the result of Op are ever used downstream. If we can
776 /// use this information to simplify Op, create a new simplified DAG node and
777 /// return true, returning the original and new nodes in Old and New.
778 /// Otherwise, analyze the expression and return a mask of KnownOne and
779 /// KnownZero bits for the expression (used to simplify the caller).
780 /// The KnownZero/One bits may only be accurate for those bits in the
782 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
783 APInt &KnownZero, APInt &KnownOne,
784 TargetLoweringOpt &TLO, unsigned Depth = 0) const;
786 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
787 /// Mask are known to be either zero or one and return them in the
788 /// KnownZero/KnownOne bitsets.
789 virtual void computeMaskedBitsForTargetNode(const SDValue Op,
793 const SelectionDAG &DAG,
794 unsigned Depth = 0) const;
796 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
797 /// targets that want to expose additional information about sign bits to the
799 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
800 unsigned Depth = 0) const;
802 struct DAGCombinerInfo {
803 void *DC; // The DAG Combiner object.
805 bool BeforeLegalizeOps;
806 bool CalledByLegalizer;
810 DAGCombinerInfo(SelectionDAG &dag, bool bl, bool blo, bool cl, void *dc)
811 : DC(dc), BeforeLegalize(bl), BeforeLegalizeOps(blo),
812 CalledByLegalizer(cl), DAG(dag) {}
814 bool isBeforeLegalize() const { return BeforeLegalize; }
815 bool isBeforeLegalizeOps() const { return BeforeLegalizeOps; }
816 bool isCalledByLegalizer() const { return CalledByLegalizer; }
818 void AddToWorklist(SDNode *N);
819 SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
821 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
822 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
824 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
827 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
828 /// and cc. If it is unable to simplify it, return a null SDValue.
829 SDValue SimplifySetCC(MVT VT, SDValue N0, SDValue N1,
830 ISD::CondCode Cond, bool foldBooleans,
831 DAGCombinerInfo &DCI, DebugLoc dl) const;
833 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
834 /// node is a GlobalAddress + offset.
836 isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) const;
838 /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
839 /// location that is 'Dist' units away from the location that the 'Base' load
841 bool isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base, unsigned Bytes,
842 int Dist, const MachineFrameInfo *MFI) const;
844 /// PerformDAGCombine - This method will be invoked for all target nodes and
845 /// for any target-independent nodes that the target has registered with
848 /// The semantics are as follows:
850 /// SDValue.Val == 0 - No change was made
851 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
852 /// otherwise - N should be replaced by the returned Operand.
854 /// In addition, methods provided by DAGCombinerInfo may be used to perform
855 /// more complex transformations.
857 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
859 //===--------------------------------------------------------------------===//
860 // TargetLowering Configuration Methods - These methods should be invoked by
861 // the derived class constructor to configure this object for the target.
865 /// setUsesGlobalOffsetTable - Specify that this target does or doesn't use a
866 /// GOT for PC-relative code.
867 void setUsesGlobalOffsetTable(bool V) { UsesGlobalOffsetTable = V; }
869 /// setShiftAmountType - Describe the type that should be used for shift
870 /// amounts. This type defaults to the pointer type.
871 void setShiftAmountType(MVT VT) { ShiftAmountTy = VT; }
873 /// setBooleanContents - Specify how the target extends the result of a
874 /// boolean value from i1 to a wider type. See getBooleanContents.
875 void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
877 /// setSchedulingPreference - Specify the target scheduling preference.
878 void setSchedulingPreference(SchedPreference Pref) {
879 SchedPreferenceInfo = Pref;
882 /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
883 /// use _setjmp to implement llvm.setjmp or the non _ version.
884 /// Defaults to false.
885 void setUseUnderscoreSetJmp(bool Val) {
886 UseUnderscoreSetJmp = Val;
889 /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
890 /// use _longjmp to implement llvm.longjmp or the non _ version.
891 /// Defaults to false.
892 void setUseUnderscoreLongJmp(bool Val) {
893 UseUnderscoreLongJmp = Val;
896 /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
897 /// specifies the register that llvm.savestack/llvm.restorestack should save
899 void setStackPointerRegisterToSaveRestore(unsigned R) {
900 StackPointerRegisterToSaveRestore = R;
903 /// setExceptionPointerRegister - If set to a physical register, this sets
904 /// the register that receives the exception address on entry to a landing
906 void setExceptionPointerRegister(unsigned R) {
907 ExceptionPointerRegister = R;
910 /// setExceptionSelectorRegister - If set to a physical register, this sets
911 /// the register that receives the exception typeid on entry to a landing
913 void setExceptionSelectorRegister(unsigned R) {
914 ExceptionSelectorRegister = R;
917 /// SelectIsExpensive - Tells the code generator not to expand operations
918 /// into sequences that use the select operations if possible.
919 void setSelectIsExpensive() { SelectIsExpensive = true; }
921 /// setIntDivIsCheap - Tells the code generator that integer divide is
922 /// expensive, and if possible, should be replaced by an alternate sequence
923 /// of instructions not containing an integer divide.
924 void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
926 /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
927 /// srl/add/sra for a signed divide by power of two, and let the target handle
929 void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
931 /// addRegisterClass - Add the specified register class as an available
932 /// regclass for the specified value type. This indicates the selector can
933 /// handle values of that class natively.
934 void addRegisterClass(MVT VT, TargetRegisterClass *RC) {
935 assert((unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
936 AvailableRegClasses.push_back(std::make_pair(VT, RC));
937 RegClassForVT[VT.getSimpleVT()] = RC;
940 /// computeRegisterProperties - Once all of the register classes are added,
941 /// this allows us to compute derived properties we expose.
942 void computeRegisterProperties();
944 /// setOperationAction - Indicate that the specified operation does not work
945 /// with the specified type and indicate what to do about it.
946 void setOperationAction(unsigned Op, MVT VT,
947 LegalizeAction Action) {
948 assert((unsigned)VT.getSimpleVT() < sizeof(OpActions[0][0])*8 &&
949 Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
950 unsigned I = (unsigned) VT.getSimpleVT();
953 OpActions[I][Op] &= ~(uint64_t(3UL) << (J*2));
954 OpActions[I][Op] |= (uint64_t)Action << (J*2);
957 /// setLoadExtAction - Indicate that the specified load with extension does
958 /// not work with the with specified type and indicate what to do about it.
959 void setLoadExtAction(unsigned ExtType, MVT VT,
960 LegalizeAction Action) {
961 assert((unsigned)VT.getSimpleVT() < sizeof(LoadExtActions[0])*4 &&
962 ExtType < array_lengthof(LoadExtActions) &&
963 "Table isn't big enough!");
964 LoadExtActions[ExtType] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
965 LoadExtActions[ExtType] |= (uint64_t)Action << VT.getSimpleVT()*2;
968 /// setTruncStoreAction - Indicate that the specified truncating store does
969 /// not work with the with specified type and indicate what to do about it.
970 void setTruncStoreAction(MVT ValVT, MVT MemVT,
971 LegalizeAction Action) {
972 assert((unsigned)ValVT.getSimpleVT() < array_lengthof(TruncStoreActions) &&
973 (unsigned)MemVT.getSimpleVT() < sizeof(TruncStoreActions[0])*4 &&
974 "Table isn't big enough!");
975 TruncStoreActions[ValVT.getSimpleVT()] &= ~(uint64_t(3UL) <<
976 MemVT.getSimpleVT()*2);
977 TruncStoreActions[ValVT.getSimpleVT()] |= (uint64_t)Action <<
978 MemVT.getSimpleVT()*2;
981 /// setIndexedLoadAction - Indicate that the specified indexed load does or
982 /// does not work with the with specified type and indicate what to do abort
983 /// it. NOTE: All indexed mode loads are initialized to Expand in
984 /// TargetLowering.cpp
985 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
986 LegalizeAction Action) {
987 assert((unsigned)VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
988 IdxMode < array_lengthof(IndexedModeActions[0][0]) &&
989 "Table isn't big enough!");
990 IndexedModeActions[(unsigned)VT.getSimpleVT()][0][IdxMode] = (uint8_t)Action;
993 /// setIndexedStoreAction - Indicate that the specified indexed store does or
994 /// does not work with the with specified type and indicate what to do about
995 /// it. NOTE: All indexed mode stores are initialized to Expand in
996 /// TargetLowering.cpp
997 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
998 LegalizeAction Action) {
999 assert((unsigned)VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
1000 IdxMode < array_lengthof(IndexedModeActions[0][1] ) &&
1001 "Table isn't big enough!");
1002 IndexedModeActions[(unsigned)VT.getSimpleVT()][1][IdxMode] = (uint8_t)Action;
1005 /// setConvertAction - Indicate that the specified conversion does or does
1006 /// not work with the with specified type and indicate what to do about it.
1007 void setConvertAction(MVT FromVT, MVT ToVT,
1008 LegalizeAction Action) {
1009 assert((unsigned)FromVT.getSimpleVT() < array_lengthof(ConvertActions) &&
1010 (unsigned)ToVT.getSimpleVT() < sizeof(ConvertActions[0])*4 &&
1011 "Table isn't big enough!");
1012 ConvertActions[FromVT.getSimpleVT()] &= ~(uint64_t(3UL) <<
1013 ToVT.getSimpleVT()*2);
1014 ConvertActions[FromVT.getSimpleVT()] |= (uint64_t)Action <<
1015 ToVT.getSimpleVT()*2;
1018 /// setCondCodeAction - Indicate that the specified condition code is or isn't
1019 /// supported on the target and indicate what to do about it.
1020 void setCondCodeAction(ISD::CondCode CC, MVT VT, LegalizeAction Action) {
1021 assert((unsigned)VT.getSimpleVT() < sizeof(CondCodeActions[0])*4 &&
1022 (unsigned)CC < array_lengthof(CondCodeActions) &&
1023 "Table isn't big enough!");
1024 CondCodeActions[(unsigned)CC] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
1025 CondCodeActions[(unsigned)CC] |= (uint64_t)Action << VT.getSimpleVT()*2;
1028 /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
1029 /// promotion code defaults to trying a larger integer/fp until it can find
1030 /// one that works. If that default is insufficient, this method can be used
1031 /// by the target to override the default.
1032 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1033 PromoteToType[std::make_pair(Opc, OrigVT.getSimpleVT())] =
1034 DestVT.getSimpleVT();
1037 /// addLegalFPImmediate - Indicate that this target can instruction select
1038 /// the specified FP immediate natively.
1039 void addLegalFPImmediate(const APFloat& Imm) {
1040 LegalFPImmediates.push_back(Imm);
1043 /// setTargetDAGCombine - Targets should invoke this method for each target
1044 /// independent node that they want to provide a custom DAG combiner for by
1045 /// implementing the PerformDAGCombine virtual method.
1046 void setTargetDAGCombine(ISD::NodeType NT) {
1047 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1048 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1051 /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
1052 /// bytes); default is 200
1053 void setJumpBufSize(unsigned Size) {
1057 /// setJumpBufAlignment - Set the target's required jmp_buf buffer
1058 /// alignment (in bytes); default is 0
1059 void setJumpBufAlignment(unsigned Align) {
1060 JumpBufAlignment = Align;
1063 /// setIfCvtBlockSizeLimit - Set the target's if-conversion block size
1064 /// limit (in number of instructions); default is 2.
1065 void setIfCvtBlockSizeLimit(unsigned Limit) {
1066 IfCvtBlockSizeLimit = Limit;
1069 /// setIfCvtDupBlockSizeLimit - Set the target's block size limit (in number
1070 /// of instructions) to be considered for code duplication during
1071 /// if-conversion; default is 2.
1072 void setIfCvtDupBlockSizeLimit(unsigned Limit) {
1073 IfCvtDupBlockSizeLimit = Limit;
1076 /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
1077 /// alignment is zero, it means the target does not care about loop alignment.
1078 void setPrefLoopAlignment(unsigned Align) {
1079 PrefLoopAlignment = Align;
1084 virtual const TargetSubtarget *getSubtarget() {
1085 assert(0 && "Not Implemented");
1086 return NULL; // this is here to silence compiler errors
1088 //===--------------------------------------------------------------------===//
1089 // Lowering methods - These methods must be implemented by targets so that
1090 // the SelectionDAGLowering code knows how to lower these.
1093 /// LowerArguments - This hook must be implemented to indicate how we should
1094 /// lower the arguments for the specified function, into the specified DAG.
1096 LowerArguments(Function &F, SelectionDAG &DAG,
1097 SmallVectorImpl<SDValue>& ArgValues, DebugLoc dl);
1099 /// LowerCallTo - This hook lowers an abstract call to a function into an
1100 /// actual call. This returns a pair of operands. The first element is the
1101 /// return value for the function (if RetTy is not VoidTy). The second
1102 /// element is the outgoing token chain.
1103 struct ArgListEntry {
1114 ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1115 isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
1117 typedef std::vector<ArgListEntry> ArgListTy;
1118 virtual std::pair<SDValue, SDValue>
1119 LowerCallTo(SDValue Chain, const Type *RetTy, bool RetSExt, bool RetZExt,
1120 bool isVarArg, bool isInreg, unsigned NumFixedArgs,
1121 unsigned CallingConv, bool isTailCall, SDValue Callee,
1122 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl);
1124 /// EmitTargetCodeForMemcpy - Emit target-specific code that performs a
1125 /// memcpy. This can be used by targets to provide code sequences for cases
1126 /// that don't fit the target's parameters for simple loads/stores and can be
1127 /// more efficient than using a library call. This function can return a null
1128 /// SDValue if the target declines to use custom code and a different
1129 /// lowering strategy should be used.
1131 /// If AlwaysInline is true, the size is constant and the target should not
1132 /// emit any calls and is strongly encouraged to attempt to emit inline code
1133 /// even if it is beyond the usual threshold because this intrinsic is being
1134 /// expanded in a place where calls are not feasible (e.g. within the prologue
1135 /// for another call). If the target chooses to decline an AlwaysInline
1136 /// request here, legalize will resort to using simple loads and stores.
1138 EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
1140 SDValue Op1, SDValue Op2,
1141 SDValue Op3, unsigned Align,
1143 const Value *DstSV, uint64_t DstOff,
1144 const Value *SrcSV, uint64_t SrcOff) {
1148 /// EmitTargetCodeForMemmove - Emit target-specific code that performs a
1149 /// memmove. This can be used by targets to provide code sequences for cases
1150 /// that don't fit the target's parameters for simple loads/stores and can be
1151 /// more efficient than using a library call. This function can return a null
1152 /// SDValue if the target declines to use custom code and a different
1153 /// lowering strategy should be used.
1155 EmitTargetCodeForMemmove(SelectionDAG &DAG, DebugLoc dl,
1157 SDValue Op1, SDValue Op2,
1158 SDValue Op3, unsigned Align,
1159 const Value *DstSV, uint64_t DstOff,
1160 const Value *SrcSV, uint64_t SrcOff) {
1164 /// EmitTargetCodeForMemset - Emit target-specific code that performs a
1165 /// memset. This can be used by targets to provide code sequences for cases
1166 /// that don't fit the target's parameters for simple stores and can be more
1167 /// efficient than using a library call. This function can return a null
1168 /// SDValue if the target declines to use custom code and a different
1169 /// lowering strategy should be used.
1171 EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
1173 SDValue Op1, SDValue Op2,
1174 SDValue Op3, unsigned Align,
1175 const Value *DstSV, uint64_t DstOff) {
1179 /// LowerOperationWrapper - This callback is invoked by the type legalizer
1180 /// to legalize nodes with an illegal operand type but legal result types.
1181 /// It replaces the LowerOperation callback in the type Legalizer.
1182 /// The reason we can not do away with LowerOperation entirely is that
1183 /// LegalizeDAG isn't yet ready to use this callback.
1184 /// TODO: Consider merging with ReplaceNodeResults.
1186 /// The target places new result values for the node in Results (their number
1187 /// and types must exactly match those of the original return values of
1188 /// the node), or leaves Results empty, which indicates that the node is not
1189 /// to be custom lowered after all.
1190 /// The default implementation calls LowerOperation.
1191 virtual void LowerOperationWrapper(SDNode *N,
1192 SmallVectorImpl<SDValue> &Results,
1195 /// LowerOperation - This callback is invoked for operations that are
1196 /// unsupported by the target, which are registered to use 'custom' lowering,
1197 /// and whose defined values are all legal.
1198 /// If the target has no operations that require custom lowering, it need not
1199 /// implement this. The default implementation of this aborts.
1200 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG);
1202 /// ReplaceNodeResults - This callback is invoked when a node result type is
1203 /// illegal for the target, and the operation was registered to use 'custom'
1204 /// lowering for that result type. The target places new result values for
1205 /// the node in Results (their number and types must exactly match those of
1206 /// the original return values of the node), or leaves Results empty, which
1207 /// indicates that the node is not to be custom lowered after all.
1209 /// If the target has no operations that require custom lowering, it need not
1210 /// implement this. The default implementation aborts.
1211 virtual void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
1212 SelectionDAG &DAG) {
1213 assert(0 && "ReplaceNodeResults not implemented for this target!");
1216 /// IsEligibleForTailCallOptimization - Check whether the call is eligible for
1217 /// tail call optimization. Targets which want to do tail call optimization
1218 /// should override this function.
1219 virtual bool IsEligibleForTailCallOptimization(CallSDNode *Call,
1221 SelectionDAG &DAG) const {
1225 /// CheckTailCallReturnConstraints - Check whether CALL node immediatly
1226 /// preceeds the RET node and whether the return uses the result of the node
1227 /// or is a void return. This function can be used by the target to determine
1228 /// eligiblity of tail call optimization.
1229 static bool CheckTailCallReturnConstraints(CallSDNode *TheCall, SDValue Ret);
1231 /// GetPossiblePreceedingTailCall - Get preceeding TailCallNodeOpCode node if
1232 /// it exists. Skip a possible ISD::TokenFactor.
1233 static SDValue GetPossiblePreceedingTailCall(SDValue Chain,
1234 unsigned TailCallNodeOpCode) {
1235 if (Chain.getOpcode() == TailCallNodeOpCode) {
1237 } else if (Chain.getOpcode() == ISD::TokenFactor) {
1238 if (Chain.getNumOperands() &&
1239 Chain.getOperand(0).getOpcode() == TailCallNodeOpCode)
1240 return Chain.getOperand(0);
1245 /// getTargetNodeName() - This method returns the name of a target specific
1247 virtual const char *getTargetNodeName(unsigned Opcode) const;
1249 /// createFastISel - This method returns a target specific FastISel object,
1250 /// or null if the target does not support "fast" ISel.
1252 createFastISel(MachineFunction &,
1253 MachineModuleInfo *, DwarfWriter *,
1254 DenseMap<const Value *, unsigned> &,
1255 DenseMap<const BasicBlock *, MachineBasicBlock *> &,
1256 DenseMap<const AllocaInst *, int> &
1258 , SmallSet<Instruction*, 8> &CatchInfoLost
1264 //===--------------------------------------------------------------------===//
1265 // Inline Asm Support hooks
1268 /// ExpandInlineAsm - This hook allows the target to expand an inline asm
1269 /// call to be explicit llvm code if it wants to. This is useful for
1270 /// turning simple inline asms into LLVM intrinsics, which gives the
1271 /// compiler more information about the behavior of the code.
1272 virtual bool ExpandInlineAsm(CallInst *CI) const {
1276 enum ConstraintType {
1277 C_Register, // Constraint represents specific register(s).
1278 C_RegisterClass, // Constraint represents any of register(s) in class.
1279 C_Memory, // Memory constraint.
1280 C_Other, // Something else.
1281 C_Unknown // Unsupported constraint.
1284 /// AsmOperandInfo - This contains information for each constraint that we are
1286 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
1287 /// ConstraintCode - This contains the actual string for the code, like "m".
1288 /// TargetLowering picks the 'best' code from ConstraintInfo::Codes that
1289 /// most closely matches the operand.
1290 std::string ConstraintCode;
1292 /// ConstraintType - Information about the constraint code, e.g. Register,
1293 /// RegisterClass, Memory, Other, Unknown.
1294 TargetLowering::ConstraintType ConstraintType;
1296 /// CallOperandval - If this is the result output operand or a
1297 /// clobber, this is null, otherwise it is the incoming operand to the
1298 /// CallInst. This gets modified as the asm is processed.
1299 Value *CallOperandVal;
1301 /// ConstraintVT - The ValueType for the operand value.
1304 /// isMatchingInputConstraint - Return true of this is an input operand that
1305 /// is a matching constraint like "4".
1306 bool isMatchingInputConstraint() const;
1308 /// getMatchedOperand - If this is an input matching constraint, this method
1309 /// returns the output operand it matches.
1310 unsigned getMatchedOperand() const;
1312 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
1313 : InlineAsm::ConstraintInfo(info),
1314 ConstraintType(TargetLowering::C_Unknown),
1315 CallOperandVal(0), ConstraintVT(MVT::Other) {
1319 /// ComputeConstraintToUse - Determines the constraint code and constraint
1320 /// type to use for the specific AsmOperandInfo, setting
1321 /// OpInfo.ConstraintCode and OpInfo.ConstraintType. If the actual operand
1322 /// being passed in is available, it can be passed in as Op, otherwise an
1323 /// empty SDValue can be passed. If hasMemory is true it means one of the asm
1324 /// constraint of the inline asm instruction being processed is 'm'.
1325 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
1328 SelectionDAG *DAG = 0) const;
1330 /// getConstraintType - Given a constraint, return the type of constraint it
1331 /// is for this target.
1332 virtual ConstraintType getConstraintType(const std::string &Constraint) const;
1334 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1335 /// return a list of registers that can be used to satisfy the constraint.
1336 /// This should only be used for C_RegisterClass constraints.
1337 virtual std::vector<unsigned>
1338 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1341 /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
1342 /// {edx}), return the register number and the register class for the
1345 /// Given a register class constraint, like 'r', if this corresponds directly
1346 /// to an LLVM register class, return a register of 0 and the register class
1349 /// This should only be used for C_Register constraints. On error,
1350 /// this returns a register number of 0 and a null register class pointer..
1351 virtual std::pair<unsigned, const TargetRegisterClass*>
1352 getRegForInlineAsmConstraint(const std::string &Constraint,
1355 /// LowerXConstraint - try to replace an X constraint, which matches anything,
1356 /// with another that has more specific requirements based on the type of the
1357 /// corresponding operand. This returns null if there is no replacement to
1359 virtual const char *LowerXConstraint(MVT ConstraintVT) const;
1361 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1362 /// vector. If it is invalid, don't add anything to Ops. If hasMemory is true
1363 /// it means one of the asm constraint of the inline asm instruction being
1364 /// processed is 'm'.
1365 virtual void LowerAsmOperandForConstraint(SDValue Op, char ConstraintLetter,
1367 std::vector<SDValue> &Ops,
1368 SelectionDAG &DAG) const;
1370 //===--------------------------------------------------------------------===//
1374 // EmitInstrWithCustomInserter - This method should be implemented by targets
1375 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1376 // instructions are special in various ways, which require special support to
1377 // insert. The specified MachineInstr is created but not inserted into any
1378 // basic blocks, and the scheduler passes ownership of it to this method.
1379 virtual MachineBasicBlock *EmitInstrWithCustomInserter(MachineInstr *MI,
1380 MachineBasicBlock *MBB) const;
1382 //===--------------------------------------------------------------------===//
1383 // Addressing mode description hooks (used by LSR etc).
1386 /// AddrMode - This represents an addressing mode of:
1387 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1388 /// If BaseGV is null, there is no BaseGV.
1389 /// If BaseOffs is zero, there is no base offset.
1390 /// If HasBaseReg is false, there is no base register.
1391 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1395 GlobalValue *BaseGV;
1399 AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1402 /// isLegalAddressingMode - Return true if the addressing mode represented by
1403 /// AM is legal for this target, for a load/store of the specified type.
1404 /// The type may be VoidTy, in which case only return true if the addressing
1405 /// mode is legal for a load/store of any legal type.
1406 /// TODO: Handle pre/postinc as well.
1407 virtual bool isLegalAddressingMode(const AddrMode &AM, const Type *Ty) const;
1409 /// isTruncateFree - Return true if it's free to truncate a value of
1410 /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1411 /// register EAX to i16 by referencing its sub-register AX.
1412 virtual bool isTruncateFree(const Type *Ty1, const Type *Ty2) const {
1416 virtual bool isTruncateFree(MVT VT1, MVT VT2) const {
1420 /// isZExtFree - Return true if any actual instruction that defines a
1421 /// value of type Ty1 implicit zero-extends the value to Ty2 in the result
1422 /// register. This does not necessarily include registers defined in
1423 /// unknown ways, such as incoming arguments, or copies from unknown
1424 /// virtual registers. Also, if isTruncateFree(Ty2, Ty1) is true, this
1425 /// does not necessarily apply to truncate instructions. e.g. on x86-64,
1426 /// all instructions that define 32-bit values implicit zero-extend the
1427 /// result out to 64 bits.
1428 virtual bool isZExtFree(const Type *Ty1, const Type *Ty2) const {
1432 virtual bool isZExtFree(MVT VT1, MVT VT2) const {
1436 /// isNarrowingProfitable - Return true if it's profitable to narrow
1437 /// operations of type VT1 to VT2. e.g. on x86, it's profitable to narrow
1438 /// from i32 to i8 but not from i32 to i16.
1439 virtual bool isNarrowingProfitable(MVT VT1, MVT VT2) const {
1443 //===--------------------------------------------------------------------===//
1444 // Div utility functions
1446 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG,
1447 std::vector<SDNode*>* Created) const;
1448 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG,
1449 std::vector<SDNode*>* Created) const;
1452 //===--------------------------------------------------------------------===//
1453 // Runtime Library hooks
1456 /// setLibcallName - Rename the default libcall routine name for the specified
1458 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1459 LibcallRoutineNames[Call] = Name;
1462 /// getLibcallName - Get the libcall routine name for the specified libcall.
1464 const char *getLibcallName(RTLIB::Libcall Call) const {
1465 return LibcallRoutineNames[Call];
1468 /// setCmpLibcallCC - Override the default CondCode to be used to test the
1469 /// result of the comparison libcall against zero.
1470 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1471 CmpLibcallCCs[Call] = CC;
1474 /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1475 /// the comparison libcall against zero.
1476 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1477 return CmpLibcallCCs[Call];
1482 const TargetData *TD;
1483 TargetLoweringObjectFile &TLOF;
1485 /// PointerTy - The type to use for pointers, usually i32 or i64.
1489 /// IsLittleEndian - True if this is a little endian target.
1491 bool IsLittleEndian;
1493 /// UsesGlobalOffsetTable - True if this target uses a GOT for PIC codegen.
1495 bool UsesGlobalOffsetTable;
1497 /// SelectIsExpensive - Tells the code generator not to expand operations
1498 /// into sequences that use the select operations if possible.
1499 bool SelectIsExpensive;
1501 /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1502 /// constants into a sequence of muls, adds, and shifts. This is a hack until
1503 /// a real cost model is in place. If we ever optimize for size, this will be
1504 /// set to true unconditionally.
1507 /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1508 /// srl/add/sra for a signed divide by power of two, and let the target handle
1510 bool Pow2DivIsCheap;
1512 /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1513 /// llvm.setjmp. Defaults to false.
1514 bool UseUnderscoreSetJmp;
1516 /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1517 /// llvm.longjmp. Defaults to false.
1518 bool UseUnderscoreLongJmp;
1520 /// ShiftAmountTy - The type to use for shift amounts, usually i8 or whatever
1524 /// BooleanContents - Information about the contents of the high-bits in
1525 /// boolean values held in a type wider than i1. See getBooleanContents.
1526 BooleanContent BooleanContents;
1528 /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1529 /// total cycles or lowest register usage.
1530 SchedPreference SchedPreferenceInfo;
1532 /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1533 unsigned JumpBufSize;
1535 /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1537 unsigned JumpBufAlignment;
1539 /// IfCvtBlockSizeLimit - The maximum allowed size for a block to be
1541 unsigned IfCvtBlockSizeLimit;
1543 /// IfCvtDupBlockSizeLimit - The maximum allowed size for a block to be
1544 /// duplicated during if-conversion.
1545 unsigned IfCvtDupBlockSizeLimit;
1547 /// PrefLoopAlignment - The perferred loop alignment.
1549 unsigned PrefLoopAlignment;
1551 /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1552 /// specifies the register that llvm.savestack/llvm.restorestack should save
1554 unsigned StackPointerRegisterToSaveRestore;
1556 /// ExceptionPointerRegister - If set to a physical register, this specifies
1557 /// the register that receives the exception address on entry to a landing
1559 unsigned ExceptionPointerRegister;
1561 /// ExceptionSelectorRegister - If set to a physical register, this specifies
1562 /// the register that receives the exception typeid on entry to a landing
1564 unsigned ExceptionSelectorRegister;
1566 /// RegClassForVT - This indicates the default register class to use for
1567 /// each ValueType the target supports natively.
1568 TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1569 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1570 MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1572 /// TransformToType - For any value types we are promoting or expanding, this
1573 /// contains the value type that we are changing to. For Expanded types, this
1574 /// contains one step of the expand (e.g. i64 -> i32), even if there are
1575 /// multiple steps required (e.g. i64 -> i16). For types natively supported
1576 /// by the system, this holds the same type (e.g. i32 -> i32).
1577 MVT TransformToType[MVT::LAST_VALUETYPE];
1579 /// OpActions - For each operation and each value type, keep a LegalizeAction
1580 /// that indicates how instruction selection should deal with the operation.
1581 /// Most operations are Legal (aka, supported natively by the target), but
1582 /// operations that are not should be described. Note that operations on
1583 /// non-legal value types are not described here.
1584 /// This array is accessed using VT.getSimpleVT(), so it is subject to
1585 /// the MVT::MAX_ALLOWED_VALUETYPE * 2 bits.
1586 uint64_t OpActions[MVT::MAX_ALLOWED_VALUETYPE/(sizeof(uint64_t)*4)][ISD::BUILTIN_OP_END];
1588 /// LoadExtActions - For each load of load extension type and each value type,
1589 /// keep a LegalizeAction that indicates how instruction selection should deal
1591 uint64_t LoadExtActions[ISD::LAST_LOADEXT_TYPE];
1593 /// TruncStoreActions - For each truncating store, keep a LegalizeAction that
1594 /// indicates how instruction selection should deal with the store.
1595 uint64_t TruncStoreActions[MVT::LAST_VALUETYPE];
1597 /// IndexedModeActions - For each indexed mode and each value type,
1598 /// keep a pair of LegalizeAction that indicates how instruction
1599 /// selection should deal with the load / store. The first
1600 /// dimension is now the value_type for the reference. The second
1601 /// dimension is the load [0] vs. store[1]. The third dimension
1602 /// represents the various modes for load store.
1603 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][2][ISD::LAST_INDEXED_MODE];
1605 /// ConvertActions - For each conversion from source type to destination type,
1606 /// keep a LegalizeAction that indicates how instruction selection should
1607 /// deal with the conversion.
1608 /// Currently, this is used only for floating->floating conversions
1609 /// (FP_EXTEND and FP_ROUND).
1610 uint64_t ConvertActions[MVT::LAST_VALUETYPE];
1612 /// CondCodeActions - For each condition code (ISD::CondCode) keep a
1613 /// LegalizeAction that indicates how instruction selection should
1614 /// deal with the condition code.
1615 uint64_t CondCodeActions[ISD::SETCC_INVALID];
1617 ValueTypeActionImpl ValueTypeActions;
1619 std::vector<APFloat> LegalFPImmediates;
1621 std::vector<std::pair<MVT, TargetRegisterClass*> > AvailableRegClasses;
1623 /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
1624 /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
1625 /// which sets a bit in this array.
1627 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
1629 /// PromoteToType - For operations that must be promoted to a specific type,
1630 /// this holds the destination type. This map should be sparse, so don't hold
1633 /// Targets add entries to this map with AddPromotedToType(..), clients access
1634 /// this with getTypeToPromoteTo(..).
1635 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1638 /// LibcallRoutineNames - Stores the name each libcall.
1640 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1642 /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
1643 /// of each of the comparison libcall against zero.
1644 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1647 /// When lowering \@llvm.memset this field specifies the maximum number of
1648 /// store operations that may be substituted for the call to memset. Targets
1649 /// must set this value based on the cost threshold for that target. Targets
1650 /// should assume that the memset will be done using as many of the largest
1651 /// store operations first, followed by smaller ones, if necessary, per
1652 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1653 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1654 /// store. This only applies to setting a constant array of a constant size.
1655 /// @brief Specify maximum number of store instructions per memset call.
1656 unsigned maxStoresPerMemset;
1658 /// When lowering \@llvm.memcpy this field specifies the maximum number of
1659 /// store operations that may be substituted for a call to memcpy. Targets
1660 /// must set this value based on the cost threshold for that target. Targets
1661 /// should assume that the memcpy will be done using as many of the largest
1662 /// store operations first, followed by smaller ones, if necessary, per
1663 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1664 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1665 /// and one 1-byte store. This only applies to copying a constant array of
1667 /// @brief Specify maximum bytes of store instructions per memcpy call.
1668 unsigned maxStoresPerMemcpy;
1670 /// When lowering \@llvm.memmove this field specifies the maximum number of
1671 /// store instructions that may be substituted for a call to memmove. Targets
1672 /// must set this value based on the cost threshold for that target. Targets
1673 /// should assume that the memmove will be done using as many of the largest
1674 /// store operations first, followed by smaller ones, if necessary, per
1675 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1676 /// with 8-bit alignment would result in nine 1-byte stores. This only
1677 /// applies to copying a constant array of constant size.
1678 /// @brief Specify maximum bytes of store instructions per memmove call.
1679 unsigned maxStoresPerMemmove;
1681 /// This field specifies whether the target machine permits unaligned memory
1682 /// accesses. This is used, for example, to determine the size of store
1683 /// operations when copying small arrays and other similar tasks.
1684 /// @brief Indicate whether the target permits unaligned memory accesses.
1685 bool allowUnalignedMemoryAccesses;
1687 /// This field specifies whether the target can benefit from code placement
1689 bool benefitFromCodePlacementOpt;
1691 } // end llvm namespace