Bug Summary

File:include/llvm/CodeGen/TargetLowering.h
Warning:line 1190, column 41
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 ARMTargetTransformInfo.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~svn362543/build-llvm/lib/Target/ARM -I /build/llvm-toolchain-snapshot-9~svn362543/lib/Target/ARM -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn362543/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~svn362543/build-llvm/lib/Target/ARM -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn362543=. -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-06-05-060531-1271-1 -x c++ /build/llvm-toolchain-snapshot-9~svn362543/lib/Target/ARM/ARMTargetTransformInfo.cpp -faddrsig

/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/ARM/ARMTargetTransformInfo.cpp

1//===- ARMTargetTransformInfo.cpp - ARM 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 "ARMTargetTransformInfo.h"
10#include "ARMSubtarget.h"
11#include "MCTargetDesc/ARMAddressingModes.h"
12#include "llvm/ADT/APInt.h"
13#include "llvm/ADT/SmallVector.h"
14#include "llvm/Analysis/LoopInfo.h"
15#include "llvm/CodeGen/CostTable.h"
16#include "llvm/CodeGen/ISDOpcodes.h"
17#include "llvm/CodeGen/ValueTypes.h"
18#include "llvm/IR/BasicBlock.h"
19#include "llvm/IR/CallSite.h"
20#include "llvm/IR/DataLayout.h"
21#include "llvm/IR/DerivedTypes.h"
22#include "llvm/IR/Instruction.h"
23#include "llvm/IR/Instructions.h"
24#include "llvm/IR/IntrinsicInst.h"
25#include "llvm/IR/Type.h"
26#include "llvm/MC/SubtargetFeature.h"
27#include "llvm/Support/Casting.h"
28#include "llvm/Support/MachineValueType.h"
29#include "llvm/Target/TargetMachine.h"
30#include <algorithm>
31#include <cassert>
32#include <cstdint>
33#include <utility>
34
35using namespace llvm;
36
37#define DEBUG_TYPE"armtti" "armtti"
38
39bool ARMTTIImpl::areInlineCompatible(const Function *Caller,
40 const Function *Callee) const {
41 const TargetMachine &TM = getTLI()->getTargetMachine();
42 const FeatureBitset &CallerBits =
43 TM.getSubtargetImpl(*Caller)->getFeatureBits();
44 const FeatureBitset &CalleeBits =
45 TM.getSubtargetImpl(*Callee)->getFeatureBits();
46
47 // To inline a callee, all features not in the whitelist must match exactly.
48 bool MatchExact = (CallerBits & ~InlineFeatureWhitelist) ==
49 (CalleeBits & ~InlineFeatureWhitelist);
50 // For features in the whitelist, the callee's features must be a subset of
51 // the callers'.
52 bool MatchSubset = ((CallerBits & CalleeBits) & InlineFeatureWhitelist) ==
53 (CalleeBits & InlineFeatureWhitelist);
54 return MatchExact && MatchSubset;
55}
56
57int ARMTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty) {
58 assert(Ty->isIntegerTy())((Ty->isIntegerTy()) ? static_cast<void> (0) : __assert_fail
("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/ARM/ARMTargetTransformInfo.cpp"
, 58, __PRETTY_FUNCTION__))
;
59
60 unsigned Bits = Ty->getPrimitiveSizeInBits();
61 if (Bits == 0 || Imm.getActiveBits() >= 64)
62 return 4;
63
64 int64_t SImmVal = Imm.getSExtValue();
65 uint64_t ZImmVal = Imm.getZExtValue();
66 if (!ST->isThumb()) {
67 if ((SImmVal >= 0 && SImmVal < 65536) ||
68 (ARM_AM::getSOImmVal(ZImmVal) != -1) ||
69 (ARM_AM::getSOImmVal(~ZImmVal) != -1))
70 return 1;
71 return ST->hasV6T2Ops() ? 2 : 3;
72 }
73 if (ST->isThumb2()) {
74 if ((SImmVal >= 0 && SImmVal < 65536) ||
75 (ARM_AM::getT2SOImmVal(ZImmVal) != -1) ||
76 (ARM_AM::getT2SOImmVal(~ZImmVal) != -1))
77 return 1;
78 return ST->hasV6T2Ops() ? 2 : 3;
79 }
80 // Thumb1, any i8 imm cost 1.
81 if (Bits == 8 || (SImmVal >= 0 && SImmVal < 256))
82 return 1;
83 if ((~SImmVal < 256) || ARM_AM::isThumbImmShiftedVal(ZImmVal))
84 return 2;
85 // Load from constantpool.
86 return 3;
87}
88
89// Constants smaller than 256 fit in the immediate field of
90// Thumb1 instructions so we return a zero cost and 1 otherwise.
91int ARMTTIImpl::getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx,
92 const APInt &Imm, Type *Ty) {
93 if (Imm.isNonNegative() && Imm.getLimitedValue() < 256)
94 return 0;
95
96 return 1;
97}
98
99int ARMTTIImpl::getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
100 Type *Ty) {
101 // Division by a constant can be turned into multiplication, but only if we
102 // know it's constant. So it's not so much that the immediate is cheap (it's
103 // not), but that the alternative is worse.
104 // FIXME: this is probably unneeded with GlobalISel.
105 if ((Opcode == Instruction::SDiv || Opcode == Instruction::UDiv ||
106 Opcode == Instruction::SRem || Opcode == Instruction::URem) &&
107 Idx == 1)
108 return 0;
109
110 if (Opcode == Instruction::And) {
111 // UXTB/UXTH
112 if (Imm == 255 || Imm == 65535)
113 return 0;
114 // Conversion to BIC is free, and means we can use ~Imm instead.
115 return std::min(getIntImmCost(Imm, Ty), getIntImmCost(~Imm, Ty));
116 }
117
118 if (Opcode == Instruction::Add)
119 // Conversion to SUB is free, and means we can use -Imm instead.
120 return std::min(getIntImmCost(Imm, Ty), getIntImmCost(-Imm, Ty));
121
122 if (Opcode == Instruction::ICmp && Imm.isNegative() &&
123 Ty->getIntegerBitWidth() == 32) {
124 int64_t NegImm = -Imm.getSExtValue();
125 if (ST->isThumb2() && NegImm < 1<<12)
126 // icmp X, #-C -> cmn X, #C
127 return 0;
128 if (ST->isThumb() && NegImm < 1<<8)
129 // icmp X, #-C -> adds X, #C
130 return 0;
131 }
132
133 // xor a, -1 can always be folded to MVN
134 if (Opcode == Instruction::Xor && Imm.isAllOnesValue())
135 return 0;
136
137 return getIntImmCost(Imm, Ty);
138}
139
140int ARMTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
141 const Instruction *I) {
142 int ISD = TLI->InstructionOpcodeToISD(Opcode);
143 assert(ISD && "Invalid opcode")((ISD && "Invalid opcode") ? static_cast<void> (
0) : __assert_fail ("ISD && \"Invalid opcode\"", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/ARM/ARMTargetTransformInfo.cpp"
, 143, __PRETTY_FUNCTION__))
;
144
145 // Single to/from double precision conversions.
146 static const CostTblEntry NEONFltDblTbl[] = {
147 // Vector fptrunc/fpext conversions.
148 { ISD::FP_ROUND, MVT::v2f64, 2 },
149 { ISD::FP_EXTEND, MVT::v2f32, 2 },
150 { ISD::FP_EXTEND, MVT::v4f32, 4 }
151 };
152
153 if (Src->isVectorTy() && ST->hasNEON() && (ISD == ISD::FP_ROUND ||
154 ISD == ISD::FP_EXTEND)) {
155 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
156 if (const auto *Entry = CostTableLookup(NEONFltDblTbl, ISD, LT.second))
157 return LT.first * Entry->Cost;
158 }
159
160 EVT SrcTy = TLI->getValueType(DL, Src);
161 EVT DstTy = TLI->getValueType(DL, Dst);
162
163 if (!SrcTy.isSimple() || !DstTy.isSimple())
164 return BaseT::getCastInstrCost(Opcode, Dst, Src);
165
166 // Some arithmetic, load and store operations have specific instructions
167 // to cast up/down their types automatically at no extra cost.
168 // TODO: Get these tables to know at least what the related operations are.
169 static const TypeConversionCostTblEntry NEONVectorConversionTbl[] = {
170 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 0 },
171 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 0 },
172 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
173 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
174 { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 0 },
175 { ISD::TRUNCATE, MVT::v4i16, MVT::v4i32, 1 },
176
177 // The number of vmovl instructions for the extension.
178 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
179 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
180 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
181 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
182 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
183 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
184 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
185 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
186 { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
187 { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
188
189 // Operations that we legalize using splitting.
190 { ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 6 },
191 { ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 3 },
192
193 // Vector float <-> i32 conversions.
194 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
195 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
196
197 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 },
198 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 },
199 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 2 },
200 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 2 },
201 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
202 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
203 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i1, 3 },
204 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i1, 3 },
205 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 },
206 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 },
207 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
208 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
209 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
210 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
211 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i32, 2 },
212 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i32, 2 },
213 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i16, 8 },
214 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i16, 8 },
215 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i32, 4 },
216 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i32, 4 },
217
218 { ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1 },
219 { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 },
220 { ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 3 },
221 { ISD::FP_TO_UINT, MVT::v4i8, MVT::v4f32, 3 },
222 { ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 2 },
223 { ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 2 },
224
225 // Vector double <-> i32 conversions.
226 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
227 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
228
229 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 },
230 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 },
231 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 3 },
232 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 3 },
233 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
234 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
235
236 { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 2 },
237 { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 2 },
238 { ISD::FP_TO_SINT, MVT::v8i16, MVT::v8f32, 4 },
239 { ISD::FP_TO_UINT, MVT::v8i16, MVT::v8f32, 4 },
240 { ISD::FP_TO_SINT, MVT::v16i16, MVT::v16f32, 8 },
241 { ISD::FP_TO_UINT, MVT::v16i16, MVT::v16f32, 8 }
242 };
243
244 if (SrcTy.isVector() && ST->hasNEON()) {
245 if (const auto *Entry = ConvertCostTableLookup(NEONVectorConversionTbl, ISD,
246 DstTy.getSimpleVT(),
247 SrcTy.getSimpleVT()))
248 return Entry->Cost;
249 }
250
251 // Scalar float to integer conversions.
252 static const TypeConversionCostTblEntry NEONFloatConversionTbl[] = {
253 { ISD::FP_TO_SINT, MVT::i1, MVT::f32, 2 },
254 { ISD::FP_TO_UINT, MVT::i1, MVT::f32, 2 },
255 { ISD::FP_TO_SINT, MVT::i1, MVT::f64, 2 },
256 { ISD::FP_TO_UINT, MVT::i1, MVT::f64, 2 },
257 { ISD::FP_TO_SINT, MVT::i8, MVT::f32, 2 },
258 { ISD::FP_TO_UINT, MVT::i8, MVT::f32, 2 },
259 { ISD::FP_TO_SINT, MVT::i8, MVT::f64, 2 },
260 { ISD::FP_TO_UINT, MVT::i8, MVT::f64, 2 },
261 { ISD::FP_TO_SINT, MVT::i16, MVT::f32, 2 },
262 { ISD::FP_TO_UINT, MVT::i16, MVT::f32, 2 },
263 { ISD::FP_TO_SINT, MVT::i16, MVT::f64, 2 },
264 { ISD::FP_TO_UINT, MVT::i16, MVT::f64, 2 },
265 { ISD::FP_TO_SINT, MVT::i32, MVT::f32, 2 },
266 { ISD::FP_TO_UINT, MVT::i32, MVT::f32, 2 },
267 { ISD::FP_TO_SINT, MVT::i32, MVT::f64, 2 },
268 { ISD::FP_TO_UINT, MVT::i32, MVT::f64, 2 },
269 { ISD::FP_TO_SINT, MVT::i64, MVT::f32, 10 },
270 { ISD::FP_TO_UINT, MVT::i64, MVT::f32, 10 },
271 { ISD::FP_TO_SINT, MVT::i64, MVT::f64, 10 },
272 { ISD::FP_TO_UINT, MVT::i64, MVT::f64, 10 }
273 };
274 if (SrcTy.isFloatingPoint() && ST->hasNEON()) {
275 if (const auto *Entry = ConvertCostTableLookup(NEONFloatConversionTbl, ISD,
276 DstTy.getSimpleVT(),
277 SrcTy.getSimpleVT()))
278 return Entry->Cost;
279 }
280
281 // Scalar integer to float conversions.
282 static const TypeConversionCostTblEntry NEONIntegerConversionTbl[] = {
283 { ISD::SINT_TO_FP, MVT::f32, MVT::i1, 2 },
284 { ISD::UINT_TO_FP, MVT::f32, MVT::i1, 2 },
285 { ISD::SINT_TO_FP, MVT::f64, MVT::i1, 2 },
286 { ISD::UINT_TO_FP, MVT::f64, MVT::i1, 2 },
287 { ISD::SINT_TO_FP, MVT::f32, MVT::i8, 2 },
288 { ISD::UINT_TO_FP, MVT::f32, MVT::i8, 2 },
289 { ISD::SINT_TO_FP, MVT::f64, MVT::i8, 2 },
290 { ISD::UINT_TO_FP, MVT::f64, MVT::i8, 2 },
291 { ISD::SINT_TO_FP, MVT::f32, MVT::i16, 2 },
292 { ISD::UINT_TO_FP, MVT::f32, MVT::i16, 2 },
293 { ISD::SINT_TO_FP, MVT::f64, MVT::i16, 2 },
294 { ISD::UINT_TO_FP, MVT::f64, MVT::i16, 2 },
295 { ISD::SINT_TO_FP, MVT::f32, MVT::i32, 2 },
296 { ISD::UINT_TO_FP, MVT::f32, MVT::i32, 2 },
297 { ISD::SINT_TO_FP, MVT::f64, MVT::i32, 2 },
298 { ISD::UINT_TO_FP, MVT::f64, MVT::i32, 2 },
299 { ISD::SINT_TO_FP, MVT::f32, MVT::i64, 10 },
300 { ISD::UINT_TO_FP, MVT::f32, MVT::i64, 10 },
301 { ISD::SINT_TO_FP, MVT::f64, MVT::i64, 10 },
302 { ISD::UINT_TO_FP, MVT::f64, MVT::i64, 10 }
303 };
304
305 if (SrcTy.isInteger() && ST->hasNEON()) {
306 if (const auto *Entry = ConvertCostTableLookup(NEONIntegerConversionTbl,
307 ISD, DstTy.getSimpleVT(),
308 SrcTy.getSimpleVT()))
309 return Entry->Cost;
310 }
311
312 // Scalar integer conversion costs.
313 static const TypeConversionCostTblEntry ARMIntegerConversionTbl[] = {
314 // i16 -> i64 requires two dependent operations.
315 { ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 2 },
316
317 // Truncates on i64 are assumed to be free.
318 { ISD::TRUNCATE, MVT::i32, MVT::i64, 0 },
319 { ISD::TRUNCATE, MVT::i16, MVT::i64, 0 },
320 { ISD::TRUNCATE, MVT::i8, MVT::i64, 0 },
321 { ISD::TRUNCATE, MVT::i1, MVT::i64, 0 }
322 };
323
324 if (SrcTy.isInteger()) {
325 if (const auto *Entry = ConvertCostTableLookup(ARMIntegerConversionTbl, ISD,
326 DstTy.getSimpleVT(),
327 SrcTy.getSimpleVT()))
328 return Entry->Cost;
329 }
330
331 return BaseT::getCastInstrCost(Opcode, Dst, Src);
332}
333
334int ARMTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
335 unsigned Index) {
336 // Penalize inserting into an D-subregister. We end up with a three times
337 // lower estimated throughput on swift.
338 if (ST->hasSlowLoadDSubregister() && Opcode == Instruction::InsertElement &&
339 ValTy->isVectorTy() && ValTy->getScalarSizeInBits() <= 32)
340 return 3;
341
342 if ((Opcode == Instruction::InsertElement ||
343 Opcode == Instruction::ExtractElement)) {
344 // Cross-class copies are expensive on many microarchitectures,
345 // so assume they are expensive by default.
346 if (ValTy->getVectorElementType()->isIntegerTy())
347 return 3;
348
349 // Even if it's not a cross class copy, this likely leads to mixing
350 // of NEON and VFP code and should be therefore penalized.
351 if (ValTy->isVectorTy() &&
352 ValTy->getScalarSizeInBits() <= 32)
353 return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index), 2U);
354 }
355
356 return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
357}
358
359int ARMTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
360 const Instruction *I) {
361 int ISD = TLI->InstructionOpcodeToISD(Opcode);
362 // On NEON a vector select gets lowered to vbsl.
363 if (ST->hasNEON() && ValTy->isVectorTy() && ISD == ISD::SELECT) {
1
Assuming the condition is true
14
Assuming 'ISD' is equal to SELECT
15
Taking true branch
364 // Lowering of some vector selects is currently far from perfect.
365 static const TypeConversionCostTblEntry NEONVectorSelectTbl[] = {
366 { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4*4 + 1*2 + 1 },
367 { ISD::SELECT, MVT::v8i1, MVT::v8i64, 50 },
368 { ISD::SELECT, MVT::v16i1, MVT::v16i64, 100 }
369 };
370
371 EVT SelCondTy = TLI->getValueType(DL, CondTy);
16
Passing null pointer value via 2nd parameter 'Ty'
17
Calling 'TargetLoweringBase::getValueType'
372 EVT SelValTy = TLI->getValueType(DL, ValTy);
373 if (SelCondTy.isSimple() && SelValTy.isSimple()) {
374 if (const auto *Entry = ConvertCostTableLookup(NEONVectorSelectTbl, ISD,
375 SelCondTy.getSimpleVT(),
376 SelValTy.getSimpleVT()))
377 return Entry->Cost;
378 }
379
380 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
381 return LT.first;
382 }
383
384 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, I);
2
Passing value via 3rd parameter 'CondTy'
3
Calling 'BasicTTIImplBase::getCmpSelInstrCost'
385}
386
387int ARMTTIImpl::getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
388 const SCEV *Ptr) {
389 // Address computations in vectorized code with non-consecutive addresses will
390 // likely result in more instructions compared to scalar code where the
391 // computation can more often be merged into the index mode. The resulting
392 // extra micro-ops can significantly decrease throughput.
393 unsigned NumVectorInstToHideOverhead = 10;
394 int MaxMergeDistance = 64;
395
396 if (Ty->isVectorTy() && SE &&
397 !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
398 return NumVectorInstToHideOverhead;
399
400 // In many cases the address computation is not merged into the instruction
401 // addressing mode.
402 return 1;
403}
404
405int ARMTTIImpl::getMemcpyCost(const Instruction *I) {
406 const MemCpyInst *MI = dyn_cast<MemCpyInst>(I);
407 assert(MI && "MemcpyInst expected")((MI && "MemcpyInst expected") ? static_cast<void>
(0) : __assert_fail ("MI && \"MemcpyInst expected\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/ARM/ARMTargetTransformInfo.cpp"
, 407, __PRETTY_FUNCTION__))
;
408 ConstantInt *C = dyn_cast<ConstantInt>(MI->getLength());
409
410 // To model the cost of a library call, we assume 1 for the call, and
411 // 3 for the argument setup.
412 const unsigned LibCallCost = 4;
413
414 // If 'size' is not a constant, a library call will be generated.
415 if (!C)
416 return LibCallCost;
417
418 const unsigned Size = C->getValue().getZExtValue();
419 const unsigned DstAlign = MI->getDestAlignment();
420 const unsigned SrcAlign = MI->getSourceAlignment();
421 const Function *F = I->getParent()->getParent();
422 const unsigned Limit = TLI->getMaxStoresPerMemmove(F->hasMinSize());
423 std::vector<EVT> MemOps;
424
425 // MemOps will be poplulated with a list of data types that needs to be
426 // loaded and stored. That's why we multiply the number of elements by 2 to
427 // get the cost for this memcpy.
428 if (getTLI()->findOptimalMemOpLowering(
429 MemOps, Limit, Size, DstAlign, SrcAlign, false /*IsMemset*/,
430 false /*ZeroMemset*/, false /*MemcpyStrSrc*/, false /*AllowOverlap*/,
431 MI->getDestAddressSpace(), MI->getSourceAddressSpace(),
432 F->getAttributes()))
433 return MemOps.size() * 2;
434
435 // If we can't find an optimal memop lowering, return the default cost
436 return LibCallCost;
437}
438
439int ARMTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
440 Type *SubTp) {
441 if (Kind == TTI::SK_Broadcast) {
442 static const CostTblEntry NEONDupTbl[] = {
443 // VDUP handles these cases.
444 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
445 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
446 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
447 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
448 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
449 {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
450
451 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
452 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
453 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
454 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1}};
455
456 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
457
458 if (const auto *Entry = CostTableLookup(NEONDupTbl, ISD::VECTOR_SHUFFLE,
459 LT.second))
460 return LT.first * Entry->Cost;
461
462 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
463 }
464 if (Kind == TTI::SK_Reverse) {
465 static const CostTblEntry NEONShuffleTbl[] = {
466 // Reverse shuffle cost one instruction if we are shuffling within a
467 // double word (vrev) or two if we shuffle a quad word (vrev, vext).
468 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
469 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
470 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
471 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
472 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
473 {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
474
475 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
476 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
477 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 2},
478 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 2}};
479
480 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
481
482 if (const auto *Entry = CostTableLookup(NEONShuffleTbl, ISD::VECTOR_SHUFFLE,
483 LT.second))
484 return LT.first * Entry->Cost;
485
486 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
487 }
488 if (Kind == TTI::SK_Select) {
489 static const CostTblEntry NEONSelShuffleTbl[] = {
490 // Select shuffle cost table for ARM. Cost is the number of instructions
491 // required to create the shuffled vector.
492
493 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
494 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
495 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
496 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
497
498 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
499 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
500 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 2},
501
502 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 16},
503
504 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 32}};
505
506 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
507 if (const auto *Entry = CostTableLookup(NEONSelShuffleTbl,
508 ISD::VECTOR_SHUFFLE, LT.second))
509 return LT.first * Entry->Cost;
510 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
511 }
512 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
513}
514
515int ARMTTIImpl::getArithmeticInstrCost(
516 unsigned Opcode, Type *Ty, TTI::OperandValueKind Op1Info,
517 TTI::OperandValueKind Op2Info, TTI::OperandValueProperties Opd1PropInfo,
518 TTI::OperandValueProperties Opd2PropInfo,
519 ArrayRef<const Value *> Args) {
520 int ISDOpcode = TLI->InstructionOpcodeToISD(Opcode);
521 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
522
523 const unsigned FunctionCallDivCost = 20;
524 const unsigned ReciprocalDivCost = 10;
525 static const CostTblEntry CostTbl[] = {
526 // Division.
527 // These costs are somewhat random. Choose a cost of 20 to indicate that
528 // vectorizing devision (added function call) is going to be very expensive.
529 // Double registers types.
530 { ISD::SDIV, MVT::v1i64, 1 * FunctionCallDivCost},
531 { ISD::UDIV, MVT::v1i64, 1 * FunctionCallDivCost},
532 { ISD::SREM, MVT::v1i64, 1 * FunctionCallDivCost},
533 { ISD::UREM, MVT::v1i64, 1 * FunctionCallDivCost},
534 { ISD::SDIV, MVT::v2i32, 2 * FunctionCallDivCost},
535 { ISD::UDIV, MVT::v2i32, 2 * FunctionCallDivCost},
536 { ISD::SREM, MVT::v2i32, 2 * FunctionCallDivCost},
537 { ISD::UREM, MVT::v2i32, 2 * FunctionCallDivCost},
538 { ISD::SDIV, MVT::v4i16, ReciprocalDivCost},
539 { ISD::UDIV, MVT::v4i16, ReciprocalDivCost},
540 { ISD::SREM, MVT::v4i16, 4 * FunctionCallDivCost},
541 { ISD::UREM, MVT::v4i16, 4 * FunctionCallDivCost},
542 { ISD::SDIV, MVT::v8i8, ReciprocalDivCost},
543 { ISD::UDIV, MVT::v8i8, ReciprocalDivCost},
544 { ISD::SREM, MVT::v8i8, 8 * FunctionCallDivCost},
545 { ISD::UREM, MVT::v8i8, 8 * FunctionCallDivCost},
546 // Quad register types.
547 { ISD::SDIV, MVT::v2i64, 2 * FunctionCallDivCost},
548 { ISD::UDIV, MVT::v2i64, 2 * FunctionCallDivCost},
549 { ISD::SREM, MVT::v2i64, 2 * FunctionCallDivCost},
550 { ISD::UREM, MVT::v2i64, 2 * FunctionCallDivCost},
551 { ISD::SDIV, MVT::v4i32, 4 * FunctionCallDivCost},
552 { ISD::UDIV, MVT::v4i32, 4 * FunctionCallDivCost},
553 { ISD::SREM, MVT::v4i32, 4 * FunctionCallDivCost},
554 { ISD::UREM, MVT::v4i32, 4 * FunctionCallDivCost},
555 { ISD::SDIV, MVT::v8i16, 8 * FunctionCallDivCost},
556 { ISD::UDIV, MVT::v8i16, 8 * FunctionCallDivCost},
557 { ISD::SREM, MVT::v8i16, 8 * FunctionCallDivCost},
558 { ISD::UREM, MVT::v8i16, 8 * FunctionCallDivCost},
559 { ISD::SDIV, MVT::v16i8, 16 * FunctionCallDivCost},
560 { ISD::UDIV, MVT::v16i8, 16 * FunctionCallDivCost},
561 { ISD::SREM, MVT::v16i8, 16 * FunctionCallDivCost},
562 { ISD::UREM, MVT::v16i8, 16 * FunctionCallDivCost},
563 // Multiplication.
564 };
565
566 if (ST->hasNEON())
567 if (const auto *Entry = CostTableLookup(CostTbl, ISDOpcode, LT.second))
568 return LT.first * Entry->Cost;
569
570 int Cost = BaseT::getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info,
571 Opd1PropInfo, Opd2PropInfo);
572
573 // This is somewhat of a hack. The problem that we are facing is that SROA
574 // creates a sequence of shift, and, or instructions to construct values.
575 // These sequences are recognized by the ISel and have zero-cost. Not so for
576 // the vectorized code. Because we have support for v2i64 but not i64 those
577 // sequences look particularly beneficial to vectorize.
578 // To work around this we increase the cost of v2i64 operations to make them
579 // seem less beneficial.
580 if (LT.second == MVT::v2i64 &&
581 Op2Info == TargetTransformInfo::OK_UniformConstantValue)
582 Cost += 4;
583
584 return Cost;
585}
586
587int ARMTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
588 unsigned AddressSpace, const Instruction *I) {
589 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
590
591 if (Src->isVectorTy() && Alignment != 16 &&
592 Src->getVectorElementType()->isDoubleTy()) {
593 // Unaligned loads/stores are extremely inefficient.
594 // We need 4 uops for vst.1/vld.1 vs 1uop for vldr/vstr.
595 return LT.first * 4;
596 }
597 return LT.first;
598}
599
600int ARMTTIImpl::getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
601 unsigned Factor,
602 ArrayRef<unsigned> Indices,
603 unsigned Alignment,
604 unsigned AddressSpace,
605 bool UseMaskForCond,
606 bool UseMaskForGaps) {
607 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~svn362543/lib/Target/ARM/ARMTargetTransformInfo.cpp"
, 607, __PRETTY_FUNCTION__))
;
608 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~svn362543/lib/Target/ARM/ARMTargetTransformInfo.cpp"
, 608, __PRETTY_FUNCTION__))
;
609
610 // vldN/vstN doesn't support vector types of i64/f64 element.
611 bool EltIs64Bits = DL.getTypeSizeInBits(VecTy->getScalarType()) == 64;
612
613 if (Factor <= TLI->getMaxSupportedInterleaveFactor() && !EltIs64Bits &&
614 !UseMaskForCond && !UseMaskForGaps) {
615 unsigned NumElts = VecTy->getVectorNumElements();
616 auto *SubVecTy = VectorType::get(VecTy->getScalarType(), NumElts / Factor);
617
618 // vldN/vstN only support legal vector types of size 64 or 128 in bits.
619 // Accesses having vector types that are a multiple of 128 bits can be
620 // matched to more than one vldN/vstN instruction.
621 if (NumElts % Factor == 0 &&
622 TLI->isLegalInterleavedAccessType(SubVecTy, DL))
623 return Factor * TLI->getNumInterleavedAccesses(SubVecTy, DL);
624 }
625
626 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
627 Alignment, AddressSpace,
628 UseMaskForCond, UseMaskForGaps);
629}
630
631void ARMTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
632 TTI::UnrollingPreferences &UP) {
633 // Only currently enable these preferences for M-Class cores.
634 if (!ST->isMClass())
635 return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP);
636
637 // Disable loop unrolling for Oz and Os.
638 UP.OptSizeThreshold = 0;
639 UP.PartialOptSizeThreshold = 0;
640 if (L->getHeader()->getParent()->hasOptSize())
641 return;
642
643 // Only enable on Thumb-2 targets.
644 if (!ST->isThumb2())
645 return;
646
647 SmallVector<BasicBlock*, 4> ExitingBlocks;
648 L->getExitingBlocks(ExitingBlocks);
649 LLVM_DEBUG(dbgs() << "Loop has:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("armtti")) { dbgs() << "Loop has:\n" << "Blocks: "
<< L->getNumBlocks() << "\n" << "Exit blocks: "
<< ExitingBlocks.size() << "\n"; } } while (false
)
650 << "Blocks: " << L->getNumBlocks() << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("armtti")) { dbgs() << "Loop has:\n" << "Blocks: "
<< L->getNumBlocks() << "\n" << "Exit blocks: "
<< ExitingBlocks.size() << "\n"; } } while (false
)
651 << "Exit blocks: " << ExitingBlocks.size() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("armtti")) { dbgs() << "Loop has:\n" << "Blocks: "
<< L->getNumBlocks() << "\n" << "Exit blocks: "
<< ExitingBlocks.size() << "\n"; } } while (false
)
;
652
653 // Only allow another exit other than the latch. This acts as an early exit
654 // as it mirrors the profitability calculation of the runtime unroller.
655 if (ExitingBlocks.size() > 2)
656 return;
657
658 // Limit the CFG of the loop body for targets with a branch predictor.
659 // Allowing 4 blocks permits if-then-else diamonds in the body.
660 if (ST->hasBranchPredictor() && L->getNumBlocks() > 4)
661 return;
662
663 // Scan the loop: don't unroll loops with calls as this could prevent
664 // inlining.
665 unsigned Cost = 0;
666 for (auto *BB : L->getBlocks()) {
667 for (auto &I : *BB) {
668 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
669 ImmutableCallSite CS(&I);
670 if (const Function *F = CS.getCalledFunction()) {
671 if (!isLoweredToCall(F))
672 continue;
673 }
674 return;
675 }
676 SmallVector<const Value*, 4> Operands(I.value_op_begin(),
677 I.value_op_end());
678 Cost += getUserCost(&I, Operands);
679 }
680 }
681
682 LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("armtti")) { dbgs() << "Cost of loop: " << Cost <<
"\n"; } } while (false)
;
683
684 UP.Partial = true;
685 UP.Runtime = true;
686 UP.UnrollRemainder = true;
687 UP.DefaultUnrollRuntimeCount = 4;
688 UP.UnrollAndJam = true;
689 UP.UnrollAndJamInnerLoopThreshold = 60;
690
691 // Force unrolling small loops can be very useful because of the branch
692 // taken cost of the backedge.
693 if (Cost < 12)
694 UP.Force = true;
695}

/build/llvm-toolchain-snapshot-9~svn362543/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~svn362543/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~svn362543/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~svn362543/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~svn362543/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~svn362543/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~svn362543/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~svn362543/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~svn362543/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~svn362543/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~svn362543/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~svn362543/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 case Instruction::AddrSpaceCast:
418 if (TLI->isFreeAddrSpaceCast(OpTy->getPointerAddressSpace(),
419 Ty->getPointerAddressSpace()))
420 return TargetTransformInfo::TCC_Free;
421 return TargetTransformInfo::TCC_Basic;
422 }
423
424 return BaseT::getOperationCost(Opcode, Ty, OpTy);
425 }
426
427 unsigned getInliningThresholdMultiplier() { return 1; }
428
429 void getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
430 TTI::UnrollingPreferences &UP) {
431 // This unrolling functionality is target independent, but to provide some
432 // motivation for its intended use, for x86:
433
434 // According to the Intel 64 and IA-32 Architectures Optimization Reference
435 // Manual, Intel Core models and later have a loop stream detector (and
436 // associated uop queue) that can benefit from partial unrolling.
437 // The relevant requirements are:
438 // - The loop must have no more than 4 (8 for Nehalem and later) branches
439 // taken, and none of them may be calls.
440 // - The loop can have no more than 18 (28 for Nehalem and later) uops.
441
442 // According to the Software Optimization Guide for AMD Family 15h
443 // Processors, models 30h-4fh (Steamroller and later) have a loop predictor
444 // and loop buffer which can benefit from partial unrolling.
445 // The relevant requirements are:
446 // - The loop must have fewer than 16 branches
447 // - The loop must have less than 40 uops in all executed loop branches
448
449 // The number of taken branches in a loop is hard to estimate here, and
450 // benchmarking has revealed that it is better not to be conservative when
451 // estimating the branch count. As a result, we'll ignore the branch limits
452 // until someone finds a case where it matters in practice.
453
454 unsigned MaxOps;
455 const TargetSubtargetInfo *ST = getST();
456 if (PartialUnrollingThreshold.getNumOccurrences() > 0)
457 MaxOps = PartialUnrollingThreshold;
458 else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
459 MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
460 else
461 return;
462
463 // Scan the loop: don't unroll loops with calls.
464 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
465 ++I) {
466 BasicBlock *BB = *I;
467
468 for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
469 if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
470 ImmutableCallSite CS(&*J);
471 if (const Function *F = CS.getCalledFunction()) {
472 if (!static_cast<T *>(this)->isLoweredToCall(F))
473 continue;
474 }
475
476 return;
477 }
478 }
479
480 // Enable runtime and partial unrolling up to the specified size.
481 // Enable using trip count upper bound to unroll loops.
482 UP.Partial = UP.Runtime = UP.UpperBound = true;
483 UP.PartialThreshold = MaxOps;
484
485 // Avoid unrolling when optimizing for size.
486 UP.OptSizeThreshold = 0;
487 UP.PartialOptSizeThreshold = 0;
488
489 // Set number of instructions optimized when "back edge"
490 // becomes "fall through" to default value of 2.
491 UP.BEInsns = 2;
492 }
493
494 int getInstructionLatency(const Instruction *I) {
495 if (isa<LoadInst>(I))
496 return getST()->getSchedModel().DefaultLoadLatency;
497
498 return BaseT::getInstructionLatency(I);
499 }
500
501 /// @}
502
503 /// \name Vector TTI Implementations
504 /// @{
505
506 unsigned getNumberOfRegisters(bool Vector) { return Vector ? 0 : 1; }
507
508 unsigned getRegisterBitWidth(bool Vector) const { return 32; }
509
510 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
511 /// are set if the result needs to be inserted and/or extracted from vectors.
512 unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
513 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~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 513, __PRETTY_FUNCTION__))
;
514 unsigned Cost = 0;
515
516 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
517 if (Insert)
518 Cost += static_cast<T *>(this)
519 ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
520 if (Extract)
521 Cost += static_cast<T *>(this)
522 ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
523 }
524
525 return Cost;
526 }
527
528 /// Estimate the overhead of scalarizing an instructions unique
529 /// non-constant operands. The types of the arguments are ordinarily
530 /// scalar, in which case the costs are multiplied with VF.
531 unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
532 unsigned VF) {
533 unsigned Cost = 0;
534 SmallPtrSet<const Value*, 4> UniqueOperands;
535 for (const Value *A : Args) {
536 if (!isa<Constant>(A) && UniqueOperands.insert(A).second) {
537 Type *VecTy = nullptr;
538 if (A->getType()->isVectorTy()) {
539 VecTy = A->getType();
540 // If A is a vector operand, VF should be 1 or correspond to A.
541 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~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 542, __PRETTY_FUNCTION__))
542 "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~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 542, __PRETTY_FUNCTION__))
;
543 }
544 else
545 VecTy = VectorType::get(A->getType(), VF);
546
547 Cost += getScalarizationOverhead(VecTy, false, true);
548 }
549 }
550
551 return Cost;
552 }
553
554 unsigned getScalarizationOverhead(Type *VecTy, ArrayRef<const Value *> Args) {
555 assert(VecTy->isVectorTy())((VecTy->isVectorTy()) ? static_cast<void> (0) : __assert_fail
("VecTy->isVectorTy()", "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 555, __PRETTY_FUNCTION__))
;
556
557 unsigned Cost = 0;
558
559 Cost += getScalarizationOverhead(VecTy, true, false);
560 if (!Args.empty())
561 Cost += getOperandsScalarizationOverhead(Args,
562 VecTy->getVectorNumElements());
563 else
564 // When no information on arguments is provided, we add the cost
565 // associated with one argument as a heuristic.
566 Cost += getScalarizationOverhead(VecTy, false, true);
567
568 return Cost;
569 }
570
571 unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
572
573 unsigned getArithmeticInstrCost(
574 unsigned Opcode, Type *Ty,
575 TTI::OperandValueKind Opd1Info = TTI::OK_AnyValue,
576 TTI::OperandValueKind Opd2Info = TTI::OK_AnyValue,
577 TTI::OperandValueProperties Opd1PropInfo = TTI::OP_None,
578 TTI::OperandValueProperties Opd2PropInfo = TTI::OP_None,
579 ArrayRef<const Value *> Args = ArrayRef<const Value *>()) {
580 // Check if any of the operands are vector operands.
581 const TargetLoweringBase *TLI = getTLI();
582 int ISD = TLI->InstructionOpcodeToISD(Opcode);
583 assert(ISD && "Invalid opcode")((ISD && "Invalid opcode") ? static_cast<void> (
0) : __assert_fail ("ISD && \"Invalid opcode\"", "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 583, __PRETTY_FUNCTION__))
;
584
585 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
586
587 bool IsFloat = Ty->isFPOrFPVectorTy();
588 // Assume that floating point arithmetic operations cost twice as much as
589 // integer operations.
590 unsigned OpCost = (IsFloat ? 2 : 1);
591
592 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
593 // The operation is legal. Assume it costs 1.
594 // TODO: Once we have extract/insert subvector cost we need to use them.
595 return LT.first * OpCost;
596 }
597
598 if (!TLI->isOperationExpand(ISD, LT.second)) {
599 // If the operation is custom lowered, then assume that the code is twice
600 // as expensive.
601 return LT.first * 2 * OpCost;
602 }
603
604 // Else, assume that we need to scalarize this op.
605 // TODO: If one of the types get legalized by splitting, handle this
606 // similarly to what getCastInstrCost() does.
607 if (Ty->isVectorTy()) {
608 unsigned Num = Ty->getVectorNumElements();
609 unsigned Cost = static_cast<T *>(this)
610 ->getArithmeticInstrCost(Opcode, Ty->getScalarType());
611 // Return the cost of multiple scalar invocation plus the cost of
612 // inserting and extracting the values.
613 return getScalarizationOverhead(Ty, Args) + Num * Cost;
614 }
615
616 // We don't know anything about this scalar instruction.
617 return OpCost;
618 }
619
620 unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
621 Type *SubTp) {
622 switch (Kind) {
623 case TTI::SK_Broadcast:
624 return getBroadcastShuffleOverhead(Tp);
625 case TTI::SK_Select:
626 case TTI::SK_Reverse:
627 case TTI::SK_Transpose:
628 case TTI::SK_PermuteSingleSrc:
629 case TTI::SK_PermuteTwoSrc:
630 return getPermuteShuffleOverhead(Tp);
631 case TTI::SK_ExtractSubvector:
632 return getExtractSubvectorOverhead(Tp, Index, SubTp);
633 case TTI::SK_InsertSubvector:
634 return getInsertSubvectorOverhead(Tp, Index, SubTp);
635 }
636 llvm_unreachable("Unknown TTI::ShuffleKind")::llvm::llvm_unreachable_internal("Unknown TTI::ShuffleKind",
"/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 636)
;
637 }
638
639 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
640 const Instruction *I = nullptr) {
641 const TargetLoweringBase *TLI = getTLI();
642 int ISD = TLI->InstructionOpcodeToISD(Opcode);
643 assert(ISD && "Invalid opcode")((ISD && "Invalid opcode") ? static_cast<void> (
0) : __assert_fail ("ISD && \"Invalid opcode\"", "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 643, __PRETTY_FUNCTION__))
;
644 std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(DL, Src);
645 std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(DL, Dst);
646
647 // Check for NOOP conversions.
648 if (SrcLT.first == DstLT.first &&
649 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
650
651 // Bitcast between types that are legalized to the same type are free.
652 if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
653 return 0;
654 }
655
656 if (Opcode == Instruction::Trunc &&
657 TLI->isTruncateFree(SrcLT.second, DstLT.second))
658 return 0;
659
660 if (Opcode == Instruction::ZExt &&
661 TLI->isZExtFree(SrcLT.second, DstLT.second))
662 return 0;
663
664 if (Opcode == Instruction::AddrSpaceCast &&
665 TLI->isFreeAddrSpaceCast(Src->getPointerAddressSpace(),
666 Dst->getPointerAddressSpace()))
667 return 0;
668
669 // If this is a zext/sext of a load, return 0 if the corresponding
670 // extending load exists on target.
671 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
672 I && isa<LoadInst>(I->getOperand(0))) {
673 EVT ExtVT = EVT::getEVT(Dst);
674 EVT LoadVT = EVT::getEVT(Src);
675 unsigned LType =
676 ((Opcode == Instruction::ZExt) ? ISD::ZEXTLOAD : ISD::SEXTLOAD);
677 if (TLI->isLoadExtLegal(LType, ExtVT, LoadVT))
678 return 0;
679 }
680
681 // If the cast is marked as legal (or promote) then assume low cost.
682 if (SrcLT.first == DstLT.first &&
683 TLI->isOperationLegalOrPromote(ISD, DstLT.second))
684 return 1;
685
686 // Handle scalar conversions.
687 if (!Src->isVectorTy() && !Dst->isVectorTy()) {
688 // Scalar bitcasts are usually free.
689 if (Opcode == Instruction::BitCast)
690 return 0;
691
692 // Just check the op cost. If the operation is legal then assume it costs
693 // 1.
694 if (!TLI->isOperationExpand(ISD, DstLT.second))
695 return 1;
696
697 // Assume that illegal scalar instruction are expensive.
698 return 4;
699 }
700
701 // Check vector-to-vector casts.
702 if (Dst->isVectorTy() && Src->isVectorTy()) {
703 // If the cast is between same-sized registers, then the check is simple.
704 if (SrcLT.first == DstLT.first &&
705 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
706
707 // Assume that Zext is done using AND.
708 if (Opcode == Instruction::ZExt)
709 return 1;
710
711 // Assume that sext is done using SHL and SRA.
712 if (Opcode == Instruction::SExt)
713 return 2;
714
715 // Just check the op cost. If the operation is legal then assume it
716 // costs
717 // 1 and multiply by the type-legalization overhead.
718 if (!TLI->isOperationExpand(ISD, DstLT.second))
719 return SrcLT.first * 1;
720 }
721
722 // If we are legalizing by splitting, query the concrete TTI for the cost
723 // of casting the original vector twice. We also need to factor in the
724 // cost of the split itself. Count that as 1, to be consistent with
725 // TLI->getTypeLegalizationCost().
726 if ((TLI->getTypeAction(Src->getContext(), TLI->getValueType(DL, Src)) ==
727 TargetLowering::TypeSplitVector) ||
728 (TLI->getTypeAction(Dst->getContext(), TLI->getValueType(DL, Dst)) ==
729 TargetLowering::TypeSplitVector)) {
730 Type *SplitDst = VectorType::get(Dst->getVectorElementType(),
731 Dst->getVectorNumElements() / 2);
732 Type *SplitSrc = VectorType::get(Src->getVectorElementType(),
733 Src->getVectorNumElements() / 2);
734 T *TTI = static_cast<T *>(this);
735 return TTI->getVectorSplitCost() +
736 (2 * TTI->getCastInstrCost(Opcode, SplitDst, SplitSrc, I));
737 }
738
739 // In other cases where the source or destination are illegal, assume
740 // the operation will get scalarized.
741 unsigned Num = Dst->getVectorNumElements();
742 unsigned Cost = static_cast<T *>(this)->getCastInstrCost(
743 Opcode, Dst->getScalarType(), Src->getScalarType(), I);
744
745 // Return the cost of multiple scalar invocation plus the cost of
746 // inserting and extracting the values.
747 return getScalarizationOverhead(Dst, true, true) + Num * Cost;
748 }
749
750 // We already handled vector-to-vector and scalar-to-scalar conversions.
751 // This
752 // is where we handle bitcast between vectors and scalars. We need to assume
753 // that the conversion is scalarized in one way or another.
754 if (Opcode == Instruction::BitCast)
755 // Illegal bitcasts are done by storing and loading from a stack slot.
756 return (Src->isVectorTy() ? getScalarizationOverhead(Src, false, true)
757 : 0) +
758 (Dst->isVectorTy() ? getScalarizationOverhead(Dst, true, false)
759 : 0);
760
761 llvm_unreachable("Unhandled cast")::llvm::llvm_unreachable_internal("Unhandled cast", "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 761)
;
762 }
763
764 unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
765 VectorType *VecTy, unsigned Index) {
766 return static_cast<T *>(this)->getVectorInstrCost(
767 Instruction::ExtractElement, VecTy, Index) +
768 static_cast<T *>(this)->getCastInstrCost(Opcode, Dst,
769 VecTy->getElementType());
770 }
771
772 unsigned getCFInstrCost(unsigned Opcode) {
773 // Branches are assumed to be predicted.
774 return 0;
775 }
776
777 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
778 const Instruction *I) {
779 const TargetLoweringBase *TLI = getTLI();
780 int ISD = TLI->InstructionOpcodeToISD(Opcode);
781 assert(ISD && "Invalid opcode")((ISD && "Invalid opcode") ? static_cast<void> (
0) : __assert_fail ("ISD && \"Invalid opcode\"", "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 781, __PRETTY_FUNCTION__))
;
4
Assuming 'ISD' is not equal to 0
5
'?' condition is true
782
783 // Selects on vectors are actually vector selects.
784 if (ISD == ISD::SELECT) {
6
Assuming 'ISD' is not equal to SELECT
7
Taking false branch
785 assert(CondTy && "CondTy must exist")((CondTy && "CondTy must exist") ? static_cast<void
> (0) : __assert_fail ("CondTy && \"CondTy must exist\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 785, __PRETTY_FUNCTION__))
;
786 if (CondTy->isVectorTy())
787 ISD = ISD::VSELECT;
788 }
789 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
790
791 if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
8
Taking false branch
792 !TLI->isOperationExpand(ISD, LT.second)) {
793 // The operation is legal. Assume it costs 1. Multiply
794 // by the type-legalization overhead.
795 return LT.first * 1;
796 }
797
798 // Otherwise, assume that the cast is scalarized.
799 // TODO: If one of the types get legalized by splitting, handle this
800 // similarly to what getCastInstrCost() does.
801 if (ValTy->isVectorTy()) {
9
Taking true branch
802 unsigned Num = ValTy->getVectorNumElements();
803 if (CondTy)
10
Assuming 'CondTy' is null
11
Taking false branch
804 CondTy = CondTy->getScalarType();
805 unsigned Cost = static_cast<T *>(this)->getCmpSelInstrCost(
13
Calling 'ARMTTIImpl::getCmpSelInstrCost'
806 Opcode, ValTy->getScalarType(), CondTy, I);
12
Passing null pointer value via 3rd parameter 'CondTy'
807
808 // Return the cost of multiple scalar invocation plus the cost of
809 // inserting and extracting the values.
810 return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
811 }
812
813 // Unknown scalar opcode.
814 return 1;
815 }
816
817 unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
818 std::pair<unsigned, MVT> LT =
819 getTLI()->getTypeLegalizationCost(DL, Val->getScalarType());
820
821 return LT.first;
822 }
823
824 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
825 unsigned AddressSpace, const Instruction *I = nullptr) {
826 assert(!Src->isVoidTy() && "Invalid type")((!Src->isVoidTy() && "Invalid type") ? static_cast
<void> (0) : __assert_fail ("!Src->isVoidTy() && \"Invalid type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 826, __PRETTY_FUNCTION__))
;
827 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Src);
828
829 // Assuming that all loads of legal types cost 1.
830 unsigned Cost = LT.first;
831
832 if (Src->isVectorTy() &&
833 Src->getPrimitiveSizeInBits() < LT.second.getSizeInBits()) {
834 // This is a vector load that legalizes to a larger type than the vector
835 // itself. Unless the corresponding extending load or truncating store is
836 // legal, then this will scalarize.
837 TargetLowering::LegalizeAction LA = TargetLowering::Expand;
838 EVT MemVT = getTLI()->getValueType(DL, Src);
839 if (Opcode == Instruction::Store)
840 LA = getTLI()->getTruncStoreAction(LT.second, MemVT);
841 else
842 LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
843
844 if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
845 // This is a vector load/store for some illegal type that is scalarized.
846 // We must account for the cost of building or decomposing the vector.
847 Cost += getScalarizationOverhead(Src, Opcode != Instruction::Store,
848 Opcode == Instruction::Store);
849 }
850 }
851
852 return Cost;
853 }
854
855 unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
856 unsigned Factor,
857 ArrayRef<unsigned> Indices,
858 unsigned Alignment, unsigned AddressSpace,
859 bool UseMaskForCond = false,
860 bool UseMaskForGaps = false) {
861 VectorType *VT = dyn_cast<VectorType>(VecTy);
862 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~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 862, __PRETTY_FUNCTION__))
;
863
864 unsigned NumElts = VT->getNumElements();
865 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~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 865, __PRETTY_FUNCTION__))
;
866
867 unsigned NumSubElts = NumElts / Factor;
868 VectorType *SubVT = VectorType::get(VT->getElementType(), NumSubElts);
869
870 // Firstly, the cost of load/store operation.
871 unsigned Cost;
872 if (UseMaskForCond || UseMaskForGaps)
873 Cost = static_cast<T *>(this)->getMaskedMemoryOpCost(
874 Opcode, VecTy, Alignment, AddressSpace);
875 else
876 Cost = static_cast<T *>(this)->getMemoryOpCost(Opcode, VecTy, Alignment,
877 AddressSpace);
878
879 // Legalize the vector type, and get the legalized and unlegalized type
880 // sizes.
881 MVT VecTyLT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
882 unsigned VecTySize =
883 static_cast<T *>(this)->getDataLayout().getTypeStoreSize(VecTy);
884 unsigned VecTyLTSize = VecTyLT.getStoreSize();
885
886 // Return the ceiling of dividing A by B.
887 auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; };
888
889 // Scale the cost of the memory operation by the fraction of legalized
890 // instructions that will actually be used. We shouldn't account for the
891 // cost of dead instructions since they will be removed.
892 //
893 // E.g., An interleaved load of factor 8:
894 // %vec = load <16 x i64>, <16 x i64>* %ptr
895 // %v0 = shufflevector %vec, undef, <0, 8>
896 //
897 // If <16 x i64> is legalized to 8 v2i64 loads, only 2 of the loads will be
898 // used (those corresponding to elements [0:1] and [8:9] of the unlegalized
899 // type). The other loads are unused.
900 //
901 // We only scale the cost of loads since interleaved store groups aren't
902 // allowed to have gaps.
903 if (Opcode == Instruction::Load && VecTySize > VecTyLTSize) {
904 // The number of loads of a legal type it will take to represent a load
905 // of the unlegalized vector type.
906 unsigned NumLegalInsts = ceil(VecTySize, VecTyLTSize);
907
908 // The number of elements of the unlegalized type that correspond to a
909 // single legal instruction.
910 unsigned NumEltsPerLegalInst = ceil(NumElts, NumLegalInsts);
911
912 // Determine which legal instructions will be used.
913 BitVector UsedInsts(NumLegalInsts, false);
914 for (unsigned Index : Indices)
915 for (unsigned Elt = 0; Elt < NumSubElts; ++Elt)
916 UsedInsts.set((Index + Elt * Factor) / NumEltsPerLegalInst);
917
918 // Scale the cost of the load by the fraction of legal instructions that
919 // will be used.
920 Cost *= UsedInsts.count() / NumLegalInsts;
921 }
922
923 // Then plus the cost of interleave operation.
924 if (Opcode == Instruction::Load) {
925 // The interleave cost is similar to extract sub vectors' elements
926 // from the wide vector, and insert them into sub vectors.
927 //
928 // E.g. An interleaved load of factor 2 (with one member of index 0):
929 // %vec = load <8 x i32>, <8 x i32>* %ptr
930 // %v0 = shuffle %vec, undef, <0, 2, 4, 6> ; Index 0
931 // The cost is estimated as extract elements at 0, 2, 4, 6 from the
932 // <8 x i32> vector and insert them into a <4 x i32> vector.
933
934 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~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 935, __PRETTY_FUNCTION__))
935 "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~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 935, __PRETTY_FUNCTION__))
;
936
937 for (unsigned Index : Indices) {
938 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~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 938, __PRETTY_FUNCTION__))
;
939
940 // Extract elements from loaded vector for each sub vector.
941 for (unsigned i = 0; i < NumSubElts; i++)
942 Cost += static_cast<T *>(this)->getVectorInstrCost(
943 Instruction::ExtractElement, VT, Index + i * Factor);
944 }
945
946 unsigned InsSubCost = 0;
947 for (unsigned i = 0; i < NumSubElts; i++)
948 InsSubCost += static_cast<T *>(this)->getVectorInstrCost(
949 Instruction::InsertElement, SubVT, i);
950
951 Cost += Indices.size() * InsSubCost;
952 } else {
953 // The interleave cost is extract all elements from sub vectors, and
954 // insert them into the wide vector.
955 //
956 // E.g. An interleaved store of factor 2:
957 // %v0_v1 = shuffle %v0, %v1, <0, 4, 1, 5, 2, 6, 3, 7>
958 // store <8 x i32> %interleaved.vec, <8 x i32>* %ptr
959 // The cost is estimated as extract all elements from both <4 x i32>
960 // vectors and insert into the <8 x i32> vector.
961
962 unsigned ExtSubCost = 0;
963 for (unsigned i = 0; i < NumSubElts; i++)
964 ExtSubCost += static_cast<T *>(this)->getVectorInstrCost(
965 Instruction::ExtractElement, SubVT, i);
966 Cost += ExtSubCost * Factor;
967
968 for (unsigned i = 0; i < NumElts; i++)
969 Cost += static_cast<T *>(this)
970 ->getVectorInstrCost(Instruction::InsertElement, VT, i);
971 }
972
973 if (!UseMaskForCond)
974 return Cost;
975
976 Type *I8Type = Type::getInt8Ty(VT->getContext());
977 VectorType *MaskVT = VectorType::get(I8Type, NumElts);
978 SubVT = VectorType::get(I8Type, NumSubElts);
979
980 // The Mask shuffling cost is extract all the elements of the Mask
981 // and insert each of them Factor times into the wide vector:
982 //
983 // E.g. an interleaved group with factor 3:
984 // %mask = icmp ult <8 x i32> %vec1, %vec2
985 // %interleaved.mask = shufflevector <8 x i1> %mask, <8 x i1> undef,
986 // <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>
987 // The cost is estimated as extract all mask elements from the <8xi1> mask
988 // vector and insert them factor times into the <24xi1> shuffled mask
989 // vector.
990 for (unsigned i = 0; i < NumSubElts; i++)
991 Cost += static_cast<T *>(this)->getVectorInstrCost(
992 Instruction::ExtractElement, SubVT, i);
993
994 for (unsigned i = 0; i < NumElts; i++)
995 Cost += static_cast<T *>(this)->getVectorInstrCost(
996 Instruction::InsertElement, MaskVT, i);
997
998 // The Gaps mask is invariant and created outside the loop, therefore the
999 // cost of creating it is not accounted for here. However if we have both
1000 // a MaskForGaps and some other mask that guards the execution of the
1001 // memory access, we need to account for the cost of And-ing the two masks
1002 // inside the loop.
1003 if (UseMaskForGaps)
1004 Cost += static_cast<T *>(this)->getArithmeticInstrCost(
1005 BinaryOperator::And, MaskVT);
1006
1007 return Cost;
1008 }
1009
1010 /// Get intrinsic cost based on arguments.
1011 unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
1012 ArrayRef<Value *> Args, FastMathFlags FMF,
1013 unsigned VF = 1) {
1014 unsigned RetVF = (RetTy->isVectorTy() ? RetTy->getVectorNumElements() : 1);
1015 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~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 1015, __PRETTY_FUNCTION__))
;
1016 auto *ConcreteTTI = static_cast<T *>(this);
1017
1018 switch (IID) {
1019 default: {
1020 // Assume that we need to scalarize this intrinsic.
1021 SmallVector<Type *, 4> Types;
1022 for (Value *Op : Args) {
1023 Type *OpTy = Op->getType();
1024 assert(VF == 1 || !OpTy->isVectorTy())((VF == 1 || !OpTy->isVectorTy()) ? static_cast<void>
(0) : __assert_fail ("VF == 1 || !OpTy->isVectorTy()", "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 1024, __PRETTY_FUNCTION__))
;
1025 Types.push_back(VF == 1 ? OpTy : VectorType::get(OpTy, VF));
1026 }
1027
1028 if (VF > 1 && !RetTy->isVoidTy())
1029 RetTy = VectorType::get(RetTy, VF);
1030
1031 // Compute the scalarization overhead based on Args for a vector
1032 // intrinsic. A vectorizer will pass a scalar RetTy and VF > 1, while
1033 // CostModel will pass a vector RetTy and VF is 1.
1034 unsigned ScalarizationCost = std::numeric_limits<unsigned>::max();
1035 if (RetVF > 1 || VF > 1) {
1036 ScalarizationCost = 0;
1037 if (!RetTy->isVoidTy())
1038 ScalarizationCost += getScalarizationOverhead(RetTy, true, false);
1039 ScalarizationCost += getOperandsScalarizationOverhead(Args, VF);
1040 }
1041
1042 return ConcreteTTI->getIntrinsicInstrCost(IID, RetTy, Types, FMF,
1043 ScalarizationCost);
1044 }
1045 case Intrinsic::masked_scatter: {
1046 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~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 1046, __PRETTY_FUNCTION__))
;
1047 Value *Mask = Args[3];
1048 bool VarMask = !isa<Constant>(Mask);
1049 unsigned Alignment = cast<ConstantInt>(Args[2])->getZExtValue();
1050 return ConcreteTTI->getGatherScatterOpCost(
1051 Instruction::Store, Args[0]->getType(), Args[1], VarMask, Alignment);
1052 }
1053 case Intrinsic::masked_gather: {
1054 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~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 1054, __PRETTY_FUNCTION__))
;
1055 Value *Mask = Args[2];
1056 bool VarMask = !isa<Constant>(Mask);
1057 unsigned Alignment = cast<ConstantInt>(Args[1])->getZExtValue();
1058 return ConcreteTTI->getGatherScatterOpCost(Instruction::Load, RetTy,
1059 Args[0], VarMask, Alignment);
1060 }
1061 case Intrinsic::experimental_vector_reduce_add:
1062 case Intrinsic::experimental_vector_reduce_mul:
1063 case Intrinsic::experimental_vector_reduce_and:
1064 case Intrinsic::experimental_vector_reduce_or:
1065 case Intrinsic::experimental_vector_reduce_xor:
1066 case Intrinsic::experimental_vector_reduce_fadd:
1067 case Intrinsic::experimental_vector_reduce_fmul:
1068 case Intrinsic::experimental_vector_reduce_smax:
1069 case Intrinsic::experimental_vector_reduce_smin:
1070 case Intrinsic::experimental_vector_reduce_fmax:
1071 case Intrinsic::experimental_vector_reduce_fmin:
1072 case Intrinsic::experimental_vector_reduce_umax:
1073 case Intrinsic::experimental_vector_reduce_umin:
1074 return getIntrinsicInstrCost(IID, RetTy, Args[0]->getType(), FMF);
1075 case Intrinsic::fshl:
1076 case Intrinsic::fshr: {
1077 Value *X = Args[0];
1078 Value *Y = Args[1];
1079 Value *Z = Args[2];
1080 TTI::OperandValueProperties OpPropsX, OpPropsY, OpPropsZ, OpPropsBW;
1081 TTI::OperandValueKind OpKindX = TTI::getOperandInfo(X, OpPropsX);
1082 TTI::OperandValueKind OpKindY = TTI::getOperandInfo(Y, OpPropsY);
1083 TTI::OperandValueKind OpKindZ = TTI::getOperandInfo(Z, OpPropsZ);
1084 TTI::OperandValueKind OpKindBW = TTI::OK_UniformConstantValue;
1085 OpPropsBW = isPowerOf2_32(RetTy->getScalarSizeInBits()) ? TTI::OP_PowerOf2
1086 : TTI::OP_None;
1087 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
1088 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
1089 unsigned Cost = 0;
1090 Cost += ConcreteTTI->getArithmeticInstrCost(BinaryOperator::Or, RetTy);
1091 Cost += ConcreteTTI->getArithmeticInstrCost(BinaryOperator::Sub, RetTy);
1092 Cost += ConcreteTTI->getArithmeticInstrCost(BinaryOperator::Shl, RetTy,
1093 OpKindX, OpKindZ, OpPropsX);
1094 Cost += ConcreteTTI->getArithmeticInstrCost(BinaryOperator::LShr, RetTy,
1095 OpKindY, OpKindZ, OpPropsY);
1096 // Non-constant shift amounts requires a modulo.
1097 if (OpKindZ != TTI::OK_UniformConstantValue &&
1098 OpKindZ != TTI::OK_NonUniformConstantValue)
1099 Cost += ConcreteTTI->getArithmeticInstrCost(BinaryOperator::URem, RetTy,
1100 OpKindZ, OpKindBW, OpPropsZ,
1101 OpPropsBW);
1102 // For non-rotates (X != Y) we must add shift-by-zero handling costs.
1103 if (X != Y) {
1104 Type *CondTy = Type::getInt1Ty(RetTy->getContext());
1105 if (RetVF > 1)
1106 CondTy = VectorType::get(CondTy, RetVF);
1107 Cost += ConcreteTTI->getCmpSelInstrCost(BinaryOperator::ICmp, RetTy,
1108 CondTy, nullptr);
1109 Cost += ConcreteTTI->getCmpSelInstrCost(BinaryOperator::Select, RetTy,
1110 CondTy, nullptr);
1111 }
1112 return Cost;
1113 }
1114 }
1115 }
1116
1117 /// Get intrinsic cost based on argument types.
1118 /// If ScalarizationCostPassed is std::numeric_limits<unsigned>::max(), the
1119 /// cost of scalarizing the arguments and the return value will be computed
1120 /// based on types.
1121 unsigned getIntrinsicInstrCost(
1122 Intrinsic::ID IID, Type *RetTy, ArrayRef<Type *> Tys, FastMathFlags FMF,
1123 unsigned ScalarizationCostPassed = std::numeric_limits<unsigned>::max()) {
1124 unsigned RetVF = (RetTy->isVectorTy() ? RetTy->getVectorNumElements() : 1);
1125 auto *ConcreteTTI = static_cast<T *>(this);
1126
1127 SmallVector<unsigned, 2> ISDs;
1128 unsigned SingleCallCost = 10; // Library call cost. Make it expensive.
1129 switch (IID) {
1130 default: {
1131 // Assume that we need to scalarize this intrinsic.
1132 unsigned ScalarizationCost = ScalarizationCostPassed;
1133 unsigned ScalarCalls = 1;
1134 Type *ScalarRetTy = RetTy;
1135 if (RetTy->isVectorTy()) {
1136 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
1137 ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
1138 ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
1139 ScalarRetTy = RetTy->getScalarType();
1140 }
1141 SmallVector<Type *, 4> ScalarTys;
1142 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1143 Type *Ty = Tys[i];
1144 if (Ty->isVectorTy()) {
1145 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
1146 ScalarizationCost += getScalarizationOverhead(Ty, false, true);
1147 ScalarCalls = std::max(ScalarCalls, Ty->getVectorNumElements());
1148 Ty = Ty->getScalarType();
1149 }
1150 ScalarTys.push_back(Ty);
1151 }
1152 if (ScalarCalls == 1)
1153 return 1; // Return cost of a scalar intrinsic. Assume it to be cheap.
1154
1155 unsigned ScalarCost =
1156 ConcreteTTI->getIntrinsicInstrCost(IID, ScalarRetTy, ScalarTys, FMF);
1157
1158 return ScalarCalls * ScalarCost + ScalarizationCost;
1159 }
1160 // Look for intrinsics that can be lowered directly or turned into a scalar
1161 // intrinsic call.
1162 case Intrinsic::sqrt:
1163 ISDs.push_back(ISD::FSQRT);
1164 break;
1165 case Intrinsic::sin:
1166 ISDs.push_back(ISD::FSIN);
1167 break;
1168 case Intrinsic::cos:
1169 ISDs.push_back(ISD::FCOS);
1170 break;
1171 case Intrinsic::exp:
1172 ISDs.push_back(ISD::FEXP);
1173 break;
1174 case Intrinsic::exp2:
1175 ISDs.push_back(ISD::FEXP2);
1176 break;
1177 case Intrinsic::log:
1178 ISDs.push_back(ISD::FLOG);
1179 break;
1180 case Intrinsic::log10:
1181 ISDs.push_back(ISD::FLOG10);
1182 break;
1183 case Intrinsic::log2:
1184 ISDs.push_back(ISD::FLOG2);
1185 break;
1186 case Intrinsic::fabs:
1187 ISDs.push_back(ISD::FABS);
1188 break;
1189 case Intrinsic::canonicalize:
1190 ISDs.push_back(ISD::FCANONICALIZE);
1191 break;
1192 case Intrinsic::minnum:
1193 ISDs.push_back(ISD::FMINNUM);
1194 if (FMF.noNaNs())
1195 ISDs.push_back(ISD::FMINIMUM);
1196 break;
1197 case Intrinsic::maxnum:
1198 ISDs.push_back(ISD::FMAXNUM);
1199 if (FMF.noNaNs())
1200 ISDs.push_back(ISD::FMAXIMUM);
1201 break;
1202 case Intrinsic::copysign:
1203 ISDs.push_back(ISD::FCOPYSIGN);
1204 break;
1205 case Intrinsic::floor:
1206 ISDs.push_back(ISD::FFLOOR);
1207 break;
1208 case Intrinsic::ceil:
1209 ISDs.push_back(ISD::FCEIL);
1210 break;
1211 case Intrinsic::trunc:
1212 ISDs.push_back(ISD::FTRUNC);
1213 break;
1214 case Intrinsic::nearbyint:
1215 ISDs.push_back(ISD::FNEARBYINT);
1216 break;
1217 case Intrinsic::rint:
1218 ISDs.push_back(ISD::FRINT);
1219 break;
1220 case Intrinsic::round:
1221 ISDs.push_back(ISD::FROUND);
1222 break;
1223 case Intrinsic::pow:
1224 ISDs.push_back(ISD::FPOW);
1225 break;
1226 case Intrinsic::fma:
1227 ISDs.push_back(ISD::FMA);
1228 break;
1229 case Intrinsic::fmuladd:
1230 ISDs.push_back(ISD::FMA);
1231 break;
1232 // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
1233 case Intrinsic::lifetime_start:
1234 case Intrinsic::lifetime_end:
1235 case Intrinsic::sideeffect:
1236 return 0;
1237 case Intrinsic::masked_store:
1238 return ConcreteTTI->getMaskedMemoryOpCost(Instruction::Store, Tys[0], 0,
1239 0);
1240 case Intrinsic::masked_load:
1241 return ConcreteTTI->getMaskedMemoryOpCost(Instruction::Load, RetTy, 0, 0);
1242 case Intrinsic::experimental_vector_reduce_add:
1243 return ConcreteTTI->getArithmeticReductionCost(Instruction::Add, Tys[0],
1244 /*IsPairwiseForm=*/false);
1245 case Intrinsic::experimental_vector_reduce_mul:
1246 return ConcreteTTI->getArithmeticReductionCost(Instruction::Mul, Tys[0],
1247 /*IsPairwiseForm=*/false);
1248 case Intrinsic::experimental_vector_reduce_and:
1249 return ConcreteTTI->getArithmeticReductionCost(Instruction::And, Tys[0],
1250 /*IsPairwiseForm=*/false);
1251 case Intrinsic::experimental_vector_reduce_or:
1252 return ConcreteTTI->getArithmeticReductionCost(Instruction::Or, Tys[0],
1253 /*IsPairwiseForm=*/false);
1254 case Intrinsic::experimental_vector_reduce_xor:
1255 return ConcreteTTI->getArithmeticReductionCost(Instruction::Xor, Tys[0],
1256 /*IsPairwiseForm=*/false);
1257 case Intrinsic::experimental_vector_reduce_fadd:
1258 return ConcreteTTI->getArithmeticReductionCost(Instruction::FAdd, Tys[0],
1259 /*IsPairwiseForm=*/false);
1260 case Intrinsic::experimental_vector_reduce_fmul:
1261 return ConcreteTTI->getArithmeticReductionCost(Instruction::FMul, Tys[0],
1262 /*IsPairwiseForm=*/false);
1263 case Intrinsic::experimental_vector_reduce_smax:
1264 case Intrinsic::experimental_vector_reduce_smin:
1265 case Intrinsic::experimental_vector_reduce_fmax:
1266 case Intrinsic::experimental_vector_reduce_fmin:
1267 return ConcreteTTI->getMinMaxReductionCost(
1268 Tys[0], CmpInst::makeCmpResultType(Tys[0]), /*IsPairwiseForm=*/false,
1269 /*IsSigned=*/true);
1270 case Intrinsic::experimental_vector_reduce_umax:
1271 case Intrinsic::experimental_vector_reduce_umin:
1272 return ConcreteTTI->getMinMaxReductionCost(
1273 Tys[0], CmpInst::makeCmpResultType(Tys[0]), /*IsPairwiseForm=*/false,
1274 /*IsSigned=*/false);
1275 case Intrinsic::sadd_sat:
1276 case Intrinsic::ssub_sat: {
1277 Type *CondTy = Type::getInt1Ty(RetTy->getContext());
1278 if (RetVF > 1)
1279 CondTy = VectorType::get(CondTy, RetVF);
1280
1281 Type *OpTy = StructType::create({RetTy, CondTy});
1282 Intrinsic::ID OverflowOp = IID == Intrinsic::sadd_sat
1283 ? Intrinsic::sadd_with_overflow
1284 : Intrinsic::ssub_with_overflow;
1285
1286 // SatMax -> Overflow && SumDiff < 0
1287 // SatMin -> Overflow && SumDiff >= 0
1288 unsigned Cost = 0;
1289 Cost += ConcreteTTI->getIntrinsicInstrCost(
1290 OverflowOp, OpTy, {RetTy, RetTy}, FMF, ScalarizationCostPassed);
1291 Cost += ConcreteTTI->getCmpSelInstrCost(BinaryOperator::ICmp, RetTy,
1292 CondTy, nullptr);
1293 Cost += 2 * ConcreteTTI->getCmpSelInstrCost(BinaryOperator::Select, RetTy,
1294 CondTy, nullptr);
1295 return Cost;
1296 }
1297 case Intrinsic::uadd_sat:
1298 case Intrinsic::usub_sat: {
1299 Type *CondTy = Type::getInt1Ty(RetTy->getContext());
1300 if (RetVF > 1)
1301 CondTy = VectorType::get(CondTy, RetVF);
1302
1303 Type *OpTy = StructType::create({RetTy, CondTy});
1304 Intrinsic::ID OverflowOp = IID == Intrinsic::uadd_sat
1305 ? Intrinsic::uadd_with_overflow
1306 : Intrinsic::usub_with_overflow;
1307
1308 unsigned Cost = 0;
1309 Cost += ConcreteTTI->getIntrinsicInstrCost(
1310 OverflowOp, OpTy, {RetTy, RetTy}, FMF, ScalarizationCostPassed);
1311 Cost += ConcreteTTI->getCmpSelInstrCost(BinaryOperator::Select, RetTy,
1312 CondTy, nullptr);
1313 return Cost;
1314 }
1315 case Intrinsic::smul_fix:
1316 case Intrinsic::umul_fix: {
1317 unsigned ExtSize = RetTy->getScalarSizeInBits() * 2;
1318 Type *ExtTy = Type::getIntNTy(RetTy->getContext(), ExtSize);
1319 if (RetVF > 1)
1320 ExtTy = VectorType::get(ExtTy, RetVF);
1321
1322 unsigned ExtOp =
1323 IID == Intrinsic::smul_fix ? Instruction::SExt : Instruction::ZExt;
1324
1325 unsigned Cost = 0;
1326 Cost += 2 * ConcreteTTI->getCastInstrCost(ExtOp, ExtTy, RetTy);
1327 Cost += ConcreteTTI->getArithmeticInstrCost(Instruction::Mul, ExtTy);
1328 Cost +=
1329 2 * ConcreteTTI->getCastInstrCost(Instruction::Trunc, RetTy, ExtTy);
1330 Cost += ConcreteTTI->getArithmeticInstrCost(Instruction::LShr, RetTy,
1331 TTI::OK_AnyValue,
1332 TTI::OK_UniformConstantValue);
1333 Cost += ConcreteTTI->getArithmeticInstrCost(Instruction::Shl, RetTy,
1334 TTI::OK_AnyValue,
1335 TTI::OK_UniformConstantValue);
1336 Cost += ConcreteTTI->getArithmeticInstrCost(Instruction::Or, RetTy);
1337 return Cost;
1338 }
1339 case Intrinsic::sadd_with_overflow:
1340 case Intrinsic::ssub_with_overflow: {
1341 Type *SumTy = RetTy->getContainedType(0);
1342 Type *OverflowTy = RetTy->getContainedType(1);
1343 unsigned Opcode = IID == Intrinsic::sadd_with_overflow
1344 ? BinaryOperator::Add
1345 : BinaryOperator::Sub;
1346
1347 // LHSSign -> LHS >= 0
1348 // RHSSign -> RHS >= 0
1349 // SumSign -> Sum >= 0
1350 //
1351 // Add:
1352 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
1353 // Sub:
1354 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
1355 unsigned Cost = 0;
1356 Cost += ConcreteTTI->getArithmeticInstrCost(Opcode, SumTy);
1357 Cost += 3 * ConcreteTTI->getCmpSelInstrCost(BinaryOperator::ICmp, SumTy,
1358 OverflowTy, nullptr);
1359 Cost += 2 * ConcreteTTI->getCmpSelInstrCost(
1360 BinaryOperator::ICmp, OverflowTy, OverflowTy, nullptr);
1361 Cost +=
1362 ConcreteTTI->getArithmeticInstrCost(BinaryOperator::And, OverflowTy);
1363 return Cost;
1364 }
1365 case Intrinsic::uadd_with_overflow:
1366 case Intrinsic::usub_with_overflow: {
1367 Type *SumTy = RetTy->getContainedType(0);
1368 Type *OverflowTy = RetTy->getContainedType(1);
1369 unsigned Opcode = IID == Intrinsic::uadd_with_overflow
1370 ? BinaryOperator::Add
1371 : BinaryOperator::Sub;
1372
1373 unsigned Cost = 0;
1374 Cost += ConcreteTTI->getArithmeticInstrCost(Opcode, SumTy);
1375 Cost += ConcreteTTI->getCmpSelInstrCost(BinaryOperator::ICmp, SumTy,
1376 OverflowTy, nullptr);
1377 return Cost;
1378 }
1379 case Intrinsic::smul_with_overflow:
1380 case Intrinsic::umul_with_overflow: {
1381 Type *MulTy = RetTy->getContainedType(0);
1382 Type *OverflowTy = RetTy->getContainedType(1);
1383 unsigned ExtSize = MulTy->getScalarSizeInBits() * 2;
1384 Type *ExtTy = Type::getIntNTy(RetTy->getContext(), ExtSize);
1385 if (MulTy->isVectorTy())
1386 ExtTy = VectorType::get(ExtTy, MulTy->getVectorNumElements() );
1387
1388 unsigned ExtOp =
1389 IID == Intrinsic::smul_fix ? Instruction::SExt : Instruction::ZExt;
1390
1391 unsigned Cost = 0;
1392 Cost += 2 * ConcreteTTI->getCastInstrCost(ExtOp, ExtTy, MulTy);
1393 Cost += ConcreteTTI->getArithmeticInstrCost(Instruction::Mul, ExtTy);
1394 Cost +=
1395 2 * ConcreteTTI->getCastInstrCost(Instruction::Trunc, MulTy, ExtTy);
1396 Cost += ConcreteTTI->getArithmeticInstrCost(Instruction::LShr, MulTy,
1397 TTI::OK_AnyValue,
1398 TTI::OK_UniformConstantValue);
1399
1400 if (IID == Intrinsic::smul_with_overflow)
1401 Cost += ConcreteTTI->getArithmeticInstrCost(
1402 Instruction::AShr, MulTy, TTI::OK_AnyValue,
1403 TTI::OK_UniformConstantValue);
1404
1405 Cost += ConcreteTTI->getCmpSelInstrCost(BinaryOperator::ICmp, MulTy,
1406 OverflowTy, nullptr);
1407 return Cost;
1408 }
1409 case Intrinsic::ctpop:
1410 ISDs.push_back(ISD::CTPOP);
1411 // In case of legalization use TCC_Expensive. This is cheaper than a
1412 // library call but still not a cheap instruction.
1413 SingleCallCost = TargetTransformInfo::TCC_Expensive;
1414 break;
1415 // FIXME: ctlz, cttz, ...
1416 }
1417
1418 const TargetLoweringBase *TLI = getTLI();
1419 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
1420
1421 SmallVector<unsigned, 2> LegalCost;
1422 SmallVector<unsigned, 2> CustomCost;
1423 for (unsigned ISD : ISDs) {
1424 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
1425 if (IID == Intrinsic::fabs && LT.second.isFloatingPoint() &&
1426 TLI->isFAbsFree(LT.second)) {
1427 return 0;
1428 }
1429
1430 // The operation is legal. Assume it costs 1.
1431 // If the type is split to multiple registers, assume that there is some
1432 // overhead to this.
1433 // TODO: Once we have extract/insert subvector cost we need to use them.
1434 if (LT.first > 1)
1435 LegalCost.push_back(LT.first * 2);
1436 else
1437 LegalCost.push_back(LT.first * 1);
1438 } else if (!TLI->isOperationExpand(ISD, LT.second)) {
1439 // If the operation is custom lowered then assume
1440 // that the code is twice as expensive.
1441 CustomCost.push_back(LT.first * 2);
1442 }
1443 }
1444
1445 auto MinLegalCostI = std::min_element(LegalCost.begin(), LegalCost.end());
1446 if (MinLegalCostI != LegalCost.end())
1447 return *MinLegalCostI;
1448
1449 auto MinCustomCostI =
1450 std::min_element(CustomCost.begin(), CustomCost.end());
1451 if (MinCustomCostI != CustomCost.end())
1452 return *MinCustomCostI;
1453
1454 // If we can't lower fmuladd into an FMA estimate the cost as a floating
1455 // point mul followed by an add.
1456 if (IID == Intrinsic::fmuladd)
1457 return ConcreteTTI->getArithmeticInstrCost(BinaryOperator::FMul, RetTy) +
1458 ConcreteTTI->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy);
1459
1460 // Else, assume that we need to scalarize this intrinsic. For math builtins
1461 // this will emit a costly libcall, adding call overhead and spills. Make it
1462 // very expensive.
1463 if (RetTy->isVectorTy()) {
1464 unsigned ScalarizationCost =
1465 ((ScalarizationCostPassed != std::numeric_limits<unsigned>::max())
1466 ? ScalarizationCostPassed
1467 : getScalarizationOverhead(RetTy, true, false));
1468 unsigned ScalarCalls = RetTy->getVectorNumElements();
1469 SmallVector<Type *, 4> ScalarTys;
1470 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1471 Type *Ty = Tys[i];
1472 if (Ty->isVectorTy())
1473 Ty = Ty->getScalarType();
1474 ScalarTys.push_back(Ty);
1475 }
1476 unsigned ScalarCost = ConcreteTTI->getIntrinsicInstrCost(
1477 IID, RetTy->getScalarType(), ScalarTys, FMF);
1478 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1479 if (Tys[i]->isVectorTy()) {
1480 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
1481 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
1482 ScalarCalls = std::max(ScalarCalls, Tys[i]->getVectorNumElements());
1483 }
1484 }
1485
1486 return ScalarCalls * ScalarCost + ScalarizationCost;
1487 }
1488
1489 // This is going to be turned into a library call, make it expensive.
1490 return SingleCallCost;
1491 }
1492
1493 /// Compute a cost of the given call instruction.
1494 ///
1495 /// Compute the cost of calling function F with return type RetTy and
1496 /// argument types Tys. F might be nullptr, in this case the cost of an
1497 /// arbitrary call with the specified signature will be returned.
1498 /// This is used, for instance, when we estimate call of a vector
1499 /// counterpart of the given function.
1500 /// \param F Called function, might be nullptr.
1501 /// \param RetTy Return value types.
1502 /// \param Tys Argument types.
1503 /// \returns The cost of Call instruction.
1504 unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
1505 return 10;
1506 }
1507
1508 unsigned getNumberOfParts(Type *Tp) {
1509 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Tp);
1510 return LT.first;
1511 }
1512
1513 unsigned getAddressComputationCost(Type *Ty, ScalarEvolution *,
1514 const SCEV *) {
1515 return 0;
1516 }
1517
1518 /// Try to calculate arithmetic and shuffle op costs for reduction operations.
1519 /// We're assuming that reduction operation are performing the following way:
1520 /// 1. Non-pairwise reduction
1521 /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
1522 /// <n x i32> <i32 n/2, i32 n/2 + 1, ..., i32 n, i32 undef, ..., i32 undef>
1523 /// \----------------v-------------/ \----------v------------/
1524 /// n/2 elements n/2 elements
1525 /// %red1 = op <n x t> %val, <n x t> val1
1526 /// After this operation we have a vector %red1 where only the first n/2
1527 /// elements are meaningful, the second n/2 elements are undefined and can be
1528 /// dropped. All other operations are actually working with the vector of
1529 /// length n/2, not n, though the real vector length is still n.
1530 /// %val2 = shufflevector<n x t> %red1, <n x t> %undef,
1531 /// <n x i32> <i32 n/4, i32 n/4 + 1, ..., i32 n/2, i32 undef, ..., i32 undef>
1532 /// \----------------v-------------/ \----------v------------/
1533 /// n/4 elements 3*n/4 elements
1534 /// %red2 = op <n x t> %red1, <n x t> val2 - working with the vector of
1535 /// length n/2, the resulting vector has length n/4 etc.
1536 /// 2. Pairwise reduction:
1537 /// Everything is the same except for an additional shuffle operation which
1538 /// is used to produce operands for pairwise kind of reductions.
1539 /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
1540 /// <n x i32> <i32 0, i32 2, ..., i32 n-2, i32 undef, ..., i32 undef>
1541 /// \-------------v----------/ \----------v------------/
1542 /// n/2 elements n/2 elements
1543 /// %val2 = shufflevector<n x t> %val, <n x t> %undef,
1544 /// <n x i32> <i32 1, i32 3, ..., i32 n-1, i32 undef, ..., i32 undef>
1545 /// \-------------v----------/ \----------v------------/
1546 /// n/2 elements n/2 elements
1547 /// %red1 = op <n x t> %val1, <n x t> val2
1548 /// Again, the operation is performed on <n x t> vector, but the resulting
1549 /// vector %red1 is <n/2 x t> vector.
1550 ///
1551 /// The cost model should take into account that the actual length of the
1552 /// vector is reduced on each iteration.
1553 unsigned getArithmeticReductionCost(unsigned Opcode, Type *Ty,
1554 bool IsPairwise) {
1555 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~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 1555, __PRETTY_FUNCTION__))
;
1556 Type *ScalarTy = Ty->getVectorElementType();
1557 unsigned NumVecElts = Ty->getVectorNumElements();
1558 unsigned NumReduxLevels = Log2_32(NumVecElts);
1559 unsigned ArithCost = 0;
1560 unsigned ShuffleCost = 0;
1561 auto *ConcreteTTI = static_cast<T *>(this);
1562 std::pair<unsigned, MVT> LT =
1563 ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
1564 unsigned LongVectorCount = 0;
1565 unsigned MVTLen =
1566 LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
1567 while (NumVecElts > MVTLen) {
1568 NumVecElts /= 2;
1569 Type *SubTy = VectorType::get(ScalarTy, NumVecElts);
1570 // Assume the pairwise shuffles add a cost.
1571 ShuffleCost += (IsPairwise + 1) *
1572 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1573 NumVecElts, SubTy);
1574 ArithCost += ConcreteTTI->getArithmeticInstrCost(Opcode, SubTy);
1575 Ty = SubTy;
1576 ++LongVectorCount;
1577 }
1578
1579 NumReduxLevels -= LongVectorCount;
1580
1581 // The minimal length of the vector is limited by the real length of vector
1582 // operations performed on the current platform. That's why several final
1583 // reduction operations are performed on the vectors with the same
1584 // architecture-dependent length.
1585
1586 // Non pairwise reductions need one shuffle per reduction level. Pairwise
1587 // reductions need two shuffles on every level, but the last one. On that
1588 // level one of the shuffles is <0, u, u, ...> which is identity.
1589 unsigned NumShuffles = NumReduxLevels;
1590 if (IsPairwise && NumReduxLevels >= 1)
1591 NumShuffles += NumReduxLevels - 1;
1592 ShuffleCost += NumShuffles *
1593 ConcreteTTI->getShuffleCost(TTI::SK_PermuteSingleSrc, Ty,
1594 0, Ty);
1595 ArithCost += NumReduxLevels *
1596 ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
1597 return ShuffleCost + ArithCost +
1598 ConcreteTTI->getVectorInstrCost(Instruction::ExtractElement, Ty, 0);
1599 }
1600
1601 /// Try to calculate op costs for min/max reduction operations.
1602 /// \param CondTy Conditional type for the Select instruction.
1603 unsigned getMinMaxReductionCost(Type *Ty, Type *CondTy, bool IsPairwise,
1604 bool) {
1605 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~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 1605, __PRETTY_FUNCTION__))
;
1606 Type *ScalarTy = Ty->getVectorElementType();
1607 Type *ScalarCondTy = CondTy->getVectorElementType();
1608 unsigned NumVecElts = Ty->getVectorNumElements();
1609 unsigned NumReduxLevels = Log2_32(NumVecElts);
1610 unsigned CmpOpcode;
1611 if (Ty->isFPOrFPVectorTy()) {
1612 CmpOpcode = Instruction::FCmp;
1613 } else {
1614 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~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 1615, __PRETTY_FUNCTION__))
1615 "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~svn362543/include/llvm/CodeGen/BasicTTIImpl.h"
, 1615, __PRETTY_FUNCTION__))
;
1616 CmpOpcode = Instruction::ICmp;
1617 }
1618 unsigned MinMaxCost = 0;
1619 unsigned ShuffleCost = 0;
1620 auto *ConcreteTTI = static_cast<T *>(this);
1621 std::pair<unsigned, MVT> LT =
1622 ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
1623 unsigned LongVectorCount = 0;
1624 unsigned MVTLen =
1625 LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
1626 while (NumVecElts > MVTLen) {
1627 NumVecElts /= 2;
1628 Type *SubTy = VectorType::get(ScalarTy, NumVecElts);
1629 CondTy = VectorType::get(ScalarCondTy, NumVecElts);
1630
1631 // Assume the pairwise shuffles add a cost.
1632 ShuffleCost += (IsPairwise + 1) *
1633 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1634 NumVecElts, SubTy);
1635 MinMaxCost +=
1636 ConcreteTTI->getCmpSelInstrCost(CmpOpcode, SubTy, CondTy, nullptr) +
1637 ConcreteTTI->getCmpSelInstrCost(Instruction::Select, SubTy, CondTy,
1638 nullptr);
1639 Ty = SubTy;
1640 ++LongVectorCount;
1641 }
1642
1643 NumReduxLevels -= LongVectorCount;
1644
1645 // The minimal length of the vector is limited by the real length of vector
1646 // operations performed on the current platform. That's why several final
1647 // reduction opertions are perfomed on the vectors with the same
1648 // architecture-dependent length.
1649
1650 // Non pairwise reductions need one shuffle per reduction level. Pairwise
1651 // reductions need two shuffles on every level, but the last one. On that
1652 // level one of the shuffles is <0, u, u, ...> which is identity.
1653 unsigned NumShuffles = NumReduxLevels;
1654 if (IsPairwise && NumReduxLevels >= 1)
1655 NumShuffles += NumReduxLevels - 1;
1656 ShuffleCost += NumShuffles *
1657 ConcreteTTI->getShuffleCost(TTI::SK_PermuteSingleSrc, Ty,
1658 0, Ty);
1659 MinMaxCost +=
1660 NumReduxLevels *
1661 (ConcreteTTI->getCmpSelInstrCost(CmpOpcode, Ty, CondTy, nullptr) +
1662 ConcreteTTI->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
1663 nullptr));
1664 // The last min/max should be in vector registers and we counted it above.
1665 // So just need a single extractelement.
1666 return ShuffleCost + MinMaxCost +
1667 ConcreteTTI->getVectorInstrCost(Instruction::ExtractElement, Ty, 0);
1668 }
1669
1670 unsigned getVectorSplitCost() { return 1; }
1671
1672 /// @}
1673};
1674
1675/// Concrete BasicTTIImpl that can be used if no further customization
1676/// is needed.
1677class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
1678 using BaseT = BasicTTIImplBase<BasicTTIImpl>;
1679
1680 friend class BasicTTIImplBase<BasicTTIImpl>;
1681
1682 const TargetSubtargetInfo *ST;
1683 const TargetLoweringBase *TLI;
1684
1685 const TargetSubtargetInfo *getST() const { return ST; }
1686 const TargetLoweringBase *getTLI() const { return TLI; }
1687
1688public:
1689 explicit BasicTTIImpl(const TargetMachine *TM, const Function &F);
1690};
1691
1692} // end namespace llvm
1693
1694#endif // LLVM_CODEGEN_BASICTTIIMPL_H

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