Bug Summary

File:llvm/lib/Analysis/LazyValueInfo.cpp
Warning:line 1330, 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~++20201129111111+e987fbdd85d/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/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~++20201129111111+e987fbdd85d/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d=. -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-11-29-190409-37574-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/Analysis/LazyValueInfo.cpp

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