Bug Summary

File:llvm/lib/Analysis/LazyValueInfo.cpp
Warning:line 1417, column 34
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 LazyValueInfo.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.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++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp

1//===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the interface for lazy computation of value constraint
10// information.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Analysis/LazyValueInfo.h"
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/Optional.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/Analysis/AssumptionCache.h"
19#include "llvm/Analysis/ConstantFolding.h"
20#include "llvm/Analysis/InstructionSimplify.h"
21#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Analysis/ValueLattice.h"
23#include "llvm/Analysis/ValueTracking.h"
24#include "llvm/IR/AssemblyAnnotationWriter.h"
25#include "llvm/IR/CFG.h"
26#include "llvm/IR/ConstantRange.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Dominators.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/PatternMatch.h"
35#include "llvm/IR/ValueHandle.h"
36#include "llvm/InitializePasses.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/FormattedStream.h"
39#include "llvm/Support/raw_ostream.h"
40#include <map>
41using namespace llvm;
42using namespace PatternMatch;
43
44#define DEBUG_TYPE"lazy-value-info" "lazy-value-info"
45
46// This is the number of worklist items we will process to try to discover an
47// answer for a given value.
48static const unsigned MaxProcessedPerValue = 500;
49
50char LazyValueInfoWrapperPass::ID = 0;
51LazyValueInfoWrapperPass::LazyValueInfoWrapperPass() : FunctionPass(ID) {
52 initializeLazyValueInfoWrapperPassPass(*PassRegistry::getPassRegistry());
53}
54INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",static void *initializeLazyValueInfoWrapperPassPassOnce(PassRegistry
&Registry) {
55 "Lazy Value Information Analysis", false, true)static void *initializeLazyValueInfoWrapperPassPassOnce(PassRegistry
&Registry) {
56INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry);
57INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
58INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",PassInfo *PI = new PassInfo( "Lazy Value Information Analysis"
, "lazy-value-info", &LazyValueInfoWrapperPass::ID, PassInfo
::NormalCtor_t(callDefaultCtor<LazyValueInfoWrapperPass>
), false, true); Registry.registerPass(*PI, true); return PI;
} static llvm::once_flag InitializeLazyValueInfoWrapperPassPassFlag
; void llvm::initializeLazyValueInfoWrapperPassPass(PassRegistry
&Registry) { llvm::call_once(InitializeLazyValueInfoWrapperPassPassFlag
, initializeLazyValueInfoWrapperPassPassOnce, std::ref(Registry
)); }
59 "Lazy Value Information Analysis", false, true)PassInfo *PI = new PassInfo( "Lazy Value Information Analysis"
, "lazy-value-info", &LazyValueInfoWrapperPass::ID, PassInfo
::NormalCtor_t(callDefaultCtor<LazyValueInfoWrapperPass>
), false, true); Registry.registerPass(*PI, true); return PI;
} static llvm::once_flag InitializeLazyValueInfoWrapperPassPassFlag
; void llvm::initializeLazyValueInfoWrapperPassPass(PassRegistry
&Registry) { llvm::call_once(InitializeLazyValueInfoWrapperPassPassFlag
, initializeLazyValueInfoWrapperPassPassOnce, std::ref(Registry
)); }
60
61namespace llvm {
62 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
63}
64
65AnalysisKey LazyValueAnalysis::Key;
66
67/// Returns true if this lattice value represents at most one possible value.
68/// This is as precise as any lattice value can get while still representing
69/// reachable code.
70static bool hasSingleValue(const ValueLatticeElement &Val) {
71 if (Val.isConstantRange() &&
72 Val.getConstantRange().isSingleElement())
73 // Integer constants are single element ranges
74 return true;
75 if (Val.isConstant())
76 // Non integer constants
77 return true;
78 return false;
79}
80
81/// Combine two sets of facts about the same value into a single set of
82/// facts. Note that this method is not suitable for merging facts along
83/// different paths in a CFG; that's what the mergeIn function is for. This
84/// is for merging facts gathered about the same value at the same location
85/// through two independent means.
86/// Notes:
87/// * This method does not promise to return the most precise possible lattice
88/// value implied by A and B. It is allowed to return any lattice element
89/// which is at least as strong as *either* A or B (unless our facts
90/// conflict, see below).
91/// * Due to unreachable code, the intersection of two lattice values could be
92/// contradictory. If this happens, we return some valid lattice value so as
93/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
94/// we do not make this guarantee. TODO: This would be a useful enhancement.
95static ValueLatticeElement intersect(const ValueLatticeElement &A,
96 const ValueLatticeElement &B) {
97 // Undefined is the strongest state. It means the value is known to be along
98 // an unreachable path.
99 if (A.isUndefined())
100 return A;
101 if (B.isUndefined())
102 return B;
103
104 // If we gave up for one, but got a useable fact from the other, use it.
105 if (A.isOverdefined())
106 return B;
107 if (B.isOverdefined())
108 return A;
109
110 // Can't get any more precise than constants.
111 if (hasSingleValue(A))
112 return A;
113 if (hasSingleValue(B))
114 return B;
115
116 // Could be either constant range or not constant here.
117 if (!A.isConstantRange() || !B.isConstantRange()) {
118 // TODO: Arbitrary choice, could be improved
119 return A;
120 }
121
122 // Intersect two constant ranges
123 ConstantRange Range =
124 A.getConstantRange().intersectWith(B.getConstantRange());
125 // Note: An empty range is implicitly converted to overdefined internally.
126 // TODO: We could instead use Undefined here since we've proven a conflict
127 // and thus know this path must be unreachable.
128 return ValueLatticeElement::getRange(std::move(Range));
129}
130
131//===----------------------------------------------------------------------===//
132// LazyValueInfoCache Decl
133//===----------------------------------------------------------------------===//
134
135namespace {
136 /// A callback value handle updates the cache when values are erased.
137 class LazyValueInfoCache;
138 struct LVIValueHandle final : public CallbackVH {
139 // Needs to access getValPtr(), which is protected.
140 friend struct DenseMapInfo<LVIValueHandle>;
141
142 LazyValueInfoCache *Parent;
143
144 LVIValueHandle(Value *V, LazyValueInfoCache *P)
145 : CallbackVH(V), Parent(P) { }
146
147 void deleted() override;
148 void allUsesReplacedWith(Value *V) override {
149 deleted();
150 }
151 };
152} // end anonymous namespace
153
154namespace {
155 /// This is the cache kept by LazyValueInfo which
156 /// maintains information about queries across the clients' queries.
157 class LazyValueInfoCache {
158 /// This is all of the cached block information for exactly one Value*.
159 /// The entries are sorted by the BasicBlock* of the
160 /// entries, allowing us to do a lookup with a binary search.
161 /// Over-defined lattice values are recorded in OverDefinedCache to reduce
162 /// memory overhead.
163 struct ValueCacheEntryTy {
164 ValueCacheEntryTy(Value *V, LazyValueInfoCache *P) : Handle(V, P) {}
165 LVIValueHandle Handle;
166 SmallDenseMap<PoisoningVH<BasicBlock>, ValueLatticeElement, 4> BlockVals;
167 };
168
169 /// This tracks, on a per-block basis, the set of values that are
170 /// over-defined at the end of that block.
171 typedef DenseMap<PoisoningVH<BasicBlock>, SmallPtrSet<Value *, 4>>
172 OverDefinedCacheTy;
173 /// Keep track of all blocks that we have ever seen, so we
174 /// don't spend time removing unused blocks from our caches.
175 DenseSet<PoisoningVH<BasicBlock> > SeenBlocks;
176
177 /// This is all of the cached information for all values,
178 /// mapped from Value* to key information.
179 DenseMap<Value *, std::unique_ptr<ValueCacheEntryTy>> ValueCache;
180 OverDefinedCacheTy OverDefinedCache;
181
182
183 public:
184 void insertResult(Value *Val, BasicBlock *BB,
185 const ValueLatticeElement &Result) {
186 SeenBlocks.insert(BB);
187
188 // Insert over-defined values into their own cache to reduce memory
189 // overhead.
190 if (Result.isOverdefined())
191 OverDefinedCache[BB].insert(Val);
192 else {
193 auto It = ValueCache.find_as(Val);
194 if (It == ValueCache.end()) {
195 ValueCache[Val] = std::make_unique<ValueCacheEntryTy>(Val, this);
196 It = ValueCache.find_as(Val);
197 assert(It != ValueCache.end() && "Val was just added to the map!")((It != ValueCache.end() && "Val was just added to the map!"
) ? static_cast<void> (0) : __assert_fail ("It != ValueCache.end() && \"Val was just added to the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 197, __PRETTY_FUNCTION__))
;
198 }
199 It->second->BlockVals[BB] = Result;
200 }
201 }
202
203 bool isOverdefined(Value *V, BasicBlock *BB) const {
204 auto ODI = OverDefinedCache.find(BB);
205
206 if (ODI == OverDefinedCache.end())
207 return false;
208
209 return ODI->second.count(V);
210 }
211
212 bool hasCachedValueInfo(Value *V, BasicBlock *BB) const {
213 if (isOverdefined(V, BB))
214 return true;
215
216 auto I = ValueCache.find_as(V);
217 if (I == ValueCache.end())
218 return false;
219
220 return I->second->BlockVals.count(BB);
221 }
222
223 ValueLatticeElement getCachedValueInfo(Value *V, BasicBlock *BB) const {
224 if (isOverdefined(V, BB))
225 return ValueLatticeElement::getOverdefined();
226
227 auto I = ValueCache.find_as(V);
228 if (I == ValueCache.end())
229 return ValueLatticeElement();
230 auto BBI = I->second->BlockVals.find(BB);
231 if (BBI == I->second->BlockVals.end())
232 return ValueLatticeElement();
233 return BBI->second;
234 }
235
236 /// clear - Empty the cache.
237 void clear() {
238 SeenBlocks.clear();
239 ValueCache.clear();
240 OverDefinedCache.clear();
241 }
242
243 /// Inform the cache that a given value has been deleted.
244 void eraseValue(Value *V);
245
246 /// This is part of the update interface to inform the cache
247 /// that a block has been deleted.
248 void eraseBlock(BasicBlock *BB);
249
250 /// Updates the cache to remove any influence an overdefined value in
251 /// OldSucc might have (unless also overdefined in NewSucc). This just
252 /// flushes elements from the cache and does not add any.
253 void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc);
254
255 friend struct LVIValueHandle;
256 };
257}
258
259void LazyValueInfoCache::eraseValue(Value *V) {
260 for (auto I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E;) {
261 // Copy and increment the iterator immediately so we can erase behind
262 // ourselves.
263 auto Iter = I++;
264 SmallPtrSetImpl<Value *> &ValueSet = Iter->second;
265 ValueSet.erase(V);
266 if (ValueSet.empty())
267 OverDefinedCache.erase(Iter);
268 }
269
270 ValueCache.erase(V);
271}
272
273void LVIValueHandle::deleted() {
274 // This erasure deallocates *this, so it MUST happen after we're done
275 // using any and all members of *this.
276 Parent->eraseValue(*this);
277}
278
279void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
280 // Shortcut if we have never seen this block.
281 DenseSet<PoisoningVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
282 if (I == SeenBlocks.end())
283 return;
284 SeenBlocks.erase(I);
285
286 auto ODI = OverDefinedCache.find(BB);
287 if (ODI != OverDefinedCache.end())
288 OverDefinedCache.erase(ODI);
289
290 for (auto &I : ValueCache)
291 I.second->BlockVals.erase(BB);
292}
293
294void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
295 BasicBlock *NewSucc) {
296 // When an edge in the graph has been threaded, values that we could not
297 // determine a value for before (i.e. were marked overdefined) may be
298 // possible to solve now. We do NOT try to proactively update these values.
299 // Instead, we clear their entries from the cache, and allow lazy updating to
300 // recompute them when needed.
301
302 // The updating process is fairly simple: we need to drop cached info
303 // for all values that were marked overdefined in OldSucc, and for those same
304 // values in any successor of OldSucc (except NewSucc) in which they were
305 // also marked overdefined.
306 std::vector<BasicBlock*> worklist;
307 worklist.push_back(OldSucc);
308
309 auto I = OverDefinedCache.find(OldSucc);
310 if (I == OverDefinedCache.end())
311 return; // Nothing to process here.
312 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
313
314 // Use a worklist to perform a depth-first search of OldSucc's successors.
315 // NOTE: We do not need a visited list since any blocks we have already
316 // visited will have had their overdefined markers cleared already, and we
317 // thus won't loop to their successors.
318 while (!worklist.empty()) {
319 BasicBlock *ToUpdate = worklist.back();
320 worklist.pop_back();
321
322 // Skip blocks only accessible through NewSucc.
323 if (ToUpdate == NewSucc) continue;
324
325 // If a value was marked overdefined in OldSucc, and is here too...
326 auto OI = OverDefinedCache.find(ToUpdate);
327 if (OI == OverDefinedCache.end())
328 continue;
329 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
330
331 bool changed = false;
332 for (Value *V : ValsToClear) {
333 if (!ValueSet.erase(V))
334 continue;
335
336 // If we removed anything, then we potentially need to update
337 // blocks successors too.
338 changed = true;
339
340 if (ValueSet.empty()) {
341 OverDefinedCache.erase(OI);
342 break;
343 }
344 }
345
346 if (!changed) continue;
347
348 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
349 }
350}
351
352
353namespace {
354/// An assembly annotator class to print LazyValueCache information in
355/// comments.
356class LazyValueInfoImpl;
357class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
358 LazyValueInfoImpl *LVIImpl;
359 // While analyzing which blocks we can solve values for, we need the dominator
360 // information. Since this is an optional parameter in LVI, we require this
361 // DomTreeAnalysis pass in the printer pass, and pass the dominator
362 // tree to the LazyValueInfoAnnotatedWriter.
363 DominatorTree &DT;
364
365public:
366 LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *L, DominatorTree &DTree)
367 : LVIImpl(L), DT(DTree) {}
368
369 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
370 formatted_raw_ostream &OS);
371
372 virtual void emitInstructionAnnot(const Instruction *I,
373 formatted_raw_ostream &OS);
374};
375}
376namespace {
377 // The actual implementation of the lazy analysis and update. Note that the
378 // inheritance from LazyValueInfoCache is intended to be temporary while
379 // splitting the code and then transitioning to a has-a relationship.
380 class LazyValueInfoImpl {
381
382 /// Cached results from previous queries
383 LazyValueInfoCache TheCache;
384
385 /// This stack holds the state of the value solver during a query.
386 /// It basically emulates the callstack of the naive
387 /// recursive value lookup process.
388 SmallVector<std::pair<BasicBlock*, Value*>, 8> BlockValueStack;
389
390 /// Keeps track of which block-value pairs are in BlockValueStack.
391 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
392
393 /// Push BV onto BlockValueStack unless it's already in there.
394 /// Returns true on success.
395 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
396 if (!BlockValueSet.insert(BV).second)
397 return false; // It's already in the stack.
398
399 LLVM_DEBUG(dbgs() << "PUSH: " << *BV.second << " in "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "PUSH: " << *BV.
second << " in " << BV.first->getName() <<
"\n"; } } while (false)
400 << BV.first->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "PUSH: " << *BV.
second << " in " << BV.first->getName() <<
"\n"; } } while (false)
;
401 BlockValueStack.push_back(BV);
402 return true;
403 }
404
405 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
406 const DataLayout &DL; ///< A mandatory DataLayout
407 DominatorTree *DT; ///< An optional DT pointer.
408 DominatorTree *DisabledDT; ///< Stores DT if it's disabled.
409
410 ValueLatticeElement getBlockValue(Value *Val, BasicBlock *BB);
411 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
412 ValueLatticeElement &Result, Instruction *CxtI = nullptr);
413 bool hasBlockValue(Value *Val, BasicBlock *BB);
414
415 // These methods process one work item and may add more. A false value
416 // returned means that the work item was not completely processed and must
417 // be revisited after going through the new items.
418 bool solveBlockValue(Value *Val, BasicBlock *BB);
419 bool solveBlockValueImpl(ValueLatticeElement &Res, Value *Val,
420 BasicBlock *BB);
421 bool solveBlockValueNonLocal(ValueLatticeElement &BBLV, Value *Val,
422 BasicBlock *BB);
423 bool solveBlockValuePHINode(ValueLatticeElement &BBLV, PHINode *PN,
424 BasicBlock *BB);
425 bool solveBlockValueSelect(ValueLatticeElement &BBLV, SelectInst *S,
426 BasicBlock *BB);
427 Optional<ConstantRange> getRangeForOperand(unsigned Op, Instruction *I,
428 BasicBlock *BB);
429 bool solveBlockValueBinaryOpImpl(
430 ValueLatticeElement &BBLV, Instruction *I, BasicBlock *BB,
431 std::function<ConstantRange(const ConstantRange &,
432 const ConstantRange &)> OpFn);
433 bool solveBlockValueBinaryOp(ValueLatticeElement &BBLV, BinaryOperator *BBI,
434 BasicBlock *BB);
435 bool solveBlockValueCast(ValueLatticeElement &BBLV, CastInst *CI,
436 BasicBlock *BB);
437 bool solveBlockValueOverflowIntrinsic(
438 ValueLatticeElement &BBLV, WithOverflowInst *WO, BasicBlock *BB);
439 bool solveBlockValueSaturatingIntrinsic(ValueLatticeElement &BBLV,
440 SaturatingInst *SI, BasicBlock *BB);
441 bool solveBlockValueIntrinsic(ValueLatticeElement &BBLV, IntrinsicInst *II,
442 BasicBlock *BB);
443 bool solveBlockValueExtractValue(ValueLatticeElement &BBLV,
444 ExtractValueInst *EVI, BasicBlock *BB);
445 void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
446 ValueLatticeElement &BBLV,
447 Instruction *BBI);
448
449 void solve();
450
451 public:
452 /// This is the query interface to determine the lattice
453 /// value for the specified Value* at the end of the specified block.
454 ValueLatticeElement getValueInBlock(Value *V, BasicBlock *BB,
455 Instruction *CxtI = nullptr);
456
457 /// This is the query interface to determine the lattice
458 /// value for the specified Value* at the specified instruction (generally
459 /// from an assume intrinsic).
460 ValueLatticeElement getValueAt(Value *V, Instruction *CxtI);
461
462 /// This is the query interface to determine the lattice
463 /// value for the specified Value* that is true on the specified edge.
464 ValueLatticeElement getValueOnEdge(Value *V, BasicBlock *FromBB,
465 BasicBlock *ToBB,
466 Instruction *CxtI = nullptr);
467
468 /// Complete flush all previously computed values
469 void clear() {
470 TheCache.clear();
471 }
472
473 /// Printing the LazyValueInfo Analysis.
474 void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
475 LazyValueInfoAnnotatedWriter Writer(this, DTree);
476 F.print(OS, &Writer);
477 }
478
479 /// This is part of the update interface to inform the cache
480 /// that a block has been deleted.
481 void eraseBlock(BasicBlock *BB) {
482 TheCache.eraseBlock(BB);
483 }
484
485 /// Disables use of the DominatorTree within LVI.
486 void disableDT() {
487 if (DT) {
488 assert(!DisabledDT && "Both DT and DisabledDT are not nullptr!")((!DisabledDT && "Both DT and DisabledDT are not nullptr!"
) ? static_cast<void> (0) : __assert_fail ("!DisabledDT && \"Both DT and DisabledDT are not nullptr!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 488, __PRETTY_FUNCTION__))
;
489 std::swap(DT, DisabledDT);
490 }
491 }
492
493 /// Enables use of the DominatorTree within LVI. Does nothing if the class
494 /// instance was initialized without a DT pointer.
495 void enableDT() {
496 if (DisabledDT) {
497 assert(!DT && "Both DT and DisabledDT are not nullptr!")((!DT && "Both DT and DisabledDT are not nullptr!") ?
static_cast<void> (0) : __assert_fail ("!DT && \"Both DT and DisabledDT are not nullptr!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 497, __PRETTY_FUNCTION__))
;
498 std::swap(DT, DisabledDT);
499 }
500 }
501
502 /// This is the update interface to inform the cache that an edge from
503 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
504 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
505
506 LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
507 DominatorTree *DT = nullptr)
508 : AC(AC), DL(DL), DT(DT), DisabledDT(nullptr) {}
509 };
510} // end anonymous namespace
511
512
513void LazyValueInfoImpl::solve() {
514 SmallVector<std::pair<BasicBlock *, Value *>, 8> StartingStack(
515 BlockValueStack.begin(), BlockValueStack.end());
516
517 unsigned processedCount = 0;
518 while (!BlockValueStack.empty()) {
519 processedCount++;
520 // Abort if we have to process too many values to get a result for this one.
521 // Because of the design of the overdefined cache currently being per-block
522 // to avoid naming-related issues (IE it wants to try to give different
523 // results for the same name in different blocks), overdefined results don't
524 // get cached globally, which in turn means we will often try to rediscover
525 // the same overdefined result again and again. Once something like
526 // PredicateInfo is used in LVI or CVP, we should be able to make the
527 // overdefined cache global, and remove this throttle.
528 if (processedCount > MaxProcessedPerValue) {
529 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "Giving up on stack because we are getting too deep\n"
; } } while (false)
530 dbgs() << "Giving up on stack because we are getting too deep\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "Giving up on stack because we are getting too deep\n"
; } } while (false)
;
531 // Fill in the original values
532 while (!StartingStack.empty()) {
533 std::pair<BasicBlock *, Value *> &e = StartingStack.back();
534 TheCache.insertResult(e.second, e.first,
535 ValueLatticeElement::getOverdefined());
536 StartingStack.pop_back();
537 }
538 BlockValueSet.clear();
539 BlockValueStack.clear();
540 return;
541 }
542 std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
543 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!")((BlockValueSet.count(e) && "Stack value should be in BlockValueSet!"
) ? static_cast<void> (0) : __assert_fail ("BlockValueSet.count(e) && \"Stack value should be in BlockValueSet!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 543, __PRETTY_FUNCTION__))
;
544
545 if (solveBlockValue(e.second, e.first)) {
546 // The work item was completely processed.
547 assert(BlockValueStack.back() == e && "Nothing should have been pushed!")((BlockValueStack.back() == e && "Nothing should have been pushed!"
) ? static_cast<void> (0) : __assert_fail ("BlockValueStack.back() == e && \"Nothing should have been pushed!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 547, __PRETTY_FUNCTION__))
;
548 assert(TheCache.hasCachedValueInfo(e.second, e.first) &&((TheCache.hasCachedValueInfo(e.second, e.first) && "Result should be in cache!"
) ? static_cast<void> (0) : __assert_fail ("TheCache.hasCachedValueInfo(e.second, e.first) && \"Result should be in cache!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 549, __PRETTY_FUNCTION__))
549 "Result should be in cache!")((TheCache.hasCachedValueInfo(e.second, e.first) && "Result should be in cache!"
) ? static_cast<void> (0) : __assert_fail ("TheCache.hasCachedValueInfo(e.second, e.first) && \"Result should be in cache!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 549, __PRETTY_FUNCTION__))
;
550
551 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "POP " << *e.second
<< " in " << e.first->getName() << " = "
<< TheCache.getCachedValueInfo(e.second, e.first) <<
"\n"; } } while (false)
552 dbgs() << "POP " << *e.second << " in " << e.first->getName() << " = "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "POP " << *e.second
<< " in " << e.first->getName() << " = "
<< TheCache.getCachedValueInfo(e.second, e.first) <<
"\n"; } } while (false)
553 << TheCache.getCachedValueInfo(e.second, e.first) << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "POP " << *e.second
<< " in " << e.first->getName() << " = "
<< TheCache.getCachedValueInfo(e.second, e.first) <<
"\n"; } } while (false)
;
554
555 BlockValueStack.pop_back();
556 BlockValueSet.erase(e);
557 } else {
558 // More work needs to be done before revisiting.
559 assert(BlockValueStack.back() != e && "Stack should have been pushed!")((BlockValueStack.back() != e && "Stack should have been pushed!"
) ? static_cast<void> (0) : __assert_fail ("BlockValueStack.back() != e && \"Stack should have been pushed!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 559, __PRETTY_FUNCTION__))
;
560 }
561 }
562}
563
564bool LazyValueInfoImpl::hasBlockValue(Value *Val, BasicBlock *BB) {
565 // If already a constant, there is nothing to compute.
566 if (isa<Constant>(Val))
567 return true;
568
569 return TheCache.hasCachedValueInfo(Val, BB);
570}
571
572ValueLatticeElement LazyValueInfoImpl::getBlockValue(Value *Val,
573 BasicBlock *BB) {
574 // If already a constant, there is nothing to compute.
575 if (Constant *VC = dyn_cast<Constant>(Val))
576 return ValueLatticeElement::get(VC);
577
578 return TheCache.getCachedValueInfo(Val, BB);
579}
580
581static ValueLatticeElement getFromRangeMetadata(Instruction *BBI) {
582 switch (BBI->getOpcode()) {
583 default: break;
584 case Instruction::Load:
585 case Instruction::Call:
586 case Instruction::Invoke:
587 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
588 if (isa<IntegerType>(BBI->getType())) {
589 return ValueLatticeElement::getRange(
590 getConstantRangeFromMetadata(*Ranges));
591 }
592 break;
593 };
594 // Nothing known - will be intersected with other facts
595 return ValueLatticeElement::getOverdefined();
596}
597
598bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
599 if (isa<Constant>(Val))
600 return true;
601
602 if (TheCache.hasCachedValueInfo(Val, BB)) {
603 // If we have a cached value, use that.
604 LLVM_DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val="do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " reuse BB '" <<
BB->getName() << "' val=" << TheCache.getCachedValueInfo
(Val, BB) << '\n'; } } while (false)
605 << TheCache.getCachedValueInfo(Val, BB) << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " reuse BB '" <<
BB->getName() << "' val=" << TheCache.getCachedValueInfo
(Val, BB) << '\n'; } } while (false)
;
606
607 // Since we're reusing a cached value, we don't need to update the
608 // OverDefinedCache. The cache will have been properly updated whenever the
609 // cached value was inserted.
610 return true;
611 }
612
613 // Hold off inserting this value into the Cache in case we have to return
614 // false and come back later.
615 ValueLatticeElement Res;
616 if (!solveBlockValueImpl(Res, Val, BB))
617 // Work pushed, will revisit
618 return false;
619
620 TheCache.insertResult(Val, BB, Res);
621 return true;
622}
623
624bool LazyValueInfoImpl::solveBlockValueImpl(ValueLatticeElement &Res,
625 Value *Val, BasicBlock *BB) {
626
627 Instruction *BBI = dyn_cast<Instruction>(Val);
628 if (!BBI || BBI->getParent() != BB)
629 return solveBlockValueNonLocal(Res, Val, BB);
630
631 if (PHINode *PN = dyn_cast<PHINode>(BBI))
632 return solveBlockValuePHINode(Res, PN, BB);
633
634 if (auto *SI = dyn_cast<SelectInst>(BBI))
635 return solveBlockValueSelect(Res, SI, BB);
636
637 // If this value is a nonnull pointer, record it's range and bailout. Note
638 // that for all other pointer typed values, we terminate the search at the
639 // definition. We could easily extend this to look through geps, bitcasts,
640 // and the like to prove non-nullness, but it's not clear that's worth it
641 // compile time wise. The context-insensitive value walk done inside
642 // isKnownNonZero gets most of the profitable cases at much less expense.
643 // This does mean that we have a sensitivity to where the defining
644 // instruction is placed, even if it could legally be hoisted much higher.
645 // That is unfortunate.
646 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
647 if (PT && isKnownNonZero(BBI, DL)) {
648 Res = ValueLatticeElement::getNot(ConstantPointerNull::get(PT));
649 return true;
650 }
651 if (BBI->getType()->isIntegerTy()) {
652 if (auto *CI = dyn_cast<CastInst>(BBI))
653 return solveBlockValueCast(Res, CI, BB);
654
655 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI))
656 return solveBlockValueBinaryOp(Res, BO, BB);
657
658 if (auto *EVI = dyn_cast<ExtractValueInst>(BBI))
659 return solveBlockValueExtractValue(Res, EVI, BB);
660
661 if (auto *II = dyn_cast<IntrinsicInst>(BBI))
662 return solveBlockValueIntrinsic(Res, II, BB);
663 }
664
665 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - unknown inst def found.\n"; }
} while (false)
666 << "' - unknown inst def found.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - unknown inst def found.\n"; }
} while (false)
;
667 Res = getFromRangeMetadata(BBI);
668 return true;
669}
670
671static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
672 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
673 return L->getPointerAddressSpace() == 0 &&
674 GetUnderlyingObject(L->getPointerOperand(),
675 L->getModule()->getDataLayout()) == Ptr;
676 }
677 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
678 return S->getPointerAddressSpace() == 0 &&
679 GetUnderlyingObject(S->getPointerOperand(),
680 S->getModule()->getDataLayout()) == Ptr;
681 }
682 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
683 if (MI->isVolatile()) return false;
684
685 // FIXME: check whether it has a valuerange that excludes zero?
686 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
687 if (!Len || Len->isZero()) return false;
688
689 if (MI->getDestAddressSpace() == 0)
690 if (GetUnderlyingObject(MI->getRawDest(),
691 MI->getModule()->getDataLayout()) == Ptr)
692 return true;
693 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
694 if (MTI->getSourceAddressSpace() == 0)
695 if (GetUnderlyingObject(MTI->getRawSource(),
696 MTI->getModule()->getDataLayout()) == Ptr)
697 return true;
698 }
699 return false;
700}
701
702/// Return true if the allocation associated with Val is ever dereferenced
703/// within the given basic block. This establishes the fact Val is not null,
704/// but does not imply that the memory at Val is dereferenceable. (Val may
705/// point off the end of the dereferenceable part of the object.)
706static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB) {
707 assert(Val->getType()->isPointerTy())((Val->getType()->isPointerTy()) ? static_cast<void>
(0) : __assert_fail ("Val->getType()->isPointerTy()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 707, __PRETTY_FUNCTION__))
;
708
709 const DataLayout &DL = BB->getModule()->getDataLayout();
710 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
711 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
712 // inside InstructionDereferencesPointer either.
713 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1))
714 for (Instruction &I : *BB)
715 if (InstructionDereferencesPointer(&I, UnderlyingVal))
716 return true;
717 return false;
718}
719
720bool LazyValueInfoImpl::solveBlockValueNonLocal(ValueLatticeElement &BBLV,
721 Value *Val, BasicBlock *BB) {
722 ValueLatticeElement Result; // Start Undefined.
723
724 // If this is the entry block, we must be asking about an argument. The
725 // value is overdefined.
726 if (BB == &BB->getParent()->getEntryBlock()) {
727 assert(isa<Argument>(Val) && "Unknown live-in to the entry block")((isa<Argument>(Val) && "Unknown live-in to the entry block"
) ? static_cast<void> (0) : __assert_fail ("isa<Argument>(Val) && \"Unknown live-in to the entry block\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 727, __PRETTY_FUNCTION__))
;
728 // Before giving up, see if we can prove the pointer non-null local to
729 // this particular block.
730 PointerType *PTy = dyn_cast<PointerType>(Val->getType());
731 if (PTy &&
732 (isKnownNonZero(Val, DL) ||
733 (isObjectDereferencedInBlock(Val, BB) &&
734 !NullPointerIsDefined(BB->getParent(), PTy->getAddressSpace())))) {
735 Result = ValueLatticeElement::getNot(ConstantPointerNull::get(PTy));
736 } else {
737 Result = ValueLatticeElement::getOverdefined();
738 }
739 BBLV = Result;
740 return true;
741 }
742
743 // Loop over all of our predecessors, merging what we know from them into
744 // result. If we encounter an unexplored predecessor, we eagerly explore it
745 // in a depth first manner. In practice, this has the effect of discovering
746 // paths we can't analyze eagerly without spending compile times analyzing
747 // other paths. This heuristic benefits from the fact that predecessors are
748 // frequently arranged such that dominating ones come first and we quickly
749 // find a path to function entry. TODO: We should consider explicitly
750 // canonicalizing to make this true rather than relying on this happy
751 // accident.
752 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
753 ValueLatticeElement EdgeResult;
754 if (!getEdgeValue(Val, *PI, BB, EdgeResult))
755 // Explore that input, then return here
756 return false;
757
758 Result.mergeIn(EdgeResult, DL);
759
760 // If we hit overdefined, exit early. The BlockVals entry is already set
761 // to overdefined.
762 if (Result.isOverdefined()) {
763 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined because of pred (non local).\n"
; } } while (false)
764 << "' - overdefined because of pred (non local).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined because of pred (non local).\n"
; } } while (false)
;
765 // Before giving up, see if we can prove the pointer non-null local to
766 // this particular block.
767 PointerType *PTy = dyn_cast<PointerType>(Val->getType());
768 if (PTy && isObjectDereferencedInBlock(Val, BB) &&
769 !NullPointerIsDefined(BB->getParent(), PTy->getAddressSpace())) {
770 Result = ValueLatticeElement::getNot(ConstantPointerNull::get(PTy));
771 }
772
773 BBLV = Result;
774 return true;
775 }
776 }
777
778 // Return the merged value, which is more precise than 'overdefined'.
779 assert(!Result.isOverdefined())((!Result.isOverdefined()) ? static_cast<void> (0) : __assert_fail
("!Result.isOverdefined()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 779, __PRETTY_FUNCTION__))
;
780 BBLV = Result;
781 return true;
782}
783
784bool LazyValueInfoImpl::solveBlockValuePHINode(ValueLatticeElement &BBLV,
785 PHINode *PN, BasicBlock *BB) {
786 ValueLatticeElement Result; // Start Undefined.
787
788 // Loop over all of our predecessors, merging what we know from them into
789 // result. See the comment about the chosen traversal order in
790 // solveBlockValueNonLocal; the same reasoning applies here.
791 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
792 BasicBlock *PhiBB = PN->getIncomingBlock(i);
793 Value *PhiVal = PN->getIncomingValue(i);
794 ValueLatticeElement EdgeResult;
795 // Note that we can provide PN as the context value to getEdgeValue, even
796 // though the results will be cached, because PN is the value being used as
797 // the cache key in the caller.
798 if (!getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN))
799 // Explore that input, then return here
800 return false;
801
802 Result.mergeIn(EdgeResult, DL);
803
804 // If we hit overdefined, exit early. The BlockVals entry is already set
805 // to overdefined.
806 if (Result.isOverdefined()) {
807 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined because of pred (local).\n"
; } } while (false)
808 << "' - overdefined because of pred (local).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined because of pred (local).\n"
; } } while (false)
;
809
810 BBLV = Result;
811 return true;
812 }
813 }
814
815 // Return the merged value, which is more precise than 'overdefined'.
816 assert(!Result.isOverdefined() && "Possible PHI in entry block?")((!Result.isOverdefined() && "Possible PHI in entry block?"
) ? static_cast<void> (0) : __assert_fail ("!Result.isOverdefined() && \"Possible PHI in entry block?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 816, __PRETTY_FUNCTION__))
;
817 BBLV = Result;
818 return true;
819}
820
821static ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
822 bool isTrueDest = true);
823
824// If we can determine a constraint on the value given conditions assumed by
825// the program, intersect those constraints with BBLV
826void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
827 Value *Val, ValueLatticeElement &BBLV, Instruction *BBI) {
828 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
829 if (!BBI)
830 return;
831
832 for (auto &AssumeVH : AC->assumptionsFor(Val)) {
833 if (!AssumeVH)
834 continue;
835 auto *I = cast<CallInst>(AssumeVH);
836 if (!isValidAssumeForContext(I, BBI, DT))
837 continue;
838
839 BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
840 }
841
842 // If guards are not used in the module, don't spend time looking for them
843 auto *GuardDecl = BBI->getModule()->getFunction(
844 Intrinsic::getName(Intrinsic::experimental_guard));
845 if (!GuardDecl || GuardDecl->use_empty())
846 return;
847
848 if (BBI->getIterator() == BBI->getParent()->begin())
849 return;
850 for (Instruction &I : make_range(std::next(BBI->getIterator().getReverse()),
851 BBI->getParent()->rend())) {
852 Value *Cond = nullptr;
853 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
854 BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
855 }
856}
857
858bool LazyValueInfoImpl::solveBlockValueSelect(ValueLatticeElement &BBLV,
859 SelectInst *SI, BasicBlock *BB) {
860
861 // Recurse on our inputs if needed
862 if (!hasBlockValue(SI->getTrueValue(), BB)) {
863 if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
864 return false;
865 BBLV = ValueLatticeElement::getOverdefined();
866 return true;
867 }
868 ValueLatticeElement TrueVal = getBlockValue(SI->getTrueValue(), BB);
869 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
870 // extra slots in the table if we can.
871 if (TrueVal.isOverdefined()) {
872 BBLV = ValueLatticeElement::getOverdefined();
873 return true;
874 }
875
876 if (!hasBlockValue(SI->getFalseValue(), BB)) {
877 if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
878 return false;
879 BBLV = ValueLatticeElement::getOverdefined();
880 return true;
881 }
882 ValueLatticeElement FalseVal = getBlockValue(SI->getFalseValue(), BB);
883 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
884 // extra slots in the table if we can.
885 if (FalseVal.isOverdefined()) {
886 BBLV = ValueLatticeElement::getOverdefined();
887 return true;
888 }
889
890 if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
891 const ConstantRange &TrueCR = TrueVal.getConstantRange();
892 const ConstantRange &FalseCR = FalseVal.getConstantRange();
893 Value *LHS = nullptr;
894 Value *RHS = nullptr;
895 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
896 // Is this a min specifically of our two inputs? (Avoid the risk of
897 // ValueTracking getting smarter looking back past our immediate inputs.)
898 if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
899 LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
900 ConstantRange ResultCR = [&]() {
901 switch (SPR.Flavor) {
902 default:
903 llvm_unreachable("unexpected minmax type!")::llvm::llvm_unreachable_internal("unexpected minmax type!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 903)
;
904 case SPF_SMIN: /// Signed minimum
905 return TrueCR.smin(FalseCR);
906 case SPF_UMIN: /// Unsigned minimum
907 return TrueCR.umin(FalseCR);
908 case SPF_SMAX: /// Signed maximum
909 return TrueCR.smax(FalseCR);
910 case SPF_UMAX: /// Unsigned maximum
911 return TrueCR.umax(FalseCR);
912 };
913 }();
914 BBLV = ValueLatticeElement::getRange(ResultCR);
915 return true;
916 }
917
918 if (SPR.Flavor == SPF_ABS) {
919 if (LHS == SI->getTrueValue()) {
920 BBLV = ValueLatticeElement::getRange(TrueCR.abs());
921 return true;
922 }
923 if (LHS == SI->getFalseValue()) {
924 BBLV = ValueLatticeElement::getRange(FalseCR.abs());
925 return true;
926 }
927 }
928
929 if (SPR.Flavor == SPF_NABS) {
930 ConstantRange Zero(APInt::getNullValue(TrueCR.getBitWidth()));
931 if (LHS == SI->getTrueValue()) {
932 BBLV = ValueLatticeElement::getRange(Zero.sub(TrueCR.abs()));
933 return true;
934 }
935 if (LHS == SI->getFalseValue()) {
936 BBLV = ValueLatticeElement::getRange(Zero.sub(FalseCR.abs()));
937 return true;
938 }
939 }
940 }
941
942 // Can we constrain the facts about the true and false values by using the
943 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
944 // TODO: We could potentially refine an overdefined true value above.
945 Value *Cond = SI->getCondition();
946 TrueVal = intersect(TrueVal,
947 getValueFromCondition(SI->getTrueValue(), Cond, true));
948 FalseVal = intersect(FalseVal,
949 getValueFromCondition(SI->getFalseValue(), Cond, false));
950
951 // Handle clamp idioms such as:
952 // %24 = constantrange<0, 17>
953 // %39 = icmp eq i32 %24, 0
954 // %40 = add i32 %24, -1
955 // %siv.next = select i1 %39, i32 16, i32 %40
956 // %siv.next = constantrange<0, 17> not <-1, 17>
957 // In general, this can handle any clamp idiom which tests the edge
958 // condition via an equality or inequality.
959 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
960 ICmpInst::Predicate Pred = ICI->getPredicate();
961 Value *A = ICI->getOperand(0);
962 if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
963 auto addConstants = [](ConstantInt *A, ConstantInt *B) {
964 assert(A->getType() == B->getType())((A->getType() == B->getType()) ? static_cast<void>
(0) : __assert_fail ("A->getType() == B->getType()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 964, __PRETTY_FUNCTION__))
;
965 return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
966 };
967 // See if either input is A + C2, subject to the constraint from the
968 // condition that A != C when that input is used. We can assume that
969 // that input doesn't include C + C2.
970 ConstantInt *CIAdded;
971 switch (Pred) {
972 default: break;
973 case ICmpInst::ICMP_EQ:
974 if (match(SI->getFalseValue(), m_Add(m_Specific(A),
975 m_ConstantInt(CIAdded)))) {
976 auto ResNot = addConstants(CIBase, CIAdded);
977 FalseVal = intersect(FalseVal,
978 ValueLatticeElement::getNot(ResNot));
979 }
980 break;
981 case ICmpInst::ICMP_NE:
982 if (match(SI->getTrueValue(), m_Add(m_Specific(A),
983 m_ConstantInt(CIAdded)))) {
984 auto ResNot = addConstants(CIBase, CIAdded);
985 TrueVal = intersect(TrueVal,
986 ValueLatticeElement::getNot(ResNot));
987 }
988 break;
989 };
990 }
991 }
992
993 ValueLatticeElement Result; // Start Undefined.
994 Result.mergeIn(TrueVal, DL);
995 Result.mergeIn(FalseVal, DL);
996 BBLV = Result;
997 return true;
998}
999
1000Optional<ConstantRange> LazyValueInfoImpl::getRangeForOperand(unsigned Op,
1001 Instruction *I,
1002 BasicBlock *BB) {
1003 if (!hasBlockValue(I->getOperand(Op), BB))
1004 if (pushBlockValue(std::make_pair(BB, I->getOperand(Op))))
1005 return None;
1006
1007 const unsigned OperandBitWidth =
1008 DL.getTypeSizeInBits(I->getOperand(Op)->getType());
1009 ConstantRange Range = ConstantRange::getFull(OperandBitWidth);
1010 if (hasBlockValue(I->getOperand(Op), BB)) {
1011 ValueLatticeElement Val = getBlockValue(I->getOperand(Op), BB);
1012 intersectAssumeOrGuardBlockValueConstantRange(I->getOperand(Op), Val, I);
1013 if (Val.isConstantRange())
1014 Range = Val.getConstantRange();
1015 }
1016 return Range;
1017}
1018
1019bool LazyValueInfoImpl::solveBlockValueCast(ValueLatticeElement &BBLV,
1020 CastInst *CI,
1021 BasicBlock *BB) {
1022 if (!CI->getOperand(0)->getType()->isSized()) {
1023 // Without knowing how wide the input is, we can't analyze it in any useful
1024 // way.
1025 BBLV = ValueLatticeElement::getOverdefined();
1026 return true;
1027 }
1028
1029 // Filter out casts we don't know how to reason about before attempting to
1030 // recurse on our operand. This can cut a long search short if we know we're
1031 // not going to be able to get any useful information anways.
1032 switch (CI->getOpcode()) {
1033 case Instruction::Trunc:
1034 case Instruction::SExt:
1035 case Instruction::ZExt:
1036 case Instruction::BitCast:
1037 break;
1038 default:
1039 // Unhandled instructions are overdefined.
1040 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown cast).\n"
; } } while (false)
1041 << "' - overdefined (unknown cast).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown cast).\n"
; } } while (false)
;
1042 BBLV = ValueLatticeElement::getOverdefined();
1043 return true;
1044 }
1045
1046 // Figure out the range of the LHS. If that fails, we still apply the
1047 // transfer rule on the full set since we may be able to locally infer
1048 // interesting facts.
1049 Optional<ConstantRange> LHSRes = getRangeForOperand(0, CI, BB);
1050 if (!LHSRes.hasValue())
1051 // More work to do before applying this transfer rule.
1052 return false;
1053 ConstantRange LHSRange = LHSRes.getValue();
1054
1055 const unsigned ResultBitWidth = CI->getType()->getIntegerBitWidth();
1056
1057 // NOTE: We're currently limited by the set of operations that ConstantRange
1058 // can evaluate symbolically. Enhancing that set will allows us to analyze
1059 // more definitions.
1060 BBLV = ValueLatticeElement::getRange(LHSRange.castOp(CI->getOpcode(),
1061 ResultBitWidth));
1062 return true;
1063}
1064
1065bool LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
1066 ValueLatticeElement &BBLV, Instruction *I, BasicBlock *BB,
1067 std::function<ConstantRange(const ConstantRange &,
1068 const ConstantRange &)> OpFn) {
1069 // Figure out the ranges of the operands. If that fails, use a
1070 // conservative range, but apply the transfer rule anyways. This
1071 // lets us pick up facts from expressions like "and i32 (call i32
1072 // @foo()), 32"
1073 Optional<ConstantRange> LHSRes = getRangeForOperand(0, I, BB);
1074 Optional<ConstantRange> RHSRes = getRangeForOperand(1, I, BB);
1075 if (!LHSRes.hasValue() || !RHSRes.hasValue())
1076 // More work to do before applying this transfer rule.
1077 return false;
1078
1079 ConstantRange LHSRange = LHSRes.getValue();
1080 ConstantRange RHSRange = RHSRes.getValue();
1081 BBLV = ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange));
1082 return true;
1083}
1084
1085bool LazyValueInfoImpl::solveBlockValueBinaryOp(ValueLatticeElement &BBLV,
1086 BinaryOperator *BO,
1087 BasicBlock *BB) {
1088
1089 assert(BO->getOperand(0)->getType()->isSized() &&((BO->getOperand(0)->getType()->isSized() &&
"all operands to binary operators are sized") ? static_cast<
void> (0) : __assert_fail ("BO->getOperand(0)->getType()->isSized() && \"all operands to binary operators are sized\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1090, __PRETTY_FUNCTION__))
1090 "all operands to binary operators are sized")((BO->getOperand(0)->getType()->isSized() &&
"all operands to binary operators are sized") ? static_cast<
void> (0) : __assert_fail ("BO->getOperand(0)->getType()->isSized() && \"all operands to binary operators are sized\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1090, __PRETTY_FUNCTION__))
;
1091 if (BO->getOpcode() == Instruction::Xor) {
1092 // Xor is the only operation not supported by ConstantRange::binaryOp().
1093 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown binary operator).\n"
; } } while (false)
1094 << "' - overdefined (unknown binary operator).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown binary operator).\n"
; } } while (false)
;
1095 BBLV = ValueLatticeElement::getOverdefined();
1096 return true;
1097 }
1098
1099 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO)) {
1100 unsigned NoWrapKind = 0;
1101 if (OBO->hasNoUnsignedWrap())
1102 NoWrapKind |= OverflowingBinaryOperator::NoUnsignedWrap;
1103 if (OBO->hasNoSignedWrap())
1104 NoWrapKind |= OverflowingBinaryOperator::NoSignedWrap;
1105
1106 return solveBlockValueBinaryOpImpl(
1107 BBLV, BO, BB,
1108 [BO, NoWrapKind](const ConstantRange &CR1, const ConstantRange &CR2) {
1109 return CR1.overflowingBinaryOp(BO->getOpcode(), CR2, NoWrapKind);
1110 });
1111 }
1112
1113 return solveBlockValueBinaryOpImpl(
1114 BBLV, BO, BB, [BO](const ConstantRange &CR1, const ConstantRange &CR2) {
1115 return CR1.binaryOp(BO->getOpcode(), CR2);
1116 });
1117}
1118
1119bool LazyValueInfoImpl::solveBlockValueOverflowIntrinsic(
1120 ValueLatticeElement &BBLV, WithOverflowInst *WO, BasicBlock *BB) {
1121 return solveBlockValueBinaryOpImpl(BBLV, WO, BB,
1122 [WO](const ConstantRange &CR1, const ConstantRange &CR2) {
1123 return CR1.binaryOp(WO->getBinaryOp(), CR2);
1124 });
1125}
1126
1127bool LazyValueInfoImpl::solveBlockValueSaturatingIntrinsic(
1128 ValueLatticeElement &BBLV, SaturatingInst *SI, BasicBlock *BB) {
1129 switch (SI->getIntrinsicID()) {
1130 case Intrinsic::uadd_sat:
1131 return solveBlockValueBinaryOpImpl(
1132 BBLV, SI, BB, [](const ConstantRange &CR1, const ConstantRange &CR2) {
1133 return CR1.uadd_sat(CR2);
1134 });
1135 case Intrinsic::usub_sat:
1136 return solveBlockValueBinaryOpImpl(
1137 BBLV, SI, BB, [](const ConstantRange &CR1, const ConstantRange &CR2) {
1138 return CR1.usub_sat(CR2);
1139 });
1140 case Intrinsic::sadd_sat:
1141 return solveBlockValueBinaryOpImpl(
1142 BBLV, SI, BB, [](const ConstantRange &CR1, const ConstantRange &CR2) {
1143 return CR1.sadd_sat(CR2);
1144 });
1145 case Intrinsic::ssub_sat:
1146 return solveBlockValueBinaryOpImpl(
1147 BBLV, SI, BB, [](const ConstantRange &CR1, const ConstantRange &CR2) {
1148 return CR1.ssub_sat(CR2);
1149 });
1150 default:
1151 llvm_unreachable("All llvm.sat intrinsic are handled.")::llvm::llvm_unreachable_internal("All llvm.sat intrinsic are handled."
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1151)
;
1152 }
1153}
1154
1155bool LazyValueInfoImpl::solveBlockValueIntrinsic(ValueLatticeElement &BBLV,
1156 IntrinsicInst *II,
1157 BasicBlock *BB) {
1158 if (auto *SI = dyn_cast<SaturatingInst>(II))
1159 return solveBlockValueSaturatingIntrinsic(BBLV, SI, BB);
1160
1161 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown intrinsic).\n"
; } } while (false)
1162 << "' - overdefined (unknown intrinsic).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown intrinsic).\n"
; } } while (false)
;
1163 BBLV = ValueLatticeElement::getOverdefined();
1164 return true;
1165}
1166
1167bool LazyValueInfoImpl::solveBlockValueExtractValue(
1168 ValueLatticeElement &BBLV, ExtractValueInst *EVI, BasicBlock *BB) {
1169 if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1170 if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 0)
1171 return solveBlockValueOverflowIntrinsic(BBLV, WO, BB);
1172
1173 // Handle extractvalue of insertvalue to allow further simplification
1174 // based on replaced with.overflow intrinsics.
1175 if (Value *V = SimplifyExtractValueInst(
1176 EVI->getAggregateOperand(), EVI->getIndices(),
1177 EVI->getModule()->getDataLayout())) {
1178 if (!hasBlockValue(V, BB)) {
1179 if (pushBlockValue({ BB, V }))
1180 return false;
1181 BBLV = ValueLatticeElement::getOverdefined();
1182 return true;
1183 }
1184 BBLV = getBlockValue(V, BB);
1185 return true;
1186 }
1187
1188 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown extractvalue).\n"
; } } while (false)
1189 << "' - overdefined (unknown extractvalue).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown extractvalue).\n"
; } } while (false)
;
1190 BBLV = ValueLatticeElement::getOverdefined();
1191 return true;
1192}
1193
1194static ValueLatticeElement getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
1195 bool isTrueDest) {
1196 Value *LHS = ICI->getOperand(0);
1197 Value *RHS = ICI->getOperand(1);
1198 CmpInst::Predicate Predicate = ICI->getPredicate();
1199
1200 if (isa<Constant>(RHS)) {
1201 if (ICI->isEquality() && LHS == Val) {
1202 // We know that V has the RHS constant if this is a true SETEQ or
1203 // false SETNE.
1204 if (isTrueDest == (Predicate == ICmpInst::ICMP_EQ))
1205 return ValueLatticeElement::get(cast<Constant>(RHS));
1206 else
1207 return ValueLatticeElement::getNot(cast<Constant>(RHS));
1208 }
1209 }
1210
1211 if (!Val->getType()->isIntegerTy())
1212 return ValueLatticeElement::getOverdefined();
1213
1214 // Use ConstantRange::makeAllowedICmpRegion in order to determine the possible
1215 // range of Val guaranteed by the condition. Recognize comparisons in the from
1216 // of:
1217 // icmp <pred> Val, ...
1218 // icmp <pred> (add Val, Offset), ...
1219 // The latter is the range checking idiom that InstCombine produces. Subtract
1220 // the offset from the allowed range for RHS in this case.
1221
1222 // Val or (add Val, Offset) can be on either hand of the comparison
1223 if (LHS != Val && !match(LHS, m_Add(m_Specific(Val), m_ConstantInt()))) {
1224 std::swap(LHS, RHS);
1225 Predicate = CmpInst::getSwappedPredicate(Predicate);
1226 }
1227
1228 ConstantInt *Offset = nullptr;
1229 if (LHS != Val)
1230 match(LHS, m_Add(m_Specific(Val), m_ConstantInt(Offset)));
1231
1232 if (LHS == Val || Offset) {
1233 // Calculate the range of values that are allowed by the comparison
1234 ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
1235 /*isFullSet=*/true);
1236 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
1237 RHSRange = ConstantRange(CI->getValue());
1238 else if (Instruction *I = dyn_cast<Instruction>(RHS))
1239 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
1240 RHSRange = getConstantRangeFromMetadata(*Ranges);
1241
1242 // If we're interested in the false dest, invert the condition
1243 CmpInst::Predicate Pred =
1244 isTrueDest ? Predicate : CmpInst::getInversePredicate(Predicate);
1245 ConstantRange TrueValues =
1246 ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1247
1248 if (Offset) // Apply the offset from above.
1249 TrueValues = TrueValues.subtract(Offset->getValue());
1250
1251 return ValueLatticeElement::getRange(std::move(TrueValues));
1252 }
1253
1254 return ValueLatticeElement::getOverdefined();
1255}
1256
1257// Handle conditions of the form
1258// extractvalue(op.with.overflow(%x, C), 1).
1259static ValueLatticeElement getValueFromOverflowCondition(
1260 Value *Val, WithOverflowInst *WO, bool IsTrueDest) {
1261 // TODO: This only works with a constant RHS for now. We could also compute
1262 // the range of the RHS, but this doesn't fit into the current structure of
1263 // the edge value calculation.
1264 const APInt *C;
1265 if (WO->getLHS() != Val || !match(WO->getRHS(), m_APInt(C)))
1266 return ValueLatticeElement::getOverdefined();
1267
1268 // Calculate the possible values of %x for which no overflow occurs.
1269 ConstantRange NWR = ConstantRange::makeExactNoWrapRegion(
1270 WO->getBinaryOp(), *C, WO->getNoWrapKind());
1271
1272 // If overflow is false, %x is constrained to NWR. If overflow is true, %x is
1273 // constrained to it's inverse (all values that might cause overflow).
1274 if (IsTrueDest)
1275 NWR = NWR.inverse();
1276 return ValueLatticeElement::getRange(NWR);
1277}
1278
1279static ValueLatticeElement
1280getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1281 DenseMap<Value*, ValueLatticeElement> &Visited);
1282
1283static ValueLatticeElement
1284getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest,
1285 DenseMap<Value*, ValueLatticeElement> &Visited) {
1286 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1287 return getValueFromICmpCondition(Val, ICI, isTrueDest);
1288
1289 if (auto *EVI = dyn_cast<ExtractValueInst>(Cond))
1290 if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1291 if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 1)
1292 return getValueFromOverflowCondition(Val, WO, isTrueDest);
1293
1294 // Handle conditions in the form of (cond1 && cond2), we know that on the
1295 // true dest path both of the conditions hold. Similarly for conditions of
1296 // the form (cond1 || cond2), we know that on the false dest path neither
1297 // condition holds.
1298 BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond);
1299 if (!BO || (isTrueDest && BO->getOpcode() != BinaryOperator::And) ||
1300 (!isTrueDest && BO->getOpcode() != BinaryOperator::Or))
1301 return ValueLatticeElement::getOverdefined();
1302
1303 // Prevent infinite recursion if Cond references itself as in this example:
1304 // Cond: "%tmp4 = and i1 %tmp4, undef"
1305 // BL: "%tmp4 = and i1 %tmp4, undef"
1306 // BR: "i1 undef"
1307 Value *BL = BO->getOperand(0);
1308 Value *BR = BO->getOperand(1);
1309 if (BL == Cond || BR == Cond)
1310 return ValueLatticeElement::getOverdefined();
1311
1312 return intersect(getValueFromCondition(Val, BL, isTrueDest, Visited),
1313 getValueFromCondition(Val, BR, isTrueDest, Visited));
1314}
1315
1316static ValueLatticeElement
1317getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1318 DenseMap<Value*, ValueLatticeElement> &Visited) {
1319 auto I = Visited.find(Cond);
1320 if (I != Visited.end())
1321 return I->second;
1322
1323 auto Result = getValueFromConditionImpl(Val, Cond, isTrueDest, Visited);
1324 Visited[Cond] = Result;
1325 return Result;
1326}
1327
1328ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
1329 bool isTrueDest) {
1330 assert(Cond && "precondition")((Cond && "precondition") ? static_cast<void> (
0) : __assert_fail ("Cond && \"precondition\"", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1330, __PRETTY_FUNCTION__))
;
1331 DenseMap<Value*, ValueLatticeElement> Visited;
1332 return getValueFromCondition(Val, Cond, isTrueDest, Visited);
1333}
1334
1335// Return true if Usr has Op as an operand, otherwise false.
1336static bool usesOperand(User *Usr, Value *Op) {
1337 return find(Usr->operands(), Op) != Usr->op_end();
1338}
1339
1340// Return true if the instruction type of Val is supported by
1341// constantFoldUser(). Currently CastInst and BinaryOperator only. Call this
1342// before calling constantFoldUser() to find out if it's even worth attempting
1343// to call it.
1344static bool isOperationFoldable(User *Usr) {
1345 return isa<CastInst>(Usr) || isa<BinaryOperator>(Usr);
1346}
1347
1348// Check if Usr can be simplified to an integer constant when the value of one
1349// of its operands Op is an integer constant OpConstVal. If so, return it as an
1350// lattice value range with a single element or otherwise return an overdefined
1351// lattice value.
1352static ValueLatticeElement constantFoldUser(User *Usr, Value *Op,
1353 const APInt &OpConstVal,
1354 const DataLayout &DL) {
1355 assert(isOperationFoldable(Usr) && "Precondition")((isOperationFoldable(Usr) && "Precondition") ? static_cast
<void> (0) : __assert_fail ("isOperationFoldable(Usr) && \"Precondition\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1355, __PRETTY_FUNCTION__))
;
1356 Constant* OpConst = Constant::getIntegerValue(Op->getType(), OpConstVal);
1357 // Check if Usr can be simplified to a constant.
1358 if (auto *CI = dyn_cast<CastInst>(Usr)) {
1359 assert(CI->getOperand(0) == Op && "Operand 0 isn't Op")((CI->getOperand(0) == Op && "Operand 0 isn't Op")
? static_cast<void> (0) : __assert_fail ("CI->getOperand(0) == Op && \"Operand 0 isn't Op\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1359, __PRETTY_FUNCTION__))
;
1360 if (auto *C = dyn_cast_or_null<ConstantInt>(
1361 SimplifyCastInst(CI->getOpcode(), OpConst,
1362 CI->getDestTy(), DL))) {
1363 return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1364 }
1365 } else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
1366 bool Op0Match = BO->getOperand(0) == Op;
1367 bool Op1Match = BO->getOperand(1) == Op;
1368 assert((Op0Match || Op1Match) &&(((Op0Match || Op1Match) && "Operand 0 nor Operand 1 isn't a match"
) ? static_cast<void> (0) : __assert_fail ("(Op0Match || Op1Match) && \"Operand 0 nor Operand 1 isn't a match\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1369, __PRETTY_FUNCTION__))
1369 "Operand 0 nor Operand 1 isn't a match")(((Op0Match || Op1Match) && "Operand 0 nor Operand 1 isn't a match"
) ? static_cast<void> (0) : __assert_fail ("(Op0Match || Op1Match) && \"Operand 0 nor Operand 1 isn't a match\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1369, __PRETTY_FUNCTION__))
;
1370 Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
1371 Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
1372 if (auto *C = dyn_cast_or_null<ConstantInt>(
1373 SimplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
1374 return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1375 }
1376 }
1377 return ValueLatticeElement::getOverdefined();
1378}
1379
1380/// Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
1381/// Val is not constrained on the edge. Result is unspecified if return value
1382/// is false.
1383static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1384 BasicBlock *BBTo, ValueLatticeElement &Result) {
1385 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
1386 // know that v != 0.
1387 if (BranchInst *BI
11.1
'BI' is non-null
11.1
'BI' is non-null
11.1
'BI' is non-null
= dyn_cast<BranchInst>(BBFrom->getTerminator())) {
11
Assuming the object is a 'BranchInst'
12
Taking true branch
1388 // If this is a conditional branch and only one successor goes to BBTo, then
1389 // we may be able to infer something from the condition.
1390 if (BI->isConditional() &&
13
Calling 'BranchInst::isConditional'
16
Returning from 'BranchInst::isConditional'
17
Taking true branch
1391 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1392 bool isTrueDest = BI->getSuccessor(0) == BBTo;
18
Assuming pointer value is null
1393 assert(BI->getSuccessor(!isTrueDest) == BBTo &&((BI->getSuccessor(!isTrueDest) == BBTo && "BBTo isn't a successor of BBFrom"
) ? static_cast<void> (0) : __assert_fail ("BI->getSuccessor(!isTrueDest) == BBTo && \"BBTo isn't a successor of BBFrom\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1394, __PRETTY_FUNCTION__))
19
'?' condition is true
1394 "BBTo isn't a successor of BBFrom")((BI->getSuccessor(!isTrueDest) == BBTo && "BBTo isn't a successor of BBFrom"
) ? static_cast<void> (0) : __assert_fail ("BI->getSuccessor(!isTrueDest) == BBTo && \"BBTo isn't a successor of BBFrom\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1394, __PRETTY_FUNCTION__))
;
1395 Value *Condition = BI->getCondition();
1396
1397 // If V is the condition of the branch itself, then we know exactly what
1398 // it is.
1399 if (Condition == Val) {
20
Assuming 'Condition' is not equal to 'Val'
21
Taking false branch
1400 Result = ValueLatticeElement::get(ConstantInt::get(
1401 Type::getInt1Ty(Val->getContext()), isTrueDest));
1402 return true;
1403 }
1404
1405 // If the condition of the branch is an equality comparison, we may be
1406 // able to infer the value.
1407 Result = getValueFromCondition(Val, Condition, isTrueDest);
1408 if (!Result.isOverdefined())
22
Calling 'ValueLatticeElement::isOverdefined'
25
Returning from 'ValueLatticeElement::isOverdefined'
26
Taking false branch
1409 return true;
1410
1411 if (User *Usr
27.1
'Usr' is non-null
27.1
'Usr' is non-null
27.1
'Usr' is non-null
= dyn_cast<User>(Val)) {
27
Assuming 'Val' is a 'User'
28
Taking true branch
1412 assert(Result.isOverdefined() && "Result isn't overdefined")((Result.isOverdefined() && "Result isn't overdefined"
) ? static_cast<void> (0) : __assert_fail ("Result.isOverdefined() && \"Result isn't overdefined\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1412, __PRETTY_FUNCTION__))
;
29
'?' condition is true
1413 // Check with isOperationFoldable() first to avoid linearly iterating
1414 // over the operands unnecessarily which can be expensive for
1415 // instructions with many operands.
1416 if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
30
Assuming the object is a 'IntegerType'
31
Taking true branch
1417 const DataLayout &DL = BBTo->getModule()->getDataLayout();
32
Called C++ object pointer is null
1418 if (usesOperand(Usr, Condition)) {
1419 // If Val has Condition as an operand and Val can be folded into a
1420 // constant with either Condition == true or Condition == false,
1421 // propagate the constant.
1422 // eg.
1423 // ; %Val is true on the edge to %then.
1424 // %Val = and i1 %Condition, true.
1425 // br %Condition, label %then, label %else
1426 APInt ConditionVal(1, isTrueDest ? 1 : 0);
1427 Result = constantFoldUser(Usr, Condition, ConditionVal, DL);
1428 } else {
1429 // If one of Val's operand has an inferred value, we may be able to
1430 // infer the value of Val.
1431 // eg.
1432 // ; %Val is 94 on the edge to %then.
1433 // %Val = add i8 %Op, 1
1434 // %Condition = icmp eq i8 %Op, 93
1435 // br i1 %Condition, label %then, label %else
1436 for (unsigned i = 0; i < Usr->getNumOperands(); ++i) {
1437 Value *Op = Usr->getOperand(i);
1438 ValueLatticeElement OpLatticeVal =
1439 getValueFromCondition(Op, Condition, isTrueDest);
1440 if (Optional<APInt> OpConst = OpLatticeVal.asConstantInteger()) {
1441 Result = constantFoldUser(Usr, Op, OpConst.getValue(), DL);
1442 break;
1443 }
1444 }
1445 }
1446 }
1447 }
1448 if (!Result.isOverdefined())
1449 return true;
1450 }
1451 }
1452
1453 // If the edge was formed by a switch on the value, then we may know exactly
1454 // what it is.
1455 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
1456 Value *Condition = SI->getCondition();
1457 if (!isa<IntegerType>(Val->getType()))
1458 return false;
1459 bool ValUsesConditionAndMayBeFoldable = false;
1460 if (Condition != Val) {
1461 // Check if Val has Condition as an operand.
1462 if (User *Usr = dyn_cast<User>(Val))
1463 ValUsesConditionAndMayBeFoldable = isOperationFoldable(Usr) &&
1464 usesOperand(Usr, Condition);
1465 if (!ValUsesConditionAndMayBeFoldable)
1466 return false;
1467 }
1468 assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&(((Condition == Val || ValUsesConditionAndMayBeFoldable) &&
"Condition != Val nor Val doesn't use Condition") ? static_cast
<void> (0) : __assert_fail ("(Condition == Val || ValUsesConditionAndMayBeFoldable) && \"Condition != Val nor Val doesn't use Condition\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1469, __PRETTY_FUNCTION__))
1469 "Condition != Val nor Val doesn't use Condition")(((Condition == Val || ValUsesConditionAndMayBeFoldable) &&
"Condition != Val nor Val doesn't use Condition") ? static_cast
<void> (0) : __assert_fail ("(Condition == Val || ValUsesConditionAndMayBeFoldable) && \"Condition != Val nor Val doesn't use Condition\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1469, __PRETTY_FUNCTION__))
;
1470
1471 bool DefaultCase = SI->getDefaultDest() == BBTo;
1472 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1473 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1474
1475 for (auto Case : SI->cases()) {
1476 APInt CaseValue = Case.getCaseValue()->getValue();
1477 ConstantRange EdgeVal(CaseValue);
1478 if (ValUsesConditionAndMayBeFoldable) {
1479 User *Usr = cast<User>(Val);
1480 const DataLayout &DL = BBTo->getModule()->getDataLayout();
1481 ValueLatticeElement EdgeLatticeVal =
1482 constantFoldUser(Usr, Condition, CaseValue, DL);
1483 if (EdgeLatticeVal.isOverdefined())
1484 return false;
1485 EdgeVal = EdgeLatticeVal.getConstantRange();
1486 }
1487 if (DefaultCase) {
1488 // It is possible that the default destination is the destination of
1489 // some cases. We cannot perform difference for those cases.
1490 // We know Condition != CaseValue in BBTo. In some cases we can use
1491 // this to infer Val == f(Condition) is != f(CaseValue). For now, we
1492 // only do this when f is identity (i.e. Val == Condition), but we
1493 // should be able to do this for any injective f.
1494 if (Case.getCaseSuccessor() != BBTo && Condition == Val)
1495 EdgesVals = EdgesVals.difference(EdgeVal);
1496 } else if (Case.getCaseSuccessor() == BBTo)
1497 EdgesVals = EdgesVals.unionWith(EdgeVal);
1498 }
1499 Result = ValueLatticeElement::getRange(std::move(EdgesVals));
1500 return true;
1501 }
1502 return false;
1503}
1504
1505/// Compute the value of Val on the edge BBFrom -> BBTo or the value at
1506/// the basic block if the edge does not constrain Val.
1507bool LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
1508 BasicBlock *BBTo,
1509 ValueLatticeElement &Result,
1510 Instruction *CxtI) {
1511 // If already a constant, there is nothing to compute.
1512 if (Constant *VC
7.1
'VC' is null
7.1
'VC' is null
7.1
'VC' is null
= dyn_cast<Constant>(Val)) {
7
Assuming 'Val' is not a 'Constant'
8
Taking false branch
1513 Result = ValueLatticeElement::get(VC);
1514 return true;
1515 }
1516
1517 ValueLatticeElement LocalResult;
1518 if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
9
Passing value via 3rd parameter 'BBTo'
10
Calling 'getEdgeValueLocal'
1519 // If we couldn't constrain the value on the edge, LocalResult doesn't
1520 // provide any information.
1521 LocalResult = ValueLatticeElement::getOverdefined();
1522
1523 if (hasSingleValue(LocalResult)) {
1524 // Can't get any more precise here
1525 Result = LocalResult;
1526 return true;
1527 }
1528
1529 if (!hasBlockValue(Val, BBFrom)) {
1530 if (pushBlockValue(std::make_pair(BBFrom, Val)))
1531 return false;
1532 // No new information.
1533 Result = LocalResult;
1534 return true;
1535 }
1536
1537 // Try to intersect ranges of the BB and the constraint on the edge.
1538 ValueLatticeElement InBlock = getBlockValue(Val, BBFrom);
1539 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock,
1540 BBFrom->getTerminator());
1541 // We can use the context instruction (generically the ultimate instruction
1542 // the calling pass is trying to simplify) here, even though the result of
1543 // this function is generally cached when called from the solve* functions
1544 // (and that cached result might be used with queries using a different
1545 // context instruction), because when this function is called from the solve*
1546 // functions, the context instruction is not provided. When called from
1547 // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
1548 // but then the result is not cached.
1549 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
1550
1551 Result = intersect(LocalResult, InBlock);
1552 return true;
1553}
1554
1555ValueLatticeElement LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
1556 Instruction *CxtI) {
1557 LLVM_DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting block end value "
<< *V << " at '" << BB->getName() <<
"'\n"; } } while (false)
1558 << BB->getName() << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting block end value "
<< *V << " at '" << BB->getName() <<
"'\n"; } } while (false)
;
1559
1560 assert(BlockValueStack.empty() && BlockValueSet.empty())((BlockValueStack.empty() && BlockValueSet.empty()) ?
static_cast<void> (0) : __assert_fail ("BlockValueStack.empty() && BlockValueSet.empty()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1560, __PRETTY_FUNCTION__))
;
1561 if (!hasBlockValue(V, BB)) {
1562 pushBlockValue(std::make_pair(BB, V));
1563 solve();
1564 }
1565 ValueLatticeElement Result = getBlockValue(V, BB);
1566 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1567
1568 LLVM_DEBUG(dbgs() << " Result = " << Result << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " Result = " <<
Result << "\n"; } } while (false)
;
1569 return Result;
1570}
1571
1572ValueLatticeElement LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
1573 LLVM_DEBUG(dbgs() << "LVI Getting value " << *V << " at '" << CxtI->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting value " <<
*V << " at '" << CxtI->getName() << "'\n"
; } } while (false)
1574 << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting value " <<
*V << " at '" << CxtI->getName() << "'\n"
; } } while (false)
;
1575
1576 if (auto *C = dyn_cast<Constant>(V))
1577 return ValueLatticeElement::get(C);
1578
1579 ValueLatticeElement Result = ValueLatticeElement::getOverdefined();
1580 if (auto *I = dyn_cast<Instruction>(V))
1581 Result = getFromRangeMetadata(I);
1582 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1583
1584 LLVM_DEBUG(dbgs() << " Result = " << Result << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " Result = " <<
Result << "\n"; } } while (false)
;
1585 return Result;
1586}
1587
1588ValueLatticeElement LazyValueInfoImpl::
1589getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1590 Instruction *CxtI) {
1591 LLVM_DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting edge value "
<< *V << " from '" << FromBB->getName()
<< "' to '" << ToBB->getName() << "'\n"
; } } while (false)
3
Assuming 'DebugFlag' is false
4
Loop condition is false. Exiting loop
1592 << FromBB->getName() << "' to '" << ToBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting edge value "
<< *V << " from '" << FromBB->getName()
<< "' to '" << ToBB->getName() << "'\n"
; } } while (false)
1593 << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting edge value "
<< *V << " from '" << FromBB->getName()
<< "' to '" << ToBB->getName() << "'\n"
; } } while (false)
;
1594
1595 ValueLatticeElement Result;
1596 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
5
Passing value via 3rd parameter 'BBTo'
6
Calling 'LazyValueInfoImpl::getEdgeValue'
1597 solve();
1598 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
1599 (void)WasFastQuery;
1600 assert(WasFastQuery && "More work to do after problem solved?")((WasFastQuery && "More work to do after problem solved?"
) ? static_cast<void> (0) : __assert_fail ("WasFastQuery && \"More work to do after problem solved?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1600, __PRETTY_FUNCTION__))
;
1601 }
1602
1603 LLVM_DEBUG(dbgs() << " Result = " << Result << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " Result = " <<
Result << "\n"; } } while (false)
;
1604 return Result;
1605}
1606
1607void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1608 BasicBlock *NewSucc) {
1609 TheCache.threadEdgeImpl(OldSucc, NewSucc);
1610}
1611
1612//===----------------------------------------------------------------------===//
1613// LazyValueInfo Impl
1614//===----------------------------------------------------------------------===//
1615
1616/// This lazily constructs the LazyValueInfoImpl.
1617static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC,
1618 const DataLayout *DL,
1619 DominatorTree *DT = nullptr) {
1620 if (!PImpl) {
1621 assert(DL && "getCache() called with a null DataLayout")((DL && "getCache() called with a null DataLayout") ?
static_cast<void> (0) : __assert_fail ("DL && \"getCache() called with a null DataLayout\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1621, __PRETTY_FUNCTION__))
;
1622 PImpl = new LazyValueInfoImpl(AC, *DL, DT);
1623 }
1624 return *static_cast<LazyValueInfoImpl*>(PImpl);
1625}
1626
1627bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
1628 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1629 const DataLayout &DL = F.getParent()->getDataLayout();
1630
1631 DominatorTreeWrapperPass *DTWP =
1632 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1633 Info.DT = DTWP ? &DTWP->getDomTree() : nullptr;
1634 Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1635
1636 if (Info.PImpl)
1637 getImpl(Info.PImpl, Info.AC, &DL, Info.DT).clear();
1638
1639 // Fully lazy.
1640 return false;
1641}
1642
1643void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1644 AU.setPreservesAll();
1645 AU.addRequired<AssumptionCacheTracker>();
1646 AU.addRequired<TargetLibraryInfoWrapperPass>();
1647}
1648
1649LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1650
1651LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1652
1653void LazyValueInfo::releaseMemory() {
1654 // If the cache was allocated, free it.
1655 if (PImpl) {
1656 delete &getImpl(PImpl, AC, nullptr);
1657 PImpl = nullptr;
1658 }
1659}
1660
1661bool LazyValueInfo::invalidate(Function &F, const PreservedAnalyses &PA,
1662 FunctionAnalysisManager::Invalidator &Inv) {
1663 // We need to invalidate if we have either failed to preserve this analyses
1664 // result directly or if any of its dependencies have been invalidated.
1665 auto PAC = PA.getChecker<LazyValueAnalysis>();
1666 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
1667 (DT && Inv.invalidate<DominatorTreeAnalysis>(F, PA)))
1668 return true;
1669
1670 return false;
1671}
1672
1673void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1674
1675LazyValueInfo LazyValueAnalysis::run(Function &F,
1676 FunctionAnalysisManager &FAM) {
1677 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1678 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1679 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
1680
1681 return LazyValueInfo(&AC, &F.getParent()->getDataLayout(), &TLI, DT);
1682}
1683
1684/// Returns true if we can statically tell that this value will never be a
1685/// "useful" constant. In practice, this means we've got something like an
1686/// alloca or a malloc call for which a comparison against a constant can
1687/// only be guarding dead code. Note that we are potentially giving up some
1688/// precision in dead code (a constant result) in favour of avoiding a
1689/// expensive search for a easily answered common query.
1690static bool isKnownNonConstant(Value *V) {
1691 V = V->stripPointerCasts();
1692 // The return val of alloc cannot be a Constant.
1693 if (isa<AllocaInst>(V))
1694 return true;
1695 return false;
1696}
1697
1698Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1699 Instruction *CxtI) {
1700 // Bail out early if V is known not to be a Constant.
1701 if (isKnownNonConstant(V))
1702 return nullptr;
1703
1704 const DataLayout &DL = BB->getModule()->getDataLayout();
1705 ValueLatticeElement Result =
1706 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1707
1708 if (Result.isConstant())
1709 return Result.getConstant();
1710 if (Result.isConstantRange()) {
1711 const ConstantRange &CR = Result.getConstantRange();
1712 if (const APInt *SingleVal = CR.getSingleElement())
1713 return ConstantInt::get(V->getContext(), *SingleVal);
1714 }
1715 return nullptr;
1716}
1717
1718ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB,
1719 Instruction *CxtI) {
1720 assert(V->getType()->isIntegerTy())((V->getType()->isIntegerTy()) ? static_cast<void>
(0) : __assert_fail ("V->getType()->isIntegerTy()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1720, __PRETTY_FUNCTION__))
;
1721 unsigned Width = V->getType()->getIntegerBitWidth();
1722 const DataLayout &DL = BB->getModule()->getDataLayout();
1723 ValueLatticeElement Result =
1724 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1725 if (Result.isUndefined())
1726 return ConstantRange::getEmpty(Width);
1727 if (Result.isConstantRange())
1728 return Result.getConstantRange();
1729 // We represent ConstantInt constants as constant ranges but other kinds
1730 // of integer constants, i.e. ConstantExpr will be tagged as constants
1731 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&((!(Result.isConstant() && isa<ConstantInt>(Result
.getConstant())) && "ConstantInt value must be represented as constantrange"
) ? static_cast<void> (0) : __assert_fail ("!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) && \"ConstantInt value must be represented as constantrange\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1732, __PRETTY_FUNCTION__))
1732 "ConstantInt value must be represented as constantrange")((!(Result.isConstant() && isa<ConstantInt>(Result
.getConstant())) && "ConstantInt value must be represented as constantrange"
) ? static_cast<void> (0) : __assert_fail ("!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) && \"ConstantInt value must be represented as constantrange\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1732, __PRETTY_FUNCTION__))
;
1733 return ConstantRange::getFull(Width);
1734}
1735
1736/// Determine whether the specified value is known to be a
1737/// constant on the specified edge. Return null if not.
1738Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1739 BasicBlock *ToBB,
1740 Instruction *CxtI) {
1741 const DataLayout &DL = FromBB->getModule()->getDataLayout();
1742 ValueLatticeElement Result =
1743 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1744
1745 if (Result.isConstant())
1746 return Result.getConstant();
1747 if (Result.isConstantRange()) {
1748 const ConstantRange &CR = Result.getConstantRange();
1749 if (const APInt *SingleVal = CR.getSingleElement())
1750 return ConstantInt::get(V->getContext(), *SingleVal);
1751 }
1752 return nullptr;
1753}
1754
1755ConstantRange LazyValueInfo::getConstantRangeOnEdge(Value *V,
1756 BasicBlock *FromBB,
1757 BasicBlock *ToBB,
1758 Instruction *CxtI) {
1759 unsigned Width = V->getType()->getIntegerBitWidth();
1760 const DataLayout &DL = FromBB->getModule()->getDataLayout();
1761 ValueLatticeElement Result =
1762 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1
Passing value via 3rd parameter 'ToBB'
2
Calling 'LazyValueInfoImpl::getValueOnEdge'
1763
1764 if (Result.isUndefined())
1765 return ConstantRange::getEmpty(Width);
1766 if (Result.isConstantRange())
1767 return Result.getConstantRange();
1768 // We represent ConstantInt constants as constant ranges but other kinds
1769 // of integer constants, i.e. ConstantExpr will be tagged as constants
1770 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&((!(Result.isConstant() && isa<ConstantInt>(Result
.getConstant())) && "ConstantInt value must be represented as constantrange"
) ? static_cast<void> (0) : __assert_fail ("!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) && \"ConstantInt value must be represented as constantrange\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1771, __PRETTY_FUNCTION__))
1771 "ConstantInt value must be represented as constantrange")((!(Result.isConstant() && isa<ConstantInt>(Result
.getConstant())) && "ConstantInt value must be represented as constantrange"
) ? static_cast<void> (0) : __assert_fail ("!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) && \"ConstantInt value must be represented as constantrange\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/LazyValueInfo.cpp"
, 1771, __PRETTY_FUNCTION__))
;
1772 return ConstantRange::getFull(Width);
1773}
1774
1775static LazyValueInfo::Tristate
1776getPredicateResult(unsigned Pred, Constant *C, const ValueLatticeElement &Val,
1777 const DataLayout &DL, TargetLibraryInfo *TLI) {
1778 // If we know the value is a constant, evaluate the conditional.
1779 Constant *Res = nullptr;
1780 if (Val.isConstant()) {
1781 Res = ConstantFoldCompareInstOperands(Pred, Val.getConstant(), C, DL, TLI);
1782 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1783 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1784 return LazyValueInfo::Unknown;
1785 }
1786
1787 if (Val.isConstantRange()) {
1788 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1789 if (!CI) return LazyValueInfo::Unknown;
1790
1791 const ConstantRange &CR = Val.getConstantRange();
1792 if (Pred == ICmpInst::ICMP_EQ) {
1793 if (!CR.contains(CI->getValue()))
1794 return LazyValueInfo::False;
1795
1796 if (CR.isSingleElement())
1797 return LazyValueInfo::True;
1798 } else if (Pred == ICmpInst::ICMP_NE) {
1799 if (!CR.contains(CI->getValue()))
1800 return LazyValueInfo::True;
1801
1802 if (CR.isSingleElement())
1803 return LazyValueInfo::False;
1804 } else {
1805 // Handle more complex predicates.
1806 ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
1807 (ICmpInst::Predicate)Pred, CI->getValue());
1808 if (TrueValues.contains(CR))
1809 return LazyValueInfo::True;
1810 if (TrueValues.inverse().contains(CR))
1811 return LazyValueInfo::False;
1812 }
1813 return LazyValueInfo::Unknown;
1814 }
1815
1816 if (Val.isNotConstant()) {
1817 // If this is an equality comparison, we can try to fold it knowing that
1818 // "V != C1".
1819 if (Pred == ICmpInst::ICMP_EQ) {
1820 // !C1 == C -> false iff C1 == C.
1821 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1822 Val.getNotConstant(), C, DL,
1823 TLI);
1824 if (Res->isNullValue())
1825 return LazyValueInfo::False;
1826 } else if (Pred == ICmpInst::ICMP_NE) {
1827 // !C1 != C -> true iff C1 == C.
1828 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1829 Val.getNotConstant(), C, DL,
1830 TLI);
1831 if (Res->isNullValue())
1832 return LazyValueInfo::True;
1833 }
1834 return LazyValueInfo::Unknown;
1835 }
1836
1837 return LazyValueInfo::Unknown;
1838}
1839
1840/// Determine whether the specified value comparison with a constant is known to
1841/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
1842LazyValueInfo::Tristate
1843LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1844 BasicBlock *FromBB, BasicBlock *ToBB,
1845 Instruction *CxtI) {
1846 const DataLayout &DL = FromBB->getModule()->getDataLayout();
1847 ValueLatticeElement Result =
1848 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1849
1850 return getPredicateResult(Pred, C, Result, DL, TLI);
1851}
1852
1853LazyValueInfo::Tristate
1854LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1855 Instruction *CxtI) {
1856 // Is or is not NonNull are common predicates being queried. If
1857 // isKnownNonZero can tell us the result of the predicate, we can
1858 // return it quickly. But this is only a fastpath, and falling
1859 // through would still be correct.
1860 const DataLayout &DL = CxtI->getModule()->getDataLayout();
1861 if (V->getType()->isPointerTy() && C->isNullValue() &&
1862 isKnownNonZero(V->stripPointerCastsSameRepresentation(), DL)) {
1863 if (Pred == ICmpInst::ICMP_EQ)
1864 return LazyValueInfo::False;
1865 else if (Pred == ICmpInst::ICMP_NE)
1866 return LazyValueInfo::True;
1867 }
1868 ValueLatticeElement Result = getImpl(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
1869 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1870 if (Ret != Unknown)
1871 return Ret;
1872
1873 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1874 // LVI as a whole tries to compute a lattice value which is conservatively
1875 // correct at a given location. In this case, we have a predicate which we
1876 // weren't able to prove about the merged result, and we're pushing that
1877 // predicate back along each incoming edge to see if we can prove it
1878 // separately for each input. As a motivating example, consider:
1879 // bb1:
1880 // %v1 = ... ; constantrange<1, 5>
1881 // br label %merge
1882 // bb2:
1883 // %v2 = ... ; constantrange<10, 20>
1884 // br label %merge
1885 // merge:
1886 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1887 // %pred = icmp eq i32 %phi, 8
1888 // We can't tell from the lattice value for '%phi' that '%pred' is false
1889 // along each path, but by checking the predicate over each input separately,
1890 // we can.
1891 // We limit the search to one step backwards from the current BB and value.
1892 // We could consider extending this to search further backwards through the
1893 // CFG and/or value graph, but there are non-obvious compile time vs quality
1894 // tradeoffs.
1895 if (CxtI) {
1896 BasicBlock *BB = CxtI->getParent();
1897
1898 // Function entry or an unreachable block. Bail to avoid confusing
1899 // analysis below.
1900 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1901 if (PI == PE)
1902 return Unknown;
1903
1904 // If V is a PHI node in the same block as the context, we need to ask
1905 // questions about the predicate as applied to the incoming value along
1906 // each edge. This is useful for eliminating cases where the predicate is
1907 // known along all incoming edges.
1908 if (auto *PHI = dyn_cast<PHINode>(V))
1909 if (PHI->getParent() == BB) {
1910 Tristate Baseline = Unknown;
1911 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1912 Value *Incoming = PHI->getIncomingValue(i);
1913 BasicBlock *PredBB = PHI->getIncomingBlock(i);
1914 // Note that PredBB may be BB itself.
1915 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1916 CxtI);
1917
1918 // Keep going as long as we've seen a consistent known result for
1919 // all inputs.
1920 Baseline = (i == 0) ? Result /* First iteration */
1921 : (Baseline == Result ? Baseline : Unknown); /* All others */
1922 if (Baseline == Unknown)
1923 break;
1924 }
1925 if (Baseline != Unknown)
1926 return Baseline;
1927 }
1928
1929 // For a comparison where the V is outside this block, it's possible
1930 // that we've branched on it before. Look to see if the value is known
1931 // on all incoming edges.
1932 if (!isa<Instruction>(V) ||
1933 cast<Instruction>(V)->getParent() != BB) {
1934 // For predecessor edge, determine if the comparison is true or false
1935 // on that edge. If they're all true or all false, we can conclude
1936 // the value of the comparison in this block.
1937 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1938 if (Baseline != Unknown) {
1939 // Check that all remaining incoming values match the first one.
1940 while (++PI != PE) {
1941 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1942 if (Ret != Baseline) break;
1943 }
1944 // If we terminated early, then one of the values didn't match.
1945 if (PI == PE) {
1946 return Baseline;
1947 }
1948 }
1949 }
1950 }
1951 return Unknown;
1952}
1953
1954void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1955 BasicBlock *NewSucc) {
1956 if (PImpl) {
1957 const DataLayout &DL = PredBB->getModule()->getDataLayout();
1958 getImpl(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1959 }
1960}
1961
1962void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1963 if (PImpl) {
1964 const DataLayout &DL = BB->getModule()->getDataLayout();
1965 getImpl(PImpl, AC, &DL, DT).eraseBlock(BB);
1966 }
1967}
1968
1969
1970void LazyValueInfo::printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
1971 if (PImpl) {
1972 getImpl(PImpl, AC, DL, DT).printLVI(F, DTree, OS);
1973 }
1974}
1975
1976void LazyValueInfo::disableDT() {
1977 if (PImpl)
1978 getImpl(PImpl, AC, DL, DT).disableDT();
1979}
1980
1981void LazyValueInfo::enableDT() {
1982 if (PImpl)
1983 getImpl(PImpl, AC, DL, DT).enableDT();
1984}
1985
1986// Print the LVI for the function arguments at the start of each basic block.
1987void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
1988 const BasicBlock *BB, formatted_raw_ostream &OS) {
1989 // Find if there are latticevalues defined for arguments of the function.
1990 auto *F = BB->getParent();
1991 for (auto &Arg : F->args()) {
1992 ValueLatticeElement Result = LVIImpl->getValueInBlock(
1993 const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
1994 if (Result.isUndefined())
1995 continue;
1996 OS << "; LatticeVal for: '" << Arg << "' is: " << Result << "\n";
1997 }
1998}
1999
2000// This function prints the LVI analysis for the instruction I at the beginning
2001// of various basic blocks. It relies on calculated values that are stored in
2002// the LazyValueInfoCache, and in the absence of cached values, recalculate the
2003// LazyValueInfo for `I`, and print that info.
2004void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
2005 const Instruction *I, formatted_raw_ostream &OS) {
2006
2007 auto *ParentBB = I->getParent();
2008 SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
2009 // We can generate (solve) LVI values only for blocks that are dominated by
2010 // the I's parent. However, to avoid generating LVI for all dominating blocks,
2011 // that contain redundant/uninteresting information, we print LVI for
2012 // blocks that may use this LVI information (such as immediate successor
2013 // blocks, and blocks that contain uses of `I`).
2014 auto printResult = [&](const BasicBlock *BB) {
2015 if (!BlocksContainingLVI.insert(BB).second)
2016 return;
2017 ValueLatticeElement Result = LVIImpl->getValueInBlock(
2018 const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
2019 OS << "; LatticeVal for: '" << *I << "' in BB: '";
2020 BB->printAsOperand(OS, false);
2021 OS << "' is: " << Result << "\n";
2022 };
2023
2024 printResult(ParentBB);
2025 // Print the LVI analysis results for the immediate successor blocks, that
2026 // are dominated by `ParentBB`.
2027 for (auto *BBSucc : successors(ParentBB))
2028 if (DT.dominates(ParentBB, BBSucc))
2029 printResult(BBSucc);
2030
2031 // Print LVI in blocks where `I` is used.
2032 for (auto *U : I->users())
2033 if (auto *UseI = dyn_cast<Instruction>(U))
2034 if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
2035 printResult(UseI->getParent());
2036
2037}
2038
2039namespace {
2040// Printer class for LazyValueInfo results.
2041class LazyValueInfoPrinter : public FunctionPass {
2042public:
2043 static char ID; // Pass identification, replacement for typeid
2044 LazyValueInfoPrinter() : FunctionPass(ID) {
2045 initializeLazyValueInfoPrinterPass(*PassRegistry::getPassRegistry());
2046 }
2047
2048 void getAnalysisUsage(AnalysisUsage &AU) const override {
2049 AU.setPreservesAll();
2050 AU.addRequired<LazyValueInfoWrapperPass>();
2051 AU.addRequired<DominatorTreeWrapperPass>();
2052 }
2053
2054 // Get the mandatory dominator tree analysis and pass this in to the
2055 // LVIPrinter. We cannot rely on the LVI's DT, since it's optional.
2056 bool runOnFunction(Function &F) override {
2057 dbgs() << "LVI for function '" << F.getName() << "':\n";
2058 auto &LVI = getAnalysis<LazyValueInfoWrapperPass>().getLVI();
2059 auto &DTree = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2060 LVI.printLVI(F, DTree, dbgs());
2061 return false;
2062 }
2063};
2064}
2065
2066char LazyValueInfoPrinter::ID = 0;
2067INITIALIZE_PASS_BEGIN(LazyValueInfoPrinter, "print-lazy-value-info",static void *initializeLazyValueInfoPrinterPassOnce(PassRegistry
&Registry) {
2068 "Lazy Value Info Printer Pass", false, false)static void *initializeLazyValueInfoPrinterPassOnce(PassRegistry
&Registry) {
2069INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)initializeLazyValueInfoWrapperPassPass(Registry);
2070INITIALIZE_PASS_END(LazyValueInfoPrinter, "print-lazy-value-info",PassInfo *PI = new PassInfo( "Lazy Value Info Printer Pass", "print-lazy-value-info"
, &LazyValueInfoPrinter::ID, PassInfo::NormalCtor_t(callDefaultCtor
<LazyValueInfoPrinter>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeLazyValueInfoPrinterPassFlag
; void llvm::initializeLazyValueInfoPrinterPass(PassRegistry &
Registry) { llvm::call_once(InitializeLazyValueInfoPrinterPassFlag
, initializeLazyValueInfoPrinterPassOnce, std::ref(Registry))
; }
2071 "Lazy Value Info Printer Pass", false, false)PassInfo *PI = new PassInfo( "Lazy Value Info Printer Pass", "print-lazy-value-info"
, &LazyValueInfoPrinter::ID, PassInfo::NormalCtor_t(callDefaultCtor
<LazyValueInfoPrinter>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeLazyValueInfoPrinterPassFlag
; void llvm::initializeLazyValueInfoPrinterPass(PassRegistry &
Registry) { llvm::call_once(InitializeLazyValueInfoPrinterPassFlag
, initializeLazyValueInfoPrinterPassOnce, std::ref(Registry))
; }

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h

1//===- llvm/Instructions.h - Instruction subclass definitions ---*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file exposes the class definitions of all of the subclasses of the
10// Instruction class. This is meant to be an easy way to get access to all
11// instruction subclasses.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_INSTRUCTIONS_H
16#define LLVM_IR_INSTRUCTIONS_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/None.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/ADT/Twine.h"
24#include "llvm/ADT/iterator.h"
25#include "llvm/ADT/iterator_range.h"
26#include "llvm/IR/Attributes.h"
27#include "llvm/IR/BasicBlock.h"
28#include "llvm/IR/CallingConv.h"
29#include "llvm/IR/Constant.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/Instruction.h"
34#include "llvm/IR/OperandTraits.h"
35#include "llvm/IR/Type.h"
36#include "llvm/IR/Use.h"
37#include "llvm/IR/User.h"
38#include "llvm/IR/Value.h"
39#include "llvm/Support/AtomicOrdering.h"
40#include "llvm/Support/Casting.h"
41#include "llvm/Support/ErrorHandling.h"
42#include <cassert>
43#include <cstddef>
44#include <cstdint>
45#include <iterator>
46
47namespace llvm {
48
49class APInt;
50class ConstantInt;
51class DataLayout;
52class LLVMContext;
53
54//===----------------------------------------------------------------------===//
55// AllocaInst Class
56//===----------------------------------------------------------------------===//
57
58/// an instruction to allocate memory on the stack
59class AllocaInst : public UnaryInstruction {
60 Type *AllocatedType;
61
62protected:
63 // Note: Instruction needs to be a friend here to call cloneImpl.
64 friend class Instruction;
65
66 AllocaInst *cloneImpl() const;
67
68public:
69 explicit AllocaInst(Type *Ty, unsigned AddrSpace,
70 Value *ArraySize = nullptr,
71 const Twine &Name = "",
72 Instruction *InsertBefore = nullptr);
73 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
74 const Twine &Name, BasicBlock *InsertAtEnd);
75
76 AllocaInst(Type *Ty, unsigned AddrSpace,
77 const Twine &Name, Instruction *InsertBefore = nullptr);
78 AllocaInst(Type *Ty, unsigned AddrSpace,
79 const Twine &Name, BasicBlock *InsertAtEnd);
80
81 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, MaybeAlign Align,
82 const Twine &Name = "", Instruction *InsertBefore = nullptr);
83 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, MaybeAlign Align,
84 const Twine &Name, BasicBlock *InsertAtEnd);
85
86 /// Return true if there is an allocation size parameter to the allocation
87 /// instruction that is not 1.
88 bool isArrayAllocation() const;
89
90 /// Get the number of elements allocated. For a simple allocation of a single
91 /// element, this will return a constant 1 value.
92 const Value *getArraySize() const { return getOperand(0); }
93 Value *getArraySize() { return getOperand(0); }
94
95 /// Overload to return most specific pointer type.
96 PointerType *getType() const {
97 return cast<PointerType>(Instruction::getType());
98 }
99
100 /// Get allocation size in bits. Returns None if size can't be determined,
101 /// e.g. in case of a VLA.
102 Optional<uint64_t> getAllocationSizeInBits(const DataLayout &DL) const;
103
104 /// Return the type that is being allocated by the instruction.
105 Type *getAllocatedType() const { return AllocatedType; }
106 /// for use only in special circumstances that need to generically
107 /// transform a whole instruction (eg: IR linking and vectorization).
108 void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
109
110 /// Return the alignment of the memory that is being allocated by the
111 /// instruction.
112 unsigned getAlignment() const {
113 if (const auto MA = decodeMaybeAlign(getSubclassDataFromInstruction() & 31))
114 return MA->value();
115 return 0;
116 }
117 void setAlignment(MaybeAlign Align);
118
119 /// Return true if this alloca is in the entry block of the function and is a
120 /// constant size. If so, the code generator will fold it into the
121 /// prolog/epilog code, so it is basically free.
122 bool isStaticAlloca() const;
123
124 /// Return true if this alloca is used as an inalloca argument to a call. Such
125 /// allocas are never considered static even if they are in the entry block.
126 bool isUsedWithInAlloca() const {
127 return getSubclassDataFromInstruction() & 32;
128 }
129
130 /// Specify whether this alloca is used to represent the arguments to a call.
131 void setUsedWithInAlloca(bool V) {
132 setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
133 (V ? 32 : 0));
134 }
135
136 /// Return true if this alloca is used as a swifterror argument to a call.
137 bool isSwiftError() const {
138 return getSubclassDataFromInstruction() & 64;
139 }
140
141 /// Specify whether this alloca is used to represent a swifterror.
142 void setSwiftError(bool V) {
143 setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) |
144 (V ? 64 : 0));
145 }
146
147 // Methods for support type inquiry through isa, cast, and dyn_cast:
148 static bool classof(const Instruction *I) {
149 return (I->getOpcode() == Instruction::Alloca);
150 }
151 static bool classof(const Value *V) {
152 return isa<Instruction>(V) && classof(cast<Instruction>(V));
153 }
154
155private:
156 // Shadow Instruction::setInstructionSubclassData with a private forwarding
157 // method so that subclasses cannot accidentally use it.
158 void setInstructionSubclassData(unsigned short D) {
159 Instruction::setInstructionSubclassData(D);
160 }
161};
162
163//===----------------------------------------------------------------------===//
164// LoadInst Class
165//===----------------------------------------------------------------------===//
166
167/// An instruction for reading from memory. This uses the SubclassData field in
168/// Value to store whether or not the load is volatile.
169class LoadInst : public UnaryInstruction {
170 void AssertOK();
171
172protected:
173 // Note: Instruction needs to be a friend here to call cloneImpl.
174 friend class Instruction;
175
176 LoadInst *cloneImpl() const;
177
178public:
179 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr = "",
180 Instruction *InsertBefore = nullptr);
181 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
182 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
183 Instruction *InsertBefore = nullptr);
184 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
185 BasicBlock *InsertAtEnd);
186 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
187 MaybeAlign Align, Instruction *InsertBefore = nullptr);
188 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
189 MaybeAlign Align, BasicBlock *InsertAtEnd);
190 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
191 MaybeAlign Align, AtomicOrdering Order,
192 SyncScope::ID SSID = SyncScope::System,
193 Instruction *InsertBefore = nullptr);
194 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
195 MaybeAlign Align, AtomicOrdering Order, SyncScope::ID SSID,
196 BasicBlock *InsertAtEnd);
197
198 // Deprecated [opaque pointer types]
199 explicit LoadInst(Value *Ptr, const Twine &NameStr = "",
200 Instruction *InsertBefore = nullptr)
201 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
202 InsertBefore) {}
203 LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd)
204 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
205 InsertAtEnd) {}
206 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
207 Instruction *InsertBefore = nullptr)
208 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
209 isVolatile, InsertBefore) {}
210 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
211 BasicBlock *InsertAtEnd)
212 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
213 isVolatile, InsertAtEnd) {}
214 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
215 Instruction *InsertBefore = nullptr)
216 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
217 isVolatile, Align, InsertBefore) {}
218 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
219 BasicBlock *InsertAtEnd)
220 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
221 isVolatile, Align, InsertAtEnd) {}
222 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
223 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
224 Instruction *InsertBefore = nullptr)
225 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
226 isVolatile, Align, Order, SSID, InsertBefore) {}
227 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
228 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd)
229 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
230 isVolatile, Align, Order, SSID, InsertAtEnd) {}
231
232 /// Return true if this is a load from a volatile memory location.
233 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
234
235 /// Specify whether this is a volatile load or not.
236 void setVolatile(bool V) {
237 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
238 (V ? 1 : 0));
239 }
240
241 /// Return the alignment of the access that is being performed.
242 /// FIXME: Remove this function once transition to Align is over.
243 /// Use getAlign() instead.
244 unsigned getAlignment() const {
245 if (const auto MA = getAlign())
246 return MA->value();
247 return 0;
248 }
249
250 /// Return the alignment of the access that is being performed.
251 MaybeAlign getAlign() const {
252 return decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31);
253 }
254
255 void setAlignment(MaybeAlign Alignment);
256
257 /// Returns the ordering constraint of this load instruction.
258 AtomicOrdering getOrdering() const {
259 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
260 }
261
262 /// Sets the ordering constraint of this load instruction. May not be Release
263 /// or AcquireRelease.
264 void setOrdering(AtomicOrdering Ordering) {
265 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
266 ((unsigned)Ordering << 7));
267 }
268
269 /// Returns the synchronization scope ID of this load instruction.
270 SyncScope::ID getSyncScopeID() const {
271 return SSID;
272 }
273
274 /// Sets the synchronization scope ID of this load instruction.
275 void setSyncScopeID(SyncScope::ID SSID) {
276 this->SSID = SSID;
277 }
278
279 /// Sets the ordering constraint and the synchronization scope ID of this load
280 /// instruction.
281 void setAtomic(AtomicOrdering Ordering,
282 SyncScope::ID SSID = SyncScope::System) {
283 setOrdering(Ordering);
284 setSyncScopeID(SSID);
285 }
286
287 bool isSimple() const { return !isAtomic() && !isVolatile(); }
288
289 bool isUnordered() const {
290 return (getOrdering() == AtomicOrdering::NotAtomic ||
291 getOrdering() == AtomicOrdering::Unordered) &&
292 !isVolatile();
293 }
294
295 Value *getPointerOperand() { return getOperand(0); }
296 const Value *getPointerOperand() const { return getOperand(0); }
297 static unsigned getPointerOperandIndex() { return 0U; }
298 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
299
300 /// Returns the address space of the pointer operand.
301 unsigned getPointerAddressSpace() const {
302 return getPointerOperandType()->getPointerAddressSpace();
303 }
304
305 // Methods for support type inquiry through isa, cast, and dyn_cast:
306 static bool classof(const Instruction *I) {
307 return I->getOpcode() == Instruction::Load;
308 }
309 static bool classof(const Value *V) {
310 return isa<Instruction>(V) && classof(cast<Instruction>(V));
311 }
312
313private:
314 // Shadow Instruction::setInstructionSubclassData with a private forwarding
315 // method so that subclasses cannot accidentally use it.
316 void setInstructionSubclassData(unsigned short D) {
317 Instruction::setInstructionSubclassData(D);
318 }
319
320 /// The synchronization scope ID of this load instruction. Not quite enough
321 /// room in SubClassData for everything, so synchronization scope ID gets its
322 /// own field.
323 SyncScope::ID SSID;
324};
325
326//===----------------------------------------------------------------------===//
327// StoreInst Class
328//===----------------------------------------------------------------------===//
329
330/// An instruction for storing to memory.
331class StoreInst : public Instruction {
332 void AssertOK();
333
334protected:
335 // Note: Instruction needs to be a friend here to call cloneImpl.
336 friend class Instruction;
337
338 StoreInst *cloneImpl() const;
339
340public:
341 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
342 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
343 StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
344 Instruction *InsertBefore = nullptr);
345 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
346 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
347 Instruction *InsertBefore = nullptr);
348 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
349 BasicBlock *InsertAtEnd);
350 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
351 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
352 Instruction *InsertBefore = nullptr);
353 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
354 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd);
355
356 // allocate space for exactly two operands
357 void *operator new(size_t s) {
358 return User::operator new(s, 2);
359 }
360
361 /// Return true if this is a store to a volatile memory location.
362 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
363
364 /// Specify whether this is a volatile store or not.
365 void setVolatile(bool V) {
366 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
367 (V ? 1 : 0));
368 }
369
370 /// Transparently provide more efficient getOperand methods.
371 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
;
372
373 /// Return the alignment of the access that is being performed
374 /// FIXME: Remove this function once transition to Align is over.
375 /// Use getAlign() instead.
376 unsigned getAlignment() const {
377 if (const auto MA = getAlign())
378 return MA->value();
379 return 0;
380 }
381
382 MaybeAlign getAlign() const {
383 return decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31);
384 }
385
386 void setAlignment(MaybeAlign Alignment);
387
388 /// Returns the ordering constraint of this store instruction.
389 AtomicOrdering getOrdering() const {
390 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
391 }
392
393 /// Sets the ordering constraint of this store instruction. May not be
394 /// Acquire or AcquireRelease.
395 void setOrdering(AtomicOrdering Ordering) {
396 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
397 ((unsigned)Ordering << 7));
398 }
399
400 /// Returns the synchronization scope ID of this store instruction.
401 SyncScope::ID getSyncScopeID() const {
402 return SSID;
403 }
404
405 /// Sets the synchronization scope ID of this store instruction.
406 void setSyncScopeID(SyncScope::ID SSID) {
407 this->SSID = SSID;
408 }
409
410 /// Sets the ordering constraint and the synchronization scope ID of this
411 /// store instruction.
412 void setAtomic(AtomicOrdering Ordering,
413 SyncScope::ID SSID = SyncScope::System) {
414 setOrdering(Ordering);
415 setSyncScopeID(SSID);
416 }
417
418 bool isSimple() const { return !isAtomic() && !isVolatile(); }
419
420 bool isUnordered() const {
421 return (getOrdering() == AtomicOrdering::NotAtomic ||
422 getOrdering() == AtomicOrdering::Unordered) &&
423 !isVolatile();
424 }
425
426 Value *getValueOperand() { return getOperand(0); }
427 const Value *getValueOperand() const { return getOperand(0); }
428
429 Value *getPointerOperand() { return getOperand(1); }
430 const Value *getPointerOperand() const { return getOperand(1); }
431 static unsigned getPointerOperandIndex() { return 1U; }
432 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
433
434 /// Returns the address space of the pointer operand.
435 unsigned getPointerAddressSpace() const {
436 return getPointerOperandType()->getPointerAddressSpace();
437 }
438
439 // Methods for support type inquiry through isa, cast, and dyn_cast:
440 static bool classof(const Instruction *I) {
441 return I->getOpcode() == Instruction::Store;
442 }
443 static bool classof(const Value *V) {
444 return isa<Instruction>(V) && classof(cast<Instruction>(V));
445 }
446
447private:
448 // Shadow Instruction::setInstructionSubclassData with a private forwarding
449 // method so that subclasses cannot accidentally use it.
450 void setInstructionSubclassData(unsigned short D) {
451 Instruction::setInstructionSubclassData(D);
452 }
453
454 /// The synchronization scope ID of this store instruction. Not quite enough
455 /// room in SubClassData for everything, so synchronization scope ID gets its
456 /// own field.
457 SyncScope::ID SSID;
458};
459
460template <>
461struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
462};
463
464DEFINE_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 { ((i_nocapture < OperandTraits
<StoreInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 464, __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) { ((i_nocapture <
OperandTraits<StoreInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 464, __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
); }
465
466//===----------------------------------------------------------------------===//
467// FenceInst Class
468//===----------------------------------------------------------------------===//
469
470/// An instruction for ordering other memory operations.
471class FenceInst : public Instruction {
472 void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
473
474protected:
475 // Note: Instruction needs to be a friend here to call cloneImpl.
476 friend class Instruction;
477
478 FenceInst *cloneImpl() const;
479
480public:
481 // Ordering may only be Acquire, Release, AcquireRelease, or
482 // SequentiallyConsistent.
483 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
484 SyncScope::ID SSID = SyncScope::System,
485 Instruction *InsertBefore = nullptr);
486 FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
487 BasicBlock *InsertAtEnd);
488
489 // allocate space for exactly zero operands
490 void *operator new(size_t s) {
491 return User::operator new(s, 0);
492 }
493
494 /// Returns the ordering constraint of this fence instruction.
495 AtomicOrdering getOrdering() const {
496 return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
497 }
498
499 /// Sets the ordering constraint of this fence instruction. May only be
500 /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
501 void setOrdering(AtomicOrdering Ordering) {
502 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
503 ((unsigned)Ordering << 1));
504 }
505
506 /// Returns the synchronization scope ID of this fence instruction.
507 SyncScope::ID getSyncScopeID() const {
508 return SSID;
509 }
510
511 /// Sets the synchronization scope ID of this fence instruction.
512 void setSyncScopeID(SyncScope::ID SSID) {
513 this->SSID = SSID;
514 }
515
516 // Methods for support type inquiry through isa, cast, and dyn_cast:
517 static bool classof(const Instruction *I) {
518 return I->getOpcode() == Instruction::Fence;
519 }
520 static bool classof(const Value *V) {
521 return isa<Instruction>(V) && classof(cast<Instruction>(V));
522 }
523
524private:
525 // Shadow Instruction::setInstructionSubclassData with a private forwarding
526 // method so that subclasses cannot accidentally use it.
527 void setInstructionSubclassData(unsigned short D) {
528 Instruction::setInstructionSubclassData(D);
529 }
530
531 /// The synchronization scope ID of this fence instruction. Not quite enough
532 /// room in SubClassData for everything, so synchronization scope ID gets its
533 /// own field.
534 SyncScope::ID SSID;
535};
536
537//===----------------------------------------------------------------------===//
538// AtomicCmpXchgInst Class
539//===----------------------------------------------------------------------===//
540
541/// An instruction that atomically checks whether a
542/// specified value is in a memory location, and, if it is, stores a new value
543/// there. The value returned by this instruction is a pair containing the
544/// original value as first element, and an i1 indicating success (true) or
545/// failure (false) as second element.
546///
547class AtomicCmpXchgInst : public Instruction {
548 void Init(Value *Ptr, Value *Cmp, Value *NewVal,
549 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
550 SyncScope::ID SSID);
551
552protected:
553 // Note: Instruction needs to be a friend here to call cloneImpl.
554 friend class Instruction;
555
556 AtomicCmpXchgInst *cloneImpl() const;
557
558public:
559 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
560 AtomicOrdering SuccessOrdering,
561 AtomicOrdering FailureOrdering,
562 SyncScope::ID SSID, Instruction *InsertBefore = nullptr);
563 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
564 AtomicOrdering SuccessOrdering,
565 AtomicOrdering FailureOrdering,
566 SyncScope::ID SSID, BasicBlock *InsertAtEnd);
567
568 // allocate space for exactly three operands
569 void *operator new(size_t s) {
570 return User::operator new(s, 3);
571 }
572
573 /// Return true if this is a cmpxchg from a volatile memory
574 /// location.
575 ///
576 bool isVolatile() const {
577 return getSubclassDataFromInstruction() & 1;
578 }
579
580 /// Specify whether this is a volatile cmpxchg.
581 ///
582 void setVolatile(bool V) {
583 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
584 (unsigned)V);
585 }
586
587 /// Return true if this cmpxchg may spuriously fail.
588 bool isWeak() const {
589 return getSubclassDataFromInstruction() & 0x100;
590 }
591
592 void setWeak(bool IsWeak) {
593 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
594 (IsWeak << 8));
595 }
596
597 /// Transparently provide more efficient getOperand methods.
598 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
;
599
600 /// Returns the success ordering constraint of this cmpxchg instruction.
601 AtomicOrdering getSuccessOrdering() const {
602 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
603 }
604
605 /// Sets the success ordering constraint of this cmpxchg instruction.
606 void setSuccessOrdering(AtomicOrdering Ordering) {
607 assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 608, __PRETTY_FUNCTION__))
608 "CmpXchg instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 608, __PRETTY_FUNCTION__))
;
609 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
610 ((unsigned)Ordering << 2));
611 }
612
613 /// Returns the failure ordering constraint of this cmpxchg instruction.
614 AtomicOrdering getFailureOrdering() const {
615 return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
616 }
617
618 /// Sets the failure ordering constraint of this cmpxchg instruction.
619 void setFailureOrdering(AtomicOrdering Ordering) {
620 assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 621, __PRETTY_FUNCTION__))
621 "CmpXchg instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 621, __PRETTY_FUNCTION__))
;
622 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
623 ((unsigned)Ordering << 5));
624 }
625
626 /// Returns the synchronization scope ID of this cmpxchg instruction.
627 SyncScope::ID getSyncScopeID() const {
628 return SSID;
629 }
630
631 /// Sets the synchronization scope ID of this cmpxchg instruction.
632 void setSyncScopeID(SyncScope::ID SSID) {
633 this->SSID = SSID;
634 }
635
636 Value *getPointerOperand() { return getOperand(0); }
637 const Value *getPointerOperand() const { return getOperand(0); }
638 static unsigned getPointerOperandIndex() { return 0U; }
639
640 Value *getCompareOperand() { return getOperand(1); }
641 const Value *getCompareOperand() const { return getOperand(1); }
642
643 Value *getNewValOperand() { return getOperand(2); }
644 const Value *getNewValOperand() const { return getOperand(2); }
645
646 /// Returns the address space of the pointer operand.
647 unsigned getPointerAddressSpace() const {
648 return getPointerOperand()->getType()->getPointerAddressSpace();
649 }
650
651 /// Returns the strongest permitted ordering on failure, given the
652 /// desired ordering on success.
653 ///
654 /// If the comparison in a cmpxchg operation fails, there is no atomic store
655 /// so release semantics cannot be provided. So this function drops explicit
656 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
657 /// operation would remain SequentiallyConsistent.
658 static AtomicOrdering
659 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
660 switch (SuccessOrdering) {
661 default:
662 llvm_unreachable("invalid cmpxchg success ordering")::llvm::llvm_unreachable_internal("invalid cmpxchg success ordering"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 662)
;
663 case AtomicOrdering::Release:
664 case AtomicOrdering::Monotonic:
665 return AtomicOrdering::Monotonic;
666 case AtomicOrdering::AcquireRelease:
667 case AtomicOrdering::Acquire:
668 return AtomicOrdering::Acquire;
669 case AtomicOrdering::SequentiallyConsistent:
670 return AtomicOrdering::SequentiallyConsistent;
671 }
672 }
673
674 // Methods for support type inquiry through isa, cast, and dyn_cast:
675 static bool classof(const Instruction *I) {
676 return I->getOpcode() == Instruction::AtomicCmpXchg;
677 }
678 static bool classof(const Value *V) {
679 return isa<Instruction>(V) && classof(cast<Instruction>(V));
680 }
681
682private:
683 // Shadow Instruction::setInstructionSubclassData with a private forwarding
684 // method so that subclasses cannot accidentally use it.
685 void setInstructionSubclassData(unsigned short D) {
686 Instruction::setInstructionSubclassData(D);
687 }
688
689 /// The synchronization scope ID of this cmpxchg instruction. Not quite
690 /// enough room in SubClassData for everything, so synchronization scope ID
691 /// gets its own field.
692 SyncScope::ID SSID;
693};
694
695template <>
696struct OperandTraits<AtomicCmpXchgInst> :
697 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
698};
699
700DEFINE_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 { ((i_nocapture < OperandTraits<AtomicCmpXchgInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 700, __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
) { ((i_nocapture < OperandTraits<AtomicCmpXchgInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 700, __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); }
701
702//===----------------------------------------------------------------------===//
703// AtomicRMWInst Class
704//===----------------------------------------------------------------------===//
705
706/// an instruction that atomically reads a memory location,
707/// combines it with another value, and then stores the result back. Returns
708/// the old value.
709///
710class AtomicRMWInst : public Instruction {
711protected:
712 // Note: Instruction needs to be a friend here to call cloneImpl.
713 friend class Instruction;
714
715 AtomicRMWInst *cloneImpl() const;
716
717public:
718 /// This enumeration lists the possible modifications atomicrmw can make. In
719 /// the descriptions, 'p' is the pointer to the instruction's memory location,
720 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
721 /// instruction. These instructions always return 'old'.
722 enum BinOp {
723 /// *p = v
724 Xchg,
725 /// *p = old + v
726 Add,
727 /// *p = old - v
728 Sub,
729 /// *p = old & v
730 And,
731 /// *p = ~(old & v)
732 Nand,
733 /// *p = old | v
734 Or,
735 /// *p = old ^ v
736 Xor,
737 /// *p = old >signed v ? old : v
738 Max,
739 /// *p = old <signed v ? old : v
740 Min,
741 /// *p = old >unsigned v ? old : v
742 UMax,
743 /// *p = old <unsigned v ? old : v
744 UMin,
745
746 /// *p = old + v
747 FAdd,
748
749 /// *p = old - v
750 FSub,
751
752 FIRST_BINOP = Xchg,
753 LAST_BINOP = FSub,
754 BAD_BINOP
755 };
756
757 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
758 AtomicOrdering Ordering, SyncScope::ID SSID,
759 Instruction *InsertBefore = nullptr);
760 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
761 AtomicOrdering Ordering, SyncScope::ID SSID,
762 BasicBlock *InsertAtEnd);
763
764 // allocate space for exactly two operands
765 void *operator new(size_t s) {
766 return User::operator new(s, 2);
767 }
768
769 BinOp getOperation() const {
770 return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
771 }
772
773 static StringRef getOperationName(BinOp Op);
774
775 static bool isFPOperation(BinOp Op) {
776 switch (Op) {
777 case AtomicRMWInst::FAdd:
778 case AtomicRMWInst::FSub:
779 return true;
780 default:
781 return false;
782 }
783 }
784
785 void setOperation(BinOp Operation) {
786 unsigned short SubclassData = getSubclassDataFromInstruction();
787 setInstructionSubclassData((SubclassData & 31) |
788 (Operation << 5));
789 }
790
791 /// Return true if this is a RMW on a volatile memory location.
792 ///
793 bool isVolatile() const {
794 return getSubclassDataFromInstruction() & 1;
795 }
796
797 /// Specify whether this is a volatile RMW or not.
798 ///
799 void setVolatile(bool V) {
800 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
801 (unsigned)V);
802 }
803
804 /// Transparently provide more efficient getOperand methods.
805 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
;
806
807 /// Returns the ordering constraint of this rmw instruction.
808 AtomicOrdering getOrdering() const {
809 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
810 }
811
812 /// Sets the ordering constraint of this rmw instruction.
813 void setOrdering(AtomicOrdering Ordering) {
814 assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 815, __PRETTY_FUNCTION__))
815 "atomicrmw instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 815, __PRETTY_FUNCTION__))
;
816 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
817 ((unsigned)Ordering << 2));
818 }
819
820 /// Returns the synchronization scope ID of this rmw instruction.
821 SyncScope::ID getSyncScopeID() const {
822 return SSID;
823 }
824
825 /// Sets the synchronization scope ID of this rmw instruction.
826 void setSyncScopeID(SyncScope::ID SSID) {
827 this->SSID = SSID;
828 }
829
830 Value *getPointerOperand() { return getOperand(0); }
831 const Value *getPointerOperand() const { return getOperand(0); }
832 static unsigned getPointerOperandIndex() { return 0U; }
833
834 Value *getValOperand() { return getOperand(1); }
835 const Value *getValOperand() const { return getOperand(1); }
836
837 /// Returns the address space of the pointer operand.
838 unsigned getPointerAddressSpace() const {
839 return getPointerOperand()->getType()->getPointerAddressSpace();
840 }
841
842 bool isFloatingPointOperation() const {
843 return isFPOperation(getOperation());
844 }
845
846 // Methods for support type inquiry through isa, cast, and dyn_cast:
847 static bool classof(const Instruction *I) {
848 return I->getOpcode() == Instruction::AtomicRMW;
849 }
850 static bool classof(const Value *V) {
851 return isa<Instruction>(V) && classof(cast<Instruction>(V));
852 }
853
854private:
855 void Init(BinOp Operation, Value *Ptr, Value *Val,
856 AtomicOrdering Ordering, SyncScope::ID SSID);
857
858 // Shadow Instruction::setInstructionSubclassData with a private forwarding
859 // method so that subclasses cannot accidentally use it.
860 void setInstructionSubclassData(unsigned short D) {
861 Instruction::setInstructionSubclassData(D);
862 }
863
864 /// The synchronization scope ID of this rmw instruction. Not quite enough
865 /// room in SubClassData for everything, so synchronization scope ID gets its
866 /// own field.
867 SyncScope::ID SSID;
868};
869
870template <>
871struct OperandTraits<AtomicRMWInst>
872 : public FixedNumOperandTraits<AtomicRMWInst,2> {
873};
874
875DEFINE_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 { ((i_nocapture < OperandTraits
<AtomicRMWInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 875, __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) { ((
i_nocapture < OperandTraits<AtomicRMWInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 875, __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); }
876
877//===----------------------------------------------------------------------===//
878// GetElementPtrInst Class
879//===----------------------------------------------------------------------===//
880
881// checkGEPType - Simple wrapper function to give a better assertion failure
882// message on bad indexes for a gep instruction.
883//
884inline Type *checkGEPType(Type *Ty) {
885 assert(Ty && "Invalid GetElementPtrInst indices for type!")((Ty && "Invalid GetElementPtrInst indices for type!"
) ? static_cast<void> (0) : __assert_fail ("Ty && \"Invalid GetElementPtrInst indices for type!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 885, __PRETTY_FUNCTION__))
;
886 return Ty;
887}
888
889/// an instruction for type-safe pointer arithmetic to
890/// access elements of arrays and structs
891///
892class GetElementPtrInst : public Instruction {
893 Type *SourceElementType;
894 Type *ResultElementType;
895
896 GetElementPtrInst(const GetElementPtrInst &GEPI);
897
898 /// Constructors - Create a getelementptr instruction with a base pointer an
899 /// list of indices. The first ctor can optionally insert before an existing
900 /// instruction, the second appends the new instruction to the specified
901 /// BasicBlock.
902 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
903 ArrayRef<Value *> IdxList, unsigned Values,
904 const Twine &NameStr, Instruction *InsertBefore);
905 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
906 ArrayRef<Value *> IdxList, unsigned Values,
907 const Twine &NameStr, BasicBlock *InsertAtEnd);
908
909 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
910
911protected:
912 // Note: Instruction needs to be a friend here to call cloneImpl.
913 friend class Instruction;
914
915 GetElementPtrInst *cloneImpl() const;
916
917public:
918 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
919 ArrayRef<Value *> IdxList,
920 const Twine &NameStr = "",
921 Instruction *InsertBefore = nullptr) {
922 unsigned Values = 1 + unsigned(IdxList.size());
923 if (!PointeeType)
924 PointeeType =
925 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
926 else
927 assert(((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 929, __PRETTY_FUNCTION__))
928 PointeeType ==((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 929, __PRETTY_FUNCTION__))
929 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 929, __PRETTY_FUNCTION__))
;
930 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
931 NameStr, InsertBefore);
932 }
933
934 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
935 ArrayRef<Value *> IdxList,
936 const Twine &NameStr,
937 BasicBlock *InsertAtEnd) {
938 unsigned Values = 1 + unsigned(IdxList.size());
939 if (!PointeeType)
940 PointeeType =
941 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
942 else
943 assert(((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 945, __PRETTY_FUNCTION__))
944 PointeeType ==((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 945, __PRETTY_FUNCTION__))
945 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 945, __PRETTY_FUNCTION__))
;
946 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
947 NameStr, InsertAtEnd);
948 }
949
950 /// Create an "inbounds" getelementptr. See the documentation for the
951 /// "inbounds" flag in LangRef.html for details.
952 static GetElementPtrInst *CreateInBounds(Value *Ptr,
953 ArrayRef<Value *> IdxList,
954 const Twine &NameStr = "",
955 Instruction *InsertBefore = nullptr){
956 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
957 }
958
959 static GetElementPtrInst *
960 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
961 const Twine &NameStr = "",
962 Instruction *InsertBefore = nullptr) {
963 GetElementPtrInst *GEP =
964 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
965 GEP->setIsInBounds(true);
966 return GEP;
967 }
968
969 static GetElementPtrInst *CreateInBounds(Value *Ptr,
970 ArrayRef<Value *> IdxList,
971 const Twine &NameStr,
972 BasicBlock *InsertAtEnd) {
973 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
974 }
975
976 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
977 ArrayRef<Value *> IdxList,
978 const Twine &NameStr,
979 BasicBlock *InsertAtEnd) {
980 GetElementPtrInst *GEP =
981 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
982 GEP->setIsInBounds(true);
983 return GEP;
984 }
985
986 /// Transparently provide more efficient getOperand methods.
987 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
;
988
989 Type *getSourceElementType() const { return SourceElementType; }
990
991 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
992 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
993
994 Type *getResultElementType() const {
995 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 996, __PRETTY_FUNCTION__))
996 cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 996, __PRETTY_FUNCTION__))
;
997 return ResultElementType;
998 }
999
1000 /// Returns the address space of this instruction's pointer type.
1001 unsigned getAddressSpace() const {
1002 // Note that this is always the same as the pointer operand's address space
1003 // and that is cheaper to compute, so cheat here.
1004 return getPointerAddressSpace();
1005 }
1006
1007 /// Returns the type of the element that would be loaded with
1008 /// a load instruction with the specified parameters.
1009 ///
1010 /// Null is returned if the indices are invalid for the specified
1011 /// pointer type.
1012 ///
1013 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
1014 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
1015 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
1016
1017 inline op_iterator idx_begin() { return op_begin()+1; }
1018 inline const_op_iterator idx_begin() const { return op_begin()+1; }
1019 inline op_iterator idx_end() { return op_end(); }
1020 inline const_op_iterator idx_end() const { return op_end(); }
1021
1022 inline iterator_range<op_iterator> indices() {
1023 return make_range(idx_begin(), idx_end());
1024 }
1025
1026 inline iterator_range<const_op_iterator> indices() const {
1027 return make_range(idx_begin(), idx_end());
1028 }
1029
1030 Value *getPointerOperand() {
1031 return getOperand(0);
1032 }
1033 const Value *getPointerOperand() const {
1034 return getOperand(0);
1035 }
1036 static unsigned getPointerOperandIndex() {
1037 return 0U; // get index for modifying correct operand.
1038 }
1039
1040 /// Method to return the pointer operand as a
1041 /// PointerType.
1042 Type *getPointerOperandType() const {
1043 return getPointerOperand()->getType();
1044 }
1045
1046 /// Returns the address space of the pointer operand.
1047 unsigned getPointerAddressSpace() const {
1048 return getPointerOperandType()->getPointerAddressSpace();
1049 }
1050
1051 /// Returns the pointer type returned by the GEP
1052 /// instruction, which may be a vector of pointers.
1053 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1054 ArrayRef<Value *> IdxList) {
1055 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1056 Ptr->getType()->getPointerAddressSpace());
1057 // Vector GEP
1058 if (Ptr->getType()->isVectorTy()) {
1059 unsigned NumElem = Ptr->getType()->getVectorNumElements();
1060 return VectorType::get(PtrTy, NumElem);
1061 }
1062 for (Value *Index : IdxList)
1063 if (Index->getType()->isVectorTy()) {
1064 unsigned NumElem = Index->getType()->getVectorNumElements();
1065 return VectorType::get(PtrTy, NumElem);
1066 }
1067 // Scalar GEP
1068 return PtrTy;
1069 }
1070
1071 unsigned getNumIndices() const { // Note: always non-negative
1072 return getNumOperands() - 1;
1073 }
1074
1075 bool hasIndices() const {
1076 return getNumOperands() > 1;
1077 }
1078
1079 /// Return true if all of the indices of this GEP are
1080 /// zeros. If so, the result pointer and the first operand have the same
1081 /// value, just potentially different types.
1082 bool hasAllZeroIndices() const;
1083
1084 /// Return true if all of the indices of this GEP are
1085 /// constant integers. If so, the result pointer and the first operand have
1086 /// a constant offset between them.
1087 bool hasAllConstantIndices() const;
1088
1089 /// Set or clear the inbounds flag on this GEP instruction.
1090 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1091 void setIsInBounds(bool b = true);
1092
1093 /// Determine whether the GEP has the inbounds flag.
1094 bool isInBounds() const;
1095
1096 /// Accumulate the constant address offset of this GEP if possible.
1097 ///
1098 /// This routine accepts an APInt into which it will accumulate the constant
1099 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1100 /// all-constant, it returns false and the value of the offset APInt is
1101 /// undefined (it is *not* preserved!). The APInt passed into this routine
1102 /// must be at least as wide as the IntPtr type for the address space of
1103 /// the base GEP pointer.
1104 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1105
1106 // Methods for support type inquiry through isa, cast, and dyn_cast:
1107 static bool classof(const Instruction *I) {
1108 return (I->getOpcode() == Instruction::GetElementPtr);
1109 }
1110 static bool classof(const Value *V) {
1111 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1112 }
1113};
1114
1115template <>
1116struct OperandTraits<GetElementPtrInst> :
1117 public VariadicOperandTraits<GetElementPtrInst, 1> {
1118};
1119
1120GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1121 ArrayRef<Value *> IdxList, unsigned Values,
1122 const Twine &NameStr,
1123 Instruction *InsertBefore)
1124 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1125 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1126 Values, InsertBefore),
1127 SourceElementType(PointeeType),
1128 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1129 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1130, __PRETTY_FUNCTION__))
1130 cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1130, __PRETTY_FUNCTION__))
;
1131 init(Ptr, IdxList, NameStr);
1132}
1133
1134GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1135 ArrayRef<Value *> IdxList, unsigned Values,
1136 const Twine &NameStr,
1137 BasicBlock *InsertAtEnd)
1138 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1139 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1140 Values, InsertAtEnd),
1141 SourceElementType(PointeeType),
1142 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1143 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1144, __PRETTY_FUNCTION__))
1144 cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1144, __PRETTY_FUNCTION__))
;
1145 init(Ptr, IdxList, NameStr);
1146}
1147
1148DEFINE_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 { ((i_nocapture < OperandTraits<GetElementPtrInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1148, __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
) { ((i_nocapture < OperandTraits<GetElementPtrInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1148, __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); }
1149
1150//===----------------------------------------------------------------------===//
1151// ICmpInst Class
1152//===----------------------------------------------------------------------===//
1153
1154/// This instruction compares its operands according to the predicate given
1155/// to the constructor. It only operates on integers or pointers. The operands
1156/// must be identical types.
1157/// Represent an integer comparison operator.
1158class ICmpInst: public CmpInst {
1159 void AssertOK() {
1160 assert(isIntPredicate() &&((isIntPredicate() && "Invalid ICmp predicate value")
? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1161, __PRETTY_FUNCTION__))
1161 "Invalid ICmp predicate value")((isIntPredicate() && "Invalid ICmp predicate value")
? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1161, __PRETTY_FUNCTION__))
;
1162 assert(getOperand(0)->getType() == getOperand(1)->getType() &&((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to ICmp instruction are not of the same type!"
) ? static_cast<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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1163, __PRETTY_FUNCTION__))
1163 "Both operands to ICmp instruction are not of the same type!")((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to ICmp instruction are not of the same type!"
) ? static_cast<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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1163, __PRETTY_FUNCTION__))
;
1164 // Check that the operands are the right type
1165 assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand
(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction"
) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1167, __PRETTY_FUNCTION__))
1166 getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand
(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction"
) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1167, __PRETTY_FUNCTION__))
1167 "Invalid operand types for ICmp instruction")(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand
(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction"
) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1167, __PRETTY_FUNCTION__))
;
1168 }
1169
1170protected:
1171 // Note: Instruction needs to be a friend here to call cloneImpl.
1172 friend class Instruction;
1173
1174 /// Clone an identical ICmpInst
1175 ICmpInst *cloneImpl() const;
1176
1177public:
1178 /// Constructor with insert-before-instruction semantics.
1179 ICmpInst(
1180 Instruction *InsertBefore, ///< Where to insert
1181 Predicate pred, ///< The predicate to use for the comparison
1182 Value *LHS, ///< The left-hand-side of the expression
1183 Value *RHS, ///< The right-hand-side of the expression
1184 const Twine &NameStr = "" ///< Name of the instruction
1185 ) : CmpInst(makeCmpResultType(LHS->getType()),
1186 Instruction::ICmp, pred, LHS, RHS, NameStr,
1187 InsertBefore) {
1188#ifndef NDEBUG
1189 AssertOK();
1190#endif
1191 }
1192
1193 /// Constructor with insert-at-end semantics.
1194 ICmpInst(
1195 BasicBlock &InsertAtEnd, ///< Block to insert into.
1196 Predicate pred, ///< The predicate to use for the comparison
1197 Value *LHS, ///< The left-hand-side of the expression
1198 Value *RHS, ///< The right-hand-side of the expression
1199 const Twine &NameStr = "" ///< Name of the instruction
1200 ) : CmpInst(makeCmpResultType(LHS->getType()),
1201 Instruction::ICmp, pred, LHS, RHS, NameStr,
1202 &InsertAtEnd) {
1203#ifndef NDEBUG
1204 AssertOK();
1205#endif
1206 }
1207
1208 /// Constructor with no-insertion semantics
1209 ICmpInst(
1210 Predicate pred, ///< The predicate to use for the comparison
1211 Value *LHS, ///< The left-hand-side of the expression
1212 Value *RHS, ///< The right-hand-side of the expression
1213 const Twine &NameStr = "" ///< Name of the instruction
1214 ) : CmpInst(makeCmpResultType(LHS->getType()),
1215 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1216#ifndef NDEBUG
1217 AssertOK();
1218#endif
1219 }
1220
1221 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1222 /// @returns the predicate that would be the result if the operand were
1223 /// regarded as signed.
1224 /// Return the signed version of the predicate
1225 Predicate getSignedPredicate() const {
1226 return getSignedPredicate(getPredicate());
1227 }
1228
1229 /// This is a static version that you can use without an instruction.
1230 /// Return the signed version of the predicate.
1231 static Predicate getSignedPredicate(Predicate pred);
1232
1233 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1234 /// @returns the predicate that would be the result if the operand were
1235 /// regarded as unsigned.
1236 /// Return the unsigned version of the predicate
1237 Predicate getUnsignedPredicate() const {
1238 return getUnsignedPredicate(getPredicate());
1239 }
1240
1241 /// This is a static version that you can use without an instruction.
1242 /// Return the unsigned version of the predicate.
1243 static Predicate getUnsignedPredicate(Predicate pred);
1244
1245 /// Return true if this predicate is either EQ or NE. This also
1246 /// tests for commutativity.
1247 static bool isEquality(Predicate P) {
1248 return P == ICMP_EQ || P == ICMP_NE;
1249 }
1250
1251 /// Return true if this predicate is either EQ or NE. This also
1252 /// tests for commutativity.
1253 bool isEquality() const {
1254 return isEquality(getPredicate());
1255 }
1256
1257 /// @returns true if the predicate of this ICmpInst is commutative
1258 /// Determine if this relation is commutative.
1259 bool isCommutative() const { return isEquality(); }
1260
1261 /// Return true if the predicate is relational (not EQ or NE).
1262 ///
1263 bool isRelational() const {
1264 return !isEquality();
1265 }
1266
1267 /// Return true if the predicate is relational (not EQ or NE).
1268 ///
1269 static bool isRelational(Predicate P) {
1270 return !isEquality(P);
1271 }
1272
1273 /// Exchange the two operands to this instruction in such a way that it does
1274 /// not modify the semantics of the instruction. The predicate value may be
1275 /// changed to retain the same result if the predicate is order dependent
1276 /// (e.g. ult).
1277 /// Swap operands and adjust predicate.
1278 void swapOperands() {
1279 setPredicate(getSwappedPredicate());
1280 Op<0>().swap(Op<1>());
1281 }
1282
1283 // Methods for support type inquiry through isa, cast, and dyn_cast:
1284 static bool classof(const Instruction *I) {
1285 return I->getOpcode() == Instruction::ICmp;
1286 }
1287 static bool classof(const Value *V) {
1288 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1289 }
1290};
1291
1292//===----------------------------------------------------------------------===//
1293// FCmpInst Class
1294//===----------------------------------------------------------------------===//
1295
1296/// This instruction compares its operands according to the predicate given
1297/// to the constructor. It only operates on floating point values or packed
1298/// vectors of floating point values. The operands must be identical types.
1299/// Represents a floating point comparison operator.
1300class FCmpInst: public CmpInst {
1301 void AssertOK() {
1302 assert(isFPPredicate() && "Invalid FCmp predicate value")((isFPPredicate() && "Invalid FCmp predicate value") ?
static_cast<void> (0) : __assert_fail ("isFPPredicate() && \"Invalid FCmp predicate value\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1302, __PRETTY_FUNCTION__))
;
1303 assert(getOperand(0)->getType() == getOperand(1)->getType() &&((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to FCmp instruction are not of the same type!"
) ? static_cast<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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1304, __PRETTY_FUNCTION__))
1304 "Both operands to FCmp instruction are not of the same type!")((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to FCmp instruction are not of the same type!"
) ? static_cast<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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1304, __PRETTY_FUNCTION__))
;
1305 // Check that the operands are the right type
1306 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&((getOperand(0)->getType()->isFPOrFPVectorTy() &&
"Invalid operand types for FCmp instruction") ? static_cast<
void> (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1307, __PRETTY_FUNCTION__))
1307 "Invalid operand types for FCmp instruction")((getOperand(0)->getType()->isFPOrFPVectorTy() &&
"Invalid operand types for FCmp instruction") ? static_cast<
void> (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1307, __PRETTY_FUNCTION__))
;
1308 }
1309
1310protected:
1311 // Note: Instruction needs to be a friend here to call cloneImpl.
1312 friend class Instruction;
1313
1314 /// Clone an identical FCmpInst
1315 FCmpInst *cloneImpl() const;
1316
1317public:
1318 /// Constructor with insert-before-instruction semantics.
1319 FCmpInst(
1320 Instruction *InsertBefore, ///< Where to insert
1321 Predicate pred, ///< The predicate to use for the comparison
1322 Value *LHS, ///< The left-hand-side of the expression
1323 Value *RHS, ///< The right-hand-side of the expression
1324 const Twine &NameStr = "" ///< Name of the instruction
1325 ) : CmpInst(makeCmpResultType(LHS->getType()),
1326 Instruction::FCmp, pred, LHS, RHS, NameStr,
1327 InsertBefore) {
1328 AssertOK();
1329 }
1330
1331 /// Constructor with insert-at-end semantics.
1332 FCmpInst(
1333 BasicBlock &InsertAtEnd, ///< Block to insert into.
1334 Predicate pred, ///< The predicate to use for the comparison
1335 Value *LHS, ///< The left-hand-side of the expression
1336 Value *RHS, ///< The right-hand-side of the expression
1337 const Twine &NameStr = "" ///< Name of the instruction
1338 ) : CmpInst(makeCmpResultType(LHS->getType()),
1339 Instruction::FCmp, pred, LHS, RHS, NameStr,
1340 &InsertAtEnd) {
1341 AssertOK();
1342 }
1343
1344 /// Constructor with no-insertion semantics
1345 FCmpInst(
1346 Predicate Pred, ///< The predicate to use for the comparison
1347 Value *LHS, ///< The left-hand-side of the expression
1348 Value *RHS, ///< The right-hand-side of the expression
1349 const Twine &NameStr = "", ///< Name of the instruction
1350 Instruction *FlagsSource = nullptr
1351 ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1352 RHS, NameStr, nullptr, FlagsSource) {
1353 AssertOK();
1354 }
1355
1356 /// @returns true if the predicate of this instruction is EQ or NE.
1357 /// Determine if this is an equality predicate.
1358 static bool isEquality(Predicate Pred) {
1359 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1360 Pred == FCMP_UNE;
1361 }
1362
1363 /// @returns true if the predicate of this instruction is EQ or NE.
1364 /// Determine if this is an equality predicate.
1365 bool isEquality() const { return isEquality(getPredicate()); }
1366
1367 /// @returns true if the predicate of this instruction is commutative.
1368 /// Determine if this is a commutative predicate.
1369 bool isCommutative() const {
1370 return isEquality() ||
1371 getPredicate() == FCMP_FALSE ||
1372 getPredicate() == FCMP_TRUE ||
1373 getPredicate() == FCMP_ORD ||
1374 getPredicate() == FCMP_UNO;
1375 }
1376
1377 /// @returns true if the predicate is relational (not EQ or NE).
1378 /// Determine if this a relational predicate.
1379 bool isRelational() const { return !isEquality(); }
1380
1381 /// Exchange the two operands to this instruction in such a way that it does
1382 /// not modify the semantics of the instruction. The predicate value may be
1383 /// changed to retain the same result if the predicate is order dependent
1384 /// (e.g. ult).
1385 /// Swap operands and adjust predicate.
1386 void swapOperands() {
1387 setPredicate(getSwappedPredicate());
1388 Op<0>().swap(Op<1>());
1389 }
1390
1391 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1392 static bool classof(const Instruction *I) {
1393 return I->getOpcode() == Instruction::FCmp;
1394 }
1395 static bool classof(const Value *V) {
1396 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1397 }
1398};
1399
1400//===----------------------------------------------------------------------===//
1401/// This class represents a function call, abstracting a target
1402/// machine's calling convention. This class uses low bit of the SubClassData
1403/// field to indicate whether or not this is a tail call. The rest of the bits
1404/// hold the calling convention of the call.
1405///
1406class CallInst : public CallBase {
1407 CallInst(const CallInst &CI);
1408
1409 /// Construct a CallInst given a range of arguments.
1410 /// Construct a CallInst from a range of arguments
1411 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1412 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1413 Instruction *InsertBefore);
1414
1415 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1416 const Twine &NameStr, Instruction *InsertBefore)
1417 : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
1418
1419 /// Construct a CallInst given a range of arguments.
1420 /// Construct a CallInst from a range of arguments
1421 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1422 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1423 BasicBlock *InsertAtEnd);
1424
1425 explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
1426 Instruction *InsertBefore);
1427
1428 CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
1429 BasicBlock *InsertAtEnd);
1430
1431 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1432 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1433 void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
1434
1435 /// Compute the number of operands to allocate.
1436 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
1437 // We need one operand for the called function, plus the input operand
1438 // counts provided.
1439 return 1 + NumArgs + NumBundleInputs;
1440 }
1441
1442protected:
1443 // Note: Instruction needs to be a friend here to call cloneImpl.
1444 friend class Instruction;
1445
1446 CallInst *cloneImpl() const;
1447
1448public:
1449 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
1450 Instruction *InsertBefore = nullptr) {
1451 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
1452 }
1453
1454 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1455 const Twine &NameStr,
1456 Instruction *InsertBefore = nullptr) {
1457 return new (ComputeNumOperands(Args.size()))
1458 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1459 }
1460
1461 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1462 ArrayRef<OperandBundleDef> Bundles = None,
1463 const Twine &NameStr = "",
1464 Instruction *InsertBefore = nullptr) {
1465 const int NumOperands =
1466 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1467 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1468
1469 return new (NumOperands, DescriptorBytes)
1470 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1471 }
1472
1473 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
1474 BasicBlock *InsertAtEnd) {
1475 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
1476 }
1477
1478 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1479 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1480 return new (ComputeNumOperands(Args.size()))
1481 CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
1482 }
1483
1484 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1485 ArrayRef<OperandBundleDef> Bundles,
1486 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1487 const int NumOperands =
1488 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1489 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1490
1491 return new (NumOperands, DescriptorBytes)
1492 CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
1493 }
1494
1495 static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
1496 Instruction *InsertBefore = nullptr) {
1497 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1498 InsertBefore);
1499 }
1500
1501 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1502 ArrayRef<OperandBundleDef> Bundles = None,
1503 const Twine &NameStr = "",
1504 Instruction *InsertBefore = nullptr) {
1505 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1506 NameStr, InsertBefore);
1507 }
1508
1509 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1510 const Twine &NameStr,
1511 Instruction *InsertBefore = nullptr) {
1512 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1513 InsertBefore);
1514 }
1515
1516 static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
1517 BasicBlock *InsertAtEnd) {
1518 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1519 InsertAtEnd);
1520 }
1521
1522 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1523 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1524 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1525 InsertAtEnd);
1526 }
1527
1528 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1529 ArrayRef<OperandBundleDef> Bundles,
1530 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1531 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1532 NameStr, InsertAtEnd);
1533 }
1534
1535 // Deprecated [opaque pointer types]
1536 static CallInst *Create(Value *Func, const Twine &NameStr = "",
1537 Instruction *InsertBefore = nullptr) {
1538 return Create(cast<FunctionType>(
1539 cast<PointerType>(Func->getType())->getElementType()),
1540 Func, NameStr, InsertBefore);
1541 }
1542
1543 // Deprecated [opaque pointer types]
1544 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1545 const Twine &NameStr,
1546 Instruction *InsertBefore = nullptr) {
1547 return Create(cast<FunctionType>(
1548 cast<PointerType>(Func->getType())->getElementType()),
1549 Func, Args, NameStr, InsertBefore);
1550 }
1551
1552 // Deprecated [opaque pointer types]
1553 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1554 ArrayRef<OperandBundleDef> Bundles = None,
1555 const Twine &NameStr = "",
1556 Instruction *InsertBefore = nullptr) {
1557 return Create(cast<FunctionType>(
1558 cast<PointerType>(Func->getType())->getElementType()),
1559 Func, Args, Bundles, NameStr, InsertBefore);
1560 }
1561
1562 // Deprecated [opaque pointer types]
1563 static CallInst *Create(Value *Func, const Twine &NameStr,
1564 BasicBlock *InsertAtEnd) {
1565 return Create(cast<FunctionType>(
1566 cast<PointerType>(Func->getType())->getElementType()),
1567 Func, NameStr, InsertAtEnd);
1568 }
1569
1570 // Deprecated [opaque pointer types]
1571 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1572 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1573 return Create(cast<FunctionType>(
1574 cast<PointerType>(Func->getType())->getElementType()),
1575 Func, Args, NameStr, InsertAtEnd);
1576 }
1577
1578 // Deprecated [opaque pointer types]
1579 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1580 ArrayRef<OperandBundleDef> Bundles,
1581 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1582 return Create(cast<FunctionType>(
1583 cast<PointerType>(Func->getType())->getElementType()),
1584 Func, Args, Bundles, NameStr, InsertAtEnd);
1585 }
1586
1587 /// Create a clone of \p CI with a different set of operand bundles and
1588 /// insert it before \p InsertPt.
1589 ///
1590 /// The returned call instruction is identical \p CI in every way except that
1591 /// the operand bundles for the new instruction are set to the operand bundles
1592 /// in \p Bundles.
1593 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1594 Instruction *InsertPt = nullptr);
1595
1596 /// Generate the IR for a call to malloc:
1597 /// 1. Compute the malloc call's argument as the specified type's size,
1598 /// possibly multiplied by the array size if the array size is not
1599 /// constant 1.
1600 /// 2. Call malloc with that argument.
1601 /// 3. Bitcast the result of the malloc call to the specified type.
1602 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1603 Type *AllocTy, Value *AllocSize,
1604 Value *ArraySize = nullptr,
1605 Function *MallocF = nullptr,
1606 const Twine &Name = "");
1607 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1608 Type *AllocTy, Value *AllocSize,
1609 Value *ArraySize = nullptr,
1610 Function *MallocF = nullptr,
1611 const Twine &Name = "");
1612 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1613 Type *AllocTy, Value *AllocSize,
1614 Value *ArraySize = nullptr,
1615 ArrayRef<OperandBundleDef> Bundles = None,
1616 Function *MallocF = nullptr,
1617 const Twine &Name = "");
1618 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1619 Type *AllocTy, Value *AllocSize,
1620 Value *ArraySize = nullptr,
1621 ArrayRef<OperandBundleDef> Bundles = None,
1622 Function *MallocF = nullptr,
1623 const Twine &Name = "");
1624 /// Generate the IR for a call to the builtin free function.
1625 static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
1626 static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
1627 static Instruction *CreateFree(Value *Source,
1628 ArrayRef<OperandBundleDef> Bundles,
1629 Instruction *InsertBefore);
1630 static Instruction *CreateFree(Value *Source,
1631 ArrayRef<OperandBundleDef> Bundles,
1632 BasicBlock *InsertAtEnd);
1633
1634 // Note that 'musttail' implies 'tail'.
1635 enum TailCallKind {
1636 TCK_None = 0,
1637 TCK_Tail = 1,
1638 TCK_MustTail = 2,
1639 TCK_NoTail = 3
1640 };
1641 TailCallKind getTailCallKind() const {
1642 return TailCallKind(getSubclassDataFromInstruction() & 3);
1643 }
1644
1645 bool isTailCall() const {
1646 unsigned Kind = getSubclassDataFromInstruction() & 3;
1647 return Kind == TCK_Tail || Kind == TCK_MustTail;
1648 }
1649
1650 bool isMustTailCall() const {
1651 return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1652 }
1653
1654 bool isNoTailCall() const {
1655 return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1656 }
1657
1658 void setTailCall(bool isTC = true) {
1659 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1660 unsigned(isTC ? TCK_Tail : TCK_None));
1661 }
1662
1663 void setTailCallKind(TailCallKind TCK) {
1664 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1665 unsigned(TCK));
1666 }
1667
1668 /// Return true if the call can return twice
1669 bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
1670 void setCanReturnTwice() {
1671 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1672 }
1673
1674 // Methods for support type inquiry through isa, cast, and dyn_cast:
1675 static bool classof(const Instruction *I) {
1676 return I->getOpcode() == Instruction::Call;
1677 }
1678 static bool classof(const Value *V) {
1679 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1680 }
1681
1682 /// Updates profile metadata by scaling it by \p S / \p T.
1683 void updateProfWeight(uint64_t S, uint64_t T);
1684
1685private:
1686 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1687 // method so that subclasses cannot accidentally use it.
1688 void setInstructionSubclassData(unsigned short D) {
1689 Instruction::setInstructionSubclassData(D);
1690 }
1691};
1692
1693CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1694 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1695 BasicBlock *InsertAtEnd)
1696 : CallBase(Ty->getReturnType(), Instruction::Call,
1697 OperandTraits<CallBase>::op_end(this) -
1698 (Args.size() + CountBundleInputs(Bundles) + 1),
1699 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1700 InsertAtEnd) {
1701 init(Ty, Func, Args, Bundles, NameStr);
1702}
1703
1704CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1705 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1706 Instruction *InsertBefore)
1707 : CallBase(Ty->getReturnType(), Instruction::Call,
1708 OperandTraits<CallBase>::op_end(this) -
1709 (Args.size() + CountBundleInputs(Bundles) + 1),
1710 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1711 InsertBefore) {
1712 init(Ty, Func, Args, Bundles, NameStr);
1713}
1714
1715//===----------------------------------------------------------------------===//
1716// SelectInst Class
1717//===----------------------------------------------------------------------===//
1718
1719/// This class represents the LLVM 'select' instruction.
1720///
1721class SelectInst : public Instruction {
1722 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1723 Instruction *InsertBefore)
1724 : Instruction(S1->getType(), Instruction::Select,
1725 &Op<0>(), 3, InsertBefore) {
1726 init(C, S1, S2);
1727 setName(NameStr);
1728 }
1729
1730 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1731 BasicBlock *InsertAtEnd)
1732 : Instruction(S1->getType(), Instruction::Select,
1733 &Op<0>(), 3, InsertAtEnd) {
1734 init(C, S1, S2);
1735 setName(NameStr);
1736 }
1737
1738 void init(Value *C, Value *S1, Value *S2) {
1739 assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select")((!areInvalidOperands(C, S1, S2) && "Invalid operands for select"
) ? static_cast<void> (0) : __assert_fail ("!areInvalidOperands(C, S1, S2) && \"Invalid operands for select\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1739, __PRETTY_FUNCTION__))
;
1740 Op<0>() = C;
1741 Op<1>() = S1;
1742 Op<2>() = S2;
1743 }
1744
1745protected:
1746 // Note: Instruction needs to be a friend here to call cloneImpl.
1747 friend class Instruction;
1748
1749 SelectInst *cloneImpl() const;
1750
1751public:
1752 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1753 const Twine &NameStr = "",
1754 Instruction *InsertBefore = nullptr,
1755 Instruction *MDFrom = nullptr) {
1756 SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1757 if (MDFrom)
1758 Sel->copyMetadata(*MDFrom);
1759 return Sel;
1760 }
1761
1762 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1763 const Twine &NameStr,
1764 BasicBlock *InsertAtEnd) {
1765 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1766 }
1767
1768 const Value *getCondition() const { return Op<0>(); }
1769 const Value *getTrueValue() const { return Op<1>(); }
1770 const Value *getFalseValue() const { return Op<2>(); }
1771 Value *getCondition() { return Op<0>(); }
1772 Value *getTrueValue() { return Op<1>(); }
1773 Value *getFalseValue() { return Op<2>(); }
1774
1775 void setCondition(Value *V) { Op<0>() = V; }
1776 void setTrueValue(Value *V) { Op<1>() = V; }
1777 void setFalseValue(Value *V) { Op<2>() = V; }
1778
1779 /// Swap the true and false values of the select instruction.
1780 /// This doesn't swap prof metadata.
1781 void swapValues() { Op<1>().swap(Op<2>()); }
1782
1783 /// Return a string if the specified operands are invalid
1784 /// for a select operation, otherwise return null.
1785 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1786
1787 /// Transparently provide more efficient getOperand methods.
1788 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
;
1789
1790 OtherOps getOpcode() const {
1791 return static_cast<OtherOps>(Instruction::getOpcode());
1792 }
1793
1794 // Methods for support type inquiry through isa, cast, and dyn_cast:
1795 static bool classof(const Instruction *I) {
1796 return I->getOpcode() == Instruction::Select;
1797 }
1798 static bool classof(const Value *V) {
1799 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1800 }
1801};
1802
1803template <>
1804struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1805};
1806
1807DEFINE_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 { ((i_nocapture <
OperandTraits<SelectInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1807, __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) { ((i_nocapture <
OperandTraits<SelectInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1807, __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); }
1808
1809//===----------------------------------------------------------------------===//
1810// VAArgInst Class
1811//===----------------------------------------------------------------------===//
1812
1813/// This class represents the va_arg llvm instruction, which returns
1814/// an argument of the specified type given a va_list and increments that list
1815///
1816class VAArgInst : public UnaryInstruction {
1817protected:
1818 // Note: Instruction needs to be a friend here to call cloneImpl.
1819 friend class Instruction;
1820
1821 VAArgInst *cloneImpl() const;
1822
1823public:
1824 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1825 Instruction *InsertBefore = nullptr)
1826 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1827 setName(NameStr);
1828 }
1829
1830 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1831 BasicBlock *InsertAtEnd)
1832 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1833 setName(NameStr);
1834 }
1835
1836 Value *getPointerOperand() { return getOperand(0); }
1837 const Value *getPointerOperand() const { return getOperand(0); }
1838 static unsigned getPointerOperandIndex() { return 0U; }
1839
1840 // Methods for support type inquiry through isa, cast, and dyn_cast:
1841 static bool classof(const Instruction *I) {
1842 return I->getOpcode() == VAArg;
1843 }
1844 static bool classof(const Value *V) {
1845 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1846 }
1847};
1848
1849//===----------------------------------------------------------------------===//
1850// ExtractElementInst Class
1851//===----------------------------------------------------------------------===//
1852
1853/// This instruction extracts a single (scalar)
1854/// element from a VectorType value
1855///
1856class ExtractElementInst : public Instruction {
1857 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1858 Instruction *InsertBefore = nullptr);
1859 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1860 BasicBlock *InsertAtEnd);
1861
1862protected:
1863 // Note: Instruction needs to be a friend here to call cloneImpl.
1864 friend class Instruction;
1865
1866 ExtractElementInst *cloneImpl() const;
1867
1868public:
1869 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1870 const Twine &NameStr = "",
1871 Instruction *InsertBefore = nullptr) {
1872 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1873 }
1874
1875 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1876 const Twine &NameStr,
1877 BasicBlock *InsertAtEnd) {
1878 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1879 }
1880
1881 /// Return true if an extractelement instruction can be
1882 /// formed with the specified operands.
1883 static bool isValidOperands(const Value *Vec, const Value *Idx);
1884
1885 Value *getVectorOperand() { return Op<0>(); }
1886 Value *getIndexOperand() { return Op<1>(); }
1887 const Value *getVectorOperand() const { return Op<0>(); }
1888 const Value *getIndexOperand() const { return Op<1>(); }
1889
1890 VectorType *getVectorOperandType() const {
1891 return cast<VectorType>(getVectorOperand()->getType());
1892 }
1893
1894 /// Transparently provide more efficient getOperand methods.
1895 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
;
1896
1897 // Methods for support type inquiry through isa, cast, and dyn_cast:
1898 static bool classof(const Instruction *I) {
1899 return I->getOpcode() == Instruction::ExtractElement;
1900 }
1901 static bool classof(const Value *V) {
1902 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1903 }
1904};
1905
1906template <>
1907struct OperandTraits<ExtractElementInst> :
1908 public FixedNumOperandTraits<ExtractElementInst, 2> {
1909};
1910
1911DEFINE_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 {
((i_nocapture < OperandTraits<ExtractElementInst>::
operands(this) && "getOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1911, __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) { ((i_nocapture < OperandTraits<ExtractElementInst
>::operands(this) && "setOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1911, __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); }
1912
1913//===----------------------------------------------------------------------===//
1914// InsertElementInst Class
1915//===----------------------------------------------------------------------===//
1916
1917/// This instruction inserts a single (scalar)
1918/// element into a VectorType value
1919///
1920class InsertElementInst : public Instruction {
1921 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1922 const Twine &NameStr = "",
1923 Instruction *InsertBefore = nullptr);
1924 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1925 BasicBlock *InsertAtEnd);
1926
1927protected:
1928 // Note: Instruction needs to be a friend here to call cloneImpl.
1929 friend class Instruction;
1930
1931 InsertElementInst *cloneImpl() const;
1932
1933public:
1934 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1935 const Twine &NameStr = "",
1936 Instruction *InsertBefore = nullptr) {
1937 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1938 }
1939
1940 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1941 const Twine &NameStr,
1942 BasicBlock *InsertAtEnd) {
1943 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1944 }
1945
1946 /// Return true if an insertelement instruction can be
1947 /// formed with the specified operands.
1948 static bool isValidOperands(const Value *Vec, const Value *NewElt,
1949 const Value *Idx);
1950
1951 /// Overload to return most specific vector type.
1952 ///
1953 VectorType *getType() const {
1954 return cast<VectorType>(Instruction::getType());
1955 }
1956
1957 /// Transparently provide more efficient getOperand methods.
1958 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
;
1959
1960 // Methods for support type inquiry through isa, cast, and dyn_cast:
1961 static bool classof(const Instruction *I) {
1962 return I->getOpcode() == Instruction::InsertElement;
1963 }
1964 static bool classof(const Value *V) {
1965 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1966 }
1967};
1968
1969template <>
1970struct OperandTraits<InsertElementInst> :
1971 public FixedNumOperandTraits<InsertElementInst, 3> {
1972};
1973
1974DEFINE_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 { ((i_nocapture < OperandTraits<InsertElementInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1974, __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
) { ((i_nocapture < OperandTraits<InsertElementInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1974, __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); }
1975
1976//===----------------------------------------------------------------------===//
1977// ShuffleVectorInst Class
1978//===----------------------------------------------------------------------===//
1979
1980/// This instruction constructs a fixed permutation of two
1981/// input vectors.
1982///
1983class ShuffleVectorInst : public Instruction {
1984protected:
1985 // Note: Instruction needs to be a friend here to call cloneImpl.
1986 friend class Instruction;
1987
1988 ShuffleVectorInst *cloneImpl() const;
1989
1990public:
1991 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1992 const Twine &NameStr = "",
1993 Instruction *InsertBefor = nullptr);
1994 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1995 const Twine &NameStr, BasicBlock *InsertAtEnd);
1996
1997 // allocate space for exactly three operands
1998 void *operator new(size_t s) {
1999 return User::operator new(s, 3);
2000 }
2001
2002 /// Swap the first 2 operands and adjust the mask to preserve the semantics
2003 /// of the instruction.
2004 void commute();
2005
2006 /// Return true if a shufflevector instruction can be
2007 /// formed with the specified operands.
2008 static bool isValidOperands(const Value *V1, const Value *V2,
2009 const Value *Mask);
2010
2011 /// Overload to return most specific vector type.
2012 ///
2013 VectorType *getType() const {
2014 return cast<VectorType>(Instruction::getType());
2015 }
2016
2017 /// Transparently provide more efficient getOperand methods.
2018 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
;
2019
2020 Constant *getMask() const {
2021 return cast<Constant>(getOperand(2));
2022 }
2023
2024 /// Return the shuffle mask value for the specified element of the mask.
2025 /// Return -1 if the element is undef.
2026 static int getMaskValue(const Constant *Mask, unsigned Elt);
2027
2028 /// Return the shuffle mask value of this instruction for the given element
2029 /// index. Return -1 if the element is undef.
2030 int getMaskValue(unsigned Elt) const {
2031 return getMaskValue(getMask(), Elt);
2032 }
2033
2034 /// Convert the input shuffle mask operand to a vector of integers. Undefined
2035 /// elements of the mask are returned as -1.
2036 static void getShuffleMask(const Constant *Mask,
2037 SmallVectorImpl<int> &Result);
2038
2039 /// Return the mask for this instruction as a vector of integers. Undefined
2040 /// elements of the mask are returned as -1.
2041 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2042 return getShuffleMask(getMask(), Result);
2043 }
2044
2045 SmallVector<int, 16> getShuffleMask() const {
2046 SmallVector<int, 16> Mask;
2047 getShuffleMask(Mask);
2048 return Mask;
2049 }
2050
2051 /// Return true if this shuffle returns a vector with a different number of
2052 /// elements than its source vectors.
2053 /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2054 /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2055 bool changesLength() const {
2056 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2057 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2058 return NumSourceElts != NumMaskElts;
2059 }
2060
2061 /// Return true if this shuffle returns a vector with a greater number of
2062 /// elements than its source vectors.
2063 /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2064 bool increasesLength() const {
2065 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2066 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2067 return NumSourceElts < NumMaskElts;
2068 }
2069
2070 /// Return true if this shuffle mask chooses elements from exactly one source
2071 /// vector.
2072 /// Example: <7,5,undef,7>
2073 /// This assumes that vector operands are the same length as the mask.
2074 static bool isSingleSourceMask(ArrayRef<int> Mask);
2075 static bool isSingleSourceMask(const Constant *Mask) {
2076 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2076, __PRETTY_FUNCTION__))
;
2077 SmallVector<int, 16> MaskAsInts;
2078 getShuffleMask(Mask, MaskAsInts);
2079 return isSingleSourceMask(MaskAsInts);
2080 }
2081
2082 /// Return true if this shuffle chooses elements from exactly one source
2083 /// vector without changing the length of that vector.
2084 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2085 /// TODO: Optionally allow length-changing shuffles.
2086 bool isSingleSource() const {
2087 return !changesLength() && isSingleSourceMask(getMask());
2088 }
2089
2090 /// Return true if this shuffle mask chooses elements from exactly one source
2091 /// vector without lane crossings. A shuffle using this mask is not
2092 /// necessarily a no-op because it may change the number of elements from its
2093 /// input vectors or it may provide demanded bits knowledge via undef lanes.
2094 /// Example: <undef,undef,2,3>
2095 static bool isIdentityMask(ArrayRef<int> Mask);
2096 static bool isIdentityMask(const Constant *Mask) {
2097 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2097, __PRETTY_FUNCTION__))
;
2098 SmallVector<int, 16> MaskAsInts;
2099 getShuffleMask(Mask, MaskAsInts);
2100 return isIdentityMask(MaskAsInts);
2101 }
2102
2103 /// Return true if this shuffle chooses elements from exactly one source
2104 /// vector without lane crossings and does not change the number of elements
2105 /// from its input vectors.
2106 /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2107 bool isIdentity() const {
2108 return !changesLength() && isIdentityMask(getShuffleMask());
2109 }
2110
2111 /// Return true if this shuffle lengthens exactly one source vector with
2112 /// undefs in the high elements.
2113 bool isIdentityWithPadding() const;
2114
2115 /// Return true if this shuffle extracts the first N elements of exactly one
2116 /// source vector.
2117 bool isIdentityWithExtract() const;
2118
2119 /// Return true if this shuffle concatenates its 2 source vectors. This
2120 /// returns false if either input is undefined. In that case, the shuffle is
2121 /// is better classified as an identity with padding operation.
2122 bool isConcat() const;
2123
2124 /// Return true if this shuffle mask chooses elements from its source vectors
2125 /// without lane crossings. A shuffle using this mask would be
2126 /// equivalent to a vector select with a constant condition operand.
2127 /// Example: <4,1,6,undef>
2128 /// This returns false if the mask does not choose from both input vectors.
2129 /// In that case, the shuffle is better classified as an identity shuffle.
2130 /// This assumes that vector operands are the same length as the mask
2131 /// (a length-changing shuffle can never be equivalent to a vector select).
2132 static bool isSelectMask(ArrayRef<int> Mask);
2133 static bool isSelectMask(const Constant *Mask) {
2134 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2134, __PRETTY_FUNCTION__))
;
2135 SmallVector<int, 16> MaskAsInts;
2136 getShuffleMask(Mask, MaskAsInts);
2137 return isSelectMask(MaskAsInts);
2138 }
2139
2140 /// Return true if this shuffle chooses elements from its source vectors
2141 /// without lane crossings and all operands have the same number of elements.
2142 /// In other words, this shuffle is equivalent to a vector select with a
2143 /// constant condition operand.
2144 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2145 /// This returns false if the mask does not choose from both input vectors.
2146 /// In that case, the shuffle is better classified as an identity shuffle.
2147 /// TODO: Optionally allow length-changing shuffles.
2148 bool isSelect() const {
2149 return !changesLength() && isSelectMask(getMask());
2150 }
2151
2152 /// Return true if this shuffle mask swaps the order of elements from exactly
2153 /// one source vector.
2154 /// Example: <7,6,undef,4>
2155 /// This assumes that vector operands are the same length as the mask.
2156 static bool isReverseMask(ArrayRef<int> Mask);
2157 static bool isReverseMask(const Constant *Mask) {
2158 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2158, __PRETTY_FUNCTION__))
;
2159 SmallVector<int, 16> MaskAsInts;
2160 getShuffleMask(Mask, MaskAsInts);
2161 return isReverseMask(MaskAsInts);
2162 }
2163
2164 /// Return true if this shuffle swaps the order of elements from exactly
2165 /// one source vector.
2166 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2167 /// TODO: Optionally allow length-changing shuffles.
2168 bool isReverse() const {
2169 return !changesLength() && isReverseMask(getMask());
2170 }
2171
2172 /// Return true if this shuffle mask chooses all elements with the same value
2173 /// as the first element of exactly one source vector.
2174 /// Example: <4,undef,undef,4>
2175 /// This assumes that vector operands are the same length as the mask.
2176 static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2177 static bool isZeroEltSplatMask(const Constant *Mask) {
2178 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2178, __PRETTY_FUNCTION__))
;
2179 SmallVector<int, 16> MaskAsInts;
2180 getShuffleMask(Mask, MaskAsInts);
2181 return isZeroEltSplatMask(MaskAsInts);
2182 }
2183
2184 /// Return true if all elements of this shuffle are the same value as the
2185 /// first element of exactly one source vector without changing the length
2186 /// of that vector.
2187 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2188 /// TODO: Optionally allow length-changing shuffles.
2189 /// TODO: Optionally allow splats from other elements.
2190 bool isZeroEltSplat() const {
2191 return !changesLength() && isZeroEltSplatMask(getMask());
2192 }
2193
2194 /// Return true if this shuffle mask is a transpose mask.
2195 /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2196 /// even- or odd-numbered vector elements from two n-dimensional source
2197 /// vectors and write each result into consecutive elements of an
2198 /// n-dimensional destination vector. Two shuffles are necessary to complete
2199 /// the transpose, one for the even elements and another for the odd elements.
2200 /// This description closely follows how the TRN1 and TRN2 AArch64
2201 /// instructions operate.
2202 ///
2203 /// For example, a simple 2x2 matrix can be transposed with:
2204 ///
2205 /// ; Original matrix
2206 /// m0 = < a, b >
2207 /// m1 = < c, d >
2208 ///
2209 /// ; Transposed matrix
2210 /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2211 /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2212 ///
2213 /// For matrices having greater than n columns, the resulting nx2 transposed
2214 /// matrix is stored in two result vectors such that one vector contains
2215 /// interleaved elements from all the even-numbered rows and the other vector
2216 /// contains interleaved elements from all the odd-numbered rows. For example,
2217 /// a 2x4 matrix can be transposed with:
2218 ///
2219 /// ; Original matrix
2220 /// m0 = < a, b, c, d >
2221 /// m1 = < e, f, g, h >
2222 ///
2223 /// ; Transposed matrix
2224 /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2225 /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2226 static bool isTransposeMask(ArrayRef<int> Mask);
2227 static bool isTransposeMask(const Constant *Mask) {
2228 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2228, __PRETTY_FUNCTION__))
;
2229 SmallVector<int, 16> MaskAsInts;
2230 getShuffleMask(Mask, MaskAsInts);
2231 return isTransposeMask(MaskAsInts);
2232 }
2233
2234 /// Return true if this shuffle transposes the elements of its inputs without
2235 /// changing the length of the vectors. This operation may also be known as a
2236 /// merge or interleave. See the description for isTransposeMask() for the
2237 /// exact specification.
2238 /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2239 bool isTranspose() const {
2240 return !changesLength() && isTransposeMask(getMask());
2241 }
2242
2243 /// Return true if this shuffle mask is an extract subvector mask.
2244 /// A valid extract subvector mask returns a smaller vector from a single
2245 /// source operand. The base extraction index is returned as well.
2246 static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2247 int &Index);
2248 static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2249 int &Index) {
2250 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2250, __PRETTY_FUNCTION__))
;
2251 SmallVector<int, 16> MaskAsInts;
2252 getShuffleMask(Mask, MaskAsInts);
2253 return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2254 }
2255
2256 /// Return true if this shuffle mask is an extract subvector mask.
2257 bool isExtractSubvectorMask(int &Index) const {
2258 int NumSrcElts = Op<0>()->getType()->getVectorNumElements();
2259 return isExtractSubvectorMask(getMask(), NumSrcElts, Index);
2260 }
2261
2262 /// Change values in a shuffle permute mask assuming the two vector operands
2263 /// of length InVecNumElts have swapped position.
2264 static void commuteShuffleMask(MutableArrayRef<int> Mask,
2265 unsigned InVecNumElts) {
2266 for (int &Idx : Mask) {
2267 if (Idx == -1)
2268 continue;
2269 Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2270 assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&((Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
"shufflevector mask index out of range") ? static_cast<void
> (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2271, __PRETTY_FUNCTION__))
2271 "shufflevector mask index out of range")((Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
"shufflevector mask index out of range") ? static_cast<void
> (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2271, __PRETTY_FUNCTION__))
;
2272 }
2273 }
2274
2275 // Methods for support type inquiry through isa, cast, and dyn_cast:
2276 static bool classof(const Instruction *I) {
2277 return I->getOpcode() == Instruction::ShuffleVector;
2278 }
2279 static bool classof(const Value *V) {
2280 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2281 }
2282};
2283
2284template <>
2285struct OperandTraits<ShuffleVectorInst> :
2286 public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2287};
2288
2289DEFINE_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 { ((i_nocapture < OperandTraits<ShuffleVectorInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2289, __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
) { ((i_nocapture < OperandTraits<ShuffleVectorInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2289, __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); }
2290
2291//===----------------------------------------------------------------------===//
2292// ExtractValueInst Class
2293//===----------------------------------------------------------------------===//
2294
2295/// This instruction extracts a struct member or array
2296/// element value from an aggregate value.
2297///
2298class ExtractValueInst : public UnaryInstruction {
2299 SmallVector<unsigned, 4> Indices;
2300
2301 ExtractValueInst(const ExtractValueInst &EVI);
2302
2303 /// Constructors - Create a extractvalue instruction with a base aggregate
2304 /// value and a list of indices. The first ctor can optionally insert before
2305 /// an existing instruction, the second appends the new instruction to the
2306 /// specified BasicBlock.
2307 inline ExtractValueInst(Value *Agg,
2308 ArrayRef<unsigned> Idxs,
2309 const Twine &NameStr,
2310 Instruction *InsertBefore);
2311 inline ExtractValueInst(Value *Agg,
2312 ArrayRef<unsigned> Idxs,
2313 const Twine &NameStr, BasicBlock *InsertAtEnd);
2314
2315 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2316
2317protected:
2318 // Note: Instruction needs to be a friend here to call cloneImpl.
2319 friend class Instruction;
2320
2321 ExtractValueInst *cloneImpl() const;
2322
2323public:
2324 static ExtractValueInst *Create(Value *Agg,
2325 ArrayRef<unsigned> Idxs,
2326 const Twine &NameStr = "",
2327 Instruction *InsertBefore = nullptr) {
2328 return new
2329 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2330 }
2331
2332 static ExtractValueInst *Create(Value *Agg,
2333 ArrayRef<unsigned> Idxs,
2334 const Twine &NameStr,
2335 BasicBlock *InsertAtEnd) {
2336 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2337 }
2338
2339 /// Returns the type of the element that would be extracted
2340 /// with an extractvalue instruction with the specified parameters.
2341 ///
2342 /// Null is returned if the indices are invalid for the specified type.
2343 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2344
2345 using idx_iterator = const unsigned*;
2346
2347 inline idx_iterator idx_begin() const { return Indices.begin(); }
2348 inline idx_iterator idx_end() const { return Indices.end(); }
2349 inline iterator_range<idx_iterator> indices() const {
2350 return make_range(idx_begin(), idx_end());
2351 }
2352
2353 Value *getAggregateOperand() {
2354 return getOperand(0);
2355 }
2356 const Value *getAggregateOperand() const {
2357 return getOperand(0);
2358 }
2359 static unsigned getAggregateOperandIndex() {
2360 return 0U; // get index for modifying correct operand
2361 }
2362
2363 ArrayRef<unsigned> getIndices() const {
2364 return Indices;
2365 }
2366
2367 unsigned getNumIndices() const {
2368 return (unsigned)Indices.size();
2369 }
2370
2371 bool hasIndices() const {
2372 return true;
2373 }
2374
2375 // Methods for support type inquiry through isa, cast, and dyn_cast:
2376 static bool classof(const Instruction *I) {
2377 return I->getOpcode() == Instruction::ExtractValue;
2378 }
2379 static bool classof(const Value *V) {
2380 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2381 }
2382};
2383
2384ExtractValueInst::ExtractValueInst(Value *Agg,
2385 ArrayRef<unsigned> Idxs,
2386 const Twine &NameStr,
2387 Instruction *InsertBefore)
2388 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2389 ExtractValue, Agg, InsertBefore) {
2390 init(Idxs, NameStr);
2391}
2392
2393ExtractValueInst::ExtractValueInst(Value *Agg,
2394 ArrayRef<unsigned> Idxs,
2395 const Twine &NameStr,
2396 BasicBlock *InsertAtEnd)
2397 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2398 ExtractValue, Agg, InsertAtEnd) {
2399 init(Idxs, NameStr);
2400}
2401
2402//===----------------------------------------------------------------------===//
2403// InsertValueInst Class
2404//===----------------------------------------------------------------------===//
2405
2406/// This instruction inserts a struct field of array element
2407/// value into an aggregate value.
2408///
2409class InsertValueInst : public Instruction {
2410 SmallVector<unsigned, 4> Indices;
2411
2412 InsertValueInst(const InsertValueInst &IVI);
2413
2414 /// Constructors - Create a insertvalue instruction with a base aggregate
2415 /// value, a value to insert, and a list of indices. The first ctor can
2416 /// optionally insert before an existing instruction, the second appends
2417 /// the new instruction to the specified BasicBlock.
2418 inline InsertValueInst(Value *Agg, Value *Val,
2419 ArrayRef<unsigned> Idxs,
2420 const Twine &NameStr,
2421 Instruction *InsertBefore);
2422 inline InsertValueInst(Value *Agg, Value *Val,
2423 ArrayRef<unsigned> Idxs,
2424 const Twine &NameStr, BasicBlock *InsertAtEnd);
2425
2426 /// Constructors - These two constructors are convenience methods because one
2427 /// and two index insertvalue instructions are so common.
2428 InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2429 const Twine &NameStr = "",
2430 Instruction *InsertBefore = nullptr);
2431 InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2432 BasicBlock *InsertAtEnd);
2433
2434 void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2435 const Twine &NameStr);
2436
2437protected:
2438 // Note: Instruction needs to be a friend here to call cloneImpl.
2439 friend class Instruction;
2440
2441 InsertValueInst *cloneImpl() const;
2442
2443public:
2444 // allocate space for exactly two operands
2445 void *operator new(size_t s) {
2446 return User::operator new(s, 2);
2447 }
2448
2449 static InsertValueInst *Create(Value *Agg, Value *Val,
2450 ArrayRef<unsigned> Idxs,
2451 const Twine &NameStr = "",
2452 Instruction *InsertBefore = nullptr) {
2453 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2454 }
2455
2456 static InsertValueInst *Create(Value *Agg, Value *Val,
2457 ArrayRef<unsigned> Idxs,
2458 const Twine &NameStr,
2459 BasicBlock *InsertAtEnd) {
2460 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2461 }
2462
2463 /// Transparently provide more efficient getOperand methods.
2464 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
;
2465
2466 using idx_iterator = const unsigned*;
2467
2468 inline idx_iterator idx_begin() const { return Indices.begin(); }
2469 inline idx_iterator idx_end() const { return Indices.end(); }
2470 inline iterator_range<idx_iterator> indices() const {
2471 return make_range(idx_begin(), idx_end());
2472 }
2473
2474 Value *getAggregateOperand() {
2475 return getOperand(0);
2476 }
2477 const Value *getAggregateOperand() const {
2478 return getOperand(0);
2479 }
2480 static unsigned getAggregateOperandIndex() {
2481 return 0U; // get index for modifying correct operand
2482 }
2483
2484 Value *getInsertedValueOperand() {
2485 return getOperand(1);
2486 }
2487 const Value *getInsertedValueOperand() const {
2488 return getOperand(1);
2489 }
2490 static unsigned getInsertedValueOperandIndex() {
2491 return 1U; // get index for modifying correct operand
2492 }
2493
2494 ArrayRef<unsigned> getIndices() const {
2495 return Indices;
2496 }
2497
2498 unsigned getNumIndices() const {
2499 return (unsigned)Indices.size();
2500 }
2501
2502 bool hasIndices() const {
2503 return true;
2504 }
2505
2506 // Methods for support type inquiry through isa, cast, and dyn_cast:
2507 static bool classof(const Instruction *I) {
2508 return I->getOpcode() == Instruction::InsertValue;
2509 }
2510 static bool classof(const Value *V) {
2511 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2512 }
2513};
2514
2515template <>
2516struct OperandTraits<InsertValueInst> :
2517 public FixedNumOperandTraits<InsertValueInst, 2> {
2518};
2519
2520InsertValueInst::InsertValueInst(Value *Agg,
2521 Value *Val,
2522 ArrayRef<unsigned> Idxs,
2523 const Twine &NameStr,
2524 Instruction *InsertBefore)
2525 : Instruction(Agg->getType(), InsertValue,
2526 OperandTraits<InsertValueInst>::op_begin(this),
2527 2, InsertBefore) {
2528 init(Agg, Val, Idxs, NameStr);
2529}
2530
2531InsertValueInst::InsertValueInst(Value *Agg,
2532 Value *Val,
2533 ArrayRef<unsigned> Idxs,
2534 const Twine &NameStr,
2535 BasicBlock *InsertAtEnd)
2536 : Instruction(Agg->getType(), InsertValue,
2537 OperandTraits<InsertValueInst>::op_begin(this),
2538 2, InsertAtEnd) {
2539 init(Agg, Val, Idxs, NameStr);
2540}
2541
2542DEFINE_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 { ((i_nocapture <
OperandTraits<InsertValueInst>::operands(this) &&
"getOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2542, __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) { ((
i_nocapture < OperandTraits<InsertValueInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2542, __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); }
2543
2544//===----------------------------------------------------------------------===//
2545// PHINode Class
2546//===----------------------------------------------------------------------===//
2547
2548// PHINode - The PHINode class is used to represent the magical mystical PHI
2549// node, that can not exist in nature, but can be synthesized in a computer
2550// scientist's overactive imagination.
2551//
2552class PHINode : public Instruction {
2553 /// The number of operands actually allocated. NumOperands is
2554 /// the number actually in use.
2555 unsigned ReservedSpace;
2556
2557 PHINode(const PHINode &PN);
2558
2559 explicit PHINode(Type *Ty, unsigned NumReservedValues,
2560 const Twine &NameStr = "",
2561 Instruction *InsertBefore = nullptr)
2562 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2563 ReservedSpace(NumReservedValues) {
2564 setName(NameStr);
2565 allocHungoffUses(ReservedSpace);
2566 }
2567
2568 PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2569 BasicBlock *InsertAtEnd)
2570 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2571 ReservedSpace(NumReservedValues) {
2572 setName(NameStr);
2573 allocHungoffUses(ReservedSpace);
2574 }
2575
2576protected:
2577 // Note: Instruction needs to be a friend here to call cloneImpl.
2578 friend class Instruction;
2579
2580 PHINode *cloneImpl() const;
2581
2582 // allocHungoffUses - this is more complicated than the generic
2583 // User::allocHungoffUses, because we have to allocate Uses for the incoming
2584 // values and pointers to the incoming blocks, all in one allocation.
2585 void allocHungoffUses(unsigned N) {
2586 User::allocHungoffUses(N, /* IsPhi */ true);
2587 }
2588
2589public:
2590 /// Constructors - NumReservedValues is a hint for the number of incoming
2591 /// edges that this phi node will have (use 0 if you really have no idea).
2592 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2593 const Twine &NameStr = "",
2594 Instruction *InsertBefore = nullptr) {
2595 return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2596 }
2597
2598 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2599 const Twine &NameStr, BasicBlock *InsertAtEnd) {
2600 return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2601 }
2602
2603 /// Provide fast operand accessors
2604 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
;
2605
2606 // Block iterator interface. This provides access to the list of incoming
2607 // basic blocks, which parallels the list of incoming values.
2608
2609 using block_iterator = BasicBlock **;
2610 using const_block_iterator = BasicBlock * const *;
2611
2612 block_iterator block_begin() {
2613 Use::UserRef *ref =
2614 reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2615 return reinterpret_cast<block_iterator>(ref + 1);
2616 }
2617
2618 const_block_iterator block_begin() const {
2619 const Use::UserRef *ref =
2620 reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2621 return reinterpret_cast<const_block_iterator>(ref + 1);
2622 }
2623
2624 block_iterator block_end() {
2625 return block_begin() + getNumOperands();
2626 }
2627
2628 const_block_iterator block_end() const {
2629 return block_begin() + getNumOperands();
2630 }
2631
2632 iterator_range<block_iterator> blocks() {
2633 return make_range(block_begin(), block_end());
2634 }
2635
2636 iterator_range<const_block_iterator> blocks() const {
2637 return make_range(block_begin(), block_end());
2638 }
2639
2640 op_range incoming_values() { return operands(); }
2641
2642 const_op_range incoming_values() const { return operands(); }
2643
2644 /// Return the number of incoming edges
2645 ///
2646 unsigned getNumIncomingValues() const { return getNumOperands(); }
2647
2648 /// Return incoming value number x
2649 ///
2650 Value *getIncomingValue(unsigned i) const {
2651 return getOperand(i);
2652 }
2653 void setIncomingValue(unsigned i, Value *V) {
2654 assert(V && "PHI node got a null value!")((V && "PHI node got a null value!") ? static_cast<
void> (0) : __assert_fail ("V && \"PHI node got a null value!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2654, __PRETTY_FUNCTION__))
;
2655 assert(getType() == V->getType() &&((getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node!"
) ? static_cast<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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2656, __PRETTY_FUNCTION__))
2656 "All operands to PHI node must be the same type as the PHI node!")((getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node!"
) ? static_cast<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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2656, __PRETTY_FUNCTION__))
;
2657 setOperand(i, V);
2658 }
2659
2660 static unsigned getOperandNumForIncomingValue(unsigned i) {
2661 return i;
2662 }
2663
2664 static unsigned getIncomingValueNumForOperand(unsigned i) {
2665 return i;
2666 }
2667
2668 /// Return incoming basic block number @p i.
2669 ///
2670 BasicBlock *getIncomingBlock(unsigned i) const {
2671 return block_begin()[i];
2672 }
2673
2674 /// Return incoming basic block corresponding
2675 /// to an operand of the PHI.
2676 ///
2677 BasicBlock *getIncomingBlock(const Use &U) const {
2678 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?")((this == U.getUser() && "Iterator doesn't point to PHI's Uses?"
) ? static_cast<void> (0) : __assert_fail ("this == U.getUser() && \"Iterator doesn't point to PHI's Uses?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2678, __PRETTY_FUNCTION__))
;
2679 return getIncomingBlock(unsigned(&U - op_begin()));
2680 }
2681
2682 /// Return incoming basic block corresponding
2683 /// to value use iterator.
2684 ///
2685 BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2686 return getIncomingBlock(I.getUse());
2687 }
2688
2689 void setIncomingBlock(unsigned i, BasicBlock *BB) {
2690 assert(BB && "PHI node got a null basic block!")((BB && "PHI node got a null basic block!") ? static_cast
<void> (0) : __assert_fail ("BB && \"PHI node got a null basic block!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2690, __PRETTY_FUNCTION__))
;
2691 block_begin()[i] = BB;
2692 }
2693
2694 /// Replace every incoming basic block \p Old to basic block \p New.
2695 void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New) {
2696 assert(New && Old && "PHI node got a null basic block!")((New && Old && "PHI node got a null basic block!"
) ? static_cast<void> (0) : __assert_fail ("New && Old && \"PHI node got a null basic block!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2696, __PRETTY_FUNCTION__))
;
2697 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2698 if (getIncomingBlock(Op) == Old)
2699 setIncomingBlock(Op, New);
2700 }
2701
2702 /// Add an incoming value to the end of the PHI list
2703 ///
2704 void addIncoming(Value *V, BasicBlock *BB) {
2705 if (getNumOperands() == ReservedSpace)
2706 growOperands(); // Get more space!
2707 // Initialize some new operands.
2708 setNumHungOffUseOperands(getNumOperands() + 1);
2709 setIncomingValue(getNumOperands() - 1, V);
2710 setIncomingBlock(getNumOperands() - 1, BB);
2711 }
2712
2713 /// Remove an incoming value. This is useful if a
2714 /// predecessor basic block is deleted. The value removed is returned.
2715 ///
2716 /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2717 /// is true), the PHI node is destroyed and any uses of it are replaced with
2718 /// dummy values. The only time there should be zero incoming values to a PHI
2719 /// node is when the block is dead, so this strategy is sound.
2720 ///
2721 Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2722
2723 Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2724 int Idx = getBasicBlockIndex(BB);
2725 assert(Idx >= 0 && "Invalid basic block argument to remove!")((Idx >= 0 && "Invalid basic block argument to remove!"
) ? static_cast<void> (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument to remove!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2725, __PRETTY_FUNCTION__))
;
2726 return removeIncomingValue(Idx, DeletePHIIfEmpty);
2727 }
2728
2729 /// Return the first index of the specified basic
2730 /// block in the value list for this PHI. Returns -1 if no instance.
2731 ///
2732 int getBasicBlockIndex(const BasicBlock *BB) const {
2733 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2734 if (block_begin()[i] == BB)
2735 return i;
2736 return -1;
2737 }
2738
2739 Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2740 int Idx = getBasicBlockIndex(BB);
2741 assert(Idx >= 0 && "Invalid basic block argument!")((Idx >= 0 && "Invalid basic block argument!") ? static_cast
<void> (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2741, __PRETTY_FUNCTION__))
;
2742 return getIncomingValue(Idx);
2743 }
2744
2745 /// Set every incoming value(s) for block \p BB to \p V.
2746 void setIncomingValueForBlock(const BasicBlock *BB, Value *V) {
2747 assert(BB && "PHI node got a null basic block!")((BB && "PHI node got a null basic block!") ? static_cast
<void> (0) : __assert_fail ("BB && \"PHI node got a null basic block!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2747, __PRETTY_FUNCTION__))
;
2748 bool Found = false;
2749 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2750 if (getIncomingBlock(Op) == BB) {
2751 Found = true;
2752 setIncomingValue(Op, V);
2753 }
2754 (void)Found;
2755 assert(Found && "Invalid basic block argument to set!")((Found && "Invalid basic block argument to set!") ? static_cast
<void> (0) : __assert_fail ("Found && \"Invalid basic block argument to set!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2755, __PRETTY_FUNCTION__))
;
2756 }
2757
2758 /// If the specified PHI node always merges together the
2759 /// same value, return the value, otherwise return null.
2760 Value *hasConstantValue() const;
2761
2762 /// Whether the specified PHI node always merges
2763 /// together the same value, assuming undefs are equal to a unique
2764 /// non-undef value.
2765 bool hasConstantOrUndefValue() const;
2766
2767 /// Methods for support type inquiry through isa, cast, and dyn_cast:
2768 static bool classof(const Instruction *I) {
2769 return I->getOpcode() == Instruction::PHI;
2770 }
2771 static bool classof(const Value *V) {
2772 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2773 }
2774
2775private:
2776 void growOperands();
2777};
2778
2779template <>
2780struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2781};
2782
2783DEFINE_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 { ((i_nocapture < OperandTraits<PHINode>::operands
(this) && "getOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2783, __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) { ((i_nocapture <
OperandTraits<PHINode>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2783, __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
); }
2784
2785//===----------------------------------------------------------------------===//
2786// LandingPadInst Class
2787//===----------------------------------------------------------------------===//
2788
2789//===---------------------------------------------------------------------------
2790/// The landingpad instruction holds all of the information
2791/// necessary to generate correct exception handling. The landingpad instruction
2792/// cannot be moved from the top of a landing pad block, which itself is
2793/// accessible only from the 'unwind' edge of an invoke. This uses the
2794/// SubclassData field in Value to store whether or not the landingpad is a
2795/// cleanup.
2796///
2797class LandingPadInst : public Instruction {
2798 /// The number of operands actually allocated. NumOperands is
2799 /// the number actually in use.
2800 unsigned ReservedSpace;
2801
2802 LandingPadInst(const LandingPadInst &LP);
2803
2804public:
2805 enum ClauseType { Catch, Filter };
2806
2807private:
2808 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2809 const Twine &NameStr, Instruction *InsertBefore);
2810 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2811 const Twine &NameStr, BasicBlock *InsertAtEnd);
2812
2813 // Allocate space for exactly zero operands.
2814 void *operator new(size_t s) {
2815 return User::operator new(s);
2816 }
2817
2818 void growOperands(unsigned Size);
2819 void init(unsigned NumReservedValues, const Twine &NameStr);
2820
2821protected:
2822 // Note: Instruction needs to be a friend here to call cloneImpl.
2823 friend class Instruction;
2824
2825 LandingPadInst *cloneImpl() const;
2826
2827public:
2828 /// Constructors - NumReservedClauses is a hint for the number of incoming
2829 /// clauses that this landingpad will have (use 0 if you really have no idea).
2830 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2831 const Twine &NameStr = "",
2832 Instruction *InsertBefore = nullptr);
2833 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2834 const Twine &NameStr, BasicBlock *InsertAtEnd);
2835
2836 /// Provide fast operand accessors
2837 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
;
2838
2839 /// Return 'true' if this landingpad instruction is a
2840 /// cleanup. I.e., it should be run when unwinding even if its landing pad
2841 /// doesn't catch the exception.
2842 bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2843
2844 /// Indicate that this landingpad instruction is a cleanup.
2845 void setCleanup(bool V) {
2846 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2847 (V ? 1 : 0));
2848 }
2849
2850 /// Add a catch or filter clause to the landing pad.
2851 void addClause(Constant *ClauseVal);
2852
2853 /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2854 /// determine what type of clause this is.
2855 Constant *getClause(unsigned Idx) const {
2856 return cast<Constant>(getOperandList()[Idx]);
2857 }
2858
2859 /// Return 'true' if the clause and index Idx is a catch clause.
2860 bool isCatch(unsigned Idx) const {
2861 return !isa<ArrayType>(getOperandList()[Idx]->getType());
2862 }
2863
2864 /// Return 'true' if the clause and index Idx is a filter clause.
2865 bool isFilter(unsigned Idx) const {
2866 return isa<ArrayType>(getOperandList()[Idx]->getType());
2867 }
2868
2869 /// Get the number of clauses for this landing pad.
2870 unsigned getNumClauses() const { return getNumOperands(); }
2871
2872 /// Grow the size of the operand list to accommodate the new
2873 /// number of clauses.
2874 void reserveClauses(unsigned Size) { growOperands(Size); }
2875
2876 // Methods for support type inquiry through isa, cast, and dyn_cast:
2877 static bool classof(const Instruction *I) {
2878 return I->getOpcode() == Instruction::LandingPad;
2879 }
2880 static bool classof(const Value *V) {
2881 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2882 }
2883};
2884
2885template <>
2886struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2887};
2888
2889DEFINE_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 { ((i_nocapture <
OperandTraits<LandingPadInst>::operands(this) &&
"getOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2889, __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) { ((
i_nocapture < OperandTraits<LandingPadInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2889, __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); }
2890
2891//===----------------------------------------------------------------------===//
2892// ReturnInst Class
2893//===----------------------------------------------------------------------===//
2894
2895//===---------------------------------------------------------------------------
2896/// Return a value (possibly void), from a function. Execution
2897/// does not continue in this function any longer.
2898///
2899class ReturnInst : public Instruction {
2900 ReturnInst(const ReturnInst &RI);
2901
2902private:
2903 // ReturnInst constructors:
2904 // ReturnInst() - 'ret void' instruction
2905 // ReturnInst( null) - 'ret void' instruction
2906 // ReturnInst(Value* X) - 'ret X' instruction
2907 // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2908 // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2909 // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2910 // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2911 //
2912 // NOTE: If the Value* passed is of type void then the constructor behaves as
2913 // if it was passed NULL.
2914 explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2915 Instruction *InsertBefore = nullptr);
2916 ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2917 explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2918
2919protected:
2920 // Note: Instruction needs to be a friend here to call cloneImpl.
2921 friend class Instruction;
2922
2923 ReturnInst *cloneImpl() const;
2924
2925public:
2926 static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2927 Instruction *InsertBefore = nullptr) {
2928 return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2929 }
2930
2931 static ReturnInst* Create(LLVMContext &C, Value *retVal,
2932 BasicBlock *InsertAtEnd) {
2933 return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2934 }
2935
2936 static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2937 return new(0) ReturnInst(C, InsertAtEnd);
2938 }
2939
2940 /// Provide fast operand accessors
2941 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
;
2942
2943 /// Convenience accessor. Returns null if there is no return value.
2944 Value *getReturnValue() const {
2945 return getNumOperands() != 0 ? getOperand(0) : nullptr;
2946 }
2947
2948 unsigned getNumSuccessors() const { return 0; }
2949
2950 // Methods for support type inquiry through isa, cast, and dyn_cast:
2951 static bool classof(const Instruction *I) {
2952 return (I->getOpcode() == Instruction::Ret);
2953 }
2954 static bool classof(const Value *V) {
2955 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2956 }
2957
2958private:
2959 BasicBlock *getSuccessor(unsigned idx) const {
2960 llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2960)
;
2961 }
2962
2963 void setSuccessor(unsigned idx, BasicBlock *B) {
2964 llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2964)
;
2965 }
2966};
2967
2968template <>
2969struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2970};
2971
2972DEFINE_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 { ((i_nocapture <
OperandTraits<ReturnInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2972, __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) { ((i_nocapture <
OperandTraits<ReturnInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2972, __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); }
2973
2974//===----------------------------------------------------------------------===//
2975// BranchInst Class
2976//===----------------------------------------------------------------------===//
2977
2978//===---------------------------------------------------------------------------
2979/// Conditional or Unconditional Branch instruction.
2980///
2981class BranchInst : public Instruction {
2982 /// Ops list - Branches are strange. The operands are ordered:
2983 /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
2984 /// they don't have to check for cond/uncond branchness. These are mostly
2985 /// accessed relative from op_end().
2986 BranchInst(const BranchInst &BI);
2987 // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2988 // BranchInst(BB *B) - 'br B'
2989 // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
2990 // BranchInst(BB* B, Inst *I) - 'br B' insert before I
2991 // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2992 // BranchInst(BB* B, BB *I) - 'br B' insert at end
2993 // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
2994 explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2995 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2996 Instruction *InsertBefore = nullptr);
2997 BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2998 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2999 BasicBlock *InsertAtEnd);
3000
3001 void AssertOK();
3002
3003protected:
3004 // Note: Instruction needs to be a friend here to call cloneImpl.
3005 friend class Instruction;
3006
3007 BranchInst *cloneImpl() const;
3008
3009public:
3010 /// Iterator type that casts an operand to a basic block.
3011 ///
3012 /// This only makes sense because the successors are stored as adjacent
3013 /// operands for branch instructions.
3014 struct succ_op_iterator
3015 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3016 std::random_access_iterator_tag, BasicBlock *,
3017 ptrdiff_t, BasicBlock *, BasicBlock *> {
3018 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3019
3020 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3021 BasicBlock *operator->() const { return operator*(); }
3022 };
3023
3024 /// The const version of `succ_op_iterator`.
3025 struct const_succ_op_iterator
3026 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3027 std::random_access_iterator_tag,
3028 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3029 const BasicBlock *> {
3030 explicit const_succ_op_iterator(const_value_op_iterator I)
3031 : iterator_adaptor_base(I) {}
3032
3033 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3034 const BasicBlock *operator->() const { return operator*(); }
3035 };
3036
3037 static BranchInst *Create(BasicBlock *IfTrue,
3038 Instruction *InsertBefore = nullptr) {
3039 return new(1) BranchInst(IfTrue, InsertBefore);
3040 }
3041
3042 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3043 Value *Cond, Instruction *InsertBefore = nullptr) {
3044 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3045 }
3046
3047 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3048 return new(1) BranchInst(IfTrue, InsertAtEnd);
3049 }
3050
3051 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3052 Value *Cond, BasicBlock *InsertAtEnd) {
3053 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3054 }
3055
3056 /// Transparently provide more efficient getOperand methods.
3057 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
;
3058
3059 bool isUnconditional() const { return getNumOperands() == 1; }
3060 bool isConditional() const { return getNumOperands() == 3; }
14
Assuming the condition is true
15
Returning the value 1, which participates in a condition later
3061
3062 Value *getCondition() const {
3063 assert(isConditional() && "Cannot get condition of an uncond branch!")((isConditional() && "Cannot get condition of an uncond branch!"
) ? static_cast<void> (0) : __assert_fail ("isConditional() && \"Cannot get condition of an uncond branch!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3063, __PRETTY_FUNCTION__))
;
3064 return Op<-3>();
3065 }
3066
3067 void setCondition(Value *V) {
3068 assert(isConditional() && "Cannot set condition of unconditional branch!")((isConditional() && "Cannot set condition of unconditional branch!"
) ? static_cast<void> (0) : __assert_fail ("isConditional() && \"Cannot set condition of unconditional branch!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3068, __PRETTY_FUNCTION__))
;
3069 Op<-3>() = V;
3070 }
3071
3072 unsigned getNumSuccessors() const { return 1+isConditional(); }
3073
3074 BasicBlock *getSuccessor(unsigned i) const {
3075 assert(i < getNumSuccessors() && "Successor # out of range for Branch!")((i < getNumSuccessors() && "Successor # out of range for Branch!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumSuccessors() && \"Successor # out of range for Branch!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3075, __PRETTY_FUNCTION__))
;
3076 return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3077 }
3078
3079 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3080 assert(idx < getNumSuccessors() && "Successor # out of range for Branch!")((idx < getNumSuccessors() && "Successor # out of range for Branch!"
) ? static_cast<void> (0) : __assert_fail ("idx < getNumSuccessors() && \"Successor # out of range for Branch!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3080, __PRETTY_FUNCTION__))
;
3081 *(&Op<-1>() - idx) = NewSucc;
3082 }
3083
3084 /// Swap the successors of this branch instruction.
3085 ///
3086 /// Swaps the successors of the branch instruction. This also swaps any
3087 /// branch weight metadata associated with the instruction so that it
3088 /// continues to map correctly to each operand.
3089 void swapSuccessors();
3090
3091 iterator_range<succ_op_iterator> successors() {
3092 return make_range(
3093 succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
3094 succ_op_iterator(value_op_end()));
3095 }
3096
3097 iterator_range<const_succ_op_iterator> successors() const {
3098 return make_range(const_succ_op_iterator(
3099 std::next(value_op_begin(), isConditional() ? 1 : 0)),
3100 const_succ_op_iterator(value_op_end()));
3101 }
3102
3103 // Methods for support type inquiry through isa, cast, and dyn_cast:
3104 static bool classof(const Instruction *I) {
3105 return (I->getOpcode() == Instruction::Br);
3106 }
3107 static bool classof(const Value *V) {
3108 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3109 }
3110};
3111
3112template <>
3113struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3114};
3115
3116DEFINE_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 { ((i_nocapture <
OperandTraits<BranchInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3116, __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) { ((i_nocapture <
OperandTraits<BranchInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3116, __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); }
3117
3118//===----------------------------------------------------------------------===//
3119// SwitchInst Class
3120//===----------------------------------------------------------------------===//
3121
3122//===---------------------------------------------------------------------------
3123/// Multiway switch
3124///
3125class SwitchInst : public Instruction {
3126 unsigned ReservedSpace;
3127
3128 // Operand[0] = Value to switch on
3129 // Operand[1] = Default basic block destination
3130 // Operand[2n ] = Value to match
3131 // Operand[2n+1] = BasicBlock to go to on match
3132 SwitchInst(const SwitchInst &SI);
3133
3134 /// Create a new switch instruction, specifying a value to switch on and a
3135 /// default destination. The number of additional cases can be specified here
3136 /// to make memory allocation more efficient. This constructor can also
3137 /// auto-insert before another instruction.
3138 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3139 Instruction *InsertBefore);
3140
3141 /// Create a new switch instruction, specifying a value to switch on and a
3142 /// default destination. The number of additional cases can be specified here
3143 /// to make memory allocation more efficient. This constructor also
3144 /// auto-inserts at the end of the specified BasicBlock.
3145 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3146 BasicBlock *InsertAtEnd);
3147
3148 // allocate space for exactly zero operands
3149 void *operator new(size_t s) {
3150 return User::operator new(s);
3151 }
3152
3153 void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3154 void growOperands();
3155
3156protected:
3157 // Note: Instruction needs to be a friend here to call cloneImpl.
3158 friend class Instruction;
3159
3160 SwitchInst *cloneImpl() const;
3161
3162public:
3163 // -2
3164 static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3165
3166 template <typename CaseHandleT> class CaseIteratorImpl;
3167
3168 /// A handle to a particular switch case. It exposes a convenient interface
3169 /// to both the case value and the successor block.
3170 ///
3171 /// We define this as a template and instantiate it to form both a const and
3172 /// non-const handle.
3173 template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3174 class CaseHandleImpl {
3175 // Directly befriend both const and non-const iterators.
3176 friend class SwitchInst::CaseIteratorImpl<
3177 CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3178
3179 protected:
3180 // Expose the switch type we're parameterized with to the iterator.
3181 using SwitchInstType = SwitchInstT;
3182
3183 SwitchInstT *SI;
3184 ptrdiff_t Index;
3185
3186 CaseHandleImpl() = default;
3187 CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3188
3189 public:
3190 /// Resolves case value for current case.
3191 ConstantIntT *getCaseValue() const {
3192 assert((unsigned)Index < SI->getNumCases() &&(((unsigned)Index < SI->getNumCases() && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3193, __PRETTY_FUNCTION__))
3193 "Index out the number of cases.")(((unsigned)Index < SI->getNumCases() && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3193, __PRETTY_FUNCTION__))
;
3194 return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3195 }
3196
3197 /// Resolves successor for current case.
3198 BasicBlockT *getCaseSuccessor() const {
3199 assert(((unsigned)Index < SI->getNumCases() ||((((unsigned)Index < SI->getNumCases() || (unsigned)Index
== DefaultPseudoIndex) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3201, __PRETTY_FUNCTION__))
3200 (unsigned)Index == DefaultPseudoIndex) &&((((unsigned)Index < SI->getNumCases() || (unsigned)Index
== DefaultPseudoIndex) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3201, __PRETTY_FUNCTION__))
3201 "Index out the number of cases.")((((unsigned)Index < SI->getNumCases() || (unsigned)Index
== DefaultPseudoIndex) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3201, __PRETTY_FUNCTION__))
;
3202 return SI->getSuccessor(getSuccessorIndex());
3203 }
3204
3205 /// Returns number of current case.
3206 unsigned getCaseIndex() const { return Index; }
3207
3208 /// Returns successor index for current case successor.
3209 unsigned getSuccessorIndex() const {
3210 assert(((unsigned)Index == DefaultPseudoIndex ||((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index <
SI->getNumCases()) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3212, __PRETTY_FUNCTION__))
3211 (unsigned)Index < SI->getNumCases()) &&((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index <
SI->getNumCases()) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3212, __PRETTY_FUNCTION__))
3212 "Index out the number of cases.")((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index <
SI->getNumCases()) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3212, __PRETTY_FUNCTION__))
;
3213 return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3214 }
3215
3216 bool operator==(const CaseHandleImpl &RHS) const {
3217 assert(SI == RHS.SI && "Incompatible operators.")((SI == RHS.SI && "Incompatible operators.") ? static_cast
<void> (0) : __assert_fail ("SI == RHS.SI && \"Incompatible operators.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3217, __PRETTY_FUNCTION__))
;
3218 return Index == RHS.Index;
3219 }
3220 };
3221
3222 using ConstCaseHandle =
3223 CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
3224
3225 class CaseHandle
3226 : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3227 friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
3228
3229 public:
3230 CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3231
3232 /// Sets the new value for current case.
3233 void setValue(ConstantInt *V) {
3234 assert((unsigned)Index < SI->getNumCases() &&(((unsigned)Index < SI->getNumCases() && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3235, __PRETTY_FUNCTION__))
3235 "Index out the number of cases.")(((unsigned)Index < SI->getNumCases() && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3235, __PRETTY_FUNCTION__))
;
3236 SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3237 }
3238
3239 /// Sets the new successor for current case.
3240 void setSuccessor(BasicBlock *S) {
3241 SI->setSuccessor(getSuccessorIndex(), S);
3242 }
3243 };
3244
3245 template <typename CaseHandleT>
3246 class CaseIteratorImpl
3247 : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3248 std::random_access_iterator_tag,
3249 CaseHandleT> {
3250 using SwitchInstT = typename CaseHandleT::SwitchInstType;
3251
3252 CaseHandleT Case;
3253
3254 public:
3255 /// Default constructed iterator is in an invalid state until assigned to
3256 /// a case for a particular switch.
3257 CaseIteratorImpl() = default;
3258
3259 /// Initializes case iterator for given SwitchInst and for given
3260 /// case number.
3261 CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3262
3263 /// Initializes case iterator for given SwitchInst and for given
3264 /// successor index.
3265 static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3266 unsigned SuccessorIndex) {
3267 assert(SuccessorIndex < SI->getNumSuccessors() &&((SuccessorIndex < SI->getNumSuccessors() && "Successor index # out of range!"
) ? static_cast<void> (0) : __assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3268, __PRETTY_FUNCTION__))
3268 "Successor index # out of range!")((SuccessorIndex < SI->getNumSuccessors() && "Successor index # out of range!"
) ? static_cast<void> (0) : __assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3268, __PRETTY_FUNCTION__))
;
3269 return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3270 : CaseIteratorImpl(SI, DefaultPseudoIndex);
3271 }
3272
3273 /// Support converting to the const variant. This will be a no-op for const
3274 /// variant.
3275 operator CaseIteratorImpl<ConstCaseHandle>() const {
3276 return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3277 }
3278
3279 CaseIteratorImpl &operator+=(ptrdiff_t N) {
3280 // Check index correctness after addition.
3281 // Note: Index == getNumCases() means end().
3282 assert(Case.Index + N >= 0 &&((Case.Index + N >= 0 && (unsigned)(Case.Index + N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3284, __PRETTY_FUNCTION__))
3283 (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&((Case.Index + N >= 0 && (unsigned)(Case.Index + N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3284, __PRETTY_FUNCTION__))
3284 "Case.Index out the number of cases.")((Case.Index + N >= 0 && (unsigned)(Case.Index + N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3284, __PRETTY_FUNCTION__))
;
3285 Case.Index += N;
3286 return *this;
3287 }
3288 CaseIteratorImpl &operator-=(ptrdiff_t N) {
3289 // Check index correctness after subtraction.
3290 // Note: Case.Index == getNumCases() means end().
3291 assert(Case.Index - N >= 0 &&((Case.Index - N >= 0 && (unsigned)(Case.Index - N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3293, __PRETTY_FUNCTION__))
3292 (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&((Case.Index - N >= 0 && (unsigned)(Case.Index - N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3293, __PRETTY_FUNCTION__))
3293 "Case.Index out the number of cases.")((Case.Index - N >= 0 && (unsigned)(Case.Index - N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3293, __PRETTY_FUNCTION__))
;
3294 Case.Index -= N;
3295 return *this;
3296 }
3297 ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
3298 assert(Case.SI == RHS.Case.SI && "Incompatible operators.")((Case.SI == RHS.Case.SI && "Incompatible operators."
) ? static_cast<void> (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3298, __PRETTY_FUNCTION__))
;
3299 return Case.Index - RHS.Case.Index;
3300 }
3301 bool operator==(const CaseIteratorImpl &RHS) const {
3302 return Case == RHS.Case;
3303 }
3304 bool operator<(const CaseIteratorImpl &RHS) const {
3305 assert(Case.SI == RHS.Case.SI && "Incompatible operators.")((Case.SI == RHS.Case.SI && "Incompatible operators."
) ? static_cast<void> (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 3305, __PRETTY_FUNCTION__))
;
3306 return Case.Index < RHS.Case.Index;
3307 }
3308 CaseHandleT &operator*() { return Case; }
3309 const CaseHandleT &operator*() const { return Case; }
3310 };
3311
3312 using CaseIt = CaseIteratorImpl<CaseHandle>;
3313 using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
3314
3315 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3316 unsigned NumCases,
3317 Instruction *InsertBefore = nullptr) {
3318 return new SwitchInst(Value, Default, NumCases, InsertBefore);
3319 }
3320
3321 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3322 unsigned NumCases, BasicBlock *InsertAtEnd) {
3323 return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3324 }
3325
3326 /// Provide fast operand accessors
3327 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
;
3328
3329 // Accessor Methods for Switch stmt
3330 Value *getCondition() const { return getOperand(0); }
3331 void setCondition(Value *V) { setOperand(0, V); }
3332
3333 BasicBlock *getDefaultDest() const {
3334 return cast<BasicBlock>(getOperand(1));
3335 }
3336
3337 void setDefaultDest(BasicBlock *DefaultCase) {
3338 setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3339 }
3340
3341 /// Return the number of 'cases' in this switch instruction, excluding the
3342 /// default case.
3343 unsigned getNumCases() const {
3344 return getNumOperands()/2 - 1;
3345 }
3346
3347 /// Returns a read/write iterator that points to the first case in the
3348 /// SwitchInst.
3349 CaseIt case_begin() {
3350 return CaseIt(this, 0);
3351 }
3352
3353 /// Returns a read-only iterator that points to the first case in the
3354 /// SwitchInst.
3355 ConstCaseIt case_begin() const {
3356 return ConstCaseIt(this, 0);
3357 }
3358
3359 /// Returns a read/write iterator that points one past the last in the
3360 /// SwitchInst.
3361 CaseIt case_end() {
3362 return CaseIt(this, getNumCases());
3363 }
3364
3365 /// Returns a read-only iterator that points one past the last in the
3366 /// SwitchInst.
3367 ConstCaseIt case_end() const {
3368 return ConstCaseIt(this, getNumCases());
3369 }
3370
3371 /// Iteration adapter for range-for loops.
3372 iterator_range<CaseIt> cases() {
3373 return make_range(case_begin(), case_end());
3374 }
3375
3376 /// Constant iteration adapter for range-for loops.
3377 ite