Bug Summary

File:llvm/lib/Transforms/Scalar/JumpThreading.cpp
Warning:line 1398, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name JumpThreading.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/lib/Transforms/Scalar -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp

1//===- JumpThreading.cpp - Thread control through conditional blocks ------===//
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 implements the Jump Threading pass.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Transforms/Scalar/JumpThreading.h"
14#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/Optional.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/Analysis/AliasAnalysis.h"
22#include "llvm/Analysis/BlockFrequencyInfo.h"
23#include "llvm/Analysis/BranchProbabilityInfo.h"
24#include "llvm/Analysis/CFG.h"
25#include "llvm/Analysis/ConstantFolding.h"
26#include "llvm/Analysis/DomTreeUpdater.h"
27#include "llvm/Analysis/GlobalsModRef.h"
28#include "llvm/Analysis/GuardUtils.h"
29#include "llvm/Analysis/InstructionSimplify.h"
30#include "llvm/Analysis/LazyValueInfo.h"
31#include "llvm/Analysis/Loads.h"
32#include "llvm/Analysis/LoopInfo.h"
33#include "llvm/Analysis/TargetLibraryInfo.h"
34#include "llvm/Analysis/ValueTracking.h"
35#include "llvm/IR/BasicBlock.h"
36#include "llvm/IR/CFG.h"
37#include "llvm/IR/Constant.h"
38#include "llvm/IR/ConstantRange.h"
39#include "llvm/IR/Constants.h"
40#include "llvm/IR/DataLayout.h"
41#include "llvm/IR/Dominators.h"
42#include "llvm/IR/Function.h"
43#include "llvm/IR/InstrTypes.h"
44#include "llvm/IR/Instruction.h"
45#include "llvm/IR/Instructions.h"
46#include "llvm/IR/IntrinsicInst.h"
47#include "llvm/IR/Intrinsics.h"
48#include "llvm/IR/LLVMContext.h"
49#include "llvm/IR/MDBuilder.h"
50#include "llvm/IR/Metadata.h"
51#include "llvm/IR/Module.h"
52#include "llvm/IR/PassManager.h"
53#include "llvm/IR/PatternMatch.h"
54#include "llvm/IR/Type.h"
55#include "llvm/IR/Use.h"
56#include "llvm/IR/User.h"
57#include "llvm/IR/Value.h"
58#include "llvm/InitializePasses.h"
59#include "llvm/Pass.h"
60#include "llvm/Support/BlockFrequency.h"
61#include "llvm/Support/BranchProbability.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/CommandLine.h"
64#include "llvm/Support/Debug.h"
65#include "llvm/Support/raw_ostream.h"
66#include "llvm/Transforms/Scalar.h"
67#include "llvm/Transforms/Utils/BasicBlockUtils.h"
68#include "llvm/Transforms/Utils/Cloning.h"
69#include "llvm/Transforms/Utils/Local.h"
70#include "llvm/Transforms/Utils/SSAUpdater.h"
71#include "llvm/Transforms/Utils/ValueMapper.h"
72#include <algorithm>
73#include <cassert>
74#include <cstddef>
75#include <cstdint>
76#include <iterator>
77#include <memory>
78#include <utility>
79
80using namespace llvm;
81using namespace jumpthreading;
82
83#define DEBUG_TYPE"jump-threading" "jump-threading"
84
85STATISTIC(NumThreads, "Number of jumps threaded")static llvm::Statistic NumThreads = {"jump-threading", "NumThreads"
, "Number of jumps threaded"}
;
86STATISTIC(NumFolds, "Number of terminators folded")static llvm::Statistic NumFolds = {"jump-threading", "NumFolds"
, "Number of terminators folded"}
;
87STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi")static llvm::Statistic NumDupes = {"jump-threading", "NumDupes"
, "Number of branch blocks duplicated to eliminate phi"}
;
88
89static cl::opt<unsigned>
90BBDuplicateThreshold("jump-threading-threshold",
91 cl::desc("Max block size to duplicate for jump threading"),
92 cl::init(6), cl::Hidden);
93
94static cl::opt<unsigned>
95ImplicationSearchThreshold(
96 "jump-threading-implication-search-threshold",
97 cl::desc("The number of predecessors to search for a stronger "
98 "condition to use to thread over a weaker condition"),
99 cl::init(3), cl::Hidden);
100
101static cl::opt<bool> PrintLVIAfterJumpThreading(
102 "print-lvi-after-jump-threading",
103 cl::desc("Print the LazyValueInfo cache after JumpThreading"), cl::init(false),
104 cl::Hidden);
105
106static cl::opt<bool> ThreadAcrossLoopHeaders(
107 "jump-threading-across-loop-headers",
108 cl::desc("Allow JumpThreading to thread across loop headers, for testing"),
109 cl::init(false), cl::Hidden);
110
111
112namespace {
113
114 /// This pass performs 'jump threading', which looks at blocks that have
115 /// multiple predecessors and multiple successors. If one or more of the
116 /// predecessors of the block can be proven to always jump to one of the
117 /// successors, we forward the edge from the predecessor to the successor by
118 /// duplicating the contents of this block.
119 ///
120 /// An example of when this can occur is code like this:
121 ///
122 /// if () { ...
123 /// X = 4;
124 /// }
125 /// if (X < 3) {
126 ///
127 /// In this case, the unconditional branch at the end of the first if can be
128 /// revectored to the false side of the second if.
129 class JumpThreading : public FunctionPass {
130 JumpThreadingPass Impl;
131
132 public:
133 static char ID; // Pass identification
134
135 JumpThreading(int T = -1) : FunctionPass(ID), Impl(T) {
136 initializeJumpThreadingPass(*PassRegistry::getPassRegistry());
137 }
138
139 bool runOnFunction(Function &F) override;
140
141 void getAnalysisUsage(AnalysisUsage &AU) const override {
142 AU.addRequired<DominatorTreeWrapperPass>();
143 AU.addPreserved<DominatorTreeWrapperPass>();
144 AU.addRequired<AAResultsWrapperPass>();
145 AU.addRequired<LazyValueInfoWrapperPass>();
146 AU.addPreserved<LazyValueInfoWrapperPass>();
147 AU.addPreserved<GlobalsAAWrapperPass>();
148 AU.addRequired<TargetLibraryInfoWrapperPass>();
149 }
150
151 void releaseMemory() override { Impl.releaseMemory(); }
152 };
153
154} // end anonymous namespace
155
156char JumpThreading::ID = 0;
157
158INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",static void *initializeJumpThreadingPassOnce(PassRegistry &
Registry) {
159 "Jump Threading", false, false)static void *initializeJumpThreadingPassOnce(PassRegistry &
Registry) {
160INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry);
161INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)initializeLazyValueInfoWrapperPassPass(Registry);
162INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
163INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)initializeAAResultsWrapperPassPass(Registry);
164INITIALIZE_PASS_END(JumpThreading, "jump-threading",PassInfo *PI = new PassInfo( "Jump Threading", "jump-threading"
, &JumpThreading::ID, PassInfo::NormalCtor_t(callDefaultCtor
<JumpThreading>), false, false); Registry.registerPass(
*PI, true); return PI; } static llvm::once_flag InitializeJumpThreadingPassFlag
; void llvm::initializeJumpThreadingPass(PassRegistry &Registry
) { llvm::call_once(InitializeJumpThreadingPassFlag, initializeJumpThreadingPassOnce
, std::ref(Registry)); }
165 "Jump Threading", false, false)PassInfo *PI = new PassInfo( "Jump Threading", "jump-threading"
, &JumpThreading::ID, PassInfo::NormalCtor_t(callDefaultCtor
<JumpThreading>), false, false); Registry.registerPass(
*PI, true); return PI; } static llvm::once_flag InitializeJumpThreadingPassFlag
; void llvm::initializeJumpThreadingPass(PassRegistry &Registry
) { llvm::call_once(InitializeJumpThreadingPassFlag, initializeJumpThreadingPassOnce
, std::ref(Registry)); }
166
167// Public interface to the Jump Threading pass
168FunctionPass *llvm::createJumpThreadingPass(int Threshold) {
169 return new JumpThreading(Threshold);
170}
171
172JumpThreadingPass::JumpThreadingPass(int T) {
173 BBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T);
174}
175
176// Update branch probability information according to conditional
177// branch probability. This is usually made possible for cloned branches
178// in inline instances by the context specific profile in the caller.
179// For instance,
180//
181// [Block PredBB]
182// [Branch PredBr]
183// if (t) {
184// Block A;
185// } else {
186// Block B;
187// }
188//
189// [Block BB]
190// cond = PN([true, %A], [..., %B]); // PHI node
191// [Branch CondBr]
192// if (cond) {
193// ... // P(cond == true) = 1%
194// }
195//
196// Here we know that when block A is taken, cond must be true, which means
197// P(cond == true | A) = 1
198//
199// Given that P(cond == true) = P(cond == true | A) * P(A) +
200// P(cond == true | B) * P(B)
201// we get:
202// P(cond == true ) = P(A) + P(cond == true | B) * P(B)
203//
204// which gives us:
205// P(A) is less than P(cond == true), i.e.
206// P(t == true) <= P(cond == true)
207//
208// In other words, if we know P(cond == true) is unlikely, we know
209// that P(t == true) is also unlikely.
210//
211static void updatePredecessorProfileMetadata(PHINode *PN, BasicBlock *BB) {
212 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
213 if (!CondBr)
214 return;
215
216 BranchProbability BP;
217 uint64_t TrueWeight, FalseWeight;
218 if (!CondBr->extractProfMetadata(TrueWeight, FalseWeight))
219 return;
220
221 // Returns the outgoing edge of the dominating predecessor block
222 // that leads to the PhiNode's incoming block:
223 auto GetPredOutEdge =
224 [](BasicBlock *IncomingBB,
225 BasicBlock *PhiBB) -> std::pair<BasicBlock *, BasicBlock *> {
226 auto *PredBB = IncomingBB;
227 auto *SuccBB = PhiBB;
228 SmallPtrSet<BasicBlock *, 16> Visited;
229 while (true) {
230 BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
231 if (PredBr && PredBr->isConditional())
232 return {PredBB, SuccBB};
233 Visited.insert(PredBB);
234 auto *SinglePredBB = PredBB->getSinglePredecessor();
235 if (!SinglePredBB)
236 return {nullptr, nullptr};
237
238 // Stop searching when SinglePredBB has been visited. It means we see
239 // an unreachable loop.
240 if (Visited.count(SinglePredBB))
241 return {nullptr, nullptr};
242
243 SuccBB = PredBB;
244 PredBB = SinglePredBB;
245 }
246 };
247
248 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
249 Value *PhiOpnd = PN->getIncomingValue(i);
250 ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd);
251
252 if (!CI || !CI->getType()->isIntegerTy(1))
253 continue;
254
255 BP = (CI->isOne() ? BranchProbability::getBranchProbability(
256 TrueWeight, TrueWeight + FalseWeight)
257 : BranchProbability::getBranchProbability(
258 FalseWeight, TrueWeight + FalseWeight));
259
260 auto PredOutEdge = GetPredOutEdge(PN->getIncomingBlock(i), BB);
261 if (!PredOutEdge.first)
262 return;
263
264 BasicBlock *PredBB = PredOutEdge.first;
265 BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
266 if (!PredBr)
267 return;
268
269 uint64_t PredTrueWeight, PredFalseWeight;
270 // FIXME: We currently only set the profile data when it is missing.
271 // With PGO, this can be used to refine even existing profile data with
272 // context information. This needs to be done after more performance
273 // testing.
274 if (PredBr->extractProfMetadata(PredTrueWeight, PredFalseWeight))
275 continue;
276
277 // We can not infer anything useful when BP >= 50%, because BP is the
278 // upper bound probability value.
279 if (BP >= BranchProbability(50, 100))
280 continue;
281
282 SmallVector<uint32_t, 2> Weights;
283 if (PredBr->getSuccessor(0) == PredOutEdge.second) {
284 Weights.push_back(BP.getNumerator());
285 Weights.push_back(BP.getCompl().getNumerator());
286 } else {
287 Weights.push_back(BP.getCompl().getNumerator());
288 Weights.push_back(BP.getNumerator());
289 }
290 PredBr->setMetadata(LLVMContext::MD_prof,
291 MDBuilder(PredBr->getParent()->getContext())
292 .createBranchWeights(Weights));
293 }
294}
295
296/// runOnFunction - Toplevel algorithm.
297bool JumpThreading::runOnFunction(Function &F) {
298 if (skipFunction(F))
299 return false;
300 auto TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
301 // Get DT analysis before LVI. When LVI is initialized it conditionally adds
302 // DT if it's available.
303 auto DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
304 auto LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
305 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
306 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy);
307 std::unique_ptr<BlockFrequencyInfo> BFI;
308 std::unique_ptr<BranchProbabilityInfo> BPI;
309 if (F.hasProfileData()) {
310 LoopInfo LI{DominatorTree(F)};
311 BPI.reset(new BranchProbabilityInfo(F, LI, TLI));
312 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
313 }
314
315 bool Changed = Impl.runImpl(F, TLI, LVI, AA, &DTU, F.hasProfileData(),
316 std::move(BFI), std::move(BPI));
317 if (PrintLVIAfterJumpThreading) {
318 dbgs() << "LVI for function '" << F.getName() << "':\n";
319 LVI->printLVI(F, *DT, dbgs());
320 }
321 return Changed;
322}
323
324PreservedAnalyses JumpThreadingPass::run(Function &F,
325 FunctionAnalysisManager &AM) {
326 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
327 // Get DT analysis before LVI. When LVI is initialized it conditionally adds
328 // DT if it's available.
329 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
330 auto &LVI = AM.getResult<LazyValueAnalysis>(F);
331 auto &AA = AM.getResult<AAManager>(F);
332 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
333
334 std::unique_ptr<BlockFrequencyInfo> BFI;
335 std::unique_ptr<BranchProbabilityInfo> BPI;
336 if (F.hasProfileData()) {
337 LoopInfo LI{DominatorTree(F)};
338 BPI.reset(new BranchProbabilityInfo(F, LI, &TLI));
339 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
340 }
341
342 bool Changed = runImpl(F, &TLI, &LVI, &AA, &DTU, F.hasProfileData(),
343 std::move(BFI), std::move(BPI));
344
345 if (!Changed)
346 return PreservedAnalyses::all();
347 PreservedAnalyses PA;
348 PA.preserve<GlobalsAA>();
349 PA.preserve<DominatorTreeAnalysis>();
350 PA.preserve<LazyValueAnalysis>();
351 return PA;
352}
353
354bool JumpThreadingPass::runImpl(Function &F, TargetLibraryInfo *TLI_,
355 LazyValueInfo *LVI_, AliasAnalysis *AA_,
356 DomTreeUpdater *DTU_, bool HasProfileData_,
357 std::unique_ptr<BlockFrequencyInfo> BFI_,
358 std::unique_ptr<BranchProbabilityInfo> BPI_) {
359 LLVM_DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "Jump threading on function '"
<< F.getName() << "'\n"; } } while (false)
;
360 TLI = TLI_;
361 LVI = LVI_;
362 AA = AA_;
363 DTU = DTU_;
364 BFI.reset();
365 BPI.reset();
366 // When profile data is available, we need to update edge weights after
367 // successful jump threading, which requires both BPI and BFI being available.
368 HasProfileData = HasProfileData_;
369 auto *GuardDecl = F.getParent()->getFunction(
370 Intrinsic::getName(Intrinsic::experimental_guard));
371 HasGuards = GuardDecl && !GuardDecl->use_empty();
372 if (HasProfileData) {
373 BPI = std::move(BPI_);
374 BFI = std::move(BFI_);
375 }
376
377 // JumpThreading must not processes blocks unreachable from entry. It's a
378 // waste of compute time and can potentially lead to hangs.
379 SmallPtrSet<BasicBlock *, 16> Unreachable;
380 assert(DTU && "DTU isn't passed into JumpThreading before using it.")((DTU && "DTU isn't passed into JumpThreading before using it."
) ? static_cast<void> (0) : __assert_fail ("DTU && \"DTU isn't passed into JumpThreading before using it.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 380, __PRETTY_FUNCTION__))
;
381 assert(DTU->hasDomTree() && "JumpThreading relies on DomTree to proceed.")((DTU->hasDomTree() && "JumpThreading relies on DomTree to proceed."
) ? static_cast<void> (0) : __assert_fail ("DTU->hasDomTree() && \"JumpThreading relies on DomTree to proceed.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 381, __PRETTY_FUNCTION__))
;
382 DominatorTree &DT = DTU->getDomTree();
383 for (auto &BB : F)
384 if (!DT.isReachableFromEntry(&BB))
385 Unreachable.insert(&BB);
386
387 if (!ThreadAcrossLoopHeaders)
388 FindLoopHeaders(F);
389
390 bool EverChanged = false;
391 bool Changed;
392 do {
393 Changed = false;
394 for (auto &BB : F) {
395 if (Unreachable.count(&BB))
396 continue;
397 while (ProcessBlock(&BB)) // Thread all of the branches we can over BB.
398 Changed = true;
399 // Stop processing BB if it's the entry or is now deleted. The following
400 // routines attempt to eliminate BB and locating a suitable replacement
401 // for the entry is non-trivial.
402 if (&BB == &F.getEntryBlock() || DTU->isBBPendingDeletion(&BB))
403 continue;
404
405 if (pred_empty(&BB)) {
406 // When ProcessBlock makes BB unreachable it doesn't bother to fix up
407 // the instructions in it. We must remove BB to prevent invalid IR.
408 LLVM_DEBUG(dbgs() << " JT: Deleting dead block '" << BB.getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " JT: Deleting dead block '"
<< BB.getName() << "' with terminator: " <<
*BB.getTerminator() << '\n'; } } while (false)
409 << "' with terminator: " << *BB.getTerminator()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " JT: Deleting dead block '"
<< BB.getName() << "' with terminator: " <<
*BB.getTerminator() << '\n'; } } while (false)
410 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " JT: Deleting dead block '"
<< BB.getName() << "' with terminator: " <<
*BB.getTerminator() << '\n'; } } while (false)
;
411 LoopHeaders.erase(&BB);
412 LVI->eraseBlock(&BB);
413 DeleteDeadBlock(&BB, DTU);
414 Changed = true;
415 continue;
416 }
417
418 // ProcessBlock doesn't thread BBs with unconditional TIs. However, if BB
419 // is "almost empty", we attempt to merge BB with its sole successor.
420 auto *BI = dyn_cast<BranchInst>(BB.getTerminator());
421 if (BI && BI->isUnconditional() &&
422 // The terminator must be the only non-phi instruction in BB.
423 BB.getFirstNonPHIOrDbg()->isTerminator() &&
424 // Don't alter Loop headers and latches to ensure another pass can
425 // detect and transform nested loops later.
426 !LoopHeaders.count(&BB) && !LoopHeaders.count(BI->getSuccessor(0)) &&
427 TryToSimplifyUncondBranchFromEmptyBlock(&BB, DTU)) {
428 // BB is valid for cleanup here because we passed in DTU. F remains
429 // BB's parent until a DTU->getDomTree() event.
430 LVI->eraseBlock(&BB);
431 Changed = true;
432 }
433 }
434 EverChanged |= Changed;
435 } while (Changed);
436
437 LoopHeaders.clear();
438 // Flush only the Dominator Tree.
439 DTU->getDomTree();
440 LVI->enableDT();
441 return EverChanged;
442}
443
444// Replace uses of Cond with ToVal when safe to do so. If all uses are
445// replaced, we can remove Cond. We cannot blindly replace all uses of Cond
446// because we may incorrectly replace uses when guards/assumes are uses of
447// of `Cond` and we used the guards/assume to reason about the `Cond` value
448// at the end of block. RAUW unconditionally replaces all uses
449// including the guards/assumes themselves and the uses before the
450// guard/assume.
451static void ReplaceFoldableUses(Instruction *Cond, Value *ToVal) {
452 assert(Cond->getType() == ToVal->getType())((Cond->getType() == ToVal->getType()) ? static_cast<
void> (0) : __assert_fail ("Cond->getType() == ToVal->getType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 452, __PRETTY_FUNCTION__))
;
453 auto *BB = Cond->getParent();
454 // We can unconditionally replace all uses in non-local blocks (i.e. uses
455 // strictly dominated by BB), since LVI information is true from the
456 // terminator of BB.
457 replaceNonLocalUsesWith(Cond, ToVal);
458 for (Instruction &I : reverse(*BB)) {
459 // Reached the Cond whose uses we are trying to replace, so there are no
460 // more uses.
461 if (&I == Cond)
462 break;
463 // We only replace uses in instructions that are guaranteed to reach the end
464 // of BB, where we know Cond is ToVal.
465 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
466 break;
467 I.replaceUsesOfWith(Cond, ToVal);
468 }
469 if (Cond->use_empty() && !Cond->mayHaveSideEffects())
470 Cond->eraseFromParent();
471}
472
473/// Return the cost of duplicating a piece of this block from first non-phi
474/// and before StopAt instruction to thread across it. Stop scanning the block
475/// when exceeding the threshold. If duplication is impossible, returns ~0U.
476static unsigned getJumpThreadDuplicationCost(BasicBlock *BB,
477 Instruction *StopAt,
478 unsigned Threshold) {
479 assert(StopAt->getParent() == BB && "Not an instruction from proper BB?")((StopAt->getParent() == BB && "Not an instruction from proper BB?"
) ? static_cast<void> (0) : __assert_fail ("StopAt->getParent() == BB && \"Not an instruction from proper BB?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 479, __PRETTY_FUNCTION__))
;
480 /// Ignore PHI nodes, these will be flattened when duplication happens.
481 BasicBlock::const_iterator I(BB->getFirstNonPHI());
482
483 // FIXME: THREADING will delete values that are just used to compute the
484 // branch, so they shouldn't count against the duplication cost.
485
486 unsigned Bonus = 0;
487 if (BB->getTerminator() == StopAt) {
488 // Threading through a switch statement is particularly profitable. If this
489 // block ends in a switch, decrease its cost to make it more likely to
490 // happen.
491 if (isa<SwitchInst>(StopAt))
492 Bonus = 6;
493
494 // The same holds for indirect branches, but slightly more so.
495 if (isa<IndirectBrInst>(StopAt))
496 Bonus = 8;
497 }
498
499 // Bump the threshold up so the early exit from the loop doesn't skip the
500 // terminator-based Size adjustment at the end.
501 Threshold += Bonus;
502
503 // Sum up the cost of each instruction until we get to the terminator. Don't
504 // include the terminator because the copy won't include it.
505 unsigned Size = 0;
506 for (; &*I != StopAt; ++I) {
507
508 // Stop scanning the block if we've reached the threshold.
509 if (Size > Threshold)
510 return Size;
511
512 // Debugger intrinsics don't incur code size.
513 if (isa<DbgInfoIntrinsic>(I)) continue;
514
515 // If this is a pointer->pointer bitcast, it is free.
516 if (isa<BitCastInst>(I) && I->getType()->isPointerTy())
517 continue;
518
519 // Bail out if this instruction gives back a token type, it is not possible
520 // to duplicate it if it is used outside this BB.
521 if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB))
522 return ~0U;
523
524 // All other instructions count for at least one unit.
525 ++Size;
526
527 // Calls are more expensive. If they are non-intrinsic calls, we model them
528 // as having cost of 4. If they are a non-vector intrinsic, we model them
529 // as having cost of 2 total, and if they are a vector intrinsic, we model
530 // them as having cost 1.
531 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
532 if (CI->cannotDuplicate() || CI->isConvergent())
533 // Blocks with NoDuplicate are modelled as having infinite cost, so they
534 // are never duplicated.
535 return ~0U;
536 else if (!isa<IntrinsicInst>(CI))
537 Size += 3;
538 else if (!CI->getType()->isVectorTy())
539 Size += 1;
540 }
541 }
542
543 return Size > Bonus ? Size - Bonus : 0;
544}
545
546/// FindLoopHeaders - We do not want jump threading to turn proper loop
547/// structures into irreducible loops. Doing this breaks up the loop nesting
548/// hierarchy and pessimizes later transformations. To prevent this from
549/// happening, we first have to find the loop headers. Here we approximate this
550/// by finding targets of backedges in the CFG.
551///
552/// Note that there definitely are cases when we want to allow threading of
553/// edges across a loop header. For example, threading a jump from outside the
554/// loop (the preheader) to an exit block of the loop is definitely profitable.
555/// It is also almost always profitable to thread backedges from within the loop
556/// to exit blocks, and is often profitable to thread backedges to other blocks
557/// within the loop (forming a nested loop). This simple analysis is not rich
558/// enough to track all of these properties and keep it up-to-date as the CFG
559/// mutates, so we don't allow any of these transformations.
560void JumpThreadingPass::FindLoopHeaders(Function &F) {
561 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
562 FindFunctionBackedges(F, Edges);
563
564 for (const auto &Edge : Edges)
565 LoopHeaders.insert(Edge.second);
566}
567
568/// getKnownConstant - Helper method to determine if we can thread over a
569/// terminator with the given value as its condition, and if so what value to
570/// use for that. What kind of value this is depends on whether we want an
571/// integer or a block address, but an undef is always accepted.
572/// Returns null if Val is null or not an appropriate constant.
573static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
574 if (!Val)
575 return nullptr;
576
577 // Undef is "known" enough.
578 if (UndefValue *U = dyn_cast<UndefValue>(Val))
579 return U;
580
581 if (Preference == WantBlockAddress)
582 return dyn_cast<BlockAddress>(Val->stripPointerCasts());
583
584 return dyn_cast<ConstantInt>(Val);
585}
586
587/// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
588/// if we can infer that the value is a known ConstantInt/BlockAddress or undef
589/// in any of our predecessors. If so, return the known list of value and pred
590/// BB in the result vector.
591///
592/// This returns true if there were any known values.
593bool JumpThreadingPass::ComputeValueKnownInPredecessorsImpl(
594 Value *V, BasicBlock *BB, PredValueInfo &Result,
595 ConstantPreference Preference,
596 DenseSet<std::pair<Value *, BasicBlock *>> &RecursionSet,
597 Instruction *CxtI) {
598 // This method walks up use-def chains recursively. Because of this, we could
599 // get into an infinite loop going around loops in the use-def chain. To
600 // prevent this, keep track of what (value, block) pairs we've already visited
601 // and terminate the search if we loop back to them
602 if (!RecursionSet.insert(std::make_pair(V, BB)).second)
603 return false;
604
605 // If V is a constant, then it is known in all predecessors.
606 if (Constant *KC = getKnownConstant(V, Preference)) {
607 for (BasicBlock *Pred : predecessors(BB))
608 Result.push_back(std::make_pair(KC, Pred));
609
610 return !Result.empty();
611 }
612
613 // If V is a non-instruction value, or an instruction in a different block,
614 // then it can't be derived from a PHI.
615 Instruction *I = dyn_cast<Instruction>(V);
616 if (!I || I->getParent() != BB) {
617
618 // Okay, if this is a live-in value, see if it has a known value at the end
619 // of any of our predecessors.
620 //
621 // FIXME: This should be an edge property, not a block end property.
622 /// TODO: Per PR2563, we could infer value range information about a
623 /// predecessor based on its terminator.
624 //
625 // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
626 // "I" is a non-local compare-with-a-constant instruction. This would be
627 // able to handle value inequalities better, for example if the compare is
628 // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
629 // Perhaps getConstantOnEdge should be smart enough to do this?
630
631 if (DTU->hasPendingDomTreeUpdates())
632 LVI->disableDT();
633 else
634 LVI->enableDT();
635 for (BasicBlock *P : predecessors(BB)) {
636 // If the value is known by LazyValueInfo to be a constant in a
637 // predecessor, use that information to try to thread this block.
638 Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI);
639 if (Constant *KC = getKnownConstant(PredCst, Preference))
640 Result.push_back(std::make_pair(KC, P));
641 }
642
643 return !Result.empty();
644 }
645
646 /// If I is a PHI node, then we know the incoming values for any constants.
647 if (PHINode *PN = dyn_cast<PHINode>(I)) {
648 if (DTU->hasPendingDomTreeUpdates())
649 LVI->disableDT();
650 else
651 LVI->enableDT();
652 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
653 Value *InVal = PN->getIncomingValue(i);
654 if (Constant *KC = getKnownConstant(InVal, Preference)) {
655 Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
656 } else {
657 Constant *CI = LVI->getConstantOnEdge(InVal,
658 PN->getIncomingBlock(i),
659 BB, CxtI);
660 if (Constant *KC = getKnownConstant(CI, Preference))
661 Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
662 }
663 }
664
665 return !Result.empty();
666 }
667
668 // Handle Cast instructions. Only see through Cast when the source operand is
669 // PHI or Cmp to save the compilation time.
670 if (CastInst *CI = dyn_cast<CastInst>(I)) {
671 Value *Source = CI->getOperand(0);
672 if (!isa<PHINode>(Source) && !isa<CmpInst>(Source))
673 return false;
674 ComputeValueKnownInPredecessorsImpl(Source, BB, Result, Preference,
675 RecursionSet, CxtI);
676 if (Result.empty())
677 return false;
678
679 // Convert the known values.
680 for (auto &R : Result)
681 R.first = ConstantExpr::getCast(CI->getOpcode(), R.first, CI->getType());
682
683 return true;
684 }
685
686 // Handle some boolean conditions.
687 if (I->getType()->getPrimitiveSizeInBits() == 1) {
688 assert(Preference == WantInteger && "One-bit non-integer type?")((Preference == WantInteger && "One-bit non-integer type?"
) ? static_cast<void> (0) : __assert_fail ("Preference == WantInteger && \"One-bit non-integer type?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 688, __PRETTY_FUNCTION__))
;
689 // X | true -> true
690 // X & false -> false
691 if (I->getOpcode() == Instruction::Or ||
692 I->getOpcode() == Instruction::And) {
693 PredValueInfoTy LHSVals, RHSVals;
694
695 ComputeValueKnownInPredecessorsImpl(I->getOperand(0), BB, LHSVals,
696 WantInteger, RecursionSet, CxtI);
697 ComputeValueKnownInPredecessorsImpl(I->getOperand(1), BB, RHSVals,
698 WantInteger, RecursionSet, CxtI);
699
700 if (LHSVals.empty() && RHSVals.empty())
701 return false;
702
703 ConstantInt *InterestingVal;
704 if (I->getOpcode() == Instruction::Or)
705 InterestingVal = ConstantInt::getTrue(I->getContext());
706 else
707 InterestingVal = ConstantInt::getFalse(I->getContext());
708
709 SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
710
711 // Scan for the sentinel. If we find an undef, force it to the
712 // interesting value: x|undef -> true and x&undef -> false.
713 for (const auto &LHSVal : LHSVals)
714 if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) {
715 Result.emplace_back(InterestingVal, LHSVal.second);
716 LHSKnownBBs.insert(LHSVal.second);
717 }
718 for (const auto &RHSVal : RHSVals)
719 if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) {
720 // If we already inferred a value for this block on the LHS, don't
721 // re-add it.
722 if (!LHSKnownBBs.count(RHSVal.second))
723 Result.emplace_back(InterestingVal, RHSVal.second);
724 }
725
726 return !Result.empty();
727 }
728
729 // Handle the NOT form of XOR.
730 if (I->getOpcode() == Instruction::Xor &&
731 isa<ConstantInt>(I->getOperand(1)) &&
732 cast<ConstantInt>(I->getOperand(1))->isOne()) {
733 ComputeValueKnownInPredecessorsImpl(I->getOperand(0), BB, Result,
734 WantInteger, RecursionSet, CxtI);
735 if (Result.empty())
736 return false;
737
738 // Invert the known values.
739 for (auto &R : Result)
740 R.first = ConstantExpr::getNot(R.first);
741
742 return true;
743 }
744
745 // Try to simplify some other binary operator values.
746 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
747 assert(Preference != WantBlockAddress((Preference != WantBlockAddress && "A binary operator creating a block address?"
) ? static_cast<void> (0) : __assert_fail ("Preference != WantBlockAddress && \"A binary operator creating a block address?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 748, __PRETTY_FUNCTION__))
748 && "A binary operator creating a block address?")((Preference != WantBlockAddress && "A binary operator creating a block address?"
) ? static_cast<void> (0) : __assert_fail ("Preference != WantBlockAddress && \"A binary operator creating a block address?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 748, __PRETTY_FUNCTION__))
;
749 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
750 PredValueInfoTy LHSVals;
751 ComputeValueKnownInPredecessorsImpl(BO->getOperand(0), BB, LHSVals,
752 WantInteger, RecursionSet, CxtI);
753
754 // Try to use constant folding to simplify the binary operator.
755 for (const auto &LHSVal : LHSVals) {
756 Constant *V = LHSVal.first;
757 Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
758
759 if (Constant *KC = getKnownConstant(Folded, WantInteger))
760 Result.push_back(std::make_pair(KC, LHSVal.second));
761 }
762 }
763
764 return !Result.empty();
765 }
766
767 // Handle compare with phi operand, where the PHI is defined in this block.
768 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
769 assert(Preference == WantInteger && "Compares only produce integers")((Preference == WantInteger && "Compares only produce integers"
) ? static_cast<void> (0) : __assert_fail ("Preference == WantInteger && \"Compares only produce integers\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 769, __PRETTY_FUNCTION__))
;
770 Type *CmpType = Cmp->getType();
771 Value *CmpLHS = Cmp->getOperand(0);
772 Value *CmpRHS = Cmp->getOperand(1);
773 CmpInst::Predicate Pred = Cmp->getPredicate();
774
775 PHINode *PN = dyn_cast<PHINode>(CmpLHS);
776 if (!PN)
777 PN = dyn_cast<PHINode>(CmpRHS);
778 if (PN && PN->getParent() == BB) {
779 const DataLayout &DL = PN->getModule()->getDataLayout();
780 // We can do this simplification if any comparisons fold to true or false.
781 // See if any do.
782 if (DTU->hasPendingDomTreeUpdates())
783 LVI->disableDT();
784 else
785 LVI->enableDT();
786 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
787 BasicBlock *PredBB = PN->getIncomingBlock(i);
788 Value *LHS, *RHS;
789 if (PN == CmpLHS) {
790 LHS = PN->getIncomingValue(i);
791 RHS = CmpRHS->DoPHITranslation(BB, PredBB);
792 } else {
793 LHS = CmpLHS->DoPHITranslation(BB, PredBB);
794 RHS = PN->getIncomingValue(i);
795 }
796 Value *Res = SimplifyCmpInst(Pred, LHS, RHS, {DL});
797 if (!Res) {
798 if (!isa<Constant>(RHS))
799 continue;
800
801 // getPredicateOnEdge call will make no sense if LHS is defined in BB.
802 auto LHSInst = dyn_cast<Instruction>(LHS);
803 if (LHSInst && LHSInst->getParent() == BB)
804 continue;
805
806 LazyValueInfo::Tristate
807 ResT = LVI->getPredicateOnEdge(Pred, LHS,
808 cast<Constant>(RHS), PredBB, BB,
809 CxtI ? CxtI : Cmp);
810 if (ResT == LazyValueInfo::Unknown)
811 continue;
812 Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
813 }
814
815 if (Constant *KC = getKnownConstant(Res, WantInteger))
816 Result.push_back(std::make_pair(KC, PredBB));
817 }
818
819 return !Result.empty();
820 }
821
822 // If comparing a live-in value against a constant, see if we know the
823 // live-in value on any predecessors.
824 if (isa<Constant>(CmpRHS) && !CmpType->isVectorTy()) {
825 Constant *CmpConst = cast<Constant>(CmpRHS);
826
827 if (!isa<Instruction>(CmpLHS) ||
828 cast<Instruction>(CmpLHS)->getParent() != BB) {
829 if (DTU->hasPendingDomTreeUpdates())
830 LVI->disableDT();
831 else
832 LVI->enableDT();
833 for (BasicBlock *P : predecessors(BB)) {
834 // If the value is known by LazyValueInfo to be a constant in a
835 // predecessor, use that information to try to thread this block.
836 LazyValueInfo::Tristate Res =
837 LVI->getPredicateOnEdge(Pred, CmpLHS,
838 CmpConst, P, BB, CxtI ? CxtI : Cmp);
839 if (Res == LazyValueInfo::Unknown)
840 continue;
841
842 Constant *ResC = ConstantInt::get(CmpType, Res);
843 Result.push_back(std::make_pair(ResC, P));
844 }
845
846 return !Result.empty();
847 }
848
849 // InstCombine can fold some forms of constant range checks into
850 // (icmp (add (x, C1)), C2). See if we have we have such a thing with
851 // x as a live-in.
852 {
853 using namespace PatternMatch;
854
855 Value *AddLHS;
856 ConstantInt *AddConst;
857 if (isa<ConstantInt>(CmpConst) &&
858 match(CmpLHS, m_Add(m_Value(AddLHS), m_ConstantInt(AddConst)))) {
859 if (!isa<Instruction>(AddLHS) ||
860 cast<Instruction>(AddLHS)->getParent() != BB) {
861 if (DTU->hasPendingDomTreeUpdates())
862 LVI->disableDT();
863 else
864 LVI->enableDT();
865 for (BasicBlock *P : predecessors(BB)) {
866 // If the value is known by LazyValueInfo to be a ConstantRange in
867 // a predecessor, use that information to try to thread this
868 // block.
869 ConstantRange CR = LVI->getConstantRangeOnEdge(
870 AddLHS, P, BB, CxtI ? CxtI : cast<Instruction>(CmpLHS));
871 // Propagate the range through the addition.
872 CR = CR.add(AddConst->getValue());
873
874 // Get the range where the compare returns true.
875 ConstantRange CmpRange = ConstantRange::makeExactICmpRegion(
876 Pred, cast<ConstantInt>(CmpConst)->getValue());
877
878 Constant *ResC;
879 if (CmpRange.contains(CR))
880 ResC = ConstantInt::getTrue(CmpType);
881 else if (CmpRange.inverse().contains(CR))
882 ResC = ConstantInt::getFalse(CmpType);
883 else
884 continue;
885
886 Result.push_back(std::make_pair(ResC, P));
887 }
888
889 return !Result.empty();
890 }
891 }
892 }
893
894 // Try to find a constant value for the LHS of a comparison,
895 // and evaluate it statically if we can.
896 PredValueInfoTy LHSVals;
897 ComputeValueKnownInPredecessorsImpl(I->getOperand(0), BB, LHSVals,
898 WantInteger, RecursionSet, CxtI);
899
900 for (const auto &LHSVal : LHSVals) {
901 Constant *V = LHSVal.first;
902 Constant *Folded = ConstantExpr::getCompare(Pred, V, CmpConst);
903 if (Constant *KC = getKnownConstant(Folded, WantInteger))
904 Result.push_back(std::make_pair(KC, LHSVal.second));
905 }
906
907 return !Result.empty();
908 }
909 }
910
911 if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
912 // Handle select instructions where at least one operand is a known constant
913 // and we can figure out the condition value for any predecessor block.
914 Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
915 Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
916 PredValueInfoTy Conds;
917 if ((TrueVal || FalseVal) &&
918 ComputeValueKnownInPredecessorsImpl(SI->getCondition(), BB, Conds,
919 WantInteger, RecursionSet, CxtI)) {
920 for (auto &C : Conds) {
921 Constant *Cond = C.first;
922
923 // Figure out what value to use for the condition.
924 bool KnownCond;
925 if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
926 // A known boolean.
927 KnownCond = CI->isOne();
928 } else {
929 assert(isa<UndefValue>(Cond) && "Unexpected condition value")((isa<UndefValue>(Cond) && "Unexpected condition value"
) ? static_cast<void> (0) : __assert_fail ("isa<UndefValue>(Cond) && \"Unexpected condition value\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 929, __PRETTY_FUNCTION__))
;
930 // Either operand will do, so be sure to pick the one that's a known
931 // constant.
932 // FIXME: Do this more cleverly if both values are known constants?
933 KnownCond = (TrueVal != nullptr);
934 }
935
936 // See if the select has a known constant value for this predecessor.
937 if (Constant *Val = KnownCond ? TrueVal : FalseVal)
938 Result.push_back(std::make_pair(Val, C.second));
939 }
940
941 return !Result.empty();
942 }
943 }
944
945 // If all else fails, see if LVI can figure out a constant value for us.
946 if (DTU->hasPendingDomTreeUpdates())
947 LVI->disableDT();
948 else
949 LVI->enableDT();
950 Constant *CI = LVI->getConstant(V, BB, CxtI);
951 if (Constant *KC = getKnownConstant(CI, Preference)) {
952 for (BasicBlock *Pred : predecessors(BB))
953 Result.push_back(std::make_pair(KC, Pred));
954 }
955
956 return !Result.empty();
957}
958
959/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
960/// in an undefined jump, decide which block is best to revector to.
961///
962/// Since we can pick an arbitrary destination, we pick the successor with the
963/// fewest predecessors. This should reduce the in-degree of the others.
964static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
965 Instruction *BBTerm = BB->getTerminator();
966 unsigned MinSucc = 0;
967 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
968 // Compute the successor with the minimum number of predecessors.
969 unsigned MinNumPreds = pred_size(TestBB);
970 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
971 TestBB = BBTerm->getSuccessor(i);
972 unsigned NumPreds = pred_size(TestBB);
973 if (NumPreds < MinNumPreds) {
974 MinSucc = i;
975 MinNumPreds = NumPreds;
976 }
977 }
978
979 return MinSucc;
980}
981
982static bool hasAddressTakenAndUsed(BasicBlock *BB) {
983 if (!BB->hasAddressTaken()) return false;
984
985 // If the block has its address taken, it may be a tree of dead constants
986 // hanging off of it. These shouldn't keep the block alive.
987 BlockAddress *BA = BlockAddress::get(BB);
988 BA->removeDeadConstantUsers();
989 return !BA->use_empty();
990}
991
992/// ProcessBlock - If there are any predecessors whose control can be threaded
993/// through to a successor, transform them now.
994bool JumpThreadingPass::ProcessBlock(BasicBlock *BB) {
995 // If the block is trivially dead, just return and let the caller nuke it.
996 // This simplifies other transformations.
997 if (DTU->isBBPendingDeletion(BB) ||
1
Assuming the condition is false
998 (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()))
2
Assuming the condition is false
999 return false;
1000
1001 // If this block has a single predecessor, and if that pred has a single
1002 // successor, merge the blocks. This encourages recursive jump threading
1003 // because now the condition in this block can be threaded through
1004 // predecessors of our predecessor block.
1005 if (MaybeMergeBasicBlockIntoOnlyPred(BB))
3
Taking false branch
1006 return true;
1007
1008 if (TryToUnfoldSelectInCurrBB(BB))
4
Taking false branch
1009 return true;
1010
1011 // Look if we can propagate guards to predecessors.
1012 if (HasGuards && ProcessGuards(BB))
5
Assuming field 'HasGuards' is false
1013 return true;
1014
1015 // What kind of constant we're looking for.
1016 ConstantPreference Preference = WantInteger;
1017
1018 // Look to see if the terminator is a conditional branch, switch or indirect
1019 // branch, if not we can't thread it.
1020 Value *Condition;
1021 Instruction *Terminator = BB->getTerminator();
1022 if (BranchInst *BI
6.1
'BI' is null
6.1
'BI' is null
6.1
'BI' is null
6.1
'BI' is null
= dyn_cast<BranchInst>(Terminator)) {
6
Assuming 'Terminator' is not a 'BranchInst'
7
Taking false branch
1023 // Can't thread an unconditional jump.
1024 if (BI->isUnconditional()) return false;
1025 Condition = BI->getCondition();
1026 } else if (SwitchInst *SI
8.1
'SI' is null
8.1
'SI' is null
8.1
'SI' is null
8.1
'SI' is null
= dyn_cast<SwitchInst>(Terminator)) {
8
Assuming 'Terminator' is not a 'SwitchInst'
9
Taking false branch
1027 Condition = SI->getCondition();
1028 } else if (IndirectBrInst *IB
10.1
'IB' is non-null
10.1
'IB' is non-null
10.1
'IB' is non-null
10.1
'IB' is non-null
= dyn_cast<IndirectBrInst>(Terminator)) {
10
Assuming 'Terminator' is a 'IndirectBrInst'
11
Taking true branch
1029 // Can't thread indirect branch with no successors.
1030 if (IB->getNumSuccessors() == 0) return false;
12
Assuming the condition is false
13
Taking false branch
1031 Condition = IB->getAddress()->stripPointerCasts();
1032 Preference = WantBlockAddress;
1033 } else {
1034 return false; // Must be an invoke or callbr.
1035 }
1036
1037 // Run constant folding to see if we can reduce the condition to a simple
1038 // constant.
1039 if (Instruction *I
14.1
'I' is non-null
14.1
'I' is non-null
14.1
'I' is non-null
14.1
'I' is non-null
= dyn_cast<Instruction>(Condition)) {
14
Assuming 'Condition' is a 'Instruction'
15
Taking true branch
1040 Value *SimpleVal =
1041 ConstantFoldInstruction(I, BB->getModule()->getDataLayout(), TLI);
1042 if (SimpleVal) {
16
Assuming 'SimpleVal' is null
17
Taking false branch
1043 I->replaceAllUsesWith(SimpleVal);
1044 if (isInstructionTriviallyDead(I, TLI))
1045 I->eraseFromParent();
1046 Condition = SimpleVal;
1047 }
1048 }
1049
1050 // If the terminator is branching on an undef, we can pick any of the
1051 // successors to branch to. Let GetBestDestForJumpOnUndef decide.
1052 if (isa<UndefValue>(Condition)) {
18
Assuming 'Condition' is not a 'UndefValue'
19
Taking false branch
1053 unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
1054 std::vector<DominatorTree::UpdateType> Updates;
1055
1056 // Fold the branch/switch.
1057 Instruction *BBTerm = BB->getTerminator();
1058 Updates.reserve(BBTerm->getNumSuccessors());
1059 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
1060 if (i == BestSucc) continue;
1061 BasicBlock *Succ = BBTerm->getSuccessor(i);
1062 Succ->removePredecessor(BB, true);
1063 Updates.push_back({DominatorTree::Delete, BB, Succ});
1064 }
1065
1066 LLVM_DEBUG(dbgs() << " In block '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " In block '" <<
BB->getName() << "' folding undef terminator: " <<
*BBTerm << '\n'; } } while (false)
1067 << "' folding undef terminator: " << *BBTerm << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " In block '" <<
BB->getName() << "' folding undef terminator: " <<
*BBTerm << '\n'; } } while (false)
;
1068 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
1069 BBTerm->eraseFromParent();
1070 DTU->applyUpdatesPermissive(Updates);
1071 return true;
1072 }
1073
1074 // If the terminator of this block is branching on a constant, simplify the
1075 // terminator to an unconditional branch. This can occur due to threading in
1076 // other blocks.
1077 if (getKnownConstant(Condition, Preference)) {
20
Taking false branch
1078 LLVM_DEBUG(dbgs() << " In block '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " In block '" <<
BB->getName() << "' folding terminator: " << *
BB->getTerminator() << '\n'; } } while (false)
1079 << "' folding terminator: " << *BB->getTerminator()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " In block '" <<
BB->getName() << "' folding terminator: " << *
BB->getTerminator() << '\n'; } } while (false)
1080 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " In block '" <<
BB->getName() << "' folding terminator: " << *
BB->getTerminator() << '\n'; } } while (false)
;
1081 ++NumFolds;
1082 ConstantFoldTerminator(BB, true, nullptr, DTU);
1083 return true;
1084 }
1085
1086 Instruction *CondInst = dyn_cast<Instruction>(Condition);
21
'Condition' is a 'Instruction'
1087
1088 // All the rest of our checks depend on the condition being an instruction.
1089 if (!CondInst
21.1
'CondInst' is non-null
21.1
'CondInst' is non-null
21.1
'CondInst' is non-null
21.1
'CondInst' is non-null
) {
22
Taking false branch
1090 // FIXME: Unify this with code below.
1091 if (ProcessThreadableEdges(Condition, BB, Preference, Terminator))
1092 return true;
1093 return false;
1094 }
1095
1096 if (CmpInst *CondCmp
23.1
'CondCmp' is null
23.1
'CondCmp' is null
23.1
'CondCmp' is null
23.1
'CondCmp' is null
= dyn_cast<CmpInst>(CondInst)) {
23
Assuming 'CondInst' is not a 'CmpInst'
24
Taking false branch
1097 // If we're branching on a conditional, LVI might be able to determine
1098 // it's value at the branch instruction. We only handle comparisons
1099 // against a constant at this time.
1100 // TODO: This should be extended to handle switches as well.
1101 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
1102 Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
1103 if (CondBr && CondConst) {
1104 // We should have returned as soon as we turn a conditional branch to
1105 // unconditional. Because its no longer interesting as far as jump
1106 // threading is concerned.
1107 assert(CondBr->isConditional() && "Threading on unconditional terminator")((CondBr->isConditional() && "Threading on unconditional terminator"
) ? static_cast<void> (0) : __assert_fail ("CondBr->isConditional() && \"Threading on unconditional terminator\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1107, __PRETTY_FUNCTION__))
;
1108
1109 if (DTU->hasPendingDomTreeUpdates())
1110 LVI->disableDT();
1111 else
1112 LVI->enableDT();
1113 LazyValueInfo::Tristate Ret =
1114 LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
1115 CondConst, CondBr);
1116 if (Ret != LazyValueInfo::Unknown) {
1117 unsigned ToRemove = Ret == LazyValueInfo::True ? 1 : 0;
1118 unsigned ToKeep = Ret == LazyValueInfo::True ? 0 : 1;
1119 BasicBlock *ToRemoveSucc = CondBr->getSuccessor(ToRemove);
1120 ToRemoveSucc->removePredecessor(BB, true);
1121 BranchInst *UncondBr =
1122 BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
1123 UncondBr->setDebugLoc(CondBr->getDebugLoc());
1124 CondBr->eraseFromParent();
1125 if (CondCmp->use_empty())
1126 CondCmp->eraseFromParent();
1127 // We can safely replace *some* uses of the CondInst if it has
1128 // exactly one value as returned by LVI. RAUW is incorrect in the
1129 // presence of guards and assumes, that have the `Cond` as the use. This
1130 // is because we use the guards/assume to reason about the `Cond` value
1131 // at the end of block, but RAUW unconditionally replaces all uses
1132 // including the guards/assumes themselves and the uses before the
1133 // guard/assume.
1134 else if (CondCmp->getParent() == BB) {
1135 auto *CI = Ret == LazyValueInfo::True ?
1136 ConstantInt::getTrue(CondCmp->getType()) :
1137 ConstantInt::getFalse(CondCmp->getType());
1138 ReplaceFoldableUses(CondCmp, CI);
1139 }
1140 DTU->applyUpdatesPermissive(
1141 {{DominatorTree::Delete, BB, ToRemoveSucc}});
1142 return true;
1143 }
1144
1145 // We did not manage to simplify this branch, try to see whether
1146 // CondCmp depends on a known phi-select pattern.
1147 if (TryToUnfoldSelect(CondCmp, BB))
1148 return true;
1149 }
1150 }
1151
1152 if (SwitchInst *SI
25.1
'SI' is null
25.1
'SI' is null
25.1
'SI' is null
25.1
'SI' is null
= dyn_cast<SwitchInst>(BB->getTerminator()))
25
Assuming the object is not a 'SwitchInst'
26
Taking false branch
1153 if (TryToUnfoldSelect(SI, BB))
1154 return true;
1155
1156 // Check for some cases that are worth simplifying. Right now we want to look
1157 // for loads that are used by a switch or by the condition for the branch. If
1158 // we see one, check to see if it's partially redundant. If so, insert a PHI
1159 // which can then be used to thread the values.
1160 Value *SimplifyValue = CondInst;
1161 if (CmpInst *CondCmp
27.1
'CondCmp' is null
27.1
'CondCmp' is null
27.1
'CondCmp' is null
27.1
'CondCmp' is null
= dyn_cast<CmpInst>(SimplifyValue))
27
Assuming 'SimplifyValue' is not a 'CmpInst'
28
Taking false branch
1162 if (isa<Constant>(CondCmp->getOperand(1)))
1163 SimplifyValue = CondCmp->getOperand(0);
1164
1165 // TODO: There are other places where load PRE would be profitable, such as
1166 // more complex comparisons.
1167 if (LoadInst *LoadI
29.1
'LoadI' is non-null
29.1
'LoadI' is non-null
29.1
'LoadI' is non-null
29.1
'LoadI' is non-null
= dyn_cast<LoadInst>(SimplifyValue))
29
Assuming 'SimplifyValue' is a 'LoadInst'
30
Taking true branch
1168 if (SimplifyPartiallyRedundantLoad(LoadI))
31
Calling 'JumpThreadingPass::SimplifyPartiallyRedundantLoad'
1169 return true;
1170
1171 // Before threading, try to propagate profile data backwards:
1172 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
1173 if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1174 updatePredecessorProfileMetadata(PN, BB);
1175
1176 // Handle a variety of cases where we are branching on something derived from
1177 // a PHI node in the current block. If we can prove that any predecessors
1178 // compute a predictable value based on a PHI node, thread those predecessors.
1179 if (ProcessThreadableEdges(CondInst, BB, Preference, Terminator))
1180 return true;
1181
1182 // If this is an otherwise-unfoldable branch on a phi node in the current
1183 // block, see if we can simplify.
1184 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
1185 if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1186 return ProcessBranchOnPHI(PN);
1187
1188 // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
1189 if (CondInst->getOpcode() == Instruction::Xor &&
1190 CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1191 return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
1192
1193 // Search for a stronger dominating condition that can be used to simplify a
1194 // conditional branch leaving BB.
1195 if (ProcessImpliedCondition(BB))
1196 return true;
1197
1198 return false;
1199}
1200
1201bool JumpThreadingPass::ProcessImpliedCondition(BasicBlock *BB) {
1202 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
1203 if (!BI || !BI->isConditional())
1204 return false;
1205
1206 Value *Cond = BI->getCondition();
1207 BasicBlock *CurrentBB = BB;
1208 BasicBlock *CurrentPred = BB->getSinglePredecessor();
1209 unsigned Iter = 0;
1210
1211 auto &DL = BB->getModule()->getDataLayout();
1212
1213 while (CurrentPred && Iter++ < ImplicationSearchThreshold) {
1214 auto *PBI = dyn_cast<BranchInst>(CurrentPred->getTerminator());
1215 if (!PBI || !PBI->isConditional())
1216 return false;
1217 if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB)
1218 return false;
1219
1220 bool CondIsTrue = PBI->getSuccessor(0) == CurrentBB;
1221 Optional<bool> Implication =
1222 isImpliedCondition(PBI->getCondition(), Cond, DL, CondIsTrue);
1223 if (Implication) {
1224 BasicBlock *KeepSucc = BI->getSuccessor(*Implication ? 0 : 1);
1225 BasicBlock *RemoveSucc = BI->getSuccessor(*Implication ? 1 : 0);
1226 RemoveSucc->removePredecessor(BB);
1227 BranchInst *UncondBI = BranchInst::Create(KeepSucc, BI);
1228 UncondBI->setDebugLoc(BI->getDebugLoc());
1229 BI->eraseFromParent();
1230 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, RemoveSucc}});
1231 return true;
1232 }
1233 CurrentBB = CurrentPred;
1234 CurrentPred = CurrentBB->getSinglePredecessor();
1235 }
1236
1237 return false;
1238}
1239
1240/// Return true if Op is an instruction defined in the given block.
1241static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB) {
1242 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
44
Assuming 'OpInst' is null
45
Taking false branch
1243 if (OpInst->getParent() == BB)
1244 return true;
1245 return false;
46
Returning zero, which participates in a condition later
1246}
1247
1248/// SimplifyPartiallyRedundantLoad - If LoadI is an obviously partially
1249/// redundant load instruction, eliminate it by replacing it with a PHI node.
1250/// This is an important optimization that encourages jump threading, and needs
1251/// to be run interlaced with other jump threading tasks.
1252bool JumpThreadingPass::SimplifyPartiallyRedundantLoad(LoadInst *LoadI) {
1253 // Don't hack volatile and ordered loads.
1254 if (!LoadI->isUnordered()) return false;
32
Calling 'LoadInst::isUnordered'
37
Returning from 'LoadInst::isUnordered'
38
Taking false branch
1255
1256 // If the load is defined in a block with exactly one predecessor, it can't be
1257 // partially redundant.
1258 BasicBlock *LoadBB = LoadI->getParent();
1259 if (LoadBB->getSinglePredecessor())
39
Assuming the condition is false
40
Taking false branch
1260 return false;
1261
1262 // If the load is defined in an EH pad, it can't be partially redundant,
1263 // because the edges between the invoke and the EH pad cannot have other
1264 // instructions between them.
1265 if (LoadBB->isEHPad())
41
Assuming the condition is false
42
Taking false branch
1266 return false;
1267
1268 Value *LoadedPtr = LoadI->getOperand(0);
1269
1270 // If the loaded operand is defined in the LoadBB and its not a phi,
1271 // it can't be available in predecessors.
1272 if (isOpDefinedInBlock(LoadedPtr, LoadBB) && !isa<PHINode>(LoadedPtr))
43
Calling 'isOpDefinedInBlock'
47
Returning from 'isOpDefinedInBlock'
1273 return false;
1274
1275 // Scan a few instructions up from the load, to see if it is obviously live at
1276 // the entry to its block.
1277 BasicBlock::iterator BBIt(LoadI);
1278 bool IsLoadCSE;
1279 if (Value *AvailableVal = FindAvailableLoadedValue(
48
Assuming 'AvailableVal' is null
49
Taking false branch
1280 LoadI, LoadBB, BBIt, DefMaxInstsToScan, AA, &IsLoadCSE)) {
1281 // If the value of the load is locally available within the block, just use
1282 // it. This frequently occurs for reg2mem'd allocas.
1283
1284 if (IsLoadCSE) {
1285 LoadInst *NLoadI = cast<LoadInst>(AvailableVal);
1286 combineMetadataForCSE(NLoadI, LoadI, false);
1287 };
1288
1289 // If the returned value is the load itself, replace with an undef. This can
1290 // only happen in dead loops.
1291 if (AvailableVal == LoadI)
1292 AvailableVal = UndefValue::get(LoadI->getType());
1293 if (AvailableVal->getType() != LoadI->getType())
1294 AvailableVal = CastInst::CreateBitOrPointerCast(
1295 AvailableVal, LoadI->getType(), "", LoadI);
1296 LoadI->replaceAllUsesWith(AvailableVal);
1297 LoadI->eraseFromParent();
1298 return true;
1299 }
1300
1301 // Otherwise, if we scanned the whole block and got to the top of the block,
1302 // we know the block is locally transparent to the load. If not, something
1303 // might clobber its value.
1304 if (BBIt != LoadBB->begin())
50
Calling 'operator!='
53
Returning from 'operator!='
54
Taking false branch
1305 return false;
1306
1307 // If all of the loads and stores that feed the value have the same AA tags,
1308 // then we can propagate them onto any newly inserted loads.
1309 AAMDNodes AATags;
1310 LoadI->getAAMetadata(AATags);
1311
1312 SmallPtrSet<BasicBlock*, 8> PredsScanned;
1313
1314 using AvailablePredsTy = SmallVector<std::pair<BasicBlock *, Value *>, 8>;
1315
1316 AvailablePredsTy AvailablePreds;
1317 BasicBlock *OneUnavailablePred = nullptr;
55
'OneUnavailablePred' initialized to a null pointer value
1318 SmallVector<LoadInst*, 8> CSELoads;
1319
1320 // If we got here, the loaded value is transparent through to the start of the
1321 // block. Check to see if it is available in any of the predecessor blocks.
1322 for (BasicBlock *PredBB : predecessors(LoadBB)) {
1323 // If we already scanned this predecessor, skip it.
1324 if (!PredsScanned.insert(PredBB).second)
1325 continue;
1326
1327 BBIt = PredBB->end();
1328 unsigned NumScanedInst = 0;
1329 Value *PredAvailable = nullptr;
1330 // NOTE: We don't CSE load that is volatile or anything stronger than
1331 // unordered, that should have been checked when we entered the function.
1332 assert(LoadI->isUnordered() &&((LoadI->isUnordered() && "Attempting to CSE volatile or atomic loads"
) ? static_cast<void> (0) : __assert_fail ("LoadI->isUnordered() && \"Attempting to CSE volatile or atomic loads\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1333, __PRETTY_FUNCTION__))
1333 "Attempting to CSE volatile or atomic loads")((LoadI->isUnordered() && "Attempting to CSE volatile or atomic loads"
) ? static_cast<void> (0) : __assert_fail ("LoadI->isUnordered() && \"Attempting to CSE volatile or atomic loads\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1333, __PRETTY_FUNCTION__))
;
1334 // If this is a load on a phi pointer, phi-translate it and search
1335 // for available load/store to the pointer in predecessors.
1336 Value *Ptr = LoadedPtr->DoPHITranslation(LoadBB, PredBB);
1337 PredAvailable = FindAvailablePtrLoadStore(
1338 Ptr, LoadI->getType(), LoadI->isAtomic(), PredBB, BBIt,
1339 DefMaxInstsToScan, AA, &IsLoadCSE, &NumScanedInst);
1340
1341 // If PredBB has a single predecessor, continue scanning through the
1342 // single predecessor.
1343 BasicBlock *SinglePredBB = PredBB;
1344 while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() &&
1345 NumScanedInst < DefMaxInstsToScan) {
1346 SinglePredBB = SinglePredBB->getSinglePredecessor();
1347 if (SinglePredBB) {
1348 BBIt = SinglePredBB->end();
1349 PredAvailable = FindAvailablePtrLoadStore(
1350 Ptr, LoadI->getType(), LoadI->isAtomic(), SinglePredBB, BBIt,
1351 (DefMaxInstsToScan - NumScanedInst), AA, &IsLoadCSE,
1352 &NumScanedInst);
1353 }
1354 }
1355
1356 if (!PredAvailable) {
1357 OneUnavailablePred = PredBB;
1358 continue;
1359 }
1360
1361 if (IsLoadCSE)
1362 CSELoads.push_back(cast<LoadInst>(PredAvailable));
1363
1364 // If so, this load is partially redundant. Remember this info so that we
1365 // can create a PHI node.
1366 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
1367 }
1368
1369 // If the loaded value isn't available in any predecessor, it isn't partially
1370 // redundant.
1371 if (AvailablePreds.empty()) return false;
56
Calling 'SmallVectorBase::empty'
59
Returning from 'SmallVectorBase::empty'
60
Taking false branch
1372
1373 // Okay, the loaded value is available in at least one (and maybe all!)
1374 // predecessors. If the value is unavailable in more than one unique
1375 // predecessor, we want to insert a merge block for those common predecessors.
1376 // This ensures that we only have to insert one reload, thus not increasing
1377 // code size.
1378 BasicBlock *UnavailablePred = nullptr;
1379
1380 // If the value is unavailable in one of predecessors, we will end up
1381 // inserting a new instruction into them. It is only valid if all the
1382 // instructions before LoadI are guaranteed to pass execution to its
1383 // successor, or if LoadI is safe to speculate.
1384 // TODO: If this logic becomes more complex, and we will perform PRE insertion
1385 // farther than to a predecessor, we need to reuse the code from GVN's PRE.
1386 // It requires domination tree analysis, so for this simple case it is an
1387 // overkill.
1388 if (PredsScanned.size() != AvailablePreds.size() &&
61
Assuming the condition is false
1389 !isSafeToSpeculativelyExecute(LoadI))
1390 for (auto I = LoadBB->begin(); &*I != LoadI; ++I)
1391 if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
1392 return false;
1393
1394 // If there is exactly one predecessor where the value is unavailable, the
1395 // already computed 'OneUnavailablePred' block is it. If it ends in an
1396 // unconditional branch, we know that it isn't a critical edge.
1397 if (PredsScanned.size() == AvailablePreds.size()+1 &&
62
Assuming the condition is true
1398 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
63
Called C++ object pointer is null
1399 UnavailablePred = OneUnavailablePred;
1400 } else if (PredsScanned.size() != AvailablePreds.size()) {
1401 // Otherwise, we had multiple unavailable predecessors or we had a critical
1402 // edge from the one.
1403 SmallVector<BasicBlock*, 8> PredsToSplit;
1404 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
1405
1406 for (const auto &AvailablePred : AvailablePreds)
1407 AvailablePredSet.insert(AvailablePred.first);
1408
1409 // Add all the unavailable predecessors to the PredsToSplit list.
1410 for (BasicBlock *P : predecessors(LoadBB)) {
1411 // If the predecessor is an indirect goto, we can't split the edge.
1412 // Same for CallBr.
1413 if (isa<IndirectBrInst>(P->getTerminator()) ||
1414 isa<CallBrInst>(P->getTerminator()))
1415 return false;
1416
1417 if (!AvailablePredSet.count(P))
1418 PredsToSplit.push_back(P);
1419 }
1420
1421 // Split them out to their own block.
1422 UnavailablePred = SplitBlockPreds(LoadBB, PredsToSplit, "thread-pre-split");
1423 }
1424
1425 // If the value isn't available in all predecessors, then there will be
1426 // exactly one where it isn't available. Insert a load on that edge and add
1427 // it to the AvailablePreds list.
1428 if (UnavailablePred) {
1429 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&((UnavailablePred->getTerminator()->getNumSuccessors() ==
1 && "Can't handle critical edge here!") ? static_cast
<void> (0) : __assert_fail ("UnavailablePred->getTerminator()->getNumSuccessors() == 1 && \"Can't handle critical edge here!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1430, __PRETTY_FUNCTION__))
1430 "Can't handle critical edge here!")((UnavailablePred->getTerminator()->getNumSuccessors() ==
1 && "Can't handle critical edge here!") ? static_cast
<void> (0) : __assert_fail ("UnavailablePred->getTerminator()->getNumSuccessors() == 1 && \"Can't handle critical edge here!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1430, __PRETTY_FUNCTION__))
;
1431 LoadInst *NewVal = new LoadInst(
1432 LoadI->getType(), LoadedPtr->DoPHITranslation(LoadBB, UnavailablePred),
1433 LoadI->getName() + ".pr", false, MaybeAlign(LoadI->getAlignment()),
1434 LoadI->getOrdering(), LoadI->getSyncScopeID(),
1435 UnavailablePred->getTerminator());
1436 NewVal->setDebugLoc(LoadI->getDebugLoc());
1437 if (AATags)
1438 NewVal->setAAMetadata(AATags);
1439
1440 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
1441 }
1442
1443 // Now we know that each predecessor of this block has a value in
1444 // AvailablePreds, sort them for efficient access as we're walking the preds.
1445 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
1446
1447 // Create a PHI node at the start of the block for the PRE'd load value.
1448 pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
1449 PHINode *PN = PHINode::Create(LoadI->getType(), std::distance(PB, PE), "",
1450 &LoadBB->front());
1451 PN->takeName(LoadI);
1452 PN->setDebugLoc(LoadI->getDebugLoc());
1453
1454 // Insert new entries into the PHI for each predecessor. A single block may
1455 // have multiple entries here.
1456 for (pred_iterator PI = PB; PI != PE; ++PI) {
1457 BasicBlock *P = *PI;
1458 AvailablePredsTy::iterator I =
1459 llvm::lower_bound(AvailablePreds, std::make_pair(P, (Value *)nullptr));
1460
1461 assert(I != AvailablePreds.end() && I->first == P &&((I != AvailablePreds.end() && I->first == P &&
"Didn't find entry for predecessor!") ? static_cast<void>
(0) : __assert_fail ("I != AvailablePreds.end() && I->first == P && \"Didn't find entry for predecessor!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1462, __PRETTY_FUNCTION__))
1462 "Didn't find entry for predecessor!")((I != AvailablePreds.end() && I->first == P &&
"Didn't find entry for predecessor!") ? static_cast<void>
(0) : __assert_fail ("I != AvailablePreds.end() && I->first == P && \"Didn't find entry for predecessor!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1462, __PRETTY_FUNCTION__))
;
1463
1464 // If we have an available predecessor but it requires casting, insert the
1465 // cast in the predecessor and use the cast. Note that we have to update the
1466 // AvailablePreds vector as we go so that all of the PHI entries for this
1467 // predecessor use the same bitcast.
1468 Value *&PredV = I->second;
1469 if (PredV->getType() != LoadI->getType())
1470 PredV = CastInst::CreateBitOrPointerCast(PredV, LoadI->getType(), "",
1471 P->getTerminator());
1472
1473 PN->addIncoming(PredV, I->first);
1474 }
1475
1476 for (LoadInst *PredLoadI : CSELoads) {
1477 combineMetadataForCSE(PredLoadI, LoadI, true);
1478 }
1479
1480 LoadI->replaceAllUsesWith(PN);
1481 LoadI->eraseFromParent();
1482
1483 return true;
1484}
1485
1486/// FindMostPopularDest - The specified list contains multiple possible
1487/// threadable destinations. Pick the one that occurs the most frequently in
1488/// the list.
1489static BasicBlock *
1490FindMostPopularDest(BasicBlock *BB,
1491 const SmallVectorImpl<std::pair<BasicBlock *,
1492 BasicBlock *>> &PredToDestList) {
1493 assert(!PredToDestList.empty())((!PredToDestList.empty()) ? static_cast<void> (0) : __assert_fail
("!PredToDestList.empty()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1493, __PRETTY_FUNCTION__))
;
1494
1495 // Determine popularity. If there are multiple possible destinations, we
1496 // explicitly choose to ignore 'undef' destinations. We prefer to thread
1497 // blocks with known and real destinations to threading undef. We'll handle
1498 // them later if interesting.
1499 DenseMap<BasicBlock*, unsigned> DestPopularity;
1500 for (const auto &PredToDest : PredToDestList)
1501 if (PredToDest.second)
1502 DestPopularity[PredToDest.second]++;
1503
1504 if (DestPopularity.empty())
1505 return nullptr;
1506
1507 // Find the most popular dest.
1508 DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
1509 BasicBlock *MostPopularDest = DPI->first;
1510 unsigned Popularity = DPI->second;
1511 SmallVector<BasicBlock*, 4> SamePopularity;
1512
1513 for (++DPI; DPI != DestPopularity.end(); ++DPI) {
1514 // If the popularity of this entry isn't higher than the popularity we've
1515 // seen so far, ignore it.
1516 if (DPI->second < Popularity)
1517 ; // ignore.
1518 else if (DPI->second == Popularity) {
1519 // If it is the same as what we've seen so far, keep track of it.
1520 SamePopularity.push_back(DPI->first);
1521 } else {
1522 // If it is more popular, remember it.
1523 SamePopularity.clear();
1524 MostPopularDest = DPI->first;
1525 Popularity = DPI->second;
1526 }
1527 }
1528
1529 // Okay, now we know the most popular destination. If there is more than one
1530 // destination, we need to determine one. This is arbitrary, but we need
1531 // to make a deterministic decision. Pick the first one that appears in the
1532 // successor list.
1533 if (!SamePopularity.empty()) {
1534 SamePopularity.push_back(MostPopularDest);
1535 Instruction *TI = BB->getTerminator();
1536 for (unsigned i = 0; ; ++i) {
1537 assert(i != TI->getNumSuccessors() && "Didn't find any successor!")((i != TI->getNumSuccessors() && "Didn't find any successor!"
) ? static_cast<void> (0) : __assert_fail ("i != TI->getNumSuccessors() && \"Didn't find any successor!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1537, __PRETTY_FUNCTION__))
;
1538
1539 if (!is_contained(SamePopularity, TI->getSuccessor(i)))
1540 continue;
1541
1542 MostPopularDest = TI->getSuccessor(i);
1543 break;
1544 }
1545 }
1546
1547 // Okay, we have finally picked the most popular destination.
1548 return MostPopularDest;
1549}
1550
1551bool JumpThreadingPass::ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
1552 ConstantPreference Preference,
1553 Instruction *CxtI) {
1554 // If threading this would thread across a loop header, don't even try to
1555 // thread the edge.
1556 if (LoopHeaders.count(BB))
1557 return false;
1558
1559 PredValueInfoTy PredValues;
1560 if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference, CxtI))
1561 return false;
1562
1563 assert(!PredValues.empty() &&((!PredValues.empty() && "ComputeValueKnownInPredecessors returned true with no values"
) ? static_cast<void> (0) : __assert_fail ("!PredValues.empty() && \"ComputeValueKnownInPredecessors returned true with no values\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1564, __PRETTY_FUNCTION__))
1564 "ComputeValueKnownInPredecessors returned true with no values")((!PredValues.empty() && "ComputeValueKnownInPredecessors returned true with no values"
) ? static_cast<void> (0) : __assert_fail ("!PredValues.empty() && \"ComputeValueKnownInPredecessors returned true with no values\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1564, __PRETTY_FUNCTION__))
;
1565
1566 LLVM_DEBUG(dbgs() << "IN BB: " << *BB;do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
1567 for (const auto &PredValue : PredValues) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
1568 dbgs() << " BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
1569 << "': FOUND condition = " << *PredValue.firstdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
1570 << " for pred '" << PredValue.second->getName() << "'.\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
1571 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
;
1572
1573 // Decide what we want to thread through. Convert our list of known values to
1574 // a list of known destinations for each pred. This also discards duplicate
1575 // predecessors and keeps track of the undefined inputs (which are represented
1576 // as a null dest in the PredToDestList).
1577 SmallPtrSet<BasicBlock*, 16> SeenPreds;
1578 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
1579
1580 BasicBlock *OnlyDest = nullptr;
1581 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
1582 Constant *OnlyVal = nullptr;
1583 Constant *MultipleVal = (Constant *)(intptr_t)~0ULL;
1584
1585 for (const auto &PredValue : PredValues) {
1586 BasicBlock *Pred = PredValue.second;
1587 if (!SeenPreds.insert(Pred).second)
1588 continue; // Duplicate predecessor entry.
1589
1590 Constant *Val = PredValue.first;
1591
1592 BasicBlock *DestBB;
1593 if (isa<UndefValue>(Val))
1594 DestBB = nullptr;
1595 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
1596 assert(isa<ConstantInt>(Val) && "Expecting a constant integer")((isa<ConstantInt>(Val) && "Expecting a constant integer"
) ? static_cast<void> (0) : __assert_fail ("isa<ConstantInt>(Val) && \"Expecting a constant integer\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1596, __PRETTY_FUNCTION__))
;
1597 DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
1598 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1599 assert(isa<ConstantInt>(Val) && "Expecting a constant integer")((isa<ConstantInt>(Val) && "Expecting a constant integer"
) ? static_cast<void> (0) : __assert_fail ("isa<ConstantInt>(Val) && \"Expecting a constant integer\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1599, __PRETTY_FUNCTION__))
;
1600 DestBB = SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor();
1601 } else {
1602 assert(isa<IndirectBrInst>(BB->getTerminator())((isa<IndirectBrInst>(BB->getTerminator()) &&
"Unexpected terminator") ? static_cast<void> (0) : __assert_fail
("isa<IndirectBrInst>(BB->getTerminator()) && \"Unexpected terminator\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1603, __PRETTY_FUNCTION__))
1603 && "Unexpected terminator")((isa<IndirectBrInst>(BB->getTerminator()) &&
"Unexpected terminator") ? static_cast<void> (0) : __assert_fail
("isa<IndirectBrInst>(BB->getTerminator()) && \"Unexpected terminator\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1603, __PRETTY_FUNCTION__))
;
1604 assert(isa<BlockAddress>(Val) && "Expecting a constant blockaddress")((isa<BlockAddress>(Val) && "Expecting a constant blockaddress"
) ? static_cast<void> (0) : __assert_fail ("isa<BlockAddress>(Val) && \"Expecting a constant blockaddress\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1604, __PRETTY_FUNCTION__))
;
1605 DestBB = cast<BlockAddress>(Val)->getBasicBlock();
1606 }
1607
1608 // If we have exactly one destination, remember it for efficiency below.
1609 if (PredToDestList.empty()) {
1610 OnlyDest = DestBB;
1611 OnlyVal = Val;
1612 } else {
1613 if (OnlyDest != DestBB)
1614 OnlyDest = MultipleDestSentinel;
1615 // It possible we have same destination, but different value, e.g. default
1616 // case in switchinst.
1617 if (Val != OnlyVal)
1618 OnlyVal = MultipleVal;
1619 }
1620
1621 // If the predecessor ends with an indirect goto, we can't change its
1622 // destination. Same for CallBr.
1623 if (isa<IndirectBrInst>(Pred->getTerminator()) ||
1624 isa<CallBrInst>(Pred->getTerminator()))
1625 continue;
1626
1627 PredToDestList.push_back(std::make_pair(Pred, DestBB));
1628 }
1629
1630 // If all edges were unthreadable, we fail.
1631 if (PredToDestList.empty())
1632 return false;
1633
1634 // If all the predecessors go to a single known successor, we want to fold,
1635 // not thread. By doing so, we do not need to duplicate the current block and
1636 // also miss potential opportunities in case we dont/cant duplicate.
1637 if (OnlyDest && OnlyDest != MultipleDestSentinel) {
1638 if (BB->hasNPredecessors(PredToDestList.size())) {
1639 bool SeenFirstBranchToOnlyDest = false;
1640 std::vector <DominatorTree::UpdateType> Updates;
1641 Updates.reserve(BB->getTerminator()->getNumSuccessors() - 1);
1642 for (BasicBlock *SuccBB : successors(BB)) {
1643 if (SuccBB == OnlyDest && !SeenFirstBranchToOnlyDest) {
1644 SeenFirstBranchToOnlyDest = true; // Don't modify the first branch.
1645 } else {
1646 SuccBB->removePredecessor(BB, true); // This is unreachable successor.
1647 Updates.push_back({DominatorTree::Delete, BB, SuccBB});
1648 }
1649 }
1650
1651 // Finally update the terminator.
1652 Instruction *Term = BB->getTerminator();
1653 BranchInst::Create(OnlyDest, Term);
1654 Term->eraseFromParent();
1655 DTU->applyUpdatesPermissive(Updates);
1656
1657 // If the condition is now dead due to the removal of the old terminator,
1658 // erase it.
1659 if (auto *CondInst = dyn_cast<Instruction>(Cond)) {
1660 if (CondInst->use_empty() && !CondInst->mayHaveSideEffects())
1661 CondInst->eraseFromParent();
1662 // We can safely replace *some* uses of the CondInst if it has
1663 // exactly one value as returned by LVI. RAUW is incorrect in the
1664 // presence of guards and assumes, that have the `Cond` as the use. This
1665 // is because we use the guards/assume to reason about the `Cond` value
1666 // at the end of block, but RAUW unconditionally replaces all uses
1667 // including the guards/assumes themselves and the uses before the
1668 // guard/assume.
1669 else if (OnlyVal && OnlyVal != MultipleVal &&
1670 CondInst->getParent() == BB)
1671 ReplaceFoldableUses(CondInst, OnlyVal);
1672 }
1673 return true;
1674 }
1675 }
1676
1677 // Determine which is the most common successor. If we have many inputs and
1678 // this block is a switch, we want to start by threading the batch that goes
1679 // to the most popular destination first. If we only know about one
1680 // threadable destination (the common case) we can avoid this.
1681 BasicBlock *MostPopularDest = OnlyDest;
1682
1683 if (MostPopularDest == MultipleDestSentinel) {
1684 // Remove any loop headers from the Dest list, ThreadEdge conservatively
1685 // won't process them, but we might have other destination that are eligible
1686 // and we still want to process.
1687 erase_if(PredToDestList,
1688 [&](const std::pair<BasicBlock *, BasicBlock *> &PredToDest) {
1689 return LoopHeaders.count(PredToDest.second) != 0;
1690 });
1691
1692 if (PredToDestList.empty())
1693 return false;
1694
1695 MostPopularDest = FindMostPopularDest(BB, PredToDestList);
1696 }
1697
1698 // Now that we know what the most popular destination is, factor all
1699 // predecessors that will jump to it into a single predecessor.
1700 SmallVector<BasicBlock*, 16> PredsToFactor;
1701 for (const auto &PredToDest : PredToDestList)
1702 if (PredToDest.second == MostPopularDest) {
1703 BasicBlock *Pred = PredToDest.first;
1704
1705 // This predecessor may be a switch or something else that has multiple
1706 // edges to the block. Factor each of these edges by listing them
1707 // according to # occurrences in PredsToFactor.
1708 for (BasicBlock *Succ : successors(Pred))
1709 if (Succ == BB)
1710 PredsToFactor.push_back(Pred);
1711 }
1712
1713 // If the threadable edges are branching on an undefined value, we get to pick
1714 // the destination that these predecessors should get to.
1715 if (!MostPopularDest)
1716 MostPopularDest = BB->getTerminator()->
1717 getSuccessor(GetBestDestForJumpOnUndef(BB));
1718
1719 // Ok, try to thread it!
1720 return TryThreadEdge(BB, PredsToFactor, MostPopularDest);
1721}
1722
1723/// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
1724/// a PHI node in the current block. See if there are any simplifications we
1725/// can do based on inputs to the phi node.
1726bool JumpThreadingPass::ProcessBranchOnPHI(PHINode *PN) {
1727 BasicBlock *BB = PN->getParent();
1728
1729 // TODO: We could make use of this to do it once for blocks with common PHI
1730 // values.
1731 SmallVector<BasicBlock*, 1> PredBBs;
1732 PredBBs.resize(1);
1733
1734 // If any of the predecessor blocks end in an unconditional branch, we can
1735 // *duplicate* the conditional branch into that block in order to further
1736 // encourage jump threading and to eliminate cases where we have branch on a
1737 // phi of an icmp (branch on icmp is much better).
1738 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1739 BasicBlock *PredBB = PN->getIncomingBlock(i);
1740 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
1741 if (PredBr->isUnconditional()) {
1742 PredBBs[0] = PredBB;
1743 // Try to duplicate BB into PredBB.
1744 if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
1745 return true;
1746 }
1747 }
1748
1749 return false;
1750}
1751
1752/// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
1753/// a xor instruction in the current block. See if there are any
1754/// simplifications we can do based on inputs to the xor.
1755bool JumpThreadingPass::ProcessBranchOnXOR(BinaryOperator *BO) {
1756 BasicBlock *BB = BO->getParent();
1757
1758 // If either the LHS or RHS of the xor is a constant, don't do this
1759 // optimization.
1760 if (isa<ConstantInt>(BO->getOperand(0)) ||
1761 isa<ConstantInt>(BO->getOperand(1)))
1762 return false;
1763
1764 // If the first instruction in BB isn't a phi, we won't be able to infer
1765 // anything special about any particular predecessor.
1766 if (!isa<PHINode>(BB->front()))
1767 return false;
1768
1769 // If this BB is a landing pad, we won't be able to split the edge into it.
1770 if (BB->isEHPad())
1771 return false;
1772
1773 // If we have a xor as the branch input to this block, and we know that the
1774 // LHS or RHS of the xor in any predecessor is true/false, then we can clone
1775 // the condition into the predecessor and fix that value to true, saving some
1776 // logical ops on that path and encouraging other paths to simplify.
1777 //
1778 // This copies something like this:
1779 //
1780 // BB:
1781 // %X = phi i1 [1], [%X']
1782 // %Y = icmp eq i32 %A, %B
1783 // %Z = xor i1 %X, %Y
1784 // br i1 %Z, ...
1785 //
1786 // Into:
1787 // BB':
1788 // %Y = icmp ne i32 %A, %B
1789 // br i1 %Y, ...
1790
1791 PredValueInfoTy XorOpValues;
1792 bool isLHS = true;
1793 if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
1794 WantInteger, BO)) {
1795 assert(XorOpValues.empty())((XorOpValues.empty()) ? static_cast<void> (0) : __assert_fail
("XorOpValues.empty()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1795, __PRETTY_FUNCTION__))
;
1796 if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
1797 WantInteger, BO))
1798 return false;
1799 isLHS = false;
1800 }
1801
1802 assert(!XorOpValues.empty() &&((!XorOpValues.empty() && "ComputeValueKnownInPredecessors returned true with no values"
) ? static_cast<void> (0) : __assert_fail ("!XorOpValues.empty() && \"ComputeValueKnownInPredecessors returned true with no values\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1803, __PRETTY_FUNCTION__))
1803 "ComputeValueKnownInPredecessors returned true with no values")((!XorOpValues.empty() && "ComputeValueKnownInPredecessors returned true with no values"
) ? static_cast<void> (0) : __assert_fail ("!XorOpValues.empty() && \"ComputeValueKnownInPredecessors returned true with no values\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1803, __PRETTY_FUNCTION__))
;
1804
1805 // Scan the information to see which is most popular: true or false. The
1806 // predecessors can be of the set true, false, or undef.
1807 unsigned NumTrue = 0, NumFalse = 0;
1808 for (const auto &XorOpValue : XorOpValues) {
1809 if (isa<UndefValue>(XorOpValue.first))
1810 // Ignore undefs for the count.
1811 continue;
1812 if (cast<ConstantInt>(XorOpValue.first)->isZero())
1813 ++NumFalse;
1814 else
1815 ++NumTrue;
1816 }
1817
1818 // Determine which value to split on, true, false, or undef if neither.
1819 ConstantInt *SplitVal = nullptr;
1820 if (NumTrue > NumFalse)
1821 SplitVal = ConstantInt::getTrue(BB->getContext());
1822 else if (NumTrue != 0 || NumFalse != 0)
1823 SplitVal = ConstantInt::getFalse(BB->getContext());
1824
1825 // Collect all of the blocks that this can be folded into so that we can
1826 // factor this once and clone it once.
1827 SmallVector<BasicBlock*, 8> BlocksToFoldInto;
1828 for (const auto &XorOpValue : XorOpValues) {
1829 if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first))
1830 continue;
1831
1832 BlocksToFoldInto.push_back(XorOpValue.second);
1833 }
1834
1835 // If we inferred a value for all of the predecessors, then duplication won't
1836 // help us. However, we can just replace the LHS or RHS with the constant.
1837 if (BlocksToFoldInto.size() ==
1838 cast<PHINode>(BB->front()).getNumIncomingValues()) {
1839 if (!SplitVal) {
1840 // If all preds provide undef, just nuke the xor, because it is undef too.
1841 BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
1842 BO->eraseFromParent();
1843 } else if (SplitVal->isZero()) {
1844 // If all preds provide 0, replace the xor with the other input.
1845 BO->replaceAllUsesWith(BO->getOperand(isLHS));
1846 BO->eraseFromParent();
1847 } else {
1848 // If all preds provide 1, set the computed value to 1.
1849 BO->setOperand(!isLHS, SplitVal);
1850 }
1851
1852 return true;
1853 }
1854
1855 // Try to duplicate BB into PredBB.
1856 return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
1857}
1858
1859/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1860/// predecessor to the PHIBB block. If it has PHI nodes, add entries for
1861/// NewPred using the entries from OldPred (suitably mapped).
1862static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1863 BasicBlock *OldPred,
1864 BasicBlock *NewPred,
1865 DenseMap<Instruction*, Value*> &ValueMap) {
1866 for (PHINode &PN : PHIBB->phis()) {
1867 // Ok, we have a PHI node. Figure out what the incoming value was for the
1868 // DestBlock.
1869 Value *IV = PN.getIncomingValueForBlock(OldPred);
1870
1871 // Remap the value if necessary.
1872 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1873 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1874 if (I != ValueMap.end())
1875 IV = I->second;
1876 }
1877
1878 PN.addIncoming(IV, NewPred);
1879 }
1880}
1881
1882/// Merge basic block BB into its sole predecessor if possible.
1883bool JumpThreadingPass::MaybeMergeBasicBlockIntoOnlyPred(BasicBlock *BB) {
1884 BasicBlock *SinglePred = BB->getSinglePredecessor();
1885 if (!SinglePred)
1886 return false;
1887
1888 const Instruction *TI = SinglePred->getTerminator();
1889 if (TI->isExceptionalTerminator() || TI->getNumSuccessors() != 1 ||
1890 SinglePred == BB || hasAddressTakenAndUsed(BB))
1891 return false;
1892
1893 // If SinglePred was a loop header, BB becomes one.
1894 if (LoopHeaders.erase(SinglePred))
1895 LoopHeaders.insert(BB);
1896
1897 LVI->eraseBlock(SinglePred);
1898 MergeBasicBlockIntoOnlyPred(BB, DTU);
1899
1900 // Now that BB is merged into SinglePred (i.e. SinglePred code followed by
1901 // BB code within one basic block `BB`), we need to invalidate the LVI
1902 // information associated with BB, because the LVI information need not be
1903 // true for all of BB after the merge. For example,
1904 // Before the merge, LVI info and code is as follows:
1905 // SinglePred: <LVI info1 for %p val>
1906 // %y = use of %p
1907 // call @exit() // need not transfer execution to successor.
1908 // assume(%p) // from this point on %p is true
1909 // br label %BB
1910 // BB: <LVI info2 for %p val, i.e. %p is true>
1911 // %x = use of %p
1912 // br label exit
1913 //
1914 // Note that this LVI info for blocks BB and SinglPred is correct for %p
1915 // (info2 and info1 respectively). After the merge and the deletion of the
1916 // LVI info1 for SinglePred. We have the following code:
1917 // BB: <LVI info2 for %p val>
1918 // %y = use of %p
1919 // call @exit()
1920 // assume(%p)
1921 // %x = use of %p <-- LVI info2 is correct from here onwards.
1922 // br label exit
1923 // LVI info2 for BB is incorrect at the beginning of BB.
1924
1925 // Invalidate LVI information for BB if the LVI is not provably true for
1926 // all of BB.
1927 if (!isGuaranteedToTransferExecutionToSuccessor(BB))
1928 LVI->eraseBlock(BB);
1929 return true;
1930}
1931
1932/// Update the SSA form. NewBB contains instructions that are copied from BB.
1933/// ValueMapping maps old values in BB to new ones in NewBB.
1934void JumpThreadingPass::UpdateSSA(
1935 BasicBlock *BB, BasicBlock *NewBB,
1936 DenseMap<Instruction *, Value *> &ValueMapping) {
1937 // If there were values defined in BB that are used outside the block, then we
1938 // now have to update all uses of the value to use either the original value,
1939 // the cloned value, or some PHI derived value. This can require arbitrary
1940 // PHI insertion, of which we are prepared to do, clean these up now.
1941 SSAUpdater SSAUpdate;
1942 SmallVector<Use *, 16> UsesToRename;
1943
1944 for (Instruction &I : *BB) {
1945 // Scan all uses of this instruction to see if it is used outside of its
1946 // block, and if so, record them in UsesToRename.
1947 for (Use &U : I.uses()) {
1948 Instruction *User = cast<Instruction>(U.getUser());
1949 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1950 if (UserPN->getIncomingBlock(U) == BB)
1951 continue;
1952 } else if (User->getParent() == BB)
1953 continue;
1954
1955 UsesToRename.push_back(&U);
1956 }
1957
1958 // If there are no uses outside the block, we're done with this instruction.
1959 if (UsesToRename.empty())
1960 continue;
1961 LLVM_DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "JT: Renaming non-local uses of: "
<< I << "\n"; } } while (false)
;
1962
1963 // We found a use of I outside of BB. Rename all uses of I that are outside
1964 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1965 // with the two values we know.
1966 SSAUpdate.Initialize(I.getType(), I.getName());
1967 SSAUpdate.AddAvailableValue(BB, &I);
1968 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]);
1969
1970 while (!UsesToRename.empty())
1971 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1972 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "\n"; } } while (false)
;
1973 }
1974}
1975
1976/// Clone instructions in range [BI, BE) to NewBB. For PHI nodes, we only clone
1977/// arguments that come from PredBB. Return the map from the variables in the
1978/// source basic block to the variables in the newly created basic block.
1979DenseMap<Instruction *, Value *>
1980JumpThreadingPass::CloneInstructions(BasicBlock::iterator BI,
1981 BasicBlock::iterator BE, BasicBlock *NewBB,
1982 BasicBlock *PredBB) {
1983 // We are going to have to map operands from the source basic block to the new
1984 // copy of the block 'NewBB'. If there are PHI nodes in the source basic
1985 // block, evaluate them to account for entry from PredBB.
1986 DenseMap<Instruction *, Value *> ValueMapping;
1987
1988 // Clone the phi nodes of the source basic block into NewBB. The resulting
1989 // phi nodes are trivial since NewBB only has one predecessor, but SSAUpdater
1990 // might need to rewrite the operand of the cloned phi.
1991 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
1992 PHINode *NewPN = PHINode::Create(PN->getType(), 1, PN->getName(), NewBB);
1993 NewPN->addIncoming(PN->getIncomingValueForBlock(PredBB), PredBB);
1994 ValueMapping[PN] = NewPN;
1995 }
1996
1997 // Clone the non-phi instructions of the source basic block into NewBB,
1998 // keeping track of the mapping and using it to remap operands in the cloned
1999 // instructions.
2000 for (; BI != BE; ++BI) {
2001 Instruction *New = BI->clone();
2002 New->setName(BI->getName());
2003 NewBB->getInstList().push_back(New);
2004 ValueMapping[&*BI] = New;
2005
2006 // Remap operands to patch up intra-block references.
2007 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2008 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
2009 DenseMap<Instruction *, Value *>::iterator I = ValueMapping.find(Inst);
2010 if (I != ValueMapping.end())
2011 New->setOperand(i, I->second);
2012 }
2013 }
2014
2015 return ValueMapping;
2016}
2017
2018/// TryThreadEdge - Thread an edge if it's safe and profitable to do so.
2019bool JumpThreadingPass::TryThreadEdge(
2020 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs,
2021 BasicBlock *SuccBB) {
2022 // If threading to the same block as we come from, we would infinite loop.
2023 if (SuccBB == BB) {
2024 LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading across BB '"
<< BB->getName() << "' - would thread to self!\n"
; } } while (false)
2025 << "' - would thread to self!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading across BB '"
<< BB->getName() << "' - would thread to self!\n"
; } } while (false)
;
2026 return false;
2027 }
2028
2029 // If threading this would thread across a loop header, don't thread the edge.
2030 // See the comments above FindLoopHeaders for justifications and caveats.
2031 if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
2032 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2033 bool BBIsHeader = LoopHeaders.count(BB);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2034 bool SuccIsHeader = LoopHeaders.count(SuccBB);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2035 dbgs() << " Not threading across "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2036 << (BBIsHeader ? "loop header BB '" : "block BB '") << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2037 << "' to dest " << (SuccIsHeader ? "loop header BB '" : "block BB '")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2038 << SuccBB->getName() << "' - it might create an irreducible loop!\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2039 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
;
2040 return false;
2041 }
2042
2043 unsigned JumpThreadCost =
2044 getJumpThreadDuplicationCost(BB, BB->getTerminator(), BBDupThreshold);
2045 if (JumpThreadCost > BBDupThreshold) {
2046 LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading BB '" <<
BB->getName() << "' - Cost is too high: " << JumpThreadCost
<< "\n"; } } while (false)
2047 << "' - Cost is too high: " << JumpThreadCost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading BB '" <<
BB->getName() << "' - Cost is too high: " << JumpThreadCost
<< "\n"; } } while (false)
;
2048 return false;
2049 }
2050
2051 ThreadEdge(BB, PredBBs, SuccBB);
2052 return true;
2053}
2054
2055/// ThreadEdge - We have decided that it is safe and profitable to factor the
2056/// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
2057/// across BB. Transform the IR to reflect this change.
2058void JumpThreadingPass::ThreadEdge(BasicBlock *BB,
2059 const SmallVectorImpl<BasicBlock *> &PredBBs,
2060 BasicBlock *SuccBB) {
2061 assert(SuccBB != BB && "Don't create an infinite loop")((SuccBB != BB && "Don't create an infinite loop") ? static_cast
<void> (0) : __assert_fail ("SuccBB != BB && \"Don't create an infinite loop\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2061, __PRETTY_FUNCTION__))
;
2062
2063 assert(!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) &&((!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB
) && "Don't thread across loop headers") ? static_cast
<void> (0) : __assert_fail ("!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) && \"Don't thread across loop headers\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2064, __PRETTY_FUNCTION__))
2064 "Don't thread across loop headers")((!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB
) && "Don't thread across loop headers") ? static_cast
<void> (0) : __assert_fail ("!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) && \"Don't thread across loop headers\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2064, __PRETTY_FUNCTION__))
;
2065
2066 // And finally, do it! Start by factoring the predecessors if needed.
2067 BasicBlock *PredBB;
2068 if (PredBBs.size() == 1)
2069 PredBB = PredBBs[0];
2070 else {
2071 LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Factoring out " <<
PredBBs.size() << " common predecessors.\n"; } } while
(false)
2072 << " common predecessors.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Factoring out " <<
PredBBs.size() << " common predecessors.\n"; } } while
(false)
;
2073 PredBB = SplitBlockPreds(BB, PredBBs, ".thr_comm");
2074 }
2075
2076 // And finally, do it!
2077 LLVM_DEBUG(dbgs() << " Threading edge from '" << PredBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Threading edge from '"
<< PredBB->getName() << "' to '" << SuccBB
->getName() << ", across block:\n " << *BB <<
"\n"; } } while (false)
2078 << "' to '" << SuccBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Threading edge from '"
<< PredBB->getName() << "' to '" << SuccBB
->getName() << ", across block:\n " << *BB <<
"\n"; } } while (false)
2079 << ", across block:\n " << *BB << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Threading edge from '"
<< PredBB->getName() << "' to '" << SuccBB
->getName() << ", across block:\n " << *BB <<
"\n"; } } while (false)
;
2080
2081 if (DTU->hasPendingDomTreeUpdates())
2082 LVI->disableDT();
2083 else
2084 LVI->enableDT();
2085 LVI->threadEdge(PredBB, BB, SuccBB);
2086
2087 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
2088 BB->getName()+".thread",
2089 BB->getParent(), BB);
2090 NewBB->moveAfter(PredBB);
2091
2092 // Set the block frequency of NewBB.
2093 if (HasProfileData) {
2094 auto NewBBFreq =
2095 BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB);
2096 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
2097 }
2098
2099 // Copy all the instructions from BB to NewBB except the terminator.
2100 DenseMap<Instruction *, Value *> ValueMapping =
2101 CloneInstructions(BB->begin(), std::prev(BB->end()), NewBB, PredBB);
2102
2103 // We didn't copy the terminator from BB over to NewBB, because there is now
2104 // an unconditional jump to SuccBB. Insert the unconditional jump.
2105 BranchInst *NewBI = BranchInst::Create(SuccBB, NewBB);
2106 NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
2107
2108 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
2109 // PHI nodes for NewBB now.
2110 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
2111
2112 // Update the terminator of PredBB to jump to NewBB instead of BB. This
2113 // eliminates predecessors from BB, which requires us to simplify any PHI
2114 // nodes in BB.
2115 Instruction *PredTerm = PredBB->getTerminator();
2116 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
2117 if (PredTerm->getSuccessor(i) == BB) {
2118 BB->removePredecessor(PredBB, true);
2119 PredTerm->setSuccessor(i, NewBB);
2120 }
2121
2122 // Enqueue required DT updates.
2123 DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, SuccBB},
2124 {DominatorTree::Insert, PredBB, NewBB},
2125 {DominatorTree::Delete, PredBB, BB}});
2126
2127 UpdateSSA(BB, NewBB, ValueMapping);
2128
2129 // At this point, the IR is fully up to date and consistent. Do a quick scan
2130 // over the new instructions and zap any that are constants or dead. This
2131 // frequently happens because of phi translation.
2132 SimplifyInstructionsInBlock(NewBB, TLI);
2133
2134 // Update the edge weight from BB to SuccBB, which should be less than before.
2135 UpdateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB);
2136
2137 // Threaded an edge!
2138 ++NumThreads;
2139}
2140
2141/// Create a new basic block that will be the predecessor of BB and successor of
2142/// all blocks in Preds. When profile data is available, update the frequency of
2143/// this new block.
2144BasicBlock *JumpThreadingPass::SplitBlockPreds(BasicBlock *BB,
2145 ArrayRef<BasicBlock *> Preds,
2146 const char *Suffix) {
2147 SmallVector<BasicBlock *, 2> NewBBs;
2148
2149 // Collect the frequencies of all predecessors of BB, which will be used to
2150 // update the edge weight of the result of splitting predecessors.
2151 DenseMap<BasicBlock *, BlockFrequency> FreqMap;
2152 if (HasProfileData)
2153 for (auto Pred : Preds)
2154 FreqMap.insert(std::make_pair(
2155 Pred, BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB)));
2156
2157 // In the case when BB is a LandingPad block we create 2 new predecessors
2158 // instead of just one.
2159 if (BB->isLandingPad()) {
2160 std::string NewName = std::string(Suffix) + ".split-lp";
2161 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs);
2162 } else {
2163 NewBBs.push_back(SplitBlockPredecessors(BB, Preds, Suffix));
2164 }
2165
2166 std::vector<DominatorTree::UpdateType> Updates;
2167 Updates.reserve((2 * Preds.size()) + NewBBs.size());
2168 for (auto NewBB : NewBBs) {
2169 BlockFrequency NewBBFreq(0);
2170 Updates.push_back({DominatorTree::Insert, NewBB, BB});
2171 for (auto Pred : predecessors(NewBB)) {
2172 Updates.push_back({DominatorTree::Delete, Pred, BB});
2173 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
2174 if (HasProfileData) // Update frequencies between Pred -> NewBB.
2175 NewBBFreq += FreqMap.lookup(Pred);
2176 }
2177 if (HasProfileData) // Apply the summed frequency to NewBB.
2178 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
2179 }
2180
2181 DTU->applyUpdatesPermissive(Updates);
2182 return NewBBs[0];
2183}
2184
2185bool JumpThreadingPass::doesBlockHaveProfileData(BasicBlock *BB) {
2186 const Instruction *TI = BB->getTerminator();
2187 assert(TI->getNumSuccessors() > 1 && "not a split")((TI->getNumSuccessors() > 1 && "not a split") ?
static_cast<void> (0) : __assert_fail ("TI->getNumSuccessors() > 1 && \"not a split\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2187, __PRETTY_FUNCTION__))
;
2188
2189 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
2190 if (!WeightsNode)
2191 return false;
2192
2193 MDString *MDName = cast<MDString>(WeightsNode->getOperand(0));
2194 if (MDName->getString() != "branch_weights")
2195 return false;
2196
2197 // Ensure there are weights for all of the successors. Note that the first
2198 // operand to the metadata node is a name, not a weight.
2199 return WeightsNode->getNumOperands() == TI->getNumSuccessors() + 1;
2200}
2201
2202/// Update the block frequency of BB and branch weight and the metadata on the
2203/// edge BB->SuccBB. This is done by scaling the weight of BB->SuccBB by 1 -
2204/// Freq(PredBB->BB) / Freq(BB->SuccBB).
2205void JumpThreadingPass::UpdateBlockFreqAndEdgeWeight(BasicBlock *PredBB,
2206 BasicBlock *BB,
2207 BasicBlock *NewBB,
2208 BasicBlock *SuccBB) {
2209 if (!HasProfileData)
2210 return;
2211
2212 assert(BFI && BPI && "BFI & BPI should have been created here")((BFI && BPI && "BFI & BPI should have been created here"
) ? static_cast<void> (0) : __assert_fail ("BFI && BPI && \"BFI & BPI should have been created here\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2212, __PRETTY_FUNCTION__))
;
2213
2214 // As the edge from PredBB to BB is deleted, we have to update the block
2215 // frequency of BB.
2216 auto BBOrigFreq = BFI->getBlockFreq(BB);
2217 auto NewBBFreq = BFI->getBlockFreq(NewBB);
2218 auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB);
2219 auto BBNewFreq = BBOrigFreq - NewBBFreq;
2220 BFI->setBlockFreq(BB, BBNewFreq.getFrequency());
2221
2222 // Collect updated outgoing edges' frequencies from BB and use them to update
2223 // edge probabilities.
2224 SmallVector<uint64_t, 4> BBSuccFreq;
2225 for (BasicBlock *Succ : successors(BB)) {
2226 auto SuccFreq = (Succ == SuccBB)
2227 ? BB2SuccBBFreq - NewBBFreq
2228 : BBOrigFreq * BPI->getEdgeProbability(BB, Succ);
2229 BBSuccFreq.push_back(SuccFreq.getFrequency());
2230 }
2231
2232 uint64_t MaxBBSuccFreq =
2233 *std::max_element(BBSuccFreq.begin(), BBSuccFreq.end());
2234
2235 SmallVector<BranchProbability, 4> BBSuccProbs;
2236 if (MaxBBSuccFreq == 0)
2237 BBSuccProbs.assign(BBSuccFreq.size(),
2238 {1, static_cast<unsigned>(BBSuccFreq.size())});
2239 else {
2240 for (uint64_t Freq : BBSuccFreq)
2241 BBSuccProbs.push_back(
2242 BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq));
2243 // Normalize edge probabilities so that they sum up to one.
2244 BranchProbability::normalizeProbabilities(BBSuccProbs.begin(),
2245 BBSuccProbs.end());
2246 }
2247
2248 // Update edge probabilities in BPI.
2249 for (int I = 0, E = BBSuccProbs.size(); I < E; I++)
2250 BPI->setEdgeProbability(BB, I, BBSuccProbs[I]);
2251
2252 // Update the profile metadata as well.
2253 //
2254 // Don't do this if the profile of the transformed blocks was statically
2255 // estimated. (This could occur despite the function having an entry
2256 // frequency in completely cold parts of the CFG.)
2257 //
2258 // In this case we don't want to suggest to subsequent passes that the
2259 // calculated weights are fully consistent. Consider this graph:
2260 //
2261 // check_1
2262 // 50% / |
2263 // eq_1 | 50%
2264 // \ |
2265 // check_2
2266 // 50% / |
2267 // eq_2 | 50%
2268 // \ |
2269 // check_3
2270 // 50% / |
2271 // eq_3 | 50%
2272 // \ |
2273 //
2274 // Assuming the blocks check_* all compare the same value against 1, 2 and 3,
2275 // the overall probabilities are inconsistent; the total probability that the
2276 // value is either 1, 2 or 3 is 150%.
2277 //
2278 // As a consequence if we thread eq_1 -> check_2 to check_3, check_2->check_3
2279 // becomes 0%. This is even worse if the edge whose probability becomes 0% is
2280 // the loop exit edge. Then based solely on static estimation we would assume
2281 // the loop was extremely hot.
2282 //
2283 // FIXME this locally as well so that BPI and BFI are consistent as well. We
2284 // shouldn't make edges extremely likely or unlikely based solely on static
2285 // estimation.
2286 if (BBSuccProbs.size() >= 2 && doesBlockHaveProfileData(BB)) {
2287 SmallVector<uint32_t, 4> Weights;
2288 for (auto Prob : BBSuccProbs)
2289 Weights.push_back(Prob.getNumerator());
2290
2291 auto TI = BB->getTerminator();
2292 TI->setMetadata(
2293 LLVMContext::MD_prof,
2294 MDBuilder(TI->getParent()->getContext()).createBranchWeights(Weights));
2295 }
2296}
2297
2298/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
2299/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
2300/// If we can duplicate the contents of BB up into PredBB do so now, this
2301/// improves the odds that the branch will be on an analyzable instruction like
2302/// a compare.
2303bool JumpThreadingPass::DuplicateCondBranchOnPHIIntoPred(
2304 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) {
2305 assert(!PredBBs.empty() && "Can't handle an empty set")((!PredBBs.empty() && "Can't handle an empty set") ? static_cast
<void> (0) : __assert_fail ("!PredBBs.empty() && \"Can't handle an empty set\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2305, __PRETTY_FUNCTION__))
;
2306
2307 // If BB is a loop header, then duplicating this block outside the loop would
2308 // cause us to transform this into an irreducible loop, don't do this.
2309 // See the comments above FindLoopHeaders for justifications and caveats.
2310 if (LoopHeaders.count(BB)) {
2311 LLVM_DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not duplicating loop header '"
<< BB->getName() << "' into predecessor block '"
<< PredBBs[0]->getName() << "' - it might create an irreducible loop!\n"
; } } while (false)
2312 << "' into predecessor block '" << PredBBs[0]->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not duplicating loop header '"
<< BB->getName() << "' into predecessor block '"
<< PredBBs[0]->getName() << "' - it might create an irreducible loop!\n"
; } } while (false)
2313 << "' - it might create an irreducible loop!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not duplicating loop header '"
<< BB->getName() << "' into predecessor block '"
<< PredBBs[0]->getName() << "' - it might create an irreducible loop!\n"
; } } while (false)
;
2314 return false;
2315 }
2316
2317 unsigned DuplicationCost =
2318 getJumpThreadDuplicationCost(BB, BB->getTerminator(), BBDupThreshold);
2319 if (DuplicationCost > BBDupThreshold) {
2320 LLVM_DEBUG(dbgs() << " Not duplicating BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not duplicating BB '"
<< BB->getName() << "' - Cost is too high: " <<
DuplicationCost << "\n"; } } while (false)
2321 << "' - Cost is too high: " << DuplicationCost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not duplicating BB '"
<< BB->getName() << "' - Cost is too high: " <<
DuplicationCost << "\n"; } } while (false)
;
2322 return false;
2323 }
2324
2325 // And finally, do it! Start by factoring the predecessors if needed.
2326 std::vector<DominatorTree::UpdateType> Updates;
2327 BasicBlock *PredBB;
2328 if (PredBBs.size() == 1)
2329 PredBB = PredBBs[0];
2330 else {
2331 LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Factoring out " <<
PredBBs.size() << " common predecessors.\n"; } } while
(false)
2332 << " common predecessors.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Factoring out " <<
PredBBs.size() << " common predecessors.\n"; } } while
(false)
;
2333 PredBB = SplitBlockPreds(BB, PredBBs, ".thr_comm");
2334 }
2335 Updates.push_back({DominatorTree::Delete, PredBB, BB});
2336
2337 // Okay, we decided to do this! Clone all the instructions in BB onto the end
2338 // of PredBB.
2339 LLVM_DEBUG(dbgs() << " Duplicating block '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Duplicating block '"
<< BB->getName() << "' into end of '" <<
PredBB->getName() << "' to eliminate branch on phi. Cost: "
<< DuplicationCost << " block is:" << *BB <<
"\n"; } } while (false)
2340 << "' into end of '" << PredBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Duplicating block '"
<< BB->getName() << "' into end of '" <<
PredBB->getName() << "' to eliminate branch on phi. Cost: "
<< DuplicationCost << " block is:" << *BB <<
"\n"; } } while (false)
2341 << "' to eliminate branch on phi. Cost: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Duplicating block '"
<< BB->getName() << "' into end of '" <<
PredBB->getName() << "' to eliminate branch on phi. Cost: "
<< DuplicationCost << " block is:" << *BB <<
"\n"; } } while (false)
2342 << DuplicationCost << " block is:" << *BB << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Duplicating block '"
<< BB->getName() << "' into end of '" <<
PredBB->getName() << "' to eliminate branch on phi. Cost: "
<< DuplicationCost << " block is:" << *BB <<
"\n"; } } while (false)
;
2343
2344 // Unless PredBB ends with an unconditional branch, split the edge so that we
2345 // can just clone the bits from BB into the end of the new PredBB.
2346 BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
2347
2348 if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
2349 BasicBlock *OldPredBB = PredBB;
2350 PredBB = SplitEdge(OldPredBB, BB);
2351 Updates.push_back({DominatorTree::Insert, OldPredBB, PredBB});
2352 Updates.push_back({DominatorTree::Insert, PredBB, BB});
2353 Updates.push_back({DominatorTree::Delete, OldPredBB, BB});
2354 OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
2355 }
2356
2357 // We are going to have to map operands from the original BB block into the
2358 // PredBB block. Evaluate PHI nodes in BB.
2359 DenseMap<Instruction*, Value*> ValueMapping;
2360
2361 BasicBlock::iterator BI = BB->begin();
2362 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
2363 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
2364 // Clone the non-phi instructions of BB into PredBB, keeping track of the
2365 // mapping and using it to remap operands in the cloned instructions.
2366 for (; BI != BB->end(); ++BI) {
2367 Instruction *New = BI->clone();
2368
2369 // Remap operands to patch up intra-block references.
2370 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2371 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
2372 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
2373 if (I != ValueMapping.end())
2374 New->setOperand(i, I->second);
2375 }
2376
2377 // If this instruction can be simplified after the operands are updated,
2378 // just use the simplified value instead. This frequently happens due to
2379 // phi translation.
2380 if (Value *IV = SimplifyInstruction(
2381 New,
2382 {BB->getModule()->getDataLayout(), TLI, nullptr, nullptr, New})) {
2383 ValueMapping[&*BI] = IV;
2384 if (!New->mayHaveSideEffects()) {
2385 New->deleteValue();
2386 New = nullptr;
2387 }
2388 } else {
2389 ValueMapping[&*BI] = New;
2390 }
2391 if (New) {
2392 // Otherwise, insert the new instruction into the block.
2393 New->setName(BI->getName());
2394 PredBB->getInstList().insert(OldPredBranch->getIterator(), New);
2395 // Update Dominance from simplified New instruction operands.
2396 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2397 if (BasicBlock *SuccBB = dyn_cast<BasicBlock>(New->getOperand(i)))
2398 Updates.push_back({DominatorTree::Insert, PredBB, SuccBB});
2399 }
2400 }
2401
2402 // Check to see if the targets of the branch had PHI nodes. If so, we need to
2403 // add entries to the PHI nodes for branch from PredBB now.
2404 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
2405 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
2406 ValueMapping);
2407 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
2408 ValueMapping);
2409
2410 UpdateSSA(BB, PredBB, ValueMapping);
2411
2412 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
2413 // that we nuked.
2414 BB->removePredecessor(PredBB, true);
2415
2416 // Remove the unconditional branch at the end of the PredBB block.
2417 OldPredBranch->eraseFromParent();
2418 DTU->applyUpdatesPermissive(Updates);
2419
2420 ++NumDupes;
2421 return true;
2422}
2423
2424// Pred is a predecessor of BB with an unconditional branch to BB. SI is
2425// a Select instruction in Pred. BB has other predecessors and SI is used in
2426// a PHI node in BB. SI has no other use.
2427// A new basic block, NewBB, is created and SI is converted to compare and
2428// conditional branch. SI is erased from parent.
2429void JumpThreadingPass::UnfoldSelectInstr(BasicBlock *Pred, BasicBlock *BB,
2430 SelectInst *SI, PHINode *SIUse,
2431 unsigned Idx) {
2432 // Expand the select.
2433 //
2434 // Pred --
2435 // | v
2436 // | NewBB
2437 // | |
2438 // |-----
2439 // v
2440 // BB
2441 BranchInst *PredTerm = cast<BranchInst>(Pred->getTerminator());
2442 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
2443 BB->getParent(), BB);
2444 // Move the unconditional branch to NewBB.
2445 PredTerm->removeFromParent();
2446 NewBB->getInstList().insert(NewBB->end(), PredTerm);
2447 // Create a conditional branch and update PHI nodes.
2448 BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
2449 SIUse->setIncomingValue(Idx, SI->getFalseValue());
2450 SIUse->addIncoming(SI->getTrueValue(), NewBB);
2451
2452 // The select is now dead.
2453 SI->eraseFromParent();
2454 DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, BB},
2455 {DominatorTree::Insert, Pred, NewBB}});
2456
2457 // Update any other PHI nodes in BB.
2458 for (BasicBlock::iterator BI = BB->begin();
2459 PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
2460 if (Phi != SIUse)
2461 Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
2462}
2463
2464bool JumpThreadingPass::TryToUnfoldSelect(SwitchInst *SI, BasicBlock *BB) {
2465 PHINode *CondPHI = dyn_cast<PHINode>(SI->getCondition());
2466
2467 if (!CondPHI || CondPHI->getParent() != BB)
2468 return false;
2469
2470 for (unsigned I = 0, E = CondPHI->getNumIncomingValues(); I != E; ++I) {
2471 BasicBlock *Pred = CondPHI->getIncomingBlock(I);
2472 SelectInst *PredSI = dyn_cast<SelectInst>(CondPHI->getIncomingValue(I));
2473
2474 // The second and third condition can be potentially relaxed. Currently
2475 // the conditions help to simplify the code and allow us to reuse existing
2476 // code, developed for TryToUnfoldSelect(CmpInst *, BasicBlock *)
2477 if (!PredSI || PredSI->getParent() != Pred || !PredSI->hasOneUse())
2478 continue;
2479
2480 BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
2481 if (!PredTerm || !PredTerm->isUnconditional())
2482 continue;
2483
2484 UnfoldSelectInstr(Pred, BB, PredSI, CondPHI, I);
2485 return true;
2486 }
2487 return false;
2488}
2489
2490/// TryToUnfoldSelect - Look for blocks of the form
2491/// bb1:
2492/// %a = select
2493/// br bb2
2494///
2495/// bb2:
2496/// %p = phi [%a, %bb1] ...
2497/// %c = icmp %p
2498/// br i1 %c
2499///
2500/// And expand the select into a branch structure if one of its arms allows %c
2501/// to be folded. This later enables threading from bb1 over bb2.
2502bool JumpThreadingPass::TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
2503 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
2504 PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
2505 Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
2506
2507 if (!CondBr || !CondBr->isConditional() || !CondLHS ||
2508 CondLHS->getParent() != BB)
2509 return false;
2510
2511 for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
2512 BasicBlock *Pred = CondLHS->getIncomingBlock(I);
2513 SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
2514
2515 // Look if one of the incoming values is a select in the corresponding
2516 // predecessor.
2517 if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
2518 continue;
2519
2520 BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
2521 if (!PredTerm || !PredTerm->isUnconditional())
2522 continue;
2523
2524 // Now check if one of the select values would allow us to constant fold the
2525 // terminator in BB. We don't do the transform if both sides fold, those
2526 // cases will be threaded in any case.
2527 if (DTU->hasPendingDomTreeUpdates())
2528 LVI->disableDT();
2529 else
2530 LVI->enableDT();
2531 LazyValueInfo::Tristate LHSFolds =
2532 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
2533 CondRHS, Pred, BB, CondCmp);
2534 LazyValueInfo::Tristate RHSFolds =
2535 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
2536 CondRHS, Pred, BB, CondCmp);
2537 if ((LHSFolds != LazyValueInfo::Unknown ||
2538 RHSFolds != LazyValueInfo::Unknown) &&
2539 LHSFolds != RHSFolds) {
2540 UnfoldSelectInstr(Pred, BB, SI, CondLHS, I);
2541 return true;
2542 }
2543 }
2544 return false;
2545}
2546
2547/// TryToUnfoldSelectInCurrBB - Look for PHI/Select or PHI/CMP/Select in the
2548/// same BB in the form
2549/// bb:
2550/// %p = phi [false, %bb1], [true, %bb2], [false, %bb3], [true, %bb4], ...
2551/// %s = select %p, trueval, falseval
2552///
2553/// or
2554///
2555/// bb:
2556/// %p = phi [0, %bb1], [1, %bb2], [0, %bb3], [1, %bb4], ...
2557/// %c = cmp %p, 0
2558/// %s = select %c, trueval, falseval
2559///
2560/// And expand the select into a branch structure. This later enables
2561/// jump-threading over bb in this pass.
2562///
2563/// Using the similar approach of SimplifyCFG::FoldCondBranchOnPHI(), unfold
2564/// select if the associated PHI has at least one constant. If the unfolded
2565/// select is not jump-threaded, it will be folded again in the later
2566/// optimizations.
2567bool JumpThreadingPass::TryToUnfoldSelectInCurrBB(BasicBlock *BB) {
2568 // If threading this would thread across a loop header, don't thread the edge.
2569 // See the comments above FindLoopHeaders for justifications and caveats.
2570 if (LoopHeaders.count(BB))
2571 return false;
2572
2573 for (BasicBlock::iterator BI = BB->begin();
2574 PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
2575 // Look for a Phi having at least one constant incoming value.
2576 if (llvm::all_of(PN->incoming_values(),
2577 [](Value *V) { return !isa<ConstantInt>(V); }))
2578 continue;
2579
2580 auto isUnfoldCandidate = [BB](SelectInst *SI, Value *V) {
2581 // Check if SI is in BB and use V as condition.
2582 if (SI->getParent() != BB)
2583 return false;
2584 Value *Cond = SI->getCondition();
2585 return (Cond && Cond == V && Cond->getType()->isIntegerTy(1));
2586 };
2587
2588 SelectInst *SI = nullptr;
2589 for (Use &U : PN->uses()) {
2590 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
2591 // Look for a ICmp in BB that compares PN with a constant and is the
2592 // condition of a Select.
2593 if (Cmp->getParent() == BB && Cmp->hasOneUse() &&
2594 isa<ConstantInt>(Cmp->getOperand(1 - U.getOperandNo())))
2595 if (SelectInst *SelectI = dyn_cast<SelectInst>(Cmp->user_back()))
2596 if (isUnfoldCandidate(SelectI, Cmp->use_begin()->get())) {
2597 SI = SelectI;
2598 break;
2599 }
2600 } else if (SelectInst *SelectI = dyn_cast<SelectInst>(U.getUser())) {
2601 // Look for a Select in BB that uses PN as condition.
2602 if (isUnfoldCandidate(SelectI, U.get())) {
2603 SI = SelectI;
2604 break;
2605 }
2606 }
2607 }
2608
2609 if (!SI)
2610 continue;
2611 // Expand the select.
2612 Instruction *Term =
2613 SplitBlockAndInsertIfThen(SI->getCondition(), SI, false);
2614 BasicBlock *SplitBB = SI->getParent();
2615 BasicBlock *NewBB = Term->getParent();
2616 PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI);
2617 NewPN->addIncoming(SI->getTrueValue(), Term->getParent());
2618 NewPN->addIncoming(SI->getFalseValue(), BB);
2619 SI->replaceAllUsesWith(NewPN);
2620 SI->eraseFromParent();
2621 // NewBB and SplitBB are newly created blocks which require insertion.
2622 std::vector<DominatorTree::UpdateType> Updates;
2623 Updates.reserve((2 * SplitBB->getTerminator()->getNumSuccessors()) + 3);
2624 Updates.push_back({DominatorTree::Insert, BB, SplitBB});
2625 Updates.push_back({DominatorTree::Insert, BB, NewBB});
2626 Updates.push_back({DominatorTree::Insert, NewBB, SplitBB});
2627 // BB's successors were moved to SplitBB, update DTU accordingly.
2628 for (auto *Succ : successors(SplitBB)) {
2629 Updates.push_back({DominatorTree::Delete, BB, Succ});
2630 Updates.push_back({DominatorTree::Insert, SplitBB, Succ});
2631 }
2632 DTU->applyUpdatesPermissive(Updates);
2633 return true;
2634 }
2635 return false;
2636}
2637
2638/// Try to propagate a guard from the current BB into one of its predecessors
2639/// in case if another branch of execution implies that the condition of this
2640/// guard is always true. Currently we only process the simplest case that
2641/// looks like:
2642///
2643/// Start:
2644/// %cond = ...
2645/// br i1 %cond, label %T1, label %F1
2646/// T1:
2647/// br label %Merge
2648/// F1:
2649/// br label %Merge
2650/// Merge:
2651/// %condGuard = ...
2652/// call void(i1, ...) @llvm.experimental.guard( i1 %condGuard )[ "deopt"() ]
2653///
2654/// And cond either implies condGuard or !condGuard. In this case all the
2655/// instructions before the guard can be duplicated in both branches, and the
2656/// guard is then threaded to one of them.
2657bool JumpThreadingPass::ProcessGuards(BasicBlock *BB) {
2658 using namespace PatternMatch;
2659
2660 // We only want to deal with two predecessors.
2661 BasicBlock *Pred1, *Pred2;
2662 auto PI = pred_begin(BB), PE = pred_end(BB);
2663 if (PI == PE)
2664 return false;
2665 Pred1 = *PI++;
2666 if (PI == PE)
2667 return false;
2668 Pred2 = *PI++;
2669 if (PI != PE)
2670 return false;
2671 if (Pred1 == Pred2)
2672 return false;
2673
2674 // Try to thread one of the guards of the block.
2675 // TODO: Look up deeper than to immediate predecessor?
2676 auto *Parent = Pred1->getSinglePredecessor();
2677 if (!Parent || Parent != Pred2->getSinglePredecessor())
2678 return false;
2679
2680 if (auto *BI = dyn_cast<BranchInst>(Parent->getTerminator()))
2681 for (auto &I : *BB)
2682 if (isGuard(&I) && ThreadGuard(BB, cast<IntrinsicInst>(&I), BI))
2683 return true;
2684
2685 return false;
2686}
2687
2688/// Try to propagate the guard from BB which is the lower block of a diamond
2689/// to one of its branches, in case if diamond's condition implies guard's
2690/// condition.
2691bool JumpThreadingPass::ThreadGuard(BasicBlock *BB, IntrinsicInst *Guard,
2692 BranchInst *BI) {
2693 assert(BI->getNumSuccessors() == 2 && "Wrong number of successors?")((BI->getNumSuccessors() == 2 && "Wrong number of successors?"
) ? static_cast<void> (0) : __assert_fail ("BI->getNumSuccessors() == 2 && \"Wrong number of successors?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2693, __PRETTY_FUNCTION__))
;
2694 assert(BI->isConditional() && "Unconditional branch has 2 successors?")((BI->isConditional() && "Unconditional branch has 2 successors?"
) ? static_cast<void> (0) : __assert_fail ("BI->isConditional() && \"Unconditional branch has 2 successors?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2694, __PRETTY_FUNCTION__))
;
2695 Value *GuardCond = Guard->getArgOperand(0);
2696 Value *BranchCond = BI->getCondition();
2697 BasicBlock *TrueDest = BI->getSuccessor(0);
2698 BasicBlock *FalseDest = BI->getSuccessor(1);
2699
2700 auto &DL = BB->getModule()->getDataLayout();
2701 bool TrueDestIsSafe = false;
2702 bool FalseDestIsSafe = false;
2703
2704 // True dest is safe if BranchCond => GuardCond.
2705 auto Impl = isImpliedCondition(BranchCond, GuardCond, DL);
2706 if (Impl && *Impl)
2707 TrueDestIsSafe = true;
2708 else {
2709 // False dest is safe if !BranchCond => GuardCond.
2710 Impl = isImpliedCondition(BranchCond, GuardCond, DL, /* LHSIsTrue */ false);
2711 if (Impl && *Impl)
2712 FalseDestIsSafe = true;
2713 }
2714
2715 if (!TrueDestIsSafe && !FalseDestIsSafe)
2716 return false;
2717
2718 BasicBlock *PredUnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest;
2719 BasicBlock *PredGuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest;
2720
2721 ValueToValueMapTy UnguardedMapping, GuardedMapping;
2722 Instruction *AfterGuard = Guard->getNextNode();
2723 unsigned Cost = getJumpThreadDuplicationCost(BB, AfterGuard, BBDupThreshold);
2724 if (Cost > BBDupThreshold)
2725 return false;
2726 // Duplicate all instructions before the guard and the guard itself to the
2727 // branch where implication is not proved.
2728 BasicBlock *GuardedBlock = DuplicateInstructionsInSplitBetween(
2729 BB, PredGuardedBlock, AfterGuard, GuardedMapping, *DTU);
2730 assert(GuardedBlock && "Could not create the guarded block?")((GuardedBlock && "Could not create the guarded block?"
) ? static_cast<void> (0) : __assert_fail ("GuardedBlock && \"Could not create the guarded block?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2730, __PRETTY_FUNCTION__))
;
2731 // Duplicate all instructions before the guard in the unguarded branch.
2732 // Since we have successfully duplicated the guarded block and this block
2733 // has fewer instructions, we expect it to succeed.
2734 BasicBlock *UnguardedBlock = DuplicateInstructionsInSplitBetween(
2735 BB, PredUnguardedBlock, Guard, UnguardedMapping, *DTU);
2736 assert(UnguardedBlock && "Could not create the unguarded block?")((UnguardedBlock && "Could not create the unguarded block?"
) ? static_cast<void> (0) : __assert_fail ("UnguardedBlock && \"Could not create the unguarded block?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2736, __PRETTY_FUNCTION__))
;
2737 LLVM_DEBUG(dbgs() << "Moved guard " << *Guard << " to block "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "Moved guard " <<
*Guard << " to block " << GuardedBlock->getName
() << "\n"; } } while (false)
2738 << GuardedBlock->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "Moved guard " <<
*Guard << " to block " << GuardedBlock->getName
() << "\n"; } } while (false)
;
2739 // Some instructions before the guard may still have uses. For them, we need
2740 // to create Phi nodes merging their copies in both guarded and unguarded
2741 // branches. Those instructions that have no uses can be just removed.
2742 SmallVector<Instruction *, 4> ToRemove;
2743 for (auto BI = BB->begin(); &*BI != AfterGuard; ++BI)
2744 if (!isa<PHINode>(&*BI))
2745 ToRemove.push_back(&*BI);
2746
2747 Instruction *InsertionPoint = &*BB->getFirstInsertionPt();
2748 assert(InsertionPoint && "Empty block?")((InsertionPoint && "Empty block?") ? static_cast<
void> (0) : __assert_fail ("InsertionPoint && \"Empty block?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2748, __PRETTY_FUNCTION__))
;
2749 // Substitute with Phis & remove.
2750 for (auto *Inst : reverse(ToRemove)) {
2751 if (!Inst->use_empty()) {
2752 PHINode *NewPN = PHINode::Create(Inst->getType(), 2);
2753 NewPN->addIncoming(UnguardedMapping[Inst], UnguardedBlock);
2754 NewPN->addIncoming(GuardedMapping[Inst], GuardedBlock);
2755 NewPN->insertBefore(InsertionPoint);
2756 Inst->replaceAllUsesWith(NewPN);
2757 }
2758 Inst->eraseFromParent();
2759 }
2760 return true;
2761}

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

<
1//===- llvm/Instructions.h - Instruction subclass definitions ---*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file exposes the class definitions of all of the subclasses of the
10// Instruction class. This is meant to be an easy way to get access to all
11// instruction subclasses.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_INSTRUCTIONS_H
16#define LLVM_IR_INSTRUCTIONS_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/None.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/ADT/Twine.h"
24#include "llvm/ADT/iterator.h"
25#include "llvm/ADT/iterator_range.h"
26#include "llvm/IR/Attributes.h"
27#include "llvm/IR/BasicBlock.h"
28#include "llvm/IR/CallingConv.h"
29#include "llvm/IR/Constant.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/Instruction.h"
34#include "llvm/IR/OperandTraits.h"
35#include "llvm/IR/Type.h"
36#include "llvm/IR/Use.h"
37#include "llvm/IR/User.h"
38#include "llvm/IR/Value.h"
39#include "llvm/Support/AtomicOrdering.h"
40#include "llvm/Support/Casting.h"
41#include "llvm/Support/ErrorHandling.h"
42#include <cassert>
43#include <cstddef>
44#include <cstdint>
45#include <iterator>
46
47namespace llvm {
48
49class APInt;
50class ConstantInt;
51class DataLayout;
52class LLVMContext;
53
54//===----------------------------------------------------------------------===//
55// AllocaInst Class
56//===----------------------------------------------------------------------===//
57
58/// an instruction to allocate memory on the stack
59class AllocaInst : public UnaryInstruction {
60 Type *AllocatedType;
61
62protected:
63 // Note: Instruction needs to be a friend here to call cloneImpl.
64 friend class Instruction;
65
66 AllocaInst *cloneImpl() const;
67
68public:
69 explicit AllocaInst(Type *Ty, unsigned AddrSpace,
70 Value *ArraySize = nullptr,
71 const Twine &Name = "",
72 Instruction *InsertBefore = nullptr);
73 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
74 const Twine &Name, BasicBlock *InsertAtEnd);
75
76 AllocaInst(Type *Ty, unsigned AddrSpace,
77 const Twine &Name, Instruction *InsertBefore = nullptr);
78 AllocaInst(Type *Ty, unsigned AddrSpace,
79 const Twine &Name, BasicBlock *InsertAtEnd);
80
81 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, MaybeAlign Align,
82 const Twine &Name = "", Instruction *InsertBefore = nullptr);
83 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, MaybeAlign Align,
84 const Twine &Name, BasicBlock *InsertAtEnd);
85
86 /// Return true if there is an allocation size parameter to the allocation
87 /// instruction that is not 1.
88 bool isArrayAllocation() const;
89
90 /// Get the number of elements allocated. For a simple allocation of a single
91 /// element, this will return a constant 1 value.
92 const Value *getArraySize() const { return getOperand(0); }
93 Value *getArraySize() { return getOperand(0); }
94
95 /// Overload to return most specific pointer type.
96 PointerType *getType() const {
97 return cast<PointerType>(Instruction::getType());
98 }
99
100 /// Get allocation size in bits. Returns None if size can't be determined,
101 /// e.g. in case of a VLA.
102 Optional<uint64_t> getAllocationSizeInBits(const DataLayout &DL) const;
103
104 /// Return the type that is being allocated by the instruction.
105 Type *getAllocatedType() const { return AllocatedType; }
106 /// for use only in special circumstances that need to generically
107 /// transform a whole instruction (eg: IR linking and vectorization).
108 void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
109
110 /// Return the alignment of the memory that is being allocated by the
111 /// instruction.
112 unsigned getAlignment() const {
113 if (const auto MA = decodeMaybeAlign(getSubclassDataFromInstruction() & 31))
114 return MA->value();
115 return 0;
116 }
117 void setAlignment(MaybeAlign Align);
118
119 /// Return true if this alloca is in the entry block of the function and is a
120 /// constant size. If so, the code generator will fold it into the
121 /// prolog/epilog code, so it is basically free.
122 bool isStaticAlloca() const;
123
124 /// Return true if this alloca is used as an inalloca argument to a call. Such
125 /// allocas are never considered static even if they are in the entry block.
126 bool isUsedWithInAlloca() const {
127 return getSubclassDataFromInstruction() & 32;
128 }
129
130 /// Specify whether this alloca is used to represent the arguments to a call.
131 void setUsedWithInAlloca(bool V) {
132 setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
133 (V ? 32 : 0));
134 }
135
136 /// Return true if this alloca is used as a swifterror argument to a call.
137 bool isSwiftError() const {
138 return getSubclassDataFromInstruction() & 64;
139 }
140
141 /// Specify whether this alloca is used to represent a swifterror.
142 void setSwiftError(bool V) {
143 setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) |
144 (V ? 64 : 0));
145 }
146
147 // Methods for support type inquiry through isa, cast, and dyn_cast:
148 static bool classof(const Instruction *I) {
149 return (I->getOpcode() == Instruction::Alloca);
150 }
151 static bool classof(const Value *V) {
152 return isa<Instruction>(V) && classof(cast<Instruction>(V));
153 }
154
155private:
156 // Shadow Instruction::setInstructionSubclassData with a private forwarding
157 // method so that subclasses cannot accidentally use it.
158 void setInstructionSubclassData(unsigned short D) {
159 Instruction::setInstructionSubclassData(D);
160 }
161};
162
163//===----------------------------------------------------------------------===//
164// LoadInst Class
165//===----------------------------------------------------------------------===//
166
167/// An instruction for reading from memory. This uses the SubclassData field in
168/// Value to store whether or not the load is volatile.
169class LoadInst : public UnaryInstruction {
170 void AssertOK();
171
172protected:
173 // Note: Instruction needs to be a friend here to call cloneImpl.
174 friend class Instruction;
175
176 LoadInst *cloneImpl() const;
177
178public:
179 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr = "",
180 Instruction *InsertBefore = nullptr);
181 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
182 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
183 Instruction *InsertBefore = nullptr);
184 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
185 BasicBlock *InsertAtEnd);
186 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
187 MaybeAlign Align, Instruction *InsertBefore = nullptr);
188 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
189 MaybeAlign Align, BasicBlock *InsertAtEnd);
190 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
191 MaybeAlign Align, AtomicOrdering Order,
192 SyncScope::ID SSID = SyncScope::System,
193 Instruction *InsertBefore = nullptr);
194 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
195 MaybeAlign Align, AtomicOrdering Order, SyncScope::ID SSID,
196 BasicBlock *InsertAtEnd);
197
198 // Deprecated [opaque pointer types]
199 explicit LoadInst(Value *Ptr, const Twine &NameStr = "",
200 Instruction *InsertBefore = nullptr)
201 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
202 InsertBefore) {}
203 LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd)
204 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
205 InsertAtEnd) {}
206 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
207 Instruction *InsertBefore = nullptr)
208 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
209 isVolatile, InsertBefore) {}
210 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
211 BasicBlock *InsertAtEnd)
212 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
213 isVolatile, InsertAtEnd) {}
214 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
215 Instruction *InsertBefore = nullptr)
216 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
217 isVolatile, Align, InsertBefore) {}
218 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
219 BasicBlock *InsertAtEnd)
220 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
221 isVolatile, Align, InsertAtEnd) {}
222 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
223 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
224 Instruction *InsertBefore = nullptr)
225 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
226 isVolatile, Align, Order, SSID, InsertBefore) {}
227 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
228 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd)
229 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
230 isVolatile, Align, Order, SSID, InsertAtEnd) {}
231
232 /// Return true if this is a load from a volatile memory location.
233 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
234
235 /// Specify whether this is a volatile load or not.
236 void setVolatile(bool V) {
237 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
238 (V ? 1 : 0));
239 }
240
241 /// Return the alignment of the access that is being performed.
242 /// FIXME: Remove this function once transition to Align is over.
243 /// Use getAlign() instead.
244 unsigned getAlignment() const {
245 if (const auto MA = getAlign())
246 return MA->value();
247 return 0;
248 }
249
250 /// Return the alignment of the access that is being performed.
251 MaybeAlign getAlign() const {
252 return decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31);
253 }
254
255 void setAlignment(MaybeAlign Alignment);
256
257 /// Returns the ordering constraint of this load instruction.
258 AtomicOrdering getOrdering() const {
259 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
260 }
261
262 /// Sets the ordering constraint of this load instruction. May not be Release
263 /// or AcquireRelease.
264 void setOrdering(AtomicOrdering Ordering) {
265 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
266 ((unsigned)Ordering << 7));
267 }
268
269 /// Returns the synchronization scope ID of this load instruction.
270 SyncScope::ID getSyncScopeID() const {
271 return SSID;
272 }
273
274 /// Sets the synchronization scope ID of this load instruction.
275 void setSyncScopeID(SyncScope::ID SSID) {
276 this->SSID = SSID;
277 }
278
279 /// Sets the ordering constraint and the synchronization scope ID of this load
280 /// instruction.
281 void setAtomic(AtomicOrdering Ordering,
282 SyncScope::ID SSID = SyncScope::System) {
283 setOrdering(Ordering);
284 setSyncScopeID(SSID);
285 }
286
287 bool isSimple() const { return !isAtomic() && !isVolatile(); }
288
289 bool isUnordered() const {
290 return (getOrdering() == AtomicOrdering::NotAtomic ||
33
Assuming the condition is false
36
Returning the value 1, which participates in a condition later
291 getOrdering() == AtomicOrdering::Unordered) &&
34
Assuming the condition is true
292 !isVolatile();
35
Assuming the condition is true
293 }
294
295 Value *getPointerOperand() { return getOperand(0); }
296 const Value *getPointerOperand() const { return getOperand(0); }
297 static unsigned getPointerOperandIndex() { return 0U; }
298 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
299
300 /// Returns the address space of the pointer operand.
301 unsigned getPointerAddressSpace() const {
302 return getPointerOperandType()->getPointerAddressSpace();
303 }
304
305 // Methods for support type inquiry through isa, cast, and dyn_cast:
306 static bool classof(const Instruction *I) {
307 return I->getOpcode() == Instruction::Load;
308 }
309 static bool classof(const Value *V) {
310 return isa<Instruction>(V) && classof(cast<Instruction>(V));
311 }
312
313private:
314 // Shadow Instruction::setInstructionSubclassData with a private forwarding
315 // method so that subclasses cannot accidentally use it.
316 void setInstructionSubclassData(unsigned short D) {
317 Instruction::setInstructionSubclassData(D);
318 }
319
320 /// The synchronization scope ID of this load instruction. Not quite enough
321 /// room in SubClassData for everything, so synchronization scope ID gets its
322 /// own field.
323 SyncScope::ID SSID;
324};
325
326//===----------------------------------------------------------------------===//
327// StoreInst Class
328//===----------------------------------------------------------------------===//
329
330/// An instruction for storing to memory.
331class StoreInst : public Instruction {
332 void AssertOK();
333
334protected:
335 // Note: Instruction needs to be a friend here to call cloneImpl.
336 friend class Instruction;
337
338 StoreInst *cloneImpl() const;
339
340public:
341 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
342 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
343 StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
344 Instruction *InsertBefore = nullptr);
345 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
346 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
347 Instruction *InsertBefore = nullptr);
348 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
349 BasicBlock *InsertAtEnd);
350 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
351 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
352 Instruction *InsertBefore = nullptr);
353 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
354 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd);
355
356 // allocate space for exactly two operands
357 void *operator new(size_t s) {
358 return User::operator new(s, 2);
359 }
360
361 /// Return true if this is a store to a volatile memory location.
362 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
363
364 /// Specify whether this is a volatile store or not.
365 void setVolatile(bool V) {
366 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
367 (V ? 1 : 0));
368 }
369
370 /// Transparently provide more efficient getOperand methods.
371 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
372
373 /// Return the alignment of the access that is being performed
374 /// FIXME: Remove this function once transition to Align is over.
375 /// Use getAlign() instead.
376 unsigned getAlignment() const {
377 if (const auto MA = getAlign())
378 return MA->value();
379 return 0;
380 }
381
382 MaybeAlign getAlign() const {
383 return decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31);
384 }
385
386 void setAlignment(MaybeAlign Alignment);
387
388 /// Returns the ordering constraint of this store instruction.
389 AtomicOrdering getOrdering() const {
390 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
391 }
392
393 /// Sets the ordering constraint of this store instruction. May not be
394 /// Acquire or AcquireRelease.
395 void setOrdering(AtomicOrdering Ordering) {
396 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
397 ((unsigned)Ordering << 7));
398 }
399
400 /// Returns the synchronization scope ID of this store instruction.
401 SyncScope::ID getSyncScopeID() const {
402 return SSID;
403 }
404
405 /// Sets the synchronization scope ID of this store instruction.
406 void setSyncScopeID(SyncScope::ID SSID) {
407 this->SSID = SSID;
408 }
409
410 /// Sets the ordering constraint and the synchronization scope ID of this
411 /// store instruction.
412 void setAtomic(AtomicOrdering Ordering,
413 SyncScope::ID SSID = SyncScope::System) {
414 setOrdering(Ordering);
415 setSyncScopeID(SSID);
416 }
417
418 bool isSimple() const { return !isAtomic() && !isVolatile(); }
419
420 bool isUnordered() const {
421 return (getOrdering() == AtomicOrdering::NotAtomic ||
422 getOrdering() == AtomicOrdering::Unordered) &&
423 !isVolatile();
424 }
425
426 Value *getValueOperand() { return getOperand(0); }
427 const Value *getValueOperand() const { return getOperand(0); }
428
429 Value *getPointerOperand() { return getOperand(1); }
430 const Value *getPointerOperand() const { return getOperand(1); }
431 static unsigned getPointerOperandIndex() { return 1U; }
432 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
433
434 /// Returns the address space of the pointer operand.
435 unsigned getPointerAddressSpace() const {
436 return getPointerOperandType()->getPointerAddressSpace();
437 }
438
439 // Methods for support type inquiry through isa, cast, and dyn_cast:
440 static bool classof(const Instruction *I) {
441 return I->getOpcode() == Instruction::Store;
442 }
443 static bool classof(const Value *V) {
444 return isa<Instruction>(V) && classof(cast<Instruction>(V));
445 }
446
447private:
448 // Shadow Instruction::setInstructionSubclassData with a private forwarding
449 // method so that subclasses cannot accidentally use it.
450 void setInstructionSubclassData(unsigned short D) {
451 Instruction::setInstructionSubclassData(D);
452 }
453
454 /// The synchronization scope ID of this store instruction. Not quite enough
455 /// room in SubClassData for everything, so synchronization scope ID gets its
456 /// own field.
457 SyncScope::ID SSID;
458};
459
460template <>
461struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
462};
463
464DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)StoreInst::op_iterator StoreInst::op_begin() { return OperandTraits
<StoreInst>::op_begin(this); } StoreInst::const_op_iterator
StoreInst::op_begin() const { return OperandTraits<StoreInst
>::op_begin(const_cast<StoreInst*>(this)); } StoreInst
::op_iterator StoreInst::op_end() { return OperandTraits<StoreInst
>::op_end(this); } StoreInst::const_op_iterator StoreInst::
op_end() const { return OperandTraits<StoreInst>::op_end
(const_cast<StoreInst*>(this)); } Value *StoreInst::getOperand
(unsigned i_nocapture) const { ((i_nocapture < OperandTraits
<StoreInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 464, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<StoreInst>::op_begin(const_cast<StoreInst
*>(this))[i_nocapture].get()); } void StoreInst::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<StoreInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 464, __PRETTY_FUNCTION__)); OperandTraits<StoreInst>::
op_begin(this)[i_nocapture] = Val_nocapture; } unsigned StoreInst
::getNumOperands() const { return OperandTraits<StoreInst>
::operands(this); } template <int Idx_nocapture> Use &
StoreInst::Op() { return this->OpFrom<Idx_nocapture>
(this); } template <int Idx_nocapture> const Use &StoreInst
::Op() const { return this->OpFrom<Idx_nocapture>(this
); }
465
466//===----------------------------------------------------------------------===//
467// FenceInst Class
468//===----------------------------------------------------------------------===//
469
470/// An instruction for ordering other memory operations.
471class FenceInst : public Instruction {
472 void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
473
474protected:
475 // Note: Instruction needs to be a friend here to call cloneImpl.
476 friend class Instruction;
477
478 FenceInst *cloneImpl() const;
479
480public:
481 // Ordering may only be Acquire, Release, AcquireRelease, or
482 // SequentiallyConsistent.
483 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
484 SyncScope::ID SSID = SyncScope::System,
485 Instruction *InsertBefore = nullptr);
486 FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
487 BasicBlock *InsertAtEnd);
488
489 // allocate space for exactly zero operands
490 void *operator new(size_t s) {
491 return User::operator new(s, 0);
492 }
493
494 /// Returns the ordering constraint of this fence instruction.
495 AtomicOrdering getOrdering() const {
496 return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
497 }
498
499 /// Sets the ordering constraint of this fence instruction. May only be
500 /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
501 void setOrdering(AtomicOrdering Ordering) {
502 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
503 ((unsigned)Ordering << 1));
504 }
505
506 /// Returns the synchronization scope ID of this fence instruction.
507 SyncScope::ID getSyncScopeID() const {
508 return SSID;
509 }
510
511 /// Sets the synchronization scope ID of this fence instruction.
512 void setSyncScopeID(SyncScope::ID SSID) {
513 this->SSID = SSID;
514 }
515
516 // Methods for support type inquiry through isa, cast, and dyn_cast:
517 static bool classof(const Instruction *I) {
518 return I->getOpcode() == Instruction::Fence;
519 }
520 static bool classof(const Value *V) {
521 return isa<Instruction>(V) && classof(cast<Instruction>(V));
522 }
523
524private:
525 // Shadow Instruction::setInstructionSubclassData with a private forwarding
526 // method so that subclasses cannot accidentally use it.
527 void setInstructionSubclassData(unsigned short D) {
528 Instruction::setInstructionSubclassData(D);
529 }
530
531 /// The synchronization scope ID of this fence instruction. Not quite enough
532 /// room in SubClassData for everything, so synchronization scope ID gets its
533 /// own field.
534 SyncScope::ID SSID;
535};
536
537//===----------------------------------------------------------------------===//
538// AtomicCmpXchgInst Class
539//===----------------------------------------------------------------------===//
540
541/// An instruction that atomically checks whether a
542/// specified value is in a memory location, and, if it is, stores a new value
543/// there. The value returned by this instruction is a pair containing the
544/// original value as first element, and an i1 indicating success (true) or
545/// failure (false) as second element.
546///
547class AtomicCmpXchgInst : public Instruction {
548 void Init(Value *Ptr, Value *Cmp, Value *NewVal,
549 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
550 SyncScope::ID SSID);
551
552protected:
553 // Note: Instruction needs to be a friend here to call cloneImpl.
554 friend class Instruction;
555
556 AtomicCmpXchgInst *cloneImpl() const;
557
558public:
559 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
560 AtomicOrdering SuccessOrdering,
561 AtomicOrdering FailureOrdering,
562 SyncScope::ID SSID, Instruction *InsertBefore = nullptr);
563 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
564 AtomicOrdering SuccessOrdering,
565 AtomicOrdering FailureOrdering,
566 SyncScope::ID SSID, BasicBlock *InsertAtEnd);
567
568 // allocate space for exactly three operands
569 void *operator new(size_t s) {
570 return User::operator new(s, 3);
571 }
572
573 /// Return true if this is a cmpxchg from a volatile memory
574 /// location.
575 ///
576 bool isVolatile() const {
577 return getSubclassDataFromInstruction() & 1;
578 }
579
580 /// Specify whether this is a volatile cmpxchg.
581 ///
582 void setVolatile(bool V) {
583 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
584 (unsigned)V);
585 }
586
587 /// Return true if this cmpxchg may spuriously fail.
588 bool isWeak() const {
589 return getSubclassDataFromInstruction() & 0x100;
590 }
591
592 void setWeak(bool IsWeak) {
593 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
594 (IsWeak << 8));
595 }
596
597 /// Transparently provide more efficient getOperand methods.
598 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
599
600 /// Returns the success ordering constraint of this cmpxchg instruction.
601 AtomicOrdering getSuccessOrdering() const {
602 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
603 }
604
605 /// Sets the success ordering constraint of this cmpxchg instruction.
606 void setSuccessOrdering(AtomicOrdering Ordering) {
607 assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 608, __PRETTY_FUNCTION__))
608 "CmpXchg instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 608, __PRETTY_FUNCTION__))
;
609 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
610 ((unsigned)Ordering << 2));
611 }
612
613 /// Returns the failure ordering constraint of this cmpxchg instruction.
614 AtomicOrdering getFailureOrdering() const {
615 return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
616 }
617
618 /// Sets the failure ordering constraint of this cmpxchg instruction.
619 void setFailureOrdering(AtomicOrdering Ordering) {
620 assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 621, __PRETTY_FUNCTION__))
621 "CmpXchg instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 621, __PRETTY_FUNCTION__))
;
622 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
623 ((unsigned)Ordering << 5));
624 }
625
626 /// Returns the synchronization scope ID of this cmpxchg instruction.
627 SyncScope::ID getSyncScopeID() const {
628 return SSID;
629 }
630
631 /// Sets the synchronization scope ID of this cmpxchg instruction.
632 void setSyncScopeID(SyncScope::ID SSID) {
633 this->SSID = SSID;
634 }
635
636 Value *getPointerOperand() { return getOperand(0); }
637 const Value *getPointerOperand() const { return getOperand(0); }
638 static unsigned getPointerOperandIndex() { return 0U; }
639
640 Value *getCompareOperand() { return getOperand(1); }
641 const Value *getCompareOperand() const { return getOperand(1); }
642
643 Value *getNewValOperand() { return getOperand(2); }
644 const Value *getNewValOperand() const { return getOperand(2); }
645
646 /// Returns the address space of the pointer operand.
647 unsigned getPointerAddressSpace() const {
648 return getPointerOperand()->getType()->getPointerAddressSpace();
649 }
650
651 /// Returns the strongest permitted ordering on failure, given the
652 /// desired ordering on success.
653 ///
654 /// If the comparison in a cmpxchg operation fails, there is no atomic store
655 /// so release semantics cannot be provided. So this function drops explicit
656 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
657 /// operation would remain SequentiallyConsistent.
658 static AtomicOrdering
659 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
660 switch (SuccessOrdering) {
661 default:
662 llvm_unreachable("invalid cmpxchg success ordering")::llvm::llvm_unreachable_internal("invalid cmpxchg success ordering"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 662)
;
663 case AtomicOrdering::Release:
664 case AtomicOrdering::Monotonic:
665 return AtomicOrdering::Monotonic;
666 case AtomicOrdering::AcquireRelease:
667 case AtomicOrdering::Acquire:
668 return AtomicOrdering::Acquire;
669 case AtomicOrdering::SequentiallyConsistent:
670 return AtomicOrdering::SequentiallyConsistent;
671 }
672 }
673
674 // Methods for support type inquiry through isa, cast, and dyn_cast:
675 static bool classof(const Instruction *I) {
676 return I->getOpcode() == Instruction::AtomicCmpXchg;
677 }
678 static bool classof(const Value *V) {
679 return isa<Instruction>(V) && classof(cast<Instruction>(V));
680 }
681
682private:
683 // Shadow Instruction::setInstructionSubclassData with a private forwarding
684 // method so that subclasses cannot accidentally use it.
685 void setInstructionSubclassData(unsigned short D) {
686 Instruction::setInstructionSubclassData(D);
687 }
688
689 /// The synchronization scope ID of this cmpxchg instruction. Not quite
690 /// enough room in SubClassData for everything, so synchronization scope ID
691 /// gets its own field.
692 SyncScope::ID SSID;
693};
694
695template <>
696struct OperandTraits<AtomicCmpXchgInst> :
697 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
698};
699
700DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)AtomicCmpXchgInst::op_iterator AtomicCmpXchgInst::op_begin() {
return OperandTraits<AtomicCmpXchgInst>::op_begin(this
); } AtomicCmpXchgInst::const_op_iterator AtomicCmpXchgInst::
op_begin() const { return OperandTraits<AtomicCmpXchgInst>
::op_begin(const_cast<AtomicCmpXchgInst*>(this)); } AtomicCmpXchgInst
::op_iterator AtomicCmpXchgInst::op_end() { return OperandTraits
<AtomicCmpXchgInst>::op_end(this); } AtomicCmpXchgInst::
const_op_iterator AtomicCmpXchgInst::op_end() const { return OperandTraits
<AtomicCmpXchgInst>::op_end(const_cast<AtomicCmpXchgInst
*>(this)); } Value *AtomicCmpXchgInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<AtomicCmpXchgInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 700, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<AtomicCmpXchgInst>::op_begin(const_cast
<AtomicCmpXchgInst*>(this))[i_nocapture].get()); } void
AtomicCmpXchgInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<AtomicCmpXchgInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 700, __PRETTY_FUNCTION__)); OperandTraits<AtomicCmpXchgInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
AtomicCmpXchgInst::getNumOperands() const { return OperandTraits
<AtomicCmpXchgInst>::operands(this); } template <int
Idx_nocapture> Use &AtomicCmpXchgInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &AtomicCmpXchgInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
701
702//===----------------------------------------------------------------------===//
703// AtomicRMWInst Class
704//===----------------------------------------------------------------------===//
705
706/// an instruction that atomically reads a memory location,
707/// combines it with another value, and then stores the result back. Returns
708/// the old value.
709///
710class AtomicRMWInst : public Instruction {
711protected:
712 // Note: Instruction needs to be a friend here to call cloneImpl.
713 friend class Instruction;
714
715 AtomicRMWInst *cloneImpl() const;
716
717public:
718 /// This enumeration lists the possible modifications atomicrmw can make. In
719 /// the descriptions, 'p' is the pointer to the instruction's memory location,
720 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
721 /// instruction. These instructions always return 'old'.
722 enum BinOp {
723 /// *p = v
724 Xchg,
725 /// *p = old + v
726 Add,
727 /// *p = old - v
728 Sub,
729 /// *p = old & v
730 And,
731 /// *p = ~(old & v)
732 Nand,
733 /// *p = old | v
734 Or,
735 /// *p = old ^ v
736 Xor,
737 /// *p = old >signed v ? old : v
738 Max,
739 /// *p = old <signed v ? old : v
740 Min,
741 /// *p = old >unsigned v ? old : v
742 UMax,
743 /// *p = old <unsigned v ? old : v
744 UMin,
745
746 /// *p = old + v
747 FAdd,
748
749 /// *p = old - v
750 FSub,
751
752 FIRST_BINOP = Xchg,
753 LAST_BINOP = FSub,
754 BAD_BINOP
755 };
756
757 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
758 AtomicOrdering Ordering, SyncScope::ID SSID,
759 Instruction *InsertBefore = nullptr);
760 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
761 AtomicOrdering Ordering, SyncScope::ID SSID,
762 BasicBlock *InsertAtEnd);
763
764 // allocate space for exactly two operands
765 void *operator new(size_t s) {
766 return User::operator new(s, 2);
767 }
768
769 BinOp getOperation() const {
770 return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
771 }
772
773 static StringRef getOperationName(BinOp Op);
774
775 static bool isFPOperation(BinOp Op) {
776 switch (Op) {
777 case AtomicRMWInst::FAdd:
778 case AtomicRMWInst::FSub:
779 return true;
780 default:
781 return false;
782 }
783 }
784
785 void setOperation(BinOp Operation) {
786 unsigned short SubclassData = getSubclassDataFromInstruction();
787 setInstructionSubclassData((SubclassData & 31) |
788 (Operation << 5));
789 }
790
791 /// Return true if this is a RMW on a volatile memory location.
792 ///
793 bool isVolatile() const {
794 return getSubclassDataFromInstruction() & 1;
795 }
796
797 /// Specify whether this is a volatile RMW or not.
798 ///
799 void setVolatile(bool V) {
800 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
801 (unsigned)V);
802 }
803
804 /// Transparently provide more efficient getOperand methods.
805 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
806
807 /// Returns the ordering constraint of this rmw instruction.
808 AtomicOrdering getOrdering() const {
809 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
810 }
811
812 /// Sets the ordering constraint of this rmw instruction.
813 void setOrdering(AtomicOrdering Ordering) {
814 assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 815, __PRETTY_FUNCTION__))
815 "atomicrmw instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 815, __PRETTY_FUNCTION__))
;
816 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
817 ((unsigned)Ordering << 2));
818 }
819
820 /// Returns the synchronization scope ID of this rmw instruction.
821 SyncScope::ID getSyncScopeID() const {
822 return SSID;
823 }
824
825 /// Sets the synchronization scope ID of this rmw instruction.
826 void setSyncScopeID(SyncScope::ID SSID) {
827 this->SSID = SSID;
828 }
829
830 Value *getPointerOperand() { return getOperand(0); }
831 const Value *getPointerOperand() const { return getOperand(0); }
832 static unsigned getPointerOperandIndex() { return 0U; }
833
834 Value *getValOperand() { return getOperand(1); }
835 const Value *getValOperand() const { return getOperand(1); }
836
837 /// Returns the address space of the pointer operand.
838 unsigned getPointerAddressSpace() const {
839 return getPointerOperand()->getType()->getPointerAddressSpace();
840 }
841
842 bool isFloatingPointOperation() const {
843 return isFPOperation(getOperation());
844 }
845
846 // Methods for support type inquiry through isa, cast, and dyn_cast:
847 static bool classof(const Instruction *I) {
848 return I->getOpcode() == Instruction::AtomicRMW;
849 }
850 static bool classof(const Value *V) {
851 return isa<Instruction>(V) && classof(cast<Instruction>(V));
852 }
853
854private:
855 void Init(BinOp Operation, Value *Ptr, Value *Val,
856 AtomicOrdering Ordering, SyncScope::ID SSID);
857
858 // Shadow Instruction::setInstructionSubclassData with a private forwarding
859 // method so that subclasses cannot accidentally use it.
860 void setInstructionSubclassData(unsigned short D) {
861 Instruction::setInstructionSubclassData(D);
862 }
863
864 /// The synchronization scope ID of this rmw instruction. Not quite enough
865 /// room in SubClassData for everything, so synchronization scope ID gets its
866 /// own field.
867 SyncScope::ID SSID;
868};
869
870template <>
871struct OperandTraits<AtomicRMWInst>
872 : public FixedNumOperandTraits<AtomicRMWInst,2> {
873};
874
875DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)AtomicRMWInst::op_iterator AtomicRMWInst::op_begin() { return
OperandTraits<AtomicRMWInst>::op_begin(this); } AtomicRMWInst
::const_op_iterator AtomicRMWInst::op_begin() const { return OperandTraits
<AtomicRMWInst>::op_begin(const_cast<AtomicRMWInst*>
(this)); } AtomicRMWInst::op_iterator AtomicRMWInst::op_end()
{ return OperandTraits<AtomicRMWInst>::op_end(this); }
AtomicRMWInst::const_op_iterator AtomicRMWInst::op_end() const
{ return OperandTraits<AtomicRMWInst>::op_end(const_cast
<AtomicRMWInst*>(this)); } Value *AtomicRMWInst::getOperand
(unsigned i_nocapture) const { ((i_nocapture < OperandTraits
<AtomicRMWInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 875, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<AtomicRMWInst>::op_begin(const_cast<
AtomicRMWInst*>(this))[i_nocapture].get()); } void AtomicRMWInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<AtomicRMWInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 875, __PRETTY_FUNCTION__)); OperandTraits<AtomicRMWInst>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned AtomicRMWInst
::getNumOperands() const { return OperandTraits<AtomicRMWInst
>::operands(this); } template <int Idx_nocapture> Use
&AtomicRMWInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
AtomicRMWInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
876
877//===----------------------------------------------------------------------===//
878// GetElementPtrInst Class
879//===----------------------------------------------------------------------===//
880
881// checkGEPType - Simple wrapper function to give a better assertion failure
882// message on bad indexes for a gep instruction.
883//
884inline Type *checkGEPType(Type *Ty) {
885 assert(Ty && "Invalid GetElementPtrInst indices for type!")((Ty && "Invalid GetElementPtrInst indices for type!"
) ? static_cast<void> (0) : __assert_fail ("Ty && \"Invalid GetElementPtrInst indices for type!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 885, __PRETTY_FUNCTION__))
;
886 return Ty;
887}
888
889/// an instruction for type-safe pointer arithmetic to
890/// access elements of arrays and structs
891///
892class GetElementPtrInst : public Instruction {
893 Type *SourceElementType;
894 Type *ResultElementType;
895
896 GetElementPtrInst(const GetElementPtrInst &GEPI);
897
898 /// Constructors - Create a getelementptr instruction with a base pointer an
899 /// list of indices. The first ctor can optionally insert before an existing
900 /// instruction, the second appends the new instruction to the specified
901 /// BasicBlock.
902 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
903 ArrayRef<Value *> IdxList, unsigned Values,
904 const Twine &NameStr, Instruction *InsertBefore);
905 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
906 ArrayRef<Value *> IdxList, unsigned Values,
907 const Twine &NameStr, BasicBlock *InsertAtEnd);
908
909 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
910
911protected:
912 // Note: Instruction needs to be a friend here to call cloneImpl.
913 friend class Instruction;
914
915 GetElementPtrInst *cloneImpl() const;
916
917public:
918 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
919 ArrayRef<Value *> IdxList,
920 const Twine &NameStr = "",
921 Instruction *InsertBefore = nullptr) {
922 unsigned Values = 1 + unsigned(IdxList.size());
923 if (!PointeeType)
924 PointeeType =
925 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
926 else
927 assert(((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 929, __PRETTY_FUNCTION__))
928 PointeeType ==((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 929, __PRETTY_FUNCTION__))
929 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 929, __PRETTY_FUNCTION__))
;
930 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
931 NameStr, InsertBefore);
932 }
933
934 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
935 ArrayRef<Value *> IdxList,
936 const Twine &NameStr,
937 BasicBlock *InsertAtEnd) {
938 unsigned Values = 1 + unsigned(IdxList.size());
939 if (!PointeeType)
940 PointeeType =
941 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
942 else
943 assert(((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 945, __PRETTY_FUNCTION__))
944 PointeeType ==((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 945, __PRETTY_FUNCTION__))
945 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 945, __PRETTY_FUNCTION__))
;
946 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
947 NameStr, InsertAtEnd);
948 }
949
950 /// Create an "inbounds" getelementptr. See the documentation for the
951 /// "inbounds" flag in LangRef.html for details.
952 static GetElementPtrInst *CreateInBounds(Value *Ptr,
953 ArrayRef<Value *> IdxList,
954 const Twine &NameStr = "",
955 Instruction *InsertBefore = nullptr){
956 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
957 }
958
959 static GetElementPtrInst *
960 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
961 const Twine &NameStr = "",
962 Instruction *InsertBefore = nullptr) {
963 GetElementPtrInst *GEP =
964 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
965 GEP->setIsInBounds(true);
966 return GEP;
967 }
968
969 static GetElementPtrInst *CreateInBounds(Value *Ptr,
970 ArrayRef<Value *> IdxList,
971 const Twine &NameStr,
972 BasicBlock *InsertAtEnd) {
973 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
974 }
975
976 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
977 ArrayRef<Value *> IdxList,
978 const Twine &NameStr,
979 BasicBlock *InsertAtEnd) {
980 GetElementPtrInst *GEP =
981 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
982 GEP->setIsInBounds(true);
983 return GEP;
984 }
985
986 /// Transparently provide more efficient getOperand methods.
987 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
988
989 Type *getSourceElementType() const { return SourceElementType; }
990
991 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
992 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
993
994 Type *getResultElementType() const {
995 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 996, __PRETTY_FUNCTION__))
996 cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 996, __PRETTY_FUNCTION__))
;
997 return ResultElementType;
998 }
999
1000 /// Returns the address space of this instruction's pointer type.
1001 unsigned getAddressSpace() const {
1002 // Note that this is always the same as the pointer operand's address space
1003 // and that is cheaper to compute, so cheat here.
1004 return getPointerAddressSpace();
1005 }
1006
1007 /// Returns the type of the element that would be loaded with
1008 /// a load instruction with the specified parameters.
1009 ///
1010 /// Null is returned if the indices are invalid for the specified
1011 /// pointer type.
1012 ///
1013 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
1014 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
1015 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
1016
1017 inline op_iterator idx_begin() { return op_begin()+1; }
1018 inline const_op_iterator idx_begin() const { return op_begin()+1; }
1019 inline op_iterator idx_end() { return op_end(); }
1020 inline const_op_iterator idx_end() const { return op_end(); }
1021
1022 inline iterator_range<op_iterator> indices() {
1023 return make_range(idx_begin(), idx_end());
1024 }
1025
1026 inline iterator_range<const_op_iterator> indices() const {
1027 return make_range(idx_begin(), idx_end());
1028 }
1029
1030 Value *getPointerOperand() {
1031 return getOperand(0);
1032 }
1033 const Value *getPointerOperand() const {
1034 return getOperand(0);
1035 }
1036 static unsigned getPointerOperandIndex() {
1037 return 0U; // get index for modifying correct operand.
1038 }
1039
1040 /// Method to return the pointer operand as a
1041 /// PointerType.
1042 Type *getPointerOperandType() const {
1043 return getPointerOperand()->getType();
1044 }
1045
1046 /// Returns the address space of the pointer operand.
1047 unsigned getPointerAddressSpace() const {
1048 return getPointerOperandType()->getPointerAddressSpace();
1049 }
1050
1051 /// Returns the pointer type returned by the GEP
1052 /// instruction, which may be a vector of pointers.
1053 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1054 ArrayRef<Value *> IdxList) {
1055 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1056 Ptr->getType()->getPointerAddressSpace());
1057 // Vector GEP
1058 if (Ptr->getType()->isVectorTy()) {
1059 unsigned NumElem = Ptr->getType()->getVectorNumElements();
1060 return VectorType::get(PtrTy, NumElem);
1061 }
1062 for (Value *Index : IdxList)
1063 if (Index->getType()->isVectorTy()) {
1064 unsigned NumElem = Index->getType()->getVectorNumElements();
1065 return VectorType::get(PtrTy, NumElem);
1066 }
1067 // Scalar GEP
1068 return PtrTy;
1069 }
1070
1071 unsigned getNumIndices() const { // Note: always non-negative
1072 return getNumOperands() - 1;
1073 }
1074
1075 bool hasIndices() const {
1076 return getNumOperands() > 1;
1077 }
1078
1079 /// Return true if all of the indices of this GEP are
1080 /// zeros. If so, the result pointer and the first operand have the same
1081 /// value, just potentially different types.
1082 bool hasAllZeroIndices() const;
1083
1084 /// Return true if all of the indices of this GEP are
1085 /// constant integers. If so, the result pointer and the first operand have
1086 /// a constant offset between them.
1087 bool hasAllConstantIndices() const;
1088
1089 /// Set or clear the inbounds flag on this GEP instruction.
1090 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1091 void setIsInBounds(bool b = true);
1092
1093 /// Determine whether the GEP has the inbounds flag.
1094 bool isInBounds() const;
1095
1096 /// Accumulate the constant address offset of this GEP if possible.
1097 ///
1098 /// This routine accepts an APInt into which it will accumulate the constant
1099 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1100 /// all-constant, it returns false and the value of the offset APInt is
1101 /// undefined (it is *not* preserved!). The APInt passed into this routine
1102 /// must be at least as wide as the IntPtr type for the address space of
1103 /// the base GEP pointer.
1104 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1105
1106 // Methods for support type inquiry through isa, cast, and dyn_cast:
1107 static bool classof(const Instruction *I) {
1108 return (I->getOpcode() == Instruction::GetElementPtr);
1109 }
1110 static bool classof(const Value *V) {
1111 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1112 }
1113};
1114
1115template <>
1116struct OperandTraits<GetElementPtrInst> :
1117 public VariadicOperandTraits<GetElementPtrInst, 1> {
1118};
1119
1120GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1121 ArrayRef<Value *> IdxList, unsigned Values,
1122 const Twine &NameStr,
1123 Instruction *InsertBefore)
1124 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1125 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1126 Values, InsertBefore),
1127 SourceElementType(PointeeType),
1128 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1129 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1130, __PRETTY_FUNCTION__))
1130 cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1130, __PRETTY_FUNCTION__))
;
1131 init(Ptr, IdxList, NameStr);
1132}
1133
1134GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1135 ArrayRef<Value *> IdxList, unsigned Values,
1136 const Twine &NameStr,
1137 BasicBlock *InsertAtEnd)
1138 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1139 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1140 Values, InsertAtEnd),
1141 SourceElementType(PointeeType),
1142 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1143 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1144, __PRETTY_FUNCTION__))
1144 cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1144, __PRETTY_FUNCTION__))
;
1145 init(Ptr, IdxList, NameStr);
1146}
1147
1148DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)GetElementPtrInst::op_iterator GetElementPtrInst::op_begin() {
return OperandTraits<GetElementPtrInst>::op_begin(this
); } GetElementPtrInst::const_op_iterator GetElementPtrInst::
op_begin() const { return OperandTraits<GetElementPtrInst>
::op_begin(const_cast<GetElementPtrInst*>(this)); } GetElementPtrInst
::op_iterator GetElementPtrInst::op_end() { return OperandTraits
<GetElementPtrInst>::op_end(this); } GetElementPtrInst::
const_op_iterator GetElementPtrInst::op_end() const { return OperandTraits
<GetElementPtrInst>::op_end(const_cast<GetElementPtrInst
*>(this)); } Value *GetElementPtrInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<GetElementPtrInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1148, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<GetElementPtrInst>::op_begin(const_cast
<GetElementPtrInst*>(this))[i_nocapture].get()); } void
GetElementPtrInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<GetElementPtrInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1148, __PRETTY_FUNCTION__)); OperandTraits<GetElementPtrInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
GetElementPtrInst::getNumOperands() const { return OperandTraits
<GetElementPtrInst>::operands(this); } template <int
Idx_nocapture> Use &GetElementPtrInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &GetElementPtrInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
1149
1150//===----------------------------------------------------------------------===//
1151// ICmpInst Class
1152//===----------------------------------------------------------------------===//
1153
1154/// This instruction compares its operands according to the predicate given
1155/// to the constructor. It only operates on integers or pointers. The operands
1156/// must be identical types.
1157/// Represent an integer comparison operator.
1158class ICmpInst: public CmpInst {
1159 void AssertOK() {
1160 assert(isIntPredicate() &&((isIntPredicate() && "Invalid ICmp predicate value")
? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1161, __PRETTY_FUNCTION__))
1161 "Invalid ICmp predicate value")((isIntPredicate() && "Invalid ICmp predicate value")
? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1161, __PRETTY_FUNCTION__))
;
1162 assert(getOperand(0)->getType() == getOperand(1)->getType() &&((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to ICmp instruction are not of the same type!"
) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1163, __PRETTY_FUNCTION__))
1163 "Both operands to ICmp instruction are not of the same type!")((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to ICmp instruction are not of the same type!"
) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1163, __PRETTY_FUNCTION__))
;
1164 // Check that the operands are the right type
1165 assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand
(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction"
) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1167, __PRETTY_FUNCTION__))
1166 getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand
(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction"
) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1167, __PRETTY_FUNCTION__))
1167 "Invalid operand types for ICmp instruction")(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand
(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction"
) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1167, __PRETTY_FUNCTION__))
;
1168 }
1169
1170protected:
1171 // Note: Instruction needs to be a friend here to call cloneImpl.
1172 friend class Instruction;
1173
1174 /// Clone an identical ICmpInst
1175 ICmpInst *cloneImpl() const;
1176
1177public:
1178 /// Constructor with insert-before-instruction semantics.
1179 ICmpInst(
1180 Instruction *InsertBefore, ///< Where to insert
1181 Predicate pred, ///< The predicate to use for the comparison
1182 Value *LHS, ///< The left-hand-side of the expression
1183 Value *RHS, ///< The right-hand-side of the expression
1184 const Twine &NameStr = "" ///< Name of the instruction
1185 ) : CmpInst(makeCmpResultType(LHS->getType()),
1186 Instruction::ICmp, pred, LHS, RHS, NameStr,
1187 InsertBefore) {
1188#ifndef NDEBUG
1189 AssertOK();
1190#endif
1191 }
1192
1193 /// Constructor with insert-at-end semantics.
1194 ICmpInst(
1195 BasicBlock &InsertAtEnd, ///< Block to insert into.
1196 Predicate pred, ///< The predicate to use for the comparison
1197 Value *LHS, ///< The left-hand-side of the expression
1198 Value *RHS, ///< The right-hand-side of the expression
1199 const Twine &NameStr = "" ///< Name of the instruction
1200 ) : CmpInst(makeCmpResultType(LHS->getType()),
1201 Instruction::ICmp, pred, LHS, RHS, NameStr,
1202 &InsertAtEnd) {
1203#ifndef NDEBUG
1204 AssertOK();
1205#endif
1206 }
1207
1208 /// Constructor with no-insertion semantics
1209 ICmpInst(
1210 Predicate pred, ///< The predicate to use for the comparison
1211 Value *LHS, ///< The left-hand-side of the expression
1212 Value *RHS, ///< The right-hand-side of the expression
1213 const Twine &NameStr = "" ///< Name of the instruction
1214 ) : CmpInst(makeCmpResultType(LHS->getType()),
1215 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1216#ifndef NDEBUG
1217 AssertOK();
1218#endif
1219 }
1220
1221 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1222 /// @returns the predicate that would be the result if the operand were
1223 /// regarded as signed.
1224 /// Return the signed version of the predicate
1225 Predicate getSignedPredicate() const {
1226 return getSignedPredicate(getPredicate());
1227 }
1228
1229 /// This is a static version that you can use without an instruction.
1230 /// Return the signed version of the predicate.
1231 static Predicate getSignedPredicate(Predicate pred);
1232
1233 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1234 /// @returns the predicate that would be the result if the operand were
1235 /// regarded as unsigned.
1236 /// Return the unsigned version of the predicate
1237 Predicate getUnsignedPredicate() const {
1238 return getUnsignedPredicate(getPredicate());
1239 }
1240
1241 /// This is a static version that you can use without an instruction.
1242 /// Return the unsigned version of the predicate.
1243 static Predicate getUnsignedPredicate(Predicate pred);
1244
1245 /// Return true if this predicate is either EQ or NE. This also
1246 /// tests for commutativity.
1247 static bool isEquality(Predicate P) {
1248 return P == ICMP_EQ || P == ICMP_NE;
1249 }
1250
1251 /// Return true if this predicate is either EQ or NE. This also
1252 /// tests for commutativity.
1253 bool isEquality() const {
1254 return isEquality(getPredicate());
1255 }
1256
1257 /// @returns true if the predicate of this ICmpInst is commutative
1258 /// Determine if this relation is commutative.
1259 bool isCommutative() const { return isEquality(); }
1260
1261 /// Return true if the predicate is relational (not EQ or NE).
1262 ///
1263 bool isRelational() const {
1264 return !isEquality();
1265 }
1266
1267 /// Return true if the predicate is relational (not EQ or NE).
1268 ///
1269 static bool isRelational(Predicate P) {
1270 return !isEquality(P);
1271 }
1272
1273 /// Exchange the two operands to this instruction in such a way that it does
1274 /// not modify the semantics of the instruction. The predicate value may be
1275 /// changed to retain the same result if the predicate is order dependent
1276 /// (e.g. ult).
1277 /// Swap operands and adjust predicate.
1278 void swapOperands() {
1279 setPredicate(getSwappedPredicate());
1280 Op<0>().swap(Op<1>());
1281 }
1282
1283 // Methods for support type inquiry through isa, cast, and dyn_cast:
1284 static bool classof(const Instruction *I) {
1285 return I->getOpcode() == Instruction::ICmp;
1286 }
1287 static bool classof(const Value *V) {
1288 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1289 }
1290};
1291
1292//===----------------------------------------------------------------------===//
1293// FCmpInst Class
1294//===----------------------------------------------------------------------===//
1295
1296/// This instruction compares its operands according to the predicate given
1297/// to the constructor. It only operates on floating point values or packed
1298/// vectors of floating point values. The operands must be identical types.
1299/// Represents a floating point comparison operator.
1300class FCmpInst: public CmpInst {
1301 void AssertOK() {
1302 assert(isFPPredicate() && "Invalid FCmp predicate value")((isFPPredicate() && "Invalid FCmp predicate value") ?
static_cast<void> (0) : __assert_fail ("isFPPredicate() && \"Invalid FCmp predicate value\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1302, __PRETTY_FUNCTION__))
;
1303 assert(getOperand(0)->getType() == getOperand(1)->getType() &&((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to FCmp instruction are not of the same type!"
) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1304, __PRETTY_FUNCTION__))
1304 "Both operands to FCmp instruction are not of the same type!")((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to FCmp instruction are not of the same type!"
) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1304, __PRETTY_FUNCTION__))
;
1305 // Check that the operands are the right type
1306 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&((getOperand(0)->getType()->isFPOrFPVectorTy() &&
"Invalid operand types for FCmp instruction") ? static_cast<
void> (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1307, __PRETTY_FUNCTION__))
1307 "Invalid operand types for FCmp instruction")((getOperand(0)->getType()->isFPOrFPVectorTy() &&
"Invalid operand types for FCmp instruction") ? static_cast<
void> (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1307, __PRETTY_FUNCTION__))
;
1308 }
1309
1310protected:
1311 // Note: Instruction needs to be a friend here to call cloneImpl.
1312 friend class Instruction;
1313
1314 /// Clone an identical FCmpInst
1315 FCmpInst *cloneImpl() const;
1316
1317public:
1318 /// Constructor with insert-before-instruction semantics.
1319 FCmpInst(
1320 Instruction *InsertBefore, ///< Where to insert
1321 Predicate pred, ///< The predicate to use for the comparison
1322 Value *LHS, ///< The left-hand-side of the expression
1323 Value *RHS, ///< The right-hand-side of the expression
1324 const Twine &NameStr = "" ///< Name of the instruction
1325 ) : CmpInst(makeCmpResultType(LHS->getType()),
1326 Instruction::FCmp, pred, LHS, RHS, NameStr,
1327 InsertBefore) {
1328 AssertOK();
1329 }
1330
1331 /// Constructor with insert-at-end semantics.
1332 FCmpInst(
1333 BasicBlock &InsertAtEnd, ///< Block to insert into.
1334 Predicate pred, ///< The predicate to use for the comparison
1335 Value *LHS, ///< The left-hand-side of the expression
1336 Value *RHS, ///< The right-hand-side of the expression
1337 const Twine &NameStr = "" ///< Name of the instruction
1338 ) : CmpInst(makeCmpResultType(LHS->getType()),
1339 Instruction::FCmp, pred, LHS, RHS, NameStr,
1340 &InsertAtEnd) {
1341 AssertOK();
1342 }
1343
1344 /// Constructor with no-insertion semantics
1345 FCmpInst(
1346 Predicate Pred, ///< The predicate to use for the comparison
1347 Value *LHS, ///< The left-hand-side of the expression
1348 Value *RHS, ///< The right-hand-side of the expression
1349 const Twine &NameStr = "", ///< Name of the instruction
1350 Instruction *FlagsSource = nullptr
1351 ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1352 RHS, NameStr, nullptr, FlagsSource) {
1353 AssertOK();
1354 }
1355
1356 /// @returns true if the predicate of this instruction is EQ or NE.
1357 /// Determine if this is an equality predicate.
1358 static bool isEquality(Predicate Pred) {
1359 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1360 Pred == FCMP_UNE;
1361 }
1362
1363 /// @returns true if the predicate of this instruction is EQ or NE.
1364 /// Determine if this is an equality predicate.
1365 bool isEquality() const { return isEquality(getPredicate()); }
1366
1367 /// @returns true if the predicate of this instruction is commutative.
1368 /// Determine if this is a commutative predicate.
1369 bool isCommutative() const {
1370 return isEquality() ||
1371 getPredicate() == FCMP_FALSE ||
1372 getPredicate() == FCMP_TRUE ||
1373 getPredicate() == FCMP_ORD ||
1374 getPredicate() == FCMP_UNO;
1375 }
1376
1377 /// @returns true if the predicate is relational (not EQ or NE).
1378 /// Determine if this a relational predicate.
1379 bool isRelational() const { return !isEquality(); }
1380
1381 /// Exchange the two operands to this instruction in such a way that it does
1382 /// not modify the semantics of the instruction. The predicate value may be
1383 /// changed to retain the same result if the predicate is order dependent
1384 /// (e.g. ult).
1385 /// Swap operands and adjust predicate.
1386 void swapOperands() {
1387 setPredicate(getSwappedPredicate());
1388 Op<0>().swap(Op<1>());
1389 }
1390
1391 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1392 static bool classof(const Instruction *I) {
1393 return I->getOpcode() == Instruction::FCmp;
1394 }
1395 static bool classof(const Value *V) {
1396 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1397 }
1398};
1399
1400//===----------------------------------------------------------------------===//
1401/// This class represents a function call, abstracting a target
1402/// machine's calling convention. This class uses low bit of the SubClassData
1403/// field to indicate whether or not this is a tail call. The rest of the bits
1404/// hold the calling convention of the call.
1405///
1406class CallInst : public CallBase {
1407 CallInst(const CallInst &CI);
1408
1409 /// Construct a CallInst given a range of arguments.
1410 /// Construct a CallInst from a range of arguments
1411 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1412 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1413 Instruction *InsertBefore);
1414
1415 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1416 const Twine &NameStr, Instruction *InsertBefore)
1417 : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
1418
1419 /// Construct a CallInst given a range of arguments.
1420 /// Construct a CallInst from a range of arguments
1421 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1422 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1423 BasicBlock *InsertAtEnd);
1424
1425 explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
1426 Instruction *InsertBefore);
1427
1428 CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
1429 BasicBlock *InsertAtEnd);
1430
1431 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1432 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1433 void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
1434
1435 /// Compute the number of operands to allocate.
1436 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
1437 // We need one operand for the called function, plus the input operand
1438 // counts provided.
1439 return 1 + NumArgs + NumBundleInputs;
1440 }
1441
1442protected:
1443 // Note: Instruction needs to be a friend here to call cloneImpl.
1444 friend class Instruction;
1445
1446 CallInst *cloneImpl() const;
1447
1448public:
1449 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
1450 Instruction *InsertBefore = nullptr) {
1451 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
1452 }
1453
1454 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1455 const Twine &NameStr,
1456 Instruction *InsertBefore = nullptr) {
1457 return new (ComputeNumOperands(Args.size()))
1458 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1459 }
1460
1461 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1462 ArrayRef<OperandBundleDef> Bundles = None,
1463 const Twine &NameStr = "",
1464 Instruction *InsertBefore = nullptr) {
1465 const int NumOperands =
1466 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1467 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1468
1469 return new (NumOperands, DescriptorBytes)
1470 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1471 }
1472
1473 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
1474 BasicBlock *InsertAtEnd) {
1475 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
1476 }
1477
1478 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1479 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1480 return new (ComputeNumOperands(Args.size()))
1481 CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
1482 }
1483
1484 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1485 ArrayRef<OperandBundleDef> Bundles,
1486 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1487 const int NumOperands =
1488 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1489 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1490
1491 return new (NumOperands, DescriptorBytes)
1492 CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
1493 }
1494
1495 static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
1496 Instruction *InsertBefore = nullptr) {
1497 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1498 InsertBefore);
1499 }
1500
1501 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1502 ArrayRef<OperandBundleDef> Bundles = None,
1503 const Twine &NameStr = "",
1504 Instruction *InsertBefore = nullptr) {
1505 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1506 NameStr, InsertBefore);
1507 }
1508
1509 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1510 const Twine &NameStr,
1511 Instruction *InsertBefore = nullptr) {
1512 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1513 InsertBefore);
1514 }
1515
1516 static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
1517 BasicBlock *InsertAtEnd) {
1518 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1519 InsertAtEnd);
1520 }
1521
1522 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1523 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1524 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1525 InsertAtEnd);
1526 }
1527
1528 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1529 ArrayRef<OperandBundleDef> Bundles,
1530 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1531 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1532 NameStr, InsertAtEnd);
1533 }
1534
1535 // Deprecated [opaque pointer types]
1536 static CallInst *Create(Value *Func, const Twine &NameStr = "",
1537 Instruction *InsertBefore = nullptr) {
1538 return Create(cast<FunctionType>(
1539 cast<PointerType>(Func->getType())->getElementType()),
1540 Func, NameStr, InsertBefore);
1541 }
1542
1543 // Deprecated [opaque pointer types]
1544 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1545 const Twine &NameStr,
1546 Instruction *InsertBefore = nullptr) {
1547 return Create(cast<FunctionType>(
1548 cast<PointerType>(Func->getType())->getElementType()),
1549 Func, Args, NameStr, InsertBefore);
1550 }
1551
1552 // Deprecated [opaque pointer types]
1553 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1554 ArrayRef<OperandBundleDef> Bundles = None,
1555 const Twine &NameStr = "",
1556 Instruction *InsertBefore = nullptr) {
1557 return Create(cast<FunctionType>(
1558 cast<PointerType>(Func->getType())->getElementType()),
1559 Func, Args, Bundles, NameStr, InsertBefore);
1560 }
1561
1562 // Deprecated [opaque pointer types]
1563 static CallInst *Create(Value *Func, const Twine &NameStr,
1564 BasicBlock *InsertAtEnd) {
1565 return Create(cast<FunctionType>(
1566 cast<PointerType>(Func->getType())->getElementType()),
1567 Func, NameStr, InsertAtEnd);
1568 }
1569
1570 // Deprecated [opaque pointer types]
1571 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1572 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1573 return Create(cast<FunctionType>(
1574 cast<PointerType>(Func->getType())->getElementType()),
1575 Func, Args, NameStr, InsertAtEnd);
1576 }
1577
1578 // Deprecated [opaque pointer types]
1579 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1580 ArrayRef<OperandBundleDef> Bundles,
1581 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1582 return Create(cast<FunctionType>(
1583 cast<PointerType>(Func->getType())->getElementType()),
1584 Func, Args, Bundles, NameStr, InsertAtEnd);
1585 }
1586
1587 /// Create a clone of \p CI with a different set of operand bundles and
1588 /// insert it before \p InsertPt.
1589 ///
1590 /// The returned call instruction is identical \p CI in every way except that
1591 /// the operand bundles for the new instruction are set to the operand bundles
1592 /// in \p Bundles.
1593 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1594 Instruction *InsertPt = nullptr);
1595
1596 /// Generate the IR for a call to malloc:
1597 /// 1. Compute the malloc call's argument as the specified type's size,
1598 /// possibly multiplied by the array size if the array size is not
1599 /// constant 1.
1600 /// 2. Call malloc with that argument.
1601 /// 3. Bitcast the result of the malloc call to the specified type.
1602 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1603 Type *AllocTy, Value *AllocSize,
1604 Value *ArraySize = nullptr,
1605 Function *MallocF = nullptr,
1606 const Twine &Name = "");
1607 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1608 Type *AllocTy, Value *AllocSize,
1609 Value *ArraySize = nullptr,
1610 Function *MallocF = nullptr,
1611 const Twine &Name = "");
1612 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1613 Type *AllocTy, Value *AllocSize,
1614 Value *ArraySize = nullptr,
1615 ArrayRef<OperandBundleDef> Bundles = None,
1616 Function *MallocF = nullptr,
1617 const Twine &Name = "");
1618 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1619 Type *AllocTy, Value *AllocSize,
1620 Value *ArraySize = nullptr,
1621 ArrayRef<OperandBundleDef> Bundles = None,
1622 Function *MallocF = nullptr,
1623 const Twine &Name = "");
1624 /// Generate the IR for a call to the builtin free function.
1625 static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
1626 static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
1627 static Instruction *CreateFree(Value *Source,
1628 ArrayRef<OperandBundleDef> Bundles,
1629 Instruction *InsertBefore);
1630 static Instruction *CreateFree(Value *Source,
1631 ArrayRef<OperandBundleDef> Bundles,
1632 BasicBlock *InsertAtEnd);
1633
1634 // Note that 'musttail' implies 'tail'.
1635 enum TailCallKind {
1636 TCK_None = 0,
1637 TCK_Tail = 1,
1638 TCK_MustTail = 2,
1639 TCK_NoTail = 3
1640 };
1641 TailCallKind getTailCallKind() const {
1642 return TailCallKind(getSubclassDataFromInstruction() & 3);
1643 }
1644
1645 bool isTailCall() const {
1646 unsigned Kind = getSubclassDataFromInstruction() & 3;
1647 return Kind == TCK_Tail || Kind == TCK_MustTail;
1648 }
1649
1650 bool isMustTailCall() const {
1651 return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1652 }
1653
1654 bool isNoTailCall() const {
1655 return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1656 }
1657
1658 void setTailCall(bool isTC = true) {
1659 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1660 unsigned(isTC ? TCK_Tail : TCK_None));
1661 }
1662
1663 void setTailCallKind(TailCallKind TCK) {
1664 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1665 unsigned(TCK));
1666 }
1667
1668 /// Return true if the call can return twice
1669 bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
1670 void setCanReturnTwice() {
1671 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1672 }
1673
1674 // Methods for support type inquiry through isa, cast, and dyn_cast:
1675 static bool classof(const Instruction *I) {
1676 return I->getOpcode() == Instruction::Call;
1677 }
1678 static bool classof(const Value *V) {
1679 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1680 }
1681
1682 /// Updates profile metadata by scaling it by \p S / \p T.
1683 void updateProfWeight(uint64_t S, uint64_t T);
1684
1685private:
1686 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1687 // method so that subclasses cannot accidentally use it.
1688 void setInstructionSubclassData(unsigned short D) {
1689 Instruction::setInstructionSubclassData(D);
1690 }
1691};
1692
1693CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1694 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1695 BasicBlock *InsertAtEnd)
1696 : CallBase(Ty->getReturnType(), Instruction::Call,
1697 OperandTraits<CallBase>::op_end(this) -
1698 (Args.size() + CountBundleInputs(Bundles) + 1),
1699 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1700 InsertAtEnd) {
1701 init(Ty, Func, Args, Bundles, NameStr);
1702}
1703
1704CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1705 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1706 Instruction *InsertBefore)
1707 : CallBase(Ty->getReturnType(), Instruction::Call,
1708 OperandTraits<CallBase>::op_end(this) -
1709 (Args.size() + CountBundleInputs(Bundles) + 1),
1710 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1711 InsertBefore) {
1712 init(Ty, Func, Args, Bundles, NameStr);
1713}
1714
1715//===----------------------------------------------------------------------===//
1716// SelectInst Class
1717//===----------------------------------------------------------------------===//
1718
1719/// This class represents the LLVM 'select' instruction.
1720///
1721class SelectInst : public Instruction {
1722 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1723 Instruction *InsertBefore)
1724 : Instruction(S1->getType(), Instruction::Select,
1725 &Op<0>(), 3, InsertBefore) {
1726 init(C, S1, S2);
1727 setName(NameStr);
1728 }
1729
1730 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1731 BasicBlock *InsertAtEnd)
1732 : Instruction(S1->getType(), Instruction::Select,
1733 &Op<0>(), 3, InsertAtEnd) {
1734 init(C, S1, S2);
1735 setName(NameStr);
1736 }
1737
1738 void init(Value *C, Value *S1, Value *S2) {
1739 assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select")((!areInvalidOperands(C, S1, S2) && "Invalid operands for select"
) ? static_cast<void> (0) : __assert_fail ("!areInvalidOperands(C, S1, S2) && \"Invalid operands for select\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1739, __PRETTY_FUNCTION__))
;
1740 Op<0>() = C;
1741 Op<1>() = S1;
1742 Op<2>() = S2;
1743 }
1744
1745protected:
1746 // Note: Instruction needs to be a friend here to call cloneImpl.
1747 friend class Instruction;
1748
1749 SelectInst *cloneImpl() const;
1750
1751public:
1752 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1753 const Twine &NameStr = "",
1754 Instruction *InsertBefore = nullptr,
1755 Instruction *MDFrom = nullptr) {
1756 SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1757 if (MDFrom)
1758 Sel->copyMetadata(*MDFrom);
1759 return Sel;
1760 }
1761
1762 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1763 const Twine &NameStr,
1764 BasicBlock *InsertAtEnd) {
1765 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1766 }
1767
1768 const Value *getCondition() const { return Op<0>(); }
1769 const Value *getTrueValue() const { return Op<1>(); }
1770 const Value *getFalseValue() const { return Op<2>(); }
1771 Value *getCondition() { return Op<0>(); }
1772 Value *getTrueValue() { return Op<1>(); }
1773 Value *getFalseValue() { return Op<2>(); }
1774
1775 void setCondition(Value *V) { Op<0>() = V; }
1776 void setTrueValue(Value *V) { Op<1>() = V; }
1777 void setFalseValue(Value *V) { Op<2>() = V; }
1778
1779 /// Swap the true and false values of the select instruction.
1780 /// This doesn't swap prof metadata.
1781 void swapValues() { Op<1>().swap(Op<2>()); }
1782
1783 /// Return a string if the specified operands are invalid
1784 /// for a select operation, otherwise return null.
1785 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1786
1787 /// Transparently provide more efficient getOperand methods.
1788 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
1789
1790 OtherOps getOpcode() const {
1791 return static_cast<OtherOps>(Instruction::getOpcode());
1792 }
1793
1794 // Methods for support type inquiry through isa, cast, and dyn_cast:
1795 static bool classof(const Instruction *I) {
1796 return I->getOpcode() == Instruction::Select;
1797 }
1798 static bool classof(const Value *V) {
1799 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1800 }
1801};
1802
1803template <>
1804struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1805};
1806
1807DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)SelectInst::op_iterator SelectInst::op_begin() { return OperandTraits
<SelectInst>::op_begin(this); } SelectInst::const_op_iterator
SelectInst::op_begin() const { return OperandTraits<SelectInst
>::op_begin(const_cast<SelectInst*>(this)); } SelectInst
::op_iterator SelectInst::op_end() { return OperandTraits<
SelectInst>::op_end(this); } SelectInst::const_op_iterator
SelectInst::op_end() const { return OperandTraits<SelectInst
>::op_end(const_cast<SelectInst*>(this)); } Value *SelectInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<SelectInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1807, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<SelectInst>::op_begin(const_cast<SelectInst
*>(this))[i_nocapture].get()); } void SelectInst::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<SelectInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1807, __PRETTY_FUNCTION__)); OperandTraits<SelectInst>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned SelectInst
::getNumOperands() const { return OperandTraits<SelectInst
>::operands(this); } template <int Idx_nocapture> Use
&SelectInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
SelectInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
1808
1809//===----------------------------------------------------------------------===//
1810// VAArgInst Class
1811//===----------------------------------------------------------------------===//
1812
1813/// This class represents the va_arg llvm instruction, which returns
1814/// an argument of the specified type given a va_list and increments that list
1815///
1816class VAArgInst : public UnaryInstruction {
1817protected:
1818 // Note: Instruction needs to be a friend here to call cloneImpl.
1819 friend class Instruction;
1820
1821 VAArgInst *cloneImpl() const;
1822
1823public:
1824 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1825 Instruction *InsertBefore = nullptr)
1826 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1827 setName(NameStr);
1828 }
1829
1830 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1831 BasicBlock *InsertAtEnd)
1832 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1833 setName(NameStr);
1834 }
1835
1836 Value *getPointerOperand() { return getOperand(0); }
1837 const Value *getPointerOperand() const { return getOperand(0); }
1838 static unsigned getPointerOperandIndex() { return 0U; }
1839
1840 // Methods for support type inquiry through isa, cast, and dyn_cast:
1841 static bool classof(const Instruction *I) {
1842 return I->getOpcode() == VAArg;
1843 }
1844 static bool classof(const Value *V) {
1845 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1846 }
1847};
1848
1849//===----------------------------------------------------------------------===//
1850// ExtractElementInst Class
1851//===----------------------------------------------------------------------===//
1852
1853/// This instruction extracts a single (scalar)
1854/// element from a VectorType value
1855///
1856class ExtractElementInst : public Instruction {
1857 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1858 Instruction *InsertBefore = nullptr);
1859 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1860 BasicBlock *InsertAtEnd);
1861
1862protected:
1863 // Note: Instruction needs to be a friend here to call cloneImpl.
1864 friend class Instruction;
1865
1866 ExtractElementInst *cloneImpl() const;
1867
1868public:
1869 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1870 const Twine &NameStr = "",
1871 Instruction *InsertBefore = nullptr) {
1872 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1873 }
1874
1875 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1876 const Twine &NameStr,
1877 BasicBlock *InsertAtEnd) {
1878 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1879 }
1880
1881 /// Return true if an extractelement instruction can be
1882 /// formed with the specified operands.
1883 static bool isValidOperands(const Value *Vec, const Value *Idx);
1884
1885 Value *getVectorOperand() { return Op<0>(); }
1886 Value *getIndexOperand() { return Op<1>(); }
1887 const Value *getVectorOperand() const { return Op<0>(); }
1888 const Value *getIndexOperand() const { return Op<1>(); }
1889
1890 VectorType *getVectorOperandType() const {
1891 return cast<VectorType>(getVectorOperand()->getType());
1892 }
1893
1894 /// Transparently provide more efficient getOperand methods.
1895 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
1896
1897 // Methods for support type inquiry through isa, cast, and dyn_cast:
1898 static bool classof(const Instruction *I) {
1899 return I->getOpcode() == Instruction::ExtractElement;
1900 }
1901 static bool classof(const Value *V) {
1902 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1903 }
1904};
1905
1906template <>
1907struct OperandTraits<ExtractElementInst> :
1908 public FixedNumOperandTraits<ExtractElementInst, 2> {
1909};
1910
1911DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)ExtractElementInst::op_iterator ExtractElementInst::op_begin(
) { return OperandTraits<ExtractElementInst>::op_begin(
this); } ExtractElementInst::const_op_iterator ExtractElementInst
::op_begin() const { return OperandTraits<ExtractElementInst
>::op_begin(const_cast<ExtractElementInst*>(this)); }
ExtractElementInst::op_iterator ExtractElementInst::op_end()
{ return OperandTraits<ExtractElementInst>::op_end(this
); } ExtractElementInst::const_op_iterator ExtractElementInst
::op_end() const { return OperandTraits<ExtractElementInst
>::op_end(const_cast<ExtractElementInst*>(this)); } Value
*ExtractElementInst::getOperand(unsigned i_nocapture) const {
((i_nocapture < OperandTraits<ExtractElementInst>::
operands(this) && "getOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1911, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<ExtractElementInst>::op_begin(const_cast
<ExtractElementInst*>(this))[i_nocapture].get()); } void
ExtractElementInst::setOperand(unsigned i_nocapture, Value *
Val_nocapture) { ((i_nocapture < OperandTraits<ExtractElementInst
>::operands(this) && "setOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1911, __PRETTY_FUNCTION__)); OperandTraits<ExtractElementInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
ExtractElementInst::getNumOperands() const { return OperandTraits
<ExtractElementInst>::operands(this); } template <int
Idx_nocapture> Use &ExtractElementInst::Op() { return
this->OpFrom<Idx_nocapture>(this); } template <int
Idx_nocapture> const Use &ExtractElementInst::Op() const
{ return this->OpFrom<Idx_nocapture>(this); }
1912
1913//===----------------------------------------------------------------------===//
1914// InsertElementInst Class
1915//===----------------------------------------------------------------------===//
1916
1917/// This instruction inserts a single (scalar)
1918/// element into a VectorType value
1919///
1920class InsertElementInst : public Instruction {
1921 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1922 const Twine &NameStr = "",
1923 Instruction *InsertBefore = nullptr);
1924 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1925 BasicBlock *InsertAtEnd);
1926
1927protected:
1928 // Note: Instruction needs to be a friend here to call cloneImpl.
1929 friend class Instruction;
1930
1931 InsertElementInst *cloneImpl() const;
1932
1933public:
1934 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1935 const Twine &NameStr = "",
1936 Instruction *InsertBefore = nullptr) {
1937 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1938 }
1939
1940 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1941 const Twine &NameStr,
1942 BasicBlock *InsertAtEnd) {
1943 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1944 }
1945
1946 /// Return true if an insertelement instruction can be
1947 /// formed with the specified operands.
1948 static bool isValidOperands(const Value *Vec, const Value *NewElt,
1949 const Value *Idx);
1950
1951 /// Overload to return most specific vector type.
1952 ///
1953 VectorType *getType() const {
1954 return cast<VectorType>(Instruction::getType());
1955 }
1956
1957 /// Transparently provide more efficient getOperand methods.
1958 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
1959
1960 // Methods for support type inquiry through isa, cast, and dyn_cast:
1961 static bool classof(const Instruction *I) {
1962 return I->getOpcode() == Instruction::InsertElement;
1963 }
1964 static bool classof(const Value *V) {
1965 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1966 }
1967};
1968
1969template <>
1970struct OperandTraits<InsertElementInst> :
1971 public FixedNumOperandTraits<InsertElementInst, 3> {
1972};
1973
1974DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)InsertElementInst::op_iterator InsertElementInst::op_begin() {
return OperandTraits<InsertElementInst>::op_begin(this
); } InsertElementInst::const_op_iterator InsertElementInst::
op_begin() const { return OperandTraits<InsertElementInst>
::op_begin(const_cast<InsertElementInst*>(this)); } InsertElementInst
::op_iterator InsertElementInst::op_end() { return OperandTraits
<InsertElementInst>::op_end(this); } InsertElementInst::
const_op_iterator InsertElementInst::op_end() const { return OperandTraits
<InsertElementInst>::op_end(const_cast<InsertElementInst
*>(this)); } Value *InsertElementInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<InsertElementInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1974, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<InsertElementInst>::op_begin(const_cast
<InsertElementInst*>(this))[i_nocapture].get()); } void
InsertElementInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<InsertElementInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 1974, __PRETTY_FUNCTION__)); OperandTraits<InsertElementInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
InsertElementInst::getNumOperands() const { return OperandTraits
<InsertElementInst>::operands(this); } template <int
Idx_nocapture> Use &InsertElementInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &InsertElementInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
1975
1976//===----------------------------------------------------------------------===//
1977// ShuffleVectorInst Class
1978//===----------------------------------------------------------------------===//
1979
1980/// This instruction constructs a fixed permutation of two
1981/// input vectors.
1982///
1983class ShuffleVectorInst : public Instruction {
1984protected:
1985 // Note: Instruction needs to be a friend here to call cloneImpl.
1986 friend class Instruction;
1987
1988 ShuffleVectorInst *cloneImpl() const;
1989
1990public:
1991 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1992 const Twine &NameStr = "",
1993 Instruction *InsertBefor = nullptr);
1994 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1995 const Twine &NameStr, BasicBlock *InsertAtEnd);
1996
1997 // allocate space for exactly three operands
1998 void *operator new(size_t s) {
1999 return User::operator new(s, 3);
2000 }
2001
2002 /// Swap the first 2 operands and adjust the mask to preserve the semantics
2003 /// of the instruction.
2004 void commute();
2005
2006 /// Return true if a shufflevector instruction can be
2007 /// formed with the specified operands.
2008 static bool isValidOperands(const Value *V1, const Value *V2,
2009 const Value *Mask);
2010
2011 /// Overload to return most specific vector type.
2012 ///
2013 VectorType *getType() const {
2014 return cast<VectorType>(Instruction::getType());
2015 }
2016
2017 /// Transparently provide more efficient getOperand methods.
2018 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2019
2020 Constant *getMask() const {
2021 return cast<Constant>(getOperand(2));
2022 }
2023
2024 /// Return the shuffle mask value for the specified element of the mask.
2025 /// Return -1 if the element is undef.
2026 static int getMaskValue(const Constant *Mask, unsigned Elt);
2027
2028 /// Return the shuffle mask value of this instruction for the given element
2029 /// index. Return -1 if the element is undef.
2030 int getMaskValue(unsigned Elt) const {
2031 return getMaskValue(getMask(), Elt);
2032 }
2033
2034 /// Convert the input shuffle mask operand to a vector of integers. Undefined
2035 /// elements of the mask are returned as -1.
2036 static void getShuffleMask(const Constant *Mask,
2037 SmallVectorImpl<int> &Result);
2038
2039 /// Return the mask for this instruction as a vector of integers. Undefined
2040 /// elements of the mask are returned as -1.
2041 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2042 return getShuffleMask(getMask(), Result);
2043 }
2044
2045 SmallVector<int, 16> getShuffleMask() const {
2046 SmallVector<int, 16> Mask;
2047 getShuffleMask(Mask);
2048 return Mask;
2049 }
2050
2051 /// Return true if this shuffle returns a vector with a different number of
2052 /// elements than its source vectors.
2053 /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2054 /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2055 bool changesLength() const {
2056 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2057 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2058 return NumSourceElts != NumMaskElts;
2059 }
2060
2061 /// Return true if this shuffle returns a vector with a greater number of
2062 /// elements than its source vectors.
2063 /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2064 bool increasesLength() const {
2065 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2066 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2067 return NumSourceElts < NumMaskElts;
2068 }
2069
2070 /// Return true if this shuffle mask chooses elements from exactly one source
2071 /// vector.
2072 /// Example: <7,5,undef,7>
2073 /// This assumes that vector operands are the same length as the mask.
2074 static bool isSingleSourceMask(ArrayRef<int> Mask);
2075 static bool isSingleSourceMask(const Constant *Mask) {
2076 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2076, __PRETTY_FUNCTION__))
;
2077 SmallVector<int, 16> MaskAsInts;
2078 getShuffleMask(Mask, MaskAsInts);
2079 return isSingleSourceMask(MaskAsInts);
2080 }
2081
2082 /// Return true if this shuffle chooses elements from exactly one source
2083 /// vector without changing the length of that vector.
2084 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2085 /// TODO: Optionally allow length-changing shuffles.
2086 bool isSingleSource() const {
2087 return !changesLength() && isSingleSourceMask(getMask());
2088 }
2089
2090 /// Return true if this shuffle mask chooses elements from exactly one source
2091 /// vector without lane crossings. A shuffle using this mask is not
2092 /// necessarily a no-op because it may change the number of elements from its
2093 /// input vectors or it may provide demanded bits knowledge via undef lanes.
2094 /// Example: <undef,undef,2,3>
2095 static bool isIdentityMask(ArrayRef<int> Mask);
2096 static bool isIdentityMask(const Constant *Mask) {
2097 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2097, __PRETTY_FUNCTION__))
;
2098 SmallVector<int, 16> MaskAsInts;
2099 getShuffleMask(Mask, MaskAsInts);
2100 return isIdentityMask(MaskAsInts);
2101 }
2102
2103 /// Return true if this shuffle chooses elements from exactly one source
2104 /// vector without lane crossings and does not change the number of elements
2105 /// from its input vectors.
2106 /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2107 bool isIdentity() const {
2108 return !changesLength() && isIdentityMask(getShuffleMask());
2109 }
2110
2111 /// Return true if this shuffle lengthens exactly one source vector with
2112 /// undefs in the high elements.
2113 bool isIdentityWithPadding() const;
2114
2115 /// Return true if this shuffle extracts the first N elements of exactly one
2116 /// source vector.
2117 bool isIdentityWithExtract() const;
2118
2119 /// Return true if this shuffle concatenates its 2 source vectors. This
2120 /// returns false if either input is undefined. In that case, the shuffle is
2121 /// is better classified as an identity with padding operation.
2122 bool isConcat() const;
2123
2124 /// Return true if this shuffle mask chooses elements from its source vectors
2125 /// without lane crossings. A shuffle using this mask would be
2126 /// equivalent to a vector select with a constant condition operand.
2127 /// Example: <4,1,6,undef>
2128 /// This returns false if the mask does not choose from both input vectors.
2129 /// In that case, the shuffle is better classified as an identity shuffle.
2130 /// This assumes that vector operands are the same length as the mask
2131 /// (a length-changing shuffle can never be equivalent to a vector select).
2132 static bool isSelectMask(ArrayRef<int> Mask);
2133 static bool isSelectMask(const Constant *Mask) {
2134 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2134, __PRETTY_FUNCTION__))
;
2135 SmallVector<int, 16> MaskAsInts;
2136 getShuffleMask(Mask, MaskAsInts);
2137 return isSelectMask(MaskAsInts);
2138 }
2139
2140 /// Return true if this shuffle chooses elements from its source vectors
2141 /// without lane crossings and all operands have the same number of elements.
2142 /// In other words, this shuffle is equivalent to a vector select with a
2143 /// constant condition operand.
2144 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2145 /// This returns false if the mask does not choose from both input vectors.
2146 /// In that case, the shuffle is better classified as an identity shuffle.
2147 /// TODO: Optionally allow length-changing shuffles.
2148 bool isSelect() const {
2149 return !changesLength() && isSelectMask(getMask());
2150 }
2151
2152 /// Return true if this shuffle mask swaps the order of elements from exactly
2153 /// one source vector.
2154 /// Example: <7,6,undef,4>
2155 /// This assumes that vector operands are the same length as the mask.
2156 static bool isReverseMask(ArrayRef<int> Mask);
2157 static bool isReverseMask(const Constant *Mask) {
2158 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2158, __PRETTY_FUNCTION__))
;
2159 SmallVector<int, 16> MaskAsInts;
2160 getShuffleMask(Mask, MaskAsInts);
2161 return isReverseMask(MaskAsInts);
2162 }
2163
2164 /// Return true if this shuffle swaps the order of elements from exactly
2165 /// one source vector.
2166 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2167 /// TODO: Optionally allow length-changing shuffles.
2168 bool isReverse() const {
2169 return !changesLength() && isReverseMask(getMask());
2170 }
2171
2172 /// Return true if this shuffle mask chooses all elements with the same value
2173 /// as the first element of exactly one source vector.
2174 /// Example: <4,undef,undef,4>
2175 /// This assumes that vector operands are the same length as the mask.
2176 static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2177 static bool isZeroEltSplatMask(const Constant *Mask) {
2178 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2178, __PRETTY_FUNCTION__))
;
2179 SmallVector<int, 16> MaskAsInts;
2180 getShuffleMask(Mask, MaskAsInts);
2181 return isZeroEltSplatMask(MaskAsInts);
2182 }
2183
2184 /// Return true if all elements of this shuffle are the same value as the
2185 /// first element of exactly one source vector without changing the length
2186 /// of that vector.
2187 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2188 /// TODO: Optionally allow length-changing shuffles.
2189 /// TODO: Optionally allow splats from other elements.
2190 bool isZeroEltSplat() const {
2191 return !changesLength() && isZeroEltSplatMask(getMask());
2192 }
2193
2194 /// Return true if this shuffle mask is a transpose mask.
2195 /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2196 /// even- or odd-numbered vector elements from two n-dimensional source
2197 /// vectors and write each result into consecutive elements of an
2198 /// n-dimensional destination vector. Two shuffles are necessary to complete
2199 /// the transpose, one for the even elements and another for the odd elements.
2200 /// This description closely follows how the TRN1 and TRN2 AArch64
2201 /// instructions operate.
2202 ///
2203 /// For example, a simple 2x2 matrix can be transposed with:
2204 ///
2205 /// ; Original matrix
2206 /// m0 = < a, b >
2207 /// m1 = < c, d >
2208 ///
2209 /// ; Transposed matrix
2210 /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2211 /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2212 ///
2213 /// For matrices having greater than n columns, the resulting nx2 transposed
2214 /// matrix is stored in two result vectors such that one vector contains
2215 /// interleaved elements from all the even-numbered rows and the other vector
2216 /// contains interleaved elements from all the odd-numbered rows. For example,
2217 /// a 2x4 matrix can be transposed with:
2218 ///
2219 /// ; Original matrix
2220 /// m0 = < a, b, c, d >
2221 /// m1 = < e, f, g, h >
2222 ///
2223 /// ; Transposed matrix
2224 /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2225 /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2226 static bool isTransposeMask(ArrayRef<int> Mask);
2227 static bool isTransposeMask(const Constant *Mask) {
2228 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2228, __PRETTY_FUNCTION__))
;
2229 SmallVector<int, 16> MaskAsInts;
2230 getShuffleMask(Mask, MaskAsInts);
2231 return isTransposeMask(MaskAsInts);
2232 }
2233
2234 /// Return true if this shuffle transposes the elements of its inputs without
2235 /// changing the length of the vectors. This operation may also be known as a
2236 /// merge or interleave. See the description for isTransposeMask() for the
2237 /// exact specification.
2238 /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2239 bool isTranspose() const {
2240 return !changesLength() && isTransposeMask(getMask());
2241 }
2242
2243 /// Return true if this shuffle mask is an extract subvector mask.
2244 /// A valid extract subvector mask returns a smaller vector from a single
2245 /// source operand. The base extraction index is returned as well.
2246 static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2247 int &Index);
2248 static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2249 int &Index) {
2250 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2250, __PRETTY_FUNCTION__))
;
2251 SmallVector<int, 16> MaskAsInts;
2252 getShuffleMask(Mask, MaskAsInts);
2253 return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2254 }
2255
2256 /// Return true if this shuffle mask is an extract subvector mask.
2257 bool isExtractSubvectorMask(int &Index) const {
2258 int NumSrcElts = Op<0>()->getType()->getVectorNumElements();
2259 return isExtractSubvectorMask(getMask(), NumSrcElts, Index);
2260 }
2261
2262 /// Change values in a shuffle permute mask assuming the two vector operands
2263 /// of length InVecNumElts have swapped position.
2264 static void commuteShuffleMask(MutableArrayRef<int> Mask,
2265 unsigned InVecNumElts) {
2266 for (int &Idx : Mask) {
2267 if (Idx == -1)
2268 continue;
2269 Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2270 assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&((Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
"shufflevector mask index out of range") ? static_cast<void
> (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2271, __PRETTY_FUNCTION__))
2271 "shufflevector mask index out of range")((Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
"shufflevector mask index out of range") ? static_cast<void
> (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2271, __PRETTY_FUNCTION__))
;
2272 }
2273 }
2274
2275 // Methods for support type inquiry through isa, cast, and dyn_cast:
2276 static bool classof(const Instruction *I) {
2277 return I->getOpcode() == Instruction::ShuffleVector;
2278 }
2279 static bool classof(const Value *V) {
2280 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2281 }
2282};
2283
2284template <>
2285struct OperandTraits<ShuffleVectorInst> :
2286 public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2287};
2288
2289DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)ShuffleVectorInst::op_iterator ShuffleVectorInst::op_begin() {
return OperandTraits<ShuffleVectorInst>::op_begin(this
); } ShuffleVectorInst::const_op_iterator ShuffleVectorInst::
op_begin() const { return OperandTraits<ShuffleVectorInst>
::op_begin(const_cast<ShuffleVectorInst*>(this)); } ShuffleVectorInst
::op_iterator ShuffleVectorInst::op_end() { return OperandTraits
<ShuffleVectorInst>::op_end(this); } ShuffleVectorInst::
const_op_iterator ShuffleVectorInst::op_end() const { return OperandTraits
<ShuffleVectorInst>::op_end(const_cast<ShuffleVectorInst
*>(this)); } Value *ShuffleVectorInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<ShuffleVectorInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2289, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<ShuffleVectorInst>::op_begin(const_cast
<ShuffleVectorInst*>(this))[i_nocapture].get()); } void
ShuffleVectorInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<ShuffleVectorInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2289, __PRETTY_FUNCTION__)); OperandTraits<ShuffleVectorInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
ShuffleVectorInst::getNumOperands() const { return OperandTraits
<ShuffleVectorInst>::operands(this); } template <int
Idx_nocapture> Use &ShuffleVectorInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &ShuffleVectorInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
2290
2291//===----------------------------------------------------------------------===//
2292// ExtractValueInst Class
2293//===----------------------------------------------------------------------===//
2294
2295/// This instruction extracts a struct member or array
2296/// element value from an aggregate value.
2297///
2298class ExtractValueInst : public UnaryInstruction {
2299 SmallVector<unsigned, 4> Indices;
2300
2301 ExtractValueInst(const ExtractValueInst &EVI);
2302
2303 /// Constructors - Create a extractvalue instruction with a base aggregate
2304 /// value and a list of indices. The first ctor can optionally insert before
2305 /// an existing instruction, the second appends the new instruction to the
2306 /// specified BasicBlock.
2307 inline ExtractValueInst(Value *Agg,
2308 ArrayRef<unsigned> Idxs,
2309 const Twine &NameStr,
2310 Instruction *InsertBefore);
2311 inline ExtractValueInst(Value *Agg,
2312 ArrayRef<unsigned> Idxs,
2313 const Twine &NameStr, BasicBlock *InsertAtEnd);
2314
2315 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2316
2317protected:
2318 // Note: Instruction needs to be a friend here to call cloneImpl.
2319 friend class Instruction;
2320
2321 ExtractValueInst *cloneImpl() const;
2322
2323public:
2324 static ExtractValueInst *Create(Value *Agg,
2325 ArrayRef<unsigned> Idxs,
2326 const Twine &NameStr = "",
2327 Instruction *InsertBefore = nullptr) {
2328 return new
2329 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2330 }
2331
2332 static ExtractValueInst *Create(Value *Agg,
2333 ArrayRef<unsigned> Idxs,
2334 const Twine &NameStr,
2335 BasicBlock *InsertAtEnd) {
2336 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2337 }
2338
2339 /// Returns the type of the element that would be extracted
2340 /// with an extractvalue instruction with the specified parameters.
2341 ///
2342 /// Null is returned if the indices are invalid for the specified type.
2343 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2344
2345 using idx_iterator = const unsigned*;
2346
2347 inline idx_iterator idx_begin() const { return Indices.begin(); }
2348 inline idx_iterator idx_end() const { return Indices.end(); }
2349 inline iterator_range<idx_iterator> indices() const {
2350 return make_range(idx_begin(), idx_end());
2351 }
2352
2353 Value *getAggregateOperand() {
2354 return getOperand(0);
2355 }
2356 const Value *getAggregateOperand() const {
2357 return getOperand(0);
2358 }
2359 static unsigned getAggregateOperandIndex() {
2360 return 0U; // get index for modifying correct operand
2361 }
2362
2363 ArrayRef<unsigned> getIndices() const {
2364 return Indices;
2365 }
2366
2367 unsigned getNumIndices() const {
2368 return (unsigned)Indices.size();
2369 }
2370
2371 bool hasIndices() const {
2372 return true;
2373 }
2374
2375 // Methods for support type inquiry through isa, cast, and dyn_cast:
2376 static bool classof(const Instruction *I) {
2377 return I->getOpcode() == Instruction::ExtractValue;
2378 }
2379 static bool classof(const Value *V) {
2380 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2381 }
2382};
2383
2384ExtractValueInst::ExtractValueInst(Value *Agg,
2385 ArrayRef<unsigned> Idxs,
2386 const Twine &NameStr,
2387 Instruction *InsertBefore)
2388 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2389 ExtractValue, Agg, InsertBefore) {
2390 init(Idxs, NameStr);
2391}
2392
2393ExtractValueInst::ExtractValueInst(Value *Agg,
2394 ArrayRef<unsigned> Idxs,
2395 const Twine &NameStr,
2396 BasicBlock *InsertAtEnd)
2397 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2398 ExtractValue, Agg, InsertAtEnd) {
2399 init(Idxs, NameStr);
2400}
2401
2402//===----------------------------------------------------------------------===//
2403// InsertValueInst Class
2404//===----------------------------------------------------------------------===//
2405
2406/// This instruction inserts a struct field of array element
2407/// value into an aggregate value.
2408///
2409class InsertValueInst : public Instruction {
2410 SmallVector<unsigned, 4> Indices;
2411
2412 InsertValueInst(const InsertValueInst &IVI);
2413
2414 /// Constructors - Create a insertvalue instruction with a base aggregate
2415 /// value, a value to insert, and a list of indices. The first ctor can
2416 /// optionally insert before an existing instruction, the second appends
2417 /// the new instruction to the specified BasicBlock.
2418 inline InsertValueInst(Value *Agg, Value *Val,
2419 ArrayRef<unsigned> Idxs,
2420 const Twine &NameStr,
2421 Instruction *InsertBefore);
2422 inline InsertValueInst(Value *Agg, Value *Val,
2423 ArrayRef<unsigned> Idxs,
2424 const Twine &NameStr, BasicBlock *InsertAtEnd);
2425
2426 /// Constructors - These two constructors are convenience methods because one
2427 /// and two index insertvalue instructions are so common.
2428 InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2429 const Twine &NameStr = "",
2430 Instruction *InsertBefore = nullptr);
2431 InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2432 BasicBlock *InsertAtEnd);
2433
2434 void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2435 const Twine &NameStr);
2436
2437protected:
2438 // Note: Instruction needs to be a friend here to call cloneImpl.
2439 friend class Instruction;
2440
2441 InsertValueInst *cloneImpl() const;
2442
2443public:
2444 // allocate space for exactly two operands
2445 void *operator new(size_t s) {
2446 return User::operator new(s, 2);
2447 }
2448
2449 static InsertValueInst *Create(Value *Agg, Value *Val,
2450 ArrayRef<unsigned> Idxs,
2451 const Twine &NameStr = "",
2452 Instruction *InsertBefore = nullptr) {
2453 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2454 }
2455
2456 static InsertValueInst *Create(Value *Agg, Value *Val,
2457 ArrayRef<unsigned> Idxs,
2458 const Twine &NameStr,
2459 BasicBlock *InsertAtEnd) {
2460 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2461 }
2462
2463 /// Transparently provide more efficient getOperand methods.
2464 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2465
2466 using idx_iterator = const unsigned*;
2467
2468 inline idx_iterator idx_begin() const { return Indices.begin(); }
2469 inline idx_iterator idx_end() const { return Indices.end(); }
2470 inline iterator_range<idx_iterator> indices() const {
2471 return make_range(idx_begin(), idx_end());
2472 }
2473
2474 Value *getAggregateOperand() {
2475 return getOperand(0);
2476 }
2477 const Value *getAggregateOperand() const {
2478 return getOperand(0);
2479 }
2480 static unsigned getAggregateOperandIndex() {
2481 return 0U; // get index for modifying correct operand
2482 }
2483
2484 Value *getInsertedValueOperand() {
2485 return getOperand(1);
2486 }
2487 const Value *getInsertedValueOperand() const {
2488 return getOperand(1);
2489 }
2490 static unsigned getInsertedValueOperandIndex() {
2491 return 1U; // get index for modifying correct operand
2492 }
2493
2494 ArrayRef<unsigned> getIndices() const {
2495 return Indices;
2496 }
2497
2498 unsigned getNumIndices() const {
2499 return (unsigned)Indices.size();
2500 }
2501
2502 bool hasIndices() const {
2503 return true;
2504 }
2505
2506 // Methods for support type inquiry through isa, cast, and dyn_cast:
2507 static bool classof(const Instruction *I) {
2508 return I->getOpcode() == Instruction::InsertValue;
2509 }
2510 static bool classof(const Value *V) {
2511 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2512 }
2513};
2514
2515template <>
2516struct OperandTraits<InsertValueInst> :
2517 public FixedNumOperandTraits<InsertValueInst, 2> {
2518};
2519
2520InsertValueInst::InsertValueInst(Value *Agg,
2521 Value *Val,
2522 ArrayRef<unsigned> Idxs,
2523 const Twine &NameStr,
2524 Instruction *InsertBefore)
2525 : Instruction(Agg->getType(), InsertValue,
2526 OperandTraits<InsertValueInst>::op_begin(this),
2527 2, InsertBefore) {
2528 init(Agg, Val, Idxs, NameStr);
2529}
2530
2531InsertValueInst::InsertValueInst(Value *Agg,
2532 Value *Val,
2533 ArrayRef<unsigned> Idxs,
2534 const Twine &NameStr,
2535 BasicBlock *InsertAtEnd)
2536 : Instruction(Agg->getType(), InsertValue,
2537 OperandTraits<InsertValueInst>::op_begin(this),
2538 2, InsertAtEnd) {
2539 init(Agg, Val, Idxs, NameStr);
2540}
2541
2542DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)InsertValueInst::op_iterator InsertValueInst::op_begin() { return
OperandTraits<InsertValueInst>::op_begin(this); } InsertValueInst
::const_op_iterator InsertValueInst::op_begin() const { return
OperandTraits<InsertValueInst>::op_begin(const_cast<
InsertValueInst*>(this)); } InsertValueInst::op_iterator InsertValueInst
::op_end() { return OperandTraits<InsertValueInst>::op_end
(this); } InsertValueInst::const_op_iterator InsertValueInst::
op_end() const { return OperandTraits<InsertValueInst>::
op_end(const_cast<InsertValueInst*>(this)); } Value *InsertValueInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<InsertValueInst>::operands(this) &&
"getOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2542, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<InsertValueInst>::op_begin(const_cast<
InsertValueInst*>(this))[i_nocapture].get()); } void InsertValueInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<InsertValueInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2542, __PRETTY_FUNCTION__)); OperandTraits<InsertValueInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
InsertValueInst::getNumOperands() const { return OperandTraits
<InsertValueInst>::operands(this); } template <int Idx_nocapture
> Use &InsertValueInst::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &InsertValueInst::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
2543
2544//===----------------------------------------------------------------------===//
2545// PHINode Class
2546//===----------------------------------------------------------------------===//
2547
2548// PHINode - The PHINode class is used to represent the magical mystical PHI
2549// node, that can not exist in nature, but can be synthesized in a computer
2550// scientist's overactive imagination.
2551//
2552class PHINode : public Instruction {
2553 /// The number of operands actually allocated. NumOperands is
2554 /// the number actually in use.
2555 unsigned ReservedSpace;
2556
2557 PHINode(const PHINode &PN);
2558
2559 explicit PHINode(Type *Ty, unsigned NumReservedValues,
2560 const Twine &NameStr = "",
2561 Instruction *InsertBefore = nullptr)
2562 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2563 ReservedSpace(NumReservedValues) {
2564 setName(NameStr);
2565 allocHungoffUses(ReservedSpace);
2566 }
2567
2568 PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2569 BasicBlock *InsertAtEnd)
2570 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2571 ReservedSpace(NumReservedValues) {
2572 setName(NameStr);
2573 allocHungoffUses(ReservedSpace);
2574 }
2575
2576protected:
2577 // Note: Instruction needs to be a friend here to call cloneImpl.
2578 friend class Instruction;
2579
2580 PHINode *cloneImpl() const;
2581
2582 // allocHungoffUses - this is more complicated than the generic
2583 // User::allocHungoffUses, because we have to allocate Uses for the incoming
2584 // values and pointers to the incoming blocks, all in one allocation.
2585 void allocHungoffUses(unsigned N) {
2586 User::allocHungoffUses(N, /* IsPhi */ true);
2587 }
2588
2589public:
2590 /// Constructors - NumReservedValues is a hint for the number of incoming
2591 /// edges that this phi node will have (use 0 if you really have no idea).
2592 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2593 const Twine &NameStr = "",
2594 Instruction *InsertBefore = nullptr) {
2595 return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2596 }
2597
2598 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2599 const Twine &NameStr, BasicBlock *InsertAtEnd) {
2600 return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2601 }
2602
2603 /// Provide fast operand accessors
2604 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2605
2606 // Block iterator interface. This provides access to the list of incoming
2607 // basic blocks, which parallels the list of incoming values.
2608
2609 using block_iterator = BasicBlock **;
2610 using const_block_iterator = BasicBlock * const *;
2611
2612 block_iterator block_begin() {
2613 Use::UserRef *ref =
2614 reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2615 return reinterpret_cast<block_iterator>(ref + 1);
2616 }
2617
2618 const_block_iterator block_begin() const {
2619 const Use::UserRef *ref =
2620 reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2621 return reinterpret_cast<const_block_iterator>(ref + 1);
2622 }
2623
2624 block_iterator block_end() {
2625 return block_begin() + getNumOperands();
2626 }
2627
2628 const_block_iterator block_end() const {
2629 return block_begin() + getNumOperands();
2630 }
2631
2632 iterator_range<block_iterator> blocks() {
2633 return make_range(block_begin(), block_end());
2634 }
2635
2636 iterator_range<const_block_iterator> blocks() const {
2637 return make_range(block_begin(), block_end());
2638 }
2639
2640 op_range incoming_values() { return operands(); }
2641
2642 const_op_range incoming_values() const { return operands(); }
2643
2644 /// Return the number of incoming edges
2645 ///
2646 unsigned getNumIncomingValues() const { return getNumOperands(); }
2647
2648 /// Return incoming value number x
2649 ///
2650 Value *getIncomingValue(unsigned i) const {
2651 return getOperand(i);
2652 }
2653 void setIncomingValue(unsigned i, Value *V) {
2654 assert(V && "PHI node got a null value!")((V && "PHI node got a null value!") ? static_cast<
void> (0) : __assert_fail ("V && \"PHI node got a null value!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2654, __PRETTY_FUNCTION__))
;
2655 assert(getType() == V->getType() &&((getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node!"
) ? static_cast<void> (0) : __assert_fail ("getType() == V->getType() && \"All operands to PHI node must be the same type as the PHI node!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2656, __PRETTY_FUNCTION__))
2656 "All operands to PHI node must be the same type as the PHI node!")((getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node!"
) ? static_cast<void> (0) : __assert_fail ("getType() == V->getType() && \"All operands to PHI node must be the same type as the PHI node!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2656, __PRETTY_FUNCTION__))
;
2657 setOperand(i, V);
2658 }
2659
2660 static unsigned getOperandNumForIncomingValue(unsigned i) {
2661 return i;
2662 }
2663
2664 static unsigned getIncomingValueNumForOperand(unsigned i) {
2665 return i;
2666 }
2667
2668 /// Return incoming basic block number @p i.
2669 ///
2670 BasicBlock *getIncomingBlock(unsigned i) const {
2671 return block_begin()[i];
2672 }
2673
2674 /// Return incoming basic block corresponding
2675 /// to an operand of the PHI.
2676 ///
2677 BasicBlock *getIncomingBlock(const Use &U) const {
2678 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?")((this == U.getUser() && "Iterator doesn't point to PHI's Uses?"
) ? static_cast<void> (0) : __assert_fail ("this == U.getUser() && \"Iterator doesn't point to PHI's Uses?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/Instructions.h"
, 2678, __PRETTY_FUNCTION__))
;
2679 return getIncomingBlock(unsigned(&U - op_begin()));
2680 }
2681