Bug Summary

File:lib/Target/AArch64/AArch64TargetTransformInfo.cpp
Warning:line 1029, column 9
Called C++ object pointer is null

Annotated Source Code

[?] Use j/k keys for keyboard navigation

/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/AArch64/AArch64TargetTransformInfo.cpp

1//===-- AArch64TargetTransformInfo.cpp - AArch64 specific TTI -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "AArch64TargetTransformInfo.h"
11#include "MCTargetDesc/AArch64AddressingModes.h"
12#include "llvm/Analysis/LoopInfo.h"
13#include "llvm/Analysis/TargetTransformInfo.h"
14#include "llvm/CodeGen/BasicTTIImpl.h"
15#include "llvm/CodeGen/CostTable.h"
16#include "llvm/CodeGen/TargetLowering.h"
17#include "llvm/IR/IntrinsicInst.h"
18#include "llvm/Support/Debug.h"
19#include <algorithm>
20using namespace llvm;
21
22#define DEBUG_TYPE"aarch64tti" "aarch64tti"
23
24static cl::opt<bool> EnableFalkorHWPFUnrollFix("enable-falkor-hwpf-unroll-fix",
25 cl::init(true), cl::Hidden);
26
27bool AArch64TTIImpl::areInlineCompatible(const Function *Caller,
28 const Function *Callee) const {
29 const TargetMachine &TM = getTLI()->getTargetMachine();
30
31 const FeatureBitset &CallerBits =
32 TM.getSubtargetImpl(*Caller)->getFeatureBits();
33 const FeatureBitset &CalleeBits =
34 TM.getSubtargetImpl(*Callee)->getFeatureBits();
35
36 // Inline a callee if its target-features are a subset of the callers
37 // target-features.
38 return (CallerBits & CalleeBits) == CalleeBits;
39}
40
41/// \brief Calculate the cost of materializing a 64-bit value. This helper
42/// method might only calculate a fraction of a larger immediate. Therefore it
43/// is valid to return a cost of ZERO.
44int AArch64TTIImpl::getIntImmCost(int64_t Val) {
45 // Check if the immediate can be encoded within an instruction.
46 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, 64))
47 return 0;
48
49 if (Val < 0)
50 Val = ~Val;
51
52 // Calculate how many moves we will need to materialize this constant.
53 unsigned LZ = countLeadingZeros((uint64_t)Val);
54 return (64 - LZ + 15) / 16;
55}
56
57/// \brief Calculate the cost of materializing the given constant.
58int AArch64TTIImpl::getIntImmCost(const APInt &Imm, Type *Ty) {
59 assert(Ty->isIntegerTy())(static_cast <bool> (Ty->isIntegerTy()) ? void (0) :
__assert_fail ("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/AArch64/AArch64TargetTransformInfo.cpp"
, 59, __extension__ __PRETTY_FUNCTION__))
;
60
61 unsigned BitSize = Ty->getPrimitiveSizeInBits();
62 if (BitSize == 0)
63 return ~0U;
64
65 // Sign-extend all constants to a multiple of 64-bit.
66 APInt ImmVal = Imm;
67 if (BitSize & 0x3f)
68 ImmVal = Imm.sext((BitSize + 63) & ~0x3fU);
69
70 // Split the constant into 64-bit chunks and calculate the cost for each
71 // chunk.
72 int Cost = 0;
73 for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
74 APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
75 int64_t Val = Tmp.getSExtValue();
76 Cost += getIntImmCost(Val);
77 }
78 // We need at least one instruction to materialze the constant.
79 return std::max(1, Cost);
80}
81
82int AArch64TTIImpl::getIntImmCost(unsigned Opcode, unsigned Idx,
83 const APInt &Imm, Type *Ty) {
84 assert(Ty->isIntegerTy())(static_cast <bool> (Ty->isIntegerTy()) ? void (0) :
__assert_fail ("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/AArch64/AArch64TargetTransformInfo.cpp"
, 84, __extension__ __PRETTY_FUNCTION__))
;
85
86 unsigned BitSize = Ty->getPrimitiveSizeInBits();
87 // There is no cost model for constants with a bit size of 0. Return TCC_Free
88 // here, so that constant hoisting will ignore this constant.
89 if (BitSize == 0)
90 return TTI::TCC_Free;
91
92 unsigned ImmIdx = ~0U;
93 switch (Opcode) {
94 default:
95 return TTI::TCC_Free;
96 case Instruction::GetElementPtr:
97 // Always hoist the base address of a GetElementPtr.
98 if (Idx == 0)
99 return 2 * TTI::TCC_Basic;
100 return TTI::TCC_Free;
101 case Instruction::Store:
102 ImmIdx = 0;
103 break;
104 case Instruction::Add:
105 case Instruction::Sub:
106 case Instruction::Mul:
107 case Instruction::UDiv:
108 case Instruction::SDiv:
109 case Instruction::URem:
110 case Instruction::SRem:
111 case Instruction::And:
112 case Instruction::Or:
113 case Instruction::Xor:
114 case Instruction::ICmp:
115 ImmIdx = 1;
116 break;
117 // Always return TCC_Free for the shift value of a shift instruction.
118 case Instruction::Shl:
119 case Instruction::LShr:
120 case Instruction::AShr:
121 if (Idx == 1)
122 return TTI::TCC_Free;
123 break;
124 case Instruction::Trunc:
125 case Instruction::ZExt:
126 case Instruction::SExt:
127 case Instruction::IntToPtr:
128 case Instruction::PtrToInt:
129 case Instruction::BitCast:
130 case Instruction::PHI:
131 case Instruction::Call:
132 case Instruction::Select:
133 case Instruction::Ret:
134 case Instruction::Load:
135 break;
136 }
137
138 if (Idx == ImmIdx) {
139 int NumConstants = (BitSize + 63) / 64;
140 int Cost = AArch64TTIImpl::getIntImmCost(Imm, Ty);
141 return (Cost <= NumConstants * TTI::TCC_Basic)
142 ? static_cast<int>(TTI::TCC_Free)
143 : Cost;
144 }
145 return AArch64TTIImpl::getIntImmCost(Imm, Ty);
146}
147
148int AArch64TTIImpl::getIntImmCost(Intrinsic::ID IID, unsigned Idx,
149 const APInt &Imm, Type *Ty) {
150 assert(Ty->isIntegerTy())(static_cast <bool> (Ty->isIntegerTy()) ? void (0) :
__assert_fail ("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/AArch64/AArch64TargetTransformInfo.cpp"
, 150, __extension__ __PRETTY_FUNCTION__))
;
151
152 unsigned BitSize = Ty->getPrimitiveSizeInBits();
153 // There is no cost model for constants with a bit size of 0. Return TCC_Free
154 // here, so that constant hoisting will ignore this constant.
155 if (BitSize == 0)
156 return TTI::TCC_Free;
157
158 switch (IID) {
159 default:
160 return TTI::TCC_Free;
161 case Intrinsic::sadd_with_overflow:
162 case Intrinsic::uadd_with_overflow:
163 case Intrinsic::ssub_with_overflow:
164 case Intrinsic::usub_with_overflow:
165 case Intrinsic::smul_with_overflow:
166 case Intrinsic::umul_with_overflow:
167 if (Idx == 1) {
168 int NumConstants = (BitSize + 63) / 64;
169 int Cost = AArch64TTIImpl::getIntImmCost(Imm, Ty);
170 return (Cost <= NumConstants * TTI::TCC_Basic)
171 ? static_cast<int>(TTI::TCC_Free)
172 : Cost;
173 }
174 break;
175 case Intrinsic::experimental_stackmap:
176 if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
177 return TTI::TCC_Free;
178 break;
179 case Intrinsic::experimental_patchpoint_void:
180 case Intrinsic::experimental_patchpoint_i64:
181 if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
182 return TTI::TCC_Free;
183 break;
184 }
185 return AArch64TTIImpl::getIntImmCost(Imm, Ty);
186}
187
188TargetTransformInfo::PopcntSupportKind
189AArch64TTIImpl::getPopcntSupport(unsigned TyWidth) {
190 assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2")(static_cast <bool> (isPowerOf2_32(TyWidth) && "Ty width must be power of 2"
) ? void (0) : __assert_fail ("isPowerOf2_32(TyWidth) && \"Ty width must be power of 2\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/AArch64/AArch64TargetTransformInfo.cpp"
, 190, __extension__ __PRETTY_FUNCTION__))
;
191 if (TyWidth == 32 || TyWidth == 64)
192 return TTI::PSK_FastHardware;
193 // TODO: AArch64TargetLowering::LowerCTPOP() supports 128bit popcount.
194 return TTI::PSK_Software;
195}
196
197bool AArch64TTIImpl::isWideningInstruction(Type *DstTy, unsigned Opcode,
198 ArrayRef<const Value *> Args) {
199
200 // A helper that returns a vector type from the given type. The number of
201 // elements in type Ty determine the vector width.
202 auto toVectorTy = [&](Type *ArgTy) {
203 return VectorType::get(ArgTy->getScalarType(),
204 DstTy->getVectorNumElements());
205 };
206
207 // Exit early if DstTy is not a vector type whose elements are at least
208 // 16-bits wide.
209 if (!DstTy->isVectorTy() || DstTy->getScalarSizeInBits() < 16)
210 return false;
211
212 // Determine if the operation has a widening variant. We consider both the
213 // "long" (e.g., usubl) and "wide" (e.g., usubw) versions of the
214 // instructions.
215 //
216 // TODO: Add additional widening operations (e.g., mul, shl, etc.) once we
217 // verify that their extending operands are eliminated during code
218 // generation.
219 switch (Opcode) {
220 case Instruction::Add: // UADDL(2), SADDL(2), UADDW(2), SADDW(2).
221 case Instruction::Sub: // USUBL(2), SSUBL(2), USUBW(2), SSUBW(2).
222 break;
223 default:
224 return false;
225 }
226
227 // To be a widening instruction (either the "wide" or "long" versions), the
228 // second operand must be a sign- or zero extend having a single user. We
229 // only consider extends having a single user because they may otherwise not
230 // be eliminated.
231 if (Args.size() != 2 ||
232 (!isa<SExtInst>(Args[1]) && !isa<ZExtInst>(Args[1])) ||
233 !Args[1]->hasOneUse())
234 return false;
235 auto *Extend = cast<CastInst>(Args[1]);
236
237 // Legalize the destination type and ensure it can be used in a widening
238 // operation.
239 auto DstTyL = TLI->getTypeLegalizationCost(DL, DstTy);
240 unsigned DstElTySize = DstTyL.second.getScalarSizeInBits();
241 if (!DstTyL.second.isVector() || DstElTySize != DstTy->getScalarSizeInBits())
242 return false;
243
244 // Legalize the source type and ensure it can be used in a widening
245 // operation.
246 Type *SrcTy = toVectorTy(Extend->getSrcTy());
247 auto SrcTyL = TLI->getTypeLegalizationCost(DL, SrcTy);
248 unsigned SrcElTySize = SrcTyL.second.getScalarSizeInBits();
249 if (!SrcTyL.second.isVector() || SrcElTySize != SrcTy->getScalarSizeInBits())
250 return false;
251
252 // Get the total number of vector elements in the legalized types.
253 unsigned NumDstEls = DstTyL.first * DstTyL.second.getVectorNumElements();
254 unsigned NumSrcEls = SrcTyL.first * SrcTyL.second.getVectorNumElements();
255
256 // Return true if the legalized types have the same number of vector elements
257 // and the destination element type size is twice that of the source type.
258 return NumDstEls == NumSrcEls && 2 * SrcElTySize == DstElTySize;
259}
260
261int AArch64TTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
262 const Instruction *I) {
263 int ISD = TLI->InstructionOpcodeToISD(Opcode);
264 assert(ISD && "Invalid opcode")(static_cast <bool> (ISD && "Invalid opcode") ?
void (0) : __assert_fail ("ISD && \"Invalid opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/AArch64/AArch64TargetTransformInfo.cpp"
, 264, __extension__ __PRETTY_FUNCTION__))
;
265
266 // If the cast is observable, and it is used by a widening instruction (e.g.,
267 // uaddl, saddw, etc.), it may be free.
268 if (I && I->hasOneUse()) {
269 auto *SingleUser = cast<Instruction>(*I->user_begin());
270 SmallVector<const Value *, 4> Operands(SingleUser->operand_values());
271 if (isWideningInstruction(Dst, SingleUser->getOpcode(), Operands)) {
272 // If the cast is the second operand, it is free. We will generate either
273 // a "wide" or "long" version of the widening instruction.
274 if (I == SingleUser->getOperand(1))
275 return 0;
276 // If the cast is not the second operand, it will be free if it looks the
277 // same as the second operand. In this case, we will generate a "long"
278 // version of the widening instruction.
279 if (auto *Cast = dyn_cast<CastInst>(SingleUser->getOperand(1)))
280 if (I->getOpcode() == Cast->getOpcode() &&
281 cast<CastInst>(I)->getSrcTy() == Cast->getSrcTy())
282 return 0;
283 }
284 }
285
286 EVT SrcTy = TLI->getValueType(DL, Src);
287 EVT DstTy = TLI->getValueType(DL, Dst);
288
289 if (!SrcTy.isSimple() || !DstTy.isSimple())
290 return BaseT::getCastInstrCost(Opcode, Dst, Src);
291
292 static const TypeConversionCostTblEntry
293 ConversionTbl[] = {
294 { ISD::TRUNCATE, MVT::v4i16, MVT::v4i32, 1 },
295 { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 0 },
296 { ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 3 },
297 { ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 6 },
298
299 // The number of shll instructions for the extension.
300 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
301 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
302 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 2 },
303 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 2 },
304 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
305 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
306 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 2 },
307 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 2 },
308 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
309 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
310 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
311 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
312 { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 2 },
313 { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 2 },
314 { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
315 { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
316
317 // LowerVectorINT_TO_FP:
318 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
319 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
320 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
321 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
322 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
323 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
324
325 // Complex: to v2f32
326 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 },
327 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 3 },
328 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i64, 2 },
329 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 },
330 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 3 },
331 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i64, 2 },
332
333 // Complex: to v4f32
334 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 4 },
335 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
336 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 },
337 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
338
339 // Complex: to v8f32
340 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i8, 10 },
341 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
342 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8, 10 },
343 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
344
345 // Complex: to v16f32
346 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i8, 21 },
347 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i8, 21 },
348
349 // Complex: to v2f64
350 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 },
351 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 4 },
352 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
353 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 },
354 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 4 },
355 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
356
357
358 // LowerVectorFP_TO_INT
359 { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f32, 1 },
360 { ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1 },
361 { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f64, 1 },
362 { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f32, 1 },
363 { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 },
364 { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f64, 1 },
365
366 // Complex, from v2f32: legal type is v2i32 (no cost) or v2i64 (1 ext).
367 { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f32, 2 },
368 { ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f32, 1 },
369 { ISD::FP_TO_SINT, MVT::v2i8, MVT::v2f32, 1 },
370 { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f32, 2 },
371 { ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f32, 1 },
372 { ISD::FP_TO_UINT, MVT::v2i8, MVT::v2f32, 1 },
373
374 // Complex, from v4f32: legal type is v4i16, 1 narrowing => ~2
375 { ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 2 },
376 { ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 2 },
377 { ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 2 },
378 { ISD::FP_TO_UINT, MVT::v4i8, MVT::v4f32, 2 },
379
380 // Complex, from v2f64: legal type is v2i32, 1 narrowing => ~2.
381 { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 2 },
382 { ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f64, 2 },
383 { ISD::FP_TO_SINT, MVT::v2i8, MVT::v2f64, 2 },
384 { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 2 },
385 { ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f64, 2 },
386 { ISD::FP_TO_UINT, MVT::v2i8, MVT::v2f64, 2 },
387 };
388
389 if (const auto *Entry = ConvertCostTableLookup(ConversionTbl, ISD,
390 DstTy.getSimpleVT(),
391 SrcTy.getSimpleVT()))
392 return Entry->Cost;
393
394 return BaseT::getCastInstrCost(Opcode, Dst, Src);
395}
396
397int AArch64TTIImpl::getExtractWithExtendCost(unsigned Opcode, Type *Dst,
398 VectorType *VecTy,
399 unsigned Index) {
400
401 // Make sure we were given a valid extend opcode.
402 assert((Opcode == Instruction::SExt || Opcode == Instruction::ZExt) &&(static_cast <bool> ((Opcode == Instruction::SExt || Opcode
== Instruction::ZExt) && "Invalid opcode") ? void (0
) : __assert_fail ("(Opcode == Instruction::SExt || Opcode == Instruction::ZExt) && \"Invalid opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/AArch64/AArch64TargetTransformInfo.cpp"
, 403, __extension__ __PRETTY_FUNCTION__))
403 "Invalid opcode")(static_cast <bool> ((Opcode == Instruction::SExt || Opcode
== Instruction::ZExt) && "Invalid opcode") ? void (0
) : __assert_fail ("(Opcode == Instruction::SExt || Opcode == Instruction::ZExt) && \"Invalid opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/AArch64/AArch64TargetTransformInfo.cpp"
, 403, __extension__ __PRETTY_FUNCTION__))
;
404
405 // We are extending an element we extract from a vector, so the source type
406 // of the extend is the element type of the vector.
407 auto *Src = VecTy->getElementType();
408
409 // Sign- and zero-extends are for integer types only.
410 assert(isa<IntegerType>(Dst) && isa<IntegerType>(Src) && "Invalid type")(static_cast <bool> (isa<IntegerType>(Dst) &&
isa<IntegerType>(Src) && "Invalid type") ? void
(0) : __assert_fail ("isa<IntegerType>(Dst) && isa<IntegerType>(Src) && \"Invalid type\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/AArch64/AArch64TargetTransformInfo.cpp"
, 410, __extension__ __PRETTY_FUNCTION__))
;
411
412 // Get the cost for the extract. We compute the cost (if any) for the extend
413 // below.
414 auto Cost = getVectorInstrCost(Instruction::ExtractElement, VecTy, Index);
415
416 // Legalize the types.
417 auto VecLT = TLI->getTypeLegalizationCost(DL, VecTy);
418 auto DstVT = TLI->getValueType(DL, Dst);
419 auto SrcVT = TLI->getValueType(DL, Src);
420
421 // If the resulting type is still a vector and the destination type is legal,
422 // we may get the extension for free. If not, get the default cost for the
423 // extend.
424 if (!VecLT.second.isVector() || !TLI->isTypeLegal(DstVT))
425 return Cost + getCastInstrCost(Opcode, Dst, Src);
426
427 // The destination type should be larger than the element type. If not, get
428 // the default cost for the extend.
429 if (DstVT.getSizeInBits() < SrcVT.getSizeInBits())
430 return Cost + getCastInstrCost(Opcode, Dst, Src);
431
432 switch (Opcode) {
433 default:
434 llvm_unreachable("Opcode should be either SExt or ZExt")::llvm::llvm_unreachable_internal("Opcode should be either SExt or ZExt"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/AArch64/AArch64TargetTransformInfo.cpp"
, 434)
;
435
436 // For sign-extends, we only need a smov, which performs the extension
437 // automatically.
438 case Instruction::SExt:
439 return Cost;
440
441 // For zero-extends, the extend is performed automatically by a umov unless
442 // the destination type is i64 and the element type is i8 or i16.
443 case Instruction::ZExt:
444 if (DstVT.getSizeInBits() != 64u || SrcVT.getSizeInBits() == 32u)
445 return Cost;
446 }
447
448 // If we are unable to perform the extend for free, get the default cost.
449 return Cost + getCastInstrCost(Opcode, Dst, Src);
450}
451
452int AArch64TTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val,
453 unsigned Index) {
454 assert(Val->isVectorTy() && "This must be a vector type")(static_cast <bool> (Val->isVectorTy() && "This must be a vector type"
) ? void (0) : __assert_fail ("Val->isVectorTy() && \"This must be a vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/AArch64/AArch64TargetTransformInfo.cpp"
, 454, __extension__ __PRETTY_FUNCTION__))
;
455
456 if (Index != -1U) {
457 // Legalize the type.
458 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Val);
459
460 // This type is legalized to a scalar type.
461 if (!LT.second.isVector())
462 return 0;
463
464 // The type may be split. Normalize the index to the new type.
465 unsigned Width = LT.second.getVectorNumElements();
466 Index = Index % Width;
467
468 // The element at index zero is already inside the vector.
469 if (Index == 0)
470 return 0;
471 }
472
473 // All other insert/extracts cost this much.
474 return ST->getVectorInsertExtractBaseCost();
475}
476
477int AArch64TTIImpl::getArithmeticInstrCost(
478 unsigned Opcode, Type *Ty, TTI::OperandValueKind Opd1Info,
479 TTI::OperandValueKind Opd2Info, TTI::OperandValueProperties Opd1PropInfo,
480 TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args) {
481 // Legalize the type.
482 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
483
484 // If the instruction is a widening instruction (e.g., uaddl, saddw, etc.),
485 // add in the widening overhead specified by the sub-target. Since the
486 // extends feeding widening instructions are performed automatically, they
487 // aren't present in the generated code and have a zero cost. By adding a
488 // widening overhead here, we attach the total cost of the combined operation
489 // to the widening instruction.
490 int Cost = 0;
491 if (isWideningInstruction(Ty, Opcode, Args))
492 Cost += ST->getWideningBaseCost();
493
494 int ISD = TLI->InstructionOpcodeToISD(Opcode);
495
496 if (ISD == ISD::SDIV &&
497 Opd2Info == TargetTransformInfo::OK_UniformConstantValue &&
498 Opd2PropInfo == TargetTransformInfo::OP_PowerOf2) {
499 // On AArch64, scalar signed division by constants power-of-two are
500 // normally expanded to the sequence ADD + CMP + SELECT + SRA.
501 // The OperandValue properties many not be same as that of previous
502 // operation; conservatively assume OP_None.
503 Cost += getArithmeticInstrCost(Instruction::Add, Ty, Opd1Info, Opd2Info,
504 TargetTransformInfo::OP_None,
505 TargetTransformInfo::OP_None);
506 Cost += getArithmeticInstrCost(Instruction::Sub, Ty, Opd1Info, Opd2Info,
507 TargetTransformInfo::OP_None,
508 TargetTransformInfo::OP_None);
509 Cost += getArithmeticInstrCost(Instruction::Select, Ty, Opd1Info, Opd2Info,
510 TargetTransformInfo::OP_None,
511 TargetTransformInfo::OP_None);
512 Cost += getArithmeticInstrCost(Instruction::AShr, Ty, Opd1Info, Opd2Info,
513 TargetTransformInfo::OP_None,
514 TargetTransformInfo::OP_None);
515 return Cost;
516 }
517
518 switch (ISD) {
519 default:
520 return Cost + BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info,
521 Opd1PropInfo, Opd2PropInfo);
522 case ISD::ADD:
523 case ISD::MUL:
524 case ISD::XOR:
525 case ISD::OR:
526 case ISD::AND:
527 // These nodes are marked as 'custom' for combining purposes only.
528 // We know that they are legal. See LowerAdd in ISelLowering.
529 return (Cost + 1) * LT.first;
530 }
531}
532
533int AArch64TTIImpl::getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
534 const SCEV *Ptr) {
535 // Address computations in vectorized code with non-consecutive addresses will
536 // likely result in more instructions compared to scalar code where the
537 // computation can more often be merged into the index mode. The resulting
538 // extra micro-ops can significantly decrease throughput.
539 unsigned NumVectorInstToHideOverhead = 10;
540 int MaxMergeDistance = 64;
541
542 if (Ty->isVectorTy() && SE &&
543 !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
544 return NumVectorInstToHideOverhead;
545
546 // In many cases the address computation is not merged into the instruction
547 // addressing mode.
548 return 1;
549}
550
551int AArch64TTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
552 Type *CondTy, const Instruction *I) {
553
554 int ISD = TLI->InstructionOpcodeToISD(Opcode);
555 // We don't lower some vector selects well that are wider than the register
556 // width.
557 if (ValTy->isVectorTy() && ISD == ISD::SELECT) {
11
Assuming 'ISD' is equal to SELECT
12
Taking true branch
558 // We would need this many instructions to hide the scalarization happening.
559 const int AmortizationCost = 20;
560 static const TypeConversionCostTblEntry
561 VectorSelectTbl[] = {
562 { ISD::SELECT, MVT::v16i1, MVT::v16i16, 16 },
563 { ISD::SELECT, MVT::v8i1, MVT::v8i32, 8 },
564 { ISD::SELECT, MVT::v16i1, MVT::v16i32, 16 },
565 { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4 * AmortizationCost },
566 { ISD::SELECT, MVT::v8i1, MVT::v8i64, 8 * AmortizationCost },
567 { ISD::SELECT, MVT::v16i1, MVT::v16i64, 16 * AmortizationCost }
568 };
569
570 EVT SelCondTy = TLI->getValueType(DL, CondTy);
13
Passing null pointer value via 2nd parameter 'Ty'
14
Calling 'TargetLoweringBase::getValueType'
571 EVT SelValTy = TLI->getValueType(DL, ValTy);
572 if (SelCondTy.isSimple() && SelValTy.isSimple()) {
573 if (const auto *Entry = ConvertCostTableLookup(VectorSelectTbl, ISD,
574 SelCondTy.getSimpleVT(),
575 SelValTy.getSimpleVT()))
576 return Entry->Cost;
577 }
578 }
579 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, I);
1
Passing value via 3rd parameter 'CondTy'
2
Calling 'BasicTTIImplBase::getCmpSelInstrCost'
580}
581
582int AArch64TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Ty,
583 unsigned Alignment, unsigned AddressSpace,
584 const Instruction *I) {
585 auto LT = TLI->getTypeLegalizationCost(DL, Ty);
586
587 if (ST->isMisaligned128StoreSlow() && Opcode == Instruction::Store &&
588 LT.second.is128BitVector() && Alignment < 16) {
589 // Unaligned stores are extremely inefficient. We don't split all
590 // unaligned 128-bit stores because the negative impact that has shown in
591 // practice on inlined block copy code.
592 // We make such stores expensive so that we will only vectorize if there
593 // are 6 other instructions getting vectorized.
594 const int AmortizationCost = 6;
595
596 return LT.first * 2 * AmortizationCost;
597 }
598
599 if (Ty->isVectorTy() && Ty->getVectorElementType()->isIntegerTy(8) &&
600 Ty->getVectorNumElements() < 8) {
601 // We scalarize the loads/stores because there is not v.4b register and we
602 // have to promote the elements to v.4h.
603 unsigned NumVecElts = Ty->getVectorNumElements();
604 unsigned NumVectorizableInstsToAmortize = NumVecElts * 2;
605 // We generate 2 instructions per vector element.
606 return NumVectorizableInstsToAmortize * NumVecElts * 2;
607 }
608
609 return LT.first;
610}
611
612int AArch64TTIImpl::getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
613 unsigned Factor,
614 ArrayRef<unsigned> Indices,
615 unsigned Alignment,
616 unsigned AddressSpace) {
617 assert(Factor >= 2 && "Invalid interleave factor")(static_cast <bool> (Factor >= 2 && "Invalid interleave factor"
) ? void (0) : __assert_fail ("Factor >= 2 && \"Invalid interleave factor\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/AArch64/AArch64TargetTransformInfo.cpp"
, 617, __extension__ __PRETTY_FUNCTION__))
;
618 assert(isa<VectorType>(VecTy) && "Expect a vector type")(static_cast <bool> (isa<VectorType>(VecTy) &&
"Expect a vector type") ? void (0) : __assert_fail ("isa<VectorType>(VecTy) && \"Expect a vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/AArch64/AArch64TargetTransformInfo.cpp"
, 618, __extension__ __PRETTY_FUNCTION__))
;
619
620 if (Factor <= TLI->getMaxSupportedInterleaveFactor()) {
621 unsigned NumElts = VecTy->getVectorNumElements();
622 auto *SubVecTy = VectorType::get(VecTy->getScalarType(), NumElts / Factor);
623
624 // ldN/stN only support legal vector types of size 64 or 128 in bits.
625 // Accesses having vector types that are a multiple of 128 bits can be
626 // matched to more than one ldN/stN instruction.
627 if (NumElts % Factor == 0 &&
628 TLI->isLegalInterleavedAccessType(SubVecTy, DL))
629 return Factor * TLI->getNumInterleavedAccesses(SubVecTy, DL);
630 }
631
632 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
633 Alignment, AddressSpace);
634}
635
636int AArch64TTIImpl::getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) {
637 int Cost = 0;
638 for (auto *I : Tys) {
639 if (!I->isVectorTy())
640 continue;
641 if (I->getScalarSizeInBits() * I->getVectorNumElements() == 128)
642 Cost += getMemoryOpCost(Instruction::Store, I, 128, 0) +
643 getMemoryOpCost(Instruction::Load, I, 128, 0);
644 }
645 return Cost;
646}
647
648unsigned AArch64TTIImpl::getMaxInterleaveFactor(unsigned VF) {
649 return ST->getMaxInterleaveFactor();
650}
651
652// For Falkor, we want to avoid having too many strided loads in a loop since
653// that can exhaust the HW prefetcher resources. We adjust the unroller
654// MaxCount preference below to attempt to ensure unrolling doesn't create too
655// many strided loads.
656static void
657getFalkorUnrollingPreferences(Loop *L, ScalarEvolution &SE,
658 TargetTransformInfo::UnrollingPreferences &UP) {
659 enum { MaxStridedLoads = 7 };
660 auto countStridedLoads = [](Loop *L, ScalarEvolution &SE) {
661 int StridedLoads = 0;
662 // FIXME? We could make this more precise by looking at the CFG and
663 // e.g. not counting loads in each side of an if-then-else diamond.
664 for (const auto BB : L->blocks()) {
665 for (auto &I : *BB) {
666 LoadInst *LMemI = dyn_cast<LoadInst>(&I);
667 if (!LMemI)
668 continue;
669
670 Value *PtrValue = LMemI->getPointerOperand();
671 if (L->isLoopInvariant(PtrValue))
672 continue;
673
674 const SCEV *LSCEV = SE.getSCEV(PtrValue);
675 const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
676 if (!LSCEVAddRec || !LSCEVAddRec->isAffine())
677 continue;
678
679 // FIXME? We could take pairing of unrolled load copies into account
680 // by looking at the AddRec, but we would probably have to limit this
681 // to loops with no stores or other memory optimization barriers.
682 ++StridedLoads;
683 // We've seen enough strided loads that seeing more won't make a
684 // difference.
685 if (StridedLoads > MaxStridedLoads / 2)
686 return StridedLoads;
687 }
688 }
689 return StridedLoads;
690 };
691
692 int StridedLoads = countStridedLoads(L, SE);
693 DEBUG(dbgs() << "falkor-hwpf: detected " << StridedLoadsdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("aarch64tti")) { dbgs() << "falkor-hwpf: detected " <<
StridedLoads << " strided loads\n"; } } while (false)
694 << " strided loads\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("aarch64tti")) { dbgs() << "falkor-hwpf: detected " <<
StridedLoads << " strided loads\n"; } } while (false)
;
695 // Pick the largest power of 2 unroll count that won't result in too many
696 // strided loads.
697 if (StridedLoads) {
698 UP.MaxCount = 1 << Log2_32(MaxStridedLoads / StridedLoads);
699 DEBUG(dbgs() << "falkor-hwpf: setting unroll MaxCount to " << UP.MaxCountdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("aarch64tti")) { dbgs() << "falkor-hwpf: setting unroll MaxCount to "
<< UP.MaxCount << '\n'; } } while (false)
700 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("aarch64tti")) { dbgs() << "falkor-hwpf: setting unroll MaxCount to "
<< UP.MaxCount << '\n'; } } while (false)
;
701 }
702}
703
704void AArch64TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
705 TTI::UnrollingPreferences &UP) {
706 // Enable partial unrolling and runtime unrolling.
707 BaseT::getUnrollingPreferences(L, SE, UP);
708
709 // For inner loop, it is more likely to be a hot one, and the runtime check
710 // can be promoted out from LICM pass, so the overhead is less, let's try
711 // a larger threshold to unroll more loops.
712 if (L->getLoopDepth() > 1)
713 UP.PartialThreshold *= 2;
714
715 // Disable partial & runtime unrolling on -Os.
716 UP.PartialOptSizeThreshold = 0;
717
718 if (ST->getProcFamily() == AArch64Subtarget::Falkor &&
719 EnableFalkorHWPFUnrollFix)
720 getFalkorUnrollingPreferences(L, SE, UP);
721}
722
723Value *AArch64TTIImpl::getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
724 Type *ExpectedType) {
725 switch (Inst->getIntrinsicID()) {
726 default:
727 return nullptr;
728 case Intrinsic::aarch64_neon_st2:
729 case Intrinsic::aarch64_neon_st3:
730 case Intrinsic::aarch64_neon_st4: {
731 // Create a struct type
732 StructType *ST = dyn_cast<StructType>(ExpectedType);
733 if (!ST)
734 return nullptr;
735 unsigned NumElts = Inst->getNumArgOperands() - 1;
736 if (ST->getNumElements() != NumElts)
737 return nullptr;
738 for (unsigned i = 0, e = NumElts; i != e; ++i) {
739 if (Inst->getArgOperand(i)->getType() != ST->getElementType(i))
740 return nullptr;
741 }
742 Value *Res = UndefValue::get(ExpectedType);
743 IRBuilder<> Builder(Inst);
744 for (unsigned i = 0, e = NumElts; i != e; ++i) {
745 Value *L = Inst->getArgOperand(i);
746 Res = Builder.CreateInsertValue(Res, L, i);
747 }
748 return Res;
749 }
750 case Intrinsic::aarch64_neon_ld2:
751 case Intrinsic::aarch64_neon_ld3:
752 case Intrinsic::aarch64_neon_ld4:
753 if (Inst->getType() == ExpectedType)
754 return Inst;
755 return nullptr;
756 }
757}
758
759bool AArch64TTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst,
760 MemIntrinsicInfo &Info) {
761 switch (Inst->getIntrinsicID()) {
762 default:
763 break;
764 case Intrinsic::aarch64_neon_ld2:
765 case Intrinsic::aarch64_neon_ld3:
766 case Intrinsic::aarch64_neon_ld4:
767 Info.ReadMem = true;
768 Info.WriteMem = false;
769 Info.PtrVal = Inst->getArgOperand(0);
770 break;
771 case Intrinsic::aarch64_neon_st2:
772 case Intrinsic::aarch64_neon_st3:
773 case Intrinsic::aarch64_neon_st4:
774 Info.ReadMem = false;
775 Info.WriteMem = true;
776 Info.PtrVal = Inst->getArgOperand(Inst->getNumArgOperands() - 1);
777 break;
778 }
779
780 switch (Inst->getIntrinsicID()) {
781 default:
782 return false;
783 case Intrinsic::aarch64_neon_ld2:
784 case Intrinsic::aarch64_neon_st2:
785 Info.MatchingId = VECTOR_LDST_TWO_ELEMENTS;
786 break;
787 case Intrinsic::aarch64_neon_ld3:
788 case Intrinsic::aarch64_neon_st3:
789 Info.MatchingId = VECTOR_LDST_THREE_ELEMENTS;
790 break;
791 case Intrinsic::aarch64_neon_ld4:
792 case Intrinsic::aarch64_neon_st4:
793 Info.MatchingId = VECTOR_LDST_FOUR_ELEMENTS;
794 break;
795 }
796 return true;
797}
798
799/// See if \p I should be considered for address type promotion. We check if \p
800/// I is a sext with right type and used in memory accesses. If it used in a
801/// "complex" getelementptr, we allow it to be promoted without finding other
802/// sext instructions that sign extended the same initial value. A getelementptr
803/// is considered as "complex" if it has more than 2 operands.
804bool AArch64TTIImpl::shouldConsiderAddressTypePromotion(
805 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) {
806 bool Considerable = false;
807 AllowPromotionWithoutCommonHeader = false;
808 if (!isa<SExtInst>(&I))
809 return false;
810 Type *ConsideredSExtType =
811 Type::getInt64Ty(I.getParent()->getParent()->getContext());
812 if (I.getType() != ConsideredSExtType)
813 return false;
814 // See if the sext is the one with the right type and used in at least one
815 // GetElementPtrInst.
816 for (const User *U : I.users()) {
817 if (const GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(U)) {
818 Considerable = true;
819 // A getelementptr is considered as "complex" if it has more than 2
820 // operands. We will promote a SExt used in such complex GEP as we
821 // expect some computation to be merged if they are done on 64 bits.
822 if (GEPInst->getNumOperands() > 2) {
823 AllowPromotionWithoutCommonHeader = true;
824 break;
825 }
826 }
827 }
828 return Considerable;
829}
830
831unsigned AArch64TTIImpl::getCacheLineSize() {
832 return ST->getCacheLineSize();
833}
834
835unsigned AArch64TTIImpl::getPrefetchDistance() {
836 return ST->getPrefetchDistance();
837}
838
839unsigned AArch64TTIImpl::getMinPrefetchStride() {
840 return ST->getMinPrefetchStride();
841}
842
843unsigned AArch64TTIImpl::getMaxPrefetchIterationsAhead() {
844 return ST->getMaxPrefetchIterationsAhead();
845}
846
847bool AArch64TTIImpl::useReductionIntrinsic(unsigned Opcode, Type *Ty,
848 TTI::ReductionFlags Flags) const {
849 assert(isa<VectorType>(Ty) && "Expected Ty to be a vector type")(static_cast <bool> (isa<VectorType>(Ty) &&
"Expected Ty to be a vector type") ? void (0) : __assert_fail
("isa<VectorType>(Ty) && \"Expected Ty to be a vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/AArch64/AArch64TargetTransformInfo.cpp"
, 849, __extension__ __PRETTY_FUNCTION__))
;
850 unsigned ScalarBits = Ty->getScalarSizeInBits();
851 switch (Opcode) {
852 case Instruction::FAdd:
853 case Instruction::FMul:
854 case Instruction::And:
855 case Instruction::Or:
856 case Instruction::Xor:
857 case Instruction::Mul:
858 return false;
859 case Instruction::Add:
860 return ScalarBits * Ty->getVectorNumElements() >= 128;
861 case Instruction::ICmp:
862 return (ScalarBits < 64) &&
863 (ScalarBits * Ty->getVectorNumElements() >= 128);
864 case Instruction::FCmp:
865 return Flags.NoNaN;
866 default:
867 llvm_unreachable("Unhandled reduction opcode")::llvm::llvm_unreachable_internal("Unhandled reduction opcode"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/AArch64/AArch64TargetTransformInfo.cpp"
, 867)
;
868 }
869 return false;
870}

/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h

1//===- BasicTTIImpl.h -------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file
11/// This file provides a helper that implements much of the TTI interface in
12/// terms of the target-independent code generator and TargetLowering
13/// interfaces.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CODEGEN_BASICTTIIMPL_H
18#define LLVM_CODEGEN_BASICTTIIMPL_H
19
20#include "llvm/ADT/APInt.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/BitVector.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/Analysis/LoopInfo.h"
26#include "llvm/Analysis/TargetTransformInfo.h"
27#include "llvm/Analysis/TargetTransformInfoImpl.h"
28#include "llvm/CodeGen/ISDOpcodes.h"
29#include "llvm/CodeGen/MachineValueType.h"
30#include "llvm/CodeGen/TargetLowering.h"
31#include "llvm/CodeGen/TargetSubtargetInfo.h"
32#include "llvm/CodeGen/ValueTypes.h"
33#include "llvm/IR/BasicBlock.h"
34#include "llvm/IR/CallSite.h"
35#include "llvm/IR/Constant.h"
36#include "llvm/IR/Constants.h"
37#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/DerivedTypes.h"
39#include "llvm/IR/InstrTypes.h"
40#include "llvm/IR/Instruction.h"
41#include "llvm/IR/Instructions.h"
42#include "llvm/IR/Intrinsics.h"
43#include "llvm/IR/Operator.h"
44#include "llvm/IR/Type.h"
45#include "llvm/IR/Value.h"
46#include "llvm/MC/MCSchedule.h"
47#include "llvm/Support/Casting.h"
48#include "llvm/Support/CommandLine.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/MathExtras.h"
51#include <algorithm>
52#include <cassert>
53#include <cstdint>
54#include <limits>
55#include <utility>
56
57namespace llvm {
58
59class Function;
60class GlobalValue;
61class LLVMContext;
62class ScalarEvolution;
63class SCEV;
64class TargetMachine;
65
66extern cl::opt<unsigned> PartialUnrollingThreshold;
67
68/// \brief Base class which can be used to help build a TTI implementation.
69///
70/// This class provides as much implementation of the TTI interface as is
71/// possible using the target independent parts of the code generator.
72///
73/// In order to subclass it, your class must implement a getST() method to
74/// return the subtarget, and a getTLI() method to return the target lowering.
75/// We need these methods implemented in the derived class so that this class
76/// doesn't have to duplicate storage for them.
77template <typename T>
78class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
79private:
80 using BaseT = TargetTransformInfoImplCRTPBase<T>;
81 using TTI = TargetTransformInfo;
82
83 /// Estimate a cost of shuffle as a sequence of extract and insert
84 /// operations.
85 unsigned getPermuteShuffleOverhead(Type *Ty) {
86 assert(Ty->isVectorTy() && "Can only shuffle vectors")(static_cast <bool> (Ty->isVectorTy() && "Can only shuffle vectors"
) ? void (0) : __assert_fail ("Ty->isVectorTy() && \"Can only shuffle vectors\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 86, __extension__ __PRETTY_FUNCTION__))
;
87 unsigned Cost = 0;
88 // Shuffle cost is equal to the cost of extracting element from its argument
89 // plus the cost of inserting them onto the result vector.
90
91 // e.g. <4 x float> has a mask of <0,5,2,7> i.e we need to extract from
92 // index 0 of first vector, index 1 of second vector,index 2 of first
93 // vector and finally index 3 of second vector and insert them at index
94 // <0,1,2,3> of result vector.
95 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
96 Cost += static_cast<T *>(this)
97 ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
98 Cost += static_cast<T *>(this)
99 ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
100 }
101 return Cost;
102 }
103
104 /// \brief Local query method delegates up to T which *must* implement this!
105 const TargetSubtargetInfo *getST() const {
106 return static_cast<const T *>(this)->getST();
107 }
108
109 /// \brief Local query method delegates up to T which *must* implement this!
110 const TargetLoweringBase *getTLI() const {
111 return static_cast<const T *>(this)->getTLI();
112 }
113
114protected:
115 explicit BasicTTIImplBase(const TargetMachine *TM, const DataLayout &DL)
116 : BaseT(DL) {}
117
118 using TargetTransformInfoImplBase::DL;
119
120public:
121 /// \name Scalar TTI Implementations
122 /// @{
123 bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
124 unsigned BitWidth, unsigned AddressSpace,
125 unsigned Alignment, bool *Fast) const {
126 EVT E = EVT::getIntegerVT(Context, BitWidth);
127 return getTLI()->allowsMisalignedMemoryAccesses(E, AddressSpace, Alignment, Fast);
128 }
129
130 bool hasBranchDivergence() { return false; }
131
132 bool isSourceOfDivergence(const Value *V) { return false; }
133
134 bool isAlwaysUniform(const Value *V) { return false; }
135
136 unsigned getFlatAddressSpace() {
137 // Return an invalid address space.
138 return -1;
139 }
140
141 bool isLegalAddImmediate(int64_t imm) {
142 return getTLI()->isLegalAddImmediate(imm);
143 }
144
145 bool isLegalICmpImmediate(int64_t imm) {
146 return getTLI()->isLegalICmpImmediate(imm);
147 }
148
149 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
150 bool HasBaseReg, int64_t Scale,
151 unsigned AddrSpace, Instruction *I = nullptr) {
152 TargetLoweringBase::AddrMode AM;
153 AM.BaseGV = BaseGV;
154 AM.BaseOffs = BaseOffset;
155 AM.HasBaseReg = HasBaseReg;
156 AM.Scale = Scale;
157 return getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace, I);
158 }
159
160 bool isLSRCostLess(TTI::LSRCost C1, TTI::LSRCost C2) {
161 return TargetTransformInfoImplBase::isLSRCostLess(C1, C2);
162 }
163
164 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
165 bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
166 TargetLoweringBase::AddrMode AM;
167 AM.BaseGV = BaseGV;
168 AM.BaseOffs = BaseOffset;
169 AM.HasBaseReg = HasBaseReg;
170 AM.Scale = Scale;
171 return getTLI()->getScalingFactorCost(DL, AM, Ty, AddrSpace);
172 }
173
174 bool isTruncateFree(Type *Ty1, Type *Ty2) {
175 return getTLI()->isTruncateFree(Ty1, Ty2);
176 }
177
178 bool isProfitableToHoist(Instruction *I) {
179 return getTLI()->isProfitableToHoist(I);
180 }
181
182 bool isTypeLegal(Type *Ty) {
183 EVT VT = getTLI()->getValueType(DL, Ty);
184 return getTLI()->isTypeLegal(VT);
185 }
186
187 int getGEPCost(Type *PointeeType, const Value *Ptr,
188 ArrayRef<const Value *> Operands) {
189 return BaseT::getGEPCost(PointeeType, Ptr, Operands);
190 }
191
192 int getExtCost(const Instruction *I, const Value *Src) {
193 if (getTLI()->isExtFree(I))
194 return TargetTransformInfo::TCC_Free;
195
196 if (isa<ZExtInst>(I) || isa<SExtInst>(I))
197 if (const LoadInst *LI = dyn_cast<LoadInst>(Src))
198 if (getTLI()->isExtLoad(LI, I, DL))
199 return TargetTransformInfo::TCC_Free;
200
201 return TargetTransformInfo::TCC_Basic;
202 }
203
204 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
205 ArrayRef<const Value *> Arguments) {
206 return BaseT::getIntrinsicCost(IID, RetTy, Arguments);
207 }
208
209 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
210 ArrayRef<Type *> ParamTys) {
211 if (IID == Intrinsic::cttz) {
212 if (getTLI()->isCheapToSpeculateCttz())
213 return TargetTransformInfo::TCC_Basic;
214 return TargetTransformInfo::TCC_Expensive;
215 }
216
217 if (IID == Intrinsic::ctlz) {
218 if (getTLI()->isCheapToSpeculateCtlz())
219 return TargetTransformInfo::TCC_Basic;
220 return TargetTransformInfo::TCC_Expensive;
221 }
222
223 return BaseT::getIntrinsicCost(IID, RetTy, ParamTys);
224 }
225
226 unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
227 unsigned &JumpTableSize) {
228 /// Try to find the estimated number of clusters. Note that the number of
229 /// clusters identified in this function could be different from the actural
230 /// numbers found in lowering. This function ignore switches that are
231 /// lowered with a mix of jump table / bit test / BTree. This function was
232 /// initially intended to be used when estimating the cost of switch in
233 /// inline cost heuristic, but it's a generic cost model to be used in other
234 /// places (e.g., in loop unrolling).
235 unsigned N = SI.getNumCases();
236 const TargetLoweringBase *TLI = getTLI();
237 const DataLayout &DL = this->getDataLayout();
238
239 JumpTableSize = 0;
240 bool IsJTAllowed = TLI->areJTsAllowed(SI.getParent()->getParent());
241
242 // Early exit if both a jump table and bit test are not allowed.
243 if (N < 1 || (!IsJTAllowed && DL.getPointerSizeInBits() < N))
244 return N;
245
246 APInt MaxCaseVal = SI.case_begin()->getCaseValue()->getValue();
247 APInt MinCaseVal = MaxCaseVal;
248 for (auto CI : SI.cases()) {
249 const APInt &CaseVal = CI.getCaseValue()->getValue();
250 if (CaseVal.sgt(MaxCaseVal))
251 MaxCaseVal = CaseVal;
252 if (CaseVal.slt(MinCaseVal))
253 MinCaseVal = CaseVal;
254 }
255
256 // Check if suitable for a bit test
257 if (N <= DL.getPointerSizeInBits()) {
258 SmallPtrSet<const BasicBlock *, 4> Dests;
259 for (auto I : SI.cases())
260 Dests.insert(I.getCaseSuccessor());
261
262 if (TLI->isSuitableForBitTests(Dests.size(), N, MinCaseVal, MaxCaseVal,
263 DL))
264 return 1;
265 }
266
267 // Check if suitable for a jump table.
268 if (IsJTAllowed) {
269 if (N < 2 || N < TLI->getMinimumJumpTableEntries())
270 return N;
271 uint64_t Range =
272 (MaxCaseVal - MinCaseVal)
273 .getLimitedValue(std::numeric_limits<uint64_t>::max() - 1) + 1;
274 // Check whether a range of clusters is dense enough for a jump table
275 if (TLI->isSuitableForJumpTable(&SI, N, Range)) {
276 JumpTableSize = Range;
277 return 1;
278 }
279 }
280 return N;
281 }
282
283 unsigned getJumpBufAlignment() { return getTLI()->getJumpBufAlignment(); }
284
285 unsigned getJumpBufSize() { return getTLI()->getJumpBufSize(); }
286
287 bool shouldBuildLookupTables() {
288 const TargetLoweringBase *TLI = getTLI();
289 return TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
290 TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
291 }
292
293 bool haveFastSqrt(Type *Ty) {
294 const TargetLoweringBase *TLI = getTLI();
295 EVT VT = TLI->getValueType(DL, Ty);
296 return TLI->isTypeLegal(VT) &&
297 TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
298 }
299
300 bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) {
301 return true;
302 }
303
304 unsigned getFPOpCost(Type *Ty) {
305 // Check whether FADD is available, as a proxy for floating-point in
306 // general.
307 const TargetLoweringBase *TLI = getTLI();
308 EVT VT = TLI->getValueType(DL, Ty);
309 if (TLI->isOperationLegalOrCustomOrPromote(ISD::FADD, VT))
310 return TargetTransformInfo::TCC_Basic;
311 return TargetTransformInfo::TCC_Expensive;
312 }
313
314 unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
315 const TargetLoweringBase *TLI = getTLI();
316 switch (Opcode) {
317 default: break;
318 case Instruction::Trunc:
319 if (TLI->isTruncateFree(OpTy, Ty))
320 return TargetTransformInfo::TCC_Free;
321 return TargetTransformInfo::TCC_Basic;
322 case Instruction::ZExt:
323 if (TLI->isZExtFree(OpTy, Ty))
324 return TargetTransformInfo::TCC_Free;
325 return TargetTransformInfo::TCC_Basic;
326 }
327
328 return BaseT::getOperationCost(Opcode, Ty, OpTy);
329 }
330
331 unsigned getInliningThresholdMultiplier() { return 1; }
332
333 void getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
334 TTI::UnrollingPreferences &UP) {
335 // This unrolling functionality is target independent, but to provide some
336 // motivation for its intended use, for x86:
337
338 // According to the Intel 64 and IA-32 Architectures Optimization Reference
339 // Manual, Intel Core models and later have a loop stream detector (and
340 // associated uop queue) that can benefit from partial unrolling.
341 // The relevant requirements are:
342 // - The loop must have no more than 4 (8 for Nehalem and later) branches
343 // taken, and none of them may be calls.
344 // - The loop can have no more than 18 (28 for Nehalem and later) uops.
345
346 // According to the Software Optimization Guide for AMD Family 15h
347 // Processors, models 30h-4fh (Steamroller and later) have a loop predictor
348 // and loop buffer which can benefit from partial unrolling.
349 // The relevant requirements are:
350 // - The loop must have fewer than 16 branches
351 // - The loop must have less than 40 uops in all executed loop branches
352
353 // The number of taken branches in a loop is hard to estimate here, and
354 // benchmarking has revealed that it is better not to be conservative when
355 // estimating the branch count. As a result, we'll ignore the branch limits
356 // until someone finds a case where it matters in practice.
357
358 unsigned MaxOps;
359 const TargetSubtargetInfo *ST = getST();
360 if (PartialUnrollingThreshold.getNumOccurrences() > 0)
361 MaxOps = PartialUnrollingThreshold;
362 else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
363 MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
364 else
365 return;
366
367 // Scan the loop: don't unroll loops with calls.
368 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
369 ++I) {
370 BasicBlock *BB = *I;
371
372 for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
373 if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
374 ImmutableCallSite CS(&*J);
375 if (const Function *F = CS.getCalledFunction()) {
376 if (!static_cast<T *>(this)->isLoweredToCall(F))
377 continue;
378 }
379
380 return;
381 }
382 }
383
384 // Enable runtime and partial unrolling up to the specified size.
385 // Enable using trip count upper bound to unroll loops.
386 UP.Partial = UP.Runtime = UP.UpperBound = true;
387 UP.PartialThreshold = MaxOps;
388
389 // Avoid unrolling when optimizing for size.
390 UP.OptSizeThreshold = 0;
391 UP.PartialOptSizeThreshold = 0;
392
393 // Set number of instructions optimized when "back edge"
394 // becomes "fall through" to default value of 2.
395 UP.BEInsns = 2;
396 }
397
398 int getInstructionLatency(const Instruction *I) {
399 if (isa<LoadInst>(I))
400 return getST()->getSchedModel().DefaultLoadLatency;
401
402 return BaseT::getInstructionLatency(I);
403 }
404
405 /// @}
406
407 /// \name Vector TTI Implementations
408 /// @{
409
410 unsigned getNumberOfRegisters(bool Vector) { return Vector ? 0 : 1; }
411
412 unsigned getRegisterBitWidth(bool Vector) const { return 32; }
413
414 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
415 /// are set if the result needs to be inserted and/or extracted from vectors.
416 unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
417 assert(Ty->isVectorTy() && "Can only scalarize vectors")(static_cast <bool> (Ty->isVectorTy() && "Can only scalarize vectors"
) ? void (0) : __assert_fail ("Ty->isVectorTy() && \"Can only scalarize vectors\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 417, __extension__ __PRETTY_FUNCTION__))
;
418 unsigned Cost = 0;
419
420 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
421 if (Insert)
422 Cost += static_cast<T *>(this)
423 ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
424 if (Extract)
425 Cost += static_cast<T *>(this)
426 ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
427 }
428
429 return Cost;
430 }
431
432 /// Estimate the overhead of scalarizing an instructions unique
433 /// non-constant operands. The types of the arguments are ordinarily
434 /// scalar, in which case the costs are multiplied with VF.
435 unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
436 unsigned VF) {
437 unsigned Cost = 0;
438 SmallPtrSet<const Value*, 4> UniqueOperands;
439 for (const Value *A : Args) {
440 if (!isa<Constant>(A) && UniqueOperands.insert(A).second) {
441 Type *VecTy = nullptr;
442 if (A->getType()->isVectorTy()) {
443 VecTy = A->getType();
444 // If A is a vector operand, VF should be 1 or correspond to A.
445 assert((VF == 1 || VF == VecTy->getVectorNumElements()) &&(static_cast <bool> ((VF == 1 || VF == VecTy->getVectorNumElements
()) && "Vector argument does not match VF") ? void (0
) : __assert_fail ("(VF == 1 || VF == VecTy->getVectorNumElements()) && \"Vector argument does not match VF\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 446, __extension__ __PRETTY_FUNCTION__))
446 "Vector argument does not match VF")(static_cast <bool> ((VF == 1 || VF == VecTy->getVectorNumElements
()) && "Vector argument does not match VF") ? void (0
) : __assert_fail ("(VF == 1 || VF == VecTy->getVectorNumElements()) && \"Vector argument does not match VF\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 446, __extension__ __PRETTY_FUNCTION__))
;
447 }
448 else
449 VecTy = VectorType::get(A->getType(), VF);
450
451 Cost += getScalarizationOverhead(VecTy, false, true);
452 }
453 }
454
455 return Cost;
456 }
457
458 unsigned getScalarizationOverhead(Type *VecTy, ArrayRef<const Value *> Args) {
459 assert(VecTy->isVectorTy())(static_cast <bool> (VecTy->isVectorTy()) ? void (0)
: __assert_fail ("VecTy->isVectorTy()", "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 459, __extension__ __PRETTY_FUNCTION__))
;
460
461 unsigned Cost = 0;
462
463 Cost += getScalarizationOverhead(VecTy, true, false);
464 if (!Args.empty())
465 Cost += getOperandsScalarizationOverhead(Args,
466 VecTy->getVectorNumElements());
467 else
468 // When no information on arguments is provided, we add the cost
469 // associated with one argument as a heuristic.
470 Cost += getScalarizationOverhead(VecTy, false, true);
471
472 return Cost;
473 }
474
475 unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
476
477 unsigned getArithmeticInstrCost(
478 unsigned Opcode, Type *Ty,
479 TTI::OperandValueKind Opd1Info = TTI::OK_AnyValue,
480 TTI::OperandValueKind Opd2Info = TTI::OK_AnyValue,
481 TTI::OperandValueProperties Opd1PropInfo = TTI::OP_None,
482 TTI::OperandValueProperties Opd2PropInfo = TTI::OP_None,
483 ArrayRef<const Value *> Args = ArrayRef<const Value *>()) {
484 // Check if any of the operands are vector operands.
485 const TargetLoweringBase *TLI = getTLI();
486 int ISD = TLI->InstructionOpcodeToISD(Opcode);
487 assert(ISD && "Invalid opcode")(static_cast <bool> (ISD && "Invalid opcode") ?
void (0) : __assert_fail ("ISD && \"Invalid opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 487, __extension__ __PRETTY_FUNCTION__))
;
488
489 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
490
491 bool IsFloat = Ty->isFPOrFPVectorTy();
492 // Assume that floating point arithmetic operations cost twice as much as
493 // integer operations.
494 unsigned OpCost = (IsFloat ? 2 : 1);
495
496 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
497 // The operation is legal. Assume it costs 1.
498 // TODO: Once we have extract/insert subvector cost we need to use them.
499 return LT.first * OpCost;
500 }
501
502 if (!TLI->isOperationExpand(ISD, LT.second)) {
503 // If the operation is custom lowered, then assume that the code is twice
504 // as expensive.
505 return LT.first * 2 * OpCost;
506 }
507
508 // Else, assume that we need to scalarize this op.
509 // TODO: If one of the types get legalized by splitting, handle this
510 // similarly to what getCastInstrCost() does.
511 if (Ty->isVectorTy()) {
512 unsigned Num = Ty->getVectorNumElements();
513 unsigned Cost = static_cast<T *>(this)
514 ->getArithmeticInstrCost(Opcode, Ty->getScalarType());
515 // Return the cost of multiple scalar invocation plus the cost of
516 // inserting and extracting the values.
517 return getScalarizationOverhead(Ty, Args) + Num * Cost;
518 }
519
520 // We don't know anything about this scalar instruction.
521 return OpCost;
522 }
523
524 unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
525 Type *SubTp) {
526 if (Kind == TTI::SK_Alternate || Kind == TTI::SK_PermuteTwoSrc ||
527 Kind == TTI::SK_PermuteSingleSrc) {
528 return getPermuteShuffleOverhead(Tp);
529 }
530 return 1;
531 }
532
533 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
534 const Instruction *I = nullptr) {
535 const TargetLoweringBase *TLI = getTLI();
536 int ISD = TLI->InstructionOpcodeToISD(Opcode);
537 assert(ISD && "Invalid opcode")(static_cast <bool> (ISD && "Invalid opcode") ?
void (0) : __assert_fail ("ISD && \"Invalid opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 537, __extension__ __PRETTY_FUNCTION__))
;
538 std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(DL, Src);
539 std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(DL, Dst);
540
541 // Check for NOOP conversions.
542 if (SrcLT.first == DstLT.first &&
543 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
544
545 // Bitcast between types that are legalized to the same type are free.
546 if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
547 return 0;
548 }
549
550 if (Opcode == Instruction::Trunc &&
551 TLI->isTruncateFree(SrcLT.second, DstLT.second))
552 return 0;
553
554 if (Opcode == Instruction::ZExt &&
555 TLI->isZExtFree(SrcLT.second, DstLT.second))
556 return 0;
557
558 if (Opcode == Instruction::AddrSpaceCast &&
559 TLI->isNoopAddrSpaceCast(Src->getPointerAddressSpace(),
560 Dst->getPointerAddressSpace()))
561 return 0;
562
563 // If this is a zext/sext of a load, return 0 if the corresponding
564 // extending load exists on target.
565 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
566 I && isa<LoadInst>(I->getOperand(0))) {
567 EVT ExtVT = EVT::getEVT(Dst);
568 EVT LoadVT = EVT::getEVT(Src);
569 unsigned LType =
570 ((Opcode == Instruction::ZExt) ? ISD::ZEXTLOAD : ISD::SEXTLOAD);
571 if (TLI->isLoadExtLegal(LType, ExtVT, LoadVT))
572 return 0;
573 }
574
575 // If the cast is marked as legal (or promote) then assume low cost.
576 if (SrcLT.first == DstLT.first &&
577 TLI->isOperationLegalOrPromote(ISD, DstLT.second))
578 return 1;
579
580 // Handle scalar conversions.
581 if (!Src->isVectorTy() && !Dst->isVectorTy()) {
582 // Scalar bitcasts are usually free.
583 if (Opcode == Instruction::BitCast)
584 return 0;
585
586 // Just check the op cost. If the operation is legal then assume it costs
587 // 1.
588 if (!TLI->isOperationExpand(ISD, DstLT.second))
589 return 1;
590
591 // Assume that illegal scalar instruction are expensive.
592 return 4;
593 }
594
595 // Check vector-to-vector casts.
596 if (Dst->isVectorTy() && Src->isVectorTy()) {
597 // If the cast is between same-sized registers, then the check is simple.
598 if (SrcLT.first == DstLT.first &&
599 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
600
601 // Assume that Zext is done using AND.
602 if (Opcode == Instruction::ZExt)
603 return 1;
604
605 // Assume that sext is done using SHL and SRA.
606 if (Opcode == Instruction::SExt)
607 return 2;
608
609 // Just check the op cost. If the operation is legal then assume it
610 // costs
611 // 1 and multiply by the type-legalization overhead.
612 if (!TLI->isOperationExpand(ISD, DstLT.second))
613 return SrcLT.first * 1;
614 }
615
616 // If we are legalizing by splitting, query the concrete TTI for the cost
617 // of casting the original vector twice. We also need to factor int the
618 // cost of the split itself. Count that as 1, to be consistent with
619 // TLI->getTypeLegalizationCost().
620 if ((TLI->getTypeAction(Src->getContext(), TLI->getValueType(DL, Src)) ==
621 TargetLowering::TypeSplitVector) ||
622 (TLI->getTypeAction(Dst->getContext(), TLI->getValueType(DL, Dst)) ==
623 TargetLowering::TypeSplitVector)) {
624 Type *SplitDst = VectorType::get(Dst->getVectorElementType(),
625 Dst->getVectorNumElements() / 2);
626 Type *SplitSrc = VectorType::get(Src->getVectorElementType(),
627 Src->getVectorNumElements() / 2);
628 T *TTI = static_cast<T *>(this);
629 return TTI->getVectorSplitCost() +
630 (2 * TTI->getCastInstrCost(Opcode, SplitDst, SplitSrc, I));
631 }
632
633 // In other cases where the source or destination are illegal, assume
634 // the operation will get scalarized.
635 unsigned Num = Dst->getVectorNumElements();
636 unsigned Cost = static_cast<T *>(this)->getCastInstrCost(
637 Opcode, Dst->getScalarType(), Src->getScalarType(), I);
638
639 // Return the cost of multiple scalar invocation plus the cost of
640 // inserting and extracting the values.
641 return getScalarizationOverhead(Dst, true, true) + Num * Cost;
642 }
643
644 // We already handled vector-to-vector and scalar-to-scalar conversions.
645 // This
646 // is where we handle bitcast between vectors and scalars. We need to assume
647 // that the conversion is scalarized in one way or another.
648 if (Opcode == Instruction::BitCast)
649 // Illegal bitcasts are done by storing and loading from a stack slot.
650 return (Src->isVectorTy() ? getScalarizationOverhead(Src, false, true)
651 : 0) +
652 (Dst->isVectorTy() ? getScalarizationOverhead(Dst, true, false)
653 : 0);
654
655 llvm_unreachable("Unhandled cast")::llvm::llvm_unreachable_internal("Unhandled cast", "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 655)
;
656 }
657
658 unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
659 VectorType *VecTy, unsigned Index) {
660 return static_cast<T *>(this)->getVectorInstrCost(
661 Instruction::ExtractElement, VecTy, Index) +
662 static_cast<T *>(this)->getCastInstrCost(Opcode, Dst,
663 VecTy->getElementType());
664 }
665
666 unsigned getCFInstrCost(unsigned Opcode) {
667 // Branches are assumed to be predicted.
668 return 0;
669 }
670
671 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
672 const Instruction *I) {
673 const TargetLoweringBase *TLI = getTLI();
674 int ISD = TLI->InstructionOpcodeToISD(Opcode);
675 assert(ISD && "Invalid opcode")(static_cast <bool> (ISD && "Invalid opcode") ?
void (0) : __assert_fail ("ISD && \"Invalid opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 675, __extension__ __PRETTY_FUNCTION__))
;
676
677 // Selects on vectors are actually vector selects.
678 if (ISD == ISD::SELECT) {
3
Assuming 'ISD' is not equal to SELECT
4
Taking false branch
679 assert(CondTy && "CondTy must exist")(static_cast <bool> (CondTy && "CondTy must exist"
) ? void (0) : __assert_fail ("CondTy && \"CondTy must exist\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 679, __extension__ __PRETTY_FUNCTION__))
;
680 if (CondTy->isVectorTy())
681 ISD = ISD::VSELECT;
682 }
683 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
684
685 if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
5
Taking false branch
686 !TLI->isOperationExpand(ISD, LT.second)) {
687 // The operation is legal. Assume it costs 1. Multiply
688 // by the type-legalization overhead.
689 return LT.first * 1;
690 }
691
692 // Otherwise, assume that the cast is scalarized.
693 // TODO: If one of the types get legalized by splitting, handle this
694 // similarly to what getCastInstrCost() does.
695 if (ValTy->isVectorTy()) {
6
Taking true branch
696 unsigned Num = ValTy->getVectorNumElements();
697 if (CondTy)
7
Assuming 'CondTy' is null
8
Taking false branch
698 CondTy = CondTy->getScalarType();
699 unsigned Cost = static_cast<T *>(this)->getCmpSelInstrCost(
10
Calling 'AArch64TTIImpl::getCmpSelInstrCost'
700 Opcode, ValTy->getScalarType(), CondTy, I);
9
Passing null pointer value via 3rd parameter 'CondTy'
701
702 // Return the cost of multiple scalar invocation plus the cost of
703 // inserting and extracting the values.
704 return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
705 }
706
707 // Unknown scalar opcode.
708 return 1;
709 }
710
711 unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
712 std::pair<unsigned, MVT> LT =
713 getTLI()->getTypeLegalizationCost(DL, Val->getScalarType());
714
715 return LT.first;
716 }
717
718 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
719 unsigned AddressSpace, const Instruction *I = nullptr) {
720 assert(!Src->isVoidTy() && "Invalid type")(static_cast <bool> (!Src->isVoidTy() && "Invalid type"
) ? void (0) : __assert_fail ("!Src->isVoidTy() && \"Invalid type\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 720, __extension__ __PRETTY_FUNCTION__))
;
721 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Src);
722
723 // Assuming that all loads of legal types cost 1.
724 unsigned Cost = LT.first;
725
726 if (Src->isVectorTy() &&
727 Src->getPrimitiveSizeInBits() < LT.second.getSizeInBits()) {
728 // This is a vector load that legalizes to a larger type than the vector
729 // itself. Unless the corresponding extending load or truncating store is
730 // legal, then this will scalarize.
731 TargetLowering::LegalizeAction LA = TargetLowering::Expand;
732 EVT MemVT = getTLI()->getValueType(DL, Src);
733 if (Opcode == Instruction::Store)
734 LA = getTLI()->getTruncStoreAction(LT.second, MemVT);
735 else
736 LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
737
738 if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
739 // This is a vector load/store for some illegal type that is scalarized.
740 // We must account for the cost of building or decomposing the vector.
741 Cost += getScalarizationOverhead(Src, Opcode != Instruction::Store,
742 Opcode == Instruction::Store);
743 }
744 }
745
746 return Cost;
747 }
748
749 unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
750 unsigned Factor,
751 ArrayRef<unsigned> Indices,
752 unsigned Alignment,
753 unsigned AddressSpace) {
754 VectorType *VT = dyn_cast<VectorType>(VecTy);
755 assert(VT && "Expect a vector type for interleaved memory op")(static_cast <bool> (VT && "Expect a vector type for interleaved memory op"
) ? void (0) : __assert_fail ("VT && \"Expect a vector type for interleaved memory op\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 755, __extension__ __PRETTY_FUNCTION__))
;
756
757 unsigned NumElts = VT->getNumElements();
758 assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor")(static_cast <bool> (Factor > 1 && NumElts %
Factor == 0 && "Invalid interleave factor") ? void (
0) : __assert_fail ("Factor > 1 && NumElts % Factor == 0 && \"Invalid interleave factor\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 758, __extension__ __PRETTY_FUNCTION__))
;
759
760 unsigned NumSubElts = NumElts / Factor;
761 VectorType *SubVT = VectorType::get(VT->getElementType(), NumSubElts);
762
763 // Firstly, the cost of load/store operation.
764 unsigned Cost = static_cast<T *>(this)->getMemoryOpCost(
765 Opcode, VecTy, Alignment, AddressSpace);
766
767 // Legalize the vector type, and get the legalized and unlegalized type
768 // sizes.
769 MVT VecTyLT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
770 unsigned VecTySize =
771 static_cast<T *>(this)->getDataLayout().getTypeStoreSize(VecTy);
772 unsigned VecTyLTSize = VecTyLT.getStoreSize();
773
774 // Return the ceiling of dividing A by B.
775 auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; };
776
777 // Scale the cost of the memory operation by the fraction of legalized
778 // instructions that will actually be used. We shouldn't account for the
779 // cost of dead instructions since they will be removed.
780 //
781 // E.g., An interleaved load of factor 8:
782 // %vec = load <16 x i64>, <16 x i64>* %ptr
783 // %v0 = shufflevector %vec, undef, <0, 8>
784 //
785 // If <16 x i64> is legalized to 8 v2i64 loads, only 2 of the loads will be
786 // used (those corresponding to elements [0:1] and [8:9] of the unlegalized
787 // type). The other loads are unused.
788 //
789 // We only scale the cost of loads since interleaved store groups aren't
790 // allowed to have gaps.
791 if (Opcode == Instruction::Load && VecTySize > VecTyLTSize) {
792 // The number of loads of a legal type it will take to represent a load
793 // of the unlegalized vector type.
794 unsigned NumLegalInsts = ceil(VecTySize, VecTyLTSize);
795
796 // The number of elements of the unlegalized type that correspond to a
797 // single legal instruction.
798 unsigned NumEltsPerLegalInst = ceil(NumElts, NumLegalInsts);
799
800 // Determine which legal instructions will be used.
801 BitVector UsedInsts(NumLegalInsts, false);
802 for (unsigned Index : Indices)
803 for (unsigned Elt = 0; Elt < NumSubElts; ++Elt)
804 UsedInsts.set((Index + Elt * Factor) / NumEltsPerLegalInst);
805
806 // Scale the cost of the load by the fraction of legal instructions that
807 // will be used.
808 Cost *= UsedInsts.count() / NumLegalInsts;
809 }
810
811 // Then plus the cost of interleave operation.
812 if (Opcode == Instruction::Load) {
813 // The interleave cost is similar to extract sub vectors' elements
814 // from the wide vector, and insert them into sub vectors.
815 //
816 // E.g. An interleaved load of factor 2 (with one member of index 0):
817 // %vec = load <8 x i32>, <8 x i32>* %ptr
818 // %v0 = shuffle %vec, undef, <0, 2, 4, 6> ; Index 0
819 // The cost is estimated as extract elements at 0, 2, 4, 6 from the
820 // <8 x i32> vector and insert them into a <4 x i32> vector.
821
822 assert(Indices.size() <= Factor &&(static_cast <bool> (Indices.size() <= Factor &&
"Interleaved memory op has too many members") ? void (0) : __assert_fail
("Indices.size() <= Factor && \"Interleaved memory op has too many members\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 823, __extension__ __PRETTY_FUNCTION__))
823 "Interleaved memory op has too many members")(static_cast <bool> (Indices.size() <= Factor &&
"Interleaved memory op has too many members") ? void (0) : __assert_fail
("Indices.size() <= Factor && \"Interleaved memory op has too many members\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 823, __extension__ __PRETTY_FUNCTION__))
;
824
825 for (unsigned Index : Indices) {
826 assert(Index < Factor && "Invalid index for interleaved memory op")(static_cast <bool> (Index < Factor && "Invalid index for interleaved memory op"
) ? void (0) : __assert_fail ("Index < Factor && \"Invalid index for interleaved memory op\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 826, __extension__ __PRETTY_FUNCTION__))
;
827
828 // Extract elements from loaded vector for each sub vector.
829 for (unsigned i = 0; i < NumSubElts; i++)
830 Cost += static_cast<T *>(this)->getVectorInstrCost(
831 Instruction::ExtractElement, VT, Index + i * Factor);
832 }
833
834 unsigned InsSubCost = 0;
835 for (unsigned i = 0; i < NumSubElts; i++)
836 InsSubCost += static_cast<T *>(this)->getVectorInstrCost(
837 Instruction::InsertElement, SubVT, i);
838
839 Cost += Indices.size() * InsSubCost;
840 } else {
841 // The interleave cost is extract all elements from sub vectors, and
842 // insert them into the wide vector.
843 //
844 // E.g. An interleaved store of factor 2:
845 // %v0_v1 = shuffle %v0, %v1, <0, 4, 1, 5, 2, 6, 3, 7>
846 // store <8 x i32> %interleaved.vec, <8 x i32>* %ptr
847 // The cost is estimated as extract all elements from both <4 x i32>
848 // vectors and insert into the <8 x i32> vector.
849
850 unsigned ExtSubCost = 0;
851 for (unsigned i = 0; i < NumSubElts; i++)
852 ExtSubCost += static_cast<T *>(this)->getVectorInstrCost(
853 Instruction::ExtractElement, SubVT, i);
854 Cost += ExtSubCost * Factor;
855
856 for (unsigned i = 0; i < NumElts; i++)
857 Cost += static_cast<T *>(this)
858 ->getVectorInstrCost(Instruction::InsertElement, VT, i);
859 }
860
861 return Cost;
862 }
863
864 /// Get intrinsic cost based on arguments.
865 unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
866 ArrayRef<Value *> Args, FastMathFlags FMF,
867 unsigned VF = 1) {
868 unsigned RetVF = (RetTy->isVectorTy() ? RetTy->getVectorNumElements() : 1);
869 assert((RetVF == 1 || VF == 1) && "VF > 1 and RetVF is a vector type")(static_cast <bool> ((RetVF == 1 || VF == 1) &&
"VF > 1 and RetVF is a vector type") ? void (0) : __assert_fail
("(RetVF == 1 || VF == 1) && \"VF > 1 and RetVF is a vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 869, __extension__ __PRETTY_FUNCTION__))
;
870
871 switch (IID) {
872 default: {
873 // Assume that we need to scalarize this intrinsic.
874 SmallVector<Type *, 4> Types;
875 for (Value *Op : Args) {
876 Type *OpTy = Op->getType();
877 assert(VF == 1 || !OpTy->isVectorTy())(static_cast <bool> (VF == 1 || !OpTy->isVectorTy())
? void (0) : __assert_fail ("VF == 1 || !OpTy->isVectorTy()"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 877, __extension__ __PRETTY_FUNCTION__))
;
878 Types.push_back(VF == 1 ? OpTy : VectorType::get(OpTy, VF));
879 }
880
881 if (VF > 1 && !RetTy->isVoidTy())
882 RetTy = VectorType::get(RetTy, VF);
883
884 // Compute the scalarization overhead based on Args for a vector
885 // intrinsic. A vectorizer will pass a scalar RetTy and VF > 1, while
886 // CostModel will pass a vector RetTy and VF is 1.
887 unsigned ScalarizationCost = std::numeric_limits<unsigned>::max();
888 if (RetVF > 1 || VF > 1) {
889 ScalarizationCost = 0;
890 if (!RetTy->isVoidTy())
891 ScalarizationCost += getScalarizationOverhead(RetTy, true, false);
892 ScalarizationCost += getOperandsScalarizationOverhead(Args, VF);
893 }
894
895 return static_cast<T *>(this)->
896 getIntrinsicInstrCost(IID, RetTy, Types, FMF, ScalarizationCost);
897 }
898 case Intrinsic::masked_scatter: {
899 assert(VF == 1 && "Can't vectorize types here.")(static_cast <bool> (VF == 1 && "Can't vectorize types here."
) ? void (0) : __assert_fail ("VF == 1 && \"Can't vectorize types here.\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 899, __extension__ __PRETTY_FUNCTION__))
;
900 Value *Mask = Args[3];
901 bool VarMask = !isa<Constant>(Mask);
902 unsigned Alignment = cast<ConstantInt>(Args[2])->getZExtValue();
903 return
904 static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Store,
905 Args[0]->getType(),
906 Args[1], VarMask,
907 Alignment);
908 }
909 case Intrinsic::masked_gather: {
910 assert(VF == 1 && "Can't vectorize types here.")(static_cast <bool> (VF == 1 && "Can't vectorize types here."
) ? void (0) : __assert_fail ("VF == 1 && \"Can't vectorize types here.\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 910, __extension__ __PRETTY_FUNCTION__))
;
911 Value *Mask = Args[2];
912 bool VarMask = !isa<Constant>(Mask);
913 unsigned Alignment = cast<ConstantInt>(Args[1])->getZExtValue();
914 return
915 static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Load,
916 RetTy, Args[0], VarMask,
917 Alignment);
918 }
919 }
920 }
921
922 /// Get intrinsic cost based on argument types.
923 /// If ScalarizationCostPassed is std::numeric_limits<unsigned>::max(), the
924 /// cost of scalarizing the arguments and the return value will be computed
925 /// based on types.
926 unsigned getIntrinsicInstrCost(
927 Intrinsic::ID IID, Type *RetTy, ArrayRef<Type *> Tys, FastMathFlags FMF,
928 unsigned ScalarizationCostPassed = std::numeric_limits<unsigned>::max()) {
929 SmallVector<unsigned, 2> ISDs;
930 unsigned SingleCallCost = 10; // Library call cost. Make it expensive.
931 switch (IID) {
932 default: {
933 // Assume that we need to scalarize this intrinsic.
934 unsigned ScalarizationCost = ScalarizationCostPassed;
935 unsigned ScalarCalls = 1;
936 Type *ScalarRetTy = RetTy;
937 if (RetTy->isVectorTy()) {
938 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
939 ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
940 ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
941 ScalarRetTy = RetTy->getScalarType();
942 }
943 SmallVector<Type *, 4> ScalarTys;
944 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
945 Type *Ty = Tys[i];
946 if (Ty->isVectorTy()) {
947 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
948 ScalarizationCost += getScalarizationOverhead(Ty, false, true);
949 ScalarCalls = std::max(ScalarCalls, Ty->getVectorNumElements());
950 Ty = Ty->getScalarType();
951 }
952 ScalarTys.push_back(Ty);
953 }
954 if (ScalarCalls == 1)
955 return 1; // Return cost of a scalar intrinsic. Assume it to be cheap.
956
957 unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
958 IID, ScalarRetTy, ScalarTys, FMF);
959
960 return ScalarCalls * ScalarCost + ScalarizationCost;
961 }
962 // Look for intrinsics that can be lowered directly or turned into a scalar
963 // intrinsic call.
964 case Intrinsic::sqrt:
965 ISDs.push_back(ISD::FSQRT);
966 break;
967 case Intrinsic::sin:
968 ISDs.push_back(ISD::FSIN);
969 break;
970 case Intrinsic::cos:
971 ISDs.push_back(ISD::FCOS);
972 break;
973 case Intrinsic::exp:
974 ISDs.push_back(ISD::FEXP);
975 break;
976 case Intrinsic::exp2:
977 ISDs.push_back(ISD::FEXP2);
978 break;
979 case Intrinsic::log:
980 ISDs.push_back(ISD::FLOG);
981 break;
982 case Intrinsic::log10:
983 ISDs.push_back(ISD::FLOG10);
984 break;
985 case Intrinsic::log2:
986 ISDs.push_back(ISD::FLOG2);
987 break;
988 case Intrinsic::fabs:
989 ISDs.push_back(ISD::FABS);
990 break;
991 case Intrinsic::minnum:
992 ISDs.push_back(ISD::FMINNUM);
993 if (FMF.noNaNs())
994 ISDs.push_back(ISD::FMINNAN);
995 break;
996 case Intrinsic::maxnum:
997 ISDs.push_back(ISD::FMAXNUM);
998 if (FMF.noNaNs())
999 ISDs.push_back(ISD::FMAXNAN);
1000 break;
1001 case Intrinsic::copysign:
1002 ISDs.push_back(ISD::FCOPYSIGN);
1003 break;
1004 case Intrinsic::floor:
1005 ISDs.push_back(ISD::FFLOOR);
1006 break;
1007 case Intrinsic::ceil:
1008 ISDs.push_back(ISD::FCEIL);
1009 break;
1010 case Intrinsic::trunc:
1011 ISDs.push_back(ISD::FTRUNC);
1012 break;
1013 case Intrinsic::nearbyint:
1014 ISDs.push_back(ISD::FNEARBYINT);
1015 break;
1016 case Intrinsic::rint:
1017 ISDs.push_back(ISD::FRINT);
1018 break;
1019 case Intrinsic::round:
1020 ISDs.push_back(ISD::FROUND);
1021 break;
1022 case Intrinsic::pow:
1023 ISDs.push_back(ISD::FPOW);
1024 break;
1025 case Intrinsic::fma:
1026 ISDs.push_back(ISD::FMA);
1027 break;
1028 case Intrinsic::fmuladd:
1029 ISDs.push_back(ISD::FMA);
1030 break;
1031 // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
1032 case Intrinsic::lifetime_start:
1033 case Intrinsic::lifetime_end:
1034 case Intrinsic::sideeffect:
1035 return 0;
1036 case Intrinsic::masked_store:
1037 return static_cast<T *>(this)
1038 ->getMaskedMemoryOpCost(Instruction::Store, Tys[0], 0, 0);
1039 case Intrinsic::masked_load:
1040 return static_cast<T *>(this)
1041 ->getMaskedMemoryOpCost(Instruction::Load, RetTy, 0, 0);
1042 case Intrinsic::ctpop:
1043 ISDs.push_back(ISD::CTPOP);
1044 // In case of legalization use TCC_Expensive. This is cheaper than a
1045 // library call but still not a cheap instruction.
1046 SingleCallCost = TargetTransformInfo::TCC_Expensive;
1047 break;
1048 // FIXME: ctlz, cttz, ...
1049 }
1050
1051 const TargetLoweringBase *TLI = getTLI();
1052 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
1053
1054 SmallVector<unsigned, 2> LegalCost;
1055 SmallVector<unsigned, 2> CustomCost;
1056 for (unsigned ISD : ISDs) {
1057 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
1058 if (IID == Intrinsic::fabs && TLI->isFAbsFree(LT.second)) {
1059 return 0;
1060 }
1061
1062 // The operation is legal. Assume it costs 1.
1063 // If the type is split to multiple registers, assume that there is some
1064 // overhead to this.
1065 // TODO: Once we have extract/insert subvector cost we need to use them.
1066 if (LT.first > 1)
1067 LegalCost.push_back(LT.first * 2);
1068 else
1069 LegalCost.push_back(LT.first * 1);
1070 } else if (!TLI->isOperationExpand(ISD, LT.second)) {
1071 // If the operation is custom lowered then assume
1072 // that the code is twice as expensive.
1073 CustomCost.push_back(LT.first * 2);
1074 }
1075 }
1076
1077 auto MinLegalCostI = std::min_element(LegalCost.begin(), LegalCost.end());
1078 if (MinLegalCostI != LegalCost.end())
1079 return *MinLegalCostI;
1080
1081 auto MinCustomCostI = std::min_element(CustomCost.begin(), CustomCost.end());
1082 if (MinCustomCostI != CustomCost.end())
1083 return *MinCustomCostI;
1084
1085 // If we can't lower fmuladd into an FMA estimate the cost as a floating
1086 // point mul followed by an add.
1087 if (IID == Intrinsic::fmuladd)
1088 return static_cast<T *>(this)
1089 ->getArithmeticInstrCost(BinaryOperator::FMul, RetTy) +
1090 static_cast<T *>(this)
1091 ->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy);
1092
1093 // Else, assume that we need to scalarize this intrinsic. For math builtins
1094 // this will emit a costly libcall, adding call overhead and spills. Make it
1095 // very expensive.
1096 if (RetTy->isVectorTy()) {
1097 unsigned ScalarizationCost =
1098 ((ScalarizationCostPassed != std::numeric_limits<unsigned>::max())
1099 ? ScalarizationCostPassed
1100 : getScalarizationOverhead(RetTy, true, false));
1101 unsigned ScalarCalls = RetTy->getVectorNumElements();
1102 SmallVector<Type *, 4> ScalarTys;
1103 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1104 Type *Ty = Tys[i];
1105 if (Ty->isVectorTy())
1106 Ty = Ty->getScalarType();
1107 ScalarTys.push_back(Ty);
1108 }
1109 unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
1110 IID, RetTy->getScalarType(), ScalarTys, FMF);
1111 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1112 if (Tys[i]->isVectorTy()) {
1113 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
1114 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
1115 ScalarCalls = std::max(ScalarCalls, Tys[i]->getVectorNumElements());
1116 }
1117 }
1118
1119 return ScalarCalls * ScalarCost + ScalarizationCost;
1120 }
1121
1122 // This is going to be turned into a library call, make it expensive.
1123 return SingleCallCost;
1124 }
1125
1126 /// \brief Compute a cost of the given call instruction.
1127 ///
1128 /// Compute the cost of calling function F with return type RetTy and
1129 /// argument types Tys. F might be nullptr, in this case the cost of an
1130 /// arbitrary call with the specified signature will be returned.
1131 /// This is used, for instance, when we estimate call of a vector
1132 /// counterpart of the given function.
1133 /// \param F Called function, might be nullptr.
1134 /// \param RetTy Return value types.
1135 /// \param Tys Argument types.
1136 /// \returns The cost of Call instruction.
1137 unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
1138 return 10;
1139 }
1140
1141 unsigned getNumberOfParts(Type *Tp) {
1142 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Tp);
1143 return LT.first;
1144 }
1145
1146 unsigned getAddressComputationCost(Type *Ty, ScalarEvolution *,
1147 const SCEV *) {
1148 return 0;
1149 }
1150
1151 /// Try to calculate arithmetic and shuffle op costs for reduction operations.
1152 /// We're assuming that reduction operation are performing the following way:
1153 /// 1. Non-pairwise reduction
1154 /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
1155 /// <n x i32> <i32 n/2, i32 n/2 + 1, ..., i32 n, i32 undef, ..., i32 undef>
1156 /// \----------------v-------------/ \----------v------------/
1157 /// n/2 elements n/2 elements
1158 /// %red1 = op <n x t> %val, <n x t> val1
1159 /// After this operation we have a vector %red1 where only the first n/2
1160 /// elements are meaningful, the second n/2 elements are undefined and can be
1161 /// dropped. All other operations are actually working with the vector of
1162 /// length n/2, not n, though the real vector length is still n.
1163 /// %val2 = shufflevector<n x t> %red1, <n x t> %undef,
1164 /// <n x i32> <i32 n/4, i32 n/4 + 1, ..., i32 n/2, i32 undef, ..., i32 undef>
1165 /// \----------------v-------------/ \----------v------------/
1166 /// n/4 elements 3*n/4 elements
1167 /// %red2 = op <n x t> %red1, <n x t> val2 - working with the vector of
1168 /// length n/2, the resulting vector has length n/4 etc.
1169 /// 2. Pairwise reduction:
1170 /// Everything is the same except for an additional shuffle operation which
1171 /// is used to produce operands for pairwise kind of reductions.
1172 /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
1173 /// <n x i32> <i32 0, i32 2, ..., i32 n-2, i32 undef, ..., i32 undef>
1174 /// \-------------v----------/ \----------v------------/
1175 /// n/2 elements n/2 elements
1176 /// %val2 = shufflevector<n x t> %val, <n x t> %undef,
1177 /// <n x i32> <i32 1, i32 3, ..., i32 n-1, i32 undef, ..., i32 undef>
1178 /// \-------------v----------/ \----------v------------/
1179 /// n/2 elements n/2 elements
1180 /// %red1 = op <n x t> %val1, <n x t> val2
1181 /// Again, the operation is performed on <n x t> vector, but the resulting
1182 /// vector %red1 is <n/2 x t> vector.
1183 ///
1184 /// The cost model should take into account that the actual length of the
1185 /// vector is reduced on each iteration.
1186 unsigned getArithmeticReductionCost(unsigned Opcode, Type *Ty,
1187 bool IsPairwise) {
1188 assert(Ty->isVectorTy() && "Expect a vector type")(static_cast <bool> (Ty->isVectorTy() && "Expect a vector type"
) ? void (0) : __assert_fail ("Ty->isVectorTy() && \"Expect a vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 1188, __extension__ __PRETTY_FUNCTION__))
;
1189 Type *ScalarTy = Ty->getVectorElementType();
1190 unsigned NumVecElts = Ty->getVectorNumElements();
1191 unsigned NumReduxLevels = Log2_32(NumVecElts);
1192 unsigned ArithCost = 0;
1193 unsigned ShuffleCost = 0;
1194 auto *ConcreteTTI = static_cast<T *>(this);
1195 std::pair<unsigned, MVT> LT =
1196 ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
1197 unsigned LongVectorCount = 0;
1198 unsigned MVTLen =
1199 LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
1200 while (NumVecElts > MVTLen) {
1201 NumVecElts /= 2;
1202 // Assume the pairwise shuffles add a cost.
1203 ShuffleCost += (IsPairwise + 1) *
1204 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1205 NumVecElts, Ty);
1206 ArithCost += ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
1207 Ty = VectorType::get(ScalarTy, NumVecElts);
1208 ++LongVectorCount;
1209 }
1210 // The minimal length of the vector is limited by the real length of vector
1211 // operations performed on the current platform. That's why several final
1212 // reduction operations are performed on the vectors with the same
1213 // architecture-dependent length.
1214 ShuffleCost += (NumReduxLevels - LongVectorCount) * (IsPairwise + 1) *
1215 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1216 NumVecElts, Ty);
1217 ArithCost += (NumReduxLevels - LongVectorCount) *
1218 ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
1219 return ShuffleCost + ArithCost + getScalarizationOverhead(Ty, false, true);
1220 }
1221
1222 /// Try to calculate op costs for min/max reduction operations.
1223 /// \param CondTy Conditional type for the Select instruction.
1224 unsigned getMinMaxReductionCost(Type *Ty, Type *CondTy, bool IsPairwise,
1225 bool) {
1226 assert(Ty->isVectorTy() && "Expect a vector type")(static_cast <bool> (Ty->isVectorTy() && "Expect a vector type"
) ? void (0) : __assert_fail ("Ty->isVectorTy() && \"Expect a vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 1226, __extension__ __PRETTY_FUNCTION__))
;
1227 Type *ScalarTy = Ty->getVectorElementType();
1228 Type *ScalarCondTy = CondTy->getVectorElementType();
1229 unsigned NumVecElts = Ty->getVectorNumElements();
1230 unsigned NumReduxLevels = Log2_32(NumVecElts);
1231 unsigned CmpOpcode;
1232 if (Ty->isFPOrFPVectorTy()) {
1233 CmpOpcode = Instruction::FCmp;
1234 } else {
1235 assert(Ty->isIntOrIntVectorTy() &&(static_cast <bool> (Ty->isIntOrIntVectorTy() &&
"expecting floating point or integer type for min/max reduction"
) ? void (0) : __assert_fail ("Ty->isIntOrIntVectorTy() && \"expecting floating point or integer type for min/max reduction\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 1236, __extension__ __PRETTY_FUNCTION__))
1236 "expecting floating point or integer type for min/max reduction")(static_cast <bool> (Ty->isIntOrIntVectorTy() &&
"expecting floating point or integer type for min/max reduction"
) ? void (0) : __assert_fail ("Ty->isIntOrIntVectorTy() && \"expecting floating point or integer type for min/max reduction\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 1236, __extension__ __PRETTY_FUNCTION__))
;
1237 CmpOpcode = Instruction::ICmp;
1238 }
1239 unsigned MinMaxCost = 0;
1240 unsigned ShuffleCost = 0;
1241 auto *ConcreteTTI = static_cast<T *>(this);
1242 std::pair<unsigned, MVT> LT =
1243 ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
1244 unsigned LongVectorCount = 0;
1245 unsigned MVTLen =
1246 LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
1247 while (NumVecElts > MVTLen) {
1248 NumVecElts /= 2;
1249 // Assume the pairwise shuffles add a cost.
1250 ShuffleCost += (IsPairwise + 1) *
1251 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1252 NumVecElts, Ty);
1253 MinMaxCost +=
1254 ConcreteTTI->getCmpSelInstrCost(CmpOpcode, Ty, CondTy, nullptr) +
1255 ConcreteTTI->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
1256 nullptr);
1257 Ty = VectorType::get(ScalarTy, NumVecElts);
1258 CondTy = VectorType::get(ScalarCondTy, NumVecElts);
1259 ++LongVectorCount;
1260 }
1261 // The minimal length of the vector is limited by the real length of vector
1262 // operations performed on the current platform. That's why several final
1263 // reduction opertions are perfomed on the vectors with the same
1264 // architecture-dependent length.
1265 ShuffleCost += (NumReduxLevels - LongVectorCount) * (IsPairwise + 1) *
1266 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1267 NumVecElts, Ty);
1268 MinMaxCost +=
1269 (NumReduxLevels - LongVectorCount) *
1270 (ConcreteTTI->getCmpSelInstrCost(CmpOpcode, Ty, CondTy, nullptr) +
1271 ConcreteTTI->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
1272 nullptr));
1273 // Need 3 extractelement instructions for scalarization + an additional
1274 // scalar select instruction.
1275 return ShuffleCost + MinMaxCost +
1276 3 * getScalarizationOverhead(Ty, /*Insert=*/false,
1277 /*Extract=*/true) +
1278 ConcreteTTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
1279 ScalarCondTy, nullptr);
1280 }
1281
1282 unsigned getVectorSplitCost() { return 1; }
1283
1284 /// @}
1285};
1286
1287/// \brief Concrete BasicTTIImpl that can be used if no further customization
1288/// is needed.
1289class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
1290 using BaseT = BasicTTIImplBase<BasicTTIImpl>;
1291
1292 friend class BasicTTIImplBase<BasicTTIImpl>;
1293
1294 const TargetSubtargetInfo *ST;
1295 const TargetLoweringBase *TLI;
1296
1297 const TargetSubtargetInfo *getST() const { return ST; }
1298 const TargetLoweringBase *getTLI() const { return TLI; }
1299
1300public:
1301 explicit BasicTTIImpl(const TargetMachine *ST, const Function &F);
1302};
1303
1304} // end namespace llvm
1305
1306#endif // LLVM_CODEGEN_BASICTTIIMPL_H

/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h

1//===- llvm/CodeGen/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// This file describes how to lower LLVM code to machine code. This has two
12/// main components:
13///
14/// 1. Which ValueTypes are natively supported by the target.
15/// 2. Which operations are supported for supported ValueTypes.
16/// 3. Cost thresholds for alternative implementations of certain operations.
17///
18/// In addition it has a few other components, like information about FP
19/// immediates.
20///
21//===----------------------------------------------------------------------===//
22
23#ifndef LLVM_CODEGEN_TARGETLOWERING_H
24#define LLVM_CODEGEN_TARGETLOWERING_H
25
26#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringRef.h"
32#include "llvm/CodeGen/DAGCombine.h"
33#include "llvm/CodeGen/ISDOpcodes.h"
34#include "llvm/CodeGen/MachineValueType.h"
35#include "llvm/CodeGen/RuntimeLibcalls.h"
36#include "llvm/CodeGen/SelectionDAG.h"
37#include "llvm/CodeGen/SelectionDAGNodes.h"
38#include "llvm/CodeGen/TargetCallingConv.h"
39#include "llvm/CodeGen/ValueTypes.h"
40#include "llvm/IR/Attributes.h"
41#include "llvm/IR/CallSite.h"
42#include "llvm/IR/CallingConv.h"
43#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/DerivedTypes.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/IRBuilder.h"
47#include "llvm/IR/InlineAsm.h"
48#include "llvm/IR/Instruction.h"
49#include "llvm/IR/Instructions.h"
50#include "llvm/IR/Type.h"
51#include "llvm/MC/MCRegisterInfo.h"
52#include "llvm/Support/AtomicOrdering.h"
53#include "llvm/Support/Casting.h"
54#include "llvm/Support/ErrorHandling.h"
55#include "llvm/Target/TargetMachine.h"
56#include <algorithm>
57#include <cassert>
58#include <climits>
59#include <cstdint>
60#include <iterator>
61#include <map>
62#include <string>
63#include <utility>
64#include <vector>
65
66namespace llvm {
67
68class BranchProbability;
69class CCState;
70class CCValAssign;
71class Constant;
72class FastISel;
73class FunctionLoweringInfo;
74class GlobalValue;
75class IntrinsicInst;
76struct KnownBits;
77class LLVMContext;
78class MachineBasicBlock;
79class MachineFunction;
80class MachineInstr;
81class MachineJumpTableInfo;
82class MachineLoop;
83class MachineRegisterInfo;
84class MCContext;
85class MCExpr;
86class Module;
87class TargetRegisterClass;
88class TargetLibraryInfo;
89class TargetRegisterInfo;
90class Value;
91
92namespace Sched {
93
94 enum Preference {
95 None, // No preference
96 Source, // Follow source order.
97 RegPressure, // Scheduling for lowest register pressure.
98 Hybrid, // Scheduling for both latency and register pressure.
99 ILP, // Scheduling for ILP in low register pressure mode.
100 VLIW // Scheduling for VLIW targets.
101 };
102
103} // end namespace Sched
104
105/// This base class for TargetLowering contains the SelectionDAG-independent
106/// parts that can be used from the rest of CodeGen.
107class TargetLoweringBase {
108public:
109 /// This enum indicates whether operations are valid for a target, and if not,
110 /// what action should be used to make them valid.
111 enum LegalizeAction : uint8_t {
112 Legal, // The target natively supports this operation.
113 Promote, // This operation should be executed in a larger type.
114 Expand, // Try to expand this to other ops, otherwise use a libcall.
115 LibCall, // Don't try to expand this to other ops, always use a libcall.
116 Custom // Use the LowerOperation hook to implement custom lowering.
117 };
118
119 /// This enum indicates whether a types are legal for a target, and if not,
120 /// what action should be used to make them valid.
121 enum LegalizeTypeAction : uint8_t {
122 TypeLegal, // The target natively supports this type.
123 TypePromoteInteger, // Replace this integer with a larger one.
124 TypeExpandInteger, // Split this integer into two of half the size.
125 TypeSoftenFloat, // Convert this float to a same size integer type,
126 // if an operation is not supported in target HW.
127 TypeExpandFloat, // Split this float into two of half the size.
128 TypeScalarizeVector, // Replace this one-element vector with its element.
129 TypeSplitVector, // Split this vector into two of half the size.
130 TypeWidenVector, // This vector should be widened into a larger vector.
131 TypePromoteFloat // Replace this float with a larger one.
132 };
133
134 /// LegalizeKind holds the legalization kind that needs to happen to EVT
135 /// in order to type-legalize it.
136 using LegalizeKind = std::pair<LegalizeTypeAction, EVT>;
137
138 /// Enum that describes how the target represents true/false values.
139 enum BooleanContent {
140 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
141 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
142 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
143 };
144
145 /// Enum that describes what type of support for selects the target has.
146 enum SelectSupportKind {
147 ScalarValSelect, // The target supports scalar selects (ex: cmov).
148 ScalarCondVectorVal, // The target supports selects with a scalar condition
149 // and vector values (ex: cmov).
150 VectorMaskSelect // The target supports vector selects with a vector
151 // mask (ex: x86 blends).
152 };
153
154 /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
155 /// to, if at all. Exists because different targets have different levels of
156 /// support for these atomic instructions, and also have different options
157 /// w.r.t. what they should expand to.
158 enum class AtomicExpansionKind {
159 None, // Don't expand the instruction.
160 LLSC, // Expand the instruction into loadlinked/storeconditional; used
161 // by ARM/AArch64.
162 LLOnly, // Expand the (load) instruction into just a load-linked, which has
163 // greater atomic guarantees than a normal load.
164 CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
165 };
166
167 /// Enum that specifies when a multiplication should be expanded.
168 enum class MulExpansionKind {
169 Always, // Always expand the instruction.
170 OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
171 // or custom.
172 };
173
174 class ArgListEntry {
175 public:
176 Value *Val = nullptr;
177 SDValue Node = SDValue();
178 Type *Ty = nullptr;
179 bool IsSExt : 1;
180 bool IsZExt : 1;
181 bool IsInReg : 1;
182 bool IsSRet : 1;
183 bool IsNest : 1;
184 bool IsByVal : 1;
185 bool IsInAlloca : 1;
186 bool IsReturned : 1;
187 bool IsSwiftSelf : 1;
188 bool IsSwiftError : 1;
189 uint16_t Alignment = 0;
190
191 ArgListEntry()
192 : IsSExt(false), IsZExt(false), IsInReg(false), IsSRet(false),
193 IsNest(false), IsByVal(false), IsInAlloca(false), IsReturned(false),
194 IsSwiftSelf(false), IsSwiftError(false) {}
195
196 void setAttributes(ImmutableCallSite *CS, unsigned ArgIdx);
197 };
198 using ArgListTy = std::vector<ArgListEntry>;
199
200 virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
201 ArgListTy &Args) const {};
202
203 static ISD::NodeType getExtendForContent(BooleanContent Content) {
204 switch (Content) {
205 case UndefinedBooleanContent:
206 // Extend by adding rubbish bits.
207 return ISD::ANY_EXTEND;
208 case ZeroOrOneBooleanContent:
209 // Extend by adding zero bits.
210 return ISD::ZERO_EXTEND;
211 case ZeroOrNegativeOneBooleanContent:
212 // Extend by copying the sign bit.
213 return ISD::SIGN_EXTEND;
214 }
215 llvm_unreachable("Invalid content kind")::llvm::llvm_unreachable_internal("Invalid content kind", "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 215)
;
216 }
217
218 /// NOTE: The TargetMachine owns TLOF.
219 explicit TargetLoweringBase(const TargetMachine &TM);
220 TargetLoweringBase(const TargetLoweringBase &) = delete;
221 TargetLoweringBase &operator=(const TargetLoweringBase &) = delete;
222 virtual ~TargetLoweringBase() = default;
223
224protected:
225 /// \brief Initialize all of the actions to default values.
226 void initActions();
227
228public:
229 const TargetMachine &getTargetMachine() const { return TM; }
230
231 virtual bool useSoftFloat() const { return false; }
232
233 /// Return the pointer type for the given address space, defaults to
234 /// the pointer type from the data layout.
235 /// FIXME: The default needs to be removed once all the code is updated.
236 MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
237 return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
238 }
239
240 /// Return the type for frame index, which is determined by
241 /// the alloca address space specified through the data layout.
242 MVT getFrameIndexTy(const DataLayout &DL) const {
243 return getPointerTy(DL, DL.getAllocaAddrSpace());
244 }
245
246 /// Return the type for operands of fence.
247 /// TODO: Let fence operands be of i32 type and remove this.
248 virtual MVT getFenceOperandTy(const DataLayout &DL) const {
249 return getPointerTy(DL);
250 }
251
252 /// EVT is not used in-tree, but is used by out-of-tree target.
253 /// A documentation for this function would be nice...
254 virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
255
256 EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const;
257
258 /// Returns the type to be used for the index operand of:
259 /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
260 /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
261 virtual MVT getVectorIdxTy(const DataLayout &DL) const {
262 return getPointerTy(DL);
263 }
264
265 virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
266 return true;
267 }
268
269 /// Return true if multiple condition registers are available.
270 bool hasMultipleConditionRegisters() const {
271 return HasMultipleConditionRegisters;
272 }
273
274 /// Return true if the target has BitExtract instructions.
275 bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
276
277 /// Return the preferred vector type legalization action.
278 virtual TargetLoweringBase::LegalizeTypeAction
279 getPreferredVectorAction(EVT VT) const {
280 // The default action for one element vectors is to scalarize
281 if (VT.getVectorNumElements() == 1)
282 return TypeScalarizeVector;
283 // The default action for other vectors is to promote
284 return TypePromoteInteger;
285 }
286
287 // There are two general methods for expanding a BUILD_VECTOR node:
288 // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
289 // them together.
290 // 2. Build the vector on the stack and then load it.
291 // If this function returns true, then method (1) will be used, subject to
292 // the constraint that all of the necessary shuffles are legal (as determined
293 // by isShuffleMaskLegal). If this function returns false, then method (2) is
294 // always used. The vector type, and the number of defined values, are
295 // provided.
296 virtual bool
297 shouldExpandBuildVectorWithShuffles(EVT /* VT */,
298 unsigned DefinedValues) const {
299 return DefinedValues < 3;
300 }
301
302 /// Return true if integer divide is usually cheaper than a sequence of
303 /// several shifts, adds, and multiplies for this target.
304 /// The definition of "cheaper" may depend on whether we're optimizing
305 /// for speed or for size.
306 virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
307
308 /// Return true if the target can handle a standalone remainder operation.
309 virtual bool hasStandaloneRem(EVT VT) const {
310 return true;
311 }
312
313 /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
314 virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
315 // Default behavior is to replace SQRT(X) with X*RSQRT(X).
316 return false;
317 }
318
319 /// Reciprocal estimate status values used by the functions below.
320 enum ReciprocalEstimate : int {
321 Unspecified = -1,
322 Disabled = 0,
323 Enabled = 1
324 };
325
326 /// Return a ReciprocalEstimate enum value for a square root of the given type
327 /// based on the function's attributes. If the operation is not overridden by
328 /// the function's attributes, "Unspecified" is returned and target defaults
329 /// are expected to be used for instruction selection.
330 int getRecipEstimateSqrtEnabled(EVT VT, MachineFunction &MF) const;
331
332 /// Return a ReciprocalEstimate enum value for a division of the given type
333 /// based on the function's attributes. If the operation is not overridden by
334 /// the function's attributes, "Unspecified" is returned and target defaults
335 /// are expected to be used for instruction selection.
336 int getRecipEstimateDivEnabled(EVT VT, MachineFunction &MF) const;
337
338 /// Return the refinement step count for a square root of the given type based
339 /// on the function's attributes. If the operation is not overridden by
340 /// the function's attributes, "Unspecified" is returned and target defaults
341 /// are expected to be used for instruction selection.
342 int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
343
344 /// Return the refinement step count for a division of the given type based
345 /// on the function's attributes. If the operation is not overridden by
346 /// the function's attributes, "Unspecified" is returned and target defaults
347 /// are expected to be used for instruction selection.
348 int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
349
350 /// Returns true if target has indicated at least one type should be bypassed.
351 bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
352
353 /// Returns map of slow types for division or remainder with corresponding
354 /// fast types
355 const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
356 return BypassSlowDivWidths;
357 }
358
359 /// Return true if Flow Control is an expensive operation that should be
360 /// avoided.
361 bool isJumpExpensive() const { return JumpIsExpensive; }
362
363 /// Return true if selects are only cheaper than branches if the branch is
364 /// unlikely to be predicted right.
365 bool isPredictableSelectExpensive() const {
366 return PredictableSelectIsExpensive;
367 }
368
369 /// If a branch or a select condition is skewed in one direction by more than
370 /// this factor, it is very likely to be predicted correctly.
371 virtual BranchProbability getPredictableBranchThreshold() const;
372
373 /// Return true if the following transform is beneficial:
374 /// fold (conv (load x)) -> (load (conv*)x)
375 /// On architectures that don't natively support some vector loads
376 /// efficiently, casting the load to a smaller vector of larger types and
377 /// loading is more efficient, however, this can be undone by optimizations in
378 /// dag combiner.
379 virtual bool isLoadBitCastBeneficial(EVT LoadVT,
380 EVT BitcastVT) const {
381 // Don't do if we could do an indexed load on the original type, but not on
382 // the new one.
383 if (!LoadVT.isSimple() || !BitcastVT.isSimple())
384 return true;
385
386 MVT LoadMVT = LoadVT.getSimpleVT();
387
388 // Don't bother doing this if it's just going to be promoted again later, as
389 // doing so might interfere with other combines.
390 if (getOperationAction(ISD::LOAD, LoadMVT) == Promote &&
391 getTypeToPromoteTo(ISD::LOAD, LoadMVT) == BitcastVT.getSimpleVT())
392 return false;
393
394 return true;
395 }
396
397 /// Return true if the following transform is beneficial:
398 /// (store (y (conv x)), y*)) -> (store x, (x*))
399 virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT) const {
400 // Default to the same logic as loads.
401 return isLoadBitCastBeneficial(StoreVT, BitcastVT);
402 }
403
404 /// Return true if it is expected to be cheaper to do a store of a non-zero
405 /// vector constant with the given size and type for the address space than to
406 /// store the individual scalar element constants.
407 virtual bool storeOfVectorConstantIsCheap(EVT MemVT,
408 unsigned NumElem,
409 unsigned AddrSpace) const {
410 return false;
411 }
412
413 /// Allow store merging after legalization in addition to before legalization.
414 /// This may catch stores that do not exist earlier (eg, stores created from
415 /// intrinsics).
416 virtual bool mergeStoresAfterLegalization() const { return true; }
417
418 /// Returns if it's reasonable to merge stores to MemVT size.
419 virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
420 const SelectionDAG &DAG) const {
421 return true;
422 }
423
424 /// \brief Return true if it is cheap to speculate a call to intrinsic cttz.
425 virtual bool isCheapToSpeculateCttz() const {
426 return false;
427 }
428
429 /// \brief Return true if it is cheap to speculate a call to intrinsic ctlz.
430 virtual bool isCheapToSpeculateCtlz() const {
431 return false;
432 }
433
434 /// \brief Return true if ctlz instruction is fast.
435 virtual bool isCtlzFast() const {
436 return false;
437 }
438
439 /// Return true if it is safe to transform an integer-domain bitwise operation
440 /// into the equivalent floating-point operation. This should be set to true
441 /// if the target has IEEE-754-compliant fabs/fneg operations for the input
442 /// type.
443 virtual bool hasBitPreservingFPLogic(EVT VT) const {
444 return false;
445 }
446
447 /// \brief Return true if it is cheaper to split the store of a merged int val
448 /// from a pair of smaller values into multiple stores.
449 virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
450 return false;
451 }
452
453 /// \brief Return if the target supports combining a
454 /// chain like:
455 /// \code
456 /// %andResult = and %val1, #mask
457 /// %icmpResult = icmp %andResult, 0
458 /// \endcode
459 /// into a single machine instruction of a form like:
460 /// \code
461 /// cc = test %register, #mask
462 /// \endcode
463 virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
464 return false;
465 }
466
467 /// Use bitwise logic to make pairs of compares more efficient. For example:
468 /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
469 /// This should be true when it takes more than one instruction to lower
470 /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
471 /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
472 virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
473 return false;
474 }
475
476 /// Return the preferred operand type if the target has a quick way to compare
477 /// integer values of the given size. Assume that any legal integer type can
478 /// be compared efficiently. Targets may override this to allow illegal wide
479 /// types to return a vector type if there is support to compare that type.
480 virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
481 MVT VT = MVT::getIntegerVT(NumBits);
482 return isTypeLegal(VT) ? VT : MVT::INVALID_SIMPLE_VALUE_TYPE;
483 }
484
485 /// Return true if the target should transform:
486 /// (X & Y) == Y ---> (~X & Y) == 0
487 /// (X & Y) != Y ---> (~X & Y) != 0
488 ///
489 /// This may be profitable if the target has a bitwise and-not operation that
490 /// sets comparison flags. A target may want to limit the transformation based
491 /// on the type of Y or if Y is a constant.
492 ///
493 /// Note that the transform will not occur if Y is known to be a power-of-2
494 /// because a mask and compare of a single bit can be handled by inverting the
495 /// predicate, for example:
496 /// (X & 8) == 8 ---> (X & 8) != 0
497 virtual bool hasAndNotCompare(SDValue Y) const {
498 return false;
499 }
500
501 /// Return true if the target has a bitwise and-not operation:
502 /// X = ~A & B
503 /// This can be used to simplify select or other instructions.
504 virtual bool hasAndNot(SDValue X) const {
505 // If the target has the more complex version of this operation, assume that
506 // it has this operation too.
507 return hasAndNotCompare(X);
508 }
509
510 /// \brief Return true if the target wants to use the optimization that
511 /// turns ext(promotableInst1(...(promotableInstN(load)))) into
512 /// promotedInst1(...(promotedInstN(ext(load)))).
513 bool enableExtLdPromotion() const { return EnableExtLdPromotion; }
514
515 /// Return true if the target can combine store(extractelement VectorTy,
516 /// Idx).
517 /// \p Cost[out] gives the cost of that transformation when this is true.
518 virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
519 unsigned &Cost) const {
520 return false;
521 }
522
523 /// Return true if target supports floating point exceptions.
524 bool hasFloatingPointExceptions() const {
525 return HasFloatingPointExceptions;
526 }
527
528 /// Return true if target always beneficiates from combining into FMA for a
529 /// given value type. This must typically return false on targets where FMA
530 /// takes more cycles to execute than FADD.
531 virtual bool enableAggressiveFMAFusion(EVT VT) const {
532 return false;
533 }
534
535 /// Return the ValueType of the result of SETCC operations.
536 virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
537 EVT VT) const;
538
539 /// Return the ValueType for comparison libcalls. Comparions libcalls include
540 /// floating point comparion calls, and Ordered/Unordered check calls on
541 /// floating point numbers.
542 virtual
543 MVT::SimpleValueType getCmpLibcallReturnType() const;
544
545 /// For targets without i1 registers, this gives the nature of the high-bits
546 /// of boolean values held in types wider than i1.
547 ///
548 /// "Boolean values" are special true/false values produced by nodes like
549 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
550 /// Not to be confused with general values promoted from i1. Some cpus
551 /// distinguish between vectors of boolean and scalars; the isVec parameter
552 /// selects between the two kinds. For example on X86 a scalar boolean should
553 /// be zero extended from i1, while the elements of a vector of booleans
554 /// should be sign extended from i1.
555 ///
556 /// Some cpus also treat floating point types the same way as they treat
557 /// vectors instead of the way they treat scalars.
558 BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
559 if (isVec)
560 return BooleanVectorContents;
561 return isFloat ? BooleanFloatContents : BooleanContents;
562 }
563
564 BooleanContent getBooleanContents(EVT Type) const {
565 return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
566 }
567
568 /// Return target scheduling preference.
569 Sched::Preference getSchedulingPreference() const {
570 return SchedPreferenceInfo;
571 }
572
573 /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
574 /// for different nodes. This function returns the preference (or none) for
575 /// the given node.
576 virtual Sched::Preference getSchedulingPreference(SDNode *) const {
577 return Sched::None;
578 }
579
580 /// Return the register class that should be used for the specified value
581 /// type.
582 virtual const TargetRegisterClass *getRegClassFor(MVT VT) const {
583 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
584 assert(RC && "This value type is not natively supported!")(static_cast <bool> (RC && "This value type is not natively supported!"
) ? void (0) : __assert_fail ("RC && \"This value type is not natively supported!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 584, __extension__ __PRETTY_FUNCTION__))
;
585 return RC;
586 }
587
588 /// Return the 'representative' register class for the specified value
589 /// type.
590 ///
591 /// The 'representative' register class is the largest legal super-reg
592 /// register class for the register class of the value type. For example, on
593 /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
594 /// register class is GR64 on x86_64.
595 virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
596 const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
597 return RC;
598 }
599
600 /// Return the cost of the 'representative' register class for the specified
601 /// value type.
602 virtual uint8_t getRepRegClassCostFor(MVT VT) const {
603 return RepRegClassCostForVT[VT.SimpleTy];
604 }
605
606 /// Return true if the target has native support for the specified value type.
607 /// This means that it has a register that directly holds it without
608 /// promotions or expansions.
609 bool isTypeLegal(EVT VT) const {
610 assert(!VT.isSimple() ||(static_cast <bool> (!VT.isSimple() || (unsigned)VT.getSimpleVT
().SimpleTy < array_lengthof(RegClassForVT)) ? void (0) : __assert_fail
("!VT.isSimple() || (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT)"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 611, __extension__ __PRETTY_FUNCTION__))
611 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT))(static_cast <bool> (!VT.isSimple() || (unsigned)VT.getSimpleVT
().SimpleTy < array_lengthof(RegClassForVT)) ? void (0) : __assert_fail
("!VT.isSimple() || (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT)"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 611, __extension__ __PRETTY_FUNCTION__))
;
612 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
613 }
614
615 class ValueTypeActionImpl {
616 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
617 /// that indicates how instruction selection should deal with the type.
618 LegalizeTypeAction ValueTypeActions[MVT::LAST_VALUETYPE];
619
620 public:
621 ValueTypeActionImpl() {
622 std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions),
623 TypeLegal);
624 }
625
626 LegalizeTypeAction getTypeAction(MVT VT) const {
627 return ValueTypeActions[VT.SimpleTy];
628 }
629
630 void setTypeAction(MVT VT, LegalizeTypeAction Action) {
631 ValueTypeActions[VT.SimpleTy] = Action;
632 }
633 };
634
635 const ValueTypeActionImpl &getValueTypeActions() const {
636 return ValueTypeActions;
637 }
638
639 /// Return how we should legalize values of this type, either it is already
640 /// legal (return 'Legal') or we need to promote it to a larger type (return
641 /// 'Promote'), or we need to expand it into multiple registers of smaller
642 /// integer type (return 'Expand'). 'Custom' is not an option.
643 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
644 return getTypeConversion(Context, VT).first;
645 }
646 LegalizeTypeAction getTypeAction(MVT VT) const {
647 return ValueTypeActions.getTypeAction(VT);
648 }
649
650 /// For types supported by the target, this is an identity function. For
651 /// types that must be promoted to larger types, this returns the larger type
652 /// to promote to. For integer types that are larger than the largest integer
653 /// register, this contains one step in the expansion to get to the smaller
654 /// register. For illegal floating point types, this returns the integer type
655 /// to transform to.
656 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
657 return getTypeConversion(Context, VT).second;
658 }
659
660 /// For types supported by the target, this is an identity function. For
661 /// types that must be expanded (i.e. integer types that are larger than the
662 /// largest integer register or illegal floating point types), this returns
663 /// the largest legal type it will be expanded to.
664 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
665 assert(!VT.isVector())(static_cast <bool> (!VT.isVector()) ? void (0) : __assert_fail
("!VT.isVector()", "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 665, __extension__ __PRETTY_FUNCTION__))
;
666 while (true) {
667 switch (getTypeAction(Context, VT)) {
668 case TypeLegal:
669 return VT;
670 case TypeExpandInteger:
671 VT = getTypeToTransformTo(Context, VT);
672 break;
673 default:
674 llvm_unreachable("Type is not legal nor is it to be expanded!")::llvm::llvm_unreachable_internal("Type is not legal nor is it to be expanded!"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 674)
;
675 }
676 }
677 }
678
679 /// Vector types are broken down into some number of legal first class types.
680 /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
681 /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
682 /// turns into 4 EVT::i32 values with both PPC and X86.
683 ///
684 /// This method returns the number of registers needed, and the VT for each
685 /// register. It also returns the VT and quantity of the intermediate values
686 /// before they are promoted/expanded.
687 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
688 EVT &IntermediateVT,
689 unsigned &NumIntermediates,
690 MVT &RegisterVT) const;
691
692 /// Certain targets such as MIPS require that some types such as vectors are
693 /// always broken down into scalars in some contexts. This occurs even if the
694 /// vector type is legal.
695 virtual unsigned getVectorTypeBreakdownForCallingConv(
696 LLVMContext &Context, EVT VT, EVT &IntermediateVT,
697 unsigned &NumIntermediates, MVT &RegisterVT) const {
698 return getVectorTypeBreakdown(Context, VT, IntermediateVT, NumIntermediates,
699 RegisterVT);
700 }
701
702 struct IntrinsicInfo {
703 unsigned opc = 0; // target opcode
704 EVT memVT; // memory VT
705
706 // value representing memory location
707 PointerUnion<const Value *, const PseudoSourceValue *> ptrVal;
708
709 int offset = 0; // offset off of ptrVal
710 unsigned size = 0; // the size of the memory location
711 // (taken from memVT if zero)
712 unsigned align = 1; // alignment
713
714 MachineMemOperand::Flags flags = MachineMemOperand::MONone;
715 IntrinsicInfo() = default;
716 };
717
718 /// Given an intrinsic, checks if on the target the intrinsic will need to map
719 /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
720 /// true and store the intrinsic information into the IntrinsicInfo that was
721 /// passed to the function.
722 virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
723 MachineFunction &,
724 unsigned /*Intrinsic*/) const {
725 return false;
726 }
727
728 /// Returns true if the target can instruction select the specified FP
729 /// immediate natively. If false, the legalizer will materialize the FP
730 /// immediate as a load from a constant pool.
731 virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
732 return false;
733 }
734
735 /// Targets can use this to indicate that they only support *some*
736 /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
737 /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
738 /// legal.
739 virtual bool isShuffleMaskLegal(ArrayRef<int> /*Mask*/, EVT /*VT*/) const {
740 return true;
741 }
742
743 /// Returns true if the operation can trap for the value type.
744 ///
745 /// VT must be a legal type. By default, we optimistically assume most
746 /// operations don't trap except for integer divide and remainder.
747 virtual bool canOpTrap(unsigned Op, EVT VT) const;
748
749 /// Similar to isShuffleMaskLegal. This is used by Targets can use this to
750 /// indicate if there is a suitable VECTOR_SHUFFLE that can be used to replace
751 /// a VAND with a constant pool entry.
752 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
753 EVT /*VT*/) const {
754 return false;
755 }
756
757 /// Return how this operation should be treated: either it is legal, needs to
758 /// be promoted to a larger size, needs to be expanded to some other code
759 /// sequence, or the target has a custom expander for it.
760 LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
761 if (VT.isExtended()) return Expand;
762 // If a target-specific SDNode requires legalization, require the target
763 // to provide custom legalization for it.
764 if (Op >= array_lengthof(OpActions[0])) return Custom;
765 return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
766 }
767
768 /// Return true if the specified operation is legal on this target or can be
769 /// made legal with custom lowering. This is used to help guide high-level
770 /// lowering decisions.
771 bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
772 return (VT == MVT::Other || isTypeLegal(VT)) &&
773 (getOperationAction(Op, VT) == Legal ||
774 getOperationAction(Op, VT) == Custom);
775 }
776
777 /// Return true if the specified operation is legal on this target or can be
778 /// made legal using promotion. This is used to help guide high-level lowering
779 /// decisions.
780 bool isOperationLegalOrPromote(unsigned Op, EVT VT) const {
781 return (VT == MVT::Other || isTypeLegal(VT)) &&
782 (getOperationAction(Op, VT) == Legal ||
783 getOperationAction(Op, VT) == Promote);
784 }
785
786 /// Return true if the specified operation is legal on this target or can be
787 /// made legal with custom lowering or using promotion. This is used to help
788 /// guide high-level lowering decisions.
789 bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT) const {
790 return (VT == MVT::Other || isTypeLegal(VT)) &&
791 (getOperationAction(Op, VT) == Legal ||
792 getOperationAction(Op, VT) == Custom ||
793 getOperationAction(Op, VT) == Promote);
794 }
795
796 /// Return true if the operation uses custom lowering, regardless of whether
797 /// the type is legal or not.
798 bool isOperationCustom(unsigned Op, EVT VT) const {
799 return getOperationAction(Op, VT) == Custom;
800 }
801
802 /// Return true if lowering to a jump table is allowed.
803 bool areJTsAllowed(const Function *Fn) const {
804 if (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")
805 return false;
806
807 return isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
808 isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
809 }
810
811 /// Check whether the range [Low,High] fits in a machine word.
812 bool rangeFitsInWord(const APInt &Low, const APInt &High,
813 const DataLayout &DL) const {
814 // FIXME: Using the pointer type doesn't seem ideal.
815 uint64_t BW = DL.getPointerSizeInBits();
816 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX(18446744073709551615UL) - 1) + 1;
817 return Range <= BW;
818 }
819
820 /// Return true if lowering to a jump table is suitable for a set of case
821 /// clusters which may contain \p NumCases cases, \p Range range of values.
822 /// FIXME: This function check the maximum table size and density, but the
823 /// minimum size is not checked. It would be nice if the the minimum size is
824 /// also combined within this function. Currently, the minimum size check is
825 /// performed in findJumpTable() in SelectionDAGBuiler and
826 /// getEstimatedNumberOfCaseClusters() in BasicTTIImpl.
827 virtual bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
828 uint64_t Range) const {
829 const bool OptForSize = SI->getParent()->getParent()->optForSize();
830 const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize);
831 const unsigned MaxJumpTableSize =
832 OptForSize || getMaximumJumpTableSize() == 0
833 ? UINT_MAX(2147483647 *2U +1U)
834 : getMaximumJumpTableSize();
835 // Check whether a range of clusters is dense enough for a jump table.
836 if (Range <= MaxJumpTableSize &&
837 (NumCases * 100 >= Range * MinDensity)) {
838 return true;
839 }
840 return false;
841 }
842
843 /// Return true if lowering to a bit test is suitable for a set of case
844 /// clusters which contains \p NumDests unique destinations, \p Low and
845 /// \p High as its lowest and highest case values, and expects \p NumCmps
846 /// case value comparisons. Check if the number of destinations, comparison
847 /// metric, and range are all suitable.
848 bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
849 const APInt &Low, const APInt &High,
850 const DataLayout &DL) const {
851 // FIXME: I don't think NumCmps is the correct metric: a single case and a
852 // range of cases both require only one branch to lower. Just looking at the
853 // number of clusters and destinations should be enough to decide whether to
854 // build bit tests.
855
856 // To lower a range with bit tests, the range must fit the bitwidth of a
857 // machine word.
858 if (!rangeFitsInWord(Low, High, DL))
859 return false;
860
861 // Decide whether it's profitable to lower this range with bit tests. Each
862 // destination requires a bit test and branch, and there is an overall range
863 // check branch. For a small number of clusters, separate comparisons might
864 // be cheaper, and for many destinations, splitting the range might be
865 // better.
866 return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
867 (NumDests == 3 && NumCmps >= 6);
868 }
869
870 /// Return true if the specified operation is illegal on this target or
871 /// unlikely to be made legal with custom lowering. This is used to help guide
872 /// high-level lowering decisions.
873 bool isOperationExpand(unsigned Op, EVT VT) const {
874 return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
875 }
876
877 /// Return true if the specified operation is legal on this target.
878 bool isOperationLegal(unsigned Op, EVT VT) const {
879 return (VT == MVT::Other || isTypeLegal(VT)) &&
880 getOperationAction(Op, VT) == Legal;
881 }
882
883 /// Return how this load with extension should be treated: either it is legal,
884 /// needs to be promoted to a larger size, needs to be expanded to some other
885 /// code sequence, or the target has a custom expander for it.
886 LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT,
887 EVT MemVT) const {
888 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
889 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
890 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
891 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::LAST_VALUETYPE &&(static_cast <bool> (ExtType < ISD::LAST_LOADEXT_TYPE
&& ValI < MVT::LAST_VALUETYPE && MemI <
MVT::LAST_VALUETYPE && "Table isn't big enough!") ? void
(0) : __assert_fail ("ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 892, __extension__ __PRETTY_FUNCTION__))
892 MemI < MVT::LAST_VALUETYPE && "Table isn't big enough!")(static_cast <bool> (ExtType < ISD::LAST_LOADEXT_TYPE
&& ValI < MVT::LAST_VALUETYPE && MemI <
MVT::LAST_VALUETYPE && "Table isn't big enough!") ? void
(0) : __assert_fail ("ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 892, __extension__ __PRETTY_FUNCTION__))
;
893 unsigned Shift = 4 * ExtType;
894 return (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
895 }
896
897 /// Return true if the specified load with extension is legal on this target.
898 bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
899 return getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
900 }
901
902 /// Return true if the specified load with extension is legal or custom
903 /// on this target.
904 bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
905 return getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
906 getLoadExtAction(ExtType, ValVT, MemVT) == Custom;
907 }
908
909 /// Return how this store with truncation should be treated: either it is
910 /// legal, needs to be promoted to a larger size, needs to be expanded to some
911 /// other code sequence, or the target has a custom expander for it.
912 LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
913 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
914 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
915 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
916 assert(ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE &&(static_cast <bool> (ValI < MVT::LAST_VALUETYPE &&
MemI < MVT::LAST_VALUETYPE && "Table isn't big enough!"
) ? void (0) : __assert_fail ("ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 917, __extension__ __PRETTY_FUNCTION__))
917 "Table isn't big enough!")(static_cast <bool> (ValI < MVT::LAST_VALUETYPE &&
MemI < MVT::LAST_VALUETYPE && "Table isn't big enough!"
) ? void (0) : __assert_fail ("ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 917, __extension__ __PRETTY_FUNCTION__))
;
918 return TruncStoreActions[ValI][MemI];
919 }
920
921 /// Return true if the specified store with truncation is legal on this
922 /// target.
923 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
924 return isTypeLegal(ValVT) && getTruncStoreAction(ValVT, MemVT) == Legal;
925 }
926
927 /// Return true if the specified store with truncation has solution on this
928 /// target.
929 bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const {
930 return isTypeLegal(ValVT) &&
931 (getTruncStoreAction(ValVT, MemVT) == Legal ||
932 getTruncStoreAction(ValVT, MemVT) == Custom);
933 }
934
935 /// Return how the indexed load should be treated: either it is legal, needs
936 /// to be promoted to a larger size, needs to be expanded to some other code
937 /// sequence, or the target has a custom expander for it.
938 LegalizeAction
939 getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
940 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&(static_cast <bool> (IdxMode < ISD::LAST_INDEXED_MODE
&& VT.isValid() && "Table isn't big enough!"
) ? void (0) : __assert_fail ("IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 941, __extension__ __PRETTY_FUNCTION__))
941 "Table isn't big enough!")(static_cast <bool> (IdxMode < ISD::LAST_INDEXED_MODE
&& VT.isValid() && "Table isn't big enough!"
) ? void (0) : __assert_fail ("IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 941, __extension__ __PRETTY_FUNCTION__))
;
942 unsigned Ty = (unsigned)VT.SimpleTy;
943 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
944 }
945
946 /// Return true if the specified indexed load is legal on this target.
947 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
948 return VT.isSimple() &&
949 (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
950 getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
951 }
952
953 /// Return how the indexed store should be treated: either it is legal, needs
954 /// to be promoted to a larger size, needs to be expanded to some other code
955 /// sequence, or the target has a custom expander for it.
956 LegalizeAction
957 getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
958 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&(static_cast <bool> (IdxMode < ISD::LAST_INDEXED_MODE
&& VT.isValid() && "Table isn't big enough!"
) ? void (0) : __assert_fail ("IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 959, __extension__ __PRETTY_FUNCTION__))
959 "Table isn't big enough!")(static_cast <bool> (IdxMode < ISD::LAST_INDEXED_MODE
&& VT.isValid() && "Table isn't big enough!"
) ? void (0) : __assert_fail ("IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 959, __extension__ __PRETTY_FUNCTION__))
;
960 unsigned Ty = (unsigned)VT.SimpleTy;
961 return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
962 }
963
964 /// Return true if the specified indexed load is legal on this target.
965 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
966 return VT.isSimple() &&
967 (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
968 getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
969 }
970
971 /// Return how the condition code should be treated: either it is legal, needs
972 /// to be expanded to some other code sequence, or the target has a custom
973 /// expander for it.
974 LegalizeAction
975 getCondCodeAction(ISD::CondCode CC, MVT VT) const {
976 assert((unsigned)CC < array_lengthof(CondCodeActions) &&(static_cast <bool> ((unsigned)CC < array_lengthof(CondCodeActions
) && ((unsigned)VT.SimpleTy >> 3) < array_lengthof
(CondCodeActions[0]) && "Table isn't big enough!") ? void
(0) : __assert_fail ("(unsigned)CC < array_lengthof(CondCodeActions) && ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 978, __extension__ __PRETTY_FUNCTION__))
977 ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) &&(static_cast <bool> ((unsigned)CC < array_lengthof(CondCodeActions
) && ((unsigned)VT.SimpleTy >> 3) < array_lengthof
(CondCodeActions[0]) && "Table isn't big enough!") ? void
(0) : __assert_fail ("(unsigned)CC < array_lengthof(CondCodeActions) && ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 978, __extension__ __PRETTY_FUNCTION__))
978 "Table isn't big enough!")(static_cast <bool> ((unsigned)CC < array_lengthof(CondCodeActions
) && ((unsigned)VT.SimpleTy >> 3) < array_lengthof
(CondCodeActions[0]) && "Table isn't big enough!") ? void
(0) : __assert_fail ("(unsigned)CC < array_lengthof(CondCodeActions) && ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 978, __extension__ __PRETTY_FUNCTION__))
;
979 // See setCondCodeAction for how this is encoded.
980 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
981 uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
982 LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
983 assert(Action != Promote && "Can't promote condition code!")(static_cast <bool> (Action != Promote && "Can't promote condition code!"
) ? void (0) : __assert_fail ("Action != Promote && \"Can't promote condition code!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 983, __extension__ __PRETTY_FUNCTION__))
;
984 return Action;
985 }
986
987 /// Return true if the specified condition code is legal on this target.
988 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
989 return
990 getCondCodeAction(CC, VT) == Legal ||
991 getCondCodeAction(CC, VT) == Custom;
992 }
993
994 /// If the action for this operation is to promote, this method returns the
995 /// ValueType to promote to.
996 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
997 assert(getOperationAction(Op, VT) == Promote &&(static_cast <bool> (getOperationAction(Op, VT) == Promote
&& "This operation isn't promoted!") ? void (0) : __assert_fail
("getOperationAction(Op, VT) == Promote && \"This operation isn't promoted!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 998, __extension__ __PRETTY_FUNCTION__))
998 "This operation isn't promoted!")(static_cast <bool> (getOperationAction(Op, VT) == Promote
&& "This operation isn't promoted!") ? void (0) : __assert_fail
("getOperationAction(Op, VT) == Promote && \"This operation isn't promoted!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 998, __extension__ __PRETTY_FUNCTION__))
;
999
1000 // See if this has an explicit type specified.
1001 std::map<std::pair<unsigned, MVT::SimpleValueType>,
1002 MVT::SimpleValueType>::const_iterator PTTI =
1003 PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
1004 if (PTTI != PromoteToType.end()) return PTTI->second;
1005
1006 assert((VT.isInteger() || VT.isFloatingPoint()) &&(static_cast <bool> ((VT.isInteger() || VT.isFloatingPoint
()) && "Cannot autopromote this type, add it with AddPromotedToType."
) ? void (0) : __assert_fail ("(VT.isInteger() || VT.isFloatingPoint()) && \"Cannot autopromote this type, add it with AddPromotedToType.\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1007, __extension__ __PRETTY_FUNCTION__))
1007 "Cannot autopromote this type, add it with AddPromotedToType.")(static_cast <bool> ((VT.isInteger() || VT.isFloatingPoint
()) && "Cannot autopromote this type, add it with AddPromotedToType."
) ? void (0) : __assert_fail ("(VT.isInteger() || VT.isFloatingPoint()) && \"Cannot autopromote this type, add it with AddPromotedToType.\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1007, __extension__ __PRETTY_FUNCTION__))
;
1008
1009 MVT NVT = VT;
1010 do {
1011 NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
1012 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&(static_cast <bool> (NVT.isInteger() == VT.isInteger() &&
NVT != MVT::isVoid && "Didn't find type to promote to!"
) ? void (0) : __assert_fail ("NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid && \"Didn't find type to promote to!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1013, __extension__ __PRETTY_FUNCTION__))
1013 "Didn't find type to promote to!")(static_cast <bool> (NVT.isInteger() == VT.isInteger() &&
NVT != MVT::isVoid && "Didn't find type to promote to!"
) ? void (0) : __assert_fail ("NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid && \"Didn't find type to promote to!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1013, __extension__ __PRETTY_FUNCTION__))
;
1014 } while (!isTypeLegal(NVT) ||
1015 getOperationAction(Op, NVT) == Promote);
1016 return NVT;
1017 }
1018
1019 /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
1020 /// operations except for the pointer size. If AllowUnknown is true, this
1021 /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1022 /// otherwise it will assert.
1023 EVT getValueType(const DataLayout &DL, Type *Ty,
1024 bool AllowUnknown = false) const {
1025 // Lower scalar pointers to native pointer types.
1026 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
15
Taking false branch
1027 return getPointerTy(DL, PTy->getAddressSpace());
1028
1029 if (Ty->isVectorTy()) {
16
Called C++ object pointer is null
1030 VectorType *VTy = cast<VectorType>(Ty);
1031 Type *Elm = VTy->getElementType();
1032 // Lower vectors of pointers to native pointer types.
1033 if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
1034 EVT PointerTy(getPointerTy(DL, PT->getAddressSpace()));
1035 Elm = PointerTy.getTypeForEVT(Ty->getContext());
1036 }
1037
1038 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
1039 VTy->getNumElements());
1040 }
1041 return EVT::getEVT(Ty, AllowUnknown);
1042 }
1043
1044 /// Return the MVT corresponding to this LLVM type. See getValueType.
1045 MVT getSimpleValueType(const DataLayout &DL, Type *Ty,
1046 bool AllowUnknown = false) const {
1047 return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
1048 }
1049
1050 /// Return the desired alignment for ByVal or InAlloca aggregate function
1051 /// arguments in the caller parameter area. This is the actual alignment, not
1052 /// its logarithm.
1053 virtual unsigned getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
1054
1055 /// Return the type of registers that this ValueType will eventually require.
1056 MVT getRegisterType(MVT VT) const {
1057 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT))(static_cast <bool> ((unsigned)VT.SimpleTy < array_lengthof
(RegisterTypeForVT)) ? void (0) : __assert_fail ("(unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT)"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1057, __extension__ __PRETTY_FUNCTION__))
;
1058 return RegisterTypeForVT[VT.SimpleTy];
1059 }
1060
1061 /// Return the type of registers that this ValueType will eventually require.
1062 MVT getRegisterType(LLVMContext &Context, EVT VT) const {
1063 if (VT.isSimple()) {
1064 assert((unsigned)VT.getSimpleVT().SimpleTy <(static_cast <bool> ((unsigned)VT.getSimpleVT().SimpleTy
< array_lengthof(RegisterTypeForVT)) ? void (0) : __assert_fail
("(unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegisterTypeForVT)"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1065, __extension__ __PRETTY_FUNCTION__))
1065 array_lengthof(RegisterTypeForVT))(static_cast <bool> ((unsigned)VT.getSimpleVT().SimpleTy
< array_lengthof(RegisterTypeForVT)) ? void (0) : __assert_fail
("(unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegisterTypeForVT)"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1065, __extension__ __PRETTY_FUNCTION__))
;
1066 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
1067 }
1068 if (VT.isVector()) {
1069 EVT VT1;
1070 MVT RegisterVT;
1071 unsigned NumIntermediates;
1072 (void)getVectorTypeBreakdown(Context, VT, VT1,
1073 NumIntermediates, RegisterVT);
1074 return RegisterVT;
1075 }
1076 if (VT.isInteger()) {
1077 return getRegisterType(Context, getTypeToTransformTo(Context, VT));
1078 }
1079 llvm_unreachable("Unsupported extended type!")::llvm::llvm_unreachable_internal("Unsupported extended type!"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1079)
;
1080 }
1081
1082 /// Return the number of registers that this ValueType will eventually
1083 /// require.
1084 ///
1085 /// This is one for any types promoted to live in larger registers, but may be
1086 /// more than one for types (like i64) that are split into pieces. For types
1087 /// like i140, which are first promoted then expanded, it is the number of
1088 /// registers needed to hold all the bits of the original type. For an i140
1089 /// on a 32 bit machine this means 5 registers.
1090 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
1091 if (VT.isSimple()) {
1092 assert((unsigned)VT.getSimpleVT().SimpleTy <(static_cast <bool> ((unsigned)VT.getSimpleVT().SimpleTy
< array_lengthof(NumRegistersForVT)) ? void (0) : __assert_fail
("(unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(NumRegistersForVT)"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1093, __extension__ __PRETTY_FUNCTION__))
1093 array_lengthof(NumRegistersForVT))(static_cast <bool> ((unsigned)VT.getSimpleVT().SimpleTy
< array_lengthof(NumRegistersForVT)) ? void (0) : __assert_fail
("(unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(NumRegistersForVT)"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1093, __extension__ __PRETTY_FUNCTION__))
;
1094 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
1095 }
1096 if (VT.isVector()) {
1097 EVT VT1;
1098 MVT VT2;
1099 unsigned NumIntermediates;
1100 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
1101 }
1102 if (VT.isInteger()) {
1103 unsigned BitWidth = VT.getSizeInBits();
1104 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
1105 return (BitWidth + RegWidth - 1) / RegWidth;
1106 }
1107 llvm_unreachable("Unsupported extended type!")::llvm::llvm_unreachable_internal("Unsupported extended type!"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1107)
;
1108 }
1109
1110 /// Certain combinations of ABIs, Targets and features require that types
1111 /// are legal for some operations and not for other operations.
1112 /// For MIPS all vector types must be passed through the integer register set.
1113 virtual MVT getRegisterTypeForCallingConv(MVT VT) const {
1114 return getRegisterType(VT);
1115 }
1116
1117 virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context,
1118 EVT VT) const {
1119 return getRegisterType(Context, VT);
1120 }
1121
1122 /// Certain targets require unusual breakdowns of certain types. For MIPS,
1123 /// this occurs when a vector type is used, as vector are passed through the
1124 /// integer register set.
1125 virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context,
1126 EVT VT) const {
1127 return getNumRegisters(Context, VT);
1128 }
1129
1130 /// Certain targets have context senstive alignment requirements, where one
1131 /// type has the alignment requirement of another type.
1132 virtual unsigned getABIAlignmentForCallingConv(Type *ArgTy,
1133 DataLayout DL) const {
1134 return DL.getABITypeAlignment(ArgTy);
1135 }
1136
1137 /// If true, then instruction selection should seek to shrink the FP constant
1138 /// of the specified type to a smaller type in order to save space and / or
1139 /// reduce runtime.
1140 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
1141
1142 // Return true if it is profitable to reduce the given load node to a smaller
1143 // type.
1144 //
1145 // e.g. (i16 (trunc (i32 (load x))) -> i16 load x should be performed
1146 virtual bool shouldReduceLoadWidth(SDNode *Load,
1147 ISD::LoadExtType ExtTy,
1148 EVT NewVT) const {
1149 return true;
1150 }
1151
1152 /// When splitting a value of the specified type into parts, does the Lo
1153 /// or Hi part come first? This usually follows the endianness, except
1154 /// for ppcf128, where the Hi part always comes first.
1155 bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const {
1156 return DL.isBigEndian() || VT == MVT::ppcf128;
1157 }
1158
1159 /// If true, the target has custom DAG combine transformations that it can
1160 /// perform for the specified node.
1161 bool hasTargetDAGCombine(ISD::NodeType NT) const {
1162 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray))(static_cast <bool> (unsigned(NT >> 3) < array_lengthof
(TargetDAGCombineArray)) ? void (0) : __assert_fail ("unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray)"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1162, __extension__ __PRETTY_FUNCTION__))
;
1163 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
1164 }
1165
1166 unsigned getGatherAllAliasesMaxDepth() const {
1167 return GatherAllAliasesMaxDepth;
1168 }
1169
1170 /// Returns the size of the platform's va_list object.
1171 virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
1172 return getPointerTy(DL).getSizeInBits();
1173 }
1174
1175 /// \brief Get maximum # of store operations permitted for llvm.memset
1176 ///
1177 /// This function returns the maximum number of store operations permitted
1178 /// to replace a call to llvm.memset. The value is set by the target at the
1179 /// performance threshold for such a replacement. If OptSize is true,
1180 /// return the limit for functions that have OptSize attribute.
1181 unsigned getMaxStoresPerMemset(bool OptSize) const {
1182 return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
1183 }
1184
1185 /// \brief Get maximum # of store operations permitted for llvm.memcpy
1186 ///
1187 /// This function returns the maximum number of store operations permitted
1188 /// to replace a call to llvm.memcpy. The value is set by the target at the
1189 /// performance threshold for such a replacement. If OptSize is true,
1190 /// return the limit for functions that have OptSize attribute.
1191 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
1192 return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
1193 }
1194
1195 /// Get maximum # of load operations permitted for memcmp
1196 ///
1197 /// This function returns the maximum number of load operations permitted
1198 /// to replace a call to memcmp. The value is set by the target at the
1199 /// performance threshold for such a replacement. If OptSize is true,
1200 /// return the limit for functions that have OptSize attribute.
1201 unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
1202 return OptSize ? MaxLoadsPerMemcmpOptSize : MaxLoadsPerMemcmp;
1203 }
1204
1205 /// \brief Get maximum # of store operations permitted for llvm.memmove
1206 ///
1207 /// This function returns the maximum number of store operations permitted
1208 /// to replace a call to llvm.memmove. The value is set by the target at the
1209 /// performance threshold for such a replacement. If OptSize is true,
1210 /// return the limit for functions that have OptSize attribute.
1211 unsigned getMaxStoresPerMemmove(bool OptSize) const {
1212 return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
1213 }
1214
1215 /// \brief Determine if the target supports unaligned memory accesses.
1216 ///
1217 /// This function returns true if the target allows unaligned memory accesses
1218 /// of the specified type in the given address space. If true, it also returns
1219 /// whether the unaligned memory access is "fast" in the last argument by
1220 /// reference. This is used, for example, in situations where an array
1221 /// copy/move/set is converted to a sequence of store operations. Its use
1222 /// helps to ensure that such replacements don't generate code that causes an
1223 /// alignment error (trap) on the target machine.
1224 virtual bool allowsMisalignedMemoryAccesses(EVT,
1225 unsigned AddrSpace = 0,
1226 unsigned Align = 1,
1227 bool * /*Fast*/ = nullptr) const {
1228 return false;
1229 }
1230
1231 /// Return true if the target supports a memory access of this type for the
1232 /// given address space and alignment. If the access is allowed, the optional
1233 /// final parameter returns if the access is also fast (as defined by the
1234 /// target).
1235 bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1236 unsigned AddrSpace = 0, unsigned Alignment = 1,
1237 bool *Fast = nullptr) const;
1238
1239 /// Returns the target specific optimal type for load and store operations as
1240 /// a result of memset, memcpy, and memmove lowering.
1241 ///
1242 /// If DstAlign is zero that means it's safe to destination alignment can
1243 /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
1244 /// a need to check it against alignment requirement, probably because the
1245 /// source does not need to be loaded. If 'IsMemset' is true, that means it's
1246 /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
1247 /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
1248 /// does not need to be loaded. It returns EVT::Other if the type should be
1249 /// determined using generic target-independent logic.
1250 virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
1251 unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
1252 bool /*IsMemset*/,
1253 bool /*ZeroMemset*/,
1254 bool /*MemcpyStrSrc*/,
1255 MachineFunction &/*MF*/) const {
1256 return MVT::Other;
1257 }
1258
1259 /// Returns true if it's safe to use load / store of the specified type to
1260 /// expand memcpy / memset inline.
1261 ///
1262 /// This is mostly true for all types except for some special cases. For
1263 /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
1264 /// fstpl which also does type conversion. Note the specified type doesn't
1265 /// have to be legal as the hook is used before type legalization.
1266 virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
1267
1268 /// Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
1269 bool usesUnderscoreSetJmp() const {
1270 return UseUnderscoreSetJmp;
1271 }
1272
1273 /// Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
1274 bool usesUnderscoreLongJmp() const {
1275 return UseUnderscoreLongJmp;
1276 }
1277
1278 /// Return lower limit for number of blocks in a jump table.
1279 virtual unsigned getMinimumJumpTableEntries() const;
1280
1281 /// Return lower limit of the density in a jump table.
1282 unsigned getMinimumJumpTableDensity(bool OptForSize) const;
1283
1284 /// Return upper limit for number of entries in a jump table.
1285 /// Zero if no limit.
1286 unsigned getMaximumJumpTableSize() const;
1287
1288 virtual bool isJumpTableRelative() const {
1289 return TM.isPositionIndependent();
1290 }
1291
1292 /// If a physical register, this specifies the register that
1293 /// llvm.savestack/llvm.restorestack should save and restore.
1294 unsigned getStackPointerRegisterToSaveRestore() const {
1295 return StackPointerRegisterToSaveRestore;
1296 }
1297
1298 /// If a physical register, this returns the register that receives the
1299 /// exception address on entry to an EH pad.
1300 virtual unsigned
1301 getExceptionPointerRegister(const Constant *PersonalityFn) const {
1302 // 0 is guaranteed to be the NoRegister value on all targets
1303 return 0;
1304 }
1305
1306 /// If a physical register, this returns the register that receives the
1307 /// exception typeid on entry to a landing pad.
1308 virtual unsigned
1309 getExceptionSelectorRegister(const Constant *PersonalityFn) const {
1310 // 0 is guaranteed to be the NoRegister value on all targets
1311 return 0;
1312 }
1313
1314 virtual bool needsFixedCatchObjects() const {
1315 report_fatal_error("Funclet EH is not implemented for this target");
1316 }
1317
1318 /// Returns the target's jmp_buf size in bytes (if never set, the default is
1319 /// 200)
1320 unsigned getJumpBufSize() const {
1321 return JumpBufSize;
1322 }
1323
1324 /// Returns the target's jmp_buf alignment in bytes (if never set, the default
1325 /// is 0)
1326 unsigned getJumpBufAlignment() const {
1327 return JumpBufAlignment;
1328 }
1329
1330 /// Return the minimum stack alignment of an argument.
1331 unsigned getMinStackArgumentAlignment() const {
1332 return MinStackArgumentAlignment;
1333 }
1334
1335 /// Return the minimum function alignment.
1336 unsigned getMinFunctionAlignment() const {
1337 return MinFunctionAlignment;
1338 }
1339
1340 /// Return the preferred function alignment.
1341 unsigned getPrefFunctionAlignment() const {
1342 return PrefFunctionAlignment;
1343 }
1344
1345 /// Return the preferred loop alignment.
1346 virtual unsigned getPrefLoopAlignment(MachineLoop *ML = nullptr) const {
1347 return PrefLoopAlignment;
1348 }
1349
1350 /// If the target has a standard location for the stack protector guard,
1351 /// returns the address of that location. Otherwise, returns nullptr.
1352 /// DEPRECATED: please override useLoadStackGuardNode and customize
1353 /// LOAD_STACK_GUARD, or customize @llvm.stackguard().
1354 virtual Value *getIRStackGuard(IRBuilder<> &IRB) const;
1355
1356 /// Inserts necessary declarations for SSP (stack protection) purpose.
1357 /// Should be used only when getIRStackGuard returns nullptr.
1358 virtual void insertSSPDeclarations(Module &M) const;
1359
1360 /// Return the variable that's previously inserted by insertSSPDeclarations,
1361 /// if any, otherwise return nullptr. Should be used only when
1362 /// getIRStackGuard returns nullptr.
1363 virtual Value *getSDagStackGuard(const Module &M) const;
1364
1365 /// If this function returns true, stack protection checks should XOR the
1366 /// frame pointer (or whichever pointer is used to address locals) into the
1367 /// stack guard value before checking it. getIRStackGuard must return nullptr
1368 /// if this returns true.
1369 virtual bool useStackGuardXorFP() const { return false; }
1370
1371 /// If the target has a standard stack protection check function that
1372 /// performs validation and error handling, returns the function. Otherwise,
1373 /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
1374 /// Should be used only when getIRStackGuard returns nullptr.
1375 virtual Value *getSSPStackGuardCheck(const Module &M) const;
1376
1377protected:
1378 Value *getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
1379 bool UseTLS) const;
1380
1381public:
1382 /// Returns the target-specific address of the unsafe stack pointer.
1383 virtual Value *getSafeStackPointerLocation(IRBuilder<> &IRB) const;
1384
1385 /// Returns the name of the symbol used to emit stack probes or the empty
1386 /// string if not applicable.
1387 virtual StringRef getStackProbeSymbolName(MachineFunction &MF) const {
1388 return "";
1389 }
1390
1391 /// Returns true if a cast between SrcAS and DestAS is a noop.
1392 virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
1393 return false;
1394 }
1395
1396 /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
1397 /// are happy to sink it into basic blocks.
1398 virtual bool isCheapAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
1399 return isNoopAddrSpaceCast(SrcAS, DestAS);
1400 }
1401
1402 /// Return true if the pointer arguments to CI should be aligned by aligning
1403 /// the object whose address is being passed. If so then MinSize is set to the
1404 /// minimum size the object must be to be aligned and PrefAlign is set to the
1405 /// preferred alignment.
1406 virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
1407 unsigned & /*PrefAlign*/) const {
1408 return false;
1409 }
1410
1411 //===--------------------------------------------------------------------===//
1412 /// \name Helpers for TargetTransformInfo implementations
1413 /// @{
1414
1415 /// Get the ISD node that corresponds to the Instruction class opcode.
1416 int InstructionOpcodeToISD(unsigned Opcode) const;
1417
1418 /// Estimate the cost of type-legalization and the legalized type.
1419 std::pair<int, MVT> getTypeLegalizationCost(const DataLayout &DL,
1420 Type *Ty) const;
1421
1422 /// @}
1423
1424 //===--------------------------------------------------------------------===//
1425 /// \name Helpers for atomic expansion.
1426 /// @{
1427
1428 /// Returns the maximum atomic operation size (in bits) supported by
1429 /// the backend. Atomic operations greater than this size (as well
1430 /// as ones that are not naturally aligned), will be expanded by
1431 /// AtomicExpandPass into an __atomic_* library call.
1432 unsigned getMaxAtomicSizeInBitsSupported() const {
1433 return MaxAtomicSizeInBitsSupported;
1434 }
1435
1436 /// Returns the size of the smallest cmpxchg or ll/sc instruction
1437 /// the backend supports. Any smaller operations are widened in
1438 /// AtomicExpandPass.
1439 ///
1440 /// Note that *unlike* operations above the maximum size, atomic ops
1441 /// are still natively supported below the minimum; they just
1442 /// require a more complex expansion.
1443 unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
1444
1445 /// Whether the target supports unaligned atomic operations.
1446 bool supportsUnalignedAtomics() const { return SupportsUnalignedAtomics; }
1447
1448 /// Whether AtomicExpandPass should automatically insert fences and reduce
1449 /// ordering for this atomic. This should be true for most architectures with
1450 /// weak memory ordering. Defaults to false.
1451 virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
1452 return false;
1453 }
1454
1455 /// Perform a load-linked operation on Addr, returning a "Value *" with the
1456 /// corresponding pointee type. This may entail some non-trivial operations to
1457 /// truncate or reconstruct types that will be illegal in the backend. See
1458 /// ARMISelLowering for an example implementation.
1459 virtual Value *emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
1460 AtomicOrdering Ord) const {
1461 llvm_unreachable("Load linked unimplemented on this target")::llvm::llvm_unreachable_internal("Load linked unimplemented on this target"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1461)
;
1462 }
1463
1464 /// Perform a store-conditional operation to Addr. Return the status of the
1465 /// store. This should be 0 if the store succeeded, non-zero otherwise.
1466 virtual Value *emitStoreConditional(IRBuilder<> &Builder, Value *Val,
1467 Value *Addr, AtomicOrdering Ord) const {
1468 llvm_unreachable("Store conditional unimplemented on this target")::llvm::llvm_unreachable_internal("Store conditional unimplemented on this target"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1468)
;
1469 }
1470
1471 /// Inserts in the IR a target-specific intrinsic specifying a fence.
1472 /// It is called by AtomicExpandPass before expanding an
1473 /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
1474 /// if shouldInsertFencesForAtomic returns true.
1475 ///
1476 /// Inst is the original atomic instruction, prior to other expansions that
1477 /// may be performed.
1478 ///
1479 /// This function should either return a nullptr, or a pointer to an IR-level
1480 /// Instruction*. Even complex fence sequences can be represented by a
1481 /// single Instruction* through an intrinsic to be lowered later.
1482 /// Backends should override this method to produce target-specific intrinsic
1483 /// for their fences.
1484 /// FIXME: Please note that the default implementation here in terms of
1485 /// IR-level fences exists for historical/compatibility reasons and is
1486 /// *unsound* ! Fences cannot, in general, be used to restore sequential
1487 /// consistency. For example, consider the following example:
1488 /// atomic<int> x = y = 0;
1489 /// int r1, r2, r3, r4;
1490 /// Thread 0:
1491 /// x.store(1);
1492 /// Thread 1:
1493 /// y.store(1);
1494 /// Thread 2:
1495 /// r1 = x.load();
1496 /// r2 = y.load();
1497 /// Thread 3:
1498 /// r3 = y.load();
1499 /// r4 = x.load();
1500 /// r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
1501 /// seq_cst. But if they are lowered to monotonic accesses, no amount of
1502 /// IR-level fences can prevent it.
1503 /// @{
1504 virtual Instruction *emitLeadingFence(IRBuilder<> &Builder, Instruction *Inst,
1505 AtomicOrdering Ord) const {
1506 if (isReleaseOrStronger(Ord) && Inst->hasAtomicStore())
1507 return Builder.CreateFence(Ord);
1508 else
1509 return nullptr;
1510 }
1511
1512 virtual Instruction *emitTrailingFence(IRBuilder<> &Builder,
1513 Instruction *Inst,
1514 AtomicOrdering Ord) const {
1515 if (isAcquireOrStronger(Ord))
1516 return Builder.CreateFence(Ord);
1517 else
1518 return nullptr;
1519 }
1520 /// @}
1521
1522 // Emits code that executes when the comparison result in the ll/sc
1523 // expansion of a cmpxchg instruction is such that the store-conditional will
1524 // not execute. This makes it possible to balance out the load-linked with
1525 // a dedicated instruction, if desired.
1526 // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
1527 // be unnecessarily held, except if clrex, inserted by this hook, is executed.
1528 virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilder<> &Builder) const {}
1529
1530 /// Returns true if the given (atomic) store should be expanded by the
1531 /// IR-level AtomicExpand pass into an "atomic xchg" which ignores its input.
1532 virtual bool shouldExpandAtomicStoreInIR(StoreInst *SI) const {
1533 return false;
1534 }
1535
1536 /// Returns true if arguments should be sign-extended in lib calls.
1537 virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
1538 return IsSigned;
1539 }
1540
1541 /// Returns how the given (atomic) load should be expanded by the
1542 /// IR-level AtomicExpand pass.
1543 virtual AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const {
1544 return AtomicExpansionKind::None;
1545 }
1546
1547 /// Returns true if the given atomic cmpxchg should be expanded by the
1548 /// IR-level AtomicExpand pass into a load-linked/store-conditional sequence
1549 /// (through emitLoadLinked() and emitStoreConditional()).
1550 virtual bool shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
1551 return false;
1552 }
1553
1554 /// Returns how the IR-level AtomicExpand pass should expand the given
1555 /// AtomicRMW, if at all. Default is to never expand.
1556 virtual AtomicExpansionKind shouldExpandAtomicRMWInIR(AtomicRMWInst *) const {
1557 return AtomicExpansionKind::None;
1558 }
1559
1560 /// On some platforms, an AtomicRMW that never actually modifies the value
1561 /// (such as fetch_add of 0) can be turned into a fence followed by an
1562 /// atomic load. This may sound useless, but it makes it possible for the
1563 /// processor to keep the cacheline shared, dramatically improving
1564 /// performance. And such idempotent RMWs are useful for implementing some
1565 /// kinds of locks, see for example (justification + benchmarks):
1566 /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
1567 /// This method tries doing that transformation, returning the atomic load if
1568 /// it succeeds, and nullptr otherwise.
1569 /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
1570 /// another round of expansion.
1571 virtual LoadInst *
1572 lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *RMWI) const {
1573 return nullptr;
1574 }
1575
1576 /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
1577 /// SIGN_EXTEND, or ANY_EXTEND).
1578 virtual ISD::NodeType getExtendForAtomicOps() const {
1579 return ISD::ZERO_EXTEND;
1580 }
1581
1582 /// @}
1583
1584 /// Returns true if we should normalize
1585 /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
1586 /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
1587 /// that it saves us from materializing N0 and N1 in an integer register.
1588 /// Targets that are able to perform and/or on flags should return false here.
1589 virtual bool shouldNormalizeToSelectSequence(LLVMContext &Context,
1590 EVT VT) const {
1591 // If a target has multiple condition registers, then it likely has logical
1592 // operations on those registers.
1593 if (hasMultipleConditionRegisters())
1594 return false;
1595 // Only do the transform if the value won't be split into multiple
1596 // registers.
1597 LegalizeTypeAction Action = getTypeAction(Context, VT);
1598 return Action != TypeExpandInteger && Action != TypeExpandFloat &&
1599 Action != TypeSplitVector;
1600 }
1601
1602 /// Return true if a select of constants (select Cond, C1, C2) should be
1603 /// transformed into simple math ops with the condition value. For example:
1604 /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
1605 virtual bool convertSelectOfConstantsToMath(EVT VT) const {
1606 return false;
1607 }
1608
1609 //===--------------------------------------------------------------------===//
1610 // TargetLowering Configuration Methods - These methods should be invoked by
1611 // the derived class constructor to configure this object for the target.
1612 //
1613protected:
1614 /// Specify how the target extends the result of integer and floating point
1615 /// boolean values from i1 to a wider type. See getBooleanContents.
1616 void setBooleanContents(BooleanContent Ty) {
1617 BooleanContents = Ty;
1618 BooleanFloatContents = Ty;
1619 }
1620
1621 /// Specify how the target extends the result of integer and floating point
1622 /// boolean values from i1 to a wider type. See getBooleanContents.
1623 void setBooleanContents(BooleanContent IntTy, BooleanContent FloatTy) {
1624 BooleanContents = IntTy;
1625 BooleanFloatContents = FloatTy;
1626 }
1627
1628 /// Specify how the target extends the result of a vector boolean value from a
1629 /// vector of i1 to a wider type. See getBooleanContents.
1630 void setBooleanVectorContents(BooleanContent Ty) {
1631 BooleanVectorContents = Ty;
1632 }
1633
1634 /// Specify the target scheduling preference.
1635 void setSchedulingPreference(Sched::Preference Pref) {
1636 SchedPreferenceInfo = Pref;
1637 }
1638
1639 /// Indicate whether this target prefers to use _setjmp to implement
1640 /// llvm.setjmp or the version without _. Defaults to false.
1641 void setUseUnderscoreSetJmp(bool Val) {
1642 UseUnderscoreSetJmp = Val;
1643 }
1644
1645 /// Indicate whether this target prefers to use _longjmp to implement
1646 /// llvm.longjmp or the version without _. Defaults to false.
1647 void setUseUnderscoreLongJmp(bool Val) {
1648 UseUnderscoreLongJmp = Val;
1649 }
1650
1651 /// Indicate the minimum number of blocks to generate jump tables.
1652 void setMinimumJumpTableEntries(unsigned Val);
1653
1654 /// Indicate the maximum number of entries in jump tables.
1655 /// Set to zero to generate unlimited jump tables.
1656 void setMaximumJumpTableSize(unsigned);
1657
1658 /// If set to a physical register, this specifies the register that
1659 /// llvm.savestack/llvm.restorestack should save and restore.
1660 void setStackPointerRegisterToSaveRestore(unsigned R) {
1661 StackPointerRegisterToSaveRestore = R;
1662 }
1663
1664 /// Tells the code generator that the target has multiple (allocatable)
1665 /// condition registers that can be used to store the results of comparisons
1666 /// for use by selects and conditional branches. With multiple condition
1667 /// registers, the code generator will not aggressively sink comparisons into
1668 /// the blocks of their users.
1669 void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
1670 HasMultipleConditionRegisters = hasManyRegs;
1671 }
1672
1673 /// Tells the code generator that the target has BitExtract instructions.
1674 /// The code generator will aggressively sink "shift"s into the blocks of
1675 /// their users if the users will generate "and" instructions which can be
1676 /// combined with "shift" to BitExtract instructions.
1677 void setHasExtractBitsInsn(bool hasExtractInsn = true) {
1678 HasExtractBitsInsn = hasExtractInsn;
1679 }
1680
1681 /// Tells the code generator not to expand logic operations on comparison
1682 /// predicates into separate sequences that increase the amount of flow
1683 /// control.
1684 void setJumpIsExpensive(bool isExpensive = true);
1685
1686 /// Tells the code generator that this target supports floating point
1687 /// exceptions and cares about preserving floating point exception behavior.
1688 void setHasFloatingPointExceptions(bool FPExceptions = true) {
1689 HasFloatingPointExceptions = FPExceptions;
1690 }
1691
1692 /// Tells the code generator which bitwidths to bypass.
1693 void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
1694 BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
1695 }
1696
1697 /// Add the specified register class as an available regclass for the
1698 /// specified value type. This indicates the selector can handle values of
1699 /// that class natively.
1700 void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
1701 assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT))(static_cast <bool> ((unsigned)VT.SimpleTy < array_lengthof
(RegClassForVT)) ? void (0) : __assert_fail ("(unsigned)VT.SimpleTy < array_lengthof(RegClassForVT)"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1701, __extension__ __PRETTY_FUNCTION__))
;
1702 RegClassForVT[VT.SimpleTy] = RC;
1703 }
1704
1705 /// Return the largest legal super-reg register class of the register class
1706 /// for the specified type and its associated "cost".
1707 virtual std::pair<const TargetRegisterClass *, uint8_t>
1708 findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const;
1709
1710 /// Once all of the register classes are added, this allows us to compute
1711 /// derived properties we expose.
1712 void computeRegisterProperties(const TargetRegisterInfo *TRI);
1713
1714 /// Indicate that the specified operation does not work with the specified
1715 /// type and indicate what to do about it. Note that VT may refer to either
1716 /// the type of a result or that of an operand of Op.
1717 void setOperationAction(unsigned Op, MVT VT,
1718 LegalizeAction Action) {
1719 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!")(static_cast <bool> (Op < array_lengthof(OpActions[0
]) && "Table isn't big enough!") ? void (0) : __assert_fail
("Op < array_lengthof(OpActions[0]) && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1719, __extension__ __PRETTY_FUNCTION__))
;
1720 OpActions[(unsigned)VT.SimpleTy][Op] = Action;
1721 }
1722
1723 /// Indicate that the specified load with extension does not work with the
1724 /// specified type and indicate what to do about it.
1725 void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
1726 LegalizeAction Action) {
1727 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&(static_cast <bool> (ExtType < ISD::LAST_LOADEXT_TYPE
&& ValVT.isValid() && MemVT.isValid() &&
"Table isn't big enough!") ? void (0) : __assert_fail ("ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() && MemVT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1728, __extension__ __PRETTY_FUNCTION__))
1728 MemVT.isValid() && "Table isn't big enough!")(static_cast <bool> (ExtType < ISD::LAST_LOADEXT_TYPE
&& ValVT.isValid() && MemVT.isValid() &&
"Table isn't big enough!") ? void (0) : __assert_fail ("ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() && MemVT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1728, __extension__ __PRETTY_FUNCTION__))
;
1729 assert((unsigned)Action < 0x10 && "too many bits for bitfield array")(static_cast <bool> ((unsigned)Action < 0x10 &&
"too many bits for bitfield array") ? void (0) : __assert_fail
("(unsigned)Action < 0x10 && \"too many bits for bitfield array\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1729, __extension__ __PRETTY_FUNCTION__))
;
1730 unsigned Shift = 4 * ExtType;
1731 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
1732 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
1733 }
1734
1735 /// Indicate that the specified truncating store does not work with the
1736 /// specified type and indicate what to do about it.
1737 void setTruncStoreAction(MVT ValVT, MVT MemVT,
1738 LegalizeAction Action) {
1739 assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!")(static_cast <bool> (ValVT.isValid() && MemVT.isValid
() && "Table isn't big enough!") ? void (0) : __assert_fail
("ValVT.isValid() && MemVT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1739, __extension__ __PRETTY_FUNCTION__))
;
1740 TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
1741 }
1742
1743 /// Indicate that the specified indexed load does or does not work with the
1744 /// specified type and indicate what to do abort it.
1745 ///
1746 /// NOTE: All indexed mode loads are initialized to Expand in
1747 /// TargetLowering.cpp
1748 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1749 LegalizeAction Action) {
1750 assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&(static_cast <bool> (VT.isValid() && IdxMode <
ISD::LAST_INDEXED_MODE && (unsigned)Action < 0xf &&
"Table isn't big enough!") ? void (0) : __assert_fail ("VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE && (unsigned)Action < 0xf && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1751, __extension__ __PRETTY_FUNCTION__))
1751 (unsigned)Action < 0xf && "Table isn't big enough!")(static_cast <bool> (VT.isValid() && IdxMode <
ISD::LAST_INDEXED_MODE && (unsigned)Action < 0xf &&
"Table isn't big enough!") ? void (0) : __assert_fail ("VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE && (unsigned)Action < 0xf && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1751, __extension__ __PRETTY_FUNCTION__))
;
1752 // Load action are kept in the upper half.
1753 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1754 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1755 }
1756
1757 /// Indicate that the specified indexed store does or does not work with the
1758 /// specified type and indicate what to do about it.
1759 ///
1760 /// NOTE: All indexed mode stores are initialized to Expand in
1761 /// TargetLowering.cpp
1762 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1763 LegalizeAction Action) {
1764 assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&(static_cast <bool> (VT.isValid() && IdxMode <
ISD::LAST_INDEXED_MODE && (unsigned)Action < 0xf &&
"Table isn't big enough!") ? void (0) : __assert_fail ("VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE && (unsigned)Action < 0xf && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1765, __extension__ __PRETTY_FUNCTION__))
1765 (unsigned)Action < 0xf && "Table isn't big enough!")(static_cast <bool> (VT.isValid() && IdxMode <
ISD::LAST_INDEXED_MODE && (unsigned)Action < 0xf &&
"Table isn't big enough!") ? void (0) : __assert_fail ("VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE && (unsigned)Action < 0xf && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1765, __extension__ __PRETTY_FUNCTION__))
;
1766 // Store action are kept in the lower half.
1767 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1768 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1769 }
1770
1771 /// Indicate that the specified condition code is or isn't supported on the
1772 /// target and indicate what to do about it.
1773 void setCondCodeAction(ISD::CondCode CC, MVT VT,
1774 LegalizeAction Action) {
1775 assert(VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) &&(static_cast <bool> (VT.isValid() && (unsigned)
CC < array_lengthof(CondCodeActions) && "Table isn't big enough!"
) ? void (0) : __assert_fail ("VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1776, __extension__ __PRETTY_FUNCTION__))
1776 "Table isn't big enough!")(static_cast <bool> (VT.isValid() && (unsigned)
CC < array_lengthof(CondCodeActions) && "Table isn't big enough!"
) ? void (0) : __assert_fail ("VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1776, __extension__ __PRETTY_FUNCTION__))
;
1777 assert((unsigned)Action < 0x10 && "too many bits for bitfield array")(static_cast <bool> ((unsigned)Action < 0x10 &&
"too many bits for bitfield array") ? void (0) : __assert_fail
("(unsigned)Action < 0x10 && \"too many bits for bitfield array\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1777, __extension__ __PRETTY_FUNCTION__))
;
1778 /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the 32-bit
1779 /// value and the upper 29 bits index into the second dimension of the array
1780 /// to select what 32-bit value to use.
1781 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1782 CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
1783 CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
1784 }
1785
1786 /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
1787 /// to trying a larger integer/fp until it can find one that works. If that
1788 /// default is insufficient, this method can be used by the target to override
1789 /// the default.
1790 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1791 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1792 }
1793
1794 /// Convenience method to set an operation to Promote and specify the type
1795 /// in a single call.
1796 void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1797 setOperationAction(Opc, OrigVT, Promote);
1798 AddPromotedToType(Opc, OrigVT, DestVT);
1799 }
1800
1801 /// Targets should invoke this method for each target independent node that
1802 /// they want to provide a custom DAG combiner for by implementing the
1803 /// PerformDAGCombine virtual method.
1804 void setTargetDAGCombine(ISD::NodeType NT) {
1805 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray))(static_cast <bool> (unsigned(NT >> 3) < array_lengthof
(TargetDAGCombineArray)) ? void (0) : __assert_fail ("unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray)"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 1805, __extension__ __PRETTY_FUNCTION__))
;
1806 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1807 }
1808
1809 /// Set the target's required jmp_buf buffer size (in bytes); default is 200
1810 void setJumpBufSize(unsigned Size) {
1811 JumpBufSize = Size;
1812 }
1813
1814 /// Set the target's required jmp_buf buffer alignment (in bytes); default is
1815 /// 0
1816 void setJumpBufAlignment(unsigned Align) {
1817 JumpBufAlignment = Align;
1818 }
1819
1820 /// Set the target's minimum function alignment (in log2(bytes))
1821 void setMinFunctionAlignment(unsigned Align) {
1822 MinFunctionAlignment = Align;
1823 }
1824
1825 /// Set the target's preferred function alignment. This should be set if
1826 /// there is a performance benefit to higher-than-minimum alignment (in
1827 /// log2(bytes))
1828 void setPrefFunctionAlignment(unsigned Align) {
1829 PrefFunctionAlignment = Align;
1830 }
1831
1832 /// Set the target's preferred loop alignment. Default alignment is zero, it
1833 /// means the target does not care about loop alignment. The alignment is
1834 /// specified in log2(bytes). The target may also override
1835 /// getPrefLoopAlignment to provide per-loop values.
1836 void setPrefLoopAlignment(unsigned Align) {
1837 PrefLoopAlignment = Align;
1838 }
1839
1840 /// Set the minimum stack alignment of an argument (in log2(bytes)).
1841 void setMinStackArgumentAlignment(unsigned Align) {
1842 MinStackArgumentAlignment = Align;
1843 }
1844
1845 /// Set the maximum atomic operation size supported by the
1846 /// backend. Atomic operations greater than this size (as well as
1847 /// ones that are not naturally aligned), will be expanded by
1848 /// AtomicExpandPass into an __atomic_* library call.
1849 void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
1850 MaxAtomicSizeInBitsSupported = SizeInBits;
1851 }
1852
1853 /// Sets the minimum cmpxchg or ll/sc size supported by the backend.
1854 void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
1855 MinCmpXchgSizeInBits = SizeInBits;
1856 }
1857
1858 /// Sets whether unaligned atomic operations are supported.
1859 void setSupportsUnalignedAtomics(bool UnalignedSupported) {
1860 SupportsUnalignedAtomics = UnalignedSupported;
1861 }
1862
1863public:
1864 //===--------------------------------------------------------------------===//
1865 // Addressing mode description hooks (used by LSR etc).
1866 //
1867
1868 /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
1869 /// instructions reading the address. This allows as much computation as
1870 /// possible to be done in the address mode for that operand. This hook lets
1871 /// targets also pass back when this should be done on intrinsics which
1872 /// load/store.
1873 virtual bool getAddrModeArguments(IntrinsicInst * /*I*/,
1874 SmallVectorImpl<Value*> &/*Ops*/,
1875 Type *&/*AccessTy*/) const {
1876 return false;
1877 }
1878
1879 /// This represents an addressing mode of:
1880 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1881 /// If BaseGV is null, there is no BaseGV.
1882 /// If BaseOffs is zero, there is no base offset.
1883 /// If HasBaseReg is false, there is no base register.
1884 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1885 /// no scale.
1886 struct AddrMode {
1887 GlobalValue *BaseGV = nullptr;
1888 int64_t BaseOffs = 0;
1889 bool HasBaseReg = false;
1890 int64_t Scale = 0;
1891 AddrMode() = default;
1892 };
1893
1894 /// Return true if the addressing mode represented by AM is legal for this
1895 /// target, for a load/store of the specified type.
1896 ///
1897 /// The type may be VoidTy, in which case only return true if the addressing
1898 /// mode is legal for a load/store of any legal type. TODO: Handle
1899 /// pre/postinc as well.
1900 ///
1901 /// If the address space cannot be determined, it will be -1.
1902 ///
1903 /// TODO: Remove default argument
1904 virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
1905 Type *Ty, unsigned AddrSpace,
1906 Instruction *I = nullptr) const;
1907
1908 /// \brief Return the cost of the scaling factor used in the addressing mode
1909 /// represented by AM for this target, for a load/store of the specified type.
1910 ///
1911 /// If the AM is supported, the return value must be >= 0.
1912 /// If the AM is not supported, it returns a negative value.
1913 /// TODO: Handle pre/postinc as well.
1914 /// TODO: Remove default argument
1915 virtual int getScalingFactorCost(const DataLayout &DL, const AddrMode &AM,
1916 Type *Ty, unsigned AS = 0) const {
1917 // Default: assume that any scaling factor used in a legal AM is free.
1918 if (isLegalAddressingMode(DL, AM, Ty, AS))
1919 return 0;
1920 return -1;
1921 }
1922
1923 /// Return true if the specified immediate is legal icmp immediate, that is
1924 /// the target has icmp instructions which can compare a register against the
1925 /// immediate without having to materialize the immediate into a register.
1926 virtual bool isLegalICmpImmediate(int64_t) const {
1927 return true;
1928 }
1929
1930 /// Return true if the specified immediate is legal add immediate, that is the
1931 /// target has add instructions which can add a register with the immediate
1932 /// without having to materialize the immediate into a register.
1933 virtual bool isLegalAddImmediate(int64_t) const {
1934 return true;
1935 }
1936
1937 /// Return true if it's significantly cheaper to shift a vector by a uniform
1938 /// scalar than by an amount which will vary across each lane. On x86, for
1939 /// example, there is a "psllw" instruction for the former case, but no simple
1940 /// instruction for a general "a << b" operation on vectors.
1941 virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
1942 return false;
1943 }
1944
1945 /// Returns true if the opcode is a commutative binary operation.
1946 virtual bool isCommutativeBinOp(unsigned Opcode) const {
1947 // FIXME: This should get its info from the td file.
1948 switch (Opcode) {
1949 case ISD::ADD:
1950 case ISD::SMIN:
1951 case ISD::SMAX:
1952 case ISD::UMIN:
1953 case ISD::UMAX:
1954 case ISD::MUL:
1955 case ISD::MULHU:
1956 case ISD::MULHS:
1957 case ISD::SMUL_LOHI:
1958 case ISD::UMUL_LOHI:
1959 case ISD::FADD:
1960 case ISD::FMUL:
1961 case ISD::AND:
1962 case ISD::OR:
1963 case ISD::XOR:
1964 case ISD::SADDO:
1965 case ISD::UADDO:
1966 case ISD::ADDC:
1967 case ISD::ADDE:
1968 case ISD::FMINNUM:
1969 case ISD::FMAXNUM:
1970 case ISD::FMINNAN:
1971 case ISD::FMAXNAN:
1972 return true;
1973 default: return false;
1974 }
1975 }
1976
1977 /// Return true if it's free to truncate a value of type FromTy to type
1978 /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
1979 /// by referencing its sub-register AX.
1980 /// Targets must return false when FromTy <= ToTy.
1981 virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
1982 return false;
1983 }
1984
1985 /// Return true if a truncation from FromTy to ToTy is permitted when deciding
1986 /// whether a call is in tail position. Typically this means that both results
1987 /// would be assigned to the same register or stack slot, but it could mean
1988 /// the target performs adequate checks of its own before proceeding with the
1989 /// tail call. Targets must return false when FromTy <= ToTy.
1990 virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
1991 return false;
1992 }
1993
1994 virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const {
1995 return false;
1996 }
1997
1998 virtual bool isProfitableToHoist(Instruction *I) const { return true; }
1999
2000 /// Return true if the extension represented by \p I is free.
2001 /// Unlikely the is[Z|FP]ExtFree family which is based on types,
2002 /// this method can use the context provided by \p I to decide
2003 /// whether or not \p I is free.
2004 /// This method extends the behavior of the is[Z|FP]ExtFree family.
2005 /// In other words, if is[Z|FP]Free returns true, then this method
2006 /// returns true as well. The converse is not true.
2007 /// The target can perform the adequate checks by overriding isExtFreeImpl.
2008 /// \pre \p I must be a sign, zero, or fp extension.
2009 bool isExtFree(const Instruction *I) const {
2010 switch (I->getOpcode()) {
2011 case Instruction::FPExt:
2012 if (isFPExtFree(EVT::getEVT(I->getType()),
2013 EVT::getEVT(I->getOperand(0)->getType())))
2014 return true;
2015 break;
2016 case Instruction::ZExt:
2017 if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
2018 return true;
2019 break;
2020 case Instruction::SExt:
2021 break;
2022 default:
2023 llvm_unreachable("Instruction is not an extension")::llvm::llvm_unreachable_internal("Instruction is not an extension"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 2023)
;
2024 }
2025 return isExtFreeImpl(I);
2026 }
2027
2028 /// Return true if \p Load and \p Ext can form an ExtLoad.
2029 /// For example, in AArch64
2030 /// %L = load i8, i8* %ptr
2031 /// %E = zext i8 %L to i32
2032 /// can be lowered into one load instruction
2033 /// ldrb w0, [x0]
2034 bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
2035 const DataLayout &DL) const {
2036 EVT VT = getValueType(DL, Ext->getType());
2037 EVT LoadVT = getValueType(DL, Load->getType());
2038
2039 // If the load has other users and the truncate is not free, the ext
2040 // probably isn't free.
2041 if (!Load->hasOneUse() && (isTypeLegal(LoadVT) || !isTypeLegal(VT)) &&
2042 !isTruncateFree(Ext->getType(), Load->getType()))
2043 return false;
2044
2045 // Check whether the target supports casts folded into loads.
2046 unsigned LType;
2047 if (isa<ZExtInst>(Ext))
2048 LType = ISD::ZEXTLOAD;
2049 else {
2050 assert(isa<SExtInst>(Ext) && "Unexpected ext type!")(static_cast <bool> (isa<SExtInst>(Ext) &&
"Unexpected ext type!") ? void (0) : __assert_fail ("isa<SExtInst>(Ext) && \"Unexpected ext type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 2050, __extension__ __PRETTY_FUNCTION__))
;
2051 LType = ISD::SEXTLOAD;
2052 }
2053
2054 return isLoadExtLegal(LType, VT, LoadVT);
2055 }
2056
2057 /// Return true if any actual instruction that defines a value of type FromTy
2058 /// implicitly zero-extends the value to ToTy in the result register.
2059 ///
2060 /// The function should return true when it is likely that the truncate can
2061 /// be freely folded with an instruction defining a value of FromTy. If
2062 /// the defining instruction is unknown (because you're looking at a
2063 /// function argument, PHI, etc.) then the target may require an
2064 /// explicit truncate, which is not necessarily free, but this function
2065 /// does not deal with those cases.
2066 /// Targets must return false when FromTy >= ToTy.
2067 virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
2068 return false;
2069 }
2070
2071 virtual bool isZExtFree(EVT FromTy, EVT ToTy) const {
2072 return false;
2073 }
2074
2075 /// Return true if the target supplies and combines to a paired load
2076 /// two loaded values of type LoadedType next to each other in memory.
2077 /// RequiredAlignment gives the minimal alignment constraints that must be met
2078 /// to be able to select this paired load.
2079 ///
2080 /// This information is *not* used to generate actual paired loads, but it is
2081 /// used to generate a sequence of loads that is easier to combine into a
2082 /// paired load.
2083 /// For instance, something like this:
2084 /// a = load i64* addr
2085 /// b = trunc i64 a to i32
2086 /// c = lshr i64 a, 32
2087 /// d = trunc i64 c to i32
2088 /// will be optimized into:
2089 /// b = load i32* addr1
2090 /// d = load i32* addr2
2091 /// Where addr1 = addr2 +/- sizeof(i32).
2092 ///
2093 /// In other words, unless the target performs a post-isel load combining,
2094 /// this information should not be provided because it will generate more
2095 /// loads.
2096 virtual bool hasPairedLoad(EVT /*LoadedType*/,
2097 unsigned & /*RequiredAlignment*/) const {
2098 return false;
2099 }
2100
2101 /// \brief Get the maximum supported factor for interleaved memory accesses.
2102 /// Default to be the minimum interleave factor: 2.
2103 virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
2104
2105 /// \brief Lower an interleaved load to target specific intrinsics. Return
2106 /// true on success.
2107 ///
2108 /// \p LI is the vector load instruction.
2109 /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
2110 /// \p Indices is the corresponding indices for each shufflevector.
2111 /// \p Factor is the interleave factor.
2112 virtual bool lowerInterleavedLoad(LoadInst *LI,
2113 ArrayRef<ShuffleVectorInst *> Shuffles,
2114 ArrayRef<unsigned> Indices,
2115 unsigned Factor) const {
2116 return false;
2117 }
2118
2119 /// \brief Lower an interleaved store to target specific intrinsics. Return
2120 /// true on success.
2121 ///
2122 /// \p SI is the vector store instruction.
2123 /// \p SVI is the shufflevector to RE-interleave the stored vector.
2124 /// \p Factor is the interleave factor.
2125 virtual bool lowerInterleavedStore(StoreInst *SI, ShuffleVectorInst *SVI,
2126 unsigned Factor) const {
2127 return false;
2128 }
2129
2130 /// Return true if zero-extending the specific node Val to type VT2 is free
2131 /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
2132 /// because it's folded such as X86 zero-extending loads).
2133 virtual bool isZExtFree(SDValue Val, EVT VT2) const {
2134 return isZExtFree(Val.getValueType(), VT2);
2135 }
2136
2137 /// Return true if an fpext operation is free (for instance, because
2138 /// single-precision floating-point numbers are implicitly extended to
2139 /// double-precision).
2140 virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const {
2141 assert(SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() &&(static_cast <bool> (SrcVT.isFloatingPoint() &&
DestVT.isFloatingPoint() && "invalid fpext types") ?
void (0) : __assert_fail ("SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() && \"invalid fpext types\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 2142, __extension__ __PRETTY_FUNCTION__))
2142 "invalid fpext types")(static_cast <bool> (SrcVT.isFloatingPoint() &&
DestVT.isFloatingPoint() && "invalid fpext types") ?
void (0) : __assert_fail ("SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() && \"invalid fpext types\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 2142, __extension__ __PRETTY_FUNCTION__))
;
2143 return false;
2144 }
2145
2146 /// Return true if an fpext operation input to an \p Opcode operation is free
2147 /// (for instance, because half-precision floating-point numbers are
2148 /// implicitly extended to float-precision) for an FMA instruction.
2149 virtual bool isFPExtFoldable(unsigned Opcode, EVT DestVT, EVT SrcVT) const {
2150 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&(static_cast <bool> (DestVT.isFloatingPoint() &&
SrcVT.isFloatingPoint() && "invalid fpext types") ? void
(0) : __assert_fail ("DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && \"invalid fpext types\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 2151, __extension__ __PRETTY_FUNCTION__))
2151 "invalid fpext types")(static_cast <bool> (DestVT.isFloatingPoint() &&
SrcVT.isFloatingPoint() && "invalid fpext types") ? void
(0) : __assert_fail ("DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && \"invalid fpext types\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 2151, __extension__ __PRETTY_FUNCTION__))
;
2152 return isFPExtFree(DestVT, SrcVT);
2153 }
2154
2155 /// Return true if folding a vector load into ExtVal (a sign, zero, or any
2156 /// extend node) is profitable.
2157 virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
2158
2159 /// Return true if an fneg operation is free to the point where it is never
2160 /// worthwhile to replace it with a bitwise operation.
2161 virtual bool isFNegFree(EVT VT) const {
2162 assert(VT.isFloatingPoint())(static_cast <bool> (VT.isFloatingPoint()) ? void (0) :
__assert_fail ("VT.isFloatingPoint()", "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 2162, __extension__ __PRETTY_FUNCTION__))
;
2163 return false;
2164 }
2165
2166 /// Return true if an fabs operation is free to the point where it is never
2167 /// worthwhile to replace it with a bitwise operation.
2168 virtual bool isFAbsFree(EVT VT) const {
2169 assert(VT.isFloatingPoint())(static_cast <bool> (VT.isFloatingPoint()) ? void (0) :
__assert_fail ("VT.isFloatingPoint()", "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 2169, __extension__ __PRETTY_FUNCTION__))
;
2170 return false;
2171 }
2172
2173 /// Return true if an FMA operation is faster than a pair of fmul and fadd
2174 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
2175 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
2176 ///
2177 /// NOTE: This may be called before legalization on types for which FMAs are
2178 /// not legal, but should return true if those types will eventually legalize
2179 /// to types that support FMAs. After legalization, it will only be called on
2180 /// types that support FMAs (via Legal or Custom actions)
2181 virtual bool isFMAFasterThanFMulAndFAdd(EVT) const {
2182 return false;
2183 }
2184
2185 /// Return true if it's profitable to narrow operations of type VT1 to
2186 /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
2187 /// i32 to i16.
2188 virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
2189 return false;
2190 }
2191
2192 /// \brief Return true if it is beneficial to convert a load of a constant to
2193 /// just the constant itself.
2194 /// On some targets it might be more efficient to use a combination of
2195 /// arithmetic instructions to materialize the constant instead of loading it
2196 /// from a constant pool.
2197 virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
2198 Type *Ty) const {
2199 return false;
2200 }
2201
2202 /// Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type
2203 /// from this source type with this index. This is needed because
2204 /// EXTRACT_SUBVECTOR usually has custom lowering that depends on the index of
2205 /// the first element, and only the target knows which lowering is cheap.
2206 virtual bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
2207 unsigned Index) const {
2208 return false;
2209 }
2210
2211 // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
2212 // even if the vector itself has multiple uses.
2213 virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
2214 return false;
2215 }
2216
2217 //===--------------------------------------------------------------------===//
2218 // Runtime Library hooks
2219 //
2220
2221 /// Rename the default libcall routine name for the specified libcall.
2222 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
2223 LibcallRoutineNames[Call] = Name;
2224 }
2225
2226 /// Get the libcall routine name for the specified libcall.
2227 const char *getLibcallName(RTLIB::Libcall Call) const {
2228 return LibcallRoutineNames[Call];
2229 }
2230
2231 /// Override the default CondCode to be used to test the result of the
2232 /// comparison libcall against zero.
2233 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
2234 CmpLibcallCCs[Call] = CC;
2235 }
2236
2237 /// Get the CondCode that's to be used to test the result of the comparison
2238 /// libcall against zero.
2239 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
2240 return CmpLibcallCCs[Call];
2241 }
2242
2243 /// Set the CallingConv that should be used for the specified libcall.
2244 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
2245 LibcallCallingConvs[Call] = CC;
2246 }
2247
2248 /// Get the CallingConv that should be used for the specified libcall.
2249 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
2250 return LibcallCallingConvs[Call];
2251 }
2252
2253 /// Execute target specific actions to finalize target lowering.
2254 /// This is used to set extra flags in MachineFrameInformation and freezing
2255 /// the set of reserved registers.
2256 /// The default implementation just freezes the set of reserved registers.
2257 virtual void finalizeLowering(MachineFunction &MF) const;
2258
2259private:
2260 const TargetMachine &TM;
2261
2262 /// Tells the code generator that the target has multiple (allocatable)
2263 /// condition registers that can be used to store the results of comparisons
2264 /// for use by selects and conditional branches. With multiple condition
2265 /// registers, the code generator will not aggressively sink comparisons into
2266 /// the blocks of their users.
2267 bool HasMultipleConditionRegisters;
2268
2269 /// Tells the code generator that the target has BitExtract instructions.
2270 /// The code generator will aggressively sink "shift"s into the blocks of
2271 /// their users if the users will generate "and" instructions which can be
2272 /// combined with "shift" to BitExtract instructions.
2273 bool HasExtractBitsInsn;
2274
2275 /// Tells the code generator to bypass slow divide or remainder
2276 /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
2277 /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
2278 /// div/rem when the operands are positive and less than 256.
2279 DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
2280
2281 /// Tells the code generator that it shouldn't generate extra flow control
2282 /// instructions and should attempt to combine flow control instructions via
2283 /// predication.
2284 bool JumpIsExpensive;
2285
2286 /// Whether the target supports or cares about preserving floating point
2287 /// exception behavior.
2288 bool HasFloatingPointExceptions;
2289
2290 /// This target prefers to use _setjmp to implement llvm.setjmp.
2291 ///
2292 /// Defaults to false.
2293 bool UseUnderscoreSetJmp;
2294
2295 /// This target prefers to use _longjmp to implement llvm.longjmp.
2296 ///
2297 /// Defaults to false.
2298 bool UseUnderscoreLongJmp;
2299
2300 /// Information about the contents of the high-bits in boolean values held in
2301 /// a type wider than i1. See getBooleanContents.
2302 BooleanContent BooleanContents;
2303
2304 /// Information about the contents of the high-bits in boolean values held in
2305 /// a type wider than i1. See getBooleanContents.
2306 BooleanContent BooleanFloatContents;
2307
2308 /// Information about the contents of the high-bits in boolean vector values
2309 /// when the element type is wider than i1. See getBooleanContents.
2310 BooleanContent BooleanVectorContents;
2311
2312 /// The target scheduling preference: shortest possible total cycles or lowest
2313 /// register usage.
2314 Sched::Preference SchedPreferenceInfo;
2315
2316 /// The size, in bytes, of the target's jmp_buf buffers
2317 unsigned JumpBufSize;
2318
2319 /// The alignment, in bytes, of the target's jmp_buf buffers
2320 unsigned JumpBufAlignment;
2321
2322 /// The minimum alignment that any argument on the stack needs to have.
2323 unsigned MinStackArgumentAlignment;
2324
2325 /// The minimum function alignment (used when optimizing for size, and to
2326 /// prevent explicitly provided alignment from leading to incorrect code).
2327 unsigned MinFunctionAlignment;
2328
2329 /// The preferred function alignment (used when alignment unspecified and
2330 /// optimizing for speed).
2331 unsigned PrefFunctionAlignment;
2332
2333 /// The preferred loop alignment.
2334 unsigned PrefLoopAlignment;
2335
2336 /// Size in bits of the maximum atomics size the backend supports.
2337 /// Accesses larger than this will be expanded by AtomicExpandPass.
2338 unsigned MaxAtomicSizeInBitsSupported;
2339
2340 /// Size in bits of the minimum cmpxchg or ll/sc operation the
2341 /// backend supports.
2342 unsigned MinCmpXchgSizeInBits;
2343
2344 /// This indicates if the target supports unaligned atomic operations.
2345 bool SupportsUnalignedAtomics;
2346
2347 /// If set to a physical register, this specifies the register that
2348 /// llvm.savestack/llvm.restorestack should save and restore.
2349 unsigned StackPointerRegisterToSaveRestore;
2350
2351 /// This indicates the default register class to use for each ValueType the
2352 /// target supports natively.
2353 const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
2354 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
2355 MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
2356
2357 /// This indicates the "representative" register class to use for each
2358 /// ValueType the target supports natively. This information is used by the
2359 /// scheduler to track register pressure. By default, the representative
2360 /// register class is the largest legal super-reg register class of the
2361 /// register class of the specified type. e.g. On x86, i8, i16, and i32's
2362 /// representative class would be GR32.
2363 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
2364
2365 /// This indicates the "cost" of the "representative" register class for each
2366 /// ValueType. The cost is used by the scheduler to approximate register
2367 /// pressure.
2368 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
2369
2370 /// For any value types we are promoting or expanding, this contains the value
2371 /// type that we are changing to. For Expanded types, this contains one step
2372 /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
2373 /// (e.g. i64 -> i16). For types natively supported by the system, this holds
2374 /// the same type (e.g. i32 -> i32).
2375 MVT TransformToType[MVT::LAST_VALUETYPE];
2376
2377 /// For each operation and each value type, keep a LegalizeAction that
2378 /// indicates how instruction selection should deal with the operation. Most
2379 /// operations are Legal (aka, supported natively by the target), but
2380 /// operations that are not should be described. Note that operations on
2381 /// non-legal value types are not described here.
2382 LegalizeAction OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
2383
2384 /// For each load extension type and each value type, keep a LegalizeAction
2385 /// that indicates how instruction selection should deal with a load of a
2386 /// specific value type and extension type. Uses 4-bits to store the action
2387 /// for each of the 4 load ext types.
2388 uint16_t LoadExtActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2389
2390 /// For each value type pair keep a LegalizeAction that indicates whether a
2391 /// truncating store of a specific value type and truncating type is legal.
2392 LegalizeAction TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2393
2394 /// For each indexed mode and each value type, keep a pair of LegalizeAction
2395 /// that indicates how instruction selection should deal with the load /
2396 /// store.
2397 ///
2398 /// The first dimension is the value_type for the reference. The second
2399 /// dimension represents the various modes for load store.
2400 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
2401
2402 /// For each condition code (ISD::CondCode) keep a LegalizeAction that
2403 /// indicates how instruction selection should deal with the condition code.
2404 ///
2405 /// Because each CC action takes up 4 bits, we need to have the array size be
2406 /// large enough to fit all of the value types. This can be done by rounding
2407 /// up the MVT::LAST_VALUETYPE value to the next multiple of 8.
2408 uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE + 7) / 8];
2409
2410protected:
2411 ValueTypeActionImpl ValueTypeActions;
2412
2413private:
2414 LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
2415
2416 /// Targets can specify ISD nodes that they would like PerformDAGCombine
2417 /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
2418 /// array.
2419 unsigned char
2420 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT8-1)/CHAR_BIT8];
2421
2422 /// For operations that must be promoted to a specific type, this holds the
2423 /// destination type. This map should be sparse, so don't hold it as an
2424 /// array.
2425 ///
2426 /// Targets add entries to this map with AddPromotedToType(..), clients access
2427 /// this with getTypeToPromoteTo(..).
2428 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
2429 PromoteToType;
2430
2431 /// Stores the name each libcall.
2432 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL + 1];
2433
2434 /// The ISD::CondCode that should be used to test the result of each of the
2435 /// comparison libcall against zero.
2436 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
2437
2438 /// Stores the CallingConv that should be used for each libcall.
2439 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
2440
2441 /// Set default libcall names and calling conventions.
2442 void InitLibcalls(const Triple &TT);
2443
2444protected:
2445 /// Return true if the extension represented by \p I is free.
2446 /// \pre \p I is a sign, zero, or fp extension and
2447 /// is[Z|FP]ExtFree of the related types is not true.
2448 virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
2449
2450 /// Depth that GatherAllAliases should should continue looking for chain
2451 /// dependencies when trying to find a more preferable chain. As an
2452 /// approximation, this should be more than the number of consecutive stores
2453 /// expected to be merged.
2454 unsigned GatherAllAliasesMaxDepth;
2455
2456 /// \brief Specify maximum number of store instructions per memset call.
2457 ///
2458 /// When lowering \@llvm.memset this field specifies the maximum number of
2459 /// store operations that may be substituted for the call to memset. Targets
2460 /// must set this value based on the cost threshold for that target. Targets
2461 /// should assume that the memset will be done using as many of the largest
2462 /// store operations first, followed by smaller ones, if necessary, per
2463 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
2464 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
2465 /// store. This only applies to setting a constant array of a constant size.
2466 unsigned MaxStoresPerMemset;
2467
2468 /// Maximum number of stores operations that may be substituted for the call
2469 /// to memset, used for functions with OptSize attribute.
2470 unsigned MaxStoresPerMemsetOptSize;
2471
2472 /// \brief Specify maximum bytes of store instructions per memcpy call.
2473 ///
2474 /// When lowering \@llvm.memcpy this field specifies the maximum number of
2475 /// store operations that may be substituted for a call to memcpy. Targets
2476 /// must set this value based on the cost threshold for that target. Targets
2477 /// should assume that the memcpy will be done using as many of the largest
2478 /// store operations first, followed by smaller ones, if necessary, per
2479 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
2480 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
2481 /// and one 1-byte store. This only applies to copying a constant array of
2482 /// constant size.
2483 unsigned MaxStoresPerMemcpy;
2484
2485 /// Maximum number of store operations that may be substituted for a call to
2486 /// memcpy, used for functions with OptSize attribute.
2487 unsigned MaxStoresPerMemcpyOptSize;
2488 unsigned MaxLoadsPerMemcmp;
2489 unsigned MaxLoadsPerMemcmpOptSize;
2490
2491 /// \brief Specify maximum bytes of store instructions per memmove call.
2492 ///
2493 /// When lowering \@llvm.memmove this field specifies the maximum number of
2494 /// store instructions that may be substituted for a call to memmove. Targets
2495 /// must set this value based on the cost threshold for that target. Targets
2496 /// should assume that the memmove will be done using as many of the largest
2497 /// store operations first, followed by smaller ones, if necessary, per
2498 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
2499 /// with 8-bit alignment would result in nine 1-byte stores. This only
2500 /// applies to copying a constant array of constant size.
2501 unsigned MaxStoresPerMemmove;
2502
2503 /// Maximum number of store instructions that may be substituted for a call to
2504 /// memmove, used for functions with OptSize attribute.
2505 unsigned MaxStoresPerMemmoveOptSize;
2506
2507 /// Tells the code generator that select is more expensive than a branch if
2508 /// the branch is usually predicted right.
2509 bool PredictableSelectIsExpensive;
2510
2511 /// \see enableExtLdPromotion.
2512 bool EnableExtLdPromotion;
2513
2514 /// Return true if the value types that can be represented by the specified
2515 /// register class are all legal.
2516 bool isLegalRC(const TargetRegisterInfo &TRI,
2517 const TargetRegisterClass &RC) const;
2518
2519 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
2520 /// sequence of memory operands that is recognized by PrologEpilogInserter.
2521 MachineBasicBlock *emitPatchPoint(MachineInstr &MI,
2522 MachineBasicBlock *MBB) const;
2523};
2524
2525/// This class defines information used to lower LLVM code to legal SelectionDAG
2526/// operators that the target instruction selector can accept natively.
2527///
2528/// This class also defines callbacks that targets must implement to lower
2529/// target-specific constructs to SelectionDAG operators.
2530class TargetLowering : public TargetLoweringBase {
2531public:
2532 struct DAGCombinerInfo;
2533
2534 TargetLowering(const TargetLowering &) = delete;
2535 TargetLowering &operator=(const TargetLowering &) = delete;
2536
2537 /// NOTE: The TargetMachine owns TLOF.
2538 explicit TargetLowering(const TargetMachine &TM);
2539
2540 bool isPositionIndependent() const;
2541
2542 /// Returns true by value, base pointer and offset pointer and addressing mode
2543 /// by reference if the node's address can be legally represented as
2544 /// pre-indexed load / store address.
2545 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
2546 SDValue &/*Offset*/,
2547 ISD::MemIndexedMode &/*AM*/,
2548 SelectionDAG &/*DAG*/) const {
2549 return false;
2550 }
2551
2552 /// Returns true by value, base pointer and offset pointer and addressing mode
2553 /// by reference if this node can be combined with a load / store to form a
2554 /// post-indexed load / store.
2555 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
2556 SDValue &/*Base*/,
2557 SDValue &/*Offset*/,
2558 ISD::MemIndexedMode &/*AM*/,
2559 SelectionDAG &/*DAG*/) const {
2560 return false;
2561 }
2562
2563 /// Return the entry encoding for a jump table in the current function. The
2564 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
2565 virtual unsigned getJumpTableEncoding() const;
2566
2567 virtual const MCExpr *
2568 LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
2569 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
2570 MCContext &/*Ctx*/) const {
2571 llvm_unreachable("Need to implement this hook if target has custom JTIs")::llvm::llvm_unreachable_internal("Need to implement this hook if target has custom JTIs"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 2571)
;
2572 }
2573
2574 /// Returns relocation base for the given PIC jumptable.
2575 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
2576 SelectionDAG &DAG) const;
2577
2578 /// This returns the relocation base for the given PIC jumptable, the same as
2579 /// getPICJumpTableRelocBase, but as an MCExpr.
2580 virtual const MCExpr *
2581 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2582 unsigned JTI, MCContext &Ctx) const;
2583
2584 /// Return true if folding a constant offset with the given GlobalAddress is
2585 /// legal. It is frequently not legal in PIC relocation models.
2586 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
2587
2588 bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
2589 SDValue &Chain) const;
2590
2591 void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
2592 SDValue &NewRHS, ISD::CondCode &CCCode,
2593 const SDLoc &DL) const;
2594
2595 /// Returns a pair of (return value, chain).
2596 /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
2597 std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
2598 EVT RetVT, ArrayRef<SDValue> Ops,
2599 bool isSigned, const SDLoc &dl,
2600 bool doesNotReturn = false,
2601 bool isReturnValueUsed = true) const;
2602
2603 /// Check whether parameters to a call that are passed in callee saved
2604 /// registers are the same as from the calling function. This needs to be
2605 /// checked for tail call eligibility.
2606 bool parametersInCSRMatch(const MachineRegisterInfo &MRI,
2607 const uint32_t *CallerPreservedMask,
2608 const SmallVectorImpl<CCValAssign> &ArgLocs,
2609 const SmallVectorImpl<SDValue> &OutVals) const;
2610
2611 //===--------------------------------------------------------------------===//
2612 // TargetLowering Optimization Methods
2613 //
2614
2615 /// A convenience struct that encapsulates a DAG, and two SDValues for
2616 /// returning information from TargetLowering to its clients that want to
2617 /// combine.
2618 struct TargetLoweringOpt {
2619 SelectionDAG &DAG;
2620 bool LegalTys;
2621 bool LegalOps;
2622 SDValue Old;
2623 SDValue New;
2624
2625 explicit TargetLoweringOpt(SelectionDAG &InDAG,
2626 bool LT, bool LO) :
2627 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
2628
2629 bool LegalTypes() const { return LegalTys; }
2630 bool LegalOperations() const { return LegalOps; }
2631
2632 bool CombineTo(SDValue O, SDValue N) {
2633 Old = O;
2634 New = N;
2635 return true;
2636 }
2637 };
2638
2639 /// Check to see if the specified operand of the specified instruction is a
2640 /// constant integer. If so, check to see if there are any bits set in the
2641 /// constant that are not demanded. If so, shrink the constant and return
2642 /// true.
2643 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
2644 TargetLoweringOpt &TLO) const;
2645
2646 // Target hook to do target-specific const optimization, which is called by
2647 // ShrinkDemandedConstant. This function should return true if the target
2648 // doesn't want ShrinkDemandedConstant to further optimize the constant.
2649 virtual bool targetShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
2650 TargetLoweringOpt &TLO) const {
2651 return false;
2652 }
2653
2654 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
2655 /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
2656 /// generalized for targets with other types of implicit widening casts.
2657 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
2658 TargetLoweringOpt &TLO) const;
2659
2660 /// Helper for SimplifyDemandedBits that can simplify an operation with
2661 /// multiple uses. This function simplifies operand \p OpIdx of \p User and
2662 /// then updates \p User with the simplified version. No other uses of
2663 /// \p OpIdx are updated. If \p User is the only user of \p OpIdx, this
2664 /// function behaves exactly like function SimplifyDemandedBits declared
2665 /// below except that it also updates the DAG by calling
2666 /// DCI.CommitTargetLoweringOpt.
2667 bool SimplifyDemandedBits(SDNode *User, unsigned OpIdx, const APInt &Demanded,
2668 DAGCombinerInfo &DCI, TargetLoweringOpt &TLO) const;
2669
2670 /// Look at Op. At this point, we know that only the DemandedMask bits of the
2671 /// result of Op are ever used downstream. If we can use this information to
2672 /// simplify Op, create a new simplified DAG node and return true, returning
2673 /// the original and new nodes in Old and New. Otherwise, analyze the
2674 /// expression and return a mask of KnownOne and KnownZero bits for the
2675 /// expression (used to simplify the caller). The KnownZero/One bits may only
2676 /// be accurate for those bits in the DemandedMask.
2677 /// \p AssumeSingleUse When this parameter is true, this function will
2678 /// attempt to simplify \p Op even if there are multiple uses.
2679 /// Callers are responsible for correctly updating the DAG based on the
2680 /// results of this function, because simply replacing replacing TLO.Old
2681 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
2682 /// has multiple uses.
2683 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
2684 KnownBits &Known,
2685 TargetLoweringOpt &TLO,
2686 unsigned Depth = 0,
2687 bool AssumeSingleUse = false) const;
2688
2689 /// Helper wrapper around SimplifyDemandedBits
2690 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
2691 DAGCombinerInfo &DCI) const;
2692
2693 /// Determine which of the bits specified in Mask are known to be either zero
2694 /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
2695 /// argument allows us to only collect the known bits that are shared by the
2696 /// requested vector elements.
2697 virtual void computeKnownBitsForTargetNode(const SDValue Op,
2698 KnownBits &Known,
2699 const APInt &DemandedElts,
2700 const SelectionDAG &DAG,
2701 unsigned Depth = 0) const;
2702
2703 /// Determine which of the bits of FrameIndex \p FIOp are known to be 0.
2704 /// Default implementation computes low bits based on alignment
2705 /// information. This should preserve known bits passed into it.
2706 virtual void computeKnownBitsForFrameIndex(const SDValue FIOp,
2707 KnownBits &Known,
2708 const APInt &DemandedElts,
2709 const SelectionDAG &DAG,
2710 unsigned Depth = 0) const;
2711
2712 /// This method can be implemented by targets that want to expose additional
2713 /// information about sign bits to the DAG Combiner. The DemandedElts
2714 /// argument allows us to only collect the minimum sign bits that are shared
2715 /// by the requested vector elements.
2716 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
2717 const APInt &DemandedElts,
2718 const SelectionDAG &DAG,
2719 unsigned Depth = 0) const;
2720
2721 struct DAGCombinerInfo {
2722 void *DC; // The DAG Combiner object.
2723 CombineLevel Level;
2724 bool CalledByLegalizer;
2725
2726 public:
2727 SelectionDAG &DAG;
2728
2729 DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
2730 : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
2731
2732 bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
2733 bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
2734 bool isAfterLegalizeVectorOps() const {
2735 return Level == AfterLegalizeDAG;
2736 }
2737 CombineLevel getDAGCombineLevel() { return Level; }
2738 bool isCalledByLegalizer() const { return CalledByLegalizer; }
2739
2740 void AddToWorklist(SDNode *N);
2741 SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo = true);
2742 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
2743 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
2744
2745 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
2746 };
2747
2748 /// Return if the N is a constant or constant vector equal to the true value
2749 /// from getBooleanContents().
2750 bool isConstTrueVal(const SDNode *N) const;
2751
2752 /// Return if the N is a constant or constant vector equal to the false value
2753 /// from getBooleanContents().
2754 bool isConstFalseVal(const SDNode *N) const;
2755
2756 /// Return a constant of type VT that contains a true value that respects
2757 /// getBooleanContents()
2758 SDValue getConstTrueVal(SelectionDAG &DAG, EVT VT, const SDLoc &DL) const;
2759
2760 /// Return if \p N is a True value when extended to \p VT.
2761 bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool Signed) const;
2762
2763 /// Try to simplify a setcc built with the specified operands and cc. If it is
2764 /// unable to simplify it, return a null SDValue.
2765 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
2766 bool foldBooleans, DAGCombinerInfo &DCI,
2767 const SDLoc &dl) const;
2768
2769 // For targets which wrap address, unwrap for analysis.
2770 virtual SDValue unwrapAddress(SDValue N) const { return N; }
2771
2772 /// Returns true (and the GlobalValue and the offset) if the node is a
2773 /// GlobalAddress + offset.
2774 virtual bool
2775 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
2776
2777 /// This method will be invoked for all target nodes and for any
2778 /// target-independent nodes that the target has registered with invoke it
2779 /// for.
2780 ///
2781 /// The semantics are as follows:
2782 /// Return Value:
2783 /// SDValue.Val == 0 - No change was made
2784 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
2785 /// otherwise - N should be replaced by the returned Operand.
2786 ///
2787 /// In addition, methods provided by DAGCombinerInfo may be used to perform
2788 /// more complex transformations.
2789 ///
2790 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
2791
2792 /// Return true if it is profitable to move a following shift through this
2793 // node, adjusting any immediate operands as necessary to preserve semantics.
2794 // This transformation may not be desirable if it disrupts a particularly
2795 // auspicious target-specific tree (e.g. bitfield extraction in AArch64).
2796 // By default, it returns true.
2797 virtual bool isDesirableToCommuteWithShift(const SDNode *N) const {
2798 return true;
2799 }
2800
2801 // Return true if it is profitable to combine a BUILD_VECTOR with a stride-pattern
2802 // to a shuffle and a truncate.
2803 // Example of such a combine:
2804 // v4i32 build_vector((extract_elt V, 1),
2805 // (extract_elt V, 3),
2806 // (extract_elt V, 5),
2807 // (extract_elt V, 7))
2808 // -->
2809 // v4i32 truncate (bitcast (shuffle<1,u,3,u,5,u,7,u> V, u) to v4i64)
2810 virtual bool isDesirableToCombineBuildVectorToShuffleTruncate(
2811 ArrayRef<int> ShuffleMask, EVT SrcVT, EVT TruncVT) const {
2812 return false;
2813 }
2814
2815 /// Return true if the target has native support for the specified value type
2816 /// and it is 'desirable' to use the type for the given node type. e.g. On x86
2817 /// i16 is legal, but undesirable since i16 instruction encodings are longer
2818 /// and some i16 instructions are slow.
2819 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
2820 // By default, assume all legal types are desirable.
2821 return isTypeLegal(VT);
2822 }
2823
2824 /// Return true if it is profitable for dag combiner to transform a floating
2825 /// point op of specified opcode to a equivalent op of an integer
2826 /// type. e.g. f32 load -> i32 load can be profitable on ARM.
2827 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
2828 EVT /*VT*/) const {
2829 return false;
2830 }
2831
2832 /// This method query the target whether it is beneficial for dag combiner to
2833 /// promote the specified node. If true, it should return the desired
2834 /// promotion type by reference.
2835 virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
2836 return false;
2837 }
2838
2839 /// Return true if the target supports swifterror attribute. It optimizes
2840 /// loads and stores to reading and writing a specific register.
2841 virtual bool supportSwiftError() const {
2842 return false;
2843 }
2844
2845 /// Return true if the target supports that a subset of CSRs for the given
2846 /// machine function is handled explicitly via copies.
2847 virtual bool supportSplitCSR(MachineFunction *MF) const {
2848 return false;
2849 }
2850
2851 /// Perform necessary initialization to handle a subset of CSRs explicitly
2852 /// via copies. This function is called at the beginning of instruction
2853 /// selection.
2854 virtual void initializeSplitCSR(MachineBasicBlock *Entry) const {
2855 llvm_unreachable("Not Implemented")::llvm::llvm_unreachable_internal("Not Implemented", "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 2855)
;
2856 }
2857
2858 /// Insert explicit copies in entry and exit blocks. We copy a subset of
2859 /// CSRs to virtual registers in the entry block, and copy them back to
2860 /// physical registers in the exit blocks. This function is called at the end
2861 /// of instruction selection.
2862 virtual void insertCopiesSplitCSR(
2863 MachineBasicBlock *Entry,
2864 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2865 llvm_unreachable("Not Implemented")::llvm::llvm_unreachable_internal("Not Implemented", "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 2865)
;
2866 }
2867
2868 //===--------------------------------------------------------------------===//
2869 // Lowering methods - These methods must be implemented by targets so that
2870 // the SelectionDAGBuilder code knows how to lower these.
2871 //
2872
2873 /// This hook must be implemented to lower the incoming (formal) arguments,
2874 /// described by the Ins array, into the specified DAG. The implementation
2875 /// should fill in the InVals array with legal-type argument values, and
2876 /// return the resulting token chain value.
2877 virtual SDValue LowerFormalArguments(
2878 SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
2879 const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
2880 SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
2881 llvm_unreachable("Not Implemented")::llvm::llvm_unreachable_internal("Not Implemented", "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 2881)
;
2882 }
2883
2884 /// This structure contains all information that is necessary for lowering
2885 /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
2886 /// needs to lower a call, and targets will see this struct in their LowerCall
2887 /// implementation.
2888 struct CallLoweringInfo {
2889 SDValue Chain;
2890 Type *RetTy = nullptr;
2891 bool RetSExt : 1;
2892 bool RetZExt : 1;
2893 bool IsVarArg : 1;
2894 bool IsInReg : 1;
2895 bool DoesNotReturn : 1;
2896 bool IsReturnValueUsed : 1;
2897 bool IsConvergent : 1;
2898 bool IsPatchPoint : 1;
2899
2900 // IsTailCall should be modified by implementations of
2901 // TargetLowering::LowerCall that perform tail call conversions.
2902 bool IsTailCall = false;
2903
2904 // Is Call lowering done post SelectionDAG type legalization.
2905 bool IsPostTypeLegalization = false;
2906
2907 unsigned NumFixedArgs = -1;
2908 CallingConv::ID CallConv = CallingConv::C;
2909 SDValue Callee;
2910 ArgListTy Args;
2911 SelectionDAG &DAG;
2912 SDLoc DL;
2913 ImmutableCallSite CS;
2914 SmallVector<ISD::OutputArg, 32> Outs;
2915 SmallVector<SDValue, 32> OutVals;
2916 SmallVector<ISD::InputArg, 32> Ins;
2917 SmallVector<SDValue, 4> InVals;
2918
2919 CallLoweringInfo(SelectionDAG &DAG)
2920 : RetSExt(false), RetZExt(false), IsVarArg(false), IsInReg(false),
2921 DoesNotReturn(false), IsReturnValueUsed(true), IsConvergent(false),
2922 IsPatchPoint(false), DAG(DAG) {}
2923
2924 CallLoweringInfo &setDebugLoc(const SDLoc &dl) {
2925 DL = dl;
2926 return *this;
2927 }
2928
2929 CallLoweringInfo &setChain(SDValue InChain) {
2930 Chain = InChain;
2931 return *this;
2932 }
2933
2934 // setCallee with target/module-specific attributes
2935 CallLoweringInfo &setLibCallee(CallingConv::ID CC, Type *ResultType,
2936 SDValue Target, ArgListTy &&ArgsList) {
2937 RetTy = ResultType;
2938 Callee = Target;
2939 CallConv = CC;
2940 NumFixedArgs = ArgsList.size();
2941 Args = std::move(ArgsList);
2942
2943 DAG.getTargetLoweringInfo().markLibCallAttributes(
2944 &(DAG.getMachineFunction()), CC, Args);
2945 return *this;
2946 }
2947
2948 CallLoweringInfo &setCallee(CallingConv::ID CC, Type *ResultType,
2949 SDValue Target, ArgListTy &&ArgsList) {
2950 RetTy = ResultType;
2951 Callee = Target;
2952 CallConv = CC;
2953 NumFixedArgs = ArgsList.size();
2954 Args = std::move(ArgsList);
2955 return *this;
2956 }
2957
2958 CallLoweringInfo &setCallee(Type *ResultType, FunctionType *FTy,
2959 SDValue Target, ArgListTy &&ArgsList,
2960 ImmutableCallSite Call) {
2961 RetTy = ResultType;
2962
2963 IsInReg = Call.hasRetAttr(Attribute::InReg);
2964 DoesNotReturn =
2965 Call.doesNotReturn() ||
2966 (!Call.isInvoke() &&
2967 isa<UnreachableInst>(Call.getInstruction()->getNextNode()));
2968 IsVarArg = FTy->isVarArg();
2969 IsReturnValueUsed = !Call.getInstruction()->use_empty();
2970 RetSExt = Call.hasRetAttr(Attribute::SExt);
2971 RetZExt = Call.hasRetAttr(Attribute::ZExt);
2972
2973 Callee = Target;
2974
2975 CallConv = Call.getCallingConv();
2976 NumFixedArgs = FTy->getNumParams();
2977 Args = std::move(ArgsList);
2978
2979 CS = Call;
2980
2981 return *this;
2982 }
2983
2984 CallLoweringInfo &setInRegister(bool Value = true) {
2985 IsInReg = Value;
2986 return *this;
2987 }
2988
2989 CallLoweringInfo &setNoReturn(bool Value = true) {
2990 DoesNotReturn = Value;
2991 return *this;
2992 }
2993
2994 CallLoweringInfo &setVarArg(bool Value = true) {
2995 IsVarArg = Value;
2996 return *this;
2997 }
2998
2999 CallLoweringInfo &setTailCall(bool Value = true) {
3000 IsTailCall = Value;
3001 return *this;
3002 }
3003
3004 CallLoweringInfo &setDiscardResult(bool Value = true) {
3005 IsReturnValueUsed = !Value;
3006 return *this;
3007 }
3008
3009 CallLoweringInfo &setConvergent(bool Value = true) {
3010 IsConvergent = Value;
3011 return *this;
3012 }
3013
3014 CallLoweringInfo &setSExtResult(bool Value = true) {
3015 RetSExt = Value;
3016 return *this;
3017 }
3018
3019 CallLoweringInfo &setZExtResult(bool Value = true) {
3020 RetZExt = Value;
3021 return *this;
3022 }
3023
3024 CallLoweringInfo &setIsPatchPoint(bool Value = true) {
3025 IsPatchPoint = Value;
3026 return *this;
3027 }
3028
3029 CallLoweringInfo &setIsPostTypeLegalization(bool Value=true) {
3030 IsPostTypeLegalization = Value;
3031 return *this;
3032 }
3033
3034 ArgListTy &getArgs() {
3035 return Args;
3036 }
3037 };
3038
3039 /// This function lowers an abstract call to a function into an actual call.
3040 /// This returns a pair of operands. The first element is the return value
3041 /// for the function (if RetTy is not VoidTy). The second element is the
3042 /// outgoing token chain. It calls LowerCall to do the actual lowering.
3043 std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
3044
3045 /// This hook must be implemented to lower calls into the specified
3046 /// DAG. The outgoing arguments to the call are described by the Outs array,
3047 /// and the values to be returned by the call are described by the Ins
3048 /// array. The implementation should fill in the InVals array with legal-type
3049 /// return values from the call, and return the resulting token chain value.
3050 virtual SDValue
3051 LowerCall(CallLoweringInfo &/*CLI*/,
3052 SmallVectorImpl<SDValue> &/*InVals*/) const {
3053 llvm_unreachable("Not Implemented")::llvm::llvm_unreachable_internal("Not Implemented", "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 3053)
;
3054 }
3055
3056 /// Target-specific cleanup for formal ByVal parameters.
3057 virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
3058
3059 /// This hook should be implemented to check whether the return values
3060 /// described by the Outs array can fit into the return registers. If false
3061 /// is returned, an sret-demotion is performed.
3062 virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
3063 MachineFunction &/*MF*/, bool /*isVarArg*/,
3064 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
3065 LLVMContext &/*Context*/) const
3066 {
3067 // Return true by default to get preexisting behavior.
3068 return true;
3069 }
3070
3071 /// This hook must be implemented to lower outgoing return values, described
3072 /// by the Outs array, into the specified DAG. The implementation should
3073 /// return the resulting token chain value.
3074 virtual SDValue LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
3075 bool /*isVarArg*/,
3076 const SmallVectorImpl<ISD::OutputArg> & /*Outs*/,
3077 const SmallVectorImpl<SDValue> & /*OutVals*/,
3078 const SDLoc & /*dl*/,
3079 SelectionDAG & /*DAG*/) const {
3080 llvm_unreachable("Not Implemented")::llvm::llvm_unreachable_internal("Not Implemented", "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 3080)
;
3081 }
3082
3083 /// Return true if result of the specified node is used by a return node
3084 /// only. It also compute and return the input chain for the tail call.
3085 ///
3086 /// This is used to determine whether it is possible to codegen a libcall as
3087 /// tail call at legalization time.
3088 virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
3089 return false;
3090 }
3091
3092 /// Return true if the target may be able emit the call instruction as a tail
3093 /// call. This is used by optimization passes to determine if it's profitable
3094 /// to duplicate return instructions to enable tailcall optimization.
3095 virtual bool mayBeEmittedAsTailCall(const CallInst *) const {
3096 return false;
3097 }
3098
3099 /// Return the builtin name for the __builtin___clear_cache intrinsic
3100 /// Default is to invoke the clear cache library call
3101 virtual const char * getClearCacheBuiltinName() const {
3102 return "__clear_cache";
3103 }
3104
3105 /// Return the register ID of the name passed in. Used by named register
3106 /// global variables extension. There is no target-independent behaviour
3107 /// so the default action is to bail.
3108 virtual unsigned getRegisterByName(const char* RegName, EVT VT,
3109 SelectionDAG &DAG) const {
3110 report_fatal_error("Named registers not implemented for this target");
3111 }
3112
3113 /// Return the type that should be used to zero or sign extend a
3114 /// zeroext/signext integer return value. FIXME: Some C calling conventions
3115 /// require the return type to be promoted, but this is not true all the time,
3116 /// e.g. i1/i8/i16 on x86/x86_64. It is also not necessary for non-C calling
3117 /// conventions. The frontend should handle this and include all of the
3118 /// necessary information.
3119 virtual EVT getTypeForExtReturn(LLVMContext &Context, EVT VT,
3120 ISD::NodeType /*ExtendKind*/) const {
3121 EVT MinVT = getRegisterType(Context, MVT::i32);
3122 return VT.bitsLT(MinVT) ? MinVT : VT;
3123 }
3124
3125 /// For some targets, an LLVM struct type must be broken down into multiple
3126 /// simple types, but the calling convention specifies that the entire struct
3127 /// must be passed in a block of consecutive registers.
3128 virtual bool
3129 functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv,
3130 bool isVarArg) const {
3131 return false;
3132 }
3133
3134 /// Returns a 0 terminated array of registers that can be safely used as
3135 /// scratch registers.
3136 virtual const MCPhysReg *getScratchRegisters(CallingConv::ID CC) const {
3137 return nullptr;
3138 }
3139
3140 /// This callback is used to prepare for a volatile or atomic load.
3141 /// It takes a chain node as input and returns the chain for the load itself.
3142 ///
3143 /// Having a callback like this is necessary for targets like SystemZ,
3144 /// which allows a CPU to reuse the result of a previous load indefinitely,
3145 /// even if a cache-coherent store is performed by another CPU. The default
3146 /// implementation does nothing.
3147 virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, const SDLoc &DL,
3148 SelectionDAG &DAG) const {
3149 return Chain;
3150 }
3151
3152 /// This callback is used to inspect load/store instructions and add
3153 /// target-specific MachineMemOperand flags to them. The default
3154 /// implementation does nothing.
3155 virtual MachineMemOperand::Flags getMMOFlags(const Instruction &I) const {
3156 return MachineMemOperand::MONone;
3157 }
3158
3159 /// This callback is invoked by the type legalizer to legalize nodes with an
3160 /// illegal operand type but legal result types. It replaces the
3161 /// LowerOperation callback in the type Legalizer. The reason we can not do
3162 /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
3163 /// use this callback.
3164 ///
3165 /// TODO: Consider merging with ReplaceNodeResults.
3166 ///
3167 /// The target places new result values for the node in Results (their number
3168 /// and types must exactly match those of the original return values of
3169 /// the node), or leaves Results empty, which indicates that the node is not
3170 /// to be custom lowered after all.
3171 /// The default implementation calls LowerOperation.
3172 virtual void LowerOperationWrapper(SDNode *N,
3173 SmallVectorImpl<SDValue> &Results,
3174 SelectionDAG &DAG) const;
3175
3176 /// This callback is invoked for operations that are unsupported by the
3177 /// target, which are registered to use 'custom' lowering, and whose defined
3178 /// values are all legal. If the target has no operations that require custom
3179 /// lowering, it need not implement this. The default implementation of this
3180 /// aborts.
3181 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
3182
3183 /// This callback is invoked when a node result type is illegal for the
3184 /// target, and the operation was registered to use 'custom' lowering for that
3185 /// result type. The target places new result values for the node in Results
3186 /// (their number and types must exactly match those of the original return
3187 /// values of the node), or leaves Results empty, which indicates that the
3188 /// node is not to be custom lowered after all.
3189 ///
3190 /// If the target has no operations that require custom lowering, it need not
3191 /// implement this. The default implementation aborts.
3192 virtual void ReplaceNodeResults(SDNode * /*N*/,
3193 SmallVectorImpl<SDValue> &/*Results*/,
3194 SelectionDAG &/*DAG*/) const {
3195 llvm_unreachable("ReplaceNodeResults not implemented for this target!")::llvm::llvm_unreachable_internal("ReplaceNodeResults not implemented for this target!"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 3195)
;
3196 }
3197
3198 /// This method returns the name of a target specific DAG node.
3199 virtual const char *getTargetNodeName(unsigned Opcode) const;
3200
3201 /// This method returns a target specific FastISel object, or null if the
3202 /// target does not support "fast" ISel.
3203 virtual FastISel *createFastISel(FunctionLoweringInfo &,
3204 const TargetLibraryInfo *) const {
3205 return nullptr;
3206 }
3207
3208 bool verifyReturnAddressArgumentIsConstant(SDValue Op,
3209 SelectionDAG &DAG) const;
3210
3211 //===--------------------------------------------------------------------===//
3212 // Inline Asm Support hooks
3213 //
3214
3215 /// This hook allows the target to expand an inline asm call to be explicit
3216 /// llvm code if it wants to. This is useful for turning simple inline asms
3217 /// into LLVM intrinsics, which gives the compiler more information about the
3218 /// behavior of the code.
3219 virtual bool ExpandInlineAsm(CallInst *) const {
3220 return false;
3221 }
3222
3223 enum ConstraintType {
3224 C_Register, // Constraint represents specific register(s).
3225 C_RegisterClass, // Constraint represents any of register(s) in class.
3226 C_Memory, // Memory constraint.
3227 C_Other, // Something else.
3228 C_Unknown // Unsupported constraint.
3229 };
3230
3231 enum ConstraintWeight {
3232 // Generic weights.
3233 CW_Invalid = -1, // No match.
3234 CW_Okay = 0, // Acceptable.
3235 CW_Good = 1, // Good weight.
3236 CW_Better = 2, // Better weight.
3237 CW_Best = 3, // Best weight.
3238
3239 // Well-known weights.
3240 CW_SpecificReg = CW_Okay, // Specific register operands.
3241 CW_Register = CW_Good, // Register operands.
3242 CW_Memory = CW_Better, // Memory operands.
3243 CW_Constant = CW_Best, // Constant operand.
3244 CW_Default = CW_Okay // Default or don't know type.
3245 };
3246
3247 /// This contains information for each constraint that we are lowering.
3248 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
3249 /// This contains the actual string for the code, like "m". TargetLowering
3250 /// picks the 'best' code from ConstraintInfo::Codes that most closely
3251 /// matches the operand.
3252 std::string ConstraintCode;
3253
3254 /// Information about the constraint code, e.g. Register, RegisterClass,
3255 /// Memory, Other, Unknown.
3256 TargetLowering::ConstraintType ConstraintType = TargetLowering::C_Unknown;
3257
3258 /// If this is the result output operand or a clobber, this is null,
3259 /// otherwise it is the incoming operand to the CallInst. This gets
3260 /// modified as the asm is processed.
3261 Value *CallOperandVal = nullptr;
3262
3263 /// The ValueType for the operand value.
3264 MVT ConstraintVT = MVT::Other;
3265
3266 /// Copy constructor for copying from a ConstraintInfo.
3267 AsmOperandInfo(InlineAsm::ConstraintInfo Info)
3268 : InlineAsm::ConstraintInfo(std::move(Info)) {}
3269
3270 /// Return true of this is an input operand that is a matching constraint
3271 /// like "4".
3272 bool isMatchingInputConstraint() const;
3273
3274 /// If this is an input matching constraint, this method returns the output
3275 /// operand it matches.
3276 unsigned getMatchedOperand() const;
3277 };
3278
3279 using AsmOperandInfoVector = std::vector<AsmOperandInfo>;
3280
3281 /// Split up the constraint string from the inline assembly value into the
3282 /// specific constraints and their prefixes, and also tie in the associated
3283 /// operand values. If this returns an empty vector, and if the constraint
3284 /// string itself isn't empty, there was an error parsing.
3285 virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL,
3286 const TargetRegisterInfo *TRI,
3287 ImmutableCallSite CS) const;
3288
3289 /// Examine constraint type and operand type and determine a weight value.
3290 /// The operand object must already have been set up with the operand type.
3291 virtual ConstraintWeight getMultipleConstraintMatchWeight(
3292 AsmOperandInfo &info, int maIndex) const;
3293
3294 /// Examine constraint string and operand type and determine a weight value.
3295 /// The operand object must already have been set up with the operand type.
3296 virtual ConstraintWeight getSingleConstraintMatchWeight(
3297 AsmOperandInfo &info, const char *constraint) const;
3298
3299 /// Determines the constraint code and constraint type to use for the specific
3300 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
3301 /// If the actual operand being passed in is available, it can be passed in as
3302 /// Op, otherwise an empty SDValue can be passed.
3303 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
3304 SDValue Op,
3305 SelectionDAG *DAG = nullptr) const;
3306
3307 /// Given a constraint, return the type of constraint it is for this target.
3308 virtual ConstraintType getConstraintType(StringRef Constraint) const;
3309
3310 /// Given a physical register constraint (e.g. {edx}), return the register
3311 /// number and the register class for the register.
3312 ///
3313 /// Given a register class constraint, like 'r', if this corresponds directly
3314 /// to an LLVM register class, return a register of 0 and the register class
3315 /// pointer.
3316 ///
3317 /// This should only be used for C_Register constraints. On error, this
3318 /// returns a register number of 0 and a null register class pointer.
3319 virtual std::pair<unsigned, const TargetRegisterClass *>
3320 getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3321 StringRef Constraint, MVT VT) const;
3322
3323 virtual unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const {
3324 if (ConstraintCode == "i")
3325 return InlineAsm::Constraint_i;
3326 else if (ConstraintCode == "m")
3327 return InlineAsm::Constraint_m;
3328 return InlineAsm::Constraint_Unknown;
3329 }
3330
3331 /// Try to replace an X constraint, which matches anything, with another that
3332 /// has more specific requirements based on the type of the corresponding
3333 /// operand. This returns null if there is no replacement to make.
3334 virtual const char *LowerXConstraint(EVT ConstraintVT) const;
3335
3336 /// Lower the specified operand into the Ops vector. If it is invalid, don't
3337 /// add anything to Ops.
3338 virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
3339 std::vector<SDValue> &Ops,
3340 SelectionDAG &DAG) const;
3341
3342 //===--------------------------------------------------------------------===//
3343 // Div utility functions
3344 //
3345 SDValue BuildSDIV(SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
3346 bool IsAfterLegalization,
3347 std::vector<SDNode *> *Created) const;
3348 SDValue BuildUDIV(SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
3349 bool IsAfterLegalization,
3350 std::vector<SDNode *> *Created) const;
3351
3352 /// Targets may override this function to provide custom SDIV lowering for
3353 /// power-of-2 denominators. If the target returns an empty SDValue, LLVM
3354 /// assumes SDIV is expensive and replaces it with a series of other integer
3355 /// operations.
3356 virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor,
3357 SelectionDAG &DAG,
3358 std::vector<SDNode *> *Created) const;
3359
3360 /// Indicate whether this target prefers to combine FDIVs with the same
3361 /// divisor. If the transform should never be done, return zero. If the
3362 /// transform should be done, return the minimum number of divisor uses
3363 /// that must exist.
3364 virtual unsigned combineRepeatedFPDivisors() const {
3365 return 0;
3366 }
3367
3368 /// Hooks for building estimates in place of slower divisions and square
3369 /// roots.
3370
3371 /// Return either a square root or its reciprocal estimate value for the input
3372 /// operand.
3373 /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
3374 /// 'Enabled' as set by a potential default override attribute.
3375 /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
3376 /// refinement iterations required to generate a sufficient (though not
3377 /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
3378 /// The boolean UseOneConstNR output is used to select a Newton-Raphson
3379 /// algorithm implementation that uses either one or two constants.
3380 /// The boolean Reciprocal is used to select whether the estimate is for the
3381 /// square root of the input operand or the reciprocal of its square root.
3382 /// A target may choose to implement its own refinement within this function.
3383 /// If that's true, then return '0' as the number of RefinementSteps to avoid
3384 /// any further refinement of the estimate.
3385 /// An empty SDValue return means no estimate sequence can be created.
3386 virtual SDValue getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
3387 int Enabled, int &RefinementSteps,
3388 bool &UseOneConstNR, bool Reciprocal) const {
3389 return SDValue();
3390 }
3391
3392 /// Return a reciprocal estimate value for the input operand.
3393 /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
3394 /// 'Enabled' as set by a potential default override attribute.
3395 /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
3396 /// refinement iterations required to generate a sufficient (though not
3397 /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
3398 /// A target may choose to implement its own refinement within this function.
3399 /// If that's true, then return '0' as the number of RefinementSteps to avoid
3400 /// any further refinement of the estimate.
3401 /// An empty SDValue return means no estimate sequence can be created.
3402 virtual SDValue getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
3403 int Enabled, int &RefinementSteps) const {
3404 return SDValue();
3405 }
3406
3407 //===--------------------------------------------------------------------===//
3408 // Legalization utility functions
3409 //
3410
3411 /// Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes,
3412 /// respectively, each computing an n/2-bit part of the result.
3413 /// \param Result A vector that will be filled with the parts of the result
3414 /// in little-endian order.
3415 /// \param LL Low bits of the LHS of the MUL. You can use this parameter
3416 /// if you want to control how low bits are extracted from the LHS.
3417 /// \param LH High bits of the LHS of the MUL. See LL for meaning.
3418 /// \param RL Low bits of the RHS of the MUL. See LL for meaning
3419 /// \param RH High bits of the RHS of the MUL. See LL for meaning.
3420 /// \returns true if the node has been expanded, false if it has not
3421 bool expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl, SDValue LHS,
3422 SDValue RHS, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
3423 SelectionDAG &DAG, MulExpansionKind Kind,
3424 SDValue LL = SDValue(), SDValue LH = SDValue(),
3425 SDValue RL = SDValue(), SDValue RH = SDValue()) const;
3426
3427 /// Expand a MUL into two nodes. One that computes the high bits of
3428 /// the result and one that computes the low bits.
3429 /// \param HiLoVT The value type to use for the Lo and Hi nodes.
3430 /// \param LL Low bits of the LHS of the MUL. You can use this parameter
3431 /// if you want to control how low bits are extracted from the LHS.
3432 /// \param LH High bits of the LHS of the MUL. See LL for meaning.
3433 /// \param RL Low bits of the RHS of the MUL. See LL for meaning
3434 /// \param RH High bits of the RHS of the MUL. See LL for meaning.
3435 /// \returns true if the node has been expanded. false if it has not
3436 bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
3437 SelectionDAG &DAG, MulExpansionKind Kind,
3438 SDValue LL = SDValue(), SDValue LH = SDValue(),
3439 SDValue RL = SDValue(), SDValue RH = SDValue()) const;
3440
3441 /// Expand float(f32) to SINT(i64) conversion
3442 /// \param N Node to expand
3443 /// \param Result output after conversion
3444 /// \returns True, if the expansion was successful, false otherwise
3445 bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3446
3447 /// Turn load of vector type into a load of the individual elements.
3448 /// \param LD load to expand
3449 /// \returns MERGE_VALUEs of the scalar loads with their chains.
3450 SDValue scalarizeVectorLoad(LoadSDNode *LD, SelectionDAG &DAG) const;
3451
3452 // Turn a store of a vector type into stores of the individual elements.
3453 /// \param ST Store with a vector value type
3454 /// \returns MERGE_VALUs of the individual store chains.
3455 SDValue scalarizeVectorStore(StoreSDNode *ST, SelectionDAG &DAG) const;
3456
3457 /// Expands an unaligned load to 2 half-size loads for an integer, and
3458 /// possibly more for vectors.
3459 std::pair<SDValue, SDValue> expandUnalignedLoad(LoadSDNode *LD,
3460 SelectionDAG &DAG) const;
3461
3462 /// Expands an unaligned store to 2 half-size stores for integer values, and
3463 /// possibly more for vectors.
3464 SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const;
3465
3466 /// Increments memory address \p Addr according to the type of the value
3467 /// \p DataVT that should be stored. If the data is stored in compressed
3468 /// form, the memory address should be incremented according to the number of
3469 /// the stored elements. This number is equal to the number of '1's bits
3470 /// in the \p Mask.
3471 /// \p DataVT is a vector type. \p Mask is a vector value.
3472 /// \p DataVT and \p Mask have the same number of vector elements.
3473 SDValue IncrementMemoryAddress(SDValue Addr, SDValue Mask, const SDLoc &DL,
3474 EVT DataVT, SelectionDAG &DAG,
3475 bool IsCompressedMemory) const;
3476
3477 /// Get a pointer to vector element \p Idx located in memory for a vector of
3478 /// type \p VecVT starting at a base address of \p VecPtr. If \p Idx is out of
3479 /// bounds the returned pointer is unspecified, but will be within the vector
3480 /// bounds.
3481 SDValue getVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT,
3482 SDValue Idx) const;
3483
3484 //===--------------------------------------------------------------------===//
3485 // Instruction Emitting Hooks
3486 //
3487
3488 /// This method should be implemented by targets that mark instructions with
3489 /// the 'usesCustomInserter' flag. These instructions are special in various
3490 /// ways, which require special support to insert. The specified MachineInstr
3491 /// is created but not inserted into any basic blocks, and this method is
3492 /// called to expand it into a sequence of instructions, potentially also
3493 /// creating new basic blocks and control flow.
3494 /// As long as the returned basic block is different (i.e., we created a new
3495 /// one), the custom inserter is free to modify the rest of \p MBB.
3496 virtual MachineBasicBlock *
3497 EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const;
3498
3499 /// This method should be implemented by targets that mark instructions with
3500 /// the 'hasPostISelHook' flag. These instructions must be adjusted after
3501 /// instruction selection by target hooks. e.g. To fill in optional defs for
3502 /// ARM 's' setting instructions.
3503 virtual void AdjustInstrPostInstrSelection(MachineInstr &MI,
3504 SDNode *Node) const;
3505
3506 /// If this function returns true, SelectionDAGBuilder emits a
3507 /// LOAD_STACK_GUARD node when it is lowering Intrinsic::stackprotector.
3508 virtual bool useLoadStackGuardNode() const {
3509 return false;
3510 }
3511
3512 virtual SDValue emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
3513 const SDLoc &DL) const {
3514 llvm_unreachable("not implemented for this target")::llvm::llvm_unreachable_internal("not implemented for this target"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/TargetLowering.h"
, 3514)
;
3515 }
3516
3517 /// Lower TLS global address SDNode for target independent emulated TLS model.
3518 virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
3519 SelectionDAG &DAG) const;
3520
3521 // seteq(x, 0) -> truncate(srl(ctlz(zext(x)), log2(#bits)))
3522 // If we're comparing for equality to zero and isCtlzFast is true, expose the
3523 // fact that this can be implemented as a ctlz/srl pair, so that the dag
3524 // combiner can fold the new nodes.
3525 SDValue lowerCmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) const;
3526
3527private:
3528 SDValue simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
3529 ISD::CondCode Cond, DAGCombinerInfo &DCI,
3530 const SDLoc &DL) const;
3531};
3532
3533/// Given an LLVM IR type and return type attributes, compute the return value
3534/// EVTs and flags, and optionally also the offsets, if the return value is
3535/// being lowered to memory.
3536void GetReturnInfo(Type *ReturnType, AttributeList attr,
3537 SmallVectorImpl<ISD::OutputArg> &Outs,
3538 const TargetLowering &TLI, const DataLayout &DL);
3539
3540} // end namespace llvm
3541
3542#endif // LLVM_CODEGEN_TARGETLOWERING_H