Bug Summary

File:include/llvm/CodeGen/TargetLowering.h
Warning:line 1168, column 9
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name AArch64TargetTransformInfo.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn358520/build-llvm/lib/Target/AArch64 -I /build/llvm-toolchain-snapshot-9~svn358520/lib/Target/AArch64 -I /build/llvm-toolchain-snapshot-9~svn358520/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn358520/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn358520/build-llvm/lib/Target/AArch64 -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn358520=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-04-17-050842-1547-1 -x c++ /build/llvm-toolchain-snapshot-9~svn358520/lib/Target/AArch64/AArch64TargetTransformInfo.cpp -faddrsig

/build/llvm-toolchain-snapshot-9~svn358520/lib/Target/AArch64/AArch64TargetTransformInfo.cpp

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

/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/BasicTTIImpl.h

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

/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h

1//===- llvm/CodeGen/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file describes how to lower LLVM code to machine code. This has two
11/// main components:
12///
13/// 1. Which ValueTypes are natively supported by the target.
14/// 2. Which operations are supported for supported ValueTypes.
15/// 3. Cost thresholds for alternative implementations of certain operations.
16///
17/// In addition it has a few other components, like information about FP
18/// immediates.
19///
20//===----------------------------------------------------------------------===//
21
22#ifndef LLVM_CODEGEN_TARGETLOWERING_H
23#define LLVM_CODEGEN_TARGETLOWERING_H
24
25#include "llvm/ADT/APInt.h"
26#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/StringRef.h"
31#include "llvm/Analysis/LegacyDivergenceAnalysis.h"
32#include "llvm/CodeGen/DAGCombine.h"
33#include "llvm/CodeGen/ISDOpcodes.h"
34#include "llvm/CodeGen/RuntimeLibcalls.h"
35#include "llvm/CodeGen/SelectionDAG.h"
36#include "llvm/CodeGen/SelectionDAGNodes.h"
37#include "llvm/CodeGen/TargetCallingConv.h"
38#include "llvm/CodeGen/ValueTypes.h"
39#include "llvm/IR/Attributes.h"
40#include "llvm/IR/CallSite.h"
41#include "llvm/IR/CallingConv.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/DerivedTypes.h"
44#include "llvm/IR/Function.h"
45#include "llvm/IR/IRBuilder.h"
46#include "llvm/IR/InlineAsm.h"
47#include "llvm/IR/Instruction.h"
48#include "llvm/IR/Instructions.h"
49#include "llvm/IR/Type.h"
50#include "llvm/MC/MCRegisterInfo.h"
51#include "llvm/Support/AtomicOrdering.h"
52#include "llvm/Support/Casting.h"
53#include "llvm/Support/ErrorHandling.h"
54#include "llvm/Support/MachineValueType.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 MaskedIntrinsic, // Use a target-specific intrinsic for the LL/SC loop.
166 };
167
168 /// Enum that specifies when a multiplication should be expanded.
169 enum class MulExpansionKind {
170 Always, // Always expand the instruction.
171 OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
172 // or custom.
173 };
174
175 class ArgListEntry {
176 public:
177 Value *Val = nullptr;
178 SDValue Node = SDValue();
179 Type *Ty = nullptr;
180 bool IsSExt : 1;
181 bool IsZExt : 1;
182 bool IsInReg : 1;
183 bool IsSRet : 1;
184 bool IsNest : 1;
185 bool IsByVal : 1;
186 bool IsInAlloca : 1;
187 bool IsReturned : 1;
188 bool IsSwiftSelf : 1;
189 bool IsSwiftError : 1;
190 uint16_t Alignment = 0;
191
192 ArgListEntry()
193 : IsSExt(false), IsZExt(false), IsInReg(false), IsSRet(false),
194 IsNest(false), IsByVal(false), IsInAlloca(false), IsReturned(false),
195 IsSwiftSelf(false), IsSwiftError(false) {}
196
197 void setAttributes(const CallBase *Call, unsigned ArgIdx);
198
199 void setAttributes(ImmutableCallSite *CS, unsigned ArgIdx) {
200 return setAttributes(cast<CallBase>(CS->getInstruction()), ArgIdx);
201 }
202 };
203 using ArgListTy = std::vector<ArgListEntry>;
204
205 virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
206 ArgListTy &Args) const {};
207
208 static ISD::NodeType getExtendForContent(BooleanContent Content) {
209 switch (Content) {
210 case UndefinedBooleanContent:
211 // Extend by adding rubbish bits.
212 return ISD::ANY_EXTEND;
213 case ZeroOrOneBooleanContent:
214 // Extend by adding zero bits.
215 return ISD::ZERO_EXTEND;
216 case ZeroOrNegativeOneBooleanContent:
217 // Extend by copying the sign bit.
218 return ISD::SIGN_EXTEND;
219 }
220 llvm_unreachable("Invalid content kind")::llvm::llvm_unreachable_internal("Invalid content kind", "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 220)
;
221 }
222
223 /// NOTE: The TargetMachine owns TLOF.
224 explicit TargetLoweringBase(const TargetMachine &TM);
225 TargetLoweringBase(const TargetLoweringBase &) = delete;
226 TargetLoweringBase &operator=(const TargetLoweringBase &) = delete;
227 virtual ~TargetLoweringBase() = default;
228
229protected:
230 /// Initialize all of the actions to default values.
231 void initActions();
232
233public:
234 const TargetMachine &getTargetMachine() const { return TM; }
235
236 virtual bool useSoftFloat() const { return false; }
237
238 /// Return the pointer type for the given address space, defaults to
239 /// the pointer type from the data layout.
240 /// FIXME: The default needs to be removed once all the code is updated.
241 MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
242 return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
243 }
244
245 /// Return the type for frame index, which is determined by
246 /// the alloca address space specified through the data layout.
247 MVT getFrameIndexTy(const DataLayout &DL) const {
248 return getPointerTy(DL, DL.getAllocaAddrSpace());
249 }
250
251 /// Return the type for operands of fence.
252 /// TODO: Let fence operands be of i32 type and remove this.
253 virtual MVT getFenceOperandTy(const DataLayout &DL) const {
254 return getPointerTy(DL);
255 }
256
257 /// EVT is not used in-tree, but is used by out-of-tree target.
258 /// A documentation for this function would be nice...
259 virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
260
261 EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
262 bool LegalTypes = true) const;
263
264 /// Returns the type to be used for the index operand of:
265 /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
266 /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
267 virtual MVT getVectorIdxTy(const DataLayout &DL) const {
268 return getPointerTy(DL);
269 }
270
271 virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
272 return true;
273 }
274
275 /// Return true if it is profitable to convert a select of FP constants into
276 /// a constant pool load whose address depends on the select condition. The
277 /// parameter may be used to differentiate a select with FP compare from
278 /// integer compare.
279 virtual bool reduceSelectOfFPConstantLoads(bool IsFPSetCC) const {
280 return true;
281 }
282
283 /// Return true if multiple condition registers are available.
284 bool hasMultipleConditionRegisters() const {
285 return HasMultipleConditionRegisters;
286 }
287
288 /// Return true if the target has BitExtract instructions.
289 bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
290
291 /// Return the preferred vector type legalization action.
292 virtual TargetLoweringBase::LegalizeTypeAction
293 getPreferredVectorAction(MVT VT) const {
294 // The default action for one element vectors is to scalarize
295 if (VT.getVectorNumElements() == 1)
296 return TypeScalarizeVector;
297 // The default action for an odd-width vector is to widen.
298 if (!VT.isPow2VectorType())
299 return TypeWidenVector;
300 // The default action for other vectors is to promote
301 return TypePromoteInteger;
302 }
303
304 // There are two general methods for expanding a BUILD_VECTOR node:
305 // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
306 // them together.
307 // 2. Build the vector on the stack and then load it.
308 // If this function returns true, then method (1) will be used, subject to
309 // the constraint that all of the necessary shuffles are legal (as determined
310 // by isShuffleMaskLegal). If this function returns false, then method (2) is
311 // always used. The vector type, and the number of defined values, are
312 // provided.
313 virtual bool
314 shouldExpandBuildVectorWithShuffles(EVT /* VT */,
315 unsigned DefinedValues) const {
316 return DefinedValues < 3;
317 }
318
319 /// Return true if integer divide is usually cheaper than a sequence of
320 /// several shifts, adds, and multiplies for this target.
321 /// The definition of "cheaper" may depend on whether we're optimizing
322 /// for speed or for size.
323 virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
324
325 /// Return true if the target can handle a standalone remainder operation.
326 virtual bool hasStandaloneRem(EVT VT) const {
327 return true;
328 }
329
330 /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
331 virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
332 // Default behavior is to replace SQRT(X) with X*RSQRT(X).
333 return false;
334 }
335
336 /// Reciprocal estimate status values used by the functions below.
337 enum ReciprocalEstimate : int {
338 Unspecified = -1,
339 Disabled = 0,
340 Enabled = 1
341 };
342
343 /// Return a ReciprocalEstimate enum value for a square root of the given type
344 /// based on the function's attributes. If the operation is not overridden by
345 /// the function's attributes, "Unspecified" is returned and target defaults
346 /// are expected to be used for instruction selection.
347 int getRecipEstimateSqrtEnabled(EVT VT, MachineFunction &MF) const;
348
349 /// Return a ReciprocalEstimate enum value for a division of the given type
350 /// based on the function's attributes. If the operation is not overridden by
351 /// the function's attributes, "Unspecified" is returned and target defaults
352 /// are expected to be used for instruction selection.
353 int getRecipEstimateDivEnabled(EVT VT, MachineFunction &MF) const;
354
355 /// Return the refinement step count for a square root of the given type based
356 /// on the function's attributes. If the operation is not overridden by
357 /// the function's attributes, "Unspecified" is returned and target defaults
358 /// are expected to be used for instruction selection.
359 int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
360
361 /// Return the refinement step count for a division of the given type based
362 /// on the function's attributes. If the operation is not overridden by
363 /// the function's attributes, "Unspecified" is returned and target defaults
364 /// are expected to be used for instruction selection.
365 int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
366
367 /// Returns true if target has indicated at least one type should be bypassed.
368 bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
369
370 /// Returns map of slow types for division or remainder with corresponding
371 /// fast types
372 const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
373 return BypassSlowDivWidths;
374 }
375
376 /// Return true if Flow Control is an expensive operation that should be
377 /// avoided.
378 bool isJumpExpensive() const { return JumpIsExpensive; }
379
380 /// Return true if selects are only cheaper than branches if the branch is
381 /// unlikely to be predicted right.
382 bool isPredictableSelectExpensive() const {
383 return PredictableSelectIsExpensive;
384 }
385
386 /// If a branch or a select condition is skewed in one direction by more than
387 /// this factor, it is very likely to be predicted correctly.
388 virtual BranchProbability getPredictableBranchThreshold() const;
389
390 /// Return true if the following transform is beneficial:
391 /// fold (conv (load x)) -> (load (conv*)x)
392 /// On architectures that don't natively support some vector loads
393 /// efficiently, casting the load to a smaller vector of larger types and
394 /// loading is more efficient, however, this can be undone by optimizations in
395 /// dag combiner.
396 virtual bool isLoadBitCastBeneficial(EVT LoadVT,
397 EVT BitcastVT) const {
398 // Don't do if we could do an indexed load on the original type, but not on
399 // the new one.
400 if (!LoadVT.isSimple() || !BitcastVT.isSimple())
401 return true;
402
403 MVT LoadMVT = LoadVT.getSimpleVT();
404
405 // Don't bother doing this if it's just going to be promoted again later, as
406 // doing so might interfere with other combines.
407 if (getOperationAction(ISD::LOAD, LoadMVT) == Promote &&
408 getTypeToPromoteTo(ISD::LOAD, LoadMVT) == BitcastVT.getSimpleVT())
409 return false;
410
411 return true;
412 }
413
414 /// Return true if the following transform is beneficial:
415 /// (store (y (conv x)), y*)) -> (store x, (x*))
416 virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT) const {
417 // Default to the same logic as loads.
418 return isLoadBitCastBeneficial(StoreVT, BitcastVT);
419 }
420
421 /// Return true if it is expected to be cheaper to do a store of a non-zero
422 /// vector constant with the given size and type for the address space than to
423 /// store the individual scalar element constants.
424 virtual bool storeOfVectorConstantIsCheap(EVT MemVT,
425 unsigned NumElem,
426 unsigned AddrSpace) const {
427 return false;
428 }
429
430 /// Allow store merging after legalization in addition to before legalization.
431 /// This may catch stores that do not exist earlier (eg, stores created from
432 /// intrinsics).
433 virtual bool mergeStoresAfterLegalization() const { return true; }
434
435 /// Returns if it's reasonable to merge stores to MemVT size.
436 virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
437 const SelectionDAG &DAG) const {
438 return true;
439 }
440
441 /// Return true if it is cheap to speculate a call to intrinsic cttz.
442 virtual bool isCheapToSpeculateCttz() const {
443 return false;
444 }
445
446 /// Return true if it is cheap to speculate a call to intrinsic ctlz.
447 virtual bool isCheapToSpeculateCtlz() const {
448 return false;
449 }
450
451 /// Return true if ctlz instruction is fast.
452 virtual bool isCtlzFast() const {
453 return false;
454 }
455
456 /// Return true if it is safe to transform an integer-domain bitwise operation
457 /// into the equivalent floating-point operation. This should be set to true
458 /// if the target has IEEE-754-compliant fabs/fneg operations for the input
459 /// type.
460 virtual bool hasBitPreservingFPLogic(EVT VT) const {
461 return false;
462 }
463
464 /// Return true if it is cheaper to split the store of a merged int val
465 /// from a pair of smaller values into multiple stores.
466 virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
467 return false;
468 }
469
470 /// Return if the target supports combining a
471 /// chain like:
472 /// \code
473 /// %andResult = and %val1, #mask
474 /// %icmpResult = icmp %andResult, 0
475 /// \endcode
476 /// into a single machine instruction of a form like:
477 /// \code
478 /// cc = test %register, #mask
479 /// \endcode
480 virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
481 return false;
482 }
483
484 /// Use bitwise logic to make pairs of compares more efficient. For example:
485 /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
486 /// This should be true when it takes more than one instruction to lower
487 /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
488 /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
489 virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
490 return false;
491 }
492
493 /// Return the preferred operand type if the target has a quick way to compare
494 /// integer values of the given size. Assume that any legal integer type can
495 /// be compared efficiently. Targets may override this to allow illegal wide
496 /// types to return a vector type if there is support to compare that type.
497 virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
498 MVT VT = MVT::getIntegerVT(NumBits);
499 return isTypeLegal(VT) ? VT : MVT::INVALID_SIMPLE_VALUE_TYPE;
500 }
501
502 /// Return true if the target should transform:
503 /// (X & Y) == Y ---> (~X & Y) == 0
504 /// (X & Y) != Y ---> (~X & Y) != 0
505 ///
506 /// This may be profitable if the target has a bitwise and-not operation that
507 /// sets comparison flags. A target may want to limit the transformation based
508 /// on the type of Y or if Y is a constant.
509 ///
510 /// Note that the transform will not occur if Y is known to be a power-of-2
511 /// because a mask and compare of a single bit can be handled by inverting the
512 /// predicate, for example:
513 /// (X & 8) == 8 ---> (X & 8) != 0
514 virtual bool hasAndNotCompare(SDValue Y) const {
515 return false;
516 }
517
518 /// Return true if the target has a bitwise and-not operation:
519 /// X = ~A & B
520 /// This can be used to simplify select or other instructions.
521 virtual bool hasAndNot(SDValue X) const {
522 // If the target has the more complex version of this operation, assume that
523 // it has this operation too.
524 return hasAndNotCompare(X);
525 }
526
527 /// There are two ways to clear extreme bits (either low or high):
528 /// Mask: x & (-1 << y) (the instcombine canonical form)
529 /// Shifts: x >> y << y
530 /// Return true if the variant with 2 shifts is preferred.
531 /// Return false if there is no preference.
532 virtual bool preferShiftsToClearExtremeBits(SDValue X) const {
533 // By default, let's assume that no one prefers shifts.
534 return false;
535 }
536
537 /// Return true if it is profitable to fold a pair of shifts into a mask.
538 /// This is usually true on most targets. But some targets, like Thumb1,
539 /// have immediate shift instructions, but no immediate "and" instruction;
540 /// this makes the fold unprofitable.
541 virtual bool shouldFoldShiftPairToMask(const SDNode *N,
542 CombineLevel Level) const {
543 return true;
544 }
545
546 /// Should we tranform the IR-optimal check for whether given truncation
547 /// down into KeptBits would be truncating or not:
548 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
549 /// Into it's more traditional form:
550 /// ((%x << C) a>> C) dstcond %x
551 /// Return true if we should transform.
552 /// Return false if there is no preference.
553 virtual bool shouldTransformSignedTruncationCheck(EVT XVT,
554 unsigned KeptBits) const {
555 // By default, let's assume that no one prefers shifts.
556 return false;
557 }
558
559 /// Return true if the target wants to use the optimization that
560 /// turns ext(promotableInst1(...(promotableInstN(load)))) into
561 /// promotedInst1(...(promotedInstN(ext(load)))).
562 bool enableExtLdPromotion() const { return EnableExtLdPromotion; }
563
564 /// Return true if the target can combine store(extractelement VectorTy,
565 /// Idx).
566 /// \p Cost[out] gives the cost of that transformation when this is true.
567 virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
568 unsigned &Cost) const {
569 return false;
570 }
571
572 /// Return true if inserting a scalar into a variable element of an undef
573 /// vector is more efficiently handled by splatting the scalar instead.
574 virtual bool shouldSplatInsEltVarIndex(EVT) const {
575 return false;
576 }
577
578 /// Return true if target supports floating point exceptions.
579 bool hasFloatingPointExceptions() const {
580 return HasFloatingPointExceptions;
581 }
582
583 /// Return true if target always beneficiates from combining into FMA for a
584 /// given value type. This must typically return false on targets where FMA
585 /// takes more cycles to execute than FADD.
586 virtual bool enableAggressiveFMAFusion(EVT VT) const {
587 return false;
588 }
589
590 /// Return the ValueType of the result of SETCC operations.
591 virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
592 EVT VT) const;
593
594 /// Return the ValueType for comparison libcalls. Comparions libcalls include
595 /// floating point comparion calls, and Ordered/Unordered check calls on
596 /// floating point numbers.
597 virtual
598 MVT::SimpleValueType getCmpLibcallReturnType() const;
599
600 /// For targets without i1 registers, this gives the nature of the high-bits
601 /// of boolean values held in types wider than i1.
602 ///
603 /// "Boolean values" are special true/false values produced by nodes like
604 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
605 /// Not to be confused with general values promoted from i1. Some cpus
606 /// distinguish between vectors of boolean and scalars; the isVec parameter
607 /// selects between the two kinds. For example on X86 a scalar boolean should
608 /// be zero extended from i1, while the elements of a vector of booleans
609 /// should be sign extended from i1.
610 ///
611 /// Some cpus also treat floating point types the same way as they treat
612 /// vectors instead of the way they treat scalars.
613 BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
614 if (isVec)
615 return BooleanVectorContents;
616 return isFloat ? BooleanFloatContents : BooleanContents;
617 }
618
619 BooleanContent getBooleanContents(EVT Type) const {
620 return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
621 }
622
623 /// Return target scheduling preference.
624 Sched::Preference getSchedulingPreference() const {
625 return SchedPreferenceInfo;
626 }
627
628 /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
629 /// for different nodes. This function returns the preference (or none) for
630 /// the given node.
631 virtual Sched::Preference getSchedulingPreference(SDNode *) const {
632 return Sched::None;
633 }
634
635 /// Return the register class that should be used for the specified value
636 /// type.
637 virtual const TargetRegisterClass *getRegClassFor(MVT VT) const {
638 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
639 assert(RC && "This value type is not natively supported!")((RC && "This value type is not natively supported!")
? static_cast<void> (0) : __assert_fail ("RC && \"This value type is not natively supported!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 639, __PRETTY_FUNCTION__))
;
640 return RC;
641 }
642
643 /// Return the 'representative' register class for the specified value
644 /// type.
645 ///
646 /// The 'representative' register class is the largest legal super-reg
647 /// register class for the register class of the value type. For example, on
648 /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
649 /// register class is GR64 on x86_64.
650 virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
651 const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
652 return RC;
653 }
654
655 /// Return the cost of the 'representative' register class for the specified
656 /// value type.
657 virtual uint8_t getRepRegClassCostFor(MVT VT) const {
658 return RepRegClassCostForVT[VT.SimpleTy];
659 }
660
661 /// Return true if SHIFT instructions should be expanded to SHIFT_PARTS
662 /// instructions, and false if a library call is preferred (e.g for code-size
663 /// reasons).
664 virtual bool shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
665 return true;
666 }
667
668 /// Return true if the target has native support for the specified value type.
669 /// This means that it has a register that directly holds it without
670 /// promotions or expansions.
671 bool isTypeLegal(EVT VT) const {
672 assert(!VT.isSimple() ||((!VT.isSimple() || (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof
(RegClassForVT)) ? static_cast<void> (0) : __assert_fail
("!VT.isSimple() || (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT)"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 673, __PRETTY_FUNCTION__))
673 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT))((!VT.isSimple() || (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof
(RegClassForVT)) ? static_cast<void> (0) : __assert_fail
("!VT.isSimple() || (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT)"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 673, __PRETTY_FUNCTION__))
;
674 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
675 }
676
677 class ValueTypeActionImpl {
678 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
679 /// that indicates how instruction selection should deal with the type.
680 LegalizeTypeAction ValueTypeActions[MVT::LAST_VALUETYPE];
681
682 public:
683 ValueTypeActionImpl() {
684 std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions),
685 TypeLegal);
686 }
687
688 LegalizeTypeAction getTypeAction(MVT VT) const {
689 return ValueTypeActions[VT.SimpleTy];
690 }
691
692 void setTypeAction(MVT VT, LegalizeTypeAction Action) {
693 ValueTypeActions[VT.SimpleTy] = Action;
694 }
695 };
696
697 const ValueTypeActionImpl &getValueTypeActions() const {
698 return ValueTypeActions;
699 }
700
701 /// Return how we should legalize values of this type, either it is already
702 /// legal (return 'Legal') or we need to promote it to a larger type (return
703 /// 'Promote'), or we need to expand it into multiple registers of smaller
704 /// integer type (return 'Expand'). 'Custom' is not an option.
705 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
706 return getTypeConversion(Context, VT).first;
707 }
708 LegalizeTypeAction getTypeAction(MVT VT) const {
709 return ValueTypeActions.getTypeAction(VT);
710 }
711
712 /// For types supported by the target, this is an identity function. For
713 /// types that must be promoted to larger types, this returns the larger type
714 /// to promote to. For integer types that are larger than the largest integer
715 /// register, this contains one step in the expansion to get to the smaller
716 /// register. For illegal floating point types, this returns the integer type
717 /// to transform to.
718 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
719 return getTypeConversion(Context, VT).second;
720 }
721
722 /// For types supported by the target, this is an identity function. For
723 /// types that must be expanded (i.e. integer types that are larger than the
724 /// largest integer register or illegal floating point types), this returns
725 /// the largest legal type it will be expanded to.
726 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
727 assert(!VT.isVector())((!VT.isVector()) ? static_cast<void> (0) : __assert_fail
("!VT.isVector()", "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 727, __PRETTY_FUNCTION__))
;
728 while (true) {
729 switch (getTypeAction(Context, VT)) {
730 case TypeLegal:
731 return VT;
732 case TypeExpandInteger:
733 VT = getTypeToTransformTo(Context, VT);
734 break;
735 default:
736 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-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 736)
;
737 }
738 }
739 }
740
741 /// Vector types are broken down into some number of legal first class types.
742 /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
743 /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
744 /// turns into 4 EVT::i32 values with both PPC and X86.
745 ///
746 /// This method returns the number of registers needed, and the VT for each
747 /// register. It also returns the VT and quantity of the intermediate values
748 /// before they are promoted/expanded.
749 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
750 EVT &IntermediateVT,
751 unsigned &NumIntermediates,
752 MVT &RegisterVT) const;
753
754 /// Certain targets such as MIPS require that some types such as vectors are
755 /// always broken down into scalars in some contexts. This occurs even if the
756 /// vector type is legal.
757 virtual unsigned getVectorTypeBreakdownForCallingConv(
758 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
759 unsigned &NumIntermediates, MVT &RegisterVT) const {
760 return getVectorTypeBreakdown(Context, VT, IntermediateVT, NumIntermediates,
761 RegisterVT);
762 }
763
764 struct IntrinsicInfo {
765 unsigned opc = 0; // target opcode
766 EVT memVT; // memory VT
767
768 // value representing memory location
769 PointerUnion<const Value *, const PseudoSourceValue *> ptrVal;
770
771 int offset = 0; // offset off of ptrVal
772 unsigned size = 0; // the size of the memory location
773 // (taken from memVT if zero)
774 unsigned align = 1; // alignment
775
776 MachineMemOperand::Flags flags = MachineMemOperand::MONone;
777 IntrinsicInfo() = default;
778 };
779
780 /// Given an intrinsic, checks if on the target the intrinsic will need to map
781 /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
782 /// true and store the intrinsic information into the IntrinsicInfo that was
783 /// passed to the function.
784 virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
785 MachineFunction &,
786 unsigned /*Intrinsic*/) const {
787 return false;
788 }
789
790 /// Returns true if the target can instruction select the specified FP
791 /// immediate natively. If false, the legalizer will materialize the FP
792 /// immediate as a load from a constant pool.
793 virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/,
794 bool ForCodeSize = false) const {
795 return false;
796 }
797
798 /// Targets can use this to indicate that they only support *some*
799 /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
800 /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
801 /// legal.
802 virtual bool isShuffleMaskLegal(ArrayRef<int> /*Mask*/, EVT /*VT*/) const {
803 return true;
804 }
805
806 /// Returns true if the operation can trap for the value type.
807 ///
808 /// VT must be a legal type. By default, we optimistically assume most
809 /// operations don't trap except for integer divide and remainder.
810 virtual bool canOpTrap(unsigned Op, EVT VT) const;
811
812 /// Similar to isShuffleMaskLegal. Targets can use this to indicate if there
813 /// is a suitable VECTOR_SHUFFLE that can be used to replace a VAND with a
814 /// constant pool entry.
815 virtual bool isVectorClearMaskLegal(ArrayRef<int> /*Mask*/,
816 EVT /*VT*/) const {
817 return false;
818 }
819
820 /// Return how this operation should be treated: either it is legal, needs to
821 /// be promoted to a larger size, needs to be expanded to some other code
822 /// sequence, or the target has a custom expander for it.
823 LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
824 if (VT.isExtended()) return Expand;
825 // If a target-specific SDNode requires legalization, require the target
826 // to provide custom legalization for it.
827 if (Op >= array_lengthof(OpActions[0])) return Custom;
828 return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
829 }
830
831 /// Custom method defined by each target to indicate if an operation which
832 /// may require a scale is supported natively by the target.
833 /// If not, the operation is illegal.
834 virtual bool isSupportedFixedPointOperation(unsigned Op, EVT VT,
835 unsigned Scale) const {
836 return false;
837 }
838
839 /// Some fixed point operations may be natively supported by the target but
840 /// only for specific scales. This method allows for checking
841 /// if the width is supported by the target for a given operation that may
842 /// depend on scale.
843 LegalizeAction getFixedPointOperationAction(unsigned Op, EVT VT,
844 unsigned Scale) const {
845 auto Action = getOperationAction(Op, VT);
846 if (Action != Legal)
847 return Action;
848
849 // This operation is supported in this type but may only work on specific
850 // scales.
851 bool Supported;
852 switch (Op) {
853 default:
854 llvm_unreachable("Unexpected fixed point operation.")::llvm::llvm_unreachable_internal("Unexpected fixed point operation."
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 854)
;
855 case ISD::SMULFIX:
856 case ISD::UMULFIX:
857 Supported = isSupportedFixedPointOperation(Op, VT, Scale);
858 break;
859 }
860
861 return Supported ? Action : Expand;
862 }
863
864 LegalizeAction getStrictFPOperationAction(unsigned Op, EVT VT) const {
865 unsigned EqOpc;
866 switch (Op) {
867 default: llvm_unreachable("Unexpected FP pseudo-opcode")::llvm::llvm_unreachable_internal("Unexpected FP pseudo-opcode"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 867)
;
868 case ISD::STRICT_FADD: EqOpc = ISD::FADD; break;
869 case ISD::STRICT_FSUB: EqOpc = ISD::FSUB; break;
870 case ISD::STRICT_FMUL: EqOpc = ISD::FMUL; break;
871 case ISD::STRICT_FDIV: EqOpc = ISD::FDIV; break;
872 case ISD::STRICT_FREM: EqOpc = ISD::FREM; break;
873 case ISD::STRICT_FSQRT: EqOpc = ISD::FSQRT; break;
874 case ISD::STRICT_FPOW: EqOpc = ISD::FPOW; break;
875 case ISD::STRICT_FPOWI: EqOpc = ISD::FPOWI; break;
876 case ISD::STRICT_FMA: EqOpc = ISD::FMA; break;
877 case ISD::STRICT_FSIN: EqOpc = ISD::FSIN; break;
878 case ISD::STRICT_FCOS: EqOpc = ISD::FCOS; break;
879 case ISD::STRICT_FEXP: EqOpc = ISD::FEXP; break;
880 case ISD::STRICT_FEXP2: EqOpc = ISD::FEXP2; break;
881 case ISD::STRICT_FLOG: EqOpc = ISD::FLOG; break;
882 case ISD::STRICT_FLOG10: EqOpc = ISD::FLOG10; break;
883 case ISD::STRICT_FLOG2: EqOpc = ISD::FLOG2; break;
884 case ISD::STRICT_FRINT: EqOpc = ISD::FRINT; break;
885 case ISD::STRICT_FNEARBYINT: EqOpc = ISD::FNEARBYINT; break;
886 case ISD::STRICT_FMAXNUM: EqOpc = ISD::FMAXNUM; break;
887 case ISD::STRICT_FMINNUM: EqOpc = ISD::FMINNUM; break;
888 case ISD::STRICT_FCEIL: EqOpc = ISD::FCEIL; break;
889 case ISD::STRICT_FFLOOR: EqOpc = ISD::FFLOOR; break;
890 case ISD::STRICT_FROUND: EqOpc = ISD::FROUND; break;
891 case ISD::STRICT_FTRUNC: EqOpc = ISD::FTRUNC; break;
892 }
893
894 auto Action = getOperationAction(EqOpc, VT);
895
896 // We don't currently handle Custom or Promote for strict FP pseudo-ops.
897 // For now, we just expand for those cases.
898 if (Action != Legal)
899 Action = Expand;
900
901 return Action;
902 }
903
904 /// Return true if the specified operation is legal on this target or can be
905 /// made legal with custom lowering. This is used to help guide high-level
906 /// lowering decisions.
907 bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
908 return (VT == MVT::Other || isTypeLegal(VT)) &&
909 (getOperationAction(Op, VT) == Legal ||
910 getOperationAction(Op, VT) == Custom);
911 }
912
913 /// Return true if the specified operation is legal on this target or can be
914 /// made legal using promotion. This is used to help guide high-level lowering
915 /// decisions.
916 bool isOperationLegalOrPromote(unsigned Op, EVT VT) const {
917 return (VT == MVT::Other || isTypeLegal(VT)) &&
918 (getOperationAction(Op, VT) == Legal ||
919 getOperationAction(Op, VT) == Promote);
920 }
921
922 /// Return true if the specified operation is legal on this target or can be
923 /// made legal with custom lowering or using promotion. This is used to help
924 /// guide high-level lowering decisions.
925 bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT) const {
926 return (VT == MVT::Other || isTypeLegal(VT)) &&
927 (getOperationAction(Op, VT) == Legal ||
928 getOperationAction(Op, VT) == Custom ||
929 getOperationAction(Op, VT) == Promote);
930 }
931
932 /// Return true if the operation uses custom lowering, regardless of whether
933 /// the type is legal or not.
934 bool isOperationCustom(unsigned Op, EVT VT) const {
935 return getOperationAction(Op, VT) == Custom;
936 }
937
938 /// Return true if lowering to a jump table is allowed.
939 virtual bool areJTsAllowed(const Function *Fn) const {
940 if (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")
941 return false;
942
943 return isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
944 isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
945 }
946
947 /// Check whether the range [Low,High] fits in a machine word.
948 bool rangeFitsInWord(const APInt &Low, const APInt &High,
949 const DataLayout &DL) const {
950 // FIXME: Using the pointer type doesn't seem ideal.
951 uint64_t BW = DL.getIndexSizeInBits(0u);
952 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX(18446744073709551615UL) - 1) + 1;
953 return Range <= BW;
954 }
955
956 /// Return true if lowering to a jump table is suitable for a set of case
957 /// clusters which may contain \p NumCases cases, \p Range range of values.
958 /// FIXME: This function check the maximum table size and density, but the
959 /// minimum size is not checked. It would be nice if the minimum size is
960 /// also combined within this function. Currently, the minimum size check is
961 /// performed in findJumpTable() in SelectionDAGBuiler and
962 /// getEstimatedNumberOfCaseClusters() in BasicTTIImpl.
963 virtual bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
964 uint64_t Range) const {
965 const bool OptForSize = SI->getParent()->getParent()->hasOptSize();
966 const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize);
967 const unsigned MaxJumpTableSize =
968 OptForSize ? UINT_MAX(2147483647 *2U +1U) : getMaximumJumpTableSize();
969 // Check whether a range of clusters is dense enough for a jump table.
970 if (Range <= MaxJumpTableSize &&
971 (NumCases * 100 >= Range * MinDensity)) {
972 return true;
973 }
974 return false;
975 }
976
977 /// Return true if lowering to a bit test is suitable for a set of case
978 /// clusters which contains \p NumDests unique destinations, \p Low and
979 /// \p High as its lowest and highest case values, and expects \p NumCmps
980 /// case value comparisons. Check if the number of destinations, comparison
981 /// metric, and range are all suitable.
982 bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
983 const APInt &Low, const APInt &High,
984 const DataLayout &DL) const {
985 // FIXME: I don't think NumCmps is the correct metric: a single case and a
986 // range of cases both require only one branch to lower. Just looking at the
987 // number of clusters and destinations should be enough to decide whether to
988 // build bit tests.
989
990 // To lower a range with bit tests, the range must fit the bitwidth of a
991 // machine word.
992 if (!rangeFitsInWord(Low, High, DL))
993 return false;
994
995 // Decide whether it's profitable to lower this range with bit tests. Each
996 // destination requires a bit test and branch, and there is an overall range
997 // check branch. For a small number of clusters, separate comparisons might
998 // be cheaper, and for many destinations, splitting the range might be
999 // better.
1000 return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
1001 (NumDests == 3 && NumCmps >= 6);
1002 }
1003
1004 /// Return true if the specified operation is illegal on this target or
1005 /// unlikely to be made legal with custom lowering. This is used to help guide
1006 /// high-level lowering decisions.
1007 bool isOperationExpand(unsigned Op, EVT VT) const {
1008 return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
1009 }
1010
1011 /// Return true if the specified operation is legal on this target.
1012 bool isOperationLegal(unsigned Op, EVT VT) const {
1013 return (VT == MVT::Other || isTypeLegal(VT)) &&
1014 getOperationAction(Op, VT) == Legal;
1015 }
1016
1017 /// Return how this load with extension should be treated: either it is legal,
1018 /// needs to be promoted to a larger size, needs to be expanded to some other
1019 /// code sequence, or the target has a custom expander for it.
1020 LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT,
1021 EVT MemVT) const {
1022 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
1023 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1024 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1025 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::LAST_VALUETYPE &&((ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT
::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE &&
"Table isn't big enough!") ? static_cast<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-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1026, __PRETTY_FUNCTION__))
1026 MemI < MVT::LAST_VALUETYPE && "Table isn't big enough!")((ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT
::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE &&
"Table isn't big enough!") ? static_cast<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-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1026, __PRETTY_FUNCTION__))
;
1027 unsigned Shift = 4 * ExtType;
1028 return (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
1029 }
1030
1031 /// Return true if the specified load with extension is legal on this target.
1032 bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1033 return getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
1034 }
1035
1036 /// Return true if the specified load with extension is legal or custom
1037 /// on this target.
1038 bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1039 return getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
1040 getLoadExtAction(ExtType, ValVT, MemVT) == Custom;
1041 }
1042
1043 /// Return how this store with truncation should be treated: either it is
1044 /// legal, needs to be promoted to a larger size, needs to be expanded to some
1045 /// other code sequence, or the target has a custom expander for it.
1046 LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
1047 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
1048 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1049 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1050 assert(ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE &&((ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE
&& "Table isn't big enough!") ? static_cast<void>
(0) : __assert_fail ("ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1051, __PRETTY_FUNCTION__))
1051 "Table isn't big enough!")((ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE
&& "Table isn't big enough!") ? static_cast<void>
(0) : __assert_fail ("ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1051, __PRETTY_FUNCTION__))
;
1052 return TruncStoreActions[ValI][MemI];
1053 }
1054
1055 /// Return true if the specified store with truncation is legal on this
1056 /// target.
1057 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
1058 return isTypeLegal(ValVT) && getTruncStoreAction(ValVT, MemVT) == Legal;
1059 }
1060
1061 /// Return true if the specified store with truncation has solution on this
1062 /// target.
1063 bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const {
1064 return isTypeLegal(ValVT) &&
1065 (getTruncStoreAction(ValVT, MemVT) == Legal ||
1066 getTruncStoreAction(ValVT, MemVT) == Custom);
1067 }
1068
1069 /// Return how the indexed load should be treated: either it is legal, needs
1070 /// to be promoted to a larger size, needs to be expanded to some other code
1071 /// sequence, or the target has a custom expander for it.
1072 LegalizeAction
1073 getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
1074 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&((IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid()
&& "Table isn't big enough!") ? static_cast<void>
(0) : __assert_fail ("IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1075, __PRETTY_FUNCTION__))
1075 "Table isn't big enough!")((IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid()
&& "Table isn't big enough!") ? static_cast<void>
(0) : __assert_fail ("IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1075, __PRETTY_FUNCTION__))
;
1076 unsigned Ty = (unsigned)VT.SimpleTy;
1077 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
1078 }
1079
1080 /// Return true if the specified indexed load is legal on this target.
1081 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
1082 return VT.isSimple() &&
1083 (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1084 getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
1085 }
1086
1087 /// Return how the indexed store should be treated: either it is legal, needs
1088 /// to be promoted to a larger size, needs to be expanded to some other code
1089 /// sequence, or the target has a custom expander for it.
1090 LegalizeAction
1091 getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
1092 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&((IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid()
&& "Table isn't big enough!") ? static_cast<void>
(0) : __assert_fail ("IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1093, __PRETTY_FUNCTION__))
1093 "Table isn't big enough!")((IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid()
&& "Table isn't big enough!") ? static_cast<void>
(0) : __assert_fail ("IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1093, __PRETTY_FUNCTION__))
;
1094 unsigned Ty = (unsigned)VT.SimpleTy;
1095 return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
1096 }
1097
1098 /// Return true if the specified indexed load is legal on this target.
1099 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
1100 return VT.isSimple() &&
1101 (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1102 getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
1103 }
1104
1105 /// Return how the condition code should be treated: either it is legal, needs
1106 /// to be expanded to some other code sequence, or the target has a custom
1107 /// expander for it.
1108 LegalizeAction
1109 getCondCodeAction(ISD::CondCode CC, MVT VT) const {
1110 assert((unsigned)CC < array_lengthof(CondCodeActions) &&(((unsigned)CC < array_lengthof(CondCodeActions) &&
((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions
[0]) && "Table isn't big enough!") ? static_cast<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-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1112, __PRETTY_FUNCTION__))
1111 ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) &&(((unsigned)CC < array_lengthof(CondCodeActions) &&
((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions
[0]) && "Table isn't big enough!") ? static_cast<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-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1112, __PRETTY_FUNCTION__))
1112 "Table isn't big enough!")(((unsigned)CC < array_lengthof(CondCodeActions) &&
((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions
[0]) && "Table isn't big enough!") ? static_cast<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-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1112, __PRETTY_FUNCTION__))
;
1113 // See setCondCodeAction for how this is encoded.
1114 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1115 uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
1116 LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
1117 assert(Action != Promote && "Can't promote condition code!")((Action != Promote && "Can't promote condition code!"
) ? static_cast<void> (0) : __assert_fail ("Action != Promote && \"Can't promote condition code!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1117, __PRETTY_FUNCTION__))
;
1118 return Action;
1119 }
1120
1121 /// Return true if the specified condition code is legal on this target.
1122 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
1123 return getCondCodeAction(CC, VT) == Legal;
1124 }
1125
1126 /// Return true if the specified condition code is legal or custom on this
1127 /// target.
1128 bool isCondCodeLegalOrCustom(ISD::CondCode CC, MVT VT) const {
1129 return getCondCodeAction(CC, VT) == Legal ||
1130 getCondCodeAction(CC, VT) == Custom;
1131 }
1132
1133 /// If the action for this operation is to promote, this method returns the
1134 /// ValueType to promote to.
1135 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
1136 assert(getOperationAction(Op, VT) == Promote &&((getOperationAction(Op, VT) == Promote && "This operation isn't promoted!"
) ? static_cast<void> (0) : __assert_fail ("getOperationAction(Op, VT) == Promote && \"This operation isn't promoted!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1137, __PRETTY_FUNCTION__))
1137 "This operation isn't promoted!")((getOperationAction(Op, VT) == Promote && "This operation isn't promoted!"
) ? static_cast<void> (0) : __assert_fail ("getOperationAction(Op, VT) == Promote && \"This operation isn't promoted!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1137, __PRETTY_FUNCTION__))
;
1138
1139 // See if this has an explicit type specified.
1140 std::map<std::pair<unsigned, MVT::SimpleValueType>,
1141 MVT::SimpleValueType>::const_iterator PTTI =
1142 PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
1143 if (PTTI != PromoteToType.end()) return PTTI->second;
1144
1145 assert((VT.isInteger() || VT.isFloatingPoint()) &&(((VT.isInteger() || VT.isFloatingPoint()) && "Cannot autopromote this type, add it with AddPromotedToType."
) ? static_cast<void> (0) : __assert_fail ("(VT.isInteger() || VT.isFloatingPoint()) && \"Cannot autopromote this type, add it with AddPromotedToType.\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1146, __PRETTY_FUNCTION__))
1146 "Cannot autopromote this type, add it with AddPromotedToType.")(((VT.isInteger() || VT.isFloatingPoint()) && "Cannot autopromote this type, add it with AddPromotedToType."
) ? static_cast<void> (0) : __assert_fail ("(VT.isInteger() || VT.isFloatingPoint()) && \"Cannot autopromote this type, add it with AddPromotedToType.\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1146, __PRETTY_FUNCTION__))
;
1147
1148 MVT NVT = VT;
1149 do {
1150 NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
1151 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&((NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid
&& "Didn't find type to promote to!") ? static_cast<
void> (0) : __assert_fail ("NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid && \"Didn't find type to promote to!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1152, __PRETTY_FUNCTION__))
1152 "Didn't find type to promote to!")((NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid
&& "Didn't find type to promote to!") ? static_cast<
void> (0) : __assert_fail ("NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid && \"Didn't find type to promote to!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1152, __PRETTY_FUNCTION__))
;
1153 } while (!isTypeLegal(NVT) ||
1154 getOperationAction(Op, NVT) == Promote);
1155 return NVT;
1156 }
1157
1158 /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
1159 /// operations except for the pointer size. If AllowUnknown is true, this
1160 /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1161 /// otherwise it will assert.
1162 EVT getValueType(const DataLayout &DL, Type *Ty,
1163 bool AllowUnknown = false) const {
1164 // Lower scalar pointers to native pointer types.
1165 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
17
Taking false branch
1166 return getPointerTy(DL, PTy->getAddressSpace());
1167
1168 if (Ty->isVectorTy()) {
18
Called C++ object pointer is null
1169 VectorType *VTy = cast<VectorType>(Ty);
1170 Type *Elm = VTy->getElementType();
1171 // Lower vectors of pointers to native pointer types.
1172 if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
1173 EVT PointerTy(getPointerTy(DL, PT->getAddressSpace()));
1174 Elm = PointerTy.getTypeForEVT(Ty->getContext());
1175 }
1176
1177 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
1178 VTy->getNumElements());
1179 }
1180 return EVT::getEVT(Ty, AllowUnknown);
1181 }
1182
1183 /// Return the MVT corresponding to this LLVM type. See getValueType.
1184 MVT getSimpleValueType(const DataLayout &DL, Type *Ty,
1185 bool AllowUnknown = false) const {
1186 return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
1187 }
1188
1189 /// Return the desired alignment for ByVal or InAlloca aggregate function
1190 /// arguments in the caller parameter area. This is the actual alignment, not
1191 /// its logarithm.
1192 virtual unsigned getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
1193
1194 /// Return the type of registers that this ValueType will eventually require.
1195 MVT getRegisterType(MVT VT) const {
1196 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT))(((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT
)) ? static_cast<void> (0) : __assert_fail ("(unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT)"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1196, __PRETTY_FUNCTION__))
;
1197 return RegisterTypeForVT[VT.SimpleTy];
1198 }
1199
1200 /// Return the type of registers that this ValueType will eventually require.
1201 MVT getRegisterType(LLVMContext &Context, EVT VT) const {
1202 if (VT.isSimple()) {
1203 assert((unsigned)VT.getSimpleVT().SimpleTy <(((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegisterTypeForVT
)) ? static_cast<void> (0) : __assert_fail ("(unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegisterTypeForVT)"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1204, __PRETTY_FUNCTION__))
1204 array_lengthof(RegisterTypeForVT))(((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegisterTypeForVT
)) ? static_cast<void> (0) : __assert_fail ("(unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegisterTypeForVT)"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1204, __PRETTY_FUNCTION__))
;
1205 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
1206 }
1207 if (VT.isVector()) {
1208 EVT VT1;
1209 MVT RegisterVT;
1210 unsigned NumIntermediates;
1211 (void)getVectorTypeBreakdown(Context, VT, VT1,
1212 NumIntermediates, RegisterVT);
1213 return RegisterVT;
1214 }
1215 if (VT.isInteger()) {
1216 return getRegisterType(Context, getTypeToTransformTo(Context, VT));
1217 }
1218 llvm_unreachable("Unsupported extended type!")::llvm::llvm_unreachable_internal("Unsupported extended type!"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1218)
;
1219 }
1220
1221 /// Return the number of registers that this ValueType will eventually
1222 /// require.
1223 ///
1224 /// This is one for any types promoted to live in larger registers, but may be
1225 /// more than one for types (like i64) that are split into pieces. For types
1226 /// like i140, which are first promoted then expanded, it is the number of
1227 /// registers needed to hold all the bits of the original type. For an i140
1228 /// on a 32 bit machine this means 5 registers.
1229 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
1230 if (VT.isSimple()) {
1231 assert((unsigned)VT.getSimpleVT().SimpleTy <(((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(NumRegistersForVT
)) ? static_cast<void> (0) : __assert_fail ("(unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(NumRegistersForVT)"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1232, __PRETTY_FUNCTION__))
1232 array_lengthof(NumRegistersForVT))(((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(NumRegistersForVT
)) ? static_cast<void> (0) : __assert_fail ("(unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(NumRegistersForVT)"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1232, __PRETTY_FUNCTION__))
;
1233 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
1234 }
1235 if (VT.isVector()) {
1236 EVT VT1;
1237 MVT VT2;
1238 unsigned NumIntermediates;
1239 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
1240 }
1241 if (VT.isInteger()) {
1242 unsigned BitWidth = VT.getSizeInBits();
1243 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
1244 return (BitWidth + RegWidth - 1) / RegWidth;
1245 }
1246 llvm_unreachable("Unsupported extended type!")::llvm::llvm_unreachable_internal("Unsupported extended type!"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1246)
;
1247 }
1248
1249 /// Certain combinations of ABIs, Targets and features require that types
1250 /// are legal for some operations and not for other operations.
1251 /// For MIPS all vector types must be passed through the integer register set.
1252 virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context,
1253 CallingConv::ID CC, EVT VT) const {
1254 return getRegisterType(Context, VT);
1255 }
1256
1257 /// Certain targets require unusual breakdowns of certain types. For MIPS,
1258 /// this occurs when a vector type is used, as vector are passed through the
1259 /// integer register set.
1260 virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context,
1261 CallingConv::ID CC,
1262 EVT VT) const {
1263 return getNumRegisters(Context, VT);
1264 }
1265
1266 /// Certain targets have context senstive alignment requirements, where one
1267 /// type has the alignment requirement of another type.
1268 virtual unsigned getABIAlignmentForCallingConv(Type *ArgTy,
1269 DataLayout DL) const {
1270 return DL.getABITypeAlignment(ArgTy);
1271 }
1272
1273 /// If true, then instruction selection should seek to shrink the FP constant
1274 /// of the specified type to a smaller type in order to save space and / or
1275 /// reduce runtime.
1276 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
1277
1278 /// Return true if it is profitable to reduce a load to a smaller type.
1279 /// Example: (i16 (trunc (i32 (load x))) -> i16 load x
1280 virtual bool shouldReduceLoadWidth(SDNode *Load, ISD::LoadExtType ExtTy,
1281 EVT NewVT) const {
1282 // By default, assume that it is cheaper to extract a subvector from a wide
1283 // vector load rather than creating multiple narrow vector loads.
1284 if (NewVT.isVector() && !Load->hasOneUse())
1285 return false;
1286
1287 return true;
1288 }
1289
1290 /// When splitting a value of the specified type into parts, does the Lo
1291 /// or Hi part come first? This usually follows the endianness, except
1292 /// for ppcf128, where the Hi part always comes first.
1293 bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const {
1294 return DL.isBigEndian() || VT == MVT::ppcf128;
1295 }
1296
1297 /// If true, the target has custom DAG combine transformations that it can
1298 /// perform for the specified node.
1299 bool hasTargetDAGCombine(ISD::NodeType NT) const {
1300 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray))((unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray
)) ? static_cast<void> (0) : __assert_fail ("unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray)"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1300, __PRETTY_FUNCTION__))
;
1301 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
1302 }
1303
1304 unsigned getGatherAllAliasesMaxDepth() const {
1305 return GatherAllAliasesMaxDepth;
1306 }
1307
1308 /// Returns the size of the platform's va_list object.
1309 virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
1310 return getPointerTy(DL).getSizeInBits();
1311 }
1312
1313 /// Get maximum # of store operations permitted for llvm.memset
1314 ///
1315 /// This function returns the maximum number of store operations permitted
1316 /// to replace a call to llvm.memset. The value is set by the target at the
1317 /// performance threshold for such a replacement. If OptSize is true,
1318 /// return the limit for functions that have OptSize attribute.
1319 unsigned getMaxStoresPerMemset(bool OptSize) const {
1320 return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
1321 }
1322
1323 /// Get maximum # of store operations permitted for llvm.memcpy
1324 ///
1325 /// This function returns the maximum number of store operations permitted
1326 /// to replace a call to llvm.memcpy. The value is set by the target at the
1327 /// performance threshold for such a replacement. If OptSize is true,
1328 /// return the limit for functions that have OptSize attribute.
1329 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
1330 return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
1331 }
1332
1333 /// \brief Get maximum # of store operations to be glued together
1334 ///
1335 /// This function returns the maximum number of store operations permitted
1336 /// to glue together during lowering of llvm.memcpy. The value is set by
1337 // the target at the performance threshold for such a replacement.
1338 virtual unsigned getMaxGluedStoresPerMemcpy() const {
1339 return MaxGluedStoresPerMemcpy;
1340 }
1341
1342 /// Get maximum # of load operations permitted for memcmp
1343 ///
1344 /// This function returns the maximum number of load operations permitted
1345 /// to replace a call to memcmp. The value is set by the target at the
1346 /// performance threshold for such a replacement. If OptSize is true,
1347 /// return the limit for functions that have OptSize attribute.
1348 unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
1349 return OptSize ? MaxLoadsPerMemcmpOptSize : MaxLoadsPerMemcmp;
1350 }
1351
1352 /// For memcmp expansion when the memcmp result is only compared equal or
1353 /// not-equal to 0, allow up to this number of load pairs per block. As an
1354 /// example, this may allow 'memcmp(a, b, 3) == 0' in a single block:
1355 /// a0 = load2bytes &a[0]
1356 /// b0 = load2bytes &b[0]
1357 /// a2 = load1byte &a[2]
1358 /// b2 = load1byte &b[2]
1359 /// r = cmp eq (a0 ^ b0 | a2 ^ b2), 0
1360 virtual unsigned getMemcmpEqZeroLoadsPerBlock() const {
1361 return 1;
1362 }
1363
1364 /// Get maximum # of store operations permitted for llvm.memmove
1365 ///
1366 /// This function returns the maximum number of store operations permitted
1367 /// to replace a call to llvm.memmove. The value is set by the target at the
1368 /// performance threshold for such a replacement. If OptSize is true,
1369 /// return the limit for functions that have OptSize attribute.
1370 unsigned getMaxStoresPerMemmove(bool OptSize) const {
1371 return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
1372 }
1373
1374 /// Determine if the target supports unaligned memory accesses.
1375 ///
1376 /// This function returns true if the target allows unaligned memory accesses
1377 /// of the specified type in the given address space. If true, it also returns
1378 /// whether the unaligned memory access is "fast" in the last argument by
1379 /// reference. This is used, for example, in situations where an array
1380 /// copy/move/set is converted to a sequence of store operations. Its use
1381 /// helps to ensure that such replacements don't generate code that causes an
1382 /// alignment error (trap) on the target machine.
1383 virtual bool allowsMisalignedMemoryAccesses(EVT,
1384 unsigned AddrSpace = 0,
1385 unsigned Align = 1,
1386 bool * /*Fast*/ = nullptr) const {
1387 return false;
1388 }
1389
1390 /// Return true if the target supports a memory access of this type for the
1391 /// given address space and alignment. If the access is allowed, the optional
1392 /// final parameter returns if the access is also fast (as defined by the
1393 /// target).
1394 bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1395 unsigned AddrSpace = 0, unsigned Alignment = 1,
1396 bool *Fast = nullptr) const;
1397
1398 /// Returns the target specific optimal type for load and store operations as
1399 /// a result of memset, memcpy, and memmove lowering.
1400 ///
1401 /// If DstAlign is zero that means it's safe to destination alignment can
1402 /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
1403 /// a need to check it against alignment requirement, probably because the
1404 /// source does not need to be loaded. If 'IsMemset' is true, that means it's
1405 /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
1406 /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
1407 /// does not need to be loaded. It returns EVT::Other if the type should be
1408 /// determined using generic target-independent logic.
1409 virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
1410 unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
1411 bool /*IsMemset*/,
1412 bool /*ZeroMemset*/,
1413 bool /*MemcpyStrSrc*/,
1414 MachineFunction &/*MF*/) const {
1415 return MVT::Other;
1416 }
1417
1418 /// Returns true if it's safe to use load / store of the specified type to
1419 /// expand memcpy / memset inline.
1420 ///
1421 /// This is mostly true for all types except for some special cases. For
1422 /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
1423 /// fstpl which also does type conversion. Note the specified type doesn't
1424 /// have to be legal as the hook is used before type legalization.
1425 virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
1426
1427 /// Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
1428 bool usesUnderscoreSetJmp() const {
1429 return UseUnderscoreSetJmp;
1430 }
1431
1432 /// Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
1433 bool usesUnderscoreLongJmp() const {
1434 return UseUnderscoreLongJmp;
1435 }
1436
1437 /// Return lower limit for number of blocks in a jump table.
1438 virtual unsigned getMinimumJumpTableEntries() const;
1439
1440 /// Return lower limit of the density in a jump table.
1441 unsigned getMinimumJumpTableDensity(bool OptForSize) const;
1442
1443 /// Return upper limit for number of entries in a jump table.
1444 /// Zero if no limit.
1445 unsigned getMaximumJumpTableSize() const;
1446
1447 virtual bool isJumpTableRelative() const {
1448 return TM.isPositionIndependent();
1449 }
1450
1451 /// If a physical register, this specifies the register that
1452 /// llvm.savestack/llvm.restorestack should save and restore.
1453 unsigned getStackPointerRegisterToSaveRestore() const {
1454 return StackPointerRegisterToSaveRestore;
1455 }
1456
1457 /// If a physical register, this returns the register that receives the
1458 /// exception address on entry to an EH pad.
1459 virtual unsigned
1460 getExceptionPointerRegister(const Constant *PersonalityFn) const {
1461 // 0 is guaranteed to be the NoRegister value on all targets
1462 return 0;
1463 }
1464
1465 /// If a physical register, this returns the register that receives the
1466 /// exception typeid on entry to a landing pad.
1467 virtual unsigned
1468 getExceptionSelectorRegister(const Constant *PersonalityFn) const {
1469 // 0 is guaranteed to be the NoRegister value on all targets
1470 return 0;
1471 }
1472
1473 virtual bool needsFixedCatchObjects() const {
1474 report_fatal_error("Funclet EH is not implemented for this target");
1475 }
1476
1477 /// Returns the target's jmp_buf size in bytes (if never set, the default is
1478 /// 200)
1479 unsigned getJumpBufSize() const {
1480 return JumpBufSize;
1481 }
1482
1483 /// Returns the target's jmp_buf alignment in bytes (if never set, the default
1484 /// is 0)
1485 unsigned getJumpBufAlignment() const {
1486 return JumpBufAlignment;
1487 }
1488
1489 /// Return the minimum stack alignment of an argument.
1490 unsigned getMinStackArgumentAlignment() const {
1491 return MinStackArgumentAlignment;
1492 }
1493
1494 /// Return the minimum function alignment.
1495 unsigned getMinFunctionAlignment() const {
1496 return MinFunctionAlignment;
1497 }
1498
1499 /// Return the preferred function alignment.
1500 unsigned getPrefFunctionAlignment() const {
1501 return PrefFunctionAlignment;
1502 }
1503
1504 /// Return the preferred loop alignment.
1505 virtual unsigned getPrefLoopAlignment(MachineLoop *ML = nullptr) const {
1506 return PrefLoopAlignment;
1507 }
1508
1509 /// Should loops be aligned even when the function is marked OptSize (but not
1510 /// MinSize).
1511 virtual bool alignLoopsWithOptSize() const {
1512 return false;
1513 }
1514
1515 /// If the target has a standard location for the stack protector guard,
1516 /// returns the address of that location. Otherwise, returns nullptr.
1517 /// DEPRECATED: please override useLoadStackGuardNode and customize
1518 /// LOAD_STACK_GUARD, or customize \@llvm.stackguard().
1519 virtual Value *getIRStackGuard(IRBuilder<> &IRB) const;
1520
1521 /// Inserts necessary declarations for SSP (stack protection) purpose.
1522 /// Should be used only when getIRStackGuard returns nullptr.
1523 virtual void insertSSPDeclarations(Module &M) const;
1524
1525 /// Return the variable that's previously inserted by insertSSPDeclarations,
1526 /// if any, otherwise return nullptr. Should be used only when
1527 /// getIRStackGuard returns nullptr.
1528 virtual Value *getSDagStackGuard(const Module &M) const;
1529
1530 /// If this function returns true, stack protection checks should XOR the
1531 /// frame pointer (or whichever pointer is used to address locals) into the
1532 /// stack guard value before checking it. getIRStackGuard must return nullptr
1533 /// if this returns true.
1534 virtual bool useStackGuardXorFP() const { return false; }
1535
1536 /// If the target has a standard stack protection check function that
1537 /// performs validation and error handling, returns the function. Otherwise,
1538 /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
1539 /// Should be used only when getIRStackGuard returns nullptr.
1540 virtual Function *getSSPStackGuardCheck(const Module &M) const;
1541
1542protected:
1543 Value *getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
1544 bool UseTLS) const;
1545
1546public:
1547 /// Returns the target-specific address of the unsafe stack pointer.
1548 virtual Value *getSafeStackPointerLocation(IRBuilder<> &IRB) const;
1549
1550 /// Returns the name of the symbol used to emit stack probes or the empty
1551 /// string if not applicable.
1552 virtual StringRef getStackProbeSymbolName(MachineFunction &MF) const {
1553 return "";
1554 }
1555
1556 /// Returns true if a cast between SrcAS and DestAS is a noop.
1557 virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
1558 return false;
1559 }
1560
1561 /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
1562 /// are happy to sink it into basic blocks.
1563 virtual bool isCheapAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
1564 return isNoopAddrSpaceCast(SrcAS, DestAS);
1565 }
1566
1567 /// Return true if the pointer arguments to CI should be aligned by aligning
1568 /// the object whose address is being passed. If so then MinSize is set to the
1569 /// minimum size the object must be to be aligned and PrefAlign is set to the
1570 /// preferred alignment.
1571 virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
1572 unsigned & /*PrefAlign*/) const {
1573 return false;
1574 }
1575
1576 //===--------------------------------------------------------------------===//
1577 /// \name Helpers for TargetTransformInfo implementations
1578 /// @{
1579
1580 /// Get the ISD node that corresponds to the Instruction class opcode.
1581 int InstructionOpcodeToISD(unsigned Opcode) const;
1582
1583 /// Estimate the cost of type-legalization and the legalized type.
1584 std::pair<int, MVT> getTypeLegalizationCost(const DataLayout &DL,
1585 Type *Ty) const;
1586
1587 /// @}
1588
1589 //===--------------------------------------------------------------------===//
1590 /// \name Helpers for atomic expansion.
1591 /// @{
1592
1593 /// Returns the maximum atomic operation size (in bits) supported by
1594 /// the backend. Atomic operations greater than this size (as well
1595 /// as ones that are not naturally aligned), will be expanded by
1596 /// AtomicExpandPass into an __atomic_* library call.
1597 unsigned getMaxAtomicSizeInBitsSupported() const {
1598 return MaxAtomicSizeInBitsSupported;
1599 }
1600
1601 /// Returns the size of the smallest cmpxchg or ll/sc instruction
1602 /// the backend supports. Any smaller operations are widened in
1603 /// AtomicExpandPass.
1604 ///
1605 /// Note that *unlike* operations above the maximum size, atomic ops
1606 /// are still natively supported below the minimum; they just
1607 /// require a more complex expansion.
1608 unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
1609
1610 /// Whether the target supports unaligned atomic operations.
1611 bool supportsUnalignedAtomics() const { return SupportsUnalignedAtomics; }
1612
1613 /// Whether AtomicExpandPass should automatically insert fences and reduce
1614 /// ordering for this atomic. This should be true for most architectures with
1615 /// weak memory ordering. Defaults to false.
1616 virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
1617 return false;
1618 }
1619
1620 /// Perform a load-linked operation on Addr, returning a "Value *" with the
1621 /// corresponding pointee type. This may entail some non-trivial operations to
1622 /// truncate or reconstruct types that will be illegal in the backend. See
1623 /// ARMISelLowering for an example implementation.
1624 virtual Value *emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
1625 AtomicOrdering Ord) const {
1626 llvm_unreachable("Load linked unimplemented on this target")::llvm::llvm_unreachable_internal("Load linked unimplemented on this target"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1626)
;
1627 }
1628
1629 /// Perform a store-conditional operation to Addr. Return the status of the
1630 /// store. This should be 0 if the store succeeded, non-zero otherwise.
1631 virtual Value *emitStoreConditional(IRBuilder<> &Builder, Value *Val,
1632 Value *Addr, AtomicOrdering Ord) const {
1633 llvm_unreachable("Store conditional unimplemented on this target")::llvm::llvm_unreachable_internal("Store conditional unimplemented on this target"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1633)
;
1634 }
1635
1636 /// Perform a masked atomicrmw using a target-specific intrinsic. This
1637 /// represents the core LL/SC loop which will be lowered at a late stage by
1638 /// the backend.
1639 virtual Value *emitMaskedAtomicRMWIntrinsic(IRBuilder<> &Builder,
1640 AtomicRMWInst *AI,
1641 Value *AlignedAddr, Value *Incr,
1642 Value *Mask, Value *ShiftAmt,
1643 AtomicOrdering Ord) const {
1644 llvm_unreachable("Masked atomicrmw expansion unimplemented on this target")::llvm::llvm_unreachable_internal("Masked atomicrmw expansion unimplemented on this target"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1644)
;
1645 }
1646
1647 /// Perform a masked cmpxchg using a target-specific intrinsic. This
1648 /// represents the core LL/SC loop which will be lowered at a late stage by
1649 /// the backend.
1650 virtual Value *emitMaskedAtomicCmpXchgIntrinsic(
1651 IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
1652 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
1653 llvm_unreachable("Masked cmpxchg expansion unimplemented on this target")::llvm::llvm_unreachable_internal("Masked cmpxchg expansion unimplemented on this target"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1653)
;
1654 }
1655
1656 /// Inserts in the IR a target-specific intrinsic specifying a fence.
1657 /// It is called by AtomicExpandPass before expanding an
1658 /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
1659 /// if shouldInsertFencesForAtomic returns true.
1660 ///
1661 /// Inst is the original atomic instruction, prior to other expansions that
1662 /// may be performed.
1663 ///
1664 /// This function should either return a nullptr, or a pointer to an IR-level
1665 /// Instruction*. Even complex fence sequences can be represented by a
1666 /// single Instruction* through an intrinsic to be lowered later.
1667 /// Backends should override this method to produce target-specific intrinsic
1668 /// for their fences.
1669 /// FIXME: Please note that the default implementation here in terms of
1670 /// IR-level fences exists for historical/compatibility reasons and is
1671 /// *unsound* ! Fences cannot, in general, be used to restore sequential
1672 /// consistency. For example, consider the following example:
1673 /// atomic<int> x = y = 0;
1674 /// int r1, r2, r3, r4;
1675 /// Thread 0:
1676 /// x.store(1);
1677 /// Thread 1:
1678 /// y.store(1);
1679 /// Thread 2:
1680 /// r1 = x.load();
1681 /// r2 = y.load();
1682 /// Thread 3:
1683 /// r3 = y.load();
1684 /// r4 = x.load();
1685 /// r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
1686 /// seq_cst. But if they are lowered to monotonic accesses, no amount of
1687 /// IR-level fences can prevent it.
1688 /// @{
1689 virtual Instruction *emitLeadingFence(IRBuilder<> &Builder, Instruction *Inst,
1690 AtomicOrdering Ord) const {
1691 if (isReleaseOrStronger(Ord) && Inst->hasAtomicStore())
1692 return Builder.CreateFence(Ord);
1693 else
1694 return nullptr;
1695 }
1696
1697 virtual Instruction *emitTrailingFence(IRBuilder<> &Builder,
1698 Instruction *Inst,
1699 AtomicOrdering Ord) const {
1700 if (isAcquireOrStronger(Ord))
1701 return Builder.CreateFence(Ord);
1702 else
1703 return nullptr;
1704 }
1705 /// @}
1706
1707 // Emits code that executes when the comparison result in the ll/sc
1708 // expansion of a cmpxchg instruction is such that the store-conditional will
1709 // not execute. This makes it possible to balance out the load-linked with
1710 // a dedicated instruction, if desired.
1711 // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
1712 // be unnecessarily held, except if clrex, inserted by this hook, is executed.
1713 virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilder<> &Builder) const {}
1714
1715 /// Returns true if the given (atomic) store should be expanded by the
1716 /// IR-level AtomicExpand pass into an "atomic xchg" which ignores its input.
1717 virtual bool shouldExpandAtomicStoreInIR(StoreInst *SI) const {
1718 return false;
1719 }
1720
1721 /// Returns true if arguments should be sign-extended in lib calls.
1722 virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
1723 return IsSigned;
1724 }
1725
1726 /// Returns how the given (atomic) load should be expanded by the
1727 /// IR-level AtomicExpand pass.
1728 virtual AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const {
1729 return AtomicExpansionKind::None;
1730 }
1731
1732 /// Returns how the given atomic cmpxchg should be expanded by the IR-level
1733 /// AtomicExpand pass.
1734 virtual AtomicExpansionKind
1735 shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
1736 return AtomicExpansionKind::None;
1737 }
1738
1739 /// Returns how the IR-level AtomicExpand pass should expand the given
1740 /// AtomicRMW, if at all. Default is to never expand.
1741 virtual AtomicExpansionKind shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
1742 return RMW->isFloatingPointOperation() ?
1743 AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None;
1744 }
1745
1746 /// On some platforms, an AtomicRMW that never actually modifies the value
1747 /// (such as fetch_add of 0) can be turned into a fence followed by an
1748 /// atomic load. This may sound useless, but it makes it possible for the
1749 /// processor to keep the cacheline shared, dramatically improving
1750 /// performance. And such idempotent RMWs are useful for implementing some
1751 /// kinds of locks, see for example (justification + benchmarks):
1752 /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
1753 /// This method tries doing that transformation, returning the atomic load if
1754 /// it succeeds, and nullptr otherwise.
1755 /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
1756 /// another round of expansion.
1757 virtual LoadInst *
1758 lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *RMWI) const {
1759 return nullptr;
1760 }
1761
1762 /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
1763 /// SIGN_EXTEND, or ANY_EXTEND).
1764 virtual ISD::NodeType getExtendForAtomicOps() const {
1765 return ISD::ZERO_EXTEND;
1766 }
1767
1768 /// @}
1769
1770 /// Returns true if we should normalize
1771 /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
1772 /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
1773 /// that it saves us from materializing N0 and N1 in an integer register.
1774 /// Targets that are able to perform and/or on flags should return false here.
1775 virtual bool shouldNormalizeToSelectSequence(LLVMContext &Context,
1776 EVT VT) const {
1777 // If a target has multiple condition registers, then it likely has logical
1778 // operations on those registers.
1779 if (hasMultipleConditionRegisters())
1780 return false;
1781 // Only do the transform if the value won't be split into multiple
1782 // registers.
1783 LegalizeTypeAction Action = getTypeAction(Context, VT);
1784 return Action != TypeExpandInteger && Action != TypeExpandFloat &&
1785 Action != TypeSplitVector;
1786 }
1787
1788 virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const { return true; }
1789
1790 /// Return true if a select of constants (select Cond, C1, C2) should be
1791 /// transformed into simple math ops with the condition value. For example:
1792 /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
1793 virtual bool convertSelectOfConstantsToMath(EVT VT) const {
1794 return false;
1795 }
1796
1797 /// Return true if it is profitable to transform an integer
1798 /// multiplication-by-constant into simpler operations like shifts and adds.
1799 /// This may be true if the target does not directly support the
1800 /// multiplication operation for the specified type or the sequence of simpler
1801 /// ops is faster than the multiply.
1802 virtual bool decomposeMulByConstant(EVT VT, SDValue C) const {
1803 return false;
1804 }
1805
1806 /// Return true if it is more correct/profitable to use strict FP_TO_INT
1807 /// conversion operations - canonicalizing the FP source value instead of
1808 /// converting all cases and then selecting based on value.
1809 /// This may be true if the target throws exceptions for out of bounds
1810 /// conversions or has fast FP CMOV.
1811 virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT,
1812 bool IsSigned) const {
1813 return false;
1814 }
1815
1816 //===--------------------------------------------------------------------===//
1817 // TargetLowering Configuration Methods - These methods should be invoked by
1818 // the derived class constructor to configure this object for the target.
1819 //
1820protected:
1821 /// Specify how the target extends the result of integer and floating point
1822 /// boolean values from i1 to a wider type. See getBooleanContents.
1823 void setBooleanContents(BooleanContent Ty) {
1824 BooleanContents = Ty;
1825 BooleanFloatContents = Ty;
1826 }
1827
1828 /// Specify how the target extends the result of integer and floating point
1829 /// boolean values from i1 to a wider type. See getBooleanContents.
1830 void setBooleanContents(BooleanContent IntTy, BooleanContent FloatTy) {
1831 BooleanContents = IntTy;
1832 BooleanFloatContents = FloatTy;
1833 }
1834
1835 /// Specify how the target extends the result of a vector boolean value from a
1836 /// vector of i1 to a wider type. See getBooleanContents.
1837 void setBooleanVectorContents(BooleanContent Ty) {
1838 BooleanVectorContents = Ty;
1839 }
1840
1841 /// Specify the target scheduling preference.
1842 void setSchedulingPreference(Sched::Preference Pref) {
1843 SchedPreferenceInfo = Pref;
1844 }
1845
1846 /// Indicate whether this target prefers to use _setjmp to implement
1847 /// llvm.setjmp or the version without _. Defaults to false.
1848 void setUseUnderscoreSetJmp(bool Val) {
1849 UseUnderscoreSetJmp = Val;
1850 }
1851
1852 /// Indicate whether this target prefers to use _longjmp to implement
1853 /// llvm.longjmp or the version without _. Defaults to false.
1854 void setUseUnderscoreLongJmp(bool Val) {
1855 UseUnderscoreLongJmp = Val;
1856 }
1857
1858 /// Indicate the minimum number of blocks to generate jump tables.
1859 void setMinimumJumpTableEntries(unsigned Val);
1860
1861 /// Indicate the maximum number of entries in jump tables.
1862 /// Set to zero to generate unlimited jump tables.
1863 void setMaximumJumpTableSize(unsigned);
1864
1865 /// If set to a physical register, this specifies the register that
1866 /// llvm.savestack/llvm.restorestack should save and restore.
1867 void setStackPointerRegisterToSaveRestore(unsigned R) {
1868 StackPointerRegisterToSaveRestore = R;
1869 }
1870
1871 /// Tells the code generator that the target has multiple (allocatable)
1872 /// condition registers that can be used to store the results of comparisons
1873 /// for use by selects and conditional branches. With multiple condition
1874 /// registers, the code generator will not aggressively sink comparisons into
1875 /// the blocks of their users.
1876 void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
1877 HasMultipleConditionRegisters = hasManyRegs;
1878 }
1879
1880 /// Tells the code generator that the target has BitExtract instructions.
1881 /// The code generator will aggressively sink "shift"s into the blocks of
1882 /// their users if the users will generate "and" instructions which can be
1883 /// combined with "shift" to BitExtract instructions.
1884 void setHasExtractBitsInsn(bool hasExtractInsn = true) {
1885 HasExtractBitsInsn = hasExtractInsn;
1886 }
1887
1888 /// Tells the code generator not to expand logic operations on comparison
1889 /// predicates into separate sequences that increase the amount of flow
1890 /// control.
1891 void setJumpIsExpensive(bool isExpensive = true);
1892
1893 /// Tells the code generator that this target supports floating point
1894 /// exceptions and cares about preserving floating point exception behavior.
1895 void setHasFloatingPointExceptions(bool FPExceptions = true) {
1896 HasFloatingPointExceptions = FPExceptions;
1897 }
1898
1899 /// Tells the code generator which bitwidths to bypass.
1900 void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
1901 BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
1902 }
1903
1904 /// Add the specified register class as an available regclass for the
1905 /// specified value type. This indicates the selector can handle values of
1906 /// that class natively.
1907 void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
1908 assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT))(((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT)) ?
static_cast<void> (0) : __assert_fail ("(unsigned)VT.SimpleTy < array_lengthof(RegClassForVT)"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1908, __PRETTY_FUNCTION__))
;
1909 RegClassForVT[VT.SimpleTy] = RC;
1910 }
1911
1912 /// Return the largest legal super-reg register class of the register class
1913 /// for the specified type and its associated "cost".
1914 virtual std::pair<const TargetRegisterClass *, uint8_t>
1915 findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const;
1916
1917 /// Once all of the register classes are added, this allows us to compute
1918 /// derived properties we expose.
1919 void computeRegisterProperties(const TargetRegisterInfo *TRI);
1920
1921 /// Indicate that the specified operation does not work with the specified
1922 /// type and indicate what to do about it. Note that VT may refer to either
1923 /// the type of a result or that of an operand of Op.
1924 void setOperationAction(unsigned Op, MVT VT,
1925 LegalizeAction Action) {
1926 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!")((Op < array_lengthof(OpActions[0]) && "Table isn't big enough!"
) ? static_cast<void> (0) : __assert_fail ("Op < array_lengthof(OpActions[0]) && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1926, __PRETTY_FUNCTION__))
;
1927 OpActions[(unsigned)VT.SimpleTy][Op] = Action;
1928 }
1929
1930 /// Indicate that the specified load with extension does not work with the
1931 /// specified type and indicate what to do about it.
1932 void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
1933 LegalizeAction Action) {
1934 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&((ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid
() && MemVT.isValid() && "Table isn't big enough!"
) ? static_cast<void> (0) : __assert_fail ("ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() && MemVT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1935, __PRETTY_FUNCTION__))
1935 MemVT.isValid() && "Table isn't big enough!")((ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid
() && MemVT.isValid() && "Table isn't big enough!"
) ? static_cast<void> (0) : __assert_fail ("ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() && MemVT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1935, __PRETTY_FUNCTION__))
;
1936 assert((unsigned)Action < 0x10 && "too many bits for bitfield array")(((unsigned)Action < 0x10 && "too many bits for bitfield array"
) ? static_cast<void> (0) : __assert_fail ("(unsigned)Action < 0x10 && \"too many bits for bitfield array\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1936, __PRETTY_FUNCTION__))
;
1937 unsigned Shift = 4 * ExtType;
1938 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
1939 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
1940 }
1941
1942 /// Indicate that the specified truncating store does not work with the
1943 /// specified type and indicate what to do about it.
1944 void setTruncStoreAction(MVT ValVT, MVT MemVT,
1945 LegalizeAction Action) {
1946 assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!")((ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!"
) ? static_cast<void> (0) : __assert_fail ("ValVT.isValid() && MemVT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1946, __PRETTY_FUNCTION__))
;
1947 TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
1948 }
1949
1950 /// Indicate that the specified indexed load does or does not work with the
1951 /// specified type and indicate what to do abort it.
1952 ///
1953 /// NOTE: All indexed mode loads are initialized to Expand in
1954 /// TargetLowering.cpp
1955 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1956 LegalizeAction Action) {
1957 assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&((VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE
&& (unsigned)Action < 0xf && "Table isn't big enough!"
) ? static_cast<void> (0) : __assert_fail ("VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE && (unsigned)Action < 0xf && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1958, __PRETTY_FUNCTION__))
1958 (unsigned)Action < 0xf && "Table isn't big enough!")((VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE
&& (unsigned)Action < 0xf && "Table isn't big enough!"
) ? static_cast<void> (0) : __assert_fail ("VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE && (unsigned)Action < 0xf && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1958, __PRETTY_FUNCTION__))
;
1959 // Load action are kept in the upper half.
1960 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1961 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1962 }
1963
1964 /// Indicate that the specified indexed store does or does not work with the
1965 /// specified type and indicate what to do about it.
1966 ///
1967 /// NOTE: All indexed mode stores are initialized to Expand in
1968 /// TargetLowering.cpp
1969 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1970 LegalizeAction Action) {
1971 assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&((VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE
&& (unsigned)Action < 0xf && "Table isn't big enough!"
) ? static_cast<void> (0) : __assert_fail ("VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE && (unsigned)Action < 0xf && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1972, __PRETTY_FUNCTION__))
1972 (unsigned)Action < 0xf && "Table isn't big enough!")((VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE
&& (unsigned)Action < 0xf && "Table isn't big enough!"
) ? static_cast<void> (0) : __assert_fail ("VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE && (unsigned)Action < 0xf && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1972, __PRETTY_FUNCTION__))
;
1973 // Store action are kept in the lower half.
1974 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1975 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1976 }
1977
1978 /// Indicate that the specified condition code is or isn't supported on the
1979 /// target and indicate what to do about it.
1980 void setCondCodeAction(ISD::CondCode CC, MVT VT,
1981 LegalizeAction Action) {
1982 assert(VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) &&((VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions
) && "Table isn't big enough!") ? static_cast<void
> (0) : __assert_fail ("VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1983, __PRETTY_FUNCTION__))
1983 "Table isn't big enough!")((VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions
) && "Table isn't big enough!") ? static_cast<void
> (0) : __assert_fail ("VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1983, __PRETTY_FUNCTION__))
;
1984 assert((unsigned)Action < 0x10 && "too many bits for bitfield array")(((unsigned)Action < 0x10 && "too many bits for bitfield array"
) ? static_cast<void> (0) : __assert_fail ("(unsigned)Action < 0x10 && \"too many bits for bitfield array\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 1984, __PRETTY_FUNCTION__))
;
1985 /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the 32-bit
1986 /// value and the upper 29 bits index into the second dimension of the array
1987 /// to select what 32-bit value to use.
1988 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1989 CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
1990 CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
1991 }
1992
1993 /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
1994 /// to trying a larger integer/fp until it can find one that works. If that
1995 /// default is insufficient, this method can be used by the target to override
1996 /// the default.
1997 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1998 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1999 }
2000
2001 /// Convenience method to set an operation to Promote and specify the type
2002 /// in a single call.
2003 void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2004 setOperationAction(Opc, OrigVT, Promote);
2005 AddPromotedToType(Opc, OrigVT, DestVT);
2006 }
2007
2008 /// Targets should invoke this method for each target independent node that
2009 /// they want to provide a custom DAG combiner for by implementing the
2010 /// PerformDAGCombine virtual method.
2011 void setTargetDAGCombine(ISD::NodeType NT) {
2012 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray))((unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray
)) ? static_cast<void> (0) : __assert_fail ("unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray)"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 2012, __PRETTY_FUNCTION__))
;
2013 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
2014 }
2015
2016 /// Set the target's required jmp_buf buffer size (in bytes); default is 200
2017 void setJumpBufSize(unsigned Size) {
2018 JumpBufSize = Size;
2019 }
2020
2021 /// Set the target's required jmp_buf buffer alignment (in bytes); default is
2022 /// 0
2023 void setJumpBufAlignment(unsigned Align) {
2024 JumpBufAlignment = Align;
2025 }
2026
2027 /// Set the target's minimum function alignment (in log2(bytes))
2028 void setMinFunctionAlignment(unsigned Align) {
2029 MinFunctionAlignment = Align;
2030 }
2031
2032 /// Set the target's preferred function alignment. This should be set if
2033 /// there is a performance benefit to higher-than-minimum alignment (in
2034 /// log2(bytes))
2035 void setPrefFunctionAlignment(unsigned Align) {
2036 PrefFunctionAlignment = Align;
2037 }
2038
2039 /// Set the target's preferred loop alignment. Default alignment is zero, it
2040 /// means the target does not care about loop alignment. The alignment is
2041 /// specified in log2(bytes). The target may also override
2042 /// getPrefLoopAlignment to provide per-loop values.
2043 void setPrefLoopAlignment(unsigned Align) {
2044 PrefLoopAlignment = Align;
2045 }
2046
2047 /// Set the minimum stack alignment of an argument (in log2(bytes)).
2048 void setMinStackArgumentAlignment(unsigned Align) {
2049 MinStackArgumentAlignment = Align;
2050 }
2051
2052 /// Set the maximum atomic operation size supported by the
2053 /// backend. Atomic operations greater than this size (as well as
2054 /// ones that are not naturally aligned), will be expanded by
2055 /// AtomicExpandPass into an __atomic_* library call.
2056 void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
2057 MaxAtomicSizeInBitsSupported = SizeInBits;
2058 }
2059
2060 /// Sets the minimum cmpxchg or ll/sc size supported by the backend.
2061 void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
2062 MinCmpXchgSizeInBits = SizeInBits;
2063 }
2064
2065 /// Sets whether unaligned atomic operations are supported.
2066 void setSupportsUnalignedAtomics(bool UnalignedSupported) {
2067 SupportsUnalignedAtomics = UnalignedSupported;
2068 }
2069
2070public:
2071 //===--------------------------------------------------------------------===//
2072 // Addressing mode description hooks (used by LSR etc).
2073 //
2074
2075 /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
2076 /// instructions reading the address. This allows as much computation as
2077 /// possible to be done in the address mode for that operand. This hook lets
2078 /// targets also pass back when this should be done on intrinsics which
2079 /// load/store.
2080 virtual bool getAddrModeArguments(IntrinsicInst * /*I*/,
2081 SmallVectorImpl<Value*> &/*Ops*/,
2082 Type *&/*AccessTy*/) const {
2083 return false;
2084 }
2085
2086 /// This represents an addressing mode of:
2087 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
2088 /// If BaseGV is null, there is no BaseGV.
2089 /// If BaseOffs is zero, there is no base offset.
2090 /// If HasBaseReg is false, there is no base register.
2091 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
2092 /// no scale.
2093 struct AddrMode {
2094 GlobalValue *BaseGV = nullptr;
2095 int64_t BaseOffs = 0;
2096 bool HasBaseReg = false;
2097 int64_t Scale = 0;
2098 AddrMode() = default;
2099 };
2100
2101 /// Return true if the addressing mode represented by AM is legal for this
2102 /// target, for a load/store of the specified type.
2103 ///
2104 /// The type may be VoidTy, in which case only return true if the addressing
2105 /// mode is legal for a load/store of any legal type. TODO: Handle
2106 /// pre/postinc as well.
2107 ///
2108 /// If the address space cannot be determined, it will be -1.
2109 ///
2110 /// TODO: Remove default argument
2111 virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
2112 Type *Ty, unsigned AddrSpace,
2113 Instruction *I = nullptr) const;
2114
2115 /// Return the cost of the scaling factor used in the addressing mode
2116 /// represented by AM for this target, for a load/store of the specified type.
2117 ///
2118 /// If the AM is supported, the return value must be >= 0.
2119 /// If the AM is not supported, it returns a negative value.
2120 /// TODO: Handle pre/postinc as well.
2121 /// TODO: Remove default argument
2122 virtual int getScalingFactorCost(const DataLayout &DL, const AddrMode &AM,
2123 Type *Ty, unsigned AS = 0) const {
2124 // Default: assume that any scaling factor used in a legal AM is free.
2125 if (isLegalAddressingMode(DL, AM, Ty, AS))
2126 return 0;
2127 return -1;
2128 }
2129
2130 /// Return true if the specified immediate is legal icmp immediate, that is
2131 /// the target has icmp instructions which can compare a register against the
2132 /// immediate without having to materialize the immediate into a register.
2133 virtual bool isLegalICmpImmediate(int64_t) const {
2134 return true;
2135 }
2136
2137 /// Return true if the specified immediate is legal add immediate, that is the
2138 /// target has add instructions which can add a register with the immediate
2139 /// without having to materialize the immediate into a register.
2140 virtual bool isLegalAddImmediate(int64_t) const {
2141 return true;
2142 }
2143
2144 /// Return true if the specified immediate is legal for the value input of a
2145 /// store instruction.
2146 virtual bool isLegalStoreImmediate(int64_t Value) const {
2147 // Default implementation assumes that at least 0 works since it is likely
2148 // that a zero register exists or a zero immediate is allowed.
2149 return Value == 0;
2150 }
2151
2152 /// Return true if it's significantly cheaper to shift a vector by a uniform
2153 /// scalar than by an amount which will vary across each lane. On x86, for
2154 /// example, there is a "psllw" instruction for the former case, but no simple
2155 /// instruction for a general "a << b" operation on vectors.
2156 virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
2157 return false;
2158 }
2159
2160 /// Returns true if the opcode is a commutative binary operation.
2161 virtual bool isCommutativeBinOp(unsigned Opcode) const {
2162 // FIXME: This should get its info from the td file.
2163 switch (Opcode) {
2164 case ISD::ADD:
2165 case ISD::SMIN:
2166 case ISD::SMAX:
2167 case ISD::UMIN:
2168 case ISD::UMAX:
2169 case ISD::MUL:
2170 case ISD::MULHU:
2171 case ISD::MULHS:
2172 case ISD::SMUL_LOHI:
2173 case ISD::UMUL_LOHI:
2174 case ISD::FADD:
2175 case ISD::FMUL:
2176 case ISD::AND:
2177 case ISD::OR:
2178 case ISD::XOR:
2179 case ISD::SADDO:
2180 case ISD::UADDO:
2181 case ISD::ADDC:
2182 case ISD::ADDE:
2183 case ISD::SADDSAT:
2184 case ISD::UADDSAT:
2185 case ISD::FMINNUM:
2186 case ISD::FMAXNUM:
2187 case ISD::FMINIMUM:
2188 case ISD::FMAXIMUM:
2189 return true;
2190 default: return false;
2191 }
2192 }
2193
2194 /// Return true if it's free to truncate a value of type FromTy to type
2195 /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
2196 /// by referencing its sub-register AX.
2197 /// Targets must return false when FromTy <= ToTy.
2198 virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
2199 return false;
2200 }
2201
2202 /// Return true if a truncation from FromTy to ToTy is permitted when deciding
2203 /// whether a call is in tail position. Typically this means that both results
2204 /// would be assigned to the same register or stack slot, but it could mean
2205 /// the target performs adequate checks of its own before proceeding with the
2206 /// tail call. Targets must return false when FromTy <= ToTy.
2207 virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
2208 return false;
2209 }
2210
2211 virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const {
2212 return false;
2213 }
2214
2215 virtual bool isProfitableToHoist(Instruction *I) const { return true; }
2216
2217 /// Return true if the extension represented by \p I is free.
2218 /// Unlikely the is[Z|FP]ExtFree family which is based on types,
2219 /// this method can use the context provided by \p I to decide
2220 /// whether or not \p I is free.
2221 /// This method extends the behavior of the is[Z|FP]ExtFree family.
2222 /// In other words, if is[Z|FP]Free returns true, then this method
2223 /// returns true as well. The converse is not true.
2224 /// The target can perform the adequate checks by overriding isExtFreeImpl.
2225 /// \pre \p I must be a sign, zero, or fp extension.
2226 bool isExtFree(const Instruction *I) const {
2227 switch (I->getOpcode()) {
2228 case Instruction::FPExt:
2229 if (isFPExtFree(EVT::getEVT(I->getType()),
2230 EVT::getEVT(I->getOperand(0)->getType())))
2231 return true;
2232 break;
2233 case Instruction::ZExt:
2234 if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
2235 return true;
2236 break;
2237 case Instruction::SExt:
2238 break;
2239 default:
2240 llvm_unreachable("Instruction is not an extension")::llvm::llvm_unreachable_internal("Instruction is not an extension"
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 2240)
;
2241 }
2242 return isExtFreeImpl(I);
2243 }
2244
2245 /// Return true if \p Load and \p Ext can form an ExtLoad.
2246 /// For example, in AArch64
2247 /// %L = load i8, i8* %ptr
2248 /// %E = zext i8 %L to i32
2249 /// can be lowered into one load instruction
2250 /// ldrb w0, [x0]
2251 bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
2252 const DataLayout &DL) const {
2253 EVT VT = getValueType(DL, Ext->getType());
2254 EVT LoadVT = getValueType(DL, Load->getType());
2255
2256 // If the load has other users and the truncate is not free, the ext
2257 // probably isn't free.
2258 if (!Load->hasOneUse() && (isTypeLegal(LoadVT) || !isTypeLegal(VT)) &&
2259 !isTruncateFree(Ext->getType(), Load->getType()))
2260 return false;
2261
2262 // Check whether the target supports casts folded into loads.
2263 unsigned LType;
2264 if (isa<ZExtInst>(Ext))
2265 LType = ISD::ZEXTLOAD;
2266 else {
2267 assert(isa<SExtInst>(Ext) && "Unexpected ext type!")((isa<SExtInst>(Ext) && "Unexpected ext type!")
? static_cast<void> (0) : __assert_fail ("isa<SExtInst>(Ext) && \"Unexpected ext type!\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 2267, __PRETTY_FUNCTION__))
;
2268 LType = ISD::SEXTLOAD;
2269 }
2270
2271 return isLoadExtLegal(LType, VT, LoadVT);
2272 }
2273
2274 /// Return true if any actual instruction that defines a value of type FromTy
2275 /// implicitly zero-extends the value to ToTy in the result register.
2276 ///
2277 /// The function should return true when it is likely that the truncate can
2278 /// be freely folded with an instruction defining a value of FromTy. If
2279 /// the defining instruction is unknown (because you're looking at a
2280 /// function argument, PHI, etc.) then the target may require an
2281 /// explicit truncate, which is not necessarily free, but this function
2282 /// does not deal with those cases.
2283 /// Targets must return false when FromTy >= ToTy.
2284 virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
2285 return false;
2286 }
2287
2288 virtual bool isZExtFree(EVT FromTy, EVT ToTy) const {
2289 return false;
2290 }
2291
2292 /// Return true if sign-extension from FromTy to ToTy is cheaper than
2293 /// zero-extension.
2294 virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const {
2295 return false;
2296 }
2297
2298 /// Return true if sinking I's operands to the same basic block as I is
2299 /// profitable, e.g. because the operands can be folded into a target
2300 /// instruction during instruction selection. After calling the function
2301 /// \p Ops contains the Uses to sink ordered by dominance (dominating users
2302 /// come first).
2303 virtual bool shouldSinkOperands(Instruction *I,
2304 SmallVectorImpl<Use *> &Ops) const {
2305 return false;
2306 }
2307
2308 /// Return true if the target supplies and combines to a paired load
2309 /// two loaded values of type LoadedType next to each other in memory.
2310 /// RequiredAlignment gives the minimal alignment constraints that must be met
2311 /// to be able to select this paired load.
2312 ///
2313 /// This information is *not* used to generate actual paired loads, but it is
2314 /// used to generate a sequence of loads that is easier to combine into a
2315 /// paired load.
2316 /// For instance, something like this:
2317 /// a = load i64* addr
2318 /// b = trunc i64 a to i32
2319 /// c = lshr i64 a, 32
2320 /// d = trunc i64 c to i32
2321 /// will be optimized into:
2322 /// b = load i32* addr1
2323 /// d = load i32* addr2
2324 /// Where addr1 = addr2 +/- sizeof(i32).
2325 ///
2326 /// In other words, unless the target performs a post-isel load combining,
2327 /// this information should not be provided because it will generate more
2328 /// loads.
2329 virtual bool hasPairedLoad(EVT /*LoadedType*/,
2330 unsigned & /*RequiredAlignment*/) const {
2331 return false;
2332 }
2333
2334 /// Return true if the target has a vector blend instruction.
2335 virtual bool hasVectorBlend() const { return false; }
2336
2337 /// Get the maximum supported factor for interleaved memory accesses.
2338 /// Default to be the minimum interleave factor: 2.
2339 virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
2340
2341 /// Lower an interleaved load to target specific intrinsics. Return
2342 /// true on success.
2343 ///
2344 /// \p LI is the vector load instruction.
2345 /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
2346 /// \p Indices is the corresponding indices for each shufflevector.
2347 /// \p Factor is the interleave factor.
2348 virtual bool lowerInterleavedLoad(LoadInst *LI,
2349 ArrayRef<ShuffleVectorInst *> Shuffles,
2350 ArrayRef<unsigned> Indices,
2351 unsigned Factor) const {
2352 return false;
2353 }
2354
2355 /// Lower an interleaved store to target specific intrinsics. Return
2356 /// true on success.
2357 ///
2358 /// \p SI is the vector store instruction.
2359 /// \p SVI is the shufflevector to RE-interleave the stored vector.
2360 /// \p Factor is the interleave factor.
2361 virtual bool lowerInterleavedStore(StoreInst *SI, ShuffleVectorInst *SVI,
2362 unsigned Factor) const {
2363 return false;
2364 }
2365
2366 /// Return true if zero-extending the specific node Val to type VT2 is free
2367 /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
2368 /// because it's folded such as X86 zero-extending loads).
2369 virtual bool isZExtFree(SDValue Val, EVT VT2) const {
2370 return isZExtFree(Val.getValueType(), VT2);
2371 }
2372
2373 /// Return true if an fpext operation is free (for instance, because
2374 /// single-precision floating-point numbers are implicitly extended to
2375 /// double-precision).
2376 virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const {
2377 assert(SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() &&((SrcVT.isFloatingPoint() && DestVT.isFloatingPoint()
&& "invalid fpext types") ? static_cast<void> (
0) : __assert_fail ("SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() && \"invalid fpext types\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 2378, __PRETTY_FUNCTION__))
2378 "invalid fpext types")((SrcVT.isFloatingPoint() && DestVT.isFloatingPoint()
&& "invalid fpext types") ? static_cast<void> (
0) : __assert_fail ("SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() && \"invalid fpext types\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 2378, __PRETTY_FUNCTION__))
;
2379 return false;
2380 }
2381
2382 /// Return true if an fpext operation input to an \p Opcode operation is free
2383 /// (for instance, because half-precision floating-point numbers are
2384 /// implicitly extended to float-precision) for an FMA instruction.
2385 virtual bool isFPExtFoldable(unsigned Opcode, EVT DestVT, EVT SrcVT) const {
2386 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&((DestVT.isFloatingPoint() && SrcVT.isFloatingPoint()
&& "invalid fpext types") ? static_cast<void> (
0) : __assert_fail ("DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && \"invalid fpext types\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 2387, __PRETTY_FUNCTION__))
2387 "invalid fpext types")((DestVT.isFloatingPoint() && SrcVT.isFloatingPoint()
&& "invalid fpext types") ? static_cast<void> (
0) : __assert_fail ("DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && \"invalid fpext types\""
, "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 2387, __PRETTY_FUNCTION__))
;
2388 return isFPExtFree(DestVT, SrcVT);
2389 }
2390
2391 /// Return true if folding a vector load into ExtVal (a sign, zero, or any
2392 /// extend node) is profitable.
2393 virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
2394
2395 /// Return true if an fneg operation is free to the point where it is never
2396 /// worthwhile to replace it with a bitwise operation.
2397 virtual bool isFNegFree(EVT VT) const {
2398 assert(VT.isFloatingPoint())((VT.isFloatingPoint()) ? static_cast<void> (0) : __assert_fail
("VT.isFloatingPoint()", "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 2398, __PRETTY_FUNCTION__))
;
2399 return false;
2400 }
2401
2402 /// Return true if an fabs operation is free to the point where it is never
2403 /// worthwhile to replace it with a bitwise operation.
2404 virtual bool isFAbsFree(EVT VT) const {
2405 assert(VT.isFloatingPoint())((VT.isFloatingPoint()) ? static_cast<void> (0) : __assert_fail
("VT.isFloatingPoint()", "/build/llvm-toolchain-snapshot-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 2405, __PRETTY_FUNCTION__))
;
2406 return false;
2407 }
2408
2409 /// Return true if an FMA operation is faster than a pair of fmul and fadd
2410 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
2411 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
2412 ///
2413 /// NOTE: This may be called before legalization on types for which FMAs are
2414 /// not legal, but should return true if those types will eventually legalize
2415 /// to types that support FMAs. After legalization, it will only be called on
2416 /// types that support FMAs (via Legal or Custom actions)
2417 virtual bool isFMAFasterThanFMulAndFAdd(EVT) const {
2418 return false;
2419 }
2420
2421 /// Return true if it's profitable to narrow operations of type VT1 to
2422 /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
2423 /// i32 to i16.
2424 virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
2425 return false;
2426 }
2427
2428 /// Return true if it is beneficial to convert a load of a constant to
2429 /// just the constant itself.
2430 /// On some targets it might be more efficient to use a combination of
2431 /// arithmetic instructions to materialize the constant instead of loading it
2432 /// from a constant pool.
2433 virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
2434 Type *Ty) const {
2435 return false;
2436 }
2437
2438 /// Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type
2439 /// from this source type with this index. This is needed because
2440 /// EXTRACT_SUBVECTOR usually has custom lowering that depends on the index of
2441 /// the first element, and only the target knows which lowering is cheap.
2442 virtual bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
2443 unsigned Index) const {
2444 return false;
2445 }
2446
2447 /// Try to convert an extract element of a vector binary operation into an
2448 /// extract element followed by a scalar operation.
2449 virtual bool shouldScalarizeBinop(SDValue VecOp) const {
2450 return false;
2451 }
2452
2453 /// Return true if extraction of a scalar element from the given vector type
2454 /// at the given index is cheap. For example, if scalar operations occur on
2455 /// the same register file as vector operations, then an extract element may
2456 /// be a sub-register rename rather than an actual instruction.
2457 virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const {
2458 return false;
2459 }
2460
2461 /// Try to convert math with an overflow comparison into the corresponding DAG
2462 /// node operation. Targets may want to override this independently of whether
2463 /// the operation is legal/custom for the given type because it may obscure
2464 /// matching of other patterns.
2465 virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT) const {
2466 // TODO: The default logic is inherited from code in CodeGenPrepare.
2467 // The opcode should not make a difference by default?
2468 if (Opcode != ISD::UADDO)
2469 return false;
2470
2471 // Allow the transform as long as we have an integer type that is not
2472 // obviously illegal and unsupported.
2473 if (VT.isVector())
2474 return false;
2475 return VT.isSimple() || !isOperationExpand(Opcode, VT);
2476 }
2477
2478 // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
2479 // even if the vector itself has multiple uses.
2480 virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
2481 return false;
2482 }
2483
2484 // Return true if CodeGenPrepare should consider splitting large offset of a
2485 // GEP to make the GEP fit into the addressing mode and can be sunk into the
2486 // same blocks of its users.
2487 virtual bool shouldConsiderGEPOffsetSplit() const { return false; }
2488
2489 //===--------------------------------------------------------------------===//
2490 // Runtime Library hooks
2491 //
2492
2493 /// Rename the default libcall routine name for the specified libcall.
2494 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
2495 LibcallRoutineNames[Call] = Name;
2496 }
2497
2498 /// Get the libcall routine name for the specified libcall.
2499 const char *getLibcallName(RTLIB::Libcall Call) const {
2500 return LibcallRoutineNames[Call];
2501 }
2502
2503 /// Override the default CondCode to be used to test the result of the
2504 /// comparison libcall against zero.
2505 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
2506 CmpLibcallCCs[Call] = CC;
2507 }
2508
2509 /// Get the CondCode that's to be used to test the result of the comparison
2510 /// libcall against zero.
2511 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
2512 return CmpLibcallCCs[Call];
2513 }
2514
2515 /// Set the CallingConv that should be used for the specified libcall.
2516 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
2517 LibcallCallingConvs[Call] = CC;
2518 }
2519
2520 /// Get the CallingConv that should be used for the specified libcall.
2521 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
2522 return LibcallCallingConvs[Call];
2523 }
2524
2525 /// Execute target specific actions to finalize target lowering.
2526 /// This is used to set extra flags in MachineFrameInformation and freezing
2527 /// the set of reserved registers.
2528 /// The default implementation just freezes the set of reserved registers.
2529 virtual void finalizeLowering(MachineFunction &MF) const;
2530
2531private:
2532 const TargetMachine &TM;
2533
2534 /// Tells the code generator that the target has multiple (allocatable)
2535 /// condition registers that can be used to store the results of comparisons
2536 /// for use by selects and conditional branches. With multiple condition
2537 /// registers, the code generator will not aggressively sink comparisons into
2538 /// the blocks of their users.
2539 bool HasMultipleConditionRegisters;
2540
2541 /// Tells the code generator that the target has BitExtract instructions.
2542 /// The code generator will aggressively sink "shift"s into the blocks of
2543 /// their users if the users will generate "and" instructions which can be
2544 /// combined with "shift" to BitExtract instructions.
2545 bool HasExtractBitsInsn;
2546
2547 /// Tells the code generator to bypass slow divide or remainder
2548 /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
2549 /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
2550 /// div/rem when the operands are positive and less than 256.
2551 DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
2552
2553 /// Tells the code generator that it shouldn't generate extra flow control
2554 /// instructions and should attempt to combine flow control instructions via
2555 /// predication.
2556 bool JumpIsExpensive;
2557
2558 /// Whether the target supports or cares about preserving floating point
2559 /// exception behavior.
2560 bool HasFloatingPointExceptions;
2561
2562 /// This target prefers to use _setjmp to implement llvm.setjmp.
2563 ///
2564 /// Defaults to false.
2565 bool UseUnderscoreSetJmp;
2566
2567 /// This target prefers to use _longjmp to implement llvm.longjmp.
2568 ///
2569 /// Defaults to false.
2570 bool UseUnderscoreLongJmp;
2571
2572 /// Information about the contents of the high-bits in boolean values held in
2573 /// a type wider than i1. See getBooleanContents.
2574 BooleanContent BooleanContents;
2575
2576 /// Information about the contents of the high-bits in boolean values held in
2577 /// a type wider than i1. See getBooleanContents.
2578 BooleanContent BooleanFloatContents;
2579
2580 /// Information about the contents of the high-bits in boolean vector values
2581 /// when the element type is wider than i1. See getBooleanContents.
2582 BooleanContent BooleanVectorContents;
2583
2584 /// The target scheduling preference: shortest possible total cycles or lowest
2585 /// register usage.
2586 Sched::Preference SchedPreferenceInfo;
2587
2588 /// The size, in bytes, of the target's jmp_buf buffers
2589 unsigned JumpBufSize;
2590
2591 /// The alignment, in bytes, of the target's jmp_buf buffers
2592 unsigned JumpBufAlignment;
2593
2594 /// The minimum alignment that any argument on the stack needs to have.
2595 unsigned MinStackArgumentAlignment;
2596
2597 /// The minimum function alignment (used when optimizing for size, and to
2598 /// prevent explicitly provided alignment from leading to incorrect code).
2599 unsigned MinFunctionAlignment;
2600
2601 /// The preferred function alignment (used when alignment unspecified and
2602 /// optimizing for speed).
2603 unsigned PrefFunctionAlignment;
2604
2605 /// The preferred loop alignment.
2606 unsigned PrefLoopAlignment;
2607
2608 /// Size in bits of the maximum atomics size the backend supports.
2609 /// Accesses larger than this will be expanded by AtomicExpandPass.
2610 unsigned MaxAtomicSizeInBitsSupported;
2611
2612 /// Size in bits of the minimum cmpxchg or ll/sc operation the
2613 /// backend supports.
2614 unsigned MinCmpXchgSizeInBits;
2615
2616 /// This indicates if the target supports unaligned atomic operations.
2617 bool SupportsUnalignedAtomics;
2618
2619 /// If set to a physical register, this specifies the register that
2620 /// llvm.savestack/llvm.restorestack should save and restore.
2621 unsigned StackPointerRegisterToSaveRestore;
2622
2623 /// This indicates the default register class to use for each ValueType the
2624 /// target supports natively.
2625 const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
2626 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
2627 MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
2628
2629 /// This indicates the "representative" register class to use for each
2630 /// ValueType the target supports natively. This information is used by the
2631 /// scheduler to track register pressure. By default, the representative
2632 /// register class is the largest legal super-reg register class of the
2633 /// register class of the specified type. e.g. On x86, i8, i16, and i32's
2634 /// representative class would be GR32.
2635 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
2636
2637 /// This indicates the "cost" of the "representative" register class for each
2638 /// ValueType. The cost is used by the scheduler to approximate register
2639 /// pressure.
2640 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
2641
2642 /// For any value types we are promoting or expanding, this contains the value
2643 /// type that we are changing to. For Expanded types, this contains one step
2644 /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
2645 /// (e.g. i64 -> i16). For types natively supported by the system, this holds
2646 /// the same type (e.g. i32 -> i32).
2647 MVT TransformToType[MVT::LAST_VALUETYPE];
2648
2649 /// For each operation and each value type, keep a LegalizeAction that
2650 /// indicates how instruction selection should deal with the operation. Most
2651 /// operations are Legal (aka, supported natively by the target), but
2652 /// operations that are not should be described. Note that operations on
2653 /// non-legal value types are not described here.
2654 LegalizeAction OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
2655
2656 /// For each load extension type and each value type, keep a LegalizeAction
2657 /// that indicates how instruction selection should deal with a load of a
2658 /// specific value type and extension type. Uses 4-bits to store the action
2659 /// for each of the 4 load ext types.
2660 uint16_t LoadExtActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2661
2662 /// For each value type pair keep a LegalizeAction that indicates whether a
2663 /// truncating store of a specific value type and truncating type is legal.
2664 LegalizeAction TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2665
2666 /// For each indexed mode and each value type, keep a pair of LegalizeAction
2667 /// that indicates how instruction selection should deal with the load /
2668 /// store.
2669 ///
2670 /// The first dimension is the value_type for the reference. The second
2671 /// dimension represents the various modes for load store.
2672 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
2673
2674 /// For each condition code (ISD::CondCode) keep a LegalizeAction that
2675 /// indicates how instruction selection should deal with the condition code.
2676 ///
2677 /// Because each CC action takes up 4 bits, we need to have the array size be
2678 /// large enough to fit all of the value types. This can be done by rounding
2679 /// up the MVT::LAST_VALUETYPE value to the next multiple of 8.
2680 uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE + 7) / 8];
2681
2682protected:
2683 ValueTypeActionImpl ValueTypeActions;
2684
2685private:
2686 LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
2687
2688 /// Targets can specify ISD nodes that they would like PerformDAGCombine
2689 /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
2690 /// array.
2691 unsigned char
2692 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT8-1)/CHAR_BIT8];
2693
2694 /// For operations that must be promoted to a specific type, this holds the
2695 /// destination type. This map should be sparse, so don't hold it as an
2696 /// array.
2697 ///
2698 /// Targets add entries to this map with AddPromotedToType(..), clients access
2699 /// this with getTypeToPromoteTo(..).
2700 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
2701 PromoteToType;
2702
2703 /// Stores the name each libcall.
2704 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL + 1];
2705
2706 /// The ISD::CondCode that should be used to test the result of each of the
2707 /// comparison libcall against zero.
2708 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
2709
2710 /// Stores the CallingConv that should be used for each libcall.
2711 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
2712
2713 /// Set default libcall names and calling conventions.
2714 void InitLibcalls(const Triple &TT);
2715
2716protected:
2717 /// Return true if the extension represented by \p I is free.
2718 /// \pre \p I is a sign, zero, or fp extension and
2719 /// is[Z|FP]ExtFree of the related types is not true.
2720 virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
2721
2722 /// Depth that GatherAllAliases should should continue looking for chain
2723 /// dependencies when trying to find a more preferable chain. As an
2724 /// approximation, this should be more than the number of consecutive stores
2725 /// expected to be merged.
2726 unsigned GatherAllAliasesMaxDepth;
2727
2728 /// Specify maximum number of store instructions per memset call.
2729 ///
2730 /// When lowering \@llvm.memset this field specifies the maximum number of
2731 /// store operations that may be substituted for the call to memset. Targets
2732 /// must set this value based on the cost threshold for that target. Targets
2733 /// should assume that the memset will be done using as many of the largest
2734 /// store operations first, followed by smaller ones, if necessary, per
2735 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
2736 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
2737 /// store. This only applies to setting a constant array of a constant size.
2738 unsigned MaxStoresPerMemset;
2739
2740 /// Maximum number of stores operations that may be substituted for the call
2741 /// to memset, used for functions with OptSize attribute.
2742 unsigned MaxStoresPerMemsetOptSize;
2743
2744 /// Specify maximum bytes of store instructions per memcpy call.
2745 ///
2746 /// When lowering \@llvm.memcpy this field specifies the maximum number of
2747 /// store operations that may be substituted for a call to memcpy. Targets
2748 /// must set this value based on the cost threshold for that target. Targets
2749 /// should assume that the memcpy will be done using as many of the largest
2750 /// store operations first, followed by smaller ones, if necessary, per
2751 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
2752 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
2753 /// and one 1-byte store. This only applies to copying a constant array of
2754 /// constant size.
2755 unsigned MaxStoresPerMemcpy;
2756
2757
2758 /// \brief Specify max number of store instructions to glue in inlined memcpy.
2759 ///
2760 /// When memcpy is inlined based on MaxStoresPerMemcpy, specify maximum number
2761 /// of store instructions to keep together. This helps in pairing and
2762 // vectorization later on.
2763 unsigned MaxGluedStoresPerMemcpy = 0;
2764
2765 /// Maximum number of store operations that may be substituted for a call to
2766 /// memcpy, used for functions with OptSize attribute.
2767 unsigned MaxStoresPerMemcpyOptSize;
2768 unsigned MaxLoadsPerMemcmp;
2769 unsigned MaxLoadsPerMemcmpOptSize;
2770
2771 /// Specify maximum bytes of store instructions per memmove call.
2772 ///
2773 /// When lowering \@llvm.memmove this field specifies the maximum number of
2774 /// store instructions that may be substituted for a call to memmove. Targets
2775 /// must set this value based on the cost threshold for that target. Targets
2776 /// should assume that the memmove will be done using as many of the largest
2777 /// store operations first, followed by smaller ones, if necessary, per
2778 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
2779 /// with 8-bit alignment would result in nine 1-byte stores. This only
2780 /// applies to copying a constant array of constant size.
2781 unsigned MaxStoresPerMemmove;
2782
2783 /// Maximum number of store instructions that may be substituted for a call to
2784 /// memmove, used for functions with OptSize attribute.
2785 unsigned MaxStoresPerMemmoveOptSize;
2786
2787 /// Tells the code generator that select is more expensive than a branch if
2788 /// the branch is usually predicted right.
2789 bool PredictableSelectIsExpensive;
2790
2791 /// \see enableExtLdPromotion.
2792 bool EnableExtLdPromotion;
2793
2794 /// Return true if the value types that can be represented by the specified
2795 /// register class are all legal.
2796 bool isLegalRC(const TargetRegisterInfo &TRI,
2797 const TargetRegisterClass &RC) const;
2798
2799 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
2800 /// sequence of memory operands that is recognized by PrologEpilogInserter.
2801 MachineBasicBlock *emitPatchPoint(MachineInstr &MI,
2802 MachineBasicBlock *MBB) const;
2803
2804 /// Replace/modify the XRay custom event operands with target-dependent
2805 /// details.
2806 MachineBasicBlock *emitXRayCustomEvent(MachineInstr &MI,
2807 MachineBasicBlock *MBB) const;
2808
2809 /// Replace/modify the XRay typed event operands with target-dependent
2810 /// details.
2811 MachineBasicBlock *emitXRayTypedEvent(MachineInstr &MI,
2812 MachineBasicBlock *MBB) const;
2813};
2814
2815/// This class defines information used to lower LLVM code to legal SelectionDAG
2816/// operators that the target instruction selector can accept natively.
2817///
2818/// This class also defines callbacks that targets must implement to lower
2819/// target-specific constructs to SelectionDAG operators.
2820class TargetLowering : public TargetLoweringBase {
2821public:
2822 struct DAGCombinerInfo;
2823
2824 TargetLowering(const TargetLowering &) = delete;
2825 TargetLowering &operator=(const TargetLowering &) = delete;
2826
2827 /// NOTE: The TargetMachine owns TLOF.
2828 explicit TargetLowering(const TargetMachine &TM);
2829
2830 bool isPositionIndependent() const;
2831
2832 virtual bool isSDNodeSourceOfDivergence(const SDNode *N,
2833 FunctionLoweringInfo *FLI,
2834 LegacyDivergenceAnalysis *DA) const {
2835 return false;
2836 }
2837
2838 virtual bool isSDNodeAlwaysUniform(const SDNode * N) const {
2839 return false;
2840 }
2841
2842 /// Returns true by value, base pointer and offset pointer and addressing mode
2843 /// by reference if the node's address can be legally represented as
2844 /// pre-indexed load / store address.
2845 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
2846 SDValue &/*Offset*/,
2847 ISD::MemIndexedMode &/*AM*/,
2848 SelectionDAG &/*DAG*/) const {
2849 return false;
2850 }
2851
2852 /// Returns true by value, base pointer and offset pointer and addressing mode
2853 /// by reference if this node can be combined with a load / store to form a
2854 /// post-indexed load / store.
2855 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
2856 SDValue &/*Base*/,
2857 SDValue &/*Offset*/,
2858 ISD::MemIndexedMode &/*AM*/,
2859 SelectionDAG &/*DAG*/) const {
2860 return false;
2861 }
2862
2863 /// Return the entry encoding for a jump table in the current function. The
2864 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
2865 virtual unsigned getJumpTableEncoding() const;
2866
2867 virtual const MCExpr *
2868 LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
2869 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
2870 MCContext &/*Ctx*/) const {
2871 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-9~svn358520/include/llvm/CodeGen/TargetLowering.h"
, 2871)
;
2872 }
2873
2874 /// Returns relocation base for the given PIC jumptable.
2875 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
2876 SelectionDAG &DAG) const;
2877
2878 /// This returns the relocation base for the given PIC jumptable, the same as
2879 /// getPICJumpTableRelocBase, but as an MCExpr.
2880 virtual const MCExpr *
2881 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2882 unsigned JTI, MCContext &Ctx) const;
2883
2884 /// Return true if folding a constant offset with the given GlobalAddress is
2885 /// legal. It is frequently not legal in PIC relocation models.
2886 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
2887
2888 bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
2889 SDValue &Chain) const;
2890
2891 void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
2892 SDValue &NewRHS, ISD::CondCode &CCCode,
2893 const SDLoc &DL) const;
2894
2895 /// Returns a pair of (return value, chain).
2896 /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
2897 std::pair<SDValue, SDValue> makeLibCall(
2898 SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, ArrayRef<SDValue> Ops,
2899 bool isSigned, const SDLoc &dl, bool doesNotReturn = false,
2900 bool isReturnValueUsed = true, bool isPostTypeLegalization = false) const;
2901
2902 /// Check whether parameters to a call that are passed in callee saved
2903 /// registers are the same as from the calling function. This needs to be
2904 /// checked for tail call eligibility.
2905 bool parametersInCSRMatch(const MachineRegisterInfo &MRI,
2906 const uint32_t *CallerPreservedMask,
2907 const SmallVectorImpl<CCValAssign> &ArgLocs,
2908 const SmallVectorImpl<SDValue> &OutVals) const;
2909
2910 //===--------------------------------------------------------------------===//
2911 // TargetLowering Optimization Methods
2912 //
2913
2914 /// A convenience struct that encapsulates a DAG, and two SDValues for
2915 /// returning information from TargetLowering to its clients that want to
2916 /// combine.
2917 struct TargetLoweringOpt {
2918 SelectionDAG &DAG;
2919 bool LegalTys;
2920 bool LegalOps;
2921 SDValue Old;
2922 SDValue New;
2923
2924 explicit TargetLoweringOpt(SelectionDAG &InDAG,
2925 bool LT, bool LO) :
2926 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
2927
2928 bool LegalTypes() const { return LegalTys; }
2929 bool LegalOperations() const { return LegalOps; }
2930
2931 bool CombineTo(SDValue O, SDValue N) {
2932 Old = O;
2933 New = N;
2934 return true;
2935 }
2936 };
2937
2938 /// Check to see if the specified operand of the specified instruction is a
2939 /// constant integer. If so, check to see if there are any bits set in the
2940 /// constant that are not demanded. If so, shrink the constant and return
2941 /// true.
2942 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
2943 TargetLoweringOpt &TLO) const;
2944
2945 // Target hook to do target-specific const optimization, which is called by
2946 // ShrinkDemandedConstant. This function should return true if the target
2947 // doesn't want ShrinkDemandedConstant to further optimize the constant.
2948 virtual bool targetShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
2949 TargetLoweringOpt &TLO) const {
2950 return false;
2951 }
2952
2953 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
2954 /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
2955 /// generalized for targets with other types of implicit widening casts.
2956 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
2957 TargetLoweringOpt &TLO) const;
2958
2959 /// Look at Op. At this point, we know that only the DemandedBits bits of the
2960 /// result of Op are ever used downstream. If we can use this information to
2961 /// simplify Op, create a new simplified DAG node and return true, returning
2962 /// the original and new nodes in Old and New. Otherwise, analyze the
2963 /// expression and return a mask of KnownOne and KnownZero bits for the
2964 /// expression (used to simplify the caller). The KnownZero/One bits may only
2965 /// be accurate for those bits in the Demanded masks.
2966 /// \p AssumeSingleUse When this parameter is true, this function will
2967 /// attempt to simplify \p Op even if there are multiple uses.
2968 /// Callers are responsible for correctly updating the DAG based on the
2969 /// results of this function, because simply replacing replacing TLO.Old
2970 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
2971 /// has multiple uses.
2972 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
2973 const APInt &DemandedElts, KnownBits &Known,
2974 TargetLoweringOpt &TLO, unsigned Depth = 0,
2975 bool AssumeSingleUse = false) const;
2976
2977 /// Helper wrapper around SimplifyDemandedBits, demanding all elements.
2978 /// Adds Op back to the worklist upon success.
2979 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
2980 KnownBits &Known, TargetLoweringOpt &TLO,
2981 unsigned Depth = 0,
2982 bool AssumeSingleUse = false) const;
2983
2984 /// Helper wrapper around SimplifyDemandedBits.
2985 /// Adds Op back to the worklist upon success.
2986 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
2987