Bug Summary

File:llvm/lib/Analysis/LazyValueInfo.cpp
Warning:line 1421, 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 -fuse-init-array -target-cpu x86-64 -dwarf-column-info -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~+201911111502510600c19528f1809/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/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~+201911111502510600c19528f1809/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -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-2019-12-07-102640-14763-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Analysis/LazyValueInfo.cpp

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