Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -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 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/lib/Transforms/Scalar -I include -I /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-command-line-argument -Wno-unknown-warning-option -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/build-llvm -ferror-limit 19 -fvisibility-inlines-hidden -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-10-17-004846-21170-1 -x c++ /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/lib/Transforms/Scalar/JumpThreading.cpp

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

/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/IR/Instructions.h

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