File: | llvm/lib/Transforms/Scalar/LICM.cpp |
Warning: | line 1198, column 20 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
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/MustExecute.h" | ||||
50 | #include "llvm/Analysis/OptimizationRemarkEmitter.h" | ||||
51 | #include "llvm/Analysis/ScalarEvolution.h" | ||||
52 | #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" | ||||
53 | #include "llvm/Analysis/TargetLibraryInfo.h" | ||||
54 | #include "llvm/Analysis/ValueTracking.h" | ||||
55 | #include "llvm/IR/CFG.h" | ||||
56 | #include "llvm/IR/Constants.h" | ||||
57 | #include "llvm/IR/DataLayout.h" | ||||
58 | #include "llvm/IR/DebugInfoMetadata.h" | ||||
59 | #include "llvm/IR/DerivedTypes.h" | ||||
60 | #include "llvm/IR/Dominators.h" | ||||
61 | #include "llvm/IR/Instructions.h" | ||||
62 | #include "llvm/IR/IntrinsicInst.h" | ||||
63 | #include "llvm/IR/LLVMContext.h" | ||||
64 | #include "llvm/IR/Metadata.h" | ||||
65 | #include "llvm/IR/PatternMatch.h" | ||||
66 | #include "llvm/IR/PredIteratorCache.h" | ||||
67 | #include "llvm/InitializePasses.h" | ||||
68 | #include "llvm/Support/CommandLine.h" | ||||
69 | #include "llvm/Support/Debug.h" | ||||
70 | #include "llvm/Support/raw_ostream.h" | ||||
71 | #include "llvm/Transforms/Scalar.h" | ||||
72 | #include "llvm/Transforms/Scalar/LoopPassManager.h" | ||||
73 | #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" | ||||
74 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" | ||||
75 | #include "llvm/Transforms/Utils/Local.h" | ||||
76 | #include "llvm/Transforms/Utils/LoopUtils.h" | ||||
77 | #include "llvm/Transforms/Utils/SSAUpdater.h" | ||||
78 | #include <algorithm> | ||||
79 | #include <utility> | ||||
80 | using namespace llvm; | ||||
81 | |||||
82 | #define DEBUG_TYPE"licm" "licm" | ||||
83 | |||||
84 | STATISTIC(NumCreatedBlocks, "Number of blocks created")static llvm::Statistic NumCreatedBlocks = {"licm", "NumCreatedBlocks" , "Number of blocks created"}; | ||||
85 | STATISTIC(NumClonedBranches, "Number of branches cloned")static llvm::Statistic NumClonedBranches = {"licm", "NumClonedBranches" , "Number of branches cloned"}; | ||||
86 | STATISTIC(NumSunk, "Number of instructions sunk out of loop")static llvm::Statistic NumSunk = {"licm", "NumSunk", "Number of instructions sunk out of loop" }; | ||||
87 | STATISTIC(NumHoisted, "Number of instructions hoisted out of loop")static llvm::Statistic NumHoisted = {"licm", "NumHoisted", "Number of instructions hoisted out of loop" }; | ||||
88 | STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk")static llvm::Statistic NumMovedLoads = {"licm", "NumMovedLoads" , "Number of load insts hoisted or sunk"}; | ||||
89 | STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk")static llvm::Statistic NumMovedCalls = {"licm", "NumMovedCalls" , "Number of call insts hoisted or sunk"}; | ||||
90 | STATISTIC(NumPromoted, "Number of memory locations promoted to registers")static llvm::Statistic NumPromoted = {"licm", "NumPromoted", "Number of memory locations promoted to registers" }; | ||||
91 | |||||
92 | /// Memory promotion is enabled by default. | ||||
93 | static cl::opt<bool> | ||||
94 | DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false), | ||||
95 | cl::desc("Disable memory promotion in LICM pass")); | ||||
96 | |||||
97 | static cl::opt<bool> ControlFlowHoisting( | ||||
98 | "licm-control-flow-hoisting", cl::Hidden, cl::init(false), | ||||
99 | cl::desc("Enable control flow (and PHI) hoisting in LICM")); | ||||
100 | |||||
101 | static cl::opt<uint32_t> MaxNumUsesTraversed( | ||||
102 | "licm-max-num-uses-traversed", cl::Hidden, cl::init(8), | ||||
103 | cl::desc("Max num uses visited for identifying load " | ||||
104 | "invariance in loop using invariant start (default = 8)")); | ||||
105 | |||||
106 | // Default value of zero implies we use the regular alias set tracker mechanism | ||||
107 | // instead of the cross product using AA to identify aliasing of the memory | ||||
108 | // location we are interested in. | ||||
109 | static cl::opt<int> | ||||
110 | LICMN2Theshold("licm-n2-threshold", cl::Hidden, cl::init(0), | ||||
111 | cl::desc("How many instruction to cross product using AA")); | ||||
112 | |||||
113 | // Experimental option to allow imprecision in LICM in pathological cases, in | ||||
114 | // exchange for faster compile. This is to be removed if MemorySSA starts to | ||||
115 | // address the same issue. This flag applies only when LICM uses MemorySSA | ||||
116 | // instead on AliasSetTracker. LICM calls MemorySSAWalker's | ||||
117 | // getClobberingMemoryAccess, up to the value of the Cap, getting perfect | ||||
118 | // accuracy. Afterwards, LICM will call into MemorySSA's getDefiningAccess, | ||||
119 | // which may not be precise, since optimizeUses is capped. The result is | ||||
120 | // correct, but we may not get as "far up" as possible to get which access is | ||||
121 | // clobbering the one queried. | ||||
122 | cl::opt<unsigned> llvm::SetLicmMssaOptCap( | ||||
123 | "licm-mssa-optimization-cap", cl::init(100), cl::Hidden, | ||||
124 | cl::desc("Enable imprecision in LICM in pathological cases, in exchange " | ||||
125 | "for faster compile. Caps the MemorySSA clobbering calls.")); | ||||
126 | |||||
127 | // Experimentally, memory promotion carries less importance than sinking and | ||||
128 | // hoisting. Limit when we do promotion when using MemorySSA, in order to save | ||||
129 | // compile time. | ||||
130 | cl::opt<unsigned> llvm::SetLicmMssaNoAccForPromotionCap( | ||||
131 | "licm-mssa-max-acc-promotion", cl::init(250), cl::Hidden, | ||||
132 | cl::desc("[LICM & MemorySSA] When MSSA in LICM is disabled, this has no " | ||||
133 | "effect. When MSSA in LICM is enabled, then this is the maximum " | ||||
134 | "number of accesses allowed to be present in a loop in order to " | ||||
135 | "enable memory promotion.")); | ||||
136 | |||||
137 | static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI); | ||||
138 | static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop, | ||||
139 | const LoopSafetyInfo *SafetyInfo, | ||||
140 | TargetTransformInfo *TTI, bool &FreeInLoop); | ||||
141 | static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, | ||||
142 | BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo, | ||||
143 | MemorySSAUpdater *MSSAU, ScalarEvolution *SE, | ||||
144 | OptimizationRemarkEmitter *ORE); | ||||
145 | static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT, | ||||
146 | const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo, | ||||
147 | MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE); | ||||
148 | static bool isSafeToExecuteUnconditionally(Instruction &Inst, | ||||
149 | const DominatorTree *DT, | ||||
150 | const Loop *CurLoop, | ||||
151 | const LoopSafetyInfo *SafetyInfo, | ||||
152 | OptimizationRemarkEmitter *ORE, | ||||
153 | const Instruction *CtxI = nullptr); | ||||
154 | static bool pointerInvalidatedByLoop(MemoryLocation MemLoc, | ||||
155 | AliasSetTracker *CurAST, Loop *CurLoop, | ||||
156 | AAResults *AA); | ||||
157 | static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU, | ||||
158 | Loop *CurLoop, | ||||
159 | SinkAndHoistLICMFlags &Flags); | ||||
160 | static Instruction *cloneInstructionInExitBlock( | ||||
161 | Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI, | ||||
162 | const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU); | ||||
163 | |||||
164 | static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, | ||||
165 | AliasSetTracker *AST, MemorySSAUpdater *MSSAU); | ||||
166 | |||||
167 | static void moveInstructionBefore(Instruction &I, Instruction &Dest, | ||||
168 | ICFLoopSafetyInfo &SafetyInfo, | ||||
169 | MemorySSAUpdater *MSSAU, ScalarEvolution *SE); | ||||
170 | |||||
171 | namespace { | ||||
172 | struct LoopInvariantCodeMotion { | ||||
173 | bool runOnLoop(Loop *L, AAResults *AA, LoopInfo *LI, DominatorTree *DT, | ||||
174 | TargetLibraryInfo *TLI, TargetTransformInfo *TTI, | ||||
175 | ScalarEvolution *SE, MemorySSA *MSSA, | ||||
176 | OptimizationRemarkEmitter *ORE); | ||||
177 | |||||
178 | LoopInvariantCodeMotion(unsigned LicmMssaOptCap, | ||||
179 | unsigned LicmMssaNoAccForPromotionCap) | ||||
180 | : LicmMssaOptCap(LicmMssaOptCap), | ||||
181 | LicmMssaNoAccForPromotionCap(LicmMssaNoAccForPromotionCap) {} | ||||
182 | |||||
183 | private: | ||||
184 | unsigned LicmMssaOptCap; | ||||
185 | unsigned LicmMssaNoAccForPromotionCap; | ||||
186 | |||||
187 | std::unique_ptr<AliasSetTracker> | ||||
188 | collectAliasInfoForLoop(Loop *L, LoopInfo *LI, AAResults *AA); | ||||
189 | std::unique_ptr<AliasSetTracker> | ||||
190 | collectAliasInfoForLoopWithMSSA(Loop *L, AAResults *AA, | ||||
191 | MemorySSAUpdater *MSSAU); | ||||
192 | }; | ||||
193 | |||||
194 | struct LegacyLICMPass : public LoopPass { | ||||
195 | static char ID; // Pass identification, replacement for typeid | ||||
196 | LegacyLICMPass( | ||||
197 | unsigned LicmMssaOptCap = SetLicmMssaOptCap, | ||||
198 | unsigned LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap) | ||||
199 | : LoopPass(ID), LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap) { | ||||
200 | initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry()); | ||||
201 | } | ||||
202 | |||||
203 | bool runOnLoop(Loop *L, LPPassManager &LPM) override { | ||||
204 | if (skipLoop(L)) | ||||
205 | return false; | ||||
206 | |||||
207 | auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); | ||||
208 | MemorySSA *MSSA = EnableMSSALoopDependency | ||||
209 | ? (&getAnalysis<MemorySSAWrapperPass>().getMSSA()) | ||||
210 | : nullptr; | ||||
211 | // For the old PM, we can't use OptimizationRemarkEmitter as an analysis | ||||
212 | // pass. Function analyses need to be preserved across loop transformations | ||||
213 | // but ORE cannot be preserved (see comment before the pass definition). | ||||
214 | OptimizationRemarkEmitter ORE(L->getHeader()->getParent()); | ||||
215 | return LICM.runOnLoop(L, | ||||
216 | &getAnalysis<AAResultsWrapperPass>().getAAResults(), | ||||
217 | &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), | ||||
218 | &getAnalysis<DominatorTreeWrapperPass>().getDomTree(), | ||||
219 | &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI( | ||||
220 | *L->getHeader()->getParent()), | ||||
221 | &getAnalysis<TargetTransformInfoWrapperPass>().getTTI( | ||||
222 | *L->getHeader()->getParent()), | ||||
223 | SE ? &SE->getSE() : nullptr, MSSA, &ORE); | ||||
224 | } | ||||
225 | |||||
226 | /// This transformation requires natural loop information & requires that | ||||
227 | /// loop preheaders be inserted into the CFG... | ||||
228 | /// | ||||
229 | void getAnalysisUsage(AnalysisUsage &AU) const override { | ||||
230 | AU.addPreserved<DominatorTreeWrapperPass>(); | ||||
231 | AU.addPreserved<LoopInfoWrapperPass>(); | ||||
232 | AU.addRequired<TargetLibraryInfoWrapperPass>(); | ||||
233 | if (EnableMSSALoopDependency) { | ||||
234 | AU.addRequired<MemorySSAWrapperPass>(); | ||||
235 | AU.addPreserved<MemorySSAWrapperPass>(); | ||||
236 | } | ||||
237 | AU.addRequired<TargetTransformInfoWrapperPass>(); | ||||
238 | getLoopAnalysisUsage(AU); | ||||
239 | } | ||||
240 | |||||
241 | private: | ||||
242 | LoopInvariantCodeMotion LICM; | ||||
243 | }; | ||||
244 | } // namespace | ||||
245 | |||||
246 | PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM, | ||||
247 | LoopStandardAnalysisResults &AR, LPMUpdater &) { | ||||
248 | // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis | ||||
249 | // pass. Function analyses need to be preserved across loop transformations | ||||
250 | // but ORE cannot be preserved (see comment before the pass definition). | ||||
251 | OptimizationRemarkEmitter ORE(L.getHeader()->getParent()); | ||||
252 | |||||
253 | LoopInvariantCodeMotion LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap); | ||||
254 | if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.TTI, &AR.SE, | ||||
255 | AR.MSSA, &ORE)) | ||||
256 | return PreservedAnalyses::all(); | ||||
257 | |||||
258 | auto PA = getLoopPassPreservedAnalyses(); | ||||
259 | |||||
260 | PA.preserve<DominatorTreeAnalysis>(); | ||||
261 | PA.preserve<LoopAnalysis>(); | ||||
262 | if (AR.MSSA) | ||||
263 | PA.preserve<MemorySSAAnalysis>(); | ||||
264 | |||||
265 | return PA; | ||||
266 | } | ||||
267 | |||||
268 | char LegacyLICMPass::ID = 0; | ||||
269 | INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",static void *initializeLegacyLICMPassPassOnce(PassRegistry & Registry) { | ||||
270 | false, false)static void *initializeLegacyLICMPassPassOnce(PassRegistry & Registry) { | ||||
271 | INITIALIZE_PASS_DEPENDENCY(LoopPass)initializeLoopPassPass(Registry); | ||||
272 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry); | ||||
273 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry); | ||||
274 | INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)initializeMemorySSAWrapperPassPass(Registry); | ||||
275 | INITIALIZE_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)); } | ||||
276 | 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)); } | ||||
277 | |||||
278 | Pass *llvm::createLICMPass() { return new LegacyLICMPass(); } | ||||
279 | Pass *llvm::createLICMPass(unsigned LicmMssaOptCap, | ||||
280 | unsigned LicmMssaNoAccForPromotionCap) { | ||||
281 | return new LegacyLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap); | ||||
282 | } | ||||
283 | |||||
284 | /// Hoist expressions out of the specified loop. Note, alias info for inner | ||||
285 | /// loop is not preserved so it is not a good idea to run LICM multiple | ||||
286 | /// times on one loop. | ||||
287 | bool LoopInvariantCodeMotion::runOnLoop( | ||||
288 | Loop *L, AAResults *AA, LoopInfo *LI, DominatorTree *DT, | ||||
289 | TargetLibraryInfo *TLI, TargetTransformInfo *TTI, ScalarEvolution *SE, | ||||
290 | MemorySSA *MSSA, OptimizationRemarkEmitter *ORE) { | ||||
291 | bool Changed = false; | ||||
292 | |||||
293 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 293, __PRETTY_FUNCTION__)); | ||||
294 | |||||
295 | // If this loop has metadata indicating that LICM is not to be performed then | ||||
296 | // just exit. | ||||
297 | if (hasDisableLICMTransformsHint(L)) { | ||||
298 | return false; | ||||
299 | } | ||||
300 | |||||
301 | std::unique_ptr<AliasSetTracker> CurAST; | ||||
302 | std::unique_ptr<MemorySSAUpdater> MSSAU; | ||||
303 | bool NoOfMemAccTooLarge = false; | ||||
304 | unsigned LicmMssaOptCounter = 0; | ||||
305 | |||||
306 | if (!MSSA) { | ||||
307 | 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); | ||||
308 | CurAST = collectAliasInfoForLoop(L, LI, AA); | ||||
309 | } else { | ||||
310 | LLVM_DEBUG(dbgs() << "LICM: Using MemorySSA.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("licm")) { dbgs() << "LICM: Using MemorySSA.\n"; } } while (false); | ||||
311 | MSSAU = std::make_unique<MemorySSAUpdater>(MSSA); | ||||
312 | |||||
313 | unsigned AccessCapCount = 0; | ||||
314 | for (auto *BB : L->getBlocks()) { | ||||
315 | if (auto *Accesses = MSSA->getBlockAccesses(BB)) { | ||||
316 | for (const auto &MA : *Accesses) { | ||||
317 | (void)MA; | ||||
318 | AccessCapCount++; | ||||
319 | if (AccessCapCount > LicmMssaNoAccForPromotionCap) { | ||||
320 | NoOfMemAccTooLarge = true; | ||||
321 | break; | ||||
322 | } | ||||
323 | } | ||||
324 | } | ||||
325 | if (NoOfMemAccTooLarge) | ||||
326 | break; | ||||
327 | } | ||||
328 | } | ||||
329 | |||||
330 | // Get the preheader block to move instructions into... | ||||
331 | BasicBlock *Preheader = L->getLoopPreheader(); | ||||
332 | |||||
333 | // Compute loop safety information. | ||||
334 | ICFLoopSafetyInfo SafetyInfo; | ||||
335 | SafetyInfo.computeLoopSafetyInfo(L); | ||||
336 | |||||
337 | // We want to visit all of the instructions in this loop... that are not parts | ||||
338 | // of our subloops (they have already had their invariants hoisted out of | ||||
339 | // their loop, into this loop, so there is no need to process the BODIES of | ||||
340 | // the subloops). | ||||
341 | // | ||||
342 | // Traverse the body of the loop in depth first order on the dominator tree so | ||||
343 | // that we are guaranteed to see definitions before we see uses. This allows | ||||
344 | // us to sink instructions in one pass, without iteration. After sinking | ||||
345 | // instructions, we perform another pass to hoist them out of the loop. | ||||
346 | SinkAndHoistLICMFlags Flags = {NoOfMemAccTooLarge, LicmMssaOptCounter, | ||||
347 | LicmMssaOptCap, LicmMssaNoAccForPromotionCap, | ||||
348 | /*IsSink=*/true}; | ||||
349 | if (L->hasDedicatedExits()) | ||||
350 | Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L, | ||||
351 | CurAST.get(), MSSAU.get(), &SafetyInfo, Flags, ORE); | ||||
352 | Flags.IsSink = false; | ||||
353 | if (Preheader) | ||||
354 | Changed |= | ||||
355 | hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L, | ||||
356 | CurAST.get(), MSSAU.get(), SE, &SafetyInfo, Flags, ORE); | ||||
357 | |||||
358 | // Now that all loop invariants have been removed from the loop, promote any | ||||
359 | // memory references to scalars that we can. | ||||
360 | // Don't sink stores from loops without dedicated block exits. Exits | ||||
361 | // containing indirect branches are not transformed by loop simplify, | ||||
362 | // make sure we catch that. An additional load may be generated in the | ||||
363 | // preheader for SSA updater, so also avoid sinking when no preheader | ||||
364 | // is available. | ||||
365 | if (!DisablePromotion && Preheader && L->hasDedicatedExits() && | ||||
366 | !NoOfMemAccTooLarge) { | ||||
367 | // Figure out the loop exits and their insertion points | ||||
368 | SmallVector<BasicBlock *, 8> ExitBlocks; | ||||
369 | L->getUniqueExitBlocks(ExitBlocks); | ||||
370 | |||||
371 | // We can't insert into a catchswitch. | ||||
372 | bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) { | ||||
373 | return isa<CatchSwitchInst>(Exit->getTerminator()); | ||||
374 | }); | ||||
375 | |||||
376 | if (!HasCatchSwitch) { | ||||
377 | SmallVector<Instruction *, 8> InsertPts; | ||||
378 | SmallVector<MemoryAccess *, 8> MSSAInsertPts; | ||||
379 | InsertPts.reserve(ExitBlocks.size()); | ||||
380 | if (MSSAU) | ||||
381 | MSSAInsertPts.reserve(ExitBlocks.size()); | ||||
382 | for (BasicBlock *ExitBlock : ExitBlocks) { | ||||
383 | InsertPts.push_back(&*ExitBlock->getFirstInsertionPt()); | ||||
384 | if (MSSAU) | ||||
385 | MSSAInsertPts.push_back(nullptr); | ||||
386 | } | ||||
387 | |||||
388 | PredIteratorCache PIC; | ||||
389 | |||||
390 | bool Promoted = false; | ||||
391 | |||||
392 | // Build an AST using MSSA. | ||||
393 | if (!CurAST.get()) | ||||
394 | CurAST = collectAliasInfoForLoopWithMSSA(L, AA, MSSAU.get()); | ||||
395 | |||||
396 | // Loop over all of the alias sets in the tracker object. | ||||
397 | for (AliasSet &AS : *CurAST) { | ||||
398 | // We can promote this alias set if it has a store, if it is a "Must" | ||||
399 | // alias set, if the pointer is loop invariant, and if we are not | ||||
400 | // eliminating any volatile loads or stores. | ||||
401 | if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() || | ||||
402 | !L->isLoopInvariant(AS.begin()->getValue())) | ||||
403 | continue; | ||||
404 | |||||
405 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 407, __PRETTY_FUNCTION__)) | ||||
406 | !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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 407, __PRETTY_FUNCTION__)) | ||||
407 | "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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 407, __PRETTY_FUNCTION__)); | ||||
408 | |||||
409 | SmallSetVector<Value *, 8> PointerMustAliases; | ||||
410 | for (const auto &ASI : AS) | ||||
411 | PointerMustAliases.insert(ASI.getValue()); | ||||
412 | |||||
413 | Promoted |= promoteLoopAccessesToScalars( | ||||
414 | PointerMustAliases, ExitBlocks, InsertPts, MSSAInsertPts, PIC, LI, | ||||
415 | DT, TLI, L, CurAST.get(), MSSAU.get(), &SafetyInfo, ORE); | ||||
416 | } | ||||
417 | |||||
418 | // Once we have promoted values across the loop body we have to | ||||
419 | // recursively reform LCSSA as any nested loop may now have values defined | ||||
420 | // within the loop used in the outer loop. | ||||
421 | // FIXME: This is really heavy handed. It would be a bit better to use an | ||||
422 | // SSAUpdater strategy during promotion that was LCSSA aware and reformed | ||||
423 | // it as it went. | ||||
424 | if (Promoted) | ||||
425 | formLCSSARecursively(*L, *DT, LI, SE); | ||||
426 | |||||
427 | Changed |= Promoted; | ||||
428 | } | ||||
429 | } | ||||
430 | |||||
431 | // Check that neither this loop nor its parent have had LCSSA broken. LICM is | ||||
432 | // specifically moving instructions across the loop boundary and so it is | ||||
433 | // especially in need of sanity checking here. | ||||
434 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 434, __PRETTY_FUNCTION__)); | ||||
435 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 436, __PRETTY_FUNCTION__)) | ||||
436 | "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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 436, __PRETTY_FUNCTION__)); | ||||
437 | |||||
438 | if (MSSAU.get() && VerifyMemorySSA) | ||||
439 | MSSAU->getMemorySSA()->verifyMemorySSA(); | ||||
440 | |||||
441 | if (Changed && SE) | ||||
442 | SE->forgetLoopDispositions(L); | ||||
443 | return Changed; | ||||
444 | } | ||||
445 | |||||
446 | /// Walk the specified region of the CFG (defined by all blocks dominated by | ||||
447 | /// the specified block, and that are in the current loop) in reverse depth | ||||
448 | /// first order w.r.t the DominatorTree. This allows us to visit uses before | ||||
449 | /// definitions, allowing us to sink a loop body in one pass without iteration. | ||||
450 | /// | ||||
451 | bool llvm::sinkRegion(DomTreeNode *N, AAResults *AA, LoopInfo *LI, | ||||
452 | DominatorTree *DT, TargetLibraryInfo *TLI, | ||||
453 | TargetTransformInfo *TTI, Loop *CurLoop, | ||||
454 | AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU, | ||||
455 | ICFLoopSafetyInfo *SafetyInfo, | ||||
456 | SinkAndHoistLICMFlags &Flags, | ||||
457 | OptimizationRemarkEmitter *ORE) { | ||||
458 | |||||
459 | // Verify inputs. | ||||
460 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 462, __PRETTY_FUNCTION__)) | ||||
461 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 462, __PRETTY_FUNCTION__)) | ||||
462 | "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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 462, __PRETTY_FUNCTION__)); | ||||
463 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 464, __PRETTY_FUNCTION__)) | ||||
464 | "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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 464, __PRETTY_FUNCTION__)); | ||||
465 | |||||
466 | // We want to visit children before parents. We will enque all the parents | ||||
467 | // before their children in the worklist and process the worklist in reverse | ||||
468 | // order. | ||||
469 | SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop); | ||||
470 | |||||
471 | bool Changed = false; | ||||
472 | for (DomTreeNode *DTN : reverse(Worklist)) { | ||||
473 | BasicBlock *BB = DTN->getBlock(); | ||||
474 | // Only need to process the contents of this block if it is not part of a | ||||
475 | // subloop (which would already have been processed). | ||||
476 | if (inSubLoop(BB, CurLoop, LI)) | ||||
477 | continue; | ||||
478 | |||||
479 | for (BasicBlock::iterator II = BB->end(); II != BB->begin();) { | ||||
480 | Instruction &I = *--II; | ||||
481 | |||||
482 | // If the instruction is dead, we would try to sink it because it isn't | ||||
483 | // used in the loop, instead, just delete it. | ||||
484 | if (isInstructionTriviallyDead(&I, TLI)) { | ||||
485 | 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); | ||||
486 | salvageKnowledge(&I); | ||||
487 | salvageDebugInfo(I); | ||||
488 | ++II; | ||||
489 | eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); | ||||
490 | Changed = true; | ||||
491 | continue; | ||||
492 | } | ||||
493 | |||||
494 | // Check to see if we can sink this instruction to the exit blocks | ||||
495 | // of the loop. We can do this if the all users of the instruction are | ||||
496 | // outside of the loop. In this case, it doesn't even matter if the | ||||
497 | // operands of the instruction are loop invariant. | ||||
498 | // | ||||
499 | bool FreeInLoop = false; | ||||
500 | if (!I.mayHaveSideEffects() && | ||||
501 | isNotUsedOrFreeInLoop(I, CurLoop, SafetyInfo, TTI, FreeInLoop) && | ||||
502 | canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, MSSAU, true, &Flags, | ||||
503 | ORE)) { | ||||
504 | if (sink(I, LI, DT, CurLoop, SafetyInfo, MSSAU, ORE)) { | ||||
505 | if (!FreeInLoop) { | ||||
506 | ++II; | ||||
507 | salvageDebugInfo(I); | ||||
508 | eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); | ||||
509 | } | ||||
510 | Changed = true; | ||||
511 | } | ||||
512 | } | ||||
513 | } | ||||
514 | } | ||||
515 | if (MSSAU && VerifyMemorySSA) | ||||
516 | MSSAU->getMemorySSA()->verifyMemorySSA(); | ||||
517 | return Changed; | ||||
518 | } | ||||
519 | |||||
520 | namespace { | ||||
521 | // This is a helper class for hoistRegion to make it able to hoist control flow | ||||
522 | // in order to be able to hoist phis. The way this works is that we initially | ||||
523 | // start hoisting to the loop preheader, and when we see a loop invariant branch | ||||
524 | // we make note of this. When we then come to hoist an instruction that's | ||||
525 | // conditional on such a branch we duplicate the branch and the relevant control | ||||
526 | // flow, then hoist the instruction into the block corresponding to its original | ||||
527 | // block in the duplicated control flow. | ||||
528 | class ControlFlowHoister { | ||||
529 | private: | ||||
530 | // Information about the loop we are hoisting from | ||||
531 | LoopInfo *LI; | ||||
532 | DominatorTree *DT; | ||||
533 | Loop *CurLoop; | ||||
534 | MemorySSAUpdater *MSSAU; | ||||
535 | |||||
536 | // A map of blocks in the loop to the block their instructions will be hoisted | ||||
537 | // to. | ||||
538 | DenseMap<BasicBlock *, BasicBlock *> HoistDestinationMap; | ||||
539 | |||||
540 | // The branches that we can hoist, mapped to the block that marks a | ||||
541 | // convergence point of their control flow. | ||||
542 | DenseMap<BranchInst *, BasicBlock *> HoistableBranches; | ||||
543 | |||||
544 | public: | ||||
545 | ControlFlowHoister(LoopInfo *LI, DominatorTree *DT, Loop *CurLoop, | ||||
546 | MemorySSAUpdater *MSSAU) | ||||
547 | : LI(LI), DT(DT), CurLoop(CurLoop), MSSAU(MSSAU) {} | ||||
548 | |||||
549 | void registerPossiblyHoistableBranch(BranchInst *BI) { | ||||
550 | // We can only hoist conditional branches with loop invariant operands. | ||||
551 | if (!ControlFlowHoisting || !BI->isConditional() || | ||||
552 | !CurLoop->hasLoopInvariantOperands(BI)) | ||||
553 | return; | ||||
554 | |||||
555 | // The branch destinations need to be in the loop, and we don't gain | ||||
556 | // anything by duplicating conditional branches with duplicate successors, | ||||
557 | // as it's essentially the same as an unconditional branch. | ||||
558 | BasicBlock *TrueDest = BI->getSuccessor(0); | ||||
559 | BasicBlock *FalseDest = BI->getSuccessor(1); | ||||
560 | if (!CurLoop->contains(TrueDest) || !CurLoop->contains(FalseDest) || | ||||
561 | TrueDest == FalseDest) | ||||
562 | return; | ||||
563 | |||||
564 | // We can hoist BI if one branch destination is the successor of the other, | ||||
565 | // or both have common successor which we check by seeing if the | ||||
566 | // intersection of their successors is non-empty. | ||||
567 | // TODO: This could be expanded to allowing branches where both ends | ||||
568 | // eventually converge to a single block. | ||||
569 | SmallPtrSet<BasicBlock *, 4> TrueDestSucc, FalseDestSucc; | ||||
570 | TrueDestSucc.insert(succ_begin(TrueDest), succ_end(TrueDest)); | ||||
571 | FalseDestSucc.insert(succ_begin(FalseDest), succ_end(FalseDest)); | ||||
572 | BasicBlock *CommonSucc = nullptr; | ||||
573 | if (TrueDestSucc.count(FalseDest)) { | ||||
574 | CommonSucc = FalseDest; | ||||
575 | } else if (FalseDestSucc.count(TrueDest)) { | ||||
576 | CommonSucc = TrueDest; | ||||
577 | } else { | ||||
578 | set_intersect(TrueDestSucc, FalseDestSucc); | ||||
579 | // If there's one common successor use that. | ||||
580 | if (TrueDestSucc.size() == 1) | ||||
581 | CommonSucc = *TrueDestSucc.begin(); | ||||
582 | // If there's more than one pick whichever appears first in the block list | ||||
583 | // (we can't use the value returned by TrueDestSucc.begin() as it's | ||||
584 | // unpredicatable which element gets returned). | ||||
585 | else if (!TrueDestSucc.empty()) { | ||||
586 | Function *F = TrueDest->getParent(); | ||||
587 | auto IsSucc = [&](BasicBlock &BB) { return TrueDestSucc.count(&BB); }; | ||||
588 | auto It = std::find_if(F->begin(), F->end(), IsSucc); | ||||
589 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 589, __PRETTY_FUNCTION__)); | ||||
590 | CommonSucc = &*It; | ||||
591 | } | ||||
592 | } | ||||
593 | // The common successor has to be dominated by the branch, as otherwise | ||||
594 | // there will be some other path to the successor that will not be | ||||
595 | // controlled by this branch so any phi we hoist would be controlled by the | ||||
596 | // wrong condition. This also takes care of avoiding hoisting of loop back | ||||
597 | // edges. | ||||
598 | // TODO: In some cases this could be relaxed if the successor is dominated | ||||
599 | // by another block that's been hoisted and we can guarantee that the | ||||
600 | // control flow has been replicated exactly. | ||||
601 | if (CommonSucc && DT->dominates(BI, CommonSucc)) | ||||
602 | HoistableBranches[BI] = CommonSucc; | ||||
603 | } | ||||
604 | |||||
605 | bool canHoistPHI(PHINode *PN) { | ||||
606 | // The phi must have loop invariant operands. | ||||
607 | if (!ControlFlowHoisting || !CurLoop->hasLoopInvariantOperands(PN)) | ||||
608 | return false; | ||||
609 | // We can hoist phis if the block they are in is the target of hoistable | ||||
610 | // branches which cover all of the predecessors of the block. | ||||
611 | SmallPtrSet<BasicBlock *, 8> PredecessorBlocks; | ||||
612 | BasicBlock *BB = PN->getParent(); | ||||
613 | for (BasicBlock *PredBB : predecessors(BB)) | ||||
614 | PredecessorBlocks.insert(PredBB); | ||||
615 | // If we have less predecessor blocks than predecessors then the phi will | ||||
616 | // have more than one incoming value for the same block which we can't | ||||
617 | // handle. | ||||
618 | // TODO: This could be handled be erasing some of the duplicate incoming | ||||
619 | // values. | ||||
620 | if (PredecessorBlocks.size() != pred_size(BB)) | ||||
621 | return false; | ||||
622 | for (auto &Pair : HoistableBranches) { | ||||
623 | if (Pair.second == BB) { | ||||
624 | // Which blocks are predecessors via this branch depends on if the | ||||
625 | // branch is triangle-like or diamond-like. | ||||
626 | if (Pair.first->getSuccessor(0) == BB) { | ||||
627 | PredecessorBlocks.erase(Pair.first->getParent()); | ||||
628 | PredecessorBlocks.erase(Pair.first->getSuccessor(1)); | ||||
629 | } else if (Pair.first->getSuccessor(1) == BB) { | ||||
630 | PredecessorBlocks.erase(Pair.first->getParent()); | ||||
631 | PredecessorBlocks.erase(Pair.first->getSuccessor(0)); | ||||
632 | } else { | ||||
633 | PredecessorBlocks.erase(Pair.first->getSuccessor(0)); | ||||
634 | PredecessorBlocks.erase(Pair.first->getSuccessor(1)); | ||||
635 | } | ||||
636 | } | ||||
637 | } | ||||
638 | // PredecessorBlocks will now be empty if for every predecessor of BB we | ||||
639 | // found a hoistable branch source. | ||||
640 | return PredecessorBlocks.empty(); | ||||
641 | } | ||||
642 | |||||
643 | BasicBlock *getOrCreateHoistedBlock(BasicBlock *BB) { | ||||
644 | if (!ControlFlowHoisting) | ||||
645 | return CurLoop->getLoopPreheader(); | ||||
646 | // If BB has already been hoisted, return that | ||||
647 | if (HoistDestinationMap.count(BB)) | ||||
648 | return HoistDestinationMap[BB]; | ||||
649 | |||||
650 | // Check if this block is conditional based on a pending branch | ||||
651 | auto HasBBAsSuccessor = | ||||
652 | [&](DenseMap<BranchInst *, BasicBlock *>::value_type &Pair) { | ||||
653 | return BB != Pair.second && (Pair.first->getSuccessor(0) == BB || | ||||
654 | Pair.first->getSuccessor(1) == BB); | ||||
655 | }; | ||||
656 | auto It = std::find_if(HoistableBranches.begin(), HoistableBranches.end(), | ||||
657 | HasBBAsSuccessor); | ||||
658 | |||||
659 | // If not involved in a pending branch, hoist to preheader | ||||
660 | BasicBlock *InitialPreheader = CurLoop->getLoopPreheader(); | ||||
661 | if (It == HoistableBranches.end()) { | ||||
662 | 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) | ||||
663 | << " 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) | ||||
664 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("licm")) { dbgs() << "LICM using " << InitialPreheader ->getName() << " as hoist destination for " << BB->getName() << "\n"; } } while (false); | ||||
665 | HoistDestinationMap[BB] = InitialPreheader; | ||||
666 | return InitialPreheader; | ||||
667 | } | ||||
668 | BranchInst *BI = It->first; | ||||
669 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 671, __PRETTY_FUNCTION__)) | ||||
670 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 671, __PRETTY_FUNCTION__)) | ||||
671 | "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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 671, __PRETTY_FUNCTION__)); | ||||
672 | |||||
673 | LLVMContext &C = BB->getContext(); | ||||
674 | BasicBlock *TrueDest = BI->getSuccessor(0); | ||||
675 | BasicBlock *FalseDest = BI->getSuccessor(1); | ||||
676 | BasicBlock *CommonSucc = HoistableBranches[BI]; | ||||
677 | BasicBlock *HoistTarget = getOrCreateHoistedBlock(BI->getParent()); | ||||
678 | |||||
679 | // Create hoisted versions of blocks that currently don't have them | ||||
680 | auto CreateHoistedBlock = [&](BasicBlock *Orig) { | ||||
681 | if (HoistDestinationMap.count(Orig)) | ||||
682 | return HoistDestinationMap[Orig]; | ||||
683 | BasicBlock *New = | ||||
684 | BasicBlock::Create(C, Orig->getName() + ".licm", Orig->getParent()); | ||||
685 | HoistDestinationMap[Orig] = New; | ||||
686 | DT->addNewBlock(New, HoistTarget); | ||||
687 | if (CurLoop->getParentLoop()) | ||||
688 | CurLoop->getParentLoop()->addBasicBlockToLoop(New, *LI); | ||||
689 | ++NumCreatedBlocks; | ||||
690 | 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) | ||||
691 | << " 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) | ||||
692 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("licm")) { dbgs() << "LICM created " << New-> getName() << " as hoist destination for " << Orig ->getName() << "\n"; } } while (false); | ||||
693 | return New; | ||||
694 | }; | ||||
695 | BasicBlock *HoistTrueDest = CreateHoistedBlock(TrueDest); | ||||
696 | BasicBlock *HoistFalseDest = CreateHoistedBlock(FalseDest); | ||||
697 | BasicBlock *HoistCommonSucc = CreateHoistedBlock(CommonSucc); | ||||
698 | |||||
699 | // Link up these blocks with branches. | ||||
700 | if (!HoistCommonSucc->getTerminator()) { | ||||
701 | // The new common successor we've generated will branch to whatever that | ||||
702 | // hoist target branched to. | ||||
703 | BasicBlock *TargetSucc = HoistTarget->getSingleSuccessor(); | ||||
704 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 704, __PRETTY_FUNCTION__)); | ||||
705 | HoistCommonSucc->moveBefore(TargetSucc); | ||||
706 | BranchInst::Create(TargetSucc, HoistCommonSucc); | ||||
707 | } | ||||
708 | if (!HoistTrueDest->getTerminator()) { | ||||
709 | HoistTrueDest->moveBefore(HoistCommonSucc); | ||||
710 | BranchInst::Create(HoistCommonSucc, HoistTrueDest); | ||||
711 | } | ||||
712 | if (!HoistFalseDest->getTerminator()) { | ||||
713 | HoistFalseDest->moveBefore(HoistCommonSucc); | ||||
714 | BranchInst::Create(HoistCommonSucc, HoistFalseDest); | ||||
715 | } | ||||
716 | |||||
717 | // If BI is being cloned to what was originally the preheader then | ||||
718 | // HoistCommonSucc will now be the new preheader. | ||||
719 | if (HoistTarget == InitialPreheader) { | ||||
720 | // Phis in the loop header now need to use the new preheader. | ||||
721 | InitialPreheader->replaceSuccessorsPhiUsesWith(HoistCommonSucc); | ||||
722 | if (MSSAU) | ||||
723 | MSSAU->wireOldPredecessorsToNewImmediatePredecessor( | ||||
724 | HoistTarget->getSingleSuccessor(), HoistCommonSucc, {HoistTarget}); | ||||
725 | // The new preheader dominates the loop header. | ||||
726 | DomTreeNode *PreheaderNode = DT->getNode(HoistCommonSucc); | ||||
727 | DomTreeNode *HeaderNode = DT->getNode(CurLoop->getHeader()); | ||||
728 | DT->changeImmediateDominator(HeaderNode, PreheaderNode); | ||||
729 | // The preheader hoist destination is now the new preheader, with the | ||||
730 | // exception of the hoist destination of this branch. | ||||
731 | for (auto &Pair : HoistDestinationMap) | ||||
732 | if (Pair.second == InitialPreheader && Pair.first != BI->getParent()) | ||||
733 | Pair.second = HoistCommonSucc; | ||||
734 | } | ||||
735 | |||||
736 | // Now finally clone BI. | ||||
737 | ReplaceInstWithInst( | ||||
738 | HoistTarget->getTerminator(), | ||||
739 | BranchInst::Create(HoistTrueDest, HoistFalseDest, BI->getCondition())); | ||||
740 | ++NumClonedBranches; | ||||
741 | |||||
742 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 743, __PRETTY_FUNCTION__)) | ||||
743 | "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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 743, __PRETTY_FUNCTION__)); | ||||
744 | return HoistDestinationMap[BB]; | ||||
745 | } | ||||
746 | }; | ||||
747 | } // namespace | ||||
748 | |||||
749 | /// Walk the specified region of the CFG (defined by all blocks dominated by | ||||
750 | /// the specified block, and that are in the current loop) in depth first | ||||
751 | /// order w.r.t the DominatorTree. This allows us to visit definitions before | ||||
752 | /// uses, allowing us to hoist a loop body in one pass without iteration. | ||||
753 | /// | ||||
754 | bool llvm::hoistRegion(DomTreeNode *N, AAResults *AA, LoopInfo *LI, | ||||
755 | DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop, | ||||
756 | AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU, | ||||
757 | ScalarEvolution *SE, ICFLoopSafetyInfo *SafetyInfo, | ||||
758 | SinkAndHoistLICMFlags &Flags, | ||||
759 | OptimizationRemarkEmitter *ORE) { | ||||
760 | // Verify inputs. | ||||
761 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 763, __PRETTY_FUNCTION__)) | ||||
762 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 763, __PRETTY_FUNCTION__)) | ||||
763 | "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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 763, __PRETTY_FUNCTION__)); | ||||
764 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 765, __PRETTY_FUNCTION__)) | ||||
765 | "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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 765, __PRETTY_FUNCTION__)); | ||||
766 | |||||
767 | ControlFlowHoister CFH(LI, DT, CurLoop, MSSAU); | ||||
768 | |||||
769 | // Keep track of instructions that have been hoisted, as they may need to be | ||||
770 | // re-hoisted if they end up not dominating all of their uses. | ||||
771 | SmallVector<Instruction *, 16> HoistedInstructions; | ||||
772 | |||||
773 | // For PHI hoisting to work we need to hoist blocks before their successors. | ||||
774 | // We can do this by iterating through the blocks in the loop in reverse | ||||
775 | // post-order. | ||||
776 | LoopBlocksRPO Worklist(CurLoop); | ||||
777 | Worklist.perform(LI); | ||||
778 | bool Changed = false; | ||||
779 | for (BasicBlock *BB : Worklist) { | ||||
780 | // Only need to process the contents of this block if it is not part of a | ||||
781 | // subloop (which would already have been processed). | ||||
782 | if (inSubLoop(BB, CurLoop, LI)) | ||||
783 | continue; | ||||
784 | |||||
785 | for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) { | ||||
786 | Instruction &I = *II++; | ||||
787 | // Try constant folding this instruction. If all the operands are | ||||
788 | // constants, it is technically hoistable, but it would be better to | ||||
789 | // just fold it. | ||||
790 | if (Constant *C = ConstantFoldInstruction( | ||||
791 | &I, I.getModule()->getDataLayout(), TLI)) { | ||||
792 | LLVM_DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *Cdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("licm")) { dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n'; } } while (false) | ||||
793 | << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("licm")) { dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n'; } } while (false); | ||||
794 | if (CurAST) | ||||
795 | CurAST->copyValue(&I, C); | ||||
796 | // FIXME MSSA: Such replacements may make accesses unoptimized (D51960). | ||||
797 | I.replaceAllUsesWith(C); | ||||
798 | if (isInstructionTriviallyDead(&I, TLI)) | ||||
799 | eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); | ||||
800 | Changed = true; | ||||
801 | continue; | ||||
802 | } | ||||
803 | |||||
804 | // Try hoisting the instruction out to the preheader. We can only do | ||||
805 | // this if all of the operands of the instruction are loop invariant and | ||||
806 | // if it is safe to hoist the instruction. | ||||
807 | // TODO: It may be safe to hoist if we are hoisting to a conditional block | ||||
808 | // and we have accurately duplicated the control flow from the loop header | ||||
809 | // to that block. | ||||
810 | if (CurLoop->hasLoopInvariantOperands(&I) && | ||||
811 | canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, MSSAU, true, &Flags, | ||||
812 | ORE) && | ||||
813 | isSafeToExecuteUnconditionally( | ||||
814 | I, DT, CurLoop, SafetyInfo, ORE, | ||||
815 | CurLoop->getLoopPreheader()->getTerminator())) { | ||||
816 | hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo, | ||||
817 | MSSAU, SE, ORE); | ||||
818 | HoistedInstructions.push_back(&I); | ||||
819 | Changed = true; | ||||
820 | continue; | ||||
821 | } | ||||
822 | |||||
823 | // Attempt to remove floating point division out of the loop by | ||||
824 | // converting it to a reciprocal multiplication. | ||||
825 | if (I.getOpcode() == Instruction::FDiv && I.hasAllowReciprocal() && | ||||
826 | CurLoop->isLoopInvariant(I.getOperand(1))) { | ||||
827 | auto Divisor = I.getOperand(1); | ||||
828 | auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0); | ||||
829 | auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor); | ||||
830 | ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags()); | ||||
831 | SafetyInfo->insertInstructionTo(ReciprocalDivisor, I.getParent()); | ||||
832 | ReciprocalDivisor->insertBefore(&I); | ||||
833 | |||||
834 | auto Product = | ||||
835 | BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor); | ||||
836 | Product->setFastMathFlags(I.getFastMathFlags()); | ||||
837 | SafetyInfo->insertInstructionTo(Product, I.getParent()); | ||||
838 | Product->insertAfter(&I); | ||||
839 | I.replaceAllUsesWith(Product); | ||||
840 | eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); | ||||
841 | |||||
842 | hoist(*ReciprocalDivisor, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), | ||||
843 | SafetyInfo, MSSAU, SE, ORE); | ||||
844 | HoistedInstructions.push_back(ReciprocalDivisor); | ||||
845 | Changed = true; | ||||
846 | continue; | ||||
847 | } | ||||
848 | |||||
849 | auto IsInvariantStart = [&](Instruction &I) { | ||||
850 | using namespace PatternMatch; | ||||
851 | return I.use_empty() && | ||||
852 | match(&I, m_Intrinsic<Intrinsic::invariant_start>()); | ||||
853 | }; | ||||
854 | auto MustExecuteWithoutWritesBefore = [&](Instruction &I) { | ||||
855 | return SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop) && | ||||
856 | SafetyInfo->doesNotWriteMemoryBefore(I, CurLoop); | ||||
857 | }; | ||||
858 | if ((IsInvariantStart(I) || isGuard(&I)) && | ||||
859 | CurLoop->hasLoopInvariantOperands(&I) && | ||||
860 | MustExecuteWithoutWritesBefore(I)) { | ||||
861 | hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo, | ||||
862 | MSSAU, SE, ORE); | ||||
863 | HoistedInstructions.push_back(&I); | ||||
864 | Changed = true; | ||||
865 | continue; | ||||
866 | } | ||||
867 | |||||
868 | if (PHINode *PN = dyn_cast<PHINode>(&I)) { | ||||
869 | if (CFH.canHoistPHI(PN)) { | ||||
870 | // Redirect incoming blocks first to ensure that we create hoisted | ||||
871 | // versions of those blocks before we hoist the phi. | ||||
872 | for (unsigned int i = 0; i < PN->getNumIncomingValues(); ++i) | ||||
873 | PN->setIncomingBlock( | ||||
874 | i, CFH.getOrCreateHoistedBlock(PN->getIncomingBlock(i))); | ||||
875 | hoist(*PN, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo, | ||||
876 | MSSAU, SE, ORE); | ||||
877 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 877, __PRETTY_FUNCTION__)); | ||||
878 | Changed = true; | ||||
879 | continue; | ||||
880 | } | ||||
881 | } | ||||
882 | |||||
883 | // Remember possibly hoistable branches so we can actually hoist them | ||||
884 | // later if needed. | ||||
885 | if (BranchInst *BI = dyn_cast<BranchInst>(&I)) | ||||
886 | CFH.registerPossiblyHoistableBranch(BI); | ||||
887 | } | ||||
888 | } | ||||
889 | |||||
890 | // If we hoisted instructions to a conditional block they may not dominate | ||||
891 | // their uses that weren't hoisted (such as phis where some operands are not | ||||
892 | // loop invariant). If so make them unconditional by moving them to their | ||||
893 | // immediate dominator. We iterate through the instructions in reverse order | ||||
894 | // which ensures that when we rehoist an instruction we rehoist its operands, | ||||
895 | // and also keep track of where in the block we are rehoisting to to make sure | ||||
896 | // that we rehoist instructions before the instructions that use them. | ||||
897 | Instruction *HoistPoint = nullptr; | ||||
898 | if (ControlFlowHoisting) { | ||||
899 | for (Instruction *I : reverse(HoistedInstructions)) { | ||||
900 | if (!llvm::all_of(I->uses(), | ||||
901 | [&](Use &U) { return DT->dominates(I, U); })) { | ||||
902 | BasicBlock *Dominator = | ||||
903 | DT->getNode(I->getParent())->getIDom()->getBlock(); | ||||
904 | if (!HoistPoint || !DT->dominates(HoistPoint->getParent(), Dominator)) { | ||||
905 | if (HoistPoint) | ||||
906 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 907, __PRETTY_FUNCTION__)) | ||||
907 | "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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 907, __PRETTY_FUNCTION__)); | ||||
908 | HoistPoint = Dominator->getTerminator(); | ||||
909 | } | ||||
910 | LLVM_DEBUG(dbgs() << "LICM rehoisting to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("licm")) { dbgs() << "LICM rehoisting to " << HoistPoint ->getParent()->getName() << ": " << *I << "\n"; } } while (false) | ||||
911 | << HoistPoint->getParent()->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("licm")) { dbgs() << "LICM rehoisting to " << HoistPoint ->getParent()->getName() << ": " << *I << "\n"; } } while (false) | ||||
912 | << ": " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("licm")) { dbgs() << "LICM rehoisting to " << HoistPoint ->getParent()->getName() << ": " << *I << "\n"; } } while (false); | ||||
913 | moveInstructionBefore(*I, *HoistPoint, *SafetyInfo, MSSAU, SE); | ||||
914 | HoistPoint = I; | ||||
915 | Changed = true; | ||||
916 | } | ||||
917 | } | ||||
918 | } | ||||
919 | if (MSSAU && VerifyMemorySSA) | ||||
920 | MSSAU->getMemorySSA()->verifyMemorySSA(); | ||||
921 | |||||
922 | // Now that we've finished hoisting make sure that LI and DT are still | ||||
923 | // valid. | ||||
924 | #ifdef EXPENSIVE_CHECKS | ||||
925 | if (Changed) { | ||||
926 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 927, __PRETTY_FUNCTION__)) | ||||
927 | "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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 927, __PRETTY_FUNCTION__)); | ||||
928 | LI->verify(*DT); | ||||
929 | } | ||||
930 | #endif | ||||
931 | |||||
932 | return Changed; | ||||
933 | } | ||||
934 | |||||
935 | // Return true if LI is invariant within scope of the loop. LI is invariant if | ||||
936 | // CurLoop is dominated by an invariant.start representing the same memory | ||||
937 | // location and size as the memory location LI loads from, and also the | ||||
938 | // invariant.start has no uses. | ||||
939 | static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT, | ||||
940 | Loop *CurLoop) { | ||||
941 | Value *Addr = LI->getOperand(0); | ||||
942 | const DataLayout &DL = LI->getModule()->getDataLayout(); | ||||
943 | const uint32_t LocSizeInBits = DL.getTypeSizeInBits(LI->getType()); | ||||
944 | |||||
945 | // if the type is i8 addrspace(x)*, we know this is the type of | ||||
946 | // llvm.invariant.start operand | ||||
947 | auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()), | ||||
948 | LI->getPointerAddressSpace()); | ||||
949 | unsigned BitcastsVisited = 0; | ||||
950 | // Look through bitcasts until we reach the i8* type (this is invariant.start | ||||
951 | // operand type). | ||||
952 | while (Addr->getType() != PtrInt8Ty) { | ||||
953 | auto *BC = dyn_cast<BitCastInst>(Addr); | ||||
954 | // Avoid traversing high number of bitcast uses. | ||||
955 | if (++BitcastsVisited > MaxNumUsesTraversed || !BC) | ||||
956 | return false; | ||||
957 | Addr = BC->getOperand(0); | ||||
958 | } | ||||
959 | |||||
960 | unsigned UsesVisited = 0; | ||||
961 | // Traverse all uses of the load operand value, to see if invariant.start is | ||||
962 | // one of the uses, and whether it dominates the load instruction. | ||||
963 | for (auto *U : Addr->users()) { | ||||
964 | // Avoid traversing for Load operand with high number of users. | ||||
965 | if (++UsesVisited > MaxNumUsesTraversed) | ||||
966 | return false; | ||||
967 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(U); | ||||
968 | // If there are escaping uses of invariant.start instruction, the load maybe | ||||
969 | // non-invariant. | ||||
970 | if (!II || II->getIntrinsicID() != Intrinsic::invariant_start || | ||||
971 | !II->use_empty()) | ||||
972 | continue; | ||||
973 | unsigned InvariantSizeInBits = | ||||
974 | cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8; | ||||
975 | // Confirm the invariant.start location size contains the load operand size | ||||
976 | // in bits. Also, the invariant.start should dominate the load, and we | ||||
977 | // should not hoist the load out of a loop that contains this dominating | ||||
978 | // invariant.start. | ||||
979 | if (LocSizeInBits <= InvariantSizeInBits && | ||||
980 | DT->properlyDominates(II->getParent(), CurLoop->getHeader())) | ||||
981 | return true; | ||||
982 | } | ||||
983 | |||||
984 | return false; | ||||
985 | } | ||||
986 | |||||
987 | namespace { | ||||
988 | /// Return true if-and-only-if we know how to (mechanically) both hoist and | ||||
989 | /// sink a given instruction out of a loop. Does not address legality | ||||
990 | /// concerns such as aliasing or speculation safety. | ||||
991 | bool isHoistableAndSinkableInst(Instruction &I) { | ||||
992 | // Only these instructions are hoistable/sinkable. | ||||
993 | return (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) || | ||||
994 | isa<FenceInst>(I) || isa<CastInst>(I) || isa<UnaryOperator>(I) || | ||||
995 | isa<BinaryOperator>(I) || isa<SelectInst>(I) || | ||||
996 | isa<GetElementPtrInst>(I) || isa<CmpInst>(I) || | ||||
997 | isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) || | ||||
998 | isa<ShuffleVectorInst>(I) || isa<ExtractValueInst>(I) || | ||||
999 | isa<InsertValueInst>(I) || isa<FreezeInst>(I)); | ||||
1000 | } | ||||
1001 | /// Return true if all of the alias sets within this AST are known not to | ||||
1002 | /// contain a Mod, or if MSSA knows thare are no MemoryDefs in the loop. | ||||
1003 | bool isReadOnly(AliasSetTracker *CurAST, const MemorySSAUpdater *MSSAU, | ||||
1004 | const Loop *L) { | ||||
1005 | if (CurAST) { | ||||
1006 | for (AliasSet &AS : *CurAST) { | ||||
1007 | if (!AS.isForwardingAliasSet() && AS.isMod()) { | ||||
1008 | return false; | ||||
1009 | } | ||||
1010 | } | ||||
1011 | return true; | ||||
1012 | } else { /*MSSAU*/ | ||||
1013 | for (auto *BB : L->getBlocks()) | ||||
1014 | if (MSSAU->getMemorySSA()->getBlockDefs(BB)) | ||||
1015 | return false; | ||||
1016 | return true; | ||||
1017 | } | ||||
1018 | } | ||||
1019 | |||||
1020 | /// Return true if I is the only Instruction with a MemoryAccess in L. | ||||
1021 | bool isOnlyMemoryAccess(const Instruction *I, const Loop *L, | ||||
1022 | const MemorySSAUpdater *MSSAU) { | ||||
1023 | for (auto *BB : L->getBlocks()) | ||||
1024 | if (auto *Accs = MSSAU->getMemorySSA()->getBlockAccesses(BB)) { | ||||
1025 | int NotAPhi = 0; | ||||
1026 | for (const auto &Acc : *Accs) { | ||||
1027 | if (isa<MemoryPhi>(&Acc)) | ||||
1028 | continue; | ||||
1029 | const auto *MUD = cast<MemoryUseOrDef>(&Acc); | ||||
1030 | if (MUD->getMemoryInst() != I || NotAPhi++ == 1) | ||||
1031 | return false; | ||||
1032 | } | ||||
1033 | } | ||||
1034 | return true; | ||||
1035 | } | ||||
1036 | } | ||||
1037 | |||||
1038 | bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT, | ||||
1039 | Loop *CurLoop, AliasSetTracker *CurAST, | ||||
1040 | MemorySSAUpdater *MSSAU, | ||||
1041 | bool TargetExecutesOncePerLoop, | ||||
1042 | SinkAndHoistLICMFlags *Flags, | ||||
1043 | OptimizationRemarkEmitter *ORE) { | ||||
1044 | // If we don't understand the instruction, bail early. | ||||
1045 | if (!isHoistableAndSinkableInst(I)) | ||||
| |||||
1046 | return false; | ||||
1047 | |||||
1048 | MemorySSA *MSSA = MSSAU ? MSSAU->getMemorySSA() : nullptr; | ||||
1049 | if (MSSA) | ||||
1050 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1050, __PRETTY_FUNCTION__)); | ||||
1051 | |||||
1052 | // Loads have extra constraints we have to verify before we can hoist them. | ||||
1053 | if (LoadInst *LI
| ||||
1054 | if (!LI->isUnordered()) | ||||
1055 | return false; // Don't sink/hoist volatile or ordered atomic loads! | ||||
1056 | |||||
1057 | // Loads from constant memory are always safe to move, even if they end up | ||||
1058 | // in the same alias set as something that ends up being modified. | ||||
1059 | if (AA->pointsToConstantMemory(LI->getOperand(0))) | ||||
1060 | return true; | ||||
1061 | if (LI->hasMetadata(LLVMContext::MD_invariant_load)) | ||||
1062 | return true; | ||||
1063 | |||||
1064 | if (LI->isAtomic() && !TargetExecutesOncePerLoop) | ||||
1065 | return false; // Don't risk duplicating unordered loads | ||||
1066 | |||||
1067 | // This checks for an invariant.start dominating the load. | ||||
1068 | if (isLoadInvariantInLoop(LI, DT, CurLoop)) | ||||
1069 | return true; | ||||
1070 | |||||
1071 | bool Invalidated; | ||||
1072 | if (CurAST) | ||||
1073 | Invalidated = pointerInvalidatedByLoop(MemoryLocation::get(LI), CurAST, | ||||
1074 | CurLoop, AA); | ||||
1075 | else | ||||
1076 | Invalidated = pointerInvalidatedByLoopWithMSSA( | ||||
1077 | MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(LI)), CurLoop, *Flags); | ||||
1078 | // Check loop-invariant address because this may also be a sinkable load | ||||
1079 | // whose address is not necessarily loop-invariant. | ||||
1080 | if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand())) | ||||
1081 | ORE->emit([&]() { | ||||
1082 | return OptimizationRemarkMissed( | ||||
1083 | DEBUG_TYPE"licm", "LoadWithLoopInvariantAddressInvalidated", LI) | ||||
1084 | << "failed to move load with loop-invariant address " | ||||
1085 | "because the loop may invalidate its value"; | ||||
1086 | }); | ||||
1087 | |||||
1088 | return !Invalidated; | ||||
1089 | } else if (CallInst *CI
| ||||
1090 | // Don't sink or hoist dbg info; it's legal, but not useful. | ||||
1091 | if (isa<DbgInfoIntrinsic>(I)) | ||||
1092 | return false; | ||||
1093 | |||||
1094 | // Don't sink calls which can throw. | ||||
1095 | if (CI->mayThrow()) | ||||
1096 | return false; | ||||
1097 | |||||
1098 | using namespace PatternMatch; | ||||
1099 | if (match(CI, m_Intrinsic<Intrinsic::assume>())) | ||||
1100 | // Assumes don't actually alias anything or throw | ||||
1101 | return true; | ||||
1102 | |||||
1103 | if (match(CI, m_Intrinsic<Intrinsic::experimental_widenable_condition>())) | ||||
1104 | // Widenable conditions don't actually alias anything or throw | ||||
1105 | return true; | ||||
1106 | |||||
1107 | // Handle simple cases by querying alias analysis. | ||||
1108 | FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI); | ||||
1109 | if (Behavior == FMRB_DoesNotAccessMemory) | ||||
1110 | return true; | ||||
1111 | if (AAResults::onlyReadsMemory(Behavior)) { | ||||
1112 | // A readonly argmemonly function only reads from memory pointed to by | ||||
1113 | // it's arguments with arbitrary offsets. If we can prove there are no | ||||
1114 | // writes to this memory in the loop, we can hoist or sink. | ||||
1115 | if (AAResults::onlyAccessesArgPointees(Behavior)) { | ||||
1116 | // TODO: expand to writeable arguments | ||||
1117 | for (Value *Op : CI->arg_operands()) | ||||
1118 | if (Op->getType()->isPointerTy()) { | ||||
1119 | bool Invalidated; | ||||
1120 | if (CurAST) | ||||
1121 | Invalidated = pointerInvalidatedByLoop( | ||||
1122 | MemoryLocation(Op, LocationSize::unknown(), AAMDNodes()), | ||||
1123 | CurAST, CurLoop, AA); | ||||
1124 | else | ||||
1125 | Invalidated = pointerInvalidatedByLoopWithMSSA( | ||||
1126 | MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(CI)), CurLoop, | ||||
1127 | *Flags); | ||||
1128 | if (Invalidated) | ||||
1129 | return false; | ||||
1130 | } | ||||
1131 | return true; | ||||
1132 | } | ||||
1133 | |||||
1134 | // If this call only reads from memory and there are no writes to memory | ||||
1135 | // in the loop, we can hoist or sink the call as appropriate. | ||||
1136 | if (isReadOnly(CurAST, MSSAU, CurLoop)) | ||||
1137 | return true; | ||||
1138 | } | ||||
1139 | |||||
1140 | // FIXME: This should use mod/ref information to see if we can hoist or | ||||
1141 | // sink the call. | ||||
1142 | |||||
1143 | return false; | ||||
1144 | } else if (auto *FI
| ||||
1145 | // Fences alias (most) everything to provide ordering. For the moment, | ||||
1146 | // just give up if there are any other memory operations in the loop. | ||||
1147 | if (CurAST) { | ||||
1148 | auto Begin = CurAST->begin(); | ||||
1149 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1149, __PRETTY_FUNCTION__)); | ||||
1150 | if (std::next(Begin) != CurAST->end()) | ||||
1151 | // constant memory for instance, TODO: handle better | ||||
1152 | return false; | ||||
1153 | auto *UniqueI = Begin->getUniqueInstruction(); | ||||
1154 | if (!UniqueI) | ||||
1155 | // other memory op, give up | ||||
1156 | return false; | ||||
1157 | (void)FI; // suppress unused variable warning | ||||
1158 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1158, __PRETTY_FUNCTION__)); | ||||
1159 | return true; | ||||
1160 | } else // MSSAU | ||||
1161 | return isOnlyMemoryAccess(FI, CurLoop, MSSAU); | ||||
1162 | } else if (auto *SI
| ||||
1163 | if (!SI->isUnordered()) | ||||
1164 | return false; // Don't sink/hoist volatile or ordered atomic store! | ||||
1165 | |||||
1166 | // We can only hoist a store that we can prove writes a value which is not | ||||
1167 | // read or overwritten within the loop. For those cases, we fallback to | ||||
1168 | // load store promotion instead. TODO: We can extend this to cases where | ||||
1169 | // there is exactly one write to the location and that write dominates an | ||||
1170 | // arbitrary number of reads in the loop. | ||||
1171 | if (CurAST) { | ||||
1172 | auto &AS = CurAST->getAliasSetFor(MemoryLocation::get(SI)); | ||||
1173 | |||||
1174 | if (AS.isRef() || !AS.isMustAlias()) | ||||
1175 | // Quick exit test, handled by the full path below as well. | ||||
1176 | return false; | ||||
1177 | auto *UniqueI = AS.getUniqueInstruction(); | ||||
1178 | if (!UniqueI) | ||||
1179 | // other memory op, give up | ||||
1180 | return false; | ||||
1181 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1181, __PRETTY_FUNCTION__)); | ||||
1182 | return true; | ||||
1183 | } else { // MSSAU | ||||
1184 | if (isOnlyMemoryAccess(SI, CurLoop, MSSAU)) | ||||
1185 | return true; | ||||
1186 | // If there are more accesses than the Promotion cap, give up, we're not | ||||
1187 | // walking a list that long. | ||||
1188 | if (Flags->NoOfMemAccTooLarge) | ||||
1189 | return false; | ||||
1190 | // Check store only if there's still "quota" to check clobber. | ||||
1191 | if (Flags->LicmMssaOptCounter >= Flags->LicmMssaOptCap) | ||||
1192 | return false; | ||||
1193 | // If there are interfering Uses (i.e. their defining access is in the | ||||
1194 | // loop), or ordered loads (stored as Defs!), don't move this store. | ||||
1195 | // Could do better here, but this is conservatively correct. | ||||
1196 | // TODO: Cache set of Uses on the first walk in runOnLoop, update when | ||||
1197 | // moving accesses. Can also extend to dominating uses. | ||||
1198 | auto *SIMD = MSSA->getMemoryAccess(SI); | ||||
| |||||
1199 | for (auto *BB : CurLoop->getBlocks()) | ||||
1200 | if (auto *Accesses = MSSA->getBlockAccesses(BB)) { | ||||
1201 | for (const auto &MA : *Accesses) | ||||
1202 | if (const auto *MU = dyn_cast<MemoryUse>(&MA)) { | ||||
1203 | auto *MD = MU->getDefiningAccess(); | ||||
1204 | if (!MSSA->isLiveOnEntryDef(MD) && | ||||
1205 | CurLoop->contains(MD->getBlock())) | ||||
1206 | return false; | ||||
1207 | // Disable hoisting past potentially interfering loads. Optimized | ||||
1208 | // Uses may point to an access outside the loop, as getClobbering | ||||
1209 | // checks the previous iteration when walking the backedge. | ||||
1210 | // FIXME: More precise: no Uses that alias SI. | ||||
1211 | if (!Flags->IsSink && !MSSA->dominates(SIMD, MU)) | ||||
1212 | return false; | ||||
1213 | } else if (const auto *MD = dyn_cast<MemoryDef>(&MA)) { | ||||
1214 | if (auto *LI = dyn_cast<LoadInst>(MD->getMemoryInst())) { | ||||
1215 | (void)LI; // Silence warning. | ||||
1216 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1216, __PRETTY_FUNCTION__)); | ||||
1217 | return false; | ||||
1218 | } | ||||
1219 | // Any call, while it may not be clobbering SI, it may be a use. | ||||
1220 | if (auto *CI = dyn_cast<CallInst>(MD->getMemoryInst())) { | ||||
1221 | // Check if the call may read from the memory locattion written | ||||
1222 | // to by SI. Check CI's attributes and arguments; the number of | ||||
1223 | // such checks performed is limited above by NoOfMemAccTooLarge. | ||||
1224 | ModRefInfo MRI = AA->getModRefInfo(CI, MemoryLocation::get(SI)); | ||||
1225 | if (isModOrRefSet(MRI)) | ||||
1226 | return false; | ||||
1227 | } | ||||
1228 | } | ||||
1229 | } | ||||
1230 | |||||
1231 | auto *Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(SI); | ||||
1232 | Flags->LicmMssaOptCounter++; | ||||
1233 | // If there are no clobbering Defs in the loop, store is safe to hoist. | ||||
1234 | return MSSA->isLiveOnEntryDef(Source) || | ||||
1235 | !CurLoop->contains(Source->getBlock()); | ||||
1236 | } | ||||
1237 | } | ||||
1238 | |||||
1239 | assert(!I.mayReadOrWriteMemory() && "unhandled aliasing")((!I.mayReadOrWriteMemory() && "unhandled aliasing") ? static_cast<void> (0) : __assert_fail ("!I.mayReadOrWriteMemory() && \"unhandled aliasing\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1239, __PRETTY_FUNCTION__)); | ||||
1240 | |||||
1241 | // We've established mechanical ability and aliasing, it's up to the caller | ||||
1242 | // to check fault safety | ||||
1243 | return true; | ||||
1244 | } | ||||
1245 | |||||
1246 | /// Returns true if a PHINode is a trivially replaceable with an | ||||
1247 | /// Instruction. | ||||
1248 | /// This is true when all incoming values are that instruction. | ||||
1249 | /// This pattern occurs most often with LCSSA PHI nodes. | ||||
1250 | /// | ||||
1251 | static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) { | ||||
1252 | for (const Value *IncValue : PN.incoming_values()) | ||||
1253 | if (IncValue != &I) | ||||
1254 | return false; | ||||
1255 | |||||
1256 | return true; | ||||
1257 | } | ||||
1258 | |||||
1259 | /// Return true if the instruction is free in the loop. | ||||
1260 | static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop, | ||||
1261 | const TargetTransformInfo *TTI) { | ||||
1262 | |||||
1263 | if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) { | ||||
1264 | if (TTI->getUserCost(GEP, TargetTransformInfo::TCK_SizeAndLatency) != | ||||
1265 | TargetTransformInfo::TCC_Free) | ||||
1266 | return false; | ||||
1267 | // For a GEP, we cannot simply use getUserCost because currently it | ||||
1268 | // optimistically assume that a GEP will fold into addressing mode | ||||
1269 | // regardless of its users. | ||||
1270 | const BasicBlock *BB = GEP->getParent(); | ||||
1271 | for (const User *U : GEP->users()) { | ||||
1272 | const Instruction *UI = cast<Instruction>(U); | ||||
1273 | if (CurLoop->contains(UI) && | ||||
1274 | (BB != UI->getParent() || | ||||
1275 | (!isa<StoreInst>(UI) && !isa<LoadInst>(UI)))) | ||||
1276 | return false; | ||||
1277 | } | ||||
1278 | return true; | ||||
1279 | } else | ||||
1280 | return TTI->getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) == | ||||
1281 | TargetTransformInfo::TCC_Free; | ||||
1282 | } | ||||
1283 | |||||
1284 | /// Return true if the only users of this instruction are outside of | ||||
1285 | /// the loop. If this is true, we can sink the instruction to the exit | ||||
1286 | /// blocks of the loop. | ||||
1287 | /// | ||||
1288 | /// We also return true if the instruction could be folded away in lowering. | ||||
1289 | /// (e.g., a GEP can be folded into a load as an addressing mode in the loop). | ||||
1290 | static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop, | ||||
1291 | const LoopSafetyInfo *SafetyInfo, | ||||
1292 | TargetTransformInfo *TTI, bool &FreeInLoop) { | ||||
1293 | const auto &BlockColors = SafetyInfo->getBlockColors(); | ||||
1294 | bool IsFree = isFreeInLoop(I, CurLoop, TTI); | ||||
1295 | for (const User *U : I.users()) { | ||||
1296 | const Instruction *UI = cast<Instruction>(U); | ||||
1297 | if (const PHINode *PN = dyn_cast<PHINode>(UI)) { | ||||
1298 | const BasicBlock *BB = PN->getParent(); | ||||
1299 | // We cannot sink uses in catchswitches. | ||||
1300 | if (isa<CatchSwitchInst>(BB->getTerminator())) | ||||
1301 | return false; | ||||
1302 | |||||
1303 | // We need to sink a callsite to a unique funclet. Avoid sinking if the | ||||
1304 | // phi use is too muddled. | ||||
1305 | if (isa<CallInst>(I)) | ||||
1306 | if (!BlockColors.empty() && | ||||
1307 | BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1) | ||||
1308 | return false; | ||||
1309 | } | ||||
1310 | |||||
1311 | if (CurLoop->contains(UI)) { | ||||
1312 | if (IsFree) { | ||||
1313 | FreeInLoop = true; | ||||
1314 | continue; | ||||
1315 | } | ||||
1316 | return false; | ||||
1317 | } | ||||
1318 | } | ||||
1319 | return true; | ||||
1320 | } | ||||
1321 | |||||
1322 | static Instruction *cloneInstructionInExitBlock( | ||||
1323 | Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI, | ||||
1324 | const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU) { | ||||
1325 | Instruction *New; | ||||
1326 | if (auto *CI = dyn_cast<CallInst>(&I)) { | ||||
1327 | const auto &BlockColors = SafetyInfo->getBlockColors(); | ||||
1328 | |||||
1329 | // Sinking call-sites need to be handled differently from other | ||||
1330 | // instructions. The cloned call-site needs a funclet bundle operand | ||||
1331 | // appropriate for its location in the CFG. | ||||
1332 | SmallVector<OperandBundleDef, 1> OpBundles; | ||||
1333 | for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles(); | ||||
1334 | BundleIdx != BundleEnd; ++BundleIdx) { | ||||
1335 | OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx); | ||||
1336 | if (Bundle.getTagID() == LLVMContext::OB_funclet) | ||||
1337 | continue; | ||||
1338 | |||||
1339 | OpBundles.emplace_back(Bundle); | ||||
1340 | } | ||||
1341 | |||||
1342 | if (!BlockColors.empty()) { | ||||
1343 | const ColorVector &CV = BlockColors.find(&ExitBlock)->second; | ||||
1344 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1344, __PRETTY_FUNCTION__)); | ||||
1345 | BasicBlock *BBColor = CV.front(); | ||||
1346 | Instruction *EHPad = BBColor->getFirstNonPHI(); | ||||
1347 | if (EHPad->isEHPad()) | ||||
1348 | OpBundles.emplace_back("funclet", EHPad); | ||||
1349 | } | ||||
1350 | |||||
1351 | New = CallInst::Create(CI, OpBundles); | ||||
1352 | } else { | ||||
1353 | New = I.clone(); | ||||
1354 | } | ||||
1355 | |||||
1356 | ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New); | ||||
1357 | if (!I.getName().empty()) | ||||
1358 | New->setName(I.getName() + ".le"); | ||||
1359 | |||||
1360 | if (MSSAU && MSSAU->getMemorySSA()->getMemoryAccess(&I)) { | ||||
1361 | // Create a new MemoryAccess and let MemorySSA set its defining access. | ||||
1362 | MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB( | ||||
1363 | New, nullptr, New->getParent(), MemorySSA::Beginning); | ||||
1364 | if (NewMemAcc) { | ||||
1365 | if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc)) | ||||
1366 | MSSAU->insertDef(MemDef, /*RenameUses=*/true); | ||||
1367 | else { | ||||
1368 | auto *MemUse = cast<MemoryUse>(NewMemAcc); | ||||
1369 | MSSAU->insertUse(MemUse, /*RenameUses=*/true); | ||||
1370 | } | ||||
1371 | } | ||||
1372 | } | ||||
1373 | |||||
1374 | // Build LCSSA PHI nodes for any in-loop operands. Note that this is | ||||
1375 | // particularly cheap because we can rip off the PHI node that we're | ||||
1376 | // replacing for the number and blocks of the predecessors. | ||||
1377 | // OPT: If this shows up in a profile, we can instead finish sinking all | ||||
1378 | // invariant instructions, and then walk their operands to re-establish | ||||
1379 | // LCSSA. That will eliminate creating PHI nodes just to nuke them when | ||||
1380 | // sinking bottom-up. | ||||
1381 | for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE; | ||||
1382 | ++OI) | ||||
1383 | if (Instruction *OInst = dyn_cast<Instruction>(*OI)) | ||||
1384 | if (Loop *OLoop = LI->getLoopFor(OInst->getParent())) | ||||
1385 | if (!OLoop->contains(&PN)) { | ||||
1386 | PHINode *OpPN = | ||||
1387 | PHINode::Create(OInst->getType(), PN.getNumIncomingValues(), | ||||
1388 | OInst->getName() + ".lcssa", &ExitBlock.front()); | ||||
1389 | for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) | ||||
1390 | OpPN->addIncoming(OInst, PN.getIncomingBlock(i)); | ||||
1391 | *OI = OpPN; | ||||
1392 | } | ||||
1393 | return New; | ||||
1394 | } | ||||
1395 | |||||
1396 | static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, | ||||
1397 | AliasSetTracker *AST, MemorySSAUpdater *MSSAU) { | ||||
1398 | if (AST) | ||||
1399 | AST->deleteValue(&I); | ||||
1400 | if (MSSAU) | ||||
1401 | MSSAU->removeMemoryAccess(&I); | ||||
1402 | SafetyInfo.removeInstruction(&I); | ||||
1403 | I.eraseFromParent(); | ||||
1404 | } | ||||
1405 | |||||
1406 | static void moveInstructionBefore(Instruction &I, Instruction &Dest, | ||||
1407 | ICFLoopSafetyInfo &SafetyInfo, | ||||
1408 | MemorySSAUpdater *MSSAU, | ||||
1409 | ScalarEvolution *SE) { | ||||
1410 | SafetyInfo.removeInstruction(&I); | ||||
1411 | SafetyInfo.insertInstructionTo(&I, Dest.getParent()); | ||||
1412 | I.moveBefore(&Dest); | ||||
1413 | if (MSSAU) | ||||
1414 | if (MemoryUseOrDef *OldMemAcc = cast_or_null<MemoryUseOrDef>( | ||||
1415 | MSSAU->getMemorySSA()->getMemoryAccess(&I))) | ||||
1416 | MSSAU->moveToPlace(OldMemAcc, Dest.getParent(), | ||||
1417 | MemorySSA::BeforeTerminator); | ||||
1418 | if (SE) | ||||
1419 | SE->forgetValue(&I); | ||||
1420 | } | ||||
1421 | |||||
1422 | static Instruction *sinkThroughTriviallyReplaceablePHI( | ||||
1423 | PHINode *TPN, Instruction *I, LoopInfo *LI, | ||||
1424 | SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies, | ||||
1425 | const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop, | ||||
1426 | MemorySSAUpdater *MSSAU) { | ||||
1427 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1428, __PRETTY_FUNCTION__)) | ||||
1428 | "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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1428, __PRETTY_FUNCTION__)); | ||||
1429 | BasicBlock *ExitBlock = TPN->getParent(); | ||||
1430 | Instruction *New; | ||||
1431 | auto It = SunkCopies.find(ExitBlock); | ||||
1432 | if (It != SunkCopies.end()) | ||||
1433 | New = It->second; | ||||
1434 | else | ||||
1435 | New = SunkCopies[ExitBlock] = cloneInstructionInExitBlock( | ||||
1436 | *I, *ExitBlock, *TPN, LI, SafetyInfo, MSSAU); | ||||
1437 | return New; | ||||
1438 | } | ||||
1439 | |||||
1440 | static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) { | ||||
1441 | BasicBlock *BB = PN->getParent(); | ||||
1442 | if (!BB->canSplitPredecessors()) | ||||
1443 | return false; | ||||
1444 | // It's not impossible to split EHPad blocks, but if BlockColors already exist | ||||
1445 | // it require updating BlockColors for all offspring blocks accordingly. By | ||||
1446 | // skipping such corner case, we can make updating BlockColors after splitting | ||||
1447 | // predecessor fairly simple. | ||||
1448 | if (!SafetyInfo->getBlockColors().empty() && BB->getFirstNonPHI()->isEHPad()) | ||||
1449 | return false; | ||||
1450 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { | ||||
1451 | BasicBlock *BBPred = *PI; | ||||
1452 | if (isa<IndirectBrInst>(BBPred->getTerminator()) || | ||||
1453 | isa<CallBrInst>(BBPred->getTerminator())) | ||||
1454 | return false; | ||||
1455 | } | ||||
1456 | return true; | ||||
1457 | } | ||||
1458 | |||||
1459 | static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT, | ||||
1460 | LoopInfo *LI, const Loop *CurLoop, | ||||
1461 | LoopSafetyInfo *SafetyInfo, | ||||
1462 | MemorySSAUpdater *MSSAU) { | ||||
1463 | #ifndef NDEBUG | ||||
1464 | SmallVector<BasicBlock *, 32> ExitBlocks; | ||||
1465 | CurLoop->getUniqueExitBlocks(ExitBlocks); | ||||
1466 | SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(), | ||||
1467 | ExitBlocks.end()); | ||||
1468 | #endif | ||||
1469 | BasicBlock *ExitBB = PN->getParent(); | ||||
1470 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1470, __PRETTY_FUNCTION__)); | ||||
1471 | |||||
1472 | // Split predecessors of the loop exit to make instructions in the loop are | ||||
1473 | // exposed to exit blocks through trivially replaceable PHIs while keeping the | ||||
1474 | // loop in the canonical form where each predecessor of each exit block should | ||||
1475 | // be contained within the loop. For example, this will convert the loop below | ||||
1476 | // from | ||||
1477 | // | ||||
1478 | // LB1: | ||||
1479 | // %v1 = | ||||
1480 | // br %LE, %LB2 | ||||
1481 | // LB2: | ||||
1482 | // %v2 = | ||||
1483 | // br %LE, %LB1 | ||||
1484 | // LE: | ||||
1485 | // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable | ||||
1486 | // | ||||
1487 | // to | ||||
1488 | // | ||||
1489 | // LB1: | ||||
1490 | // %v1 = | ||||
1491 | // br %LE.split, %LB2 | ||||
1492 | // LB2: | ||||
1493 | // %v2 = | ||||
1494 | // br %LE.split2, %LB1 | ||||
1495 | // LE.split: | ||||
1496 | // %p1 = phi [%v1, %LB1] <-- trivially replaceable | ||||
1497 | // br %LE | ||||
1498 | // LE.split2: | ||||
1499 | // %p2 = phi [%v2, %LB2] <-- trivially replaceable | ||||
1500 | // br %LE | ||||
1501 | // LE: | ||||
1502 | // %p = phi [%p1, %LE.split], [%p2, %LE.split2] | ||||
1503 | // | ||||
1504 | const auto &BlockColors = SafetyInfo->getBlockColors(); | ||||
1505 | SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB)); | ||||
1506 | while (!PredBBs.empty()) { | ||||
1507 | BasicBlock *PredBB = *PredBBs.begin(); | ||||
1508 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1509, __PRETTY_FUNCTION__)) | ||||
1509 | "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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1509, __PRETTY_FUNCTION__)); | ||||
1510 | if (PN->getBasicBlockIndex(PredBB) >= 0) { | ||||
1511 | BasicBlock *NewPred = SplitBlockPredecessors( | ||||
1512 | ExitBB, PredBB, ".split.loop.exit", DT, LI, MSSAU, true); | ||||
1513 | // Since we do not allow splitting EH-block with BlockColors in | ||||
1514 | // canSplitPredecessors(), we can simply assign predecessor's color to | ||||
1515 | // the new block. | ||||
1516 | if (!BlockColors.empty()) | ||||
1517 | // Grab a reference to the ColorVector to be inserted before getting the | ||||
1518 | // reference to the vector we are copying because inserting the new | ||||
1519 | // element in BlockColors might cause the map to be reallocated. | ||||
1520 | SafetyInfo->copyColors(NewPred, PredBB); | ||||
1521 | } | ||||
1522 | PredBBs.remove(PredBB); | ||||
1523 | } | ||||
1524 | } | ||||
1525 | |||||
1526 | /// When an instruction is found to only be used outside of the loop, this | ||||
1527 | /// function moves it to the exit blocks and patches up SSA form as needed. | ||||
1528 | /// This method is guaranteed to remove the original instruction from its | ||||
1529 | /// position, and may either delete it or move it to outside of the loop. | ||||
1530 | /// | ||||
1531 | static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT, | ||||
1532 | const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo, | ||||
1533 | MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE) { | ||||
1534 | LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("licm")) { dbgs() << "LICM sinking instruction: " << I << "\n"; } } while (false); | ||||
1535 | ORE->emit([&]() { | ||||
1536 | return OptimizationRemark(DEBUG_TYPE"licm", "InstSunk", &I) | ||||
1537 | << "sinking " << ore::NV("Inst", &I); | ||||
1538 | }); | ||||
1539 | bool Changed = false; | ||||
1540 | if (isa<LoadInst>(I)) | ||||
1541 | ++NumMovedLoads; | ||||
1542 | else if (isa<CallInst>(I)) | ||||
1543 | ++NumMovedCalls; | ||||
1544 | ++NumSunk; | ||||
1545 | |||||
1546 | // Iterate over users to be ready for actual sinking. Replace users via | ||||
1547 | // unreachable blocks with undef and make all user PHIs trivially replaceable. | ||||
1548 | SmallPtrSet<Instruction *, 8> VisitedUsers; | ||||
1549 | for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) { | ||||
1550 | auto *User = cast<Instruction>(*UI); | ||||
1551 | Use &U = UI.getUse(); | ||||
1552 | ++UI; | ||||
1553 | |||||
1554 | if (VisitedUsers.count(User) || CurLoop->contains(User)) | ||||
1555 | continue; | ||||
1556 | |||||
1557 | if (!DT->isReachableFromEntry(User->getParent())) { | ||||
1558 | U = UndefValue::get(I.getType()); | ||||
1559 | Changed = true; | ||||
1560 | continue; | ||||
1561 | } | ||||
1562 | |||||
1563 | // The user must be a PHI node. | ||||
1564 | PHINode *PN = cast<PHINode>(User); | ||||
1565 | |||||
1566 | // Surprisingly, instructions can be used outside of loops without any | ||||
1567 | // exits. This can only happen in PHI nodes if the incoming block is | ||||
1568 | // unreachable. | ||||
1569 | BasicBlock *BB = PN->getIncomingBlock(U); | ||||
1570 | if (!DT->isReachableFromEntry(BB)) { | ||||
1571 | U = UndefValue::get(I.getType()); | ||||
1572 | Changed = true; | ||||
1573 | continue; | ||||
1574 | } | ||||
1575 | |||||
1576 | VisitedUsers.insert(PN); | ||||
1577 | if (isTriviallyReplaceablePHI(*PN, I)) | ||||
1578 | continue; | ||||
1579 | |||||
1580 | if (!canSplitPredecessors(PN, SafetyInfo)) | ||||
1581 | return Changed; | ||||
1582 | |||||
1583 | // Split predecessors of the PHI so that we can make users trivially | ||||
1584 | // replaceable. | ||||
1585 | splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo, MSSAU); | ||||
1586 | |||||
1587 | // Should rebuild the iterators, as they may be invalidated by | ||||
1588 | // splitPredecessorsOfLoopExit(). | ||||
1589 | UI = I.user_begin(); | ||||
1590 | UE = I.user_end(); | ||||
1591 | } | ||||
1592 | |||||
1593 | if (VisitedUsers.empty()) | ||||
1594 | return Changed; | ||||
1595 | |||||
1596 | #ifndef NDEBUG | ||||
1597 | SmallVector<BasicBlock *, 32> ExitBlocks; | ||||
1598 | CurLoop->getUniqueExitBlocks(ExitBlocks); | ||||
1599 | SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(), | ||||
1600 | ExitBlocks.end()); | ||||
1601 | #endif | ||||
1602 | |||||
1603 | // Clones of this instruction. Don't create more than one per exit block! | ||||
1604 | SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies; | ||||
1605 | |||||
1606 | // If this instruction is only used outside of the loop, then all users are | ||||
1607 | // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of | ||||
1608 | // the instruction. | ||||
1609 | SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end()); | ||||
1610 | for (auto *UI : Users) { | ||||
1611 | auto *User = cast<Instruction>(UI); | ||||
1612 | |||||
1613 | if (CurLoop->contains(User)) | ||||
1614 | continue; | ||||
1615 | |||||
1616 | PHINode *PN = cast<PHINode>(User); | ||||
1617 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1618, __PRETTY_FUNCTION__)) | ||||
1618 | "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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1618, __PRETTY_FUNCTION__)); | ||||
1619 | // The PHI must be trivially replaceable. | ||||
1620 | Instruction *New = sinkThroughTriviallyReplaceablePHI( | ||||
1621 | PN, &I, LI, SunkCopies, SafetyInfo, CurLoop, MSSAU); | ||||
1622 | PN->replaceAllUsesWith(New); | ||||
1623 | eraseInstruction(*PN, *SafetyInfo, nullptr, nullptr); | ||||
1624 | Changed = true; | ||||
1625 | } | ||||
1626 | return Changed; | ||||
1627 | } | ||||
1628 | |||||
1629 | /// When an instruction is found to only use loop invariant operands that | ||||
1630 | /// is safe to hoist, this instruction is called to do the dirty work. | ||||
1631 | /// | ||||
1632 | static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, | ||||
1633 | BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo, | ||||
1634 | MemorySSAUpdater *MSSAU, ScalarEvolution *SE, | ||||
1635 | OptimizationRemarkEmitter *ORE) { | ||||
1636 | 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) | ||||
1637 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("licm")) { dbgs() << "LICM hoisting to " << Dest ->getName() << ": " << I << "\n"; } } while (false); | ||||
1638 | ORE->emit([&]() { | ||||
1639 | return OptimizationRemark(DEBUG_TYPE"licm", "Hoisted", &I) << "hoisting " | ||||
1640 | << ore::NV("Inst", &I); | ||||
1641 | }); | ||||
1642 | |||||
1643 | // Metadata can be dependent on conditions we are hoisting above. | ||||
1644 | // Conservatively strip all metadata on the instruction unless we were | ||||
1645 | // guaranteed to execute I if we entered the loop, in which case the metadata | ||||
1646 | // is valid in the loop preheader. | ||||
1647 | if (I.hasMetadataOtherThanDebugLoc() && | ||||
1648 | // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning | ||||
1649 | // time in isGuaranteedToExecute if we don't actually have anything to | ||||
1650 | // drop. It is a compile time optimization, not required for correctness. | ||||
1651 | !SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop)) | ||||
1652 | I.dropUnknownNonDebugMetadata(); | ||||
1653 | |||||
1654 | if (isa<PHINode>(I)) | ||||
1655 | // Move the new node to the end of the phi list in the destination block. | ||||
1656 | moveInstructionBefore(I, *Dest->getFirstNonPHI(), *SafetyInfo, MSSAU, SE); | ||||
1657 | else | ||||
1658 | // Move the new node to the destination block, before its terminator. | ||||
1659 | moveInstructionBefore(I, *Dest->getTerminator(), *SafetyInfo, MSSAU, SE); | ||||
1660 | |||||
1661 | // Apply line 0 debug locations when we are moving instructions to different | ||||
1662 | // basic blocks because we want to avoid jumpy line tables. | ||||
1663 | if (const DebugLoc &DL = I.getDebugLoc()) | ||||
1664 | I.setDebugLoc(DebugLoc::get(0, 0, DL.getScope(), DL.getInlinedAt())); | ||||
1665 | |||||
1666 | if (isa<LoadInst>(I)) | ||||
1667 | ++NumMovedLoads; | ||||
1668 | else if (isa<CallInst>(I)) | ||||
1669 | ++NumMovedCalls; | ||||
1670 | ++NumHoisted; | ||||
1671 | } | ||||
1672 | |||||
1673 | /// Only sink or hoist an instruction if it is not a trapping instruction, | ||||
1674 | /// or if the instruction is known not to trap when moved to the preheader. | ||||
1675 | /// or if it is a trapping instruction and is guaranteed to execute. | ||||
1676 | static bool isSafeToExecuteUnconditionally(Instruction &Inst, | ||||
1677 | const DominatorTree *DT, | ||||
1678 | const Loop *CurLoop, | ||||
1679 | const LoopSafetyInfo *SafetyInfo, | ||||
1680 | OptimizationRemarkEmitter *ORE, | ||||
1681 | const Instruction *CtxI) { | ||||
1682 | if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT)) | ||||
1683 | return true; | ||||
1684 | |||||
1685 | bool GuaranteedToExecute = | ||||
1686 | SafetyInfo->isGuaranteedToExecute(Inst, DT, CurLoop); | ||||
1687 | |||||
1688 | if (!GuaranteedToExecute) { | ||||
1689 | auto *LI = dyn_cast<LoadInst>(&Inst); | ||||
1690 | if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand())) | ||||
1691 | ORE->emit([&]() { | ||||
1692 | return OptimizationRemarkMissed( | ||||
1693 | DEBUG_TYPE"licm", "LoadWithLoopInvariantAddressCondExecuted", LI) | ||||
1694 | << "failed to hoist load with loop-invariant address " | ||||
1695 | "because load is conditionally executed"; | ||||
1696 | }); | ||||
1697 | } | ||||
1698 | |||||
1699 | return GuaranteedToExecute; | ||||
1700 | } | ||||
1701 | |||||
1702 | namespace { | ||||
1703 | class LoopPromoter : public LoadAndStorePromoter { | ||||
1704 | Value *SomePtr; // Designated pointer to store to. | ||||
1705 | const SmallSetVector<Value *, 8> &PointerMustAliases; | ||||
1706 | SmallVectorImpl<BasicBlock *> &LoopExitBlocks; | ||||
1707 | SmallVectorImpl<Instruction *> &LoopInsertPts; | ||||
1708 | SmallVectorImpl<MemoryAccess *> &MSSAInsertPts; | ||||
1709 | PredIteratorCache &PredCache; | ||||
1710 | AliasSetTracker &AST; | ||||
1711 | MemorySSAUpdater *MSSAU; | ||||
1712 | LoopInfo &LI; | ||||
1713 | DebugLoc DL; | ||||
1714 | int Alignment; | ||||
1715 | bool UnorderedAtomic; | ||||
1716 | AAMDNodes AATags; | ||||
1717 | ICFLoopSafetyInfo &SafetyInfo; | ||||
1718 | |||||
1719 | Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const { | ||||
1720 | if (Instruction *I = dyn_cast<Instruction>(V)) | ||||
1721 | if (Loop *L = LI.getLoopFor(I->getParent())) | ||||
1722 | if (!L->contains(BB)) { | ||||
1723 | // We need to create an LCSSA PHI node for the incoming value and | ||||
1724 | // store that. | ||||
1725 | PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB), | ||||
1726 | I->getName() + ".lcssa", &BB->front()); | ||||
1727 | for (BasicBlock *Pred : PredCache.get(BB)) | ||||
1728 | PN->addIncoming(I, Pred); | ||||
1729 | return PN; | ||||
1730 | } | ||||
1731 | return V; | ||||
1732 | } | ||||
1733 | |||||
1734 | public: | ||||
1735 | LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S, | ||||
1736 | const SmallSetVector<Value *, 8> &PMA, | ||||
1737 | SmallVectorImpl<BasicBlock *> &LEB, | ||||
1738 | SmallVectorImpl<Instruction *> &LIP, | ||||
1739 | SmallVectorImpl<MemoryAccess *> &MSSAIP, PredIteratorCache &PIC, | ||||
1740 | AliasSetTracker &ast, MemorySSAUpdater *MSSAU, LoopInfo &li, | ||||
1741 | DebugLoc dl, int alignment, bool UnorderedAtomic, | ||||
1742 | const AAMDNodes &AATags, ICFLoopSafetyInfo &SafetyInfo) | ||||
1743 | : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA), | ||||
1744 | LoopExitBlocks(LEB), LoopInsertPts(LIP), MSSAInsertPts(MSSAIP), | ||||
1745 | PredCache(PIC), AST(ast), MSSAU(MSSAU), LI(li), DL(std::move(dl)), | ||||
1746 | Alignment(alignment), UnorderedAtomic(UnorderedAtomic), AATags(AATags), | ||||
1747 | SafetyInfo(SafetyInfo) {} | ||||
1748 | |||||
1749 | bool isInstInList(Instruction *I, | ||||
1750 | const SmallVectorImpl<Instruction *> &) const override { | ||||
1751 | Value *Ptr; | ||||
1752 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) | ||||
1753 | Ptr = LI->getOperand(0); | ||||
1754 | else | ||||
1755 | Ptr = cast<StoreInst>(I)->getPointerOperand(); | ||||
1756 | return PointerMustAliases.count(Ptr); | ||||
1757 | } | ||||
1758 | |||||
1759 | void doExtraRewritesBeforeFinalDeletion() override { | ||||
1760 | // Insert stores after in the loop exit blocks. Each exit block gets a | ||||
1761 | // store of the live-out values that feed them. Since we've already told | ||||
1762 | // the SSA updater about the defs in the loop and the preheader | ||||
1763 | // definition, it is all set and we can start using it. | ||||
1764 | for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) { | ||||
1765 | BasicBlock *ExitBlock = LoopExitBlocks[i]; | ||||
1766 | Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock); | ||||
1767 | LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock); | ||||
1768 | Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock); | ||||
1769 | Instruction *InsertPos = LoopInsertPts[i]; | ||||
1770 | StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos); | ||||
1771 | if (UnorderedAtomic) | ||||
1772 | NewSI->setOrdering(AtomicOrdering::Unordered); | ||||
1773 | NewSI->setAlignment(Align(Alignment)); | ||||
1774 | NewSI->setDebugLoc(DL); | ||||
1775 | if (AATags) | ||||
1776 | NewSI->setAAMetadata(AATags); | ||||
1777 | |||||
1778 | if (MSSAU) { | ||||
1779 | MemoryAccess *MSSAInsertPoint = MSSAInsertPts[i]; | ||||
1780 | MemoryAccess *NewMemAcc; | ||||
1781 | if (!MSSAInsertPoint) { | ||||
1782 | NewMemAcc = MSSAU->createMemoryAccessInBB( | ||||
1783 | NewSI, nullptr, NewSI->getParent(), MemorySSA::Beginning); | ||||
1784 | } else { | ||||
1785 | NewMemAcc = | ||||
1786 | MSSAU->createMemoryAccessAfter(NewSI, nullptr, MSSAInsertPoint); | ||||
1787 | } | ||||
1788 | MSSAInsertPts[i] = NewMemAcc; | ||||
1789 | MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true); | ||||
1790 | // FIXME: true for safety, false may still be correct. | ||||
1791 | } | ||||
1792 | } | ||||
1793 | } | ||||
1794 | |||||
1795 | void replaceLoadWithValue(LoadInst *LI, Value *V) const override { | ||||
1796 | // Update alias analysis. | ||||
1797 | AST.copyValue(LI, V); | ||||
1798 | } | ||||
1799 | void instructionDeleted(Instruction *I) const override { | ||||
1800 | SafetyInfo.removeInstruction(I); | ||||
1801 | AST.deleteValue(I); | ||||
1802 | if (MSSAU) | ||||
1803 | MSSAU->removeMemoryAccess(I); | ||||
1804 | } | ||||
1805 | }; | ||||
1806 | |||||
1807 | |||||
1808 | /// Return true iff we can prove that a caller of this function can not inspect | ||||
1809 | /// the contents of the provided object in a well defined program. | ||||
1810 | bool isKnownNonEscaping(Value *Object, const TargetLibraryInfo *TLI) { | ||||
1811 | if (isa<AllocaInst>(Object)) | ||||
1812 | // Since the alloca goes out of scope, we know the caller can't retain a | ||||
1813 | // reference to it and be well defined. Thus, we don't need to check for | ||||
1814 | // capture. | ||||
1815 | return true; | ||||
1816 | |||||
1817 | // For all other objects we need to know that the caller can't possibly | ||||
1818 | // have gotten a reference to the object. There are two components of | ||||
1819 | // that: | ||||
1820 | // 1) Object can't be escaped by this function. This is what | ||||
1821 | // PointerMayBeCaptured checks. | ||||
1822 | // 2) Object can't have been captured at definition site. For this, we | ||||
1823 | // need to know the return value is noalias. At the moment, we use a | ||||
1824 | // weaker condition and handle only AllocLikeFunctions (which are | ||||
1825 | // known to be noalias). TODO | ||||
1826 | return isAllocLikeFn(Object, TLI) && | ||||
1827 | !PointerMayBeCaptured(Object, true, true); | ||||
1828 | } | ||||
1829 | |||||
1830 | } // namespace | ||||
1831 | |||||
1832 | /// Try to promote memory values to scalars by sinking stores out of the | ||||
1833 | /// loop and moving loads to before the loop. We do this by looping over | ||||
1834 | /// the stores in the loop, looking for stores to Must pointers which are | ||||
1835 | /// loop invariant. | ||||
1836 | /// | ||||
1837 | bool llvm::promoteLoopAccessesToScalars( | ||||
1838 | const SmallSetVector<Value *, 8> &PointerMustAliases, | ||||
1839 | SmallVectorImpl<BasicBlock *> &ExitBlocks, | ||||
1840 | SmallVectorImpl<Instruction *> &InsertPts, | ||||
1841 | SmallVectorImpl<MemoryAccess *> &MSSAInsertPts, PredIteratorCache &PIC, | ||||
1842 | LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, | ||||
1843 | Loop *CurLoop, AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU, | ||||
1844 | ICFLoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE) { | ||||
1845 | // Verify inputs. | ||||
1846 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1848, __PRETTY_FUNCTION__)) | ||||
1847 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1848, __PRETTY_FUNCTION__)) | ||||
1848 | "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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 1848, __PRETTY_FUNCTION__)); | ||||
1849 | |||||
1850 | Value *SomePtr = *PointerMustAliases.begin(); | ||||
1851 | BasicBlock *Preheader = CurLoop->getLoopPreheader(); | ||||
1852 | |||||
1853 | // It is not safe to promote a load/store from the loop if the load/store is | ||||
1854 | // conditional. For example, turning: | ||||
1855 | // | ||||
1856 | // for () { if (c) *P += 1; } | ||||
1857 | // | ||||
1858 | // into: | ||||
1859 | // | ||||
1860 | // tmp = *P; for () { if (c) tmp +=1; } *P = tmp; | ||||
1861 | // | ||||
1862 | // is not safe, because *P may only be valid to access if 'c' is true. | ||||
1863 | // | ||||
1864 | // The safety property divides into two parts: | ||||
1865 | // p1) The memory may not be dereferenceable on entry to the loop. In this | ||||
1866 | // case, we can't insert the required load in the preheader. | ||||
1867 | // p2) The memory model does not allow us to insert a store along any dynamic | ||||
1868 | // path which did not originally have one. | ||||
1869 | // | ||||
1870 | // If at least one store is guaranteed to execute, both properties are | ||||
1871 | // satisfied, and promotion is legal. | ||||
1872 | // | ||||
1873 | // This, however, is not a necessary condition. Even if no store/load is | ||||
1874 | // guaranteed to execute, we can still establish these properties. | ||||
1875 | // We can establish (p1) by proving that hoisting the load into the preheader | ||||
1876 | // is safe (i.e. proving dereferenceability on all paths through the loop). We | ||||
1877 | // can use any access within the alias set to prove dereferenceability, | ||||
1878 | // since they're all must alias. | ||||
1879 | // | ||||
1880 | // There are two ways establish (p2): | ||||
1881 | // a) Prove the location is thread-local. In this case the memory model | ||||
1882 | // requirement does not apply, and stores are safe to insert. | ||||
1883 | // b) Prove a store dominates every exit block. In this case, if an exit | ||||
1884 | // blocks is reached, the original dynamic path would have taken us through | ||||
1885 | // the store, so inserting a store into the exit block is safe. Note that this | ||||
1886 | // is different from the store being guaranteed to execute. For instance, | ||||
1887 | // if an exception is thrown on the first iteration of the loop, the original | ||||
1888 | // store is never executed, but the exit blocks are not executed either. | ||||
1889 | |||||
1890 | bool DereferenceableInPH = false; | ||||
1891 | bool SafeToInsertStore = false; | ||||
1892 | |||||
1893 | SmallVector<Instruction *, 64> LoopUses; | ||||
1894 | |||||
1895 | // We start with an alignment of one and try to find instructions that allow | ||||
1896 | // us to prove better alignment. | ||||
1897 | Align Alignment; | ||||
1898 | // Keep track of which types of access we see | ||||
1899 | bool SawUnorderedAtomic = false; | ||||
1900 | bool SawNotAtomic = false; | ||||
1901 | AAMDNodes AATags; | ||||
1902 | |||||
1903 | const DataLayout &MDL = Preheader->getModule()->getDataLayout(); | ||||
1904 | |||||
1905 | bool IsKnownThreadLocalObject = false; | ||||
1906 | if (SafetyInfo->anyBlockMayThrow()) { | ||||
1907 | // If a loop can throw, we have to insert a store along each unwind edge. | ||||
1908 | // That said, we can't actually make the unwind edge explicit. Therefore, | ||||
1909 | // we have to prove that the store is dead along the unwind edge. We do | ||||
1910 | // this by proving that the caller can't have a reference to the object | ||||
1911 | // after return and thus can't possibly load from the object. | ||||
1912 | Value *Object = getUnderlyingObject(SomePtr); | ||||
1913 | if (!isKnownNonEscaping(Object, TLI)) | ||||
1914 | return false; | ||||
1915 | // Subtlety: Alloca's aren't visible to callers, but *are* potentially | ||||
1916 | // visible to other threads if captured and used during their lifetimes. | ||||
1917 | IsKnownThreadLocalObject = !isa<AllocaInst>(Object); | ||||
1918 | } | ||||
1919 | |||||
1920 | // Check that all of the pointers in the alias set have the same type. We | ||||
1921 | // cannot (yet) promote a memory location that is loaded and stored in | ||||
1922 | // different sizes. While we are at it, collect alignment and AA info. | ||||
1923 | for (Value *ASIV : PointerMustAliases) { | ||||
1924 | // Check that all of the pointers in the alias set have the same type. We | ||||
1925 | // cannot (yet) promote a memory location that is loaded and stored in | ||||
1926 | // different sizes. | ||||
1927 | if (SomePtr->getType() != ASIV->getType()) | ||||
1928 | return false; | ||||
1929 | |||||
1930 | for (User *U : ASIV->users()) { | ||||
1931 | // Ignore instructions that are outside the loop. | ||||
1932 | Instruction *UI = dyn_cast<Instruction>(U); | ||||
1933 | if (!UI || !CurLoop->contains(UI)) | ||||
1934 | continue; | ||||
1935 | |||||
1936 | // If there is an non-load/store instruction in the loop, we can't promote | ||||
1937 | // it. | ||||
1938 | if (LoadInst *Load = dyn_cast<LoadInst>(UI)) { | ||||
1939 | if (!Load->isUnordered()) | ||||
1940 | return false; | ||||
1941 | |||||
1942 | SawUnorderedAtomic |= Load->isAtomic(); | ||||
1943 | SawNotAtomic |= !Load->isAtomic(); | ||||
1944 | |||||
1945 | Align InstAlignment = Load->getAlign(); | ||||
1946 | |||||
1947 | // Note that proving a load safe to speculate requires proving | ||||
1948 | // sufficient alignment at the target location. Proving it guaranteed | ||||
1949 | // to execute does as well. Thus we can increase our guaranteed | ||||
1950 | // alignment as well. | ||||
1951 | if (!DereferenceableInPH || (InstAlignment > Alignment)) | ||||
1952 | if (isSafeToExecuteUnconditionally(*Load, DT, CurLoop, SafetyInfo, | ||||
1953 | ORE, Preheader->getTerminator())) { | ||||
1954 | DereferenceableInPH = true; | ||||
1955 | Alignment = std::max(Alignment, InstAlignment); | ||||
1956 | } | ||||
1957 | } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) { | ||||
1958 | // Stores *of* the pointer are not interesting, only stores *to* the | ||||
1959 | // pointer. | ||||
1960 | if (UI->getOperand(1) != ASIV) | ||||
1961 | continue; | ||||
1962 | if (!Store->isUnordered()) | ||||
1963 | return false; | ||||
1964 | |||||
1965 | SawUnorderedAtomic |= Store->isAtomic(); | ||||
1966 | SawNotAtomic |= !Store->isAtomic(); | ||||
1967 | |||||
1968 | // If the store is guaranteed to execute, both properties are satisfied. | ||||
1969 | // We may want to check if a store is guaranteed to execute even if we | ||||
1970 | // already know that promotion is safe, since it may have higher | ||||
1971 | // alignment than any other guaranteed stores, in which case we can | ||||
1972 | // raise the alignment on the promoted store. | ||||
1973 | Align InstAlignment = Store->getAlign(); | ||||
1974 | |||||
1975 | if (!DereferenceableInPH || !SafeToInsertStore || | ||||
1976 | (InstAlignment > Alignment)) { | ||||
1977 | if (SafetyInfo->isGuaranteedToExecute(*UI, DT, CurLoop)) { | ||||
1978 | DereferenceableInPH = true; | ||||
1979 | SafeToInsertStore = true; | ||||
1980 | Alignment = std::max(Alignment, InstAlignment); | ||||
1981 | } | ||||
1982 | } | ||||
1983 | |||||
1984 | // If a store dominates all exit blocks, it is safe to sink. | ||||
1985 | // As explained above, if an exit block was executed, a dominating | ||||
1986 | // store must have been executed at least once, so we are not | ||||
1987 | // introducing stores on paths that did not have them. | ||||
1988 | // Note that this only looks at explicit exit blocks. If we ever | ||||
1989 | // start sinking stores into unwind edges (see above), this will break. | ||||
1990 | if (!SafeToInsertStore) | ||||
1991 | SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) { | ||||
1992 | return DT->dominates(Store->getParent(), Exit); | ||||
1993 | }); | ||||
1994 | |||||
1995 | // If the store is not guaranteed to execute, we may still get | ||||
1996 | // deref info through it. | ||||
1997 | if (!DereferenceableInPH) { | ||||
1998 | DereferenceableInPH = isDereferenceableAndAlignedPointer( | ||||
1999 | Store->getPointerOperand(), Store->getValueOperand()->getType(), | ||||
2000 | Store->getAlign(), MDL, Preheader->getTerminator(), DT); | ||||
2001 | } | ||||
2002 | } else | ||||
2003 | return false; // Not a load or store. | ||||
2004 | |||||
2005 | // Merge the AA tags. | ||||
2006 | if (LoopUses.empty()) { | ||||
2007 | // On the first load/store, just take its AA tags. | ||||
2008 | UI->getAAMetadata(AATags); | ||||
2009 | } else if (AATags) { | ||||
2010 | UI->getAAMetadata(AATags, /* Merge = */ true); | ||||
2011 | } | ||||
2012 | |||||
2013 | LoopUses.push_back(UI); | ||||
2014 | } | ||||
2015 | } | ||||
2016 | |||||
2017 | // If we found both an unordered atomic instruction and a non-atomic memory | ||||
2018 | // access, bail. We can't blindly promote non-atomic to atomic since we | ||||
2019 | // might not be able to lower the result. We can't downgrade since that | ||||
2020 | // would violate memory model. Also, align 0 is an error for atomics. | ||||
2021 | if (SawUnorderedAtomic && SawNotAtomic) | ||||
2022 | return false; | ||||
2023 | |||||
2024 | // If we're inserting an atomic load in the preheader, we must be able to | ||||
2025 | // lower it. We're only guaranteed to be able to lower naturally aligned | ||||
2026 | // atomics. | ||||
2027 | auto *SomePtrElemType = SomePtr->getType()->getPointerElementType(); | ||||
2028 | if (SawUnorderedAtomic && | ||||
2029 | Alignment < MDL.getTypeStoreSize(SomePtrElemType)) | ||||
2030 | return false; | ||||
2031 | |||||
2032 | // If we couldn't prove we can hoist the load, bail. | ||||
2033 | if (!DereferenceableInPH) | ||||
2034 | return false; | ||||
2035 | |||||
2036 | // We know we can hoist the load, but don't have a guaranteed store. | ||||
2037 | // Check whether the location is thread-local. If it is, then we can insert | ||||
2038 | // stores along paths which originally didn't have them without violating the | ||||
2039 | // memory model. | ||||
2040 | if (!SafeToInsertStore) { | ||||
2041 | if (IsKnownThreadLocalObject) | ||||
2042 | SafeToInsertStore = true; | ||||
2043 | else { | ||||
2044 | Value *Object = getUnderlyingObject(SomePtr); | ||||
2045 | SafeToInsertStore = | ||||
2046 | (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) && | ||||
2047 | !PointerMayBeCaptured(Object, true, true); | ||||
2048 | } | ||||
2049 | } | ||||
2050 | |||||
2051 | // If we've still failed to prove we can sink the store, give up. | ||||
2052 | if (!SafeToInsertStore) | ||||
2053 | return false; | ||||
2054 | |||||
2055 | // Otherwise, this is safe to promote, lets do it! | ||||
2056 | 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) | ||||
2057 | << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("licm")) { dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr << '\n'; } } while (false); | ||||
2058 | ORE->emit([&]() { | ||||
2059 | return OptimizationRemark(DEBUG_TYPE"licm", "PromoteLoopAccessesToScalar", | ||||
2060 | LoopUses[0]) | ||||
2061 | << "Moving accesses to memory location out of the loop"; | ||||
2062 | }); | ||||
2063 | ++NumPromoted; | ||||
2064 | |||||
2065 | // Look at all the loop uses, and try to merge their locations. | ||||
2066 | std::vector<const DILocation *> LoopUsesLocs; | ||||
2067 | for (auto U : LoopUses) | ||||
2068 | LoopUsesLocs.push_back(U->getDebugLoc().get()); | ||||
2069 | auto DL = DebugLoc(DILocation::getMergedLocations(LoopUsesLocs)); | ||||
2070 | |||||
2071 | // We use the SSAUpdater interface to insert phi nodes as required. | ||||
2072 | SmallVector<PHINode *, 16> NewPHIs; | ||||
2073 | SSAUpdater SSA(&NewPHIs); | ||||
2074 | LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks, | ||||
2075 | InsertPts, MSSAInsertPts, PIC, *CurAST, MSSAU, *LI, DL, | ||||
2076 | Alignment.value(), SawUnorderedAtomic, AATags, | ||||
2077 | *SafetyInfo); | ||||
2078 | |||||
2079 | // Set up the preheader to have a definition of the value. It is the live-out | ||||
2080 | // value from the preheader that uses in the loop will use. | ||||
2081 | LoadInst *PreheaderLoad = new LoadInst( | ||||
2082 | SomePtr->getType()->getPointerElementType(), SomePtr, | ||||
2083 | SomePtr->getName() + ".promoted", Preheader->getTerminator()); | ||||
2084 | if (SawUnorderedAtomic) | ||||
2085 | PreheaderLoad->setOrdering(AtomicOrdering::Unordered); | ||||
2086 | PreheaderLoad->setAlignment(Alignment); | ||||
2087 | PreheaderLoad->setDebugLoc(DebugLoc()); | ||||
2088 | if (AATags) | ||||
2089 | PreheaderLoad->setAAMetadata(AATags); | ||||
2090 | SSA.AddAvailableValue(Preheader, PreheaderLoad); | ||||
2091 | |||||
2092 | if (MSSAU) { | ||||
2093 | MemoryAccess *PreheaderLoadMemoryAccess = MSSAU->createMemoryAccessInBB( | ||||
2094 | PreheaderLoad, nullptr, PreheaderLoad->getParent(), MemorySSA::End); | ||||
2095 | MemoryUse *NewMemUse = cast<MemoryUse>(PreheaderLoadMemoryAccess); | ||||
2096 | MSSAU->insertUse(NewMemUse, /*RenameUses=*/true); | ||||
2097 | } | ||||
2098 | |||||
2099 | if (MSSAU && VerifyMemorySSA) | ||||
2100 | MSSAU->getMemorySSA()->verifyMemorySSA(); | ||||
2101 | // Rewrite all the loads in the loop and remember all the definitions from | ||||
2102 | // stores in the loop. | ||||
2103 | Promoter.run(LoopUses); | ||||
2104 | |||||
2105 | if (MSSAU && VerifyMemorySSA) | ||||
2106 | MSSAU->getMemorySSA()->verifyMemorySSA(); | ||||
2107 | // If the SSAUpdater didn't use the load in the preheader, just zap it now. | ||||
2108 | if (PreheaderLoad->use_empty()) | ||||
2109 | eraseInstruction(*PreheaderLoad, *SafetyInfo, CurAST, MSSAU); | ||||
2110 | |||||
2111 | return true; | ||||
2112 | } | ||||
2113 | |||||
2114 | /// Returns an owning pointer to an alias set which incorporates aliasing info | ||||
2115 | /// from L and all subloops of L. | ||||
2116 | std::unique_ptr<AliasSetTracker> | ||||
2117 | LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI, | ||||
2118 | AAResults *AA) { | ||||
2119 | auto CurAST = std::make_unique<AliasSetTracker>(*AA); | ||||
2120 | |||||
2121 | // Add everything from all the sub loops. | ||||
2122 | for (Loop *InnerL : L->getSubLoops()) | ||||
2123 | for (BasicBlock *BB : InnerL->blocks()) | ||||
2124 | CurAST->add(*BB); | ||||
2125 | |||||
2126 | // And merge in this loop (without anything from inner loops). | ||||
2127 | for (BasicBlock *BB : L->blocks()) | ||||
2128 | if (LI->getLoopFor(BB) == L) | ||||
2129 | CurAST->add(*BB); | ||||
2130 | |||||
2131 | return CurAST; | ||||
2132 | } | ||||
2133 | |||||
2134 | std::unique_ptr<AliasSetTracker> | ||||
2135 | LoopInvariantCodeMotion::collectAliasInfoForLoopWithMSSA( | ||||
2136 | Loop *L, AAResults *AA, MemorySSAUpdater *MSSAU) { | ||||
2137 | auto *MSSA = MSSAU->getMemorySSA(); | ||||
2138 | auto CurAST = std::make_unique<AliasSetTracker>(*AA, MSSA, L); | ||||
2139 | CurAST->addAllInstructionsInLoopUsingMSSA(); | ||||
2140 | return CurAST; | ||||
2141 | } | ||||
2142 | |||||
2143 | static bool pointerInvalidatedByLoop(MemoryLocation MemLoc, | ||||
2144 | AliasSetTracker *CurAST, Loop *CurLoop, | ||||
2145 | AAResults *AA) { | ||||
2146 | // First check to see if any of the basic blocks in CurLoop invalidate *V. | ||||
2147 | bool isInvalidatedAccordingToAST = CurAST->getAliasSetFor(MemLoc).isMod(); | ||||
2148 | |||||
2149 | if (!isInvalidatedAccordingToAST || !LICMN2Theshold) | ||||
2150 | return isInvalidatedAccordingToAST; | ||||
2151 | |||||
2152 | // Check with a diagnostic analysis if we can refine the information above. | ||||
2153 | // This is to identify the limitations of using the AST. | ||||
2154 | // The alias set mechanism used by LICM has a major weakness in that it | ||||
2155 | // combines all things which may alias into a single set *before* asking | ||||
2156 | // modref questions. As a result, a single readonly call within a loop will | ||||
2157 | // collapse all loads and stores into a single alias set and report | ||||
2158 | // invalidation if the loop contains any store. For example, readonly calls | ||||
2159 | // with deopt states have this form and create a general alias set with all | ||||
2160 | // loads and stores. In order to get any LICM in loops containing possible | ||||
2161 | // deopt states we need a more precise invalidation of checking the mod ref | ||||
2162 | // info of each instruction within the loop and LI. This has a complexity of | ||||
2163 | // O(N^2), so currently, it is used only as a diagnostic tool since the | ||||
2164 | // default value of LICMN2Threshold is zero. | ||||
2165 | |||||
2166 | // Don't look at nested loops. | ||||
2167 | if (CurLoop->begin() != CurLoop->end()) | ||||
2168 | return true; | ||||
2169 | |||||
2170 | int N = 0; | ||||
2171 | for (BasicBlock *BB : CurLoop->getBlocks()) | ||||
2172 | for (Instruction &I : *BB) { | ||||
2173 | if (N >= LICMN2Theshold) { | ||||
2174 | 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) | ||||
2175 | << *(MemLoc.Ptr) << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("licm")) { dbgs() << "Alasing N2 threshold exhausted for " << *(MemLoc.Ptr) << "\n"; } } while (false); | ||||
2176 | return true; | ||||
2177 | } | ||||
2178 | N++; | ||||
2179 | auto Res = AA->getModRefInfo(&I, MemLoc); | ||||
2180 | if (isModSet(Res)) { | ||||
2181 | 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 ) | ||||
2182 | << *(MemLoc.Ptr) << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("licm")) { dbgs() << "Aliasing failed on " << I << " for " << *(MemLoc.Ptr) << "\n"; } } while (false ); | ||||
2183 | return true; | ||||
2184 | } | ||||
2185 | } | ||||
2186 | 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); | ||||
2187 | return false; | ||||
2188 | } | ||||
2189 | |||||
2190 | static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU, | ||||
2191 | Loop *CurLoop, | ||||
2192 | SinkAndHoistLICMFlags &Flags) { | ||||
2193 | // For hoisting, use the walker to determine safety | ||||
2194 | if (!Flags.IsSink) { | ||||
2195 | MemoryAccess *Source; | ||||
2196 | // See declaration of SetLicmMssaOptCap for usage details. | ||||
2197 | if (Flags.LicmMssaOptCounter >= Flags.LicmMssaOptCap) | ||||
2198 | Source = MU->getDefiningAccess(); | ||||
2199 | else { | ||||
2200 | Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(MU); | ||||
2201 | Flags.LicmMssaOptCounter++; | ||||
2202 | } | ||||
2203 | return !MSSA->isLiveOnEntryDef(Source) && | ||||
2204 | CurLoop->contains(Source->getBlock()); | ||||
2205 | } | ||||
2206 | |||||
2207 | // For sinking, we'd need to check all Defs below this use. The getClobbering | ||||
2208 | // call will look on the backedge of the loop, but will check aliasing with | ||||
2209 | // the instructions on the previous iteration. | ||||
2210 | // For example: | ||||
2211 | // for (i ... ) | ||||
2212 | // load a[i] ( Use (LoE) | ||||
2213 | // store a[i] ( 1 = Def (2), with 2 = Phi for the loop. | ||||
2214 | // i++; | ||||
2215 | // The load sees no clobbering inside the loop, as the backedge alias check | ||||
2216 | // does phi translation, and will check aliasing against store a[i-1]. | ||||
2217 | // However sinking the load outside the loop, below the store is incorrect. | ||||
2218 | |||||
2219 | // For now, only sink if there are no Defs in the loop, and the existing ones | ||||
2220 | // precede the use and are in the same block. | ||||
2221 | // FIXME: Increase precision: Safe to sink if Use post dominates the Def; | ||||
2222 | // needs PostDominatorTreeAnalysis. | ||||
2223 | // FIXME: More precise: no Defs that alias this Use. | ||||
2224 | if (Flags.NoOfMemAccTooLarge) | ||||
2225 | return true; | ||||
2226 | for (auto *BB : CurLoop->getBlocks()) | ||||
2227 | if (auto *Accesses = MSSA->getBlockDefs(BB)) | ||||
2228 | for (const auto &MA : *Accesses) | ||||
2229 | if (const auto *MD = dyn_cast<MemoryDef>(&MA)) | ||||
2230 | if (MU->getBlock() != MD->getBlock() || | ||||
2231 | !MSSA->locallyDominates(MD, MU)) | ||||
2232 | return true; | ||||
2233 | return false; | ||||
2234 | } | ||||
2235 | |||||
2236 | /// Little predicate that returns true if the specified basic block is in | ||||
2237 | /// a subloop of the current one, not the current one itself. | ||||
2238 | /// | ||||
2239 | static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) { | ||||
2240 | 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-12~++20200828100629+cfde93e5d6b/llvm/lib/Transforms/Scalar/LICM.cpp" , 2240, __PRETTY_FUNCTION__)); | ||||
2241 | return LI->getLoopFor(BB) != CurLoop; | ||||
2242 | } |
1 | //===- llvm/Instructions.h - Instruction subclass definitions ---*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file exposes the class definitions of all of the subclasses of the |
10 | // Instruction class. This is meant to be an easy way to get access to all |
11 | // instruction subclasses. |
12 | // |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #ifndef LLVM_IR_INSTRUCTIONS_H |
16 | #define LLVM_IR_INSTRUCTIONS_H |
17 | |
18 | #include "llvm/ADT/ArrayRef.h" |
19 | #include "llvm/ADT/Bitfields.h" |
20 | #include "llvm/ADT/None.h" |
21 | #include "llvm/ADT/STLExtras.h" |
22 | #include "llvm/ADT/SmallVector.h" |
23 | #include "llvm/ADT/StringRef.h" |
24 | #include "llvm/ADT/Twine.h" |
25 | #include "llvm/ADT/iterator.h" |
26 | #include "llvm/ADT/iterator_range.h" |
27 | #include "llvm/IR/Attributes.h" |
28 | #include "llvm/IR/BasicBlock.h" |
29 | #include "llvm/IR/CallingConv.h" |
30 | #include "llvm/IR/CFG.h" |
31 | #include "llvm/IR/Constant.h" |
32 | #include "llvm/IR/DerivedTypes.h" |
33 | #include "llvm/IR/Function.h" |
34 | #include "llvm/IR/InstrTypes.h" |
35 | #include "llvm/IR/Instruction.h" |
36 | #include "llvm/IR/OperandTraits.h" |
37 | #include "llvm/IR/Type.h" |
38 | #include "llvm/IR/Use.h" |
39 | #include "llvm/IR/User.h" |
40 | #include "llvm/IR/Value.h" |
41 | #include "llvm/Support/AtomicOrdering.h" |
42 | #include "llvm/Support/Casting.h" |
43 | #include "llvm/Support/ErrorHandling.h" |
44 | #include <cassert> |
45 | #include <cstddef> |
46 | #include <cstdint> |
47 | #include <iterator> |
48 | |
49 | namespace llvm { |
50 | |
51 | class APInt; |
52 | class ConstantInt; |
53 | class DataLayout; |
54 | class LLVMContext; |
55 | |
56 | //===----------------------------------------------------------------------===// |
57 | // AllocaInst Class |
58 | //===----------------------------------------------------------------------===// |
59 | |
60 | /// an instruction to allocate memory on the stack |
61 | class AllocaInst : public UnaryInstruction { |
62 | Type *AllocatedType; |
63 | |
64 | using AlignmentField = AlignmentBitfieldElementT<0>; |
65 | using UsedWithInAllocaField = BoolBitfieldElementT<AlignmentField::NextBit>; |
66 | using SwiftErrorField = BoolBitfieldElementT<UsedWithInAllocaField::NextBit>; |
67 | static_assert(Bitfield::areContiguous<AlignmentField, UsedWithInAllocaField, |
68 | SwiftErrorField>(), |
69 | "Bitfields must be contiguous"); |
70 | |
71 | protected: |
72 | // Note: Instruction needs to be a friend here to call cloneImpl. |
73 | friend class Instruction; |
74 | |
75 | AllocaInst *cloneImpl() const; |
76 | |
77 | public: |
78 | explicit AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, |
79 | const Twine &Name, Instruction *InsertBefore); |
80 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, |
81 | const Twine &Name, BasicBlock *InsertAtEnd); |
82 | |
83 | AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, |
84 | Instruction *InsertBefore); |
85 | AllocaInst(Type *Ty, unsigned AddrSpace, |
86 | const Twine &Name, BasicBlock *InsertAtEnd); |
87 | |
88 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align, |
89 | const Twine &Name = "", Instruction *InsertBefore = nullptr); |
90 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align, |
91 | const Twine &Name, BasicBlock *InsertAtEnd); |
92 | |
93 | /// Return true if there is an allocation size parameter to the allocation |
94 | /// instruction that is not 1. |
95 | bool isArrayAllocation() const; |
96 | |
97 | /// Get the number of elements allocated. For a simple allocation of a single |
98 | /// element, this will return a constant 1 value. |
99 | const Value *getArraySize() const { return getOperand(0); } |
100 | Value *getArraySize() { return getOperand(0); } |
101 | |
102 | /// Overload to return most specific pointer type. |
103 | PointerType *getType() const { |
104 | return cast<PointerType>(Instruction::getType()); |
105 | } |
106 | |
107 | /// Get allocation size in bits. Returns None if size can't be determined, |
108 | /// e.g. in case of a VLA. |
109 | Optional<uint64_t> getAllocationSizeInBits(const DataLayout &DL) const; |
110 | |
111 | /// Return the type that is being allocated by the instruction. |
112 | Type *getAllocatedType() const { return AllocatedType; } |
113 | /// for use only in special circumstances that need to generically |
114 | /// transform a whole instruction (eg: IR linking and vectorization). |
115 | void setAllocatedType(Type *Ty) { AllocatedType = Ty; } |
116 | |
117 | /// Return the alignment of the memory that is being allocated by the |
118 | /// instruction. |
119 | Align getAlign() const { |
120 | return Align(1ULL << getSubclassData<AlignmentField>()); |
121 | } |
122 | |
123 | void setAlignment(Align Align) { |
124 | setSubclassData<AlignmentField>(Log2(Align)); |
125 | } |
126 | |
127 | // FIXME: Remove this one transition to Align is over. |
128 | unsigned getAlignment() const { return getAlign().value(); } |
129 | |
130 | /// Return true if this alloca is in the entry block of the function and is a |
131 | /// constant size. If so, the code generator will fold it into the |
132 | /// prolog/epilog code, so it is basically free. |
133 | bool isStaticAlloca() const; |
134 | |
135 | /// Return true if this alloca is used as an inalloca argument to a call. Such |
136 | /// allocas are never considered static even if they are in the entry block. |
137 | bool isUsedWithInAlloca() const { |
138 | return getSubclassData<UsedWithInAllocaField>(); |
139 | } |
140 | |
141 | /// Specify whether this alloca is used to represent the arguments to a call. |
142 | void setUsedWithInAlloca(bool V) { |
143 | setSubclassData<UsedWithInAllocaField>(V); |
144 | } |
145 | |
146 | /// Return true if this alloca is used as a swifterror argument to a call. |
147 | bool isSwiftError() const { return getSubclassData<SwiftErrorField>(); } |
148 | /// Specify whether this alloca is used to represent a swifterror. |
149 | void setSwiftError(bool V) { setSubclassData<SwiftErrorField>(V); } |
150 | |
151 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
152 | static bool classof(const Instruction *I) { |
153 | return (I->getOpcode() == Instruction::Alloca); |
154 | } |
155 | static bool classof(const Value *V) { |
156 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
157 | } |
158 | |
159 | private: |
160 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
161 | // method so that subclasses cannot accidentally use it. |
162 | template <typename Bitfield> |
163 | void setSubclassData(typename Bitfield::Type Value) { |
164 | Instruction::setSubclassData<Bitfield>(Value); |
165 | } |
166 | }; |
167 | |
168 | //===----------------------------------------------------------------------===// |
169 | // LoadInst Class |
170 | //===----------------------------------------------------------------------===// |
171 | |
172 | /// An instruction for reading from memory. This uses the SubclassData field in |
173 | /// Value to store whether or not the load is volatile. |
174 | class LoadInst : public UnaryInstruction { |
175 | using VolatileField = BoolBitfieldElementT<0>; |
176 | using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>; |
177 | using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>; |
178 | static_assert( |
179 | Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(), |
180 | "Bitfields must be contiguous"); |
181 | |
182 | void AssertOK(); |
183 | |
184 | protected: |
185 | // Note: Instruction needs to be a friend here to call cloneImpl. |
186 | friend class Instruction; |
187 | |
188 | LoadInst *cloneImpl() const; |
189 | |
190 | public: |
191 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, |
192 | Instruction *InsertBefore); |
193 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd); |
194 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
195 | Instruction *InsertBefore); |
196 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
197 | BasicBlock *InsertAtEnd); |
198 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
199 | Align Align, Instruction *InsertBefore = nullptr); |
200 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
201 | Align Align, BasicBlock *InsertAtEnd); |
202 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
203 | Align Align, AtomicOrdering Order, |
204 | SyncScope::ID SSID = SyncScope::System, |
205 | Instruction *InsertBefore = nullptr); |
206 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
207 | Align Align, AtomicOrdering Order, SyncScope::ID SSID, |
208 | BasicBlock *InsertAtEnd); |
209 | |
210 | /// Return true if this is a load from a volatile memory location. |
211 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
212 | |
213 | /// Specify whether this is a volatile load or not. |
214 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
215 | |
216 | /// Return the alignment of the access that is being performed. |
217 | /// FIXME: Remove this function once transition to Align is over. |
218 | /// Use getAlign() instead. |
219 | unsigned getAlignment() const { return getAlign().value(); } |
220 | |
221 | /// Return the alignment of the access that is being performed. |
222 | Align getAlign() const { |
223 | return Align(1ULL << (getSubclassData<AlignmentField>())); |
224 | } |
225 | |
226 | void setAlignment(Align Align) { |
227 | setSubclassData<AlignmentField>(Log2(Align)); |
228 | } |
229 | |
230 | /// Returns the ordering constraint of this load instruction. |
231 | AtomicOrdering getOrdering() const { |
232 | return getSubclassData<OrderingField>(); |
233 | } |
234 | /// Sets the ordering constraint of this load instruction. May not be Release |
235 | /// or AcquireRelease. |
236 | void setOrdering(AtomicOrdering Ordering) { |
237 | setSubclassData<OrderingField>(Ordering); |
238 | } |
239 | |
240 | /// Returns the synchronization scope ID of this load instruction. |
241 | SyncScope::ID getSyncScopeID() const { |
242 | return SSID; |
243 | } |
244 | |
245 | /// Sets the synchronization scope ID of this load instruction. |
246 | void setSyncScopeID(SyncScope::ID SSID) { |
247 | this->SSID = SSID; |
248 | } |
249 | |
250 | /// Sets the ordering constraint and the synchronization scope ID of this load |
251 | /// instruction. |
252 | void setAtomic(AtomicOrdering Ordering, |
253 | SyncScope::ID SSID = SyncScope::System) { |
254 | setOrdering(Ordering); |
255 | setSyncScopeID(SSID); |
256 | } |
257 | |
258 | bool isSimple() const { return !isAtomic() && !isVolatile(); } |
259 | |
260 | bool isUnordered() const { |
261 | return (getOrdering() == AtomicOrdering::NotAtomic || |
262 | getOrdering() == AtomicOrdering::Unordered) && |
263 | !isVolatile(); |
264 | } |
265 | |
266 | Value *getPointerOperand() { return getOperand(0); } |
267 | const Value *getPointerOperand() const { return getOperand(0); } |
268 | static unsigned getPointerOperandIndex() { return 0U; } |
269 | Type *getPointerOperandType() const { return getPointerOperand()->getType(); } |
270 | |
271 | /// Returns the address space of the pointer operand. |
272 | unsigned getPointerAddressSpace() const { |
273 | return getPointerOperandType()->getPointerAddressSpace(); |
274 | } |
275 | |
276 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
277 | static bool classof(const Instruction *I) { |
278 | return I->getOpcode() == Instruction::Load; |
279 | } |
280 | static bool classof(const Value *V) { |
281 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
282 | } |
283 | |
284 | private: |
285 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
286 | // method so that subclasses cannot accidentally use it. |
287 | template <typename Bitfield> |
288 | void setSubclassData(typename Bitfield::Type Value) { |
289 | Instruction::setSubclassData<Bitfield>(Value); |
290 | } |
291 | |
292 | /// The synchronization scope ID of this load instruction. Not quite enough |
293 | /// room in SubClassData for everything, so synchronization scope ID gets its |
294 | /// own field. |
295 | SyncScope::ID SSID; |
296 | }; |
297 | |
298 | //===----------------------------------------------------------------------===// |
299 | // StoreInst Class |
300 | //===----------------------------------------------------------------------===// |
301 | |
302 | /// An instruction for storing to memory. |
303 | class StoreInst : public Instruction { |
304 | using VolatileField = BoolBitfieldElementT<0>; |
305 | using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>; |
306 | using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>; |
307 | static_assert( |
308 | Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(), |
309 | "Bitfields must be contiguous"); |
310 | |
311 | void AssertOK(); |
312 | |
313 | protected: |
314 | // Note: Instruction needs to be a friend here to call cloneImpl. |
315 | friend class Instruction; |
316 | |
317 | StoreInst *cloneImpl() const; |
318 | |
319 | public: |
320 | StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore); |
321 | StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd); |
322 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Instruction *InsertBefore); |
323 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd); |
324 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
325 | Instruction *InsertBefore = nullptr); |
326 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
327 | BasicBlock *InsertAtEnd); |
328 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
329 | AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System, |
330 | Instruction *InsertBefore = nullptr); |
331 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
332 | AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd); |
333 | |
334 | // allocate space for exactly two operands |
335 | void *operator new(size_t s) { |
336 | return User::operator new(s, 2); |
337 | } |
338 | |
339 | /// Return true if this is a store to a volatile memory location. |
340 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
341 | |
342 | /// Specify whether this is a volatile store or not. |
343 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
344 | |
345 | /// Transparently provide more efficient getOperand methods. |
346 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
347 | |
348 | /// Return the alignment of the access that is being performed |
349 | /// FIXME: Remove this function once transition to Align is over. |
350 | /// Use getAlign() instead. |
351 | unsigned getAlignment() const { return getAlign().value(); } |
352 | |
353 | Align getAlign() const { |
354 | return Align(1ULL << (getSubclassData<AlignmentField>())); |
355 | } |
356 | |
357 | void setAlignment(Align Align) { |
358 | setSubclassData<AlignmentField>(Log2(Align)); |
359 | } |
360 | |
361 | /// Returns the ordering constraint of this store instruction. |
362 | AtomicOrdering getOrdering() const { |
363 | return getSubclassData<OrderingField>(); |
364 | } |
365 | |
366 | /// Sets the ordering constraint of this store instruction. May not be |
367 | /// Acquire or AcquireRelease. |
368 | void setOrdering(AtomicOrdering Ordering) { |
369 | setSubclassData<OrderingField>(Ordering); |
370 | } |
371 | |
372 | /// Returns the synchronization scope ID of this store instruction. |
373 | SyncScope::ID getSyncScopeID() const { |
374 | return SSID; |
375 | } |
376 | |
377 | /// Sets the synchronization scope ID of this store instruction. |
378 | void setSyncScopeID(SyncScope::ID SSID) { |
379 | this->SSID = SSID; |
380 | } |
381 | |
382 | /// Sets the ordering constraint and the synchronization scope ID of this |
383 | /// store instruction. |
384 | void setAtomic(AtomicOrdering Ordering, |
385 | SyncScope::ID SSID = SyncScope::System) { |
386 | setOrdering(Ordering); |
387 | setSyncScopeID(SSID); |
388 | } |
389 | |
390 | bool isSimple() const { return !isAtomic() && !isVolatile(); } |
391 | |
392 | bool isUnordered() const { |
393 | return (getOrdering() == AtomicOrdering::NotAtomic || |
394 | getOrdering() == AtomicOrdering::Unordered) && |
395 | !isVolatile(); |
396 | } |
397 | |
398 | Value *getValueOperand() { return getOperand(0); } |
399 | const Value *getValueOperand() const { return getOperand(0); } |
400 | |
401 | Value *getPointerOperand() { return getOperand(1); } |
402 | const Value *getPointerOperand() const { return getOperand(1); } |
403 | static unsigned getPointerOperandIndex() { return 1U; } |
404 | Type *getPointerOperandType() const { return getPointerOperand()->getType(); } |
405 | |
406 | /// Returns the address space of the pointer operand. |
407 | unsigned getPointerAddressSpace() const { |
408 | return getPointerOperandType()->getPointerAddressSpace(); |
409 | } |
410 | |
411 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
412 | static bool classof(const Instruction *I) { |
413 | return I->getOpcode() == Instruction::Store; |
414 | } |
415 | static bool classof(const Value *V) { |
416 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
417 | } |
418 | |
419 | private: |
420 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
421 | // method so that subclasses cannot accidentally use it. |
422 | template <typename Bitfield> |
423 | void setSubclassData(typename Bitfield::Type Value) { |
424 | Instruction::setSubclassData<Bitfield>(Value); |
425 | } |
426 | |
427 | /// The synchronization scope ID of this store instruction. Not quite enough |
428 | /// room in SubClassData for everything, so synchronization scope ID gets its |
429 | /// own field. |
430 | SyncScope::ID SSID; |
431 | }; |
432 | |
433 | template <> |
434 | struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> { |
435 | }; |
436 | |
437 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)StoreInst::op_iterator StoreInst::op_begin() { return OperandTraits <StoreInst>::op_begin(this); } StoreInst::const_op_iterator StoreInst::op_begin() const { return OperandTraits<StoreInst >::op_begin(const_cast<StoreInst*>(this)); } StoreInst ::op_iterator StoreInst::op_end() { return OperandTraits<StoreInst >::op_end(this); } StoreInst::const_op_iterator StoreInst:: op_end() const { return OperandTraits<StoreInst>::op_end (const_cast<StoreInst*>(this)); } Value *StoreInst::getOperand (unsigned i_nocapture) const { ((i_nocapture < OperandTraits <StoreInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 437, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<StoreInst>::op_begin(const_cast<StoreInst *>(this))[i_nocapture].get()); } void StoreInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<StoreInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 437, __PRETTY_FUNCTION__)); OperandTraits<StoreInst>:: op_begin(this)[i_nocapture] = Val_nocapture; } unsigned StoreInst ::getNumOperands() const { return OperandTraits<StoreInst> ::operands(this); } template <int Idx_nocapture> Use & StoreInst::Op() { return this->OpFrom<Idx_nocapture> (this); } template <int Idx_nocapture> const Use &StoreInst ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
438 | |
439 | //===----------------------------------------------------------------------===// |
440 | // FenceInst Class |
441 | //===----------------------------------------------------------------------===// |
442 | |
443 | /// An instruction for ordering other memory operations. |
444 | class FenceInst : public Instruction { |
445 | using OrderingField = AtomicOrderingBitfieldElementT<0>; |
446 | |
447 | void Init(AtomicOrdering Ordering, SyncScope::ID SSID); |
448 | |
449 | protected: |
450 | // Note: Instruction needs to be a friend here to call cloneImpl. |
451 | friend class Instruction; |
452 | |
453 | FenceInst *cloneImpl() const; |
454 | |
455 | public: |
456 | // Ordering may only be Acquire, Release, AcquireRelease, or |
457 | // SequentiallyConsistent. |
458 | FenceInst(LLVMContext &C, AtomicOrdering Ordering, |
459 | SyncScope::ID SSID = SyncScope::System, |
460 | Instruction *InsertBefore = nullptr); |
461 | FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID, |
462 | BasicBlock *InsertAtEnd); |
463 | |
464 | // allocate space for exactly zero operands |
465 | void *operator new(size_t s) { |
466 | return User::operator new(s, 0); |
467 | } |
468 | |
469 | /// Returns the ordering constraint of this fence instruction. |
470 | AtomicOrdering getOrdering() const { |
471 | return getSubclassData<OrderingField>(); |
472 | } |
473 | |
474 | /// Sets the ordering constraint of this fence instruction. May only be |
475 | /// Acquire, Release, AcquireRelease, or SequentiallyConsistent. |
476 | void setOrdering(AtomicOrdering Ordering) { |
477 | setSubclassData<OrderingField>(Ordering); |
478 | } |
479 | |
480 | /// Returns the synchronization scope ID of this fence instruction. |
481 | SyncScope::ID getSyncScopeID() const { |
482 | return SSID; |
483 | } |
484 | |
485 | /// Sets the synchronization scope ID of this fence instruction. |
486 | void setSyncScopeID(SyncScope::ID SSID) { |
487 | this->SSID = SSID; |
488 | } |
489 | |
490 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
491 | static bool classof(const Instruction *I) { |
492 | return I->getOpcode() == Instruction::Fence; |
493 | } |
494 | static bool classof(const Value *V) { |
495 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
496 | } |
497 | |
498 | private: |
499 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
500 | // method so that subclasses cannot accidentally use it. |
501 | template <typename Bitfield> |
502 | void setSubclassData(typename Bitfield::Type Value) { |
503 | Instruction::setSubclassData<Bitfield>(Value); |
504 | } |
505 | |
506 | /// The synchronization scope ID of this fence instruction. Not quite enough |
507 | /// room in SubClassData for everything, so synchronization scope ID gets its |
508 | /// own field. |
509 | SyncScope::ID SSID; |
510 | }; |
511 | |
512 | //===----------------------------------------------------------------------===// |
513 | // AtomicCmpXchgInst Class |
514 | //===----------------------------------------------------------------------===// |
515 | |
516 | /// An instruction that atomically checks whether a |
517 | /// specified value is in a memory location, and, if it is, stores a new value |
518 | /// there. The value returned by this instruction is a pair containing the |
519 | /// original value as first element, and an i1 indicating success (true) or |
520 | /// failure (false) as second element. |
521 | /// |
522 | class AtomicCmpXchgInst : public Instruction { |
523 | void Init(Value *Ptr, Value *Cmp, Value *NewVal, Align Align, |
524 | AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering, |
525 | SyncScope::ID SSID); |
526 | |
527 | template <unsigned Offset> |
528 | using AtomicOrderingBitfieldElement = |
529 | typename Bitfield::Element<AtomicOrdering, Offset, 3, |
530 | AtomicOrdering::LAST>; |
531 | |
532 | protected: |
533 | // Note: Instruction needs to be a friend here to call cloneImpl. |
534 | friend class Instruction; |
535 | |
536 | AtomicCmpXchgInst *cloneImpl() const; |
537 | |
538 | public: |
539 | AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment, |
540 | AtomicOrdering SuccessOrdering, |
541 | AtomicOrdering FailureOrdering, SyncScope::ID SSID, |
542 | Instruction *InsertBefore = nullptr); |
543 | AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment, |
544 | AtomicOrdering SuccessOrdering, |
545 | AtomicOrdering FailureOrdering, SyncScope::ID SSID, |
546 | BasicBlock *InsertAtEnd); |
547 | |
548 | // allocate space for exactly three operands |
549 | void *operator new(size_t s) { |
550 | return User::operator new(s, 3); |
551 | } |
552 | |
553 | using VolatileField = BoolBitfieldElementT<0>; |
554 | using WeakField = BoolBitfieldElementT<VolatileField::NextBit>; |
555 | using SuccessOrderingField = |
556 | AtomicOrderingBitfieldElementT<WeakField::NextBit>; |
557 | using FailureOrderingField = |
558 | AtomicOrderingBitfieldElementT<SuccessOrderingField::NextBit>; |
559 | using AlignmentField = |
560 | AlignmentBitfieldElementT<FailureOrderingField::NextBit>; |
561 | static_assert( |
562 | Bitfield::areContiguous<VolatileField, WeakField, SuccessOrderingField, |
563 | FailureOrderingField, AlignmentField>(), |
564 | "Bitfields must be contiguous"); |
565 | |
566 | /// Return the alignment of the memory that is being allocated by the |
567 | /// instruction. |
568 | Align getAlign() const { |
569 | return Align(1ULL << getSubclassData<AlignmentField>()); |
570 | } |
571 | |
572 | void setAlignment(Align Align) { |
573 | setSubclassData<AlignmentField>(Log2(Align)); |
574 | } |
575 | |
576 | /// Return true if this is a cmpxchg from a volatile memory |
577 | /// location. |
578 | /// |
579 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
580 | |
581 | /// Specify whether this is a volatile cmpxchg. |
582 | /// |
583 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
584 | |
585 | /// Return true if this cmpxchg may spuriously fail. |
586 | bool isWeak() const { return getSubclassData<WeakField>(); } |
587 | |
588 | void setWeak(bool IsWeak) { setSubclassData<WeakField>(IsWeak); } |
589 | |
590 | /// Transparently provide more efficient getOperand methods. |
591 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
592 | |
593 | /// Returns the success ordering constraint of this cmpxchg instruction. |
594 | AtomicOrdering getSuccessOrdering() const { |
595 | return getSubclassData<SuccessOrderingField>(); |
596 | } |
597 | |
598 | /// Sets the success ordering constraint of this cmpxchg instruction. |
599 | void setSuccessOrdering(AtomicOrdering Ordering) { |
600 | assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 601, __PRETTY_FUNCTION__)) |
601 | "CmpXchg instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 601, __PRETTY_FUNCTION__)); |
602 | setSubclassData<SuccessOrderingField>(Ordering); |
603 | } |
604 | |
605 | /// Returns the failure ordering constraint of this cmpxchg instruction. |
606 | AtomicOrdering getFailureOrdering() const { |
607 | return getSubclassData<FailureOrderingField>(); |
608 | } |
609 | |
610 | /// Sets the failure ordering constraint of this cmpxchg instruction. |
611 | void setFailureOrdering(AtomicOrdering Ordering) { |
612 | assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 613, __PRETTY_FUNCTION__)) |
613 | "CmpXchg instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 613, __PRETTY_FUNCTION__)); |
614 | setSubclassData<FailureOrderingField>(Ordering); |
615 | } |
616 | |
617 | /// Returns the synchronization scope ID of this cmpxchg instruction. |
618 | SyncScope::ID getSyncScopeID() const { |
619 | return SSID; |
620 | } |
621 | |
622 | /// Sets the synchronization scope ID of this cmpxchg instruction. |
623 | void setSyncScopeID(SyncScope::ID SSID) { |
624 | this->SSID = SSID; |
625 | } |
626 | |
627 | Value *getPointerOperand() { return getOperand(0); } |
628 | const Value *getPointerOperand() const { return getOperand(0); } |
629 | static unsigned getPointerOperandIndex() { return 0U; } |
630 | |
631 | Value *getCompareOperand() { return getOperand(1); } |
632 | const Value *getCompareOperand() const { return getOperand(1); } |
633 | |
634 | Value *getNewValOperand() { return getOperand(2); } |
635 | const Value *getNewValOperand() const { return getOperand(2); } |
636 | |
637 | /// Returns the address space of the pointer operand. |
638 | unsigned getPointerAddressSpace() const { |
639 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
640 | } |
641 | |
642 | /// Returns the strongest permitted ordering on failure, given the |
643 | /// desired ordering on success. |
644 | /// |
645 | /// If the comparison in a cmpxchg operation fails, there is no atomic store |
646 | /// so release semantics cannot be provided. So this function drops explicit |
647 | /// Release requests from the AtomicOrdering. A SequentiallyConsistent |
648 | /// operation would remain SequentiallyConsistent. |
649 | static AtomicOrdering |
650 | getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) { |
651 | switch (SuccessOrdering) { |
652 | default: |
653 | llvm_unreachable("invalid cmpxchg success ordering")::llvm::llvm_unreachable_internal("invalid cmpxchg success ordering" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 653); |
654 | case AtomicOrdering::Release: |
655 | case AtomicOrdering::Monotonic: |
656 | return AtomicOrdering::Monotonic; |
657 | case AtomicOrdering::AcquireRelease: |
658 | case AtomicOrdering::Acquire: |
659 | return AtomicOrdering::Acquire; |
660 | case AtomicOrdering::SequentiallyConsistent: |
661 | return AtomicOrdering::SequentiallyConsistent; |
662 | } |
663 | } |
664 | |
665 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
666 | static bool classof(const Instruction *I) { |
667 | return I->getOpcode() == Instruction::AtomicCmpXchg; |
668 | } |
669 | static bool classof(const Value *V) { |
670 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
671 | } |
672 | |
673 | private: |
674 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
675 | // method so that subclasses cannot accidentally use it. |
676 | template <typename Bitfield> |
677 | void setSubclassData(typename Bitfield::Type Value) { |
678 | Instruction::setSubclassData<Bitfield>(Value); |
679 | } |
680 | |
681 | /// The synchronization scope ID of this cmpxchg instruction. Not quite |
682 | /// enough room in SubClassData for everything, so synchronization scope ID |
683 | /// gets its own field. |
684 | SyncScope::ID SSID; |
685 | }; |
686 | |
687 | template <> |
688 | struct OperandTraits<AtomicCmpXchgInst> : |
689 | public FixedNumOperandTraits<AtomicCmpXchgInst, 3> { |
690 | }; |
691 | |
692 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)AtomicCmpXchgInst::op_iterator AtomicCmpXchgInst::op_begin() { return OperandTraits<AtomicCmpXchgInst>::op_begin(this ); } AtomicCmpXchgInst::const_op_iterator AtomicCmpXchgInst:: op_begin() const { return OperandTraits<AtomicCmpXchgInst> ::op_begin(const_cast<AtomicCmpXchgInst*>(this)); } AtomicCmpXchgInst ::op_iterator AtomicCmpXchgInst::op_end() { return OperandTraits <AtomicCmpXchgInst>::op_end(this); } AtomicCmpXchgInst:: const_op_iterator AtomicCmpXchgInst::op_end() const { return OperandTraits <AtomicCmpXchgInst>::op_end(const_cast<AtomicCmpXchgInst *>(this)); } Value *AtomicCmpXchgInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<AtomicCmpXchgInst >::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 692, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<AtomicCmpXchgInst>::op_begin(const_cast <AtomicCmpXchgInst*>(this))[i_nocapture].get()); } void AtomicCmpXchgInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((i_nocapture < OperandTraits<AtomicCmpXchgInst> ::operands(this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 692, __PRETTY_FUNCTION__)); OperandTraits<AtomicCmpXchgInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned AtomicCmpXchgInst::getNumOperands() const { return OperandTraits <AtomicCmpXchgInst>::operands(this); } template <int Idx_nocapture> Use &AtomicCmpXchgInst::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &AtomicCmpXchgInst::Op() const { return this ->OpFrom<Idx_nocapture>(this); } |
693 | |
694 | //===----------------------------------------------------------------------===// |
695 | // AtomicRMWInst Class |
696 | //===----------------------------------------------------------------------===// |
697 | |
698 | /// an instruction that atomically reads a memory location, |
699 | /// combines it with another value, and then stores the result back. Returns |
700 | /// the old value. |
701 | /// |
702 | class AtomicRMWInst : public Instruction { |
703 | protected: |
704 | // Note: Instruction needs to be a friend here to call cloneImpl. |
705 | friend class Instruction; |
706 | |
707 | AtomicRMWInst *cloneImpl() const; |
708 | |
709 | public: |
710 | /// This enumeration lists the possible modifications atomicrmw can make. In |
711 | /// the descriptions, 'p' is the pointer to the instruction's memory location, |
712 | /// 'old' is the initial value of *p, and 'v' is the other value passed to the |
713 | /// instruction. These instructions always return 'old'. |
714 | enum BinOp : unsigned { |
715 | /// *p = v |
716 | Xchg, |
717 | /// *p = old + v |
718 | Add, |
719 | /// *p = old - v |
720 | Sub, |
721 | /// *p = old & v |
722 | And, |
723 | /// *p = ~(old & v) |
724 | Nand, |
725 | /// *p = old | v |
726 | Or, |
727 | /// *p = old ^ v |
728 | Xor, |
729 | /// *p = old >signed v ? old : v |
730 | Max, |
731 | /// *p = old <signed v ? old : v |
732 | Min, |
733 | /// *p = old >unsigned v ? old : v |
734 | UMax, |
735 | /// *p = old <unsigned v ? old : v |
736 | UMin, |
737 | |
738 | /// *p = old + v |
739 | FAdd, |
740 | |
741 | /// *p = old - v |
742 | FSub, |
743 | |
744 | FIRST_BINOP = Xchg, |
745 | LAST_BINOP = FSub, |
746 | BAD_BINOP |
747 | }; |
748 | |
749 | private: |
750 | template <unsigned Offset> |
751 | using AtomicOrderingBitfieldElement = |
752 | typename Bitfield::Element<AtomicOrdering, Offset, 3, |
753 | AtomicOrdering::LAST>; |
754 | |
755 | template <unsigned Offset> |
756 | using BinOpBitfieldElement = |
757 | typename Bitfield::Element<BinOp, Offset, 4, BinOp::LAST_BINOP>; |
758 | |
759 | public: |
760 | AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment, |
761 | AtomicOrdering Ordering, SyncScope::ID SSID, |
762 | Instruction *InsertBefore = nullptr); |
763 | AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment, |
764 | AtomicOrdering Ordering, SyncScope::ID SSID, |
765 | BasicBlock *InsertAtEnd); |
766 | |
767 | // allocate space for exactly two operands |
768 | void *operator new(size_t s) { |
769 | return User::operator new(s, 2); |
770 | } |
771 | |
772 | using VolatileField = BoolBitfieldElementT<0>; |
773 | using AtomicOrderingField = |
774 | AtomicOrderingBitfieldElementT<VolatileField::NextBit>; |
775 | using OperationField = BinOpBitfieldElement<AtomicOrderingField::NextBit>; |
776 | using AlignmentField = AlignmentBitfieldElementT<OperationField::NextBit>; |
777 | static_assert(Bitfield::areContiguous<VolatileField, AtomicOrderingField, |
778 | OperationField, AlignmentField>(), |
779 | "Bitfields must be contiguous"); |
780 | |
781 | BinOp getOperation() const { return getSubclassData<OperationField>(); } |
782 | |
783 | static StringRef getOperationName(BinOp Op); |
784 | |
785 | static bool isFPOperation(BinOp Op) { |
786 | switch (Op) { |
787 | case AtomicRMWInst::FAdd: |
788 | case AtomicRMWInst::FSub: |
789 | return true; |
790 | default: |
791 | return false; |
792 | } |
793 | } |
794 | |
795 | void setOperation(BinOp Operation) { |
796 | setSubclassData<OperationField>(Operation); |
797 | } |
798 | |
799 | /// Return the alignment of the memory that is being allocated by the |
800 | /// instruction. |
801 | Align getAlign() const { |
802 | return Align(1ULL << getSubclassData<AlignmentField>()); |
803 | } |
804 | |
805 | void setAlignment(Align Align) { |
806 | setSubclassData<AlignmentField>(Log2(Align)); |
807 | } |
808 | |
809 | /// Return true if this is a RMW on a volatile memory location. |
810 | /// |
811 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
812 | |
813 | /// Specify whether this is a volatile RMW or not. |
814 | /// |
815 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
816 | |
817 | /// Transparently provide more efficient getOperand methods. |
818 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
819 | |
820 | /// Returns the ordering constraint of this rmw instruction. |
821 | AtomicOrdering getOrdering() const { |
822 | return getSubclassData<AtomicOrderingField>(); |
823 | } |
824 | |
825 | /// Sets the ordering constraint of this rmw instruction. |
826 | void setOrdering(AtomicOrdering Ordering) { |
827 | assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 828, __PRETTY_FUNCTION__)) |
828 | "atomicrmw instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 828, __PRETTY_FUNCTION__)); |
829 | setSubclassData<AtomicOrderingField>(Ordering); |
830 | } |
831 | |
832 | /// Returns the synchronization scope ID of this rmw instruction. |
833 | SyncScope::ID getSyncScopeID() const { |
834 | return SSID; |
835 | } |
836 | |
837 | /// Sets the synchronization scope ID of this rmw instruction. |
838 | void setSyncScopeID(SyncScope::ID SSID) { |
839 | this->SSID = SSID; |
840 | } |
841 | |
842 | Value *getPointerOperand() { return getOperand(0); } |
843 | const Value *getPointerOperand() const { return getOperand(0); } |
844 | static unsigned getPointerOperandIndex() { return 0U; } |
845 | |
846 | Value *getValOperand() { return getOperand(1); } |
847 | const Value *getValOperand() const { return getOperand(1); } |
848 | |
849 | /// Returns the address space of the pointer operand. |
850 | unsigned getPointerAddressSpace() const { |
851 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
852 | } |
853 | |
854 | bool isFloatingPointOperation() const { |
855 | return isFPOperation(getOperation()); |
856 | } |
857 | |
858 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
859 | static bool classof(const Instruction *I) { |
860 | return I->getOpcode() == Instruction::AtomicRMW; |
861 | } |
862 | static bool classof(const Value *V) { |
863 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
864 | } |
865 | |
866 | private: |
867 | void Init(BinOp Operation, Value *Ptr, Value *Val, Align Align, |
868 | AtomicOrdering Ordering, SyncScope::ID SSID); |
869 | |
870 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
871 | // method so that subclasses cannot accidentally use it. |
872 | template <typename Bitfield> |
873 | void setSubclassData(typename Bitfield::Type Value) { |
874 | Instruction::setSubclassData<Bitfield>(Value); |
875 | } |
876 | |
877 | /// The synchronization scope ID of this rmw instruction. Not quite enough |
878 | /// room in SubClassData for everything, so synchronization scope ID gets its |
879 | /// own field. |
880 | SyncScope::ID SSID; |
881 | }; |
882 | |
883 | template <> |
884 | struct OperandTraits<AtomicRMWInst> |
885 | : public FixedNumOperandTraits<AtomicRMWInst,2> { |
886 | }; |
887 | |
888 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)AtomicRMWInst::op_iterator AtomicRMWInst::op_begin() { return OperandTraits<AtomicRMWInst>::op_begin(this); } AtomicRMWInst ::const_op_iterator AtomicRMWInst::op_begin() const { return OperandTraits <AtomicRMWInst>::op_begin(const_cast<AtomicRMWInst*> (this)); } AtomicRMWInst::op_iterator AtomicRMWInst::op_end() { return OperandTraits<AtomicRMWInst>::op_end(this); } AtomicRMWInst::const_op_iterator AtomicRMWInst::op_end() const { return OperandTraits<AtomicRMWInst>::op_end(const_cast <AtomicRMWInst*>(this)); } Value *AtomicRMWInst::getOperand (unsigned i_nocapture) const { ((i_nocapture < OperandTraits <AtomicRMWInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 888, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<AtomicRMWInst>::op_begin(const_cast< AtomicRMWInst*>(this))[i_nocapture].get()); } void AtomicRMWInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( i_nocapture < OperandTraits<AtomicRMWInst>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 888, __PRETTY_FUNCTION__)); OperandTraits<AtomicRMWInst> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned AtomicRMWInst ::getNumOperands() const { return OperandTraits<AtomicRMWInst >::operands(this); } template <int Idx_nocapture> Use &AtomicRMWInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & AtomicRMWInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
889 | |
890 | //===----------------------------------------------------------------------===// |
891 | // GetElementPtrInst Class |
892 | //===----------------------------------------------------------------------===// |
893 | |
894 | // checkGEPType - Simple wrapper function to give a better assertion failure |
895 | // message on bad indexes for a gep instruction. |
896 | // |
897 | inline Type *checkGEPType(Type *Ty) { |
898 | assert(Ty && "Invalid GetElementPtrInst indices for type!")((Ty && "Invalid GetElementPtrInst indices for type!" ) ? static_cast<void> (0) : __assert_fail ("Ty && \"Invalid GetElementPtrInst indices for type!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 898, __PRETTY_FUNCTION__)); |
899 | return Ty; |
900 | } |
901 | |
902 | /// an instruction for type-safe pointer arithmetic to |
903 | /// access elements of arrays and structs |
904 | /// |
905 | class GetElementPtrInst : public Instruction { |
906 | Type *SourceElementType; |
907 | Type *ResultElementType; |
908 | |
909 | GetElementPtrInst(const GetElementPtrInst &GEPI); |
910 | |
911 | /// Constructors - Create a getelementptr instruction with a base pointer an |
912 | /// list of indices. The first ctor can optionally insert before an existing |
913 | /// instruction, the second appends the new instruction to the specified |
914 | /// BasicBlock. |
915 | inline GetElementPtrInst(Type *PointeeType, Value *Ptr, |
916 | ArrayRef<Value *> IdxList, unsigned Values, |
917 | const Twine &NameStr, Instruction *InsertBefore); |
918 | inline GetElementPtrInst(Type *PointeeType, Value *Ptr, |
919 | ArrayRef<Value *> IdxList, unsigned Values, |
920 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
921 | |
922 | void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr); |
923 | |
924 | protected: |
925 | // Note: Instruction needs to be a friend here to call cloneImpl. |
926 | friend class Instruction; |
927 | |
928 | GetElementPtrInst *cloneImpl() const; |
929 | |
930 | public: |
931 | static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr, |
932 | ArrayRef<Value *> IdxList, |
933 | const Twine &NameStr = "", |
934 | Instruction *InsertBefore = nullptr) { |
935 | unsigned Values = 1 + unsigned(IdxList.size()); |
936 | if (!PointeeType) |
937 | PointeeType = |
938 | cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(); |
939 | else |
940 | assert(((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 942, __PRETTY_FUNCTION__)) |
941 | PointeeType ==((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 942, __PRETTY_FUNCTION__)) |
942 | cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 942, __PRETTY_FUNCTION__)); |
943 | return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values, |
944 | NameStr, InsertBefore); |
945 | } |
946 | |
947 | static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr, |
948 | ArrayRef<Value *> IdxList, |
949 | const Twine &NameStr, |
950 | BasicBlock *InsertAtEnd) { |
951 | unsigned Values = 1 + unsigned(IdxList.size()); |
952 | if (!PointeeType) |
953 | PointeeType = |
954 | cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(); |
955 | else |
956 | assert(((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 958, __PRETTY_FUNCTION__)) |
957 | PointeeType ==((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 958, __PRETTY_FUNCTION__)) |
958 | cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 958, __PRETTY_FUNCTION__)); |
959 | return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values, |
960 | NameStr, InsertAtEnd); |
961 | } |
962 | |
963 | /// Create an "inbounds" getelementptr. See the documentation for the |
964 | /// "inbounds" flag in LangRef.html for details. |
965 | static GetElementPtrInst *CreateInBounds(Value *Ptr, |
966 | ArrayRef<Value *> IdxList, |
967 | const Twine &NameStr = "", |
968 | Instruction *InsertBefore = nullptr){ |
969 | return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore); |
970 | } |
971 | |
972 | static GetElementPtrInst * |
973 | CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList, |
974 | const Twine &NameStr = "", |
975 | Instruction *InsertBefore = nullptr) { |
976 | GetElementPtrInst *GEP = |
977 | Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore); |
978 | GEP->setIsInBounds(true); |
979 | return GEP; |
980 | } |
981 | |
982 | static GetElementPtrInst *CreateInBounds(Value *Ptr, |
983 | ArrayRef<Value *> IdxList, |
984 | const Twine &NameStr, |
985 | BasicBlock *InsertAtEnd) { |
986 | return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd); |
987 | } |
988 | |
989 | static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr, |
990 | ArrayRef<Value *> IdxList, |
991 | const Twine &NameStr, |
992 | BasicBlock *InsertAtEnd) { |
993 | GetElementPtrInst *GEP = |
994 | Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd); |
995 | GEP->setIsInBounds(true); |
996 | return GEP; |
997 | } |
998 | |
999 | /// Transparently provide more efficient getOperand methods. |
1000 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1001 | |
1002 | Type *getSourceElementType() const { return SourceElementType; } |
1003 | |
1004 | void setSourceElementType(Type *Ty) { SourceElementType = Ty; } |
1005 | void setResultElementType(Type *Ty) { ResultElementType = Ty; } |
1006 | |
1007 | Type *getResultElementType() const { |
1008 | assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1009, __PRETTY_FUNCTION__)) |
1009 | cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1009, __PRETTY_FUNCTION__)); |
1010 | return ResultElementType; |
1011 | } |
1012 | |
1013 | /// Returns the address space of this instruction's pointer type. |
1014 | unsigned getAddressSpace() const { |
1015 | // Note that this is always the same as the pointer operand's address space |
1016 | // and that is cheaper to compute, so cheat here. |
1017 | return getPointerAddressSpace(); |
1018 | } |
1019 | |
1020 | /// Returns the result type of a getelementptr with the given source |
1021 | /// element type and indexes. |
1022 | /// |
1023 | /// Null is returned if the indices are invalid for the specified |
1024 | /// source element type. |
1025 | static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList); |
1026 | static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList); |
1027 | static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList); |
1028 | |
1029 | /// Return the type of the element at the given index of an indexable |
1030 | /// type. This is equivalent to "getIndexedType(Agg, {Zero, Idx})". |
1031 | /// |
1032 | /// Returns null if the type can't be indexed, or the given index is not |
1033 | /// legal for the given type. |
1034 | static Type *getTypeAtIndex(Type *Ty, Value *Idx); |
1035 | static Type *getTypeAtIndex(Type *Ty, uint64_t Idx); |
1036 | |
1037 | inline op_iterator idx_begin() { return op_begin()+1; } |
1038 | inline const_op_iterator idx_begin() const { return op_begin()+1; } |
1039 | inline op_iterator idx_end() { return op_end(); } |
1040 | inline const_op_iterator idx_end() const { return op_end(); } |
1041 | |
1042 | inline iterator_range<op_iterator> indices() { |
1043 | return make_range(idx_begin(), idx_end()); |
1044 | } |
1045 | |
1046 | inline iterator_range<const_op_iterator> indices() const { |
1047 | return make_range(idx_begin(), idx_end()); |
1048 | } |
1049 | |
1050 | Value *getPointerOperand() { |
1051 | return getOperand(0); |
1052 | } |
1053 | const Value *getPointerOperand() const { |
1054 | return getOperand(0); |
1055 | } |
1056 | static unsigned getPointerOperandIndex() { |
1057 | return 0U; // get index for modifying correct operand. |
1058 | } |
1059 | |
1060 | /// Method to return the pointer operand as a |
1061 | /// PointerType. |
1062 | Type *getPointerOperandType() const { |
1063 | return getPointerOperand()->getType(); |
1064 | } |
1065 | |
1066 | /// Returns the address space of the pointer operand. |
1067 | unsigned getPointerAddressSpace() const { |
1068 | return getPointerOperandType()->getPointerAddressSpace(); |
1069 | } |
1070 | |
1071 | /// Returns the pointer type returned by the GEP |
1072 | /// instruction, which may be a vector of pointers. |
1073 | static Type *getGEPReturnType(Type *ElTy, Value *Ptr, |
1074 | ArrayRef<Value *> IdxList) { |
1075 | Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)), |
1076 | Ptr->getType()->getPointerAddressSpace()); |
1077 | // Vector GEP |
1078 | if (auto *PtrVTy = dyn_cast<VectorType>(Ptr->getType())) { |
1079 | ElementCount EltCount = PtrVTy->getElementCount(); |
1080 | return VectorType::get(PtrTy, EltCount); |
1081 | } |
1082 | for (Value *Index : IdxList) |
1083 | if (auto *IndexVTy = dyn_cast<VectorType>(Index->getType())) { |
1084 | ElementCount EltCount = IndexVTy->getElementCount(); |
1085 | return VectorType::get(PtrTy, EltCount); |
1086 | } |
1087 | // Scalar GEP |
1088 | return PtrTy; |
1089 | } |
1090 | |
1091 | unsigned getNumIndices() const { // Note: always non-negative |
1092 | return getNumOperands() - 1; |
1093 | } |
1094 | |
1095 | bool hasIndices() const { |
1096 | return getNumOperands() > 1; |
1097 | } |
1098 | |
1099 | /// Return true if all of the indices of this GEP are |
1100 | /// zeros. If so, the result pointer and the first operand have the same |
1101 | /// value, just potentially different types. |
1102 | bool hasAllZeroIndices() const; |
1103 | |
1104 | /// Return true if all of the indices of this GEP are |
1105 | /// constant integers. If so, the result pointer and the first operand have |
1106 | /// a constant offset between them. |
1107 | bool hasAllConstantIndices() const; |
1108 | |
1109 | /// Set or clear the inbounds flag on this GEP instruction. |
1110 | /// See LangRef.html for the meaning of inbounds on a getelementptr. |
1111 | void setIsInBounds(bool b = true); |
1112 | |
1113 | /// Determine whether the GEP has the inbounds flag. |
1114 | bool isInBounds() const; |
1115 | |
1116 | /// Accumulate the constant address offset of this GEP if possible. |
1117 | /// |
1118 | /// This routine accepts an APInt into which it will accumulate the constant |
1119 | /// offset of this GEP if the GEP is in fact constant. If the GEP is not |
1120 | /// all-constant, it returns false and the value of the offset APInt is |
1121 | /// undefined (it is *not* preserved!). The APInt passed into this routine |
1122 | /// must be at least as wide as the IntPtr type for the address space of |
1123 | /// the base GEP pointer. |
1124 | bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const; |
1125 | |
1126 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1127 | static bool classof(const Instruction *I) { |
1128 | return (I->getOpcode() == Instruction::GetElementPtr); |
1129 | } |
1130 | static bool classof(const Value *V) { |
1131 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1132 | } |
1133 | }; |
1134 | |
1135 | template <> |
1136 | struct OperandTraits<GetElementPtrInst> : |
1137 | public VariadicOperandTraits<GetElementPtrInst, 1> { |
1138 | }; |
1139 | |
1140 | GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr, |
1141 | ArrayRef<Value *> IdxList, unsigned Values, |
1142 | const Twine &NameStr, |
1143 | Instruction *InsertBefore) |
1144 | : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr, |
1145 | OperandTraits<GetElementPtrInst>::op_end(this) - Values, |
1146 | Values, InsertBefore), |
1147 | SourceElementType(PointeeType), |
1148 | ResultElementType(getIndexedType(PointeeType, IdxList)) { |
1149 | assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1150, __PRETTY_FUNCTION__)) |
1150 | cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1150, __PRETTY_FUNCTION__)); |
1151 | init(Ptr, IdxList, NameStr); |
1152 | } |
1153 | |
1154 | GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr, |
1155 | ArrayRef<Value *> IdxList, unsigned Values, |
1156 | const Twine &NameStr, |
1157 | BasicBlock *InsertAtEnd) |
1158 | : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr, |
1159 | OperandTraits<GetElementPtrInst>::op_end(this) - Values, |
1160 | Values, InsertAtEnd), |
1161 | SourceElementType(PointeeType), |
1162 | ResultElementType(getIndexedType(PointeeType, IdxList)) { |
1163 | assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1164, __PRETTY_FUNCTION__)) |
1164 | cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1164, __PRETTY_FUNCTION__)); |
1165 | init(Ptr, IdxList, NameStr); |
1166 | } |
1167 | |
1168 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)GetElementPtrInst::op_iterator GetElementPtrInst::op_begin() { return OperandTraits<GetElementPtrInst>::op_begin(this ); } GetElementPtrInst::const_op_iterator GetElementPtrInst:: op_begin() const { return OperandTraits<GetElementPtrInst> ::op_begin(const_cast<GetElementPtrInst*>(this)); } GetElementPtrInst ::op_iterator GetElementPtrInst::op_end() { return OperandTraits <GetElementPtrInst>::op_end(this); } GetElementPtrInst:: const_op_iterator GetElementPtrInst::op_end() const { return OperandTraits <GetElementPtrInst>::op_end(const_cast<GetElementPtrInst *>(this)); } Value *GetElementPtrInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<GetElementPtrInst >::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1168, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<GetElementPtrInst>::op_begin(const_cast <GetElementPtrInst*>(this))[i_nocapture].get()); } void GetElementPtrInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((i_nocapture < OperandTraits<GetElementPtrInst> ::operands(this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1168, __PRETTY_FUNCTION__)); OperandTraits<GetElementPtrInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned GetElementPtrInst::getNumOperands() const { return OperandTraits <GetElementPtrInst>::operands(this); } template <int Idx_nocapture> Use &GetElementPtrInst::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &GetElementPtrInst::Op() const { return this ->OpFrom<Idx_nocapture>(this); } |
1169 | |
1170 | //===----------------------------------------------------------------------===// |
1171 | // ICmpInst Class |
1172 | //===----------------------------------------------------------------------===// |
1173 | |
1174 | /// This instruction compares its operands according to the predicate given |
1175 | /// to the constructor. It only operates on integers or pointers. The operands |
1176 | /// must be identical types. |
1177 | /// Represent an integer comparison operator. |
1178 | class ICmpInst: public CmpInst { |
1179 | void AssertOK() { |
1180 | assert(isIntPredicate() &&((isIntPredicate() && "Invalid ICmp predicate value") ? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1181, __PRETTY_FUNCTION__)) |
1181 | "Invalid ICmp predicate value")((isIntPredicate() && "Invalid ICmp predicate value") ? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1181, __PRETTY_FUNCTION__)); |
1182 | assert(getOperand(0)->getType() == getOperand(1)->getType() &&((getOperand(0)->getType() == getOperand(1)->getType() && "Both operands to ICmp instruction are not of the same type!" ) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1183, __PRETTY_FUNCTION__)) |
1183 | "Both operands to ICmp instruction are not of the same type!")((getOperand(0)->getType() == getOperand(1)->getType() && "Both operands to ICmp instruction are not of the same type!" ) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1183, __PRETTY_FUNCTION__)); |
1184 | // Check that the operands are the right type |
1185 | assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand (0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction" ) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1187, __PRETTY_FUNCTION__)) |
1186 | getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand (0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction" ) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1187, __PRETTY_FUNCTION__)) |
1187 | "Invalid operand types for ICmp instruction")(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand (0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction" ) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1187, __PRETTY_FUNCTION__)); |
1188 | } |
1189 | |
1190 | protected: |
1191 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1192 | friend class Instruction; |
1193 | |
1194 | /// Clone an identical ICmpInst |
1195 | ICmpInst *cloneImpl() const; |
1196 | |
1197 | public: |
1198 | /// Constructor with insert-before-instruction semantics. |
1199 | ICmpInst( |
1200 | Instruction *InsertBefore, ///< Where to insert |
1201 | Predicate pred, ///< The predicate to use for the comparison |
1202 | Value *LHS, ///< The left-hand-side of the expression |
1203 | Value *RHS, ///< The right-hand-side of the expression |
1204 | const Twine &NameStr = "" ///< Name of the instruction |
1205 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1206 | Instruction::ICmp, pred, LHS, RHS, NameStr, |
1207 | InsertBefore) { |
1208 | #ifndef NDEBUG |
1209 | AssertOK(); |
1210 | #endif |
1211 | } |
1212 | |
1213 | /// Constructor with insert-at-end semantics. |
1214 | ICmpInst( |
1215 | BasicBlock &InsertAtEnd, ///< Block to insert into. |
1216 | Predicate pred, ///< The predicate to use for the comparison |
1217 | Value *LHS, ///< The left-hand-side of the expression |
1218 | Value *RHS, ///< The right-hand-side of the expression |
1219 | const Twine &NameStr = "" ///< Name of the instruction |
1220 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1221 | Instruction::ICmp, pred, LHS, RHS, NameStr, |
1222 | &InsertAtEnd) { |
1223 | #ifndef NDEBUG |
1224 | AssertOK(); |
1225 | #endif |
1226 | } |
1227 | |
1228 | /// Constructor with no-insertion semantics |
1229 | ICmpInst( |
1230 | Predicate pred, ///< The predicate to use for the comparison |
1231 | Value *LHS, ///< The left-hand-side of the expression |
1232 | Value *RHS, ///< The right-hand-side of the expression |
1233 | const Twine &NameStr = "" ///< Name of the instruction |
1234 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1235 | Instruction::ICmp, pred, LHS, RHS, NameStr) { |
1236 | #ifndef NDEBUG |
1237 | AssertOK(); |
1238 | #endif |
1239 | } |
1240 | |
1241 | /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc. |
1242 | /// @returns the predicate that would be the result if the operand were |
1243 | /// regarded as signed. |
1244 | /// Return the signed version of the predicate |
1245 | Predicate getSignedPredicate() const { |
1246 | return getSignedPredicate(getPredicate()); |
1247 | } |
1248 | |
1249 | /// This is a static version that you can use without an instruction. |
1250 | /// Return the signed version of the predicate. |
1251 | static Predicate getSignedPredicate(Predicate pred); |
1252 | |
1253 | /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc. |
1254 | /// @returns the predicate that would be the result if the operand were |
1255 | /// regarded as unsigned. |
1256 | /// Return the unsigned version of the predicate |
1257 | Predicate getUnsignedPredicate() const { |
1258 | return getUnsignedPredicate(getPredicate()); |
1259 | } |
1260 | |
1261 | /// This is a static version that you can use without an instruction. |
1262 | /// Return the unsigned version of the predicate. |
1263 | static Predicate getUnsignedPredicate(Predicate pred); |
1264 | |
1265 | /// Return true if this predicate is either EQ or NE. This also |
1266 | /// tests for commutativity. |
1267 | static bool isEquality(Predicate P) { |
1268 | return P == ICMP_EQ || P == ICMP_NE; |
1269 | } |
1270 | |
1271 | /// Return true if this predicate is either EQ or NE. This also |
1272 | /// tests for commutativity. |
1273 | bool isEquality() const { |
1274 | return isEquality(getPredicate()); |
1275 | } |
1276 | |
1277 | /// @returns true if the predicate of this ICmpInst is commutative |
1278 | /// Determine if this relation is commutative. |
1279 | bool isCommutative() const { return isEquality(); } |
1280 | |
1281 | /// Return true if the predicate is relational (not EQ or NE). |
1282 | /// |
1283 | bool isRelational() const { |
1284 | return !isEquality(); |
1285 | } |
1286 | |
1287 | /// Return true if the predicate is relational (not EQ or NE). |
1288 | /// |
1289 | static bool isRelational(Predicate P) { |
1290 | return !isEquality(P); |
1291 | } |
1292 | |
1293 | /// Exchange the two operands to this instruction in such a way that it does |
1294 | /// not modify the semantics of the instruction. The predicate value may be |
1295 | /// changed to retain the same result if the predicate is order dependent |
1296 | /// (e.g. ult). |
1297 | /// Swap operands and adjust predicate. |
1298 | void swapOperands() { |
1299 | setPredicate(getSwappedPredicate()); |
1300 | Op<0>().swap(Op<1>()); |
1301 | } |
1302 | |
1303 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1304 | static bool classof(const Instruction *I) { |
1305 | return I->getOpcode() == Instruction::ICmp; |
1306 | } |
1307 | static bool classof(const Value *V) { |
1308 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1309 | } |
1310 | }; |
1311 | |
1312 | //===----------------------------------------------------------------------===// |
1313 | // FCmpInst Class |
1314 | //===----------------------------------------------------------------------===// |
1315 | |
1316 | /// This instruction compares its operands according to the predicate given |
1317 | /// to the constructor. It only operates on floating point values or packed |
1318 | /// vectors of floating point values. The operands must be identical types. |
1319 | /// Represents a floating point comparison operator. |
1320 | class FCmpInst: public CmpInst { |
1321 | void AssertOK() { |
1322 | assert(isFPPredicate() && "Invalid FCmp predicate value")((isFPPredicate() && "Invalid FCmp predicate value") ? static_cast<void> (0) : __assert_fail ("isFPPredicate() && \"Invalid FCmp predicate value\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1322, __PRETTY_FUNCTION__)); |
1323 | assert(getOperand(0)->getType() == getOperand(1)->getType() &&((getOperand(0)->getType() == getOperand(1)->getType() && "Both operands to FCmp instruction are not of the same type!" ) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1324, __PRETTY_FUNCTION__)) |
1324 | "Both operands to FCmp instruction are not of the same type!")((getOperand(0)->getType() == getOperand(1)->getType() && "Both operands to FCmp instruction are not of the same type!" ) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1324, __PRETTY_FUNCTION__)); |
1325 | // Check that the operands are the right type |
1326 | assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&((getOperand(0)->getType()->isFPOrFPVectorTy() && "Invalid operand types for FCmp instruction") ? static_cast< void> (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1327, __PRETTY_FUNCTION__)) |
1327 | "Invalid operand types for FCmp instruction")((getOperand(0)->getType()->isFPOrFPVectorTy() && "Invalid operand types for FCmp instruction") ? static_cast< void> (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1327, __PRETTY_FUNCTION__)); |
1328 | } |
1329 | |
1330 | protected: |
1331 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1332 | friend class Instruction; |
1333 | |
1334 | /// Clone an identical FCmpInst |
1335 | FCmpInst *cloneImpl() const; |
1336 | |
1337 | public: |
1338 | /// Constructor with insert-before-instruction semantics. |
1339 | FCmpInst( |
1340 | Instruction *InsertBefore, ///< Where to insert |
1341 | Predicate pred, ///< The predicate to use for the comparison |
1342 | Value *LHS, ///< The left-hand-side of the expression |
1343 | Value *RHS, ///< The right-hand-side of the expression |
1344 | const Twine &NameStr = "" ///< Name of the instruction |
1345 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1346 | Instruction::FCmp, pred, LHS, RHS, NameStr, |
1347 | InsertBefore) { |
1348 | AssertOK(); |
1349 | } |
1350 | |
1351 | /// Constructor with insert-at-end semantics. |
1352 | FCmpInst( |
1353 | BasicBlock &InsertAtEnd, ///< Block to insert into. |
1354 | Predicate pred, ///< The predicate to use for the comparison |
1355 | Value *LHS, ///< The left-hand-side of the expression |
1356 | Value *RHS, ///< The right-hand-side of the expression |
1357 | const Twine &NameStr = "" ///< Name of the instruction |
1358 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1359 | Instruction::FCmp, pred, LHS, RHS, NameStr, |
1360 | &InsertAtEnd) { |
1361 | AssertOK(); |
1362 | } |
1363 | |
1364 | /// Constructor with no-insertion semantics |
1365 | FCmpInst( |
1366 | Predicate Pred, ///< The predicate to use for the comparison |
1367 | Value *LHS, ///< The left-hand-side of the expression |
1368 | Value *RHS, ///< The right-hand-side of the expression |
1369 | const Twine &NameStr = "", ///< Name of the instruction |
1370 | Instruction *FlagsSource = nullptr |
1371 | ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS, |
1372 | RHS, NameStr, nullptr, FlagsSource) { |
1373 | AssertOK(); |
1374 | } |
1375 | |
1376 | /// @returns true if the predicate of this instruction is EQ or NE. |
1377 | /// Determine if this is an equality predicate. |
1378 | static bool isEquality(Predicate Pred) { |
1379 | return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ || |
1380 | Pred == FCMP_UNE; |
1381 | } |
1382 | |
1383 | /// @returns true if the predicate of this instruction is EQ or NE. |
1384 | /// Determine if this is an equality predicate. |
1385 | bool isEquality() const { return isEquality(getPredicate()); } |
1386 | |
1387 | /// @returns true if the predicate of this instruction is commutative. |
1388 | /// Determine if this is a commutative predicate. |
1389 | bool isCommutative() const { |
1390 | return isEquality() || |
1391 | getPredicate() == FCMP_FALSE || |
1392 | getPredicate() == FCMP_TRUE || |
1393 | getPredicate() == FCMP_ORD || |
1394 | getPredicate() == FCMP_UNO; |
1395 | } |
1396 | |
1397 | /// @returns true if the predicate is relational (not EQ or NE). |
1398 | /// Determine if this a relational predicate. |
1399 | bool isRelational() const { return !isEquality(); } |
1400 | |
1401 | /// Exchange the two operands to this instruction in such a way that it does |
1402 | /// not modify the semantics of the instruction. The predicate value may be |
1403 | /// changed to retain the same result if the predicate is order dependent |
1404 | /// (e.g. ult). |
1405 | /// Swap operands and adjust predicate. |
1406 | void swapOperands() { |
1407 | setPredicate(getSwappedPredicate()); |
1408 | Op<0>().swap(Op<1>()); |
1409 | } |
1410 | |
1411 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
1412 | static bool classof(const Instruction *I) { |
1413 | return I->getOpcode() == Instruction::FCmp; |
1414 | } |
1415 | static bool classof(const Value *V) { |
1416 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1417 | } |
1418 | }; |
1419 | |
1420 | //===----------------------------------------------------------------------===// |
1421 | /// This class represents a function call, abstracting a target |
1422 | /// machine's calling convention. This class uses low bit of the SubClassData |
1423 | /// field to indicate whether or not this is a tail call. The rest of the bits |
1424 | /// hold the calling convention of the call. |
1425 | /// |
1426 | class CallInst : public CallBase { |
1427 | CallInst(const CallInst &CI); |
1428 | |
1429 | /// Construct a CallInst given a range of arguments. |
1430 | /// Construct a CallInst from a range of arguments |
1431 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1432 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1433 | Instruction *InsertBefore); |
1434 | |
1435 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1436 | const Twine &NameStr, Instruction *InsertBefore) |
1437 | : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {} |
1438 | |
1439 | /// Construct a CallInst given a range of arguments. |
1440 | /// Construct a CallInst from a range of arguments |
1441 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1442 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1443 | BasicBlock *InsertAtEnd); |
1444 | |
1445 | explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr, |
1446 | Instruction *InsertBefore); |
1447 | |
1448 | CallInst(FunctionType *ty, Value *F, const Twine &NameStr, |
1449 | BasicBlock *InsertAtEnd); |
1450 | |
1451 | void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args, |
1452 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr); |
1453 | void init(FunctionType *FTy, Value *Func, const Twine &NameStr); |
1454 | |
1455 | /// Compute the number of operands to allocate. |
1456 | static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) { |
1457 | // We need one operand for the called function, plus the input operand |
1458 | // counts provided. |
1459 | return 1 + NumArgs + NumBundleInputs; |
1460 | } |
1461 | |
1462 | protected: |
1463 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1464 | friend class Instruction; |
1465 | |
1466 | CallInst *cloneImpl() const; |
1467 | |
1468 | public: |
1469 | static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "", |
1470 | Instruction *InsertBefore = nullptr) { |
1471 | return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore); |
1472 | } |
1473 | |
1474 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1475 | const Twine &NameStr, |
1476 | Instruction *InsertBefore = nullptr) { |
1477 | return new (ComputeNumOperands(Args.size())) |
1478 | CallInst(Ty, Func, Args, None, NameStr, InsertBefore); |
1479 | } |
1480 | |
1481 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1482 | ArrayRef<OperandBundleDef> Bundles = None, |
1483 | const Twine &NameStr = "", |
1484 | Instruction *InsertBefore = nullptr) { |
1485 | const int NumOperands = |
1486 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
1487 | const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
1488 | |
1489 | return new (NumOperands, DescriptorBytes) |
1490 | CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore); |
1491 | } |
1492 | |
1493 | static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr, |
1494 | BasicBlock *InsertAtEnd) { |
1495 | return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd); |
1496 | } |
1497 | |
1498 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1499 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1500 | return new (ComputeNumOperands(Args.size())) |
1501 | CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd); |
1502 | } |
1503 | |
1504 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1505 | ArrayRef<OperandBundleDef> Bundles, |
1506 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1507 | const int NumOperands = |
1508 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
1509 | const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
1510 | |
1511 | return new (NumOperands, DescriptorBytes) |
1512 | CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd); |
1513 | } |
1514 | |
1515 | static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "", |
1516 | Instruction *InsertBefore = nullptr) { |
1517 | return Create(Func.getFunctionType(), Func.getCallee(), NameStr, |
1518 | InsertBefore); |
1519 | } |
1520 | |
1521 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1522 | ArrayRef<OperandBundleDef> Bundles = None, |
1523 | const Twine &NameStr = "", |
1524 | Instruction *InsertBefore = nullptr) { |
1525 | return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles, |
1526 | NameStr, InsertBefore); |
1527 | } |
1528 | |
1529 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1530 | const Twine &NameStr, |
1531 | Instruction *InsertBefore = nullptr) { |
1532 | return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr, |
1533 | InsertBefore); |
1534 | } |
1535 | |
1536 | static CallInst *Create(FunctionCallee Func, const Twine &NameStr, |
1537 | BasicBlock *InsertAtEnd) { |
1538 | return Create(Func.getFunctionType(), Func.getCallee(), NameStr, |
1539 | InsertAtEnd); |
1540 | } |
1541 | |
1542 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1543 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1544 | return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr, |
1545 | InsertAtEnd); |
1546 | } |
1547 | |
1548 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1549 | ArrayRef<OperandBundleDef> Bundles, |
1550 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1551 | return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles, |
1552 | NameStr, InsertAtEnd); |
1553 | } |
1554 | |
1555 | /// Create a clone of \p CI with a different set of operand bundles and |
1556 | /// insert it before \p InsertPt. |
1557 | /// |
1558 | /// The returned call instruction is identical \p CI in every way except that |
1559 | /// the operand bundles for the new instruction are set to the operand bundles |
1560 | /// in \p Bundles. |
1561 | static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles, |
1562 | Instruction *InsertPt = nullptr); |
1563 | |
1564 | /// Create a clone of \p CI with a different set of operand bundles and |
1565 | /// insert it before \p InsertPt. |
1566 | /// |
1567 | /// The returned call instruction is identical \p CI in every way except that |
1568 | /// the operand bundle for the new instruction is set to the operand bundle |
1569 | /// in \p Bundle. |
1570 | static CallInst *CreateWithReplacedBundle(CallInst *CI, |
1571 | OperandBundleDef Bundle, |
1572 | Instruction *InsertPt = nullptr); |
1573 | |
1574 | /// Generate the IR for a call to malloc: |
1575 | /// 1. Compute the malloc call's argument as the specified type's size, |
1576 | /// possibly multiplied by the array size if the array size is not |
1577 | /// constant 1. |
1578 | /// 2. Call malloc with that argument. |
1579 | /// 3. Bitcast the result of the malloc call to the specified type. |
1580 | static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, |
1581 | Type *AllocTy, Value *AllocSize, |
1582 | Value *ArraySize = nullptr, |
1583 | Function *MallocF = nullptr, |
1584 | const Twine &Name = ""); |
1585 | static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy, |
1586 | Type *AllocTy, Value *AllocSize, |
1587 | Value *ArraySize = nullptr, |
1588 | Function *MallocF = nullptr, |
1589 | const Twine &Name = ""); |
1590 | static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, |
1591 | Type *AllocTy, Value *AllocSize, |
1592 | Value *ArraySize = nullptr, |
1593 | ArrayRef<OperandBundleDef> Bundles = None, |
1594 | Function *MallocF = nullptr, |
1595 | const Twine &Name = ""); |
1596 | static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy, |
1597 | Type *AllocTy, Value *AllocSize, |
1598 | Value *ArraySize = nullptr, |
1599 | ArrayRef<OperandBundleDef> Bundles = None, |
1600 | Function *MallocF = nullptr, |
1601 | const Twine &Name = ""); |
1602 | /// Generate the IR for a call to the builtin free function. |
1603 | static Instruction *CreateFree(Value *Source, Instruction *InsertBefore); |
1604 | static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd); |
1605 | static Instruction *CreateFree(Value *Source, |
1606 | ArrayRef<OperandBundleDef> Bundles, |
1607 | Instruction *InsertBefore); |
1608 | static Instruction *CreateFree(Value *Source, |
1609 | ArrayRef<OperandBundleDef> Bundles, |
1610 | BasicBlock *InsertAtEnd); |
1611 | |
1612 | // Note that 'musttail' implies 'tail'. |
1613 | enum TailCallKind : unsigned { |
1614 | TCK_None = 0, |
1615 | TCK_Tail = 1, |
1616 | TCK_MustTail = 2, |
1617 | TCK_NoTail = 3, |
1618 | TCK_LAST = TCK_NoTail |
1619 | }; |
1620 | |
1621 | using TailCallKindField = Bitfield::Element<TailCallKind, 0, 2, TCK_LAST>; |
1622 | static_assert( |
1623 | Bitfield::areContiguous<TailCallKindField, CallBase::CallingConvField>(), |
1624 | "Bitfields must be contiguous"); |
1625 | |
1626 | TailCallKind getTailCallKind() const { |
1627 | return getSubclassData<TailCallKindField>(); |
1628 | } |
1629 | |
1630 | bool isTailCall() const { |
1631 | TailCallKind Kind = getTailCallKind(); |
1632 | return Kind == TCK_Tail || Kind == TCK_MustTail; |
1633 | } |
1634 | |
1635 | bool isMustTailCall() const { return getTailCallKind() == TCK_MustTail; } |
1636 | |
1637 | bool isNoTailCall() const { return getTailCallKind() == TCK_NoTail; } |
1638 | |
1639 | void setTailCallKind(TailCallKind TCK) { |
1640 | setSubclassData<TailCallKindField>(TCK); |
1641 | } |
1642 | |
1643 | void setTailCall(bool IsTc = true) { |
1644 | setTailCallKind(IsTc ? TCK_Tail : TCK_None); |
1645 | } |
1646 | |
1647 | /// Return true if the call can return twice |
1648 | bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); } |
1649 | void setCanReturnTwice() { |
1650 | addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice); |
1651 | } |
1652 | |
1653 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1654 | static bool classof(const Instruction *I) { |
1655 | return I->getOpcode() == Instruction::Call; |
1656 | } |
1657 | static bool classof(const Value *V) { |
1658 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1659 | } |
1660 | |
1661 | /// Updates profile metadata by scaling it by \p S / \p T. |
1662 | void updateProfWeight(uint64_t S, uint64_t T); |
1663 | |
1664 | private: |
1665 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
1666 | // method so that subclasses cannot accidentally use it. |
1667 | template <typename Bitfield> |
1668 | void setSubclassData(typename Bitfield::Type Value) { |
1669 | Instruction::setSubclassData<Bitfield>(Value); |
1670 | } |
1671 | }; |
1672 | |
1673 | CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1674 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1675 | BasicBlock *InsertAtEnd) |
1676 | : CallBase(Ty->getReturnType(), Instruction::Call, |
1677 | OperandTraits<CallBase>::op_end(this) - |
1678 | (Args.size() + CountBundleInputs(Bundles) + 1), |
1679 | unsigned(Args.size() + CountBundleInputs(Bundles) + 1), |
1680 | InsertAtEnd) { |
1681 | init(Ty, Func, Args, Bundles, NameStr); |
1682 | } |
1683 | |
1684 | CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1685 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1686 | Instruction *InsertBefore) |
1687 | : CallBase(Ty->getReturnType(), Instruction::Call, |
1688 | OperandTraits<CallBase>::op_end(this) - |
1689 | (Args.size() + CountBundleInputs(Bundles) + 1), |
1690 | unsigned(Args.size() + CountBundleInputs(Bundles) + 1), |
1691 | InsertBefore) { |
1692 | init(Ty, Func, Args, Bundles, NameStr); |
1693 | } |
1694 | |
1695 | //===----------------------------------------------------------------------===// |
1696 | // SelectInst Class |
1697 | //===----------------------------------------------------------------------===// |
1698 | |
1699 | /// This class represents the LLVM 'select' instruction. |
1700 | /// |
1701 | class SelectInst : public Instruction { |
1702 | SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr, |
1703 | Instruction *InsertBefore) |
1704 | : Instruction(S1->getType(), Instruction::Select, |
1705 | &Op<0>(), 3, InsertBefore) { |
1706 | init(C, S1, S2); |
1707 | setName(NameStr); |
1708 | } |
1709 | |
1710 | SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr, |
1711 | BasicBlock *InsertAtEnd) |
1712 | : Instruction(S1->getType(), Instruction::Select, |
1713 | &Op<0>(), 3, InsertAtEnd) { |
1714 | init(C, S1, S2); |
1715 | setName(NameStr); |
1716 | } |
1717 | |
1718 | void init(Value *C, Value *S1, Value *S2) { |
1719 | assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select")((!areInvalidOperands(C, S1, S2) && "Invalid operands for select" ) ? static_cast<void> (0) : __assert_fail ("!areInvalidOperands(C, S1, S2) && \"Invalid operands for select\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1719, __PRETTY_FUNCTION__)); |
1720 | Op<0>() = C; |
1721 | Op<1>() = S1; |
1722 | Op<2>() = S2; |
1723 | } |
1724 | |
1725 | protected: |
1726 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1727 | friend class Instruction; |
1728 | |
1729 | SelectInst *cloneImpl() const; |
1730 | |
1731 | public: |
1732 | static SelectInst *Create(Value *C, Value *S1, Value *S2, |
1733 | const Twine &NameStr = "", |
1734 | Instruction *InsertBefore = nullptr, |
1735 | Instruction *MDFrom = nullptr) { |
1736 | SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore); |
1737 | if (MDFrom) |
1738 | Sel->copyMetadata(*MDFrom); |
1739 | return Sel; |
1740 | } |
1741 | |
1742 | static SelectInst *Create(Value *C, Value *S1, Value *S2, |
1743 | const Twine &NameStr, |
1744 | BasicBlock *InsertAtEnd) { |
1745 | return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd); |
1746 | } |
1747 | |
1748 | const Value *getCondition() const { return Op<0>(); } |
1749 | const Value *getTrueValue() const { return Op<1>(); } |
1750 | const Value *getFalseValue() const { return Op<2>(); } |
1751 | Value *getCondition() { return Op<0>(); } |
1752 | Value *getTrueValue() { return Op<1>(); } |
1753 | Value *getFalseValue() { return Op<2>(); } |
1754 | |
1755 | void setCondition(Value *V) { Op<0>() = V; } |
1756 | void setTrueValue(Value *V) { Op<1>() = V; } |
1757 | void setFalseValue(Value *V) { Op<2>() = V; } |
1758 | |
1759 | /// Swap the true and false values of the select instruction. |
1760 | /// This doesn't swap prof metadata. |
1761 | void swapValues() { Op<1>().swap(Op<2>()); } |
1762 | |
1763 | /// Return a string if the specified operands are invalid |
1764 | /// for a select operation, otherwise return null. |
1765 | static const char *areInvalidOperands(Value *Cond, Value *True, Value *False); |
1766 | |
1767 | /// Transparently provide more efficient getOperand methods. |
1768 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1769 | |
1770 | OtherOps getOpcode() const { |
1771 | return static_cast<OtherOps>(Instruction::getOpcode()); |
1772 | } |
1773 | |
1774 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1775 | static bool classof(const Instruction *I) { |
1776 | return I->getOpcode() == Instruction::Select; |
1777 | } |
1778 | static bool classof(const Value *V) { |
1779 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1780 | } |
1781 | }; |
1782 | |
1783 | template <> |
1784 | struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> { |
1785 | }; |
1786 | |
1787 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)SelectInst::op_iterator SelectInst::op_begin() { return OperandTraits <SelectInst>::op_begin(this); } SelectInst::const_op_iterator SelectInst::op_begin() const { return OperandTraits<SelectInst >::op_begin(const_cast<SelectInst*>(this)); } SelectInst ::op_iterator SelectInst::op_end() { return OperandTraits< SelectInst>::op_end(this); } SelectInst::const_op_iterator SelectInst::op_end() const { return OperandTraits<SelectInst >::op_end(const_cast<SelectInst*>(this)); } Value *SelectInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<SelectInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1787, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<SelectInst>::op_begin(const_cast<SelectInst *>(this))[i_nocapture].get()); } void SelectInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<SelectInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1787, __PRETTY_FUNCTION__)); OperandTraits<SelectInst> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned SelectInst ::getNumOperands() const { return OperandTraits<SelectInst >::operands(this); } template <int Idx_nocapture> Use &SelectInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & SelectInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
1788 | |
1789 | //===----------------------------------------------------------------------===// |
1790 | // VAArgInst Class |
1791 | //===----------------------------------------------------------------------===// |
1792 | |
1793 | /// This class represents the va_arg llvm instruction, which returns |
1794 | /// an argument of the specified type given a va_list and increments that list |
1795 | /// |
1796 | class VAArgInst : public UnaryInstruction { |
1797 | protected: |
1798 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1799 | friend class Instruction; |
1800 | |
1801 | VAArgInst *cloneImpl() const; |
1802 | |
1803 | public: |
1804 | VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "", |
1805 | Instruction *InsertBefore = nullptr) |
1806 | : UnaryInstruction(Ty, VAArg, List, InsertBefore) { |
1807 | setName(NameStr); |
1808 | } |
1809 | |
1810 | VAArgInst(Value *List, Type *Ty, const Twine &NameStr, |
1811 | BasicBlock *InsertAtEnd) |
1812 | : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) { |
1813 | setName(NameStr); |
1814 | } |
1815 | |
1816 | Value *getPointerOperand() { return getOperand(0); } |
1817 | const Value *getPointerOperand() const { return getOperand(0); } |
1818 | static unsigned getPointerOperandIndex() { return 0U; } |
1819 | |
1820 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1821 | static bool classof(const Instruction *I) { |
1822 | return I->getOpcode() == VAArg; |
1823 | } |
1824 | static bool classof(const Value *V) { |
1825 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1826 | } |
1827 | }; |
1828 | |
1829 | //===----------------------------------------------------------------------===// |
1830 | // ExtractElementInst Class |
1831 | //===----------------------------------------------------------------------===// |
1832 | |
1833 | /// This instruction extracts a single (scalar) |
1834 | /// element from a VectorType value |
1835 | /// |
1836 | class ExtractElementInst : public Instruction { |
1837 | ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "", |
1838 | Instruction *InsertBefore = nullptr); |
1839 | ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr, |
1840 | BasicBlock *InsertAtEnd); |
1841 | |
1842 | protected: |
1843 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1844 | friend class Instruction; |
1845 | |
1846 | ExtractElementInst *cloneImpl() const; |
1847 | |
1848 | public: |
1849 | static ExtractElementInst *Create(Value *Vec, Value *Idx, |
1850 | const Twine &NameStr = "", |
1851 | Instruction *InsertBefore = nullptr) { |
1852 | return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore); |
1853 | } |
1854 | |
1855 | static ExtractElementInst *Create(Value *Vec, Value *Idx, |
1856 | const Twine &NameStr, |
1857 | BasicBlock *InsertAtEnd) { |
1858 | return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd); |
1859 | } |
1860 | |
1861 | /// Return true if an extractelement instruction can be |
1862 | /// formed with the specified operands. |
1863 | static bool isValidOperands(const Value *Vec, const Value *Idx); |
1864 | |
1865 | Value *getVectorOperand() { return Op<0>(); } |
1866 | Value *getIndexOperand() { return Op<1>(); } |
1867 | const Value *getVectorOperand() const { return Op<0>(); } |
1868 | const Value *getIndexOperand() const { return Op<1>(); } |
1869 | |
1870 | VectorType *getVectorOperandType() const { |
1871 | return cast<VectorType>(getVectorOperand()->getType()); |
1872 | } |
1873 | |
1874 | /// Transparently provide more efficient getOperand methods. |
1875 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1876 | |
1877 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1878 | static bool classof(const Instruction *I) { |
1879 | return I->getOpcode() == Instruction::ExtractElement; |
1880 | } |
1881 | static bool classof(const Value *V) { |
1882 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1883 | } |
1884 | }; |
1885 | |
1886 | template <> |
1887 | struct OperandTraits<ExtractElementInst> : |
1888 | public FixedNumOperandTraits<ExtractElementInst, 2> { |
1889 | }; |
1890 | |
1891 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)ExtractElementInst::op_iterator ExtractElementInst::op_begin( ) { return OperandTraits<ExtractElementInst>::op_begin( this); } ExtractElementInst::const_op_iterator ExtractElementInst ::op_begin() const { return OperandTraits<ExtractElementInst >::op_begin(const_cast<ExtractElementInst*>(this)); } ExtractElementInst::op_iterator ExtractElementInst::op_end() { return OperandTraits<ExtractElementInst>::op_end(this ); } ExtractElementInst::const_op_iterator ExtractElementInst ::op_end() const { return OperandTraits<ExtractElementInst >::op_end(const_cast<ExtractElementInst*>(this)); } Value *ExtractElementInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<ExtractElementInst>:: operands(this) && "getOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1891, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<ExtractElementInst>::op_begin(const_cast <ExtractElementInst*>(this))[i_nocapture].get()); } void ExtractElementInst::setOperand(unsigned i_nocapture, Value * Val_nocapture) { ((i_nocapture < OperandTraits<ExtractElementInst >::operands(this) && "setOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1891, __PRETTY_FUNCTION__)); OperandTraits<ExtractElementInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ExtractElementInst::getNumOperands() const { return OperandTraits <ExtractElementInst>::operands(this); } template <int Idx_nocapture> Use &ExtractElementInst::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &ExtractElementInst::Op() const { return this->OpFrom<Idx_nocapture>(this); } |
1892 | |
1893 | //===----------------------------------------------------------------------===// |
1894 | // InsertElementInst Class |
1895 | //===----------------------------------------------------------------------===// |
1896 | |
1897 | /// This instruction inserts a single (scalar) |
1898 | /// element into a VectorType value |
1899 | /// |
1900 | class InsertElementInst : public Instruction { |
1901 | InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, |
1902 | const Twine &NameStr = "", |
1903 | Instruction *InsertBefore = nullptr); |
1904 | InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr, |
1905 | BasicBlock *InsertAtEnd); |
1906 | |
1907 | protected: |
1908 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1909 | friend class Instruction; |
1910 | |
1911 | InsertElementInst *cloneImpl() const; |
1912 | |
1913 | public: |
1914 | static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx, |
1915 | const Twine &NameStr = "", |
1916 | Instruction *InsertBefore = nullptr) { |
1917 | return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore); |
1918 | } |
1919 | |
1920 | static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx, |
1921 | const Twine &NameStr, |
1922 | BasicBlock *InsertAtEnd) { |
1923 | return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd); |
1924 | } |
1925 | |
1926 | /// Return true if an insertelement instruction can be |
1927 | /// formed with the specified operands. |
1928 | static bool isValidOperands(const Value *Vec, const Value *NewElt, |
1929 | const Value *Idx); |
1930 | |
1931 | /// Overload to return most specific vector type. |
1932 | /// |
1933 | VectorType *getType() const { |
1934 | return cast<VectorType>(Instruction::getType()); |
1935 | } |
1936 | |
1937 | /// Transparently provide more efficient getOperand methods. |
1938 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1939 | |
1940 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1941 | static bool classof(const Instruction *I) { |
1942 | return I->getOpcode() == Instruction::InsertElement; |
1943 | } |
1944 | static bool classof(const Value *V) { |
1945 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1946 | } |
1947 | }; |
1948 | |
1949 | template <> |
1950 | struct OperandTraits<InsertElementInst> : |
1951 | public FixedNumOperandTraits<InsertElementInst, 3> { |
1952 | }; |
1953 | |
1954 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)InsertElementInst::op_iterator InsertElementInst::op_begin() { return OperandTraits<InsertElementInst>::op_begin(this ); } InsertElementInst::const_op_iterator InsertElementInst:: op_begin() const { return OperandTraits<InsertElementInst> ::op_begin(const_cast<InsertElementInst*>(this)); } InsertElementInst ::op_iterator InsertElementInst::op_end() { return OperandTraits <InsertElementInst>::op_end(this); } InsertElementInst:: const_op_iterator InsertElementInst::op_end() const { return OperandTraits <InsertElementInst>::op_end(const_cast<InsertElementInst *>(this)); } Value *InsertElementInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<InsertElementInst >::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1954, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<InsertElementInst>::op_begin(const_cast <InsertElementInst*>(this))[i_nocapture].get()); } void InsertElementInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((i_nocapture < OperandTraits<InsertElementInst> ::operands(this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 1954, __PRETTY_FUNCTION__)); OperandTraits<InsertElementInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned InsertElementInst::getNumOperands() const { return OperandTraits <InsertElementInst>::operands(this); } template <int Idx_nocapture> Use &InsertElementInst::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &InsertElementInst::Op() const { return this ->OpFrom<Idx_nocapture>(this); } |
1955 | |
1956 | //===----------------------------------------------------------------------===// |
1957 | // ShuffleVectorInst Class |
1958 | //===----------------------------------------------------------------------===// |
1959 | |
1960 | constexpr int UndefMaskElem = -1; |
1961 | |
1962 | /// This instruction constructs a fixed permutation of two |
1963 | /// input vectors. |
1964 | /// |
1965 | /// For each element of the result vector, the shuffle mask selects an element |
1966 | /// from one of the input vectors to copy to the result. Non-negative elements |
1967 | /// in the mask represent an index into the concatenated pair of input vectors. |
1968 | /// UndefMaskElem (-1) specifies that the result element is undefined. |
1969 | /// |
1970 | /// For scalable vectors, all the elements of the mask must be 0 or -1. This |
1971 | /// requirement may be relaxed in the future. |
1972 | class ShuffleVectorInst : public Instruction { |
1973 | SmallVector<int, 4> ShuffleMask; |
1974 | Constant *ShuffleMaskForBitcode; |
1975 | |
1976 | protected: |
1977 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1978 | friend class Instruction; |
1979 | |
1980 | ShuffleVectorInst *cloneImpl() const; |
1981 | |
1982 | public: |
1983 | ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, |
1984 | const Twine &NameStr = "", |
1985 | Instruction *InsertBefor = nullptr); |
1986 | ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, |
1987 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
1988 | ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, |
1989 | const Twine &NameStr = "", |
1990 | Instruction *InsertBefor = nullptr); |
1991 | ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, |
1992 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
1993 | |
1994 | void *operator new(size_t s) { return User::operator new(s, 2); } |
1995 | |
1996 | /// Swap the operands and adjust the mask to preserve the semantics |
1997 | /// of the instruction. |
1998 | void commute(); |
1999 | |
2000 | /// Return true if a shufflevector instruction can be |
2001 | /// formed with the specified operands. |
2002 | static bool isValidOperands(const Value *V1, const Value *V2, |
2003 | const Value *Mask); |
2004 | static bool isValidOperands(const Value *V1, const Value *V2, |
2005 | ArrayRef<int> Mask); |
2006 | |
2007 | /// Overload to return most specific vector type. |
2008 | /// |
2009 | VectorType *getType() const { |
2010 | return cast<VectorType>(Instruction::getType()); |
2011 | } |
2012 | |
2013 | /// Transparently provide more efficient getOperand methods. |
2014 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2015 | |
2016 | /// Return the shuffle mask value of this instruction for the given element |
2017 | /// index. Return UndefMaskElem if the element is undef. |
2018 | int getMaskValue(unsigned Elt) const { return ShuffleMask[Elt]; } |
2019 | |
2020 | /// Convert the input shuffle mask operand to a vector of integers. Undefined |
2021 | /// elements of the mask are returned as UndefMaskElem. |
2022 | static void getShuffleMask(const Constant *Mask, |
2023 | SmallVectorImpl<int> &Result); |
2024 | |
2025 | /// Return the mask for this instruction as a vector of integers. Undefined |
2026 | /// elements of the mask are returned as UndefMaskElem. |
2027 | void getShuffleMask(SmallVectorImpl<int> &Result) const { |
2028 | Result.assign(ShuffleMask.begin(), ShuffleMask.end()); |
2029 | } |
2030 | |
2031 | /// Return the mask for this instruction, for use in bitcode. |
2032 | /// |
2033 | /// TODO: This is temporary until we decide a new bitcode encoding for |
2034 | /// shufflevector. |
2035 | Constant *getShuffleMaskForBitcode() const { return ShuffleMaskForBitcode; } |
2036 | |
2037 | static Constant *convertShuffleMaskForBitcode(ArrayRef<int> Mask, |
2038 | Type *ResultTy); |
2039 | |
2040 | void setShuffleMask(ArrayRef<int> Mask); |
2041 | |
2042 | ArrayRef<int> getShuffleMask() const { return ShuffleMask; } |
2043 | |
2044 | /// Return true if this shuffle returns a vector with a different number of |
2045 | /// elements than its source vectors. |
2046 | /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3> |
2047 | /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5> |
2048 | bool changesLength() const { |
2049 | unsigned NumSourceElts = cast<VectorType>(Op<0>()->getType()) |
2050 | ->getElementCount() |
2051 | .getKnownMinValue(); |
2052 | unsigned NumMaskElts = ShuffleMask.size(); |
2053 | return NumSourceElts != NumMaskElts; |
2054 | } |
2055 | |
2056 | /// Return true if this shuffle returns a vector with a greater number of |
2057 | /// elements than its source vectors. |
2058 | /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3> |
2059 | bool increasesLength() const { |
2060 | unsigned NumSourceElts = |
2061 | cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); |
2062 | unsigned NumMaskElts = ShuffleMask.size(); |
2063 | return NumSourceElts < NumMaskElts; |
2064 | } |
2065 | |
2066 | /// Return true if this shuffle mask chooses elements from exactly one source |
2067 | /// vector. |
2068 | /// Example: <7,5,undef,7> |
2069 | /// This assumes that vector operands are the same length as the mask. |
2070 | static bool isSingleSourceMask(ArrayRef<int> Mask); |
2071 | static bool isSingleSourceMask(const Constant *Mask) { |
2072 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2072, __PRETTY_FUNCTION__)); |
2073 | SmallVector<int, 16> MaskAsInts; |
2074 | getShuffleMask(Mask, MaskAsInts); |
2075 | return isSingleSourceMask(MaskAsInts); |
2076 | } |
2077 | |
2078 | /// Return true if this shuffle chooses elements from exactly one source |
2079 | /// vector without changing the length of that vector. |
2080 | /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3> |
2081 | /// TODO: Optionally allow length-changing shuffles. |
2082 | bool isSingleSource() const { |
2083 | return !changesLength() && isSingleSourceMask(ShuffleMask); |
2084 | } |
2085 | |
2086 | /// Return true if this shuffle mask chooses elements from exactly one source |
2087 | /// vector without lane crossings. A shuffle using this mask is not |
2088 | /// necessarily a no-op because it may change the number of elements from its |
2089 | /// input vectors or it may provide demanded bits knowledge via undef lanes. |
2090 | /// Example: <undef,undef,2,3> |
2091 | static bool isIdentityMask(ArrayRef<int> Mask); |
2092 | static bool isIdentityMask(const Constant *Mask) { |
2093 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2093, __PRETTY_FUNCTION__)); |
2094 | SmallVector<int, 16> MaskAsInts; |
2095 | getShuffleMask(Mask, MaskAsInts); |
2096 | return isIdentityMask(MaskAsInts); |
2097 | } |
2098 | |
2099 | /// Return true if this shuffle chooses elements from exactly one source |
2100 | /// vector without lane crossings and does not change the number of elements |
2101 | /// from its input vectors. |
2102 | /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef> |
2103 | bool isIdentity() const { |
2104 | return !changesLength() && isIdentityMask(ShuffleMask); |
2105 | } |
2106 | |
2107 | /// Return true if this shuffle lengthens exactly one source vector with |
2108 | /// undefs in the high elements. |
2109 | bool isIdentityWithPadding() const; |
2110 | |
2111 | /// Return true if this shuffle extracts the first N elements of exactly one |
2112 | /// source vector. |
2113 | bool isIdentityWithExtract() const; |
2114 | |
2115 | /// Return true if this shuffle concatenates its 2 source vectors. This |
2116 | /// returns false if either input is undefined. In that case, the shuffle is |
2117 | /// is better classified as an identity with padding operation. |
2118 | bool isConcat() const; |
2119 | |
2120 | /// Return true if this shuffle mask chooses elements from its source vectors |
2121 | /// without lane crossings. A shuffle using this mask would be |
2122 | /// equivalent to a vector select with a constant condition operand. |
2123 | /// Example: <4,1,6,undef> |
2124 | /// This returns false if the mask does not choose from both input vectors. |
2125 | /// In that case, the shuffle is better classified as an identity shuffle. |
2126 | /// This assumes that vector operands are the same length as the mask |
2127 | /// (a length-changing shuffle can never be equivalent to a vector select). |
2128 | static bool isSelectMask(ArrayRef<int> Mask); |
2129 | static bool isSelectMask(const Constant *Mask) { |
2130 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2130, __PRETTY_FUNCTION__)); |
2131 | SmallVector<int, 16> MaskAsInts; |
2132 | getShuffleMask(Mask, MaskAsInts); |
2133 | return isSelectMask(MaskAsInts); |
2134 | } |
2135 | |
2136 | /// Return true if this shuffle chooses elements from its source vectors |
2137 | /// without lane crossings and all operands have the same number of elements. |
2138 | /// In other words, this shuffle is equivalent to a vector select with a |
2139 | /// constant condition operand. |
2140 | /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3> |
2141 | /// This returns false if the mask does not choose from both input vectors. |
2142 | /// In that case, the shuffle is better classified as an identity shuffle. |
2143 | /// TODO: Optionally allow length-changing shuffles. |
2144 | bool isSelect() const { |
2145 | return !changesLength() && isSelectMask(ShuffleMask); |
2146 | } |
2147 | |
2148 | /// Return true if this shuffle mask swaps the order of elements from exactly |
2149 | /// one source vector. |
2150 | /// Example: <7,6,undef,4> |
2151 | /// This assumes that vector operands are the same length as the mask. |
2152 | static bool isReverseMask(ArrayRef<int> Mask); |
2153 | static bool isReverseMask(const Constant *Mask) { |
2154 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2154, __PRETTY_FUNCTION__)); |
2155 | SmallVector<int, 16> MaskAsInts; |
2156 | getShuffleMask(Mask, MaskAsInts); |
2157 | return isReverseMask(MaskAsInts); |
2158 | } |
2159 | |
2160 | /// Return true if this shuffle swaps the order of elements from exactly |
2161 | /// one source vector. |
2162 | /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef> |
2163 | /// TODO: Optionally allow length-changing shuffles. |
2164 | bool isReverse() const { |
2165 | return !changesLength() && isReverseMask(ShuffleMask); |
2166 | } |
2167 | |
2168 | /// Return true if this shuffle mask chooses all elements with the same value |
2169 | /// as the first element of exactly one source vector. |
2170 | /// Example: <4,undef,undef,4> |
2171 | /// This assumes that vector operands are the same length as the mask. |
2172 | static bool isZeroEltSplatMask(ArrayRef<int> Mask); |
2173 | static bool isZeroEltSplatMask(const Constant *Mask) { |
2174 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2174, __PRETTY_FUNCTION__)); |
2175 | SmallVector<int, 16> MaskAsInts; |
2176 | getShuffleMask(Mask, MaskAsInts); |
2177 | return isZeroEltSplatMask(MaskAsInts); |
2178 | } |
2179 | |
2180 | /// Return true if all elements of this shuffle are the same value as the |
2181 | /// first element of exactly one source vector without changing the length |
2182 | /// of that vector. |
2183 | /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0> |
2184 | /// TODO: Optionally allow length-changing shuffles. |
2185 | /// TODO: Optionally allow splats from other elements. |
2186 | bool isZeroEltSplat() const { |
2187 | return !changesLength() && isZeroEltSplatMask(ShuffleMask); |
2188 | } |
2189 | |
2190 | /// Return true if this shuffle mask is a transpose mask. |
2191 | /// Transpose vector masks transpose a 2xn matrix. They read corresponding |
2192 | /// even- or odd-numbered vector elements from two n-dimensional source |
2193 | /// vectors and write each result into consecutive elements of an |
2194 | /// n-dimensional destination vector. Two shuffles are necessary to complete |
2195 | /// the transpose, one for the even elements and another for the odd elements. |
2196 | /// This description closely follows how the TRN1 and TRN2 AArch64 |
2197 | /// instructions operate. |
2198 | /// |
2199 | /// For example, a simple 2x2 matrix can be transposed with: |
2200 | /// |
2201 | /// ; Original matrix |
2202 | /// m0 = < a, b > |
2203 | /// m1 = < c, d > |
2204 | /// |
2205 | /// ; Transposed matrix |
2206 | /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 > |
2207 | /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 > |
2208 | /// |
2209 | /// For matrices having greater than n columns, the resulting nx2 transposed |
2210 | /// matrix is stored in two result vectors such that one vector contains |
2211 | /// interleaved elements from all the even-numbered rows and the other vector |
2212 | /// contains interleaved elements from all the odd-numbered rows. For example, |
2213 | /// a 2x4 matrix can be transposed with: |
2214 | /// |
2215 | /// ; Original matrix |
2216 | /// m0 = < a, b, c, d > |
2217 | /// m1 = < e, f, g, h > |
2218 | /// |
2219 | /// ; Transposed matrix |
2220 | /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 > |
2221 | /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 > |
2222 | static bool isTransposeMask(ArrayRef<int> Mask); |
2223 | static bool isTransposeMask(const Constant *Mask) { |
2224 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2224, __PRETTY_FUNCTION__)); |
2225 | SmallVector<int, 16> MaskAsInts; |
2226 | getShuffleMask(Mask, MaskAsInts); |
2227 | return isTransposeMask(MaskAsInts); |
2228 | } |
2229 | |
2230 | /// Return true if this shuffle transposes the elements of its inputs without |
2231 | /// changing the length of the vectors. This operation may also be known as a |
2232 | /// merge or interleave. See the description for isTransposeMask() for the |
2233 | /// exact specification. |
2234 | /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6> |
2235 | bool isTranspose() const { |
2236 | return !changesLength() && isTransposeMask(ShuffleMask); |
2237 | } |
2238 | |
2239 | /// Return true if this shuffle mask is an extract subvector mask. |
2240 | /// A valid extract subvector mask returns a smaller vector from a single |
2241 | /// source operand. The base extraction index is returned as well. |
2242 | static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts, |
2243 | int &Index); |
2244 | static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts, |
2245 | int &Index) { |
2246 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2246, __PRETTY_FUNCTION__)); |
2247 | SmallVector<int, 16> MaskAsInts; |
2248 | getShuffleMask(Mask, MaskAsInts); |
2249 | return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index); |
2250 | } |
2251 | |
2252 | /// Return true if this shuffle mask is an extract subvector mask. |
2253 | bool isExtractSubvectorMask(int &Index) const { |
2254 | int NumSrcElts = |
2255 | cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); |
2256 | return isExtractSubvectorMask(ShuffleMask, NumSrcElts, Index); |
2257 | } |
2258 | |
2259 | /// Change values in a shuffle permute mask assuming the two vector operands |
2260 | /// of length InVecNumElts have swapped position. |
2261 | static void commuteShuffleMask(MutableArrayRef<int> Mask, |
2262 | unsigned InVecNumElts) { |
2263 | for (int &Idx : Mask) { |
2264 | if (Idx == -1) |
2265 | continue; |
2266 | Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts; |
2267 | assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&((Idx >= 0 && Idx < (int)InVecNumElts * 2 && "shufflevector mask index out of range") ? static_cast<void > (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2268, __PRETTY_FUNCTION__)) |
2268 | "shufflevector mask index out of range")((Idx >= 0 && Idx < (int)InVecNumElts * 2 && "shufflevector mask index out of range") ? static_cast<void > (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2268, __PRETTY_FUNCTION__)); |
2269 | } |
2270 | } |
2271 | |
2272 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2273 | static bool classof(const Instruction *I) { |
2274 | return I->getOpcode() == Instruction::ShuffleVector; |
2275 | } |
2276 | static bool classof(const Value *V) { |
2277 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2278 | } |
2279 | }; |
2280 | |
2281 | template <> |
2282 | struct OperandTraits<ShuffleVectorInst> |
2283 | : public FixedNumOperandTraits<ShuffleVectorInst, 2> {}; |
2284 | |
2285 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)ShuffleVectorInst::op_iterator ShuffleVectorInst::op_begin() { return OperandTraits<ShuffleVectorInst>::op_begin(this ); } ShuffleVectorInst::const_op_iterator ShuffleVectorInst:: op_begin() const { return OperandTraits<ShuffleVectorInst> ::op_begin(const_cast<ShuffleVectorInst*>(this)); } ShuffleVectorInst ::op_iterator ShuffleVectorInst::op_end() { return OperandTraits <ShuffleVectorInst>::op_end(this); } ShuffleVectorInst:: const_op_iterator ShuffleVectorInst::op_end() const { return OperandTraits <ShuffleVectorInst>::op_end(const_cast<ShuffleVectorInst *>(this)); } Value *ShuffleVectorInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<ShuffleVectorInst >::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2285, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<ShuffleVectorInst>::op_begin(const_cast <ShuffleVectorInst*>(this))[i_nocapture].get()); } void ShuffleVectorInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((i_nocapture < OperandTraits<ShuffleVectorInst> ::operands(this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2285, __PRETTY_FUNCTION__)); OperandTraits<ShuffleVectorInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ShuffleVectorInst::getNumOperands() const { return OperandTraits <ShuffleVectorInst>::operands(this); } template <int Idx_nocapture> Use &ShuffleVectorInst::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &ShuffleVectorInst::Op() const { return this ->OpFrom<Idx_nocapture>(this); } |
2286 | |
2287 | //===----------------------------------------------------------------------===// |
2288 | // ExtractValueInst Class |
2289 | //===----------------------------------------------------------------------===// |
2290 | |
2291 | /// This instruction extracts a struct member or array |
2292 | /// element value from an aggregate value. |
2293 | /// |
2294 | class ExtractValueInst : public UnaryInstruction { |
2295 | SmallVector<unsigned, 4> Indices; |
2296 | |
2297 | ExtractValueInst(const ExtractValueInst &EVI); |
2298 | |
2299 | /// Constructors - Create a extractvalue instruction with a base aggregate |
2300 | /// value and a list of indices. The first ctor can optionally insert before |
2301 | /// an existing instruction, the second appends the new instruction to the |
2302 | /// specified BasicBlock. |
2303 | inline ExtractValueInst(Value *Agg, |
2304 | ArrayRef<unsigned> Idxs, |
2305 | const Twine &NameStr, |
2306 | Instruction *InsertBefore); |
2307 | inline ExtractValueInst(Value *Agg, |
2308 | ArrayRef<unsigned> Idxs, |
2309 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2310 | |
2311 | void init(ArrayRef<unsigned> Idxs, const Twine &NameStr); |
2312 | |
2313 | protected: |
2314 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2315 | friend class Instruction; |
2316 | |
2317 | ExtractValueInst *cloneImpl() const; |
2318 | |
2319 | public: |
2320 | static ExtractValueInst *Create(Value *Agg, |
2321 | ArrayRef<unsigned> Idxs, |
2322 | const Twine &NameStr = "", |
2323 | Instruction *InsertBefore = nullptr) { |
2324 | return new |
2325 | ExtractValueInst(Agg, Idxs, NameStr, InsertBefore); |
2326 | } |
2327 | |
2328 | static ExtractValueInst *Create(Value *Agg, |
2329 | ArrayRef<unsigned> Idxs, |
2330 | const Twine &NameStr, |
2331 | BasicBlock *InsertAtEnd) { |
2332 | return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd); |
2333 | } |
2334 | |
2335 | /// Returns the type of the element that would be extracted |
2336 | /// with an extractvalue instruction with the specified parameters. |
2337 | /// |
2338 | /// Null is returned if the indices are invalid for the specified type. |
2339 | static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs); |
2340 | |
2341 | using idx_iterator = const unsigned*; |
2342 | |
2343 | inline idx_iterator idx_begin() const { return Indices.begin(); } |
2344 | inline idx_iterator idx_end() const { return Indices.end(); } |
2345 | inline iterator_range<idx_iterator> indices() const { |
2346 | return make_range(idx_begin(), idx_end()); |
2347 | } |
2348 | |
2349 | Value *getAggregateOperand() { |
2350 | return getOperand(0); |
2351 | } |
2352 | const Value *getAggregateOperand() const { |
2353 | return getOperand(0); |
2354 | } |
2355 | static unsigned getAggregateOperandIndex() { |
2356 | return 0U; // get index for modifying correct operand |
2357 | } |
2358 | |
2359 | ArrayRef<unsigned> getIndices() const { |
2360 | return Indices; |
2361 | } |
2362 | |
2363 | unsigned getNumIndices() const { |
2364 | return (unsigned)Indices.size(); |
2365 | } |
2366 | |
2367 | bool hasIndices() const { |
2368 | return true; |
2369 | } |
2370 | |
2371 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2372 | static bool classof(const Instruction *I) { |
2373 | return I->getOpcode() == Instruction::ExtractValue; |
2374 | } |
2375 | static bool classof(const Value *V) { |
2376 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2377 | } |
2378 | }; |
2379 | |
2380 | ExtractValueInst::ExtractValueInst(Value *Agg, |
2381 | ArrayRef<unsigned> Idxs, |
2382 | const Twine &NameStr, |
2383 | Instruction *InsertBefore) |
2384 | : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)), |
2385 | ExtractValue, Agg, InsertBefore) { |
2386 | init(Idxs, NameStr); |
2387 | } |
2388 | |
2389 | ExtractValueInst::ExtractValueInst(Value *Agg, |
2390 | ArrayRef<unsigned> Idxs, |
2391 | const Twine &NameStr, |
2392 | BasicBlock *InsertAtEnd) |
2393 | : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)), |
2394 | ExtractValue, Agg, InsertAtEnd) { |
2395 | init(Idxs, NameStr); |
2396 | } |
2397 | |
2398 | //===----------------------------------------------------------------------===// |
2399 | // InsertValueInst Class |
2400 | //===----------------------------------------------------------------------===// |
2401 | |
2402 | /// This instruction inserts a struct field of array element |
2403 | /// value into an aggregate value. |
2404 | /// |
2405 | class InsertValueInst : public Instruction { |
2406 | SmallVector<unsigned, 4> Indices; |
2407 | |
2408 | InsertValueInst(const InsertValueInst &IVI); |
2409 | |
2410 | /// Constructors - Create a insertvalue instruction with a base aggregate |
2411 | /// value, a value to insert, and a list of indices. The first ctor can |
2412 | /// optionally insert before an existing instruction, the second appends |
2413 | /// the new instruction to the specified BasicBlock. |
2414 | inline InsertValueInst(Value *Agg, Value *Val, |
2415 | ArrayRef<unsigned> Idxs, |
2416 | const Twine &NameStr, |
2417 | Instruction *InsertBefore); |
2418 | inline InsertValueInst(Value *Agg, Value *Val, |
2419 | ArrayRef<unsigned> Idxs, |
2420 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2421 | |
2422 | /// Constructors - These two constructors are convenience methods because one |
2423 | /// and two index insertvalue instructions are so common. |
2424 | InsertValueInst(Value *Agg, Value *Val, unsigned Idx, |
2425 | const Twine &NameStr = "", |
2426 | Instruction *InsertBefore = nullptr); |
2427 | InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr, |
2428 | BasicBlock *InsertAtEnd); |
2429 | |
2430 | void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, |
2431 | const Twine &NameStr); |
2432 | |
2433 | protected: |
2434 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2435 | friend class Instruction; |
2436 | |
2437 | InsertValueInst *cloneImpl() const; |
2438 | |
2439 | public: |
2440 | // allocate space for exactly two operands |
2441 | void *operator new(size_t s) { |
2442 | return User::operator new(s, 2); |
2443 | } |
2444 | |
2445 | static InsertValueInst *Create(Value *Agg, Value *Val, |
2446 | ArrayRef<unsigned> Idxs, |
2447 | const Twine &NameStr = "", |
2448 | Instruction *InsertBefore = nullptr) { |
2449 | return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore); |
2450 | } |
2451 | |
2452 | static InsertValueInst *Create(Value *Agg, Value *Val, |
2453 | ArrayRef<unsigned> Idxs, |
2454 | const Twine &NameStr, |
2455 | BasicBlock *InsertAtEnd) { |
2456 | return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd); |
2457 | } |
2458 | |
2459 | /// Transparently provide more efficient getOperand methods. |
2460 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2461 | |
2462 | using idx_iterator = const unsigned*; |
2463 | |
2464 | inline idx_iterator idx_begin() const { return Indices.begin(); } |
2465 | inline idx_iterator idx_end() const { return Indices.end(); } |
2466 | inline iterator_range<idx_iterator> indices() const { |
2467 | return make_range(idx_begin(), idx_end()); |
2468 | } |
2469 | |
2470 | Value *getAggregateOperand() { |
2471 | return getOperand(0); |
2472 | } |
2473 | const Value *getAggregateOperand() const { |
2474 | return getOperand(0); |
2475 | } |
2476 | static unsigned getAggregateOperandIndex() { |
2477 | return 0U; // get index for modifying correct operand |
2478 | } |
2479 | |
2480 | Value *getInsertedValueOperand() { |
2481 | return getOperand(1); |
2482 | } |
2483 | const Value *getInsertedValueOperand() const { |
2484 | return getOperand(1); |
2485 | } |
2486 | static unsigned getInsertedValueOperandIndex() { |
2487 | return 1U; // get index for modifying correct operand |
2488 | } |
2489 | |
2490 | ArrayRef<unsigned> getIndices() const { |
2491 | return Indices; |
2492 | } |
2493 | |
2494 | unsigned getNumIndices() const { |
2495 | return (unsigned)Indices.size(); |
2496 | } |
2497 | |
2498 | bool hasIndices() const { |
2499 | return true; |
2500 | } |
2501 | |
2502 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2503 | static bool classof(const Instruction *I) { |
2504 | return I->getOpcode() == Instruction::InsertValue; |
2505 | } |
2506 | static bool classof(const Value *V) { |
2507 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2508 | } |
2509 | }; |
2510 | |
2511 | template <> |
2512 | struct OperandTraits<InsertValueInst> : |
2513 | public FixedNumOperandTraits<InsertValueInst, 2> { |
2514 | }; |
2515 | |
2516 | InsertValueInst::InsertValueInst(Value *Agg, |
2517 | Value *Val, |
2518 | ArrayRef<unsigned> Idxs, |
2519 | const Twine &NameStr, |
2520 | Instruction *InsertBefore) |
2521 | : Instruction(Agg->getType(), InsertValue, |
2522 | OperandTraits<InsertValueInst>::op_begin(this), |
2523 | 2, InsertBefore) { |
2524 | init(Agg, Val, Idxs, NameStr); |
2525 | } |
2526 | |
2527 | InsertValueInst::InsertValueInst(Value *Agg, |
2528 | Value *Val, |
2529 | ArrayRef<unsigned> Idxs, |
2530 | const Twine &NameStr, |
2531 | BasicBlock *InsertAtEnd) |
2532 | : Instruction(Agg->getType(), InsertValue, |
2533 | OperandTraits<InsertValueInst>::op_begin(this), |
2534 | 2, InsertAtEnd) { |
2535 | init(Agg, Val, Idxs, NameStr); |
2536 | } |
2537 | |
2538 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)InsertValueInst::op_iterator InsertValueInst::op_begin() { return OperandTraits<InsertValueInst>::op_begin(this); } InsertValueInst ::const_op_iterator InsertValueInst::op_begin() const { return OperandTraits<InsertValueInst>::op_begin(const_cast< InsertValueInst*>(this)); } InsertValueInst::op_iterator InsertValueInst ::op_end() { return OperandTraits<InsertValueInst>::op_end (this); } InsertValueInst::const_op_iterator InsertValueInst:: op_end() const { return OperandTraits<InsertValueInst>:: op_end(const_cast<InsertValueInst*>(this)); } Value *InsertValueInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<InsertValueInst>::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2538, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<InsertValueInst>::op_begin(const_cast< InsertValueInst*>(this))[i_nocapture].get()); } void InsertValueInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( i_nocapture < OperandTraits<InsertValueInst>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2538, __PRETTY_FUNCTION__)); OperandTraits<InsertValueInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned InsertValueInst::getNumOperands() const { return OperandTraits <InsertValueInst>::operands(this); } template <int Idx_nocapture > Use &InsertValueInst::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &InsertValueInst::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
2539 | |
2540 | //===----------------------------------------------------------------------===// |
2541 | // PHINode Class |
2542 | //===----------------------------------------------------------------------===// |
2543 | |
2544 | // PHINode - The PHINode class is used to represent the magical mystical PHI |
2545 | // node, that can not exist in nature, but can be synthesized in a computer |
2546 | // scientist's overactive imagination. |
2547 | // |
2548 | class PHINode : public Instruction { |
2549 | /// The number of operands actually allocated. NumOperands is |
2550 | /// the number actually in use. |
2551 | unsigned ReservedSpace; |
2552 | |
2553 | PHINode(const PHINode &PN); |
2554 | |
2555 | explicit PHINode(Type *Ty, unsigned NumReservedValues, |
2556 | const Twine &NameStr = "", |
2557 | Instruction *InsertBefore = nullptr) |
2558 | : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore), |
2559 | ReservedSpace(NumReservedValues) { |
2560 | setName(NameStr); |
2561 | allocHungoffUses(ReservedSpace); |
2562 | } |
2563 | |
2564 | PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr, |
2565 | BasicBlock *InsertAtEnd) |
2566 | : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd), |
2567 | ReservedSpace(NumReservedValues) { |
2568 | setName(NameStr); |
2569 | allocHungoffUses(ReservedSpace); |
2570 | } |
2571 | |
2572 | protected: |
2573 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2574 | friend class Instruction; |
2575 | |
2576 | PHINode *cloneImpl() const; |
2577 | |
2578 | // allocHungoffUses - this is more complicated than the generic |
2579 | // User::allocHungoffUses, because we have to allocate Uses for the incoming |
2580 | // values and pointers to the incoming blocks, all in one allocation. |
2581 | void allocHungoffUses(unsigned N) { |
2582 | User::allocHungoffUses(N, /* IsPhi */ true); |
2583 | } |
2584 | |
2585 | public: |
2586 | /// Constructors - NumReservedValues is a hint for the number of incoming |
2587 | /// edges that this phi node will have (use 0 if you really have no idea). |
2588 | static PHINode *Create(Type *Ty, unsigned NumReservedValues, |
2589 | const Twine &NameStr = "", |
2590 | Instruction *InsertBefore = nullptr) { |
2591 | return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore); |
2592 | } |
2593 | |
2594 | static PHINode *Create(Type *Ty, unsigned NumReservedValues, |
2595 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
2596 | return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd); |
2597 | } |
2598 | |
2599 | /// Provide fast operand accessors |
2600 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2601 | |
2602 | // Block iterator interface. This provides access to the list of incoming |
2603 | // basic blocks, which parallels the list of incoming values. |
2604 | |
2605 | using block_iterator = BasicBlock **; |
2606 | using const_block_iterator = BasicBlock * const *; |
2607 | |
2608 | block_iterator block_begin() { |
2609 | return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace); |
2610 | } |
2611 | |
2612 | const_block_iterator block_begin() const { |
2613 | return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace); |
2614 | } |
2615 | |
2616 | block_iterator block_end() { |
2617 | return block_begin() + getNumOperands(); |
2618 | } |
2619 | |
2620 | const_block_iterator block_end() const { |
2621 | return block_begin() + getNumOperands(); |
2622 | } |
2623 | |
2624 | iterator_range<block_iterator> blocks() { |
2625 | return make_range(block_begin(), block_end()); |
2626 | } |
2627 | |
2628 | iterator_range<const_block_iterator> blocks() const { |
2629 | return make_range(block_begin(), block_end()); |
2630 | } |
2631 | |
2632 | op_range incoming_values() { return operands(); } |
2633 | |
2634 | const_op_range incoming_values() const { return operands(); } |
2635 | |
2636 | /// Return the number of incoming edges |
2637 | /// |
2638 | unsigned getNumIncomingValues() const { return getNumOperands(); } |
2639 | |
2640 | /// Return incoming value number x |
2641 | /// |
2642 | Value *getIncomingValue(unsigned i) const { |
2643 | return getOperand(i); |
2644 | } |
2645 | void setIncomingValue(unsigned i, Value *V) { |
2646 | assert(V && "PHI node got a null value!")((V && "PHI node got a null value!") ? static_cast< void> (0) : __assert_fail ("V && \"PHI node got a null value!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2646, __PRETTY_FUNCTION__)); |
2647 | assert(getType() == V->getType() &&((getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node!" ) ? static_cast<void> (0) : __assert_fail ("getType() == V->getType() && \"All operands to PHI node must be the same type as the PHI node!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2648, __PRETTY_FUNCTION__)) |
2648 | "All operands to PHI node must be the same type as the PHI node!")((getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node!" ) ? static_cast<void> (0) : __assert_fail ("getType() == V->getType() && \"All operands to PHI node must be the same type as the PHI node!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2648, __PRETTY_FUNCTION__)); |
2649 | setOperand(i, V); |
2650 | } |
2651 | |
2652 | static unsigned getOperandNumForIncomingValue(unsigned i) { |
2653 | return i; |
2654 | } |
2655 | |
2656 | static unsigned getIncomingValueNumForOperand(unsigned i) { |
2657 | return i; |
2658 | } |
2659 | |
2660 | /// Return incoming basic block number @p i. |
2661 | /// |
2662 | BasicBlock *getIncomingBlock(unsigned i) const { |
2663 | return block_begin()[i]; |
2664 | } |
2665 | |
2666 | /// Return incoming basic block corresponding |
2667 | /// to an operand of the PHI. |
2668 | /// |
2669 | BasicBlock *getIncomingBlock(const Use &U) const { |
2670 | assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?")((this == U.getUser() && "Iterator doesn't point to PHI's Uses?" ) ? static_cast<void> (0) : __assert_fail ("this == U.getUser() && \"Iterator doesn't point to PHI's Uses?\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2670, __PRETTY_FUNCTION__)); |
2671 | return getIncomingBlock(unsigned(&U - op_begin())); |
2672 | } |
2673 | |
2674 | /// Return incoming basic block corresponding |
2675 | /// to value use iterator. |
2676 | /// |
2677 | BasicBlock *getIncomingBlock(Value::const_user_iterator I) const { |
2678 | return getIncomingBlock(I.getUse()); |
2679 | } |
2680 | |
2681 | void setIncomingBlock(unsigned i, BasicBlock *BB) { |
2682 | assert(BB && "PHI node got a null basic block!")((BB && "PHI node got a null basic block!") ? static_cast <void> (0) : __assert_fail ("BB && \"PHI node got a null basic block!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2682, __PRETTY_FUNCTION__)); |
2683 | block_begin()[i] = BB; |
2684 | } |
2685 | |
2686 | /// Replace every incoming basic block \p Old to basic block \p New. |
2687 | void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New) { |
2688 | assert(New && Old && "PHI node got a null basic block!")((New && Old && "PHI node got a null basic block!" ) ? static_cast<void> (0) : __assert_fail ("New && Old && \"PHI node got a null basic block!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2688, __PRETTY_FUNCTION__)); |
2689 | for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op) |
2690 | if (getIncomingBlock(Op) == Old) |
2691 | setIncomingBlock(Op, New); |
2692 | } |
2693 | |
2694 | /// Add an incoming value to the end of the PHI list |
2695 | /// |
2696 | void addIncoming(Value *V, BasicBlock *BB) { |
2697 | if (getNumOperands() == ReservedSpace) |
2698 | growOperands(); // Get more space! |
2699 | // Initialize some new operands. |
2700 | setNumHungOffUseOperands(getNumOperands() + 1); |
2701 | setIncomingValue(getNumOperands() - 1, V); |
2702 | setIncomingBlock(getNumOperands() - 1, BB); |
2703 | } |
2704 | |
2705 | /// Remove an incoming value. This is useful if a |
2706 | /// predecessor basic block is deleted. The value removed is returned. |
2707 | /// |
2708 | /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty |
2709 | /// is true), the PHI node is destroyed and any uses of it are replaced with |
2710 | /// dummy values. The only time there should be zero incoming values to a PHI |
2711 | /// node is when the block is dead, so this strategy is sound. |
2712 | /// |
2713 | Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true); |
2714 | |
2715 | Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) { |
2716 | int Idx = getBasicBlockIndex(BB); |
2717 | assert(Idx >= 0 && "Invalid basic block argument to remove!")((Idx >= 0 && "Invalid basic block argument to remove!" ) ? static_cast<void> (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument to remove!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2717, __PRETTY_FUNCTION__)); |
2718 | return removeIncomingValue(Idx, DeletePHIIfEmpty); |
2719 | } |
2720 | |
2721 | /// Return the first index of the specified basic |
2722 | /// block in the value list for this PHI. Returns -1 if no instance. |
2723 | /// |
2724 | int getBasicBlockIndex(const BasicBlock *BB) const { |
2725 | for (unsigned i = 0, e = getNumOperands(); i != e; ++i) |
2726 | if (block_begin()[i] == BB) |
2727 | return i; |
2728 | return -1; |
2729 | } |
2730 | |
2731 | Value *getIncomingValueForBlock(const BasicBlock *BB) const { |
2732 | int Idx = getBasicBlockIndex(BB); |
2733 | assert(Idx >= 0 && "Invalid basic block argument!")((Idx >= 0 && "Invalid basic block argument!") ? static_cast <void> (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2733, __PRETTY_FUNCTION__)); |
2734 | return getIncomingValue(Idx); |
2735 | } |
2736 | |
2737 | /// Set every incoming value(s) for block \p BB to \p V. |
2738 | void setIncomingValueForBlock(const BasicBlock *BB, Value *V) { |
2739 | assert(BB && "PHI node got a null basic block!")((BB && "PHI node got a null basic block!") ? static_cast <void> (0) : __assert_fail ("BB && \"PHI node got a null basic block!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2739, __PRETTY_FUNCTION__)); |
2740 | bool Found = false; |
2741 | for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op) |
2742 | if (getIncomingBlock(Op) == BB) { |
2743 | Found = true; |
2744 | setIncomingValue(Op, V); |
2745 | } |
2746 | (void)Found; |
2747 | assert(Found && "Invalid basic block argument to set!")((Found && "Invalid basic block argument to set!") ? static_cast <void> (0) : __assert_fail ("Found && \"Invalid basic block argument to set!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2747, __PRETTY_FUNCTION__)); |
2748 | } |
2749 | |
2750 | /// If the specified PHI node always merges together the |
2751 | /// same value, return the value, otherwise return null. |
2752 | Value *hasConstantValue() const; |
2753 | |
2754 | /// Whether the specified PHI node always merges |
2755 | /// together the same value, assuming undefs are equal to a unique |
2756 | /// non-undef value. |
2757 | bool hasConstantOrUndefValue() const; |
2758 | |
2759 | /// If the PHI node is complete which means all of its parent's predecessors |
2760 | /// have incoming value in this PHI, return true, otherwise return false. |
2761 | bool isComplete() const { |
2762 | return llvm::all_of(predecessors(getParent()), |
2763 | [this](const BasicBlock *Pred) { |
2764 | return getBasicBlockIndex(Pred) >= 0; |
2765 | }); |
2766 | } |
2767 | |
2768 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
2769 | static bool classof(const Instruction *I) { |
2770 | return I->getOpcode() == Instruction::PHI; |
2771 | } |
2772 | static bool classof(const Value *V) { |
2773 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2774 | } |
2775 | |
2776 | private: |
2777 | void growOperands(); |
2778 | }; |
2779 | |
2780 | template <> |
2781 | struct OperandTraits<PHINode> : public HungoffOperandTraits<2> { |
2782 | }; |
2783 | |
2784 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)PHINode::op_iterator PHINode::op_begin() { return OperandTraits <PHINode>::op_begin(this); } PHINode::const_op_iterator PHINode::op_begin() const { return OperandTraits<PHINode> ::op_begin(const_cast<PHINode*>(this)); } PHINode::op_iterator PHINode::op_end() { return OperandTraits<PHINode>::op_end (this); } PHINode::const_op_iterator PHINode::op_end() const { return OperandTraits<PHINode>::op_end(const_cast<PHINode *>(this)); } Value *PHINode::getOperand(unsigned i_nocapture ) const { ((i_nocapture < OperandTraits<PHINode>::operands (this) && "getOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2784, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<PHINode>::op_begin(const_cast<PHINode *>(this))[i_nocapture].get()); } void PHINode::setOperand( unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<PHINode>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2784, __PRETTY_FUNCTION__)); OperandTraits<PHINode>:: op_begin(this)[i_nocapture] = Val_nocapture; } unsigned PHINode ::getNumOperands() const { return OperandTraits<PHINode> ::operands(this); } template <int Idx_nocapture> Use & PHINode::Op() { return this->OpFrom<Idx_nocapture>(this ); } template <int Idx_nocapture> const Use &PHINode ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
2785 | |
2786 | //===----------------------------------------------------------------------===// |
2787 | // LandingPadInst Class |
2788 | //===----------------------------------------------------------------------===// |
2789 | |
2790 | //===--------------------------------------------------------------------------- |
2791 | /// The landingpad instruction holds all of the information |
2792 | /// necessary to generate correct exception handling. The landingpad instruction |
2793 | /// cannot be moved from the top of a landing pad block, which itself is |
2794 | /// accessible only from the 'unwind' edge of an invoke. This uses the |
2795 | /// SubclassData field in Value to store whether or not the landingpad is a |
2796 | /// cleanup. |
2797 | /// |
2798 | class LandingPadInst : public Instruction { |
2799 | using CleanupField = BoolBitfieldElementT<0>; |
2800 | |
2801 | /// The number of operands actually allocated. NumOperands is |
2802 | /// the number actually in use. |
2803 | unsigned ReservedSpace; |
2804 | |
2805 | LandingPadInst(const LandingPadInst &LP); |
2806 | |
2807 | public: |
2808 | enum ClauseType { Catch, Filter }; |
2809 | |
2810 | private: |
2811 | explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues, |
2812 | const Twine &NameStr, Instruction *InsertBefore); |
2813 | explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues, |
2814 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2815 | |
2816 | // Allocate space for exactly zero operands. |
2817 | void *operator new(size_t s) { |
2818 | return User::operator new(s); |
2819 | } |
2820 | |
2821 | void growOperands(unsigned Size); |
2822 | void init(unsigned NumReservedValues, const Twine &NameStr); |
2823 | |
2824 | protected: |
2825 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2826 | friend class Instruction; |
2827 | |
2828 | LandingPadInst *cloneImpl() const; |
2829 | |
2830 | public: |
2831 | /// Constructors - NumReservedClauses is a hint for the number of incoming |
2832 | /// clauses that this landingpad will have (use 0 if you really have no idea). |
2833 | static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses, |
2834 | const Twine &NameStr = "", |
2835 | Instruction *InsertBefore = nullptr); |
2836 | static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses, |
2837 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2838 | |
2839 | /// Provide fast operand accessors |
2840 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2841 | |
2842 | /// Return 'true' if this landingpad instruction is a |
2843 | /// cleanup. I.e., it should be run when unwinding even if its landing pad |
2844 | /// doesn't catch the exception. |
2845 | bool isCleanup() const { return getSubclassData<CleanupField>(); } |
2846 | |
2847 | /// Indicate that this landingpad instruction is a cleanup. |
2848 | void setCleanup(bool V) { setSubclassData<CleanupField>(V); } |
2849 | |
2850 | /// Add a catch or filter clause to the landing pad. |
2851 | void addClause(Constant *ClauseVal); |
2852 | |
2853 | /// Get the value of the clause at index Idx. Use isCatch/isFilter to |
2854 | /// determine what type of clause this is. |
2855 | Constant *getClause(unsigned Idx) const { |
2856 | return cast<Constant>(getOperandList()[Idx]); |
2857 | } |
2858 | |
2859 | /// Return 'true' if the clause and index Idx is a catch clause. |
2860 | bool isCatch(unsigned Idx) const { |
2861 | return !isa<ArrayType>(getOperandList()[Idx]->getType()); |
2862 | } |
2863 | |
2864 | /// Return 'true' if the clause and index Idx is a filter clause. |
2865 | bool isFilter(unsigned Idx) const { |
2866 | return isa<ArrayType>(getOperandList()[Idx]->getType()); |
2867 | } |
2868 | |
2869 | /// Get the number of clauses for this landing pad. |
2870 | unsigned getNumClauses() const { return getNumOperands(); } |
2871 | |
2872 | /// Grow the size of the operand list to accommodate the new |
2873 | /// number of clauses. |
2874 | void reserveClauses(unsigned Size) { growOperands(Size); } |
2875 | |
2876 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2877 | static bool classof(const Instruction *I) { |
2878 | return I->getOpcode() == Instruction::LandingPad; |
2879 | } |
2880 | static bool classof(const Value *V) { |
2881 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2882 | } |
2883 | }; |
2884 | |
2885 | template <> |
2886 | struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> { |
2887 | }; |
2888 | |
2889 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)LandingPadInst::op_iterator LandingPadInst::op_begin() { return OperandTraits<LandingPadInst>::op_begin(this); } LandingPadInst ::const_op_iterator LandingPadInst::op_begin() const { return OperandTraits<LandingPadInst>::op_begin(const_cast< LandingPadInst*>(this)); } LandingPadInst::op_iterator LandingPadInst ::op_end() { return OperandTraits<LandingPadInst>::op_end (this); } LandingPadInst::const_op_iterator LandingPadInst::op_end () const { return OperandTraits<LandingPadInst>::op_end (const_cast<LandingPadInst*>(this)); } Value *LandingPadInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<LandingPadInst>::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2889, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<LandingPadInst>::op_begin(const_cast< LandingPadInst*>(this))[i_nocapture].get()); } void LandingPadInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( i_nocapture < OperandTraits<LandingPadInst>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/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 | /// |
2899 | class ReturnInst : public Instruction { |
2900 | ReturnInst(const ReturnInst &RI); |
2901 | |
2902 | private: |
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 | |
2919 | protected: |
2920 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2921 | friend class Instruction; |
2922 | |
2923 | ReturnInst *cloneImpl() const; |
2924 | |
2925 | public: |
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 | |
2958 | private: |
2959 | BasicBlock *getSuccessor(unsigned idx) const { |
2960 | llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2960); |
2961 | } |
2962 | |
2963 | void setSuccessor(unsigned idx, BasicBlock *B) { |
2964 | llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2964); |
2965 | } |
2966 | }; |
2967 | |
2968 | template <> |
2969 | struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> { |
2970 | }; |
2971 | |
2972 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)ReturnInst::op_iterator ReturnInst::op_begin() { return OperandTraits <ReturnInst>::op_begin(this); } ReturnInst::const_op_iterator ReturnInst::op_begin() const { return OperandTraits<ReturnInst >::op_begin(const_cast<ReturnInst*>(this)); } ReturnInst ::op_iterator ReturnInst::op_end() { return OperandTraits< ReturnInst>::op_end(this); } ReturnInst::const_op_iterator ReturnInst::op_end() const { return OperandTraits<ReturnInst >::op_end(const_cast<ReturnInst*>(this)); } Value *ReturnInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<ReturnInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 2972, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<ReturnInst>::op_begin(const_cast<ReturnInst *>(this))[i_nocapture].get()); } void ReturnInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<ReturnInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/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 | /// |
2981 | class BranchInst : public Instruction { |
2982 | /// Ops list - Branches are strange. The operands are ordered: |
2983 | /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because |
2984 | /// they don't have to check for cond/uncond branchness. These are mostly |
2985 | /// accessed relative from op_end(). |
2986 | BranchInst(const BranchInst &BI); |
2987 | // BranchInst constructors (where {B, T, F} are blocks, and C is a condition): |
2988 | // BranchInst(BB *B) - 'br B' |
2989 | // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F' |
2990 | // BranchInst(BB* B, Inst *I) - 'br B' insert before I |
2991 | // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I |
2992 | // BranchInst(BB* B, BB *I) - 'br B' insert at end |
2993 | // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end |
2994 | explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr); |
2995 | BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, |
2996 | Instruction *InsertBefore = nullptr); |
2997 | BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd); |
2998 | BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, |
2999 | BasicBlock *InsertAtEnd); |
3000 | |
3001 | void AssertOK(); |
3002 | |
3003 | protected: |
3004 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3005 | friend class Instruction; |
3006 | |
3007 | BranchInst *cloneImpl() const; |
3008 | |
3009 | public: |
3010 | /// Iterator type that casts an operand to a basic block. |
3011 | /// |
3012 | /// This only makes sense because the successors are stored as adjacent |
3013 | /// operands for branch instructions. |
3014 | struct succ_op_iterator |
3015 | : iterator_adaptor_base<succ_op_iterator, value_op_iterator, |
3016 | std::random_access_iterator_tag, BasicBlock *, |
3017 | ptrdiff_t, BasicBlock *, BasicBlock *> { |
3018 | explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {} |
3019 | |
3020 | BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3021 | BasicBlock *operator->() const { return operator*(); } |
3022 | }; |
3023 | |
3024 | /// The const version of `succ_op_iterator`. |
3025 | struct const_succ_op_iterator |
3026 | : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator, |
3027 | std::random_access_iterator_tag, |
3028 | const BasicBlock *, ptrdiff_t, const BasicBlock *, |
3029 | const BasicBlock *> { |
3030 | explicit const_succ_op_iterator(const_value_op_iterator I) |
3031 | : iterator_adaptor_base(I) {} |
3032 | |
3033 | const BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3034 | const BasicBlock *operator->() const { return operator*(); } |
3035 | }; |
3036 | |
3037 | static BranchInst *Create(BasicBlock *IfTrue, |
3038 | Instruction *InsertBefore = nullptr) { |
3039 | return new(1) BranchInst(IfTrue, InsertBefore); |
3040 | } |
3041 | |
3042 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse, |
3043 | Value *Cond, Instruction *InsertBefore = nullptr) { |
3044 | return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore); |
3045 | } |
3046 | |
3047 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) { |
3048 | return new(1) BranchInst(IfTrue, InsertAtEnd); |
3049 | } |
3050 | |
3051 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse, |
3052 | Value *Cond, BasicBlock *InsertAtEnd) { |
3053 | return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd); |
3054 | } |
3055 | |
3056 | /// Transparently provide more efficient getOperand methods. |
3057 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
3058 | |
3059 | bool isUnconditional() const { return getNumOperands() == 1; } |
3060 | bool isConditional() const { return getNumOperands() == 3; } |
3061 | |
3062 | Value *getCondition() const { |
3063 | assert(isConditional() && "Cannot get condition of an uncond branch!")((isConditional() && "Cannot get condition of an uncond branch!" ) ? static_cast<void> (0) : __assert_fail ("isConditional() && \"Cannot get condition of an uncond branch!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3063, __PRETTY_FUNCTION__)); |
3064 | return Op<-3>(); |
3065 | } |
3066 | |
3067 | void setCondition(Value *V) { |
3068 | assert(isConditional() && "Cannot set condition of unconditional branch!")((isConditional() && "Cannot set condition of unconditional branch!" ) ? static_cast<void> (0) : __assert_fail ("isConditional() && \"Cannot set condition of unconditional branch!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3068, __PRETTY_FUNCTION__)); |
3069 | Op<-3>() = V; |
3070 | } |
3071 | |
3072 | unsigned getNumSuccessors() const { return 1+isConditional(); } |
3073 | |
3074 | BasicBlock *getSuccessor(unsigned i) const { |
3075 | assert(i < getNumSuccessors() && "Successor # out of range for Branch!")((i < getNumSuccessors() && "Successor # out of range for Branch!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumSuccessors() && \"Successor # out of range for Branch!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3075, __PRETTY_FUNCTION__)); |
3076 | return cast_or_null<BasicBlock>((&Op<-1>() - i)->get()); |
3077 | } |
3078 | |
3079 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
3080 | assert(idx < getNumSuccessors() && "Successor # out of range for Branch!")((idx < getNumSuccessors() && "Successor # out of range for Branch!" ) ? static_cast<void> (0) : __assert_fail ("idx < getNumSuccessors() && \"Successor # out of range for Branch!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3080, __PRETTY_FUNCTION__)); |
3081 | *(&Op<-1>() - idx) = NewSucc; |
3082 | } |
3083 | |
3084 | /// Swap the successors of this branch instruction. |
3085 | /// |
3086 | /// Swaps the successors of the branch instruction. This also swaps any |
3087 | /// branch weight metadata associated with the instruction so that it |
3088 | /// continues to map correctly to each operand. |
3089 | void swapSuccessors(); |
3090 | |
3091 | iterator_range<succ_op_iterator> successors() { |
3092 | return make_range( |
3093 | succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)), |
3094 | succ_op_iterator(value_op_end())); |
3095 | } |
3096 | |
3097 | iterator_range<const_succ_op_iterator> successors() const { |
3098 | return make_range(const_succ_op_iterator( |
3099 | std::next(value_op_begin(), isConditional() ? 1 : 0)), |
3100 | const_succ_op_iterator(value_op_end())); |
3101 | } |
3102 | |
3103 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3104 | static bool classof(const Instruction *I) { |
3105 | return (I->getOpcode() == Instruction::Br); |
3106 | } |
3107 | static bool classof(const Value *V) { |
3108 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3109 | } |
3110 | }; |
3111 | |
3112 | template <> |
3113 | struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> { |
3114 | }; |
3115 | |
3116 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)BranchInst::op_iterator BranchInst::op_begin() { return OperandTraits <BranchInst>::op_begin(this); } BranchInst::const_op_iterator BranchInst::op_begin() const { return OperandTraits<BranchInst >::op_begin(const_cast<BranchInst*>(this)); } BranchInst ::op_iterator BranchInst::op_end() { return OperandTraits< BranchInst>::op_end(this); } BranchInst::const_op_iterator BranchInst::op_end() const { return OperandTraits<BranchInst >::op_end(const_cast<BranchInst*>(this)); } Value *BranchInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<BranchInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3116, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<BranchInst>::op_begin(const_cast<BranchInst *>(this))[i_nocapture].get()); } void BranchInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<BranchInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3116, __PRETTY_FUNCTION__)); OperandTraits<BranchInst> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned BranchInst ::getNumOperands() const { return OperandTraits<BranchInst >::operands(this); } template <int Idx_nocapture> Use &BranchInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & BranchInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
3117 | |
3118 | //===----------------------------------------------------------------------===// |
3119 | // SwitchInst Class |
3120 | //===----------------------------------------------------------------------===// |
3121 | |
3122 | //===--------------------------------------------------------------------------- |
3123 | /// Multiway switch |
3124 | /// |
3125 | class SwitchInst : public Instruction { |
3126 | unsigned ReservedSpace; |
3127 | |
3128 | // Operand[0] = Value to switch on |
3129 | // Operand[1] = Default basic block destination |
3130 | // Operand[2n ] = Value to match |
3131 | // Operand[2n+1] = BasicBlock to go to on match |
3132 | SwitchInst(const SwitchInst &SI); |
3133 | |
3134 | /// Create a new switch instruction, specifying a value to switch on and a |
3135 | /// default destination. The number of additional cases can be specified here |
3136 | /// to make memory allocation more efficient. This constructor can also |
3137 | /// auto-insert before another instruction. |
3138 | SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, |
3139 | Instruction *InsertBefore); |
3140 | |
3141 | /// Create a new switch instruction, specifying a value to switch on and a |
3142 | /// default destination. The number of additional cases can be specified here |
3143 | /// to make memory allocation more efficient. This constructor also |
3144 | /// auto-inserts at the end of the specified BasicBlock. |
3145 | SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, |
3146 | BasicBlock *InsertAtEnd); |
3147 | |
3148 | // allocate space for exactly zero operands |
3149 | void *operator new(size_t s) { |
3150 | return User::operator new(s); |
3151 | } |
3152 | |
3153 | void init(Value *Value, BasicBlock *Default, unsigned NumReserved); |
3154 | void growOperands(); |
3155 | |
3156 | protected: |
3157 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3158 | friend class Instruction; |
3159 | |
3160 | SwitchInst *cloneImpl() const; |
3161 | |
3162 | public: |
3163 | // -2 |
3164 | static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1); |
3165 | |
3166 | template <typename CaseHandleT> class CaseIteratorImpl; |
3167 | |
3168 | /// A handle to a particular switch case. It exposes a convenient interface |
3169 | /// to both the case value and the successor block. |
3170 | /// |
3171 | /// We define this as a template and instantiate it to form both a const and |
3172 | /// non-const handle. |
3173 | template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT> |
3174 | class CaseHandleImpl { |
3175 | // Directly befriend both const and non-const iterators. |
3176 | friend class SwitchInst::CaseIteratorImpl< |
3177 | CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>; |
3178 | |
3179 | protected: |
3180 | // Expose the switch type we're parameterized with to the iterator. |
3181 | using SwitchInstType = SwitchInstT; |
3182 | |
3183 | SwitchInstT *SI; |
3184 | ptrdiff_t Index; |
3185 | |
3186 | CaseHandleImpl() = default; |
3187 | CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {} |
3188 | |
3189 | public: |
3190 | /// Resolves case value for current case. |
3191 | ConstantIntT *getCaseValue() const { |
3192 | assert((unsigned)Index < SI->getNumCases() &&(((unsigned)Index < SI->getNumCases() && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3193, __PRETTY_FUNCTION__)) |
3193 | "Index out the number of cases.")(((unsigned)Index < SI->getNumCases() && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3193, __PRETTY_FUNCTION__)); |
3194 | return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2)); |
3195 | } |
3196 | |
3197 | /// Resolves successor for current case. |
3198 | BasicBlockT *getCaseSuccessor() const { |
3199 | assert(((unsigned)Index < SI->getNumCases() ||((((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3201, __PRETTY_FUNCTION__)) |
3200 | (unsigned)Index == DefaultPseudoIndex) &&((((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3201, __PRETTY_FUNCTION__)) |
3201 | "Index out the number of cases.")((((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3201, __PRETTY_FUNCTION__)); |
3202 | return SI->getSuccessor(getSuccessorIndex()); |
3203 | } |
3204 | |
3205 | /// Returns number of current case. |
3206 | unsigned getCaseIndex() const { return Index; } |
3207 | |
3208 | /// Returns successor index for current case successor. |
3209 | unsigned getSuccessorIndex() const { |
3210 | assert(((unsigned)Index == DefaultPseudoIndex ||((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3212, __PRETTY_FUNCTION__)) |
3211 | (unsigned)Index < SI->getNumCases()) &&((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3212, __PRETTY_FUNCTION__)) |
3212 | "Index out the number of cases.")((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3212, __PRETTY_FUNCTION__)); |
3213 | return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0; |
3214 | } |
3215 | |
3216 | bool operator==(const CaseHandleImpl &RHS) const { |
3217 | assert(SI == RHS.SI && "Incompatible operators.")((SI == RHS.SI && "Incompatible operators.") ? static_cast <void> (0) : __assert_fail ("SI == RHS.SI && \"Incompatible operators.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3217, __PRETTY_FUNCTION__)); |
3218 | return Index == RHS.Index; |
3219 | } |
3220 | }; |
3221 | |
3222 | using ConstCaseHandle = |
3223 | CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>; |
3224 | |
3225 | class CaseHandle |
3226 | : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> { |
3227 | friend class SwitchInst::CaseIteratorImpl<CaseHandle>; |
3228 | |
3229 | public: |
3230 | CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {} |
3231 | |
3232 | /// Sets the new value for current case. |
3233 | void setValue(ConstantInt *V) { |
3234 | assert((unsigned)Index < SI->getNumCases() &&(((unsigned)Index < SI->getNumCases() && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3235, __PRETTY_FUNCTION__)) |
3235 | "Index out the number of cases.")(((unsigned)Index < SI->getNumCases() && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3235, __PRETTY_FUNCTION__)); |
3236 | SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V)); |
3237 | } |
3238 | |
3239 | /// Sets the new successor for current case. |
3240 | void setSuccessor(BasicBlock *S) { |
3241 | SI->setSuccessor(getSuccessorIndex(), S); |
3242 | } |
3243 | }; |
3244 | |
3245 | template <typename CaseHandleT> |
3246 | class CaseIteratorImpl |
3247 | : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>, |
3248 | std::random_access_iterator_tag, |
3249 | CaseHandleT> { |
3250 | using SwitchInstT = typename CaseHandleT::SwitchInstType; |
3251 | |
3252 | CaseHandleT Case; |
3253 | |
3254 | public: |
3255 | /// Default constructed iterator is in an invalid state until assigned to |
3256 | /// a case for a particular switch. |
3257 | CaseIteratorImpl() = default; |
3258 | |
3259 | /// Initializes case iterator for given SwitchInst and for given |
3260 | /// case number. |
3261 | CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {} |
3262 | |
3263 | /// Initializes case iterator for given SwitchInst and for given |
3264 | /// successor index. |
3265 | static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI, |
3266 | unsigned SuccessorIndex) { |
3267 | assert(SuccessorIndex < SI->getNumSuccessors() &&((SuccessorIndex < SI->getNumSuccessors() && "Successor index # out of range!" ) ? static_cast<void> (0) : __assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3268, __PRETTY_FUNCTION__)) |
3268 | "Successor index # out of range!")((SuccessorIndex < SI->getNumSuccessors() && "Successor index # out of range!" ) ? static_cast<void> (0) : __assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3268, __PRETTY_FUNCTION__)); |
3269 | return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1) |
3270 | : CaseIteratorImpl(SI, DefaultPseudoIndex); |
3271 | } |
3272 | |
3273 | /// Support converting to the const variant. This will be a no-op for const |
3274 | /// variant. |
3275 | operator CaseIteratorImpl<ConstCaseHandle>() const { |
3276 | return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index); |
3277 | } |
3278 | |
3279 | CaseIteratorImpl &operator+=(ptrdiff_t N) { |
3280 | // Check index correctness after addition. |
3281 | // Note: Index == getNumCases() means end(). |
3282 | assert(Case.Index + N >= 0 &&((Case.Index + N >= 0 && (unsigned)(Case.Index + N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3284, __PRETTY_FUNCTION__)) |
3283 | (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&((Case.Index + N >= 0 && (unsigned)(Case.Index + N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3284, __PRETTY_FUNCTION__)) |
3284 | "Case.Index out the number of cases.")((Case.Index + N >= 0 && (unsigned)(Case.Index + N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3284, __PRETTY_FUNCTION__)); |
3285 | Case.Index += N; |
3286 | return *this; |
3287 | } |
3288 | CaseIteratorImpl &operator-=(ptrdiff_t N) { |
3289 | // Check index correctness after subtraction. |
3290 | // Note: Case.Index == getNumCases() means end(). |
3291 | assert(Case.Index - N >= 0 &&((Case.Index - N >= 0 && (unsigned)(Case.Index - N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3293, __PRETTY_FUNCTION__)) |
3292 | (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&((Case.Index - N >= 0 && (unsigned)(Case.Index - N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3293, __PRETTY_FUNCTION__)) |
3293 | "Case.Index out the number of cases.")((Case.Index - N >= 0 && (unsigned)(Case.Index - N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3293, __PRETTY_FUNCTION__)); |
3294 | Case.Index -= N; |
3295 | return *this; |
3296 | } |
3297 | ptrdiff_t operator-(const CaseIteratorImpl &RHS) const { |
3298 | assert(Case.SI == RHS.Case.SI && "Incompatible operators.")((Case.SI == RHS.Case.SI && "Incompatible operators." ) ? static_cast<void> (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3298, __PRETTY_FUNCTION__)); |
3299 | return Case.Index - RHS.Case.Index; |
3300 | } |
3301 | bool operator==(const CaseIteratorImpl &RHS) const { |
3302 | return Case == RHS.Case; |
3303 | } |
3304 | bool operator<(const CaseIteratorImpl &RHS) const { |
3305 | assert(Case.SI == RHS.Case.SI && "Incompatible operators.")((Case.SI == RHS.Case.SI && "Incompatible operators." ) ? static_cast<void> (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3305, __PRETTY_FUNCTION__)); |
3306 | return Case.Index < RHS.Case.Index; |
3307 | } |
3308 | CaseHandleT &operator*() { return Case; } |
3309 | const CaseHandleT &operator*() const { return Case; } |
3310 | }; |
3311 | |
3312 | using CaseIt = CaseIteratorImpl<CaseHandle>; |
3313 | using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>; |
3314 | |
3315 | static SwitchInst *Create(Value *Value, BasicBlock *Default, |
3316 | unsigned NumCases, |
3317 | Instruction *InsertBefore = nullptr) { |
3318 | return new SwitchInst(Value, Default, NumCases, InsertBefore); |
3319 | } |
3320 | |
3321 | static SwitchInst *Create(Value *Value, BasicBlock *Default, |
3322 | unsigned NumCases, BasicBlock *InsertAtEnd) { |
3323 | return new SwitchInst(Value, Default, NumCases, InsertAtEnd); |
3324 | } |
3325 | |
3326 | /// Provide fast operand accessors |
3327 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
3328 | |
3329 | // Accessor Methods for Switch stmt |
3330 | Value *getCondition() const { return getOperand(0); } |
3331 | void setCondition(Value *V) { setOperand(0, V); } |
3332 | |
3333 | BasicBlock *getDefaultDest() const { |
3334 | return cast<BasicBlock>(getOperand(1)); |
3335 | } |
3336 | |
3337 | void setDefaultDest(BasicBlock *DefaultCase) { |
3338 | setOperand(1, reinterpret_cast<Value*>(DefaultCase)); |
3339 | } |
3340 | |
3341 | /// Return the number of 'cases' in this switch instruction, excluding the |
3342 | /// default case. |
3343 | unsigned getNumCases() const { |
3344 | return getNumOperands()/2 - 1; |
3345 | } |
3346 | |
3347 | /// Returns a read/write iterator that points to the first case in the |
3348 | /// SwitchInst. |
3349 | CaseIt case_begin() { |
3350 | return CaseIt(this, 0); |
3351 | } |
3352 | |
3353 | /// Returns a read-only iterator that points to the first case in the |
3354 | /// SwitchInst. |
3355 | ConstCaseIt case_begin() const { |
3356 | return ConstCaseIt(this, 0); |
3357 | } |
3358 | |
3359 | /// Returns a read/write iterator that points one past the last in the |
3360 | /// SwitchInst. |
3361 | CaseIt case_end() { |
3362 | return CaseIt(this, getNumCases()); |
3363 | } |
3364 | |
3365 | /// Returns a read-only iterator that points one past the last in the |
3366 | /// SwitchInst. |
3367 | ConstCaseIt case_end() const { |
3368 | return ConstCaseIt(this, getNumCases()); |
3369 | } |
3370 | |
3371 | /// Iteration adapter for range-for loops. |
3372 | iterator_range<CaseIt> cases() { |
3373 | return make_range(case_begin(), case_end()); |
3374 | } |
3375 | |
3376 | /// Constant iteration adapter for range-for loops. |
3377 | iterator_range<ConstCaseIt> cases() const { |
3378 | return make_range(case_begin(), case_end()); |
3379 | } |
3380 | |
3381 | /// Returns an iterator that points to the default case. |
3382 | /// Note: this iterator allows to resolve successor only. Attempt |
3383 | /// to resolve case value causes an assertion. |
3384 | /// Also note, that increment and decrement also causes an assertion and |
3385 | /// makes iterator invalid. |
3386 | CaseIt case_default() { |
3387 | return CaseIt(this, DefaultPseudoIndex); |
3388 | } |
3389 | ConstCaseIt case_default() const { |
3390 | return ConstCaseIt(this, DefaultPseudoIndex); |
3391 | } |
3392 | |
3393 | /// Search all of the case values for the specified constant. If it is |
3394 | /// explicitly handled, return the case iterator of it, otherwise return |
3395 | /// default case iterator to indicate that it is handled by the default |
3396 | /// handler. |
3397 | CaseIt findCaseValue(const ConstantInt *C) { |
3398 | CaseIt I = llvm::find_if( |
3399 | cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; }); |
3400 | if (I != case_end()) |
3401 | return I; |
3402 | |
3403 | return case_default(); |
3404 | } |
3405 | ConstCaseIt findCaseValue(const ConstantInt *C) const { |
3406 | ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) { |
3407 | return Case.getCaseValue() == C; |
3408 | }); |
3409 | if (I != case_end()) |
3410 | return I; |
3411 | |
3412 | return case_default(); |
3413 | } |
3414 | |
3415 | /// Finds the unique case value for a given successor. Returns null if the |
3416 | /// successor is not found, not unique, or is the default case. |
3417 | ConstantInt *findCaseDest(BasicBlock *BB) { |
3418 | if (BB == getDefaultDest()) |
3419 | return nullptr; |
3420 | |
3421 | ConstantInt *CI = nullptr; |
3422 | for (auto Case : cases()) { |
3423 | if (Case.getCaseSuccessor() != BB) |
3424 | continue; |
3425 | |
3426 | if (CI) |
3427 | return nullptr; // Multiple cases lead to BB. |
3428 | |
3429 | CI = Case.getCaseValue(); |
3430 | } |
3431 | |
3432 | return CI; |
3433 | } |
3434 | |
3435 | /// Add an entry to the switch instruction. |
3436 | /// Note: |
3437 | /// This action invalidates case_end(). Old case_end() iterator will |
3438 | /// point to the added case. |
3439 | void addCase(ConstantInt *OnVal, BasicBlock *Dest); |
3440 | |
3441 | /// This method removes the specified case and its successor from the switch |
3442 | /// instruction. Note that this operation may reorder the remaining cases at |
3443 | /// index idx and above. |
3444 | /// Note: |
3445 | /// This action invalidates iterators for all cases following the one removed, |
3446 | /// including the case_end() iterator. It returns an iterator for the next |
3447 | /// case. |
3448 | CaseIt removeCase(CaseIt I); |
3449 | |
3450 | unsigned getNumSuccessors() const { return getNumOperands()/2; } |
3451 | BasicBlock *getSuccessor(unsigned idx) const { |
3452 | assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!")((idx < getNumSuccessors() &&"Successor idx out of range for switch!" ) ? static_cast<void> (0) : __assert_fail ("idx < getNumSuccessors() &&\"Successor idx out of range for switch!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3452, __PRETTY_FUNCTION__)); |
3453 | return cast<BasicBlock>(getOperand(idx*2+1)); |
3454 | } |
3455 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
3456 | assert(idx < getNumSuccessors() && "Successor # out of range for switch!")((idx < getNumSuccessors() && "Successor # out of range for switch!" ) ? static_cast<void> (0) : __assert_fail ("idx < getNumSuccessors() && \"Successor # out of range for switch!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3456, __PRETTY_FUNCTION__)); |
3457 | setOperand(idx * 2 + 1, NewSucc); |
3458 | } |
3459 | |
3460 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3461 | static bool classof(const Instruction *I) { |
3462 | return I->getOpcode() == Instruction::Switch; |
3463 | } |
3464 | static bool classof(const Value *V) { |
3465 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3466 | } |
3467 | }; |
3468 | |
3469 | /// A wrapper class to simplify modification of SwitchInst cases along with |
3470 | /// their prof branch_weights metadata. |
3471 | class SwitchInstProfUpdateWrapper { |
3472 | SwitchInst &SI; |
3473 | Optional<SmallVector<uint32_t, 8> > Weights = None; |
3474 | bool Changed = false; |
3475 | |
3476 | protected: |
3477 | static MDNode *getProfBranchWeightsMD(const SwitchInst &SI); |
3478 | |
3479 | MDNode *buildProfBranchWeightsMD(); |
3480 | |
3481 | void init(); |
3482 | |
3483 | public: |
3484 | using CaseWeightOpt = Optional<uint32_t>; |
3485 | SwitchInst *operator->() { return &SI; } |
3486 | SwitchInst &operator*() { return SI; } |
3487 | operator SwitchInst *() { return &SI; } |
3488 | |
3489 | SwitchInstProfUpdateWrapper(SwitchInst &SI) : SI(SI) { init(); } |
3490 | |
3491 | ~SwitchInstProfUpdateWrapper() { |
3492 | if (Changed) |
3493 | SI.setMetadata(LLVMContext::MD_prof, buildProfBranchWeightsMD()); |
3494 | } |
3495 | |
3496 | /// Delegate the call to the underlying SwitchInst::removeCase() and remove |
3497 | /// correspondent branch weight. |
3498 | SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I); |
3499 | |
3500 | /// Delegate the call to the underlying SwitchInst::addCase() and set the |
3501 | /// specified branch weight for the added case. |
3502 | void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W); |
3503 | |
3504 | /// Delegate the call to the underlying SwitchInst::eraseFromParent() and mark |
3505 | /// this object to not touch the underlying SwitchInst in destructor. |
3506 | SymbolTableList<Instruction>::iterator eraseFromParent(); |
3507 | |
3508 | void setSuccessorWeight(unsigned idx, CaseWeightOpt W); |
3509 | CaseWeightOpt getSuccessorWeight(unsigned idx); |
3510 | |
3511 | static CaseWeightOpt getSuccessorWeight(const SwitchInst &SI, unsigned idx); |
3512 | }; |
3513 | |
3514 | template <> |
3515 | struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> { |
3516 | }; |
3517 | |
3518 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)SwitchInst::op_iterator SwitchInst::op_begin() { return OperandTraits <SwitchInst>::op_begin(this); } SwitchInst::const_op_iterator SwitchInst::op_begin() const { return OperandTraits<SwitchInst >::op_begin(const_cast<SwitchInst*>(this)); } SwitchInst ::op_iterator SwitchInst::op_end() { return OperandTraits< SwitchInst>::op_end(this); } SwitchInst::const_op_iterator SwitchInst::op_end() const { return OperandTraits<SwitchInst >::op_end(const_cast<SwitchInst*>(this)); } Value *SwitchInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<SwitchInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SwitchInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3518, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<SwitchInst>::op_begin(const_cast<SwitchInst *>(this))[i_nocapture].get()); } void SwitchInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<SwitchInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SwitchInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3518, __PRETTY_FUNCTION__)); OperandTraits<SwitchInst> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned SwitchInst ::getNumOperands() const { return OperandTraits<SwitchInst >::operands(this); } template <int Idx_nocapture> Use &SwitchInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & SwitchInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
3519 | |
3520 | //===----------------------------------------------------------------------===// |
3521 | // IndirectBrInst Class |
3522 | //===----------------------------------------------------------------------===// |
3523 | |
3524 | //===--------------------------------------------------------------------------- |
3525 | /// Indirect Branch Instruction. |
3526 | /// |
3527 | class IndirectBrInst : public Instruction { |
3528 | unsigned ReservedSpace; |
3529 | |
3530 | // Operand[0] = Address to jump to |
3531 | // Operand[n+1] = n-th destination |
3532 | IndirectBrInst(const IndirectBrInst &IBI); |
3533 | |
3534 | /// Create a new indirectbr instruction, specifying an |
3535 | /// Address to jump to. The number of expected destinations can be specified |
3536 | /// here to make memory allocation more efficient. This constructor can also |
3537 | /// autoinsert before another instruction. |
3538 | IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore); |
3539 | |
3540 | /// Create a new indirectbr instruction, specifying an |
3541 | /// Address to jump to. The number of expected destinations can be specified |
3542 | /// here to make memory allocation more efficient. This constructor also |
3543 | /// autoinserts at the end of the specified BasicBlock. |
3544 | IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd); |
3545 | |
3546 | // allocate space for exactly zero operands |
3547 | void *operator new(size_t s) { |
3548 | return User::operator new(s); |
3549 | } |
3550 | |
3551 | void init(Value *Address, unsigned NumDests); |
3552 | void growOperands(); |
3553 | |
3554 | protected: |
3555 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3556 | friend class Instruction; |
3557 | |
3558 | IndirectBrInst *cloneImpl() const; |
3559 | |
3560 | public: |
3561 | /// Iterator type that casts an operand to a basic block. |
3562 | /// |
3563 | /// This only makes sense because the successors are stored as adjacent |
3564 | /// operands for indirectbr instructions. |
3565 | struct succ_op_iterator |
3566 | : iterator_adaptor_base<succ_op_iterator, value_op_iterator, |
3567 | std::random_access_iterator_tag, BasicBlock *, |
3568 | ptrdiff_t, BasicBlock *, BasicBlock *> { |
3569 | explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {} |
3570 | |
3571 | BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3572 | BasicBlock *operator->() const { return operator*(); } |
3573 | }; |
3574 | |
3575 | /// The const version of `succ_op_iterator`. |
3576 | struct const_succ_op_iterator |
3577 | : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator, |
3578 | std::random_access_iterator_tag, |
3579 | const BasicBlock *, ptrdiff_t, const BasicBlock *, |
3580 | const BasicBlock *> { |
3581 | explicit const_succ_op_iterator(const_value_op_iterator I) |
3582 | : iterator_adaptor_base(I) {} |
3583 | |
3584 | const BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3585 | const BasicBlock *operator->() const { return operator*(); } |
3586 | }; |
3587 | |
3588 | static IndirectBrInst *Create(Value *Address, unsigned NumDests, |
3589 | Instruction *InsertBefore = nullptr) { |
3590 | return new IndirectBrInst(Address, NumDests, InsertBefore); |
3591 | } |
3592 | |
3593 | static IndirectBrInst *Create(Value *Address, unsigned NumDests, |
3594 | BasicBlock *InsertAtEnd) { |
3595 | return new IndirectBrInst(Address, NumDests, InsertAtEnd); |
3596 | } |
3597 | |
3598 | /// Provide fast operand accessors. |
3599 | 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; |
3600 | |
3601 | // Accessor Methods for IndirectBrInst instruction. |
3602 | Value *getAddress() { return getOperand(0); } |
3603 | const Value *getAddress() const { return getOperand(0); } |
3604 | void setAddress(Value *V) { setOperand(0, V); } |
3605 | |
3606 | /// return the number of possible destinations in this |
3607 | /// indirectbr instruction. |
3608 | unsigned getNumDestinations() const { return getNumOperands()-1; } |
3609 | |
3610 | /// Return the specified destination. |
3611 | BasicBlock *getDestination(unsigned i) { return getSuccessor(i); } |
3612 | const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); } |
3613 | |
3614 | /// Add a destination. |
3615 | /// |
3616 | void addDestination(BasicBlock *Dest); |
3617 | |
3618 | /// This method removes the specified successor from the |
3619 | /// indirectbr instruction. |
3620 | void removeDestination(unsigned i); |
3621 | |
3622 | unsigned getNumSuccessors() const { return getNumOperands()-1; } |
3623 | BasicBlock *getSuccessor(unsigned i) const { |
3624 | return cast<BasicBlock>(getOperand(i+1)); |
3625 | } |
3626 | void setSuccessor(unsigned i, BasicBlock *NewSucc) { |
3627 | setOperand(i + 1, NewSucc); |
3628 | } |
3629 | |
3630 | iterator_range<succ_op_iterator> successors() { |
3631 | return make_range(succ_op_iterator(std::next(value_op_begin())), |
3632 | succ_op_iterator(value_op_end())); |
3633 | } |
3634 | |
3635 | iterator_range<const_succ_op_iterator> successors() const { |
3636 | return make_range(const_succ_op_iterator(std::next(value_op_begin())), |
3637 | const_succ_op_iterator(value_op_end())); |
3638 | } |
3639 | |
3640 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3641 | static bool classof(const Instruction *I) { |
3642 | return I->getOpcode() == Instruction::IndirectBr; |
3643 | } |
3644 | static bool classof(const Value *V) { |
3645 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3646 | } |
3647 | }; |
3648 | |
3649 | template <> |
3650 | struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> { |
3651 | }; |
3652 | |
3653 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)IndirectBrInst::op_iterator IndirectBrInst::op_begin() { return OperandTraits<IndirectBrInst>::op_begin(this); } IndirectBrInst ::const_op_iterator IndirectBrInst::op_begin() const { return OperandTraits<IndirectBrInst>::op_begin(const_cast< IndirectBrInst*>(this)); } IndirectBrInst::op_iterator IndirectBrInst ::op_end() { return OperandTraits<IndirectBrInst>::op_end (this); } IndirectBrInst::const_op_iterator IndirectBrInst::op_end () const { return OperandTraits<IndirectBrInst>::op_end (const_cast<IndirectBrInst*>(this)); } Value *IndirectBrInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3653, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<IndirectBrInst>::op_begin(const_cast< IndirectBrInst*>(this))[i_nocapture].get()); } void IndirectBrInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( i_nocapture < OperandTraits<IndirectBrInst>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3653, __PRETTY_FUNCTION__)); OperandTraits<IndirectBrInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned IndirectBrInst::getNumOperands() const { return OperandTraits <IndirectBrInst>::operands(this); } template <int Idx_nocapture > Use &IndirectBrInst::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &IndirectBrInst::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
3654 | |
3655 | //===----------------------------------------------------------------------===// |
3656 | // InvokeInst Class |
3657 | //===----------------------------------------------------------------------===// |
3658 | |
3659 | /// Invoke instruction. The SubclassData field is used to hold the |
3660 | /// calling convention of the call. |
3661 | /// |
3662 | class InvokeInst : public CallBase { |
3663 | /// The number of operands for this call beyond the called function, |
3664 | /// arguments, and operand bundles. |
3665 | static constexpr int NumExtraOperands = 2; |
3666 | |
3667 | /// The index from the end of the operand array to the normal destination. |
3668 | static constexpr int NormalDestOpEndIdx = -3; |
3669 | |
3670 | /// The index from the end of the operand array to the unwind destination. |
3671 | static constexpr int UnwindDestOpEndIdx = -2; |
3672 | |
3673 | InvokeInst(const InvokeInst &BI); |
3674 | |
3675 | /// Construct an InvokeInst given a range of arguments. |
3676 | /// |
3677 | /// Construct an InvokeInst from a range of arguments |
3678 | inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3679 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3680 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3681 | const Twine &NameStr, Instruction *InsertBefore); |
3682 | |
3683 | inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3684 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3685 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3686 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
3687 | |
3688 | void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3689 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3690 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr); |
3691 | |
3692 | /// Compute the number of operands to allocate. |
3693 | static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) { |
3694 | // We need one operand for the called function, plus our extra operands and |
3695 | // the input operand counts provided. |
3696 | return 1 + NumExtraOperands + NumArgs + NumBundleInputs; |
3697 | } |
3698 | |
3699 | protected: |
3700 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3701 | friend class Instruction; |
3702 | |
3703 | InvokeInst *cloneImpl() const; |
3704 | |
3705 | public: |
3706 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3707 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3708 | const Twine &NameStr, |
3709 | Instruction *InsertBefore = nullptr) { |
3710 | int NumOperands = ComputeNumOperands(Args.size()); |
3711 | return new (NumOperands) |
3712 | InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands, |
3713 | NameStr, InsertBefore); |
3714 | } |
3715 | |
3716 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3717 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3718 | ArrayRef<OperandBundleDef> Bundles = None, |
3719 | const Twine &NameStr = "", |
3720 | Instruction *InsertBefore = nullptr) { |
3721 | int NumOperands = |
3722 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
3723 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
3724 | |
3725 | return new (NumOperands, DescriptorBytes) |
3726 | InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands, |
3727 | NameStr, InsertBefore); |
3728 | } |
3729 | |
3730 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3731 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3732 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3733 | int NumOperands = ComputeNumOperands(Args.size()); |
3734 | return new (NumOperands) |
3735 | InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands, |
3736 | NameStr, InsertAtEnd); |
3737 | } |
3738 | |
3739 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3740 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3741 | ArrayRef<OperandBundleDef> Bundles, |
3742 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3743 | int NumOperands = |
3744 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
3745 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
3746 | |
3747 | return new (NumOperands, DescriptorBytes) |
3748 | InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands, |
3749 | NameStr, InsertAtEnd); |
3750 | } |
3751 | |
3752 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
3753 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3754 | const Twine &NameStr, |
3755 | Instruction *InsertBefore = nullptr) { |
3756 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
3757 | IfException, Args, None, NameStr, InsertBefore); |
3758 | } |
3759 | |
3760 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
3761 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3762 | ArrayRef<OperandBundleDef> Bundles = None, |
3763 | const Twine &NameStr = "", |
3764 | Instruction *InsertBefore = nullptr) { |
3765 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
3766 | IfException, Args, Bundles, NameStr, InsertBefore); |
3767 | } |
3768 | |
3769 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
3770 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3771 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3772 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
3773 | IfException, Args, NameStr, InsertAtEnd); |
3774 | } |
3775 | |
3776 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
3777 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3778 | ArrayRef<OperandBundleDef> Bundles, |
3779 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3780 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
3781 | IfException, Args, Bundles, NameStr, InsertAtEnd); |
3782 | } |
3783 | |
3784 | /// Create a clone of \p II with a different set of operand bundles and |
3785 | /// insert it before \p InsertPt. |
3786 | /// |
3787 | /// The returned invoke instruction is identical to \p II in every way except |
3788 | /// that the operand bundles for the new instruction are set to the operand |
3789 | /// bundles in \p Bundles. |
3790 | static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles, |
3791 | Instruction *InsertPt = nullptr); |
3792 | |
3793 | /// Create a clone of \p II with a different set of operand bundles and |
3794 | /// insert it before \p InsertPt. |
3795 | /// |
3796 | /// The returned invoke instruction is identical to \p II in every way except |
3797 | /// that the operand bundle for the new instruction is set to the operand |
3798 | /// bundle in \p Bundle. |
3799 | static InvokeInst *CreateWithReplacedBundle(InvokeInst *II, |
3800 | OperandBundleDef Bundles, |
3801 | Instruction *InsertPt = nullptr); |
3802 | |
3803 | // get*Dest - Return the destination basic blocks... |
3804 | BasicBlock *getNormalDest() const { |
3805 | return cast<BasicBlock>(Op<NormalDestOpEndIdx>()); |
3806 | } |
3807 | BasicBlock *getUnwindDest() const { |
3808 | return cast<BasicBlock>(Op<UnwindDestOpEndIdx>()); |
3809 | } |
3810 | void setNormalDest(BasicBlock *B) { |
3811 | Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B); |
3812 | } |
3813 | void setUnwindDest(BasicBlock *B) { |
3814 | Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B); |
3815 | } |
3816 | |
3817 | /// Get the landingpad instruction from the landing pad |
3818 | /// block (the unwind destination). |
3819 | LandingPadInst *getLandingPadInst() const; |
3820 | |
3821 | BasicBlock *getSuccessor(unsigned i) const { |
3822 | assert(i < 2 && "Successor # out of range for invoke!")((i < 2 && "Successor # out of range for invoke!") ? static_cast<void> (0) : __assert_fail ("i < 2 && \"Successor # out of range for invoke!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3822, __PRETTY_FUNCTION__)); |
3823 | return i == 0 ? getNormalDest() : getUnwindDest(); |
3824 | } |
3825 | |
3826 | void setSuccessor(unsigned i, BasicBlock *NewSucc) { |
3827 | assert(i < 2 && "Successor # out of range for invoke!")((i < 2 && "Successor # out of range for invoke!") ? static_cast<void> (0) : __assert_fail ("i < 2 && \"Successor # out of range for invoke!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 3827, __PRETTY_FUNCTION__)); |
3828 | if (i == 0) |
3829 | setNormalDest(NewSucc); |
3830 | else |
3831 | setUnwindDest(NewSucc); |
3832 | } |
3833 | |
3834 | unsigned getNumSuccessors() const { return 2; } |
3835 | |
3836 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3837 | static bool classof(const Instruction *I) { |
3838 | return (I->getOpcode() == Instruction::Invoke); |
3839 | } |
3840 | static bool classof(const Value *V) { |
3841 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3842 | } |
3843 | |
3844 | private: |
3845 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
3846 | // method so that subclasses cannot accidentally use it. |
3847 | template <typename Bitfield> |
3848 | void setSubclassData(typename Bitfield::Type Value) { |
3849 | Instruction::setSubclassData<Bitfield>(Value); |
3850 | } |
3851 | }; |
3852 | |
3853 | InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3854 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3855 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3856 | const Twine &NameStr, Instruction *InsertBefore) |
3857 | : CallBase(Ty->getReturnType(), Instruction::Invoke, |
3858 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
3859 | InsertBefore) { |
3860 | init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr); |
3861 | } |
3862 | |
3863 | InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3864 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3865 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3866 | const Twine &NameStr, BasicBlock *InsertAtEnd) |
3867 | : CallBase(Ty->getReturnType(), Instruction::Invoke, |
3868 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
3869 | InsertAtEnd) { |
3870 | init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr); |
3871 | } |
3872 | |
3873 | //===----------------------------------------------------------------------===// |
3874 | // CallBrInst Class |
3875 | //===----------------------------------------------------------------------===// |
3876 | |
3877 | /// CallBr instruction, tracking function calls that may not return control but |
3878 | /// instead transfer it to a third location. The SubclassData field is used to |
3879 | /// hold the calling convention of the call. |
3880 | /// |
3881 | class CallBrInst : public CallBase { |
3882 | |
3883 | unsigned NumIndirectDests; |
3884 | |
3885 | CallBrInst(const CallBrInst &BI); |
3886 | |
3887 | /// Construct a CallBrInst given a range of arguments. |
3888 | /// |
3889 | /// Construct a CallBrInst from a range of arguments |
3890 | inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
3891 | ArrayRef<BasicBlock *> IndirectDests, |
3892 | ArrayRef<Value *> Args, |
3893 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3894 | const Twine &NameStr, Instruction *InsertBefore); |
3895 | |
3896 | inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
3897 | ArrayRef<BasicBlock *> IndirectDests, |
3898 | ArrayRef<Value *> Args, |
3899 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3900 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
3901 | |
3902 | void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest, |
3903 | ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args, |
3904 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr); |
3905 | |
3906 | /// Should the Indirect Destinations change, scan + update the Arg list. |
3907 | void updateArgBlockAddresses(unsigned i, BasicBlock *B); |
3908 | |
3909 | /// Compute the number of operands to allocate. |
3910 | static int ComputeNumOperands(int NumArgs, int NumIndirectDests, |
3911 | int NumBundleInputs = 0) { |
3912 | // We need one operand for the called function, plus our extra operands and |
3913 | // the input operand counts provided. |
3914 | return 2 + NumIndirectDests + NumArgs + NumBundleInputs; |
3915 | } |
3916 | |
3917 | protected: |
3918 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3919 | friend class Instruction; |
3920 | |
3921 | CallBrInst *cloneImpl() const; |
3922 | |
3923 | public: |
3924 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
3925 | BasicBlock *DefaultDest, |
3926 | ArrayRef<BasicBlock *> IndirectDests, |
3927 | ArrayRef<Value *> Args, const Twine &NameStr, |
3928 | Instruction *InsertBefore = nullptr) { |
3929 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size()); |
3930 | return new (NumOperands) |
3931 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None, |
3932 | NumOperands, NameStr, InsertBefore); |
3933 | } |
3934 | |
3935 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
3936 | BasicBlock *DefaultDest, |
3937 | ArrayRef<BasicBlock *> IndirectDests, |
3938 | ArrayRef<Value *> Args, |
3939 | ArrayRef<OperandBundleDef> Bundles = None, |
3940 | const Twine &NameStr = "", |
3941 | Instruction *InsertBefore = nullptr) { |
3942 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(), |
3943 | CountBundleInputs(Bundles)); |
3944 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
3945 | |
3946 | return new (NumOperands, DescriptorBytes) |
3947 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, |
3948 | NumOperands, NameStr, InsertBefore); |
3949 | } |
3950 | |
3951 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
3952 | BasicBlock *DefaultDest, |
3953 | ArrayRef<BasicBlock *> IndirectDests, |
3954 | ArrayRef<Value *> Args, const Twine &NameStr, |
3955 | BasicBlock *InsertAtEnd) { |
3956 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size()); |
3957 | return new (NumOperands) |
3958 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None, |
3959 | NumOperands, NameStr, InsertAtEnd); |
3960 | } |
3961 | |
3962 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
3963 | BasicBlock *DefaultDest, |
3964 | ArrayRef<BasicBlock *> IndirectDests, |
3965 | ArrayRef<Value *> Args, |
3966 | ArrayRef<OperandBundleDef> Bundles, |
3967 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3968 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(), |
3969 | CountBundleInputs(Bundles)); |
3970 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
3971 | |
3972 | return new (NumOperands, DescriptorBytes) |
3973 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, |
3974 | NumOperands, NameStr, InsertAtEnd); |
3975 | } |
3976 | |
3977 | static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest, |
3978 | ArrayRef<BasicBlock *> IndirectDests, |
3979 | ArrayRef<Value *> Args, const Twine &NameStr, |
3980 | Instruction *InsertBefore = nullptr) { |
3981 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
3982 | IndirectDests, Args, NameStr, InsertBefore); |
3983 | } |
3984 | |
3985 | static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest, |
3986 | ArrayRef<BasicBlock *> IndirectDests, |
3987 | ArrayRef<Value *> Args, |
3988 | ArrayRef<OperandBundleDef> Bundles = None, |
3989 | const Twine &NameStr = "", |
3990 | Instruction *InsertBefore = nullptr) { |
3991 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
3992 | IndirectDests, Args, Bundles, NameStr, InsertBefore); |
3993 | } |
3994 | |
3995 | static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest, |
3996 | ArrayRef<BasicBlock *> IndirectDests, |
3997 | ArrayRef<Value *> Args, const Twine &NameStr, |
3998 | BasicBlock *InsertAtEnd) { |
3999 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
4000 | IndirectDests, Args, NameStr, InsertAtEnd); |
4001 | } |
4002 | |
4003 | static CallBrInst *Create(FunctionCallee Func, |
4004 | BasicBlock *DefaultDest, |
4005 | ArrayRef<BasicBlock *> IndirectDests, |
4006 | ArrayRef<Value *> Args, |
4007 | ArrayRef<OperandBundleDef> Bundles, |
4008 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
4009 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
4010 | IndirectDests, Args, Bundles, NameStr, InsertAtEnd); |
4011 | } |
4012 | |
4013 | /// Create a clone of \p CBI with a different set of operand bundles and |
4014 | /// insert it before \p InsertPt. |
4015 | /// |
4016 | /// The returned callbr instruction is identical to \p CBI in every way |
4017 | /// except that the operand bundles for the new instruction are set to the |
4018 | /// operand bundles in \p Bundles. |
4019 | static CallBrInst *Create(CallBrInst *CBI, |
4020 | ArrayRef<OperandBundleDef> Bundles, |
4021 | Instruction *InsertPt = nullptr); |
4022 | |
4023 | /// Return the number of callbr indirect dest labels. |
4024 | /// |
4025 | unsigned getNumIndirectDests() const { return NumIndirectDests; } |
4026 | |
4027 | /// getIndirectDestLabel - Return the i-th indirect dest label. |
4028 | /// |
4029 | Value *getIndirectDestLabel(unsigned i) const { |
4030 | assert(i < getNumIndirectDests() && "Out of bounds!")((i < getNumIndirectDests() && "Out of bounds!") ? static_cast<void> (0) : __assert_fail ("i < getNumIndirectDests() && \"Out of bounds!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4030, __PRETTY_FUNCTION__)); |
4031 | return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() + |
4032 | 1); |
4033 | } |
4034 | |
4035 | Value *getIndirectDestLabelUse(unsigned i) const { |
4036 | assert(i < getNumIndirectDests() && "Out of bounds!")((i < getNumIndirectDests() && "Out of bounds!") ? static_cast<void> (0) : __assert_fail ("i < getNumIndirectDests() && \"Out of bounds!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4036, __PRETTY_FUNCTION__)); |
4037 | return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() + |
4038 | 1); |
4039 | } |
4040 | |
4041 | // Return the destination basic blocks... |
4042 | BasicBlock *getDefaultDest() const { |
4043 | return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1)); |
4044 | } |
4045 | BasicBlock *getIndirectDest(unsigned i) const { |
4046 | return cast_or_null<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i)); |
4047 | } |
4048 | SmallVector<BasicBlock *, 16> getIndirectDests() const { |
4049 | SmallVector<BasicBlock *, 16> IndirectDests; |
4050 | for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i) |
4051 | IndirectDests.push_back(getIndirectDest(i)); |
4052 | return IndirectDests; |
4053 | } |
4054 | void setDefaultDest(BasicBlock *B) { |
4055 | *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B); |
4056 | } |
4057 | void setIndirectDest(unsigned i, BasicBlock *B) { |
4058 | updateArgBlockAddresses(i, B); |
4059 | *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B); |
4060 | } |
4061 | |
4062 | BasicBlock *getSuccessor(unsigned i) const { |
4063 | assert(i < getNumSuccessors() + 1 &&((i < getNumSuccessors() + 1 && "Successor # out of range for callbr!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumSuccessors() + 1 && \"Successor # out of range for callbr!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4064, __PRETTY_FUNCTION__)) |
4064 | "Successor # out of range for callbr!")((i < getNumSuccessors() + 1 && "Successor # out of range for callbr!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumSuccessors() + 1 && \"Successor # out of range for callbr!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4064, __PRETTY_FUNCTION__)); |
4065 | return i == 0 ? getDefaultDest() : getIndirectDest(i - 1); |
4066 | } |
4067 | |
4068 | void setSuccessor(unsigned i, BasicBlock *NewSucc) { |
4069 | assert(i < getNumIndirectDests() + 1 &&((i < getNumIndirectDests() + 1 && "Successor # out of range for callbr!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumIndirectDests() + 1 && \"Successor # out of range for callbr!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4070, __PRETTY_FUNCTION__)) |
4070 | "Successor # out of range for callbr!")((i < getNumIndirectDests() + 1 && "Successor # out of range for callbr!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumIndirectDests() + 1 && \"Successor # out of range for callbr!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4070, __PRETTY_FUNCTION__)); |
4071 | return i == 0 ? setDefaultDest(NewSucc) : setIndirectDest(i - 1, NewSucc); |
4072 | } |
4073 | |
4074 | unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; } |
4075 | |
4076 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4077 | static bool classof(const Instruction *I) { |
4078 | return (I->getOpcode() == Instruction::CallBr); |
4079 | } |
4080 | static bool classof(const Value *V) { |
4081 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4082 | } |
4083 | |
4084 | private: |
4085 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
4086 | // method so that subclasses cannot accidentally use it. |
4087 | template <typename Bitfield> |
4088 | void setSubclassData(typename Bitfield::Type Value) { |
4089 | Instruction::setSubclassData<Bitfield>(Value); |
4090 | } |
4091 | }; |
4092 | |
4093 | CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
4094 | ArrayRef<BasicBlock *> IndirectDests, |
4095 | ArrayRef<Value *> Args, |
4096 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
4097 | const Twine &NameStr, Instruction *InsertBefore) |
4098 | : CallBase(Ty->getReturnType(), Instruction::CallBr, |
4099 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
4100 | InsertBefore) { |
4101 | init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr); |
4102 | } |
4103 | |
4104 | CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
4105 | ArrayRef<BasicBlock *> IndirectDests, |
4106 | ArrayRef<Value *> Args, |
4107 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
4108 | const Twine &NameStr, BasicBlock *InsertAtEnd) |
4109 | : CallBase(Ty->getReturnType(), Instruction::CallBr, |
4110 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
4111 | InsertAtEnd) { |
4112 | init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr); |
4113 | } |
4114 | |
4115 | //===----------------------------------------------------------------------===// |
4116 | // ResumeInst Class |
4117 | //===----------------------------------------------------------------------===// |
4118 | |
4119 | //===--------------------------------------------------------------------------- |
4120 | /// Resume the propagation of an exception. |
4121 | /// |
4122 | class ResumeInst : public Instruction { |
4123 | ResumeInst(const ResumeInst &RI); |
4124 | |
4125 | explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr); |
4126 | ResumeInst(Value *Exn, BasicBlock *InsertAtEnd); |
4127 | |
4128 | protected: |
4129 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4130 | friend class Instruction; |
4131 | |
4132 | ResumeInst *cloneImpl() const; |
4133 | |
4134 | public: |
4135 | static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) { |
4136 | return new(1) ResumeInst(Exn, InsertBefore); |
4137 | } |
4138 | |
4139 | static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) { |
4140 | return new(1) ResumeInst(Exn, InsertAtEnd); |
4141 | } |
4142 | |
4143 | /// Provide fast operand accessors |
4144 | 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; |
4145 | |
4146 | /// Convenience accessor. |
4147 | Value *getValue() const { return Op<0>(); } |
4148 | |
4149 | unsigned getNumSuccessors() const { return 0; } |
4150 | |
4151 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4152 | static bool classof(const Instruction *I) { |
4153 | return I->getOpcode() == Instruction::Resume; |
4154 | } |
4155 | static bool classof(const Value *V) { |
4156 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4157 | } |
4158 | |
4159 | private: |
4160 | BasicBlock *getSuccessor(unsigned idx) const { |
4161 | llvm_unreachable("ResumeInst has no successors!")::llvm::llvm_unreachable_internal("ResumeInst has no successors!" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4161); |
4162 | } |
4163 | |
4164 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
4165 | llvm_unreachable("ResumeInst has no successors!")::llvm::llvm_unreachable_internal("ResumeInst has no successors!" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4165); |
4166 | } |
4167 | }; |
4168 | |
4169 | template <> |
4170 | struct OperandTraits<ResumeInst> : |
4171 | public FixedNumOperandTraits<ResumeInst, 1> { |
4172 | }; |
4173 | |
4174 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)ResumeInst::op_iterator ResumeInst::op_begin() { return OperandTraits <ResumeInst>::op_begin(this); } ResumeInst::const_op_iterator ResumeInst::op_begin() const { return OperandTraits<ResumeInst >::op_begin(const_cast<ResumeInst*>(this)); } ResumeInst ::op_iterator ResumeInst::op_end() { return OperandTraits< ResumeInst>::op_end(this); } ResumeInst::const_op_iterator ResumeInst::op_end() const { return OperandTraits<ResumeInst >::op_end(const_cast<ResumeInst*>(this)); } Value *ResumeInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<ResumeInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ResumeInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4174, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<ResumeInst>::op_begin(const_cast<ResumeInst *>(this))[i_nocapture].get()); } void ResumeInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<ResumeInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ResumeInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4174, __PRETTY_FUNCTION__)); OperandTraits<ResumeInst> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ResumeInst ::getNumOperands() const { return OperandTraits<ResumeInst >::operands(this); } template <int Idx_nocapture> Use &ResumeInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & ResumeInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
4175 | |
4176 | //===----------------------------------------------------------------------===// |
4177 | // CatchSwitchInst Class |
4178 | //===----------------------------------------------------------------------===// |
4179 | class CatchSwitchInst : public Instruction { |
4180 | using UnwindDestField = BoolBitfieldElementT<0>; |
4181 | |
4182 | /// The number of operands actually allocated. NumOperands is |
4183 | /// the number actually in use. |
4184 | unsigned ReservedSpace; |
4185 | |
4186 | // Operand[0] = Outer scope |
4187 | // Operand[1] = Unwind block destination |
4188 | // Operand[n] = BasicBlock to go to on match |
4189 | CatchSwitchInst(const CatchSwitchInst &CSI); |
4190 | |
4191 | /// Create a new switch instruction, specifying a |
4192 | /// default destination. The number of additional handlers can be specified |
4193 | /// here to make memory allocation more efficient. |
4194 | /// This constructor can also autoinsert before another instruction. |
4195 | CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, |
4196 | unsigned NumHandlers, const Twine &NameStr, |
4197 | Instruction *InsertBefore); |
4198 | |
4199 | /// Create a new switch instruction, specifying a |
4200 | /// default destination. The number of additional handlers can be specified |
4201 | /// here to make memory allocation more efficient. |
4202 | /// This constructor also autoinserts at the end of the specified BasicBlock. |
4203 | CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, |
4204 | unsigned NumHandlers, const Twine &NameStr, |
4205 | BasicBlock *InsertAtEnd); |
4206 | |
4207 | // allocate space for exactly zero operands |
4208 | void *operator new(size_t s) { return User::operator new(s); } |
4209 | |
4210 | void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved); |
4211 | void growOperands(unsigned Size); |
4212 | |
4213 | protected: |
4214 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4215 | friend class Instruction; |
4216 | |
4217 | CatchSwitchInst *cloneImpl() const; |
4218 | |
4219 | public: |
4220 | static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest, |
4221 | unsigned NumHandlers, |
4222 | const Twine &NameStr = "", |
4223 | Instruction *InsertBefore = nullptr) { |
4224 | return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr, |
4225 | InsertBefore); |
4226 | } |
4227 | |
4228 | static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest, |
4229 | unsigned NumHandlers, const Twine &NameStr, |
4230 | BasicBlock *InsertAtEnd) { |
4231 | return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr, |
4232 | InsertAtEnd); |
4233 | } |
4234 | |
4235 | /// Provide fast operand accessors |
4236 | 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; |
4237 | |
4238 | // Accessor Methods for CatchSwitch stmt |
4239 | Value *getParentPad() const { return getOperand(0); } |
4240 | void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); } |
4241 | |
4242 | // Accessor Methods for CatchSwitch stmt |
4243 | bool hasUnwindDest() const { return getSubclassData<UnwindDestField>(); } |
4244 | bool unwindsToCaller() const { return !hasUnwindDest(); } |
4245 | BasicBlock *getUnwindDest() const { |
4246 | if (hasUnwindDest()) |
4247 | return cast<BasicBlock>(getOperand(1)); |
4248 | return nullptr; |
4249 | } |
4250 | void setUnwindDest(BasicBlock *UnwindDest) { |
4251 | assert(UnwindDest)((UnwindDest) ? static_cast<void> (0) : __assert_fail ( "UnwindDest", "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4251, __PRETTY_FUNCTION__)); |
4252 | assert(hasUnwindDest())((hasUnwindDest()) ? static_cast<void> (0) : __assert_fail ("hasUnwindDest()", "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4252, __PRETTY_FUNCTION__)); |
4253 | setOperand(1, UnwindDest); |
4254 | } |
4255 | |
4256 | /// return the number of 'handlers' in this catchswitch |
4257 | /// instruction, except the default handler |
4258 | unsigned getNumHandlers() const { |
4259 | if (hasUnwindDest()) |
4260 | return getNumOperands() - 2; |
4261 | return getNumOperands() - 1; |
4262 | } |
4263 | |
4264 | private: |
4265 | static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); } |
4266 | static const BasicBlock *handler_helper(const Value *V) { |
4267 | return cast<BasicBlock>(V); |
4268 | } |
4269 | |
4270 | public: |
4271 | using DerefFnTy = BasicBlock *(*)(Value *); |
4272 | using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>; |
4273 | using handler_range = iterator_range<handler_iterator>; |
4274 | using ConstDerefFnTy = const BasicBlock *(*)(const Value *); |
4275 | using const_handler_iterator = |
4276 | mapped_iterator<const_op_iterator, ConstDerefFnTy>; |
4277 | using const_handler_range = iterator_range<const_handler_iterator>; |
4278 | |
4279 | /// Returns an iterator that points to the first handler in CatchSwitchInst. |
4280 | handler_iterator handler_begin() { |
4281 | op_iterator It = op_begin() + 1; |
4282 | if (hasUnwindDest()) |
4283 | ++It; |
4284 | return handler_iterator(It, DerefFnTy(handler_helper)); |
4285 | } |
4286 | |
4287 | /// Returns an iterator that points to the first handler in the |
4288 | /// CatchSwitchInst. |
4289 | const_handler_iterator handler_begin() const { |
4290 | const_op_iterator It = op_begin() + 1; |
4291 | if (hasUnwindDest()) |
4292 | ++It; |
4293 | return const_handler_iterator(It, ConstDerefFnTy(handler_helper)); |
4294 | } |
4295 | |
4296 | /// Returns a read-only iterator that points one past the last |
4297 | /// handler in the CatchSwitchInst. |
4298 | handler_iterator handler_end() { |
4299 | return handler_iterator(op_end(), DerefFnTy(handler_helper)); |
4300 | } |
4301 | |
4302 | /// Returns an iterator that points one past the last handler in the |
4303 | /// CatchSwitchInst. |
4304 | const_handler_iterator handler_end() const { |
4305 | return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper)); |
4306 | } |
4307 | |
4308 | /// iteration adapter for range-for loops. |
4309 | handler_range handlers() { |
4310 | return make_range(handler_begin(), handler_end()); |
4311 | } |
4312 | |
4313 | /// iteration adapter for range-for loops. |
4314 | const_handler_range handlers() const { |
4315 | return make_range(handler_begin(), handler_end()); |
4316 | } |
4317 | |
4318 | /// Add an entry to the switch instruction... |
4319 | /// Note: |
4320 | /// This action invalidates handler_end(). Old handler_end() iterator will |
4321 | /// point to the added handler. |
4322 | void addHandler(BasicBlock *Dest); |
4323 | |
4324 | void removeHandler(handler_iterator HI); |
4325 | |
4326 | unsigned getNumSuccessors() const { return getNumOperands() - 1; } |
4327 | BasicBlock *getSuccessor(unsigned Idx) const { |
4328 | assert(Idx < getNumSuccessors() &&((Idx < getNumSuccessors() && "Successor # out of range for catchswitch!" ) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4329, __PRETTY_FUNCTION__)) |
4329 | "Successor # out of range for catchswitch!")((Idx < getNumSuccessors() && "Successor # out of range for catchswitch!" ) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4329, __PRETTY_FUNCTION__)); |
4330 | return cast<BasicBlock>(getOperand(Idx + 1)); |
4331 | } |
4332 | void setSuccessor(unsigned Idx, BasicBlock *NewSucc) { |
4333 | assert(Idx < getNumSuccessors() &&((Idx < getNumSuccessors() && "Successor # out of range for catchswitch!" ) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4334, __PRETTY_FUNCTION__)) |
4334 | "Successor # out of range for catchswitch!")((Idx < getNumSuccessors() && "Successor # out of range for catchswitch!" ) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4334, __PRETTY_FUNCTION__)); |
4335 | setOperand(Idx + 1, NewSucc); |
4336 | } |
4337 | |
4338 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4339 | static bool classof(const Instruction *I) { |
4340 | return I->getOpcode() == Instruction::CatchSwitch; |
4341 | } |
4342 | static bool classof(const Value *V) { |
4343 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4344 | } |
4345 | }; |
4346 | |
4347 | template <> |
4348 | struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {}; |
4349 | |
4350 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)CatchSwitchInst::op_iterator CatchSwitchInst::op_begin() { return OperandTraits<CatchSwitchInst>::op_begin(this); } CatchSwitchInst ::const_op_iterator CatchSwitchInst::op_begin() const { return OperandTraits<CatchSwitchInst>::op_begin(const_cast< CatchSwitchInst*>(this)); } CatchSwitchInst::op_iterator CatchSwitchInst ::op_end() { return OperandTraits<CatchSwitchInst>::op_end (this); } CatchSwitchInst::const_op_iterator CatchSwitchInst:: op_end() const { return OperandTraits<CatchSwitchInst>:: op_end(const_cast<CatchSwitchInst*>(this)); } Value *CatchSwitchInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<CatchSwitchInst>::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<CatchSwitchInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4350, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<CatchSwitchInst>::op_begin(const_cast< CatchSwitchInst*>(this))[i_nocapture].get()); } void CatchSwitchInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( i_nocapture < OperandTraits<CatchSwitchInst>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<CatchSwitchInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4350, __PRETTY_FUNCTION__)); OperandTraits<CatchSwitchInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned CatchSwitchInst::getNumOperands() const { return OperandTraits <CatchSwitchInst>::operands(this); } template <int Idx_nocapture > Use &CatchSwitchInst::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &CatchSwitchInst::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
4351 | |
4352 | //===----------------------------------------------------------------------===// |
4353 | // CleanupPadInst Class |
4354 | //===----------------------------------------------------------------------===// |
4355 | class CleanupPadInst : public FuncletPadInst { |
4356 | private: |
4357 | explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args, |
4358 | unsigned Values, const Twine &NameStr, |
4359 | Instruction *InsertBefore) |
4360 | : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values, |
4361 | NameStr, InsertBefore) {} |
4362 | explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args, |
4363 | unsigned Values, const Twine &NameStr, |
4364 | BasicBlock *InsertAtEnd) |
4365 | : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values, |
4366 | NameStr, InsertAtEnd) {} |
4367 | |
4368 | public: |
4369 | static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None, |
4370 | const Twine &NameStr = "", |
4371 | Instruction *InsertBefore = nullptr) { |
4372 | unsigned Values = 1 + Args.size(); |
4373 | return new (Values) |
4374 | CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore); |
4375 | } |
4376 | |
4377 | static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args, |
4378 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
4379 | unsigned Values = 1 + Args.size(); |
4380 | return new (Values) |
4381 | CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd); |
4382 | } |
4383 | |
4384 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4385 | static bool classof(const Instruction *I) { |
4386 | return I->getOpcode() == Instruction::CleanupPad; |
4387 | } |
4388 | static bool classof(const Value *V) { |
4389 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4390 | } |
4391 | }; |
4392 | |
4393 | //===----------------------------------------------------------------------===// |
4394 | // CatchPadInst Class |
4395 | //===----------------------------------------------------------------------===// |
4396 | class CatchPadInst : public FuncletPadInst { |
4397 | private: |
4398 | explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args, |
4399 | unsigned Values, const Twine &NameStr, |
4400 | Instruction *InsertBefore) |
4401 | : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values, |
4402 | NameStr, InsertBefore) {} |
4403 | explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args, |
4404 | unsigned Values, const Twine &NameStr, |
4405 | BasicBlock *InsertAtEnd) |
4406 | : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values, |
4407 | NameStr, InsertAtEnd) {} |
4408 | |
4409 | public: |
4410 | static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args, |
4411 | const Twine &NameStr = "", |
4412 | Instruction *InsertBefore = nullptr) { |
4413 | unsigned Values = 1 + Args.size(); |
4414 | return new (Values) |
4415 | CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore); |
4416 | } |
4417 | |
4418 | static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args, |
4419 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
4420 | unsigned Values = 1 + Args.size(); |
4421 | return new (Values) |
4422 | CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd); |
4423 | } |
4424 | |
4425 | /// Convenience accessors |
4426 | CatchSwitchInst *getCatchSwitch() const { |
4427 | return cast<CatchSwitchInst>(Op<-1>()); |
4428 | } |
4429 | void setCatchSwitch(Value *CatchSwitch) { |
4430 | assert(CatchSwitch)((CatchSwitch) ? static_cast<void> (0) : __assert_fail ( "CatchSwitch", "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4430, __PRETTY_FUNCTION__)); |
4431 | Op<-1>() = CatchSwitch; |
4432 | } |
4433 | |
4434 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4435 | static bool classof(const Instruction *I) { |
4436 | return I->getOpcode() == Instruction::CatchPad; |
4437 | } |
4438 | static bool classof(const Value *V) { |
4439 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4440 | } |
4441 | }; |
4442 | |
4443 | //===----------------------------------------------------------------------===// |
4444 | // CatchReturnInst Class |
4445 | //===----------------------------------------------------------------------===// |
4446 | |
4447 | class CatchReturnInst : public Instruction { |
4448 | CatchReturnInst(const CatchReturnInst &RI); |
4449 | CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore); |
4450 | CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd); |
4451 | |
4452 | void init(Value *CatchPad, BasicBlock *BB); |
4453 | |
4454 | protected: |
4455 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4456 | friend class Instruction; |
4457 | |
4458 | CatchReturnInst *cloneImpl() const; |
4459 | |
4460 | public: |
4461 | static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB, |
4462 | Instruction *InsertBefore = nullptr) { |
4463 | assert(CatchPad)((CatchPad) ? static_cast<void> (0) : __assert_fail ("CatchPad" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4463, __PRETTY_FUNCTION__)); |
4464 | assert(BB)((BB) ? static_cast<void> (0) : __assert_fail ("BB", "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4464, __PRETTY_FUNCTION__)); |
4465 | return new (2) CatchReturnInst(CatchPad, BB, InsertBefore); |
4466 | } |
4467 | |
4468 | static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB, |
4469 | BasicBlock *InsertAtEnd) { |
4470 | assert(CatchPad)((CatchPad) ? static_cast<void> (0) : __assert_fail ("CatchPad" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4470, __PRETTY_FUNCTION__)); |
4471 | assert(BB)((BB) ? static_cast<void> (0) : __assert_fail ("BB", "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4471, __PRETTY_FUNCTION__)); |
4472 | return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd); |
4473 | } |
4474 | |
4475 | /// Provide fast operand accessors |
4476 | 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; |
4477 | |
4478 | /// Convenience accessors. |
4479 | CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); } |
4480 | void setCatchPad(CatchPadInst *CatchPad) { |
4481 | assert(CatchPad)((CatchPad) ? static_cast<void> (0) : __assert_fail ("CatchPad" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4481, __PRETTY_FUNCTION__)); |
4482 | Op<0>() = CatchPad; |
4483 | } |
4484 | |
4485 | BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); } |
4486 | void setSuccessor(BasicBlock *NewSucc) { |
4487 | assert(NewSucc)((NewSucc) ? static_cast<void> (0) : __assert_fail ("NewSucc" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4487, __PRETTY_FUNCTION__)); |
4488 | Op<1>() = NewSucc; |
4489 | } |
4490 | unsigned getNumSuccessors() const { return 1; } |
4491 | |
4492 | /// Get the parentPad of this catchret's catchpad's catchswitch. |
4493 | /// The successor block is implicitly a member of this funclet. |
4494 | Value *getCatchSwitchParentPad() const { |
4495 | return getCatchPad()->getCatchSwitch()->getParentPad(); |
4496 | } |
4497 | |
4498 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4499 | static bool classof(const Instruction *I) { |
4500 | return (I->getOpcode() == Instruction::CatchRet); |
4501 | } |
4502 | static bool classof(const Value *V) { |
4503 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4504 | } |
4505 | |
4506 | private: |
4507 | BasicBlock *getSuccessor(unsigned Idx) const { |
4508 | assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!")((Idx < getNumSuccessors() && "Successor # out of range for catchret!" ) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchret!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4508, __PRETTY_FUNCTION__)); |
4509 | return getSuccessor(); |
4510 | } |
4511 | |
4512 | void setSuccessor(unsigned Idx, BasicBlock *B) { |
4513 | assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!")((Idx < getNumSuccessors() && "Successor # out of range for catchret!" ) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchret!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4513, __PRETTY_FUNCTION__)); |
4514 | setSuccessor(B); |
4515 | } |
4516 | }; |
4517 | |
4518 | template <> |
4519 | struct OperandTraits<CatchReturnInst> |
4520 | : public FixedNumOperandTraits<CatchReturnInst, 2> {}; |
4521 | |
4522 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)CatchReturnInst::op_iterator CatchReturnInst::op_begin() { return OperandTraits<CatchReturnInst>::op_begin(this); } CatchReturnInst ::const_op_iterator CatchReturnInst::op_begin() const { return OperandTraits<CatchReturnInst>::op_begin(const_cast< CatchReturnInst*>(this)); } CatchReturnInst::op_iterator CatchReturnInst ::op_end() { return OperandTraits<CatchReturnInst>::op_end (this); } CatchReturnInst::const_op_iterator CatchReturnInst:: op_end() const { return OperandTraits<CatchReturnInst>:: op_end(const_cast<CatchReturnInst*>(this)); } Value *CatchReturnInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<CatchReturnInst>::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<CatchReturnInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4522, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<CatchReturnInst>::op_begin(const_cast< CatchReturnInst*>(this))[i_nocapture].get()); } void CatchReturnInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( i_nocapture < OperandTraits<CatchReturnInst>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<CatchReturnInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4522, __PRETTY_FUNCTION__)); OperandTraits<CatchReturnInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned CatchReturnInst::getNumOperands() const { return OperandTraits <CatchReturnInst>::operands(this); } template <int Idx_nocapture > Use &CatchReturnInst::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &CatchReturnInst::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
4523 | |
4524 | //===----------------------------------------------------------------------===// |
4525 | // CleanupReturnInst Class |
4526 | //===----------------------------------------------------------------------===// |
4527 | |
4528 | class CleanupReturnInst : public Instruction { |
4529 | using UnwindDestField = BoolBitfieldElementT<0>; |
4530 | |
4531 | private: |
4532 | CleanupReturnInst(const CleanupReturnInst &RI); |
4533 | CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values, |
4534 | Instruction *InsertBefore = nullptr); |
4535 | CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values, |
4536 | BasicBlock *InsertAtEnd); |
4537 | |
4538 | void init(Value *CleanupPad, BasicBlock *UnwindBB); |
4539 | |
4540 | protected: |
4541 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4542 | friend class Instruction; |
4543 | |
4544 | CleanupReturnInst *cloneImpl() const; |
4545 | |
4546 | public: |
4547 | static CleanupReturnInst *Create(Value *CleanupPad, |
4548 | BasicBlock *UnwindBB = nullptr, |
4549 | Instruction *InsertBefore = nullptr) { |
4550 | assert(CleanupPad)((CleanupPad) ? static_cast<void> (0) : __assert_fail ( "CleanupPad", "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4550, __PRETTY_FUNCTION__)); |
4551 | unsigned Values = 1; |
4552 | if (UnwindBB) |
4553 | ++Values; |
4554 | return new (Values) |
4555 | CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore); |
4556 | } |
4557 | |
4558 | static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB, |
4559 | BasicBlock *InsertAtEnd) { |
4560 | assert(CleanupPad)((CleanupPad) ? static_cast<void> (0) : __assert_fail ( "CleanupPad", "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4560, __PRETTY_FUNCTION__)); |
4561 | unsigned Values = 1; |
4562 | if (UnwindBB) |
4563 | ++Values; |
4564 | return new (Values) |
4565 | CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd); |
4566 | } |
4567 | |
4568 | /// Provide fast operand accessors |
4569 | 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; |
4570 | |
4571 | bool hasUnwindDest() const { return getSubclassData<UnwindDestField>(); } |
4572 | bool unwindsToCaller() const { return !hasUnwindDest(); } |
4573 | |
4574 | /// Convenience accessor. |
4575 | CleanupPadInst *getCleanupPad() const { |
4576 | return cast<CleanupPadInst>(Op<0>()); |
4577 | } |
4578 | void setCleanupPad(CleanupPadInst *CleanupPad) { |
4579 | assert(CleanupPad)((CleanupPad) ? static_cast<void> (0) : __assert_fail ( "CleanupPad", "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4579, __PRETTY_FUNCTION__)); |
4580 | Op<0>() = CleanupPad; |
4581 | } |
4582 | |
4583 | unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; } |
4584 | |
4585 | BasicBlock *getUnwindDest() const { |
4586 | return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr; |
4587 | } |
4588 | void setUnwindDest(BasicBlock *NewDest) { |
4589 | assert(NewDest)((NewDest) ? static_cast<void> (0) : __assert_fail ("NewDest" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4589, __PRETTY_FUNCTION__)); |
4590 | assert(hasUnwindDest())((hasUnwindDest()) ? static_cast<void> (0) : __assert_fail ("hasUnwindDest()", "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4590, __PRETTY_FUNCTION__)); |
4591 | Op<1>() = NewDest; |
4592 | } |
4593 | |
4594 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4595 | static bool classof(const Instruction *I) { |
4596 | return (I->getOpcode() == Instruction::CleanupRet); |
4597 | } |
4598 | static bool classof(const Value *V) { |
4599 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4600 | } |
4601 | |
4602 | private: |
4603 | BasicBlock *getSuccessor(unsigned Idx) const { |
4604 | assert(Idx == 0)((Idx == 0) ? static_cast<void> (0) : __assert_fail ("Idx == 0" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4604, __PRETTY_FUNCTION__)); |
4605 | return getUnwindDest(); |
4606 | } |
4607 | |
4608 | void setSuccessor(unsigned Idx, BasicBlock *B) { |
4609 | assert(Idx == 0)((Idx == 0) ? static_cast<void> (0) : __assert_fail ("Idx == 0" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4609, __PRETTY_FUNCTION__)); |
4610 | setUnwindDest(B); |
4611 | } |
4612 | |
4613 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
4614 | // method so that subclasses cannot accidentally use it. |
4615 | template <typename Bitfield> |
4616 | void setSubclassData(typename Bitfield::Type Value) { |
4617 | Instruction::setSubclassData<Bitfield>(Value); |
4618 | } |
4619 | }; |
4620 | |
4621 | template <> |
4622 | struct OperandTraits<CleanupReturnInst> |
4623 | : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {}; |
4624 | |
4625 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)CleanupReturnInst::op_iterator CleanupReturnInst::op_begin() { return OperandTraits<CleanupReturnInst>::op_begin(this ); } CleanupReturnInst::const_op_iterator CleanupReturnInst:: op_begin() const { return OperandTraits<CleanupReturnInst> ::op_begin(const_cast<CleanupReturnInst*>(this)); } CleanupReturnInst ::op_iterator CleanupReturnInst::op_end() { return OperandTraits <CleanupReturnInst>::op_end(this); } CleanupReturnInst:: const_op_iterator CleanupReturnInst::op_end() const { return OperandTraits <CleanupReturnInst>::op_end(const_cast<CleanupReturnInst *>(this)); } Value *CleanupReturnInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<CleanupReturnInst >::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<CleanupReturnInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4625, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<CleanupReturnInst>::op_begin(const_cast <CleanupReturnInst*>(this))[i_nocapture].get()); } void CleanupReturnInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((i_nocapture < OperandTraits<CleanupReturnInst> ::operands(this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<CleanupReturnInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4625, __PRETTY_FUNCTION__)); OperandTraits<CleanupReturnInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned CleanupReturnInst::getNumOperands() const { return OperandTraits <CleanupReturnInst>::operands(this); } template <int Idx_nocapture> Use &CleanupReturnInst::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &CleanupReturnInst::Op() const { return this ->OpFrom<Idx_nocapture>(this); } |
4626 | |
4627 | //===----------------------------------------------------------------------===// |
4628 | // UnreachableInst Class |
4629 | //===----------------------------------------------------------------------===// |
4630 | |
4631 | //===--------------------------------------------------------------------------- |
4632 | /// This function has undefined behavior. In particular, the |
4633 | /// presence of this instruction indicates some higher level knowledge that the |
4634 | /// end of the block cannot be reached. |
4635 | /// |
4636 | class UnreachableInst : public Instruction { |
4637 | protected: |
4638 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4639 | friend class Instruction; |
4640 | |
4641 | UnreachableInst *cloneImpl() const; |
4642 | |
4643 | public: |
4644 | explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr); |
4645 | explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd); |
4646 | |
4647 | // allocate space for exactly zero operands |
4648 | void *operator new(size_t s) { |
4649 | return User::operator new(s, 0); |
4650 | } |
4651 | |
4652 | unsigned getNumSuccessors() const { return 0; } |
4653 | |
4654 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4655 | static bool classof(const Instruction *I) { |
4656 | return I->getOpcode() == Instruction::Unreachable; |
4657 | } |
4658 | static bool classof(const Value *V) { |
4659 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4660 | } |
4661 | |
4662 | private: |
4663 | BasicBlock *getSuccessor(unsigned idx) const { |
4664 | llvm_unreachable("UnreachableInst has no successors!")::llvm::llvm_unreachable_internal("UnreachableInst has no successors!" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4664); |
4665 | } |
4666 | |
4667 | void setSuccessor(unsigned idx, BasicBlock *B) { |
4668 | llvm_unreachable("UnreachableInst has no successors!")::llvm::llvm_unreachable_internal("UnreachableInst has no successors!" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 4668); |
4669 | } |
4670 | }; |
4671 | |
4672 | //===----------------------------------------------------------------------===// |
4673 | // TruncInst Class |
4674 | //===----------------------------------------------------------------------===// |
4675 | |
4676 | /// This class represents a truncation of integer types. |
4677 | class TruncInst : public CastInst { |
4678 | protected: |
4679 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4680 | friend class Instruction; |
4681 | |
4682 | /// Clone an identical TruncInst |
4683 | TruncInst *cloneImpl() const; |
4684 | |
4685 | public: |
4686 | /// Constructor with insert-before-instruction semantics |
4687 | TruncInst( |
4688 | Value *S, ///< The value to be truncated |
4689 | Type *Ty, ///< The (smaller) type to truncate to |
4690 | const Twine &NameStr = "", ///< A name for the new instruction |
4691 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4692 | ); |
4693 | |
4694 | /// Constructor with insert-at-end-of-block semantics |
4695 | TruncInst( |
4696 | Value *S, ///< The value to be truncated |
4697 | Type *Ty, ///< The (smaller) type to truncate to |
4698 | const Twine &NameStr, ///< A name for the new instruction |
4699 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4700 | ); |
4701 | |
4702 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4703 | static bool classof(const Instruction *I) { |
4704 | return I->getOpcode() == Trunc; |
4705 | } |
4706 | static bool classof(const Value *V) { |
4707 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4708 | } |
4709 | }; |
4710 | |
4711 | //===----------------------------------------------------------------------===// |
4712 | // ZExtInst Class |
4713 | //===----------------------------------------------------------------------===// |
4714 | |
4715 | /// This class represents zero extension of integer types. |
4716 | class ZExtInst : public CastInst { |
4717 | protected: |
4718 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4719 | friend class Instruction; |
4720 | |
4721 | /// Clone an identical ZExtInst |
4722 | ZExtInst *cloneImpl() const; |
4723 | |
4724 | public: |
4725 | /// Constructor with insert-before-instruction semantics |
4726 | ZExtInst( |
4727 | Value *S, ///< The value to be zero extended |
4728 | Type *Ty, ///< The type to zero extend to |
4729 | const Twine &NameStr = "", ///< A name for the new instruction |
4730 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4731 | ); |
4732 | |
4733 | /// Constructor with insert-at-end semantics. |
4734 | ZExtInst( |
4735 | Value *S, ///< The value to be zero extended |
4736 | Type *Ty, ///< The type to zero extend to |
4737 | const Twine &NameStr, ///< A name for the new instruction |
4738 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4739 | ); |
4740 | |
4741 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4742 | static bool classof(const Instruction *I) { |
4743 | return I->getOpcode() == ZExt; |
4744 | } |
4745 | static bool classof(const Value *V) { |
4746 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4747 | } |
4748 | }; |
4749 | |
4750 | //===----------------------------------------------------------------------===// |
4751 | // SExtInst Class |
4752 | //===----------------------------------------------------------------------===// |
4753 | |
4754 | /// This class represents a sign extension of integer types. |
4755 | class SExtInst : public CastInst { |
4756 | protected: |
4757 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4758 | friend class Instruction; |
4759 | |
4760 | /// Clone an identical SExtInst |
4761 | SExtInst *cloneImpl() const; |
4762 | |
4763 | public: |
4764 | /// Constructor with insert-before-instruction semantics |
4765 | SExtInst( |
4766 | Value *S, ///< The value to be sign extended |
4767 | Type *Ty, ///< The type to sign extend to |
4768 | const Twine &NameStr = "", ///< A name for the new instruction |
4769 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4770 | ); |
4771 | |
4772 | /// Constructor with insert-at-end-of-block semantics |
4773 | SExtInst( |
4774 | Value *S, ///< The value to be sign extended |
4775 | Type *Ty, ///< The type to sign extend to |
4776 | const Twine &NameStr, ///< A name for the new instruction |
4777 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4778 | ); |
4779 | |
4780 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4781 | static bool classof(const Instruction *I) { |
4782 | return I->getOpcode() == SExt; |
4783 | } |
4784 | static bool classof(const Value *V) { |
4785 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4786 | } |
4787 | }; |
4788 | |
4789 | //===----------------------------------------------------------------------===// |
4790 | // FPTruncInst Class |
4791 | //===----------------------------------------------------------------------===// |
4792 | |
4793 | /// This class represents a truncation of floating point types. |
4794 | class FPTruncInst : public CastInst { |
4795 | protected: |
4796 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4797 | friend class Instruction; |
4798 | |
4799 | /// Clone an identical FPTruncInst |
4800 | FPTruncInst *cloneImpl() const; |
4801 | |
4802 | public: |
4803 | /// Constructor with insert-before-instruction semantics |
4804 | FPTruncInst( |
4805 | Value *S, ///< The value to be truncated |
4806 | Type *Ty, ///< The type to truncate to |
4807 | const Twine &NameStr = "", ///< A name for the new instruction |
4808 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4809 | ); |
4810 | |
4811 | /// Constructor with insert-before-instruction semantics |
4812 | FPTruncInst( |
4813 | Value *S, ///< The value to be truncated |
4814 | Type *Ty, ///< The type to truncate to |
4815 | const Twine &NameStr, ///< A name for the new instruction |
4816 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4817 | ); |
4818 | |
4819 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4820 | static bool classof(const Instruction *I) { |
4821 | return I->getOpcode() == FPTrunc; |
4822 | } |
4823 | static bool classof(const Value *V) { |
4824 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4825 | } |
4826 | }; |
4827 | |
4828 | //===----------------------------------------------------------------------===// |
4829 | // FPExtInst Class |
4830 | //===----------------------------------------------------------------------===// |
4831 | |
4832 | /// This class represents an extension of floating point types. |
4833 | class FPExtInst : public CastInst { |
4834 | protected: |
4835 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4836 | friend class Instruction; |
4837 | |
4838 | /// Clone an identical FPExtInst |
4839 | FPExtInst *cloneImpl() const; |
4840 | |
4841 | public: |
4842 | /// Constructor with insert-before-instruction semantics |
4843 | FPExtInst( |
4844 | Value *S, ///< The value to be extended |
4845 | Type *Ty, ///< The type to extend to |
4846 | const Twine &NameStr = "", ///< A name for the new instruction |
4847 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4848 | ); |
4849 | |
4850 | /// Constructor with insert-at-end-of-block semantics |
4851 | FPExtInst( |
4852 | Value *S, ///< The value to be extended |
4853 | Type *Ty, ///< The type to extend to |
4854 | const Twine &NameStr, ///< A name for the new instruction |
4855 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4856 | ); |
4857 | |
4858 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4859 | static bool classof(const Instruction *I) { |
4860 | return I->getOpcode() == FPExt; |
4861 | } |
4862 | static bool classof(const Value *V) { |
4863 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4864 | } |
4865 | }; |
4866 | |
4867 | //===----------------------------------------------------------------------===// |
4868 | // UIToFPInst Class |
4869 | //===----------------------------------------------------------------------===// |
4870 | |
4871 | /// This class represents a cast unsigned integer to floating point. |
4872 | class UIToFPInst : public CastInst { |
4873 | protected: |
4874 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4875 | friend class Instruction; |
4876 | |
4877 | /// Clone an identical UIToFPInst |
4878 | UIToFPInst *cloneImpl() const; |
4879 | |
4880 | public: |
4881 | /// Constructor with insert-before-instruction semantics |
4882 | UIToFPInst( |
4883 | Value *S, ///< The value to be converted |
4884 | Type *Ty, ///< The type to convert to |
4885 | const Twine &NameStr = "", ///< A name for the new instruction |
4886 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4887 | ); |
4888 | |
4889 | /// Constructor with insert-at-end-of-block semantics |
4890 | UIToFPInst( |
4891 | Value *S, ///< The value to be converted |
4892 | Type *Ty, ///< The type to convert to |
4893 | const Twine &NameStr, ///< A name for the new instruction |
4894 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4895 | ); |
4896 | |
4897 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4898 | static bool classof(const Instruction *I) { |
4899 | return I->getOpcode() == UIToFP; |
4900 | } |
4901 | static bool classof(const Value *V) { |
4902 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4903 | } |
4904 | }; |
4905 | |
4906 | //===----------------------------------------------------------------------===// |
4907 | // SIToFPInst Class |
4908 | //===----------------------------------------------------------------------===// |
4909 | |
4910 | /// This class represents a cast from signed integer to floating point. |
4911 | class SIToFPInst : public CastInst { |
4912 | protected: |
4913 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4914 | friend class Instruction; |
4915 | |
4916 | /// Clone an identical SIToFPInst |
4917 | SIToFPInst *cloneImpl() const; |
4918 | |
4919 | public: |
4920 | /// Constructor with insert-before-instruction semantics |
4921 | SIToFPInst( |
4922 | Value *S, ///< The value to be converted |
4923 | Type *Ty, ///< The type to convert to |
4924 | const Twine &NameStr = "", ///< A name for the new instruction |
4925 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4926 | ); |
4927 | |
4928 | /// Constructor with insert-at-end-of-block semantics |
4929 | SIToFPInst( |
4930 | Value *S, ///< The value to be converted |
4931 | Type *Ty, ///< The type to convert to |
4932 | const Twine &NameStr, ///< A name for the new instruction |
4933 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4934 | ); |
4935 | |
4936 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4937 | static bool classof(const Instruction *I) { |
4938 | return I->getOpcode() == SIToFP; |
4939 | } |
4940 | static bool classof(const Value *V) { |
4941 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4942 | } |
4943 | }; |
4944 | |
4945 | //===----------------------------------------------------------------------===// |
4946 | // FPToUIInst Class |
4947 | //===----------------------------------------------------------------------===// |
4948 | |
4949 | /// This class represents a cast from floating point to unsigned integer |
4950 | class FPToUIInst : public CastInst { |
4951 | protected: |
4952 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4953 | friend class Instruction; |
4954 | |
4955 | /// Clone an identical FPToUIInst |
4956 | FPToUIInst *cloneImpl() const; |
4957 | |
4958 | public: |
4959 | /// Constructor with insert-before-instruction semantics |
4960 | FPToUIInst( |
4961 | Value *S, ///< The value to be converted |
4962 | Type *Ty, ///< The type to convert to |
4963 | const Twine &NameStr = "", ///< A name for the new instruction |
4964 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4965 | ); |
4966 | |
4967 | /// Constructor with insert-at-end-of-block semantics |
4968 | FPToUIInst( |
4969 | Value *S, ///< The value to be converted |
4970 | Type *Ty, ///< The type to convert to |
4971 | const Twine &NameStr, ///< A name for the new instruction |
4972 | BasicBlock *InsertAtEnd ///< Where to insert the new instruction |
4973 | ); |
4974 | |
4975 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4976 | static bool classof(const Instruction *I) { |
4977 | return I->getOpcode() == FPToUI; |
4978 | } |
4979 | static bool classof(const Value *V) { |
4980 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4981 | } |
4982 | }; |
4983 | |
4984 | //===----------------------------------------------------------------------===// |
4985 | // FPToSIInst Class |
4986 | //===----------------------------------------------------------------------===// |
4987 | |
4988 | /// This class represents a cast from floating point to signed integer. |
4989 | class FPToSIInst : public CastInst { |
4990 | protected: |
4991 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4992 | friend class Instruction; |
4993 | |
4994 | /// Clone an identical FPToSIInst |
4995 | FPToSIInst *cloneImpl() const; |
4996 | |
4997 | public: |
4998 | /// Constructor with insert-before-instruction semantics |
4999 | FPToSIInst( |
5000 | Value *S, ///< The value to be converted |
5001 | Type *Ty, ///< The type to convert to |
5002 | const Twine &NameStr = "", ///< A name for the new instruction |
5003 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5004 | ); |
5005 | |
5006 | /// Constructor with insert-at-end-of-block semantics |
5007 | FPToSIInst( |
5008 | Value *S, ///< The value to be converted |
5009 | Type *Ty, ///< The type to convert to |
5010 | const Twine &NameStr, ///< A name for the new instruction |
5011 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5012 | ); |
5013 | |
5014 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
5015 | static bool classof(const Instruction *I) { |
5016 | return I->getOpcode() == FPToSI; |
5017 | } |
5018 | static bool classof(const Value *V) { |
5019 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5020 | } |
5021 | }; |
5022 | |
5023 | //===----------------------------------------------------------------------===// |
5024 | // IntToPtrInst Class |
5025 | //===----------------------------------------------------------------------===// |
5026 | |
5027 | /// This class represents a cast from an integer to a pointer. |
5028 | class IntToPtrInst : public CastInst { |
5029 | public: |
5030 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5031 | friend class Instruction; |
5032 | |
5033 | /// Constructor with insert-before-instruction semantics |
5034 | IntToPtrInst( |
5035 | Value *S, ///< The value to be converted |
5036 | Type *Ty, ///< The type to convert to |
5037 | const Twine &NameStr = "", ///< A name for the new instruction |
5038 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5039 | ); |
5040 | |
5041 | /// Constructor with insert-at-end-of-block semantics |
5042 | IntToPtrInst( |
5043 | Value *S, ///< The value to be converted |
5044 | Type *Ty, ///< The type to convert to |
5045 | const Twine &NameStr, ///< A name for the new instruction |
5046 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5047 | ); |
5048 | |
5049 | /// Clone an identical IntToPtrInst. |
5050 | IntToPtrInst *cloneImpl() const; |
5051 | |
5052 | /// Returns the address space of this instruction's pointer type. |
5053 | unsigned getAddressSpace() const { |
5054 | return getType()->getPointerAddressSpace(); |
5055 | } |
5056 | |
5057 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5058 | static bool classof(const Instruction *I) { |
5059 | return I->getOpcode() == IntToPtr; |
5060 | } |
5061 | static bool classof(const Value *V) { |
5062 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5063 | } |
5064 | }; |
5065 | |
5066 | //===----------------------------------------------------------------------===// |
5067 | // PtrToIntInst Class |
5068 | //===----------------------------------------------------------------------===// |
5069 | |
5070 | /// This class represents a cast from a pointer to an integer. |
5071 | class PtrToIntInst : public CastInst { |
5072 | protected: |
5073 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5074 | friend class Instruction; |
5075 | |
5076 | /// Clone an identical PtrToIntInst. |
5077 | PtrToIntInst *cloneImpl() const; |
5078 | |
5079 | public: |
5080 | /// Constructor with insert-before-instruction semantics |
5081 | PtrToIntInst( |
5082 | Value *S, ///< The value to be converted |
5083 | Type *Ty, ///< The type to convert to |
5084 | const Twine &NameStr = "", ///< A name for the new instruction |
5085 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5086 | ); |
5087 | |
5088 | /// Constructor with insert-at-end-of-block semantics |
5089 | PtrToIntInst( |
5090 | Value *S, ///< The value to be converted |
5091 | Type *Ty, ///< The type to convert to |
5092 | const Twine &NameStr, ///< A name for the new instruction |
5093 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5094 | ); |
5095 | |
5096 | /// Gets the pointer operand. |
5097 | Value *getPointerOperand() { return getOperand(0); } |
5098 | /// Gets the pointer operand. |
5099 | const Value *getPointerOperand() const { return getOperand(0); } |
5100 | /// Gets the operand index of the pointer operand. |
5101 | static unsigned getPointerOperandIndex() { return 0U; } |
5102 | |
5103 | /// Returns the address space of the pointer operand. |
5104 | unsigned getPointerAddressSpace() const { |
5105 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
5106 | } |
5107 | |
5108 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5109 | static bool classof(const Instruction *I) { |
5110 | return I->getOpcode() == PtrToInt; |
5111 | } |
5112 | static bool classof(const Value *V) { |
5113 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5114 | } |
5115 | }; |
5116 | |
5117 | //===----------------------------------------------------------------------===// |
5118 | // BitCastInst Class |
5119 | //===----------------------------------------------------------------------===// |
5120 | |
5121 | /// This class represents a no-op cast from one type to another. |
5122 | class BitCastInst : public CastInst { |
5123 | protected: |
5124 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5125 | friend class Instruction; |
5126 | |
5127 | /// Clone an identical BitCastInst. |
5128 | BitCastInst *cloneImpl() const; |
5129 | |
5130 | public: |
5131 | /// Constructor with insert-before-instruction semantics |
5132 | BitCastInst( |
5133 | Value *S, ///< The value to be casted |
5134 | Type *Ty, ///< The type to casted to |
5135 | const Twine &NameStr = "", ///< A name for the new instruction |
5136 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5137 | ); |
5138 | |
5139 | /// Constructor with insert-at-end-of-block semantics |
5140 | BitCastInst( |
5141 | Value *S, ///< The value to be casted |
5142 | Type *Ty, ///< The type to casted to |
5143 | const Twine &NameStr, ///< A name for the new instruction |
5144 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5145 | ); |
5146 | |
5147 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5148 | static bool classof(const Instruction *I) { |
5149 | return I->getOpcode() == BitCast; |
5150 | } |
5151 | static bool classof(const Value *V) { |
5152 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5153 | } |
5154 | }; |
5155 | |
5156 | //===----------------------------------------------------------------------===// |
5157 | // AddrSpaceCastInst Class |
5158 | //===----------------------------------------------------------------------===// |
5159 | |
5160 | /// This class represents a conversion between pointers from one address space |
5161 | /// to another. |
5162 | class AddrSpaceCastInst : public CastInst { |
5163 | protected: |
5164 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5165 | friend class Instruction; |
5166 | |
5167 | /// Clone an identical AddrSpaceCastInst. |
5168 | AddrSpaceCastInst *cloneImpl() const; |
5169 | |
5170 | public: |
5171 | /// Constructor with insert-before-instruction semantics |
5172 | AddrSpaceCastInst( |
5173 | Value *S, ///< The value to be casted |
5174 | Type *Ty, ///< The type to casted to |
5175 | const Twine &NameStr = "", ///< A name for the new instruction |
5176 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5177 | ); |
5178 | |
5179 | /// Constructor with insert-at-end-of-block semantics |
5180 | AddrSpaceCastInst( |
5181 | Value *S, ///< The value to be casted |
5182 | Type *Ty, ///< The type to casted to |
5183 | const Twine &NameStr, ///< A name for the new instruction |
5184 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5185 | ); |
5186 | |
5187 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5188 | static bool classof(const Instruction *I) { |
5189 | return I->getOpcode() == AddrSpaceCast; |
5190 | } |
5191 | static bool classof(const Value *V) { |
5192 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5193 | } |
5194 | |
5195 | /// Gets the pointer operand. |
5196 | Value *getPointerOperand() { |
5197 | return getOperand(0); |
5198 | } |
5199 | |
5200 | /// Gets the pointer operand. |
5201 | const Value *getPointerOperand() const { |
5202 | return getOperand(0); |
5203 | } |
5204 | |
5205 | /// Gets the operand index of the pointer operand. |
5206 | static unsigned getPointerOperandIndex() { |
5207 | return 0U; |
5208 | } |
5209 | |
5210 | /// Returns the address space of the pointer operand. |
5211 | unsigned getSrcAddressSpace() const { |
5212 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
5213 | } |
5214 | |
5215 | /// Returns the address space of the result. |
5216 | unsigned getDestAddressSpace() const { |
5217 | return getType()->getPointerAddressSpace(); |
5218 | } |
5219 | }; |
5220 | |
5221 | /// A helper function that returns the pointer operand of a load or store |
5222 | /// instruction. Returns nullptr if not load or store. |
5223 | inline const Value *getLoadStorePointerOperand(const Value *V) { |
5224 | if (auto *Load = dyn_cast<LoadInst>(V)) |
5225 | return Load->getPointerOperand(); |
5226 | if (auto *Store = dyn_cast<StoreInst>(V)) |
5227 | return Store->getPointerOperand(); |
5228 | return nullptr; |
5229 | } |
5230 | inline Value *getLoadStorePointerOperand(Value *V) { |
5231 | return const_cast<Value *>( |
5232 | getLoadStorePointerOperand(static_cast<const Value *>(V))); |
5233 | } |
5234 | |
5235 | /// A helper function that returns the pointer operand of a load, store |
5236 | /// or GEP instruction. Returns nullptr if not load, store, or GEP. |
5237 | inline const Value *getPointerOperand(const Value *V) { |
5238 | if (auto *Ptr = getLoadStorePointerOperand(V)) |
5239 | return Ptr; |
5240 | if (auto *Gep = dyn_cast<GetElementPtrInst>(V)) |
5241 | return Gep->getPointerOperand(); |
5242 | return nullptr; |
5243 | } |
5244 | inline Value *getPointerOperand(Value *V) { |
5245 | return const_cast<Value *>(getPointerOperand(static_cast<const Value *>(V))); |
5246 | } |
5247 | |
5248 | /// A helper function that returns the alignment of load or store instruction. |
5249 | inline Align getLoadStoreAlignment(Value *I) { |
5250 | assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(((isa<LoadInst>(I) || isa<StoreInst>(I)) && "Expected Load or Store instruction") ? static_cast<void> (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 5251, __PRETTY_FUNCTION__)) |
5251 | "Expected Load or Store instruction")(((isa<LoadInst>(I) || isa<StoreInst>(I)) && "Expected Load or Store instruction") ? static_cast<void> (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 5251, __PRETTY_FUNCTION__)); |
5252 | if (auto *LI = dyn_cast<LoadInst>(I)) |
5253 | return LI->getAlign(); |
5254 | return cast<StoreInst>(I)->getAlign(); |
5255 | } |
5256 | |
5257 | /// A helper function that returns the address space of the pointer operand of |
5258 | /// load or store instruction. |
5259 | inline unsigned getLoadStoreAddressSpace(Value *I) { |
5260 | assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(((isa<LoadInst>(I) || isa<StoreInst>(I)) && "Expected Load or Store instruction") ? static_cast<void> (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 5261, __PRETTY_FUNCTION__)) |
5261 | "Expected Load or Store instruction")(((isa<LoadInst>(I) || isa<StoreInst>(I)) && "Expected Load or Store instruction") ? static_cast<void> (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "/build/llvm-toolchain-snapshot-12~++20200828100629+cfde93e5d6b/llvm/include/llvm/IR/Instructions.h" , 5261, __PRETTY_FUNCTION__)); |
5262 | if (auto *LI = dyn_cast<LoadInst>(I)) |
5263 | return LI->getPointerAddressSpace(); |
5264 | return cast<StoreInst>(I)->getPointerAddressSpace(); |
5265 | } |
5266 | |
5267 | //===----------------------------------------------------------------------===// |
5268 | // FreezeInst Class |
5269 | //===----------------------------------------------------------------------===// |
5270 | |
5271 | /// This class represents a freeze function that returns random concrete |
5272 | /// value if an operand is either a poison value or an undef value |
5273 | class FreezeInst : public UnaryInstruction { |
5274 | protected: |
5275 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5276 | friend class Instruction; |
5277 | |
5278 | /// Clone an identical FreezeInst |
5279 | FreezeInst *cloneImpl() const; |
5280 | |
5281 | public: |
5282 | explicit FreezeInst(Value *S, |
5283 | const Twine &NameStr = "", |
5284 | Instruction *InsertBefore = nullptr); |
5285 | FreezeInst(Value *S, const Twine &NameStr, BasicBlock *InsertAtEnd); |
5286 | |
5287 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5288 | static inline bool classof(const Instruction *I) { |
5289 | return I->getOpcode() == Freeze; |
5290 | } |
5291 | static inline bool classof(const Value *V) { |
5292 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5293 | } |
5294 | }; |
5295 | |
5296 | } // end namespace llvm |
5297 | |
5298 | #endif // LLVM_IR_INSTRUCTIONS_H |