Bug Summary

File:lib/Transforms/Vectorize/SLPVectorizer.cpp
Warning:line 3312, column 27
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 SLPVectorizer.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -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 -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-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/lib/Transforms/Vectorize -I /build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn325118/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.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-7~svn325118/build-llvm/lib/Transforms/Vectorize -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-02-14-150435-17243-1 -x c++ /build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp

/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp

1//===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass implements the Bottom Up SLP vectorizer. It detects consecutive
11// stores that can be put together into vector-stores. Next, it attempts to
12// construct vectorizable tree using the use-def chains. If a profitable tree
13// was found, the SLP vectorizer performs vectorization on the tree.
14//
15// The pass is inspired by the work described in the paper:
16// "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
17//
18//===----------------------------------------------------------------------===//
19
20#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/DenseSet.h"
24#include "llvm/ADT/MapVector.h"
25#include "llvm/ADT/None.h"
26#include "llvm/ADT/Optional.h"
27#include "llvm/ADT/PostOrderIterator.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SetVector.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallSet.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/iterator.h"
35#include "llvm/ADT/iterator_range.h"
36#include "llvm/Analysis/AliasAnalysis.h"
37#include "llvm/Analysis/CodeMetrics.h"
38#include "llvm/Analysis/DemandedBits.h"
39#include "llvm/Analysis/GlobalsModRef.h"
40#include "llvm/Analysis/LoopAccessAnalysis.h"
41#include "llvm/Analysis/LoopInfo.h"
42#include "llvm/Analysis/MemoryLocation.h"
43#include "llvm/Analysis/OptimizationRemarkEmitter.h"
44#include "llvm/Analysis/ScalarEvolution.h"
45#include "llvm/Analysis/ScalarEvolutionExpressions.h"
46#include "llvm/Analysis/TargetLibraryInfo.h"
47#include "llvm/Analysis/TargetTransformInfo.h"
48#include "llvm/Analysis/ValueTracking.h"
49#include "llvm/Analysis/VectorUtils.h"
50#include "llvm/IR/Attributes.h"
51#include "llvm/IR/BasicBlock.h"
52#include "llvm/IR/Constant.h"
53#include "llvm/IR/Constants.h"
54#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/DebugLoc.h"
56#include "llvm/IR/DerivedTypes.h"
57#include "llvm/IR/Dominators.h"
58#include "llvm/IR/Function.h"
59#include "llvm/IR/IRBuilder.h"
60#include "llvm/IR/InstrTypes.h"
61#include "llvm/IR/Instruction.h"
62#include "llvm/IR/Instructions.h"
63#include "llvm/IR/IntrinsicInst.h"
64#include "llvm/IR/Intrinsics.h"
65#include "llvm/IR/Module.h"
66#include "llvm/IR/NoFolder.h"
67#include "llvm/IR/Operator.h"
68#include "llvm/IR/PassManager.h"
69#include "llvm/IR/PatternMatch.h"
70#include "llvm/IR/Type.h"
71#include "llvm/IR/Use.h"
72#include "llvm/IR/User.h"
73#include "llvm/IR/Value.h"
74#include "llvm/IR/ValueHandle.h"
75#include "llvm/IR/Verifier.h"
76#include "llvm/Pass.h"
77#include "llvm/Support/Casting.h"
78#include "llvm/Support/CommandLine.h"
79#include "llvm/Support/Compiler.h"
80#include "llvm/Support/DOTGraphTraits.h"
81#include "llvm/Support/Debug.h"
82#include "llvm/Support/ErrorHandling.h"
83#include "llvm/Support/GraphWriter.h"
84#include "llvm/Support/KnownBits.h"
85#include "llvm/Support/MathExtras.h"
86#include "llvm/Support/raw_ostream.h"
87#include "llvm/Transforms/Utils/LoopUtils.h"
88#include "llvm/Transforms/Vectorize.h"
89#include <algorithm>
90#include <cassert>
91#include <cstdint>
92#include <iterator>
93#include <memory>
94#include <set>
95#include <string>
96#include <tuple>
97#include <utility>
98#include <vector>
99
100using namespace llvm;
101using namespace llvm::PatternMatch;
102using namespace slpvectorizer;
103
104#define SV_NAME"slp-vectorizer" "slp-vectorizer"
105#define DEBUG_TYPE"SLP" "SLP"
106
107STATISTIC(NumVectorInstructions, "Number of vector instructions generated")static llvm::Statistic NumVectorInstructions = {"SLP", "NumVectorInstructions"
, "Number of vector instructions generated", {0}, {false}}
;
108
109static cl::opt<int>
110 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
111 cl::desc("Only vectorize if you gain more than this "
112 "number "));
113
114static cl::opt<bool>
115ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
116 cl::desc("Attempt to vectorize horizontal reductions"));
117
118static cl::opt<bool> ShouldStartVectorizeHorAtStore(
119 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
120 cl::desc(
121 "Attempt to vectorize horizontal reductions feeding into a store"));
122
123static cl::opt<int>
124MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
125 cl::desc("Attempt to vectorize for this register size in bits"));
126
127/// Limits the size of scheduling regions in a block.
128/// It avoid long compile times for _very_ large blocks where vector
129/// instructions are spread over a wide range.
130/// This limit is way higher than needed by real-world functions.
131static cl::opt<int>
132ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
133 cl::desc("Limit the size of the SLP scheduling region per block"));
134
135static cl::opt<int> MinVectorRegSizeOption(
136 "slp-min-reg-size", cl::init(128), cl::Hidden,
137 cl::desc("Attempt to vectorize for this register size in bits"));
138
139static cl::opt<unsigned> RecursionMaxDepth(
140 "slp-recursion-max-depth", cl::init(12), cl::Hidden,
141 cl::desc("Limit the recursion depth when building a vectorizable tree"));
142
143static cl::opt<unsigned> MinTreeSize(
144 "slp-min-tree-size", cl::init(3), cl::Hidden,
145 cl::desc("Only vectorize small trees if they are fully vectorizable"));
146
147static cl::opt<bool>
148 ViewSLPTree("view-slp-tree", cl::Hidden,
149 cl::desc("Display the SLP trees with Graphviz"));
150
151// Limit the number of alias checks. The limit is chosen so that
152// it has no negative effect on the llvm benchmarks.
153static const unsigned AliasedCheckLimit = 10;
154
155// Another limit for the alias checks: The maximum distance between load/store
156// instructions where alias checks are done.
157// This limit is useful for very large basic blocks.
158static const unsigned MaxMemDepDistance = 160;
159
160/// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
161/// regions to be handled.
162static const int MinScheduleRegionSize = 16;
163
164/// \brief Predicate for the element types that the SLP vectorizer supports.
165///
166/// The most important thing to filter here are types which are invalid in LLVM
167/// vectors. We also filter target specific types which have absolutely no
168/// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
169/// avoids spending time checking the cost model and realizing that they will
170/// be inevitably scalarized.
171static bool isValidElementType(Type *Ty) {
172 return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
173 !Ty->isPPC_FP128Ty();
174}
175
176/// \returns true if all of the instructions in \p VL are in the same block or
177/// false otherwise.
178static bool allSameBlock(ArrayRef<Value *> VL) {
179 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
180 if (!I0)
181 return false;
182 BasicBlock *BB = I0->getParent();
183 for (int i = 1, e = VL.size(); i < e; i++) {
184 Instruction *I = dyn_cast<Instruction>(VL[i]);
185 if (!I)
186 return false;
187
188 if (BB != I->getParent())
189 return false;
190 }
191 return true;
192}
193
194/// \returns True if all of the values in \p VL are constants.
195static bool allConstant(ArrayRef<Value *> VL) {
196 for (Value *i : VL)
197 if (!isa<Constant>(i))
198 return false;
199 return true;
200}
201
202/// \returns True if all of the values in \p VL are identical.
203static bool isSplat(ArrayRef<Value *> VL) {
204 for (unsigned i = 1, e = VL.size(); i < e; ++i)
205 if (VL[i] != VL[0])
206 return false;
207 return true;
208}
209
210/// Checks if the vector of instructions can be represented as a shuffle, like:
211/// %x0 = extractelement <4 x i8> %x, i32 0
212/// %x3 = extractelement <4 x i8> %x, i32 3
213/// %y1 = extractelement <4 x i8> %y, i32 1
214/// %y2 = extractelement <4 x i8> %y, i32 2
215/// %x0x0 = mul i8 %x0, %x0
216/// %x3x3 = mul i8 %x3, %x3
217/// %y1y1 = mul i8 %y1, %y1
218/// %y2y2 = mul i8 %y2, %y2
219/// %ins1 = insertelement <4 x i8> undef, i8 %x0x0, i32 0
220/// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
221/// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
222/// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
223/// ret <4 x i8> %ins4
224/// can be transformed into:
225/// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
226/// i32 6>
227/// %2 = mul <4 x i8> %1, %1
228/// ret <4 x i8> %2
229/// We convert this initially to something like:
230/// %x0 = extractelement <4 x i8> %x, i32 0
231/// %x3 = extractelement <4 x i8> %x, i32 3
232/// %y1 = extractelement <4 x i8> %y, i32 1
233/// %y2 = extractelement <4 x i8> %y, i32 2
234/// %1 = insertelement <4 x i8> undef, i8 %x0, i32 0
235/// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
236/// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
237/// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
238/// %5 = mul <4 x i8> %4, %4
239/// %6 = extractelement <4 x i8> %5, i32 0
240/// %ins1 = insertelement <4 x i8> undef, i8 %6, i32 0
241/// %7 = extractelement <4 x i8> %5, i32 1
242/// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
243/// %8 = extractelement <4 x i8> %5, i32 2
244/// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
245/// %9 = extractelement <4 x i8> %5, i32 3
246/// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
247/// ret <4 x i8> %ins4
248/// InstCombiner transforms this into a shuffle and vector mul
249static Optional<TargetTransformInfo::ShuffleKind>
250isShuffle(ArrayRef<Value *> VL) {
251 auto *EI0 = cast<ExtractElementInst>(VL[0]);
252 unsigned Size = EI0->getVectorOperandType()->getVectorNumElements();
253 Value *Vec1 = nullptr;
254 Value *Vec2 = nullptr;
255 enum ShuffleMode {Unknown, FirstAlternate, SecondAlternate, Permute};
256 ShuffleMode CommonShuffleMode = Unknown;
257 for (unsigned I = 0, E = VL.size(); I < E; ++I) {
258 auto *EI = cast<ExtractElementInst>(VL[I]);
259 auto *Vec = EI->getVectorOperand();
260 // All vector operands must have the same number of vector elements.
261 if (Vec->getType()->getVectorNumElements() != Size)
262 return None;
263 auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
264 if (!Idx)
265 return None;
266 // Undefined behavior if Idx is negative or >= Size.
267 if (Idx->getValue().uge(Size))
268 continue;
269 unsigned IntIdx = Idx->getValue().getZExtValue();
270 // We can extractelement from undef vector.
271 if (isa<UndefValue>(Vec))
272 continue;
273 // For correct shuffling we have to have at most 2 different vector operands
274 // in all extractelement instructions.
275 if (Vec1 && Vec2 && Vec != Vec1 && Vec != Vec2)
276 return None;
277 if (CommonShuffleMode == Permute)
278 continue;
279 // If the extract index is not the same as the operation number, it is a
280 // permutation.
281 if (IntIdx != I) {
282 CommonShuffleMode = Permute;
283 continue;
284 }
285 // Check the shuffle mode for the current operation.
286 if (!Vec1)
287 Vec1 = Vec;
288 else if (Vec != Vec1)
289 Vec2 = Vec;
290 // Example: shufflevector A, B, <0,5,2,7>
291 // I is odd and IntIdx for A == I - FirstAlternate shuffle.
292 // I is even and IntIdx for B == I - FirstAlternate shuffle.
293 // Example: shufflevector A, B, <4,1,6,3>
294 // I is even and IntIdx for A == I - SecondAlternate shuffle.
295 // I is odd and IntIdx for B == I - SecondAlternate shuffle.
296 const bool IIsEven = I & 1;
297 const bool CurrVecIsA = Vec == Vec1;
298 const bool IIsOdd = !IIsEven;
299 const bool CurrVecIsB = !CurrVecIsA;
300 ShuffleMode CurrentShuffleMode =
301 ((IIsOdd && CurrVecIsA) || (IIsEven && CurrVecIsB)) ? FirstAlternate
302 : SecondAlternate;
303 // Common mode is not set or the same as the shuffle mode of the current
304 // operation - alternate.
305 if (CommonShuffleMode == Unknown)
306 CommonShuffleMode = CurrentShuffleMode;
307 // Common shuffle mode is not the same as the shuffle mode of the current
308 // operation - permutation.
309 if (CommonShuffleMode != CurrentShuffleMode)
310 CommonShuffleMode = Permute;
311 }
312 // If we're not crossing lanes in different vectors, consider it as blending.
313 if ((CommonShuffleMode == FirstAlternate ||
314 CommonShuffleMode == SecondAlternate) &&
315 Vec2)
316 return TargetTransformInfo::SK_Alternate;
317 // If Vec2 was never used, we have a permutation of a single vector, otherwise
318 // we have permutation of 2 vectors.
319 return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
320 : TargetTransformInfo::SK_PermuteSingleSrc;
321}
322
323///\returns Opcode that can be clubbed with \p Op to create an alternate
324/// sequence which can later be merged as a ShuffleVector instruction.
325static unsigned getAltOpcode(unsigned Op) {
326 switch (Op) {
327 case Instruction::FAdd:
328 return Instruction::FSub;
329 case Instruction::FSub:
330 return Instruction::FAdd;
331 case Instruction::Add:
332 return Instruction::Sub;
333 case Instruction::Sub:
334 return Instruction::Add;
335 default:
336 return 0;
337 }
338}
339
340static bool isOdd(unsigned Value) {
341 return Value & 1;
342}
343
344static bool sameOpcodeOrAlt(unsigned Opcode, unsigned AltOpcode,
345 unsigned CheckedOpcode) {
346 return Opcode == CheckedOpcode || AltOpcode == CheckedOpcode;
347}
348
349/// Chooses the correct key for scheduling data. If \p Op has the same (or
350/// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
351/// OpValue.
352static Value *isOneOf(Value *OpValue, Value *Op) {
353 auto *I = dyn_cast<Instruction>(Op);
354 if (!I)
355 return OpValue;
356 auto *OpInst = cast<Instruction>(OpValue);
357 unsigned OpInstOpcode = OpInst->getOpcode();
358 unsigned IOpcode = I->getOpcode();
359 if (sameOpcodeOrAlt(OpInstOpcode, getAltOpcode(OpInstOpcode), IOpcode))
360 return Op;
361 return OpValue;
362}
363
364namespace {
365
366/// Contains data for the instructions going to be vectorized.
367struct RawInstructionsData {
368 /// Main Opcode of the instructions going to be vectorized.
369 unsigned Opcode = 0;
370
371 /// The list of instructions have some instructions with alternate opcodes.
372 bool HasAltOpcodes = false;
373};
374
375} // end anonymous namespace
376
377/// Checks the list of the vectorized instructions \p VL and returns info about
378/// this list.
379static RawInstructionsData getMainOpcode(ArrayRef<Value *> VL) {
380 auto *I0 = dyn_cast<Instruction>(VL[0]);
381 if (!I0)
382 return {};
383 RawInstructionsData Res;
384 unsigned Opcode = I0->getOpcode();
385 // Walk through the list of the vectorized instructions
386 // in order to check its structure described by RawInstructionsData.
387 for (unsigned Cnt = 0, E = VL.size(); Cnt != E; ++Cnt) {
388 auto *I = dyn_cast<Instruction>(VL[Cnt]);
389 if (!I)
390 return {};
391 if (Opcode != I->getOpcode())
392 Res.HasAltOpcodes = true;
393 }
394 Res.Opcode = Opcode;
395 return Res;
396}
397
398namespace {
399
400/// Main data required for vectorization of instructions.
401struct InstructionsState {
402 /// The very first instruction in the list with the main opcode.
403 Value *OpValue = nullptr;
404
405 /// The main opcode for the list of instructions.
406 unsigned Opcode = 0;
407
408 /// Some of the instructions in the list have alternate opcodes.
409 bool IsAltShuffle = false;
410
411 InstructionsState() = default;
412 InstructionsState(Value *OpValue, unsigned Opcode, bool IsAltShuffle)
413 : OpValue(OpValue), Opcode(Opcode), IsAltShuffle(IsAltShuffle) {}
414};
415
416} // end anonymous namespace
417
418/// \returns analysis of the Instructions in \p VL described in
419/// InstructionsState, the Opcode that we suppose the whole list
420/// could be vectorized even if its structure is diverse.
421static InstructionsState getSameOpcode(ArrayRef<Value *> VL) {
422 auto Res = getMainOpcode(VL);
423 unsigned Opcode = Res.Opcode;
424 if (!Res.HasAltOpcodes)
425 return InstructionsState(VL[0], Opcode, false);
426 auto *OpInst = cast<Instruction>(VL[0]);
427 unsigned AltOpcode = getAltOpcode(Opcode);
428 // Examine each element in the list instructions VL to determine
429 // if some operations there could be considered as an alternative
430 // (for example as subtraction relates to addition operation).
431 for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
432 auto *I = cast<Instruction>(VL[Cnt]);
433 unsigned InstOpcode = I->getOpcode();
434 if ((Res.HasAltOpcodes &&
435 InstOpcode != (isOdd(Cnt) ? AltOpcode : Opcode)) ||
436 (!Res.HasAltOpcodes && InstOpcode != Opcode)) {
437 return InstructionsState(OpInst, 0, false);
438 }
439 }
440 return InstructionsState(OpInst, Opcode, Res.HasAltOpcodes);
441}
442
443/// \returns true if all of the values in \p VL have the same type or false
444/// otherwise.
445static bool allSameType(ArrayRef<Value *> VL) {
446 Type *Ty = VL[0]->getType();
447 for (int i = 1, e = VL.size(); i < e; i++)
448 if (VL[i]->getType() != Ty)
449 return false;
450
451 return true;
452}
453
454/// \returns True if Extract{Value,Element} instruction extracts element Idx.
455static bool matchExtractIndex(Instruction *E, unsigned Idx, unsigned Opcode) {
456 assert(Opcode == Instruction::ExtractElement ||(static_cast <bool> (Opcode == Instruction::ExtractElement
|| Opcode == Instruction::ExtractValue) ? void (0) : __assert_fail
("Opcode == Instruction::ExtractElement || Opcode == Instruction::ExtractValue"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 457, __extension__ __PRETTY_FUNCTION__))
457 Opcode == Instruction::ExtractValue)(static_cast <bool> (Opcode == Instruction::ExtractElement
|| Opcode == Instruction::ExtractValue) ? void (0) : __assert_fail
("Opcode == Instruction::ExtractElement || Opcode == Instruction::ExtractValue"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 457, __extension__ __PRETTY_FUNCTION__))
;
458 if (Opcode == Instruction::ExtractElement) {
459 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
460 return CI && CI->getZExtValue() == Idx;
461 } else {
462 ExtractValueInst *EI = cast<ExtractValueInst>(E);
463 return EI->getNumIndices() == 1 && *EI->idx_begin() == Idx;
464 }
465}
466
467/// \returns True if in-tree use also needs extract. This refers to
468/// possible scalar operand in vectorized instruction.
469static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
470 TargetLibraryInfo *TLI) {
471 unsigned Opcode = UserInst->getOpcode();
472 switch (Opcode) {
473 case Instruction::Load: {
474 LoadInst *LI = cast<LoadInst>(UserInst);
475 return (LI->getPointerOperand() == Scalar);
476 }
477 case Instruction::Store: {
478 StoreInst *SI = cast<StoreInst>(UserInst);
479 return (SI->getPointerOperand() == Scalar);
480 }
481 case Instruction::Call: {
482 CallInst *CI = cast<CallInst>(UserInst);
483 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
484 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
485 return (CI->getArgOperand(1) == Scalar);
486 }
487 LLVM_FALLTHROUGH[[clang::fallthrough]];
488 }
489 default:
490 return false;
491 }
492}
493
494/// \returns the AA location that is being access by the instruction.
495static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA) {
496 if (StoreInst *SI = dyn_cast<StoreInst>(I))
497 return MemoryLocation::get(SI);
498 if (LoadInst *LI = dyn_cast<LoadInst>(I))
499 return MemoryLocation::get(LI);
500 return MemoryLocation();
501}
502
503/// \returns True if the instruction is not a volatile or atomic load/store.
504static bool isSimple(Instruction *I) {
505 if (LoadInst *LI = dyn_cast<LoadInst>(I))
506 return LI->isSimple();
507 if (StoreInst *SI = dyn_cast<StoreInst>(I))
508 return SI->isSimple();
509 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
510 return !MI->isVolatile();
511 return true;
512}
513
514namespace llvm {
515
516namespace slpvectorizer {
517
518/// Bottom Up SLP Vectorizer.
519class BoUpSLP {
520public:
521 using ValueList = SmallVector<Value *, 8>;
522 using InstrList = SmallVector<Instruction *, 16>;
523 using ValueSet = SmallPtrSet<Value *, 16>;
524 using StoreList = SmallVector<StoreInst *, 8>;
525 using ExtraValueToDebugLocsMap =
526 MapVector<Value *, SmallVector<Instruction *, 2>>;
527
528 BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
529 TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li,
530 DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
531 const DataLayout *DL, OptimizationRemarkEmitter *ORE)
532 : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
533 DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
534 CodeMetrics::collectEphemeralValues(F, AC, EphValues);
535 // Use the vector register size specified by the target unless overridden
536 // by a command-line option.
537 // TODO: It would be better to limit the vectorization factor based on
538 // data type rather than just register size. For example, x86 AVX has
539 // 256-bit registers, but it does not support integer operations
540 // at that width (that requires AVX2).
541 if (MaxVectorRegSizeOption.getNumOccurrences())
542 MaxVecRegSize = MaxVectorRegSizeOption;
543 else
544 MaxVecRegSize = TTI->getRegisterBitWidth(true);
545
546 if (MinVectorRegSizeOption.getNumOccurrences())
547 MinVecRegSize = MinVectorRegSizeOption;
548 else
549 MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
550 }
551
552 /// \brief Vectorize the tree that starts with the elements in \p VL.
553 /// Returns the vectorized root.
554 Value *vectorizeTree();
555
556 /// Vectorize the tree but with the list of externally used values \p
557 /// ExternallyUsedValues. Values in this MapVector can be replaced but the
558 /// generated extractvalue instructions.
559 Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
560
561 /// \returns the cost incurred by unwanted spills and fills, caused by
562 /// holding live values over call sites.
563 int getSpillCost();
564
565 /// \returns the vectorization cost of the subtree that starts at \p VL.
566 /// A negative number means that this is profitable.
567 int getTreeCost();
568
569 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
570 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
571 void buildTree(ArrayRef<Value *> Roots,
572 ArrayRef<Value *> UserIgnoreLst = None);
573
574 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
575 /// the purpose of scheduling and extraction in the \p UserIgnoreLst taking
576 /// into account (anf updating it, if required) list of externally used
577 /// values stored in \p ExternallyUsedValues.
578 void buildTree(ArrayRef<Value *> Roots,
579 ExtraValueToDebugLocsMap &ExternallyUsedValues,
580 ArrayRef<Value *> UserIgnoreLst = None);
581
582 /// Clear the internal data structures that are created by 'buildTree'.
583 void deleteTree() {
584 VectorizableTree.clear();
585 ScalarToTreeEntry.clear();
586 MustGather.clear();
587 ExternalUses.clear();
588 NumOpsWantToKeepOrder.clear();
589 for (auto &Iter : BlocksSchedules) {
590 BlockScheduling *BS = Iter.second.get();
591 BS->clear();
592 }
593 MinBWs.clear();
594 }
595
596 unsigned getTreeSize() const { return VectorizableTree.size(); }
597
598 /// \brief Perform LICM and CSE on the newly generated gather sequences.
599 void optimizeGatherSequence();
600
601 /// \returns true if it is beneficial to reverse the vector order.
602 bool shouldReorder() const {
603 return std::accumulate(
604 NumOpsWantToKeepOrder.begin(), NumOpsWantToKeepOrder.end(), 0,
605 [](int Val1,
606 const decltype(NumOpsWantToKeepOrder)::value_type &Val2) {
607 return Val1 + (Val2.second < 0 ? 1 : -1);
608 }) > 0;
609 }
610
611 /// \return The vector element size in bits to use when vectorizing the
612 /// expression tree ending at \p V. If V is a store, the size is the width of
613 /// the stored value. Otherwise, the size is the width of the largest loaded
614 /// value reaching V. This method is used by the vectorizer to calculate
615 /// vectorization factors.
616 unsigned getVectorElementSize(Value *V);
617
618 /// Compute the minimum type sizes required to represent the entries in a
619 /// vectorizable tree.
620 void computeMinimumValueSizes();
621
622 // \returns maximum vector register size as set by TTI or overridden by cl::opt.
623 unsigned getMaxVecRegSize() const {
624 return MaxVecRegSize;
625 }
626
627 // \returns minimum vector register size as set by cl::opt.
628 unsigned getMinVecRegSize() const {
629 return MinVecRegSize;
630 }
631
632 /// \brief Check if ArrayType or StructType is isomorphic to some VectorType.
633 ///
634 /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
635 unsigned canMapToVector(Type *T, const DataLayout &DL) const;
636
637 /// \returns True if the VectorizableTree is both tiny and not fully
638 /// vectorizable. We do not vectorize such trees.
639 bool isTreeTinyAndNotFullyVectorizable();
640
641 OptimizationRemarkEmitter *getORE() { return ORE; }
642
643private:
644 struct TreeEntry;
645
646 /// Checks if all users of \p I are the part of the vectorization tree.
647 bool areAllUsersVectorized(Instruction *I) const;
648
649 /// \returns the cost of the vectorizable entry.
650 int getEntryCost(TreeEntry *E);
651
652 /// This is the recursive part of buildTree.
653 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth, int);
654
655 /// \returns True if the ExtractElement/ExtractValue instructions in VL can
656 /// be vectorized to use the original vector (or aggregate "bitcast" to a vector).
657 bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue) const;
658
659 /// Vectorize a single entry in the tree.
660 Value *vectorizeTree(TreeEntry *E);
661
662 /// Vectorize a single entry in the tree, starting in \p VL.
663 Value *vectorizeTree(ArrayRef<Value *> VL);
664
665 /// \returns the scalarization cost for this type. Scalarization in this
666 /// context means the creation of vectors from a group of scalars.
667 int getGatherCost(Type *Ty, const DenseSet<unsigned> &ShuffledIndices);
668
669 /// \returns the scalarization cost for this list of values. Assuming that
670 /// this subtree gets vectorized, we may need to extract the values from the
671 /// roots. This method calculates the cost of extracting the values.
672 int getGatherCost(ArrayRef<Value *> VL);
673
674 /// \brief Set the Builder insert point to one after the last instruction in
675 /// the bundle
676 void setInsertPointAfterBundle(ArrayRef<Value *> VL, Value *OpValue);
677
678 /// \returns a vector from a collection of scalars in \p VL.
679 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
680
681 /// \returns whether the VectorizableTree is fully vectorizable and will
682 /// be beneficial even the tree height is tiny.
683 bool isFullyVectorizableTinyTree();
684
685 /// \reorder commutative operands in alt shuffle if they result in
686 /// vectorized code.
687 void reorderAltShuffleOperands(unsigned Opcode, ArrayRef<Value *> VL,
688 SmallVectorImpl<Value *> &Left,
689 SmallVectorImpl<Value *> &Right);
690
691 /// \reorder commutative operands to get better probability of
692 /// generating vectorized code.
693 void reorderInputsAccordingToOpcode(unsigned Opcode, ArrayRef<Value *> VL,
694 SmallVectorImpl<Value *> &Left,
695 SmallVectorImpl<Value *> &Right);
696 struct TreeEntry {
697 TreeEntry(std::vector<TreeEntry> &Container) : Container(Container) {}
698
699 /// \returns true if the scalars in VL are equal to this entry.
700 bool isSame(ArrayRef<Value *> VL) const {
701 if (VL.size() == Scalars.size())
702 return std::equal(VL.begin(), VL.end(), Scalars.begin());
703 return VL.size() == ReuseShuffleIndices.size() &&
704 std::equal(
705 VL.begin(), VL.end(), ReuseShuffleIndices.begin(),
706 [this](Value *V, unsigned Idx) { return V == Scalars[Idx]; });
707 }
708
709 /// A vector of scalars.
710 ValueList Scalars;
711
712 /// The Scalars are vectorized into this value. It is initialized to Null.
713 Value *VectorizedValue = nullptr;
714
715 /// Do we need to gather this sequence ?
716 bool NeedToGather = false;
717
718 /// Does this sequence require some shuffling?
719 SmallVector<unsigned, 4> ReuseShuffleIndices;
720
721 /// Points back to the VectorizableTree.
722 ///
723 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has
724 /// to be a pointer and needs to be able to initialize the child iterator.
725 /// Thus we need a reference back to the container to translate the indices
726 /// to entries.
727 std::vector<TreeEntry> &Container;
728
729 /// The TreeEntry index containing the user of this entry. We can actually
730 /// have multiple users so the data structure is not truly a tree.
731 SmallVector<int, 1> UserTreeIndices;
732 };
733
734 /// Create a new VectorizableTree entry.
735 void newTreeEntry(ArrayRef<Value *> VL, bool Vectorized, int &UserTreeIdx,
736 ArrayRef<unsigned> ReuseShuffleIndices = None) {
737 VectorizableTree.emplace_back(VectorizableTree);
738 int idx = VectorizableTree.size() - 1;
739 TreeEntry *Last = &VectorizableTree[idx];
740 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
741 Last->NeedToGather = !Vectorized;
742 Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
743 ReuseShuffleIndices.end());
744 if (Vectorized) {
745 for (int i = 0, e = VL.size(); i != e; ++i) {
746 assert(!getTreeEntry(VL[i]) && "Scalar already in tree!")(static_cast <bool> (!getTreeEntry(VL[i]) && "Scalar already in tree!"
) ? void (0) : __assert_fail ("!getTreeEntry(VL[i]) && \"Scalar already in tree!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 746, __extension__ __PRETTY_FUNCTION__))
;
747 ScalarToTreeEntry[VL[i]] = idx;
748 }
749 } else {
750 MustGather.insert(VL.begin(), VL.end());
751 }
752
753 if (UserTreeIdx >= 0)
754 Last->UserTreeIndices.push_back(UserTreeIdx);
755 UserTreeIdx = idx;
756 }
757
758 /// -- Vectorization State --
759 /// Holds all of the tree entries.
760 std::vector<TreeEntry> VectorizableTree;
761
762 TreeEntry *getTreeEntry(Value *V) {
763 auto I = ScalarToTreeEntry.find(V);
764 if (I != ScalarToTreeEntry.end())
765 return &VectorizableTree[I->second];
766 return nullptr;
767 }
768
769 /// Maps a specific scalar to its tree entry.
770 SmallDenseMap<Value*, int> ScalarToTreeEntry;
771
772 /// A list of scalars that we found that we need to keep as scalars.
773 ValueSet MustGather;
774
775 /// This POD struct describes one external user in the vectorized tree.
776 struct ExternalUser {
777 ExternalUser(Value *S, llvm::User *U, int L)
778 : Scalar(S), User(U), Lane(L) {}
779
780 // Which scalar in our function.
781 Value *Scalar;
782
783 // Which user that uses the scalar.
784 llvm::User *User;
785
786 // Which lane does the scalar belong to.
787 int Lane;
788 };
789 using UserList = SmallVector<ExternalUser, 16>;
790
791 /// Checks if two instructions may access the same memory.
792 ///
793 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
794 /// is invariant in the calling loop.
795 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
796 Instruction *Inst2) {
797 // First check if the result is already in the cache.
798 AliasCacheKey key = std::make_pair(Inst1, Inst2);
799 Optional<bool> &result = AliasCache[key];
800 if (result.hasValue()) {
801 return result.getValue();
802 }
803 MemoryLocation Loc2 = getLocation(Inst2, AA);
804 bool aliased = true;
805 if (Loc1.Ptr && Loc2.Ptr && isSimple(Inst1) && isSimple(Inst2)) {
806 // Do the alias check.
807 aliased = AA->alias(Loc1, Loc2);
808 }
809 // Store the result in the cache.
810 result = aliased;
811 return aliased;
812 }
813
814 using AliasCacheKey = std::pair<Instruction *, Instruction *>;
815
816 /// Cache for alias results.
817 /// TODO: consider moving this to the AliasAnalysis itself.
818 DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
819
820 /// Removes an instruction from its block and eventually deletes it.
821 /// It's like Instruction::eraseFromParent() except that the actual deletion
822 /// is delayed until BoUpSLP is destructed.
823 /// This is required to ensure that there are no incorrect collisions in the
824 /// AliasCache, which can happen if a new instruction is allocated at the
825 /// same address as a previously deleted instruction.
826 void eraseInstruction(Instruction *I) {
827 I->removeFromParent();
828 I->dropAllReferences();
829 DeletedInstructions.emplace_back(I);
830 }
831
832 /// Temporary store for deleted instructions. Instructions will be deleted
833 /// eventually when the BoUpSLP is destructed.
834 SmallVector<unique_value, 8> DeletedInstructions;
835
836 /// A list of values that need to extracted out of the tree.
837 /// This list holds pairs of (Internal Scalar : External User). External User
838 /// can be nullptr, it means that this Internal Scalar will be used later,
839 /// after vectorization.
840 UserList ExternalUses;
841
842 /// Values used only by @llvm.assume calls.
843 SmallPtrSet<const Value *, 32> EphValues;
844
845 /// Holds all of the instructions that we gathered.
846 SetVector<Instruction *> GatherSeq;
847
848 /// A list of blocks that we are going to CSE.
849 SetVector<BasicBlock *> CSEBlocks;
850
851 /// Contains all scheduling relevant data for an instruction.
852 /// A ScheduleData either represents a single instruction or a member of an
853 /// instruction bundle (= a group of instructions which is combined into a
854 /// vector instruction).
855 struct ScheduleData {
856 // The initial value for the dependency counters. It means that the
857 // dependencies are not calculated yet.
858 enum { InvalidDeps = -1 };
859
860 ScheduleData() = default;
861
862 void init(int BlockSchedulingRegionID, Value *OpVal) {
863 FirstInBundle = this;
864 NextInBundle = nullptr;
865 NextLoadStore = nullptr;
866 IsScheduled = false;
867 SchedulingRegionID = BlockSchedulingRegionID;
868 UnscheduledDepsInBundle = UnscheduledDeps;
869 clearDependencies();
870 OpValue = OpVal;
871 }
872
873 /// Returns true if the dependency information has been calculated.
874 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
875
876 /// Returns true for single instructions and for bundle representatives
877 /// (= the head of a bundle).
878 bool isSchedulingEntity() const { return FirstInBundle == this; }
879
880 /// Returns true if it represents an instruction bundle and not only a
881 /// single instruction.
882 bool isPartOfBundle() const {
883 return NextInBundle != nullptr || FirstInBundle != this;
884 }
885
886 /// Returns true if it is ready for scheduling, i.e. it has no more
887 /// unscheduled depending instructions/bundles.
888 bool isReady() const {
889 assert(isSchedulingEntity() &&(static_cast <bool> (isSchedulingEntity() && "can't consider non-scheduling entity for ready list"
) ? void (0) : __assert_fail ("isSchedulingEntity() && \"can't consider non-scheduling entity for ready list\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 890, __extension__ __PRETTY_FUNCTION__))
890 "can't consider non-scheduling entity for ready list")(static_cast <bool> (isSchedulingEntity() && "can't consider non-scheduling entity for ready list"
) ? void (0) : __assert_fail ("isSchedulingEntity() && \"can't consider non-scheduling entity for ready list\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 890, __extension__ __PRETTY_FUNCTION__))
;
891 return UnscheduledDepsInBundle == 0 && !IsScheduled;
892 }
893
894 /// Modifies the number of unscheduled dependencies, also updating it for
895 /// the whole bundle.
896 int incrementUnscheduledDeps(int Incr) {
897 UnscheduledDeps += Incr;
898 return FirstInBundle->UnscheduledDepsInBundle += Incr;
899 }
900
901 /// Sets the number of unscheduled dependencies to the number of
902 /// dependencies.
903 void resetUnscheduledDeps() {
904 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
905 }
906
907 /// Clears all dependency information.
908 void clearDependencies() {
909 Dependencies = InvalidDeps;
910 resetUnscheduledDeps();
911 MemoryDependencies.clear();
912 }
913
914 void dump(raw_ostream &os) const {
915 if (!isSchedulingEntity()) {
916 os << "/ " << *Inst;
917 } else if (NextInBundle) {
918 os << '[' << *Inst;
919 ScheduleData *SD = NextInBundle;
920 while (SD) {
921 os << ';' << *SD->Inst;
922 SD = SD->NextInBundle;
923 }
924 os << ']';
925 } else {
926 os << *Inst;
927 }
928 }
929
930 Instruction *Inst = nullptr;
931
932 /// Points to the head in an instruction bundle (and always to this for
933 /// single instructions).
934 ScheduleData *FirstInBundle = nullptr;
935
936 /// Single linked list of all instructions in a bundle. Null if it is a
937 /// single instruction.
938 ScheduleData *NextInBundle = nullptr;
939
940 /// Single linked list of all memory instructions (e.g. load, store, call)
941 /// in the block - until the end of the scheduling region.
942 ScheduleData *NextLoadStore = nullptr;
943
944 /// The dependent memory instructions.
945 /// This list is derived on demand in calculateDependencies().
946 SmallVector<ScheduleData *, 4> MemoryDependencies;
947
948 /// This ScheduleData is in the current scheduling region if this matches
949 /// the current SchedulingRegionID of BlockScheduling.
950 int SchedulingRegionID = 0;
951
952 /// Used for getting a "good" final ordering of instructions.
953 int SchedulingPriority = 0;
954
955 /// The number of dependencies. Constitutes of the number of users of the
956 /// instruction plus the number of dependent memory instructions (if any).
957 /// This value is calculated on demand.
958 /// If InvalidDeps, the number of dependencies is not calculated yet.
959 int Dependencies = InvalidDeps;
960
961 /// The number of dependencies minus the number of dependencies of scheduled
962 /// instructions. As soon as this is zero, the instruction/bundle gets ready
963 /// for scheduling.
964 /// Note that this is negative as long as Dependencies is not calculated.
965 int UnscheduledDeps = InvalidDeps;
966
967 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
968 /// single instructions.
969 int UnscheduledDepsInBundle = InvalidDeps;
970
971 /// True if this instruction is scheduled (or considered as scheduled in the
972 /// dry-run).
973 bool IsScheduled = false;
974
975 /// Opcode of the current instruction in the schedule data.
976 Value *OpValue = nullptr;
977 };
978
979#ifndef NDEBUG
980 friend inline raw_ostream &operator<<(raw_ostream &os,
981 const BoUpSLP::ScheduleData &SD) {
982 SD.dump(os);
983 return os;
984 }
985#endif
986
987 friend struct GraphTraits<BoUpSLP *>;
988 friend struct DOTGraphTraits<BoUpSLP *>;
989
990 /// Contains all scheduling data for a basic block.
991 struct BlockScheduling {
992 BlockScheduling(BasicBlock *BB)
993 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
994
995 void clear() {
996 ReadyInsts.clear();
997 ScheduleStart = nullptr;
998 ScheduleEnd = nullptr;
999 FirstLoadStoreInRegion = nullptr;
1000 LastLoadStoreInRegion = nullptr;
1001
1002 // Reduce the maximum schedule region size by the size of the
1003 // previous scheduling run.
1004 ScheduleRegionSizeLimit -= ScheduleRegionSize;
1005 if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
1006 ScheduleRegionSizeLimit = MinScheduleRegionSize;
1007 ScheduleRegionSize = 0;
1008
1009 // Make a new scheduling region, i.e. all existing ScheduleData is not
1010 // in the new region yet.
1011 ++SchedulingRegionID;
1012 }
1013
1014 ScheduleData *getScheduleData(Value *V) {
1015 ScheduleData *SD = ScheduleDataMap[V];
1016 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
1017 return SD;
1018 return nullptr;
1019 }
1020
1021 ScheduleData *getScheduleData(Value *V, Value *Key) {
1022 if (V == Key)
1023 return getScheduleData(V);
1024 auto I = ExtraScheduleDataMap.find(V);
1025 if (I != ExtraScheduleDataMap.end()) {
1026 ScheduleData *SD = I->second[Key];
1027 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
1028 return SD;
1029 }
1030 return nullptr;
1031 }
1032
1033 bool isInSchedulingRegion(ScheduleData *SD) {
1034 return SD->SchedulingRegionID == SchedulingRegionID;
1035 }
1036
1037 /// Marks an instruction as scheduled and puts all dependent ready
1038 /// instructions into the ready-list.
1039 template <typename ReadyListType>
1040 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
1041 SD->IsScheduled = true;
1042 DEBUG(dbgs() << "SLP: schedule " << *SD << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: schedule " << *SD <<
"\n"; } } while (false)
;
1043
1044 ScheduleData *BundleMember = SD;
1045 while (BundleMember) {
1046 if (BundleMember->Inst != BundleMember->OpValue) {
1047 BundleMember = BundleMember->NextInBundle;
1048 continue;
1049 }
1050 // Handle the def-use chain dependencies.
1051 for (Use &U : BundleMember->Inst->operands()) {
1052 auto *I = dyn_cast<Instruction>(U.get());
1053 if (!I)
1054 continue;
1055 doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
1056 if (OpDef && OpDef->hasValidDependencies() &&
1057 OpDef->incrementUnscheduledDeps(-1) == 0) {
1058 // There are no more unscheduled dependencies after
1059 // decrementing, so we can put the dependent instruction
1060 // into the ready list.
1061 ScheduleData *DepBundle = OpDef->FirstInBundle;
1062 assert(!DepBundle->IsScheduled &&(static_cast <bool> (!DepBundle->IsScheduled &&
"already scheduled bundle gets ready") ? void (0) : __assert_fail
("!DepBundle->IsScheduled && \"already scheduled bundle gets ready\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 1063, __extension__ __PRETTY_FUNCTION__))
1063 "already scheduled bundle gets ready")(static_cast <bool> (!DepBundle->IsScheduled &&
"already scheduled bundle gets ready") ? void (0) : __assert_fail
("!DepBundle->IsScheduled && \"already scheduled bundle gets ready\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 1063, __extension__ __PRETTY_FUNCTION__))
;
1064 ReadyList.insert(DepBundle);
1065 DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: gets ready (def): " <<
*DepBundle << "\n"; } } while (false)
1066 << "SLP: gets ready (def): " << *DepBundle << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: gets ready (def): " <<
*DepBundle << "\n"; } } while (false)
;
1067 }
1068 });
1069 }
1070 // Handle the memory dependencies.
1071 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
1072 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
1073 // There are no more unscheduled dependencies after decrementing,
1074 // so we can put the dependent instruction into the ready list.
1075 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
1076 assert(!DepBundle->IsScheduled &&(static_cast <bool> (!DepBundle->IsScheduled &&
"already scheduled bundle gets ready") ? void (0) : __assert_fail
("!DepBundle->IsScheduled && \"already scheduled bundle gets ready\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 1077, __extension__ __PRETTY_FUNCTION__))
1077 "already scheduled bundle gets ready")(static_cast <bool> (!DepBundle->IsScheduled &&
"already scheduled bundle gets ready") ? void (0) : __assert_fail
("!DepBundle->IsScheduled && \"already scheduled bundle gets ready\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 1077, __extension__ __PRETTY_FUNCTION__))
;
1078 ReadyList.insert(DepBundle);
1079 DEBUG(dbgs() << "SLP: gets ready (mem): " << *DepBundledo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: gets ready (mem): " <<
*DepBundle << "\n"; } } while (false)
1080 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: gets ready (mem): " <<
*DepBundle << "\n"; } } while (false)
;
1081 }
1082 }
1083 BundleMember = BundleMember->NextInBundle;
1084 }
1085 }
1086
1087 void doForAllOpcodes(Value *V,
1088 function_ref<void(ScheduleData *SD)> Action) {
1089 if (ScheduleData *SD = getScheduleData(V))
1090 Action(SD);
1091 auto I = ExtraScheduleDataMap.find(V);
1092 if (I != ExtraScheduleDataMap.end())
1093 for (auto &P : I->second)
1094 if (P.second->SchedulingRegionID == SchedulingRegionID)
1095 Action(P.second);
1096 }
1097
1098 /// Put all instructions into the ReadyList which are ready for scheduling.
1099 template <typename ReadyListType>
1100 void initialFillReadyList(ReadyListType &ReadyList) {
1101 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
1102 doForAllOpcodes(I, [&](ScheduleData *SD) {
1103 if (SD->isSchedulingEntity() && SD->isReady()) {
1104 ReadyList.insert(SD);
1105 DEBUG(dbgs() << "SLP: initially in ready list: " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: initially in ready list: "
<< *I << "\n"; } } while (false)
;
1106 }
1107 });
1108 }
1109 }
1110
1111 /// Checks if a bundle of instructions can be scheduled, i.e. has no
1112 /// cyclic dependencies. This is only a dry-run, no instructions are
1113 /// actually moved at this stage.
1114 bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, Value *OpValue);
1115
1116 /// Un-bundles a group of instructions.
1117 void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
1118
1119 /// Allocates schedule data chunk.
1120 ScheduleData *allocateScheduleDataChunks();
1121
1122 /// Extends the scheduling region so that V is inside the region.
1123 /// \returns true if the region size is within the limit.
1124 bool extendSchedulingRegion(Value *V, Value *OpValue);
1125
1126 /// Initialize the ScheduleData structures for new instructions in the
1127 /// scheduling region.
1128 void initScheduleData(Instruction *FromI, Instruction *ToI,
1129 ScheduleData *PrevLoadStore,
1130 ScheduleData *NextLoadStore);
1131
1132 /// Updates the dependency information of a bundle and of all instructions/
1133 /// bundles which depend on the original bundle.
1134 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
1135 BoUpSLP *SLP);
1136
1137 /// Sets all instruction in the scheduling region to un-scheduled.
1138 void resetSchedule();
1139
1140 BasicBlock *BB;
1141
1142 /// Simple memory allocation for ScheduleData.
1143 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
1144
1145 /// The size of a ScheduleData array in ScheduleDataChunks.
1146 int ChunkSize;
1147
1148 /// The allocator position in the current chunk, which is the last entry
1149 /// of ScheduleDataChunks.
1150 int ChunkPos;
1151
1152 /// Attaches ScheduleData to Instruction.
1153 /// Note that the mapping survives during all vectorization iterations, i.e.
1154 /// ScheduleData structures are recycled.
1155 DenseMap<Value *, ScheduleData *> ScheduleDataMap;
1156
1157 /// Attaches ScheduleData to Instruction with the leading key.
1158 DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
1159 ExtraScheduleDataMap;
1160
1161 struct ReadyList : SmallVector<ScheduleData *, 8> {
1162 void insert(ScheduleData *SD) { push_back(SD); }
1163 };
1164
1165 /// The ready-list for scheduling (only used for the dry-run).
1166 ReadyList ReadyInsts;
1167
1168 /// The first instruction of the scheduling region.
1169 Instruction *ScheduleStart = nullptr;
1170
1171 /// The first instruction _after_ the scheduling region.
1172 Instruction *ScheduleEnd = nullptr;
1173
1174 /// The first memory accessing instruction in the scheduling region
1175 /// (can be null).
1176 ScheduleData *FirstLoadStoreInRegion = nullptr;
1177
1178 /// The last memory accessing instruction in the scheduling region
1179 /// (can be null).
1180 ScheduleData *LastLoadStoreInRegion = nullptr;
1181
1182 /// The current size of the scheduling region.
1183 int ScheduleRegionSize = 0;
1184
1185 /// The maximum size allowed for the scheduling region.
1186 int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
1187
1188 /// The ID of the scheduling region. For a new vectorization iteration this
1189 /// is incremented which "removes" all ScheduleData from the region.
1190 // Make sure that the initial SchedulingRegionID is greater than the
1191 // initial SchedulingRegionID in ScheduleData (which is 0).
1192 int SchedulingRegionID = 1;
1193 };
1194
1195 /// Attaches the BlockScheduling structures to basic blocks.
1196 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
1197
1198 /// Performs the "real" scheduling. Done before vectorization is actually
1199 /// performed in a basic block.
1200 void scheduleBlock(BlockScheduling *BS);
1201
1202 /// List of users to ignore during scheduling and that don't need extracting.
1203 ArrayRef<Value *> UserIgnoreList;
1204
1205 /// Number of operation bundles that contain consecutive operations - number
1206 /// of operation bundles that contain consecutive operations in reversed
1207 /// order.
1208 DenseMap<unsigned, int> NumOpsWantToKeepOrder;
1209
1210 // Analysis and block reference.
1211 Function *F;
1212 ScalarEvolution *SE;
1213 TargetTransformInfo *TTI;
1214 TargetLibraryInfo *TLI;
1215 AliasAnalysis *AA;
1216 LoopInfo *LI;
1217 DominatorTree *DT;
1218 AssumptionCache *AC;
1219 DemandedBits *DB;
1220 const DataLayout *DL;
1221 OptimizationRemarkEmitter *ORE;
1222
1223 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
1224 unsigned MinVecRegSize; // Set by cl::opt (default: 128).
1225
1226 /// Instruction builder to construct the vectorized tree.
1227 IRBuilder<> Builder;
1228
1229 /// A map of scalar integer values to the smallest bit width with which they
1230 /// can legally be represented. The values map to (width, signed) pairs,
1231 /// where "width" indicates the minimum bit width and "signed" is True if the
1232 /// value must be signed-extended, rather than zero-extended, back to its
1233 /// original width.
1234 MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
1235};
1236
1237} // end namespace slpvectorizer
1238
1239template <> struct GraphTraits<BoUpSLP *> {
1240 using TreeEntry = BoUpSLP::TreeEntry;
1241
1242 /// NodeRef has to be a pointer per the GraphWriter.
1243 using NodeRef = TreeEntry *;
1244
1245 /// \brief Add the VectorizableTree to the index iterator to be able to return
1246 /// TreeEntry pointers.
1247 struct ChildIteratorType
1248 : public iterator_adaptor_base<ChildIteratorType,
1249 SmallVector<int, 1>::iterator> {
1250 std::vector<TreeEntry> &VectorizableTree;
1251
1252 ChildIteratorType(SmallVector<int, 1>::iterator W,
1253 std::vector<TreeEntry> &VT)
1254 : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
1255
1256 NodeRef operator*() { return &VectorizableTree[*I]; }
1257 };
1258
1259 static NodeRef getEntryNode(BoUpSLP &R) { return &R.VectorizableTree[0]; }
1260
1261 static ChildIteratorType child_begin(NodeRef N) {
1262 return {N->UserTreeIndices.begin(), N->Container};
1263 }
1264
1265 static ChildIteratorType child_end(NodeRef N) {
1266 return {N->UserTreeIndices.end(), N->Container};
1267 }
1268
1269 /// For the node iterator we just need to turn the TreeEntry iterator into a
1270 /// TreeEntry* iterator so that it dereferences to NodeRef.
1271 using nodes_iterator = pointer_iterator<std::vector<TreeEntry>::iterator>;
1272
1273 static nodes_iterator nodes_begin(BoUpSLP *R) {
1274 return nodes_iterator(R->VectorizableTree.begin());
1275 }
1276
1277 static nodes_iterator nodes_end(BoUpSLP *R) {
1278 return nodes_iterator(R->VectorizableTree.end());
1279 }
1280
1281 static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
1282};
1283
1284template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
1285 using TreeEntry = BoUpSLP::TreeEntry;
1286
1287 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
1288
1289 std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
1290 std::string Str;
1291 raw_string_ostream OS(Str);
1292 if (isSplat(Entry->Scalars)) {
1293 OS << "<splat> " << *Entry->Scalars[0];
1294 return Str;
1295 }
1296 for (auto V : Entry->Scalars) {
1297 OS << *V;
1298 if (std::any_of(
1299 R->ExternalUses.begin(), R->ExternalUses.end(),
1300 [&](const BoUpSLP::ExternalUser &EU) { return EU.Scalar == V; }))
1301 OS << " <extract>";
1302 OS << "\n";
1303 }
1304 return Str;
1305 }
1306
1307 static std::string getNodeAttributes(const TreeEntry *Entry,
1308 const BoUpSLP *) {
1309 if (Entry->NeedToGather)
1310 return "color=red";
1311 return "";
1312 }
1313};
1314
1315} // end namespace llvm
1316
1317void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
1318 ArrayRef<Value *> UserIgnoreLst) {
1319 ExtraValueToDebugLocsMap ExternallyUsedValues;
1320 buildTree(Roots, ExternallyUsedValues, UserIgnoreLst);
1321}
1322
1323void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
1324 ExtraValueToDebugLocsMap &ExternallyUsedValues,
1325 ArrayRef<Value *> UserIgnoreLst) {
1326 deleteTree();
1327 UserIgnoreList = UserIgnoreLst;
1328 if (!allSameType(Roots))
1329 return;
1330 buildTree_rec(Roots, 0, -1);
1331
1332 // Collect the values that we need to extract from the tree.
1333 for (TreeEntry &EIdx : VectorizableTree) {
1334 TreeEntry *Entry = &EIdx;
1335
1336 // No need to handle users of gathered values.
1337 if (Entry->NeedToGather)
1338 continue;
1339
1340 // For each lane:
1341 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1342 Value *Scalar = Entry->Scalars[Lane];
1343 int FoundLane = Lane;
1344 if (!Entry->ReuseShuffleIndices.empty()) {
1345 FoundLane =
1346 std::distance(Entry->ReuseShuffleIndices.begin(),
1347 llvm::find(Entry->ReuseShuffleIndices, FoundLane));
1348 }
1349
1350 // Check if the scalar is externally used as an extra arg.
1351 auto ExtI = ExternallyUsedValues.find(Scalar);
1352 if (ExtI != ExternallyUsedValues.end()) {
1353 DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane " <<do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Need to extract: Extra arg from lane "
<< Lane << " from " << *Scalar << ".\n"
; } } while (false)
1354 Lane << " from " << *Scalar << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Need to extract: Extra arg from lane "
<< Lane << " from " << *Scalar << ".\n"
; } } while (false)
;
1355 ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
1356 }
1357 for (User *U : Scalar->users()) {
1358 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Checking user:" << *U <<
".\n"; } } while (false)
;
1359
1360 Instruction *UserInst = dyn_cast<Instruction>(U);
1361 if (!UserInst)
1362 continue;
1363
1364 // Skip in-tree scalars that become vectors
1365 if (TreeEntry *UseEntry = getTreeEntry(U)) {
1366 Value *UseScalar = UseEntry->Scalars[0];
1367 // Some in-tree scalars will remain as scalar in vectorized
1368 // instructions. If that is the case, the one in Lane 0 will
1369 // be used.
1370 if (UseScalar != U ||
1371 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
1372 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *Udo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: \tInternal user will be removed:"
<< *U << ".\n"; } } while (false)
1373 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: \tInternal user will be removed:"
<< *U << ".\n"; } } while (false)
;
1374 assert(!UseEntry->NeedToGather && "Bad state")(static_cast <bool> (!UseEntry->NeedToGather &&
"Bad state") ? void (0) : __assert_fail ("!UseEntry->NeedToGather && \"Bad state\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 1374, __extension__ __PRETTY_FUNCTION__))
;
1375 continue;
1376 }
1377 }
1378
1379 // Ignore users in the user ignore list.
1380 if (is_contained(UserIgnoreList, UserInst))
1381 continue;
1382
1383 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Need to extract:" << *
U << " from lane " << Lane << " from " <<
*Scalar << ".\n"; } } while (false)
1384 Lane << " from " << *Scalar << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Need to extract:" << *
U << " from lane " << Lane << " from " <<
*Scalar << ".\n"; } } while (false)
;
1385 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
1386 }
1387 }
1388 }
1389}
1390
1391void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
1392 int UserTreeIdx) {
1393 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!")(static_cast <bool> ((allConstant(VL) || allSameType(VL
)) && "Invalid types!") ? void (0) : __assert_fail ("(allConstant(VL) || allSameType(VL)) && \"Invalid types!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 1393, __extension__ __PRETTY_FUNCTION__))
;
1394
1395 InstructionsState S = getSameOpcode(VL);
1396 if (Depth == RecursionMaxDepth) {
1397 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering due to max recursion depth.\n"
; } } while (false)
;
1398 newTreeEntry(VL, false, UserTreeIdx);
1399 return;
1400 }
1401
1402 // Don't handle vectors.
1403 if (S.OpValue->getType()->isVectorTy()) {
1404 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering due to vector type.\n"
; } } while (false)
;
1405 newTreeEntry(VL, false, UserTreeIdx);
1406 return;
1407 }
1408
1409 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
1410 if (SI->getValueOperand()->getType()->isVectorTy()) {
1411 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering due to store vector type.\n"
; } } while (false)
;
1412 newTreeEntry(VL, false, UserTreeIdx);
1413 return;
1414 }
1415
1416 // If all of the operands are identical or constant we have a simple solution.
1417 if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.Opcode) {
1418 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering due to C,S,B,O. \n"
; } } while (false)
;
1419 newTreeEntry(VL, false, UserTreeIdx);
1420 return;
1421 }
1422
1423 // We now know that this is a vector of instructions of the same type from
1424 // the same block.
1425
1426 // Don't vectorize ephemeral values.
1427 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1428 if (EphValues.count(VL[i])) {
1429 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: The instruction (" << *
VL[i] << ") is ephemeral.\n"; } } while (false)
1430 ") is ephemeral.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: The instruction (" << *
VL[i] << ") is ephemeral.\n"; } } while (false)
;
1431 newTreeEntry(VL, false, UserTreeIdx);
1432 return;
1433 }
1434 }
1435
1436 // Check if this is a duplicate of another entry.
1437 if (TreeEntry *E = getTreeEntry(S.OpValue)) {
1438 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: \tChecking bundle: " <<
*S.OpValue << ".\n"; } } while (false)
;
1439 if (!E->isSame(VL)) {
1440 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering due to partial overlap.\n"
; } } while (false)
;
1441 newTreeEntry(VL, false, UserTreeIdx);
1442 return;
1443 }
1444 // Record the reuse of the tree node. FIXME, currently this is only used to
1445 // properly draw the graph rather than for the actual vectorization.
1446 E->UserTreeIndices.push_back(UserTreeIdx);
1447 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Perfect diamond merge at " <<
*S.OpValue << ".\n"; } } while (false)
;
1448 return;
1449 }
1450
1451 // Check that none of the instructions in the bundle are already in the tree.
1452 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1453 auto *I = dyn_cast<Instruction>(VL[i]);
1454 if (!I)
1455 continue;
1456 if (getTreeEntry(I)) {
1457 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: The instruction (" << *
VL[i] << ") is already in tree.\n"; } } while (false)
1458 ") is already in tree.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: The instruction (" << *
VL[i] << ") is already in tree.\n"; } } while (false)
;
1459 newTreeEntry(VL, false, UserTreeIdx);
1460 return;
1461 }
1462 }
1463
1464 // If any of the scalars is marked as a value that needs to stay scalar, then
1465 // we need to gather the scalars.
1466 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1467 if (MustGather.count(VL[i])) {
1468 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering due to gathered scalar.\n"
; } } while (false)
;
1469 newTreeEntry(VL, false, UserTreeIdx);
1470 return;
1471 }
1472 }
1473
1474 // Check that all of the users of the scalars that we want to vectorize are
1475 // schedulable.
1476 auto *VL0 = cast<Instruction>(S.OpValue);
1477 BasicBlock *BB = VL0->getParent();
1478
1479 if (!DT->isReachableFromEntry(BB)) {
1480 // Don't go into unreachable blocks. They may contain instructions with
1481 // dependency cycles which confuse the final scheduling.
1482 DEBUG(dbgs() << "SLP: bundle in unreachable block.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: bundle in unreachable block.\n"
; } } while (false)
;
1483 newTreeEntry(VL, false, UserTreeIdx);
1484 return;
1485 }
1486
1487 // Check that every instruction appears once in this bundle.
1488 SmallVector<unsigned, 4> ReuseShuffleIndicies;
1489 SmallVector<Value *, 4> UniqueValues;
1490 DenseMap<Value *, unsigned> UniquePositions;
1491 for (Value *V : VL) {
1492 auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
1493 ReuseShuffleIndicies.emplace_back(Res.first->second);
1494 if (Res.second)
1495 UniqueValues.emplace_back(V);
1496 }
1497 if (UniqueValues.size() == VL.size()) {
1498 ReuseShuffleIndicies.clear();
1499 } else {
1500 DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Shuffle for reused scalars.\n"
; } } while (false)
;
1501 if (UniqueValues.size() <= 1 || !llvm::isPowerOf2_32(UniqueValues.size())) {
1502 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Scalar used twice in bundle.\n"
; } } while (false)
;
1503 newTreeEntry(VL, false, UserTreeIdx);
1504 return;
1505 }
1506 VL = UniqueValues;
1507 }
1508
1509 auto &BSRef = BlocksSchedules[BB];
1510 if (!BSRef)
1511 BSRef = llvm::make_unique<BlockScheduling>(BB);
1512
1513 BlockScheduling &BS = *BSRef.get();
1514
1515 if (!BS.tryScheduleBundle(VL, this, VL0)) {
1516 DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: We are not able to schedule this bundle!\n"
; } } while (false)
;
1517 assert((!BS.getScheduleData(VL0) ||(static_cast <bool> ((!BS.getScheduleData(VL0) || !BS.getScheduleData
(VL0)->isPartOfBundle()) && "tryScheduleBundle should cancelScheduling on failure"
) ? void (0) : __assert_fail ("(!BS.getScheduleData(VL0) || !BS.getScheduleData(VL0)->isPartOfBundle()) && \"tryScheduleBundle should cancelScheduling on failure\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 1519, __extension__ __PRETTY_FUNCTION__))
1518 !BS.getScheduleData(VL0)->isPartOfBundle()) &&(static_cast <bool> ((!BS.getScheduleData(VL0) || !BS.getScheduleData
(VL0)->isPartOfBundle()) && "tryScheduleBundle should cancelScheduling on failure"
) ? void (0) : __assert_fail ("(!BS.getScheduleData(VL0) || !BS.getScheduleData(VL0)->isPartOfBundle()) && \"tryScheduleBundle should cancelScheduling on failure\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 1519, __extension__ __PRETTY_FUNCTION__))
1519 "tryScheduleBundle should cancelScheduling on failure")(static_cast <bool> ((!BS.getScheduleData(VL0) || !BS.getScheduleData
(VL0)->isPartOfBundle()) && "tryScheduleBundle should cancelScheduling on failure"
) ? void (0) : __assert_fail ("(!BS.getScheduleData(VL0) || !BS.getScheduleData(VL0)->isPartOfBundle()) && \"tryScheduleBundle should cancelScheduling on failure\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 1519, __extension__ __PRETTY_FUNCTION__))
;
1520 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1521 return;
1522 }
1523 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: We are able to schedule this bundle.\n"
; } } while (false)
;
1524
1525 unsigned ShuffleOrOp = S.IsAltShuffle ?
1526 (unsigned) Instruction::ShuffleVector : S.Opcode;
1527 switch (ShuffleOrOp) {
1528 case Instruction::PHI: {
1529 PHINode *PH = dyn_cast<PHINode>(VL0);
1530
1531 // Check for terminator values (e.g. invoke).
1532 for (unsigned j = 0; j < VL.size(); ++j)
1533 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1534 TerminatorInst *Term = dyn_cast<TerminatorInst>(
1535 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1536 if (Term) {
1537 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n"
; } } while (false)
;
1538 BS.cancelScheduling(VL, VL0);
1539 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1540 return;
1541 }
1542 }
1543
1544 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1545 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of PHINodes.\n"
; } } while (false)
;
1546
1547 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1548 ValueList Operands;
1549 // Prepare the operand vector.
1550 for (Value *j : VL)
1551 Operands.push_back(cast<PHINode>(j)->getIncomingValueForBlock(
1552 PH->getIncomingBlock(i)));
1553
1554 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1555 }
1556 return;
1557 }
1558 case Instruction::ExtractValue:
1559 case Instruction::ExtractElement: {
1560 bool Reuse = canReuseExtract(VL, VL0);
1561 if (Reuse) {
1562 DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Reusing or shuffling extract sequence.\n"
; } } while (false)
;
1563 ++NumOpsWantToKeepOrder[S.Opcode];
1564 } else {
1565 SmallVector<Value *, 4> ReverseVL(VL.rbegin(), VL.rend());
1566 if (canReuseExtract(ReverseVL, VL0))
1567 --NumOpsWantToKeepOrder[S.Opcode];
1568 BS.cancelScheduling(VL, VL0);
1569 }
1570 newTreeEntry(VL, Reuse, UserTreeIdx, ReuseShuffleIndicies);
1571 return;
1572 }
1573 case Instruction::Load: {
1574 // Check that a vectorized load would load the same memory as a scalar
1575 // load. For example, we don't want to vectorize loads that are smaller
1576 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
1577 // treats loading/storing it as an i8 struct. If we vectorize loads/stores
1578 // from such a struct, we read/write packed bits disagreeing with the
1579 // unvectorized version.
1580 Type *ScalarTy = VL0->getType();
1581
1582 if (DL->getTypeSizeInBits(ScalarTy) !=
1583 DL->getTypeAllocSizeInBits(ScalarTy)) {
1584 BS.cancelScheduling(VL, VL0);
1585 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1586 DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering loads of non-packed type.\n"
; } } while (false)
;
1587 return;
1588 }
1589
1590 // Make sure all loads in the bundle are simple - we can't vectorize
1591 // atomic or volatile loads.
1592 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1593 LoadInst *L = cast<LoadInst>(VL[i]);
1594 if (!L->isSimple()) {
1595 BS.cancelScheduling(VL, VL0);
1596 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1597 DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering non-simple loads.\n"
; } } while (false)
;
1598 return;
1599 }
1600 }
1601
1602 // Check if the loads are consecutive, reversed, or neither.
1603 // TODO: What we really want is to sort the loads, but for now, check
1604 // the two likely directions.
1605 bool Consecutive = true;
1606 bool ReverseConsecutive = true;
1607 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1608 if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
1609 Consecutive = false;
1610 break;
1611 } else {
1612 ReverseConsecutive = false;
1613 }
1614 }
1615
1616 if (Consecutive) {
1617 ++NumOpsWantToKeepOrder[S.Opcode];
1618 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1619 DEBUG(dbgs() << "SLP: added a vector of loads.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of loads.\n";
} } while (false)
;
1620 return;
1621 }
1622
1623 // If none of the load pairs were consecutive when checked in order,
1624 // check the reverse order.
1625 if (ReverseConsecutive)
1626 for (unsigned i = VL.size() - 1; i > 0; --i)
1627 if (!isConsecutiveAccess(VL[i], VL[i - 1], *DL, *SE)) {
1628 ReverseConsecutive = false;
1629 break;
1630 }
1631
1632 BS.cancelScheduling(VL, VL0);
1633 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1634
1635 if (ReverseConsecutive) {
1636 --NumOpsWantToKeepOrder[S.Opcode];
1637 DEBUG(dbgs() << "SLP: Gathering reversed loads.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering reversed loads.\n"
; } } while (false)
;
1638 } else {
1639 DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering non-consecutive loads.\n"
; } } while (false)
;
1640 }
1641 return;
1642 }
1643 case Instruction::ZExt:
1644 case Instruction::SExt:
1645 case Instruction::FPToUI:
1646 case Instruction::FPToSI:
1647 case Instruction::FPExt:
1648 case Instruction::PtrToInt:
1649 case Instruction::IntToPtr:
1650 case Instruction::SIToFP:
1651 case Instruction::UIToFP:
1652 case Instruction::Trunc:
1653 case Instruction::FPTrunc:
1654 case Instruction::BitCast: {
1655 Type *SrcTy = VL0->getOperand(0)->getType();
1656 for (unsigned i = 0; i < VL.size(); ++i) {
1657 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1658 if (Ty != SrcTy || !isValidElementType(Ty)) {
1659 BS.cancelScheduling(VL, VL0);
1660 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1661 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering casts with different src types.\n"
; } } while (false)
;
1662 return;
1663 }
1664 }
1665 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1666 DEBUG(dbgs() << "SLP: added a vector of casts.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of casts.\n";
} } while (false)
;
1667
1668 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1669 ValueList Operands;
1670 // Prepare the operand vector.
1671 for (Value *j : VL)
1672 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1673
1674 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1675 }
1676 return;
1677 }
1678 case Instruction::ICmp:
1679 case Instruction::FCmp: {
1680 // Check that all of the compares have the same predicate.
1681 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
1682 Type *ComparedTy = VL0->getOperand(0)->getType();
1683 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1684 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1685 if (Cmp->getPredicate() != P0 ||
1686 Cmp->getOperand(0)->getType() != ComparedTy) {
1687 BS.cancelScheduling(VL, VL0);
1688 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1689 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering cmp with different predicate.\n"
; } } while (false)
;
1690 return;
1691 }
1692 }
1693
1694 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1695 DEBUG(dbgs() << "SLP: added a vector of compares.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of compares.\n"
; } } while (false)
;
1696
1697 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1698 ValueList Operands;
1699 // Prepare the operand vector.
1700 for (Value *j : VL)
1701 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1702
1703 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1704 }
1705 return;
1706 }
1707 case Instruction::Select:
1708 case Instruction::Add:
1709 case Instruction::FAdd:
1710 case Instruction::Sub:
1711 case Instruction::FSub:
1712 case Instruction::Mul:
1713 case Instruction::FMul:
1714 case Instruction::UDiv:
1715 case Instruction::SDiv:
1716 case Instruction::FDiv:
1717 case Instruction::URem:
1718 case Instruction::SRem:
1719 case Instruction::FRem:
1720 case Instruction::Shl:
1721 case Instruction::LShr:
1722 case Instruction::AShr:
1723 case Instruction::And:
1724 case Instruction::Or:
1725 case Instruction::Xor:
1726 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1727 DEBUG(dbgs() << "SLP: added a vector of bin op.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of bin op.\n"
; } } while (false)
;
1728
1729 // Sort operands of the instructions so that each side is more likely to
1730 // have the same opcode.
1731 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1732 ValueList Left, Right;
1733 reorderInputsAccordingToOpcode(S.Opcode, VL, Left, Right);
1734 buildTree_rec(Left, Depth + 1, UserTreeIdx);
1735 buildTree_rec(Right, Depth + 1, UserTreeIdx);
1736 return;
1737 }
1738
1739 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1740 ValueList Operands;
1741 // Prepare the operand vector.
1742 for (Value *j : VL)
1743 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1744
1745 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1746 }
1747 return;
1748
1749 case Instruction::GetElementPtr: {
1750 // We don't combine GEPs with complicated (nested) indexing.
1751 for (unsigned j = 0; j < VL.size(); ++j) {
1752 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1753 DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n"
; } } while (false)
;
1754 BS.cancelScheduling(VL, VL0);
1755 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1756 return;
1757 }
1758 }
1759
1760 // We can't combine several GEPs into one vector if they operate on
1761 // different types.
1762 Type *Ty0 = VL0->getOperand(0)->getType();
1763 for (unsigned j = 0; j < VL.size(); ++j) {
1764 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1765 if (Ty0 != CurTy) {
1766 DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: not-vectorizable GEP (different types).\n"
; } } while (false)
;
1767 BS.cancelScheduling(VL, VL0);
1768 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1769 return;
1770 }
1771 }
1772
1773 // We don't combine GEPs with non-constant indexes.
1774 for (unsigned j = 0; j < VL.size(); ++j) {
1775 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1776 if (!isa<ConstantInt>(Op)) {
1777 DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n"
; } } while (false)
1778 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n"
; } } while (false)
;
1779 BS.cancelScheduling(VL, VL0);
1780 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1781 return;
1782 }
1783 }
1784
1785 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1786 DEBUG(dbgs() << "SLP: added a vector of GEPs.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of GEPs.\n"; }
} while (false)
;
1787 for (unsigned i = 0, e = 2; i < e; ++i) {
1788 ValueList Operands;
1789 // Prepare the operand vector.
1790 for (Value *j : VL)
1791 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1792
1793 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1794 }
1795 return;
1796 }
1797 case Instruction::Store: {
1798 // Check if the stores are consecutive or of we need to swizzle them.
1799 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1800 if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
1801 BS.cancelScheduling(VL, VL0);
1802 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1803 DEBUG(dbgs() << "SLP: Non-consecutive store.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Non-consecutive store.\n"; }
} while (false)
;
1804 return;
1805 }
1806
1807 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1808 DEBUG(dbgs() << "SLP: added a vector of stores.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of stores.\n"
; } } while (false)
;
1809
1810 ValueList Operands;
1811 for (Value *j : VL)
1812 Operands.push_back(cast<Instruction>(j)->getOperand(0));
1813
1814 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1815 return;
1816 }
1817 case Instruction::Call: {
1818 // Check if the calls are all to the same vectorizable intrinsic.
1819 CallInst *CI = cast<CallInst>(VL0);
1820 // Check if this is an Intrinsic call or something that can be
1821 // represented by an intrinsic call
1822 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
1823 if (!isTriviallyVectorizable(ID)) {
1824 BS.cancelScheduling(VL, VL0);
1825 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1826 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Non-vectorizable call.\n"; }
} while (false)
;
1827 return;
1828 }
1829 Function *Int = CI->getCalledFunction();
1830 Value *A1I = nullptr;
1831 if (hasVectorInstrinsicScalarOpd(ID, 1))
1832 A1I = CI->getArgOperand(1);
1833 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1834 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1835 if (!CI2 || CI2->getCalledFunction() != Int ||
1836 getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
1837 !CI->hasIdenticalOperandBundleSchema(*CI2)) {
1838 BS.cancelScheduling(VL, VL0);
1839 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1840 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: mismatched calls:" << *
CI << "!=" << *VL[i] << "\n"; } } while (false
)
1841 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: mismatched calls:" << *
CI << "!=" << *VL[i] << "\n"; } } while (false
)
;
1842 return;
1843 }
1844 // ctlz,cttz and powi are special intrinsics whose second argument
1845 // should be same in order for them to be vectorized.
1846 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1847 Value *A1J = CI2->getArgOperand(1);
1848 if (A1I != A1J) {
1849 BS.cancelScheduling(VL, VL0);
1850 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1851 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CIdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: mismatched arguments in call:"
<< *CI << " argument "<< A1I<<"!=" <<
A1J << "\n"; } } while (false)
1852 << " argument "<< A1I<<"!=" << A1Jdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: mismatched arguments in call:"
<< *CI << " argument "<< A1I<<"!=" <<
A1J << "\n"; } } while (false)
1853 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: mismatched arguments in call:"
<< *CI << " argument "<< A1I<<"!=" <<
A1J << "\n"; } } while (false)
;
1854 return;
1855 }
1856 }
1857 // Verify that the bundle operands are identical between the two calls.
1858 if (CI->hasOperandBundles() &&
1859 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
1860 CI->op_begin() + CI->getBundleOperandsEndIndex(),
1861 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
1862 BS.cancelScheduling(VL, VL0);
1863 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1864 DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" << *CI << "!="do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: mismatched bundle operands in calls:"
<< *CI << "!=" << *VL[i] << '\n'; } }
while (false)
1865 << *VL[i] << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: mismatched bundle operands in calls:"
<< *CI << "!=" << *VL[i] << '\n'; } }
while (false)
;
1866 return;
1867 }
1868 }
1869
1870 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1871 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1872 ValueList Operands;
1873 // Prepare the operand vector.
1874 for (Value *j : VL) {
1875 CallInst *CI2 = dyn_cast<CallInst>(j);
1876 Operands.push_back(CI2->getArgOperand(i));
1877 }
1878 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1879 }
1880 return;
1881 }
1882 case Instruction::ShuffleVector:
1883 // If this is not an alternate sequence of opcode like add-sub
1884 // then do not vectorize this instruction.
1885 if (!S.IsAltShuffle) {
1886 BS.cancelScheduling(VL, VL0);
1887 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1888 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: ShuffleVector are not vectorized.\n"
; } } while (false)
;
1889 return;
1890 }
1891 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1892 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a ShuffleVector op.\n"
; } } while (false)
;
1893
1894 // Reorder operands if reordering would enable vectorization.
1895 if (isa<BinaryOperator>(VL0)) {
1896 ValueList Left, Right;
1897 reorderAltShuffleOperands(S.Opcode, VL, Left, Right);
1898 buildTree_rec(Left, Depth + 1, UserTreeIdx);
1899 buildTree_rec(Right, Depth + 1, UserTreeIdx);
1900 return;
1901 }
1902
1903 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1904 ValueList Operands;
1905 // Prepare the operand vector.
1906 for (Value *j : VL)
1907 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1908
1909 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1910 }
1911 return;
1912
1913 default:
1914 BS.cancelScheduling(VL, VL0);
1915 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1916 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering unknown instruction.\n"
; } } while (false)
;
1917 return;
1918 }
1919}
1920
1921unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
1922 unsigned N;
1923 Type *EltTy;
1924 auto *ST = dyn_cast<StructType>(T);
1925 if (ST) {
1926 N = ST->getNumElements();
1927 EltTy = *ST->element_begin();
1928 } else {
1929 N = cast<ArrayType>(T)->getNumElements();
1930 EltTy = cast<ArrayType>(T)->getElementType();
1931 }
1932 if (!isValidElementType(EltTy))
1933 return 0;
1934 uint64_t VTSize = DL.getTypeStoreSizeInBits(VectorType::get(EltTy, N));
1935 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
1936 return 0;
1937 if (ST) {
1938 // Check that struct is homogeneous.
1939 for (const auto *Ty : ST->elements())
1940 if (Ty != EltTy)
1941 return 0;
1942 }
1943 return N;
1944}
1945
1946bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue) const {
1947 Instruction *E0 = cast<Instruction>(OpValue);
1948 assert(E0->getOpcode() == Instruction::ExtractElement ||(static_cast <bool> (E0->getOpcode() == Instruction::
ExtractElement || E0->getOpcode() == Instruction::ExtractValue
) ? void (0) : __assert_fail ("E0->getOpcode() == Instruction::ExtractElement || E0->getOpcode() == Instruction::ExtractValue"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 1949, __extension__ __PRETTY_FUNCTION__))
1949 E0->getOpcode() == Instruction::ExtractValue)(static_cast <bool> (E0->getOpcode() == Instruction::
ExtractElement || E0->getOpcode() == Instruction::ExtractValue
) ? void (0) : __assert_fail ("E0->getOpcode() == Instruction::ExtractElement || E0->getOpcode() == Instruction::ExtractValue"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 1949, __extension__ __PRETTY_FUNCTION__))
;
1950 assert(E0->getOpcode() == getSameOpcode(VL).Opcode && "Invalid opcode")(static_cast <bool> (E0->getOpcode() == getSameOpcode
(VL).Opcode && "Invalid opcode") ? void (0) : __assert_fail
("E0->getOpcode() == getSameOpcode(VL).Opcode && \"Invalid opcode\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 1950, __extension__ __PRETTY_FUNCTION__))
;
1951 // Check if all of the extracts come from the same vector and from the
1952 // correct offset.
1953 Value *Vec = E0->getOperand(0);
1954
1955 // We have to extract from a vector/aggregate with the same number of elements.
1956 unsigned NElts;
1957 if (E0->getOpcode() == Instruction::ExtractValue) {
1958 const DataLayout &DL = E0->getModule()->getDataLayout();
1959 NElts = canMapToVector(Vec->getType(), DL);
1960 if (!NElts)
1961 return false;
1962 // Check if load can be rewritten as load of vector.
1963 LoadInst *LI = dyn_cast<LoadInst>(Vec);
1964 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
1965 return false;
1966 } else {
1967 NElts = Vec->getType()->getVectorNumElements();
1968 }
1969
1970 if (NElts != VL.size())
1971 return false;
1972
1973 // Check that all of the indices extract from the correct offset.
1974 for (unsigned I = 0, E = VL.size(); I < E; ++I) {
1975 Instruction *Inst = cast<Instruction>(VL[I]);
1976 if (!matchExtractIndex(Inst, I, Inst->getOpcode()))
1977 return false;
1978 if (Inst->getOperand(0) != Vec)
1979 return false;
1980 }
1981
1982 return true;
1983}
1984
1985bool BoUpSLP::areAllUsersVectorized(Instruction *I) const {
1986 return I->hasOneUse() ||
1987 std::all_of(I->user_begin(), I->user_end(), [this](User *U) {
1988 return ScalarToTreeEntry.count(U) > 0;
1989 });
1990}
1991
1992int BoUpSLP::getEntryCost(TreeEntry *E) {
1993 ArrayRef<Value*> VL = E->Scalars;
1994
1995 Type *ScalarTy = VL[0]->getType();
1996 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1997 ScalarTy = SI->getValueOperand()->getType();
1998 else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
1999 ScalarTy = CI->getOperand(0)->getType();
2000 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2001
2002 // If we have computed a smaller type for the expression, update VecTy so
2003 // that the costs will be accurate.
2004 if (MinBWs.count(VL[0]))
2005 VecTy = VectorType::get(
2006 IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
2007
2008 unsigned ReuseShuffleNumbers = E->ReuseShuffleIndices.size();
2009 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
2010 int ReuseShuffleCost = 0;
2011 if (NeedToShuffleReuses) {
2012 ReuseShuffleCost =
2013 TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
2014 }
2015 if (E->NeedToGather) {
2016 if (allConstant(VL))
2017 return 0;
2018 if (isSplat(VL)) {
2019 return ReuseShuffleCost +
2020 TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
2021 }
2022 if (getSameOpcode(VL).Opcode == Instruction::ExtractElement &&
2023 allSameType(VL) && allSameBlock(VL)) {
2024 Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = isShuffle(VL);
2025 if (ShuffleKind.hasValue()) {
2026 int Cost = TTI->getShuffleCost(ShuffleKind.getValue(), VecTy);
2027 for (auto *V : VL) {
2028 // If all users of instruction are going to be vectorized and this
2029 // instruction itself is not going to be vectorized, consider this
2030 // instruction as dead and remove its cost from the final cost of the
2031 // vectorized tree.
2032 if (areAllUsersVectorized(cast<Instruction>(V)) &&
2033 !ScalarToTreeEntry.count(V)) {
2034 auto *IO = cast<ConstantInt>(
2035 cast<ExtractElementInst>(V)->getIndexOperand());
2036 Cost -= TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
2037 IO->getZExtValue());
2038 }
2039 }
2040 return ReuseShuffleCost + Cost;
2041 }
2042 }
2043 return ReuseShuffleCost + getGatherCost(VL);
2044 }
2045 InstructionsState S = getSameOpcode(VL);
2046 assert(S.Opcode && allSameType(VL) && allSameBlock(VL) && "Invalid VL")(static_cast <bool> (S.Opcode && allSameType(VL
) && allSameBlock(VL) && "Invalid VL") ? void
(0) : __assert_fail ("S.Opcode && allSameType(VL) && allSameBlock(VL) && \"Invalid VL\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2046, __extension__ __PRETTY_FUNCTION__))
;
2047 Instruction *VL0 = cast<Instruction>(S.OpValue);
2048 unsigned ShuffleOrOp = S.IsAltShuffle ?
2049 (unsigned) Instruction::ShuffleVector : S.Opcode;
2050 switch (ShuffleOrOp) {
2051 case Instruction::PHI:
2052 return 0;
2053
2054 case Instruction::ExtractValue:
2055 case Instruction::ExtractElement:
2056 if (NeedToShuffleReuses) {
2057 unsigned Idx = 0;
2058 for (unsigned I : E->ReuseShuffleIndices) {
2059 if (ShuffleOrOp == Instruction::ExtractElement) {
2060 auto *IO = cast<ConstantInt>(
2061 cast<ExtractElementInst>(VL[I])->getIndexOperand());
2062 Idx = IO->getZExtValue();
2063 ReuseShuffleCost -= TTI->getVectorInstrCost(
2064 Instruction::ExtractElement, VecTy, Idx);
2065 } else {
2066 ReuseShuffleCost -= TTI->getVectorInstrCost(
2067 Instruction::ExtractElement, VecTy, Idx);
2068 ++Idx;
2069 }
2070 }
2071 Idx = ReuseShuffleNumbers;
2072 for (Value *V : VL) {
2073 if (ShuffleOrOp == Instruction::ExtractElement) {
2074 auto *IO = cast<ConstantInt>(
2075 cast<ExtractElementInst>(V)->getIndexOperand());
2076 Idx = IO->getZExtValue();
2077 } else {
2078 --Idx;
2079 }
2080 ReuseShuffleCost +=
2081 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, Idx);
2082 }
2083 }
2084 if (canReuseExtract(VL, S.OpValue)) {
2085 int DeadCost = ReuseShuffleCost;
2086 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2087 Instruction *E = cast<Instruction>(VL[i]);
2088 // If all users are going to be vectorized, instruction can be
2089 // considered as dead.
2090 // The same, if have only one user, it will be vectorized for sure.
2091 if (areAllUsersVectorized(E))
2092 // Take credit for instruction that will become dead.
2093 DeadCost -=
2094 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
2095 }
2096 return DeadCost;
2097 }
2098 return ReuseShuffleCost + getGatherCost(VL);
2099
2100 case Instruction::ZExt:
2101 case Instruction::SExt:
2102 case Instruction::FPToUI:
2103 case Instruction::FPToSI:
2104 case Instruction::FPExt:
2105 case Instruction::PtrToInt:
2106 case Instruction::IntToPtr:
2107 case Instruction::SIToFP:
2108 case Instruction::UIToFP:
2109 case Instruction::Trunc:
2110 case Instruction::FPTrunc:
2111 case Instruction::BitCast: {
2112 Type *SrcTy = VL0->getOperand(0)->getType();
2113 if (NeedToShuffleReuses) {
2114 ReuseShuffleCost -=
2115 (ReuseShuffleNumbers - VL.size()) *
2116 TTI->getCastInstrCost(S.Opcode, ScalarTy, SrcTy, VL0);
2117 }
2118
2119 // Calculate the cost of this instruction.
2120 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
2121 VL0->getType(), SrcTy, VL0);
2122
2123 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
2124 int VecCost = 0;
2125 // Check if the values are candidates to demote.
2126 if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
2127 VecCost = ReuseShuffleCost +
2128 TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy, VL0);
2129 }
2130 return VecCost - ScalarCost;
2131 }
2132 case Instruction::FCmp:
2133 case Instruction::ICmp:
2134 case Instruction::Select: {
2135 // Calculate the cost of this instruction.
2136 if (NeedToShuffleReuses) {
2137 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) *
2138 TTI->getCmpSelInstrCost(S.Opcode, ScalarTy,
2139 Builder.getInt1Ty(), VL0);
2140 }
2141 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
2142 int ScalarCost = VecTy->getNumElements() *
2143 TTI->getCmpSelInstrCost(S.Opcode, ScalarTy, Builder.getInt1Ty(), VL0);
2144 int VecCost = TTI->getCmpSelInstrCost(S.Opcode, VecTy, MaskTy, VL0);
2145 return ReuseShuffleCost + VecCost - ScalarCost;
2146 }
2147 case Instruction::Add:
2148 case Instruction::FAdd:
2149 case Instruction::Sub:
2150 case Instruction::FSub:
2151 case Instruction::Mul:
2152 case Instruction::FMul:
2153 case Instruction::UDiv:
2154 case Instruction::SDiv:
2155 case Instruction::FDiv:
2156 case Instruction::URem:
2157 case Instruction::SRem:
2158 case Instruction::FRem:
2159 case Instruction::Shl:
2160 case Instruction::LShr:
2161 case Instruction::AShr:
2162 case Instruction::And:
2163 case Instruction::Or:
2164 case Instruction::Xor: {
2165 // Certain instructions can be cheaper to vectorize if they have a
2166 // constant second vector operand.
2167 TargetTransformInfo::OperandValueKind Op1VK =
2168 TargetTransformInfo::OK_AnyValue;
2169 TargetTransformInfo::OperandValueKind Op2VK =
2170 TargetTransformInfo::OK_UniformConstantValue;
2171 TargetTransformInfo::OperandValueProperties Op1VP =
2172 TargetTransformInfo::OP_None;
2173 TargetTransformInfo::OperandValueProperties Op2VP =
2174 TargetTransformInfo::OP_None;
2175
2176 // If all operands are exactly the same ConstantInt then set the
2177 // operand kind to OK_UniformConstantValue.
2178 // If instead not all operands are constants, then set the operand kind
2179 // to OK_AnyValue. If all operands are constants but not the same,
2180 // then set the operand kind to OK_NonUniformConstantValue.
2181 ConstantInt *CInt = nullptr;
2182 for (unsigned i = 0; i < VL.size(); ++i) {
2183 const Instruction *I = cast<Instruction>(VL[i]);
2184 if (!isa<ConstantInt>(I->getOperand(1))) {
2185 Op2VK = TargetTransformInfo::OK_AnyValue;
2186 break;
2187 }
2188 if (i == 0) {
2189 CInt = cast<ConstantInt>(I->getOperand(1));
2190 continue;
2191 }
2192 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
2193 CInt != cast<ConstantInt>(I->getOperand(1)))
2194 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
2195 }
2196 // FIXME: Currently cost of model modification for division by power of
2197 // 2 is handled for X86 and AArch64. Add support for other targets.
2198 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
2199 CInt->getValue().isPowerOf2())
2200 Op2VP = TargetTransformInfo::OP_PowerOf2;
2201
2202 SmallVector<const Value *, 4> Operands(VL0->operand_values());
2203 if (NeedToShuffleReuses) {
2204 ReuseShuffleCost -=
2205 (ReuseShuffleNumbers - VL.size()) *
2206 TTI->getArithmeticInstrCost(S.Opcode, ScalarTy, Op1VK, Op2VK, Op1VP,
2207 Op2VP, Operands);
2208 }
2209 int ScalarCost =
2210 VecTy->getNumElements() *
2211 TTI->getArithmeticInstrCost(S.Opcode, ScalarTy, Op1VK, Op2VK, Op1VP,
2212 Op2VP, Operands);
2213 int VecCost = TTI->getArithmeticInstrCost(S.Opcode, VecTy, Op1VK, Op2VK,
2214 Op1VP, Op2VP, Operands);
2215 return ReuseShuffleCost + VecCost - ScalarCost;
2216 }
2217 case Instruction::GetElementPtr: {
2218 TargetTransformInfo::OperandValueKind Op1VK =
2219 TargetTransformInfo::OK_AnyValue;
2220 TargetTransformInfo::OperandValueKind Op2VK =
2221 TargetTransformInfo::OK_UniformConstantValue;
2222
2223 if (NeedToShuffleReuses) {
2224 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) *
2225 TTI->getArithmeticInstrCost(Instruction::Add,
2226 ScalarTy, Op1VK, Op2VK);
2227 }
2228 int ScalarCost =
2229 VecTy->getNumElements() *
2230 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
2231 int VecCost =
2232 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
2233
2234 return ReuseShuffleCost + VecCost - ScalarCost;
2235 }
2236 case Instruction::Load: {
2237 // Cost of wide load - cost of scalar loads.
2238 unsigned alignment = dyn_cast<LoadInst>(VL0)->getAlignment();
2239 if (NeedToShuffleReuses) {
2240 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) *
2241 TTI->getMemoryOpCost(Instruction::Load, ScalarTy,
2242 alignment, 0, VL0);
2243 }
2244 int ScalarLdCost = VecTy->getNumElements() *
2245 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, alignment, 0, VL0);
2246 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load,
2247 VecTy, alignment, 0, VL0);
2248 return ReuseShuffleCost + VecLdCost - ScalarLdCost;
2249 }
2250 case Instruction::Store: {
2251 // We know that we can merge the stores. Calculate the cost.
2252 unsigned alignment = dyn_cast<StoreInst>(VL0)->getAlignment();
2253 if (NeedToShuffleReuses) {
2254 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) *
2255 TTI->getMemoryOpCost(Instruction::Store, ScalarTy,
2256 alignment, 0, VL0);
2257 }
2258 int ScalarStCost = VecTy->getNumElements() *
2259 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, alignment, 0, VL0);
2260 int VecStCost = TTI->getMemoryOpCost(Instruction::Store,
2261 VecTy, alignment, 0, VL0);
2262 return ReuseShuffleCost + VecStCost - ScalarStCost;
2263 }
2264 case Instruction::Call: {
2265 CallInst *CI = cast<CallInst>(VL0);
2266 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
2267
2268 // Calculate the cost of the scalar and vector calls.
2269 SmallVector<Type*, 4> ScalarTys;
2270 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op)
2271 ScalarTys.push_back(CI->getArgOperand(op)->getType());
2272
2273 FastMathFlags FMF;
2274 if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
2275 FMF = FPMO->getFastMathFlags();
2276
2277 if (NeedToShuffleReuses) {
2278 ReuseShuffleCost -=
2279 (ReuseShuffleNumbers - VL.size()) *
2280 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
2281 }
2282 int ScalarCallCost = VecTy->getNumElements() *
2283 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
2284
2285 SmallVector<Value *, 4> Args(CI->arg_operands());
2286 int VecCallCost = TTI->getIntrinsicInstrCost(ID, CI->getType(), Args, FMF,
2287 VecTy->getNumElements());
2288
2289 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCostdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Call cost "<< VecCallCost
- ScalarCallCost << " (" << VecCallCost <<
"-" << ScalarCallCost << ")" << " for " <<
*CI << "\n"; } } while (false)
2290 << " (" << VecCallCost << "-" << ScalarCallCost << ")"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Call cost "<< VecCallCost
- ScalarCallCost << " (" << VecCallCost <<
"-" << ScalarCallCost << ")" << " for " <<
*CI << "\n"; } } while (false)
2291 << " for " << *CI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Call cost "<< VecCallCost
- ScalarCallCost << " (" << VecCallCost <<
"-" << ScalarCallCost << ")" << " for " <<
*CI << "\n"; } } while (false)
;
2292
2293 return ReuseShuffleCost + VecCallCost - ScalarCallCost;
2294 }
2295 case Instruction::ShuffleVector: {
2296 TargetTransformInfo::OperandValueKind Op1VK =
2297 TargetTransformInfo::OK_AnyValue;
2298 TargetTransformInfo::OperandValueKind Op2VK =
2299 TargetTransformInfo::OK_AnyValue;
2300 int ScalarCost = 0;
2301 if (NeedToShuffleReuses) {
2302 for (unsigned Idx : E->ReuseShuffleIndices) {
2303 Instruction *I = cast<Instruction>(VL[Idx]);
2304 if (!I)
2305 continue;
2306 ReuseShuffleCost -= TTI->getArithmeticInstrCost(
2307 I->getOpcode(), ScalarTy, Op1VK, Op2VK);
2308 }
2309 for (Value *V : VL) {
2310 Instruction *I = cast<Instruction>(V);
2311 if (!I)
2312 continue;
2313 ReuseShuffleCost += TTI->getArithmeticInstrCost(
2314 I->getOpcode(), ScalarTy, Op1VK, Op2VK);
2315 }
2316 }
2317 int VecCost = 0;
2318 for (Value *i : VL) {
2319 Instruction *I = cast<Instruction>(i);
2320 if (!I)
2321 break;
2322 ScalarCost +=
2323 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
2324 }
2325 // VecCost is equal to sum of the cost of creating 2 vectors
2326 // and the cost of creating shuffle.
2327 Instruction *I0 = cast<Instruction>(VL[0]);
2328 VecCost =
2329 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
2330 Instruction *I1 = cast<Instruction>(VL[1]);
2331 VecCost +=
2332 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
2333 VecCost +=
2334 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
2335 return ReuseShuffleCost + VecCost - ScalarCost;
2336 }
2337 default:
2338 llvm_unreachable("Unknown instruction")::llvm::llvm_unreachable_internal("Unknown instruction", "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2338)
;
2339 }
2340}
2341
2342bool BoUpSLP::isFullyVectorizableTinyTree() {
2343 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Check whether the tree with height "
<< VectorizableTree.size() << " is fully vectorizable .\n"
; } } while (false)
2344 VectorizableTree.size() << " is fully vectorizable .\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Check whether the tree with height "
<< VectorizableTree.size() << " is fully vectorizable .\n"
; } } while (false)
;
2345
2346 // We only handle trees of heights 1 and 2.
2347 if (VectorizableTree.size() == 1 && !VectorizableTree[0].NeedToGather)
2348 return true;
2349
2350 if (VectorizableTree.size() != 2)
2351 return false;
2352
2353 // Handle splat and all-constants stores.
2354 if (!VectorizableTree[0].NeedToGather &&
2355 (allConstant(VectorizableTree[1].Scalars) ||
2356 isSplat(VectorizableTree[1].Scalars)))
2357 return true;
2358
2359 // Gathering cost would be too much for tiny trees.
2360 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
2361 return false;
2362
2363 return true;
2364}
2365
2366bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() {
2367 // We can vectorize the tree if its size is greater than or equal to the
2368 // minimum size specified by the MinTreeSize command line option.
2369 if (VectorizableTree.size() >= MinTreeSize)
2370 return false;
2371
2372 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
2373 // can vectorize it if we can prove it fully vectorizable.
2374 if (isFullyVectorizableTinyTree())
2375 return false;
2376
2377 assert(VectorizableTree.empty()(static_cast <bool> (VectorizableTree.empty() ? ExternalUses
.empty() : true && "We shouldn't have any external users"
) ? void (0) : __assert_fail ("VectorizableTree.empty() ? ExternalUses.empty() : true && \"We shouldn't have any external users\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2379, __extension__ __PRETTY_FUNCTION__))
2378 ? ExternalUses.empty()(static_cast <bool> (VectorizableTree.empty() ? ExternalUses
.empty() : true && "We shouldn't have any external users"
) ? void (0) : __assert_fail ("VectorizableTree.empty() ? ExternalUses.empty() : true && \"We shouldn't have any external users\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2379, __extension__ __PRETTY_FUNCTION__))
2379 : true && "We shouldn't have any external users")(static_cast <bool> (VectorizableTree.empty() ? ExternalUses
.empty() : true && "We shouldn't have any external users"
) ? void (0) : __assert_fail ("VectorizableTree.empty() ? ExternalUses.empty() : true && \"We shouldn't have any external users\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2379, __extension__ __PRETTY_FUNCTION__))
;
2380
2381 // Otherwise, we can't vectorize the tree. It is both tiny and not fully
2382 // vectorizable.
2383 return true;
2384}
2385
2386int BoUpSLP::getSpillCost() {
2387 // Walk from the bottom of the tree to the top, tracking which values are
2388 // live. When we see a call instruction that is not part of our tree,
2389 // query TTI to see if there is a cost to keeping values live over it
2390 // (for example, if spills and fills are required).
2391 unsigned BundleWidth = VectorizableTree.front().Scalars.size();
2392 int Cost = 0;
2393
2394 SmallPtrSet<Instruction*, 4> LiveValues;
2395 Instruction *PrevInst = nullptr;
2396
2397 for (const auto &N : VectorizableTree) {
2398 Instruction *Inst = dyn_cast<Instruction>(N.Scalars[0]);
2399 if (!Inst)
2400 continue;
2401
2402 if (!PrevInst) {
2403 PrevInst = Inst;
2404 continue;
2405 }
2406
2407 // Update LiveValues.
2408 LiveValues.erase(PrevInst);
2409 for (auto &J : PrevInst->operands()) {
2410 if (isa<Instruction>(&*J) && getTreeEntry(&*J))
2411 LiveValues.insert(cast<Instruction>(&*J));
2412 }
2413
2414 DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: #LV: " << LiveValues.size
(); for (auto *X : LiveValues) dbgs() << " " << X
->getName(); dbgs() << ", Looking at "; Inst->dump
();; } } while (false)
2415 dbgs() << "SLP: #LV: " << LiveValues.size();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: #LV: " << LiveValues.size
(); for (auto *X : LiveValues) dbgs() << " " << X
->getName(); dbgs() << ", Looking at "; Inst->dump
();; } } while (false)
2416 for (auto *X : LiveValues)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: #LV: " << LiveValues.size
(); for (auto *X : LiveValues) dbgs() << " " << X
->getName(); dbgs() << ", Looking at "; Inst->dump
();; } } while (false)
2417 dbgs() << " " << X->getName();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: #LV: " << LiveValues.size
(); for (auto *X : LiveValues) dbgs() << " " << X
->getName(); dbgs() << ", Looking at "; Inst->dump
();; } } while (false)
2418 dbgs() << ", Looking at ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: #LV: " << LiveValues.size
(); for (auto *X : LiveValues) dbgs() << " " << X
->getName(); dbgs() << ", Looking at "; Inst->dump
();; } } while (false)
2419 Inst->dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: #LV: " << LiveValues.size
(); for (auto *X : LiveValues) dbgs() << " " << X
->getName(); dbgs() << ", Looking at "; Inst->dump
();; } } while (false)
2420 )do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: #LV: " << LiveValues.size
(); for (auto *X : LiveValues) dbgs() << " " << X
->getName(); dbgs() << ", Looking at "; Inst->dump
();; } } while (false)
;
2421
2422 // Now find the sequence of instructions between PrevInst and Inst.
2423 BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
2424 PrevInstIt =
2425 PrevInst->getIterator().getReverse();
2426 while (InstIt != PrevInstIt) {
2427 if (PrevInstIt == PrevInst->getParent()->rend()) {
2428 PrevInstIt = Inst->getParent()->rbegin();
2429 continue;
2430 }
2431
2432 if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
2433 SmallVector<Type*, 4> V;
2434 for (auto *II : LiveValues)
2435 V.push_back(VectorType::get(II->getType(), BundleWidth));
2436 Cost += TTI->getCostOfKeepingLiveOverCall(V);
2437 }
2438
2439 ++PrevInstIt;
2440 }
2441
2442 PrevInst = Inst;
2443 }
2444
2445 return Cost;
2446}
2447
2448int BoUpSLP::getTreeCost() {
2449 int Cost = 0;
2450 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Calculating cost for tree of size "
<< VectorizableTree.size() << ".\n"; } } while (
false)
2451 VectorizableTree.size() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Calculating cost for tree of size "
<< VectorizableTree.size() << ".\n"; } } while (
false)
;
2452
2453 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
2454
2455 for (TreeEntry &TE : VectorizableTree) {
2456 int C = getEntryCost(&TE);
2457 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for bundle that starts with " << *TE.Scalars[0] <<
".\n"; } } while (false)
2458 << *TE.Scalars[0] << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for bundle that starts with " << *TE.Scalars[0] <<
".\n"; } } while (false)
;
2459 Cost += C;
2460 }
2461
2462 SmallSet<Value *, 16> ExtractCostCalculated;
2463 int ExtractCost = 0;
2464 for (ExternalUser &EU : ExternalUses) {
2465 // We only add extract cost once for the same scalar.
2466 if (!ExtractCostCalculated.insert(EU.Scalar).second)
2467 continue;
2468
2469 // Uses by ephemeral values are free (because the ephemeral value will be
2470 // removed prior to code generation, and so the extraction will be
2471 // removed as well).
2472 if (EphValues.count(EU.User))
2473 continue;
2474
2475 // If we plan to rewrite the tree in a smaller type, we will need to sign
2476 // extend the extracted value back to the original type. Here, we account
2477 // for the extract and the added cost of the sign extend if needed.
2478 auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth);
2479 auto *ScalarRoot = VectorizableTree[0].Scalars[0];
2480 if (MinBWs.count(ScalarRoot)) {
2481 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
2482 auto Extend =
2483 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
2484 VecTy = VectorType::get(MinTy, BundleWidth);
2485 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
2486 VecTy, EU.Lane);
2487 } else {
2488 ExtractCost +=
2489 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
2490 }
2491 }
2492
2493 int SpillCost = getSpillCost();
2494 Cost += SpillCost + ExtractCost;
2495
2496 std::string Str;
2497 {
2498 raw_string_ostream OS(Str);
2499 OS << "SLP: Spill Cost = " << SpillCost << ".\n"
2500 << "SLP: Extract Cost = " << ExtractCost << ".\n"
2501 << "SLP: Total Cost = " << Cost << ".\n";
2502 }
2503 DEBUG(dbgs() << Str)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << Str; } } while (false)
;
2504
2505 if (ViewSLPTree)
2506 ViewGraph(this, "SLP" + F->getName(), false, Str);
2507
2508 return Cost;
2509}
2510
2511int BoUpSLP::getGatherCost(Type *Ty,
2512 const DenseSet<unsigned> &ShuffledIndices) {
2513 int Cost = 0;
2514 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
2515 if (!ShuffledIndices.count(i))
2516 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
2517 if (!ShuffledIndices.empty())
2518 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
2519 return Cost;
2520}
2521
2522int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
2523 // Find the type of the operands in VL.
2524 Type *ScalarTy = VL[0]->getType();
2525 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2526 ScalarTy = SI->getValueOperand()->getType();
2527 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2528 // Find the cost of inserting/extracting values from the vector.
2529 // Check if the same elements are inserted several times and count them as
2530 // shuffle candidates.
2531 DenseSet<unsigned> ShuffledElements;
2532 DenseSet<Value *> UniqueElements;
2533 // Iterate in reverse order to consider insert elements with the high cost.
2534 for (unsigned I = VL.size(); I > 0; --I) {
2535 unsigned Idx = I - 1;
2536 if (!UniqueElements.insert(VL[Idx]).second)
2537 ShuffledElements.insert(Idx);
2538 }
2539 return getGatherCost(VecTy, ShuffledElements);
2540}
2541
2542// Reorder commutative operations in alternate shuffle if the resulting vectors
2543// are consecutive loads. This would allow us to vectorize the tree.
2544// If we have something like-
2545// load a[0] - load b[0]
2546// load b[1] + load a[1]
2547// load a[2] - load b[2]
2548// load a[3] + load b[3]
2549// Reordering the second load b[1] load a[1] would allow us to vectorize this
2550// code.
2551void BoUpSLP::reorderAltShuffleOperands(unsigned Opcode, ArrayRef<Value *> VL,
2552 SmallVectorImpl<Value *> &Left,
2553 SmallVectorImpl<Value *> &Right) {
2554 // Push left and right operands of binary operation into Left and Right
2555 unsigned AltOpcode = getAltOpcode(Opcode);
2556 (void)AltOpcode;
2557 for (Value *V : VL) {
2558 auto *I = cast<Instruction>(V);
2559 assert(sameOpcodeOrAlt(Opcode, AltOpcode, I->getOpcode()) &&(static_cast <bool> (sameOpcodeOrAlt(Opcode, AltOpcode,
I->getOpcode()) && "Incorrect instruction in vector"
) ? void (0) : __assert_fail ("sameOpcodeOrAlt(Opcode, AltOpcode, I->getOpcode()) && \"Incorrect instruction in vector\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2560, __extension__ __PRETTY_FUNCTION__))
2560 "Incorrect instruction in vector")(static_cast <bool> (sameOpcodeOrAlt(Opcode, AltOpcode,
I->getOpcode()) && "Incorrect instruction in vector"
) ? void (0) : __assert_fail ("sameOpcodeOrAlt(Opcode, AltOpcode, I->getOpcode()) && \"Incorrect instruction in vector\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2560, __extension__ __PRETTY_FUNCTION__))
;
2561 Left.push_back(I->getOperand(0));
2562 Right.push_back(I->getOperand(1));
2563 }
2564
2565 // Reorder if we have a commutative operation and consecutive access
2566 // are on either side of the alternate instructions.
2567 for (unsigned j = 0; j < VL.size() - 1; ++j) {
2568 if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2569 if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2570 Instruction *VL1 = cast<Instruction>(VL[j]);
2571 Instruction *VL2 = cast<Instruction>(VL[j + 1]);
2572 if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
2573 std::swap(Left[j], Right[j]);
2574 continue;
2575 } else if (VL2->isCommutative() &&
2576 isConsecutiveAccess(L, L1, *DL, *SE)) {
2577 std::swap(Left[j + 1], Right[j + 1]);
2578 continue;
2579 }
2580 // else unchanged
2581 }
2582 }
2583 if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2584 if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2585 Instruction *VL1 = cast<Instruction>(VL[j]);
2586 Instruction *VL2 = cast<Instruction>(VL[j + 1]);
2587 if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
2588 std::swap(Left[j], Right[j]);
2589 continue;
2590 } else if (VL2->isCommutative() &&
2591 isConsecutiveAccess(L, L1, *DL, *SE)) {
2592 std::swap(Left[j + 1], Right[j + 1]);
2593 continue;
2594 }
2595 // else unchanged
2596 }
2597 }
2598 }
2599}
2600
2601// Return true if I should be commuted before adding it's left and right
2602// operands to the arrays Left and Right.
2603//
2604// The vectorizer is trying to either have all elements one side being
2605// instruction with the same opcode to enable further vectorization, or having
2606// a splat to lower the vectorizing cost.
2607static bool shouldReorderOperands(
2608 int i, unsigned Opcode, Instruction &I, ArrayRef<Value *> Left,
2609 ArrayRef<Value *> Right, bool AllSameOpcodeLeft, bool AllSameOpcodeRight,
2610 bool SplatLeft, bool SplatRight, Value *&VLeft, Value *&VRight) {
2611 VLeft = I.getOperand(0);
2612 VRight = I.getOperand(1);
2613 // If we have "SplatRight", try to see if commuting is needed to preserve it.
2614 if (SplatRight) {
2615 if (VRight == Right[i - 1])
2616 // Preserve SplatRight
2617 return false;
2618 if (VLeft == Right[i - 1]) {
2619 // Commuting would preserve SplatRight, but we don't want to break
2620 // SplatLeft either, i.e. preserve the original order if possible.
2621 // (FIXME: why do we care?)
2622 if (SplatLeft && VLeft == Left[i - 1])
2623 return false;
2624 return true;
2625 }
2626 }
2627 // Symmetrically handle Right side.
2628 if (SplatLeft) {
2629 if (VLeft == Left[i - 1])
2630 // Preserve SplatLeft
2631 return false;
2632 if (VRight == Left[i - 1])
2633 return true;
2634 }
2635
2636 Instruction *ILeft = dyn_cast<Instruction>(VLeft);
2637 Instruction *IRight = dyn_cast<Instruction>(VRight);
2638
2639 // If we have "AllSameOpcodeRight", try to see if the left operands preserves
2640 // it and not the right, in this case we want to commute.
2641 if (AllSameOpcodeRight) {
2642 unsigned RightPrevOpcode = cast<Instruction>(Right[i - 1])->getOpcode();
2643 if (IRight && RightPrevOpcode == IRight->getOpcode())
2644 // Do not commute, a match on the right preserves AllSameOpcodeRight
2645 return false;
2646 if (ILeft && RightPrevOpcode == ILeft->getOpcode()) {
2647 // We have a match and may want to commute, but first check if there is
2648 // not also a match on the existing operands on the Left to preserve
2649 // AllSameOpcodeLeft, i.e. preserve the original order if possible.
2650 // (FIXME: why do we care?)
2651 if (AllSameOpcodeLeft && ILeft &&
2652 cast<Instruction>(Left[i - 1])->getOpcode() == ILeft->getOpcode())
2653 return false;
2654 return true;
2655 }
2656 }
2657 // Symmetrically handle Left side.
2658 if (AllSameOpcodeLeft) {
2659 unsigned LeftPrevOpcode = cast<Instruction>(Left[i - 1])->getOpcode();
2660 if (ILeft && LeftPrevOpcode == ILeft->getOpcode())
2661 return false;
2662 if (IRight && LeftPrevOpcode == IRight->getOpcode())
2663 return true;
2664 }
2665 return false;
2666}
2667
2668void BoUpSLP::reorderInputsAccordingToOpcode(unsigned Opcode,
2669 ArrayRef<Value *> VL,
2670 SmallVectorImpl<Value *> &Left,
2671 SmallVectorImpl<Value *> &Right) {
2672 if (!VL.empty()) {
2673 // Peel the first iteration out of the loop since there's nothing
2674 // interesting to do anyway and it simplifies the checks in the loop.
2675 auto *I = cast<Instruction>(VL[0]);
2676 Value *VLeft = I->getOperand(0);
2677 Value *VRight = I->getOperand(1);
2678 if (!isa<Instruction>(VRight) && isa<Instruction>(VLeft))
2679 // Favor having instruction to the right. FIXME: why?
2680 std::swap(VLeft, VRight);
2681 Left.push_back(VLeft);
2682 Right.push_back(VRight);
2683 }
2684
2685 // Keep track if we have instructions with all the same opcode on one side.
2686 bool AllSameOpcodeLeft = isa<Instruction>(Left[0]);
2687 bool AllSameOpcodeRight = isa<Instruction>(Right[0]);
2688 // Keep track if we have one side with all the same value (broadcast).
2689 bool SplatLeft = true;
2690 bool SplatRight = true;
2691
2692 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
2693 Instruction *I = cast<Instruction>(VL[i]);
2694 assert(((I->getOpcode() == Opcode && I->isCommutative()) ||(static_cast <bool> (((I->getOpcode() == Opcode &&
I->isCommutative()) || (I->getOpcode() != Opcode &&
Instruction::isCommutative(Opcode))) && "Can only process commutative instruction"
) ? void (0) : __assert_fail ("((I->getOpcode() == Opcode && I->isCommutative()) || (I->getOpcode() != Opcode && Instruction::isCommutative(Opcode))) && \"Can only process commutative instruction\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2696, __extension__ __PRETTY_FUNCTION__))
2695 (I->getOpcode() != Opcode && Instruction::isCommutative(Opcode))) &&(static_cast <bool> (((I->getOpcode() == Opcode &&
I->isCommutative()) || (I->getOpcode() != Opcode &&
Instruction::isCommutative(Opcode))) && "Can only process commutative instruction"
) ? void (0) : __assert_fail ("((I->getOpcode() == Opcode && I->isCommutative()) || (I->getOpcode() != Opcode && Instruction::isCommutative(Opcode))) && \"Can only process commutative instruction\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2696, __extension__ __PRETTY_FUNCTION__))
2696 "Can only process commutative instruction")(static_cast <bool> (((I->getOpcode() == Opcode &&
I->isCommutative()) || (I->getOpcode() != Opcode &&
Instruction::isCommutative(Opcode))) && "Can only process commutative instruction"
) ? void (0) : __assert_fail ("((I->getOpcode() == Opcode && I->isCommutative()) || (I->getOpcode() != Opcode && Instruction::isCommutative(Opcode))) && \"Can only process commutative instruction\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2696, __extension__ __PRETTY_FUNCTION__))
;
2697 // Commute to favor either a splat or maximizing having the same opcodes on
2698 // one side.
2699 Value *VLeft;
2700 Value *VRight;
2701 if (shouldReorderOperands(i, Opcode, *I, Left, Right, AllSameOpcodeLeft,
2702 AllSameOpcodeRight, SplatLeft, SplatRight, VLeft,
2703 VRight)) {
2704 Left.push_back(VRight);
2705 Right.push_back(VLeft);
2706 } else {
2707 Left.push_back(VLeft);
2708 Right.push_back(VRight);
2709 }
2710 // Update Splat* and AllSameOpcode* after the insertion.
2711 SplatRight = SplatRight && (Right[i - 1] == Right[i]);
2712 SplatLeft = SplatLeft && (Left[i - 1] == Left[i]);
2713 AllSameOpcodeLeft = AllSameOpcodeLeft && isa<Instruction>(Left[i]) &&
2714 (cast<Instruction>(Left[i - 1])->getOpcode() ==
2715 cast<Instruction>(Left[i])->getOpcode());
2716 AllSameOpcodeRight = AllSameOpcodeRight && isa<Instruction>(Right[i]) &&
2717 (cast<Instruction>(Right[i - 1])->getOpcode() ==
2718 cast<Instruction>(Right[i])->getOpcode());
2719 }
2720
2721 // If one operand end up being broadcast, return this operand order.
2722 if (SplatRight || SplatLeft)
2723 return;
2724
2725 // Finally check if we can get longer vectorizable chain by reordering
2726 // without breaking the good operand order detected above.
2727 // E.g. If we have something like-
2728 // load a[0] load b[0]
2729 // load b[1] load a[1]
2730 // load a[2] load b[2]
2731 // load a[3] load b[3]
2732 // Reordering the second load b[1] load a[1] would allow us to vectorize
2733 // this code and we still retain AllSameOpcode property.
2734 // FIXME: This load reordering might break AllSameOpcode in some rare cases
2735 // such as-
2736 // add a[0],c[0] load b[0]
2737 // add a[1],c[2] load b[1]
2738 // b[2] load b[2]
2739 // add a[3],c[3] load b[3]
2740 for (unsigned j = 0; j < VL.size() - 1; ++j) {
2741 if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2742 if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2743 if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2744 std::swap(Left[j + 1], Right[j + 1]);
2745 continue;
2746 }
2747 }
2748 }
2749 if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2750 if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2751 if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2752 std::swap(Left[j + 1], Right[j + 1]);
2753 continue;
2754 }
2755 }
2756 }
2757 // else unchanged
2758 }
2759}
2760
2761void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL, Value *OpValue) {
2762 // Get the basic block this bundle is in. All instructions in the bundle
2763 // should be in this block.
2764 auto *Front = cast<Instruction>(OpValue);
2765 auto *BB = Front->getParent();
2766 const unsigned Opcode = cast<Instruction>(OpValue)->getOpcode();
2767 const unsigned AltOpcode = getAltOpcode(Opcode);
2768 assert(llvm::all_of(make_range(VL.begin(), VL.end()), [=](Value *V) -> bool {(static_cast <bool> (llvm::all_of(make_range(VL.begin()
, VL.end()), [=](Value *V) -> bool { return !sameOpcodeOrAlt
(Opcode, AltOpcode, cast<Instruction>(V)->getOpcode(
)) || cast<Instruction>(V)->getParent() == BB; })) ?
void (0) : __assert_fail ("llvm::all_of(make_range(VL.begin(), VL.end()), [=](Value *V) -> bool { return !sameOpcodeOrAlt(Opcode, AltOpcode, cast<Instruction>(V)->getOpcode()) || cast<Instruction>(V)->getParent() == BB; })"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2772, __extension__ __PRETTY_FUNCTION__))
2769 return !sameOpcodeOrAlt(Opcode, AltOpcode,(static_cast <bool> (llvm::all_of(make_range(VL.begin()
, VL.end()), [=](Value *V) -> bool { return !sameOpcodeOrAlt
(Opcode, AltOpcode, cast<Instruction>(V)->getOpcode(
)) || cast<Instruction>(V)->getParent() == BB; })) ?
void (0) : __assert_fail ("llvm::all_of(make_range(VL.begin(), VL.end()), [=](Value *V) -> bool { return !sameOpcodeOrAlt(Opcode, AltOpcode, cast<Instruction>(V)->getOpcode()) || cast<Instruction>(V)->getParent() == BB; })"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2772, __extension__ __PRETTY_FUNCTION__))
2770 cast<Instruction>(V)->getOpcode()) ||(static_cast <bool> (llvm::all_of(make_range(VL.begin()
, VL.end()), [=](Value *V) -> bool { return !sameOpcodeOrAlt
(Opcode, AltOpcode, cast<Instruction>(V)->getOpcode(
)) || cast<Instruction>(V)->getParent() == BB; })) ?
void (0) : __assert_fail ("llvm::all_of(make_range(VL.begin(), VL.end()), [=](Value *V) -> bool { return !sameOpcodeOrAlt(Opcode, AltOpcode, cast<Instruction>(V)->getOpcode()) || cast<Instruction>(V)->getParent() == BB; })"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2772, __extension__ __PRETTY_FUNCTION__))
2771 cast<Instruction>(V)->getParent() == BB;(static_cast <bool> (llvm::all_of(make_range(VL.begin()
, VL.end()), [=](Value *V) -> bool { return !sameOpcodeOrAlt
(Opcode, AltOpcode, cast<Instruction>(V)->getOpcode(
)) || cast<Instruction>(V)->getParent() == BB; })) ?
void (0) : __assert_fail ("llvm::all_of(make_range(VL.begin(), VL.end()), [=](Value *V) -> bool { return !sameOpcodeOrAlt(Opcode, AltOpcode, cast<Instruction>(V)->getOpcode()) || cast<Instruction>(V)->getParent() == BB; })"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2772, __extension__ __PRETTY_FUNCTION__))
2772 }))(static_cast <bool> (llvm::all_of(make_range(VL.begin()
, VL.end()), [=](Value *V) -> bool { return !sameOpcodeOrAlt
(Opcode, AltOpcode, cast<Instruction>(V)->getOpcode(
)) || cast<Instruction>(V)->getParent() == BB; })) ?
void (0) : __assert_fail ("llvm::all_of(make_range(VL.begin(), VL.end()), [=](Value *V) -> bool { return !sameOpcodeOrAlt(Opcode, AltOpcode, cast<Instruction>(V)->getOpcode()) || cast<Instruction>(V)->getParent() == BB; })"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2772, __extension__ __PRETTY_FUNCTION__))
;
2773
2774 // The last instruction in the bundle in program order.
2775 Instruction *LastInst = nullptr;
2776
2777 // Find the last instruction. The common case should be that BB has been
2778 // scheduled, and the last instruction is VL.back(). So we start with
2779 // VL.back() and iterate over schedule data until we reach the end of the
2780 // bundle. The end of the bundle is marked by null ScheduleData.
2781 if (BlocksSchedules.count(BB)) {
2782 auto *Bundle =
2783 BlocksSchedules[BB]->getScheduleData(isOneOf(OpValue, VL.back()));
2784 if (Bundle && Bundle->isPartOfBundle())
2785 for (; Bundle; Bundle = Bundle->NextInBundle)
2786 if (Bundle->OpValue == Bundle->Inst)
2787 LastInst = Bundle->Inst;
2788 }
2789
2790 // LastInst can still be null at this point if there's either not an entry
2791 // for BB in BlocksSchedules or there's no ScheduleData available for
2792 // VL.back(). This can be the case if buildTree_rec aborts for various
2793 // reasons (e.g., the maximum recursion depth is reached, the maximum region
2794 // size is reached, etc.). ScheduleData is initialized in the scheduling
2795 // "dry-run".
2796 //
2797 // If this happens, we can still find the last instruction by brute force. We
2798 // iterate forwards from Front (inclusive) until we either see all
2799 // instructions in the bundle or reach the end of the block. If Front is the
2800 // last instruction in program order, LastInst will be set to Front, and we
2801 // will visit all the remaining instructions in the block.
2802 //
2803 // One of the reasons we exit early from buildTree_rec is to place an upper
2804 // bound on compile-time. Thus, taking an additional compile-time hit here is
2805 // not ideal. However, this should be exceedingly rare since it requires that
2806 // we both exit early from buildTree_rec and that the bundle be out-of-order
2807 // (causing us to iterate all the way to the end of the block).
2808 if (!LastInst) {
2809 SmallPtrSet<Value *, 16> Bundle(VL.begin(), VL.end());
2810 for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
2811 if (Bundle.erase(&I) && sameOpcodeOrAlt(Opcode, AltOpcode, I.getOpcode()))
2812 LastInst = &I;
2813 if (Bundle.empty())
2814 break;
2815 }
2816 }
2817
2818 // Set the insertion point after the last instruction in the bundle. Set the
2819 // debug location to Front.
2820 Builder.SetInsertPoint(BB, ++LastInst->getIterator());
2821 Builder.SetCurrentDebugLocation(Front->getDebugLoc());
2822}
2823
2824Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
2825 Value *Vec = UndefValue::get(Ty);
2826 // Generate the 'InsertElement' instruction.
2827 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
2828 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
2829 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
2830 GatherSeq.insert(Insrt);
2831 CSEBlocks.insert(Insrt->getParent());
2832
2833 // Add to our 'need-to-extract' list.
2834 if (TreeEntry *E = getTreeEntry(VL[i])) {
2835 // Find which lane we need to extract.
2836 int FoundLane = -1;
2837 for (unsigned Lane = 0, LE = E->Scalars.size(); Lane != LE; ++Lane) {
2838 // Is this the lane of the scalar that we are looking for ?
2839 if (E->Scalars[Lane] == VL[i]) {
2840 FoundLane = Lane;
2841 break;
2842 }
2843 }
2844 assert(FoundLane >= 0 && "Could not find the correct lane")(static_cast <bool> (FoundLane >= 0 && "Could not find the correct lane"
) ? void (0) : __assert_fail ("FoundLane >= 0 && \"Could not find the correct lane\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2844, __extension__ __PRETTY_FUNCTION__))
;
2845 if (!E->ReuseShuffleIndices.empty()) {
2846 FoundLane =
2847 std::distance(E->ReuseShuffleIndices.begin(),
2848 llvm::find(E->ReuseShuffleIndices, FoundLane));
2849 }
2850 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
2851 }
2852 }
2853 }
2854
2855 return Vec;
2856}
2857
2858Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
2859 InstructionsState S = getSameOpcode(VL);
2860 if (S.Opcode) {
2861 if (TreeEntry *E = getTreeEntry(S.OpValue)) {
2862 if (E->isSame(VL)) {
2863 Value *V = vectorizeTree(E);
2864 if (VL.size() == E->Scalars.size() && !E->ReuseShuffleIndices.empty()) {
2865 // We need to get the vectorized value but without shuffle.
2866 if (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
2867 V = SV->getOperand(0);
2868 } else {
2869 // Reshuffle to get only unique values.
2870 SmallVector<unsigned, 4> UniqueIdxs;
2871 SmallSet<unsigned, 4> UsedIdxs;
2872 for(unsigned Idx : E->ReuseShuffleIndices)
2873 if (UsedIdxs.insert(Idx).second)
2874 UniqueIdxs.emplace_back(Idx);
2875 V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
2876 UniqueIdxs);
2877 }
2878 }
2879 return V;
2880 }
2881 }
2882 }
2883
2884 Type *ScalarTy = S.OpValue->getType();
2885 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
2886 ScalarTy = SI->getValueOperand()->getType();
2887
2888 // Check that every instruction appears once in this bundle.
2889 SmallVector<unsigned, 4> ReuseShuffleIndicies;
2890 SmallVector<Value *, 4> UniqueValues;
2891 if (VL.size() > 2) {
2892 DenseMap<Value *, unsigned> UniquePositions;
2893 for (Value *V : VL) {
2894 auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
2895 ReuseShuffleIndicies.emplace_back(Res.first->second);
2896 if (Res.second || isa<Constant>(V))
2897 UniqueValues.emplace_back(V);
2898 }
2899 // Do not shuffle single element or if number of unique values is not power
2900 // of 2.
2901 if (UniqueValues.size() == VL.size() || UniqueValues.size() <= 1 ||
2902 !llvm::isPowerOf2_32(UniqueValues.size()))
2903 ReuseShuffleIndicies.clear();
2904 else
2905 VL = UniqueValues;
2906 }
2907 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2908
2909 Value *V = Gather(VL, VecTy);
2910 if (!ReuseShuffleIndicies.empty()) {
2911 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
2912 ReuseShuffleIndicies, "shuffle");
2913 if (auto *I = dyn_cast<Instruction>(V)) {
2914 GatherSeq.insert(I);
2915 CSEBlocks.insert(I->getParent());
2916 }
2917 }
2918 return V;
2919}
2920
2921Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
2922 IRBuilder<>::InsertPointGuard Guard(Builder);
2923
2924 if (E->VectorizedValue) {
1
Assuming the condition is false
2
Taking false branch
2925 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*E->Scalars[0] << ".\n"; } } while (false)
;
2926 return E->VectorizedValue;
2927 }
2928
2929 InstructionsState S = getSameOpcode(E->Scalars);
2930 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
2931 Type *ScalarTy = VL0->getType();
2932 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
3
Taking false branch
2933 ScalarTy = SI->getValueOperand()->getType();
2934 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
2935
2936 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
2937
2938 if (E->NeedToGather) {
4
Assuming the condition is false
5
Taking false branch
2939 setInsertPointAfterBundle(E->Scalars, VL0);
2940 auto *V = Gather(E->Scalars, VecTy);
2941 if (NeedToShuffleReuses) {
2942 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
2943 E->ReuseShuffleIndices, "shuffle");
2944 if (auto *I = dyn_cast<Instruction>(V)) {
2945 GatherSeq.insert(I);
2946 CSEBlocks.insert(I->getParent());
2947 }
2948 }
2949 E->VectorizedValue = V;
2950 return V;
2951 }
2952
2953 unsigned ShuffleOrOp = S.IsAltShuffle ?
6
'?' condition is false
2954 (unsigned) Instruction::ShuffleVector : S.Opcode;
2955 switch (ShuffleOrOp) {
7
Control jumps to 'case Call:' at line 3302
2956 case Instruction::PHI: {
2957 PHINode *PH = dyn_cast<PHINode>(VL0);
2958 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
2959 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2960 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
2961 Value *V = NewPhi;
2962 if (NeedToShuffleReuses) {
2963 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
2964 E->ReuseShuffleIndices, "shuffle");
2965 }
2966 E->VectorizedValue = V;
2967
2968 // PHINodes may have multiple entries from the same block. We want to
2969 // visit every block once.
2970 SmallSet<BasicBlock*, 4> VisitedBBs;
2971
2972 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
2973 ValueList Operands;
2974 BasicBlock *IBB = PH->getIncomingBlock(i);
2975
2976 if (!VisitedBBs.insert(IBB).second) {
2977 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
2978 continue;
2979 }
2980
2981 // Prepare the operand vector.
2982 for (Value *V : E->Scalars)
2983 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(IBB));
2984
2985 Builder.SetInsertPoint(IBB->getTerminator());
2986 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2987 Value *Vec = vectorizeTree(Operands);
2988 NewPhi->addIncoming(Vec, IBB);
2989 }
2990
2991 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&(static_cast <bool> (NewPhi->getNumIncomingValues() ==
PH->getNumIncomingValues() && "Invalid number of incoming values"
) ? void (0) : __assert_fail ("NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && \"Invalid number of incoming values\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2992, __extension__ __PRETTY_FUNCTION__))
2992 "Invalid number of incoming values")(static_cast <bool> (NewPhi->getNumIncomingValues() ==
PH->getNumIncomingValues() && "Invalid number of incoming values"
) ? void (0) : __assert_fail ("NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && \"Invalid number of incoming values\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 2992, __extension__ __PRETTY_FUNCTION__))
;
2993 return V;
2994 }
2995
2996 case Instruction::ExtractElement: {
2997 if (canReuseExtract(E->Scalars, VL0)) {
2998 Value *V = VL0->getOperand(0);
2999 if (NeedToShuffleReuses) {
3000 Builder.SetInsertPoint(VL0);
3001 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3002 E->ReuseShuffleIndices, "shuffle");
3003 }
3004 E->VectorizedValue = V;
3005 return V;
3006 }
3007 setInsertPointAfterBundle(E->Scalars, VL0);
3008 auto *V = Gather(E->Scalars, VecTy);
3009 if (NeedToShuffleReuses) {
3010 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3011 E->ReuseShuffleIndices, "shuffle");
3012 if (auto *I = dyn_cast<Instruction>(V)) {
3013 GatherSeq.insert(I);
3014 CSEBlocks.insert(I->getParent());
3015 }
3016 }
3017 E->VectorizedValue = V;
3018 return V;
3019 }
3020 case Instruction::ExtractValue: {
3021 if (canReuseExtract(E->Scalars, VL0)) {
3022 LoadInst *LI = cast<LoadInst>(VL0->getOperand(0));
3023 Builder.SetInsertPoint(LI);
3024 PointerType *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
3025 Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
3026 LoadInst *V = Builder.CreateAlignedLoad(Ptr, LI->getAlignment());
3027 Value *NewV = propagateMetadata(V, E->Scalars);
3028 if (NeedToShuffleReuses) {
3029 NewV = Builder.CreateShuffleVector(
3030 NewV, UndefValue::get(VecTy), E->ReuseShuffleIndices, "shuffle");
3031 }
3032 E->VectorizedValue = NewV;
3033 return NewV;
3034 }
3035 setInsertPointAfterBundle(E->Scalars, VL0);
3036 auto *V = Gather(E->Scalars, VecTy);
3037 if (NeedToShuffleReuses) {
3038 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3039 E->ReuseShuffleIndices, "shuffle");
3040 if (auto *I = dyn_cast<Instruction>(V)) {
3041 GatherSeq.insert(I);
3042 CSEBlocks.insert(I->getParent());
3043 }
3044 }
3045 E->VectorizedValue = V;
3046 return V;
3047 }
3048 case Instruction::ZExt:
3049 case Instruction::SExt:
3050 case Instruction::FPToUI:
3051 case Instruction::FPToSI:
3052 case Instruction::FPExt:
3053 case Instruction::PtrToInt:
3054 case Instruction::IntToPtr:
3055 case Instruction::SIToFP:
3056 case Instruction::UIToFP:
3057 case Instruction::Trunc:
3058 case Instruction::FPTrunc:
3059 case Instruction::BitCast: {
3060 ValueList INVL;
3061 for (Value *V : E->Scalars)
3062 INVL.push_back(cast<Instruction>(V)->getOperand(0));
3063
3064 setInsertPointAfterBundle(E->Scalars, VL0);
3065
3066 Value *InVec = vectorizeTree(INVL);
3067
3068 if (E->VectorizedValue) {
3069 DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
3070 return E->VectorizedValue;
3071 }
3072
3073 CastInst *CI = dyn_cast<CastInst>(VL0);
3074 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
3075 if (NeedToShuffleReuses) {
3076 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3077 E->ReuseShuffleIndices, "shuffle");
3078 }
3079 E->VectorizedValue = V;
3080 ++NumVectorInstructions;
3081 return V;
3082 }
3083 case Instruction::FCmp:
3084 case Instruction::ICmp: {
3085 ValueList LHSV, RHSV;
3086 for (Value *V : E->Scalars) {
3087 LHSV.push_back(cast<Instruction>(V)->getOperand(0));
3088 RHSV.push_back(cast<Instruction>(V)->getOperand(1));
3089 }
3090
3091 setInsertPointAfterBundle(E->Scalars, VL0);
3092
3093 Value *L = vectorizeTree(LHSV);
3094 Value *R = vectorizeTree(RHSV);
3095
3096 if (E->VectorizedValue) {
3097 DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
3098 return E->VectorizedValue;
3099 }
3100
3101 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
3102 Value *V;
3103 if (S.Opcode == Instruction::FCmp)
3104 V = Builder.CreateFCmp(P0, L, R);
3105 else
3106 V = Builder.CreateICmp(P0, L, R);
3107
3108 propagateIRFlags(V, E->Scalars, VL0);
3109 if (NeedToShuffleReuses) {
3110 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3111 E->ReuseShuffleIndices, "shuffle");
3112 }
3113 E->VectorizedValue = V;
3114 ++NumVectorInstructions;
3115 return V;
3116 }
3117 case Instruction::Select: {
3118 ValueList TrueVec, FalseVec, CondVec;
3119 for (Value *V : E->Scalars) {
3120 CondVec.push_back(cast<Instruction>(V)->getOperand(0));
3121 TrueVec.push_back(cast<Instruction>(V)->getOperand(1));
3122 FalseVec.push_back(cast<Instruction>(V)->getOperand(2));
3123 }
3124
3125 setInsertPointAfterBundle(E->Scalars, VL0);
3126
3127 Value *Cond = vectorizeTree(CondVec);
3128 Value *True = vectorizeTree(TrueVec);
3129 Value *False = vectorizeTree(FalseVec);
3130
3131 if (E->VectorizedValue) {
3132 DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
3133 return E->VectorizedValue;
3134 }
3135
3136 Value *V = Builder.CreateSelect(Cond, True, False);
3137 if (NeedToShuffleReuses) {
3138 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3139 E->ReuseShuffleIndices, "shuffle");
3140 }
3141 E->VectorizedValue = V;
3142 ++NumVectorInstructions;
3143 return V;
3144 }
3145 case Instruction::Add:
3146 case Instruction::FAdd:
3147 case Instruction::Sub:
3148 case Instruction::FSub:
3149 case Instruction::Mul:
3150 case Instruction::FMul:
3151 case Instruction::UDiv:
3152 case Instruction::SDiv:
3153 case Instruction::FDiv:
3154 case Instruction::URem:
3155 case Instruction::SRem:
3156 case Instruction::FRem:
3157 case Instruction::Shl:
3158 case Instruction::LShr:
3159 case Instruction::AShr:
3160 case Instruction::And:
3161 case Instruction::Or:
3162 case Instruction::Xor: {
3163 ValueList LHSVL, RHSVL;
3164 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
3165 reorderInputsAccordingToOpcode(S.Opcode, E->Scalars, LHSVL,
3166 RHSVL);
3167 else
3168 for (Value *V : E->Scalars) {
3169 auto *I = cast<Instruction>(V);
3170 LHSVL.push_back(I->getOperand(0));
3171 RHSVL.push_back(I->getOperand(1));
3172 }
3173
3174 setInsertPointAfterBundle(E->Scalars, VL0);
3175
3176 Value *LHS = vectorizeTree(LHSVL);
3177 Value *RHS = vectorizeTree(RHSVL);
3178
3179 if (E->VectorizedValue) {
3180 DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
3181 return E->VectorizedValue;
3182 }
3183
3184 Value *V = Builder.CreateBinOp(
3185 static_cast<Instruction::BinaryOps>(S.Opcode), LHS, RHS);
3186 propagateIRFlags(V, E->Scalars, VL0);
3187 if (auto *I = dyn_cast<Instruction>(V))
3188 V = propagateMetadata(I, E->Scalars);
3189
3190 if (NeedToShuffleReuses) {
3191 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3192 E->ReuseShuffleIndices, "shuffle");
3193 }
3194 E->VectorizedValue = V;
3195 ++NumVectorInstructions;
3196
3197 return V;
3198 }
3199 case Instruction::Load: {
3200 // Loads are inserted at the head of the tree because we don't want to
3201 // sink them all the way down past store instructions.
3202 setInsertPointAfterBundle(E->Scalars, VL0);
3203
3204 LoadInst *LI = cast<LoadInst>(VL0);
3205 Type *ScalarLoadTy = LI->getType();
3206 unsigned AS = LI->getPointerAddressSpace();
3207
3208 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
3209 VecTy->getPointerTo(AS));
3210
3211 // The pointer operand uses an in-tree scalar so we add the new BitCast to
3212 // ExternalUses list to make sure that an extract will be generated in the
3213 // future.
3214 Value *PO = LI->getPointerOperand();
3215 if (getTreeEntry(PO))
3216 ExternalUses.push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
3217
3218 unsigned Alignment = LI->getAlignment();
3219 LI = Builder.CreateLoad(VecPtr);
3220 if (!Alignment) {
3221 Alignment = DL->getABITypeAlignment(ScalarLoadTy);
3222 }
3223 LI->setAlignment(Alignment);
3224 Value *V = propagateMetadata(LI, E->Scalars);
3225 if (NeedToShuffleReuses) {
3226 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3227 E->ReuseShuffleIndices, "shuffle");
3228 }
3229 E->VectorizedValue = V;
3230 ++NumVectorInstructions;
3231 return V;
3232 }
3233 case Instruction::Store: {
3234 StoreInst *SI = cast<StoreInst>(VL0);
3235 unsigned Alignment = SI->getAlignment();
3236 unsigned AS = SI->getPointerAddressSpace();
3237
3238 ValueList ScalarStoreValues;
3239 for (Value *V : E->Scalars)
3240 ScalarStoreValues.push_back(cast<StoreInst>(V)->getValueOperand());
3241
3242 setInsertPointAfterBundle(E->Scalars, VL0);
3243
3244 Value *VecValue = vectorizeTree(ScalarStoreValues);
3245 Value *ScalarPtr = SI->getPointerOperand();
3246 Value *VecPtr = Builder.CreateBitCast(ScalarPtr, VecTy->getPointerTo(AS));
3247 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
3248
3249 // The pointer operand uses an in-tree scalar, so add the new BitCast to
3250 // ExternalUses to make sure that an extract will be generated in the
3251 // future.
3252 if (getTreeEntry(ScalarPtr))
3253 ExternalUses.push_back(ExternalUser(ScalarPtr, cast<User>(VecPtr), 0));
3254
3255 if (!Alignment)
3256 Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
3257
3258 S->setAlignment(Alignment);
3259 Value *V = propagateMetadata(S, E->Scalars);
3260 if (NeedToShuffleReuses) {
3261 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3262 E->ReuseShuffleIndices, "shuffle");
3263 }
3264 E->VectorizedValue = V;
3265 ++NumVectorInstructions;
3266 return V;
3267 }
3268 case Instruction::GetElementPtr: {
3269 setInsertPointAfterBundle(E->Scalars, VL0);
3270
3271 ValueList Op0VL;
3272 for (Value *V : E->Scalars)
3273 Op0VL.push_back(cast<GetElementPtrInst>(V)->getOperand(0));
3274
3275 Value *Op0 = vectorizeTree(Op0VL);
3276
3277 std::vector<Value *> OpVecs;
3278 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
3279 ++j) {
3280 ValueList OpVL;
3281 for (Value *V : E->Scalars)
3282 OpVL.push_back(cast<GetElementPtrInst>(V)->getOperand(j));
3283
3284 Value *OpVec = vectorizeTree(OpVL);
3285 OpVecs.push_back(OpVec);
3286 }
3287
3288 Value *V = Builder.CreateGEP(
3289 cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
3290 if (Instruction *I = dyn_cast<Instruction>(V))
3291 V = propagateMetadata(I, E->Scalars);
3292
3293 if (NeedToShuffleReuses) {
3294 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3295 E->ReuseShuffleIndices, "shuffle");
3296 }
3297 E->VectorizedValue = V;
3298 ++NumVectorInstructions;
3299
3300 return V;
3301 }
3302 case Instruction::Call: {
3303 CallInst *CI = cast<CallInst>(VL0);
8
Calling 'cast'
32
Returning from 'cast'
33
'CI' initialized here
3304 setInsertPointAfterBundle(E->Scalars, VL0);
3305 Function *FI;
3306 Intrinsic::ID IID = Intrinsic::not_intrinsic;
3307 Value *ScalarArg = nullptr;
3308 if (CI && (FI = CI->getCalledFunction())) {
34
Assuming 'CI' is null
3309 IID = FI->getIntrinsicID();
3310 }
3311 std::vector<Value *> OpVecs;
3312 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
35
Called C++ object pointer is null
3313 ValueList OpVL;
3314 // ctlz,cttz and powi are special intrinsics whose second argument is
3315 // a scalar. This argument should not be vectorized.
3316 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
3317 CallInst *CEI = cast<CallInst>(VL0);
3318 ScalarArg = CEI->getArgOperand(j);
3319 OpVecs.push_back(CEI->getArgOperand(j));
3320 continue;
3321 }
3322 for (Value *V : E->Scalars) {
3323 CallInst *CEI = cast<CallInst>(V);
3324 OpVL.push_back(CEI->getArgOperand(j));
3325 }
3326
3327 Value *OpVec = vectorizeTree(OpVL);
3328 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: OpVec[" << j << "]: "
<< *OpVec << "\n"; } } while (false)
;
3329 OpVecs.push_back(OpVec);
3330 }
3331
3332 Module *M = F->getParent();
3333 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3334 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
3335 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
3336 SmallVector<OperandBundleDef, 1> OpBundles;
3337 CI->getOperandBundlesAsDefs(OpBundles);
3338 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
3339
3340 // The scalar argument uses an in-tree scalar so we add the new vectorized
3341 // call to ExternalUses list to make sure that an extract will be
3342 // generated in the future.
3343 if (ScalarArg && getTreeEntry(ScalarArg))
3344 ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
3345
3346 propagateIRFlags(V, E->Scalars, VL0);
3347 if (NeedToShuffleReuses) {
3348 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3349 E->ReuseShuffleIndices, "shuffle");
3350 }
3351 E->VectorizedValue = V;
3352 ++NumVectorInstructions;
3353 return V;
3354 }
3355 case Instruction::ShuffleVector: {
3356 ValueList LHSVL, RHSVL;
3357 assert(Instruction::isBinaryOp(S.Opcode) &&(static_cast <bool> (Instruction::isBinaryOp(S.Opcode) &&
"Invalid Shuffle Vector Operand") ? void (0) : __assert_fail
("Instruction::isBinaryOp(S.Opcode) && \"Invalid Shuffle Vector Operand\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3358, __extension__ __PRETTY_FUNCTION__))
3358 "Invalid Shuffle Vector Operand")(static_cast <bool> (Instruction::isBinaryOp(S.Opcode) &&
"Invalid Shuffle Vector Operand") ? void (0) : __assert_fail
("Instruction::isBinaryOp(S.Opcode) && \"Invalid Shuffle Vector Operand\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3358, __extension__ __PRETTY_FUNCTION__))
;
3359 reorderAltShuffleOperands(S.Opcode, E->Scalars, LHSVL, RHSVL);
3360 setInsertPointAfterBundle(E->Scalars, VL0);
3361
3362 Value *LHS = vectorizeTree(LHSVL);
3363 Value *RHS = vectorizeTree(RHSVL);
3364
3365 if (E->VectorizedValue) {
3366 DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
3367 return E->VectorizedValue;
3368 }
3369
3370 // Create a vector of LHS op1 RHS
3371 Value *V0 = Builder.CreateBinOp(
3372 static_cast<Instruction::BinaryOps>(S.Opcode), LHS, RHS);
3373
3374 unsigned AltOpcode = getAltOpcode(S.Opcode);
3375 // Create a vector of LHS op2 RHS
3376 Value *V1 = Builder.CreateBinOp(
3377 static_cast<Instruction::BinaryOps>(AltOpcode), LHS, RHS);
3378
3379 // Create shuffle to take alternate operations from the vector.
3380 // Also, gather up odd and even scalar ops to propagate IR flags to
3381 // each vector operation.
3382 ValueList OddScalars, EvenScalars;
3383 unsigned e = E->Scalars.size();
3384 SmallVector<Constant *, 8> Mask(e);
3385 for (unsigned i = 0; i < e; ++i) {
3386 if (isOdd(i)) {
3387 Mask[i] = Builder.getInt32(e + i);
3388 OddScalars.push_back(E->Scalars[i]);
3389 } else {
3390 Mask[i] = Builder.getInt32(i);
3391 EvenScalars.push_back(E->Scalars[i]);
3392 }
3393 }
3394
3395 Value *ShuffleMask = ConstantVector::get(Mask);
3396 propagateIRFlags(V0, EvenScalars);
3397 propagateIRFlags(V1, OddScalars);
3398
3399 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
3400 if (Instruction *I = dyn_cast<Instruction>(V))
3401 V = propagateMetadata(I, E->Scalars);
3402 if (NeedToShuffleReuses) {
3403 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3404 E->ReuseShuffleIndices, "shuffle");
3405 }
3406 E->VectorizedValue = V;
3407 ++NumVectorInstructions;
3408
3409 return V;
3410 }
3411 default:
3412 llvm_unreachable("unknown inst")::llvm::llvm_unreachable_internal("unknown inst", "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3412)
;
3413 }
3414 return nullptr;
3415}
3416
3417Value *BoUpSLP::vectorizeTree() {
3418 ExtraValueToDebugLocsMap ExternallyUsedValues;
3419 return vectorizeTree(ExternallyUsedValues);
3420}
3421
3422Value *
3423BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3424 // All blocks must be scheduled before any instructions are inserted.
3425 for (auto &BSIter : BlocksSchedules) {
3426 scheduleBlock(BSIter.second.get());
3427 }
3428
3429 Builder.SetInsertPoint(&F->getEntryBlock().front());
3430 auto *VectorRoot = vectorizeTree(&VectorizableTree[0]);
3431
3432 // If the vectorized tree can be rewritten in a smaller type, we truncate the
3433 // vectorized root. InstCombine will then rewrite the entire expression. We
3434 // sign extend the extracted values below.
3435 auto *ScalarRoot = VectorizableTree[0].Scalars[0];
3436 if (MinBWs.count(ScalarRoot)) {
3437 if (auto *I = dyn_cast<Instruction>(VectorRoot))
3438 Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
3439 auto BundleWidth = VectorizableTree[0].Scalars.size();
3440 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
3441 auto *VecTy = VectorType::get(MinTy, BundleWidth);
3442 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
3443 VectorizableTree[0].VectorizedValue = Trunc;
3444 }
3445
3446 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Extracting " << ExternalUses
.size() << " values .\n"; } } while (false)
;
3447
3448 // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
3449 // specified by ScalarType.
3450 auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
3451 if (!MinBWs.count(ScalarRoot))
3452 return Ex;
3453 if (MinBWs[ScalarRoot].second)
3454 return Builder.CreateSExt(Ex, ScalarType);
3455 return Builder.CreateZExt(Ex, ScalarType);
3456 };
3457
3458 // Extract all of the elements with the external uses.
3459 for (const auto &ExternalUse : ExternalUses) {
3460 Value *Scalar = ExternalUse.Scalar;
3461 llvm::User *User = ExternalUse.User;
3462
3463 // Skip users that we already RAUW. This happens when one instruction
3464 // has multiple uses of the same value.
3465 if (User && !is_contained(Scalar->users(), User))
3466 continue;
3467 TreeEntry *E = getTreeEntry(Scalar);
3468 assert(E && "Invalid scalar")(static_cast <bool> (E && "Invalid scalar") ? void
(0) : __assert_fail ("E && \"Invalid scalar\"", "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3468, __extension__ __PRETTY_FUNCTION__))
;
3469 assert(!E->NeedToGather && "Extracting from a gather list")(static_cast <bool> (!E->NeedToGather && "Extracting from a gather list"
) ? void (0) : __assert_fail ("!E->NeedToGather && \"Extracting from a gather list\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3469, __extension__ __PRETTY_FUNCTION__))
;
3470
3471 Value *Vec = E->VectorizedValue;
3472 assert(Vec && "Can't find vectorizable value")(static_cast <bool> (Vec && "Can't find vectorizable value"
) ? void (0) : __assert_fail ("Vec && \"Can't find vectorizable value\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3472, __extension__ __PRETTY_FUNCTION__))
;
3473
3474 Value *Lane = Builder.getInt32(ExternalUse.Lane);
3475 // If User == nullptr, the Scalar is used as extra arg. Generate
3476 // ExtractElement instruction and update the record for this scalar in
3477 // ExternallyUsedValues.
3478 if (!User) {
3479 assert(ExternallyUsedValues.count(Scalar) &&(static_cast <bool> (ExternallyUsedValues.count(Scalar)
&& "Scalar with nullptr as an external user must be registered in "
"ExternallyUsedValues map") ? void (0) : __assert_fail ("ExternallyUsedValues.count(Scalar) && \"Scalar with nullptr as an external user must be registered in \" \"ExternallyUsedValues map\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3481, __extension__ __PRETTY_FUNCTION__))
3480 "Scalar with nullptr as an external user must be registered in "(static_cast <bool> (ExternallyUsedValues.count(Scalar)
&& "Scalar with nullptr as an external user must be registered in "
"ExternallyUsedValues map") ? void (0) : __assert_fail ("ExternallyUsedValues.count(Scalar) && \"Scalar with nullptr as an external user must be registered in \" \"ExternallyUsedValues map\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3481, __extension__ __PRETTY_FUNCTION__))
3481 "ExternallyUsedValues map")(static_cast <bool> (ExternallyUsedValues.count(Scalar)
&& "Scalar with nullptr as an external user must be registered in "
"ExternallyUsedValues map") ? void (0) : __assert_fail ("ExternallyUsedValues.count(Scalar) && \"Scalar with nullptr as an external user must be registered in \" \"ExternallyUsedValues map\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3481, __extension__ __PRETTY_FUNCTION__))
;
3482 if (auto *VecI = dyn_cast<Instruction>(Vec)) {
3483 Builder.SetInsertPoint(VecI->getParent(),
3484 std::next(VecI->getIterator()));
3485 } else {
3486 Builder.SetInsertPoint(&F->getEntryBlock().front());
3487 }
3488 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3489 Ex = extend(ScalarRoot, Ex, Scalar->getType());
3490 CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
3491 auto &Locs = ExternallyUsedValues[Scalar];
3492 ExternallyUsedValues.insert({Ex, Locs});
3493 ExternallyUsedValues.erase(Scalar);
3494 continue;
3495 }
3496
3497 // Generate extracts for out-of-tree users.
3498 // Find the insertion point for the extractelement lane.
3499 if (auto *VecI = dyn_cast<Instruction>(Vec)) {
3500 if (PHINode *PH = dyn_cast<PHINode>(User)) {
3501 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
3502 if (PH->getIncomingValue(i) == Scalar) {
3503 TerminatorInst *IncomingTerminator =
3504 PH->getIncomingBlock(i)->getTerminator();
3505 if (isa<CatchSwitchInst>(IncomingTerminator)) {
3506 Builder.SetInsertPoint(VecI->getParent(),
3507 std::next(VecI->getIterator()));
3508 } else {
3509 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
3510 }
3511 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3512 Ex = extend(ScalarRoot, Ex, Scalar->getType());
3513 CSEBlocks.insert(PH->getIncomingBlock(i));
3514 PH->setOperand(i, Ex);
3515 }
3516 }
3517 } else {
3518 Builder.SetInsertPoint(cast<Instruction>(User));
3519 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3520 Ex = extend(ScalarRoot, Ex, Scalar->getType());
3521 CSEBlocks.insert(cast<Instruction>(User)->getParent());
3522 User->replaceUsesOfWith(Scalar, Ex);
3523 }
3524 } else {
3525 Builder.SetInsertPoint(&F->getEntryBlock().front());
3526 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3527 Ex = extend(ScalarRoot, Ex, Scalar->getType());
3528 CSEBlocks.insert(&F->getEntryBlock());
3529 User->replaceUsesOfWith(Scalar, Ex);
3530 }
3531
3532 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Replaced:" << *User <<
".\n"; } } while (false)
;
3533 }
3534
3535 // For each vectorized value:
3536 for (TreeEntry &EIdx : VectorizableTree) {
3537 TreeEntry *Entry = &EIdx;
3538
3539 // No need to handle users of gathered values.
3540 if (Entry->NeedToGather)
3541 continue;
3542
3543 assert(Entry->VectorizedValue && "Can't find vectorizable value")(static_cast <bool> (Entry->VectorizedValue &&
"Can't find vectorizable value") ? void (0) : __assert_fail (
"Entry->VectorizedValue && \"Can't find vectorizable value\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3543, __extension__ __PRETTY_FUNCTION__))
;
3544
3545 // For each lane:
3546 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3547 Value *Scalar = Entry->Scalars[Lane];
3548
3549 Type *Ty = Scalar->getType();
3550 if (!Ty->isVoidTy()) {
3551#ifndef NDEBUG
3552 for (User *U : Scalar->users()) {
3553 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: \tvalidating user:" <<
*U << ".\n"; } } while (false)
;
3554
3555 // It is legal to replace users in the ignorelist by undef.
3556 assert((getTreeEntry(U) || is_contained(UserIgnoreList, U)) &&(static_cast <bool> ((getTreeEntry(U) || is_contained(UserIgnoreList
, U)) && "Replacing out-of-tree value with undef") ? void
(0) : __assert_fail ("(getTreeEntry(U) || is_contained(UserIgnoreList, U)) && \"Replacing out-of-tree value with undef\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3557, __extension__ __PRETTY_FUNCTION__))
3557 "Replacing out-of-tree value with undef")(static_cast <bool> ((getTreeEntry(U) || is_contained(UserIgnoreList
, U)) && "Replacing out-of-tree value with undef") ? void
(0) : __assert_fail ("(getTreeEntry(U) || is_contained(UserIgnoreList, U)) && \"Replacing out-of-tree value with undef\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3557, __extension__ __PRETTY_FUNCTION__))
;
3558 }
3559#endif
3560 Value *Undef = UndefValue::get(Ty);
3561 Scalar->replaceAllUsesWith(Undef);
3562 }
3563 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: \tErasing scalar:" << *
Scalar << ".\n"; } } while (false)
;
3564 eraseInstruction(cast<Instruction>(Scalar));
3565 }
3566 }
3567
3568 Builder.ClearInsertionPoint();
3569
3570 return VectorizableTree[0].VectorizedValue;
3571}
3572
3573void BoUpSLP::optimizeGatherSequence() {
3574 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Optimizing " << GatherSeq
.size() << " gather sequences instructions.\n"; } } while
(false)
3575 << " gather sequences instructions.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Optimizing " << GatherSeq
.size() << " gather sequences instructions.\n"; } } while
(false)
;
3576 // LICM InsertElementInst sequences.
3577 for (Instruction *I : GatherSeq) {
3578 if (!isa<InsertElementInst>(I) && !isa<ShuffleVectorInst>(I))
3579 continue;
3580
3581 // Check if this block is inside a loop.
3582 Loop *L = LI->getLoopFor(I->getParent());
3583 if (!L)
3584 continue;
3585
3586 // Check if it has a preheader.
3587 BasicBlock *PreHeader = L->getLoopPreheader();
3588 if (!PreHeader)
3589 continue;
3590
3591 // If the vector or the element that we insert into it are
3592 // instructions that are defined in this basic block then we can't
3593 // hoist this instruction.
3594 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
3595 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
3596 if (Op0 && L->contains(Op0))
3597 continue;
3598 if (Op1 && L->contains(Op1))
3599 continue;
3600
3601 // We can hoist this instruction. Move it to the pre-header.
3602 I->moveBefore(PreHeader->getTerminator());
3603 }
3604
3605 // Make a list of all reachable blocks in our CSE queue.
3606 SmallVector<const DomTreeNode *, 8> CSEWorkList;
3607 CSEWorkList.reserve(CSEBlocks.size());
3608 for (BasicBlock *BB : CSEBlocks)
3609 if (DomTreeNode *N = DT->getNode(BB)) {
3610 assert(DT->isReachableFromEntry(N))(static_cast <bool> (DT->isReachableFromEntry(N)) ? void
(0) : __assert_fail ("DT->isReachableFromEntry(N)", "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3610, __extension__ __PRETTY_FUNCTION__))
;
3611 CSEWorkList.push_back(N);
3612 }
3613
3614 // Sort blocks by domination. This ensures we visit a block after all blocks
3615 // dominating it are visited.
3616 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
3617 [this](const DomTreeNode *A, const DomTreeNode *B) {
3618 return DT->properlyDominates(A, B);
3619 });
3620
3621 // Perform O(N^2) search over the gather sequences and merge identical
3622 // instructions. TODO: We can further optimize this scan if we split the
3623 // instructions into different buckets based on the insert lane.
3624 SmallVector<Instruction *, 16> Visited;
3625 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
3626 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&(static_cast <bool> ((I == CSEWorkList.begin() || !DT->
dominates(*I, *std::prev(I))) && "Worklist not sorted properly!"
) ? void (0) : __assert_fail ("(I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && \"Worklist not sorted properly!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3627, __extension__ __PRETTY_FUNCTION__))
3627 "Worklist not sorted properly!")(static_cast <bool> ((I == CSEWorkList.begin() || !DT->
dominates(*I, *std::prev(I))) && "Worklist not sorted properly!"
) ? void (0) : __assert_fail ("(I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && \"Worklist not sorted properly!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3627, __extension__ __PRETTY_FUNCTION__))
;
3628 BasicBlock *BB = (*I)->getBlock();
3629 // For all instructions in blocks containing gather sequences:
3630 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
3631 Instruction *In = &*it++;
3632 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
3633 continue;
3634
3635 // Check if we can replace this instruction with any of the
3636 // visited instructions.
3637 for (Instruction *v : Visited) {
3638 if (In->isIdenticalTo(v) &&
3639 DT->dominates(v->getParent(), In->getParent())) {
3640 In->replaceAllUsesWith(v);
3641 eraseInstruction(In);
3642 In = nullptr;
3643 break;
3644 }
3645 }
3646 if (In) {
3647 assert(!is_contained(Visited, In))(static_cast <bool> (!is_contained(Visited, In)) ? void
(0) : __assert_fail ("!is_contained(Visited, In)", "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3647, __extension__ __PRETTY_FUNCTION__))
;
3648 Visited.push_back(In);
3649 }
3650 }
3651 }
3652 CSEBlocks.clear();
3653 GatherSeq.clear();
3654}
3655
3656// Groups the instructions to a bundle (which is then a single scheduling entity)
3657// and schedules instructions until the bundle gets ready.
3658bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
3659 BoUpSLP *SLP, Value *OpValue) {
3660 if (isa<PHINode>(OpValue))
3661 return true;
3662
3663 // Initialize the instruction bundle.
3664 Instruction *OldScheduleEnd = ScheduleEnd;
3665 ScheduleData *PrevInBundle = nullptr;
3666 ScheduleData *Bundle = nullptr;
3667 bool ReSchedule = false;
3668 DEBUG(dbgs() << "SLP: bundle: " << *OpValue << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: bundle: " << *OpValue
<< "\n"; } } while (false)
;
3669
3670 // Make sure that the scheduling region contains all
3671 // instructions of the bundle.
3672 for (Value *V : VL) {
3673 if (!extendSchedulingRegion(V, OpValue))
3674 return false;
3675 }
3676
3677 for (Value *V : VL) {
3678 ScheduleData *BundleMember = getScheduleData(V);
3679 assert(BundleMember &&(static_cast <bool> (BundleMember && "no ScheduleData for bundle member (maybe not in same basic block)"
) ? void (0) : __assert_fail ("BundleMember && \"no ScheduleData for bundle member (maybe not in same basic block)\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3680, __extension__ __PRETTY_FUNCTION__))
3680 "no ScheduleData for bundle member (maybe not in same basic block)")(static_cast <bool> (BundleMember && "no ScheduleData for bundle member (maybe not in same basic block)"
) ? void (0) : __assert_fail ("BundleMember && \"no ScheduleData for bundle member (maybe not in same basic block)\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3680, __extension__ __PRETTY_FUNCTION__))
;
3681 if (BundleMember->IsScheduled) {
3682 // A bundle member was scheduled as single instruction before and now
3683 // needs to be scheduled as part of the bundle. We just get rid of the
3684 // existing schedule.
3685 DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMemberdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: reset schedule because " <<
*BundleMember << " was already scheduled\n"; } } while
(false)
3686 << " was already scheduled\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: reset schedule because " <<
*BundleMember << " was already scheduled\n"; } } while
(false)
;
3687 ReSchedule = true;
3688 }
3689 assert(BundleMember->isSchedulingEntity() &&(static_cast <bool> (BundleMember->isSchedulingEntity
() && "bundle member already part of other bundle") ?
void (0) : __assert_fail ("BundleMember->isSchedulingEntity() && \"bundle member already part of other bundle\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3690, __extension__ __PRETTY_FUNCTION__))
3690 "bundle member already part of other bundle")(static_cast <bool> (BundleMember->isSchedulingEntity
() && "bundle member already part of other bundle") ?
void (0) : __assert_fail ("BundleMember->isSchedulingEntity() && \"bundle member already part of other bundle\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3690, __extension__ __PRETTY_FUNCTION__))
;
3691 if (PrevInBundle) {
3692 PrevInBundle->NextInBundle = BundleMember;
3693 } else {
3694 Bundle = BundleMember;
3695 }
3696 BundleMember->UnscheduledDepsInBundle = 0;
3697 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
3698
3699 // Group the instructions to a bundle.
3700 BundleMember->FirstInBundle = Bundle;
3701 PrevInBundle = BundleMember;
3702 }
3703 if (ScheduleEnd != OldScheduleEnd) {
3704 // The scheduling region got new instructions at the lower end (or it is a
3705 // new region for the first bundle). This makes it necessary to
3706 // recalculate all dependencies.
3707 // It is seldom that this needs to be done a second time after adding the
3708 // initial bundle to the region.
3709 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3710 doForAllOpcodes(I, [](ScheduleData *SD) {
3711 SD->clearDependencies();
3712 });
3713 }
3714 ReSchedule = true;
3715 }
3716 if (ReSchedule) {
3717 resetSchedule();
3718 initialFillReadyList(ReadyInsts);
3719 }
3720
3721 DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: try schedule bundle " <<
*Bundle << " in block " << BB->getName() <<
"\n"; } } while (false)
3722 << BB->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: try schedule bundle " <<
*Bundle << " in block " << BB->getName() <<
"\n"; } } while (false)
;
3723
3724 calculateDependencies(Bundle, true, SLP);
3725
3726 // Now try to schedule the new bundle. As soon as the bundle is "ready" it
3727 // means that there are no cyclic dependencies and we can schedule it.
3728 // Note that's important that we don't "schedule" the bundle yet (see
3729 // cancelScheduling).
3730 while (!Bundle->isReady() && !ReadyInsts.empty()) {
3731
3732 ScheduleData *pickedSD = ReadyInsts.back();
3733 ReadyInsts.pop_back();
3734
3735 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
3736 schedule(pickedSD, ReadyInsts);
3737 }
3738 }
3739 if (!Bundle->isReady()) {
3740 cancelScheduling(VL, OpValue);
3741 return false;
3742 }
3743 return true;
3744}
3745
3746void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
3747 Value *OpValue) {
3748 if (isa<PHINode>(OpValue))
3749 return;
3750
3751 ScheduleData *Bundle = getScheduleData(OpValue);
3752 DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: cancel scheduling of " <<
*Bundle << "\n"; } } while (false)
;
3753 assert(!Bundle->IsScheduled &&(static_cast <bool> (!Bundle->IsScheduled &&
"Can't cancel bundle which is already scheduled") ? void (0)
: __assert_fail ("!Bundle->IsScheduled && \"Can't cancel bundle which is already scheduled\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3754, __extension__ __PRETTY_FUNCTION__))
3754 "Can't cancel bundle which is already scheduled")(static_cast <bool> (!Bundle->IsScheduled &&
"Can't cancel bundle which is already scheduled") ? void (0)
: __assert_fail ("!Bundle->IsScheduled && \"Can't cancel bundle which is already scheduled\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3754, __extension__ __PRETTY_FUNCTION__))
;
3755 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&(static_cast <bool> (Bundle->isSchedulingEntity() &&
Bundle->isPartOfBundle() && "tried to unbundle something which is not a bundle"
) ? void (0) : __assert_fail ("Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() && \"tried to unbundle something which is not a bundle\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3756, __extension__ __PRETTY_FUNCTION__))
3756 "tried to unbundle something which is not a bundle")(static_cast <bool> (Bundle->isSchedulingEntity() &&
Bundle->isPartOfBundle() && "tried to unbundle something which is not a bundle"
) ? void (0) : __assert_fail ("Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() && \"tried to unbundle something which is not a bundle\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3756, __extension__ __PRETTY_FUNCTION__))
;
3757
3758 // Un-bundle: make single instructions out of the bundle.
3759 ScheduleData *BundleMember = Bundle;
3760 while (BundleMember) {
3761 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links")(static_cast <bool> (BundleMember->FirstInBundle == Bundle
&& "corrupt bundle links") ? void (0) : __assert_fail
("BundleMember->FirstInBundle == Bundle && \"corrupt bundle links\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3761, __extension__ __PRETTY_FUNCTION__))
;
3762 BundleMember->FirstInBundle = BundleMember;
3763 ScheduleData *Next = BundleMember->NextInBundle;
3764 BundleMember->NextInBundle = nullptr;
3765 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
3766 if (BundleMember->UnscheduledDepsInBundle == 0) {
3767 ReadyInsts.insert(BundleMember);
3768 }
3769 BundleMember = Next;
3770 }
3771}
3772
3773BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
3774 // Allocate a new ScheduleData for the instruction.
3775 if (ChunkPos >= ChunkSize) {
3776 ScheduleDataChunks.push_back(llvm::make_unique<ScheduleData[]>(ChunkSize));
3777 ChunkPos = 0;
3778 }
3779 return &(ScheduleDataChunks.back()[ChunkPos++]);
3780}
3781
3782bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
3783 Value *OpValue) {
3784 if (getScheduleData(V, isOneOf(OpValue, V)))
3785 return true;
3786 Instruction *I = dyn_cast<Instruction>(V);
3787 assert(I && "bundle member must be an instruction")(static_cast <bool> (I && "bundle member must be an instruction"
) ? void (0) : __assert_fail ("I && \"bundle member must be an instruction\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3787, __extension__ __PRETTY_FUNCTION__))
;
3788 assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled")(static_cast <bool> (!isa<PHINode>(I) && "phi nodes don't need to be scheduled"
) ? void (0) : __assert_fail ("!isa<PHINode>(I) && \"phi nodes don't need to be scheduled\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3788, __extension__ __PRETTY_FUNCTION__))
;
3789 auto &&CheckSheduleForI = [this, OpValue](Instruction *I) -> bool {
3790 ScheduleData *ISD = getScheduleData(I);
3791 if (!ISD)
3792 return false;
3793 assert(isInSchedulingRegion(ISD) &&(static_cast <bool> (isInSchedulingRegion(ISD) &&
"ScheduleData not in scheduling region") ? void (0) : __assert_fail
("isInSchedulingRegion(ISD) && \"ScheduleData not in scheduling region\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3794, __extension__ __PRETTY_FUNCTION__))
3794 "ScheduleData not in scheduling region")(static_cast <bool> (isInSchedulingRegion(ISD) &&
"ScheduleData not in scheduling region") ? void (0) : __assert_fail
("isInSchedulingRegion(ISD) && \"ScheduleData not in scheduling region\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3794, __extension__ __PRETTY_FUNCTION__))
;
3795 ScheduleData *SD = allocateScheduleDataChunks();
3796 SD->Inst = I;
3797 SD->init(SchedulingRegionID, OpValue);
3798 ExtraScheduleDataMap[I][OpValue] = SD;
3799 return true;
3800 };
3801 if (CheckSheduleForI(I))
3802 return true;
3803 if (!ScheduleStart) {
3804 // It's the first instruction in the new region.
3805 initScheduleData(I, I->getNextNode(), nullptr, nullptr);
3806 ScheduleStart = I;
3807 ScheduleEnd = I->getNextNode();
3808 if (isOneOf(OpValue, I) != I)
3809 CheckSheduleForI(I);
3810 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?")(static_cast <bool> (ScheduleEnd && "tried to vectorize a TerminatorInst?"
) ? void (0) : __assert_fail ("ScheduleEnd && \"tried to vectorize a TerminatorInst?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3810, __extension__ __PRETTY_FUNCTION__))
;
3811 DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: initialize schedule region to "
<< *I << "\n"; } } while (false)
;
3812 return true;
3813 }
3814 // Search up and down at the same time, because we don't know if the new
3815 // instruction is above or below the existing scheduling region.
3816 BasicBlock::reverse_iterator UpIter =
3817 ++ScheduleStart->getIterator().getReverse();
3818 BasicBlock::reverse_iterator UpperEnd = BB->rend();
3819 BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
3820 BasicBlock::iterator LowerEnd = BB->end();
3821 while (true) {
3822 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
3823 DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: exceeded schedule region size limit\n"
; } } while (false)
;
3824 return false;
3825 }
3826
3827 if (UpIter != UpperEnd) {
3828 if (&*UpIter == I) {
3829 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
3830 ScheduleStart = I;
3831 if (isOneOf(OpValue, I) != I)
3832 CheckSheduleForI(I);
3833 DEBUG(dbgs() << "SLP: extend schedule region start to " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: extend schedule region start to "
<< *I << "\n"; } } while (false)
;
3834 return true;
3835 }
3836 UpIter++;
3837 }
3838 if (DownIter != LowerEnd) {
3839 if (&*DownIter == I) {
3840 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
3841 nullptr);
3842 ScheduleEnd = I->getNextNode();
3843 if (isOneOf(OpValue, I) != I)
3844 CheckSheduleForI(I);
3845 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?")(static_cast <bool> (ScheduleEnd && "tried to vectorize a TerminatorInst?"
) ? void (0) : __assert_fail ("ScheduleEnd && \"tried to vectorize a TerminatorInst?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3845, __extension__ __PRETTY_FUNCTION__))
;
3846 DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: extend schedule region end to "
<< *I << "\n"; } } while (false)
;
3847 return true;
3848 }
3849 DownIter++;
3850 }
3851 assert((UpIter != UpperEnd || DownIter != LowerEnd) &&(static_cast <bool> ((UpIter != UpperEnd || DownIter !=
LowerEnd) && "instruction not found in block") ? void
(0) : __assert_fail ("(UpIter != UpperEnd || DownIter != LowerEnd) && \"instruction not found in block\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3852, __extension__ __PRETTY_FUNCTION__))
3852 "instruction not found in block")(static_cast <bool> ((UpIter != UpperEnd || DownIter !=
LowerEnd) && "instruction not found in block") ? void
(0) : __assert_fail ("(UpIter != UpperEnd || DownIter != LowerEnd) && \"instruction not found in block\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3852, __extension__ __PRETTY_FUNCTION__))
;
3853 }
3854 return true;
3855}
3856
3857void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
3858 Instruction *ToI,
3859 ScheduleData *PrevLoadStore,
3860 ScheduleData *NextLoadStore) {
3861 ScheduleData *CurrentLoadStore = PrevLoadStore;
3862 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
3863 ScheduleData *SD = ScheduleDataMap[I];
3864 if (!SD) {
3865 SD = allocateScheduleDataChunks();
3866 ScheduleDataMap[I] = SD;
3867 SD->Inst = I;
3868 }
3869 assert(!isInSchedulingRegion(SD) &&(static_cast <bool> (!isInSchedulingRegion(SD) &&
"new ScheduleData already in scheduling region") ? void (0) :
__assert_fail ("!isInSchedulingRegion(SD) && \"new ScheduleData already in scheduling region\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3870, __extension__ __PRETTY_FUNCTION__))
3870 "new ScheduleData already in scheduling region")(static_cast <bool> (!isInSchedulingRegion(SD) &&
"new ScheduleData already in scheduling region") ? void (0) :
__assert_fail ("!isInSchedulingRegion(SD) && \"new ScheduleData already in scheduling region\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3870, __extension__ __PRETTY_FUNCTION__))
;
3871 SD->init(SchedulingRegionID, I);
3872
3873 if (I->mayReadOrWriteMemory() &&
3874 (!isa<IntrinsicInst>(I) ||
3875 cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect)) {
3876 // Update the linked list of memory accessing instructions.
3877 if (CurrentLoadStore) {
3878 CurrentLoadStore->NextLoadStore = SD;
3879 } else {
3880 FirstLoadStoreInRegion = SD;
3881 }
3882 CurrentLoadStore = SD;
3883 }
3884 }
3885 if (NextLoadStore) {
3886 if (CurrentLoadStore)
3887 CurrentLoadStore->NextLoadStore = NextLoadStore;
3888 } else {
3889 LastLoadStoreInRegion = CurrentLoadStore;
3890 }
3891}
3892
3893void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
3894 bool InsertInReadyList,
3895 BoUpSLP *SLP) {
3896 assert(SD->isSchedulingEntity())(static_cast <bool> (SD->isSchedulingEntity()) ? void
(0) : __assert_fail ("SD->isSchedulingEntity()", "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3896, __extension__ __PRETTY_FUNCTION__))
;
3897
3898 SmallVector<ScheduleData *, 10> WorkList;
3899 WorkList.push_back(SD);
3900
3901 while (!WorkList.empty()) {
3902 ScheduleData *SD = WorkList.back();
3903 WorkList.pop_back();
3904
3905 ScheduleData *BundleMember = SD;
3906 while (BundleMember) {
3907 assert(isInSchedulingRegion(BundleMember))(static_cast <bool> (isInSchedulingRegion(BundleMember)
) ? void (0) : __assert_fail ("isInSchedulingRegion(BundleMember)"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3907, __extension__ __PRETTY_FUNCTION__))
;
3908 if (!BundleMember->hasValidDependencies()) {
3909
3910 DEBUG(dbgs() << "SLP: update deps of " << *BundleMember << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: update deps of " <<
*BundleMember << "\n"; } } while (false)
;
3911 BundleMember->Dependencies = 0;
3912 BundleMember->resetUnscheduledDeps();
3913
3914 // Handle def-use chain dependencies.
3915 if (BundleMember->OpValue != BundleMember->Inst) {
3916 ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
3917 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
3918 BundleMember->Dependencies++;
3919 ScheduleData *DestBundle = UseSD->FirstInBundle;
3920 if (!DestBundle->IsScheduled)
3921 BundleMember->incrementUnscheduledDeps(1);
3922 if (!DestBundle->hasValidDependencies())
3923 WorkList.push_back(DestBundle);
3924 }
3925 } else {
3926 for (User *U : BundleMember->Inst->users()) {
3927 if (isa<Instruction>(U)) {
3928 ScheduleData *UseSD = getScheduleData(U);
3929 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
3930 BundleMember->Dependencies++;
3931 ScheduleData *DestBundle = UseSD->FirstInBundle;
3932 if (!DestBundle->IsScheduled)
3933 BundleMember->incrementUnscheduledDeps(1);
3934 if (!DestBundle->hasValidDependencies())
3935 WorkList.push_back(DestBundle);
3936 }
3937 } else {
3938 // I'm not sure if this can ever happen. But we need to be safe.
3939 // This lets the instruction/bundle never be scheduled and
3940 // eventually disable vectorization.
3941 BundleMember->Dependencies++;
3942 BundleMember->incrementUnscheduledDeps(1);
3943 }
3944 }
3945 }
3946
3947 // Handle the memory dependencies.
3948 ScheduleData *DepDest = BundleMember->NextLoadStore;
3949 if (DepDest) {
3950 Instruction *SrcInst = BundleMember->Inst;
3951 MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
3952 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
3953 unsigned numAliased = 0;
3954 unsigned DistToSrc = 1;
3955
3956 while (DepDest) {
3957 assert(isInSchedulingRegion(DepDest))(static_cast <bool> (isInSchedulingRegion(DepDest)) ? void
(0) : __assert_fail ("isInSchedulingRegion(DepDest)", "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 3957, __extension__ __PRETTY_FUNCTION__))
;
3958
3959 // We have two limits to reduce the complexity:
3960 // 1) AliasedCheckLimit: It's a small limit to reduce calls to
3961 // SLP->isAliased (which is the expensive part in this loop).
3962 // 2) MaxMemDepDistance: It's for very large blocks and it aborts
3963 // the whole loop (even if the loop is fast, it's quadratic).
3964 // It's important for the loop break condition (see below) to
3965 // check this limit even between two read-only instructions.
3966 if (DistToSrc >= MaxMemDepDistance ||
3967 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
3968 (numAliased >= AliasedCheckLimit ||
3969 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
3970
3971 // We increment the counter only if the locations are aliased
3972 // (instead of counting all alias checks). This gives a better
3973 // balance between reduced runtime and accurate dependencies.
3974 numAliased++;
3975
3976 DepDest->MemoryDependencies.push_back(BundleMember);
3977 BundleMember->Dependencies++;
3978 ScheduleData *DestBundle = DepDest->FirstInBundle;
3979 if (!DestBundle->IsScheduled) {
3980 BundleMember->incrementUnscheduledDeps(1);
3981 }
3982 if (!DestBundle->hasValidDependencies()) {
3983 WorkList.push_back(DestBundle);
3984 }
3985 }
3986 DepDest = DepDest->NextLoadStore;
3987
3988 // Example, explaining the loop break condition: Let's assume our
3989 // starting instruction is i0 and MaxMemDepDistance = 3.
3990 //
3991 // +--------v--v--v
3992 // i0,i1,i2,i3,i4,i5,i6,i7,i8
3993 // +--------^--^--^
3994 //
3995 // MaxMemDepDistance let us stop alias-checking at i3 and we add
3996 // dependencies from i0 to i3,i4,.. (even if they are not aliased).
3997 // Previously we already added dependencies from i3 to i6,i7,i8
3998 // (because of MaxMemDepDistance). As we added a dependency from
3999 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
4000 // and we can abort this loop at i6.
4001 if (DistToSrc >= 2 * MaxMemDepDistance)
4002 break;
4003 DistToSrc++;
4004 }
4005 }
4006 }
4007 BundleMember = BundleMember->NextInBundle;
4008 }
4009 if (InsertInReadyList && SD->isReady()) {
4010 ReadyInsts.push_back(SD);
4011 DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: gets ready on update: " <<
*SD->Inst << "\n"; } } while (false)
;
4012 }
4013 }
4014}
4015
4016void BoUpSLP::BlockScheduling::resetSchedule() {
4017 assert(ScheduleStart &&(static_cast <bool> (ScheduleStart && "tried to reset schedule on block which has not been scheduled"
) ? void (0) : __assert_fail ("ScheduleStart && \"tried to reset schedule on block which has not been scheduled\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 4018, __extension__ __PRETTY_FUNCTION__))
4018 "tried to reset schedule on block which has not been scheduled")(static_cast <bool> (ScheduleStart && "tried to reset schedule on block which has not been scheduled"
) ? void (0) : __assert_fail ("ScheduleStart && \"tried to reset schedule on block which has not been scheduled\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 4018, __extension__ __PRETTY_FUNCTION__))
;
4019 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
4020 doForAllOpcodes(I, [&](ScheduleData *SD) {
4021 assert(isInSchedulingRegion(SD) &&(static_cast <bool> (isInSchedulingRegion(SD) &&
"ScheduleData not in scheduling region") ? void (0) : __assert_fail
("isInSchedulingRegion(SD) && \"ScheduleData not in scheduling region\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 4022, __extension__ __PRETTY_FUNCTION__))
4022 "ScheduleData not in scheduling region")(static_cast <bool> (isInSchedulingRegion(SD) &&
"ScheduleData not in scheduling region") ? void (0) : __assert_fail
("isInSchedulingRegion(SD) && \"ScheduleData not in scheduling region\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 4022, __extension__ __PRETTY_FUNCTION__))
;
4023 SD->IsScheduled = false;
4024 SD->resetUnscheduledDeps();
4025 });
4026 }
4027 ReadyInsts.clear();
4028}
4029
4030void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
4031 if (!BS->ScheduleStart)
4032 return;
4033
4034 DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: schedule block " << BS
->BB->getName() << "\n"; } } while (false)
;
4035
4036 BS->resetSchedule();
4037
4038 // For the real scheduling we use a more sophisticated ready-list: it is
4039 // sorted by the original instruction location. This lets the final schedule
4040 // be as close as possible to the original instruction order.
4041 struct ScheduleDataCompare {
4042 bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
4043 return SD2->SchedulingPriority < SD1->SchedulingPriority;
4044 }
4045 };
4046 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
4047
4048 // Ensure that all dependency data is updated and fill the ready-list with
4049 // initial instructions.
4050 int Idx = 0;
4051 int NumToSchedule = 0;
4052 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
4053 I = I->getNextNode()) {
4054 BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
4055 assert(SD->isPartOfBundle() ==(static_cast <bool> (SD->isPartOfBundle() == (getTreeEntry
(SD->Inst) != nullptr) && "scheduler and vectorizer bundle mismatch"
) ? void (0) : __assert_fail ("SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr) && \"scheduler and vectorizer bundle mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 4057, __extension__ __PRETTY_FUNCTION__))
4056 (getTreeEntry(SD->Inst) != nullptr) &&(static_cast <bool> (SD->isPartOfBundle() == (getTreeEntry
(SD->Inst) != nullptr) && "scheduler and vectorizer bundle mismatch"
) ? void (0) : __assert_fail ("SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr) && \"scheduler and vectorizer bundle mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 4057, __extension__ __PRETTY_FUNCTION__))
4057 "scheduler and vectorizer bundle mismatch")(static_cast <bool> (SD->isPartOfBundle() == (getTreeEntry
(SD->Inst) != nullptr) && "scheduler and vectorizer bundle mismatch"
) ? void (0) : __assert_fail ("SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr) && \"scheduler and vectorizer bundle mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 4057, __extension__ __PRETTY_FUNCTION__))
;
4058 SD->FirstInBundle->SchedulingPriority = Idx++;
4059 if (SD->isSchedulingEntity()) {
4060 BS->calculateDependencies(SD, false, this);
4061 NumToSchedule++;
4062 }
4063 });
4064 }
4065 BS->initialFillReadyList(ReadyInsts);
4066
4067 Instruction *LastScheduledInst = BS->ScheduleEnd;
4068
4069 // Do the "real" scheduling.
4070 while (!ReadyInsts.empty()) {
4071 ScheduleData *picked = *ReadyInsts.begin();
4072 ReadyInsts.erase(ReadyInsts.begin());
4073
4074 // Move the scheduled instruction(s) to their dedicated places, if not
4075 // there yet.
4076 ScheduleData *BundleMember = picked;
4077 while (BundleMember) {
4078 Instruction *pickedInst = BundleMember->Inst;
4079 if (LastScheduledInst->getNextNode() != pickedInst) {
4080 BS->BB->getInstList().remove(pickedInst);
4081 BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
4082 pickedInst);
4083 }
4084 LastScheduledInst = pickedInst;
4085 BundleMember = BundleMember->NextInBundle;
4086 }
4087
4088 BS->schedule(picked, ReadyInsts);
4089 NumToSchedule--;
4090 }
4091 assert(NumToSchedule == 0 && "could not schedule all instructions")(static_cast <bool> (NumToSchedule == 0 && "could not schedule all instructions"
) ? void (0) : __assert_fail ("NumToSchedule == 0 && \"could not schedule all instructions\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 4091, __extension__ __PRETTY_FUNCTION__))
;
4092
4093 // Avoid duplicate scheduling of the block.
4094 BS->ScheduleStart = nullptr;
4095}
4096
4097unsigned BoUpSLP::getVectorElementSize(Value *V) {
4098 // If V is a store, just return the width of the stored value without
4099 // traversing the expression tree. This is the common case.
4100 if (auto *Store = dyn_cast<StoreInst>(V))
4101 return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
4102
4103 // If V is not a store, we can traverse the expression tree to find loads
4104 // that feed it. The type of the loaded value may indicate a more suitable
4105 // width than V's type. We want to base the vector element size on the width
4106 // of memory operations where possible.
4107 SmallVector<Instruction *, 16> Worklist;
4108 SmallPtrSet<Instruction *, 16> Visited;
4109 if (auto *I = dyn_cast<Instruction>(V))
4110 Worklist.push_back(I);
4111
4112 // Traverse the expression tree in bottom-up order looking for loads. If we
4113 // encounter an instruciton we don't yet handle, we give up.
4114 auto MaxWidth = 0u;
4115 auto FoundUnknownInst = false;
4116 while (!Worklist.empty() && !FoundUnknownInst) {
4117 auto *I = Worklist.pop_back_val();
4118 Visited.insert(I);
4119
4120 // We should only be looking at scalar instructions here. If the current
4121 // instruction has a vector type, give up.
4122 auto *Ty = I->getType();
4123 if (isa<VectorType>(Ty))
4124 FoundUnknownInst = true;
4125
4126 // If the current instruction is a load, update MaxWidth to reflect the
4127 // width of the loaded value.
4128 else if (isa<LoadInst>(I))
4129 MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
4130
4131 // Otherwise, we need to visit the operands of the instruction. We only
4132 // handle the interesting cases from buildTree here. If an operand is an
4133 // instruction we haven't yet visited, we add it to the worklist.
4134 else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
4135 isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
4136 for (Use &U : I->operands())
4137 if (auto *J = dyn_cast<Instruction>(U.get()))
4138 if (!Visited.count(J))
4139 Worklist.push_back(J);
4140 }
4141
4142 // If we don't yet handle the instruction, give up.
4143 else
4144 FoundUnknownInst = true;
4145 }
4146
4147 // If we didn't encounter a memory access in the expression tree, or if we
4148 // gave up for some reason, just return the width of V.
4149 if (!MaxWidth || FoundUnknownInst)
4150 return DL->getTypeSizeInBits(V->getType());
4151
4152 // Otherwise, return the maximum width we found.
4153 return MaxWidth;
4154}
4155
4156// Determine if a value V in a vectorizable expression Expr can be demoted to a
4157// smaller type with a truncation. We collect the values that will be demoted
4158// in ToDemote and additional roots that require investigating in Roots.
4159static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
4160 SmallVectorImpl<Value *> &ToDemote,
4161 SmallVectorImpl<Value *> &Roots) {
4162 // We can always demote constants.
4163 if (isa<Constant>(V)) {
4164 ToDemote.push_back(V);
4165 return true;
4166 }
4167
4168 // If the value is not an instruction in the expression with only one use, it
4169 // cannot be demoted.
4170 auto *I = dyn_cast<Instruction>(V);
4171 if (!I || !I->hasOneUse() || !Expr.count(I))
4172 return false;
4173
4174 switch (I->getOpcode()) {
4175
4176 // We can always demote truncations and extensions. Since truncations can
4177 // seed additional demotion, we save the truncated value.
4178 case Instruction::Trunc:
4179 Roots.push_back(I->getOperand(0));
4180 break;
4181 case Instruction::ZExt:
4182 case Instruction::SExt:
4183 break;
4184
4185 // We can demote certain binary operations if we can demote both of their
4186 // operands.
4187 case Instruction::Add:
4188 case Instruction::Sub:
4189 case Instruction::Mul:
4190 case Instruction::And:
4191 case Instruction::Or:
4192 case Instruction::Xor:
4193 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
4194 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
4195 return false;
4196 break;
4197
4198 // We can demote selects if we can demote their true and false values.
4199 case Instruction::Select: {
4200 SelectInst *SI = cast<SelectInst>(I);
4201 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
4202 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
4203 return false;
4204 break;
4205 }
4206
4207 // We can demote phis if we can demote all their incoming operands. Note that
4208 // we don't need to worry about cycles since we ensure single use above.
4209 case Instruction::PHI: {
4210 PHINode *PN = cast<PHINode>(I);
4211 for (Value *IncValue : PN->incoming_values())
4212 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
4213 return false;
4214 break;
4215 }
4216
4217 // Otherwise, conservatively give up.
4218 default:
4219 return false;
4220 }
4221
4222 // Record the value that we can demote.
4223 ToDemote.push_back(V);
4224 return true;
4225}
4226
4227void BoUpSLP::computeMinimumValueSizes() {
4228 // If there are no external uses, the expression tree must be rooted by a
4229 // store. We can't demote in-memory values, so there is nothing to do here.
4230 if (ExternalUses.empty())
4231 return;
4232
4233 // We only attempt to truncate integer expressions.
4234 auto &TreeRoot = VectorizableTree[0].Scalars;
4235 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
4236 if (!TreeRootIT)
4237 return;
4238
4239 // If the expression is not rooted by a store, these roots should have
4240 // external uses. We will rely on InstCombine to rewrite the expression in
4241 // the narrower type. However, InstCombine only rewrites single-use values.
4242 // This means that if a tree entry other than a root is used externally, it
4243 // must have multiple uses and InstCombine will not rewrite it. The code
4244 // below ensures that only the roots are used externally.
4245 SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
4246 for (auto &EU : ExternalUses)
4247 if (!Expr.erase(EU.Scalar))
4248 return;
4249 if (!Expr.empty())
4250 return;
4251
4252 // Collect the scalar values of the vectorizable expression. We will use this
4253 // context to determine which values can be demoted. If we see a truncation,
4254 // we mark it as seeding another demotion.
4255 for (auto &Entry : VectorizableTree)
4256 Expr.insert(Entry.Scalars.begin(), Entry.Scalars.end());
4257
4258 // Ensure the roots of the vectorizable tree don't form a cycle. They must
4259 // have a single external user that is not in the vectorizable tree.
4260 for (auto *Root : TreeRoot)
4261 if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
4262 return;
4263
4264 // Conservatively determine if we can actually truncate the roots of the
4265 // expression. Collect the values that can be demoted in ToDemote and
4266 // additional roots that require investigating in Roots.
4267 SmallVector<Value *, 32> ToDemote;
4268 SmallVector<Value *, 4> Roots;
4269 for (auto *Root : TreeRoot) {
4270 // Do not include top zext/sext/trunc operations to those to be demoted, it
4271 // produces noise cast<vect>, trunc <vect>, exctract <vect>, cast <extract>
4272 // sequence.
4273 if (isa<Constant>(Root))
4274 continue;
4275 auto *I = dyn_cast<Instruction>(Root);
4276 if (!I || !I->hasOneUse() || !Expr.count(I))
4277 return;
4278 if (isa<ZExtInst>(I) || isa<SExtInst>(I))
4279 continue;
4280 if (auto *TI = dyn_cast<TruncInst>(I)) {
4281 Roots.push_back(TI->getOperand(0));
4282 continue;
4283 }
4284 if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
4285 return;
4286 }
4287
4288 // The maximum bit width required to represent all the values that can be
4289 // demoted without loss of precision. It would be safe to truncate the roots
4290 // of the expression to this width.
4291 auto MaxBitWidth = 8u;
4292
4293 // We first check if all the bits of the roots are demanded. If they're not,
4294 // we can truncate the roots to this narrower type.
4295 for (auto *Root : TreeRoot) {
4296 auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
4297 MaxBitWidth = std::max<unsigned>(
4298 Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
4299 }
4300
4301 // True if the roots can be zero-extended back to their original type, rather
4302 // than sign-extended. We know that if the leading bits are not demanded, we
4303 // can safely zero-extend. So we initialize IsKnownPositive to True.
4304 bool IsKnownPositive = true;
4305
4306 // If all the bits of the roots are demanded, we can try a little harder to
4307 // compute a narrower type. This can happen, for example, if the roots are
4308 // getelementptr indices. InstCombine promotes these indices to the pointer
4309 // width. Thus, all their bits are technically demanded even though the
4310 // address computation might be vectorized in a smaller type.
4311 //
4312 // We start by looking at each entry that can be demoted. We compute the
4313 // maximum bit width required to store the scalar by using ValueTracking to
4314 // compute the number of high-order bits we can truncate.
4315 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType())) {
4316 MaxBitWidth = 8u;
4317
4318 // Determine if the sign bit of all the roots is known to be zero. If not,
4319 // IsKnownPositive is set to False.
4320 IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
4321 KnownBits Known = computeKnownBits(R, *DL);
4322 return Known.isNonNegative();
4323 });
4324
4325 // Determine the maximum number of bits required to store the scalar
4326 // values.
4327 for (auto *Scalar : ToDemote) {
4328 auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
4329 auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
4330 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
4331 }
4332
4333 // If we can't prove that the sign bit is zero, we must add one to the
4334 // maximum bit width to account for the unknown sign bit. This preserves
4335 // the existing sign bit so we can safely sign-extend the root back to the
4336 // original type. Otherwise, if we know the sign bit is zero, we will
4337 // zero-extend the root instead.
4338 //
4339 // FIXME: This is somewhat suboptimal, as there will be cases where adding
4340 // one to the maximum bit width will yield a larger-than-necessary
4341 // type. In general, we need to add an extra bit only if we can't
4342 // prove that the upper bit of the original type is equal to the
4343 // upper bit of the proposed smaller type. If these two bits are the
4344 // same (either zero or one) we know that sign-extending from the
4345 // smaller type will result in the same value. Here, since we can't
4346 // yet prove this, we are just making the proposed smaller type
4347 // larger to ensure correctness.
4348 if (!IsKnownPositive)
4349 ++MaxBitWidth;
4350 }
4351
4352 // Round MaxBitWidth up to the next power-of-two.
4353 if (!isPowerOf2_64(MaxBitWidth))
4354 MaxBitWidth = NextPowerOf2(MaxBitWidth);
4355
4356 // If the maximum bit width we compute is less than the with of the roots'
4357 // type, we can proceed with the narrowing. Otherwise, do nothing.
4358 if (MaxBitWidth >= TreeRootIT->getBitWidth())
4359 return;
4360
4361 // If we can truncate the root, we must collect additional values that might
4362 // be demoted as a result. That is, those seeded by truncations we will
4363 // modify.
4364 while (!Roots.empty())
4365 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
4366
4367 // Finally, map the values we can demote to the maximum bit with we computed.
4368 for (auto *Scalar : ToDemote)
4369 MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
4370}
4371
4372namespace {
4373
4374/// The SLPVectorizer Pass.
4375struct SLPVectorizer : public FunctionPass {
4376 SLPVectorizerPass Impl;
4377
4378 /// Pass identification, replacement for typeid
4379 static char ID;
4380
4381 explicit SLPVectorizer() : FunctionPass(ID) {
4382 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
4383 }
4384
4385 bool doInitialization(Module &M) override {
4386 return false;
4387 }
4388
4389 bool runOnFunction(Function &F) override {
4390 if (skipFunction(F))
4391 return false;
4392
4393 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4394 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
4395 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
4396 auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
4397 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4398 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4399 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4400 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4401 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
4402 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
4403
4404 return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
4405 }
4406
4407 void getAnalysisUsage(AnalysisUsage &AU) const override {
4408 FunctionPass::getAnalysisUsage(AU);
4409 AU.addRequired<AssumptionCacheTracker>();
4410 AU.addRequired<ScalarEvolutionWrapperPass>();
4411 AU.addRequired<AAResultsWrapperPass>();
4412 AU.addRequired<TargetTransformInfoWrapperPass>();
4413 AU.addRequired<LoopInfoWrapperPass>();
4414 AU.addRequired<DominatorTreeWrapperPass>();
4415 AU.addRequired<DemandedBitsWrapperPass>();
4416 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
4417 AU.addPreserved<LoopInfoWrapperPass>();
4418 AU.addPreserved<DominatorTreeWrapperPass>();
4419 AU.addPreserved<AAResultsWrapperPass>();
4420 AU.addPreserved<GlobalsAAWrapperPass>();
4421 AU.setPreservesCFG();
4422 }
4423};
4424
4425} // end anonymous namespace
4426
4427PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
4428 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
4429 auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
4430 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
4431 auto *AA = &AM.getResult<AAManager>(F);
4432 auto *LI = &AM.getResult<LoopAnalysis>(F);
4433 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
4434 auto *AC = &AM.getResult<AssumptionAnalysis>(F);
4435 auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
4436 auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
4437
4438 bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
4439 if (!Changed)
4440 return PreservedAnalyses::all();
4441
4442 PreservedAnalyses PA;
4443 PA.preserveSet<CFGAnalyses>();
4444 PA.preserve<AAManager>();
4445 PA.preserve<GlobalsAA>();
4446 return PA;
4447}
4448
4449bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
4450 TargetTransformInfo *TTI_,
4451 TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
4452 LoopInfo *LI_, DominatorTree *DT_,
4453 AssumptionCache *AC_, DemandedBits *DB_,
4454 OptimizationRemarkEmitter *ORE_) {
4455 SE = SE_;
4456 TTI = TTI_;
4457 TLI = TLI_;
4458 AA = AA_;
4459 LI = LI_;
4460 DT = DT_;
4461 AC = AC_;
4462 DB = DB_;
4463 DL = &F.getParent()->getDataLayout();
4464
4465 Stores.clear();
4466 GEPs.clear();
4467 bool Changed = false;
4468
4469 // If the target claims to have no vector registers don't attempt
4470 // vectorization.
4471 if (!TTI->getNumberOfRegisters(true))
4472 return false;
4473
4474 // Don't vectorize when the attribute NoImplicitFloat is used.
4475 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
4476 return false;
4477
4478 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing blocks in " <<
F.getName() << ".\n"; } } while (false)
;
4479
4480 // Use the bottom up slp vectorizer to construct chains that start with
4481 // store instructions.
4482 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
4483
4484 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
4485 // delete instructions.
4486
4487 // Scan the blocks in the function in post order.
4488 for (auto BB : post_order(&F.getEntryBlock())) {
4489 collectSeedInstructions(BB);
4490
4491 // Vectorize trees that end at stores.
4492 if (!Stores.empty()) {
4493 DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Found stores for " << Stores
.size() << " underlying objects.\n"; } } while (false)
4494 << " underlying objects.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Found stores for " << Stores
.size() << " underlying objects.\n"; } } while (false)
;
4495 Changed |= vectorizeStoreChains(R);
4496 }
4497
4498 // Vectorize trees that end at reductions.
4499 Changed |= vectorizeChainsInBlock(BB, R);
4500
4501 // Vectorize the index computations of getelementptr instructions. This
4502 // is primarily intended to catch gather-like idioms ending at
4503 // non-consecutive loads.
4504 if (!GEPs.empty()) {
4505 DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Found GEPs for " << GEPs
.size() << " underlying objects.\n"; } } while (false)
4506 << " underlying objects.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Found GEPs for " << GEPs
.size() << " underlying objects.\n"; } } while (false)
;
4507 Changed |= vectorizeGEPIndices(BB, R);
4508 }
4509 }
4510
4511 if (Changed) {
4512 R.optimizeGatherSequence();
4513 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: vectorized \"" << F.getName
() << "\"\n"; } } while (false)
;
4514 DEBUG(verifyFunction(F))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { verifyFunction(F); } } while (false)
;
4515 }
4516 return Changed;
4517}
4518
4519/// \brief Check that the Values in the slice in VL array are still existent in
4520/// the WeakTrackingVH array.
4521/// Vectorization of part of the VL array may cause later values in the VL array
4522/// to become invalid. We track when this has happened in the WeakTrackingVH
4523/// array.
4524static bool hasValueBeenRAUWed(ArrayRef<Value *> VL,
4525 ArrayRef<WeakTrackingVH> VH, unsigned SliceBegin,
4526 unsigned SliceSize) {
4527 VL = VL.slice(SliceBegin, SliceSize);
4528 VH = VH.slice(SliceBegin, SliceSize);
4529 return !std::equal(VL.begin(), VL.end(), VH.begin());
4530}
4531
4532bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
4533 unsigned VecRegSize) {
4534 const unsigned ChainLen = Chain.size();
4535 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLendo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing a store chain of length "
<< ChainLen << "\n"; } } while (false)
4536 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing a store chain of length "
<< ChainLen << "\n"; } } while (false)
;
4537 const unsigned Sz = R.getVectorElementSize(Chain[0]);
4538 const unsigned VF = VecRegSize / Sz;
4539
4540 if (!isPowerOf2_32(Sz) || VF < 2)
4541 return false;
4542
4543 // Keep track of values that were deleted by vectorizing in the loop below.
4544 const SmallVector<WeakTrackingVH, 8> TrackValues(Chain.begin(), Chain.end());
4545
4546 bool Changed = false;
4547 // Look for profitable vectorizable trees at all offsets, starting at zero.
4548 for (unsigned i = 0, e = ChainLen; i + VF <= e; ++i) {
4549
4550 // Check that a previous iteration of this loop did not delete the Value.
4551 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
4552 continue;
4553
4554 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << ido { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing " << VF <<
" stores at offset " << i << "\n"; } } while (false
)
4555 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing " << VF <<
" stores at offset " << i << "\n"; } } while (false
)
;
4556 ArrayRef<Value *> Operands = Chain.slice(i, VF);
4557
4558 R.buildTree(Operands);
4559 if (R.isTreeTinyAndNotFullyVectorizable())
4560 continue;
4561
4562 R.computeMinimumValueSizes();
4563
4564 int Cost = R.getTreeCost();
4565
4566 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Found cost=" << Cost <<
" for VF=" << VF << "\n"; } } while (false)
;
4567 if (Cost < -SLPCostThreshold) {
4568 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Decided to vectorize cost=" <<
Cost << "\n"; } } while (false)
;
4569
4570 using namespace ore;
4571
4572 R.getORE()->emit(OptimizationRemark(SV_NAME"slp-vectorizer", "StoresVectorized",
4573 cast<StoreInst>(Chain[i]))
4574 << "Stores SLP vectorized with cost " << NV("Cost", Cost)
4575 << " and with tree size "
4576 << NV("TreeSize", R.getTreeSize()));
4577
4578 R.vectorizeTree();
4579
4580 // Move to the next bundle.
4581 i += VF - 1;
4582 Changed = true;
4583 }
4584 }
4585
4586 return Changed;
4587}
4588
4589bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
4590 BoUpSLP &R) {
4591 SetVector<StoreInst *> Heads;
4592 SmallDenseSet<StoreInst *> Tails;
4593 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
4594
4595 // We may run into multiple chains that merge into a single chain. We mark the
4596 // stores that we vectorized so that we don't visit the same store twice.
4597 BoUpSLP::ValueSet VectorizedStores;
4598 bool Changed = false;
4599
4600 // Do a quadratic search on all of the given stores in reverse order and find
4601 // all of the pairs of stores that follow each other.
4602 SmallVector<unsigned, 16> IndexQueue;
4603 unsigned E = Stores.size();
4604 IndexQueue.resize(E - 1);
4605 for (unsigned I = E; I > 0; --I) {
4606 unsigned Idx = I - 1;
4607 // If a store has multiple consecutive store candidates, search Stores
4608 // array according to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
4609 // This is because usually pairing with immediate succeeding or preceding
4610 // candidate create the best chance to find slp vectorization opportunity.
4611 unsigned Offset = 1;
4612 unsigned Cnt = 0;
4613 for (unsigned J = 0; J < E - 1; ++J, ++Offset) {
4614 if (Idx >= Offset) {
4615 IndexQueue[Cnt] = Idx - Offset;
4616 ++Cnt;
4617 }
4618 if (Idx + Offset < E) {
4619 IndexQueue[Cnt] = Idx + Offset;
4620 ++Cnt;
4621 }
4622 }
4623
4624 for (auto K : IndexQueue) {
4625 if (isConsecutiveAccess(Stores[K], Stores[Idx], *DL, *SE)) {
4626 Tails.insert(Stores[Idx]);
4627 Heads.insert(Stores[K]);
4628 ConsecutiveChain[Stores[K]] = Stores[Idx];
4629 break;
4630 }
4631 }
4632 }
4633
4634 // For stores that start but don't end a link in the chain:
4635 for (auto *SI : llvm::reverse(Heads)) {
4636 if (Tails.count(SI))
4637 continue;
4638
4639 // We found a store instr that starts a chain. Now follow the chain and try
4640 // to vectorize it.
4641 BoUpSLP::ValueList Operands;
4642 StoreInst *I = SI;
4643 // Collect the chain into a list.
4644 while ((Tails.count(I) || Heads.count(I)) && !VectorizedStores.count(I)) {
4645 Operands.push_back(I);
4646 // Move to the next value in the chain.
4647 I = ConsecutiveChain[I];
4648 }
4649
4650 // FIXME: Is division-by-2 the correct step? Should we assert that the
4651 // register size is a power-of-2?
4652 for (unsigned Size = R.getMaxVecRegSize(); Size >= R.getMinVecRegSize();
4653 Size /= 2) {
4654 if (vectorizeStoreChain(Operands, R, Size)) {
4655 // Mark the vectorized stores so that we don't vectorize them again.
4656 VectorizedStores.insert(Operands.begin(), Operands.end());
4657 Changed = true;
4658 break;
4659 }
4660 }
4661 }
4662
4663 return Changed;
4664}
4665
4666void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
4667 // Initialize the collections. We will make a single pass over the block.
4668 Stores.clear();
4669 GEPs.clear();
4670
4671 // Visit the store and getelementptr instructions in BB and organize them in
4672 // Stores and GEPs according to the underlying objects of their pointer
4673 // operands.
4674 for (Instruction &I : *BB) {
4675 // Ignore store instructions that are volatile or have a pointer operand
4676 // that doesn't point to a scalar type.
4677 if (auto *SI = dyn_cast<StoreInst>(&I)) {
4678 if (!SI->isSimple())
4679 continue;
4680 if (!isValidElementType(SI->getValueOperand()->getType()))
4681 continue;
4682 Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
4683 }
4684
4685 // Ignore getelementptr instructions that have more than one index, a
4686 // constant index, or a pointer operand that doesn't point to a scalar
4687 // type.
4688 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
4689 auto Idx = GEP->idx_begin()->get();
4690 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
4691 continue;
4692 if (!isValidElementType(Idx->getType()))
4693 continue;
4694 if (GEP->getType()->isVectorTy())
4695 continue;
4696 GEPs[GetUnderlyingObject(GEP->getPointerOperand(), *DL)].push_back(GEP);
4697 }
4698 }
4699}
4700
4701bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
4702 if (!A || !B)
4703 return false;
4704 Value *VL[] = { A, B };
4705 return tryToVectorizeList(VL, R, /*UserCost=*/0, true);
4706}
4707
4708bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
4709 int UserCost, bool AllowReorder) {
4710 if (VL.size() < 2)
4711 return false;
4712
4713 DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " << VL.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Trying to vectorize a list of length = "
<< VL.size() << ".\n"; } } while (false)
4714 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Trying to vectorize a list of length = "
<< VL.size() << ".\n"; } } while (false)
;
4715
4716 // Check that all of the parts are scalar instructions of the same type.
4717 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
4718 if (!I0)
4719 return false;
4720
4721 unsigned Opcode0 = I0->getOpcode();
4722
4723 unsigned Sz = R.getVectorElementSize(I0);
4724 unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
4725 unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
4726 if (MaxVF < 2) {
4727 R.getORE()->emit([&]() {
4728 return OptimizationRemarkMissed(
4729 SV_NAME"slp-vectorizer", "SmallVF", I0)
4730 << "Cannot SLP vectorize list: vectorization factor "
4731 << "less than 2 is not supported";
4732 });
4733 return false;
4734 }
4735
4736 for (Value *V : VL) {
4737 Type *Ty = V->getType();
4738 if (!isValidElementType(Ty)) {
4739 // NOTE: the following will give user internal llvm type name, which may not be useful
4740 R.getORE()->emit([&]() {
4741 std::string type_str;
4742 llvm::raw_string_ostream rso(type_str);
4743 Ty->print(rso);
4744 return OptimizationRemarkMissed(
4745 SV_NAME"slp-vectorizer", "UnsupportedType", I0)
4746 << "Cannot SLP vectorize list: type "
4747 << rso.str() + " is unsupported by vectorizer";
4748 });
4749 return false;
4750 }
4751 Instruction *Inst = dyn_cast<Instruction>(V);
4752
4753 if (!Inst)
4754 return false;
4755 if (Inst->getOpcode() != Opcode0) {
4756 R.getORE()->emit([&]() {
4757 return OptimizationRemarkMissed(
4758 SV_NAME"slp-vectorizer", "InequableTypes", I0)
4759 << "Cannot SLP vectorize list: not all of the "
4760 << "parts of scalar instructions are of the same type: "
4761 << ore::NV("Instruction1Opcode", I0) << " and "
4762 << ore::NV("Instruction2Opcode", Inst);
4763 });
4764 return false;
4765 }
4766 }
4767
4768 bool Changed = false;
4769 bool CandidateFound = false;
4770 int MinCost = SLPCostThreshold;
4771
4772 // Keep track of values that were deleted by vectorizing in the loop below.
4773 SmallVector<WeakTrackingVH, 8> TrackValues(VL.begin(), VL.end());
4774
4775 unsigned NextInst = 0, MaxInst = VL.size();
4776 for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF;
4777 VF /= 2) {
4778 // No actual vectorization should happen, if number of parts is the same as
4779 // provided vectorization factor (i.e. the scalar type is used for vector
4780 // code during codegen).
4781 auto *VecTy = VectorType::get(VL[0]->getType(), VF);
4782 if (TTI->getNumberOfParts(VecTy) == VF)
4783 continue;
4784 for (unsigned I = NextInst; I < MaxInst; ++I) {
4785 unsigned OpsWidth = 0;
4786
4787 if (I + VF > MaxInst)
4788 OpsWidth = MaxInst - I;
4789 else
4790 OpsWidth = VF;
4791
4792 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
4793 break;
4794
4795 // Check that a previous iteration of this loop did not delete the Value.
4796 if (hasValueBeenRAUWed(VL, TrackValues, I, OpsWidth))
4797 continue;
4798
4799 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing " << OpsWidth
<< " operations " << "\n"; } } while (false)
4800 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing " << OpsWidth
<< " operations " << "\n"; } } while (false)
;
4801 ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
4802
4803 R.buildTree(Ops);
4804 // TODO: check if we can allow reordering for more cases.
4805 if (AllowReorder && R.shouldReorder()) {
4806 // Conceptually, there is nothing actually preventing us from trying to
4807 // reorder a larger list. In fact, we do exactly this when vectorizing
4808 // reductions. However, at this point, we only expect to get here when
4809 // there are exactly two operations.
4810 assert(Ops.size() == 2)(static_cast <bool> (Ops.size() == 2) ? void (0) : __assert_fail
("Ops.size() == 2", "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 4810, __extension__ __PRETTY_FUNCTION__))
;
4811 Value *ReorderedOps[] = {Ops[1], Ops[0]};
4812 R.buildTree(ReorderedOps, None);
4813 }
4814 if (R.isTreeTinyAndNotFullyVectorizable())
4815 continue;
4816
4817 R.computeMinimumValueSizes();
4818 int Cost = R.getTreeCost() - UserCost;
4819 CandidateFound = true;
4820 MinCost = std::min(MinCost, Cost);
4821
4822 if (Cost < -SLPCostThreshold) {
4823 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Vectorizing list at cost:" <<
Cost << ".\n"; } } while (false)
;
4824 R.getORE()->emit(OptimizationRemark(SV_NAME"slp-vectorizer", "VectorizedList",
4825 cast<Instruction>(Ops[0]))
4826 << "SLP vectorized with cost " << ore::NV("Cost", Cost)
4827 << " and with tree size "
4828 << ore::NV("TreeSize", R.getTreeSize()));
4829
4830 R.vectorizeTree();
4831 // Move to the next bundle.
4832 I += VF - 1;
4833 NextInst = I + 1;
4834 Changed = true;
4835 }
4836 }
4837 }
4838
4839 if (!Changed && CandidateFound) {
4840 R.getORE()->emit([&]() {
4841 return OptimizationRemarkMissed(
4842 SV_NAME"slp-vectorizer", "NotBeneficial", I0)
4843 << "List vectorization was possible but not beneficial with cost "
4844 << ore::NV("Cost", MinCost) << " >= "
4845 << ore::NV("Treshold", -SLPCostThreshold);
4846 });
4847 } else if (!Changed) {
4848 R.getORE()->emit([&]() {
4849 return OptimizationRemarkMissed(
4850 SV_NAME"slp-vectorizer", "NotPossible", I0)
4851 << "Cannot SLP vectorize list: vectorization was impossible"
4852 << " with available vectorization factors";
4853 });
4854 }
4855 return Changed;
4856}
4857
4858bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
4859 if (!I)
4860 return false;
4861
4862 if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
4863 return false;
4864
4865 Value *P = I->getParent();
4866
4867 // Vectorize in current basic block only.
4868 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
4869 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
4870 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
4871 return false;
4872
4873 // Try to vectorize V.
4874 if (tryToVectorizePair(Op0, Op1, R))
4875 return true;
4876
4877 auto *A = dyn_cast<BinaryOperator>(Op0);
4878 auto *B = dyn_cast<BinaryOperator>(Op1);
4879 // Try to skip B.
4880 if (B && B->hasOneUse()) {
4881 auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
4882 auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
4883 if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
4884 return true;
4885 if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
4886 return true;
4887 }
4888
4889 // Try to skip A.
4890 if (A && A->hasOneUse()) {
4891 auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
4892 auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
4893 if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
4894 return true;
4895 if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
4896 return true;
4897 }
4898 return false;
4899}
4900
4901/// \brief Generate a shuffle mask to be used in a reduction tree.
4902///
4903/// \param VecLen The length of the vector to be reduced.
4904/// \param NumEltsToRdx The number of elements that should be reduced in the
4905/// vector.
4906/// \param IsPairwise Whether the reduction is a pairwise or splitting
4907/// reduction. A pairwise reduction will generate a mask of
4908/// <0,2,...> or <1,3,..> while a splitting reduction will generate
4909/// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
4910/// \param IsLeft True will generate a mask of even elements, odd otherwise.
4911static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
4912 bool IsPairwise, bool IsLeft,
4913 IRBuilder<> &Builder) {
4914 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask")(static_cast <bool> ((IsPairwise || !IsLeft) &&
"Don't support a <0,1,undef,...> mask") ? void (0) : __assert_fail
("(IsPairwise || !IsLeft) && \"Don't support a <0,1,undef,...> mask\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 4914, __extension__ __PRETTY_FUNCTION__))
;
4915
4916 SmallVector<Constant *, 32> ShuffleMask(
4917 VecLen, UndefValue::get(Builder.getInt32Ty()));
4918
4919 if (IsPairwise)
4920 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
4921 for (unsigned i = 0; i != NumEltsToRdx; ++i)
4922 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
4923 else
4924 // Move the upper half of the vector to the lower half.
4925 for (unsigned i = 0; i != NumEltsToRdx; ++i)
4926 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
4927
4928 return ConstantVector::get(ShuffleMask);
4929}
4930
4931namespace {
4932
4933/// Model horizontal reductions.
4934///
4935/// A horizontal reduction is a tree of reduction operations (currently add and
4936/// fadd) that has operations that can be put into a vector as its leaf.
4937/// For example, this tree:
4938///
4939/// mul mul mul mul
4940/// \ / \ /
4941/// + +
4942/// \ /
4943/// +
4944/// This tree has "mul" as its reduced values and "+" as its reduction
4945/// operations. A reduction might be feeding into a store or a binary operation
4946/// feeding a phi.
4947/// ...
4948/// \ /
4949/// +
4950/// |
4951/// phi +=
4952///
4953/// Or:
4954/// ...
4955/// \ /
4956/// +
4957/// |
4958/// *p =
4959///
4960class HorizontalReduction {
4961 using ReductionOpsType = SmallVector<Value *, 16>;
4962 using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
4963 ReductionOpsListType ReductionOps;
4964 SmallVector<Value *, 32> ReducedVals;
4965 // Use map vector to make stable output.
4966 MapVector<Instruction *, Value *> ExtraArgs;
4967
4968 /// Kind of the reduction data.
4969 enum ReductionKind {
4970 RK_None, /// Not a reduction.
4971 RK_Arithmetic, /// Binary reduction data.
4972 RK_Min, /// Minimum reduction data.
4973 RK_UMin, /// Unsigned minimum reduction data.
4974 RK_Max, /// Maximum reduction data.
4975 RK_UMax, /// Unsigned maximum reduction data.
4976 };
4977
4978 /// Contains info about operation, like its opcode, left and right operands.
4979 class OperationData {
4980 /// Opcode of the instruction.
4981 unsigned Opcode = 0;
4982
4983 /// Left operand of the reduction operation.
4984 Value *LHS = nullptr;
4985
4986 /// Right operand of the reduction operation.
4987 Value *RHS = nullptr;
4988
4989 /// Kind of the reduction operation.
4990 ReductionKind Kind = RK_None;
4991
4992 /// True if float point min/max reduction has no NaNs.
4993 bool NoNaN = false;
4994
4995 /// Checks if the reduction operation can be vectorized.
4996 bool isVectorizable() const {
4997 return LHS && RHS &&
4998 // We currently only support adds && min/max reductions.
4999 ((Kind == RK_Arithmetic &&
5000 (Opcode == Instruction::Add || Opcode == Instruction::FAdd)) ||
5001 ((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
5002 (Kind == RK_Min || Kind == RK_Max)) ||
5003 (Opcode == Instruction::ICmp &&
5004 (Kind == RK_UMin || Kind == RK_UMax)));
5005 }
5006
5007 /// Creates reduction operation with the current opcode.
5008 Value *createOp(IRBuilder<> &Builder, const Twine &Name) const {
5009 assert(isVectorizable() &&(static_cast <bool> (isVectorizable() && "Expected add|fadd or min/max reduction operation."
) ? void (0) : __assert_fail ("isVectorizable() && \"Expected add|fadd or min/max reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5010, __extension__ __PRETTY_FUNCTION__))
5010 "Expected add|fadd or min/max reduction operation.")(static_cast <bool> (isVectorizable() && "Expected add|fadd or min/max reduction operation."
) ? void (0) : __assert_fail ("isVectorizable() && \"Expected add|fadd or min/max reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5010, __extension__ __PRETTY_FUNCTION__))
;
5011 Value *Cmp;
5012 switch (Kind) {
5013 case RK_Arithmetic:
5014 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, LHS, RHS,
5015 Name);
5016 case RK_Min:
5017 Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSLT(LHS, RHS)
5018 : Builder.CreateFCmpOLT(LHS, RHS);
5019 break;
5020 case RK_Max:
5021 Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSGT(LHS, RHS)
5022 : Builder.CreateFCmpOGT(LHS, RHS);
5023 break;
5024 case RK_UMin:
5025 assert(Opcode == Instruction::ICmp && "Expected integer types.")(static_cast <bool> (Opcode == Instruction::ICmp &&
"Expected integer types.") ? void (0) : __assert_fail ("Opcode == Instruction::ICmp && \"Expected integer types.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5025, __extension__ __PRETTY_FUNCTION__))
;
5026 Cmp = Builder.CreateICmpULT(LHS, RHS);
5027 break;
5028 case RK_UMax:
5029 assert(Opcode == Instruction::ICmp && "Expected integer types.")(static_cast <bool> (Opcode == Instruction::ICmp &&
"Expected integer types.") ? void (0) : __assert_fail ("Opcode == Instruction::ICmp && \"Expected integer types.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5029, __extension__ __PRETTY_FUNCTION__))
;
5030 Cmp = Builder.CreateICmpUGT(LHS, RHS);
5031 break;
5032 case RK_None:
5033 llvm_unreachable("Unknown reduction operation.")::llvm::llvm_unreachable_internal("Unknown reduction operation."
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5033)
;
5034 }
5035 return Builder.CreateSelect(Cmp, LHS, RHS, Name);
5036 }
5037
5038 public:
5039 explicit OperationData() = default;
5040
5041 /// Construction for reduced values. They are identified by opcode only and
5042 /// don't have associated LHS/RHS values.
5043 explicit OperationData(Value *V) {
5044 if (auto *I = dyn_cast<Instruction>(V))
5045 Opcode = I->getOpcode();
5046 }
5047
5048 /// Constructor for reduction operations with opcode and its left and
5049 /// right operands.
5050 OperationData(unsigned Opcode, Value *LHS, Value *RHS, ReductionKind Kind,
5051 bool NoNaN = false)
5052 : Opcode(Opcode), LHS(LHS), RHS(RHS), Kind(Kind), NoNaN(NoNaN) {
5053 assert(Kind != RK_None && "One of the reduction operations is expected.")(static_cast <bool> (Kind != RK_None && "One of the reduction operations is expected."
) ? void (0) : __assert_fail ("Kind != RK_None && \"One of the reduction operations is expected.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5053, __extension__ __PRETTY_FUNCTION__))
;
5054 }
5055
5056 explicit operator bool() const { return Opcode; }
5057
5058 /// Get the index of the first operand.
5059 unsigned getFirstOperandIndex() const {
5060 assert(!!*this && "The opcode is not set.")(static_cast <bool> (!!*this && "The opcode is not set."
) ? void (0) : __assert_fail ("!!*this && \"The opcode is not set.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5060, __extension__ __PRETTY_FUNCTION__))
;
5061 switch (Kind) {
5062 case RK_Min:
5063 case RK_UMin:
5064 case RK_Max:
5065 case RK_UMax:
5066 return 1;
5067 case RK_Arithmetic:
5068 case RK_None:
5069 break;
5070 }
5071 return 0;
5072 }
5073
5074 /// Total number of operands in the reduction operation.
5075 unsigned getNumberOfOperands() const {
5076 assert(Kind != RK_None && !!*this && LHS && RHS &&(static_cast <bool> (Kind != RK_None && !!*this
&& LHS && RHS && "Expected reduction operation."
) ? void (0) : __assert_fail ("Kind != RK_None && !!*this && LHS && RHS && \"Expected reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5077, __extension__ __PRETTY_FUNCTION__))
5077 "Expected reduction operation.")(static_cast <bool> (Kind != RK_None && !!*this
&& LHS && RHS && "Expected reduction operation."
) ? void (0) : __assert_fail ("Kind != RK_None && !!*this && LHS && RHS && \"Expected reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5077, __extension__ __PRETTY_FUNCTION__))
;
5078 switch (Kind) {
5079 case RK_Arithmetic:
5080 return 2;
5081 case RK_Min:
5082 case RK_UMin:
5083 case RK_Max:
5084 case RK_UMax:
5085 return 3;
5086 case RK_None:
5087 break;
5088 }
5089 llvm_unreachable("Reduction kind is not set")::llvm::llvm_unreachable_internal("Reduction kind is not set"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5089)
;
5090 }
5091
5092 /// Checks if the operation has the same parent as \p P.
5093 bool hasSameParent(Instruction *I, Value *P, bool IsRedOp) const {
5094 assert(Kind != RK_None && !!*this && LHS && RHS &&(static_cast <bool> (Kind != RK_None && !!*this
&& LHS && RHS && "Expected reduction operation."
) ? void (0) : __assert_fail ("Kind != RK_None && !!*this && LHS && RHS && \"Expected reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5095, __extension__ __PRETTY_FUNCTION__))
5095 "Expected reduction operation.")(static_cast <bool> (Kind != RK_None && !!*this
&& LHS && RHS && "Expected reduction operation."
) ? void (0) : __assert_fail ("Kind != RK_None && !!*this && LHS && RHS && \"Expected reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5095, __extension__ __PRETTY_FUNCTION__))
;
5096 if (!IsRedOp)
5097 return I->getParent() == P;
5098 switch (Kind) {
5099 case RK_Arithmetic:
5100 // Arithmetic reduction operation must be used once only.
5101 return I->getParent() == P;
5102 case RK_Min:
5103 case RK_UMin:
5104 case RK_Max:
5105 case RK_UMax: {
5106 // SelectInst must be used twice while the condition op must have single
5107 // use only.
5108 auto *Cmp = cast<Instruction>(cast<SelectInst>(I)->getCondition());
5109 return I->getParent() == P && Cmp && Cmp->getParent() == P;
5110 }
5111 case RK_None:
5112 break;
5113 }
5114 llvm_unreachable("Reduction kind is not set")::llvm::llvm_unreachable_internal("Reduction kind is not set"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5114)
;
5115 }
5116 /// Expected number of uses for reduction operations/reduced values.
5117 bool hasRequiredNumberOfUses(Instruction *I, bool IsReductionOp) const {
5118 assert(Kind != RK_None && !!*this && LHS && RHS &&(static_cast <bool> (Kind != RK_None && !!*this
&& LHS && RHS && "Expected reduction operation."
) ? void (0) : __assert_fail ("Kind != RK_None && !!*this && LHS && RHS && \"Expected reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5119, __extension__ __PRETTY_FUNCTION__))
5119 "Expected reduction operation.")(static_cast <bool> (Kind != RK_None && !!*this
&& LHS && RHS && "Expected reduction operation."
) ? void (0) : __assert_fail ("Kind != RK_None && !!*this && LHS && RHS && \"Expected reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5119, __extension__ __PRETTY_FUNCTION__))
;
5120 switch (Kind) {
5121 case RK_Arithmetic:
5122 return I->hasOneUse();
5123 case RK_Min:
5124 case RK_UMin:
5125 case RK_Max:
5126 case RK_UMax:
5127 return I->hasNUses(2) &&
5128 (!IsReductionOp ||
5129 cast<SelectInst>(I)->getCondition()->hasOneUse());
5130 case RK_None:
5131 break;
5132 }
5133 llvm_unreachable("Reduction kind is not set")::llvm::llvm_unreachable_internal("Reduction kind is not set"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5133)
;
5134 }
5135
5136 /// Initializes the list of reduction operations.
5137 void initReductionOps(ReductionOpsListType &ReductionOps) {
5138 assert(Kind != RK_None && !!*this && LHS && RHS &&(static_cast <bool> (Kind != RK_None && !!*this
&& LHS && RHS && "Expected reduction operation."
) ? void (0) : __assert_fail ("Kind != RK_None && !!*this && LHS && RHS && \"Expected reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5139, __extension__ __PRETTY_FUNCTION__))
5139 "Expected reduction operation.")(static_cast <bool> (Kind != RK_None && !!*this
&& LHS && RHS && "Expected reduction operation."
) ? void (0) : __assert_fail ("Kind != RK_None && !!*this && LHS && RHS && \"Expected reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5139, __extension__ __PRETTY_FUNCTION__))
;
5140 switch (Kind) {
5141 case RK_Arithmetic:
5142 ReductionOps.assign(1, ReductionOpsType());
5143 break;
5144 case RK_Min:
5145 case RK_UMin:
5146 case RK_Max:
5147 case RK_UMax:
5148 ReductionOps.assign(2, ReductionOpsType());
5149 break;
5150 case RK_None:
5151 llvm_unreachable("Reduction kind is not set")::llvm::llvm_unreachable_internal("Reduction kind is not set"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5151)
;
5152 }
5153 }
5154 /// Add all reduction operations for the reduction instruction \p I.
5155 void addReductionOps(Instruction *I, ReductionOpsListType &ReductionOps) {
5156 assert(Kind != RK_None && !!*this && LHS && RHS &&(static_cast <bool> (Kind != RK_None && !!*this
&& LHS && RHS && "Expected reduction operation."
) ? void (0) : __assert_fail ("Kind != RK_None && !!*this && LHS && RHS && \"Expected reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5157, __extension__ __PRETTY_FUNCTION__))
5157 "Expected reduction operation.")(static_cast <bool> (Kind != RK_None && !!*this
&& LHS && RHS && "Expected reduction operation."
) ? void (0) : __assert_fail ("Kind != RK_None && !!*this && LHS && RHS && \"Expected reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5157, __extension__ __PRETTY_FUNCTION__))
;
5158 switch (Kind) {
5159 case RK_Arithmetic:
5160 ReductionOps[0].emplace_back(I);
5161 break;
5162 case RK_Min:
5163 case RK_UMin:
5164 case RK_Max:
5165 case RK_UMax:
5166 ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
5167 ReductionOps[1].emplace_back(I);
5168 break;
5169 case RK_None:
5170 llvm_unreachable("Reduction kind is not set")::llvm::llvm_unreachable_internal("Reduction kind is not set"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5170)
;
5171 }
5172 }
5173
5174 /// Checks if instruction is associative and can be vectorized.
5175 bool isAssociative(Instruction *I) const {
5176 assert(Kind != RK_None && *this && LHS && RHS &&(static_cast <bool> (Kind != RK_None && *this &&
LHS && RHS && "Expected reduction operation."
) ? void (0) : __assert_fail ("Kind != RK_None && *this && LHS && RHS && \"Expected reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5177, __extension__ __PRETTY_FUNCTION__))
5177 "Expected reduction operation.")(static_cast <bool> (Kind != RK_None && *this &&
LHS && RHS && "Expected reduction operation."
) ? void (0) : __assert_fail ("Kind != RK_None && *this && LHS && RHS && \"Expected reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5177, __extension__ __PRETTY_FUNCTION__))
;
5178 switch (Kind) {
5179 case RK_Arithmetic:
5180 return I->isAssociative();
5181 case RK_Min:
5182 case RK_Max:
5183 return Opcode == Instruction::ICmp ||
5184 cast<Instruction>(I->getOperand(0))->isFast();
5185 case RK_UMin:
5186 case RK_UMax:
5187 assert(Opcode == Instruction::ICmp &&(static_cast <bool> (Opcode == Instruction::ICmp &&
"Only integer compare operation is expected.") ? void (0) : __assert_fail
("Opcode == Instruction::ICmp && \"Only integer compare operation is expected.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5188, __extension__ __PRETTY_FUNCTION__))
5188 "Only integer compare operation is expected.")(static_cast <bool> (Opcode == Instruction::ICmp &&
"Only integer compare operation is expected.") ? void (0) : __assert_fail
("Opcode == Instruction::ICmp && \"Only integer compare operation is expected.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5188, __extension__ __PRETTY_FUNCTION__))
;
5189 return true;
5190 case RK_None:
5191 break;
5192 }
5193 llvm_unreachable("Reduction kind is not set")::llvm::llvm_unreachable_internal("Reduction kind is not set"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5193)
;
5194 }
5195
5196 /// Checks if the reduction operation can be vectorized.
5197 bool isVectorizable(Instruction *I) const {
5198 return isVectorizable() && isAssociative(I);
5199 }
5200
5201 /// Checks if two operation data are both a reduction op or both a reduced
5202 /// value.
5203 bool operator==(const OperationData &OD) {
5204 assert(((Kind != OD.Kind) || ((!LHS == !OD.LHS) && (!RHS == !OD.RHS))) &&(static_cast <bool> (((Kind != OD.Kind) || ((!LHS == !OD
.LHS) && (!RHS == !OD.RHS))) && "One of the comparing operations is incorrect."
) ? void (0) : __assert_fail ("((Kind != OD.Kind) || ((!LHS == !OD.LHS) && (!RHS == !OD.RHS))) && \"One of the comparing operations is incorrect.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5205, __extension__ __PRETTY_FUNCTION__))
5205 "One of the comparing operations is incorrect.")(static_cast <bool> (((Kind != OD.Kind) || ((!LHS == !OD
.LHS) && (!RHS == !OD.RHS))) && "One of the comparing operations is incorrect."
) ? void (0) : __assert_fail ("((Kind != OD.Kind) || ((!LHS == !OD.LHS) && (!RHS == !OD.RHS))) && \"One of the comparing operations is incorrect.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5205, __extension__ __PRETTY_FUNCTION__))
;
5206 return this == &OD || (Kind == OD.Kind && Opcode == OD.Opcode);
5207 }
5208 bool operator!=(const OperationData &OD) { return !(*this == OD); }
5209 void clear() {
5210 Opcode = 0;
5211 LHS = nullptr;
5212 RHS = nullptr;
5213 Kind = RK_None;
5214 NoNaN = false;
5215 }
5216
5217 /// Get the opcode of the reduction operation.
5218 unsigned getOpcode() const {
5219 assert(isVectorizable() && "Expected vectorizable operation.")(static_cast <bool> (isVectorizable() && "Expected vectorizable operation."
) ? void (0) : __assert_fail ("isVectorizable() && \"Expected vectorizable operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5219, __extension__ __PRETTY_FUNCTION__))
;
5220 return Opcode;
5221 }
5222
5223 /// Get kind of reduction data.
5224 ReductionKind getKind() const { return Kind; }
5225 Value *getLHS() const { return LHS; }
5226 Value *getRHS() const { return RHS; }
5227 Type *getConditionType() const {
5228 switch (Kind) {
5229 case RK_Arithmetic:
5230 return nullptr;
5231 case RK_Min:
5232 case RK_Max:
5233 case RK_UMin:
5234 case RK_UMax:
5235 return CmpInst::makeCmpResultType(LHS->getType());
5236 case RK_None:
5237 break;
5238 }
5239 llvm_unreachable("Reduction kind is not set")::llvm::llvm_unreachable_internal("Reduction kind is not set"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5239)
;
5240 }
5241
5242 /// Creates reduction operation with the current opcode with the IR flags
5243 /// from \p ReductionOps.
5244 Value *createOp(IRBuilder<> &Builder, const Twine &Name,
5245 const ReductionOpsListType &ReductionOps) const {
5246 assert(isVectorizable() &&(static_cast <bool> (isVectorizable() && "Expected add|fadd or min/max reduction operation."
) ? void (0) : __assert_fail ("isVectorizable() && \"Expected add|fadd or min/max reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5247, __extension__ __PRETTY_FUNCTION__))
5247 "Expected add|fadd or min/max reduction operation.")(static_cast <bool> (isVectorizable() && "Expected add|fadd or min/max reduction operation."
) ? void (0) : __assert_fail ("isVectorizable() && \"Expected add|fadd or min/max reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5247, __extension__ __PRETTY_FUNCTION__))
;
5248 auto *Op = createOp(Builder, Name);
5249 switch (Kind) {
5250 case RK_Arithmetic:
5251 propagateIRFlags(Op, ReductionOps[0]);
5252 return Op;
5253 case RK_Min:
5254 case RK_Max:
5255 case RK_UMin:
5256 case RK_UMax:
5257 if (auto *SI = dyn_cast<SelectInst>(Op))
5258 propagateIRFlags(SI->getCondition(), ReductionOps[0]);
5259 propagateIRFlags(Op, ReductionOps[1]);
5260 return Op;
5261 case RK_None:
5262 break;
5263 }
5264 llvm_unreachable("Unknown reduction operation.")::llvm::llvm_unreachable_internal("Unknown reduction operation."
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5264)
;
5265 }
5266 /// Creates reduction operation with the current opcode with the IR flags
5267 /// from \p I.
5268 Value *createOp(IRBuilder<> &Builder, const Twine &Name,
5269 Instruction *I) const {
5270 assert(isVectorizable() &&(static_cast <bool> (isVectorizable() && "Expected add|fadd or min/max reduction operation."
) ? void (0) : __assert_fail ("isVectorizable() && \"Expected add|fadd or min/max reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5271, __extension__ __PRETTY_FUNCTION__))
5271 "Expected add|fadd or min/max reduction operation.")(static_cast <bool> (isVectorizable() && "Expected add|fadd or min/max reduction operation."
) ? void (0) : __assert_fail ("isVectorizable() && \"Expected add|fadd or min/max reduction operation.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5271, __extension__ __PRETTY_FUNCTION__))
;
5272 auto *Op = createOp(Builder, Name);
5273 switch (Kind) {
5274 case RK_Arithmetic:
5275 propagateIRFlags(Op, I);
5276 return Op;
5277 case RK_Min:
5278 case RK_Max:
5279 case RK_UMin:
5280 case RK_UMax:
5281 if (auto *SI = dyn_cast<SelectInst>(Op)) {
5282 propagateIRFlags(SI->getCondition(),
5283 cast<SelectInst>(I)->getCondition());
5284 }
5285 propagateIRFlags(Op, I);
5286 return Op;
5287 case RK_None:
5288 break;
5289 }
5290 llvm_unreachable("Unknown reduction operation.")::llvm::llvm_unreachable_internal("Unknown reduction operation."
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5290)
;
5291 }
5292
5293 TargetTransformInfo::ReductionFlags getFlags() const {
5294 TargetTransformInfo::ReductionFlags Flags;
5295 Flags.NoNaN = NoNaN;
5296 switch (Kind) {
5297 case RK_Arithmetic:
5298 break;
5299 case RK_Min:
5300 Flags.IsSigned = Opcode == Instruction::ICmp;
5301 Flags.IsMaxOp = false;
5302 break;
5303 case RK_Max:
5304 Flags.IsSigned = Opcode == Instruction::ICmp;
5305 Flags.IsMaxOp = true;
5306 break;
5307 case RK_UMin:
5308 Flags.IsSigned = false;
5309 Flags.IsMaxOp = false;
5310 break;
5311 case RK_UMax:
5312 Flags.IsSigned = false;
5313 Flags.IsMaxOp = true;
5314 break;
5315 case RK_None:
5316 llvm_unreachable("Reduction kind is not set")::llvm::llvm_unreachable_internal("Reduction kind is not set"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5316)
;
5317 }
5318 return Flags;
5319 }
5320 };
5321
5322 Instruction *ReductionRoot = nullptr;
5323
5324 /// The operation data of the reduction operation.
5325 OperationData ReductionData;
5326
5327 /// The operation data of the values we perform a reduction on.
5328 OperationData ReducedValueData;
5329
5330 /// Should we model this reduction as a pairwise reduction tree or a tree that
5331 /// splits the vector in halves and adds those halves.
5332 bool IsPairwiseReduction = false;
5333
5334 /// Checks if the ParentStackElem.first should be marked as a reduction
5335 /// operation with an extra argument or as extra argument itself.
5336 void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
5337 Value *ExtraArg) {
5338 if (ExtraArgs.count(ParentStackElem.first)) {
5339 ExtraArgs[ParentStackElem.first] = nullptr;
5340 // We ran into something like:
5341 // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
5342 // The whole ParentStackElem.first should be considered as an extra value
5343 // in this case.
5344 // Do not perform analysis of remaining operands of ParentStackElem.first
5345 // instruction, this whole instruction is an extra argument.
5346 ParentStackElem.second = ParentStackElem.first->getNumOperands();
5347 } else {
5348 // We ran into something like:
5349 // ParentStackElem.first += ... + ExtraArg + ...
5350 ExtraArgs[ParentStackElem.first] = ExtraArg;
5351 }
5352 }
5353
5354 static OperationData getOperationData(Value *V) {
5355 if (!V)
5356 return OperationData();
5357
5358 Value *LHS;
5359 Value *RHS;
5360 if (m_BinOp(m_Value(LHS), m_Value(RHS)).match(V)) {
5361 return OperationData(cast<BinaryOperator>(V)->getOpcode(), LHS, RHS,
5362 RK_Arithmetic);
5363 }
5364 if (auto *Select = dyn_cast<SelectInst>(V)) {
5365 // Look for a min/max pattern.
5366 if (m_UMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
5367 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
5368 } else if (m_SMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
5369 return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
5370 } else if (m_OrdFMin(m_Value(LHS), m_Value(RHS)).match(Select) ||
5371 m_UnordFMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
5372 return OperationData(
5373 Instruction::FCmp, LHS, RHS, RK_Min,
5374 cast<Instruction>(Select->getCondition())->hasNoNaNs());
5375 } else if (m_UMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
5376 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
5377 } else if (m_SMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
5378 return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
5379 } else if (m_OrdFMax(m_Value(LHS), m_Value(RHS)).match(Select) ||
5380 m_UnordFMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
5381 return OperationData(
5382 Instruction::FCmp, LHS, RHS, RK_Max,
5383 cast<Instruction>(Select->getCondition())->hasNoNaNs());
5384 }
5385 }
5386 return OperationData(V);
5387 }
5388
5389public:
5390 HorizontalReduction() = default;
5391
5392 /// \brief Try to find a reduction tree.
5393 bool matchAssociativeReduction(PHINode *Phi, Instruction *B) {
5394 assert((!Phi || is_contained(Phi->operands(), B)) &&(static_cast <bool> ((!Phi || is_contained(Phi->operands
(), B)) && "Thi phi needs to use the binary operator"
) ? void (0) : __assert_fail ("(!Phi || is_contained(Phi->operands(), B)) && \"Thi phi needs to use the binary operator\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5395, __extension__ __PRETTY_FUNCTION__))
5395 "Thi phi needs to use the binary operator")(static_cast <bool> ((!Phi || is_contained(Phi->operands
(), B)) && "Thi phi needs to use the binary operator"
) ? void (0) : __assert_fail ("(!Phi || is_contained(Phi->operands(), B)) && \"Thi phi needs to use the binary operator\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5395, __extension__ __PRETTY_FUNCTION__))
;
5396
5397 ReductionData = getOperationData(B);
5398
5399 // We could have a initial reductions that is not an add.
5400 // r *= v1 + v2 + v3 + v4
5401 // In such a case start looking for a tree rooted in the first '+'.
5402 if (Phi) {
5403 if (ReductionData.getLHS() == Phi) {
5404 Phi = nullptr;
5405 B = dyn_cast<Instruction>(ReductionData.getRHS());
5406 ReductionData = getOperationData(B);
5407 } else if (ReductionData.getRHS() == Phi) {
5408 Phi = nullptr;
5409 B = dyn_cast<Instruction>(ReductionData.getLHS());
5410 ReductionData = getOperationData(B);
5411 }
5412 }
5413
5414 if (!ReductionData.isVectorizable(B))
5415 return false;
5416
5417 Type *Ty = B->getType();
5418 if (!isValidElementType(Ty))
5419 return false;
5420
5421 ReducedValueData.clear();
5422 ReductionRoot = B;
5423
5424 // Post order traverse the reduction tree starting at B. We only handle true
5425 // trees containing only binary operators.
5426 SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
5427 Stack.push_back(std::make_pair(B, ReductionData.getFirstOperandIndex()));
5428 ReductionData.initReductionOps(ReductionOps);
5429 while (!Stack.empty()) {
5430 Instruction *TreeN = Stack.back().first;
5431 unsigned EdgeToVist = Stack.back().second++;
5432 OperationData OpData = getOperationData(TreeN);
5433 bool IsReducedValue = OpData != ReductionData;
5434
5435 // Postorder vist.
5436 if (IsReducedValue || EdgeToVist == OpData.getNumberOfOperands()) {
5437 if (IsReducedValue)
5438 ReducedVals.push_back(TreeN);
5439 else {
5440 auto I = ExtraArgs.find(TreeN);
5441 if (I != ExtraArgs.end() && !I->second) {
5442 // Check if TreeN is an extra argument of its parent operation.
5443 if (Stack.size() <= 1) {
5444 // TreeN can't be an extra argument as it is a root reduction
5445 // operation.
5446 return false;
5447 }
5448 // Yes, TreeN is an extra argument, do not add it to a list of
5449 // reduction operations.
5450 // Stack[Stack.size() - 2] always points to the parent operation.
5451 markExtraArg(Stack[Stack.size() - 2], TreeN);
5452 ExtraArgs.erase(TreeN);
5453 } else
5454 ReductionData.addReductionOps(TreeN, ReductionOps);
5455 }
5456 // Retract.
5457 Stack.pop_back();
5458 continue;
5459 }
5460
5461 // Visit left or right.
5462 Value *NextV = TreeN->getOperand(EdgeToVist);
5463 if (NextV != Phi) {
5464 auto *I = dyn_cast<Instruction>(NextV);
5465 OpData = getOperationData(I);
5466 // Continue analysis if the next operand is a reduction operation or
5467 // (possibly) a reduced value. If the reduced value opcode is not set,
5468 // the first met operation != reduction operation is considered as the
5469 // reduced value class.
5470 if (I && (!ReducedValueData || OpData == ReducedValueData ||
5471 OpData == ReductionData)) {
5472 const bool IsReductionOperation = OpData == ReductionData;
5473 // Only handle trees in the current basic block.
5474 if (!ReductionData.hasSameParent(I, B->getParent(),
5475 IsReductionOperation)) {
5476 // I is an extra argument for TreeN (its parent operation).
5477 markExtraArg(Stack.back(), I);
5478 continue;
5479 }
5480
5481 // Each tree node needs to have minimal number of users except for the
5482 // ultimate reduction.
5483 if (!ReductionData.hasRequiredNumberOfUses(I,
5484 OpData == ReductionData) &&
5485 I != B) {
5486 // I is an extra argument for TreeN (its parent operation).
5487 markExtraArg(Stack.back(), I);
5488 continue;
5489 }
5490
5491 if (IsReductionOperation) {
5492 // We need to be able to reassociate the reduction operations.
5493 if (!OpData.isAssociative(I)) {
5494 // I is an extra argument for TreeN (its parent operation).
5495 markExtraArg(Stack.back(), I);
5496 continue;
5497 }
5498 } else if (ReducedValueData &&
5499 ReducedValueData != OpData) {
5500 // Make sure that the opcodes of the operations that we are going to
5501 // reduce match.
5502 // I is an extra argument for TreeN (its parent operation).
5503 markExtraArg(Stack.back(), I);
5504 continue;
5505 } else if (!ReducedValueData)
5506 ReducedValueData = OpData;
5507
5508 Stack.push_back(std::make_pair(I, OpData.getFirstOperandIndex()));
5509 continue;
5510 }
5511 }
5512 // NextV is an extra argument for TreeN (its parent operation).
5513 markExtraArg(Stack.back(), NextV);
5514 }
5515 return true;
5516 }
5517
5518 /// \brief Attempt to vectorize the tree found by
5519 /// matchAssociativeReduction.
5520 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
5521 if (ReducedVals.empty())
5522 return false;
5523
5524 // If there is a sufficient number of reduction values, reduce
5525 // to a nearby power-of-2. Can safely generate oversized
5526 // vectors and rely on the backend to split them to legal sizes.
5527 unsigned NumReducedVals = ReducedVals.size();
5528 if (NumReducedVals < 4)
5529 return false;
5530
5531 unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
5532
5533 Value *VectorizedTree = nullptr;
5534 IRBuilder<> Builder(ReductionRoot);
5535 FastMathFlags Unsafe;
5536 Unsafe.setFast();
5537 Builder.setFastMathFlags(Unsafe);
5538 unsigned i = 0;
5539
5540 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
5541 // The same extra argument may be used several time, so log each attempt
5542 // to use it.
5543 for (auto &Pair : ExtraArgs)
5544 ExternallyUsedValues[Pair.second].push_back(Pair.first);
5545 SmallVector<Value *, 16> IgnoreList;
5546 for (auto &V : ReductionOps)
5547 IgnoreList.append(V.begin(), V.end());
5548 while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
5549 auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
5550 V.buildTree(VL, ExternallyUsedValues, IgnoreList);
5551 if (V.shouldReorder()) {
5552 SmallVector<Value *, 8> Reversed(VL.rbegin(), VL.rend());
5553 V.buildTree(Reversed, ExternallyUsedValues, IgnoreList);
5554 }
5555 if (V.isTreeTinyAndNotFullyVectorizable())
5556 break;
5557
5558 V.computeMinimumValueSizes();
5559
5560 // Estimate cost.
5561 int Cost =
5562 V.getTreeCost() + getReductionCost(TTI, ReducedVals[i], ReduxWidth);
5563 if (Cost >= -SLPCostThreshold) {
5564 V.getORE()->emit([&]() {
5565 return OptimizationRemarkMissed(
5566 SV_NAME"slp-vectorizer", "HorSLPNotBeneficial", cast<Instruction>(VL[0]))
5567 << "Vectorizing horizontal reduction is possible"
5568 << "but not beneficial with cost "
5569 << ore::NV("Cost", Cost) << " and threshold "
5570 << ore::NV("Threshold", -SLPCostThreshold);
5571 });
5572 break;
5573 }
5574
5575 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Costdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
<< Cost << ". (HorRdx)\n"; } } while (false)
5576 << ". (HorRdx)\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
<< Cost << ". (HorRdx)\n"; } } while (false)
;
5577 V.getORE()->emit([&]() {
5578 return OptimizationRemark(
5579 SV_NAME"slp-vectorizer", "VectorizedHorizontalReduction", cast<Instruction>(VL[0]))
5580 << "Vectorized horizontal reduction with cost "
5581 << ore::NV("Cost", Cost) << " and with tree size "
5582 << ore::NV("TreeSize", V.getTreeSize());
5583 });
5584
5585 // Vectorize a tree.
5586 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
5587 Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
5588
5589 // Emit a reduction.
5590 Value *ReducedSubTree =
5591 emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
5592 if (VectorizedTree) {
5593 Builder.SetCurrentDebugLocation(Loc);
5594 OperationData VectReductionData(ReductionData.getOpcode(),
5595 VectorizedTree, ReducedSubTree,
5596 ReductionData.getKind());
5597 VectorizedTree =
5598 VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
5599 } else
5600 VectorizedTree = ReducedSubTree;
5601 i += ReduxWidth;
5602 ReduxWidth = PowerOf2Floor(NumReducedVals - i);
5603 }
5604
5605 if (VectorizedTree) {
5606 // Finish the reduction.
5607 for (; i < NumReducedVals; ++i) {
5608 auto *I = cast<Instruction>(ReducedVals[i]);
5609 Builder.SetCurrentDebugLocation(I->getDebugLoc());
5610 OperationData VectReductionData(ReductionData.getOpcode(),
5611 VectorizedTree, I,
5612 ReductionData.getKind());
5613 VectorizedTree = VectReductionData.createOp(Builder, "", ReductionOps);
5614 }
5615 for (auto &Pair : ExternallyUsedValues) {
5616 assert(!Pair.second.empty() &&(static_cast <bool> (!Pair.second.empty() && "At least one DebugLoc must be inserted"
) ? void (0) : __assert_fail ("!Pair.second.empty() && \"At least one DebugLoc must be inserted\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5617, __extension__ __PRETTY_FUNCTION__))
5617 "At least one DebugLoc must be inserted")(static_cast <bool> (!Pair.second.empty() && "At least one DebugLoc must be inserted"
) ? void (0) : __assert_fail ("!Pair.second.empty() && \"At least one DebugLoc must be inserted\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5617, __extension__ __PRETTY_FUNCTION__))
;
5618 // Add each externally used value to the final reduction.
5619 for (auto *I : Pair.second) {
5620 Builder.SetCurrentDebugLocation(I->getDebugLoc());
5621 OperationData VectReductionData(ReductionData.getOpcode(),
5622 VectorizedTree, Pair.first,
5623 ReductionData.getKind());
5624 VectorizedTree = VectReductionData.createOp(Builder, "op.extra", I);
5625 }
5626 }
5627 // Update users.
5628 ReductionRoot->replaceAllUsesWith(VectorizedTree);
5629 }
5630 return VectorizedTree != nullptr;
5631 }
5632
5633 unsigned numReductionValues() const {
5634 return ReducedVals.size();
5635 }
5636
5637private:
5638 /// \brief Calculate the cost of a reduction.
5639 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal,
5640 unsigned ReduxWidth) {
5641 Type *ScalarTy = FirstReducedVal->getType();
5642 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
5643
5644 int PairwiseRdxCost;
5645 int SplittingRdxCost;
5646 switch (ReductionData.getKind()) {
5647 case RK_Arithmetic:
5648 PairwiseRdxCost =
5649 TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
5650 /*IsPairwiseForm=*/true);
5651 SplittingRdxCost =
5652 TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
5653 /*IsPairwiseForm=*/false);
5654 break;
5655 case RK_Min:
5656 case RK_Max:
5657 case RK_UMin:
5658 case RK_UMax: {
5659 Type *VecCondTy = CmpInst::makeCmpResultType(VecTy);
5660 bool IsUnsigned = ReductionData.getKind() == RK_UMin ||
5661 ReductionData.getKind() == RK_UMax;
5662 PairwiseRdxCost =
5663 TTI->getMinMaxReductionCost(VecTy, VecCondTy,
5664 /*IsPairwiseForm=*/true, IsUnsigned);
5665 SplittingRdxCost =
5666 TTI->getMinMaxReductionCost(VecTy, VecCondTy,
5667 /*IsPairwiseForm=*/false, IsUnsigned);
5668 break;
5669 }
5670 case RK_None:
5671 llvm_unreachable("Expected arithmetic or min/max reduction operation")::llvm::llvm_unreachable_internal("Expected arithmetic or min/max reduction operation"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5671)
;
5672 }
5673
5674 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
5675 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
5676
5677 int ScalarReduxCost;
5678 switch (ReductionData.getKind()) {
5679 case RK_Arithmetic:
5680 ScalarReduxCost =
5681 TTI->getArithmeticInstrCost(ReductionData.getOpcode(), ScalarTy);
5682 break;
5683 case RK_Min:
5684 case RK_Max:
5685 case RK_UMin:
5686 case RK_UMax:
5687 ScalarReduxCost =
5688 TTI->getCmpSelInstrCost(ReductionData.getOpcode(), ScalarTy) +
5689 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
5690 CmpInst::makeCmpResultType(ScalarTy));
5691 break;
5692 case RK_None:
5693 llvm_unreachable("Expected arithmetic or min/max reduction operation")::llvm::llvm_unreachable_internal("Expected arithmetic or min/max reduction operation"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5693)
;
5694 }
5695 ScalarReduxCost *= (ReduxWidth - 1);
5696
5697 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCostdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << VecReduxCost
- ScalarReduxCost << " for reduction that starts with "
<< *FirstReducedVal << " (It is a " << (IsPairwiseReduction
? "pairwise" : "splitting") << " reduction)\n"; } } while
(false)
5698 << " for reduction that starts with " << *FirstReducedValdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << VecReduxCost
- ScalarReduxCost << " for reduction that starts with "
<< *FirstReducedVal << " (It is a " << (IsPairwiseReduction
? "pairwise" : "splitting") << " reduction)\n"; } } while
(false)
5699 << " (It is a "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << VecReduxCost
- ScalarReduxCost << " for reduction that starts with "
<< *FirstReducedVal << " (It is a " << (IsPairwiseReduction
? "pairwise" : "splitting") << " reduction)\n"; } } while
(false)
5700 << (IsPairwiseReduction ? "pairwise" : "splitting")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << VecReduxCost
- ScalarReduxCost << " for reduction that starts with "
<< *FirstReducedVal << " (It is a " << (IsPairwiseReduction
? "pairwise" : "splitting") << " reduction)\n"; } } while
(false)
5701 << " reduction)\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << VecReduxCost
- ScalarReduxCost << " for reduction that starts with "
<< *FirstReducedVal << " (It is a " << (IsPairwiseReduction
? "pairwise" : "splitting") << " reduction)\n"; } } while
(false)
;
5702
5703 return VecReduxCost - ScalarReduxCost;
5704 }
5705
5706 /// \brief Emit a horizontal reduction of the vectorized value.
5707 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
5708 unsigned ReduxWidth, const TargetTransformInfo *TTI) {
5709 assert(VectorizedValue && "Need to have a vectorized tree node")(static_cast <bool> (VectorizedValue && "Need to have a vectorized tree node"
) ? void (0) : __assert_fail ("VectorizedValue && \"Need to have a vectorized tree node\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5709, __extension__ __PRETTY_FUNCTION__))
;
5710 assert(isPowerOf2_32(ReduxWidth) &&(static_cast <bool> (isPowerOf2_32(ReduxWidth) &&
"We only handle power-of-two reductions for now") ? void (0)
: __assert_fail ("isPowerOf2_32(ReduxWidth) && \"We only handle power-of-two reductions for now\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5711, __extension__ __PRETTY_FUNCTION__))
5711 "We only handle power-of-two reductions for now")(static_cast <bool> (isPowerOf2_32(ReduxWidth) &&
"We only handle power-of-two reductions for now") ? void (0)
: __assert_fail ("isPowerOf2_32(ReduxWidth) && \"We only handle power-of-two reductions for now\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 5711, __extension__ __PRETTY_FUNCTION__))
;
5712
5713 if (!IsPairwiseReduction)
5714 return createSimpleTargetReduction(
5715 Builder, TTI, ReductionData.getOpcode(), VectorizedValue,
5716 ReductionData.getFlags(), ReductionOps.back());
5717
5718 Value *TmpVec = VectorizedValue;
5719 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
5720 Value *LeftMask =
5721 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
5722 Value *RightMask =
5723 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
5724
5725 Value *LeftShuf = Builder.CreateShuffleVector(
5726 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
5727 Value *RightShuf = Builder.CreateShuffleVector(
5728 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
5729 "rdx.shuf.r");
5730 OperationData VectReductionData(ReductionData.getOpcode(), LeftShuf,
5731 RightShuf, ReductionData.getKind());
5732 TmpVec = VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
5733 }
5734
5735 // The result is in the first element of the vector.
5736 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
5737 }
5738};
5739
5740} // end anonymous namespace
5741
5742/// \brief Recognize construction of vectors like
5743/// %ra = insertelement <4 x float> undef, float %s0, i32 0
5744/// %rb = insertelement <4 x float> %ra, float %s1, i32 1
5745/// %rc = insertelement <4 x float> %rb, float %s2, i32 2
5746/// %rd = insertelement <4 x float> %rc, float %s3, i32 3
5747/// starting from the last insertelement instruction.
5748///
5749/// Returns true if it matches
5750static bool findBuildVector(InsertElementInst *LastInsertElem,
5751 TargetTransformInfo *TTI,
5752 SmallVectorImpl<Value *> &BuildVectorOpds,
5753 int &UserCost) {
5754 UserCost = 0;
5755 Value *V = nullptr;
5756 do {
5757 if (auto *CI = dyn_cast<ConstantInt>(LastInsertElem->getOperand(2))) {
5758 UserCost += TTI->getVectorInstrCost(Instruction::InsertElement,
5759 LastInsertElem->getType(),
5760 CI->getZExtValue());
5761 }
5762 BuildVectorOpds.push_back(LastInsertElem->getOperand(1));
5763 V = LastInsertElem->getOperand(0);
5764 if (isa<UndefValue>(V))
5765 break;
5766 LastInsertElem = dyn_cast<InsertElementInst>(V);
5767 if (!LastInsertElem || !LastInsertElem->hasOneUse())
5768 return false;
5769 } while (true);
5770 std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
5771 return true;
5772}
5773
5774/// \brief Like findBuildVector, but looks for construction of aggregate.
5775///
5776/// \return true if it matches.
5777static bool findBuildAggregate(InsertValueInst *IV,
5778 SmallVectorImpl<Value *> &BuildVectorOpds) {
5779 Value *V;
5780 do {
5781 BuildVectorOpds.push_back(IV->getInsertedValueOperand());
5782 V = IV->getAggregateOperand();
5783 if (isa<UndefValue>(V))
5784 break;
5785 IV = dyn_cast<InsertValueInst>(V);
5786 if (!IV || !IV->hasOneUse())
5787 return false;
5788 } while (true);
5789 std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
5790 return true;
5791}
5792
5793static bool PhiTypeSorterFunc(Value *V, Value *V2) {
5794 return V->getType() < V2->getType();
5795}
5796
5797/// \brief Try and get a reduction value from a phi node.
5798///
5799/// Given a phi node \p P in a block \p ParentBB, consider possible reductions
5800/// if they come from either \p ParentBB or a containing loop latch.
5801///
5802/// \returns A candidate reduction value if possible, or \code nullptr \endcode
5803/// if not possible.
5804static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
5805 BasicBlock *ParentBB, LoopInfo *LI) {
5806 // There are situations where the reduction value is not dominated by the
5807 // reduction phi. Vectorizing such cases has been reported to cause
5808 // miscompiles. See PR25787.
5809 auto DominatedReduxValue = [&](Value *R) {
5810 return (
5811 dyn_cast<Instruction>(R) &&
5812 DT->dominates(P->getParent(), dyn_cast<Instruction>(R)->getParent()));
5813 };
5814
5815 Value *Rdx = nullptr;
5816
5817 // Return the incoming value if it comes from the same BB as the phi node.
5818 if (P->getIncomingBlock(0) == ParentBB) {
5819 Rdx = P->getIncomingValue(0);
5820 } else if (P->getIncomingBlock(1) == ParentBB) {
5821 Rdx = P->getIncomingValue(1);
5822 }
5823
5824 if (Rdx && DominatedReduxValue(Rdx))
5825 return Rdx;
5826
5827 // Otherwise, check whether we have a loop latch to look at.
5828 Loop *BBL = LI->getLoopFor(ParentBB);
5829 if (!BBL)
5830 return nullptr;
5831 BasicBlock *BBLatch = BBL->getLoopLatch();
5832 if (!BBLatch)
5833 return nullptr;
5834
5835 // There is a loop latch, return the incoming value if it comes from
5836 // that. This reduction pattern occasionally turns up.
5837 if (P->getIncomingBlock(0) == BBLatch) {
5838 Rdx = P->getIncomingValue(0);
5839 } else if (P->getIncomingBlock(1) == BBLatch) {
5840 Rdx = P->getIncomingValue(1);
5841 }
5842
5843 if (Rdx && DominatedReduxValue(Rdx))
5844 return Rdx;
5845
5846 return nullptr;
5847}
5848
5849/// Attempt to reduce a horizontal reduction.
5850/// If it is legal to match a horizontal reduction feeding the phi node \a P
5851/// with reduction operators \a Root (or one of its operands) in a basic block
5852/// \a BB, then check if it can be done. If horizontal reduction is not found
5853/// and root instruction is a binary operation, vectorization of the operands is
5854/// attempted.
5855/// \returns true if a horizontal reduction was matched and reduced or operands
5856/// of one of the binary instruction were vectorized.
5857/// \returns false if a horizontal reduction was not matched (or not possible)
5858/// or no vectorization of any binary operation feeding \a Root instruction was
5859/// performed.
5860static bool tryToVectorizeHorReductionOrInstOperands(
5861 PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
5862 TargetTransformInfo *TTI,
5863 const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
5864 if (!ShouldVectorizeHor)
5865 return false;
5866
5867 if (!Root)
5868 return false;
5869
5870 if (Root->getParent() != BB || isa<PHINode>(Root))
5871 return false;
5872 // Start analysis starting from Root instruction. If horizontal reduction is
5873 // found, try to vectorize it. If it is not a horizontal reduction or
5874 // vectorization is not possible or not effective, and currently analyzed
5875 // instruction is a binary operation, try to vectorize the operands, using
5876 // pre-order DFS traversal order. If the operands were not vectorized, repeat
5877 // the same procedure considering each operand as a possible root of the
5878 // horizontal reduction.
5879 // Interrupt the process if the Root instruction itself was vectorized or all
5880 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
5881 SmallVector<std::pair<WeakTrackingVH, unsigned>, 8> Stack(1, {Root, 0});
5882 SmallSet<Value *, 8> VisitedInstrs;
5883 bool Res = false;
5884 while (!Stack.empty()) {
5885 Value *V;
5886 unsigned Level;
5887 std::tie(V, Level) = Stack.pop_back_val();
5888 if (!V)
5889 continue;
5890 auto *Inst = dyn_cast<Instruction>(V);
5891 if (!Inst)
5892 continue;
5893 auto *BI = dyn_cast<BinaryOperator>(Inst);
5894 auto *SI = dyn_cast<SelectInst>(Inst);
5895 if (BI || SI) {
5896 HorizontalReduction HorRdx;
5897 if (HorRdx.matchAssociativeReduction(P, Inst)) {
5898 if (HorRdx.tryToReduce(R, TTI)) {
5899 Res = true;
5900 // Set P to nullptr to avoid re-analysis of phi node in
5901 // matchAssociativeReduction function unless this is the root node.
5902 P = nullptr;
5903 continue;
5904 }
5905 }
5906 if (P && BI) {
5907 Inst = dyn_cast<Instruction>(BI->getOperand(0));
5908 if (Inst == P)
5909 Inst = dyn_cast<Instruction>(BI->getOperand(1));
5910 if (!Inst) {
5911 // Set P to nullptr to avoid re-analysis of phi node in
5912 // matchAssociativeReduction function unless this is the root node.
5913 P = nullptr;
5914 continue;
5915 }
5916 }
5917 }
5918 // Set P to nullptr to avoid re-analysis of phi node in
5919 // matchAssociativeReduction function unless this is the root node.
5920 P = nullptr;
5921 if (Vectorize(Inst, R)) {
5922 Res = true;
5923 continue;
5924 }
5925
5926 // Try to vectorize operands.
5927 // Continue analysis for the instruction from the same basic block only to
5928 // save compile time.
5929 if (++Level < RecursionMaxDepth)
5930 for (auto *Op : Inst->operand_values())
5931 if (VisitedInstrs.insert(Op).second)
5932 if (auto *I = dyn_cast<Instruction>(Op))
5933 if (!isa<PHINode>(I) && I->getParent() == BB)
5934 Stack.emplace_back(Op, Level);
5935 }
5936 return Res;
5937}
5938
5939bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
5940 BasicBlock *BB, BoUpSLP &R,
5941 TargetTransformInfo *TTI) {
5942 if (!V)
5943 return false;
5944 auto *I = dyn_cast<Instruction>(V);
5945 if (!I)
5946 return false;
5947
5948 if (!isa<BinaryOperator>(I))
5949 P = nullptr;
5950 // Try to match and vectorize a horizontal reduction.
5951 auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
5952 return tryToVectorize(I, R);
5953 };
5954 return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
5955 ExtraVectorization);
5956}
5957
5958bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
5959 BasicBlock *BB, BoUpSLP &R) {
5960 const DataLayout &DL = BB->getModule()->getDataLayout();
5961 if (!R.canMapToVector(IVI->getType(), DL))
5962 return false;
5963
5964 SmallVector<Value *, 16> BuildVectorOpds;
5965 if (!findBuildAggregate(IVI, BuildVectorOpds))
5966 return false;
5967
5968 DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: array mappable to vector: " <<
*IVI << "\n"; } } while (false)
;
5969 // Aggregate value is unlikely to be processed in vector register, we need to
5970 // extract scalars into scalar registers, so NeedExtraction is set true.
5971 return tryToVectorizeList(BuildVectorOpds, R);
5972}
5973
5974bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
5975 BasicBlock *BB, BoUpSLP &R) {
5976 int UserCost;
5977 SmallVector<Value *, 16> BuildVectorOpds;
5978 if (!findBuildVector(IEI, TTI, BuildVectorOpds, UserCost) ||
5979 (llvm::all_of(BuildVectorOpds,
5980 [](Value *V) { return isa<ExtractElementInst>(V); }) &&
5981 isShuffle(BuildVectorOpds)))
5982 return false;
5983
5984 // Vectorize starting with the build vector operands ignoring the BuildVector
5985 // instructions for the purpose of scheduling and user extraction.
5986 return tryToVectorizeList(BuildVectorOpds, R, UserCost);
5987}
5988
5989bool SLPVectorizerPass::vectorizeCmpInst(CmpInst *CI, BasicBlock *BB,
5990 BoUpSLP &R) {
5991 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R))
5992 return true;
5993
5994 bool OpsChanged = false;
5995 for (int Idx = 0; Idx < 2; ++Idx) {
5996 OpsChanged |=
5997 vectorizeRootInstruction(nullptr, CI->getOperand(Idx), BB, R, TTI);
5998 }
5999 return OpsChanged;
6000}
6001
6002bool SLPVectorizerPass::vectorizeSimpleInstructions(
6003 SmallVectorImpl<WeakVH> &Instructions, BasicBlock *BB, BoUpSLP &R) {
6004 bool OpsChanged = false;
6005 for (auto &VH : reverse(Instructions)) {
6006 auto *I = dyn_cast_or_null<Instruction>(VH);
6007 if (!I)
6008 continue;
6009 if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
6010 OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
6011 else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
6012 OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
6013 else if (auto *CI = dyn_cast<CmpInst>(I))
6014 OpsChanged |= vectorizeCmpInst(CI, BB, R);
6015 }
6016 Instructions.clear();
6017 return OpsChanged;
6018}
6019
6020bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
6021 bool Changed = false;
6022 SmallVector<Value *, 4> Incoming;
6023 SmallSet<Value *, 16> VisitedInstrs;
6024
6025 bool HaveVectorizedPhiNodes = true;
6026 while (HaveVectorizedPhiNodes) {
6027 HaveVectorizedPhiNodes = false;
6028
6029 // Collect the incoming values from the PHIs.
6030 Incoming.clear();
6031 for (Instruction &I : *BB) {
6032 PHINode *P = dyn_cast<PHINode>(&I);
6033 if (!P)
6034 break;
6035
6036 if (!VisitedInstrs.count(P))
6037 Incoming.push_back(P);
6038 }
6039
6040 // Sort by type.
6041 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
6042
6043 // Try to vectorize elements base on their type.
6044 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
6045 E = Incoming.end();
6046 IncIt != E;) {
6047
6048 // Look for the next elements with the same type.
6049 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
6050 while (SameTypeIt != E &&
6051 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
6052 VisitedInstrs.insert(*SameTypeIt);
6053 ++SameTypeIt;
6054 }
6055
6056 // Try to vectorize them.
6057 unsigned NumElts = (SameTypeIt - IncIt);
6058 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { errs() << "SLP: Trying to vectorize starting at PHIs ("
<< NumElts << ")\n"; } } while (false)
;
6059 // The order in which the phi nodes appear in the program does not matter.
6060 // So allow tryToVectorizeList to reorder them if it is beneficial. This
6061 // is done when there are exactly two elements since tryToVectorizeList
6062 // asserts that there are only two values when AllowReorder is true.
6063 bool AllowReorder = NumElts == 2;
6064 if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R,
6065 /*UserCost=*/0, AllowReorder)) {
6066 // Success start over because instructions might have been changed.
6067 HaveVectorizedPhiNodes = true;
6068 Changed = true;
6069 break;
6070 }
6071
6072 // Start over at the next instruction of a different type (or the end).
6073 IncIt = SameTypeIt;
6074 }
6075 }
6076
6077 VisitedInstrs.clear();
6078
6079 SmallVector<WeakVH, 8> PostProcessInstructions;
6080 SmallDenseSet<Instruction *, 4> KeyNodes;
6081 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
6082 // We may go through BB multiple times so skip the one we have checked.
6083 if (!VisitedInstrs.insert(&*it).second) {
6084 if (it->use_empty() && KeyNodes.count(&*it) > 0 &&
6085 vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) {
6086 // We would like to start over since some instructions are deleted
6087 // and the iterator may become invalid value.
6088 Changed = true;
6089 it = BB->begin();
6090 e = BB->end();
6091 }
6092 continue;
6093 }
6094
6095 if (isa<DbgInfoIntrinsic>(it))
6096 continue;
6097
6098 // Try to vectorize reductions that use PHINodes.
6099 if (PHINode *P = dyn_cast<PHINode>(it)) {
6100 // Check that the PHI is a reduction PHI.
6101 if (P->getNumIncomingValues() != 2)
6102 return Changed;
6103
6104 // Try to match and vectorize a horizontal reduction.
6105 if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
6106 TTI)) {
6107 Changed = true;
6108 it = BB->begin();
6109 e = BB->end();
6110 continue;
6111 }
6112 continue;
6113 }
6114
6115 // Ran into an instruction without users, like terminator, or function call
6116 // with ignored return value, store. Ignore unused instructions (basing on
6117 // instruction type, except for CallInst and InvokeInst).
6118 if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
6119 isa<InvokeInst>(it))) {
6120 KeyNodes.insert(&*it);
6121 bool OpsChanged = false;
6122 if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
6123 for (auto *V : it->operand_values()) {
6124 // Try to match and vectorize a horizontal reduction.
6125 OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
6126 }
6127 }
6128 // Start vectorization of post-process list of instructions from the
6129 // top-tree instructions to try to vectorize as many instructions as
6130 // possible.
6131 OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R);
6132 if (OpsChanged) {
6133 // We would like to start over since some instructions are deleted
6134 // and the iterator may become invalid value.
6135 Changed = true;
6136 it = BB->begin();
6137 e = BB->end();
6138 continue;
6139 }
6140 }
6141
6142 if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
6143 isa<InsertValueInst>(it))
6144 PostProcessInstructions.push_back(&*it);
6145
6146 }
6147
6148 return Changed;
6149}
6150
6151bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
6152 auto Changed = false;
6153 for (auto &Entry : GEPs) {
6154 // If the getelementptr list has fewer than two elements, there's nothing
6155 // to do.
6156 if (Entry.second.size() < 2)
6157 continue;
6158
6159 DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing a getelementptr list of length "
<< Entry.second.size() << ".\n"; } } while (false
)
6160 << Entry.second.size() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing a getelementptr list of length "
<< Entry.second.size() << ".\n"; } } while (false
)
;
6161
6162 // We process the getelementptr list in chunks of 16 (like we do for
6163 // stores) to minimize compile-time.
6164 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
6165 auto Len = std::min<unsigned>(BE - BI, 16);
6166 auto GEPList = makeArrayRef(&Entry.second[BI], Len);
6167
6168 // Initialize a set a candidate getelementptrs. Note that we use a
6169 // SetVector here to preserve program order. If the index computations
6170 // are vectorizable and begin with loads, we want to minimize the chance
6171 // of having to reorder them later.
6172 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
6173
6174 // Some of the candidates may have already been vectorized after we
6175 // initially collected them. If so, the WeakTrackingVHs will have
6176 // nullified the
6177 // values, so remove them from the set of candidates.
6178 Candidates.remove(nullptr);
6179
6180 // Remove from the set of candidates all pairs of getelementptrs with
6181 // constant differences. Such getelementptrs are likely not good
6182 // candidates for vectorization in a bottom-up phase since one can be
6183 // computed from the other. We also ensure all candidate getelementptr
6184 // indices are unique.
6185 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
6186 auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
6187 if (!Candidates.count(GEPI))
6188 continue;
6189 auto *SCEVI = SE->getSCEV(GEPList[I]);
6190 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
6191 auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
6192 auto *SCEVJ = SE->getSCEV(GEPList[J]);
6193 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
6194 Candidates.remove(GEPList[I]);
6195 Candidates.remove(GEPList[J]);
6196 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
6197 Candidates.remove(GEPList[J]);
6198 }
6199 }
6200 }
6201
6202 // We break out of the above computation as soon as we know there are
6203 // fewer than two candidates remaining.
6204 if (Candidates.size() < 2)
6205 continue;
6206
6207 // Add the single, non-constant index of each candidate to the bundle. We
6208 // ensured the indices met these constraints when we originally collected
6209 // the getelementptrs.
6210 SmallVector<Value *, 16> Bundle(Candidates.size());
6211 auto BundleIndex = 0u;
6212 for (auto *V : Candidates) {
6213 auto *GEP = cast<GetElementPtrInst>(V);
6214 auto *GEPIdx = GEP->idx_begin()->get();
6215 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx))(static_cast <bool> (GEP->getNumIndices() == 1 || !isa
<Constant>(GEPIdx)) ? void (0) : __assert_fail ("GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx)"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 6215, __extension__ __PRETTY_FUNCTION__))
;
6216 Bundle[BundleIndex++] = GEPIdx;
6217 }
6218
6219 // Try and vectorize the indices. We are currently only interested in
6220 // gather-like cases of the form:
6221 //
6222 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
6223 //
6224 // where the loads of "a", the loads of "b", and the subtractions can be
6225 // performed in parallel. It's likely that detecting this pattern in a
6226 // bottom-up phase will be simpler and less costly than building a
6227 // full-blown top-down phase beginning at the consecutive loads.
6228 Changed |= tryToVectorizeList(Bundle, R);
6229 }
6230 }
6231 return Changed;
6232}
6233
6234bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
6235 bool Changed = false;
6236 // Attempt to sort and vectorize each of the store-groups.
6237 for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
6238 ++it) {
6239 if (it->second.size() < 2)
6240 continue;
6241
6242 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing a store chain of length "
<< it->second.size() << ".\n"; } } while (false
)
6243 << it->second.size() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing a store chain of length "
<< it->second.size() << ".\n"; } } while (false
)
;
6244
6245 // Process the stores in chunks of 16.
6246 // TODO: The limit of 16 inhibits greater vectorization factors.
6247 // For example, AVX2 supports v32i8. Increasing this limit, however,
6248 // may cause a significant compile-time increase.
6249 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
6250 unsigned Len = std::min<unsigned>(CE - CI, 16);
6251 Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len), R);
6252 }
6253 }
6254 return Changed;
6255}
6256
6257char SLPVectorizer::ID = 0;
6258
6259static const char lv_name[] = "SLP Vectorizer";
6260
6261INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)static void *initializeSLPVectorizerPassOnce(PassRegistry &
Registry) {
6262INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)initializeAAResultsWrapperPassPass(Registry);
6263INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry);
6264INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry);
6265INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)initializeScalarEvolutionWrapperPassPass(Registry);
6266INITIALIZE_PASS_DEPENDENCY(LoopSimplify)initializeLoopSimplifyPass(Registry);
6267INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)initializeDemandedBitsWrapperPassPass(Registry);
6268INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)initializeOptimizationRemarkEmitterWrapperPassPass(Registry);
6269INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)PassInfo *PI = new PassInfo( lv_name, "slp-vectorizer", &
SLPVectorizer::ID, PassInfo::NormalCtor_t(callDefaultCtor<
SLPVectorizer>), false, false); Registry.registerPass(*PI,
true); return PI; } static llvm::once_flag InitializeSLPVectorizerPassFlag
; void llvm::initializeSLPVectorizerPass(PassRegistry &Registry
) { llvm::call_once(InitializeSLPVectorizerPassFlag, initializeSLPVectorizerPassOnce
, std::ref(Registry)); }
6270
6271Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }

/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
11// and dyn_cast_or_null<X>() templates.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_CASTING_H
16#define LLVM_SUPPORT_CASTING_H
17
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/type_traits.h"
20#include <cassert>
21#include <memory>
22#include <type_traits>
23
24namespace llvm {
25
26//===----------------------------------------------------------------------===//
27// isa<x> Support Templates
28//===----------------------------------------------------------------------===//
29
30// Define a template that can be specialized by smart pointers to reflect the
31// fact that they are automatically dereferenced, and are not involved with the
32// template selection process... the default implementation is a noop.
33//
34template<typename From> struct simplify_type {
35 using SimpleType = From; // The real type this represents...
36
37 // An accessor to get the real value...
38 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
39};
40
41template<typename From> struct simplify_type<const From> {
42 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
43 using SimpleType =
44 typename add_const_past_pointer<NonConstSimpleType>::type;
45 using RetType =
46 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
47
48 static RetType getSimplifiedValue(const From& Val) {
49 return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val));
12
Calling 'simplify_type::getSimplifiedValue'
13
Returning from 'simplify_type::getSimplifiedValue'
50 }
51};
52
53// The core of the implementation of isa<X> is here; To and From should be
54// the names of classes. This template can be specialized to customize the
55// implementation of isa<> without rewriting it from scratch.
56template <typename To, typename From, typename Enabler = void>
57struct isa_impl {
58 static inline bool doit(const From &Val) {
59 return To::classof(&Val);
19
Calling 'CallInst::classof'
25
Returning from 'CallInst::classof'
60 }
61};
62
63/// \brief Always allow upcasts, and perform no dynamic check for them.
64template <typename To, typename From>
65struct isa_impl<
66 To, From, typename std::enable_if<std::is_base_of<To, From>::value>::type> {
67 static inline bool doit(const From &) { return true; }
68};
69
70template <typename To, typename From> struct isa_impl_cl {
71 static inline bool doit(const From &Val) {
72 return isa_impl<To, From>::doit(Val);
73 }
74};
75
76template <typename To, typename From> struct isa_impl_cl<To, const From> {
77 static inline bool doit(const From &Val) {
78 return isa_impl<To, From>::doit(Val);
79 }
80};
81
82template <typename To, typename From>
83struct isa_impl_cl<To, const std::unique_ptr<From>> {
84 static inline bool doit(const std::unique_ptr<From> &Val) {
85 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 85, __extension__ __PRETTY_FUNCTION__))
;
86 return isa_impl_cl<To, From>::doit(*Val);
87 }
88};
89
90template <typename To, typename From> struct isa_impl_cl<To, From*> {
91 static inline bool doit(const From *Val) {
92 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 92, __extension__ __PRETTY_FUNCTION__))
;
93 return isa_impl<To, From>::doit(*Val);
94 }
95};
96
97template <typename To, typename From> struct isa_impl_cl<To, From*const> {
98 static inline bool doit(const From *Val) {
99 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 99, __extension__ __PRETTY_FUNCTION__))
;
100 return isa_impl<To, From>::doit(*Val);
101 }
102};
103
104template <typename To, typename From> struct isa_impl_cl<To, const From*> {
105 static inline bool doit(const From *Val) {
106 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 106, __extension__ __PRETTY_FUNCTION__))
;
17
Within the expansion of the macro 'assert':
107 return isa_impl<To, From>::doit(*Val);
18
Calling 'isa_impl::doit'
26
Returning from 'isa_impl::doit'
108 }
109};
110
111template <typename To, typename From> struct isa_impl_cl<To, const From*const> {
112 static inline bool doit(const From *Val) {
113 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 113, __extension__ __PRETTY_FUNCTION__))
;
114 return isa_impl<To, From>::doit(*Val);
115 }
116};
117
118template<typename To, typename From, typename SimpleFrom>
119struct isa_impl_wrap {
120 // When From != SimplifiedType, we can simplify the type some more by using
121 // the simplify_type template.
122 static bool doit(const From &Val) {
123 return isa_impl_wrap<To, SimpleFrom,
15
Calling 'isa_impl_wrap::doit'
28
Returning from 'isa_impl_wrap::doit'
124 typename simplify_type<SimpleFrom>::SimpleType>::doit(
125 simplify_type<const From>::getSimplifiedValue(Val));
11
Calling 'simplify_type::getSimplifiedValue'
14
Returning from 'simplify_type::getSimplifiedValue'
126 }
127};
128
129template<typename To, typename FromTy>
130struct isa_impl_wrap<To, FromTy, FromTy> {
131 // When From == SimpleType, we are as simple as we are going to get.
132 static bool doit(const FromTy &Val) {
133 return isa_impl_cl<To,FromTy>::doit(Val);
16
Calling 'isa_impl_cl::doit'
27
Returning from 'isa_impl_cl::doit'
134 }
135};
136
137// isa<X> - Return true if the parameter to the template is an instance of the
138// template type argument. Used like this:
139//
140// if (isa<Type>(myVal)) { ... }
141//
142template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
143 return isa_impl_wrap<X, const Y,
10
Calling 'isa_impl_wrap::doit'
29
Returning from 'isa_impl_wrap::doit'
144 typename simplify_type<const Y>::SimpleType>::doit(Val);
145}
146
147//===----------------------------------------------------------------------===//
148// cast<x> Support Templates
149//===----------------------------------------------------------------------===//
150
151template<class To, class From> struct cast_retty;
152
153// Calculate what type the 'cast' function should return, based on a requested
154// type of To and a source type of From.
155template<class To, class From> struct cast_retty_impl {
156 using ret_type = To &; // Normal case, return Ty&
157};
158template<class To, class From> struct cast_retty_impl<To, const From> {
159 using ret_type = const To &; // Normal case, return Ty&
160};
161
162template<class To, class From> struct cast_retty_impl<To, From*> {
163 using ret_type = To *; // Pointer arg case, return Ty*
164};
165
166template<class To, class From> struct cast_retty_impl<To, const From*> {
167 using ret_type = const To *; // Constant pointer arg case, return const Ty*
168};
169
170template<class To, class From> struct cast_retty_impl<To, const From*const> {
171 using ret_type = const To *; // Constant pointer arg case, return const Ty*
172};
173
174template <class To, class From>
175struct cast_retty_impl<To, std::unique_ptr<From>> {
176private:
177 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
178 using ResultType = typename std::remove_pointer<PointerType>::type;
179
180public:
181 using ret_type = std::unique_ptr<ResultType>;
182};
183
184template<class To, class From, class SimpleFrom>
185struct cast_retty_wrap {
186 // When the simplified type and the from type are not the same, use the type
187 // simplifier to reduce the type, then reuse cast_retty_impl to get the
188 // resultant type.
189 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
190};
191
192template<class To, class FromTy>
193struct cast_retty_wrap<To, FromTy, FromTy> {
194 // When the simplified type is equal to the from type, use it directly.
195 using ret_type = typename cast_retty_impl<To,FromTy>::ret_type;
196};
197
198template<class To, class From>
199struct cast_retty {
200 using ret_type = typename cast_retty_wrap<
201 To, From, typename simplify_type<From>::SimpleType>::ret_type;
202};
203
204// Ensure the non-simple values are converted using the simplify_type template
205// that may be specialized by smart pointers...
206//
207template<class To, class From, class SimpleFrom> struct cast_convert_val {
208 // This is not a simple type, use the template to simplify it...
209 static typename cast_retty<To, From>::ret_type doit(From &Val) {
210 return cast_convert_val<To, SimpleFrom,
211 typename simplify_type<SimpleFrom>::SimpleType>::doit(
212 simplify_type<From>::getSimplifiedValue(Val));
213 }
214};
215
216template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> {
217 // This _is_ a simple type, just cast it.
218 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
219 typename cast_retty<To, FromTy>::ret_type Res2
220 = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val);
221 return Res2;
222 }
223};
224
225template <class X> struct is_simple_type {
226 static const bool value =
227 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
228};
229
230// cast<X> - Return the argument parameter cast to the specified type. This
231// casting operator asserts that the type is correct, so it does not return null
232// on failure. It does not allow a null argument (use cast_or_null for that).
233// It is typically used like this:
234//
235// cast<Instruction>(myVal)->getParent()
236//
237template <class X, class Y>
238inline typename std::enable_if<!is_simple_type<Y>::value,
239 typename cast_retty<X, const Y>::ret_type>::type
240cast(const Y &Val) {
241 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 241, __extension__ __PRETTY_FUNCTION__))
;
242 return cast_convert_val<
243 X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val);
244}
245
246template <class X, class Y>
247inline typename cast_retty<X, Y>::ret_type cast(Y &Val) {
248 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 248, __extension__ __PRETTY_FUNCTION__))
;
249 return cast_convert_val<X, Y,
250 typename simplify_type<Y>::SimpleType>::doit(Val);
251}
252
253template <class X, class Y>
254inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) {
255 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 255, __extension__ __PRETTY_FUNCTION__))
;
9
Within the expansion of the macro 'assert':
a
Calling 'isa'
b
Returning from 'isa'
256 return cast_convert_val<X, Y*,
30
Calling 'cast_convert_val::doit'
31
Returning from 'cast_convert_val::doit'
257 typename simplify_type<Y*>::SimpleType>::doit(Val);
258}
259
260template <class X, class Y>
261inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
262cast(std::unique_ptr<Y> &&Val) {
263 assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val.get()) &&
"cast<Ty>() argument of incompatible type!") ? void (0
) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 263, __extension__ __PRETTY_FUNCTION__))
;
264 using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type;
265 return ret_type(
266 cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit(
267 Val.release()));
268}
269
270// cast_or_null<X> - Functionally identical to cast, except that a null value is
271// accepted.
272//
273template <class X, class Y>
274LLVM_NODISCARD[[clang::warn_unused_result]] inline
275 typename std::enable_if<!is_simple_type<Y>::value,
276 typename cast_retty<X, const Y>::ret_type>::type
277 cast_or_null(const Y &Val) {
278 if (!Val)
279 return nullptr;
280 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 280, __extension__ __PRETTY_FUNCTION__))
;
281 return cast<X>(Val);
282}
283
284template <class X, class Y>
285LLVM_NODISCARD[[clang::warn_unused_result]] inline
286 typename std::enable_if<!is_simple_type<Y>::value,
287 typename cast_retty<X, Y>::ret_type>::type
288 cast_or_null(Y &Val) {
289 if (!Val)
290 return nullptr;
291 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 291, __extension__ __PRETTY_FUNCTION__))
;
292 return cast<X>(Val);
293}
294
295template <class X, class Y>
296LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
297cast_or_null(Y *Val) {
298 if (!Val) return nullptr;
299 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 299, __extension__ __PRETTY_FUNCTION__))
;
300 return cast<X>(Val);
301}
302
303template <class X, class Y>
304inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
305cast_or_null(std::unique_ptr<Y> &&Val) {
306 if (!Val)
307 return nullptr;
308 return cast<X>(std::move(Val));
309}
310
311// dyn_cast<X> - Return the argument parameter cast to the specified type. This
312// casting operator returns null if the argument is of the wrong type, so it can
313// be used to test for a type as well as cast if successful. This should be
314// used in the context of an if statement like this:
315//
316// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
317//
318
319template <class X, class Y>
320LLVM_NODISCARD[[clang::warn_unused_result]] inline
321 typename std::enable_if<!is_simple_type<Y>::value,
322 typename cast_retty<X, const Y>::ret_type>::type
323 dyn_cast(const Y &Val) {
324 return isa<X>(Val) ? cast<X>(Val) : nullptr;
325}
326
327template <class X, class Y>
328LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) {
329 return isa<X>(Val) ? cast<X>(Val) : nullptr;
330}
331
332template <class X, class Y>
333LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) {
334 return isa<X>(Val) ? cast<X>(Val) : nullptr;
335}
336
337// dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null
338// value is accepted.
339//
340template <class X, class Y>
341LLVM_NODISCARD[[clang::warn_unused_result]] inline
342 typename std::enable_if<!is_simple_type<Y>::value,
343 typename cast_retty<X, const Y>::ret_type>::type
344 dyn_cast_or_null(const Y &Val) {
345 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
346}
347
348template <class X, class Y>
349LLVM_NODISCARD[[clang::warn_unused_result]] inline
350 typename std::enable_if<!is_simple_type<Y>::value,
351 typename cast_retty<X, Y>::ret_type>::type
352 dyn_cast_or_null(Y &Val) {
353 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
354}
355
356template <class X, class Y>
357LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
358dyn_cast_or_null(Y *Val) {
359 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
360}
361
362// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
363// taking ownership of the input pointer iff isa<X>(Val) is true. If the
364// cast is successful, From refers to nullptr on exit and the casted value
365// is returned. If the cast is unsuccessful, the function returns nullptr
366// and From is unchanged.
367template <class X, class Y>
368LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val)
369 -> decltype(cast<X>(Val)) {
370 if (!isa<X>(Val))
371 return nullptr;
372 return cast<X>(std::move(Val));
373}
374
375template <class X, class Y>
376LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val)
377 -> decltype(cast<X>(Val)) {
378 return unique_dyn_cast<X, Y>(Val);
379}
380
381// dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that
382// a null value is accepted.
383template <class X, class Y>
384LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val)
385 -> decltype(cast<X>(Val)) {
386 if (!Val)
387 return nullptr;
388 return unique_dyn_cast<X, Y>(Val);
389}
390
391template <class X, class Y>
392LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val)
393 -> decltype(cast<X>(Val)) {
394 return unique_dyn_cast_or_null<X, Y>(Val);
395}
396
397} // end namespace llvm
398
399#endif // LLVM_SUPPORT_CASTING_H

/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h

1//===- llvm/Instructions.h - Instruction subclass definitions ---*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file exposes the class definitions of all of the subclasses of the
11// Instruction class. This is meant to be an easy way to get access to all
12// instruction subclasses.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_IR_INSTRUCTIONS_H
17#define LLVM_IR_INSTRUCTIONS_H
18
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/None.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/ADT/Twine.h"
25#include "llvm/ADT/iterator.h"
26#include "llvm/ADT/iterator_range.h"
27#include "llvm/IR/Attributes.h"
28#include "llvm/IR/BasicBlock.h"
29#include "llvm/IR/CallingConv.h"
30#include "llvm/IR/Constant.h"
31#include "llvm/IR/DerivedTypes.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/InstrTypes.h"
34#include "llvm/IR/Instruction.h"
35#include "llvm/IR/OperandTraits.h"
36#include "llvm/IR/Type.h"
37#include "llvm/IR/Use.h"
38#include "llvm/IR/User.h"
39#include "llvm/IR/Value.h"
40#include "llvm/Support/AtomicOrdering.h"
41#include "llvm/Support/Casting.h"
42#include "llvm/Support/ErrorHandling.h"
43#include <cassert>
44#include <cstddef>
45#include <cstdint>
46#include <iterator>
47
48namespace llvm {
49
50class APInt;
51class ConstantInt;
52class DataLayout;
53class LLVMContext;
54
55//===----------------------------------------------------------------------===//
56// AllocaInst Class
57//===----------------------------------------------------------------------===//
58
59/// an instruction to allocate memory on the stack
60class AllocaInst : public UnaryInstruction {
61 Type *AllocatedType;
62
63protected:
64 // Note: Instruction needs to be a friend here to call cloneImpl.
65 friend class Instruction;
66
67 AllocaInst *cloneImpl() const;
68
69public:
70 explicit AllocaInst(Type *Ty, unsigned AddrSpace,
71 Value *ArraySize = nullptr,
72 const Twine &Name = "",
73 Instruction *InsertBefore = nullptr);
74 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
75 const Twine &Name, BasicBlock *InsertAtEnd);
76
77 AllocaInst(Type *Ty, unsigned AddrSpace,
78 const Twine &Name, Instruction *InsertBefore = nullptr);
79 AllocaInst(Type *Ty, unsigned AddrSpace,
80 const Twine &Name, BasicBlock *InsertAtEnd);
81
82 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
83 const Twine &Name = "", Instruction *InsertBefore = nullptr);
84 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
85 const Twine &Name, BasicBlock *InsertAtEnd);
86
87 /// Return true if there is an allocation size parameter to the allocation
88 /// instruction that is not 1.
89 bool isArrayAllocation() const;
90
91 /// Get the number of elements allocated. For a simple allocation of a single
92 /// element, this will return a constant 1 value.
93 const Value *getArraySize() const { return getOperand(0); }
94 Value *getArraySize() { return getOperand(0); }
95
96 /// Overload to return most specific pointer type.
97 PointerType *getType() const {
98 return cast<PointerType>(Instruction::getType());
99 }
100
101 /// Return the type that is being allocated by the instruction.
102 Type *getAllocatedType() const { return AllocatedType; }
103 /// for use only in special circumstances that need to generically
104 /// transform a whole instruction (eg: IR linking and vectorization).
105 void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
106
107 /// Return the alignment of the memory that is being allocated by the
108 /// instruction.
109 unsigned getAlignment() const {
110 return (1u << (getSubclassDataFromInstruction() & 31)) >> 1;
111 }
112 void setAlignment(unsigned Align);
113
114 /// Return true if this alloca is in the entry block of the function and is a
115 /// constant size. If so, the code generator will fold it into the
116 /// prolog/epilog code, so it is basically free.
117 bool isStaticAlloca() const;
118
119 /// Return true if this alloca is used as an inalloca argument to a call. Such
120 /// allocas are never considered static even if they are in the entry block.
121 bool isUsedWithInAlloca() const {
122 return getSubclassDataFromInstruction() & 32;
123 }
124
125 /// Specify whether this alloca is used to represent the arguments to a call.
126 void setUsedWithInAlloca(bool V) {
127 setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
128 (V ? 32 : 0));
129 }
130
131 /// Return true if this alloca is used as a swifterror argument to a call.
132 bool isSwiftError() const {
133 return getSubclassDataFromInstruction() & 64;
134 }
135
136 /// Specify whether this alloca is used to represent a swifterror.
137 void setSwiftError(bool V) {
138 setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) |
139 (V ? 64 : 0));
140 }
141
142 // Methods for support type inquiry through isa, cast, and dyn_cast:
143 static bool classof(const Instruction *I) {
144 return (I->getOpcode() == Instruction::Alloca);
145 }
146 static bool classof(const Value *V) {
147 return isa<Instruction>(V) && classof(cast<Instruction>(V));
148 }
149
150private:
151 // Shadow Instruction::setInstructionSubclassData with a private forwarding
152 // method so that subclasses cannot accidentally use it.
153 void setInstructionSubclassData(unsigned short D) {
154 Instruction::setInstructionSubclassData(D);
155 }
156};
157
158//===----------------------------------------------------------------------===//
159// LoadInst Class
160//===----------------------------------------------------------------------===//
161
162/// An instruction for reading from memory. This uses the SubclassData field in
163/// Value to store whether or not the load is volatile.
164class LoadInst : public UnaryInstruction {
165 void AssertOK();
166
167protected:
168 // Note: Instruction needs to be a friend here to call cloneImpl.
169 friend class Instruction;
170
171 LoadInst *cloneImpl() const;
172
173public:
174 LoadInst(Value *Ptr, const Twine &NameStr, Instruction *InsertBefore);
175 LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
176 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile = false,
177 Instruction *InsertBefore = nullptr);
178 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile = false,
179 Instruction *InsertBefore = nullptr)
180 : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
181 NameStr, isVolatile, InsertBefore) {}
182 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
183 BasicBlock *InsertAtEnd);
184 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
185 Instruction *InsertBefore = nullptr)
186 : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
187 NameStr, isVolatile, Align, InsertBefore) {}
188 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
189 unsigned Align, Instruction *InsertBefore = nullptr);
190 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
191 unsigned Align, BasicBlock *InsertAtEnd);
192 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
193 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
194 Instruction *InsertBefore = nullptr)
195 : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
196 NameStr, isVolatile, Align, Order, SSID, InsertBefore) {}
197 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
198 unsigned Align, AtomicOrdering Order,
199 SyncScope::ID SSID = SyncScope::System,
200 Instruction *InsertBefore = nullptr);
201 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
202 unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
203 BasicBlock *InsertAtEnd);
204 LoadInst(Value *Ptr, const char *NameStr, Instruction *InsertBefore);
205 LoadInst(Value *Ptr, const char *NameStr, BasicBlock *InsertAtEnd);
206 LoadInst(Type *Ty, Value *Ptr, const char *NameStr = nullptr,
207 bool isVolatile = false, Instruction *InsertBefore = nullptr);
208 explicit LoadInst(Value *Ptr, const char *NameStr = nullptr,
209 bool isVolatile = false,
210 Instruction *InsertBefore = nullptr)
211 : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
212 NameStr, isVolatile, InsertBefore) {}
213 LoadInst(Value *Ptr, const char *NameStr, bool isVolatile,
214 BasicBlock *InsertAtEnd);
215
216 /// Return true if this is a load from a volatile memory location.
217 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
218
219 /// Specify whether this is a volatile load or not.
220 void setVolatile(bool V) {
221 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
222 (V ? 1 : 0));
223 }
224
225 /// Return the alignment of the access that is being performed.
226 unsigned getAlignment() const {
227 return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
228 }
229
230 void setAlignment(unsigned Align);
231
232 /// Returns the ordering constraint of this load instruction.
233 AtomicOrdering getOrdering() const {
234 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
235 }
236
237 /// Sets the ordering constraint of this load instruction. May not be Release
238 /// or AcquireRelease.
239 void setOrdering(AtomicOrdering Ordering) {
240 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
241 ((unsigned)Ordering << 7));
242 }
243
244 /// Returns the synchronization scope ID of this load instruction.
245 SyncScope::ID getSyncScopeID() const {
246 return SSID;
247 }
248
249 /// Sets the synchronization scope ID of this load instruction.
250 void setSyncScopeID(SyncScope::ID SSID) {
251 this->SSID = SSID;
252 }
253
254 /// Sets the ordering constraint and the synchronization scope ID of this load
255 /// instruction.
256 void setAtomic(AtomicOrdering Ordering,
257 SyncScope::ID SSID = SyncScope::System) {
258 setOrdering(Ordering);
259 setSyncScopeID(SSID);
260 }
261
262 bool isSimple() const { return !isAtomic() && !isVolatile(); }
263
264 bool isUnordered() const {
265 return (getOrdering() == AtomicOrdering::NotAtomic ||
266 getOrdering() == AtomicOrdering::Unordered) &&
267 !isVolatile();
268 }
269
270 Value *getPointerOperand() { return getOperand(0); }
271 const Value *getPointerOperand() const { return getOperand(0); }
272 static unsigned getPointerOperandIndex() { return 0U; }
273 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
274
275 /// Returns the address space of the pointer operand.
276 unsigned getPointerAddressSpace() const {
277 return getPointerOperandType()->getPointerAddressSpace();
278 }
279
280 // Methods for support type inquiry through isa, cast, and dyn_cast:
281 static bool classof(const Instruction *I) {
282 return I->getOpcode() == Instruction::Load;
283 }
284 static bool classof(const Value *V) {
285 return isa<Instruction>(V) && classof(cast<Instruction>(V));
286 }
287
288private:
289 // Shadow Instruction::setInstructionSubclassData with a private forwarding
290 // method so that subclasses cannot accidentally use it.
291 void setInstructionSubclassData(unsigned short D) {
292 Instruction::setInstructionSubclassData(D);
293 }
294
295 /// The synchronization scope ID of this load instruction. Not quite enough
296 /// room in SubClassData for everything, so synchronization scope ID gets its
297 /// own field.
298 SyncScope::ID SSID;
299};
300
301//===----------------------------------------------------------------------===//
302// StoreInst Class
303//===----------------------------------------------------------------------===//
304
305/// An instruction for storing to memory.
306class StoreInst : public Instruction {
307 void AssertOK();
308
309protected:
310 // Note: Instruction needs to be a friend here to call cloneImpl.
311 friend class Instruction;
312
313 StoreInst *cloneImpl() const;
314
315public:
316 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
317 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
318 StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
319 Instruction *InsertBefore = nullptr);
320 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
321 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
322 unsigned Align, Instruction *InsertBefore = nullptr);
323 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
324 unsigned Align, BasicBlock *InsertAtEnd);
325 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
326 unsigned Align, AtomicOrdering Order,
327 SyncScope::ID SSID = SyncScope::System,
328 Instruction *InsertBefore = nullptr);
329 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
330 unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
331 BasicBlock *InsertAtEnd);
332
333 // allocate space for exactly two operands
334 void *operator new(size_t s) {
335 return User::operator new(s, 2);
336 }
337
338 /// Return true if this is a store to a volatile memory location.
339 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
340
341 /// Specify whether this is a volatile store or not.
342 void setVolatile(bool V) {
343 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
344 (V ? 1 : 0));
345 }
346
347 /// Transparently provide more efficient getOperand methods.
348 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
349
350 /// Return the alignment of the access that is being performed
351 unsigned getAlignment() const {
352 return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
353 }
354
355 void setAlignment(unsigned Align);
356
357 /// Returns the ordering constraint of this store instruction.
358 AtomicOrdering getOrdering() const {
359 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
360 }
361
362 /// Sets the ordering constraint of this store instruction. May not be
363 /// Acquire or AcquireRelease.
364 void setOrdering(AtomicOrdering Ordering) {
365 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
366 ((unsigned)Ordering << 7));
367 }
368
369 /// Returns the synchronization scope ID of this store instruction.
370 SyncScope::ID getSyncScopeID() const {
371 return SSID;
372 }
373
374 /// Sets the synchronization scope ID of this store instruction.
375 void setSyncScopeID(SyncScope::ID SSID) {
376 this->SSID = SSID;
377 }
378
379 /// Sets the ordering constraint and the synchronization scope ID of this
380 /// store instruction.
381 void setAtomic(AtomicOrdering Ordering,
382 SyncScope::ID SSID = SyncScope::System) {
383 setOrdering(Ordering);
384 setSyncScopeID(SSID);
385 }
386
387 bool isSimple() const { return !isAtomic() && !isVolatile(); }
388
389 bool isUnordered() const {
390 return (getOrdering() == AtomicOrdering::NotAtomic ||
391 getOrdering() == AtomicOrdering::Unordered) &&
392 !isVolatile();
393 }
394
395 Value *getValueOperand() { return getOperand(0); }
396 const Value *getValueOperand() const { return getOperand(0); }
397
398 Value *getPointerOperand() { return getOperand(1); }
399 const Value *getPointerOperand() const { return getOperand(1); }
400 static unsigned getPointerOperandIndex() { return 1U; }
401 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
402
403 /// Returns the address space of the pointer operand.
404 unsigned getPointerAddressSpace() const {
405 return getPointerOperandType()->getPointerAddressSpace();
406 }
407
408 // Methods for support type inquiry through isa, cast, and dyn_cast:
409 static bool classof(const Instruction *I) {
410 return I->getOpcode() == Instruction::Store;
411 }
412 static bool classof(const Value *V) {
413 return isa<Instruction>(V) && classof(cast<Instruction>(V));
414 }
415
416private:
417 // Shadow Instruction::setInstructionSubclassData with a private forwarding
418 // method so that subclasses cannot accidentally use it.
419 void setInstructionSubclassData(unsigned short D) {
420 Instruction::setInstructionSubclassData(D);
421 }
422
423 /// The synchronization scope ID of this store instruction. Not quite enough
424 /// room in SubClassData for everything, so synchronization scope ID gets its
425 /// own field.
426 SyncScope::ID SSID;
427};
428
429template <>
430struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
431};
432
433DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)StoreInst::op_iterator StoreInst::op_begin() { return OperandTraits
<StoreInst>::op_begin(this); } StoreInst::const_op_iterator
StoreInst::op_begin() const { return OperandTraits<StoreInst
>::op_begin(const_cast<StoreInst*>(this)); } StoreInst
::op_iterator StoreInst::op_end() { return OperandTraits<StoreInst
>::op_end(this); } StoreInst::const_op_iterator StoreInst::
op_end() const { return OperandTraits<StoreInst>::op_end
(const_cast<StoreInst*>(this)); } Value *StoreInst::getOperand
(unsigned i_nocapture) const { (static_cast <bool> (i_nocapture
< OperandTraits<StoreInst>::operands(this) &&
"getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 433, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<StoreInst>::op_begin(const_cast
<StoreInst*>(this))[i_nocapture].get()); } void StoreInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast
<bool> (i_nocapture < OperandTraits<StoreInst>
::operands(this) && "setOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 433, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
StoreInst>::op_begin(this)[i_nocapture] = Val_nocapture; }
unsigned StoreInst::getNumOperands() const { return OperandTraits
<StoreInst>::operands(this); } template <int Idx_nocapture
> Use &StoreInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
StoreInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
434
435//===----------------------------------------------------------------------===//
436// FenceInst Class
437//===----------------------------------------------------------------------===//
438
439/// An instruction for ordering other memory operations.
440class FenceInst : public Instruction {
441 void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
442
443protected:
444 // Note: Instruction needs to be a friend here to call cloneImpl.
445 friend class Instruction;
446
447 FenceInst *cloneImpl() const;
448
449public:
450 // Ordering may only be Acquire, Release, AcquireRelease, or
451 // SequentiallyConsistent.
452 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
453 SyncScope::ID SSID = SyncScope::System,
454 Instruction *InsertBefore = nullptr);
455 FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
456 BasicBlock *InsertAtEnd);
457
458 // allocate space for exactly zero operands
459 void *operator new(size_t s) {
460 return User::operator new(s, 0);
461 }
462
463 /// Returns the ordering constraint of this fence instruction.
464 AtomicOrdering getOrdering() const {
465 return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
466 }
467
468 /// Sets the ordering constraint of this fence instruction. May only be
469 /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
470 void setOrdering(AtomicOrdering Ordering) {
471 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
472 ((unsigned)Ordering << 1));
473 }
474
475 /// Returns the synchronization scope ID of this fence instruction.
476 SyncScope::ID getSyncScopeID() const {
477 return SSID;
478 }
479
480 /// Sets the synchronization scope ID of this fence instruction.
481 void setSyncScopeID(SyncScope::ID SSID) {
482 this->SSID = SSID;
483 }
484
485 // Methods for support type inquiry through isa, cast, and dyn_cast:
486 static bool classof(const Instruction *I) {
487 return I->getOpcode() == Instruction::Fence;
488 }
489 static bool classof(const Value *V) {
490 return isa<Instruction>(V) && classof(cast<Instruction>(V));
491 }
492
493private:
494 // Shadow Instruction::setInstructionSubclassData with a private forwarding
495 // method so that subclasses cannot accidentally use it.
496 void setInstructionSubclassData(unsigned short D) {
497 Instruction::setInstructionSubclassData(D);
498 }
499
500 /// The synchronization scope ID of this fence instruction. Not quite enough
501 /// room in SubClassData for everything, so synchronization scope ID gets its
502 /// own field.
503 SyncScope::ID SSID;
504};
505
506//===----------------------------------------------------------------------===//
507// AtomicCmpXchgInst Class
508//===----------------------------------------------------------------------===//
509
510/// an instruction that atomically checks whether a
511/// specified value is in a memory location, and, if it is, stores a new value
512/// there. Returns the value that was loaded.
513///
514class AtomicCmpXchgInst : public Instruction {
515 void Init(Value *Ptr, Value *Cmp, Value *NewVal,
516 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
517 SyncScope::ID SSID);
518
519protected:
520 // Note: Instruction needs to be a friend here to call cloneImpl.
521 friend class Instruction;
522
523 AtomicCmpXchgInst *cloneImpl() const;
524
525public:
526 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
527 AtomicOrdering SuccessOrdering,
528 AtomicOrdering FailureOrdering,
529 SyncScope::ID SSID, Instruction *InsertBefore = nullptr);
530 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
531 AtomicOrdering SuccessOrdering,
532 AtomicOrdering FailureOrdering,
533 SyncScope::ID SSID, BasicBlock *InsertAtEnd);
534
535 // allocate space for exactly three operands
536 void *operator new(size_t s) {
537 return User::operator new(s, 3);
538 }
539
540 /// Return true if this is a cmpxchg from a volatile memory
541 /// location.
542 ///
543 bool isVolatile() const {
544 return getSubclassDataFromInstruction() & 1;
545 }
546
547 /// Specify whether this is a volatile cmpxchg.
548 ///
549 void setVolatile(bool V) {
550 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
551 (unsigned)V);
552 }
553
554 /// Return true if this cmpxchg may spuriously fail.
555 bool isWeak() const {
556 return getSubclassDataFromInstruction() & 0x100;
557 }
558
559 void setWeak(bool IsWeak) {
560 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
561 (IsWeak << 8));
562 }
563
564 /// Transparently provide more efficient getOperand methods.
565 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
566
567 /// Returns the success ordering constraint of this cmpxchg instruction.
568 AtomicOrdering getSuccessOrdering() const {
569 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
570 }
571
572 /// Sets the success ordering constraint of this cmpxchg instruction.
573 void setSuccessOrdering(AtomicOrdering Ordering) {
574 assert(Ordering != AtomicOrdering::NotAtomic &&(static_cast <bool> (Ordering != AtomicOrdering::NotAtomic
&& "CmpXchg instructions can only be atomic.") ? void
(0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 575, __extension__ __PRETTY_FUNCTION__))
575 "CmpXchg instructions can only be atomic.")(static_cast <bool> (Ordering != AtomicOrdering::NotAtomic
&& "CmpXchg instructions can only be atomic.") ? void
(0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 575, __extension__ __PRETTY_FUNCTION__))
;
576 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
577 ((unsigned)Ordering << 2));
578 }
579
580 /// Returns the failure ordering constraint of this cmpxchg instruction.
581 AtomicOrdering getFailureOrdering() const {
582 return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
583 }
584
585 /// Sets the failure ordering constraint of this cmpxchg instruction.
586 void setFailureOrdering(AtomicOrdering Ordering) {
587 assert(Ordering != AtomicOrdering::NotAtomic &&(static_cast <bool> (Ordering != AtomicOrdering::NotAtomic
&& "CmpXchg instructions can only be atomic.") ? void
(0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 588, __extension__ __PRETTY_FUNCTION__))
588 "CmpXchg instructions can only be atomic.")(static_cast <bool> (Ordering != AtomicOrdering::NotAtomic
&& "CmpXchg instructions can only be atomic.") ? void
(0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 588, __extension__ __PRETTY_FUNCTION__))
;
589 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
590 ((unsigned)Ordering << 5));
591 }
592
593 /// Returns the synchronization scope ID of this cmpxchg instruction.
594 SyncScope::ID getSyncScopeID() const {
595 return SSID;
596 }
597
598 /// Sets the synchronization scope ID of this cmpxchg instruction.
599 void setSyncScopeID(SyncScope::ID SSID) {
600 this->SSID = SSID;
601 }
602
603 Value *getPointerOperand() { return getOperand(0); }
604 const Value *getPointerOperand() const { return getOperand(0); }
605 static unsigned getPointerOperandIndex() { return 0U; }
606
607 Value *getCompareOperand() { return getOperand(1); }
608 const Value *getCompareOperand() const { return getOperand(1); }
609
610 Value *getNewValOperand() { return getOperand(2); }
611 const Value *getNewValOperand() const { return getOperand(2); }
612
613 /// Returns the address space of the pointer operand.
614 unsigned getPointerAddressSpace() const {
615 return getPointerOperand()->getType()->getPointerAddressSpace();
616 }
617
618 /// Returns the strongest permitted ordering on failure, given the
619 /// desired ordering on success.
620 ///
621 /// If the comparison in a cmpxchg operation fails, there is no atomic store
622 /// so release semantics cannot be provided. So this function drops explicit
623 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
624 /// operation would remain SequentiallyConsistent.
625 static AtomicOrdering
626 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
627 switch (SuccessOrdering) {
628 default:
629 llvm_unreachable("invalid cmpxchg success ordering")::llvm::llvm_unreachable_internal("invalid cmpxchg success ordering"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 629)
;
630 case AtomicOrdering::Release:
631 case AtomicOrdering::Monotonic:
632 return AtomicOrdering::Monotonic;
633 case AtomicOrdering::AcquireRelease:
634 case AtomicOrdering::Acquire:
635 return AtomicOrdering::Acquire;
636 case AtomicOrdering::SequentiallyConsistent:
637 return AtomicOrdering::SequentiallyConsistent;
638 }
639 }
640
641 // Methods for support type inquiry through isa, cast, and dyn_cast:
642 static bool classof(const Instruction *I) {
643 return I->getOpcode() == Instruction::AtomicCmpXchg;
644 }
645 static bool classof(const Value *V) {
646 return isa<Instruction>(V) && classof(cast<Instruction>(V));
647 }
648
649private:
650 // Shadow Instruction::setInstructionSubclassData with a private forwarding
651 // method so that subclasses cannot accidentally use it.
652 void setInstructionSubclassData(unsigned short D) {
653 Instruction::setInstructionSubclassData(D);
654 }
655
656 /// The synchronization scope ID of this cmpxchg instruction. Not quite
657 /// enough room in SubClassData for everything, so synchronization scope ID
658 /// gets its own field.
659 SyncScope::ID SSID;
660};
661
662template <>
663struct OperandTraits<AtomicCmpXchgInst> :
664 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
665};
666
667DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)AtomicCmpXchgInst::op_iterator AtomicCmpXchgInst::op_begin() {
return OperandTraits<AtomicCmpXchgInst>::op_begin(this
); } AtomicCmpXchgInst::const_op_iterator AtomicCmpXchgInst::
op_begin() const { return OperandTraits<AtomicCmpXchgInst>
::op_begin(const_cast<AtomicCmpXchgInst*>(this)); } AtomicCmpXchgInst
::op_iterator AtomicCmpXchgInst::op_end() { return OperandTraits
<AtomicCmpXchgInst>::op_end(this); } AtomicCmpXchgInst::
const_op_iterator AtomicCmpXchgInst::op_end() const { return OperandTraits
<AtomicCmpXchgInst>::op_end(const_cast<AtomicCmpXchgInst
*>(this)); } Value *AtomicCmpXchgInst::getOperand(unsigned
i_nocapture) const { (static_cast <bool> (i_nocapture <
OperandTraits<AtomicCmpXchgInst>::operands(this) &&
"getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 667, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<AtomicCmpXchgInst>::op_begin
(const_cast<AtomicCmpXchgInst*>(this))[i_nocapture].get
()); } void AtomicCmpXchgInst::setOperand(unsigned i_nocapture
, Value *Val_nocapture) { (static_cast <bool> (i_nocapture
< OperandTraits<AtomicCmpXchgInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 667, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
AtomicCmpXchgInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned AtomicCmpXchgInst::getNumOperands() const { return
OperandTraits<AtomicCmpXchgInst>::operands(this); } template
<int Idx_nocapture> Use &AtomicCmpXchgInst::Op() {
return this->OpFrom<Idx_nocapture>(this); } template
<int Idx_nocapture> const Use &AtomicCmpXchgInst::
Op() const { return this->OpFrom<Idx_nocapture>(this
); }
668
669//===----------------------------------------------------------------------===//
670// AtomicRMWInst Class
671//===----------------------------------------------------------------------===//
672
673/// an instruction that atomically reads a memory location,
674/// combines it with another value, and then stores the result back. Returns
675/// the old value.
676///
677class AtomicRMWInst : public Instruction {
678protected:
679 // Note: Instruction needs to be a friend here to call cloneImpl.
680 friend class Instruction;
681
682 AtomicRMWInst *cloneImpl() const;
683
684public:
685 /// This enumeration lists the possible modifications atomicrmw can make. In
686 /// the descriptions, 'p' is the pointer to the instruction's memory location,
687 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
688 /// instruction. These instructions always return 'old'.
689 enum BinOp {
690 /// *p = v
691 Xchg,
692 /// *p = old + v
693 Add,
694 /// *p = old - v
695 Sub,
696 /// *p = old & v
697 And,
698 /// *p = ~(old & v)
699 Nand,
700 /// *p = old | v
701 Or,
702 /// *p = old ^ v
703 Xor,
704 /// *p = old >signed v ? old : v
705 Max,
706 /// *p = old <signed v ? old : v
707 Min,
708 /// *p = old >unsigned v ? old : v
709 UMax,
710 /// *p = old <unsigned v ? old : v
711 UMin,
712
713 FIRST_BINOP = Xchg,
714 LAST_BINOP = UMin,
715 BAD_BINOP
716 };
717
718 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
719 AtomicOrdering Ordering, SyncScope::ID SSID,
720 Instruction *InsertBefore = nullptr);
721 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
722 AtomicOrdering Ordering, SyncScope::ID SSID,
723 BasicBlock *InsertAtEnd);
724
725 // allocate space for exactly two operands
726 void *operator new(size_t s) {
727 return User::operator new(s, 2);
728 }
729
730 BinOp getOperation() const {
731 return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
732 }
733
734 void setOperation(BinOp Operation) {
735 unsigned short SubclassData = getSubclassDataFromInstruction();
736 setInstructionSubclassData((SubclassData & 31) |
737 (Operation << 5));
738 }
739
740 /// Return true if this is a RMW on a volatile memory location.
741 ///
742 bool isVolatile() const {
743 return getSubclassDataFromInstruction() & 1;
744 }
745
746 /// Specify whether this is a volatile RMW or not.
747 ///
748 void setVolatile(bool V) {
749 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
750 (unsigned)V);
751 }
752
753 /// Transparently provide more efficient getOperand methods.
754 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
755
756 /// Returns the ordering constraint of this rmw instruction.
757 AtomicOrdering getOrdering() const {
758 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
759 }
760
761 /// Sets the ordering constraint of this rmw instruction.
762 void setOrdering(AtomicOrdering Ordering) {
763 assert(Ordering != AtomicOrdering::NotAtomic &&(static_cast <bool> (Ordering != AtomicOrdering::NotAtomic
&& "atomicrmw instructions can only be atomic.") ? void
(0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 764, __extension__ __PRETTY_FUNCTION__))
764 "atomicrmw instructions can only be atomic.")(static_cast <bool> (Ordering != AtomicOrdering::NotAtomic
&& "atomicrmw instructions can only be atomic.") ? void
(0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 764, __extension__ __PRETTY_FUNCTION__))
;
765 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
766 ((unsigned)Ordering << 2));
767 }
768
769 /// Returns the synchronization scope ID of this rmw instruction.
770 SyncScope::ID getSyncScopeID() const {
771 return SSID;
772 }
773
774 /// Sets the synchronization scope ID of this rmw instruction.
775 void setSyncScopeID(SyncScope::ID SSID) {
776 this->SSID = SSID;
777 }
778
779 Value *getPointerOperand() { return getOperand(0); }
780 const Value *getPointerOperand() const { return getOperand(0); }
781 static unsigned getPointerOperandIndex() { return 0U; }
782
783 Value *getValOperand() { return getOperand(1); }
784 const Value *getValOperand() const { return getOperand(1); }
785
786 /// Returns the address space of the pointer operand.
787 unsigned getPointerAddressSpace() const {
788 return getPointerOperand()->getType()->getPointerAddressSpace();
789 }
790
791 // Methods for support type inquiry through isa, cast, and dyn_cast:
792 static bool classof(const Instruction *I) {
793 return I->getOpcode() == Instruction::AtomicRMW;
794 }
795 static bool classof(const Value *V) {
796 return isa<Instruction>(V) && classof(cast<Instruction>(V));
797 }
798
799private:
800 void Init(BinOp Operation, Value *Ptr, Value *Val,
801 AtomicOrdering Ordering, SyncScope::ID SSID);
802
803 // Shadow Instruction::setInstructionSubclassData with a private forwarding
804 // method so that subclasses cannot accidentally use it.
805 void setInstructionSubclassData(unsigned short D) {
806 Instruction::setInstructionSubclassData(D);
807 }
808
809 /// The synchronization scope ID of this rmw instruction. Not quite enough
810 /// room in SubClassData for everything, so synchronization scope ID gets its
811 /// own field.
812 SyncScope::ID SSID;
813};
814
815template <>
816struct OperandTraits<AtomicRMWInst>
817 : public FixedNumOperandTraits<AtomicRMWInst,2> {
818};
819
820DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)AtomicRMWInst::op_iterator AtomicRMWInst::op_begin() { return
OperandTraits<AtomicRMWInst>::op_begin(this); } AtomicRMWInst
::const_op_iterator AtomicRMWInst::op_begin() const { return OperandTraits
<AtomicRMWInst>::op_begin(const_cast<AtomicRMWInst*>
(this)); } AtomicRMWInst::op_iterator AtomicRMWInst::op_end()
{ return OperandTraits<AtomicRMWInst>::op_end(this); }
AtomicRMWInst::const_op_iterator AtomicRMWInst::op_end() const
{ return OperandTraits<AtomicRMWInst>::op_end(const_cast
<AtomicRMWInst*>(this)); } Value *AtomicRMWInst::getOperand
(unsigned i_nocapture) const { (static_cast <bool> (i_nocapture
< OperandTraits<AtomicRMWInst>::operands(this) &&
"getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 820, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<AtomicRMWInst>::op_begin(const_cast
<AtomicRMWInst*>(this))[i_nocapture].get()); } void AtomicRMWInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast
<bool> (i_nocapture < OperandTraits<AtomicRMWInst
>::operands(this) && "setOperand() out of range!")
? void (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 820, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
AtomicRMWInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned AtomicRMWInst::getNumOperands() const { return OperandTraits
<AtomicRMWInst>::operands(this); } template <int Idx_nocapture
> Use &AtomicRMWInst::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &AtomicRMWInst::Op() const { return this->OpFrom
<Idx_nocapture>(this); }
821
822//===----------------------------------------------------------------------===//
823// GetElementPtrInst Class
824//===----------------------------------------------------------------------===//
825
826// checkGEPType - Simple wrapper function to give a better assertion failure
827// message on bad indexes for a gep instruction.
828//
829inline Type *checkGEPType(Type *Ty) {
830 assert(Ty && "Invalid GetElementPtrInst indices for type!")(static_cast <bool> (Ty && "Invalid GetElementPtrInst indices for type!"
) ? void (0) : __assert_fail ("Ty && \"Invalid GetElementPtrInst indices for type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 830, __extension__ __PRETTY_FUNCTION__))
;
831 return Ty;
832}
833
834/// an instruction for type-safe pointer arithmetic to
835/// access elements of arrays and structs
836///
837class GetElementPtrInst : public Instruction {
838 Type *SourceElementType;
839 Type *ResultElementType;
840
841 GetElementPtrInst(const GetElementPtrInst &GEPI);
842
843 /// Constructors - Create a getelementptr instruction with a base pointer an
844 /// list of indices. The first ctor can optionally insert before an existing
845 /// instruction, the second appends the new instruction to the specified
846 /// BasicBlock.
847 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
848 ArrayRef<Value *> IdxList, unsigned Values,
849 const Twine &NameStr, Instruction *InsertBefore);
850 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
851 ArrayRef<Value *> IdxList, unsigned Values,
852 const Twine &NameStr, BasicBlock *InsertAtEnd);
853
854 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
855
856protected:
857 // Note: Instruction needs to be a friend here to call cloneImpl.
858 friend class Instruction;
859
860 GetElementPtrInst *cloneImpl() const;
861
862public:
863 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
864 ArrayRef<Value *> IdxList,
865 const Twine &NameStr = "",
866 Instruction *InsertBefore = nullptr) {
867 unsigned Values = 1 + unsigned(IdxList.size());
868 if (!PointeeType)
869 PointeeType =
870 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
871 else
872 assert((static_cast <bool> (PointeeType == cast<PointerType
>(Ptr->getType()->getScalarType())->getElementType
()) ? void (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 874, __extension__ __PRETTY_FUNCTION__))
873 PointeeType ==(static_cast <bool> (PointeeType == cast<PointerType
>(Ptr->getType()->getScalarType())->getElementType
()) ? void (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 874, __extension__ __PRETTY_FUNCTION__))
874 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())(static_cast <bool> (PointeeType == cast<PointerType
>(Ptr->getType()->getScalarType())->getElementType
()) ? void (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 874, __extension__ __PRETTY_FUNCTION__))
;
875 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
876 NameStr, InsertBefore);
877 }
878
879 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
880 ArrayRef<Value *> IdxList,
881 const Twine &NameStr,
882 BasicBlock *InsertAtEnd) {
883 unsigned Values = 1 + unsigned(IdxList.size());
884 if (!PointeeType)
885 PointeeType =
886 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
887 else
888 assert((static_cast <bool> (PointeeType == cast<PointerType
>(Ptr->getType()->getScalarType())->getElementType
()) ? void (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 890, __extension__ __PRETTY_FUNCTION__))
889 PointeeType ==(static_cast <bool> (PointeeType == cast<PointerType
>(Ptr->getType()->getScalarType())->getElementType
()) ? void (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 890, __extension__ __PRETTY_FUNCTION__))
890 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())(static_cast <bool> (PointeeType == cast<PointerType
>(Ptr->getType()->getScalarType())->getElementType
()) ? void (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 890, __extension__ __PRETTY_FUNCTION__))
;
891 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
892 NameStr, InsertAtEnd);
893 }
894
895 /// Create an "inbounds" getelementptr. See the documentation for the
896 /// "inbounds" flag in LangRef.html for details.
897 static GetElementPtrInst *CreateInBounds(Value *Ptr,
898 ArrayRef<Value *> IdxList,
899 const Twine &NameStr = "",
900 Instruction *InsertBefore = nullptr){
901 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
902 }
903
904 static GetElementPtrInst *
905 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
906 const Twine &NameStr = "",
907 Instruction *InsertBefore = nullptr) {
908 GetElementPtrInst *GEP =
909 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
910 GEP->setIsInBounds(true);
911 return GEP;
912 }
913
914 static GetElementPtrInst *CreateInBounds(Value *Ptr,
915 ArrayRef<Value *> IdxList,
916 const Twine &NameStr,
917 BasicBlock *InsertAtEnd) {
918 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
919 }
920
921 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
922 ArrayRef<Value *> IdxList,
923 const Twine &NameStr,
924 BasicBlock *InsertAtEnd) {
925 GetElementPtrInst *GEP =
926 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
927 GEP->setIsInBounds(true);
928 return GEP;
929 }
930
931 /// Transparently provide more efficient getOperand methods.
932 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
933
934 Type *getSourceElementType() const { return SourceElementType; }
935
936 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
937 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
938
939 Type *getResultElementType() const {
940 assert(ResultElementType ==(static_cast <bool> (ResultElementType == cast<PointerType
>(getType()->getScalarType())->getElementType()) ? void
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 941, __extension__ __PRETTY_FUNCTION__))
941 cast<PointerType>(getType()->getScalarType())->getElementType())(static_cast <bool> (ResultElementType == cast<PointerType
>(getType()->getScalarType())->getElementType()) ? void
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 941, __extension__ __PRETTY_FUNCTION__))
;
942 return ResultElementType;
943 }
944
945 /// Returns the address space of this instruction's pointer type.
946 unsigned getAddressSpace() const {
947 // Note that this is always the same as the pointer operand's address space
948 // and that is cheaper to compute, so cheat here.
949 return getPointerAddressSpace();
950 }
951
952 /// Returns the type of the element that would be loaded with
953 /// a load instruction with the specified parameters.
954 ///
955 /// Null is returned if the indices are invalid for the specified
956 /// pointer type.
957 ///
958 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
959 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
960 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
961
962 inline op_iterator idx_begin() { return op_begin()+1; }
963 inline const_op_iterator idx_begin() const { return op_begin()+1; }
964 inline op_iterator idx_end() { return op_end(); }
965 inline const_op_iterator idx_end() const { return op_end(); }
966
967 inline iterator_range<op_iterator> indices() {
968 return make_range(idx_begin(), idx_end());
969 }
970
971 inline iterator_range<const_op_iterator> indices() const {
972 return make_range(idx_begin(), idx_end());
973 }
974
975 Value *getPointerOperand() {
976 return getOperand(0);
977 }
978 const Value *getPointerOperand() const {
979 return getOperand(0);
980 }
981 static unsigned getPointerOperandIndex() {
982 return 0U; // get index for modifying correct operand.
983 }
984
985 /// Method to return the pointer operand as a
986 /// PointerType.
987 Type *getPointerOperandType() const {
988 return getPointerOperand()->getType();
989 }
990
991 /// Returns the address space of the pointer operand.
992 unsigned getPointerAddressSpace() const {
993 return getPointerOperandType()->getPointerAddressSpace();
994 }
995
996 /// Returns the pointer type returned by the GEP
997 /// instruction, which may be a vector of pointers.
998 static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
999 return getGEPReturnType(
1000 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(),
1001 Ptr, IdxList);
1002 }
1003 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1004 ArrayRef<Value *> IdxList) {
1005 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1006 Ptr->getType()->getPointerAddressSpace());
1007 // Vector GEP
1008 if (Ptr->getType()->isVectorTy()) {
1009 unsigned NumElem = Ptr->getType()->getVectorNumElements();
1010 return VectorType::get(PtrTy, NumElem);
1011 }
1012 for (Value *Index : IdxList)
1013 if (Index->getType()->isVectorTy()) {
1014 unsigned NumElem = Index->getType()->getVectorNumElements();
1015 return VectorType::get(PtrTy, NumElem);
1016 }
1017 // Scalar GEP
1018 return PtrTy;
1019 }
1020
1021 unsigned getNumIndices() const { // Note: always non-negative
1022 return getNumOperands() - 1;
1023 }
1024
1025 bool hasIndices() const {
1026 return getNumOperands() > 1;
1027 }
1028
1029 /// Return true if all of the indices of this GEP are
1030 /// zeros. If so, the result pointer and the first operand have the same
1031 /// value, just potentially different types.
1032 bool hasAllZeroIndices() const;
1033
1034 /// Return true if all of the indices of this GEP are
1035 /// constant integers. If so, the result pointer and the first operand have
1036 /// a constant offset between them.
1037 bool hasAllConstantIndices() const;
1038
1039 /// Set or clear the inbounds flag on this GEP instruction.
1040 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1041 void setIsInBounds(bool b = true);
1042
1043 /// Determine whether the GEP has the inbounds flag.
1044 bool isInBounds() const;
1045
1046 /// Accumulate the constant address offset of this GEP if possible.
1047 ///
1048 /// This routine accepts an APInt into which it will accumulate the constant
1049 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1050 /// all-constant, it returns false and the value of the offset APInt is
1051 /// undefined (it is *not* preserved!). The APInt passed into this routine
1052 /// must be at least as wide as the IntPtr type for the address space of
1053 /// the base GEP pointer.
1054 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1055
1056 // Methods for support type inquiry through isa, cast, and dyn_cast:
1057 static bool classof(const Instruction *I) {
1058 return (I->getOpcode() == Instruction::GetElementPtr);
1059 }
1060 static bool classof(const Value *V) {
1061 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1062 }
1063};
1064
1065template <>
1066struct OperandTraits<GetElementPtrInst> :
1067 public VariadicOperandTraits<GetElementPtrInst, 1> {
1068};
1069
1070GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1071 ArrayRef<Value *> IdxList, unsigned Values,
1072 const Twine &NameStr,
1073 Instruction *InsertBefore)
1074 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1075 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1076 Values, InsertBefore),
1077 SourceElementType(PointeeType),
1078 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1079 assert(ResultElementType ==(static_cast <bool> (ResultElementType == cast<PointerType
>(getType()->getScalarType())->getElementType()) ? void
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1080, __extension__ __PRETTY_FUNCTION__))
1080 cast<PointerType>(getType()->getScalarType())->getElementType())(static_cast <bool> (ResultElementType == cast<PointerType
>(getType()->getScalarType())->getElementType()) ? void
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1080, __extension__ __PRETTY_FUNCTION__))
;
1081 init(Ptr, IdxList, NameStr);
1082}
1083
1084GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1085 ArrayRef<Value *> IdxList, unsigned Values,
1086 const Twine &NameStr,
1087 BasicBlock *InsertAtEnd)
1088 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1089 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1090 Values, InsertAtEnd),
1091 SourceElementType(PointeeType),
1092 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1093 assert(ResultElementType ==(static_cast <bool> (ResultElementType == cast<PointerType
>(getType()->getScalarType())->getElementType()) ? void
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1094, __extension__ __PRETTY_FUNCTION__))
1094 cast<PointerType>(getType()->getScalarType())->getElementType())(static_cast <bool> (ResultElementType == cast<PointerType
>(getType()->getScalarType())->getElementType()) ? void
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1094, __extension__ __PRETTY_FUNCTION__))
;
1095 init(Ptr, IdxList, NameStr);
1096}
1097
1098DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)GetElementPtrInst::op_iterator GetElementPtrInst::op_begin() {
return OperandTraits<GetElementPtrInst>::op_begin(this
); } GetElementPtrInst::const_op_iterator GetElementPtrInst::
op_begin() const { return OperandTraits<GetElementPtrInst>
::op_begin(const_cast<GetElementPtrInst*>(this)); } GetElementPtrInst
::op_iterator GetElementPtrInst::op_end() { return OperandTraits
<GetElementPtrInst>::op_end(this); } GetElementPtrInst::
const_op_iterator GetElementPtrInst::op_end() const { return OperandTraits
<GetElementPtrInst>::op_end(const_cast<GetElementPtrInst
*>(this)); } Value *GetElementPtrInst::getOperand(unsigned
i_nocapture) const { (static_cast <bool> (i_nocapture <
OperandTraits<GetElementPtrInst>::operands(this) &&
"getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1098, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<GetElementPtrInst>::op_begin
(const_cast<GetElementPtrInst*>(this))[i_nocapture].get
()); } void GetElementPtrInst::setOperand(unsigned i_nocapture
, Value *Val_nocapture) { (static_cast <bool> (i_nocapture
< OperandTraits<GetElementPtrInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1098, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
GetElementPtrInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned GetElementPtrInst::getNumOperands() const { return
OperandTraits<GetElementPtrInst>::operands(this); } template
<int Idx_nocapture> Use &GetElementPtrInst::Op() {
return this->OpFrom<Idx_nocapture>(this); } template
<int Idx_nocapture> const Use &GetElementPtrInst::
Op() const { return this->OpFrom<Idx_nocapture>(this
); }
1099
1100//===----------------------------------------------------------------------===//
1101// ICmpInst Class
1102//===----------------------------------------------------------------------===//
1103
1104/// This instruction compares its operands according to the predicate given
1105/// to the constructor. It only operates on integers or pointers. The operands
1106/// must be identical types.
1107/// Represent an integer comparison operator.
1108class ICmpInst: public CmpInst {
1109 void AssertOK() {
1110 assert(isIntPredicate() &&(static_cast <bool> (isIntPredicate() && "Invalid ICmp predicate value"
) ? void (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1111, __extension__ __PRETTY_FUNCTION__))
1111 "Invalid ICmp predicate value")(static_cast <bool> (isIntPredicate() && "Invalid ICmp predicate value"
) ? void (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1111, __extension__ __PRETTY_FUNCTION__))
;
1112 assert(getOperand(0)->getType() == getOperand(1)->getType() &&(static_cast <bool> (getOperand(0)->getType() == getOperand
(1)->getType() && "Both operands to ICmp instruction are not of the same type!"
) ? void (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1113, __extension__ __PRETTY_FUNCTION__))
1113 "Both operands to ICmp instruction are not of the same type!")(static_cast <bool> (getOperand(0)->getType() == getOperand
(1)->getType() && "Both operands to ICmp instruction are not of the same type!"
) ? void (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1113, __extension__ __PRETTY_FUNCTION__))
;
1114 // Check that the operands are the right type
1115 assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||(static_cast <bool> ((getOperand(0)->getType()->isIntOrIntVectorTy
() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
"Invalid operand types for ICmp instruction") ? void (0) : __assert_fail
("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1117, __extension__ __PRETTY_FUNCTION__))
1116 getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&(static_cast <bool> ((getOperand(0)->getType()->isIntOrIntVectorTy
() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
"Invalid operand types for ICmp instruction") ? void (0) : __assert_fail
("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1117, __extension__ __PRETTY_FUNCTION__))
1117 "Invalid operand types for ICmp instruction")(static_cast <bool> ((getOperand(0)->getType()->isIntOrIntVectorTy
() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
"Invalid operand types for ICmp instruction") ? void (0) : __assert_fail
("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1117, __extension__ __PRETTY_FUNCTION__))
;
1118 }
1119
1120protected:
1121 // Note: Instruction needs to be a friend here to call cloneImpl.
1122 friend class Instruction;
1123
1124 /// Clone an identical ICmpInst
1125 ICmpInst *cloneImpl() const;
1126
1127public:
1128 /// Constructor with insert-before-instruction semantics.
1129 ICmpInst(
1130 Instruction *InsertBefore, ///< Where to insert
1131 Predicate pred, ///< The predicate to use for the comparison
1132 Value *LHS, ///< The left-hand-side of the expression
1133 Value *RHS, ///< The right-hand-side of the expression
1134 const Twine &NameStr = "" ///< Name of the instruction
1135 ) : CmpInst(makeCmpResultType(LHS->getType()),
1136 Instruction::ICmp, pred, LHS, RHS, NameStr,
1137 InsertBefore) {
1138#ifndef NDEBUG
1139 AssertOK();
1140#endif
1141 }
1142
1143 /// Constructor with insert-at-end semantics.
1144 ICmpInst(
1145 BasicBlock &InsertAtEnd, ///< Block to insert into.
1146 Predicate pred, ///< The predicate to use for the comparison
1147 Value *LHS, ///< The left-hand-side of the expression
1148 Value *RHS, ///< The right-hand-side of the expression
1149 const Twine &NameStr = "" ///< Name of the instruction
1150 ) : CmpInst(makeCmpResultType(LHS->getType()),
1151 Instruction::ICmp, pred, LHS, RHS, NameStr,
1152 &InsertAtEnd) {
1153#ifndef NDEBUG
1154 AssertOK();
1155#endif
1156 }
1157
1158 /// Constructor with no-insertion semantics
1159 ICmpInst(
1160 Predicate pred, ///< The predicate to use for the comparison
1161 Value *LHS, ///< The left-hand-side of the expression
1162 Value *RHS, ///< The right-hand-side of the expression
1163 const Twine &NameStr = "" ///< Name of the instruction
1164 ) : CmpInst(makeCmpResultType(LHS->getType()),
1165 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1166#ifndef NDEBUG
1167 AssertOK();
1168#endif
1169 }
1170
1171 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1172 /// @returns the predicate that would be the result if the operand were
1173 /// regarded as signed.
1174 /// Return the signed version of the predicate
1175 Predicate getSignedPredicate() const {
1176 return getSignedPredicate(getPredicate());
1177 }
1178
1179 /// This is a static version that you can use without an instruction.
1180 /// Return the signed version of the predicate.
1181 static Predicate getSignedPredicate(Predicate pred);
1182
1183 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1184 /// @returns the predicate that would be the result if the operand were
1185 /// regarded as unsigned.
1186 /// Return the unsigned version of the predicate
1187 Predicate getUnsignedPredicate() const {
1188 return getUnsignedPredicate(getPredicate());
1189 }
1190
1191 /// This is a static version that you can use without an instruction.
1192 /// Return the unsigned version of the predicate.
1193 static Predicate getUnsignedPredicate(Predicate pred);
1194
1195 /// Return true if this predicate is either EQ or NE. This also
1196 /// tests for commutativity.
1197 static bool isEquality(Predicate P) {
1198 return P == ICMP_EQ || P == ICMP_NE;
1199 }
1200
1201 /// Return true if this predicate is either EQ or NE. This also
1202 /// tests for commutativity.
1203 bool isEquality() const {
1204 return isEquality(getPredicate());
1205 }
1206
1207 /// @returns true if the predicate of this ICmpInst is commutative
1208 /// Determine if this relation is commutative.
1209 bool isCommutative() const { return isEquality(); }
1210
1211 /// Return true if the predicate is relational (not EQ or NE).
1212 ///
1213 bool isRelational() const {
1214 return !isEquality();
1215 }
1216
1217 /// Return true if the predicate is relational (not EQ or NE).
1218 ///
1219 static bool isRelational(Predicate P) {
1220 return !isEquality(P);
1221 }
1222
1223 /// Exchange the two operands to this instruction in such a way that it does
1224 /// not modify the semantics of the instruction. The predicate value may be
1225 /// changed to retain the same result if the predicate is order dependent
1226 /// (e.g. ult).
1227 /// Swap operands and adjust predicate.
1228 void swapOperands() {
1229 setPredicate(getSwappedPredicate());
1230 Op<0>().swap(Op<1>());
1231 }
1232
1233 // Methods for support type inquiry through isa, cast, and dyn_cast:
1234 static bool classof(const Instruction *I) {
1235 return I->getOpcode() == Instruction::ICmp;
1236 }
1237 static bool classof(const Value *V) {
1238 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1239 }
1240};
1241
1242//===----------------------------------------------------------------------===//
1243// FCmpInst Class
1244//===----------------------------------------------------------------------===//
1245
1246/// This instruction compares its operands according to the predicate given
1247/// to the constructor. It only operates on floating point values or packed
1248/// vectors of floating point values. The operands must be identical types.
1249/// Represents a floating point comparison operator.
1250class FCmpInst: public CmpInst {
1251 void AssertOK() {
1252 assert(isFPPredicate() && "Invalid FCmp predicate value")(static_cast <bool> (isFPPredicate() && "Invalid FCmp predicate value"
) ? void (0) : __assert_fail ("isFPPredicate() && \"Invalid FCmp predicate value\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1252, __extension__ __PRETTY_FUNCTION__))
;
1253 assert(getOperand(0)->getType() == getOperand(1)->getType() &&(static_cast <bool> (getOperand(0)->getType() == getOperand
(1)->getType() && "Both operands to FCmp instruction are not of the same type!"
) ? void (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1254, __extension__ __PRETTY_FUNCTION__))
1254 "Both operands to FCmp instruction are not of the same type!")(static_cast <bool> (getOperand(0)->getType() == getOperand
(1)->getType() && "Both operands to FCmp instruction are not of the same type!"
) ? void (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1254, __extension__ __PRETTY_FUNCTION__))
;
1255 // Check that the operands are the right type
1256 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&(static_cast <bool> (getOperand(0)->getType()->isFPOrFPVectorTy
() && "Invalid operand types for FCmp instruction") ?
void (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1257, __extension__ __PRETTY_FUNCTION__))
1257 "Invalid operand types for FCmp instruction")(static_cast <bool> (getOperand(0)->getType()->isFPOrFPVectorTy
() && "Invalid operand types for FCmp instruction") ?
void (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1257, __extension__ __PRETTY_FUNCTION__))
;
1258 }
1259
1260protected:
1261 // Note: Instruction needs to be a friend here to call cloneImpl.
1262 friend class Instruction;
1263
1264 /// Clone an identical FCmpInst
1265 FCmpInst *cloneImpl() const;
1266
1267public:
1268 /// Constructor with insert-before-instruction semantics.
1269 FCmpInst(
1270 Instruction *InsertBefore, ///< Where to insert
1271 Predicate pred, ///< The predicate to use for the comparison
1272 Value *LHS, ///< The left-hand-side of the expression
1273 Value *RHS, ///< The right-hand-side of the expression
1274 const Twine &NameStr = "" ///< Name of the instruction
1275 ) : CmpInst(makeCmpResultType(LHS->getType()),
1276 Instruction::FCmp, pred, LHS, RHS, NameStr,
1277 InsertBefore) {
1278 AssertOK();
1279 }
1280
1281 /// Constructor with insert-at-end semantics.
1282 FCmpInst(
1283 BasicBlock &InsertAtEnd, ///< Block to insert into.
1284 Predicate pred, ///< The predicate to use for the comparison
1285 Value *LHS, ///< The left-hand-side of the expression
1286 Value *RHS, ///< The right-hand-side of the expression
1287 const Twine &NameStr = "" ///< Name of the instruction
1288 ) : CmpInst(makeCmpResultType(LHS->getType()),
1289 Instruction::FCmp, pred, LHS, RHS, NameStr,
1290 &InsertAtEnd) {
1291 AssertOK();
1292 }
1293
1294 /// Constructor with no-insertion semantics
1295 FCmpInst(
1296 Predicate pred, ///< The predicate to use for the comparison
1297 Value *LHS, ///< The left-hand-side of the expression
1298 Value *RHS, ///< The right-hand-side of the expression
1299 const Twine &NameStr = "" ///< Name of the instruction
1300 ) : CmpInst(makeCmpResultType(LHS->getType()),
1301 Instruction::FCmp, pred, LHS, RHS, NameStr) {
1302 AssertOK();
1303 }
1304
1305 /// @returns true if the predicate of this instruction is EQ or NE.
1306 /// Determine if this is an equality predicate.
1307 static bool isEquality(Predicate Pred) {
1308 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1309 Pred == FCMP_UNE;
1310 }
1311
1312 /// @returns true if the predicate of this instruction is EQ or NE.
1313 /// Determine if this is an equality predicate.
1314 bool isEquality() const { return isEquality(getPredicate()); }
1315
1316 /// @returns true if the predicate of this instruction is commutative.
1317 /// Determine if this is a commutative predicate.
1318 bool isCommutative() const {
1319 return isEquality() ||
1320 getPredicate() == FCMP_FALSE ||
1321 getPredicate() == FCMP_TRUE ||
1322 getPredicate() == FCMP_ORD ||
1323 getPredicate() == FCMP_UNO;
1324 }
1325
1326 /// @returns true if the predicate is relational (not EQ or NE).
1327 /// Determine if this a relational predicate.
1328 bool isRelational() const { return !isEquality(); }
1329
1330 /// Exchange the two operands to this instruction in such a way that it does
1331 /// not modify the semantics of the instruction. The predicate value may be
1332 /// changed to retain the same result if the predicate is order dependent
1333 /// (e.g. ult).
1334 /// Swap operands and adjust predicate.
1335 void swapOperands() {
1336 setPredicate(getSwappedPredicate());
1337 Op<0>().swap(Op<1>());
1338 }
1339
1340 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1341 static bool classof(const Instruction *I) {
1342 return I->getOpcode() == Instruction::FCmp;
1343 }
1344 static bool classof(const Value *V) {
1345 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1346 }
1347};
1348
1349//===----------------------------------------------------------------------===//
1350/// This class represents a function call, abstracting a target
1351/// machine's calling convention. This class uses low bit of the SubClassData
1352/// field to indicate whether or not this is a tail call. The rest of the bits
1353/// hold the calling convention of the call.
1354///
1355class CallInst : public Instruction,
1356 public OperandBundleUser<CallInst, User::op_iterator> {
1357 friend class OperandBundleUser<CallInst, User::op_iterator>;
1358
1359 AttributeList Attrs; ///< parameter attributes for call
1360 FunctionType *FTy;
1361
1362 CallInst(const CallInst &CI);
1363
1364 /// Construct a CallInst given a range of arguments.
1365 /// Construct a CallInst from a range of arguments
1366 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1367 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1368 Instruction *InsertBefore);
1369
1370 inline CallInst(Value *Func, ArrayRef<Value *> Args,
1371 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1372 Instruction *InsertBefore)
1373 : CallInst(cast<FunctionType>(
1374 cast<PointerType>(Func->getType())->getElementType()),
1375 Func, Args, Bundles, NameStr, InsertBefore) {}
1376
1377 inline CallInst(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr,
1378 Instruction *InsertBefore)
1379 : CallInst(Func, Args, None, NameStr, InsertBefore) {}
1380
1381 /// Construct a CallInst given a range of arguments.
1382 /// Construct a CallInst from a range of arguments
1383 inline CallInst(Value *Func, ArrayRef<Value *> Args,
1384 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1385 BasicBlock *InsertAtEnd);
1386
1387 explicit CallInst(Value *F, const Twine &NameStr,
1388 Instruction *InsertBefore);
1389
1390 CallInst(Value *F, const Twine &NameStr, BasicBlock *InsertAtEnd);
1391
1392 void init(Value *Func, ArrayRef<Value *> Args,
1393 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
1394 init(cast<FunctionType>(
1395 cast<PointerType>(Func->getType())->getElementType()),
1396 Func, Args, Bundles, NameStr);
1397 }
1398 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1399 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1400 void init(Value *Func, const Twine &NameStr);
1401
1402 bool hasDescriptor() const { return HasDescriptor; }
1403
1404protected:
1405 // Note: Instruction needs to be a friend here to call cloneImpl.
1406 friend class Instruction;
1407
1408 CallInst *cloneImpl() const;
1409
1410public:
1411 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1412 ArrayRef<OperandBundleDef> Bundles = None,
1413 const Twine &NameStr = "",
1414 Instruction *InsertBefore = nullptr) {
1415 return Create(cast<FunctionType>(
1416 cast<PointerType>(Func->getType())->getElementType()),
1417 Func, Args, Bundles, NameStr, InsertBefore);
1418 }
1419
1420 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1421 const Twine &NameStr,
1422 Instruction *InsertBefore = nullptr) {
1423 return Create(cast<FunctionType>(
1424 cast<PointerType>(Func->getType())->getElementType()),
1425 Func, Args, None, NameStr, InsertBefore);
1426 }
1427
1428 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1429 const Twine &NameStr,
1430 Instruction *InsertBefore = nullptr) {
1431 return new (unsigned(Args.size() + 1))
1432 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1433 }
1434
1435 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1436 ArrayRef<OperandBundleDef> Bundles = None,
1437 const Twine &NameStr = "",
1438 Instruction *InsertBefore = nullptr) {
1439 const unsigned TotalOps =
1440 unsigned(Args.size()) + CountBundleInputs(Bundles) + 1;
1441 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1442
1443 return new (TotalOps, DescriptorBytes)
1444 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1445 }
1446
1447 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1448 ArrayRef<OperandBundleDef> Bundles,
1449 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1450 const unsigned TotalOps =
1451 unsigned(Args.size()) + CountBundleInputs(Bundles) + 1;
1452 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1453
1454 return new (TotalOps, DescriptorBytes)
1455 CallInst(Func, Args, Bundles, NameStr, InsertAtEnd);
1456 }
1457
1458 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1459 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1460 return new (unsigned(Args.size() + 1))
1461 CallInst(Func, Args, None, NameStr, InsertAtEnd);
1462 }
1463
1464 static CallInst *Create(Value *F, const Twine &NameStr = "",
1465 Instruction *InsertBefore = nullptr) {
1466 return new(1) CallInst(F, NameStr, InsertBefore);
1467 }
1468
1469 static CallInst *Create(Value *F, const Twine &NameStr,
1470 BasicBlock *InsertAtEnd) {
1471 return new(1) CallInst(F, NameStr, InsertAtEnd);
1472 }
1473
1474 /// Create a clone of \p CI with a different set of operand bundles and
1475 /// insert it before \p InsertPt.
1476 ///
1477 /// The returned call instruction is identical \p CI in every way except that
1478 /// the operand bundles for the new instruction are set to the operand bundles
1479 /// in \p Bundles.
1480 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1481 Instruction *InsertPt = nullptr);
1482
1483 /// Generate the IR for a call to malloc:
1484 /// 1. Compute the malloc call's argument as the specified type's size,
1485 /// possibly multiplied by the array size if the array size is not
1486 /// constant 1.
1487 /// 2. Call malloc with that argument.
1488 /// 3. Bitcast the result of the malloc call to the specified type.
1489 static Instruction *CreateMalloc(Instruction *InsertBefore,
1490 Type *IntPtrTy, Type *AllocTy,
1491 Value *AllocSize, Value *ArraySize = nullptr,
1492 Function* MallocF = nullptr,
1493 const Twine &Name = "");
1494 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd,
1495 Type *IntPtrTy, Type *AllocTy,
1496 Value *AllocSize, Value *ArraySize = nullptr,
1497 Function* MallocF = nullptr,
1498 const Twine &Name = "");
1499 static Instruction *CreateMalloc(Instruction *InsertBefore,
1500 Type *IntPtrTy, Type *AllocTy,
1501 Value *AllocSize, Value *ArraySize = nullptr,
1502 ArrayRef<OperandBundleDef> Bundles = None,
1503 Function* MallocF = nullptr,
1504 const Twine &Name = "");
1505 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd,
1506 Type *IntPtrTy, Type *AllocTy,
1507 Value *AllocSize, Value *ArraySize = nullptr,
1508 ArrayRef<OperandBundleDef> Bundles = None,
1509 Function* MallocF = nullptr,
1510 const Twine &Name = "");
1511 /// Generate the IR for a call to the builtin free function.
1512 static Instruction *CreateFree(Value *Source,
1513 Instruction *InsertBefore);
1514 static Instruction *CreateFree(Value *Source,
1515 BasicBlock *InsertAtEnd);
1516 static Instruction *CreateFree(Value *Source,
1517 ArrayRef<OperandBundleDef> Bundles,
1518 Instruction *InsertBefore);
1519 static Instruction *CreateFree(Value *Source,
1520 ArrayRef<OperandBundleDef> Bundles,
1521 BasicBlock *InsertAtEnd);
1522
1523 FunctionType *getFunctionType() const { return FTy; }
1524
1525 void mutateFunctionType(FunctionType *FTy) {
1526 mutateType(FTy->getReturnType());
1527 this->FTy = FTy;
1528 }
1529
1530 // Note that 'musttail' implies 'tail'.
1531 enum TailCallKind { TCK_None = 0, TCK_Tail = 1, TCK_MustTail = 2,
1532 TCK_NoTail = 3 };
1533 TailCallKind getTailCallKind() const {
1534 return TailCallKind(getSubclassDataFromInstruction() & 3);
1535 }
1536
1537 bool isTailCall() const {
1538 unsigned Kind = getSubclassDataFromInstruction() & 3;
1539 return Kind == TCK_Tail || Kind == TCK_MustTail;
1540 }
1541
1542 bool isMustTailCall() const {
1543 return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1544 }
1545
1546 bool isNoTailCall() const {
1547 return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1548 }
1549
1550 void setTailCall(bool isTC = true) {
1551 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1552 unsigned(isTC ? TCK_Tail : TCK_None));
1553 }
1554
1555 void setTailCallKind(TailCallKind TCK) {
1556 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1557 unsigned(TCK));
1558 }
1559
1560 /// Provide fast operand accessors
1561 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
1562
1563 /// Return the number of call arguments.
1564 ///
1565 unsigned getNumArgOperands() const {
1566 return getNumOperands() - getNumTotalBundleOperands() - 1;
1567 }
1568
1569 /// getArgOperand/setArgOperand - Return/set the i-th call argument.
1570 ///
1571 Value *getArgOperand(unsigned i) const {
1572 assert(i < getNumArgOperands() && "Out of bounds!")(static_cast <bool> (i < getNumArgOperands() &&
"Out of bounds!") ? void (0) : __assert_fail ("i < getNumArgOperands() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1572, __extension__ __PRETTY_FUNCTION__))
;
1573 return getOperand(i);
1574 }
1575 void setArgOperand(unsigned i, Value *v) {
1576 assert(i < getNumArgOperands() && "Out of bounds!")(static_cast <bool> (i < getNumArgOperands() &&
"Out of bounds!") ? void (0) : __assert_fail ("i < getNumArgOperands() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1576, __extension__ __PRETTY_FUNCTION__))
;
1577 setOperand(i, v);
1578 }
1579
1580 /// Return the iterator pointing to the beginning of the argument list.
1581 op_iterator arg_begin() { return op_begin(); }
1582
1583 /// Return the iterator pointing to the end of the argument list.
1584 op_iterator arg_end() {
1585 // [ call args ], [ operand bundles ], callee
1586 return op_end() - getNumTotalBundleOperands() - 1;
1587 }
1588
1589 /// Iteration adapter for range-for loops.
1590 iterator_range<op_iterator> arg_operands() {
1591 return make_range(arg_begin(), arg_end());
1592 }
1593
1594 /// Return the iterator pointing to the beginning of the argument list.
1595 const_op_iterator arg_begin() const { return op_begin(); }
1596
1597 /// Return the iterator pointing to the end of the argument list.
1598 const_op_iterator arg_end() const {
1599 // [ call args ], [ operand bundles ], callee
1600 return op_end() - getNumTotalBundleOperands() - 1;
1601 }
1602
1603 /// Iteration adapter for range-for loops.
1604 iterator_range<const_op_iterator> arg_operands() const {
1605 return make_range(arg_begin(), arg_end());
1606 }
1607
1608 /// Wrappers for getting the \c Use of a call argument.
1609 const Use &getArgOperandUse(unsigned i) const {
1610 assert(i < getNumArgOperands() && "Out of bounds!")(static_cast <bool> (i < getNumArgOperands() &&
"Out of bounds!") ? void (0) : __assert_fail ("i < getNumArgOperands() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1610, __extension__ __PRETTY_FUNCTION__))
;
1611 return getOperandUse(i);
1612 }
1613 Use &getArgOperandUse(unsigned i) {
1614 assert(i < getNumArgOperands() && "Out of bounds!")(static_cast <bool> (i < getNumArgOperands() &&
"Out of bounds!") ? void (0) : __assert_fail ("i < getNumArgOperands() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1614, __extension__ __PRETTY_FUNCTION__))
;
1615 return getOperandUse(i);
1616 }
1617
1618 /// If one of the arguments has the 'returned' attribute, return its
1619 /// operand value. Otherwise, return nullptr.
1620 Value *getReturnedArgOperand() const;
1621
1622 /// getCallingConv/setCallingConv - Get or set the calling convention of this
1623 /// function call.
1624 CallingConv::ID getCallingConv() const {
1625 return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 2);
1626 }
1627 void setCallingConv(CallingConv::ID CC) {
1628 auto ID = static_cast<unsigned>(CC);
1629 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention")(static_cast <bool> (!(ID & ~CallingConv::MaxID) &&
"Unsupported calling convention") ? void (0) : __assert_fail
("!(ID & ~CallingConv::MaxID) && \"Unsupported calling convention\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1629, __extension__ __PRETTY_FUNCTION__))
;
1630 setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
1631 (ID << 2));
1632 }
1633
1634 /// Return the parameter attributes for this call.
1635 ///
1636 AttributeList getAttributes() const { return Attrs; }
1637
1638 /// Set the parameter attributes for this call.
1639 ///
1640 void setAttributes(AttributeList A) { Attrs = A; }
1641
1642 /// adds the attribute to the list of attributes.
1643 void addAttribute(unsigned i, Attribute::AttrKind Kind);
1644
1645 /// adds the attribute to the list of attributes.
1646 void addAttribute(unsigned i, Attribute Attr);
1647
1648 /// Adds the attribute to the indicated argument
1649 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
1650
1651 /// Adds the attribute to the indicated argument
1652 void addParamAttr(unsigned ArgNo, Attribute Attr);
1653
1654 /// removes the attribute from the list of attributes.
1655 void removeAttribute(unsigned i, Attribute::AttrKind Kind);
1656
1657 /// removes the attribute from the list of attributes.
1658 void removeAttribute(unsigned i, StringRef Kind);
1659
1660 /// Removes the attribute from the given argument
1661 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
1662
1663 /// Removes the attribute from the given argument
1664 void removeParamAttr(unsigned ArgNo, StringRef Kind);
1665
1666 /// adds the dereferenceable attribute to the list of attributes.
1667 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
1668
1669 /// adds the dereferenceable_or_null attribute to the list of
1670 /// attributes.
1671 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
1672
1673 /// Determine whether this call has the given attribute.
1674 bool hasFnAttr(Attribute::AttrKind Kind) const {
1675 assert(Kind != Attribute::NoBuiltin &&(static_cast <bool> (Kind != Attribute::NoBuiltin &&
"Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin"
) ? void (0) : __assert_fail ("Kind != Attribute::NoBuiltin && \"Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1676, __extension__ __PRETTY_FUNCTION__))
1676 "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin")(static_cast <bool> (Kind != Attribute::NoBuiltin &&
"Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin"
) ? void (0) : __assert_fail ("Kind != Attribute::NoBuiltin && \"Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1676, __extension__ __PRETTY_FUNCTION__))
;
1677 return hasFnAttrImpl(Kind);
1678 }
1679
1680 /// Determine whether this call has the given attribute.
1681 bool hasFnAttr(StringRef Kind) const {
1682 return hasFnAttrImpl(Kind);
1683 }
1684
1685 /// Determine whether the return value has the given attribute.
1686 bool hasRetAttr(Attribute::AttrKind Kind) const;
1687
1688 /// Determine whether the argument or parameter has the given attribute.
1689 bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
1690
1691 /// Get the attribute of a given kind at a position.
1692 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
1693 return getAttributes().getAttribute(i, Kind);
1694 }
1695
1696 /// Get the attribute of a given kind at a position.
1697 Attribute getAttribute(unsigned i, StringRef Kind) const {
1698 return getAttributes().getAttribute(i, Kind);
1699 }
1700
1701 /// Get the attribute of a given kind from a given arg
1702 Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
1703 assert(ArgNo < getNumArgOperands() && "Out of bounds")(static_cast <bool> (ArgNo < getNumArgOperands() &&
"Out of bounds") ? void (0) : __assert_fail ("ArgNo < getNumArgOperands() && \"Out of bounds\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1703, __extension__ __PRETTY_FUNCTION__))
;
1704 return getAttributes().getParamAttr(ArgNo, Kind);
1705 }
1706
1707 /// Get the attribute of a given kind from a given arg
1708 Attribute getParamAttr(unsigned ArgNo, StringRef Kind) const {
1709 assert(ArgNo < getNumArgOperands() && "Out of bounds")(static_cast <bool> (ArgNo < getNumArgOperands() &&
"Out of bounds") ? void (0) : __assert_fail ("ArgNo < getNumArgOperands() && \"Out of bounds\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1709, __extension__ __PRETTY_FUNCTION__))
;
1710 return getAttributes().getParamAttr(ArgNo, Kind);
1711 }
1712
1713 /// Return true if the data operand at index \p i has the attribute \p
1714 /// A.
1715 ///
1716 /// Data operands include call arguments and values used in operand bundles,
1717 /// but does not include the callee operand. This routine dispatches to the
1718 /// underlying AttributeList or the OperandBundleUser as appropriate.
1719 ///
1720 /// The index \p i is interpreted as
1721 ///
1722 /// \p i == Attribute::ReturnIndex -> the return value
1723 /// \p i in [1, arg_size + 1) -> argument number (\p i - 1)
1724 /// \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
1725 /// (\p i - 1) in the operand list.
1726 bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const;
1727
1728 /// Extract the alignment of the return value.
1729 unsigned getRetAlignment() const { return Attrs.getRetAlignment(); }
1730
1731 /// Extract the alignment for a call or parameter (0=unknown).
1732 unsigned getParamAlignment(unsigned ArgNo) const {
1733 return Attrs.getParamAlignment(ArgNo);
1734 }
1735
1736 /// Extract the number of dereferenceable bytes for a call or
1737 /// parameter (0=unknown).
1738 uint64_t getDereferenceableBytes(unsigned i) const {
1739 return Attrs.getDereferenceableBytes(i);
1740 }
1741
1742 /// Extract the number of dereferenceable_or_null bytes for a call or
1743 /// parameter (0=unknown).
1744 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
1745 return Attrs.getDereferenceableOrNullBytes(i);
1746 }
1747
1748 /// @brief Determine if the return value is marked with NoAlias attribute.
1749 bool returnDoesNotAlias() const {
1750 return Attrs.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
1751 }
1752
1753 /// Return true if the call should not be treated as a call to a
1754 /// builtin.
1755 bool isNoBuiltin() const {
1756 return hasFnAttrImpl(Attribute::NoBuiltin) &&
1757 !hasFnAttrImpl(Attribute::Builtin);
1758 }
1759
1760 /// Determine if the call requires strict floating point semantics.
1761 bool isStrictFP() const { return hasFnAttr(Attribute::StrictFP); }
1762
1763 /// Return true if the call should not be inlined.
1764 bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1765 void setIsNoInline() {
1766 addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
1767 }
1768
1769 /// Return true if the call can return twice
1770 bool canReturnTwice() const {
1771 return hasFnAttr(Attribute::ReturnsTwice);
1772 }
1773 void setCanReturnTwice() {
1774 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1775 }
1776
1777 /// Determine if the call does not access memory.
1778 bool doesNotAccessMemory() const {
1779 return hasFnAttr(Attribute::ReadNone);
1780 }
1781 void setDoesNotAccessMemory() {
1782 addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
1783 }
1784
1785 /// Determine if the call does not access or only reads memory.
1786 bool onlyReadsMemory() const {
1787 return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1788 }
1789 void setOnlyReadsMemory() {
1790 addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
1791 }
1792
1793 /// Determine if the call does not access or only writes memory.
1794 bool doesNotReadMemory() const {
1795 return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
1796 }
1797 void setDoesNotReadMemory() {
1798 addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
1799 }
1800
1801 /// @brief Determine if the call can access memmory only using pointers based
1802 /// on its arguments.
1803 bool onlyAccessesArgMemory() const {
1804 return hasFnAttr(Attribute::ArgMemOnly);
1805 }
1806 void setOnlyAccessesArgMemory() {
1807 addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
1808 }
1809
1810 /// @brief Determine if the function may only access memory that is
1811 /// inaccessible from the IR.
1812 bool onlyAccessesInaccessibleMemory() const {
1813 return hasFnAttr(Attribute::InaccessibleMemOnly);
1814 }
1815 void setOnlyAccessesInaccessibleMemory() {
1816 addAttribute(AttributeList::FunctionIndex, Attribute::InaccessibleMemOnly);
1817 }
1818
1819 /// @brief Determine if the function may only access memory that is
1820 /// either inaccessible from the IR or pointed to by its arguments.
1821 bool onlyAccessesInaccessibleMemOrArgMem() const {
1822 return hasFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
1823 }
1824 void setOnlyAccessesInaccessibleMemOrArgMem() {
1825 addAttribute(AttributeList::FunctionIndex, Attribute::InaccessibleMemOrArgMemOnly);
1826 }
1827
1828 /// Determine if the call cannot return.
1829 bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1830 void setDoesNotReturn() {
1831 addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
1832 }
1833
1834 /// Determine if the call cannot unwind.
1835 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1836 void setDoesNotThrow() {
1837 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
1838 }
1839
1840 /// Determine if the call cannot be duplicated.
1841 bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
1842 void setCannotDuplicate() {
1843 addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
1844 }
1845
1846 /// Determine if the call is convergent
1847 bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
1848 void setConvergent() {
1849 addAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1850 }
1851 void setNotConvergent() {
1852 removeAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1853 }
1854
1855 /// Determine if the call returns a structure through first
1856 /// pointer argument.
1857 bool hasStructRetAttr() const {
1858 if (getNumArgOperands() == 0)
1859 return false;
1860
1861 // Be friendly and also check the callee.
1862 return paramHasAttr(0, Attribute::StructRet);
1863 }
1864
1865 /// Determine if any call argument is an aggregate passed by value.
1866 bool hasByValArgument() const {
1867 return Attrs.hasAttrSomewhere(Attribute::ByVal);
1868 }
1869
1870 /// Return the function called, or null if this is an
1871 /// indirect function invocation.
1872 ///
1873 Function *getCalledFunction() const {
1874 return dyn_cast<Function>(Op<-1>());
1875 }
1876
1877 /// Get a pointer to the function that is invoked by this
1878 /// instruction.
1879 const Value *getCalledValue() const { return Op<-1>(); }
1880 Value *getCalledValue() { return Op<-1>(); }
1881
1882 /// Set the function called.
1883 void setCalledFunction(Value* Fn) {
1884 setCalledFunction(
1885 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
1886 Fn);
1887 }
1888 void setCalledFunction(FunctionType *FTy, Value *Fn) {
1889 this->FTy = FTy;
1890 assert(FTy == cast<FunctionType>((static_cast <bool> (FTy == cast<FunctionType>( cast
<PointerType>(Fn->getType())->getElementType())) ?
void (0) : __assert_fail ("FTy == cast<FunctionType>( cast<PointerType>(Fn->getType())->getElementType())"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1891, __extension__ __PRETTY_FUNCTION__))
1891 cast<PointerType>(Fn->getType())->getElementType()))(static_cast <bool> (FTy == cast<FunctionType>( cast
<PointerType>(Fn->getType())->getElementType())) ?
void (0) : __assert_fail ("FTy == cast<FunctionType>( cast<PointerType>(Fn->getType())->getElementType())"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1891, __extension__ __PRETTY_FUNCTION__))
;
1892 Op<-1>() = Fn;
1893 }
1894
1895 /// Check if this call is an inline asm statement.
1896 bool isInlineAsm() const {
1897 return isa<InlineAsm>(Op<-1>());
1898 }
1899
1900 // Methods for support type inquiry through isa, cast, and dyn_cast:
1901 static bool classof(const Instruction *I) {
1902 return I->getOpcode() == Instruction::Call;
20
Calling 'Instruction::getOpcode'
23
Returning from 'Instruction::getOpcode'
24
Assuming the condition is true
1903 }
1904 static bool classof(const Value *V) {
1905 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1906 }
1907
1908private:
1909 template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
1910 if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
1911 return true;
1912
1913 // Operand bundles override attributes on the called function, but don't
1914 // override attributes directly present on the call instruction.
1915 if (isFnAttrDisallowedByOpBundle(Kind))
1916 return false;
1917
1918 if (const Function *F = getCalledFunction())
1919 return F->getAttributes().hasAttribute(AttributeList::FunctionIndex,
1920 Kind);
1921 return false;
1922 }
1923
1924 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1925 // method so that subclasses cannot accidentally use it.
1926 void setInstructionSubclassData(unsigned short D) {
1927 Instruction::setInstructionSubclassData(D);
1928 }
1929};
1930
1931template <>
1932struct OperandTraits<CallInst> : public VariadicOperandTraits<CallInst, 1> {
1933};
1934
1935CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
1936 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1937 BasicBlock *InsertAtEnd)
1938 : Instruction(
1939 cast<FunctionType>(cast<PointerType>(Func->getType())
1940 ->getElementType())->getReturnType(),
1941 Instruction::Call, OperandTraits<CallInst>::op_end(this) -
1942 (Args.size() + CountBundleInputs(Bundles) + 1),
1943 unsigned(Args.size() + CountBundleInputs(Bundles) + 1), InsertAtEnd) {
1944 init(Func, Args, Bundles, NameStr);
1945}
1946
1947CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1948 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1949 Instruction *InsertBefore)
1950 : Instruction(Ty->getReturnType(), Instruction::Call,
1951 OperandTraits<CallInst>::op_end(this) -
1952 (Args.size() + CountBundleInputs(Bundles) + 1),
1953 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1954 InsertBefore) {
1955 init(Ty, Func, Args, Bundles, NameStr);
1956}
1957
1958// Note: if you get compile errors about private methods then
1959// please update your code to use the high-level operand
1960// interfaces. See line 943 above.
1961DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallInst, Value)CallInst::op_iterator CallInst::op_begin() { return OperandTraits
<CallInst>::op_begin(this); } CallInst::const_op_iterator
CallInst::op_begin() const { return OperandTraits<CallInst
>::op_begin(const_cast<CallInst*>(this)); } CallInst
::op_iterator CallInst::op_end() { return OperandTraits<CallInst
>::op_end(this); } CallInst::const_op_iterator CallInst::op_end
() const { return OperandTraits<CallInst>::op_end(const_cast
<CallInst*>(this)); } Value *CallInst::getOperand(unsigned
i_nocapture) const { (static_cast <bool> (i_nocapture <
OperandTraits<CallInst>::operands(this) && "getOperand() out of range!"
) ? void (0) : __assert_fail ("i_nocapture < OperandTraits<CallInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1961, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<CallInst>::op_begin(const_cast
<CallInst*>(this))[i_nocapture].get()); } void CallInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast
<bool> (i_nocapture < OperandTraits<CallInst>
::operands(this) && "setOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<CallInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1961, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
CallInst>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
CallInst::getNumOperands() const { return OperandTraits<CallInst
>::operands(this); } template <int Idx_nocapture> Use
&CallInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
CallInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
1962
1963//===----------------------------------------------------------------------===//
1964// SelectInst Class
1965//===----------------------------------------------------------------------===//
1966
1967/// This class represents the LLVM 'select' instruction.
1968///
1969class SelectInst : public Instruction {
1970 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1971 Instruction *InsertBefore)
1972 : Instruction(S1->getType(), Instruction::Select,
1973 &Op<0>(), 3, InsertBefore) {
1974 init(C, S1, S2);
1975 setName(NameStr);
1976 }
1977
1978 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1979 BasicBlock *InsertAtEnd)
1980 : Instruction(S1->getType(), Instruction::Select,
1981 &Op<0>(), 3, InsertAtEnd) {
1982 init(C, S1, S2);
1983 setName(NameStr);
1984 }
1985
1986 void init(Value *C, Value *S1, Value *S2) {
1987 assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select")(static_cast <bool> (!areInvalidOperands(C, S1, S2) &&
"Invalid operands for select") ? void (0) : __assert_fail ("!areInvalidOperands(C, S1, S2) && \"Invalid operands for select\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 1987, __extension__ __PRETTY_FUNCTION__))
;
1988 Op<0>() = C;
1989 Op<1>() = S1;
1990 Op<2>() = S2;
1991 }
1992
1993protected:
1994 // Note: Instruction needs to be a friend here to call cloneImpl.
1995 friend class Instruction;
1996
1997 SelectInst *cloneImpl() const;
1998
1999public:
2000 static SelectInst *Create(Value *C, Value *S1, Value *S2,
2001 const Twine &NameStr = "",
2002 Instruction *InsertBefore = nullptr,
2003 Instruction *MDFrom = nullptr) {
2004 SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
2005 if (MDFrom)
2006 Sel->copyMetadata(*MDFrom);
2007 return Sel;
2008 }
2009
2010 static SelectInst *Create(Value *C, Value *S1, Value *S2,
2011 const Twine &NameStr,
2012 BasicBlock *InsertAtEnd) {
2013 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
2014 }
2015
2016 const Value *getCondition() const { return Op<0>(); }
2017 const Value *getTrueValue() const { return Op<1>(); }
2018 const Value *getFalseValue() const { return Op<2>(); }
2019 Value *getCondition() { return Op<0>(); }
2020 Value *getTrueValue() { return Op<1>(); }
2021 Value *getFalseValue() { return Op<2>(); }
2022
2023 void setCondition(Value *V) { Op<0>() = V; }
2024 void setTrueValue(Value *V) { Op<1>() = V; }
2025 void setFalseValue(Value *V) { Op<2>() = V; }
2026
2027 /// Return a string if the specified operands are invalid
2028 /// for a select operation, otherwise return null.
2029 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
2030
2031 /// Transparently provide more efficient getOperand methods.
2032 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2033
2034 OtherOps getOpcode() const {
2035 return static_cast<OtherOps>(Instruction::getOpcode());
2036 }
2037
2038 // Methods for support type inquiry through isa, cast, and dyn_cast:
2039 static bool classof(const Instruction *I) {
2040 return I->getOpcode() == Instruction::Select;
2041 }
2042 static bool classof(const Value *V) {
2043 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2044 }
2045};
2046
2047template <>
2048struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
2049};
2050
2051DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)SelectInst::op_iterator SelectInst::op_begin() { return OperandTraits
<SelectInst>::op_begin(this); } SelectInst::const_op_iterator
SelectInst::op_begin() const { return OperandTraits<SelectInst
>::op_begin(const_cast<SelectInst*>(this)); } SelectInst
::op_iterator SelectInst::op_end() { return OperandTraits<
SelectInst>::op_end(this); } SelectInst::const_op_iterator
SelectInst::op_end() const { return OperandTraits<SelectInst
>::op_end(const_cast<SelectInst*>(this)); } Value *SelectInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<SelectInst>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2051, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<SelectInst>::op_begin(const_cast
<SelectInst*>(this))[i_nocapture].get()); } void SelectInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast
<bool> (i_nocapture < OperandTraits<SelectInst>
::operands(this) && "setOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2051, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
SelectInst>::op_begin(this)[i_nocapture] = Val_nocapture; }
unsigned SelectInst::getNumOperands() const { return OperandTraits
<SelectInst>::operands(this); } template <int Idx_nocapture
> Use &SelectInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
SelectInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
2052
2053//===----------------------------------------------------------------------===//
2054// VAArgInst Class
2055//===----------------------------------------------------------------------===//
2056
2057/// This class represents the va_arg llvm instruction, which returns
2058/// an argument of the specified type given a va_list and increments that list
2059///
2060class VAArgInst : public UnaryInstruction {
2061protected:
2062 // Note: Instruction needs to be a friend here to call cloneImpl.
2063 friend class Instruction;
2064
2065 VAArgInst *cloneImpl() const;
2066
2067public:
2068 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
2069 Instruction *InsertBefore = nullptr)
2070 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
2071 setName(NameStr);
2072 }
2073
2074 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
2075 BasicBlock *InsertAtEnd)
2076 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
2077 setName(NameStr);
2078 }
2079
2080 Value *getPointerOperand() { return getOperand(0); }
2081 const Value *getPointerOperand() const { return getOperand(0); }
2082 static unsigned getPointerOperandIndex() { return 0U; }
2083
2084 // Methods for support type inquiry through isa, cast, and dyn_cast:
2085 static bool classof(const Instruction *I) {
2086 return I->getOpcode() == VAArg;
2087 }
2088 static bool classof(const Value *V) {
2089 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2090 }
2091};
2092
2093//===----------------------------------------------------------------------===//
2094// ExtractElementInst Class
2095//===----------------------------------------------------------------------===//
2096
2097/// This instruction extracts a single (scalar)
2098/// element from a VectorType value
2099///
2100class ExtractElementInst : public Instruction {
2101 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
2102 Instruction *InsertBefore = nullptr);
2103 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
2104 BasicBlock *InsertAtEnd);
2105
2106protected:
2107 // Note: Instruction needs to be a friend here to call cloneImpl.
2108 friend class Instruction;
2109
2110 ExtractElementInst *cloneImpl() const;
2111
2112public:
2113 static ExtractElementInst *Create(Value *Vec, Value *Idx,
2114 const Twine &NameStr = "",
2115 Instruction *InsertBefore = nullptr) {
2116 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
2117 }
2118
2119 static ExtractElementInst *Create(Value *Vec, Value *Idx,
2120 const Twine &NameStr,
2121 BasicBlock *InsertAtEnd) {
2122 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
2123 }
2124
2125 /// Return true if an extractelement instruction can be
2126 /// formed with the specified operands.
2127 static bool isValidOperands(const Value *Vec, const Value *Idx);
2128
2129 Value *getVectorOperand() { return Op<0>(); }
2130 Value *getIndexOperand() { return Op<1>(); }
2131 const Value *getVectorOperand() const { return Op<0>(); }
2132 const Value *getIndexOperand() const { return Op<1>(); }
2133
2134 VectorType *getVectorOperandType() const {
2135 return cast<VectorType>(getVectorOperand()->getType());
2136 }
2137
2138 /// Transparently provide more efficient getOperand methods.
2139 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2140
2141 // Methods for support type inquiry through isa, cast, and dyn_cast:
2142 static bool classof(const Instruction *I) {
2143 return I->getOpcode() == Instruction::ExtractElement;
2144 }
2145 static bool classof(const Value *V) {
2146 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2147 }
2148};
2149
2150template <>
2151struct OperandTraits<ExtractElementInst> :
2152 public FixedNumOperandTraits<ExtractElementInst, 2> {
2153};
2154
2155DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)ExtractElementInst::op_iterator ExtractElementInst::op_begin(
) { return OperandTraits<ExtractElementInst>::op_begin(
this); } ExtractElementInst::const_op_iterator ExtractElementInst
::op_begin() const { return OperandTraits<ExtractElementInst
>::op_begin(const_cast<ExtractElementInst*>(this)); }
ExtractElementInst::op_iterator ExtractElementInst::op_end()
{ return OperandTraits<ExtractElementInst>::op_end(this
); } ExtractElementInst::const_op_iterator ExtractElementInst
::op_end() const { return OperandTraits<ExtractElementInst
>::op_end(const_cast<ExtractElementInst*>(this)); } Value
*ExtractElementInst::getOperand(unsigned i_nocapture) const {
(static_cast <bool> (i_nocapture < OperandTraits<
ExtractElementInst>::operands(this) && "getOperand() out of range!"
) ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2155, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<ExtractElementInst>::op_begin
(const_cast<ExtractElementInst*>(this))[i_nocapture].get
()); } void ExtractElementInst::setOperand(unsigned i_nocapture
, Value *Val_nocapture) { (static_cast <bool> (i_nocapture
< OperandTraits<ExtractElementInst>::operands(this)
&& "setOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2155, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
ExtractElementInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned ExtractElementInst::getNumOperands() const { return
OperandTraits<ExtractElementInst>::operands(this); } template
<int Idx_nocapture> Use &ExtractElementInst::Op() {
return this->OpFrom<Idx_nocapture>(this); } template
<int Idx_nocapture> const Use &ExtractElementInst::
Op() const { return this->OpFrom<Idx_nocapture>(this
); }
2156
2157//===----------------------------------------------------------------------===//
2158// InsertElementInst Class
2159//===----------------------------------------------------------------------===//
2160
2161/// This instruction inserts a single (scalar)
2162/// element into a VectorType value
2163///
2164class InsertElementInst : public Instruction {
2165 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
2166 const Twine &NameStr = "",
2167 Instruction *InsertBefore = nullptr);
2168 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
2169 BasicBlock *InsertAtEnd);
2170
2171protected:
2172 // Note: Instruction needs to be a friend here to call cloneImpl.
2173 friend class Instruction;
2174
2175 InsertElementInst *cloneImpl() const;
2176
2177public:
2178 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2179 const Twine &NameStr = "",
2180 Instruction *InsertBefore = nullptr) {
2181 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
2182 }
2183
2184 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2185 const Twine &NameStr,
2186 BasicBlock *InsertAtEnd) {
2187 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
2188 }
2189
2190 /// Return true if an insertelement instruction can be
2191 /// formed with the specified operands.
2192 static bool isValidOperands(const Value *Vec, const Value *NewElt,
2193 const Value *Idx);
2194
2195 /// Overload to return most specific vector type.
2196 ///
2197 VectorType *getType() const {
2198 return cast<VectorType>(Instruction::getType());
2199 }
2200
2201 /// Transparently provide more efficient getOperand methods.
2202 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2203
2204 // Methods for support type inquiry through isa, cast, and dyn_cast:
2205 static bool classof(const Instruction *I) {
2206 return I->getOpcode() == Instruction::InsertElement;
2207 }
2208 static bool classof(const Value *V) {
2209 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2210 }
2211};
2212
2213template <>
2214struct OperandTraits<InsertElementInst> :
2215 public FixedNumOperandTraits<InsertElementInst, 3> {
2216};
2217
2218DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)InsertElementInst::op_iterator InsertElementInst::op_begin() {
return OperandTraits<InsertElementInst>::op_begin(this
); } InsertElementInst::const_op_iterator InsertElementInst::
op_begin() const { return OperandTraits<InsertElementInst>
::op_begin(const_cast<InsertElementInst*>(this)); } InsertElementInst
::op_iterator InsertElementInst::op_end() { return OperandTraits
<InsertElementInst>::op_end(this); } InsertElementInst::
const_op_iterator InsertElementInst::op_end() const { return OperandTraits
<InsertElementInst>::op_end(const_cast<InsertElementInst
*>(this)); } Value *InsertElementInst::getOperand(unsigned
i_nocapture) const { (static_cast <bool> (i_nocapture <
OperandTraits<InsertElementInst>::operands(this) &&
"getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2218, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<InsertElementInst>::op_begin
(const_cast<InsertElementInst*>(this))[i_nocapture].get
()); } void InsertElementInst::setOperand(unsigned i_nocapture
, Value *Val_nocapture) { (static_cast <bool> (i_nocapture
< OperandTraits<InsertElementInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2218, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
InsertElementInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned InsertElementInst::getNumOperands() const { return
OperandTraits<InsertElementInst>::operands(this); } template
<int Idx_nocapture> Use &InsertElementInst::Op() {
return this->OpFrom<Idx_nocapture>(this); } template
<int Idx_nocapture> const Use &InsertElementInst::
Op() const { return this->OpFrom<Idx_nocapture>(this
); }
2219
2220//===----------------------------------------------------------------------===//
2221// ShuffleVectorInst Class
2222//===----------------------------------------------------------------------===//
2223
2224/// This instruction constructs a fixed permutation of two
2225/// input vectors.
2226///
2227class ShuffleVectorInst : public Instruction {
2228protected:
2229 // Note: Instruction needs to be a friend here to call cloneImpl.
2230 friend class Instruction;
2231
2232 ShuffleVectorInst *cloneImpl() const;
2233
2234public:
2235 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2236 const Twine &NameStr = "",
2237 Instruction *InsertBefor = nullptr);
2238 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2239 const Twine &NameStr, BasicBlock *InsertAtEnd);
2240
2241 // allocate space for exactly three operands
2242 void *operator new(size_t s) {
2243 return User::operator new(s, 3);
2244 }
2245
2246 /// Return true if a shufflevector instruction can be
2247 /// formed with the specified operands.
2248 static bool isValidOperands(const Value *V1, const Value *V2,
2249 const Value *Mask);
2250
2251 /// Overload to return most specific vector type.
2252 ///
2253 VectorType *getType() const {
2254 return cast<VectorType>(Instruction::getType());
2255 }
2256
2257 /// Transparently provide more efficient getOperand methods.
2258 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2259
2260 Constant *getMask() const {
2261 return cast<Constant>(getOperand(2));
2262 }
2263
2264 /// Return the shuffle mask value for the specified element of the mask.
2265 /// Return -1 if the element is undef.
2266 static int getMaskValue(Constant *Mask, unsigned Elt);
2267
2268 /// Return the shuffle mask value of this instruction for the given element
2269 /// index. Return -1 if the element is undef.
2270 int getMaskValue(unsigned Elt) const {
2271 return getMaskValue(getMask(), Elt);
2272 }
2273
2274 /// Convert the input shuffle mask operand to a vector of integers. Undefined
2275 /// elements of the mask are returned as -1.
2276 static void getShuffleMask(Constant *Mask, SmallVectorImpl<int> &Result);
2277
2278 /// Return the mask for this instruction as a vector of integers. Undefined
2279 /// elements of the mask are returned as -1.
2280 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2281 return getShuffleMask(getMask(), Result);
2282 }
2283
2284 SmallVector<int, 16> getShuffleMask() const {
2285 SmallVector<int, 16> Mask;
2286 getShuffleMask(Mask);
2287 return Mask;
2288 }
2289
2290 /// Change values in a shuffle permute mask assuming the two vector operands
2291 /// of length InVecNumElts have swapped position.
2292 static void commuteShuffleMask(MutableArrayRef<int> Mask,
2293 unsigned InVecNumElts) {
2294 for (int &Idx : Mask) {
2295 if (Idx == -1)
2296 continue;
2297 Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2298 assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&(static_cast <bool> (Idx >= 0 && Idx < (int
)InVecNumElts * 2 && "shufflevector mask index out of range"
) ? void (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2299, __extension__ __PRETTY_FUNCTION__))
2299 "shufflevector mask index out of range")(static_cast <bool> (Idx >= 0 && Idx < (int
)InVecNumElts * 2 && "shufflevector mask index out of range"
) ? void (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2299, __extension__ __PRETTY_FUNCTION__))
;
2300 }
2301 }
2302
2303 // Methods for support type inquiry through isa, cast, and dyn_cast:
2304 static bool classof(const Instruction *I) {
2305 return I->getOpcode() == Instruction::ShuffleVector;
2306 }
2307 static bool classof(const Value *V) {
2308 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2309 }
2310};
2311
2312template <>
2313struct OperandTraits<ShuffleVectorInst> :
2314 public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2315};
2316
2317DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)ShuffleVectorInst::op_iterator ShuffleVectorInst::op_begin() {
return OperandTraits<ShuffleVectorInst>::op_begin(this
); } ShuffleVectorInst::const_op_iterator ShuffleVectorInst::
op_begin() const { return OperandTraits<ShuffleVectorInst>
::op_begin(const_cast<ShuffleVectorInst*>(this)); } ShuffleVectorInst
::op_iterator ShuffleVectorInst::op_end() { return OperandTraits
<ShuffleVectorInst>::op_end(this); } ShuffleVectorInst::
const_op_iterator ShuffleVectorInst::op_end() const { return OperandTraits
<ShuffleVectorInst>::op_end(const_cast<ShuffleVectorInst
*>(this)); } Value *ShuffleVectorInst::getOperand(unsigned
i_nocapture) const { (static_cast <bool> (i_nocapture <
OperandTraits<ShuffleVectorInst>::operands(this) &&
"getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2317, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<ShuffleVectorInst>::op_begin
(const_cast<ShuffleVectorInst*>(this))[i_nocapture].get
()); } void ShuffleVectorInst::setOperand(unsigned i_nocapture
, Value *Val_nocapture) { (static_cast <bool> (i_nocapture
< OperandTraits<ShuffleVectorInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2317, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
ShuffleVectorInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned ShuffleVectorInst::getNumOperands() const { return
OperandTraits<ShuffleVectorInst>::operands(this); } template
<int Idx_nocapture> Use &ShuffleVectorInst::Op() {
return this->OpFrom<Idx_nocapture>(this); } template
<int Idx_nocapture> const Use &ShuffleVectorInst::
Op() const { return this->OpFrom<Idx_nocapture>(this
); }
2318
2319//===----------------------------------------------------------------------===//
2320// ExtractValueInst Class
2321//===----------------------------------------------------------------------===//
2322
2323/// This instruction extracts a struct member or array
2324/// element value from an aggregate value.
2325///
2326class ExtractValueInst : public UnaryInstruction {
2327 SmallVector<unsigned, 4> Indices;
2328
2329 ExtractValueInst(const ExtractValueInst &EVI);
2330
2331 /// Constructors - Create a extractvalue instruction with a base aggregate
2332 /// value and a list of indices. The first ctor can optionally insert before
2333 /// an existing instruction, the second appends the new instruction to the
2334 /// specified BasicBlock.
2335 inline ExtractValueInst(Value *Agg,
2336 ArrayRef<unsigned> Idxs,
2337 const Twine &NameStr,
2338 Instruction *InsertBefore);
2339 inline ExtractValueInst(Value *Agg,
2340 ArrayRef<unsigned> Idxs,
2341 const Twine &NameStr, BasicBlock *InsertAtEnd);
2342
2343 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2344
2345protected:
2346 // Note: Instruction needs to be a friend here to call cloneImpl.
2347 friend class Instruction;
2348
2349 ExtractValueInst *cloneImpl() const;
2350
2351public:
2352 static ExtractValueInst *Create(Value *Agg,
2353 ArrayRef<unsigned> Idxs,
2354 const Twine &NameStr = "",
2355 Instruction *InsertBefore = nullptr) {
2356 return new
2357 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2358 }
2359
2360 static ExtractValueInst *Create(Value *Agg,
2361 ArrayRef<unsigned> Idxs,
2362 const Twine &NameStr,
2363 BasicBlock *InsertAtEnd) {
2364 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2365 }
2366
2367 /// Returns the type of the element that would be extracted
2368 /// with an extractvalue instruction with the specified parameters.
2369 ///
2370 /// Null is returned if the indices are invalid for the specified type.
2371 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2372
2373 using idx_iterator = const unsigned*;
2374
2375 inline idx_iterator idx_begin() const { return Indices.begin(); }
2376 inline idx_iterator idx_end() const { return Indices.end(); }
2377 inline iterator_range<idx_iterator> indices() const {
2378 return make_range(idx_begin(), idx_end());
2379 }
2380
2381 Value *getAggregateOperand() {
2382 return getOperand(0);
2383 }
2384 const Value *getAggregateOperand() const {
2385 return getOperand(0);
2386 }
2387 static unsigned getAggregateOperandIndex() {
2388 return 0U; // get index for modifying correct operand
2389 }
2390
2391 ArrayRef<unsigned> getIndices() const {
2392 return Indices;
2393 }
2394
2395 unsigned getNumIndices() const {
2396 return (unsigned)Indices.size();
2397 }
2398
2399 bool hasIndices() const {
2400 return true;
2401 }
2402
2403 // Methods for support type inquiry through isa, cast, and dyn_cast:
2404 static bool classof(const Instruction *I) {
2405 return I->getOpcode() == Instruction::ExtractValue;
2406 }
2407 static bool classof(const Value *V) {
2408 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2409 }
2410};
2411
2412ExtractValueInst::ExtractValueInst(Value *Agg,
2413 ArrayRef<unsigned> Idxs,
2414 const Twine &NameStr,
2415 Instruction *InsertBefore)
2416 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2417 ExtractValue, Agg, InsertBefore) {
2418 init(Idxs, NameStr);
2419}
2420
2421ExtractValueInst::ExtractValueInst(Value *Agg,
2422 ArrayRef<unsigned> Idxs,
2423 const Twine &NameStr,
2424 BasicBlock *InsertAtEnd)
2425 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2426 ExtractValue, Agg, InsertAtEnd) {
2427 init(Idxs, NameStr);
2428}
2429
2430//===----------------------------------------------------------------------===//
2431// InsertValueInst Class
2432//===----------------------------------------------------------------------===//
2433
2434/// This instruction inserts a struct field of array element
2435/// value into an aggregate value.
2436///
2437class InsertValueInst : public Instruction {
2438 SmallVector<unsigned, 4> Indices;
2439
2440 InsertValueInst(const InsertValueInst &IVI);
2441
2442 /// Constructors - Create a insertvalue instruction with a base aggregate
2443 /// value, a value to insert, and a list of indices. The first ctor can
2444 /// optionally insert before an existing instruction, the second appends
2445 /// the new instruction to the specified BasicBlock.
2446 inline InsertValueInst(Value *Agg, Value *Val,
2447 ArrayRef<unsigned> Idxs,
2448 const Twine &NameStr,
2449 Instruction *InsertBefore);
2450 inline InsertValueInst(Value *Agg, Value *Val,
2451 ArrayRef<unsigned> Idxs,
2452 const Twine &NameStr, BasicBlock *InsertAtEnd);
2453
2454 /// Constructors - These two constructors are convenience methods because one
2455 /// and two index insertvalue instructions are so common.
2456 InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2457 const Twine &NameStr = "",
2458 Instruction *InsertBefore = nullptr);
2459 InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2460 BasicBlock *InsertAtEnd);
2461
2462 void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2463 const Twine &NameStr);
2464
2465protected:
2466 // Note: Instruction needs to be a friend here to call cloneImpl.
2467 friend class Instruction;
2468
2469 InsertValueInst *cloneImpl() const;
2470
2471public:
2472 // allocate space for exactly two operands
2473 void *operator new(size_t s) {
2474 return User::operator new(s, 2);
2475 }
2476
2477 static InsertValueInst *Create(Value *Agg, Value *Val,
2478 ArrayRef<unsigned> Idxs,
2479 const Twine &NameStr = "",
2480 Instruction *InsertBefore = nullptr) {
2481 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2482 }
2483
2484 static InsertValueInst *Create(Value *Agg, Value *Val,
2485 ArrayRef<unsigned> Idxs,
2486 const Twine &NameStr,
2487 BasicBlock *InsertAtEnd) {
2488 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2489 }
2490
2491 /// Transparently provide more efficient getOperand methods.
2492 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2493
2494 using idx_iterator = const unsigned*;
2495
2496 inline idx_iterator idx_begin() const { return Indices.begin(); }
2497 inline idx_iterator idx_end() const { return Indices.end(); }
2498 inline iterator_range<idx_iterator> indices() const {
2499 return make_range(idx_begin(), idx_end());
2500 }
2501
2502 Value *getAggregateOperand() {
2503 return getOperand(0);
2504 }
2505 const Value *getAggregateOperand() const {
2506 return getOperand(0);
2507 }
2508 static unsigned getAggregateOperandIndex() {
2509 return 0U; // get index for modifying correct operand
2510 }
2511
2512 Value *getInsertedValueOperand() {
2513 return getOperand(1);
2514 }
2515 const Value *getInsertedValueOperand() const {
2516 return getOperand(1);
2517 }
2518 static unsigned getInsertedValueOperandIndex() {
2519 return 1U; // get index for modifying correct operand
2520 }
2521
2522 ArrayRef<unsigned> getIndices() const {
2523 return Indices;
2524 }
2525
2526 unsigned getNumIndices() const {
2527 return (unsigned)Indices.size();
2528 }
2529
2530 bool hasIndices() const {
2531 return true;
2532 }
2533
2534 // Methods for support type inquiry through isa, cast, and dyn_cast:
2535 static bool classof(const Instruction *I) {
2536 return I->getOpcode() == Instruction::InsertValue;
2537 }
2538 static bool classof(const Value *V) {
2539 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2540 }
2541};
2542
2543template <>
2544struct OperandTraits<InsertValueInst> :
2545 public FixedNumOperandTraits<InsertValueInst, 2> {
2546};
2547
2548InsertValueInst::InsertValueInst(Value *Agg,
2549 Value *Val,
2550 ArrayRef<unsigned> Idxs,
2551 const Twine &NameStr,
2552 Instruction *InsertBefore)
2553 : Instruction(Agg->getType(), InsertValue,
2554 OperandTraits<InsertValueInst>::op_begin(this),
2555 2, InsertBefore) {
2556 init(Agg, Val, Idxs, NameStr);
2557}
2558
2559InsertValueInst::InsertValueInst(Value *Agg,
2560 Value *Val,
2561 ArrayRef<unsigned> Idxs,
2562 const Twine &NameStr,
2563 BasicBlock *InsertAtEnd)
2564 : Instruction(Agg->getType(), InsertValue,
2565 OperandTraits<InsertValueInst>::op_begin(this),
2566 2, InsertAtEnd) {
2567 init(Agg, Val, Idxs, NameStr);
2568}
2569
2570DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)InsertValueInst::op_iterator InsertValueInst::op_begin() { return
OperandTraits<InsertValueInst>::op_begin(this); } InsertValueInst
::const_op_iterator InsertValueInst::op_begin() const { return
OperandTraits<InsertValueInst>::op_begin(const_cast<
InsertValueInst*>(this)); } InsertValueInst::op_iterator InsertValueInst
::op_end() { return OperandTraits<InsertValueInst>::op_end
(this); } InsertValueInst::const_op_iterator InsertValueInst::
op_end() const { return OperandTraits<InsertValueInst>::
op_end(const_cast<InsertValueInst*>(this)); } Value *InsertValueInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<InsertValueInst>::
operands(this) && "getOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2570, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<InsertValueInst>::op_begin
(const_cast<InsertValueInst*>(this))[i_nocapture].get()
); } void InsertValueInst::setOperand(unsigned i_nocapture, Value
*Val_nocapture) { (static_cast <bool> (i_nocapture <
OperandTraits<InsertValueInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2570, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
InsertValueInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned InsertValueInst::getNumOperands() const { return
OperandTraits<InsertValueInst>::operands(this); } template
<int Idx_nocapture> Use &InsertValueInst::Op() { return
this->OpFrom<Idx_nocapture>(this); } template <int
Idx_nocapture> const Use &InsertValueInst::Op() const
{ return this->OpFrom<Idx_nocapture>(this); }
2571
2572//===----------------------------------------------------------------------===//
2573// PHINode Class
2574//===----------------------------------------------------------------------===//
2575
2576// PHINode - The PHINode class is used to represent the magical mystical PHI
2577// node, that can not exist in nature, but can be synthesized in a computer
2578// scientist's overactive imagination.
2579//
2580class PHINode : public Instruction {
2581 /// The number of operands actually allocated. NumOperands is
2582 /// the number actually in use.
2583 unsigned ReservedSpace;
2584
2585 PHINode(const PHINode &PN);
2586
2587 explicit PHINode(Type *Ty, unsigned NumReservedValues,
2588 const Twine &NameStr = "",
2589 Instruction *InsertBefore = nullptr)
2590 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2591 ReservedSpace(NumReservedValues) {
2592 setName(NameStr);
2593 allocHungoffUses(ReservedSpace);
2594 }
2595
2596 PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2597 BasicBlock *InsertAtEnd)
2598 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2599 ReservedSpace(NumReservedValues) {
2600 setName(NameStr);
2601 allocHungoffUses(ReservedSpace);
2602 }
2603
2604protected:
2605 // Note: Instruction needs to be a friend here to call cloneImpl.
2606 friend class Instruction;
2607
2608 PHINode *cloneImpl() const;
2609
2610 // allocHungoffUses - this is more complicated than the generic
2611 // User::allocHungoffUses, because we have to allocate Uses for the incoming
2612 // values and pointers to the incoming blocks, all in one allocation.
2613 void allocHungoffUses(unsigned N) {
2614 User::allocHungoffUses(N, /* IsPhi */ true);
2615 }
2616
2617public:
2618 /// Constructors - NumReservedValues is a hint for the number of incoming
2619 /// edges that this phi node will have (use 0 if you really have no idea).
2620 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2621 const Twine &NameStr = "",
2622 Instruction *InsertBefore = nullptr) {
2623 return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2624 }
2625
2626 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2627 const Twine &NameStr, BasicBlock *InsertAtEnd) {
2628 return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2629 }
2630
2631 /// Provide fast operand accessors
2632 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2633
2634 // Block iterator interface. This provides access to the list of incoming
2635 // basic blocks, which parallels the list of incoming values.
2636
2637 using block_iterator = BasicBlock **;
2638 using const_block_iterator = BasicBlock * const *;
2639
2640 block_iterator block_begin() {
2641 Use::UserRef *ref =
2642 reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2643 return reinterpret_cast<block_iterator>(ref + 1);
2644 }
2645
2646 const_block_iterator block_begin() const {
2647 const Use::UserRef *ref =
2648 reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2649 return reinterpret_cast<const_block_iterator>(ref + 1);
2650 }
2651
2652 block_iterator block_end() {
2653 return block_begin() + getNumOperands();
2654 }
2655
2656 const_block_iterator block_end() const {
2657 return block_begin() + getNumOperands();
2658 }
2659
2660 iterator_range<block_iterator> blocks() {
2661 return make_range(block_begin(), block_end());
2662 }
2663
2664 iterator_range<const_block_iterator> blocks() const {
2665 return make_range(block_begin(), block_end());
2666 }
2667
2668 op_range incoming_values() { return operands(); }
2669
2670 const_op_range incoming_values() const { return operands(); }
2671
2672 /// Return the number of incoming edges
2673 ///
2674 unsigned getNumIncomingValues() const { return getNumOperands(); }
2675
2676 /// Return incoming value number x
2677 ///
2678 Value *getIncomingValue(unsigned i) const {
2679 return getOperand(i);
2680 }
2681 void setIncomingValue(unsigned i, Value *V) {
2682 assert(V && "PHI node got a null value!")(static_cast <bool> (V && "PHI node got a null value!"
) ? void (0) : __assert_fail ("V && \"PHI node got a null value!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2682, __extension__ __PRETTY_FUNCTION__))
;
2683 assert(getType() == V->getType() &&(static_cast <bool> (getType() == V->getType() &&
"All operands to PHI node must be the same type as the PHI node!"
) ? void (0) : __assert_fail ("getType() == V->getType() && \"All operands to PHI node must be the same type as the PHI node!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2684, __extension__ __PRETTY_FUNCTION__))
2684 "All operands to PHI node must be the same type as the PHI node!")(static_cast <bool> (getType() == V->getType() &&
"All operands to PHI node must be the same type as the PHI node!"
) ? void (0) : __assert_fail ("getType() == V->getType() && \"All operands to PHI node must be the same type as the PHI node!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2684, __extension__ __PRETTY_FUNCTION__))
;
2685 setOperand(i, V);
2686 }
2687
2688 static unsigned getOperandNumForIncomingValue(unsigned i) {
2689 return i;
2690 }
2691
2692 static unsigned getIncomingValueNumForOperand(unsigned i) {
2693 return i;
2694 }
2695
2696 /// Return incoming basic block number @p i.
2697 ///
2698 BasicBlock *getIncomingBlock(unsigned i) const {
2699 return block_begin()[i];
2700 }
2701
2702 /// Return incoming basic block corresponding
2703 /// to an operand of the PHI.
2704 ///
2705 BasicBlock *getIncomingBlock(const Use &U) const {
2706 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?")(static_cast <bool> (this == U.getUser() && "Iterator doesn't point to PHI's Uses?"
) ? void (0) : __assert_fail ("this == U.getUser() && \"Iterator doesn't point to PHI's Uses?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2706, __extension__ __PRETTY_FUNCTION__))
;
2707 return getIncomingBlock(unsigned(&U - op_begin()));
2708 }
2709
2710 /// Return incoming basic block corresponding
2711 /// to value use iterator.
2712 ///
2713 BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2714 return getIncomingBlock(I.getUse());
2715 }
2716
2717 void setIncomingBlock(unsigned i, BasicBlock *BB) {
2718 assert(BB && "PHI node got a null basic block!")(static_cast <bool> (BB && "PHI node got a null basic block!"
) ? void (0) : __assert_fail ("BB && \"PHI node got a null basic block!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2718, __extension__ __PRETTY_FUNCTION__))
;
2719 block_begin()[i] = BB;
2720 }
2721
2722 /// Add an incoming value to the end of the PHI list
2723 ///
2724 void addIncoming(Value *V, BasicBlock *BB) {
2725 if (getNumOperands() == ReservedSpace)
2726 growOperands(); // Get more space!
2727 // Initialize some new operands.
2728 setNumHungOffUseOperands(getNumOperands() + 1);
2729 setIncomingValue(getNumOperands() - 1, V);
2730 setIncomingBlock(getNumOperands() - 1, BB);
2731 }
2732
2733 /// Remove an incoming value. This is useful if a
2734 /// predecessor basic block is deleted. The value removed is returned.
2735 ///
2736 /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2737 /// is true), the PHI node is destroyed and any uses of it are replaced with
2738 /// dummy values. The only time there should be zero incoming values to a PHI
2739 /// node is when the block is dead, so this strategy is sound.
2740 ///
2741 Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2742
2743 Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2744 int Idx = getBasicBlockIndex(BB);
2745 assert(Idx >= 0 && "Invalid basic block argument to remove!")(static_cast <bool> (Idx >= 0 && "Invalid basic block argument to remove!"
) ? void (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument to remove!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2745, __extension__ __PRETTY_FUNCTION__))
;
2746 return removeIncomingValue(Idx, DeletePHIIfEmpty);
2747 }
2748
2749 /// Return the first index of the specified basic
2750 /// block in the value list for this PHI. Returns -1 if no instance.
2751 ///
2752 int getBasicBlockIndex(const BasicBlock *BB) const {
2753 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2754 if (block_begin()[i] == BB)
2755 return i;
2756 return -1;
2757 }
2758
2759 Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2760 int Idx = getBasicBlockIndex(BB);
2761 assert(Idx >= 0 && "Invalid basic block argument!")(static_cast <bool> (Idx >= 0 && "Invalid basic block argument!"
) ? void (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2761, __extension__ __PRETTY_FUNCTION__))
;
2762 return getIncomingValue(Idx);
2763 }
2764
2765 /// If the specified PHI node always merges together the
2766 /// same value, return the value, otherwise return null.
2767 Value *hasConstantValue() const;
2768
2769 /// Whether the specified PHI node always merges
2770 /// together the same value, assuming undefs are equal to a unique
2771 /// non-undef value.
2772 bool hasConstantOrUndefValue() const;
2773
2774 /// Methods for support type inquiry through isa, cast, and dyn_cast:
2775 static bool classof(const Instruction *I) {
2776 return I->getOpcode() == Instruction::PHI;
2777 }
2778 static bool classof(const Value *V) {
2779 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2780 }
2781
2782private:
2783 void growOperands();
2784};
2785
2786template <>
2787struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2788};
2789
2790DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)PHINode::op_iterator PHINode::op_begin() { return OperandTraits
<PHINode>::op_begin(this); } PHINode::const_op_iterator
PHINode::op_begin() const { return OperandTraits<PHINode>
::op_begin(const_cast<PHINode*>(this)); } PHINode::op_iterator
PHINode::op_end() { return OperandTraits<PHINode>::op_end
(this); } PHINode::const_op_iterator PHINode::op_end() const {
return OperandTraits<PHINode>::op_end(const_cast<PHINode
*>(this)); } Value *PHINode::getOperand(unsigned i_nocapture
) const { (static_cast <bool> (i_nocapture < OperandTraits
<PHINode>::operands(this) && "getOperand() out of range!"
) ? void (0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2790, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<PHINode>::op_begin(const_cast
<PHINode*>(this))[i_nocapture].get()); } void PHINode::
setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast
<bool> (i_nocapture < OperandTraits<PHINode>::
operands(this) && "setOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2790, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
PHINode>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
PHINode::getNumOperands() const { return OperandTraits<PHINode
>::operands(this); } template <int Idx_nocapture> Use
&PHINode::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
PHINode::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
2791
2792//===----------------------------------------------------------------------===//
2793// LandingPadInst Class
2794//===----------------------------------------------------------------------===//
2795
2796//===---------------------------------------------------------------------------
2797/// The landingpad instruction holds all of the information
2798/// necessary to generate correct exception handling. The landingpad instruction
2799/// cannot be moved from the top of a landing pad block, which itself is
2800/// accessible only from the 'unwind' edge of an invoke. This uses the
2801/// SubclassData field in Value to store whether or not the landingpad is a
2802/// cleanup.
2803///
2804class LandingPadInst : public Instruction {
2805 /// The number of operands actually allocated. NumOperands is
2806 /// the number actually in use.
2807 unsigned ReservedSpace;
2808
2809 LandingPadInst(const LandingPadInst &LP);
2810
2811public:
2812 enum ClauseType { Catch, Filter };
2813
2814private:
2815 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2816 const Twine &NameStr, Instruction *InsertBefore);
2817 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2818 const Twine &NameStr, BasicBlock *InsertAtEnd);
2819
2820 // Allocate space for exactly zero operands.
2821 void *operator new(size_t s) {
2822 return User::operator new(s);
2823 }
2824
2825 void growOperands(unsigned Size);
2826 void init(unsigned NumReservedValues, const Twine &NameStr);
2827
2828protected:
2829 // Note: Instruction needs to be a friend here to call cloneImpl.
2830 friend class Instruction;
2831
2832 LandingPadInst *cloneImpl() const;
2833
2834public:
2835 /// Constructors - NumReservedClauses is a hint for the number of incoming
2836 /// clauses that this landingpad will have (use 0 if you really have no idea).
2837 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2838 const Twine &NameStr = "",
2839 Instruction *InsertBefore = nullptr);
2840 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2841 const Twine &NameStr, BasicBlock *InsertAtEnd);
2842
2843 /// Provide fast operand accessors
2844 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2845
2846 /// Return 'true' if this landingpad instruction is a
2847 /// cleanup. I.e., it should be run when unwinding even if its landing pad
2848 /// doesn't catch the exception.
2849 bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2850
2851 /// Indicate that this landingpad instruction is a cleanup.
2852 void setCleanup(bool V) {
2853 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2854 (V ? 1 : 0));
2855 }
2856
2857 /// Add a catch or filter clause to the landing pad.
2858 void addClause(Constant *ClauseVal);
2859
2860 /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2861 /// determine what type of clause this is.
2862 Constant *getClause(unsigned Idx) const {
2863 return cast<Constant>(getOperandList()[Idx]);
2864 }
2865
2866 /// Return 'true' if the clause and index Idx is a catch clause.
2867 bool isCatch(unsigned Idx) const {
2868 return !isa<ArrayType>(getOperandList()[Idx]->getType());
2869 }
2870
2871 /// Return 'true' if the clause and index Idx is a filter clause.
2872 bool isFilter(unsigned Idx) const {
2873 return isa<ArrayType>(getOperandList()[Idx]->getType());
2874 }
2875
2876 /// Get the number of clauses for this landing pad.
2877 unsigned getNumClauses() const { return getNumOperands(); }
2878
2879 /// Grow the size of the operand list to accommodate the new
2880 /// number of clauses.
2881 void reserveClauses(unsigned Size) { growOperands(Size); }
2882
2883 // Methods for support type inquiry through isa, cast, and dyn_cast:
2884 static bool classof(const Instruction *I) {
2885 return I->getOpcode() == Instruction::LandingPad;
2886 }
2887 static bool classof(const Value *V) {
2888 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2889 }
2890};
2891
2892template <>
2893struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2894};
2895
2896DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)LandingPadInst::op_iterator LandingPadInst::op_begin() { return
OperandTraits<LandingPadInst>::op_begin(this); } LandingPadInst
::const_op_iterator LandingPadInst::op_begin() const { return
OperandTraits<LandingPadInst>::op_begin(const_cast<
LandingPadInst*>(this)); } LandingPadInst::op_iterator LandingPadInst
::op_end() { return OperandTraits<LandingPadInst>::op_end
(this); } LandingPadInst::const_op_iterator LandingPadInst::op_end
() const { return OperandTraits<LandingPadInst>::op_end
(const_cast<LandingPadInst*>(this)); } Value *LandingPadInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<LandingPadInst>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2896, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<LandingPadInst>::op_begin(
const_cast<LandingPadInst*>(this))[i_nocapture].get());
} void LandingPadInst::setOperand(unsigned i_nocapture, Value
*Val_nocapture) { (static_cast <bool> (i_nocapture <
OperandTraits<LandingPadInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2896, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
LandingPadInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned LandingPadInst::getNumOperands() const { return OperandTraits
<LandingPadInst>::operands(this); } template <int Idx_nocapture
> Use &LandingPadInst::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &LandingPadInst::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
2897
2898//===----------------------------------------------------------------------===//
2899// ReturnInst Class
2900//===----------------------------------------------------------------------===//
2901
2902//===---------------------------------------------------------------------------
2903/// Return a value (possibly void), from a function. Execution
2904/// does not continue in this function any longer.
2905///
2906class ReturnInst : public TerminatorInst {
2907 ReturnInst(const ReturnInst &RI);
2908
2909private:
2910 // ReturnInst constructors:
2911 // ReturnInst() - 'ret void' instruction
2912 // ReturnInst( null) - 'ret void' instruction
2913 // ReturnInst(Value* X) - 'ret X' instruction
2914 // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2915 // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2916 // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2917 // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2918 //
2919 // NOTE: If the Value* passed is of type void then the constructor behaves as
2920 // if it was passed NULL.
2921 explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2922 Instruction *InsertBefore = nullptr);
2923 ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2924 explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2925
2926protected:
2927 // Note: Instruction needs to be a friend here to call cloneImpl.
2928 friend class Instruction;
2929
2930 ReturnInst *cloneImpl() const;
2931
2932public:
2933 static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2934 Instruction *InsertBefore = nullptr) {
2935 return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2936 }
2937
2938 static ReturnInst* Create(LLVMContext &C, Value *retVal,
2939 BasicBlock *InsertAtEnd) {
2940 return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2941 }
2942
2943 static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2944 return new(0) ReturnInst(C, InsertAtEnd);
2945 }
2946
2947 /// Provide fast operand accessors
2948 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2949
2950 /// Convenience accessor. Returns null if there is no return value.
2951 Value *getReturnValue() const {
2952 return getNumOperands() != 0 ? getOperand(0) : nullptr;
2953 }
2954
2955 unsigned getNumSuccessors() const { return 0; }
2956
2957 // Methods for support type inquiry through isa, cast, and dyn_cast:
2958 static bool classof(const Instruction *I) {
2959 return (I->getOpcode() == Instruction::Ret);
2960 }
2961 static bool classof(const Value *V) {
2962 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2963 }
2964
2965private:
2966 friend TerminatorInst;
2967
2968 BasicBlock *getSuccessor(unsigned idx) const {
2969 llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2969)
;
2970 }
2971
2972 void setSuccessor(unsigned idx, BasicBlock *B) {
2973 llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2973)
;
2974 }
2975};
2976
2977template <>
2978struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2979};
2980
2981DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)ReturnInst::op_iterator ReturnInst::op_begin() { return OperandTraits
<ReturnInst>::op_begin(this); } ReturnInst::const_op_iterator
ReturnInst::op_begin() const { return OperandTraits<ReturnInst
>::op_begin(const_cast<ReturnInst*>(this)); } ReturnInst
::op_iterator ReturnInst::op_end() { return OperandTraits<
ReturnInst>::op_end(this); } ReturnInst::const_op_iterator
ReturnInst::op_end() const { return OperandTraits<ReturnInst
>::op_end(const_cast<ReturnInst*>(this)); } Value *ReturnInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<ReturnInst>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2981, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<ReturnInst>::op_begin(const_cast
<ReturnInst*>(this))[i_nocapture].get()); } void ReturnInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast
<bool> (i_nocapture < OperandTraits<ReturnInst>
::operands(this) && "setOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 2981, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
ReturnInst>::op_begin(this)[i_nocapture] = Val_nocapture; }
unsigned ReturnInst::getNumOperands() const { return OperandTraits
<ReturnInst>::operands(this); } template <int Idx_nocapture
> Use &ReturnInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
ReturnInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
2982
2983//===----------------------------------------------------------------------===//
2984// BranchInst Class
2985//===----------------------------------------------------------------------===//
2986
2987//===---------------------------------------------------------------------------
2988/// Conditional or Unconditional Branch instruction.
2989///
2990class BranchInst : public TerminatorInst {
2991 /// Ops list - Branches are strange. The operands are ordered:
2992 /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
2993 /// they don't have to check for cond/uncond branchness. These are mostly
2994 /// accessed relative from op_end().
2995 BranchInst(const BranchInst &BI);
2996 // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2997 // BranchInst(BB *B) - 'br B'
2998 // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
2999 // BranchInst(BB* B, Inst *I) - 'br B' insert before I
3000 // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
3001 // BranchInst(BB* B, BB *I) - 'br B' insert at end
3002 // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
3003 explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
3004 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3005 Instruction *InsertBefore = nullptr);
3006 BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
3007 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3008 BasicBlock *InsertAtEnd);
3009
3010 void AssertOK();
3011
3012protected:
3013 // Note: Instruction needs to be a friend here to call cloneImpl.
3014 friend class Instruction;
3015
3016 BranchInst *cloneImpl() const;
3017
3018public:
3019 static BranchInst *Create(BasicBlock *IfTrue,
3020 Instruction *InsertBefore = nullptr) {
3021 return new(1) BranchInst(IfTrue, InsertBefore);
3022 }
3023
3024 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3025 Value *Cond, Instruction *InsertBefore = nullptr) {
3026 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3027 }
3028
3029 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3030 return new(1) BranchInst(IfTrue, InsertAtEnd);
3031 }
3032
3033 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3034 Value *Cond, BasicBlock *InsertAtEnd) {
3035 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3036 }
3037
3038 /// Transparently provide more efficient getOperand methods.
3039 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
3040
3041 bool isUnconditional() const { return getNumOperands() == 1; }
3042 bool isConditional() const { return getNumOperands() == 3; }
3043
3044 Value *getCondition() const {
3045 assert(isConditional() && "Cannot get condition of an uncond branch!")(static_cast <bool> (isConditional() && "Cannot get condition of an uncond branch!"
) ? void (0) : __assert_fail ("isConditional() && \"Cannot get condition of an uncond branch!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3045, __extension__ __PRETTY_FUNCTION__))
;
3046 return Op<-3>();
3047 }
3048
3049 void setCondition(Value *V) {
3050 assert(isConditional() && "Cannot set condition of unconditional branch!")(static_cast <bool> (isConditional() && "Cannot set condition of unconditional branch!"
) ? void (0) : __assert_fail ("isConditional() && \"Cannot set condition of unconditional branch!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3050, __extension__ __PRETTY_FUNCTION__))
;
3051 Op<-3>() = V;
3052 }
3053
3054 unsigned getNumSuccessors() const { return 1+isConditional(); }
3055
3056 BasicBlock *getSuccessor(unsigned i) const {
3057 assert(i < getNumSuccessors() && "Successor # out of range for Branch!")(static_cast <bool> (i < getNumSuccessors() &&
"Successor # out of range for Branch!") ? void (0) : __assert_fail
("i < getNumSuccessors() && \"Successor # out of range for Branch!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3057, __extension__ __PRETTY_FUNCTION__))
;
3058 return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3059 }
3060
3061 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3062 assert(idx < getNumSuccessors() && "Successor # out of range for Branch!")(static_cast <bool> (idx < getNumSuccessors() &&
"Successor # out of range for Branch!") ? void (0) : __assert_fail
("idx < getNumSuccessors() && \"Successor # out of range for Branch!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3062, __extension__ __PRETTY_FUNCTION__))
;
3063 *(&Op<-1>() - idx) = NewSucc;
3064 }
3065
3066 /// Swap the successors of this branch instruction.
3067 ///
3068 /// Swaps the successors of the branch instruction. This also swaps any
3069 /// branch weight metadata associated with the instruction so that it
3070 /// continues to map correctly to each operand.
3071 void swapSuccessors();
3072
3073 // Methods for support type inquiry through isa, cast, and dyn_cast:
3074 static bool classof(const Instruction *I) {
3075 return (I->getOpcode() == Instruction::Br);
3076 }
3077 static bool classof(const Value *V) {
3078 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3079 }
3080};
3081
3082template <>
3083struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3084};
3085
3086DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)BranchInst::op_iterator BranchInst::op_begin() { return OperandTraits
<BranchInst>::op_begin(this); } BranchInst::const_op_iterator
BranchInst::op_begin() const { return OperandTraits<BranchInst
>::op_begin(const_cast<BranchInst*>(this)); } BranchInst
::op_iterator BranchInst::op_end() { return OperandTraits<
BranchInst>::op_end(this); } BranchInst::const_op_iterator
BranchInst::op_end() const { return OperandTraits<BranchInst
>::op_end(const_cast<BranchInst*>(this)); } Value *BranchInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<BranchInst>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3086, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<BranchInst>::op_begin(const_cast
<BranchInst*>(this))[i_nocapture].get()); } void BranchInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast
<bool> (i_nocapture < OperandTraits<BranchInst>
::operands(this) && "setOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3086, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
BranchInst>::op_begin(this)[i_nocapture] = Val_nocapture; }
unsigned BranchInst::getNumOperands() const { return OperandTraits
<BranchInst>::operands(this); } template <int Idx_nocapture
> Use &BranchInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
BranchInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
3087
3088//===----------------------------------------------------------------------===//
3089// SwitchInst Class
3090//===----------------------------------------------------------------------===//
3091
3092//===---------------------------------------------------------------------------
3093/// Multiway switch
3094///
3095class SwitchInst : public TerminatorInst {
3096 unsigned ReservedSpace;
3097
3098 // Operand[0] = Value to switch on
3099 // Operand[1] = Default basic block destination
3100 // Operand[2n ] = Value to match
3101 // Operand[2n+1] = BasicBlock to go to on match
3102 SwitchInst(const SwitchInst &SI);
3103
3104 /// Create a new switch instruction, specifying a value to switch on and a
3105 /// default destination. The number of additional cases can be specified here
3106 /// to make memory allocation more efficient. This constructor can also
3107 /// auto-insert before another instruction.
3108 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3109 Instruction *InsertBefore);
3110
3111 /// Create a new switch instruction, specifying a value to switch on and a
3112 /// default destination. The number of additional cases can be specified here
3113 /// to make memory allocation more efficient. This constructor also
3114 /// auto-inserts at the end of the specified BasicBlock.
3115 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3116 BasicBlock *InsertAtEnd);
3117
3118 // allocate space for exactly zero operands
3119 void *operator new(size_t s) {
3120 return User::operator new(s);
3121 }
3122
3123 void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3124 void growOperands();
3125
3126protected:
3127 // Note: Instruction needs to be a friend here to call cloneImpl.
3128 friend class Instruction;
3129
3130 SwitchInst *cloneImpl() const;
3131
3132public:
3133 // -2
3134 static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3135
3136 template <typename CaseHandleT> class CaseIteratorImpl;
3137
3138 /// A handle to a particular switch case. It exposes a convenient interface
3139 /// to both the case value and the successor block.
3140 ///
3141 /// We define this as a template and instantiate it to form both a const and
3142 /// non-const handle.
3143 template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3144 class CaseHandleImpl {
3145 // Directly befriend both const and non-const iterators.
3146 friend class SwitchInst::CaseIteratorImpl<
3147 CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3148
3149 protected:
3150 // Expose the switch type we're parameterized with to the iterator.
3151 using SwitchInstType = SwitchInstT;
3152
3153 SwitchInstT *SI;
3154 ptrdiff_t Index;
3155
3156 CaseHandleImpl() = default;
3157 CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3158
3159 public:
3160 /// Resolves case value for current case.
3161 ConstantIntT *getCaseValue() const {
3162 assert((unsigned)Index < SI->getNumCases() &&(static_cast <bool> ((unsigned)Index < SI->getNumCases
() && "Index out the number of cases.") ? void (0) : __assert_fail
("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3163, __extension__ __PRETTY_FUNCTION__))
3163 "Index out the number of cases.")(static_cast <bool> ((unsigned)Index < SI->getNumCases
() && "Index out the number of cases.") ? void (0) : __assert_fail
("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3163, __extension__ __PRETTY_FUNCTION__))
;
3164 return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3165 }
3166
3167 /// Resolves successor for current case.
3168 BasicBlockT *getCaseSuccessor() const {
3169 assert(((unsigned)Index < SI->getNumCases() ||(static_cast <bool> (((unsigned)Index < SI->getNumCases
() || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases."
) ? void (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3171, __extension__ __PRETTY_FUNCTION__))
3170 (unsigned)Index == DefaultPseudoIndex) &&(static_cast <bool> (((unsigned)Index < SI->getNumCases
() || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases."
) ? void (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3171, __extension__ __PRETTY_FUNCTION__))
3171 "Index out the number of cases.")(static_cast <bool> (((unsigned)Index < SI->getNumCases
() || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases."
) ? void (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3171, __extension__ __PRETTY_FUNCTION__))
;
3172 return SI->getSuccessor(getSuccessorIndex());
3173 }
3174
3175 /// Returns number of current case.
3176 unsigned getCaseIndex() const { return Index; }
3177
3178 /// Returns TerminatorInst's successor index for current case successor.
3179 unsigned getSuccessorIndex() const {
3180 assert(((unsigned)Index == DefaultPseudoIndex ||(static_cast <bool> (((unsigned)Index == DefaultPseudoIndex
|| (unsigned)Index < SI->getNumCases()) && "Index out the number of cases."
) ? void (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3182, __extension__ __PRETTY_FUNCTION__))
3181 (unsigned)Index < SI->getNumCases()) &&(static_cast <bool> (((unsigned)Index == DefaultPseudoIndex
|| (unsigned)Index < SI->getNumCases()) && "Index out the number of cases."
) ? void (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3182, __extension__ __PRETTY_FUNCTION__))
3182 "Index out the number of cases.")(static_cast <bool> (((unsigned)Index == DefaultPseudoIndex
|| (unsigned)Index < SI->getNumCases()) && "Index out the number of cases."
) ? void (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3182, __extension__ __PRETTY_FUNCTION__))
;
3183 return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3184 }
3185
3186 bool operator==(const CaseHandleImpl &RHS) const {
3187 assert(SI == RHS.SI && "Incompatible operators.")(static_cast <bool> (SI == RHS.SI && "Incompatible operators."
) ? void (0) : __assert_fail ("SI == RHS.SI && \"Incompatible operators.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3187, __extension__ __PRETTY_FUNCTION__))
;
3188 return Index == RHS.Index;
3189 }
3190 };
3191
3192 using ConstCaseHandle =
3193 CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
3194
3195 class CaseHandle
3196 : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3197 friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
3198
3199 public:
3200 CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3201
3202 /// Sets the new value for current case.
3203 void setValue(ConstantInt *V) {
3204 assert((unsigned)Index < SI->getNumCases() &&(static_cast <bool> ((unsigned)Index < SI->getNumCases
() && "Index out the number of cases.") ? void (0) : __assert_fail
("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3205, __extension__ __PRETTY_FUNCTION__))
3205 "Index out the number of cases.")(static_cast <bool> ((unsigned)Index < SI->getNumCases
() && "Index out the number of cases.") ? void (0) : __assert_fail
("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3205, __extension__ __PRETTY_FUNCTION__))
;
3206 SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3207 }
3208
3209 /// Sets the new successor for current case.
3210 void setSuccessor(BasicBlock *S) {
3211 SI->setSuccessor(getSuccessorIndex(), S);
3212 }
3213 };
3214
3215 template <typename CaseHandleT>
3216 class CaseIteratorImpl
3217 : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3218 std::random_access_iterator_tag,
3219 CaseHandleT> {
3220 using SwitchInstT = typename CaseHandleT::SwitchInstType;
3221
3222 CaseHandleT Case;
3223
3224 public:
3225 /// Default constructed iterator is in an invalid state until assigned to
3226 /// a case for a particular switch.
3227 CaseIteratorImpl() = default;
3228
3229 /// Initializes case iterator for given SwitchInst and for given
3230 /// case number.
3231 CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3232
3233 /// Initializes case iterator for given SwitchInst and for given
3234 /// TerminatorInst's successor index.
3235 static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3236 unsigned SuccessorIndex) {
3237 assert(SuccessorIndex < SI->getNumSuccessors() &&(static_cast <bool> (SuccessorIndex < SI->getNumSuccessors
() && "Successor index # out of range!") ? void (0) :
__assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3238, __extension__ __PRETTY_FUNCTION__))
3238 "Successor index # out of range!")(static_cast <bool> (SuccessorIndex < SI->getNumSuccessors
() && "Successor index # out of range!") ? void (0) :
__assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3238, __extension__ __PRETTY_FUNCTION__))
;
3239 return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3240 : CaseIteratorImpl(SI, DefaultPseudoIndex);
3241 }
3242
3243 /// Support converting to the const variant. This will be a no-op for const
3244 /// variant.
3245 operator CaseIteratorImpl<ConstCaseHandle>() const {
3246 return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3247 }
3248
3249 CaseIteratorImpl &operator+=(ptrdiff_t N) {
3250 // Check index correctness after addition.
3251 // Note: Index == getNumCases() means end().
3252 assert(Case.Index + N >= 0 &&(static_cast <bool> (Case.Index + N >= 0 && (
unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
"Case.Index out the number of cases.") ? void (0) : __assert_fail
("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3254, __extension__ __PRETTY_FUNCTION__))
3253 (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&(static_cast <bool> (Case.Index + N >= 0 && (
unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
"Case.Index out the number of cases.") ? void (0) : __assert_fail
("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3254, __extension__ __PRETTY_FUNCTION__))
3254 "Case.Index out the number of cases.")(static_cast <bool> (Case.Index + N >= 0 && (
unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
"Case.Index out the number of cases.") ? void (0) : __assert_fail
("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3254, __extension__ __PRETTY_FUNCTION__))
;
3255 Case.Index += N;
3256 return *this;
3257 }
3258 CaseIteratorImpl &operator-=(ptrdiff_t N) {
3259 // Check index correctness after subtraction.
3260 // Note: Case.Index == getNumCases() means end().
3261 assert(Case.Index - N >= 0 &&(static_cast <bool> (Case.Index - N >= 0 && (
unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
"Case.Index out the number of cases.") ? void (0) : __assert_fail
("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3263, __extension__ __PRETTY_FUNCTION__))
3262 (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&(static_cast <bool> (Case.Index - N >= 0 && (
unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
"Case.Index out the number of cases.") ? void (0) : __assert_fail
("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3263, __extension__ __PRETTY_FUNCTION__))
3263 "Case.Index out the number of cases.")(static_cast <bool> (Case.Index - N >= 0 && (
unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
"Case.Index out the number of cases.") ? void (0) : __assert_fail
("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3263, __extension__ __PRETTY_FUNCTION__))
;
3264 Case.Index -= N;
3265 return *this;
3266 }
3267 ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
3268 assert(Case.SI == RHS.Case.SI && "Incompatible operators.")(static_cast <bool> (Case.SI == RHS.Case.SI && "Incompatible operators."
) ? void (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3268, __extension__ __PRETTY_FUNCTION__))
;
3269 return Case.Index - RHS.Case.Index;
3270 }
3271 bool operator==(const CaseIteratorImpl &RHS) const {
3272 return Case == RHS.Case;
3273 }
3274 bool operator<(const CaseIteratorImpl &RHS) const {
3275 assert(Case.SI == RHS.Case.SI && "Incompatible operators.")(static_cast <bool> (Case.SI == RHS.Case.SI && "Incompatible operators."
) ? void (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3275, __extension__ __PRETTY_FUNCTION__))
;
3276 return Case.Index < RHS.Case.Index;
3277 }
3278 CaseHandleT &operator*() { return Case; }
3279 const CaseHandleT &operator*() const { return Case; }
3280 };
3281
3282 using CaseIt = CaseIteratorImpl<CaseHandle>;
3283 using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
3284
3285 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3286 unsigned NumCases,
3287 Instruction *InsertBefore = nullptr) {
3288 return new SwitchInst(Value, Default, NumCases, InsertBefore);
3289 }
3290
3291 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3292 unsigned NumCases, BasicBlock *InsertAtEnd) {
3293 return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3294 }
3295
3296 /// Provide fast operand accessors
3297 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
3298
3299 // Accessor Methods for Switch stmt
3300 Value *getCondition() const { return getOperand(0); }
3301 void setCondition(Value *V) { setOperand(0, V); }
3302
3303 BasicBlock *getDefaultDest() const {
3304 return cast<BasicBlock>(getOperand(1));
3305 }
3306
3307 void setDefaultDest(BasicBlock *DefaultCase) {
3308 setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3309 }
3310
3311 /// Return the number of 'cases' in this switch instruction, excluding the
3312 /// default case.
3313 unsigned getNumCases() const {
3314 return getNumOperands()/2 - 1;
3315 }
3316
3317 /// Returns a read/write iterator that points to the first case in the
3318 /// SwitchInst.
3319 CaseIt case_begin() {
3320 return CaseIt(this, 0);
3321 }
3322
3323 /// Returns a read-only iterator that points to the first case in the
3324 /// SwitchInst.
3325 ConstCaseIt case_begin() const {
3326 return ConstCaseIt(this, 0);
3327 }
3328
3329 /// Returns a read/write iterator that points one past the last in the
3330 /// SwitchInst.
3331 CaseIt case_end() {
3332 return CaseIt(this, getNumCases());
3333 }
3334
3335 /// Returns a read-only iterator that points one past the last in the
3336 /// SwitchInst.
3337 ConstCaseIt case_end() const {
3338 return ConstCaseIt(this, getNumCases());
3339 }
3340
3341 /// Iteration adapter for range-for loops.
3342 iterator_range<CaseIt> cases() {
3343 return make_range(case_begin(), case_end());
3344 }
3345
3346 /// Constant iteration adapter for range-for loops.
3347 iterator_range<ConstCaseIt> cases() const {
3348 return make_range(case_begin(), case_end());
3349 }
3350
3351 /// Returns an iterator that points to the default case.
3352 /// Note: this iterator allows to resolve successor only. Attempt
3353 /// to resolve case value causes an assertion.
3354 /// Also note, that increment and decrement also causes an assertion and
3355 /// makes iterator invalid.
3356 CaseIt case_default() {
3357 return CaseIt(this, DefaultPseudoIndex);
3358 }
3359 ConstCaseIt case_default() const {
3360 return ConstCaseIt(this, DefaultPseudoIndex);
3361 }
3362
3363 /// Search all of the case values for the specified constant. If it is
3364 /// explicitly handled, return the case iterator of it, otherwise return
3365 /// default case iterator to indicate that it is handled by the default
3366 /// handler.
3367 CaseIt findCaseValue(const ConstantInt *C) {
3368 CaseIt I = llvm::find_if(
3369 cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3370 if (I != case_end())
3371 return I;
3372
3373 return case_default();
3374 }
3375 ConstCaseIt findCaseValue(const ConstantInt *C) const {
3376 ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3377 return Case.getCaseValue() == C;
3378 });
3379 if (I != case_end())
3380 return I;
3381
3382 return case_default();
3383 }
3384
3385 /// Finds the unique case value for a given successor. Returns null if the
3386 /// successor is not found, not unique, or is the default case.
3387 ConstantInt *findCaseDest(BasicBlock *BB) {
3388 if (BB == getDefaultDest())
3389 return nullptr;
3390
3391 ConstantInt *CI = nullptr;
3392 for (auto Case : cases()) {
3393 if (Case.getCaseSuccessor() != BB)
3394 continue;
3395
3396 if (CI)
3397 return nullptr; // Multiple cases lead to BB.
3398
3399 CI = Case.getCaseValue();
3400 }
3401
3402 return CI;
3403 }
3404
3405 /// Add an entry to the switch instruction.
3406 /// Note:
3407 /// This action invalidates case_end(). Old case_end() iterator will
3408 /// point to the added case.
3409 void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3410
3411 /// This method removes the specified case and its successor from the switch
3412 /// instruction. Note that this operation may reorder the remaining cases at
3413 /// index idx and above.
3414 /// Note:
3415 /// This action invalidates iterators for all cases following the one removed,
3416 /// including the case_end() iterator. It returns an iterator for the next
3417 /// case.
3418 CaseIt removeCase(CaseIt I);
3419
3420 unsigned getNumSuccessors() const { return getNumOperands()/2; }
3421 BasicBlock *getSuccessor(unsigned idx) const {
3422 assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!")(static_cast <bool> (idx < getNumSuccessors() &&
"Successor idx out of range for switch!") ? void (0) : __assert_fail
("idx < getNumSuccessors() &&\"Successor idx out of range for switch!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3422, __extension__ __PRETTY_FUNCTION__))
;
3423 return cast<BasicBlock>(getOperand(idx*2+1));
3424 }
3425 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3426 assert(idx < getNumSuccessors() && "Successor # out of range for switch!")(static_cast <bool> (idx < getNumSuccessors() &&
"Successor # out of range for switch!") ? void (0) : __assert_fail
("idx < getNumSuccessors() && \"Successor # out of range for switch!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3426, __extension__ __PRETTY_FUNCTION__))
;
3427 setOperand(idx * 2 + 1, NewSucc);
3428 }
3429
3430 // Methods for support type inquiry through isa, cast, and dyn_cast:
3431 static bool classof(const Instruction *I) {
3432 return I->getOpcode() == Instruction::Switch;
3433 }
3434 static bool classof(const Value *V) {
3435 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3436 }
3437};
3438
3439template <>
3440struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3441};
3442
3443DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)SwitchInst::op_iterator SwitchInst::op_begin() { return OperandTraits
<SwitchInst>::op_begin(this); } SwitchInst::const_op_iterator
SwitchInst::op_begin() const { return OperandTraits<SwitchInst
>::op_begin(const_cast<SwitchInst*>(this)); } SwitchInst
::op_iterator SwitchInst::op_end() { return OperandTraits<
SwitchInst>::op_end(this); } SwitchInst::const_op_iterator
SwitchInst::op_end() const { return OperandTraits<SwitchInst
>::op_end(const_cast<SwitchInst*>(this)); } Value *SwitchInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<SwitchInst>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<SwitchInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3443, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<SwitchInst>::op_begin(const_cast
<SwitchInst*>(this))[i_nocapture].get()); } void SwitchInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast
<bool> (i_nocapture < OperandTraits<SwitchInst>
::operands(this) && "setOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<SwitchInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3443, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
SwitchInst>::op_begin(this)[i_nocapture] = Val_nocapture; }
unsigned SwitchInst::getNumOperands() const { return OperandTraits
<SwitchInst>::operands(this); } template <int Idx_nocapture
> Use &SwitchInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
SwitchInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
3444
3445//===----------------------------------------------------------------------===//
3446// IndirectBrInst Class
3447//===----------------------------------------------------------------------===//
3448
3449//===---------------------------------------------------------------------------
3450/// Indirect Branch Instruction.
3451///
3452class IndirectBrInst : public TerminatorInst {
3453 unsigned ReservedSpace;
3454
3455 // Operand[0] = Address to jump to
3456 // Operand[n+1] = n-th destination
3457 IndirectBrInst(const IndirectBrInst &IBI);
3458
3459 /// Create a new indirectbr instruction, specifying an
3460 /// Address to jump to. The number of expected destinations can be specified
3461 /// here to make memory allocation more efficient. This constructor can also
3462 /// autoinsert before another instruction.
3463 IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3464
3465 /// Create a new indirectbr instruction, specifying an
3466 /// Address to jump to. The number of expected destinations can be specified
3467 /// here to make memory allocation more efficient. This constructor also
3468 /// autoinserts at the end of the specified BasicBlock.
3469 IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3470
3471 // allocate space for exactly zero operands
3472 void *operator new(size_t s) {
3473 return User::operator new(s);
3474 }
3475
3476 void init(Value *Address, unsigned NumDests);
3477 void growOperands();
3478
3479protected:
3480 // Note: Instruction needs to be a friend here to call cloneImpl.
3481 friend class Instruction;
3482
3483 IndirectBrInst *cloneImpl() const;
3484
3485public:
3486 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3487 Instruction *InsertBefore = nullptr) {
3488 return new IndirectBrInst(Address, NumDests, InsertBefore);
3489 }
3490
3491 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3492 BasicBlock *InsertAtEnd) {
3493 return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3494 }
3495
3496 /// Provide fast operand accessors.
3497 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
3498
3499 // Accessor Methods for IndirectBrInst instruction.
3500 Value *getAddress() { return getOperand(0); }
3501 const Value *getAddress() const { return getOperand(0); }
3502 void setAddress(Value *V) { setOperand(0, V); }
3503
3504 /// return the number of possible destinations in this
3505 /// indirectbr instruction.
3506 unsigned getNumDestinations() const { return getNumOperands()-1; }
3507
3508 /// Return the specified destination.
3509 BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3510 const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3511
3512 /// Add a destination.
3513 ///
3514 void addDestination(BasicBlock *Dest);
3515
3516 /// This method removes the specified successor from the
3517 /// indirectbr instruction.
3518 void removeDestination(unsigned i);
3519
3520 unsigned getNumSuccessors() const { return getNumOperands()-1; }
3521 BasicBlock *getSuccessor(unsigned i) const {
3522 return cast<BasicBlock>(getOperand(i+1));
3523 }
3524 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3525 setOperand(i + 1, NewSucc);
3526 }
3527
3528 // Methods for support type inquiry through isa, cast, and dyn_cast:
3529 static bool classof(const Instruction *I) {
3530 return I->getOpcode() == Instruction::IndirectBr;
3531 }
3532 static bool classof(const Value *V) {
3533 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3534 }
3535};
3536
3537template <>
3538struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3539};
3540
3541DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)IndirectBrInst::op_iterator IndirectBrInst::op_begin() { return
OperandTraits<IndirectBrInst>::op_begin(this); } IndirectBrInst
::const_op_iterator IndirectBrInst::op_begin() const { return
OperandTraits<IndirectBrInst>::op_begin(const_cast<
IndirectBrInst*>(this)); } IndirectBrInst::op_iterator IndirectBrInst
::op_end() { return OperandTraits<IndirectBrInst>::op_end
(this); } IndirectBrInst::const_op_iterator IndirectBrInst::op_end
() const { return OperandTraits<IndirectBrInst>::op_end
(const_cast<IndirectBrInst*>(this)); } Value *IndirectBrInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<IndirectBrInst>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3541, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<IndirectBrInst>::op_begin(
const_cast<IndirectBrInst*>(this))[i_nocapture].get());
} void IndirectBrInst::setOperand(unsigned i_nocapture, Value
*Val_nocapture) { (static_cast <bool> (i_nocapture <
OperandTraits<IndirectBrInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3541, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
IndirectBrInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned IndirectBrInst::getNumOperands() const { return OperandTraits
<IndirectBrInst>::operands(this); } template <int Idx_nocapture
> Use &IndirectBrInst::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &IndirectBrInst::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
3542
3543//===----------------------------------------------------------------------===//
3544// InvokeInst Class
3545//===----------------------------------------------------------------------===//
3546
3547/// Invoke instruction. The SubclassData field is used to hold the
3548/// calling convention of the call.
3549///
3550class InvokeInst : public TerminatorInst,
3551 public OperandBundleUser<InvokeInst, User::op_iterator> {
3552 friend class OperandBundleUser<InvokeInst, User::op_iterator>;
3553
3554 AttributeList Attrs;
3555 FunctionType *FTy;
3556
3557 InvokeInst(const InvokeInst &BI);
3558
3559 /// Construct an InvokeInst given a range of arguments.
3560 ///
3561 /// Construct an InvokeInst from a range of arguments
3562 inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3563 ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3564 unsigned Values, const Twine &NameStr,
3565 Instruction *InsertBefore)
3566 : InvokeInst(cast<FunctionType>(
3567 cast<PointerType>(Func->getType())->getElementType()),
3568 Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3569 InsertBefore) {}
3570
3571 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3572 BasicBlock *IfException, ArrayRef<Value *> Args,
3573 ArrayRef<OperandBundleDef> Bundles, unsigned Values,
3574 const Twine &NameStr, Instruction *InsertBefore);
3575 /// Construct an InvokeInst given a range of arguments.
3576 ///
3577 /// Construct an InvokeInst from a range of arguments
3578 inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3579 ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3580 unsigned Values, const Twine &NameStr,
3581 BasicBlock *InsertAtEnd);
3582
3583 bool hasDescriptor() const { return HasDescriptor; }
3584
3585 void init(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3586 ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3587 const Twine &NameStr) {
3588 init(cast<FunctionType>(
3589 cast<PointerType>(Func->getType())->getElementType()),
3590 Func, IfNormal, IfException, Args, Bundles, NameStr);
3591 }
3592
3593 void init(FunctionType *FTy, Value *Func, BasicBlock *IfNormal,
3594 BasicBlock *IfException, ArrayRef<Value *> Args,
3595 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3596
3597protected:
3598 // Note: Instruction needs to be a friend here to call cloneImpl.
3599 friend class Instruction;
3600
3601 InvokeInst *cloneImpl() const;
3602
3603public:
3604 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3605 BasicBlock *IfException, ArrayRef<Value *> Args,
3606 const Twine &NameStr,
3607 Instruction *InsertBefore = nullptr) {
3608 return Create(cast<FunctionType>(
3609 cast<PointerType>(Func->getType())->getElementType()),
3610 Func, IfNormal, IfException, Args, None, NameStr,
3611 InsertBefore);
3612 }
3613
3614 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3615 BasicBlock *IfException, ArrayRef<Value *> Args,
3616 ArrayRef<OperandBundleDef> Bundles = None,
3617 const Twine &NameStr = "",
3618 Instruction *InsertBefore = nullptr) {
3619 return Create(cast<FunctionType>(
3620 cast<PointerType>(Func->getType())->getElementType()),
3621 Func, IfNormal, IfException, Args, Bundles, NameStr,
3622 InsertBefore);
3623 }
3624
3625 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3626 BasicBlock *IfException, ArrayRef<Value *> Args,
3627 const Twine &NameStr,
3628 Instruction *InsertBefore = nullptr) {
3629 unsigned Values = unsigned(Args.size()) + 3;
3630 return new (Values) InvokeInst(Ty, Func, IfNormal, IfException, Args, None,
3631 Values, NameStr, InsertBefore);
3632 }
3633
3634 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3635 BasicBlock *IfException, ArrayRef<Value *> Args,
3636 ArrayRef<OperandBundleDef> Bundles = None,
3637 const Twine &NameStr = "",
3638 Instruction *InsertBefore = nullptr) {
3639 unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3640 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3641
3642 return new (Values, DescriptorBytes)
3643 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, Values,
3644 NameStr, InsertBefore);
3645 }
3646
3647 static InvokeInst *Create(Value *Func,
3648 BasicBlock *IfNormal, BasicBlock *IfException,
3649 ArrayRef<Value *> Args, const Twine &NameStr,
3650 BasicBlock *InsertAtEnd) {
3651 unsigned Values = unsigned(Args.size()) + 3;
3652 return new (Values) InvokeInst(Func, IfNormal, IfException, Args, None,
3653 Values, NameStr, InsertAtEnd);
3654 }
3655
3656 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3657 BasicBlock *IfException, ArrayRef<Value *> Args,
3658 ArrayRef<OperandBundleDef> Bundles,
3659 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3660 unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3661 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3662
3663 return new (Values, DescriptorBytes)
3664 InvokeInst(Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3665 InsertAtEnd);
3666 }
3667
3668 /// Create a clone of \p II with a different set of operand bundles and
3669 /// insert it before \p InsertPt.
3670 ///
3671 /// The returned invoke instruction is identical to \p II in every way except
3672 /// that the operand bundles for the new instruction are set to the operand
3673 /// bundles in \p Bundles.
3674 static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3675 Instruction *InsertPt = nullptr);
3676
3677 /// Provide fast operand accessors
3678 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
3679
3680 FunctionType *getFunctionType() const { return FTy; }
3681
3682 void mutateFunctionType(FunctionType *FTy) {
3683 mutateType(FTy->getReturnType());
3684 this->FTy = FTy;
3685 }
3686
3687 /// Return the number of invoke arguments.
3688 ///
3689 unsigned getNumArgOperands() const {
3690 return getNumOperands() - getNumTotalBundleOperands() - 3;
3691 }
3692
3693 /// getArgOperand/setArgOperand - Return/set the i-th invoke argument.
3694 ///
3695 Value *getArgOperand(unsigned i) const {
3696 assert(i < getNumArgOperands() && "Out of bounds!")(static_cast <bool> (i < getNumArgOperands() &&
"Out of bounds!") ? void (0) : __assert_fail ("i < getNumArgOperands() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3696, __extension__ __PRETTY_FUNCTION__))
;
3697 return getOperand(i);
3698 }
3699 void setArgOperand(unsigned i, Value *v) {
3700 assert(i < getNumArgOperands() && "Out of bounds!")(static_cast <bool> (i < getNumArgOperands() &&
"Out of bounds!") ? void (0) : __assert_fail ("i < getNumArgOperands() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3700, __extension__ __PRETTY_FUNCTION__))
;
3701 setOperand(i, v);
3702 }
3703
3704 /// Return the iterator pointing to the beginning of the argument list.
3705 op_iterator arg_begin() { return op_begin(); }
3706
3707 /// Return the iterator pointing to the end of the argument list.
3708 op_iterator arg_end() {
3709 // [ invoke args ], [ operand bundles ], normal dest, unwind dest, callee
3710 return op_end() - getNumTotalBundleOperands() - 3;
3711 }
3712
3713 /// Iteration adapter for range-for loops.
3714 iterator_range<op_iterator> arg_operands() {
3715 return make_range(arg_begin(), arg_end());
3716 }
3717
3718 /// Return the iterator pointing to the beginning of the argument list.
3719 const_op_iterator arg_begin() const { return op_begin(); }
3720
3721 /// Return the iterator pointing to the end of the argument list.
3722 const_op_iterator arg_end() const {
3723 // [ invoke args ], [ operand bundles ], normal dest, unwind dest, callee
3724 return op_end() - getNumTotalBundleOperands() - 3;
3725 }
3726
3727 /// Iteration adapter for range-for loops.
3728 iterator_range<const_op_iterator> arg_operands() const {
3729 return make_range(arg_begin(), arg_end());
3730 }
3731
3732 /// Wrappers for getting the \c Use of a invoke argument.
3733 const Use &getArgOperandUse(unsigned i) const {
3734 assert(i < getNumArgOperands() && "Out of bounds!")(static_cast <bool> (i < getNumArgOperands() &&
"Out of bounds!") ? void (0) : __assert_fail ("i < getNumArgOperands() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3734, __extension__ __PRETTY_FUNCTION__))
;
3735 return getOperandUse(i);
3736 }
3737 Use &getArgOperandUse(unsigned i) {
3738 assert(i < getNumArgOperands() && "Out of bounds!")(static_cast <bool> (i < getNumArgOperands() &&
"Out of bounds!") ? void (0) : __assert_fail ("i < getNumArgOperands() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3738, __extension__ __PRETTY_FUNCTION__))
;
3739 return getOperandUse(i);
3740 }
3741
3742 /// If one of the arguments has the 'returned' attribute, return its
3743 /// operand value. Otherwise, return nullptr.
3744 Value *getReturnedArgOperand() const;
3745
3746 /// getCallingConv/setCallingConv - Get or set the calling convention of this
3747 /// function call.
3748 CallingConv::ID getCallingConv() const {
3749 return static_cast<CallingConv::ID>(getSubclassDataFromInstruction());
3750 }
3751 void setCallingConv(CallingConv::ID CC) {
3752 auto ID = static_cast<unsigned>(CC);
3753 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention")(static_cast <bool> (!(ID & ~CallingConv::MaxID) &&
"Unsupported calling convention") ? void (0) : __assert_fail
("!(ID & ~CallingConv::MaxID) && \"Unsupported calling convention\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3753, __extension__ __PRETTY_FUNCTION__))
;
3754 setInstructionSubclassData(ID);
3755 }
3756
3757 /// Return the parameter attributes for this invoke.
3758 ///
3759 AttributeList getAttributes() const { return Attrs; }
3760
3761 /// Set the parameter attributes for this invoke.
3762 ///
3763 void setAttributes(AttributeList A) { Attrs = A; }
3764
3765 /// adds the attribute to the list of attributes.
3766 void addAttribute(unsigned i, Attribute::AttrKind Kind);
3767
3768 /// adds the attribute to the list of attributes.
3769 void addAttribute(unsigned i, Attribute Attr);
3770
3771 /// Adds the attribute to the indicated argument
3772 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
3773
3774 /// removes the attribute from the list of attributes.
3775 void removeAttribute(unsigned i, Attribute::AttrKind Kind);
3776
3777 /// removes the attribute from the list of attributes.
3778 void removeAttribute(unsigned i, StringRef Kind);
3779
3780 /// Removes the attribute from the given argument
3781 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
3782
3783 /// adds the dereferenceable attribute to the list of attributes.
3784 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
3785
3786 /// adds the dereferenceable_or_null attribute to the list of
3787 /// attributes.
3788 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
3789
3790 /// Determine whether this call has the given attribute.
3791 bool hasFnAttr(Attribute::AttrKind Kind) const {
3792 assert(Kind != Attribute::NoBuiltin &&(static_cast <bool> (Kind != Attribute::NoBuiltin &&
"Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin"
) ? void (0) : __assert_fail ("Kind != Attribute::NoBuiltin && \"Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3793, __extension__ __PRETTY_FUNCTION__))
3793 "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin")(static_cast <bool> (Kind != Attribute::NoBuiltin &&
"Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin"
) ? void (0) : __assert_fail ("Kind != Attribute::NoBuiltin && \"Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3793, __extension__ __PRETTY_FUNCTION__))
;
3794 return hasFnAttrImpl(Kind);
3795 }
3796
3797 /// Determine whether this call has the given attribute.
3798 bool hasFnAttr(StringRef Kind) const {
3799 return hasFnAttrImpl(Kind);
3800 }
3801
3802 /// Determine whether the return value has the given attribute.
3803 bool hasRetAttr(Attribute::AttrKind Kind) const;
3804
3805 /// Determine whether the argument or parameter has the given attribute.
3806 bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
3807
3808 /// Get the attribute of a given kind at a position.
3809 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
3810 return getAttributes().getAttribute(i, Kind);
3811 }
3812
3813 /// Get the attribute of a given kind at a position.
3814 Attribute getAttribute(unsigned i, StringRef Kind) const {
3815 return getAttributes().getAttribute(i, Kind);
3816 }
3817
3818 /// Return true if the data operand at index \p i has the attribute \p
3819 /// A.
3820 ///
3821 /// Data operands include invoke arguments and values used in operand bundles,
3822 /// but does not include the invokee operand, or the two successor blocks.
3823 /// This routine dispatches to the underlying AttributeList or the
3824 /// OperandBundleUser as appropriate.
3825 ///
3826 /// The index \p i is interpreted as
3827 ///
3828 /// \p i == Attribute::ReturnIndex -> the return value
3829 /// \p i in [1, arg_size + 1) -> argument number (\p i - 1)
3830 /// \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
3831 /// (\p i - 1) in the operand list.
3832 bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const;
3833
3834 /// Extract the alignment of the return value.
3835 unsigned getRetAlignment() const { return Attrs.getRetAlignment(); }
3836
3837 /// Extract the alignment for a call or parameter (0=unknown).
3838 unsigned getParamAlignment(unsigned ArgNo) const {
3839 return Attrs.getParamAlignment(ArgNo);
3840 }
3841
3842 /// Extract the number of dereferenceable bytes for a call or
3843 /// parameter (0=unknown).
3844 uint64_t getDereferenceableBytes(unsigned i) const {
3845 return Attrs.getDereferenceableBytes(i);
3846 }
3847
3848 /// Extract the number of dereferenceable_or_null bytes for a call or
3849 /// parameter (0=unknown).
3850 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
3851 return Attrs.getDereferenceableOrNullBytes(i);
3852 }
3853
3854 /// @brief Determine if the return value is marked with NoAlias attribute.
3855 bool returnDoesNotAlias() const {
3856 return Attrs.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
3857 }
3858
3859 /// Return true if the call should not be treated as a call to a
3860 /// builtin.
3861 bool isNoBuiltin() const {
3862 // We assert in hasFnAttr if one passes in Attribute::NoBuiltin, so we have
3863 // to check it by hand.
3864 return hasFnAttrImpl(Attribute::NoBuiltin) &&
3865 !hasFnAttrImpl(Attribute::Builtin);
3866 }
3867
3868 /// Determine if the call requires strict floating point semantics.
3869 bool isStrictFP() const { return hasFnAttr(Attribute::StrictFP); }
3870
3871 /// Return true if the call should not be inlined.
3872 bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
3873 void setIsNoInline() {
3874 addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
3875 }
3876
3877 /// Determine if the call does not access memory.
3878 bool doesNotAccessMemory() const {
3879 return hasFnAttr(Attribute::ReadNone);
3880 }
3881 void setDoesNotAccessMemory() {
3882 addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
3883 }
3884
3885 /// Determine if the call does not access or only reads memory.
3886 bool onlyReadsMemory() const {
3887 return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
3888 }
3889 void setOnlyReadsMemory() {
3890 addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
3891 }
3892
3893 /// Determine if the call does not access or only writes memory.
3894 bool doesNotReadMemory() const {
3895 return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
3896 }
3897 void setDoesNotReadMemory() {
3898 addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
3899 }
3900
3901 /// @brief Determine if the call access memmory only using it's pointer
3902 /// arguments.
3903 bool onlyAccessesArgMemory() const {
3904 return hasFnAttr(Attribute::ArgMemOnly);
3905 }
3906 void setOnlyAccessesArgMemory() {
3907 addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
3908 }
3909
3910 /// @brief Determine if the function may only access memory that is
3911 /// inaccessible from the IR.
3912 bool onlyAccessesInaccessibleMemory() const {
3913 return hasFnAttr(Attribute::InaccessibleMemOnly);
3914 }
3915 void setOnlyAccessesInaccessibleMemory() {
3916 addAttribute(AttributeList::FunctionIndex, Attribute::InaccessibleMemOnly);
3917 }
3918
3919 /// @brief Determine if the function may only access memory that is
3920 /// either inaccessible from the IR or pointed to by its arguments.
3921 bool onlyAccessesInaccessibleMemOrArgMem() const {
3922 return hasFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
3923 }
3924 void setOnlyAccessesInaccessibleMemOrArgMem() {
3925 addAttribute(AttributeList::FunctionIndex, Attribute::InaccessibleMemOrArgMemOnly);
3926 }
3927
3928 /// Determine if the call cannot return.
3929 bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
3930 void setDoesNotReturn() {
3931 addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
3932 }
3933
3934 /// Determine if the call cannot unwind.
3935 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3936 void setDoesNotThrow() {
3937 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3938 }
3939
3940 /// Determine if the invoke cannot be duplicated.
3941 bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
3942 void setCannotDuplicate() {
3943 addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
3944 }
3945
3946 /// Determine if the invoke is convergent
3947 bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
3948 void setConvergent() {
3949 addAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
3950 }
3951 void setNotConvergent() {
3952 removeAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
3953 }
3954
3955 /// Determine if the call returns a structure through first
3956 /// pointer argument.
3957 bool hasStructRetAttr() const {
3958 if (getNumArgOperands() == 0)
3959 return false;
3960
3961 // Be friendly and also check the callee.
3962 return paramHasAttr(0, Attribute::StructRet);
3963 }
3964
3965 /// Determine if any call argument is an aggregate passed by value.
3966 bool hasByValArgument() const {
3967 return Attrs.hasAttrSomewhere(Attribute::ByVal);
3968 }
3969
3970 /// Return the function called, or null if this is an
3971 /// indirect function invocation.
3972 ///
3973 Function *getCalledFunction() const {
3974 return dyn_cast<Function>(Op<-3>());
3975 }
3976
3977 /// Get a pointer to the function that is invoked by this
3978 /// instruction
3979 const Value *getCalledValue() const { return Op<-3>(); }
3980 Value *getCalledValue() { return Op<-3>(); }
3981
3982 /// Set the function called.
3983 void setCalledFunction(Value* Fn) {
3984 setCalledFunction(
3985 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
3986 Fn);
3987 }
3988 void setCalledFunction(FunctionType *FTy, Value *Fn) {
3989 this->FTy = FTy;
3990 assert(FTy == cast<FunctionType>((static_cast <bool> (FTy == cast<FunctionType>( cast
<PointerType>(Fn->getType())->getElementType())) ?
void (0) : __assert_fail ("FTy == cast<FunctionType>( cast<PointerType>(Fn->getType())->getElementType())"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3991, __extension__ __PRETTY_FUNCTION__))
3991 cast<PointerType>(Fn->getType())->getElementType()))(static_cast <bool> (FTy == cast<FunctionType>( cast
<PointerType>(Fn->getType())->getElementType())) ?
void (0) : __assert_fail ("FTy == cast<FunctionType>( cast<PointerType>(Fn->getType())->getElementType())"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 3991, __extension__ __PRETTY_FUNCTION__))
;
3992 Op<-3>() = Fn;
3993 }
3994
3995 // get*Dest - Return the destination basic blocks...
3996 BasicBlock *getNormalDest() const {
3997 return cast<BasicBlock>(Op<-2>());
3998 }
3999 BasicBlock *getUnwindDest() const {
4000 return cast<BasicBlock>(Op<-1>());
4001 }
4002 void setNormalDest(BasicBlock *B) {
4003 Op<-2>() = reinterpret_cast<Value*>(B);
4004 }
4005 void setUnwindDest(BasicBlock *B) {
4006 Op<-1>() = reinterpret_cast<Value*>(B);
4007 }
4008
4009 /// Get the landingpad instruction from the landing pad
4010 /// block (the unwind destination).
4011 LandingPadInst *getLandingPadInst() const;
4012
4013 BasicBlock *getSuccessor(unsigned i) const {
4014 assert(i < 2 && "Successor # out of range for invoke!")(static_cast <bool> (i < 2 && "Successor # out of range for invoke!"
) ? void (0) : __assert_fail ("i < 2 && \"Successor # out of range for invoke!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4014, __extension__ __PRETTY_FUNCTION__))
;
4015 return i == 0 ? getNormalDest() : getUnwindDest();
4016 }
4017
4018 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4019 assert(idx < 2 && "Successor # out of range for invoke!")(static_cast <bool> (idx < 2 && "Successor # out of range for invoke!"
) ? void (0) : __assert_fail ("idx < 2 && \"Successor # out of range for invoke!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4019, __extension__ __PRETTY_FUNCTION__))
;
4020 *(&Op<-2>() + idx) = reinterpret_cast<Value*>(NewSucc);
4021 }
4022
4023 unsigned getNumSuccessors() const { return 2; }
4024
4025 // Methods for support type inquiry through isa, cast, and dyn_cast:
4026 static bool classof(const Instruction *I) {
4027 return (I->getOpcode() == Instruction::Invoke);
4028 }
4029 static bool classof(const Value *V) {
4030 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4031 }
4032
4033private:
4034 template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
4035 if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
4036 return true;
4037
4038 // Operand bundles override attributes on the called function, but don't
4039 // override attributes directly present on the invoke instruction.
4040 if (isFnAttrDisallowedByOpBundle(Kind))
4041 return false;
4042
4043 if (const Function *F = getCalledFunction())
4044 return F->getAttributes().hasAttribute(AttributeList::FunctionIndex,
4045 Kind);
4046 return false;
4047 }
4048
4049 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4050 // method so that subclasses cannot accidentally use it.
4051 void setInstructionSubclassData(unsigned short D) {
4052 Instruction::setInstructionSubclassData(D);
4053 }
4054};
4055
4056template <>
4057struct OperandTraits<InvokeInst> : public VariadicOperandTraits<InvokeInst, 3> {
4058};
4059
4060InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
4061 BasicBlock *IfException, ArrayRef<Value *> Args,
4062 ArrayRef<OperandBundleDef> Bundles, unsigned Values,
4063 const Twine &NameStr, Instruction *InsertBefore)
4064 : TerminatorInst(Ty->getReturnType(), Instruction::Invoke,
4065 OperandTraits<InvokeInst>::op_end(this) - Values, Values,
4066 InsertBefore) {
4067 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
4068}
4069
4070InvokeInst::InvokeInst(Value *Func, BasicBlock *IfNormal,
4071 BasicBlock *IfException, ArrayRef<Value *> Args,
4072 ArrayRef<OperandBundleDef> Bundles, unsigned Values,
4073 const Twine &NameStr, BasicBlock *InsertAtEnd)
4074 : TerminatorInst(
4075 cast<FunctionType>(cast<PointerType>(Func->getType())
4076 ->getElementType())->getReturnType(),
4077 Instruction::Invoke, OperandTraits<InvokeInst>::op_end(this) - Values,
4078 Values, InsertAtEnd) {
4079 init(Func, IfNormal, IfException, Args, Bundles, NameStr);
4080}
4081
4082DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InvokeInst, Value)InvokeInst::op_iterator InvokeInst::op_begin() { return OperandTraits
<InvokeInst>::op_begin(this); } InvokeInst::const_op_iterator
InvokeInst::op_begin() const { return OperandTraits<InvokeInst
>::op_begin(const_cast<InvokeInst*>(this)); } InvokeInst
::op_iterator InvokeInst::op_end() { return OperandTraits<
InvokeInst>::op_end(this); } InvokeInst::const_op_iterator
InvokeInst::op_end() const { return OperandTraits<InvokeInst
>::op_end(const_cast<InvokeInst*>(this)); } Value *InvokeInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<InvokeInst>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<InvokeInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4082, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<InvokeInst>::op_begin(const_cast
<InvokeInst*>(this))[i_nocapture].get()); } void InvokeInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast
<bool> (i_nocapture < OperandTraits<InvokeInst>
::operands(this) && "setOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<InvokeInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4082, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
InvokeInst>::op_begin(this)[i_nocapture] = Val_nocapture; }
unsigned InvokeInst::getNumOperands() const { return OperandTraits
<InvokeInst>::operands(this); } template <int Idx_nocapture
> Use &InvokeInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
InvokeInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
4083
4084//===----------------------------------------------------------------------===//
4085// ResumeInst Class
4086//===----------------------------------------------------------------------===//
4087
4088//===---------------------------------------------------------------------------
4089/// Resume the propagation of an exception.
4090///
4091class ResumeInst : public TerminatorInst {
4092 ResumeInst(const ResumeInst &RI);
4093
4094 explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4095 ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4096
4097protected:
4098 // Note: Instruction needs to be a friend here to call cloneImpl.
4099 friend class Instruction;
4100
4101 ResumeInst *cloneImpl() const;
4102
4103public:
4104 static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4105 return new(1) ResumeInst(Exn, InsertBefore);
4106 }
4107
4108 static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4109 return new(1) ResumeInst(Exn, InsertAtEnd);
4110 }
4111
4112 /// Provide fast operand accessors
4113 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
4114
4115 /// Convenience accessor.
4116 Value *getValue() const { return Op<0>(); }
4117
4118 unsigned getNumSuccessors() const { return 0; }
4119
4120 // Methods for support type inquiry through isa, cast, and dyn_cast:
4121 static bool classof(const Instruction *I) {
4122 return I->getOpcode() == Instruction::Resume;
4123 }
4124 static bool classof(const Value *V) {
4125 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4126 }
4127
4128private:
4129 friend TerminatorInst;
4130
4131 BasicBlock *getSuccessor(unsigned idx) const {
4132 llvm_unreachable("ResumeInst has no successors!")::llvm::llvm_unreachable_internal("ResumeInst has no successors!"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4132)
;
4133 }
4134
4135 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4136 llvm_unreachable("ResumeInst has no successors!")::llvm::llvm_unreachable_internal("ResumeInst has no successors!"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4136)
;
4137 }
4138};
4139
4140template <>
4141struct OperandTraits<ResumeInst> :
4142 public FixedNumOperandTraits<ResumeInst, 1> {
4143};
4144
4145DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)ResumeInst::op_iterator ResumeInst::op_begin() { return OperandTraits
<ResumeInst>::op_begin(this); } ResumeInst::const_op_iterator
ResumeInst::op_begin() const { return OperandTraits<ResumeInst
>::op_begin(const_cast<ResumeInst*>(this)); } ResumeInst
::op_iterator ResumeInst::op_end() { return OperandTraits<
ResumeInst>::op_end(this); } ResumeInst::const_op_iterator
ResumeInst::op_end() const { return OperandTraits<ResumeInst
>::op_end(const_cast<ResumeInst*>(this)); } Value *ResumeInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<ResumeInst>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<ResumeInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4145, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<ResumeInst>::op_begin(const_cast
<ResumeInst*>(this))[i_nocapture].get()); } void ResumeInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast
<bool> (i_nocapture < OperandTraits<ResumeInst>
::operands(this) && "setOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<ResumeInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4145, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
ResumeInst>::op_begin(this)[i_nocapture] = Val_nocapture; }
unsigned ResumeInst::getNumOperands() const { return OperandTraits
<ResumeInst>::operands(this); } template <int Idx_nocapture
> Use &ResumeInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
ResumeInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
4146
4147//===----------------------------------------------------------------------===//
4148// CatchSwitchInst Class
4149//===----------------------------------------------------------------------===//
4150class CatchSwitchInst : public TerminatorInst {
4151 /// The number of operands actually allocated. NumOperands is
4152 /// the number actually in use.
4153 unsigned ReservedSpace;
4154
4155 // Operand[0] = Outer scope
4156 // Operand[1] = Unwind block destination
4157 // Operand[n] = BasicBlock to go to on match
4158 CatchSwitchInst(const CatchSwitchInst &CSI);
4159
4160 /// Create a new switch instruction, specifying a
4161 /// default destination. The number of additional handlers can be specified
4162 /// here to make memory allocation more efficient.
4163 /// This constructor can also autoinsert before another instruction.
4164 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4165 unsigned NumHandlers, const Twine &NameStr,
4166 Instruction *InsertBefore);
4167
4168 /// Create a new switch instruction, specifying a
4169 /// default destination. The number of additional handlers can be specified
4170 /// here to make memory allocation more efficient.
4171 /// This constructor also autoinserts at the end of the specified BasicBlock.
4172 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4173 unsigned NumHandlers, const Twine &NameStr,
4174 BasicBlock *InsertAtEnd);
4175
4176 // allocate space for exactly zero operands
4177 void *operator new(size_t s) { return User::operator new(s); }
4178
4179 void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4180 void growOperands(unsigned Size);
4181
4182protected:
4183 // Note: Instruction needs to be a friend here to call cloneImpl.
4184 friend class Instruction;
4185
4186 CatchSwitchInst *cloneImpl() const;
4187
4188public:
4189 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4190 unsigned NumHandlers,
4191 const Twine &NameStr = "",
4192 Instruction *InsertBefore = nullptr) {
4193 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4194 InsertBefore);
4195 }
4196
4197 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4198 unsigned NumHandlers, const Twine &NameStr,
4199 BasicBlock *InsertAtEnd) {
4200 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4201 InsertAtEnd);
4202 }
4203
4204 /// Provide fast operand accessors
4205 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
4206
4207 // Accessor Methods for CatchSwitch stmt
4208 Value *getParentPad() const { return getOperand(0); }
4209 void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4210
4211 // Accessor Methods for CatchSwitch stmt
4212 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4213 bool unwindsToCaller() const { return !hasUnwindDest(); }
4214 BasicBlock *getUnwindDest() const {
4215 if (hasUnwindDest())
4216 return cast<BasicBlock>(getOperand(1));
4217 return nullptr;
4218 }
4219 void setUnwindDest(BasicBlock *UnwindDest) {
4220 assert(UnwindDest)(static_cast <bool> (UnwindDest) ? void (0) : __assert_fail
("UnwindDest", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4220, __extension__ __PRETTY_FUNCTION__))
;
4221 assert(hasUnwindDest())(static_cast <bool> (hasUnwindDest()) ? void (0) : __assert_fail
("hasUnwindDest()", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4221, __extension__ __PRETTY_FUNCTION__))
;
4222 setOperand(1, UnwindDest);
4223 }
4224
4225 /// return the number of 'handlers' in this catchswitch
4226 /// instruction, except the default handler
4227 unsigned getNumHandlers() const {
4228 if (hasUnwindDest())
4229 return getNumOperands() - 2;
4230 return getNumOperands() - 1;
4231 }
4232
4233private:
4234 static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4235 static const BasicBlock *handler_helper(const Value *V) {
4236 return cast<BasicBlock>(V);
4237 }
4238
4239public:
4240 using DerefFnTy = BasicBlock *(*)(Value *);
4241 using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>;
4242 using handler_range = iterator_range<handler_iterator>;
4243 using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
4244 using const_handler_iterator =
4245 mapped_iterator<const_op_iterator, ConstDerefFnTy>;
4246 using const_handler_range = iterator_range<const_handler_iterator>;
4247
4248 /// Returns an iterator that points to the first handler in CatchSwitchInst.
4249 handler_iterator handler_begin() {
4250 op_iterator It = op_begin() + 1;
4251 if (hasUnwindDest())
4252 ++It;
4253 return handler_iterator(It, DerefFnTy(handler_helper));
4254 }
4255
4256 /// Returns an iterator that points to the first handler in the
4257 /// CatchSwitchInst.
4258 const_handler_iterator handler_begin() const {
4259 const_op_iterator It = op_begin() + 1;
4260 if (hasUnwindDest())
4261 ++It;
4262 return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4263 }
4264
4265 /// Returns a read-only iterator that points one past the last
4266 /// handler in the CatchSwitchInst.
4267 handler_iterator handler_end() {
4268 return handler_iterator(op_end(), DerefFnTy(handler_helper));
4269 }
4270
4271 /// Returns an iterator that points one past the last handler in the
4272 /// CatchSwitchInst.
4273 const_handler_iterator handler_end() const {
4274 return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4275 }
4276
4277 /// iteration adapter for range-for loops.
4278 handler_range handlers() {
4279 return make_range(handler_begin(), handler_end());
4280 }
4281
4282 /// iteration adapter for range-for loops.
4283 const_handler_range handlers() const {
4284 return make_range(handler_begin(), handler_end());
4285 }
4286
4287 /// Add an entry to the switch instruction...
4288 /// Note:
4289 /// This action invalidates handler_end(). Old handler_end() iterator will
4290 /// point to the added handler.
4291 void addHandler(BasicBlock *Dest);
4292
4293 void removeHandler(handler_iterator HI);
4294
4295 unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4296 BasicBlock *getSuccessor(unsigned Idx) const {
4297 assert(Idx < getNumSuccessors() &&(static_cast <bool> (Idx < getNumSuccessors() &&
"Successor # out of range for catchswitch!") ? void (0) : __assert_fail
("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4298, __extension__ __PRETTY_FUNCTION__))
4298 "Successor # out of range for catchswitch!")(static_cast <bool> (Idx < getNumSuccessors() &&
"Successor # out of range for catchswitch!") ? void (0) : __assert_fail
("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4298, __extension__ __PRETTY_FUNCTION__))
;
4299 return cast<BasicBlock>(getOperand(Idx + 1));
4300 }
4301 void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4302 assert(Idx < getNumSuccessors() &&(static_cast <bool> (Idx < getNumSuccessors() &&
"Successor # out of range for catchswitch!") ? void (0) : __assert_fail
("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4303, __extension__ __PRETTY_FUNCTION__))
4303 "Successor # out of range for catchswitch!")(static_cast <bool> (Idx < getNumSuccessors() &&
"Successor # out of range for catchswitch!") ? void (0) : __assert_fail
("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4303, __extension__ __PRETTY_FUNCTION__))
;
4304 setOperand(Idx + 1, NewSucc);
4305 }
4306
4307 // Methods for support type inquiry through isa, cast, and dyn_cast:
4308 static bool classof(const Instruction *I) {
4309 return I->getOpcode() == Instruction::CatchSwitch;
4310 }
4311 static bool classof(const Value *V) {
4312 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4313 }
4314};
4315
4316template <>
4317struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {};
4318
4319DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)CatchSwitchInst::op_iterator CatchSwitchInst::op_begin() { return
OperandTraits<CatchSwitchInst>::op_begin(this); } CatchSwitchInst
::const_op_iterator CatchSwitchInst::op_begin() const { return
OperandTraits<CatchSwitchInst>::op_begin(const_cast<
CatchSwitchInst*>(this)); } CatchSwitchInst::op_iterator CatchSwitchInst
::op_end() { return OperandTraits<CatchSwitchInst>::op_end
(this); } CatchSwitchInst::const_op_iterator CatchSwitchInst::
op_end() const { return OperandTraits<CatchSwitchInst>::
op_end(const_cast<CatchSwitchInst*>(this)); } Value *CatchSwitchInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<CatchSwitchInst>::
operands(this) && "getOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<CatchSwitchInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4319, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<CatchSwitchInst>::op_begin
(const_cast<CatchSwitchInst*>(this))[i_nocapture].get()
); } void CatchSwitchInst::setOperand(unsigned i_nocapture, Value
*Val_nocapture) { (static_cast <bool> (i_nocapture <
OperandTraits<CatchSwitchInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<CatchSwitchInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4319, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
CatchSwitchInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned CatchSwitchInst::getNumOperands() const { return
OperandTraits<CatchSwitchInst>::operands(this); } template
<int Idx_nocapture> Use &CatchSwitchInst::Op() { return
this->OpFrom<Idx_nocapture>(this); } template <int
Idx_nocapture> const Use &CatchSwitchInst::Op() const
{ return this->OpFrom<Idx_nocapture>(this); }
4320
4321//===----------------------------------------------------------------------===//
4322// CleanupPadInst Class
4323//===----------------------------------------------------------------------===//
4324class CleanupPadInst : public FuncletPadInst {
4325private:
4326 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4327 unsigned Values, const Twine &NameStr,
4328 Instruction *InsertBefore)
4329 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4330 NameStr, InsertBefore) {}
4331 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4332 unsigned Values, const Twine &NameStr,
4333 BasicBlock *InsertAtEnd)
4334 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4335 NameStr, InsertAtEnd) {}
4336
4337public:
4338 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4339 const Twine &NameStr = "",
4340 Instruction *InsertBefore = nullptr) {
4341 unsigned Values = 1 + Args.size();
4342 return new (Values)
4343 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4344 }
4345
4346 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4347 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4348 unsigned Values = 1 + Args.size();
4349 return new (Values)
4350 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4351 }
4352
4353 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4354 static bool classof(const Instruction *I) {
4355 return I->getOpcode() == Instruction::CleanupPad;
4356 }
4357 static bool classof(const Value *V) {
4358 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4359 }
4360};
4361
4362//===----------------------------------------------------------------------===//
4363// CatchPadInst Class
4364//===----------------------------------------------------------------------===//
4365class CatchPadInst : public FuncletPadInst {
4366private:
4367 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4368 unsigned Values, const Twine &NameStr,
4369 Instruction *InsertBefore)
4370 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4371 NameStr, InsertBefore) {}
4372 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4373 unsigned Values, const Twine &NameStr,
4374 BasicBlock *InsertAtEnd)
4375 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4376 NameStr, InsertAtEnd) {}
4377
4378public:
4379 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4380 const Twine &NameStr = "",
4381 Instruction *InsertBefore = nullptr) {
4382 unsigned Values = 1 + Args.size();
4383 return new (Values)
4384 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4385 }
4386
4387 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4388 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4389 unsigned Values = 1 + Args.size();
4390 return new (Values)
4391 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4392 }
4393
4394 /// Convenience accessors
4395 CatchSwitchInst *getCatchSwitch() const {
4396 return cast<CatchSwitchInst>(Op<-1>());
4397 }
4398 void setCatchSwitch(Value *CatchSwitch) {
4399 assert(CatchSwitch)(static_cast <bool> (CatchSwitch) ? void (0) : __assert_fail
("CatchSwitch", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4399, __extension__ __PRETTY_FUNCTION__))
;
4400 Op<-1>() = CatchSwitch;
4401 }
4402
4403 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4404 static bool classof(const Instruction *I) {
4405 return I->getOpcode() == Instruction::CatchPad;
4406 }
4407 static bool classof(const Value *V) {
4408 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4409 }
4410};
4411
4412//===----------------------------------------------------------------------===//
4413// CatchReturnInst Class
4414//===----------------------------------------------------------------------===//
4415
4416class CatchReturnInst : public TerminatorInst {
4417 CatchReturnInst(const CatchReturnInst &RI);
4418 CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4419 CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4420
4421 void init(Value *CatchPad, BasicBlock *BB);
4422
4423protected:
4424 // Note: Instruction needs to be a friend here to call cloneImpl.
4425 friend class Instruction;
4426
4427 CatchReturnInst *cloneImpl() const;
4428
4429public:
4430 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4431 Instruction *InsertBefore = nullptr) {
4432 assert(CatchPad)(static_cast <bool> (CatchPad) ? void (0) : __assert_fail
("CatchPad", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4432, __extension__ __PRETTY_FUNCTION__))
;
4433 assert(BB)(static_cast <bool> (BB) ? void (0) : __assert_fail ("BB"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4433, __extension__ __PRETTY_FUNCTION__))
;
4434 return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4435 }
4436
4437 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4438 BasicBlock *InsertAtEnd) {
4439 assert(CatchPad)(static_cast <bool> (CatchPad) ? void (0) : __assert_fail
("CatchPad", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4439, __extension__ __PRETTY_FUNCTION__))
;
4440 assert(BB)(static_cast <bool> (BB) ? void (0) : __assert_fail ("BB"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4440, __extension__ __PRETTY_FUNCTION__))
;
4441 return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4442 }
4443
4444 /// Provide fast operand accessors
4445 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
4446
4447 /// Convenience accessors.
4448 CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4449 void setCatchPad(CatchPadInst *CatchPad) {
4450 assert(CatchPad)(static_cast <bool> (CatchPad) ? void (0) : __assert_fail
("CatchPad", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4450, __extension__ __PRETTY_FUNCTION__))
;
4451 Op<0>() = CatchPad;
4452 }
4453
4454 BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4455 void setSuccessor(BasicBlock *NewSucc) {
4456 assert(NewSucc)(static_cast <bool> (NewSucc) ? void (0) : __assert_fail
("NewSucc", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4456, __extension__ __PRETTY_FUNCTION__))
;
4457 Op<1>() = NewSucc;
4458 }
4459 unsigned getNumSuccessors() const { return 1; }
4460
4461 /// Get the parentPad of this catchret's catchpad's catchswitch.
4462 /// The successor block is implicitly a member of this funclet.
4463 Value *getCatchSwitchParentPad() const {
4464 return getCatchPad()->getCatchSwitch()->getParentPad();
4465 }
4466
4467 // Methods for support type inquiry through isa, cast, and dyn_cast:
4468 static bool classof(const Instruction *I) {
4469 return (I->getOpcode() == Instruction::CatchRet);
4470 }
4471 static bool classof(const Value *V) {
4472 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4473 }
4474
4475private:
4476 friend TerminatorInst;
4477
4478 BasicBlock *getSuccessor(unsigned Idx) const {
4479 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!")(static_cast <bool> (Idx < getNumSuccessors() &&
"Successor # out of range for catchret!") ? void (0) : __assert_fail
("Idx < getNumSuccessors() && \"Successor # out of range for catchret!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4479, __extension__ __PRETTY_FUNCTION__))
;
4480 return getSuccessor();
4481 }
4482
4483 void setSuccessor(unsigned Idx, BasicBlock *B) {
4484 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!")(static_cast <bool> (Idx < getNumSuccessors() &&
"Successor # out of range for catchret!") ? void (0) : __assert_fail
("Idx < getNumSuccessors() && \"Successor # out of range for catchret!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4484, __extension__ __PRETTY_FUNCTION__))
;
4485 setSuccessor(B);
4486 }
4487};
4488
4489template <>
4490struct OperandTraits<CatchReturnInst>
4491 : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4492
4493DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)CatchReturnInst::op_iterator CatchReturnInst::op_begin() { return
OperandTraits<CatchReturnInst>::op_begin(this); } CatchReturnInst
::const_op_iterator CatchReturnInst::op_begin() const { return
OperandTraits<CatchReturnInst>::op_begin(const_cast<
CatchReturnInst*>(this)); } CatchReturnInst::op_iterator CatchReturnInst
::op_end() { return OperandTraits<CatchReturnInst>::op_end
(this); } CatchReturnInst::const_op_iterator CatchReturnInst::
op_end() const { return OperandTraits<CatchReturnInst>::
op_end(const_cast<CatchReturnInst*>(this)); } Value *CatchReturnInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<CatchReturnInst>::
operands(this) && "getOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<CatchReturnInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4493, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<CatchReturnInst>::op_begin
(const_cast<CatchReturnInst*>(this))[i_nocapture].get()
); } void CatchReturnInst::setOperand(unsigned i_nocapture, Value
*Val_nocapture) { (static_cast <bool> (i_nocapture <
OperandTraits<CatchReturnInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<CatchReturnInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4493, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
CatchReturnInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned CatchReturnInst::getNumOperands() const { return
OperandTraits<CatchReturnInst>::operands(this); } template
<int Idx_nocapture> Use &CatchReturnInst::Op() { return
this->OpFrom<Idx_nocapture>(this); } template <int
Idx_nocapture> const Use &CatchReturnInst::Op() const
{ return this->OpFrom<Idx_nocapture>(this); }
4494
4495//===----------------------------------------------------------------------===//
4496// CleanupReturnInst Class
4497//===----------------------------------------------------------------------===//
4498
4499class CleanupReturnInst : public TerminatorInst {
4500private:
4501 CleanupReturnInst(const CleanupReturnInst &RI);
4502 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4503 Instruction *InsertBefore = nullptr);
4504 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4505 BasicBlock *InsertAtEnd);
4506
4507 void init(Value *CleanupPad, BasicBlock *UnwindBB);
4508
4509protected:
4510 // Note: Instruction needs to be a friend here to call cloneImpl.
4511 friend class Instruction;
4512
4513 CleanupReturnInst *cloneImpl() const;
4514
4515public:
4516 static CleanupReturnInst *Create(Value *CleanupPad,
4517 BasicBlock *UnwindBB = nullptr,
4518 Instruction *InsertBefore = nullptr) {
4519 assert(CleanupPad)(static_cast <bool> (CleanupPad) ? void (0) : __assert_fail
("CleanupPad", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4519, __extension__ __PRETTY_FUNCTION__))
;
4520 unsigned Values = 1;
4521 if (UnwindBB)
4522 ++Values;
4523 return new (Values)
4524 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4525 }
4526
4527 static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4528 BasicBlock *InsertAtEnd) {
4529 assert(CleanupPad)(static_cast <bool> (CleanupPad) ? void (0) : __assert_fail
("CleanupPad", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4529, __extension__ __PRETTY_FUNCTION__))
;
4530 unsigned Values = 1;
4531 if (UnwindBB)
4532 ++Values;
4533 return new (Values)
4534 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4535 }
4536
4537 /// Provide fast operand accessors
4538 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
4539
4540 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4541 bool unwindsToCaller() const { return !hasUnwindDest(); }
4542
4543 /// Convenience accessor.
4544 CleanupPadInst *getCleanupPad() const {
4545 return cast<CleanupPadInst>(Op<0>());
4546 }
4547 void setCleanupPad(CleanupPadInst *CleanupPad) {
4548 assert(CleanupPad)(static_cast <bool> (CleanupPad) ? void (0) : __assert_fail
("CleanupPad", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4548, __extension__ __PRETTY_FUNCTION__))
;
4549 Op<0>() = CleanupPad;
4550 }
4551
4552 unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4553
4554 BasicBlock *getUnwindDest() const {
4555 return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4556 }
4557 void setUnwindDest(BasicBlock *NewDest) {
4558 assert(NewDest)(static_cast <bool> (NewDest) ? void (0) : __assert_fail
("NewDest", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4558, __extension__ __PRETTY_FUNCTION__))
;
4559 assert(hasUnwindDest())(static_cast <bool> (hasUnwindDest()) ? void (0) : __assert_fail
("hasUnwindDest()", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4559, __extension__ __PRETTY_FUNCTION__))
;
4560 Op<1>() = NewDest;
4561 }
4562
4563 // Methods for support type inquiry through isa, cast, and dyn_cast:
4564 static bool classof(const Instruction *I) {
4565 return (I->getOpcode() == Instruction::CleanupRet);
4566 }
4567 static bool classof(const Value *V) {
4568 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4569 }
4570
4571private:
4572 friend TerminatorInst;
4573
4574 BasicBlock *getSuccessor(unsigned Idx) const {
4575 assert(Idx == 0)(static_cast <bool> (Idx == 0) ? void (0) : __assert_fail
("Idx == 0", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4575, __extension__ __PRETTY_FUNCTION__))
;
4576 return getUnwindDest();
4577 }
4578
4579 void setSuccessor(unsigned Idx, BasicBlock *B) {
4580 assert(Idx == 0)(static_cast <bool> (Idx == 0) ? void (0) : __assert_fail
("Idx == 0", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4580, __extension__ __PRETTY_FUNCTION__))
;
4581 setUnwindDest(B);
4582 }
4583
4584 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4585 // method so that subclasses cannot accidentally use it.
4586 void setInstructionSubclassData(unsigned short D) {
4587 Instruction::setInstructionSubclassData(D);
4588 }
4589};
4590
4591template <>
4592struct OperandTraits<CleanupReturnInst>
4593 : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4594
4595DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)CleanupReturnInst::op_iterator CleanupReturnInst::op_begin() {
return OperandTraits<CleanupReturnInst>::op_begin(this
); } CleanupReturnInst::const_op_iterator CleanupReturnInst::
op_begin() const { return OperandTraits<CleanupReturnInst>
::op_begin(const_cast<CleanupReturnInst*>(this)); } CleanupReturnInst
::op_iterator CleanupReturnInst::op_end() { return OperandTraits
<CleanupReturnInst>::op_end(this); } CleanupReturnInst::
const_op_iterator CleanupReturnInst::op_end() const { return OperandTraits
<CleanupReturnInst>::op_end(const_cast<CleanupReturnInst
*>(this)); } Value *CleanupReturnInst::getOperand(unsigned
i_nocapture) const { (static_cast <bool> (i_nocapture <
OperandTraits<CleanupReturnInst>::operands(this) &&
"getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<CleanupReturnInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4595, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<CleanupReturnInst>::op_begin
(const_cast<CleanupReturnInst*>(this))[i_nocapture].get
()); } void CleanupReturnInst::setOperand(unsigned i_nocapture
, Value *Val_nocapture) { (static_cast <bool> (i_nocapture
< OperandTraits<CleanupReturnInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<CleanupReturnInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4595, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
CleanupReturnInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned CleanupReturnInst::getNumOperands() const { return
OperandTraits<CleanupReturnInst>::operands(this); } template
<int Idx_nocapture> Use &CleanupReturnInst::Op() {
return this->OpFrom<Idx_nocapture>(this); } template
<int Idx_nocapture> const Use &CleanupReturnInst::
Op() const { return this->OpFrom<Idx_nocapture>(this
); }
4596
4597//===----------------------------------------------------------------------===//
4598// UnreachableInst Class
4599//===----------------------------------------------------------------------===//
4600
4601//===---------------------------------------------------------------------------
4602/// This function has undefined behavior. In particular, the
4603/// presence of this instruction indicates some higher level knowledge that the
4604/// end of the block cannot be reached.
4605///
4606class UnreachableInst : public TerminatorInst {
4607protected:
4608 // Note: Instruction needs to be a friend here to call cloneImpl.
4609 friend class Instruction;
4610
4611 UnreachableInst *cloneImpl() const;
4612
4613public:
4614 explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4615 explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4616
4617 // allocate space for exactly zero operands
4618 void *operator new(size_t s) {
4619 return User::operator new(s, 0);
4620 }
4621
4622 unsigned getNumSuccessors() const { return 0; }
4623
4624 // Methods for support type inquiry through isa, cast, and dyn_cast:
4625 static bool classof(const Instruction *I) {
4626 return I->getOpcode() == Instruction::Unreachable;
4627 }
4628 static bool classof(const Value *V) {
4629 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4630 }
4631
4632private:
4633 friend TerminatorInst;
4634
4635 BasicBlock *getSuccessor(unsigned idx) const {
4636 llvm_unreachable("UnreachableInst has no successors!")::llvm::llvm_unreachable_internal("UnreachableInst has no successors!"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4636)
;
4637 }
4638
4639 void setSuccessor(unsigned idx, BasicBlock *B) {
4640 llvm_unreachable("UnreachableInst has no successors!")::llvm::llvm_unreachable_internal("UnreachableInst has no successors!"
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instructions.h"
, 4640)
;
4641 }
4642};
4643
4644//===----------------------------------------------------------------------===//
4645// TruncInst Class
4646//===----------------------------------------------------------------------===//
4647
4648/// This class represents a truncation of integer types.
4649class TruncInst : public CastInst {
4650protected:
4651 // Note: Instruction needs to be a friend here to call cloneImpl.
4652 friend class Instruction;
4653
4654 /// Clone an identical TruncInst
4655 TruncInst *cloneImpl() const;
4656
4657public:
4658 /// Constructor with insert-before-instruction semantics
4659 TruncInst(
4660 Value *S, ///< The value to be truncated
4661 Type *Ty, ///< The (smaller) type to truncate to
4662 const Twine &NameStr = "", ///< A name for the new instruction
4663 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4664 );
4665
4666 /// Constructor with insert-at-end-of-block semantics
4667 TruncInst(
4668 Value *S, ///< The value to be truncated
4669 Type *Ty, ///< The (smaller) type to truncate to
4670 const Twine &NameStr, ///< A name for the new instruction
4671 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4672 );
4673
4674 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4675 static bool classof(const Instruction *I) {
4676 return I->getOpcode() == Trunc;
4677 }
4678 static bool classof(const Value *V) {
4679 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4680 }
4681};
4682
4683//===----------------------------------------------------------------------===//
4684// ZExtInst Class
4685//===----------------------------------------------------------------------===//
4686
4687/// This class represents zero extension of integer types.
4688class ZExtInst : public CastInst {
4689protected:
4690 // Note: Instruction needs to be a friend here to call cloneImpl.
4691 friend class Instruction;
4692
4693 /// Clone an identical ZExtInst
4694 ZExtInst *cloneImpl() const;
4695
4696public:
4697 /// Constructor with insert-before-instruction semantics
4698 ZExtInst(
4699 Value *S, ///< The value to be zero extended
4700 Type *Ty, ///< The type to zero extend to
4701 const Twine &NameStr = "", ///< A name for the new instruction
4702 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4703 );
4704
4705 /// Constructor with insert-at-end semantics.
4706 ZExtInst(
4707 Value *S, ///< The value to be zero extended
4708 Type *Ty, ///< The type to zero extend to
4709 const Twine &NameStr, ///< A name for the new instruction
4710 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4711 );
4712
4713 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4714 static bool classof(const Instruction *I) {
4715 return I->getOpcode() == ZExt;
4716 }
4717 static bool classof(const Value *V) {
4718 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4719 }
4720};
4721
4722//===----------------------------------------------------------------------===//
4723// SExtInst Class
4724//===----------------------------------------------------------------------===//
4725
4726/// This class represents a sign extension of integer types.
4727class SExtInst : public CastInst {
4728protected:
4729 // Note: Instruction needs to be a friend here to call cloneImpl.
4730 friend class Instruction;
4731
4732 /// Clone an identical SExtInst
4733 SExtInst *cloneImpl() const;
4734
4735public:
4736 /// Constructor with insert-before-instruction semantics
4737 SExtInst(
4738 Value *S, ///< The value to be sign extended
4739 Type *Ty, ///< The type to sign extend to
4740 const Twine &NameStr = "", ///< A name for the new instruction
4741 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4742 );
4743
4744 /// Constructor with insert-at-end-of-block semantics
4745 SExtInst(
4746 Value *S, ///< The value to be sign extended
4747 Type *Ty, ///< The type to sign extend to
4748 const Twine &NameStr, ///< A name for the new instruction
4749 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4750 );
4751
4752 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4753 static bool classof(const Instruction *I) {
4754 return I->getOpcode() == SExt;
4755 }
4756 static bool classof(const Value *V) {
4757 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4758 }
4759};
4760
4761//===----------------------------------------------------------------------===//
4762// FPTruncInst Class
4763//===----------------------------------------------------------------------===//
4764
4765/// This class represents a truncation of floating point types.
4766class FPTruncInst : public CastInst {
4767protected:
4768 // Note: Instruction needs to be a friend here to call cloneImpl.
4769 friend class Instruction;
4770
4771 /// Clone an identical FPTruncInst
4772 FPTruncInst *cloneImpl() const;
4773
4774public:
4775 /// Constructor with insert-before-instruction semantics
4776 FPTruncInst(
4777 Value *S, ///< The value to be truncated
4778 Type *Ty, ///< The type to truncate to
4779 const Twine &NameStr = "", ///< A name for the new instruction
4780 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4781 );
4782
4783 /// Constructor with insert-before-instruction semantics
4784 FPTruncInst(
4785 Value *S, ///< The value to be truncated
4786 Type *Ty, ///< The type to truncate to
4787 const Twine &NameStr, ///< A name for the new instruction
4788 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4789 );
4790
4791 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4792 static bool classof(const Instruction *I) {
4793 return I->getOpcode() == FPTrunc;
4794 }
4795 static bool classof(const Value *V) {
4796 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4797 }
4798};
4799
4800//===----------------------------------------------------------------------===//
4801// FPExtInst Class
4802//===----------------------------------------------------------------------===//
4803
4804/// This class represents an extension of floating point types.
4805class FPExtInst : public CastInst {
4806protected:
4807 // Note: Instruction needs to be a friend here to call cloneImpl.
4808 friend class Instruction;
4809
4810 /// Clone an identical FPExtInst
4811 FPExtInst *cloneImpl() const;
4812
4813public:
4814 /// Constructor with insert-before-instruction semantics
4815 FPExtInst(
4816 Value *S, ///< The value to be extended
4817 Type *Ty, ///< The type to extend to
4818 const Twine &NameStr = "", ///< A name for the new instruction
4819 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4820 );
4821
4822 /// Constructor with insert-at-end-of-block semantics
4823 FPExtInst(
4824 Value *S, ///< The value to be extended
4825 Type *Ty, ///< The type to extend to
4826 const Twine &NameStr, ///< A name for the new instruction
4827 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4828 );
4829
4830 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4831 static bool classof(const Instruction *I) {
4832 return I->getOpcode() == FPExt;
4833 }
4834 static bool classof(const Value *V) {
4835 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4836 }
4837};
4838
4839//===----------------------------------------------------------------------===//
4840// UIToFPInst Class
4841//===----------------------------------------------------------------------===//
4842
4843/// This class represents a cast unsigned integer to floating point.
4844class UIToFPInst : public CastInst {
4845protected:
4846 // Note: Instruction needs to be a friend here to call cloneImpl.
4847 friend class Instruction;
4848
4849 /// Clone an identical UIToFPInst
4850 UIToFPInst *cloneImpl() const;
4851
4852public:
4853 /// Constructor with insert-before-instruction semantics
4854 UIToFPInst(
4855 Value *S, ///< The value to be converted
4856 Type *Ty, ///< The type to convert to
4857 const Twine &NameStr = "", ///< A name for the new instruction
4858 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4859 );
4860
4861 /// Constructor with insert-at-end-of-block semantics
4862 UIToFPInst(
4863 Value *S, ///< The value to be converted
4864 Type *Ty, ///< The type to convert to
4865 const Twine &NameStr, ///< A name for the new instruction
4866 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4867 );
4868
4869 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4870 static bool classof(const Instruction *I) {
4871 return I->getOpcode() == UIToFP;
4872 }
4873 static bool classof(const Value *V) {
4874 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4875 }
4876};
4877
4878//===----------------------------------------------------------------------===//
4879// SIToFPInst Class
4880//===----------------------------------------------------------------------===//
4881
4882/// This class represents a cast from signed integer to floating point.
4883class SIToFPInst : public CastInst {
4884protected:
4885 // Note: Instruction needs to be a friend here to call cloneImpl.
4886 friend class Instruction;
4887
4888 /// Clone an identical SIToFPInst
4889 SIToFPInst *cloneImpl() const;
4890
4891public:
4892 /// Constructor with insert-before-instruction semantics
4893 SIToFPInst(
4894 Value *S, ///< The value to be converted
4895 Type *Ty, ///< The type to convert to
4896 const Twine &NameStr = "", ///< A name for the new instruction
4897 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4898 );
4899
4900 /// Constructor with insert-at-end-of-block semantics
4901 SIToFPInst(
4902 Value *S, ///< The value to be converted
4903 Type *Ty, ///< The type to convert to
4904 const Twine &NameStr, ///< A name for the new instruction
4905 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4906 );
4907
4908 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4909 static bool classof(const Instruction *I) {
4910 return I->getOpcode() == SIToFP;
4911 }
4912 static bool classof(const Value *V) {
4913 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4914 }
4915};
4916
4917//===----------------------------------------------------------------------===//
4918// FPToUIInst Class
4919//===----------------------------------------------------------------------===//
4920
4921/// This class represents a cast from floating point to unsigned integer
4922class FPToUIInst : public CastInst {
4923protected:
4924 // Note: Instruction needs to be a friend here to call cloneImpl.
4925 friend class Instruction;
4926
4927 /// Clone an identical FPToUIInst
4928 FPToUIInst *cloneImpl() const;
4929
4930public:
4931 /// Constructor with insert-before-instruction semantics
4932 FPToUIInst(
4933 Value *S, ///< The value to be converted
4934 Type *Ty, ///< The type to convert to
4935 const Twine &NameStr = "", ///< A name for the new instruction
4936 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4937 );
4938
4939 /// Constructor with insert-at-end-of-block semantics
4940 FPToUIInst(
4941 Value *S, ///< The value to be converted
4942 Type *Ty, ///< The type to convert to
4943 const Twine &NameStr, ///< A name for the new instruction
4944 BasicBlock *InsertAtEnd ///< Where to insert the new instruction
4945 );
4946
4947 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4948 static bool classof(const Instruction *I) {
4949 return I->getOpcode() == FPToUI;
4950 }
4951 static bool classof(const Value *V) {
4952 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4953 }
4954};
4955
4956//===----------------------------------------------------------------------===//
4957// FPToSIInst Class
4958//===----------------------------------------------------------------------===//
4959
4960/// This class represents a cast from floating point to signed integer.
4961class FPToSIInst : public CastInst {
4962protected:
4963 // Note: Instruction needs to be a friend here to call cloneImpl.
4964 friend class Instruction;
4965
4966 /// Clone an identical FPToSIInst
4967 FPToSIInst *cloneImpl() const;
4968
4969public:
4970 /// Constructor with insert-before-instruction semantics
4971 FPToSIInst(
4972 Value *S, ///< The value to be converted
4973 Type *Ty, ///< The type to convert to
4974 const Twine &NameStr = "", ///< A name for the new instruction
4975 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4976 );
4977
4978 /// Constructor with insert-at-end-of-block semantics
4979 FPToSIInst(
4980 Value *S, ///< The value to be converted
4981 Type *Ty, ///< The type to convert to
4982 const Twine &NameStr, ///< A name for the new instruction
4983 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4984 );
4985
4986 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4987 static bool classof(const Instruction *I) {
4988 return I->getOpcode() == FPToSI;
4989 }
4990 static bool classof(const Value *V) {
4991 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4992 }
4993};
4994
4995//===----------------------------------------------------------------------===//
4996// IntToPtrInst Class
4997//===----------------------------------------------------------------------===//
4998
4999/// This class represents a cast from an integer to a pointer.
5000class IntToPtrInst : public CastInst {
5001public:
5002 // Note: Instruction needs to be a friend here to call cloneImpl.
5003 friend class Instruction;
5004
5005 /// Constructor with insert-before-instruction semantics
5006 IntToPtrInst(
5007 Value *S, ///< The value to be converted
5008 Type *Ty, ///< The type to convert to
5009 const Twine &NameStr = "", ///< A name for the new instruction
5010 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5011 );
5012
5013 /// Constructor with insert-at-end-of-block semantics
5014 IntToPtrInst(
5015 Value *S, ///< The value to be converted
5016 Type *Ty, ///< The type to convert to
5017 const Twine &NameStr, ///< A name for the new instruction
5018 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5019 );
5020
5021 /// Clone an identical IntToPtrInst.
5022 IntToPtrInst *cloneImpl() const;
5023
5024 /// Returns the address space of this instruction's pointer type.
5025 unsigned getAddressSpace() const {
5026 return getType()->getPointerAddressSpace();
5027 }
5028
5029 // Methods for support type inquiry through isa, cast, and dyn_cast:
5030 static bool classof(const Instruction *I) {
5031 return I->getOpcode() == IntToPtr;
5032 }
5033 static bool classof(const Value *V) {
5034 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5035 }
5036};
5037
5038//===----------------------------------------------------------------------===//
5039// PtrToIntInst Class
5040//===----------------------------------------------------------------------===//
5041
5042/// This class represents a cast from a pointer to an integer.
5043class PtrToIntInst : public CastInst {
5044protected:
5045 // Note: Instruction needs to be a friend here to call cloneImpl.
5046 friend class Instruction;
5047
5048 /// Clone an identical PtrToIntInst.
5049 PtrToIntInst *cloneImpl() const;
5050
5051public:
5052 /// Constructor with insert-before-instruction semantics
5053 PtrToIntInst(
5054 Value *S, ///< The value to be converted
5055 Type *Ty, ///< The type to convert to
5056 const Twine &NameStr = "", ///< A name for the new instruction
5057 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5058 );
5059
5060 /// Constructor with insert-at-end-of-block semantics
5061 PtrToIntInst(
5062 Value *S, ///< The value to be converted
5063 Type *Ty, ///< The type to convert to
5064 const Twine &NameStr, ///< A name for the new instruction
5065 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5066 );
5067
5068 /// Gets the pointer operand.
5069 Value *getPointerOperand() { return getOperand(0); }
5070 /// Gets the pointer operand.
5071 const Value *getPointerOperand() const { return getOperand(0); }
5072 /// Gets the operand index of the pointer operand.
5073 static unsigned getPointerOperandIndex() { return 0U; }
5074
5075 /// Returns the address space of the pointer operand.
5076 unsigned getPointerAddressSpace() const {
5077 return getPointerOperand()->getType()->getPointerAddressSpace();
5078 }
5079
5080 // Methods for support type inquiry through isa, cast, and dyn_cast:
5081 static bool classof(const Instruction *I) {
5082 return I->getOpcode() == PtrToInt;
5083 }
5084 static bool classof(const Value *V) {
5085 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5086 }
5087};
5088
5089//===----------------------------------------------------------------------===//
5090// BitCastInst Class
5091//===----------------------------------------------------------------------===//
5092
5093/// This class represents a no-op cast from one type to another.
5094class BitCastInst : public CastInst {
5095protected:
5096 // Note: Instruction needs to be a friend here to call cloneImpl.
5097 friend class Instruction;
5098
5099 /// Clone an identical BitCastInst.
5100 BitCastInst *cloneImpl() const;
5101
5102public:
5103 /// Constructor with insert-before-instruction semantics
5104 BitCastInst(
5105 Value *S, ///< The value to be casted
5106 Type *Ty, ///< The type to casted to
5107 const Twine &NameStr = "", ///< A name for the new instruction
5108 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5109 );
5110
5111 /// Constructor with insert-at-end-of-block semantics
5112 BitCastInst(
5113 Value *S, ///< The value to be casted
5114 Type *Ty, ///< The type to casted to
5115 const Twine &NameStr, ///< A name for the new instruction
5116 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5117 );
5118
5119 // Methods for support type inquiry through isa, cast, and dyn_cast:
5120 static bool classof(const Instruction *I) {
5121 return I->getOpcode() == BitCast;
5122 }
5123 static bool classof(const Value *V) {
5124 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5125 }
5126};
5127
5128//===----------------------------------------------------------------------===//
5129// AddrSpaceCastInst Class
5130//===----------------------------------------------------------------------===//
5131
5132/// This class represents a conversion between pointers from one address space
5133/// to another.
5134class AddrSpaceCastInst : public CastInst {
5135protected:
5136 // Note: Instruction needs to be a friend here to call cloneImpl.
5137 friend class Instruction;
5138
5139 /// Clone an identical AddrSpaceCastInst.
5140 AddrSpaceCastInst *cloneImpl() const;
5141
5142public:
5143 /// Constructor with insert-before-instruction semantics
5144 AddrSpaceCastInst(
5145 Value *S, ///< The value to be casted
5146 Type *Ty, ///< The type to casted to
5147 const Twine &NameStr = "", ///< A name for the new instruction
5148 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5149 );
5150
5151 /// Constructor with insert-at-end-of-block semantics
5152 AddrSpaceCastInst(
5153 Value *S, ///< The value to be casted
5154 Type *Ty, ///< The type to casted to
5155 const Twine &NameStr, ///< A name for the new instruction
5156 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5157 );
5158
5159 // Methods for support type inquiry through isa, cast, and dyn_cast:
5160 static bool classof(const Instruction *I) {
5161 return I->getOpcode() == AddrSpaceCast;
5162 }
5163 static bool classof(const Value *V) {
5164 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5165 }
5166
5167 /// Gets the pointer operand.
5168 Value *getPointerOperand() {
5169 return getOperand(0);
5170 }
5171
5172 /// Gets the pointer operand.
5173 const Value *getPointerOperand() const {
5174 return getOperand(0);
5175 }
5176
5177 /// Gets the operand index of the pointer operand.
5178 static unsigned getPointerOperandIndex() {
5179 return 0U;
5180 }
5181
5182 /// Returns the address space of the pointer operand.
5183 unsigned getSrcAddressSpace() const {
5184 return getPointerOperand()->getType()->getPointerAddressSpace();
5185 }
5186
5187 /// Returns the address space of the result.
5188 unsigned getDestAddressSpace() const {
5189 return getType()->getPointerAddressSpace();
5190 }
5191};
5192
5193} // end namespace llvm
5194
5195#endif // LLVM_IR_INSTRUCTIONS_H

/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instruction.h

1//===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the declaration of the Instruction class, which is the
11// base class for all of the LLVM instructions.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_INSTRUCTION_H
16#define LLVM_IR_INSTRUCTION_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/None.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/ilist_node.h"
22#include "llvm/IR/DebugLoc.h"
23#include "llvm/IR/SymbolTableListTraits.h"
24#include "llvm/IR/User.h"
25#include "llvm/IR/Value.h"
26#include "llvm/Support/Casting.h"
27#include <algorithm>
28#include <cassert>
29#include <cstdint>
30#include <utility>
31
32namespace llvm {
33
34class BasicBlock;
35class FastMathFlags;
36class MDNode;
37class Module;
38struct AAMDNodes;
39
40template <> struct ilist_alloc_traits<Instruction> {
41 static inline void deleteNode(Instruction *V);
42};
43
44class Instruction : public User,
45 public ilist_node_with_parent<Instruction, BasicBlock> {
46 BasicBlock *Parent;
47 DebugLoc DbgLoc; // 'dbg' Metadata cache.
48
49 enum {
50 /// This is a bit stored in the SubClassData field which indicates whether
51 /// this instruction has metadata attached to it or not.
52 HasMetadataBit = 1 << 15
53 };
54
55protected:
56 ~Instruction(); // Use deleteValue() to delete a generic Instruction.
57
58public:
59 Instruction(const Instruction &) = delete;
60 Instruction &operator=(const Instruction &) = delete;
61
62 /// Specialize the methods defined in Value, as we know that an instruction
63 /// can only be used by other instructions.
64 Instruction *user_back() { return cast<Instruction>(*user_begin());}
65 const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
66
67 inline const BasicBlock *getParent() const { return Parent; }
68 inline BasicBlock *getParent() { return Parent; }
69
70 /// Return the module owning the function this instruction belongs to
71 /// or nullptr it the function does not have a module.
72 ///
73 /// Note: this is undefined behavior if the instruction does not have a
74 /// parent, or the parent basic block does not have a parent function.
75 const Module *getModule() const;
76 Module *getModule() {
77 return const_cast<Module *>(
78 static_cast<const Instruction *>(this)->getModule());
79 }
80
81 /// Return the function this instruction belongs to.
82 ///
83 /// Note: it is undefined behavior to call this on an instruction not
84 /// currently inserted into a function.
85 const Function *getFunction() const;
86 Function *getFunction() {
87 return const_cast<Function *>(
88 static_cast<const Instruction *>(this)->getFunction());
89 }
90
91 /// This method unlinks 'this' from the containing basic block, but does not
92 /// delete it.
93 void removeFromParent();
94
95 /// This method unlinks 'this' from the containing basic block and deletes it.
96 ///
97 /// \returns an iterator pointing to the element after the erased one
98 SymbolTableList<Instruction>::iterator eraseFromParent();
99
100 /// Insert an unlinked instruction into a basic block immediately before
101 /// the specified instruction.
102 void insertBefore(Instruction *InsertPos);
103
104 /// Insert an unlinked instruction into a basic block immediately after the
105 /// specified instruction.
106 void insertAfter(Instruction *InsertPos);
107
108 /// Unlink this instruction from its current basic block and insert it into
109 /// the basic block that MovePos lives in, right before MovePos.
110 void moveBefore(Instruction *MovePos);
111
112 /// Unlink this instruction and insert into BB before I.
113 ///
114 /// \pre I is a valid iterator into BB.
115 void moveBefore(BasicBlock &BB, SymbolTableList<Instruction>::iterator I);
116
117 /// Unlink this instruction from its current basic block and insert it into
118 /// the basic block that MovePos lives in, right after MovePos.
119 void moveAfter(Instruction *MovePos);
120
121 //===--------------------------------------------------------------------===//
122 // Subclass classification.
123 //===--------------------------------------------------------------------===//
124
125 /// Returns a member of one of the enums like Instruction::Add.
126 unsigned getOpcode() const { return getValueID() - InstructionVal; }
21
Calling 'Value::getValueID'
22
Returning from 'Value::getValueID'
127
128 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
129 bool isTerminator() const { return isTerminator(getOpcode()); }
130 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
131 bool isShift() { return isShift(getOpcode()); }
132 bool isCast() const { return isCast(getOpcode()); }
133 bool isFuncletPad() const { return isFuncletPad(getOpcode()); }
134
135 static const char* getOpcodeName(unsigned OpCode);
136
137 static inline bool isTerminator(unsigned OpCode) {
138 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
139 }
140
141 static inline bool isBinaryOp(unsigned Opcode) {
142 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
143 }
144
145 /// Determine if the Opcode is one of the shift instructions.
146 static inline bool isShift(unsigned Opcode) {
147 return Opcode >= Shl && Opcode <= AShr;
148 }
149
150 /// Return true if this is a logical shift left or a logical shift right.
151 inline bool isLogicalShift() const {
152 return getOpcode() == Shl || getOpcode() == LShr;
153 }
154
155 /// Return true if this is an arithmetic shift right.
156 inline bool isArithmeticShift() const {
157 return getOpcode() == AShr;
158 }
159
160 /// Determine if the Opcode is and/or/xor.
161 static inline bool isBitwiseLogicOp(unsigned Opcode) {
162 return Opcode == And || Opcode == Or || Opcode == Xor;
163 }
164
165 /// Return true if this is and/or/xor.
166 inline bool isBitwiseLogicOp() const {
167 return isBitwiseLogicOp(getOpcode());
168 }
169
170 /// Determine if the OpCode is one of the CastInst instructions.
171 static inline bool isCast(unsigned OpCode) {
172 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
173 }
174
175 /// Determine if the OpCode is one of the FuncletPadInst instructions.
176 static inline bool isFuncletPad(unsigned OpCode) {
177 return OpCode >= FuncletPadOpsBegin && OpCode < FuncletPadOpsEnd;
178 }
179
180 //===--------------------------------------------------------------------===//
181 // Metadata manipulation.
182 //===--------------------------------------------------------------------===//
183
184 /// Return true if this instruction has any metadata attached to it.
185 bool hasMetadata() const { return DbgLoc || hasMetadataHashEntry(); }
186
187 /// Return true if this instruction has metadata attached to it other than a
188 /// debug location.
189 bool hasMetadataOtherThanDebugLoc() const {
190 return hasMetadataHashEntry();
191 }
192
193 /// Get the metadata of given kind attached to this Instruction.
194 /// If the metadata is not found then return null.
195 MDNode *getMetadata(unsigned KindID) const {
196 if (!hasMetadata()) return nullptr;
197 return getMetadataImpl(KindID);
198 }
199
200 /// Get the metadata of given kind attached to this Instruction.
201 /// If the metadata is not found then return null.
202 MDNode *getMetadata(StringRef Kind) const {
203 if (!hasMetadata()) return nullptr;
204 return getMetadataImpl(Kind);
205 }
206
207 /// Get all metadata attached to this Instruction. The first element of each
208 /// pair returned is the KindID, the second element is the metadata value.
209 /// This list is returned sorted by the KindID.
210 void
211 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
212 if (hasMetadata())
213 getAllMetadataImpl(MDs);
214 }
215
216 /// This does the same thing as getAllMetadata, except that it filters out the
217 /// debug location.
218 void getAllMetadataOtherThanDebugLoc(
219 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
220 if (hasMetadataOtherThanDebugLoc())
221 getAllMetadataOtherThanDebugLocImpl(MDs);
222 }
223
224 /// Fills the AAMDNodes structure with AA metadata from this instruction.
225 /// When Merge is true, the existing AA metadata is merged with that from this
226 /// instruction providing the most-general result.
227 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
228
229 /// Set the metadata of the specified kind to the specified node. This updates
230 /// or replaces metadata if already present, or removes it if Node is null.
231 void setMetadata(unsigned KindID, MDNode *Node);
232 void setMetadata(StringRef Kind, MDNode *Node);
233
234 /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty,
235 /// specifies the list of meta data that needs to be copied. If \p WL is
236 /// empty, all meta data will be copied.
237 void copyMetadata(const Instruction &SrcInst,
238 ArrayRef<unsigned> WL = ArrayRef<unsigned>());
239
240 /// If the instruction has "branch_weights" MD_prof metadata and the MDNode
241 /// has three operands (including name string), swap the order of the
242 /// metadata.
243 void swapProfMetadata();
244
245 /// Drop all unknown metadata except for debug locations.
246 /// @{
247 /// Passes are required to drop metadata they don't understand. This is a
248 /// convenience method for passes to do so.
249 void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs);
250 void dropUnknownNonDebugMetadata() {
251 return dropUnknownNonDebugMetadata(None);
252 }
253 void dropUnknownNonDebugMetadata(unsigned ID1) {
254 return dropUnknownNonDebugMetadata(makeArrayRef(ID1));
255 }
256 void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) {
257 unsigned IDs[] = {ID1, ID2};
258 return dropUnknownNonDebugMetadata(IDs);
259 }
260 /// @}
261
262 /// Sets the metadata on this instruction from the AAMDNodes structure.
263 void setAAMetadata(const AAMDNodes &N);
264
265 /// Retrieve the raw weight values of a conditional branch or select.
266 /// Returns true on success with profile weights filled in.
267 /// Returns false if no metadata or invalid metadata was found.
268 bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const;
269
270 /// Retrieve total raw weight values of a branch.
271 /// Returns true on success with profile total weights filled in.
272 /// Returns false if no metadata was found.
273 bool extractProfTotalWeight(uint64_t &TotalVal) const;
274
275 /// Updates branch_weights metadata by scaling it by \p S / \p T.
276 void updateProfWeight(uint64_t S, uint64_t T);
277
278 /// Sets the branch_weights metadata to \p W for CallInst.
279 void setProfWeight(uint64_t W);
280
281 /// Set the debug location information for this instruction.
282 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
283
284 /// Return the debug location for this node as a DebugLoc.
285 const DebugLoc &getDebugLoc() const { return DbgLoc; }
286
287 /// Set or clear the nsw flag on this instruction, which must be an operator
288 /// which supports this flag. See LangRef.html for the meaning of this flag.
289 void setHasNoUnsignedWrap(bool b = true);
290
291 /// Set or clear the nsw flag on this instruction, which must be an operator
292 /// which supports this flag. See LangRef.html for the meaning of this flag.
293 void setHasNoSignedWrap(bool b = true);
294
295 /// Set or clear the exact flag on this instruction, which must be an operator
296 /// which supports this flag. See LangRef.html for the meaning of this flag.
297 void setIsExact(bool b = true);
298
299 /// Determine whether the no unsigned wrap flag is set.
300 bool hasNoUnsignedWrap() const;
301
302 /// Determine whether the no signed wrap flag is set.
303 bool hasNoSignedWrap() const;
304
305 /// Drops flags that may cause this instruction to evaluate to poison despite
306 /// having non-poison inputs.
307 void dropPoisonGeneratingFlags();
308
309 /// Determine whether the exact flag is set.
310 bool isExact() const;
311
312 /// Set or clear all fast-math-flags on this instruction, which must be an
313 /// operator which supports this flag. See LangRef.html for the meaning of
314 /// this flag.
315 void setFast(bool B);
316
317 /// Set or clear the reassociation flag on this instruction, which must be
318 /// an operator which supports this flag. See LangRef.html for the meaning of
319 /// this flag.
320 void setHasAllowReassoc(bool B);
321
322 /// Set or clear the no-nans flag on this instruction, which must be an
323 /// operator which supports this flag. See LangRef.html for the meaning of
324 /// this flag.
325 void setHasNoNaNs(bool B);
326
327 /// Set or clear the no-infs flag on this instruction, which must be an
328 /// operator which supports this flag. See LangRef.html for the meaning of
329 /// this flag.
330 void setHasNoInfs(bool B);
331
332 /// Set or clear the no-signed-zeros flag on this instruction, which must be
333 /// an operator which supports this flag. See LangRef.html for the meaning of
334 /// this flag.
335 void setHasNoSignedZeros(bool B);
336
337 /// Set or clear the allow-reciprocal flag on this instruction, which must be
338 /// an operator which supports this flag. See LangRef.html for the meaning of
339 /// this flag.
340 void setHasAllowReciprocal(bool B);
341
342 /// Set or clear the approximate-math-functions flag on this instruction,
343 /// which must be an operator which supports this flag. See LangRef.html for
344 /// the meaning of this flag.
345 void setHasApproxFunc(bool B);
346
347 /// Convenience function for setting multiple fast-math flags on this
348 /// instruction, which must be an operator which supports these flags. See
349 /// LangRef.html for the meaning of these flags.
350 void setFastMathFlags(FastMathFlags FMF);
351
352 /// Convenience function for transferring all fast-math flag values to this
353 /// instruction, which must be an operator which supports these flags. See
354 /// LangRef.html for the meaning of these flags.
355 void copyFastMathFlags(FastMathFlags FMF);
356
357 /// Determine whether all fast-math-flags are set.
358 bool isFast() const;
359
360 /// Determine whether the allow-reassociation flag is set.
361 bool hasAllowReassoc() const;
362
363 /// Determine whether the no-NaNs flag is set.
364 bool hasNoNaNs() const;
365
366 /// Determine whether the no-infs flag is set.
367 bool hasNoInfs() const;
368
369 /// Determine whether the no-signed-zeros flag is set.
370 bool hasNoSignedZeros() const;
371
372 /// Determine whether the allow-reciprocal flag is set.
373 bool hasAllowReciprocal() const;
374
375 /// Determine whether the allow-contract flag is set.
376 bool hasAllowContract() const;
377
378 /// Determine whether the approximate-math-functions flag is set.
379 bool hasApproxFunc() const;
380
381 /// Convenience function for getting all the fast-math flags, which must be an
382 /// operator which supports these flags. See LangRef.html for the meaning of
383 /// these flags.
384 FastMathFlags getFastMathFlags() const;
385
386 /// Copy I's fast-math flags
387 void copyFastMathFlags(const Instruction *I);
388
389 /// Convenience method to copy supported exact, fast-math, and (optionally)
390 /// wrapping flags from V to this instruction.
391 void copyIRFlags(const Value *V, bool IncludeWrapFlags = true);
392
393 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
394 /// V and this instruction.
395 void andIRFlags(const Value *V);
396
397 /// Merge 2 debug locations and apply it to the Instruction. If the
398 /// instruction is a CallIns, we need to traverse the inline chain to find
399 /// the common scope. This is not efficient for N-way merging as each time
400 /// you merge 2 iterations, you need to rebuild the hashmap to find the
401 /// common scope. However, we still choose this API because:
402 /// 1) Simplicity: it takes 2 locations instead of a list of locations.
403 /// 2) In worst case, it increases the complexity from O(N*I) to
404 /// O(2*N*I), where N is # of Instructions to merge, and I is the
405 /// maximum level of inline stack. So it is still linear.
406 /// 3) Merging of call instructions should be extremely rare in real
407 /// applications, thus the N-way merging should be in code path.
408 /// The DebugLoc attached to this instruction will be overwritten by the
409 /// merged DebugLoc.
410 void applyMergedLocation(const DILocation *LocA, const DILocation *LocB);
411
412private:
413 /// Return true if we have an entry in the on-the-side metadata hash.
414 bool hasMetadataHashEntry() const {
415 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
416 }
417
418 // These are all implemented in Metadata.cpp.
419 MDNode *getMetadataImpl(unsigned KindID) const;
420 MDNode *getMetadataImpl(StringRef Kind) const;
421 void
422 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
423 void getAllMetadataOtherThanDebugLocImpl(
424 SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
425 /// Clear all hashtable-based metadata from this instruction.
426 void clearMetadataHashEntries();
427
428public:
429 //===--------------------------------------------------------------------===//
430 // Predicates and helper methods.
431 //===--------------------------------------------------------------------===//
432
433 /// Return true if the instruction is associative:
434 ///
435 /// Associative operators satisfy: x op (y op z) === (x op y) op z
436 ///
437 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
438 ///
439 bool isAssociative() const LLVM_READONLY__attribute__((__pure__));
440 static bool isAssociative(unsigned Opcode) {
441 return Opcode == And || Opcode == Or || Opcode == Xor ||
442 Opcode == Add || Opcode == Mul;
443 }
444
445 /// Return true if the instruction is commutative:
446 ///
447 /// Commutative operators satisfy: (x op y) === (y op x)
448 ///
449 /// In LLVM, these are the commutative operators, plus SetEQ and SetNE, when
450 /// applied to any type.
451 ///
452 bool isCommutative() const { return isCommutative(getOpcode()); }
453 static bool isCommutative(unsigned Opcode) {
454 switch (Opcode) {
455 case Add: case FAdd:
456 case Mul: case FMul:
457 case And: case Or: case Xor:
458 return true;
459 default:
460 return false;
461 }
462 }
463
464 /// Return true if the instruction is idempotent:
465 ///
466 /// Idempotent operators satisfy: x op x === x
467 ///
468 /// In LLVM, the And and Or operators are idempotent.
469 ///
470 bool isIdempotent() const { return isIdempotent(getOpcode()); }
471 static bool isIdempotent(unsigned Opcode) {
472 return Opcode == And || Opcode == Or;
473 }
474
475 /// Return true if the instruction is nilpotent:
476 ///
477 /// Nilpotent operators satisfy: x op x === Id,
478 ///
479 /// where Id is the identity for the operator, i.e. a constant such that
480 /// x op Id === x and Id op x === x for all x.
481 ///
482 /// In LLVM, the Xor operator is nilpotent.
483 ///
484 bool isNilpotent() const { return isNilpotent(getOpcode()); }
485 static bool isNilpotent(unsigned Opcode) {
486 return Opcode == Xor;
487 }
488
489 /// Return true if this instruction may modify memory.
490 bool mayWriteToMemory() const;
491
492 /// Return true if this instruction may read memory.
493 bool mayReadFromMemory() const;
494
495 /// Return true if this instruction may read or write memory.
496 bool mayReadOrWriteMemory() const {
497 return mayReadFromMemory() || mayWriteToMemory();
498 }
499
500 /// Return true if this instruction has an AtomicOrdering of unordered or
501 /// higher.
502 bool isAtomic() const;
503
504 /// Return true if this atomic instruction loads from memory.
505 bool hasAtomicLoad() const;
506
507 /// Return true if this atomic instruction stores to memory.
508 bool hasAtomicStore() const;
509
510 /// Return true if this instruction may throw an exception.
511 bool mayThrow() const;
512
513 /// Return true if this instruction behaves like a memory fence: it can load
514 /// or store to memory location without being given a memory location.
515 bool isFenceLike() const {
516 switch (getOpcode()) {
517 default:
518 return false;
519 // This list should be kept in sync with the list in mayWriteToMemory for
520 // all opcodes which don't have a memory location.
521 case Instruction::Fence:
522 case Instruction::CatchPad:
523 case Instruction::CatchRet:
524 case Instruction::Call:
525 case Instruction::Invoke:
526 return true;
527 }
528 }
529
530 /// Return true if the instruction may have side effects.
531 ///
532 /// Note that this does not consider malloc and alloca to have side
533 /// effects because the newly allocated memory is completely invisible to
534 /// instructions which don't use the returned value. For cases where this
535 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
536 bool mayHaveSideEffects() const { return mayWriteToMemory() || mayThrow(); }
537
538 /// Return true if the instruction can be removed if the result is unused.
539 ///
540 /// When constant folding some instructions cannot be removed even if their
541 /// results are unused. Specifically terminator instructions and calls that
542 /// may have side effects cannot be removed without semantically changing the
543 /// generated program.
544 bool isSafeToRemove() const;
545
546 /// Return true if the instruction is a variety of EH-block.
547 bool isEHPad() const {
548 switch (getOpcode()) {
549 case Instruction::CatchSwitch:
550 case Instruction::CatchPad:
551 case Instruction::CleanupPad:
552 case Instruction::LandingPad:
553 return true;
554 default:
555 return false;
556 }
557 }
558
559 /// Create a copy of 'this' instruction that is identical in all ways except
560 /// the following:
561 /// * The instruction has no parent
562 /// * The instruction has no name
563 ///
564 Instruction *clone() const;
565
566 /// Return true if the specified instruction is exactly identical to the
567 /// current one. This means that all operands match and any extra information
568 /// (e.g. load is volatile) agree.
569 bool isIdenticalTo(const Instruction *I) const;
570
571 /// This is like isIdenticalTo, except that it ignores the
572 /// SubclassOptionalData flags, which may specify conditions under which the
573 /// instruction's result is undefined.
574 bool isIdenticalToWhenDefined(const Instruction *I) const;
575
576 /// When checking for operation equivalence (using isSameOperationAs) it is
577 /// sometimes useful to ignore certain attributes.
578 enum OperationEquivalenceFlags {
579 /// Check for equivalence ignoring load/store alignment.
580 CompareIgnoringAlignment = 1<<0,
581 /// Check for equivalence treating a type and a vector of that type
582 /// as equivalent.
583 CompareUsingScalarTypes = 1<<1
584 };
585
586 /// This function determines if the specified instruction executes the same
587 /// operation as the current one. This means that the opcodes, type, operand
588 /// types and any other factors affecting the operation must be the same. This
589 /// is similar to isIdenticalTo except the operands themselves don't have to
590 /// be identical.
591 /// @returns true if the specified instruction is the same operation as
592 /// the current one.
593 /// @brief Determine if one instruction is the same operation as another.
594 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
595
596 /// Return true if there are any uses of this instruction in blocks other than
597 /// the specified block. Note that PHI nodes are considered to evaluate their
598 /// operands in the corresponding predecessor block.
599 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
600
601
602 /// Methods for support type inquiry through isa, cast, and dyn_cast:
603 static bool classof(const Value *V) {
604 return V->getValueID() >= Value::InstructionVal;
605 }
606
607 //----------------------------------------------------------------------
608 // Exported enumerations.
609 //
610 enum TermOps { // These terminate basic blocks
611#define FIRST_TERM_INST(N) TermOpsBegin = N,
612#define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
613#define LAST_TERM_INST(N) TermOpsEnd = N+1
614#include "llvm/IR/Instruction.def"
615 };
616
617 enum BinaryOps {
618#define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
619#define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
620#define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
621#include "llvm/IR/Instruction.def"
622 };
623
624 enum MemoryOps {
625#define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
626#define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
627#define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
628#include "llvm/IR/Instruction.def"
629 };
630
631 enum CastOps {
632#define FIRST_CAST_INST(N) CastOpsBegin = N,
633#define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
634#define LAST_CAST_INST(N) CastOpsEnd = N+1
635#include "llvm/IR/Instruction.def"
636 };
637
638 enum FuncletPadOps {
639#define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N,
640#define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N,
641#define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1
642#include "llvm/IR/Instruction.def"
643 };
644
645 enum OtherOps {
646#define FIRST_OTHER_INST(N) OtherOpsBegin = N,
647#define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
648#define LAST_OTHER_INST(N) OtherOpsEnd = N+1
649#include "llvm/IR/Instruction.def"
650 };
651
652private:
653 friend class SymbolTableListTraits<Instruction>;
654
655 // Shadow Value::setValueSubclassData with a private forwarding method so that
656 // subclasses cannot accidentally use it.
657 void setValueSubclassData(unsigned short D) {
658 Value::setValueSubclassData(D);
659 }
660
661 unsigned short getSubclassDataFromValue() const {
662 return Value::getSubclassDataFromValue();
663 }
664
665 void setHasMetadataHashEntry(bool V) {
666 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
667 (V ? HasMetadataBit : 0));
668 }
669
670 void setParent(BasicBlock *P);
671
672protected:
673 // Instruction subclasses can stick up to 15 bits of stuff into the
674 // SubclassData field of instruction with these members.
675
676 // Verify that only the low 15 bits are used.
677 void setInstructionSubclassData(unsigned short D) {
678 assert((D & HasMetadataBit) == 0 && "Out of range value put into field")(static_cast <bool> ((D & HasMetadataBit) == 0 &&
"Out of range value put into field") ? void (0) : __assert_fail
("(D & HasMetadataBit) == 0 && \"Out of range value put into field\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/IR/Instruction.h"
, 678, __extension__ __PRETTY_FUNCTION__))
;
679 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
680 }
681
682 unsigned getSubclassDataFromInstruction() const {
683 return getSubclassDataFromValue() & ~HasMetadataBit;
684 }
685
686 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
687 Instruction *InsertBefore = nullptr);
688 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
689 BasicBlock *InsertAtEnd);
690
691private:
692 /// Create a copy of this instruction.
693 Instruction *cloneImpl() const;
694};
695
696inline void ilist_alloc_traits<Instruction>::deleteNode(Instruction *V) {
697 V->deleteValue();
698}
699
700} // end namespace llvm
701
702#endif // LLVM_IR_INSTRUCTION_H