Bug Summary

File:llvm/lib/Transforms/Scalar/LICM.cpp
Warning:line 1288, column 20
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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

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

1//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
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 pass performs loop invariant code motion, attempting to remove as much
10// code from the body of a loop as possible. It does this by either hoisting
11// code into the preheader block, or by sinking code to the exit blocks if it is
12// safe. This pass also promotes must-aliased memory locations in the loop to
13// live in registers, thus hoisting and sinking "invariant" loads and stores.
14//
15// This pass uses alias analysis for two purposes:
16//
17// 1. Moving loop invariant loads and calls out of loops. If we can determine
18// that a load or call inside of a loop never aliases anything stored to,
19// we can hoist it or sink it like any other instruction.
20// 2. Scalar Promotion of Memory - If there is a store instruction inside of
21// the loop, we try to move the store to happen AFTER the loop instead of
22// inside of the loop. This can only happen if a few conditions are true:
23// A. The pointer stored through is loop invariant
24// B. There are no stores or loads in the loop which _may_ alias the
25// pointer. There are no calls in the loop which mod/ref the pointer.
26// If these conditions are true, we can promote the loads and stores in the
27// loop of the pointer to use a temporary alloca'd variable. We then use
28// the SSAUpdater to construct the appropriate SSA form for the value.
29//
30//===----------------------------------------------------------------------===//
31
32#include "llvm/Transforms/Scalar/LICM.h"
33#include "llvm/ADT/SetOperations.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/Analysis/AliasAnalysis.h"
36#include "llvm/Analysis/AliasSetTracker.h"
37#include "llvm/Analysis/BasicAliasAnalysis.h"
38#include "llvm/Analysis/CaptureTracking.h"
39#include "llvm/Analysis/ConstantFolding.h"
40#include "llvm/Analysis/GlobalsModRef.h"
41#include "llvm/Analysis/GuardUtils.h"
42#include "llvm/Analysis/Loads.h"
43#include "llvm/Analysis/LoopInfo.h"
44#include "llvm/Analysis/LoopIterator.h"
45#include "llvm/Analysis/LoopPass.h"
46#include "llvm/Analysis/MemoryBuiltins.h"
47#include "llvm/Analysis/MemorySSA.h"
48#include "llvm/Analysis/MemorySSAUpdater.h"
49#include "llvm/Analysis/OptimizationRemarkEmitter.h"
50#include "llvm/Analysis/ScalarEvolution.h"
51#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
52#include "llvm/Analysis/TargetLibraryInfo.h"
53#include "llvm/Analysis/ValueTracking.h"
54#include "llvm/IR/CFG.h"
55#include "llvm/IR/Constants.h"
56#include "llvm/IR/DataLayout.h"
57#include "llvm/IR/DebugInfoMetadata.h"
58#include "llvm/IR/DerivedTypes.h"
59#include "llvm/IR/Dominators.h"
60#include "llvm/IR/Instructions.h"
61#include "llvm/IR/IntrinsicInst.h"
62#include "llvm/IR/LLVMContext.h"
63#include "llvm/IR/Metadata.h"
64#include "llvm/IR/PatternMatch.h"
65#include "llvm/IR/PredIteratorCache.h"
66#include "llvm/InitializePasses.h"
67#include "llvm/Support/CommandLine.h"
68#include "llvm/Support/Debug.h"
69#include "llvm/Support/raw_ostream.h"
70#include "llvm/Transforms/Scalar.h"
71#include "llvm/Transforms/Scalar/LoopPassManager.h"
72#include "llvm/Transforms/Utils/BasicBlockUtils.h"
73#include "llvm/Transforms/Utils/Local.h"
74#include "llvm/Transforms/Utils/LoopUtils.h"
75#include "llvm/Transforms/Utils/SSAUpdater.h"
76#include <algorithm>
77#include <utility>
78using namespace llvm;
79
80#define DEBUG_TYPE"licm" "licm"
81
82STATISTIC(NumCreatedBlocks, "Number of blocks created")static llvm::Statistic NumCreatedBlocks = {"licm", "NumCreatedBlocks"
, "Number of blocks created"}
;
83STATISTIC(NumClonedBranches, "Number of branches cloned")static llvm::Statistic NumClonedBranches = {"licm", "NumClonedBranches"
, "Number of branches cloned"}
;
84STATISTIC(NumSunk, "Number of instructions sunk out of loop")static llvm::Statistic NumSunk = {"licm", "NumSunk", "Number of instructions sunk out of loop"
}
;
85STATISTIC(NumHoisted, "Number of instructions hoisted out of loop")static llvm::Statistic NumHoisted = {"licm", "NumHoisted", "Number of instructions hoisted out of loop"
}
;
86STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk")static llvm::Statistic NumMovedLoads = {"licm", "NumMovedLoads"
, "Number of load insts hoisted or sunk"}
;
87STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk")static llvm::Statistic NumMovedCalls = {"licm", "NumMovedCalls"
, "Number of call insts hoisted or sunk"}
;
88STATISTIC(NumPromoted, "Number of memory locations promoted to registers")static llvm::Statistic NumPromoted = {"licm", "NumPromoted", "Number of memory locations promoted to registers"
}
;
89
90/// Memory promotion is enabled by default.
91static cl::opt<bool>
92 DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),
93 cl::desc("Disable memory promotion in LICM pass"));
94
95static cl::opt<bool> ControlFlowHoisting(
96 "licm-control-flow-hoisting", cl::Hidden, cl::init(false),
97 cl::desc("Enable control flow (and PHI) hoisting in LICM"));
98
99static cl::opt<uint32_t> MaxNumUsesTraversed(
100 "licm-max-num-uses-traversed", cl::Hidden, cl::init(8),
101 cl::desc("Max num uses visited for identifying load "
102 "invariance in loop using invariant start (default = 8)"));
103
104// Default value of zero implies we use the regular alias set tracker mechanism
105// instead of the cross product using AA to identify aliasing of the memory
106// location we are interested in.
107static cl::opt<int>
108LICMN2Theshold("licm-n2-threshold", cl::Hidden, cl::init(0),
109 cl::desc("How many instruction to cross product using AA"));
110
111// Experimental option to allow imprecision in LICM in pathological cases, in
112// exchange for faster compile. This is to be removed if MemorySSA starts to
113// address the same issue. This flag applies only when LICM uses MemorySSA
114// instead on AliasSetTracker. LICM calls MemorySSAWalker's
115// getClobberingMemoryAccess, up to the value of the Cap, getting perfect
116// accuracy. Afterwards, LICM will call into MemorySSA's getDefiningAccess,
117// which may not be precise, since optimizeUses is capped. The result is
118// correct, but we may not get as "far up" as possible to get which access is
119// clobbering the one queried.
120cl::opt<unsigned> llvm::SetLicmMssaOptCap(
121 "licm-mssa-optimization-cap", cl::init(100), cl::Hidden,
122 cl::desc("Enable imprecision in LICM in pathological cases, in exchange "
123 "for faster compile. Caps the MemorySSA clobbering calls."));
124
125// Experimentally, memory promotion carries less importance than sinking and
126// hoisting. Limit when we do promotion when using MemorySSA, in order to save
127// compile time.
128cl::opt<unsigned> llvm::SetLicmMssaNoAccForPromotionCap(
129 "licm-mssa-max-acc-promotion", cl::init(250), cl::Hidden,
130 cl::desc("[LICM & MemorySSA] When MSSA in LICM is disabled, this has no "
131 "effect. When MSSA in LICM is enabled, then this is the maximum "
132 "number of accesses allowed to be present in a loop in order to "
133 "enable memory promotion."));
134
135static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
136static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
137 const LoopSafetyInfo *SafetyInfo,
138 TargetTransformInfo *TTI, bool &FreeInLoop);
139static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
140 BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,
141 MemorySSAUpdater *MSSAU, ScalarEvolution *SE,
142 OptimizationRemarkEmitter *ORE);
143static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
144 const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo,
145 MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE);
146static bool isSafeToExecuteUnconditionally(Instruction &Inst,
147 const DominatorTree *DT,
148 const Loop *CurLoop,
149 const LoopSafetyInfo *SafetyInfo,
150 OptimizationRemarkEmitter *ORE,
151 const Instruction *CtxI = nullptr);
152static bool pointerInvalidatedByLoop(MemoryLocation MemLoc,
153 AliasSetTracker *CurAST, Loop *CurLoop,
154 AliasAnalysis *AA);
155static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU,
156 Loop *CurLoop,
157 SinkAndHoistLICMFlags &Flags);
158static Instruction *CloneInstructionInExitBlock(
159 Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,
160 const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU);
161
162static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo,
163 AliasSetTracker *AST, MemorySSAUpdater *MSSAU);
164
165static void moveInstructionBefore(Instruction &I, Instruction &Dest,
166 ICFLoopSafetyInfo &SafetyInfo,
167 MemorySSAUpdater *MSSAU, ScalarEvolution *SE);
168
169namespace {
170struct LoopInvariantCodeMotion {
171 using ASTrackerMapTy = DenseMap<Loop *, std::unique_ptr<AliasSetTracker>>;
172 bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
173 TargetLibraryInfo *TLI, TargetTransformInfo *TTI,
174 ScalarEvolution *SE, MemorySSA *MSSA,
175 OptimizationRemarkEmitter *ORE, bool DeleteAST);
176
177 ASTrackerMapTy &getLoopToAliasSetMap() { return LoopToAliasSetMap; }
178 LoopInvariantCodeMotion(unsigned LicmMssaOptCap,
179 unsigned LicmMssaNoAccForPromotionCap)
180 : LicmMssaOptCap(LicmMssaOptCap),
181 LicmMssaNoAccForPromotionCap(LicmMssaNoAccForPromotionCap) {}
182
183private:
184 ASTrackerMapTy LoopToAliasSetMap;
185 unsigned LicmMssaOptCap;
186 unsigned LicmMssaNoAccForPromotionCap;
187
188 std::unique_ptr<AliasSetTracker>
189 collectAliasInfoForLoop(Loop *L, LoopInfo *LI, AliasAnalysis *AA);
190 std::unique_ptr<AliasSetTracker>
191 collectAliasInfoForLoopWithMSSA(Loop *L, AliasAnalysis *AA,
192 MemorySSAUpdater *MSSAU);
193};
194
195struct LegacyLICMPass : public LoopPass {
196 static char ID; // Pass identification, replacement for typeid
197 LegacyLICMPass(
198 unsigned LicmMssaOptCap = SetLicmMssaOptCap,
199 unsigned LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap)
200 : LoopPass(ID), LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap) {
201 initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
202 }
203
204 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
205 if (skipLoop(L)) {
206 // If we have run LICM on a previous loop but now we are skipping
207 // (because we've hit the opt-bisect limit), we need to clear the
208 // loop alias information.
209 LICM.getLoopToAliasSetMap().clear();
210 return false;
211 }
212
213 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
214 MemorySSA *MSSA = EnableMSSALoopDependency
215 ? (&getAnalysis<MemorySSAWrapperPass>().getMSSA())
216 : nullptr;
217 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
218 // pass. Function analyses need to be preserved across loop transformations
219 // but ORE cannot be preserved (see comment before the pass definition).
220 OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
221 return LICM.runOnLoop(L,
222 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
223 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
224 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
225 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
226 *L->getHeader()->getParent()),
227 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
228 *L->getHeader()->getParent()),
229 SE ? &SE->getSE() : nullptr, MSSA, &ORE, false);
230 }
231
232 /// This transformation requires natural loop information & requires that
233 /// loop preheaders be inserted into the CFG...
234 ///
235 void getAnalysisUsage(AnalysisUsage &AU) const override {
236 AU.addPreserved<DominatorTreeWrapperPass>();
237 AU.addPreserved<LoopInfoWrapperPass>();
238 AU.addRequired<TargetLibraryInfoWrapperPass>();
239 if (EnableMSSALoopDependency) {
240 AU.addRequired<MemorySSAWrapperPass>();
241 AU.addPreserved<MemorySSAWrapperPass>();
242 }
243 AU.addRequired<TargetTransformInfoWrapperPass>();
244 getLoopAnalysisUsage(AU);
245 }
246
247 using llvm::Pass::doFinalization;
248
249 bool doFinalization() override {
250 auto &AliasSetMap = LICM.getLoopToAliasSetMap();
251 // All loops in the AliasSetMap should be cleaned up already. The only case
252 // where we fail to do so is if an outer loop gets deleted before LICM
253 // visits it.
254 assert(all_of(AliasSetMap,((all_of(AliasSetMap, [](LoopInvariantCodeMotion::ASTrackerMapTy
::value_type &KV) { return !KV.first->getParentLoop();
}) && "Didn't free loop alias sets") ? static_cast<
void> (0) : __assert_fail ("all_of(AliasSetMap, [](LoopInvariantCodeMotion::ASTrackerMapTy::value_type &KV) { return !KV.first->getParentLoop(); }) && \"Didn't free loop alias sets\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 258, __PRETTY_FUNCTION__))
255 [](LoopInvariantCodeMotion::ASTrackerMapTy::value_type &KV) {((all_of(AliasSetMap, [](LoopInvariantCodeMotion::ASTrackerMapTy
::value_type &KV) { return !KV.first->getParentLoop();
}) && "Didn't free loop alias sets") ? static_cast<
void> (0) : __assert_fail ("all_of(AliasSetMap, [](LoopInvariantCodeMotion::ASTrackerMapTy::value_type &KV) { return !KV.first->getParentLoop(); }) && \"Didn't free loop alias sets\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 258, __PRETTY_FUNCTION__))
256 return !KV.first->getParentLoop();((all_of(AliasSetMap, [](LoopInvariantCodeMotion::ASTrackerMapTy
::value_type &KV) { return !KV.first->getParentLoop();
}) && "Didn't free loop alias sets") ? static_cast<
void> (0) : __assert_fail ("all_of(AliasSetMap, [](LoopInvariantCodeMotion::ASTrackerMapTy::value_type &KV) { return !KV.first->getParentLoop(); }) && \"Didn't free loop alias sets\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 258, __PRETTY_FUNCTION__))
257 }) &&((all_of(AliasSetMap, [](LoopInvariantCodeMotion::ASTrackerMapTy
::value_type &KV) { return !KV.first->getParentLoop();
}) && "Didn't free loop alias sets") ? static_cast<
void> (0) : __assert_fail ("all_of(AliasSetMap, [](LoopInvariantCodeMotion::ASTrackerMapTy::value_type &KV) { return !KV.first->getParentLoop(); }) && \"Didn't free loop alias sets\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 258, __PRETTY_FUNCTION__))
258 "Didn't free loop alias sets")((all_of(AliasSetMap, [](LoopInvariantCodeMotion::ASTrackerMapTy
::value_type &KV) { return !KV.first->getParentLoop();
}) && "Didn't free loop alias sets") ? static_cast<
void> (0) : __assert_fail ("all_of(AliasSetMap, [](LoopInvariantCodeMotion::ASTrackerMapTy::value_type &KV) { return !KV.first->getParentLoop(); }) && \"Didn't free loop alias sets\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 258, __PRETTY_FUNCTION__))
;
259 AliasSetMap.clear();
260 return false;
261 }
262
263private:
264 LoopInvariantCodeMotion LICM;
265
266 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
267 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
268 Loop *L) override;
269
270 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
271 /// set.
272 void deleteAnalysisValue(Value *V, Loop *L) override;
273
274 /// Simple Analysis hook. Delete loop L from alias set map.
275 void deleteAnalysisLoop(Loop *L) override;
276};
277} // namespace
278
279PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM,
280 LoopStandardAnalysisResults &AR, LPMUpdater &) {
281 const auto &FAM =
282 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
283 Function *F = L.getHeader()->getParent();
284
285 auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
286 // FIXME: This should probably be optional rather than required.
287 if (!ORE)
288 report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not "
289 "cached at a higher level");
290
291 LoopInvariantCodeMotion LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap);
292 if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.TTI, &AR.SE,
293 AR.MSSA, ORE, true))
294 return PreservedAnalyses::all();
295
296 auto PA = getLoopPassPreservedAnalyses();
297
298 PA.preserve<DominatorTreeAnalysis>();
299 PA.preserve<LoopAnalysis>();
300 if (AR.MSSA)
301 PA.preserve<MemorySSAAnalysis>();
302
303 return PA;
304}
305
306char LegacyLICMPass::ID = 0;
307INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",static void *initializeLegacyLICMPassPassOnce(PassRegistry &
Registry) {
308 false, false)static void *initializeLegacyLICMPassPassOnce(PassRegistry &
Registry) {
309INITIALIZE_PASS_DEPENDENCY(LoopPass)initializeLoopPassPass(Registry);
310INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
311INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry);
312INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)initializeMemorySSAWrapperPassPass(Registry);
313INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,PassInfo *PI = new PassInfo( "Loop Invariant Code Motion", "licm"
, &LegacyLICMPass::ID, PassInfo::NormalCtor_t(callDefaultCtor
<LegacyLICMPass>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeLegacyLICMPassPassFlag
; void llvm::initializeLegacyLICMPassPass(PassRegistry &Registry
) { llvm::call_once(InitializeLegacyLICMPassPassFlag, initializeLegacyLICMPassPassOnce
, std::ref(Registry)); }
314 false)PassInfo *PI = new PassInfo( "Loop Invariant Code Motion", "licm"
, &LegacyLICMPass::ID, PassInfo::NormalCtor_t(callDefaultCtor
<LegacyLICMPass>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeLegacyLICMPassPassFlag
; void llvm::initializeLegacyLICMPassPass(PassRegistry &Registry
) { llvm::call_once(InitializeLegacyLICMPassPassFlag, initializeLegacyLICMPassPassOnce
, std::ref(Registry)); }
315
316Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
317Pass *llvm::createLICMPass(unsigned LicmMssaOptCap,
318 unsigned LicmMssaNoAccForPromotionCap) {
319 return new LegacyLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap);
320}
321
322/// Hoist expressions out of the specified loop. Note, alias info for inner
323/// loop is not preserved so it is not a good idea to run LICM multiple
324/// times on one loop.
325/// We should delete AST for inner loops in the new pass manager to avoid
326/// memory leak.
327///
328bool LoopInvariantCodeMotion::runOnLoop(
329 Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
330 TargetLibraryInfo *TLI, TargetTransformInfo *TTI, ScalarEvolution *SE,
331 MemorySSA *MSSA, OptimizationRemarkEmitter *ORE, bool DeleteAST) {
332 bool Changed = false;
333
334 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.")((L->isLCSSAForm(*DT) && "Loop is not in LCSSA form."
) ? static_cast<void> (0) : __assert_fail ("L->isLCSSAForm(*DT) && \"Loop is not in LCSSA form.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 334, __PRETTY_FUNCTION__))
;
335
336 // If this loop has metadata indicating that LICM is not to be performed then
337 // just exit.
338 if (hasDisableLICMTransformsHint(L)) {
339 return false;
340 }
341
342 std::unique_ptr<AliasSetTracker> CurAST;
343 std::unique_ptr<MemorySSAUpdater> MSSAU;
344 bool NoOfMemAccTooLarge = false;
345 unsigned LicmMssaOptCounter = 0;
346
347 if (!MSSA) {
348 LLVM_DEBUG(dbgs() << "LICM: Using Alias Set Tracker.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM: Using Alias Set Tracker.\n"
; } } while (false)
;
349 CurAST = collectAliasInfoForLoop(L, LI, AA);
350 } else {
351 LLVM_DEBUG(dbgs() << "LICM: Using MemorySSA.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM: Using MemorySSA.\n"; } } while
(false)
;
352 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
353
354 unsigned AccessCapCount = 0;
355 for (auto *BB : L->getBlocks()) {
356 if (auto *Accesses = MSSA->getBlockAccesses(BB)) {
357 for (const auto &MA : *Accesses) {
358 (void)MA;
359 AccessCapCount++;
360 if (AccessCapCount > LicmMssaNoAccForPromotionCap) {
361 NoOfMemAccTooLarge = true;
362 break;
363 }
364 }
365 }
366 if (NoOfMemAccTooLarge)
367 break;
368 }
369 }
370
371 // Get the preheader block to move instructions into...
372 BasicBlock *Preheader = L->getLoopPreheader();
373
374 // Compute loop safety information.
375 ICFLoopSafetyInfo SafetyInfo(DT);
376 SafetyInfo.computeLoopSafetyInfo(L);
377
378 // We want to visit all of the instructions in this loop... that are not parts
379 // of our subloops (they have already had their invariants hoisted out of
380 // their loop, into this loop, so there is no need to process the BODIES of
381 // the subloops).
382 //
383 // Traverse the body of the loop in depth first order on the dominator tree so
384 // that we are guaranteed to see definitions before we see uses. This allows
385 // us to sink instructions in one pass, without iteration. After sinking
386 // instructions, we perform another pass to hoist them out of the loop.
387 SinkAndHoistLICMFlags Flags = {NoOfMemAccTooLarge, LicmMssaOptCounter,
388 LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
389 /*IsSink=*/true};
390 if (L->hasDedicatedExits())
391 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L,
392 CurAST.get(), MSSAU.get(), &SafetyInfo, Flags, ORE);
393 Flags.IsSink = false;
394 if (Preheader)
395 Changed |=
396 hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
397 CurAST.get(), MSSAU.get(), SE, &SafetyInfo, Flags, ORE);
398
399 // Now that all loop invariants have been removed from the loop, promote any
400 // memory references to scalars that we can.
401 // Don't sink stores from loops without dedicated block exits. Exits
402 // containing indirect branches are not transformed by loop simplify,
403 // make sure we catch that. An additional load may be generated in the
404 // preheader for SSA updater, so also avoid sinking when no preheader
405 // is available.
406 if (!DisablePromotion && Preheader && L->hasDedicatedExits() &&
407 !NoOfMemAccTooLarge) {
408 // Figure out the loop exits and their insertion points
409 SmallVector<BasicBlock *, 8> ExitBlocks;
410 L->getUniqueExitBlocks(ExitBlocks);
411
412 // We can't insert into a catchswitch.
413 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
414 return isa<CatchSwitchInst>(Exit->getTerminator());
415 });
416
417 if (!HasCatchSwitch) {
418 SmallVector<Instruction *, 8> InsertPts;
419 SmallVector<MemoryAccess *, 8> MSSAInsertPts;
420 InsertPts.reserve(ExitBlocks.size());
421 if (MSSAU)
422 MSSAInsertPts.reserve(ExitBlocks.size());
423 for (BasicBlock *ExitBlock : ExitBlocks) {
424 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
425 if (MSSAU)
426 MSSAInsertPts.push_back(nullptr);
427 }
428
429 PredIteratorCache PIC;
430
431 bool Promoted = false;
432
433 // Build an AST using MSSA.
434 if (!CurAST.get())
435 CurAST = collectAliasInfoForLoopWithMSSA(L, AA, MSSAU.get());
436
437 // Loop over all of the alias sets in the tracker object.
438 for (AliasSet &AS : *CurAST) {
439 // We can promote this alias set if it has a store, if it is a "Must"
440 // alias set, if the pointer is loop invariant, and if we are not
441 // eliminating any volatile loads or stores.
442 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
443 !L->isLoopInvariant(AS.begin()->getValue()))
444 continue;
445
446 assert(((!AS.empty() && "Must alias set should have at least one pointer element in it!"
) ? static_cast<void> (0) : __assert_fail ("!AS.empty() && \"Must alias set should have at least one pointer element in it!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 448, __PRETTY_FUNCTION__))
447 !AS.empty() &&((!AS.empty() && "Must alias set should have at least one pointer element in it!"
) ? static_cast<void> (0) : __assert_fail ("!AS.empty() && \"Must alias set should have at least one pointer element in it!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 448, __PRETTY_FUNCTION__))
448 "Must alias set should have at least one pointer element in it!")((!AS.empty() && "Must alias set should have at least one pointer element in it!"
) ? static_cast<void> (0) : __assert_fail ("!AS.empty() && \"Must alias set should have at least one pointer element in it!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 448, __PRETTY_FUNCTION__))
;
449
450 SmallSetVector<Value *, 8> PointerMustAliases;
451 for (const auto &ASI : AS)
452 PointerMustAliases.insert(ASI.getValue());
453
454 Promoted |= promoteLoopAccessesToScalars(
455 PointerMustAliases, ExitBlocks, InsertPts, MSSAInsertPts, PIC, LI,
456 DT, TLI, L, CurAST.get(), MSSAU.get(), &SafetyInfo, ORE);
457 }
458
459 // Once we have promoted values across the loop body we have to
460 // recursively reform LCSSA as any nested loop may now have values defined
461 // within the loop used in the outer loop.
462 // FIXME: This is really heavy handed. It would be a bit better to use an
463 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
464 // it as it went.
465 if (Promoted)
466 formLCSSARecursively(*L, *DT, LI, SE);
467
468 Changed |= Promoted;
469 }
470 }
471
472 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
473 // specifically moving instructions across the loop boundary and so it is
474 // especially in need of sanity checking here.
475 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!")((L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!"
) ? static_cast<void> (0) : __assert_fail ("L->isLCSSAForm(*DT) && \"Loop not left in LCSSA form after LICM!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 475, __PRETTY_FUNCTION__))
;
476 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&(((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm
(*DT)) && "Parent loop not left in LCSSA form after LICM!"
) ? static_cast<void> (0) : __assert_fail ("(!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) && \"Parent loop not left in LCSSA form after LICM!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 477, __PRETTY_FUNCTION__))
477 "Parent loop not left in LCSSA form after LICM!")(((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm
(*DT)) && "Parent loop not left in LCSSA form after LICM!"
) ? static_cast<void> (0) : __assert_fail ("(!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) && \"Parent loop not left in LCSSA form after LICM!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 477, __PRETTY_FUNCTION__))
;
478
479 // If this loop is nested inside of another one, save the alias information
480 // for when we process the outer loop.
481 if (!MSSAU.get() && CurAST.get() && L->getParentLoop() && !DeleteAST)
482 LoopToAliasSetMap[L] = std::move(CurAST);
483
484 if (MSSAU.get() && VerifyMemorySSA)
485 MSSAU->getMemorySSA()->verifyMemorySSA();
486
487 if (Changed && SE)
488 SE->forgetLoopDispositions(L);
489 return Changed;
490}
491
492/// Walk the specified region of the CFG (defined by all blocks dominated by
493/// the specified block, and that are in the current loop) in reverse depth
494/// first order w.r.t the DominatorTree. This allows us to visit uses before
495/// definitions, allowing us to sink a loop body in one pass without iteration.
496///
497bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
498 DominatorTree *DT, TargetLibraryInfo *TLI,
499 TargetTransformInfo *TTI, Loop *CurLoop,
500 AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU,
501 ICFLoopSafetyInfo *SafetyInfo,
502 SinkAndHoistLICMFlags &Flags,
503 OptimizationRemarkEmitter *ORE) {
504
505 // Verify inputs.
506 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&((N != nullptr && AA != nullptr && LI != nullptr
&& DT != nullptr && CurLoop != nullptr &&
SafetyInfo != nullptr && "Unexpected input to sinkRegion."
) ? static_cast<void> (0) : __assert_fail ("N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && CurLoop != nullptr && SafetyInfo != nullptr && \"Unexpected input to sinkRegion.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 508, __PRETTY_FUNCTION__))
507 CurLoop != nullptr && SafetyInfo != nullptr &&((N != nullptr && AA != nullptr && LI != nullptr
&& DT != nullptr && CurLoop != nullptr &&
SafetyInfo != nullptr && "Unexpected input to sinkRegion."
) ? static_cast<void> (0) : __assert_fail ("N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && CurLoop != nullptr && SafetyInfo != nullptr && \"Unexpected input to sinkRegion.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 508, __PRETTY_FUNCTION__))
508 "Unexpected input to sinkRegion.")((N != nullptr && AA != nullptr && LI != nullptr
&& DT != nullptr && CurLoop != nullptr &&
SafetyInfo != nullptr && "Unexpected input to sinkRegion."
) ? static_cast<void> (0) : __assert_fail ("N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && CurLoop != nullptr && SafetyInfo != nullptr && \"Unexpected input to sinkRegion.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 508, __PRETTY_FUNCTION__))
;
509 assert(((CurAST != nullptr) ^ (MSSAU != nullptr)) &&((((CurAST != nullptr) ^ (MSSAU != nullptr)) && "Either AliasSetTracker or MemorySSA should be initialized."
) ? static_cast<void> (0) : __assert_fail ("((CurAST != nullptr) ^ (MSSAU != nullptr)) && \"Either AliasSetTracker or MemorySSA should be initialized.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 510, __PRETTY_FUNCTION__))
510 "Either AliasSetTracker or MemorySSA should be initialized.")((((CurAST != nullptr) ^ (MSSAU != nullptr)) && "Either AliasSetTracker or MemorySSA should be initialized."
) ? static_cast<void> (0) : __assert_fail ("((CurAST != nullptr) ^ (MSSAU != nullptr)) && \"Either AliasSetTracker or MemorySSA should be initialized.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 510, __PRETTY_FUNCTION__))
;
511
512 // We want to visit children before parents. We will enque all the parents
513 // before their children in the worklist and process the worklist in reverse
514 // order.
515 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
516
517 bool Changed = false;
518 for (DomTreeNode *DTN : reverse(Worklist)) {
519 BasicBlock *BB = DTN->getBlock();
520 // Only need to process the contents of this block if it is not part of a
521 // subloop (which would already have been processed).
522 if (inSubLoop(BB, CurLoop, LI))
523 continue;
524
525 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
526 Instruction &I = *--II;
527
528 // If the instruction is dead, we would try to sink it because it isn't
529 // used in the loop, instead, just delete it.
530 if (isInstructionTriviallyDead(&I, TLI)) {
531 LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM deleting dead inst: " <<
I << '\n'; } } while (false)
;
532 salvageDebugInfo(I);
533 ++II;
534 eraseInstruction(I, *SafetyInfo, CurAST, MSSAU);
535 Changed = true;
536 continue;
537 }
538
539 // Check to see if we can sink this instruction to the exit blocks
540 // of the loop. We can do this if the all users of the instruction are
541 // outside of the loop. In this case, it doesn't even matter if the
542 // operands of the instruction are loop invariant.
543 //
544 bool FreeInLoop = false;
545 if (isNotUsedOrFreeInLoop(I, CurLoop, SafetyInfo, TTI, FreeInLoop) &&
546 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, MSSAU, true, &Flags,
547 ORE) &&
548 !I.mayHaveSideEffects()) {
549 if (sink(I, LI, DT, CurLoop, SafetyInfo, MSSAU, ORE)) {
550 if (!FreeInLoop) {
551 ++II;
552 eraseInstruction(I, *SafetyInfo, CurAST, MSSAU);
553 }
554 Changed = true;
555 }
556 }
557 }
558 }
559 if (MSSAU && VerifyMemorySSA)
560 MSSAU->getMemorySSA()->verifyMemorySSA();
561 return Changed;
562}
563
564namespace {
565// This is a helper class for hoistRegion to make it able to hoist control flow
566// in order to be able to hoist phis. The way this works is that we initially
567// start hoisting to the loop preheader, and when we see a loop invariant branch
568// we make note of this. When we then come to hoist an instruction that's
569// conditional on such a branch we duplicate the branch and the relevant control
570// flow, then hoist the instruction into the block corresponding to its original
571// block in the duplicated control flow.
572class ControlFlowHoister {
573private:
574 // Information about the loop we are hoisting from
575 LoopInfo *LI;
576 DominatorTree *DT;
577 Loop *CurLoop;
578 MemorySSAUpdater *MSSAU;
579
580 // A map of blocks in the loop to the block their instructions will be hoisted
581 // to.
582 DenseMap<BasicBlock *, BasicBlock *> HoistDestinationMap;
583
584 // The branches that we can hoist, mapped to the block that marks a
585 // convergence point of their control flow.
586 DenseMap<BranchInst *, BasicBlock *> HoistableBranches;
587
588public:
589 ControlFlowHoister(LoopInfo *LI, DominatorTree *DT, Loop *CurLoop,
590 MemorySSAUpdater *MSSAU)
591 : LI(LI), DT(DT), CurLoop(CurLoop), MSSAU(MSSAU) {}
592
593 void registerPossiblyHoistableBranch(BranchInst *BI) {
594 // We can only hoist conditional branches with loop invariant operands.
595 if (!ControlFlowHoisting || !BI->isConditional() ||
596 !CurLoop->hasLoopInvariantOperands(BI))
597 return;
598
599 // The branch destinations need to be in the loop, and we don't gain
600 // anything by duplicating conditional branches with duplicate successors,
601 // as it's essentially the same as an unconditional branch.
602 BasicBlock *TrueDest = BI->getSuccessor(0);
603 BasicBlock *FalseDest = BI->getSuccessor(1);
604 if (!CurLoop->contains(TrueDest) || !CurLoop->contains(FalseDest) ||
605 TrueDest == FalseDest)
606 return;
607
608 // We can hoist BI if one branch destination is the successor of the other,
609 // or both have common successor which we check by seeing if the
610 // intersection of their successors is non-empty.
611 // TODO: This could be expanded to allowing branches where both ends
612 // eventually converge to a single block.
613 SmallPtrSet<BasicBlock *, 4> TrueDestSucc, FalseDestSucc;
614 TrueDestSucc.insert(succ_begin(TrueDest), succ_end(TrueDest));
615 FalseDestSucc.insert(succ_begin(FalseDest), succ_end(FalseDest));
616 BasicBlock *CommonSucc = nullptr;
617 if (TrueDestSucc.count(FalseDest)) {
618 CommonSucc = FalseDest;
619 } else if (FalseDestSucc.count(TrueDest)) {
620 CommonSucc = TrueDest;
621 } else {
622 set_intersect(TrueDestSucc, FalseDestSucc);
623 // If there's one common successor use that.
624 if (TrueDestSucc.size() == 1)
625 CommonSucc = *TrueDestSucc.begin();
626 // If there's more than one pick whichever appears first in the block list
627 // (we can't use the value returned by TrueDestSucc.begin() as it's
628 // unpredicatable which element gets returned).
629 else if (!TrueDestSucc.empty()) {
630 Function *F = TrueDest->getParent();
631 auto IsSucc = [&](BasicBlock &BB) { return TrueDestSucc.count(&BB); };
632 auto It = std::find_if(F->begin(), F->end(), IsSucc);
633 assert(It != F->end() && "Could not find successor in function")((It != F->end() && "Could not find successor in function"
) ? static_cast<void> (0) : __assert_fail ("It != F->end() && \"Could not find successor in function\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 633, __PRETTY_FUNCTION__))
;
634 CommonSucc = &*It;
635 }
636 }
637 // The common successor has to be dominated by the branch, as otherwise
638 // there will be some other path to the successor that will not be
639 // controlled by this branch so any phi we hoist would be controlled by the
640 // wrong condition. This also takes care of avoiding hoisting of loop back
641 // edges.
642 // TODO: In some cases this could be relaxed if the successor is dominated
643 // by another block that's been hoisted and we can guarantee that the
644 // control flow has been replicated exactly.
645 if (CommonSucc && DT->dominates(BI, CommonSucc))
646 HoistableBranches[BI] = CommonSucc;
647 }
648
649 bool canHoistPHI(PHINode *PN) {
650 // The phi must have loop invariant operands.
651 if (!ControlFlowHoisting || !CurLoop->hasLoopInvariantOperands(PN))
652 return false;
653 // We can hoist phis if the block they are in is the target of hoistable
654 // branches which cover all of the predecessors of the block.
655 SmallPtrSet<BasicBlock *, 8> PredecessorBlocks;
656 BasicBlock *BB = PN->getParent();
657 for (BasicBlock *PredBB : predecessors(BB))
658 PredecessorBlocks.insert(PredBB);
659 // If we have less predecessor blocks than predecessors then the phi will
660 // have more than one incoming value for the same block which we can't
661 // handle.
662 // TODO: This could be handled be erasing some of the duplicate incoming
663 // values.
664 if (PredecessorBlocks.size() != pred_size(BB))
665 return false;
666 for (auto &Pair : HoistableBranches) {
667 if (Pair.second == BB) {
668 // Which blocks are predecessors via this branch depends on if the
669 // branch is triangle-like or diamond-like.
670 if (Pair.first->getSuccessor(0) == BB) {
671 PredecessorBlocks.erase(Pair.first->getParent());
672 PredecessorBlocks.erase(Pair.first->getSuccessor(1));
673 } else if (Pair.first->getSuccessor(1) == BB) {
674 PredecessorBlocks.erase(Pair.first->getParent());
675 PredecessorBlocks.erase(Pair.first->getSuccessor(0));
676 } else {
677 PredecessorBlocks.erase(Pair.first->getSuccessor(0));
678 PredecessorBlocks.erase(Pair.first->getSuccessor(1));
679 }
680 }
681 }
682 // PredecessorBlocks will now be empty if for every predecessor of BB we
683 // found a hoistable branch source.
684 return PredecessorBlocks.empty();
685 }
686
687 BasicBlock *getOrCreateHoistedBlock(BasicBlock *BB) {
688 if (!ControlFlowHoisting)
689 return CurLoop->getLoopPreheader();
690 // If BB has already been hoisted, return that
691 if (HoistDestinationMap.count(BB))
692 return HoistDestinationMap[BB];
693
694 // Check if this block is conditional based on a pending branch
695 auto HasBBAsSuccessor =
696 [&](DenseMap<BranchInst *, BasicBlock *>::value_type &Pair) {
697 return BB != Pair.second && (Pair.first->getSuccessor(0) == BB ||
698 Pair.first->getSuccessor(1) == BB);
699 };
700 auto It = std::find_if(HoistableBranches.begin(), HoistableBranches.end(),
701 HasBBAsSuccessor);
702
703 // If not involved in a pending branch, hoist to preheader
704 BasicBlock *InitialPreheader = CurLoop->getLoopPreheader();
705 if (It == HoistableBranches.end()) {
706 LLVM_DEBUG(dbgs() << "LICM using " << InitialPreheader->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM using " << InitialPreheader
->getName() << " as hoist destination for " <<
BB->getName() << "\n"; } } while (false)
707 << " as hoist destination for " << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM using " << InitialPreheader
->getName() << " as hoist destination for " <<
BB->getName() << "\n"; } } while (false)
708 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM using " << InitialPreheader
->getName() << " as hoist destination for " <<
BB->getName() << "\n"; } } while (false)
;
709 HoistDestinationMap[BB] = InitialPreheader;
710 return InitialPreheader;
711 }
712 BranchInst *BI = It->first;
713 assert(std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor) ==((std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor
) == HoistableBranches.end() && "BB is expected to be the target of at most one branch"
) ? static_cast<void> (0) : __assert_fail ("std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor) == HoistableBranches.end() && \"BB is expected to be the target of at most one branch\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 715, __PRETTY_FUNCTION__))
714 HoistableBranches.end() &&((std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor
) == HoistableBranches.end() && "BB is expected to be the target of at most one branch"
) ? static_cast<void> (0) : __assert_fail ("std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor) == HoistableBranches.end() && \"BB is expected to be the target of at most one branch\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 715, __PRETTY_FUNCTION__))
715 "BB is expected to be the target of at most one branch")((std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor
) == HoistableBranches.end() && "BB is expected to be the target of at most one branch"
) ? static_cast<void> (0) : __assert_fail ("std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor) == HoistableBranches.end() && \"BB is expected to be the target of at most one branch\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 715, __PRETTY_FUNCTION__))
;
716
717 LLVMContext &C = BB->getContext();
718 BasicBlock *TrueDest = BI->getSuccessor(0);
719 BasicBlock *FalseDest = BI->getSuccessor(1);
720 BasicBlock *CommonSucc = HoistableBranches[BI];
721 BasicBlock *HoistTarget = getOrCreateHoistedBlock(BI->getParent());
722
723 // Create hoisted versions of blocks that currently don't have them
724 auto CreateHoistedBlock = [&](BasicBlock *Orig) {
725 if (HoistDestinationMap.count(Orig))
726 return HoistDestinationMap[Orig];
727 BasicBlock *New =
728 BasicBlock::Create(C, Orig->getName() + ".licm", Orig->getParent());
729 HoistDestinationMap[Orig] = New;
730 DT->addNewBlock(New, HoistTarget);
731 if (CurLoop->getParentLoop())
732 CurLoop->getParentLoop()->addBasicBlockToLoop(New, *LI);
733 ++NumCreatedBlocks;
734 LLVM_DEBUG(dbgs() << "LICM created " << New->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM created " << New->
getName() << " as hoist destination for " << Orig
->getName() << "\n"; } } while (false)
735 << " as hoist destination for " << Orig->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM created " << New->
getName() << " as hoist destination for " << Orig
->getName() << "\n"; } } while (false)
736 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM created " << New->
getName() << " as hoist destination for " << Orig
->getName() << "\n"; } } while (false)
;
737 return New;
738 };
739 BasicBlock *HoistTrueDest = CreateHoistedBlock(TrueDest);
740 BasicBlock *HoistFalseDest = CreateHoistedBlock(FalseDest);
741 BasicBlock *HoistCommonSucc = CreateHoistedBlock(CommonSucc);
742
743 // Link up these blocks with branches.
744 if (!HoistCommonSucc->getTerminator()) {
745 // The new common successor we've generated will branch to whatever that
746 // hoist target branched to.
747 BasicBlock *TargetSucc = HoistTarget->getSingleSuccessor();
748 assert(TargetSucc && "Expected hoist target to have a single successor")((TargetSucc && "Expected hoist target to have a single successor"
) ? static_cast<void> (0) : __assert_fail ("TargetSucc && \"Expected hoist target to have a single successor\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 748, __PRETTY_FUNCTION__))
;
749 HoistCommonSucc->moveBefore(TargetSucc);
750 BranchInst::Create(TargetSucc, HoistCommonSucc);
751 }
752 if (!HoistTrueDest->getTerminator()) {
753 HoistTrueDest->moveBefore(HoistCommonSucc);
754 BranchInst::Create(HoistCommonSucc, HoistTrueDest);
755 }
756 if (!HoistFalseDest->getTerminator()) {
757 HoistFalseDest->moveBefore(HoistCommonSucc);
758 BranchInst::Create(HoistCommonSucc, HoistFalseDest);
759 }
760
761 // If BI is being cloned to what was originally the preheader then
762 // HoistCommonSucc will now be the new preheader.
763 if (HoistTarget == InitialPreheader) {
764 // Phis in the loop header now need to use the new preheader.
765 InitialPreheader->replaceSuccessorsPhiUsesWith(HoistCommonSucc);
766 if (MSSAU)
767 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(
768 HoistTarget->getSingleSuccessor(), HoistCommonSucc, {HoistTarget});
769 // The new preheader dominates the loop header.
770 DomTreeNode *PreheaderNode = DT->getNode(HoistCommonSucc);
771 DomTreeNode *HeaderNode = DT->getNode(CurLoop->getHeader());
772 DT->changeImmediateDominator(HeaderNode, PreheaderNode);
773 // The preheader hoist destination is now the new preheader, with the
774 // exception of the hoist destination of this branch.
775 for (auto &Pair : HoistDestinationMap)
776 if (Pair.second == InitialPreheader && Pair.first != BI->getParent())
777 Pair.second = HoistCommonSucc;
778 }
779
780 // Now finally clone BI.
781 ReplaceInstWithInst(
782 HoistTarget->getTerminator(),
783 BranchInst::Create(HoistTrueDest, HoistFalseDest, BI->getCondition()));
784 ++NumClonedBranches;
785
786 assert(CurLoop->getLoopPreheader() &&((CurLoop->getLoopPreheader() && "Hoisting blocks should not have destroyed preheader"
) ? static_cast<void> (0) : __assert_fail ("CurLoop->getLoopPreheader() && \"Hoisting blocks should not have destroyed preheader\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 787, __PRETTY_FUNCTION__))
787 "Hoisting blocks should not have destroyed preheader")((CurLoop->getLoopPreheader() && "Hoisting blocks should not have destroyed preheader"
) ? static_cast<void> (0) : __assert_fail ("CurLoop->getLoopPreheader() && \"Hoisting blocks should not have destroyed preheader\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 787, __PRETTY_FUNCTION__))
;
788 return HoistDestinationMap[BB];
789 }
790};
791} // namespace
792
793
794/// Return true if we know how to rewrite all uses of the given alloca after
795/// hoisting it out of the loop. The main concerns are a) potential captures
796/// and b) invariant.start markers which don't capture, but are no longer
797/// valid w/o a corresponding invariant.end.
798static bool canRewriteUsesOfAlloca(AllocaInst &AI) {
799 // TODO: This looks a lot like capture tracking, but we need to remove any
800 // invariant starts if we extend the lifetime of the alloca by hoisting it.
801 // We should probably refactor capture tracking into a form which allows us
802 // to reuse the relevant bits and remove the duplicated logic here.
803
804 SmallVector<Use *, 16> Worklist;
805 for (Use &U : AI.uses())
806 Worklist.push_back(&U);
807
808 unsigned NumUsesExplored = 0;
809 while (!Worklist.empty()) {
810 Use *U = Worklist.pop_back_val();
811 Instruction *I = cast<Instruction>(U->getUser());
812 NumUsesExplored++;
813 if (NumUsesExplored > DefaultMaxUsesToExplore)
814 return false;
815 // Non capturing, terminating uses
816 if (isa<LoadInst>(I) ||
817 (isa<StoreInst>(I) && U->getOperandNo() == 1))
818 continue;
819 // Non capturing, non-terminating
820 if (!isa<BitCastInst>(I) && !isa<GetElementPtrInst>(I))
821 return false;
822 for (Use &U : I->uses())
823 Worklist.push_back(&U);
824 }
825 return true;
826}
827
828/// Walk the specified region of the CFG (defined by all blocks dominated by
829/// the specified block, and that are in the current loop) in depth first
830/// order w.r.t the DominatorTree. This allows us to visit definitions before
831/// uses, allowing us to hoist a loop body in one pass without iteration.
832///
833bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
834 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
835 AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU,
836 ScalarEvolution *SE, ICFLoopSafetyInfo *SafetyInfo,
837 SinkAndHoistLICMFlags &Flags,
838 OptimizationRemarkEmitter *ORE) {
839 // Verify inputs.
840 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&((N != nullptr && AA != nullptr && LI != nullptr
&& DT != nullptr && CurLoop != nullptr &&
SafetyInfo != nullptr && "Unexpected input to hoistRegion."
) ? static_cast<void> (0) : __assert_fail ("N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && CurLoop != nullptr && SafetyInfo != nullptr && \"Unexpected input to hoistRegion.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 842, __PRETTY_FUNCTION__))
841 CurLoop != nullptr && SafetyInfo != nullptr &&((N != nullptr && AA != nullptr && LI != nullptr
&& DT != nullptr && CurLoop != nullptr &&
SafetyInfo != nullptr && "Unexpected input to hoistRegion."
) ? static_cast<void> (0) : __assert_fail ("N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && CurLoop != nullptr && SafetyInfo != nullptr && \"Unexpected input to hoistRegion.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 842, __PRETTY_FUNCTION__))
842 "Unexpected input to hoistRegion.")((N != nullptr && AA != nullptr && LI != nullptr
&& DT != nullptr && CurLoop != nullptr &&
SafetyInfo != nullptr && "Unexpected input to hoistRegion."
) ? static_cast<void> (0) : __assert_fail ("N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && CurLoop != nullptr && SafetyInfo != nullptr && \"Unexpected input to hoistRegion.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 842, __PRETTY_FUNCTION__))
;
843 assert(((CurAST != nullptr) ^ (MSSAU != nullptr)) &&((((CurAST != nullptr) ^ (MSSAU != nullptr)) && "Either AliasSetTracker or MemorySSA should be initialized."
) ? static_cast<void> (0) : __assert_fail ("((CurAST != nullptr) ^ (MSSAU != nullptr)) && \"Either AliasSetTracker or MemorySSA should be initialized.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 844, __PRETTY_FUNCTION__))
844 "Either AliasSetTracker or MemorySSA should be initialized.")((((CurAST != nullptr) ^ (MSSAU != nullptr)) && "Either AliasSetTracker or MemorySSA should be initialized."
) ? static_cast<void> (0) : __assert_fail ("((CurAST != nullptr) ^ (MSSAU != nullptr)) && \"Either AliasSetTracker or MemorySSA should be initialized.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 844, __PRETTY_FUNCTION__))
;
845
846 ControlFlowHoister CFH(LI, DT, CurLoop, MSSAU);
847
848 // Keep track of instructions that have been hoisted, as they may need to be
849 // re-hoisted if they end up not dominating all of their uses.
850 SmallVector<Instruction *, 16> HoistedInstructions;
851
852 // For PHI hoisting to work we need to hoist blocks before their successors.
853 // We can do this by iterating through the blocks in the loop in reverse
854 // post-order.
855 LoopBlocksRPO Worklist(CurLoop);
856 Worklist.perform(LI);
857 bool Changed = false;
858 for (BasicBlock *BB : Worklist) {
859 // Only need to process the contents of this block if it is not part of a
860 // subloop (which would already have been processed).
861 if (inSubLoop(BB, CurLoop, LI))
862 continue;
863
864 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
865 Instruction &I = *II++;
866 // Try constant folding this instruction. If all the operands are
867 // constants, it is technically hoistable, but it would be better to
868 // just fold it.
869 if (Constant *C = ConstantFoldInstruction(
870 &I, I.getModule()->getDataLayout(), TLI)) {
871 LLVM_DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *Cdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM folding inst: " << I <<
" --> " << *C << '\n'; } } while (false)
872 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM folding inst: " << I <<
" --> " << *C << '\n'; } } while (false)
;
873 if (CurAST)
874 CurAST->copyValue(&I, C);
875 // FIXME MSSA: Such replacements may make accesses unoptimized (D51960).
876 I.replaceAllUsesWith(C);
877 if (isInstructionTriviallyDead(&I, TLI))
878 eraseInstruction(I, *SafetyInfo, CurAST, MSSAU);
879 Changed = true;
880 continue;
881 }
882
883 // Try hoisting the instruction out to the preheader. We can only do
884 // this if all of the operands of the instruction are loop invariant and
885 // if it is safe to hoist the instruction.
886 // TODO: It may be safe to hoist if we are hoisting to a conditional block
887 // and we have accurately duplicated the control flow from the loop header
888 // to that block.
889 if (CurLoop->hasLoopInvariantOperands(&I) &&
890 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, MSSAU, true, &Flags,
891 ORE) &&
892 isSafeToExecuteUnconditionally(
893 I, DT, CurLoop, SafetyInfo, ORE,
894 CurLoop->getLoopPreheader()->getTerminator())) {
895 hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
896 MSSAU, SE, ORE);
897 HoistedInstructions.push_back(&I);
898 Changed = true;
899 continue;
900 }
901
902 // Attempt to remove floating point division out of the loop by
903 // converting it to a reciprocal multiplication.
904 if (I.getOpcode() == Instruction::FDiv &&
905 CurLoop->isLoopInvariant(I.getOperand(1)) &&
906 I.hasAllowReciprocal()) {
907 auto Divisor = I.getOperand(1);
908 auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
909 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
910 ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
911 SafetyInfo->insertInstructionTo(ReciprocalDivisor, I.getParent());
912 ReciprocalDivisor->insertBefore(&I);
913
914 auto Product =
915 BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
916 Product->setFastMathFlags(I.getFastMathFlags());
917 SafetyInfo->insertInstructionTo(Product, I.getParent());
918 Product->insertAfter(&I);
919 I.replaceAllUsesWith(Product);
920 eraseInstruction(I, *SafetyInfo, CurAST, MSSAU);
921
922 hoist(*ReciprocalDivisor, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB),
923 SafetyInfo, MSSAU, SE, ORE);
924 HoistedInstructions.push_back(ReciprocalDivisor);
925 Changed = true;
926 continue;
927 }
928
929 auto IsInvariantStart = [&](Instruction &I) {
930 using namespace PatternMatch;
931 return I.use_empty() &&
932 match(&I, m_Intrinsic<Intrinsic::invariant_start>());
933 };
934 auto MustExecuteWithoutWritesBefore = [&](Instruction &I) {
935 return SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop) &&
936 SafetyInfo->doesNotWriteMemoryBefore(I, CurLoop);
937 };
938 if ((IsInvariantStart(I) || isGuard(&I)) &&
939 CurLoop->hasLoopInvariantOperands(&I) &&
940 MustExecuteWithoutWritesBefore(I)) {
941 hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
942 MSSAU, SE, ORE);
943 HoistedInstructions.push_back(&I);
944 Changed = true;
945 continue;
946 }
947
948 if (isa<AllocaInst>(&I) &&
949 SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop) &&
950 canRewriteUsesOfAlloca(cast<AllocaInst>(I))) {
951 hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
952 MSSAU, SE, ORE);
953 HoistedInstructions.push_back(&I);
954 Changed = true;
955 continue;
956 }
957
958 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
959 if (CFH.canHoistPHI(PN)) {
960 // Redirect incoming blocks first to ensure that we create hoisted
961 // versions of those blocks before we hoist the phi.
962 for (unsigned int i = 0; i < PN->getNumIncomingValues(); ++i)
963 PN->setIncomingBlock(
964 i, CFH.getOrCreateHoistedBlock(PN->getIncomingBlock(i)));
965 hoist(*PN, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
966 MSSAU, SE, ORE);
967 assert(DT->dominates(PN, BB) && "Conditional PHIs not expected")((DT->dominates(PN, BB) && "Conditional PHIs not expected"
) ? static_cast<void> (0) : __assert_fail ("DT->dominates(PN, BB) && \"Conditional PHIs not expected\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 967, __PRETTY_FUNCTION__))
;
968 Changed = true;
969 continue;
970 }
971 }
972
973 // Remember possibly hoistable branches so we can actually hoist them
974 // later if needed.
975 if (BranchInst *BI = dyn_cast<BranchInst>(&I))
976 CFH.registerPossiblyHoistableBranch(BI);
977 }
978 }
979
980 // If we hoisted instructions to a conditional block they may not dominate
981 // their uses that weren't hoisted (such as phis where some operands are not
982 // loop invariant). If so make them unconditional by moving them to their
983 // immediate dominator. We iterate through the instructions in reverse order
984 // which ensures that when we rehoist an instruction we rehoist its operands,
985 // and also keep track of where in the block we are rehoisting to to make sure
986 // that we rehoist instructions before the instructions that use them.
987 Instruction *HoistPoint = nullptr;
988 if (ControlFlowHoisting) {
989 for (Instruction *I : reverse(HoistedInstructions)) {
990 if (!llvm::all_of(I->uses(),
991 [&](Use &U) { return DT->dominates(I, U); })) {
992 BasicBlock *Dominator =
993 DT->getNode(I->getParent())->getIDom()->getBlock();
994 if (!HoistPoint || !DT->dominates(HoistPoint->getParent(), Dominator)) {
995 if (HoistPoint)
996 assert(DT->dominates(Dominator, HoistPoint->getParent()) &&((DT->dominates(Dominator, HoistPoint->getParent()) &&
"New hoist point expected to dominate old hoist point") ? static_cast
<void> (0) : __assert_fail ("DT->dominates(Dominator, HoistPoint->getParent()) && \"New hoist point expected to dominate old hoist point\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 997, __PRETTY_FUNCTION__))
997 "New hoist point expected to dominate old hoist point")((DT->dominates(Dominator, HoistPoint->getParent()) &&
"New hoist point expected to dominate old hoist point") ? static_cast
<void> (0) : __assert_fail ("DT->dominates(Dominator, HoistPoint->getParent()) && \"New hoist point expected to dominate old hoist point\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 997, __PRETTY_FUNCTION__))
;
998 HoistPoint = Dominator->getTerminator();
999 }
1000 LLVM_DEBUG(dbgs() << "LICM rehoisting to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM rehoisting to " << HoistPoint
->getParent()->getName() << ": " << *I <<
"\n"; } } while (false)
1001 << HoistPoint->getParent()->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM rehoisting to " << HoistPoint
->getParent()->getName() << ": " << *I <<
"\n"; } } while (false)
1002 << ": " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM rehoisting to " << HoistPoint
->getParent()->getName() << ": " << *I <<
"\n"; } } while (false)
;
1003 moveInstructionBefore(*I, *HoistPoint, *SafetyInfo, MSSAU, SE);
1004 HoistPoint = I;
1005 Changed = true;
1006 }
1007 }
1008 }
1009 if (MSSAU && VerifyMemorySSA)
1010 MSSAU->getMemorySSA()->verifyMemorySSA();
1011
1012 // Now that we've finished hoisting make sure that LI and DT are still
1013 // valid.
1014#ifdef EXPENSIVE_CHECKS
1015 if (Changed) {
1016 assert(DT->verify(DominatorTree::VerificationLevel::Fast) &&((DT->verify(DominatorTree::VerificationLevel::Fast) &&
"Dominator tree verification failed") ? static_cast<void>
(0) : __assert_fail ("DT->verify(DominatorTree::VerificationLevel::Fast) && \"Dominator tree verification failed\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1017, __PRETTY_FUNCTION__))
1017 "Dominator tree verification failed")((DT->verify(DominatorTree::VerificationLevel::Fast) &&
"Dominator tree verification failed") ? static_cast<void>
(0) : __assert_fail ("DT->verify(DominatorTree::VerificationLevel::Fast) && \"Dominator tree verification failed\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1017, __PRETTY_FUNCTION__))
;
1018 LI->verify(*DT);
1019 }
1020#endif
1021
1022 return Changed;
1023}
1024
1025// Return true if LI is invariant within scope of the loop. LI is invariant if
1026// CurLoop is dominated by an invariant.start representing the same memory
1027// location and size as the memory location LI loads from, and also the
1028// invariant.start has no uses.
1029static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT,
1030 Loop *CurLoop) {
1031 Value *Addr = LI->getOperand(0);
1032 const DataLayout &DL = LI->getModule()->getDataLayout();
1033 const uint32_t LocSizeInBits = DL.getTypeSizeInBits(LI->getType());
1034
1035 // if the type is i8 addrspace(x)*, we know this is the type of
1036 // llvm.invariant.start operand
1037 auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()),
1038 LI->getPointerAddressSpace());
1039 unsigned BitcastsVisited = 0;
1040 // Look through bitcasts until we reach the i8* type (this is invariant.start
1041 // operand type).
1042 while (Addr->getType() != PtrInt8Ty) {
1043 auto *BC = dyn_cast<BitCastInst>(Addr);
1044 // Avoid traversing high number of bitcast uses.
1045 if (++BitcastsVisited > MaxNumUsesTraversed || !BC)
1046 return false;
1047 Addr = BC->getOperand(0);
1048 }
1049
1050 unsigned UsesVisited = 0;
1051 // Traverse all uses of the load operand value, to see if invariant.start is
1052 // one of the uses, and whether it dominates the load instruction.
1053 for (auto *U : Addr->users()) {
1054 // Avoid traversing for Load operand with high number of users.
1055 if (++UsesVisited > MaxNumUsesTraversed)
1056 return false;
1057 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
1058 // If there are escaping uses of invariant.start instruction, the load maybe
1059 // non-invariant.
1060 if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
1061 !II->use_empty())
1062 continue;
1063 unsigned InvariantSizeInBits =
1064 cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8;
1065 // Confirm the invariant.start location size contains the load operand size
1066 // in bits. Also, the invariant.start should dominate the load, and we
1067 // should not hoist the load out of a loop that contains this dominating
1068 // invariant.start.
1069 if (LocSizeInBits <= InvariantSizeInBits &&
1070 DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
1071 return true;
1072 }
1073
1074 return false;
1075}
1076
1077namespace {
1078/// Return true if-and-only-if we know how to (mechanically) both hoist and
1079/// sink a given instruction out of a loop. Does not address legality
1080/// concerns such as aliasing or speculation safety.
1081bool isHoistableAndSinkableInst(Instruction &I) {
1082 // Only these instructions are hoistable/sinkable.
1083 return (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
2
Assuming 'I' is not a 'LoadInst'
3
Assuming 'I' is not a 'StoreInst'
4
Assuming 'I' is not a 'CallInst'
16
Returning the value 1, which participates in a condition later
1084 isa<FenceInst>(I) || isa<CastInst>(I) ||
5
Assuming 'I' is not a 'FenceInst'
6
Assuming 'I' is not a 'CastInst'
1085 isa<UnaryOperator>(I) || isa<BinaryOperator>(I) ||
7
Assuming 'I' is not a 'UnaryOperator'
8
Assuming 'I' is not a 'BinaryOperator'
1086 isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
9
Assuming 'I' is not a 'SelectInst'
10
Assuming 'I' is not a 'GetElementPtrInst'
11
Assuming 'I' is not a 'CmpInst'
1087 isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
12
Assuming 'I' is not a 'InsertElementInst'
13
Assuming 'I' is not a 'ExtractElementInst'
1088 isa<ShuffleVectorInst>(I) || isa<ExtractValueInst>(I) ||
14
Assuming 'I' is not a 'ShuffleVectorInst'
15
Assuming 'I' is a 'ExtractValueInst'
1089 isa<InsertValueInst>(I));
1090}
1091/// Return true if all of the alias sets within this AST are known not to
1092/// contain a Mod, or if MSSA knows thare are no MemoryDefs in the loop.
1093bool isReadOnly(AliasSetTracker *CurAST, const MemorySSAUpdater *MSSAU,
1094 const Loop *L) {
1095 if (CurAST) {
1096 for (AliasSet &AS : *CurAST) {
1097 if (!AS.isForwardingAliasSet() && AS.isMod()) {
1098 return false;
1099 }
1100 }
1101 return true;
1102 } else { /*MSSAU*/
1103 for (auto *BB : L->getBlocks())
1104 if (MSSAU->getMemorySSA()->getBlockDefs(BB))
1105 return false;
1106 return true;
1107 }
1108}
1109
1110/// Return true if I is the only Instruction with a MemoryAccess in L.
1111bool isOnlyMemoryAccess(const Instruction *I, const Loop *L,
1112 const MemorySSAUpdater *MSSAU) {
1113 for (auto *BB : L->getBlocks())
1114 if (auto *Accs = MSSAU->getMemorySSA()->getBlockAccesses(BB)) {
1115 int NotAPhi = 0;
1116 for (const auto &Acc : *Accs) {
1117 if (isa<MemoryPhi>(&Acc))
1118 continue;
1119 const auto *MUD = cast<MemoryUseOrDef>(&Acc);
1120 if (MUD->getMemoryInst() != I || NotAPhi++ == 1)
1121 return false;
1122 }
1123 }
1124 return true;
1125}
1126}
1127
1128bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
1129 Loop *CurLoop, AliasSetTracker *CurAST,
1130 MemorySSAUpdater *MSSAU,
1131 bool TargetExecutesOncePerLoop,
1132 SinkAndHoistLICMFlags *Flags,
1133 OptimizationRemarkEmitter *ORE) {
1134 // If we don't understand the instruction, bail early.
1135 if (!isHoistableAndSinkableInst(I))
1
Calling 'isHoistableAndSinkableInst'
17
Returning from 'isHoistableAndSinkableInst'
18
Taking false branch
1136 return false;
1137
1138 MemorySSA *MSSA = MSSAU ? MSSAU->getMemorySSA() : nullptr;
19
Assuming 'MSSAU' is non-null
20
'?' condition is true
21
'MSSA' initialized here
1139 if (MSSA)
22
Assuming 'MSSA' is null
23
Taking false branch
1140 assert(Flags != nullptr && "Flags cannot be null.")((Flags != nullptr && "Flags cannot be null.") ? static_cast
<void> (0) : __assert_fail ("Flags != nullptr && \"Flags cannot be null.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1140, __PRETTY_FUNCTION__))
;
1141
1142 // Loads have extra constraints we have to verify before we can hoist them.
1143 if (LoadInst *LI
24.1
'LI' is null
24.1
'LI' is null
= dyn_cast<LoadInst>(&I)) {
24
Assuming the object is not a 'LoadInst'
25
Taking false branch
1144 if (!LI->isUnordered())
1145 return false; // Don't sink/hoist volatile or ordered atomic loads!
1146
1147 // Loads from constant memory are always safe to move, even if they end up
1148 // in the same alias set as something that ends up being modified.
1149 if (AA->pointsToConstantMemory(LI->getOperand(0)))
1150 return true;
1151 if (LI->hasMetadata(LLVMContext::MD_invariant_load))
1152 return true;
1153
1154 if (LI->isAtomic() && !TargetExecutesOncePerLoop)
1155 return false; // Don't risk duplicating unordered loads
1156
1157 // This checks for an invariant.start dominating the load.
1158 if (isLoadInvariantInLoop(LI, DT, CurLoop))
1159 return true;
1160
1161 bool Invalidated;
1162 if (CurAST)
1163 Invalidated = pointerInvalidatedByLoop(MemoryLocation::get(LI), CurAST,
1164 CurLoop, AA);
1165 else
1166 Invalidated = pointerInvalidatedByLoopWithMSSA(
1167 MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(LI)), CurLoop, *Flags);
1168 // Check loop-invariant address because this may also be a sinkable load
1169 // whose address is not necessarily loop-invariant.
1170 if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand()))
1171 ORE->emit([&]() {
1172 return OptimizationRemarkMissed(
1173 DEBUG_TYPE"licm", "LoadWithLoopInvariantAddressInvalidated", LI)
1174 << "failed to move load with loop-invariant address "
1175 "because the loop may invalidate its value";
1176 });
1177
1178 return !Invalidated;
1179 } else if (CallInst *CI
26.1
'CI' is null
26.1
'CI' is null
= dyn_cast<CallInst>(&I)) {
26
Assuming the object is not a 'CallInst'
27
Taking false branch
1180 // Don't sink or hoist dbg info; it's legal, but not useful.
1181 if (isa<DbgInfoIntrinsic>(I))
1182 return false;
1183
1184 // Don't sink calls which can throw.
1185 if (CI->mayThrow())
1186 return false;
1187
1188 using namespace PatternMatch;
1189 if (match(CI, m_Intrinsic<Intrinsic::assume>()))
1190 // Assumes don't actually alias anything or throw
1191 return true;
1192
1193 if (match(CI, m_Intrinsic<Intrinsic::experimental_widenable_condition>()))
1194 // Widenable conditions don't actually alias anything or throw
1195 return true;
1196
1197 // Handle simple cases by querying alias analysis.
1198 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
1199 if (Behavior == FMRB_DoesNotAccessMemory)
1200 return true;
1201 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
1202 // A readonly argmemonly function only reads from memory pointed to by
1203 // it's arguments with arbitrary offsets. If we can prove there are no
1204 // writes to this memory in the loop, we can hoist or sink.
1205 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
1206 // TODO: expand to writeable arguments
1207 for (Value *Op : CI->arg_operands())
1208 if (Op->getType()->isPointerTy()) {
1209 bool Invalidated;
1210 if (CurAST)
1211 Invalidated = pointerInvalidatedByLoop(
1212 MemoryLocation(Op, LocationSize::unknown(), AAMDNodes()),
1213 CurAST, CurLoop, AA);
1214 else
1215 Invalidated = pointerInvalidatedByLoopWithMSSA(
1216 MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(CI)), CurLoop,
1217 *Flags);
1218 if (Invalidated)
1219 return false;
1220 }
1221 return true;
1222 }
1223
1224 // If this call only reads from memory and there are no writes to memory
1225 // in the loop, we can hoist or sink the call as appropriate.
1226 if (isReadOnly(CurAST, MSSAU, CurLoop))
1227 return true;
1228 }
1229
1230 // FIXME: This should use mod/ref information to see if we can hoist or
1231 // sink the call.
1232
1233 return false;
1234 } else if (auto *FI
28.1
'FI' is null
28.1
'FI' is null
= dyn_cast<FenceInst>(&I)) {
28
Assuming the object is not a 'FenceInst'
29
Taking false branch
1235 // Fences alias (most) everything to provide ordering. For the moment,
1236 // just give up if there are any other memory operations in the loop.
1237 if (CurAST) {
1238 auto Begin = CurAST->begin();
1239 assert(Begin != CurAST->end() && "must contain FI")((Begin != CurAST->end() && "must contain FI") ? static_cast
<void> (0) : __assert_fail ("Begin != CurAST->end() && \"must contain FI\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1239, __PRETTY_FUNCTION__))
;
1240 if (std::next(Begin) != CurAST->end())
1241 // constant memory for instance, TODO: handle better
1242 return false;
1243 auto *UniqueI = Begin->getUniqueInstruction();
1244 if (!UniqueI)
1245 // other memory op, give up
1246 return false;
1247 (void)FI; // suppress unused variable warning
1248 assert(UniqueI == FI && "AS must contain FI")((UniqueI == FI && "AS must contain FI") ? static_cast
<void> (0) : __assert_fail ("UniqueI == FI && \"AS must contain FI\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1248, __PRETTY_FUNCTION__))
;
1249 return true;
1250 } else // MSSAU
1251 return isOnlyMemoryAccess(FI, CurLoop, MSSAU);
1252 } else if (auto *SI
30.1
'SI' is non-null
30.1
'SI' is non-null
= dyn_cast<StoreInst>(&I)) {
30
Assuming the object is a 'StoreInst'
31
Taking true branch
1253 if (!SI->isUnordered())
32
Calling 'StoreInst::isUnordered'
36
Returning from 'StoreInst::isUnordered'
37
Taking false branch
1254 return false; // Don't sink/hoist volatile or ordered atomic store!
1255
1256 // We can only hoist a store that we can prove writes a value which is not
1257 // read or overwritten within the loop. For those cases, we fallback to
1258 // load store promotion instead. TODO: We can extend this to cases where
1259 // there is exactly one write to the location and that write dominates an
1260 // arbitrary number of reads in the loop.
1261 if (CurAST) {
38
Assuming 'CurAST' is null
39
Taking false branch
1262 auto &AS = CurAST->getAliasSetFor(MemoryLocation::get(SI));
1263
1264 if (AS.isRef() || !AS.isMustAlias())
1265 // Quick exit test, handled by the full path below as well.
1266 return false;
1267 auto *UniqueI = AS.getUniqueInstruction();
1268 if (!UniqueI)
1269 // other memory op, give up
1270 return false;
1271 assert(UniqueI == SI && "AS must contain SI")((UniqueI == SI && "AS must contain SI") ? static_cast
<void> (0) : __assert_fail ("UniqueI == SI && \"AS must contain SI\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1271, __PRETTY_FUNCTION__))
;
1272 return true;
1273 } else { // MSSAU
1274 if (isOnlyMemoryAccess(SI, CurLoop, MSSAU))
40
Assuming the condition is false
41
Taking false branch
1275 return true;
1276 // If there are more accesses than the Promotion cap, give up, we're not
1277 // walking a list that long.
1278 if (Flags->NoOfMemAccTooLarge)
42
Assuming field 'NoOfMemAccTooLarge' is false
43
Taking false branch
1279 return false;
1280 // Check store only if there's still "quota" to check clobber.
1281 if (Flags->LicmMssaOptCounter >= Flags->LicmMssaOptCap)
44
Assuming field 'LicmMssaOptCounter' is < field 'LicmMssaOptCap'
45
Taking false branch
1282 return false;
1283 // If there are interfering Uses (i.e. their defining access is in the
1284 // loop), or ordered loads (stored as Defs!), don't move this store.
1285 // Could do better here, but this is conservatively correct.
1286 // TODO: Cache set of Uses on the first walk in runOnLoop, update when
1287 // moving accesses. Can also extend to dominating uses.
1288 auto *SIMD = MSSA->getMemoryAccess(SI);
46
Called C++ object pointer is null
1289 for (auto *BB : CurLoop->getBlocks())
1290 if (auto *Accesses = MSSA->getBlockAccesses(BB)) {
1291 for (const auto &MA : *Accesses)
1292 if (const auto *MU = dyn_cast<MemoryUse>(&MA)) {
1293 auto *MD = MU->getDefiningAccess();
1294 if (!MSSA->isLiveOnEntryDef(MD) &&
1295 CurLoop->contains(MD->getBlock()))
1296 return false;
1297 // Disable hoisting past potentially interfering loads. Optimized
1298 // Uses may point to an access outside the loop, as getClobbering
1299 // checks the previous iteration when walking the backedge.
1300 // FIXME: More precise: no Uses that alias SI.
1301 if (!Flags->IsSink && !MSSA->dominates(SIMD, MU))
1302 return false;
1303 } else if (const auto *MD = dyn_cast<MemoryDef>(&MA)) {
1304 if (auto *LI = dyn_cast<LoadInst>(MD->getMemoryInst())) {
1305 (void)LI; // Silence warning.
1306 assert(!LI->isUnordered() && "Expected unordered load")((!LI->isUnordered() && "Expected unordered load")
? static_cast<void> (0) : __assert_fail ("!LI->isUnordered() && \"Expected unordered load\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1306, __PRETTY_FUNCTION__))
;
1307 return false;
1308 }
1309 // Any call, while it may not be clobbering SI, it may be a use.
1310 if (auto *CI = dyn_cast<CallInst>(MD->getMemoryInst())) {
1311 // Check if the call may read from the memory locattion written
1312 // to by SI. Check CI's attributes and arguments; the number of
1313 // such checks performed is limited above by NoOfMemAccTooLarge.
1314 ModRefInfo MRI = AA->getModRefInfo(CI, MemoryLocation::get(SI));
1315 if (isModOrRefSet(MRI))
1316 return false;
1317 }
1318 }
1319 }
1320
1321 auto *Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(SI);
1322 Flags->LicmMssaOptCounter++;
1323 // If there are no clobbering Defs in the loop, store is safe to hoist.
1324 return MSSA->isLiveOnEntryDef(Source) ||
1325 !CurLoop->contains(Source->getBlock());
1326 }
1327 }
1328
1329 assert(!I.mayReadOrWriteMemory() && "unhandled aliasing")((!I.mayReadOrWriteMemory() && "unhandled aliasing") ?
static_cast<void> (0) : __assert_fail ("!I.mayReadOrWriteMemory() && \"unhandled aliasing\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1329, __PRETTY_FUNCTION__))
;
1330
1331 // We've established mechanical ability and aliasing, it's up to the caller
1332 // to check fault safety
1333 return true;
1334}
1335
1336/// Returns true if a PHINode is a trivially replaceable with an
1337/// Instruction.
1338/// This is true when all incoming values are that instruction.
1339/// This pattern occurs most often with LCSSA PHI nodes.
1340///
1341static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) {
1342 for (const Value *IncValue : PN.incoming_values())
1343 if (IncValue != &I)
1344 return false;
1345
1346 return true;
1347}
1348
1349/// Return true if the instruction is free in the loop.
1350static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop,
1351 const TargetTransformInfo *TTI) {
1352
1353 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1354 if (TTI->getUserCost(GEP) != TargetTransformInfo::TCC_Free)
1355 return false;
1356 // For a GEP, we cannot simply use getUserCost because currently it
1357 // optimistically assume that a GEP will fold into addressing mode
1358 // regardless of its users.
1359 const BasicBlock *BB = GEP->getParent();
1360 for (const User *U : GEP->users()) {
1361 const Instruction *UI = cast<Instruction>(U);
1362 if (CurLoop->contains(UI) &&
1363 (BB != UI->getParent() ||
1364 (!isa<StoreInst>(UI) && !isa<LoadInst>(UI))))
1365 return false;
1366 }
1367 return true;
1368 } else
1369 return TTI->getUserCost(&I) == TargetTransformInfo::TCC_Free;
1370}
1371
1372/// Return true if the only users of this instruction are outside of
1373/// the loop. If this is true, we can sink the instruction to the exit
1374/// blocks of the loop.
1375///
1376/// We also return true if the instruction could be folded away in lowering.
1377/// (e.g., a GEP can be folded into a load as an addressing mode in the loop).
1378static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
1379 const LoopSafetyInfo *SafetyInfo,
1380 TargetTransformInfo *TTI, bool &FreeInLoop) {
1381 const auto &BlockColors = SafetyInfo->getBlockColors();
1382 bool IsFree = isFreeInLoop(I, CurLoop, TTI);
1383 for (const User *U : I.users()) {
1384 const Instruction *UI = cast<Instruction>(U);
1385 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
1386 const BasicBlock *BB = PN->getParent();
1387 // We cannot sink uses in catchswitches.
1388 if (isa<CatchSwitchInst>(BB->getTerminator()))
1389 return false;
1390
1391 // We need to sink a callsite to a unique funclet. Avoid sinking if the
1392 // phi use is too muddled.
1393 if (isa<CallInst>(I))
1394 if (!BlockColors.empty() &&
1395 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
1396 return false;
1397 }
1398
1399 if (CurLoop->contains(UI)) {
1400 if (IsFree) {
1401 FreeInLoop = true;
1402 continue;
1403 }
1404 return false;
1405 }
1406 }
1407 return true;
1408}
1409
1410static Instruction *CloneInstructionInExitBlock(
1411 Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,
1412 const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU) {
1413 Instruction *New;
1414 if (auto *CI = dyn_cast<CallInst>(&I)) {
1415 const auto &BlockColors = SafetyInfo->getBlockColors();
1416
1417 // Sinking call-sites need to be handled differently from other
1418 // instructions. The cloned call-site needs a funclet bundle operand
1419 // appropriate for its location in the CFG.
1420 SmallVector<OperandBundleDef, 1> OpBundles;
1421 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
1422 BundleIdx != BundleEnd; ++BundleIdx) {
1423 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
1424 if (Bundle.getTagID() == LLVMContext::OB_funclet)
1425 continue;
1426
1427 OpBundles.emplace_back(Bundle);
1428 }
1429
1430 if (!BlockColors.empty()) {
1431 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
1432 assert(CV.size() == 1 && "non-unique color for exit block!")((CV.size() == 1 && "non-unique color for exit block!"
) ? static_cast<void> (0) : __assert_fail ("CV.size() == 1 && \"non-unique color for exit block!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1432, __PRETTY_FUNCTION__))
;
1433 BasicBlock *BBColor = CV.front();
1434 Instruction *EHPad = BBColor->getFirstNonPHI();
1435 if (EHPad->isEHPad())
1436 OpBundles.emplace_back("funclet", EHPad);
1437 }
1438
1439 New = CallInst::Create(CI, OpBundles);
1440 } else {
1441 New = I.clone();
1442 }
1443
1444 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
1445 if (!I.getName().empty())
1446 New->setName(I.getName() + ".le");
1447
1448 if (MSSAU && MSSAU->getMemorySSA()->getMemoryAccess(&I)) {
1449 // Create a new MemoryAccess and let MemorySSA set its defining access.
1450 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1451 New, nullptr, New->getParent(), MemorySSA::Beginning);
1452 if (NewMemAcc) {
1453 if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc))
1454 MSSAU->insertDef(MemDef, /*RenameUses=*/true);
1455 else {
1456 auto *MemUse = cast<MemoryUse>(NewMemAcc);
1457 MSSAU->insertUse(MemUse, /*RenameUses=*/true);
1458 }
1459 }
1460 }
1461
1462 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
1463 // particularly cheap because we can rip off the PHI node that we're
1464 // replacing for the number and blocks of the predecessors.
1465 // OPT: If this shows up in a profile, we can instead finish sinking all
1466 // invariant instructions, and then walk their operands to re-establish
1467 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
1468 // sinking bottom-up.
1469 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
1470 ++OI)
1471 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
1472 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
1473 if (!OLoop->contains(&PN)) {
1474 PHINode *OpPN =
1475 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
1476 OInst->getName() + ".lcssa", &ExitBlock.front());
1477 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1478 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
1479 *OI = OpPN;
1480 }
1481 return New;
1482}
1483
1484static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo,
1485 AliasSetTracker *AST, MemorySSAUpdater *MSSAU) {
1486 if (AST)
1487 AST->deleteValue(&I);
1488 if (MSSAU)
1489 MSSAU->removeMemoryAccess(&I);
1490 SafetyInfo.removeInstruction(&I);
1491 I.eraseFromParent();
1492}
1493
1494static void moveInstructionBefore(Instruction &I, Instruction &Dest,
1495 ICFLoopSafetyInfo &SafetyInfo,
1496 MemorySSAUpdater *MSSAU,
1497 ScalarEvolution *SE) {
1498 SafetyInfo.removeInstruction(&I);
1499 SafetyInfo.insertInstructionTo(&I, Dest.getParent());
1500 I.moveBefore(&Dest);
1501 if (MSSAU)
1502 if (MemoryUseOrDef *OldMemAcc = cast_or_null<MemoryUseOrDef>(
1503 MSSAU->getMemorySSA()->getMemoryAccess(&I)))
1504 MSSAU->moveToPlace(OldMemAcc, Dest.getParent(),
1505 MemorySSA::BeforeTerminator);
1506 if (SE)
1507 SE->forgetValue(&I);
1508}
1509
1510static Instruction *sinkThroughTriviallyReplaceablePHI(
1511 PHINode *TPN, Instruction *I, LoopInfo *LI,
1512 SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies,
1513 const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop,
1514 MemorySSAUpdater *MSSAU) {
1515 assert(isTriviallyReplaceablePHI(*TPN, *I) &&((isTriviallyReplaceablePHI(*TPN, *I) && "Expect only trivially replaceable PHI"
) ? static_cast<void> (0) : __assert_fail ("isTriviallyReplaceablePHI(*TPN, *I) && \"Expect only trivially replaceable PHI\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1516, __PRETTY_FUNCTION__))
1516 "Expect only trivially replaceable PHI")((isTriviallyReplaceablePHI(*TPN, *I) && "Expect only trivially replaceable PHI"
) ? static_cast<void> (0) : __assert_fail ("isTriviallyReplaceablePHI(*TPN, *I) && \"Expect only trivially replaceable PHI\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1516, __PRETTY_FUNCTION__))
;
1517 BasicBlock *ExitBlock = TPN->getParent();
1518 Instruction *New;
1519 auto It = SunkCopies.find(ExitBlock);
1520 if (It != SunkCopies.end())
1521 New = It->second;
1522 else
1523 New = SunkCopies[ExitBlock] = CloneInstructionInExitBlock(
1524 *I, *ExitBlock, *TPN, LI, SafetyInfo, MSSAU);
1525 return New;
1526}
1527
1528static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) {
1529 BasicBlock *BB = PN->getParent();
1530 if (!BB->canSplitPredecessors())
1531 return false;
1532 // It's not impossible to split EHPad blocks, but if BlockColors already exist
1533 // it require updating BlockColors for all offspring blocks accordingly. By
1534 // skipping such corner case, we can make updating BlockColors after splitting
1535 // predecessor fairly simple.
1536 if (!SafetyInfo->getBlockColors().empty() && BB->getFirstNonPHI()->isEHPad())
1537 return false;
1538 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1539 BasicBlock *BBPred = *PI;
1540 if (isa<IndirectBrInst>(BBPred->getTerminator()))
1541 return false;
1542 }
1543 return true;
1544}
1545
1546static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT,
1547 LoopInfo *LI, const Loop *CurLoop,
1548 LoopSafetyInfo *SafetyInfo,
1549 MemorySSAUpdater *MSSAU) {
1550#ifndef NDEBUG
1551 SmallVector<BasicBlock *, 32> ExitBlocks;
1552 CurLoop->getUniqueExitBlocks(ExitBlocks);
1553 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
1554 ExitBlocks.end());
1555#endif
1556 BasicBlock *ExitBB = PN->getParent();
1557 assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.")((ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block."
) ? static_cast<void> (0) : __assert_fail ("ExitBlockSet.count(ExitBB) && \"Expect the PHI is in an exit block.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1557, __PRETTY_FUNCTION__))
;
1558
1559 // Split predecessors of the loop exit to make instructions in the loop are
1560 // exposed to exit blocks through trivially replaceable PHIs while keeping the
1561 // loop in the canonical form where each predecessor of each exit block should
1562 // be contained within the loop. For example, this will convert the loop below
1563 // from
1564 //
1565 // LB1:
1566 // %v1 =
1567 // br %LE, %LB2
1568 // LB2:
1569 // %v2 =
1570 // br %LE, %LB1
1571 // LE:
1572 // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable
1573 //
1574 // to
1575 //
1576 // LB1:
1577 // %v1 =
1578 // br %LE.split, %LB2
1579 // LB2:
1580 // %v2 =
1581 // br %LE.split2, %LB1
1582 // LE.split:
1583 // %p1 = phi [%v1, %LB1] <-- trivially replaceable
1584 // br %LE
1585 // LE.split2:
1586 // %p2 = phi [%v2, %LB2] <-- trivially replaceable
1587 // br %LE
1588 // LE:
1589 // %p = phi [%p1, %LE.split], [%p2, %LE.split2]
1590 //
1591 const auto &BlockColors = SafetyInfo->getBlockColors();
1592 SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));
1593 while (!PredBBs.empty()) {
1594 BasicBlock *PredBB = *PredBBs.begin();
1595 assert(CurLoop->contains(PredBB) &&((CurLoop->contains(PredBB) && "Expect all predecessors are in the loop"
) ? static_cast<void> (0) : __assert_fail ("CurLoop->contains(PredBB) && \"Expect all predecessors are in the loop\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1596, __PRETTY_FUNCTION__))
1596 "Expect all predecessors are in the loop")((CurLoop->contains(PredBB) && "Expect all predecessors are in the loop"
) ? static_cast<void> (0) : __assert_fail ("CurLoop->contains(PredBB) && \"Expect all predecessors are in the loop\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1596, __PRETTY_FUNCTION__))
;
1597 if (PN->getBasicBlockIndex(PredBB) >= 0) {
1598 BasicBlock *NewPred = SplitBlockPredecessors(
1599 ExitBB, PredBB, ".split.loop.exit", DT, LI, MSSAU, true);
1600 // Since we do not allow splitting EH-block with BlockColors in
1601 // canSplitPredecessors(), we can simply assign predecessor's color to
1602 // the new block.
1603 if (!BlockColors.empty())
1604 // Grab a reference to the ColorVector to be inserted before getting the
1605 // reference to the vector we are copying because inserting the new
1606 // element in BlockColors might cause the map to be reallocated.
1607 SafetyInfo->copyColors(NewPred, PredBB);
1608 }
1609 PredBBs.remove(PredBB);
1610 }
1611}
1612
1613/// When an instruction is found to only be used outside of the loop, this
1614/// function moves it to the exit blocks and patches up SSA form as needed.
1615/// This method is guaranteed to remove the original instruction from its
1616/// position, and may either delete it or move it to outside of the loop.
1617///
1618static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
1619 const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo,
1620 MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE) {
1621 LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM sinking instruction: " <<
I << "\n"; } } while (false)
;
1622 ORE->emit([&]() {
1623 return OptimizationRemark(DEBUG_TYPE"licm", "InstSunk", &I)
1624 << "sinking " << ore::NV("Inst", &I);
1625 });
1626 bool Changed = false;
1627 if (isa<LoadInst>(I))
1628 ++NumMovedLoads;
1629 else if (isa<CallInst>(I))
1630 ++NumMovedCalls;
1631 ++NumSunk;
1632
1633 // Iterate over users to be ready for actual sinking. Replace users via
1634 // unreachable blocks with undef and make all user PHIs trivially replaceable.
1635 SmallPtrSet<Instruction *, 8> VisitedUsers;
1636 for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) {
1637 auto *User = cast<Instruction>(*UI);
1638 Use &U = UI.getUse();
1639 ++UI;
1640
1641 if (VisitedUsers.count(User) || CurLoop->contains(User))
1642 continue;
1643
1644 if (!DT->isReachableFromEntry(User->getParent())) {
1645 U = UndefValue::get(I.getType());
1646 Changed = true;
1647 continue;
1648 }
1649
1650 // The user must be a PHI node.
1651 PHINode *PN = cast<PHINode>(User);
1652
1653 // Surprisingly, instructions can be used outside of loops without any
1654 // exits. This can only happen in PHI nodes if the incoming block is
1655 // unreachable.
1656 BasicBlock *BB = PN->getIncomingBlock(U);
1657 if (!DT->isReachableFromEntry(BB)) {
1658 U = UndefValue::get(I.getType());
1659 Changed = true;
1660 continue;
1661 }
1662
1663 VisitedUsers.insert(PN);
1664 if (isTriviallyReplaceablePHI(*PN, I))
1665 continue;
1666
1667 if (!canSplitPredecessors(PN, SafetyInfo))
1668 return Changed;
1669
1670 // Split predecessors of the PHI so that we can make users trivially
1671 // replaceable.
1672 splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo, MSSAU);
1673
1674 // Should rebuild the iterators, as they may be invalidated by
1675 // splitPredecessorsOfLoopExit().
1676 UI = I.user_begin();
1677 UE = I.user_end();
1678 }
1679
1680 if (VisitedUsers.empty())
1681 return Changed;
1682
1683#ifndef NDEBUG
1684 SmallVector<BasicBlock *, 32> ExitBlocks;
1685 CurLoop->getUniqueExitBlocks(ExitBlocks);
1686 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
1687 ExitBlocks.end());
1688#endif
1689
1690 // Clones of this instruction. Don't create more than one per exit block!
1691 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
1692
1693 // If this instruction is only used outside of the loop, then all users are
1694 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
1695 // the instruction.
1696 SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end());
1697 for (auto *UI : Users) {
1698 auto *User = cast<Instruction>(UI);
1699
1700 if (CurLoop->contains(User))
1701 continue;
1702
1703 PHINode *PN = cast<PHINode>(User);
1704 assert(ExitBlockSet.count(PN->getParent()) &&((ExitBlockSet.count(PN->getParent()) && "The LCSSA PHI is not in an exit block!"
) ? static_cast<void> (0) : __assert_fail ("ExitBlockSet.count(PN->getParent()) && \"The LCSSA PHI is not in an exit block!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1705, __PRETTY_FUNCTION__))
1705 "The LCSSA PHI is not in an exit block!")((ExitBlockSet.count(PN->getParent()) && "The LCSSA PHI is not in an exit block!"
) ? static_cast<void> (0) : __assert_fail ("ExitBlockSet.count(PN->getParent()) && \"The LCSSA PHI is not in an exit block!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1705, __PRETTY_FUNCTION__))
;
1706 // The PHI must be trivially replaceable.
1707 Instruction *New = sinkThroughTriviallyReplaceablePHI(
1708 PN, &I, LI, SunkCopies, SafetyInfo, CurLoop, MSSAU);
1709 PN->replaceAllUsesWith(New);
1710 eraseInstruction(*PN, *SafetyInfo, nullptr, nullptr);
1711 Changed = true;
1712 }
1713 return Changed;
1714}
1715
1716/// When an instruction is found to only use loop invariant operands that
1717/// is safe to hoist, this instruction is called to do the dirty work.
1718///
1719static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
1720 BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,
1721 MemorySSAUpdater *MSSAU, ScalarEvolution *SE,
1722 OptimizationRemarkEmitter *ORE) {
1723 LLVM_DEBUG(dbgs() << "LICM hoisting to " << Dest->getName() << ": " << Ido { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM hoisting to " << Dest
->getName() << ": " << I << "\n"; } } while
(false)
1724 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM hoisting to " << Dest
->getName() << ": " << I << "\n"; } } while
(false)
;
1725 ORE->emit([&]() {
1726 return OptimizationRemark(DEBUG_TYPE"licm", "Hoisted", &I) << "hoisting "
1727 << ore::NV("Inst", &I);
1728 });
1729
1730 // Metadata can be dependent on conditions we are hoisting above.
1731 // Conservatively strip all metadata on the instruction unless we were
1732 // guaranteed to execute I if we entered the loop, in which case the metadata
1733 // is valid in the loop preheader.
1734 if (I.hasMetadataOtherThanDebugLoc() &&
1735 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
1736 // time in isGuaranteedToExecute if we don't actually have anything to
1737 // drop. It is a compile time optimization, not required for correctness.
1738 !SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop))
1739 I.dropUnknownNonDebugMetadata();
1740
1741 if (isa<PHINode>(I))
1742 // Move the new node to the end of the phi list in the destination block.
1743 moveInstructionBefore(I, *Dest->getFirstNonPHI(), *SafetyInfo, MSSAU, SE);
1744 else
1745 // Move the new node to the destination block, before its terminator.
1746 moveInstructionBefore(I, *Dest->getTerminator(), *SafetyInfo, MSSAU, SE);
1747
1748 // Apply line 0 debug locations when we are moving instructions to different
1749 // basic blocks because we want to avoid jumpy line tables.
1750 if (const DebugLoc &DL = I.getDebugLoc())
1751 I.setDebugLoc(DebugLoc::get(0, 0, DL.getScope(), DL.getInlinedAt()));
1752
1753 if (isa<LoadInst>(I))
1754 ++NumMovedLoads;
1755 else if (isa<CallInst>(I))
1756 ++NumMovedCalls;
1757 ++NumHoisted;
1758}
1759
1760/// Only sink or hoist an instruction if it is not a trapping instruction,
1761/// or if the instruction is known not to trap when moved to the preheader.
1762/// or if it is a trapping instruction and is guaranteed to execute.
1763static bool isSafeToExecuteUnconditionally(Instruction &Inst,
1764 const DominatorTree *DT,
1765 const Loop *CurLoop,
1766 const LoopSafetyInfo *SafetyInfo,
1767 OptimizationRemarkEmitter *ORE,
1768 const Instruction *CtxI) {
1769 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
1770 return true;
1771
1772 bool GuaranteedToExecute =
1773 SafetyInfo->isGuaranteedToExecute(Inst, DT, CurLoop);
1774
1775 if (!GuaranteedToExecute) {
1776 auto *LI = dyn_cast<LoadInst>(&Inst);
1777 if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
1778 ORE->emit([&]() {
1779 return OptimizationRemarkMissed(
1780 DEBUG_TYPE"licm", "LoadWithLoopInvariantAddressCondExecuted", LI)
1781 << "failed to hoist load with loop-invariant address "
1782 "because load is conditionally executed";
1783 });
1784 }
1785
1786 return GuaranteedToExecute;
1787}
1788
1789namespace {
1790class LoopPromoter : public LoadAndStorePromoter {
1791 Value *SomePtr; // Designated pointer to store to.
1792 const SmallSetVector<Value *, 8> &PointerMustAliases;
1793 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
1794 SmallVectorImpl<Instruction *> &LoopInsertPts;
1795 SmallVectorImpl<MemoryAccess *> &MSSAInsertPts;
1796 PredIteratorCache &PredCache;
1797 AliasSetTracker &AST;
1798 MemorySSAUpdater *MSSAU;
1799 LoopInfo &LI;
1800 DebugLoc DL;
1801 int Alignment;
1802 bool UnorderedAtomic;
1803 AAMDNodes AATags;
1804 ICFLoopSafetyInfo &SafetyInfo;
1805
1806 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
1807 if (Instruction *I = dyn_cast<Instruction>(V))
1808 if (Loop *L = LI.getLoopFor(I->getParent()))
1809 if (!L->contains(BB)) {
1810 // We need to create an LCSSA PHI node for the incoming value and
1811 // store that.
1812 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
1813 I->getName() + ".lcssa", &BB->front());
1814 for (BasicBlock *Pred : PredCache.get(BB))
1815 PN->addIncoming(I, Pred);
1816 return PN;
1817 }
1818 return V;
1819 }
1820
1821public:
1822 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
1823 const SmallSetVector<Value *, 8> &PMA,
1824 SmallVectorImpl<BasicBlock *> &LEB,
1825 SmallVectorImpl<Instruction *> &LIP,
1826 SmallVectorImpl<MemoryAccess *> &MSSAIP, PredIteratorCache &PIC,
1827 AliasSetTracker &ast, MemorySSAUpdater *MSSAU, LoopInfo &li,
1828 DebugLoc dl, int alignment, bool UnorderedAtomic,
1829 const AAMDNodes &AATags, ICFLoopSafetyInfo &SafetyInfo)
1830 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
1831 LoopExitBlocks(LEB), LoopInsertPts(LIP), MSSAInsertPts(MSSAIP),
1832 PredCache(PIC), AST(ast), MSSAU(MSSAU), LI(li), DL(std::move(dl)),
1833 Alignment(alignment), UnorderedAtomic(UnorderedAtomic), AATags(AATags),
1834 SafetyInfo(SafetyInfo) {}
1835
1836 bool isInstInList(Instruction *I,
1837 const SmallVectorImpl<Instruction *> &) const override {
1838 Value *Ptr;
1839 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1840 Ptr = LI->getOperand(0);
1841 else
1842 Ptr = cast<StoreInst>(I)->getPointerOperand();
1843 return PointerMustAliases.count(Ptr);
1844 }
1845
1846 void doExtraRewritesBeforeFinalDeletion() override {
1847 // Insert stores after in the loop exit blocks. Each exit block gets a
1848 // store of the live-out values that feed them. Since we've already told
1849 // the SSA updater about the defs in the loop and the preheader
1850 // definition, it is all set and we can start using it.
1851 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
1852 BasicBlock *ExitBlock = LoopExitBlocks[i];
1853 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1854 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1855 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1856 Instruction *InsertPos = LoopInsertPts[i];
1857 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
1858 if (UnorderedAtomic)
1859 NewSI->setOrdering(AtomicOrdering::Unordered);
1860 NewSI->setAlignment(MaybeAlign(Alignment));
1861 NewSI->setDebugLoc(DL);
1862 if (AATags)
1863 NewSI->setAAMetadata(AATags);
1864
1865 if (MSSAU) {
1866 MemoryAccess *MSSAInsertPoint = MSSAInsertPts[i];
1867 MemoryAccess *NewMemAcc;
1868 if (!MSSAInsertPoint) {
1869 NewMemAcc = MSSAU->createMemoryAccessInBB(
1870 NewSI, nullptr, NewSI->getParent(), MemorySSA::Beginning);
1871 } else {
1872 NewMemAcc =
1873 MSSAU->createMemoryAccessAfter(NewSI, nullptr, MSSAInsertPoint);
1874 }
1875 MSSAInsertPts[i] = NewMemAcc;
1876 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
1877 // FIXME: true for safety, false may still be correct.
1878 }
1879 }
1880 }
1881
1882 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
1883 // Update alias analysis.
1884 AST.copyValue(LI, V);
1885 }
1886 void instructionDeleted(Instruction *I) const override {
1887 SafetyInfo.removeInstruction(I);
1888 AST.deleteValue(I);
1889 if (MSSAU)
1890 MSSAU->removeMemoryAccess(I);
1891 }
1892};
1893
1894
1895/// Return true iff we can prove that a caller of this function can not inspect
1896/// the contents of the provided object in a well defined program.
1897bool isKnownNonEscaping(Value *Object, const TargetLibraryInfo *TLI) {
1898 if (isa<AllocaInst>(Object))
1899 // Since the alloca goes out of scope, we know the caller can't retain a
1900 // reference to it and be well defined. Thus, we don't need to check for
1901 // capture.
1902 return true;
1903
1904 // For all other objects we need to know that the caller can't possibly
1905 // have gotten a reference to the object. There are two components of
1906 // that:
1907 // 1) Object can't be escaped by this function. This is what
1908 // PointerMayBeCaptured checks.
1909 // 2) Object can't have been captured at definition site. For this, we
1910 // need to know the return value is noalias. At the moment, we use a
1911 // weaker condition and handle only AllocLikeFunctions (which are
1912 // known to be noalias). TODO
1913 return isAllocLikeFn(Object, TLI) &&
1914 !PointerMayBeCaptured(Object, true, true);
1915}
1916
1917} // namespace
1918
1919/// Try to promote memory values to scalars by sinking stores out of the
1920/// loop and moving loads to before the loop. We do this by looping over
1921/// the stores in the loop, looking for stores to Must pointers which are
1922/// loop invariant.
1923///
1924bool llvm::promoteLoopAccessesToScalars(
1925 const SmallSetVector<Value *, 8> &PointerMustAliases,
1926 SmallVectorImpl<BasicBlock *> &ExitBlocks,
1927 SmallVectorImpl<Instruction *> &InsertPts,
1928 SmallVectorImpl<MemoryAccess *> &MSSAInsertPts, PredIteratorCache &PIC,
1929 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
1930 Loop *CurLoop, AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU,
1931 ICFLoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE) {
1932 // Verify inputs.
1933 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&((LI != nullptr && DT != nullptr && CurLoop !=
nullptr && CurAST != nullptr && SafetyInfo !=
nullptr && "Unexpected Input to promoteLoopAccessesToScalars"
) ? static_cast<void> (0) : __assert_fail ("LI != nullptr && DT != nullptr && CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr && \"Unexpected Input to promoteLoopAccessesToScalars\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1935, __PRETTY_FUNCTION__))
1934 CurAST != nullptr && SafetyInfo != nullptr &&((LI != nullptr && DT != nullptr && CurLoop !=
nullptr && CurAST != nullptr && SafetyInfo !=
nullptr && "Unexpected Input to promoteLoopAccessesToScalars"
) ? static_cast<void> (0) : __assert_fail ("LI != nullptr && DT != nullptr && CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr && \"Unexpected Input to promoteLoopAccessesToScalars\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1935, __PRETTY_FUNCTION__))
1935 "Unexpected Input to promoteLoopAccessesToScalars")((LI != nullptr && DT != nullptr && CurLoop !=
nullptr && CurAST != nullptr && SafetyInfo !=
nullptr && "Unexpected Input to promoteLoopAccessesToScalars"
) ? static_cast<void> (0) : __assert_fail ("LI != nullptr && DT != nullptr && CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr && \"Unexpected Input to promoteLoopAccessesToScalars\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1935, __PRETTY_FUNCTION__))
;
1936
1937 Value *SomePtr = *PointerMustAliases.begin();
1938 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1939
1940 // It is not safe to promote a load/store from the loop if the load/store is
1941 // conditional. For example, turning:
1942 //
1943 // for () { if (c) *P += 1; }
1944 //
1945 // into:
1946 //
1947 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
1948 //
1949 // is not safe, because *P may only be valid to access if 'c' is true.
1950 //
1951 // The safety property divides into two parts:
1952 // p1) The memory may not be dereferenceable on entry to the loop. In this
1953 // case, we can't insert the required load in the preheader.
1954 // p2) The memory model does not allow us to insert a store along any dynamic
1955 // path which did not originally have one.
1956 //
1957 // If at least one store is guaranteed to execute, both properties are
1958 // satisfied, and promotion is legal.
1959 //
1960 // This, however, is not a necessary condition. Even if no store/load is
1961 // guaranteed to execute, we can still establish these properties.
1962 // We can establish (p1) by proving that hoisting the load into the preheader
1963 // is safe (i.e. proving dereferenceability on all paths through the loop). We
1964 // can use any access within the alias set to prove dereferenceability,
1965 // since they're all must alias.
1966 //
1967 // There are two ways establish (p2):
1968 // a) Prove the location is thread-local. In this case the memory model
1969 // requirement does not apply, and stores are safe to insert.
1970 // b) Prove a store dominates every exit block. In this case, if an exit
1971 // blocks is reached, the original dynamic path would have taken us through
1972 // the store, so inserting a store into the exit block is safe. Note that this
1973 // is different from the store being guaranteed to execute. For instance,
1974 // if an exception is thrown on the first iteration of the loop, the original
1975 // store is never executed, but the exit blocks are not executed either.
1976
1977 bool DereferenceableInPH = false;
1978 bool SafeToInsertStore = false;
1979
1980 SmallVector<Instruction *, 64> LoopUses;
1981
1982 // We start with an alignment of one and try to find instructions that allow
1983 // us to prove better alignment.
1984 unsigned Alignment = 1;
1985 // Keep track of which types of access we see
1986 bool SawUnorderedAtomic = false;
1987 bool SawNotAtomic = false;
1988 AAMDNodes AATags;
1989
1990 const DataLayout &MDL = Preheader->getModule()->getDataLayout();
1991
1992 bool IsKnownThreadLocalObject = false;
1993 if (SafetyInfo->anyBlockMayThrow()) {
1994 // If a loop can throw, we have to insert a store along each unwind edge.
1995 // That said, we can't actually make the unwind edge explicit. Therefore,
1996 // we have to prove that the store is dead along the unwind edge. We do
1997 // this by proving that the caller can't have a reference to the object
1998 // after return and thus can't possibly load from the object.
1999 Value *Object = GetUnderlyingObject(SomePtr, MDL);
2000 if (!isKnownNonEscaping(Object, TLI))
2001 return false;
2002 // Subtlety: Alloca's aren't visible to callers, but *are* potentially
2003 // visible to other threads if captured and used during their lifetimes.
2004 IsKnownThreadLocalObject = !isa<AllocaInst>(Object);
2005 }
2006
2007 // Check that all of the pointers in the alias set have the same type. We
2008 // cannot (yet) promote a memory location that is loaded and stored in
2009 // different sizes. While we are at it, collect alignment and AA info.
2010 for (Value *ASIV : PointerMustAliases) {
2011 // Check that all of the pointers in the alias set have the same type. We
2012 // cannot (yet) promote a memory location that is loaded and stored in
2013 // different sizes.
2014 if (SomePtr->getType() != ASIV->getType())
2015 return false;
2016
2017 for (User *U : ASIV->users()) {
2018 // Ignore instructions that are outside the loop.
2019 Instruction *UI = dyn_cast<Instruction>(U);
2020 if (!UI || !CurLoop->contains(UI))
2021 continue;
2022
2023 // If there is an non-load/store instruction in the loop, we can't promote
2024 // it.
2025 if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
2026 if (!Load->isUnordered())
2027 return false;
2028
2029 SawUnorderedAtomic |= Load->isAtomic();
2030 SawNotAtomic |= !Load->isAtomic();
2031
2032 unsigned InstAlignment = Load->getAlignment();
2033 if (!InstAlignment)
2034 InstAlignment =
2035 MDL.getABITypeAlignment(Load->getType());
2036
2037 // Note that proving a load safe to speculate requires proving
2038 // sufficient alignment at the target location. Proving it guaranteed
2039 // to execute does as well. Thus we can increase our guaranteed
2040 // alignment as well.
2041 if (!DereferenceableInPH || (InstAlignment > Alignment))
2042 if (isSafeToExecuteUnconditionally(*Load, DT, CurLoop, SafetyInfo,
2043 ORE, Preheader->getTerminator())) {
2044 DereferenceableInPH = true;
2045 Alignment = std::max(Alignment, InstAlignment);
2046 }
2047 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
2048 // Stores *of* the pointer are not interesting, only stores *to* the
2049 // pointer.
2050 if (UI->getOperand(1) != ASIV)
2051 continue;
2052 if (!Store->isUnordered())
2053 return false;
2054
2055 SawUnorderedAtomic |= Store->isAtomic();
2056 SawNotAtomic |= !Store->isAtomic();
2057
2058 // If the store is guaranteed to execute, both properties are satisfied.
2059 // We may want to check if a store is guaranteed to execute even if we
2060 // already know that promotion is safe, since it may have higher
2061 // alignment than any other guaranteed stores, in which case we can
2062 // raise the alignment on the promoted store.
2063 unsigned InstAlignment = Store->getAlignment();
2064 if (!InstAlignment)
2065 InstAlignment =
2066 MDL.getABITypeAlignment(Store->getValueOperand()->getType());
2067
2068 if (!DereferenceableInPH || !SafeToInsertStore ||
2069 (InstAlignment > Alignment)) {
2070 if (SafetyInfo->isGuaranteedToExecute(*UI, DT, CurLoop)) {
2071 DereferenceableInPH = true;
2072 SafeToInsertStore = true;
2073 Alignment = std::max(Alignment, InstAlignment);
2074 }
2075 }
2076
2077 // If a store dominates all exit blocks, it is safe to sink.
2078 // As explained above, if an exit block was executed, a dominating
2079 // store must have been executed at least once, so we are not
2080 // introducing stores on paths that did not have them.
2081 // Note that this only looks at explicit exit blocks. If we ever
2082 // start sinking stores into unwind edges (see above), this will break.
2083 if (!SafeToInsertStore)
2084 SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
2085 return DT->dominates(Store->getParent(), Exit);
2086 });
2087
2088 // If the store is not guaranteed to execute, we may still get
2089 // deref info through it.
2090 if (!DereferenceableInPH) {
2091 DereferenceableInPH = isDereferenceableAndAlignedPointer(
2092 Store->getPointerOperand(), Store->getValueOperand()->getType(),
2093 MaybeAlign(Store->getAlignment()), MDL,
2094 Preheader->getTerminator(), DT);
2095 }
2096 } else
2097 return false; // Not a load or store.
2098
2099 // Merge the AA tags.
2100 if (LoopUses.empty()) {
2101 // On the first load/store, just take its AA tags.
2102 UI->getAAMetadata(AATags);
2103 } else if (AATags) {
2104 UI->getAAMetadata(AATags, /* Merge = */ true);
2105 }
2106
2107 LoopUses.push_back(UI);
2108 }
2109 }
2110
2111 // If we found both an unordered atomic instruction and a non-atomic memory
2112 // access, bail. We can't blindly promote non-atomic to atomic since we
2113 // might not be able to lower the result. We can't downgrade since that
2114 // would violate memory model. Also, align 0 is an error for atomics.
2115 if (SawUnorderedAtomic && SawNotAtomic)
2116 return false;
2117
2118 // If we're inserting an atomic load in the preheader, we must be able to
2119 // lower it. We're only guaranteed to be able to lower naturally aligned
2120 // atomics.
2121 auto *SomePtrElemType = SomePtr->getType()->getPointerElementType();
2122 if (SawUnorderedAtomic &&
2123 Alignment < MDL.getTypeStoreSize(SomePtrElemType))
2124 return false;
2125
2126 // If we couldn't prove we can hoist the load, bail.
2127 if (!DereferenceableInPH)
2128 return false;
2129
2130 // We know we can hoist the load, but don't have a guaranteed store.
2131 // Check whether the location is thread-local. If it is, then we can insert
2132 // stores along paths which originally didn't have them without violating the
2133 // memory model.
2134 if (!SafeToInsertStore) {
2135 if (IsKnownThreadLocalObject)
2136 SafeToInsertStore = true;
2137 else {
2138 Value *Object = GetUnderlyingObject(SomePtr, MDL);
2139 SafeToInsertStore =
2140 (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) &&
2141 !PointerMayBeCaptured(Object, true, true);
2142 }
2143 }
2144
2145 // If we've still failed to prove we can sink the store, give up.
2146 if (!SafeToInsertStore)
2147 return false;
2148
2149 // Otherwise, this is safe to promote, lets do it!
2150 LLVM_DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtrdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM: Promoting value stored to in loop: "
<< *SomePtr << '\n'; } } while (false)
2151 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM: Promoting value stored to in loop: "
<< *SomePtr << '\n'; } } while (false)
;
2152 ORE->emit([&]() {
2153 return OptimizationRemark(DEBUG_TYPE"licm", "PromoteLoopAccessesToScalar",
2154 LoopUses[0])
2155 << "Moving accesses to memory location out of the loop";
2156 });
2157 ++NumPromoted;
2158
2159 // Grab a debug location for the inserted loads/stores; given that the
2160 // inserted loads/stores have little relation to the original loads/stores,
2161 // this code just arbitrarily picks a location from one, since any debug
2162 // location is better than none.
2163 DebugLoc DL = LoopUses[0]->getDebugLoc();
2164
2165 // We use the SSAUpdater interface to insert phi nodes as required.
2166 SmallVector<PHINode *, 16> NewPHIs;
2167 SSAUpdater SSA(&NewPHIs);
2168 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
2169 InsertPts, MSSAInsertPts, PIC, *CurAST, MSSAU, *LI, DL,
2170 Alignment, SawUnorderedAtomic, AATags, *SafetyInfo);
2171
2172 // Set up the preheader to have a definition of the value. It is the live-out
2173 // value from the preheader that uses in the loop will use.
2174 LoadInst *PreheaderLoad = new LoadInst(
2175 SomePtr->getType()->getPointerElementType(), SomePtr,
2176 SomePtr->getName() + ".promoted", Preheader->getTerminator());
2177 if (SawUnorderedAtomic)
2178 PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
2179 PreheaderLoad->setAlignment(MaybeAlign(Alignment));
2180 PreheaderLoad->setDebugLoc(DL);
2181 if (AATags)
2182 PreheaderLoad->setAAMetadata(AATags);
2183 SSA.AddAvailableValue(Preheader, PreheaderLoad);
2184
2185 if (MSSAU) {
2186 MemoryAccess *PreheaderLoadMemoryAccess = MSSAU->createMemoryAccessInBB(
2187 PreheaderLoad, nullptr, PreheaderLoad->getParent(), MemorySSA::End);
2188 MemoryUse *NewMemUse = cast<MemoryUse>(PreheaderLoadMemoryAccess);
2189 MSSAU->insertUse(NewMemUse, /*RenameUses=*/true);
2190 }
2191
2192 if (MSSAU && VerifyMemorySSA)
2193 MSSAU->getMemorySSA()->verifyMemorySSA();
2194 // Rewrite all the loads in the loop and remember all the definitions from
2195 // stores in the loop.
2196 Promoter.run(LoopUses);
2197
2198 if (MSSAU && VerifyMemorySSA)
2199 MSSAU->getMemorySSA()->verifyMemorySSA();
2200 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
2201 if (PreheaderLoad->use_empty())
2202 eraseInstruction(*PreheaderLoad, *SafetyInfo, CurAST, MSSAU);
2203
2204 return true;
2205}
2206
2207/// Returns an owning pointer to an alias set which incorporates aliasing info
2208/// from L and all subloops of L.
2209/// FIXME: In new pass manager, there is no helper function to handle loop
2210/// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed
2211/// from scratch for every loop. Hook up with the helper functions when
2212/// available in the new pass manager to avoid redundant computation.
2213std::unique_ptr<AliasSetTracker>
2214LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
2215 AliasAnalysis *AA) {
2216 std::unique_ptr<AliasSetTracker> CurAST;
2217 SmallVector<Loop *, 4> RecomputeLoops;
2218 for (Loop *InnerL : L->getSubLoops()) {
2219 auto MapI = LoopToAliasSetMap.find(InnerL);
2220 // If the AST for this inner loop is missing it may have been merged into
2221 // some other loop's AST and then that loop unrolled, and so we need to
2222 // recompute it.
2223 if (MapI == LoopToAliasSetMap.end()) {
2224 RecomputeLoops.push_back(InnerL);
2225 continue;
2226 }
2227 std::unique_ptr<AliasSetTracker> InnerAST = std::move(MapI->second);
2228
2229 if (CurAST) {
2230 // What if InnerLoop was modified by other passes ?
2231 // Once we've incorporated the inner loop's AST into ours, we don't need
2232 // the subloop's anymore.
2233 CurAST->add(*InnerAST);
2234 } else {
2235 CurAST = std::move(InnerAST);
2236 }
2237 LoopToAliasSetMap.erase(MapI);
2238 }
2239 if (!CurAST)
2240 CurAST = std::make_unique<AliasSetTracker>(*AA);
2241
2242 // Add everything from the sub loops that are no longer directly available.
2243 for (Loop *InnerL : RecomputeLoops)
2244 for (BasicBlock *BB : InnerL->blocks())
2245 CurAST->add(*BB);
2246
2247 // And merge in this loop (without anything from inner loops).
2248 for (BasicBlock *BB : L->blocks())
2249 if (LI->getLoopFor(BB) == L)
2250 CurAST->add(*BB);
2251
2252 return CurAST;
2253}
2254
2255std::unique_ptr<AliasSetTracker>
2256LoopInvariantCodeMotion::collectAliasInfoForLoopWithMSSA(
2257 Loop *L, AliasAnalysis *AA, MemorySSAUpdater *MSSAU) {
2258 auto *MSSA = MSSAU->getMemorySSA();
2259 auto CurAST = std::make_unique<AliasSetTracker>(*AA, MSSA, L);
2260 CurAST->addAllInstructionsInLoopUsingMSSA();
2261 return CurAST;
2262}
2263
2264/// Simple analysis hook. Clone alias set info.
2265///
2266void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
2267 Loop *L) {
2268 auto ASTIt = LICM.getLoopToAliasSetMap().find(L);
2269 if (ASTIt == LICM.getLoopToAliasSetMap().end())
2270 return;
2271
2272 ASTIt->second->copyValue(From, To);
2273}
2274
2275/// Simple Analysis hook. Delete value V from alias set
2276///
2277void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
2278 auto ASTIt = LICM.getLoopToAliasSetMap().find(L);
2279 if (ASTIt == LICM.getLoopToAliasSetMap().end())
2280 return;
2281
2282 ASTIt->second->deleteValue(V);
2283}
2284
2285/// Simple Analysis hook. Delete value L from alias set map.
2286///
2287void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
2288 if (!LICM.getLoopToAliasSetMap().count(L))
2289 return;
2290
2291 LICM.getLoopToAliasSetMap().erase(L);
2292}
2293
2294static bool pointerInvalidatedByLoop(MemoryLocation MemLoc,
2295 AliasSetTracker *CurAST, Loop *CurLoop,
2296 AliasAnalysis *AA) {
2297 // First check to see if any of the basic blocks in CurLoop invalidate *V.
2298 bool isInvalidatedAccordingToAST = CurAST->getAliasSetFor(MemLoc).isMod();
2299
2300 if (!isInvalidatedAccordingToAST || !LICMN2Theshold)
2301 return isInvalidatedAccordingToAST;
2302
2303 // Check with a diagnostic analysis if we can refine the information above.
2304 // This is to identify the limitations of using the AST.
2305 // The alias set mechanism used by LICM has a major weakness in that it
2306 // combines all things which may alias into a single set *before* asking
2307 // modref questions. As a result, a single readonly call within a loop will
2308 // collapse all loads and stores into a single alias set and report
2309 // invalidation if the loop contains any store. For example, readonly calls
2310 // with deopt states have this form and create a general alias set with all
2311 // loads and stores. In order to get any LICM in loops containing possible
2312 // deopt states we need a more precise invalidation of checking the mod ref
2313 // info of each instruction within the loop and LI. This has a complexity of
2314 // O(N^2), so currently, it is used only as a diagnostic tool since the
2315 // default value of LICMN2Threshold is zero.
2316
2317 // Don't look at nested loops.
2318 if (CurLoop->begin() != CurLoop->end())
2319 return true;
2320
2321 int N = 0;
2322 for (BasicBlock *BB : CurLoop->getBlocks())
2323 for (Instruction &I : *BB) {
2324 if (N >= LICMN2Theshold) {
2325 LLVM_DEBUG(dbgs() << "Alasing N2 threshold exhausted for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "Alasing N2 threshold exhausted for "
<< *(MemLoc.Ptr) << "\n"; } } while (false)
2326 << *(MemLoc.Ptr) << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "Alasing N2 threshold exhausted for "
<< *(MemLoc.Ptr) << "\n"; } } while (false)
;
2327 return true;
2328 }
2329 N++;
2330 auto Res = AA->getModRefInfo(&I, MemLoc);
2331 if (isModSet(Res)) {
2332 LLVM_DEBUG(dbgs() << "Aliasing failed on " << I << " for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "Aliasing failed on " << I <<
" for " << *(MemLoc.Ptr) << "\n"; } } while (false
)
2333 << *(MemLoc.Ptr) << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "Aliasing failed on " << I <<
" for " << *(MemLoc.Ptr) << "\n"; } } while (false
)
;
2334 return true;
2335 }
2336 }
2337 LLVM_DEBUG(dbgs() << "Aliasing okay for " << *(MemLoc.Ptr) << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "Aliasing okay for " << *(MemLoc
.Ptr) << "\n"; } } while (false)
;
2338 return false;
2339}
2340
2341static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU,
2342 Loop *CurLoop,
2343 SinkAndHoistLICMFlags &Flags) {
2344 // For hoisting, use the walker to determine safety
2345 if (!Flags.IsSink) {
2346 MemoryAccess *Source;
2347 // See declaration of SetLicmMssaOptCap for usage details.
2348 if (Flags.LicmMssaOptCounter >= Flags.LicmMssaOptCap)
2349 Source = MU->getDefiningAccess();
2350 else {
2351 Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(MU);
2352 Flags.LicmMssaOptCounter++;
2353 }
2354 return !MSSA->isLiveOnEntryDef(Source) &&
2355 CurLoop->contains(Source->getBlock());
2356 }
2357
2358 // For sinking, we'd need to check all Defs below this use. The getClobbering
2359 // call will look on the backedge of the loop, but will check aliasing with
2360 // the instructions on the previous iteration.
2361 // For example:
2362 // for (i ... )
2363 // load a[i] ( Use (LoE)
2364 // store a[i] ( 1 = Def (2), with 2 = Phi for the loop.
2365 // i++;
2366 // The load sees no clobbering inside the loop, as the backedge alias check
2367 // does phi translation, and will check aliasing against store a[i-1].
2368 // However sinking the load outside the loop, below the store is incorrect.
2369
2370 // For now, only sink if there are no Defs in the loop, and the existing ones
2371 // precede the use and are in the same block.
2372 // FIXME: Increase precision: Safe to sink if Use post dominates the Def;
2373 // needs PostDominatorTreeAnalysis.
2374 // FIXME: More precise: no Defs that alias this Use.
2375 if (Flags.NoOfMemAccTooLarge)
2376 return true;
2377 for (auto *BB : CurLoop->getBlocks())
2378 if (auto *Accesses = MSSA->getBlockDefs(BB))
2379 for (const auto &MA : *Accesses)
2380 if (const auto *MD = dyn_cast<MemoryDef>(&MA))
2381 if (MU->getBlock() != MD->getBlock() ||
2382 !MSSA->locallyDominates(MD, MU))
2383 return true;
2384 return false;
2385}
2386
2387/// Little predicate that returns true if the specified basic block is in
2388/// a subloop of the current one, not the current one itself.
2389///
2390static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
2391 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop")((CurLoop->contains(BB) && "Only valid if BB is IN the loop"
) ? static_cast<void> (0) : __assert_fail ("CurLoop->contains(BB) && \"Only valid if BB is IN the loop\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Scalar/LICM.cpp"
, 2391, __PRETTY_FUNCTION__))
;
2392 return LI->getLoopFor(BB) != CurLoop;
2393}

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

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