Bug Summary

File:llvm/lib/Analysis/LazyValueInfo.cpp
Warning:line 1310, column 34
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -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 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/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-12/lib/clang/12.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-12~++20200917111122+b03c2b8395b/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-09-17-195756-12974-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/LazyValueInfo.cpp

/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/LazyValueInfo.cpp

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