LLVM 24.0.0git
LICM.cpp
Go to the documentation of this file.
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// Hoisting operations out of loops is a canonicalization transform. It
16// enables and simplifies subsequent optimizations in the middle-end.
17// Rematerialization of hoisted instructions to reduce register pressure is the
18// responsibility of the back-end, which has more accurate information about
19// register pressure and also handles other optimizations than LICM that
20// increase live-ranges.
21//
22// This pass uses alias analysis for two purposes:
23//
24// 1. Moving loop invariant loads and calls out of loops. If we can determine
25// that a load or call inside of a loop never aliases anything stored to,
26// we can hoist it or sink it like any other instruction.
27// 2. Scalar Promotion of Memory - If there is a store instruction inside of
28// the loop, we try to move the store to happen AFTER the loop instead of
29// inside of the loop. This can only happen if a few conditions are true:
30// A. The pointer stored through is loop invariant
31// B. There are no stores or loads in the loop which _may_ alias the
32// pointer. There are no calls in the loop which mod/ref the pointer.
33// If these conditions are true, we can promote the loads and stores in the
34// loop of the pointer to use a temporary alloca'd variable. We then use
35// the SSAUpdater to construct the appropriate SSA form for the value.
36//
37//===----------------------------------------------------------------------===//
38
40#include "ScalarOptions.h"
41#include "llvm/ADT/DenseMap.h"
43#include "llvm/ADT/Statistic.h"
51#include "llvm/Analysis/Loads.h"
65#include "llvm/IR/CFG.h"
66#include "llvm/IR/Constants.h"
67#include "llvm/IR/DataLayout.h"
70#include "llvm/IR/Dominators.h"
71#include "llvm/IR/IRBuilder.h"
74#include "llvm/IR/LLVMContext.h"
75#include "llvm/IR/Metadata.h"
76#include "llvm/IR/Module.h"
80#include "llvm/Support/Debug.h"
88#include <algorithm>
89#include <utility>
90using namespace llvm;
91
92namespace llvm {
93class LPMUpdater;
94} // namespace llvm
95
96#define DEBUG_TYPE "licm"
97
98STATISTIC(NumSunk, "Number of instructions sunk out of loop");
99STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
100STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
101STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
102STATISTIC(NumPromotionCandidates, "Number of promotion candidates");
103STATISTIC(NumLoadPromoted, "Number of load-only promotions");
104STATISTIC(NumLoadStorePromoted, "Number of load and store promotions");
105STATISTIC(NumMinMaxHoisted,
106 "Number of min/max expressions hoisted out of the loop");
107STATISTIC(NumGEPsHoisted,
108 "Number of geps reassociated and hoisted out of the loop");
109STATISTIC(NumAddSubHoisted, "Number of add/subtract expressions reassociated "
110 "and hoisted out of the loop");
111STATISTIC(NumFPAssociationsHoisted, "Number of invariant FP expressions "
112 "reassociated and hoisted out of the loop");
113STATISTIC(NumIntAssociationsHoisted,
114 "Number of invariant int expressions "
115 "reassociated and hoisted out of the loop");
116STATISTIC(NumBOAssociationsHoisted, "Number of invariant BinaryOp expressions "
117 "reassociated and hoisted out of the loop");
118
119unsigned
122 .licm_mssa_optimization_cap;
123}
124
126 const cl::LibraryOptionsContext *LibraryOptions) {
128 .licm_mssa_max_acc_promotion;
129}
130
131static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
132static bool isNotUsedOrFoldableInLoop(const Instruction &I, const Loop *CurLoop,
133 const LoopSafetyInfo *SafetyInfo,
135 bool &FoldableInLoop, bool LoopNestMode);
136static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
137 BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,
140static bool sink(Instruction &I, const LICMDependencies &Deps,
141 const Loop *CurLoop);
143 Instruction &Inst, const DominatorTree *DT, const TargetLibraryInfo *TLI,
144 const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo,
145 OptimizationRemarkEmitter *ORE, const Instruction *CtxI,
146 AssumptionCache *AC, bool AllowSpeculation);
148 AAResults *AA, Loop *CurLoop,
149 SinkAndHoistLICMFlags &Flags);
151 MemoryUse *MU, Loop *CurLoop,
152 Instruction &I,
154 bool InvariantGroup);
155static bool pointerInvalidatedByBlock(BasicBlock &BB, MemorySSA &MSSA,
156 MemoryUse &MU);
157/// Aggregates various functions for hoisting computations out of loop.
158static bool hoistArithmetics(const ScalarOptions &Opts, Instruction &I, Loop &L,
159 const LICMDependencies &Deps);
160static bool hoistInsertPastInsert(InsertElementInst *Ins, Loop *CurLoop,
161 DominatorTree *DT, BasicBlock *HoistDest,
162 ICFLoopSafetyInfo *SafetyInfo,
166 Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,
167 const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU);
168
169static void eraseInstruction(Instruction &I, const LICMDependencies &Deps);
170
172 ICFLoopSafetyInfo &SafetyInfo,
174
175static void foreachMemoryAccess(MemorySSA *MSSA, Loop *L,
176 function_ref<void(Instruction *)> Fn);
178 std::pair<SmallSetVector<Value *, 8>, bool>;
181 ICFLoopSafetyInfo *SafetyInfo,
182 const SmallPtrSetImpl<const MDNode *> &LoopLocalAliasScopes, Loop *L);
183
184namespace {
185struct LoopInvariantCodeMotion {
186 bool runOnLoop(Loop *L, const LICMDependencies &Deps,
187 bool LoopNestMode = false);
188
189 LoopInvariantCodeMotion(const ScalarOptions &Opts, const LICMOptions &LO)
190 : Opts(Opts),
191 LicmMssaOptCap(LO.MssaOptCap.value_or(Opts.licm_mssa_optimization_cap)),
192 LicmMssaNoAccForPromotionCap(LO.MssaNoAccForPromotionCap.value_or(
193 Opts.licm_mssa_max_acc_promotion)),
194 LicmAllowSpeculation(LO.AllowSpeculation) {}
195
196private:
197 const ScalarOptions &Opts;
198 unsigned LicmMssaOptCap;
199 unsigned LicmMssaNoAccForPromotionCap;
200 bool LicmAllowSpeculation;
201};
202
203struct LegacyLICMPass : public LoopPass {
204 static char ID; // Pass identification, replacement for typeid
205 LegacyLICMPass() : LoopPass(ID) {
207 }
208
209 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
210 if (skipLoop(L))
211 return false;
212
213 LLVM_DEBUG(dbgs() << "Perform LICM on Loop with header at block "
214 << L->getHeader()->getNameOrAsOperand() << "\n");
215
216 Function *F = L->getHeader()->getParent();
217
218 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
219 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
220 MemorySSAUpdater MSSAU(MSSA);
221 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
222 // pass. Function analyses need to be preserved across loop transformations
223 // but ORE cannot be preserved (see comment before the pass definition).
224 OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
225 const ScalarOptions &Opts = getScalarOptions(*F);
226 LoopInvariantCodeMotion LICM(Opts, LICMOptions());
227 ICFLoopSafetyInfo SafetyInfo(L);
228 LICMDependencies Deps{
229 SinkAndHoistDependencies{
230 getAnalysis<AAResultsWrapperPass>().getAAResults(),
231 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), MSSAU, &ORE},
232 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F),
233 getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
234 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(*F),
235 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*F),
236 SE ? &SE->getSE() : nullptr,
237 SafetyInfo};
238 return LICM.runOnLoop(L, Deps);
239 }
240
241 /// This transformation requires natural loop information & requires that
242 /// loop preheaders be inserted into the CFG...
243 ///
244 void getAnalysisUsage(AnalysisUsage &AU) const override {
245 AU.addPreserved<DominatorTreeWrapperPass>();
246 AU.addPreserved<LoopInfoWrapperPass>();
247 AU.addRequired<TargetLibraryInfoWrapperPass>();
248 AU.addRequired<MemorySSAWrapperPass>();
249 AU.addPreserved<MemorySSAWrapperPass>();
250 AU.addRequired<TargetTransformInfoWrapperPass>();
251 AU.addRequired<AssumptionCacheTracker>();
254 AU.addPreserved<LazyBlockFrequencyInfoPass>();
255 AU.addPreserved<LazyBranchProbabilityInfoPass>();
256 }
257};
258} // namespace
259
262 if (!AR.MSSA)
263 reportFatalUsageError("LICM requires MemorySSA (loop-mssa)");
264
265 // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis
266 // pass. Function analyses need to be preserved across loop transformations
267 // but ORE cannot be preserved (see comment before the pass definition).
268 OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
269
270 MemorySSAUpdater MSSAU(AR.MSSA);
271 ICFLoopSafetyInfo SafetyInfo(&L);
272 SinkAndHoistDependencies SHDeps{AR.AA, AR.DT, MSSAU, &ORE};
273 LICMDependencies Deps{SHDeps, AR.AC, AR.LI, AR.TLI,
274 AR.TTI, &AR.SE, SafetyInfo};
275 LoopInvariantCodeMotion LICM(getScalarOptions(L), Opts);
276 if (!LICM.runOnLoop(&L, Deps))
277 return PreservedAnalyses::all();
278
280 PA.preserve<MemorySSAAnalysis>();
281
282 return PA;
283}
284
286 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
287 static_cast<PassInfoMixin<LICMPass> *>(this)->printPipeline(
288 OS, MapClassName2PassName);
289
290 OS << '<';
291 OS << (Opts.AllowSpeculation ? "" : "no-") << "allowspeculation";
292 OS << '>';
293}
294
297 LPMUpdater &) {
298 if (!AR.MSSA)
299 reportFatalUsageError("LNICM requires MemorySSA (loop-mssa)");
300
301 // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis
302 // pass. Function analyses need to be preserved across loop transformations
303 // but ORE cannot be preserved (see comment before the pass definition).
305
306 MemorySSAUpdater MSSAU(AR.MSSA);
307 Loop &OutermostLoop = LN.getOutermostLoop();
308 ICFLoopSafetyInfo SafetyInfo(&OutermostLoop);
309 SinkAndHoistDependencies SHDeps{AR.AA, AR.DT, MSSAU, &ORE};
310 LICMDependencies Deps{SHDeps, AR.AC, AR.LI, AR.TLI,
311 AR.TTI, &AR.SE, SafetyInfo};
312 LoopInvariantCodeMotion LICM(getScalarOptions(OutermostLoop), Opts);
313
314 bool Changed = LICM.runOnLoop(&OutermostLoop, Deps, true);
315
316 if (!Changed)
317 return PreservedAnalyses::all();
318
320
321 PA.preserve<DominatorTreeAnalysis>();
322 PA.preserve<LoopAnalysis>();
323 PA.preserve<MemorySSAAnalysis>();
324
325 return PA;
326}
327
329 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
330 static_cast<PassInfoMixin<LNICMPass> *>(this)->printPipeline(
331 OS, MapClassName2PassName);
332
333 OS << '<';
334 OS << (Opts.AllowSpeculation ? "" : "no-") << "allowspeculation";
335 OS << '>';
336}
337
338char LegacyLICMPass::ID = 0;
339INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
340 false, false)
346INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
347 false)
348
349Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
350
352 MemorySSA &MSSA)
353 : SinkAndHoistLICMFlags(getScalarOptions(L).licm_mssa_optimization_cap,
354 getScalarOptions(L).licm_mssa_max_acc_promotion,
355 IsSink, L, MSSA) {}
356
358 unsigned LicmMssaOptCap, unsigned LicmMssaNoAccForPromotionCap, bool IsSink,
359 Loop &L, MemorySSA &MSSA)
362 IsSink(IsSink) {
363 unsigned AccessCapCount = 0;
364 for (auto *BB : L.getBlocks())
365 if (const auto *Accesses = MSSA.getBlockAccesses(BB))
366 for (const auto &MA : *Accesses) {
367 (void)MA;
368 ++AccessCapCount;
369 if (AccessCapCount > LicmMssaNoAccForPromotionCap) {
370 NoOfMemAccTooLarge = true;
371 return;
372 }
373 }
374}
375
376/// Hoist expressions out of the specified loop. Note, alias info for inner
377/// loop is not preserved so it is not a good idea to run LICM multiple
378/// times on one loop.
379bool LoopInvariantCodeMotion::runOnLoop(Loop *L, const LICMDependencies &Deps,
380 bool LoopNestMode) {
381 bool Changed = false;
382
383 assert(L->isLCSSAForm(Deps.DT) && "Loop is not in LCSSA form.");
384
385 // If this loop has metadata indicating that LICM is not to be performed then
386 // just exit.
388 return false;
389 }
390
391 // Don't sink stores from loops with coroutine suspend instructions.
392 // LICM would sink instructions into the default destination of
393 // the coroutine switch. The default destination of the switch is to
394 // handle the case where the coroutine is suspended, by which point the
395 // coroutine frame may have been destroyed. No instruction can be sunk there.
396 // FIXME: This would unfortunately hurt the performance of coroutines, however
397 // there is currently no general solution for this. Similar issues could also
398 // potentially happen in other passes where instructions are being moved
399 // across that edge.
400 bool HasCoroSuspendInst = false;
401
402 // AA metadata declared to be local to each iteration cannot be used to infer
403 // alias information when promoting stores.
404 SmallPtrSet<const MDNode *, 4> LoopLocalAliasScopes;
405
406 for (BasicBlock *BB : L->getBlocks()) {
407 for (Instruction &I : *BB) {
408 using namespace PatternMatch;
409 HasCoroSuspendInst |= match(&I, m_Intrinsic<Intrinsic::coro_suspend>());
410
411 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
412 for (const MDOperand &Op : Decl->getScopeList()->operands())
413 LoopLocalAliasScopes.insert(cast<MDNode>(Op.get()));
414 }
415 }
416
417 MemorySSA *MSSA = Deps.MSSAU.getMemorySSA();
418 SinkAndHoistLICMFlags Flags(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
419 /*IsSink=*/true, *L, *MSSA);
420
421 // Get the preheader block to move instructions into...
422 BasicBlock *Preheader = L->getLoopPreheader();
423
424 // We want to visit all of the instructions in this loop... that are not parts
425 // of our subloops (they have already had their invariants hoisted out of
426 // their loop, into this loop, so there is no need to process the BODIES of
427 // the subloops).
428 //
429 // Traverse the body of the loop in depth first order on the dominator tree so
430 // that we are guaranteed to see definitions before we see uses. This allows
431 // us to sink instructions in one pass, without iteration. After sinking
432 // instructions, we perform another pass to hoist them out of the loop.
433 if (L->hasDedicatedExits())
434 Changed |=
435 LoopNestMode
436 ? sinkRegionForLoopNest(Deps.DT.getNode(L->getHeader()), Deps, L,
437 Flags)
438 : sinkRegion(Deps.DT.getNode(L->getHeader()), Deps, L, Flags);
439 Flags.setIsSink(false);
440 if (Preheader)
441 Changed |= hoistRegion(Deps.DT.getNode(L->getHeader()), Deps, L, Flags,
442 LoopNestMode, LicmAllowSpeculation);
443
444 // Now that all loop invariants have been removed from the loop, promote any
445 // memory references to scalars that we can.
446 // Don't sink stores from loops without dedicated block exits. Exits
447 // containing indirect branches are not transformed by loop simplify,
448 // make sure we catch that. An additional load may be generated in the
449 // preheader for SSA updater, so also avoid sinking when no preheader
450 // is available.
451 if (!Opts.disable_licm_promotion && Preheader && L->hasDedicatedExits() &&
452 !Flags.tooManyMemoryAccesses() && !HasCoroSuspendInst) {
453 // Figure out the loop exits and their insertion points
454 SmallVector<BasicBlock *, 8> ExitBlocks;
455 L->getUniqueExitBlocks(ExitBlocks);
456
457 // We can't insert into a catchswitch.
458 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
459 return isa<CatchSwitchInst>(Exit->getTerminator());
460 });
461
462 if (!HasCatchSwitch) {
464 SmallVector<MemoryAccess *, 8> MSSAInsertPts;
465 InsertPts.reserve(ExitBlocks.size());
466 MSSAInsertPts.reserve(ExitBlocks.size());
468
469 // Promoting one set of accesses may make the pointers for another set
470 // loop invariant, so run this in a loop.
471 bool Promoted = false;
472 bool LocalPromoted;
473 do {
474 LocalPromoted = false;
475
476 // Recompute the insertion points each time we compute the promotion
477 // candidates, so we don't sink past a store which was promoted in a
478 // previous iteration.
479 InsertPts.clear();
480 MSSAInsertPts.clear();
481 for (BasicBlock *ExitBlock : ExitBlocks) {
482 InsertPts.push_back(ExitBlock->getFirstInsertionPt());
483 MSSAInsertPts.push_back(nullptr);
484 }
485
486 for (auto [PointerMustAliases, HasReadsOutsideSet] :
487 collectPromotionCandidates(MSSA, &Deps.AA, &Deps.DT,
488 &Deps.SafetyInfo, LoopLocalAliasScopes,
489 L)) {
490 LocalPromoted |= promoteLoopAccessesToScalars(
491 PointerMustAliases, ExitBlocks, InsertPts, MSSAInsertPts, PIC,
492 Deps, L, LicmAllowSpeculation, HasReadsOutsideSet);
493 }
494 Promoted |= LocalPromoted;
495 } while (LocalPromoted);
496
497 // Once we have promoted values across the loop body we have to
498 // recursively reform LCSSA as any nested loop may now have values defined
499 // within the loop used in the outer loop.
500 // FIXME: This is really heavy handed. It would be a bit better to use an
501 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
502 // it as it went.
503 if (Promoted)
504 formLCSSARecursively(*L, Deps.DT, &Deps.LI, Deps.SE);
505
506 Changed |= Promoted;
507 }
508 }
509
510 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
511 // specifically moving instructions across the loop boundary and so it is
512 // especially in need of basic functional correctness checking here.
513 assert(L->isLCSSAForm(Deps.DT) && "Loop not left in LCSSA form after LICM!");
514 assert((L->isOutermost() || L->getParentLoop()->isLCSSAForm(Deps.DT)) &&
515 "Parent loop not left in LCSSA form after LICM!");
516
517 if (VerifyMemorySSA)
518 MSSA->verifyMemorySSA();
519
520 if (Changed && Deps.SE)
522 return Changed;
523}
524
525/// Walk the specified region of the CFG (defined by all blocks dominated by
526/// the specified block, and that are in the current loop) in reverse depth
527/// first order w.r.t the DominatorTree. This allows us to visit uses before
528/// definitions, allowing us to sink a loop body in one pass without iteration.
529///
531 Loop *CurLoop, SinkAndHoistLICMFlags &Flags,
532 Loop *OutermostLoop) {
533
534 // Verify inputs.
535 assert(N != nullptr && CurLoop != nullptr &&
536 "Unexpected input to sinkRegion.");
537
538 // We want to visit children before parents. We will enqueue all the parents
539 // before their children in the worklist and process the worklist in reverse
540 // order.
542 collectChildrenInLoop(&Deps.DT, N, CurLoop);
543
544 bool Changed = false;
545 for (BasicBlock *BB : reverse(Worklist)) {
546 // subloop (which would already have been processed).
547 if (inSubLoop(BB, CurLoop, &Deps.LI))
548 continue;
549
550 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
551 Instruction &I = *--II;
552
553 // The instruction is not used in the loop if it is dead. In this case,
554 // we just delete it instead of sinking it.
555 if (isInstructionTriviallyDead(&I, &Deps.TLI)) {
556 LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
559 ++II;
560 eraseInstruction(I, Deps);
561 Changed = true;
562 continue;
563 }
564
565 // Check to see if we can sink this instruction to the exit blocks
566 // of the loop. We can do this if the all users of the instruction are
567 // outside of the loop. In this case, it doesn't even matter if the
568 // operands of the instruction are loop invariant.
569 //
570 bool FoldableInLoop = false;
571 bool LoopNestMode = OutermostLoop != nullptr;
572 if (!I.mayHaveSideEffects() &&
573 isNotUsedOrFoldableInLoop(I, LoopNestMode ? OutermostLoop : CurLoop,
574 &Deps.SafetyInfo, &Deps.TTI, FoldableInLoop,
575 LoopNestMode) &&
576 canSinkOrHoistInst(I, Deps, CurLoop, true, Flags)) {
577 if (sink(I, Deps, CurLoop)) {
578 if (!FoldableInLoop) {
579 ++II;
581 eraseInstruction(I, Deps);
582 }
583 Changed = true;
584 }
585 }
586 }
587 }
588 if (VerifyMemorySSA)
590 return Changed;
591}
592
594 Loop *CurLoop, SinkAndHoistLICMFlags &Flags) {
595
596 bool Changed = false;
598 Worklist.insert(CurLoop);
599 appendLoopsToWorklist(*CurLoop, Worklist);
600 while (!Worklist.empty()) {
601 Loop *L = Worklist.pop_back_val();
602 Changed |=
603 sinkRegion(Deps.DT.getNode(L->getHeader()), Deps, L, Flags, CurLoop);
604 }
605 return Changed;
606}
607
608/// Walk the specified region of the CFG (defined by all blocks dominated by
609/// the specified block, and that are in the current loop) in depth first
610/// order w.r.t the DominatorTree. This allows us to visit definitions before
611/// uses, allowing us to hoist a loop body in one pass without iteration.
612///
614 Loop *CurLoop, SinkAndHoistLICMFlags &Flags,
615 bool LoopNestMode, bool AllowSpeculation) {
616 // Verify inputs.
617 assert(N != nullptr && CurLoop != nullptr &&
618 "Unexpected input to hoistRegion.");
619
620 const ScalarOptions &Opts = getScalarOptions(*CurLoop);
621 LoopBlocksRPO Worklist(CurLoop);
622 Worklist.perform(&Deps.LI);
623 bool Changed = false;
624 BasicBlock *Preheader = CurLoop->getLoopPreheader();
625 for (BasicBlock *BB : Worklist) {
626 // Only need to process the contents of this block if it is not part of a
627 // subloop (which would already have been processed).
628 if (!LoopNestMode && inSubLoop(BB, CurLoop, &Deps.LI))
629 continue;
630
632 // Try hoisting the instruction out to the preheader. We can only do
633 // this if all of the operands of the instruction are loop invariant and
634 // if it is safe to hoist the instruction.
635 if (CurLoop->hasLoopInvariantOperands(&I) &&
636 canSinkOrHoistInst(I, Deps, CurLoop, true, Flags) &&
638 I, &Deps.DT, &Deps.TLI, CurLoop, &Deps.SafetyInfo, Deps.ORE,
639 Preheader->getTerminator(), &Deps.AC, AllowSpeculation)) {
640 hoist(I, &Deps.DT, CurLoop, Preheader, &Deps.SafetyInfo, Deps.MSSAU,
641 Deps.SE, Deps.ORE);
642 Changed = true;
643 continue;
644 }
645
646 if (auto *Ins = dyn_cast<InsertElementInst>(&I))
647 if (hoistInsertPastInsert(Ins, CurLoop, &Deps.DT, Preheader,
648 &Deps.SafetyInfo, Deps.MSSAU, Deps.SE,
649 Deps.ORE)) {
650 Changed = true;
651 continue;
652 }
653
654 // Attempt to remove floating point division out of the loop by
655 // converting it to a reciprocal multiplication.
656 if (I.getOpcode() == Instruction::FDiv && I.hasAllowReciprocal() &&
657 CurLoop->isLoopInvariant(I.getOperand(1))) {
658 auto Divisor = I.getOperand(1);
659 auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
660 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
661 ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
662 Deps.SafetyInfo.insertInstructionTo(ReciprocalDivisor, I.getParent());
663 ReciprocalDivisor->insertBefore(I.getIterator());
664 ReciprocalDivisor->setDebugLoc(I.getDebugLoc());
665
666 auto Product =
667 BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
668 Product->setFastMathFlags(I.getFastMathFlags());
669 Deps.SafetyInfo.insertInstructionTo(Product, I.getParent());
670 Product->insertAfter(I.getIterator());
671 Product->setDebugLoc(I.getDebugLoc());
672 I.replaceAllUsesWith(Product);
673 eraseInstruction(I, Deps);
674
675 hoist(*ReciprocalDivisor, &Deps.DT, CurLoop, Preheader,
676 &Deps.SafetyInfo, Deps.MSSAU, Deps.SE, Deps.ORE);
677 Changed = true;
678 continue;
679 }
680
681 auto IsInvariantStart = [&](Instruction &I) {
682 using namespace PatternMatch;
683 return I.use_empty() &&
685 };
686 auto MustExecuteWithoutWritesBefore = [&](Instruction &I) {
687 return Deps.SafetyInfo.isGuaranteedToExecute(I, &Deps.DT) &&
689 };
690 if ((IsInvariantStart(I) || isGuard(&I)) &&
691 CurLoop->hasLoopInvariantOperands(&I) &&
692 MustExecuteWithoutWritesBefore(I)) {
693 hoist(I, &Deps.DT, CurLoop, Preheader, &Deps.SafetyInfo, Deps.MSSAU,
694 Deps.SE, Deps.ORE);
695 Changed = true;
696 continue;
697 }
698
699 // Try to reassociate instructions so that part of computations can be
700 // done out of loop.
701 if (hoistArithmetics(Opts, I, *CurLoop, Deps)) {
702 Changed = true;
703 continue;
704 }
705 }
706 }
707
708 if (VerifyMemorySSA)
710
711 // Now that we've finished hoisting make sure that LI and DT are still
712 // valid.
713#ifdef EXPENSIVE_CHECKS
714 if (Changed) {
715 assert(Deps.DT.verify(DominatorTree::VerificationLevel::Fast) &&
716 "Dominator tree verification failed");
717 Deps.LI.verify();
718 }
719#endif
720
721 return Changed;
722}
723
724static std::optional<uint64_t>
726 // Must have constant insertion lane.
727 auto *InsertedIdxCI = dyn_cast<ConstantInt>(Ins->getOperand(2));
728 if (!InsertedIdxCI)
729 return std::nullopt;
730 auto *VecTy = cast<VectorType>(Ins->getType());
731
732 // Avoid hoisting past out of bounds inserts.
733 if (InsertedIdxCI->isNegative() ||
734 InsertedIdxCI->getValue().uge(
735 VecTy->getElementCount().getKnownMinValue()))
736 return std::nullopt;
737 return InsertedIdxCI->getValue().getLimitedValue();
738}
739
741 DominatorTree *DT, BasicBlock *HoistDest,
742 ICFLoopSafetyInfo *SafetyInfo,
745 // Canonicalize:
746 // %inner = insertelement %base, %variant, C1
747 // %outer = insertelement %inner, %invariant, C2
748 // into:
749 // %outer = insertelement %base, %invariant, C2
750 // %inner = insertelement %outer, %variant, C1
751 // so we can hoist %outer
752
753 // The instruction we are hoisting must have invariant insertion data
754 Value *InsertedElt = Ins->getOperand(1);
755 if (!CurLoop->isLoopInvariant(InsertedElt))
756 return false;
757
758 std::optional<uint64_t> HoistIdx = getConstantInsertionIndex(Ins);
759 if (!HoistIdx)
760 return false;
761
762 InsertElementInst *Inner = Ins;
763 while (!CurLoop->isLoopInvariant(Inner->getOperand(0))) {
764 // If the inner value isn't invariant, check to see if it is another insert
765 // All instructions in the chain must be in the same basic block
766 auto *InnerIns = dyn_cast<InsertElementInst>(Inner->getOperand(0));
767 if (!InnerIns || InnerIns->getParent() != Ins->getParent())
768 return false;
769
770 // Make sure not hoisting past insertions into the same lane
771 std::optional<uint64_t> InsertIdx = getConstantInsertionIndex(InnerIns);
772 if (!InsertIdx || *InsertIdx == *HoistIdx)
773 return false;
774
775 // Instruction being hoisted past must only have one use
776 if (!InnerIns->hasOneUse())
777 return false;
778
779 Inner = InnerIns;
780 }
781
782 // Base case of `insertelement <4 x i8> %invar0, i8 %invar1, i32 2` handled in
783 // base LICM logic
784 if (Inner == Ins)
785 return false;
786
787 Ins->replaceAllUsesWith(Ins->getOperand(0));
788 Ins->moveBefore(Inner->getIterator());
789 Ins->setOperand(0, Inner->getOperand(0));
790 Inner->setOperand(0, Ins);
791 hoist(*Ins, DT, CurLoop, HoistDest, SafetyInfo, MSSAU, SE, ORE);
792 return true;
793}
794
795// Return true if LI is invariant within scope of the loop. LI is invariant if
796// CurLoop is dominated by an invariant.start representing the same memory
797// location and size as the memory location LI loads from, and also the
798// invariant.start has no uses.
800 Loop *CurLoop) {
801 Value *Addr = LI->getPointerOperand();
802 const DataLayout &DL = LI->getDataLayout();
803 const TypeSize LocSizeInBits = DL.getTypeSizeInBits(LI->getType());
804
805 // It is not currently possible for clang to generate an invariant.start
806 // intrinsic with scalable vector types because we don't support thread local
807 // sizeless types and we don't permit sizeless types in structs or classes.
808 // Furthermore, even if support is added for this in future the intrinsic
809 // itself is defined to have a size of -1 for variable sized objects. This
810 // makes it impossible to verify if the intrinsic envelops our region of
811 // interest. For example, both <vscale x 32 x i8> and <vscale x 16 x i8>
812 // types would have a -1 parameter, but the former is clearly double the size
813 // of the latter.
814 if (LocSizeInBits.isScalable())
815 return false;
816
817 // If we've ended up at a global/constant, bail. We shouldn't be looking at
818 // uselists for non-local Values in a loop pass.
819 if (isa<Constant>(Addr))
820 return false;
821
822 const ScalarOptions &Opts = getScalarOptions(*LI->getFunction());
823 unsigned UsesVisited = 0;
824 // Traverse all uses of the load operand value, to see if invariant.start is
825 // one of the uses, and whether it dominates the load instruction.
826 for (auto *U : Addr->users()) {
827 // Avoid traversing for Load operand with high number of users.
828 if (++UsesVisited > Opts.licm_max_num_uses_traversed)
829 return false;
831 // If there are escaping uses of invariant.start instruction, the load maybe
832 // non-invariant.
833 if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
834 !II->use_empty())
835 continue;
836 ConstantInt *InvariantSize = cast<ConstantInt>(II->getArgOperand(0));
837 // The intrinsic supports having a -1 argument for variable sized objects
838 // so we should check for that here.
839 if (InvariantSize->isNegative())
840 continue;
841 uint64_t InvariantSizeInBits = InvariantSize->getSExtValue() * 8;
842 // Confirm the invariant.start location size contains the load operand size
843 // in bits. Also, the invariant.start should dominate the load, and we
844 // should not hoist the load out of a loop that contains this dominating
845 // invariant.start.
846 if (LocSizeInBits.getFixedValue() <= InvariantSizeInBits &&
847 DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
848 return true;
849 }
850
851 return false;
852}
853
854/// Return true if-and-only-if we know how to (mechanically) both hoist and
855/// sink a given instruction out of a loop. Does not address legality
856/// concerns such as aliasing or speculation safety.
867
868/// Return true if I is the only Instruction with a MemoryAccess in L.
869static bool isOnlyMemoryAccess(const Instruction *I, const Loop *L,
870 const MemorySSAUpdater &MSSAU) {
871 for (auto *BB : L->getBlocks())
872 if (auto *Accs = MSSAU.getMemorySSA()->getBlockAccesses(BB)) {
873 int NotAPhi = 0;
874 for (const auto &Acc : *Accs) {
875 if (isa<MemoryPhi>(&Acc))
876 continue;
877 const auto *MUD = cast<MemoryUseOrDef>(&Acc);
878 if (MUD->getMemoryInst() != I || NotAPhi++ == 1)
879 return false;
880 }
881 }
882 return true;
883}
884
886 BatchAAResults &BAA,
888 MemoryUseOrDef *MA) {
889 // See declaration of SetLicmMssaOptCap for usage details.
890 if (Flags.tooManyClobberingCalls())
891 return MA->getDefiningAccess();
892
893 MemoryAccess *Source =
895 Flags.incrementClobberingCalls();
896 return Source;
897}
898
900 Loop *CurLoop, bool TargetExecutesOncePerLoop,
901 SinkAndHoistLICMFlags &Flags) {
902 if (!LI.isUnordered())
903 return false; // Don't sink/hoist volatile or ordered atomic loads!
904
905 // Loads from constant memory are always safe to move, even if they end up
906 // in the same alias set as something that ends up being modified.
907 if (!isModSet(Deps.AA.getModRefInfoMask(LI.getOperand(0))))
908 return true;
909 if (LI.hasMetadata(LLVMContext::MD_invariant_load))
910 return true;
911
912 if (LI.isAtomic() && !TargetExecutesOncePerLoop)
913 return false; // Don't risk duplicating unordered loads
914
915 // This checks for an invariant.start dominating the load.
916 if (isLoadInvariantInLoop(&LI, &Deps.DT, CurLoop))
917 return true;
918
919 auto *MU = cast<MemoryUse>(Deps.MSSAU.getMemorySSA()->getMemoryAccess(&LI));
920
921 bool InvariantGroup = LI.hasMetadata(LLVMContext::MD_invariant_group);
922
923 bool Invalidated =
924 pointerInvalidatedByLoop(Deps, MU, CurLoop, LI, Flags, InvariantGroup);
925 // Check loop-invariant address because this may also be a sinkable load
926 // whose address is not necessarily loop-invariant.
927 if (Deps.ORE && Invalidated &&
928 CurLoop->isLoopInvariant(LI.getPointerOperand()))
929 Deps.ORE->emit([&]() {
931 DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", &LI)
932 << "failed to move load with loop-invariant address "
933 "because the loop may invalidate its value";
934 });
935
936 return !Invalidated;
937}
938
940 const SinkAndHoistDependencies &Deps,
941 Loop *CurLoop, bool TargetExecutesOncePerLoop,
942 SinkAndHoistLICMFlags &Flags) {
943 // If we don't understand the instruction, bail early.
945 return false;
946
947 MemorySSA *MSSA = Deps.MSSAU.getMemorySSA();
948 // Loads have extra constraints we have to verify before we can hoist them.
949 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
950 return canHoistLoad(*LI, Deps, CurLoop, TargetExecutesOncePerLoop, Flags);
951 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
952 // Don't sink calls which can throw.
953 if (CI->mayThrow())
954 return false;
955
956 // Convergent attribute has been used on operations that involve
957 // inter-thread communication which results are implicitly affected by the
958 // enclosing control flows. It is not safe to hoist or sink such operations
959 // across control flow.
960 if (CI->isConvergent())
961 return false;
962
963 // FIXME: Current LLVM IR semantics don't work well with coroutines and
964 // thread local globals. We currently treat getting the address of a thread
965 // local global as not accessing memory, even though it may not be a
966 // constant throughout a function with coroutines. Remove this check after
967 // we better model semantics of thread local globals.
968 if (CI->getFunction()->isPresplitCoroutine())
969 return false;
970
971 using namespace PatternMatch;
973 // Assumes don't actually alias anything or throw
974 return true;
975
976 // Handle simple cases by querying alias analysis.
977 MemoryEffects Behavior = Deps.AA.getMemoryEffects(CI);
978
979 if (Behavior.doesNotAccessMemory())
980 return true;
981 if (Behavior.onlyReadsMemory()) {
982 // Might have stale MemoryDef for call that was later inferred to be
983 // read-only.
984 auto *MU = dyn_cast<MemoryUse>(MSSA->getMemoryAccess(CI));
985 if (!MU)
986 return false;
987
988 // If we can prove there are no writes to the memory read by the call, we
989 // can hoist or sink.
990 return !pointerInvalidatedByLoop(Deps, MU, CurLoop, I, Flags,
991 /*InvariantGroup=*/false);
992 }
993
994 if (Behavior.onlyWritesMemory()) {
995 // can hoist or sink if there are no conflicting read/writes to the
996 // memory location written to by the call.
997 return noConflictingReadWrites(CI, MSSA, &Deps.AA, CurLoop, Flags);
998 }
999
1000 return false;
1001 } else if (auto *FI = dyn_cast<FenceInst>(&I)) {
1002 // Fences alias (most) everything to provide ordering. For the moment,
1003 // just give up if there are any other memory operations in the loop.
1004 return isOnlyMemoryAccess(FI, CurLoop, Deps.MSSAU);
1005 } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
1006 if (!SI->isUnordered())
1007 return false; // Don't sink/hoist volatile or ordered atomic store!
1008
1009 // We can only hoist a store that we can prove writes a value which is not
1010 // read or overwritten within the loop. For those cases, we fallback to
1011 // load store promotion instead. TODO: We can extend this to cases where
1012 // there is exactly one write to the location and that write dominates an
1013 // arbitrary number of reads in the loop.
1014 if (isOnlyMemoryAccess(SI, CurLoop, Deps.MSSAU))
1015 return true;
1016 return noConflictingReadWrites(SI, MSSA, &Deps.AA, CurLoop, Flags);
1017 }
1018
1019 assert(!I.mayReadOrWriteMemory() && "unhandled aliasing");
1020
1021 // We've established mechanical ability and aliasing, it's up to the caller
1022 // to check fault safety
1023 return true;
1024}
1025
1026/// Returns true if a PHINode is a trivially replaceable with an
1027/// Instruction.
1028/// This is true when all incoming values are that instruction.
1029/// This pattern occurs most often with LCSSA PHI nodes.
1030///
1031static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) {
1032 for (const Value *IncValue : PN.incoming_values())
1033 if (IncValue != &I)
1034 return false;
1035
1036 return true;
1037}
1038
1039/// Return true if the instruction is foldable in the loop.
1040static bool isFoldableInLoop(const Instruction &I, const Loop *CurLoop,
1041 const TargetTransformInfo *TTI) {
1042 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1043 InstructionCost CostI =
1044 TTI->getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
1045 if (CostI != TargetTransformInfo::TCC_Free)
1046 return false;
1047 // For a GEP, we cannot simply use getInstructionCost because currently
1048 // it optimistically assumes that a GEP will fold into addressing mode
1049 // regardless of its users.
1050 const BasicBlock *BB = GEP->getParent();
1051 for (const User *U : GEP->users()) {
1052 const Instruction *UI = cast<Instruction>(U);
1053 if (CurLoop->contains(UI) &&
1054 (BB != UI->getParent() ||
1055 (!isa<StoreInst>(UI) && !isa<LoadInst>(UI))))
1056 return false;
1057 }
1058 return true;
1059 }
1060
1061 return false;
1062}
1063
1064/// Return true if the only users of this instruction are outside of
1065/// the loop. If this is true, we can sink the instruction to the exit
1066/// blocks of the loop.
1067///
1068/// We also return true if the instruction could be folded away in lowering.
1069/// (e.g., a GEP can be folded into a load as an addressing mode in the loop).
1070static bool isNotUsedOrFoldableInLoop(const Instruction &I, const Loop *CurLoop,
1071 const LoopSafetyInfo *SafetyInfo,
1073 bool &FoldableInLoop, bool LoopNestMode) {
1074 bool IsFoldable = isFoldableInLoop(I, CurLoop, TTI);
1075 for (const User *U : I.users()) {
1076 const Instruction *UI = cast<Instruction>(U);
1077 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
1078 const BasicBlock *BB = PN->getParent();
1079 // We cannot sink uses in catchswitches.
1081 return false;
1082
1083 // We need to sink a callsite to a unique funclet. Avoid sinking if the
1084 // phi use is too muddled.
1085 if (isa<CallInst>(I)) {
1086 const auto &BlockColors = SafetyInfo->getBlockColors();
1087 if (!BlockColors.empty() &&
1088 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
1089 return false;
1090 }
1091
1092 if (LoopNestMode) {
1093 while (isa<PHINode>(UI) && UI->hasOneUser() &&
1094 UI->getNumOperands() == 1) {
1095 if (!CurLoop->contains(UI))
1096 break;
1097 UI = cast<Instruction>(UI->user_back());
1098 }
1099 }
1100 }
1101
1102 if (CurLoop->contains(UI)) {
1103 if (IsFoldable) {
1104 FoldableInLoop = true;
1105 continue;
1106 }
1107 return false;
1108 }
1109 }
1110 return true;
1111}
1112
1114 Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,
1115 const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU) {
1116 Instruction *New;
1117 if (auto *CI = dyn_cast<CallInst>(&I)) {
1118 const auto &BlockColors = SafetyInfo->getBlockColors();
1119
1120 // Sinking call-sites need to be handled differently from other
1121 // instructions. The cloned call-site needs a funclet bundle operand
1122 // appropriate for its location in the CFG.
1124 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
1125 BundleIdx != BundleEnd; ++BundleIdx) {
1126 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
1127 if (Bundle.getTagID() == LLVMContext::OB_funclet)
1128 continue;
1129
1130 OpBundles.emplace_back(Bundle);
1131 }
1132
1133 if (!BlockColors.empty()) {
1134 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
1135 assert(CV.size() == 1 && "non-unique color for exit block!");
1136 BasicBlock *BBColor = CV.front();
1137 BasicBlock::iterator EHPad = BBColor->getFirstNonPHIIt();
1138 if (EHPad->isEHPad())
1139 OpBundles.emplace_back("funclet", &*EHPad);
1140 }
1141
1142 New = CallInst::Create(CI, OpBundles);
1143 New->copyMetadata(*CI);
1144 } else {
1145 New = I.clone();
1146 }
1147
1148 New->insertInto(&ExitBlock, ExitBlock.getFirstInsertionPt());
1149 if (!I.getName().empty())
1150 New->setName(I.getName() + ".le");
1151
1152 if (MSSAU.getMemorySSA()->getMemoryAccess(&I)) {
1153 // Create a new MemoryAccess and let MemorySSA set its defining access.
1154 // After running some passes, MemorySSA might be outdated, and the
1155 // instruction `I` may have become a non-memory touching instruction.
1156 MemoryAccess *NewMemAcc = MSSAU.createMemoryAccessInBB(
1157 New, nullptr, New->getParent(), MemorySSA::Beginning,
1158 /*CreationMustSucceed=*/false);
1159 if (NewMemAcc) {
1160 if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc))
1161 MSSAU.insertDef(MemDef, /*RenameUses=*/true);
1162 else {
1163 auto *MemUse = cast<MemoryUse>(NewMemAcc);
1164 MSSAU.insertUse(MemUse, /*RenameUses=*/true);
1165 }
1166 }
1167 }
1168
1169 // Build LCSSA PHI nodes for any in-loop operands (if legal). Note that
1170 // this is particularly cheap because we can rip off the PHI node that we're
1171 // replacing for the number and blocks of the predecessors.
1172 // OPT: If this shows up in a profile, we can instead finish sinking all
1173 // invariant instructions, and then walk their operands to re-establish
1174 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
1175 // sinking bottom-up.
1176 for (Use &Op : New->operands())
1177 if (LI->wouldBeOutOfLoopUseRequiringLCSSA(Op.get(), PN.getParent())) {
1178 auto *OInst = cast<Instruction>(Op.get());
1179 PHINode *OpPN =
1180 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
1181 OInst->getName() + ".lcssa");
1182 OpPN->insertBefore(ExitBlock.begin());
1183 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1184 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
1185 Op = OpPN;
1186 }
1187 return New;
1188}
1189
1191 Deps.MSSAU.removeMemoryAccess(&I);
1193 I.eraseFromParent();
1194}
1195
1197 ICFLoopSafetyInfo &SafetyInfo,
1198 MemorySSAUpdater &MSSAU,
1199 ScalarEvolution *SE) {
1200 SafetyInfo.removeInstruction(&I);
1201 SafetyInfo.insertInstructionTo(&I, Dest->getParent());
1202 I.moveBefore(*Dest->getParent(), Dest);
1204 MSSAU.getMemorySSA()->getMemoryAccess(&I)))
1205 MSSAU.moveToPlace(OldMemAcc, Dest->getParent(),
1207 if (SE)
1209}
1210
1212 PHINode *TPN, Instruction *I, LoopInfo *LI,
1214 const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop,
1215 MemorySSAUpdater &MSSAU) {
1217 "Expect only trivially replaceable PHI");
1218 BasicBlock *ExitBlock = TPN->getParent();
1219 auto [It, Inserted] = SunkCopies.try_emplace(ExitBlock);
1220 if (Inserted)
1221 It->second = cloneInstructionInExitBlock(*I, *ExitBlock, *TPN, LI,
1222 SafetyInfo, MSSAU);
1223 return It->second;
1224}
1225
1226static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) {
1227 BasicBlock *BB = PN->getParent();
1228 if (!BB->canSplitPredecessors())
1229 return false;
1230 // It's not impossible to split EHPad blocks, but if BlockColors already exist
1231 // it require updating BlockColors for all offspring blocks accordingly. By
1232 // skipping such corner case, we can make updating BlockColors after splitting
1233 // predecessor fairly simple.
1234 if (!SafetyInfo->getBlockColors().empty() &&
1235 BB->getFirstNonPHIIt()->isEHPad())
1236 return false;
1237 for (BasicBlock *BBPred : predecessors(BB)) {
1238 if (isa<IndirectBrInst>(BBPred->getTerminator()))
1239 return false;
1240 }
1241 return true;
1242}
1243
1245 LoopInfo *LI, const Loop *CurLoop,
1246 LoopSafetyInfo *SafetyInfo,
1247 MemorySSAUpdater *MSSAU) {
1248#ifndef NDEBUG
1250 CurLoop->getUniqueExitBlocks(ExitBlocks);
1251 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(llvm::from_range, ExitBlocks);
1252#endif
1253 BasicBlock *ExitBB = PN->getParent();
1254 assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.");
1255
1256 // Split predecessors of the loop exit to make instructions in the loop are
1257 // exposed to exit blocks through trivially replaceable PHIs while keeping the
1258 // loop in the canonical form where each predecessor of each exit block should
1259 // be contained within the loop. For example, this will convert the loop below
1260 // from
1261 //
1262 // LB1:
1263 // %v1 =
1264 // br %LE, %LB2
1265 // LB2:
1266 // %v2 =
1267 // br %LE, %LB1
1268 // LE:
1269 // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable
1270 //
1271 // to
1272 //
1273 // LB1:
1274 // %v1 =
1275 // br %LE.split, %LB2
1276 // LB2:
1277 // %v2 =
1278 // br %LE.split2, %LB1
1279 // LE.split:
1280 // %p1 = phi [%v1, %LB1] <-- trivially replaceable
1281 // br %LE
1282 // LE.split2:
1283 // %p2 = phi [%v2, %LB2] <-- trivially replaceable
1284 // br %LE
1285 // LE:
1286 // %p = phi [%p1, %LE.split], [%p2, %LE.split2]
1287 //
1288 const auto &BlockColors = SafetyInfo->getBlockColors();
1289 SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));
1290 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1291 while (!PredBBs.empty()) {
1292 BasicBlock *PredBB = *PredBBs.begin();
1293 assert(CurLoop->contains(PredBB) &&
1294 "Expect all predecessors are in the loop");
1295 if (PN->getBasicBlockIndex(PredBB) >= 0) {
1297 ExitBB, PredBB, ".split.loop.exit", &DTU, LI, MSSAU, true);
1298 // Since we do not allow splitting EH-block with BlockColors in
1299 // canSplitPredecessors(), we can simply assign predecessor's color to
1300 // the new block.
1301 if (!BlockColors.empty())
1302 // Grab a reference to the ColorVector to be inserted before getting the
1303 // reference to the vector we are copying because inserting the new
1304 // element in BlockColors might cause the map to be reallocated.
1305 SafetyInfo->copyColors(NewPred, PredBB);
1306 }
1307 PredBBs.remove(PredBB);
1308 }
1309}
1310
1311/// When an instruction is found to only be used outside of the loop, this
1312/// function moves it to the exit blocks and patches up SSA form as needed.
1313/// This method is guaranteed to remove the original instruction from its
1314/// position, and may either delete it or move it to outside of the loop.
1315///
1316static bool sink(Instruction &I, const LICMDependencies &Deps,
1317 const Loop *CurLoop) {
1318 bool Changed = false;
1319 LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
1320
1321 // Iterate over users to be ready for actual sinking. Replace users via
1322 // unreachable blocks with undef and make all user PHIs trivially replaceable.
1323 SmallPtrSet<Instruction *, 8> VisitedUsers;
1324 for (Instruction::user_iterator UI = I.user_begin(), UE = I.user_end();
1325 UI != UE;) {
1326 auto *User = cast<Instruction>(*UI);
1327 Use &U = UI.getUse();
1328 ++UI;
1329
1330 if (VisitedUsers.count(User) || CurLoop->contains(User))
1331 continue;
1332
1333 if (!Deps.DT.isReachableFromEntry(User->getParent())) {
1334 U = PoisonValue::get(I.getType());
1335 Changed = true;
1336 continue;
1337 }
1338
1339 // The user must be a PHI node.
1340 PHINode *PN = cast<PHINode>(User);
1341
1342 // Surprisingly, instructions can be used outside of loops without any
1343 // exits. This can only happen in PHI nodes if the incoming block is
1344 // unreachable.
1345 BasicBlock *BB = PN->getIncomingBlock(U);
1346 if (!Deps.DT.isReachableFromEntry(BB)) {
1347 U = PoisonValue::get(I.getType());
1348 Changed = true;
1349 continue;
1350 }
1351
1352 VisitedUsers.insert(PN);
1353 if (isTriviallyReplaceablePHI(*PN, I))
1354 continue;
1355
1356 if (!canSplitPredecessors(PN, &Deps.SafetyInfo))
1357 return Changed;
1358
1359 // Split predecessors of the PHI so that we can make users trivially
1360 // replaceable.
1361 splitPredecessorsOfLoopExit(PN, &Deps.DT, &Deps.LI, CurLoop,
1362 &Deps.SafetyInfo, &Deps.MSSAU);
1363
1364 // Should rebuild the iterators, as they may be invalidated by
1365 // splitPredecessorsOfLoopExit().
1366 UI = I.user_begin();
1367 UE = I.user_end();
1368 }
1369
1370 if (VisitedUsers.empty())
1371 return Changed;
1372
1373 Deps.ORE->emit([&]() {
1374 return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
1375 << "sinking " << ore::NV("Inst", &I);
1376 });
1377 if (isa<LoadInst>(I))
1378 ++NumMovedLoads;
1379 else if (isa<CallInst>(I))
1380 ++NumMovedCalls;
1381 ++NumSunk;
1382
1383#ifndef NDEBUG
1385 CurLoop->getUniqueExitBlocks(ExitBlocks);
1386 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(llvm::from_range, ExitBlocks);
1387#endif
1388
1389 // Clones of this instruction. Don't create more than one per exit block!
1391
1392 // If this instruction is only used outside of the loop, then all users are
1393 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
1394 // the instruction.
1395 // First check if I is worth sinking for all uses. Sink only when it is worth
1396 // across all uses.
1397 SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end());
1398 for (auto *UI : Users) {
1399 auto *User = cast<Instruction>(UI);
1400
1401 if (CurLoop->contains(User))
1402 continue;
1403
1404 PHINode *PN = cast<PHINode>(User);
1405 assert(ExitBlockSet.count(PN->getParent()) &&
1406 "The LCSSA PHI is not in an exit block!");
1407
1408 // The PHI must be trivially replaceable.
1410 PN, &I, &Deps.LI, SunkCopies, &Deps.SafetyInfo, CurLoop, Deps.MSSAU);
1411 // As we sink the instruction out of the BB, drop its debug location.
1412 New->dropLocation();
1413 PN->replaceAllUsesWith(New);
1414 eraseInstruction(*PN, Deps);
1415 Changed = true;
1416 }
1417 return Changed;
1418}
1419
1420/// When an instruction is found to only use loop invariant operands that
1421/// is safe to hoist, this instruction is called to do the dirty work.
1422///
1423static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
1424 BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,
1427 LLVM_DEBUG(dbgs() << "LICM hoisting to " << Dest->getNameOrAsOperand() << ": "
1428 << I << "\n");
1429 ORE->emit([&]() {
1430 return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting "
1431 << ore::NV("Inst", &I);
1432 });
1433
1434 // Metadata can be dependent on conditions we are hoisting above.
1435 // Conservatively strip all metadata on the instruction unless we were
1436 // guaranteed to execute I if we entered the loop, in which case the metadata
1437 // is valid in the loop preheader.
1438 // Similarly, If I is a call and it is not guaranteed to execute in the loop,
1439 // then moving to the preheader means we should strip attributes on the call
1440 // that can cause UB since we may be hoisting above conditions that allowed
1441 // inferring those attributes. They may not be valid at the preheader.
1442 if ((I.hasMetadataOtherThanDebugLoc() || isa<CallInst>(I)) &&
1443 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
1444 // time in isGuaranteedToExecute if we don't actually have anything to
1445 // drop. It is a compile time optimization, not required for correctness.
1446 !SafetyInfo->isGuaranteedToExecute(I, DT)) {
1447 I.dropUBImplyingAttrsAndMetadata();
1448 }
1449
1450 if (isa<PHINode>(I))
1451 // Move the new node to the end of the phi list in the destination block.
1452 moveInstructionBefore(I, Dest->getFirstNonPHIIt(), *SafetyInfo, MSSAU, SE);
1453 else
1454 // Move the new node to the destination block, before its terminator.
1455 moveInstructionBefore(I, Dest->getTerminator()->getIterator(), *SafetyInfo,
1456 MSSAU, SE);
1457
1458 I.updateLocationAfterHoist();
1459
1460 if (isa<LoadInst>(I))
1461 ++NumMovedLoads;
1462 else if (isa<CallInst>(I))
1463 ++NumMovedCalls;
1464 ++NumHoisted;
1465}
1466
1467/// Only sink or hoist an instruction if it is not a trapping instruction,
1468/// or if the instruction is known not to trap when moved to the preheader.
1469/// or if it is a trapping instruction and is guaranteed to execute.
1471 Instruction &Inst, const DominatorTree *DT, const TargetLibraryInfo *TLI,
1472 const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo,
1473 OptimizationRemarkEmitter *ORE, const Instruction *CtxI,
1474 AssumptionCache *AC, bool AllowSpeculation) {
1475 if (AllowSpeculation &&
1476 isSafeToSpeculativelyExecute(&Inst, CtxI, AC, DT, TLI))
1477 return true;
1478
1479 bool GuaranteedToExecute = SafetyInfo->isGuaranteedToExecute(Inst, DT);
1480
1481 if (!GuaranteedToExecute) {
1482 auto *LI = dyn_cast<LoadInst>(&Inst);
1483 if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
1484 ORE->emit([&]() {
1486 DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
1487 << "failed to hoist load with loop-invariant address "
1488 "because load is conditionally executed";
1489 });
1490 }
1491
1492 return GuaranteedToExecute;
1493}
1494
1495namespace {
1496class LoopPromoter : public LoadAndStorePromoter {
1497 Value *SomePtr; // Designated pointer to store to.
1498 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
1499 SmallVectorImpl<BasicBlock::iterator> &LoopInsertPts;
1500 SmallVectorImpl<MemoryAccess *> &MSSAInsertPts;
1501 PredIteratorCache &PredCache;
1502 MemorySSAUpdater &MSSAU;
1503 LoopInfo &LI;
1504 DebugLoc DL;
1506 bool UnorderedAtomic;
1507 AAMDNodes AATags;
1508 ICFLoopSafetyInfo &SafetyInfo;
1509 bool CanInsertStoresInExitBlocks;
1511
1512 // We're about to add a use of V in a loop exit block. Insert an LCSSA phi
1513 // (if legal) if doing so would add an out-of-loop use to an instruction
1514 // defined in-loop.
1515 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
1516 if (!LI.wouldBeOutOfLoopUseRequiringLCSSA(V, BB))
1517 return V;
1518
1520 // We need to create an LCSSA PHI node for the incoming value and
1521 // store that.
1522 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
1523 I->getName() + ".lcssa");
1524 PN->insertBefore(BB->begin());
1525 for (BasicBlock *Pred : PredCache.get(BB))
1526 PN->addIncoming(I, Pred);
1527 return PN;
1528 }
1529
1530public:
1531 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
1532 SmallVectorImpl<BasicBlock *> &LEB,
1533 SmallVectorImpl<BasicBlock::iterator> &LIP,
1534 SmallVectorImpl<MemoryAccess *> &MSSAIP, PredIteratorCache &PIC,
1535 MemorySSAUpdater &MSSAU, LoopInfo &li, DebugLoc dl,
1536 Align Alignment, bool UnorderedAtomic, const AAMDNodes &AATags,
1537 ICFLoopSafetyInfo &SafetyInfo, bool CanInsertStoresInExitBlocks)
1538 : LoadAndStorePromoter(Insts, S), SomePtr(SP), LoopExitBlocks(LEB),
1539 LoopInsertPts(LIP), MSSAInsertPts(MSSAIP), PredCache(PIC), MSSAU(MSSAU),
1540 LI(li), DL(std::move(dl)), Alignment(Alignment),
1541 UnorderedAtomic(UnorderedAtomic), AATags(AATags),
1542 SafetyInfo(SafetyInfo),
1543 CanInsertStoresInExitBlocks(CanInsertStoresInExitBlocks), Uses(Insts) {}
1544
1545 void insertStoresInLoopExitBlocks() {
1546 // Insert stores after in the loop exit blocks. Each exit block gets a
1547 // store of the live-out values that feed them. Since we've already told
1548 // the SSA updater about the defs in the loop and the preheader
1549 // definition, it is all set and we can start using it.
1550 DIAssignID *NewID = nullptr;
1551 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
1552 BasicBlock *ExitBlock = LoopExitBlocks[i];
1553 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1554 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1555 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1556 BasicBlock::iterator InsertPos = LoopInsertPts[i];
1557 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
1558 if (UnorderedAtomic)
1559 NewSI->setOrdering(AtomicOrdering::Unordered);
1560 NewSI->setAlignment(Alignment);
1561 NewSI->setDebugLoc(DL);
1562 // Attach DIAssignID metadata to the new store, generating it on the
1563 // first loop iteration.
1564 if (i == 0) {
1565 // NewSI will have its DIAssignID set here if there are any stores in
1566 // Uses with a DIAssignID attachment. This merged ID will then be
1567 // attached to the other inserted stores (in the branch below).
1568 NewSI->mergeDIAssignID(Uses);
1570 NewSI->getMetadata(LLVMContext::MD_DIAssignID));
1571 } else {
1572 // Attach the DIAssignID (or nullptr) merged from Uses in the branch
1573 // above.
1574 NewSI->setMetadata(LLVMContext::MD_DIAssignID, NewID);
1575 }
1576
1577 if (AATags)
1578 NewSI->setAAMetadata(AATags);
1579
1580 MemoryAccess *MSSAInsertPoint = MSSAInsertPts[i];
1581 MemoryAccess *NewMemAcc;
1582 if (!MSSAInsertPoint) {
1583 NewMemAcc = MSSAU.createMemoryAccessInBB(
1584 NewSI, nullptr, NewSI->getParent(), MemorySSA::Beginning);
1585 } else {
1586 NewMemAcc =
1587 MSSAU.createMemoryAccessAfter(NewSI, nullptr, MSSAInsertPoint);
1588 }
1589 MSSAInsertPts[i] = NewMemAcc;
1590 MSSAU.insertDef(cast<MemoryDef>(NewMemAcc), true);
1591 // FIXME: true for safety, false may still be correct.
1592 }
1593 }
1594
1595 void doExtraRewritesBeforeFinalDeletion() override {
1596 if (CanInsertStoresInExitBlocks)
1597 insertStoresInLoopExitBlocks();
1598 }
1599
1600 void instructionDeleted(Instruction *I) const override {
1601 SafetyInfo.removeInstruction(I);
1602 MSSAU.removeMemoryAccess(I);
1603 }
1604
1605 bool shouldDelete(Instruction *I) const override {
1606 if (isa<StoreInst>(I))
1607 return CanInsertStoresInExitBlocks;
1608 return true;
1609 }
1610};
1611
1612bool isNotCapturedBeforeOrInLoop(const Value *V, const Loop *L,
1613 DominatorTree *DT) {
1614 // We can perform the captured-before check against any instruction in the
1615 // loop header, as the loop header is reachable from any instruction inside
1616 // the loop.
1617 // TODO: ReturnCaptures=true shouldn't be necessary here.
1619 V, /*ReturnCaptures=*/true, L->getHeader()->getTerminator(), DT,
1620 /*IncludeI=*/false, CaptureComponents::Provenance));
1621}
1622
1623/// Return true if we can prove that a caller cannot inspect the object if an
1624/// unwind occurs inside the loop.
1625bool isNotVisibleOnUnwindInLoop(const Value *Object, const Loop *L,
1626 DominatorTree *DT) {
1627 bool RequiresNoCaptureBeforeUnwind;
1628 if (!isNotVisibleOnUnwind(Object, RequiresNoCaptureBeforeUnwind))
1629 return false;
1630
1631 return !RequiresNoCaptureBeforeUnwind ||
1632 isNotCapturedBeforeOrInLoop(Object, L, DT);
1633}
1634
1635bool isThreadLocalObject(const Value *Object, const Loop *L,
1636 DominatorTree *DT) {
1637 // The object must be function-local to start with, and then not captured
1638 // before/in the loop.
1639 if (isIdentifiedFunctionLocal(Object) &&
1640 isNotCapturedBeforeOrInLoop(Object, L, DT))
1641 return true;
1642
1643 // In a single-threaded environment, all objects are effectively thread-local.
1644 const Module *M = L->getHeader()->getModule();
1645 return M->getThreadModel() == ThreadModel::Single;
1646}
1647
1648} // namespace
1649
1650/// Try to promote memory values to scalars by sinking stores out of the
1651/// loop and moving loads to before the loop. We do this by looping over
1652/// the stores in the loop, looking for stores to Must pointers which are
1653/// loop invariant.
1654///
1656 const SmallSetVector<Value *, 8> &PointerMustAliases,
1660 const LICMDependencies &Deps, Loop *CurLoop, bool AllowSpeculation,
1661 bool HasReadsOutsideSet) {
1662 // Verify inputs.
1663 assert(CurLoop != nullptr &&
1664 "Unexpected Input to promoteLoopAccessesToScalars");
1665
1666 LLVM_DEBUG({
1667 dbgs() << "Trying to promote set of must-aliased pointers:\n";
1668 for (Value *Ptr : PointerMustAliases)
1669 dbgs() << " " << *Ptr << "\n";
1670 });
1671 ++NumPromotionCandidates;
1672
1673 Value *SomePtr = *PointerMustAliases.begin();
1674 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1675
1676 // It is not safe to promote a load/store from the loop if the load/store is
1677 // conditional. For example, turning:
1678 //
1679 // for () { if (c) *P += 1; }
1680 //
1681 // into:
1682 //
1683 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
1684 //
1685 // is not safe, because *P may only be valid to access if 'c' is true.
1686 //
1687 // The safety property divides into two parts:
1688 // p1) The memory may not be dereferenceable on entry to the loop. In this
1689 // case, we can't insert the required load in the preheader.
1690 // p2) The memory model does not allow us to insert a store along any dynamic
1691 // path which did not originally have one.
1692 //
1693 // If at least one store is guaranteed to execute, both properties are
1694 // satisfied, and promotion is legal.
1695 //
1696 // This, however, is not a necessary condition. Even if no store/load is
1697 // guaranteed to execute, we can still establish these properties.
1698 // We can establish (p1) by proving that hoisting the load into the preheader
1699 // is safe (i.e. proving dereferenceability on all paths through the loop). We
1700 // can use any access within the alias set to prove dereferenceability,
1701 // since they're all must alias.
1702 //
1703 // There are two ways establish (p2):
1704 // a) Prove the location is thread-local. In this case the memory model
1705 // requirement does not apply, and stores are safe to insert.
1706 // b) Prove a store dominates every exit block. In this case, if an exit
1707 // blocks is reached, the original dynamic path would have taken us through
1708 // the store, so inserting a store into the exit block is safe. Note that this
1709 // is different from the store being guaranteed to execute. For instance,
1710 // if an exception is thrown on the first iteration of the loop, the original
1711 // store is never executed, but the exit blocks are not executed either.
1712
1713 bool DereferenceableInPH = false;
1714 bool StoreIsGuaranteedToExecute = false;
1715 bool LoadIsGuaranteedToExecute = false;
1716 bool FoundLoadToPromote = false;
1717
1718 // Goes from Unknown to either Safe or Unsafe, but can't switch between them.
1719 enum {
1720 StoreSafe,
1721 StoreUnsafe,
1722 StoreSafetyUnknown,
1723 } StoreSafety = StoreSafetyUnknown;
1724
1726
1727 // We start with an alignment of one and try to find instructions that allow
1728 // us to prove better alignment.
1729 Align Alignment;
1730 // Keep track of which types of access we see
1731 bool SawUnorderedAtomic = false;
1732 bool SawNotAtomic = false;
1733 AAMDNodes AATags;
1734
1735 const DataLayout &MDL = Preheader->getDataLayout();
1736
1737 // If there are reads outside the promoted set, then promoting stores is
1738 // definitely not safe.
1739 if (HasReadsOutsideSet)
1740 StoreSafety = StoreUnsafe;
1741
1742 if (StoreSafety == StoreSafetyUnknown && Deps.SafetyInfo.anyBlockMayThrow()) {
1743 // If a loop can throw, we have to insert a store along each unwind edge.
1744 // That said, we can't actually make the unwind edge explicit. Therefore,
1745 // we have to prove that the store is dead along the unwind edge. We do
1746 // this by proving that the caller can't have a reference to the object
1747 // after return and thus can't possibly load from the object.
1748 Value *Object = getUnderlyingObject(SomePtr);
1749 if (!isNotVisibleOnUnwindInLoop(Object, CurLoop, &Deps.DT))
1750 StoreSafety = StoreUnsafe;
1751 }
1752
1753 // Check that all accesses to pointers in the alias set use the same type.
1754 // We cannot (yet) promote a memory location that is loaded and stored in
1755 // different sizes. While we are at it, collect alignment and AA info.
1756 Type *AccessTy = nullptr;
1757 for (Value *ASIV : PointerMustAliases) {
1758 for (Use &U : ASIV->uses()) {
1759 // Ignore instructions that are outside the loop.
1760 Instruction *UI = dyn_cast<Instruction>(U.getUser());
1761 if (!UI || !CurLoop->contains(UI))
1762 continue;
1763
1764 // If there is an non-load/store instruction in the loop, we can't promote
1765 // it.
1766 if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
1767 if (!Load->isUnordered())
1768 return false;
1769
1770 SawUnorderedAtomic |= Load->isAtomic();
1771 SawNotAtomic |= !Load->isAtomic();
1772 FoundLoadToPromote = true;
1773
1774 Align InstAlignment = Load->getAlign();
1775
1776 if (!LoadIsGuaranteedToExecute)
1777 LoadIsGuaranteedToExecute =
1778 Deps.SafetyInfo.isGuaranteedToExecute(*UI, &Deps.DT);
1779
1780 // Note that proving a load safe to speculate requires proving
1781 // sufficient alignment at the target location. Proving it guaranteed
1782 // to execute does as well. Thus we can increase our guaranteed
1783 // alignment as well.
1784 if (!DereferenceableInPH || (InstAlignment > Alignment))
1786 *Load, &Deps.DT, &Deps.TLI, CurLoop, &Deps.SafetyInfo,
1787 Deps.ORE, Preheader->getTerminator(), &Deps.AC,
1788 AllowSpeculation)) {
1789 DereferenceableInPH = true;
1790 Alignment = std::max(Alignment, InstAlignment);
1791 }
1792 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
1793 // Stores *of* the pointer are not interesting, only stores *to* the
1794 // pointer.
1795 if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
1796 continue;
1797 if (!Store->isUnordered())
1798 return false;
1799
1800 SawUnorderedAtomic |= Store->isAtomic();
1801 SawNotAtomic |= !Store->isAtomic();
1802
1803 // If the store is guaranteed to execute, both properties are satisfied.
1804 // We may want to check if a store is guaranteed to execute even if we
1805 // already know that promotion is safe, since it may have higher
1806 // alignment than any other guaranteed stores, in which case we can
1807 // raise the alignment on the promoted store.
1808 Align InstAlignment = Store->getAlign();
1809 bool GuaranteedToExecute =
1810 Deps.SafetyInfo.isGuaranteedToExecute(*UI, &Deps.DT);
1811 StoreIsGuaranteedToExecute |= GuaranteedToExecute;
1812 if (GuaranteedToExecute) {
1813 DereferenceableInPH = true;
1814 if (StoreSafety == StoreSafetyUnknown)
1815 StoreSafety = StoreSafe;
1816 Alignment = std::max(Alignment, InstAlignment);
1817 }
1818
1819 // If a store dominates all exit blocks, it is safe to sink.
1820 // As explained above, if an exit block was executed, a dominating
1821 // store must have been executed at least once, so we are not
1822 // introducing stores on paths that did not have them.
1823 // Note that this only looks at explicit exit blocks. If we ever
1824 // start sinking stores into unwind edges (see above), this will break.
1825 if (StoreSafety == StoreSafetyUnknown &&
1826 llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
1827 return Deps.DT.dominates(Store->getParent(), Exit);
1828 }))
1829 StoreSafety = StoreSafe;
1830
1831 // If the store is not guaranteed to execute, we may still get
1832 // deref info through it.
1833 if (!DereferenceableInPH) {
1834 DereferenceableInPH = isDereferenceableAndAlignedPointer(
1835 Store->getPointerOperand(), Store->getValueOperand()->getType(),
1836 Store->getAlign(),
1837 SimplifyQuery(MDL, &Deps.TLI, &Deps.DT, &Deps.AC,
1838 Preheader->getTerminator()));
1839 }
1840 } else
1841 continue; // Not a load or store.
1842
1843 if (!AccessTy)
1844 AccessTy = getLoadStoreType(UI);
1845 else if (AccessTy != getLoadStoreType(UI))
1846 return false;
1847
1848 // Merge the AA tags.
1849 if (LoopUses.empty()) {
1850 // On the first load/store, just take its AA tags.
1851 AATags = UI->getAAMetadata();
1852 } else if (AATags) {
1853 AATags = AATags.merge(UI->getAAMetadata());
1854 }
1855
1856 LoopUses.push_back(UI);
1857 }
1858 }
1859
1860 // If we found both an unordered atomic instruction and a non-atomic memory
1861 // access, bail. We can't blindly promote non-atomic to atomic since we
1862 // might not be able to lower the result. We can't downgrade since that
1863 // would violate memory model. Also, align 0 is an error for atomics.
1864 if (SawUnorderedAtomic && SawNotAtomic)
1865 return false;
1866
1867 // If we're inserting an atomic load in the preheader, we must be able to
1868 // lower it. We're only guaranteed to be able to lower naturally aligned
1869 // atomics.
1870 if (SawUnorderedAtomic && Alignment < MDL.getTypeStoreSize(AccessTy))
1871 return false;
1872
1873 // If we couldn't prove we can hoist the load, bail.
1874 if (!DereferenceableInPH) {
1875 LLVM_DEBUG(dbgs() << "Not promoting: Not dereferenceable in preheader\n");
1876 return false;
1877 }
1878
1879 // We know we can hoist the load, but don't have a guaranteed store.
1880 // Check whether the location is writable and thread-local. If it is, then we
1881 // can insert stores along paths which originally didn't have them without
1882 // violating the memory model.
1883 if (StoreSafety == StoreSafetyUnknown) {
1884 Value *Object = getUnderlyingObject(SomePtr);
1885 bool ExplicitlyDereferenceableOnly;
1886 // The dereferenceability query here is only required to satisfy the
1887 // writable contract, actual dereferenceability has already been proven
1888 // above. As such, we can ignore frees.
1889 if (isWritableObject(Object, ExplicitlyDereferenceableOnly) &&
1890 (!ExplicitlyDereferenceableOnly ||
1891 isDereferenceablePointer(SomePtr, AccessTy, MDL,
1892 /*IgnoreFree=*/true)) &&
1893 isThreadLocalObject(Object, CurLoop, &Deps.DT))
1894 StoreSafety = StoreSafe;
1895 }
1896
1897 // If we've still failed to prove we can sink the store, hoist the load
1898 // only, if possible.
1899 if (StoreSafety != StoreSafe && !FoundLoadToPromote)
1900 // If we cannot hoist the load either, give up.
1901 return false;
1902
1903 // Lets do the promotion!
1904 if (StoreSafety == StoreSafe) {
1905 LLVM_DEBUG(dbgs() << "LICM: Promoting load/store of the value: " << *SomePtr
1906 << '\n');
1907 ++NumLoadStorePromoted;
1908 } else {
1909 LLVM_DEBUG(dbgs() << "LICM: Promoting load of the value: " << *SomePtr
1910 << '\n');
1911 ++NumLoadPromoted;
1912 }
1913
1914 Deps.ORE->emit([&]() {
1915 return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar",
1916 LoopUses[0])
1917 << "Moving accesses to memory location out of the loop";
1918 });
1919
1920 // Look at all the loop uses, and try to merge their locations.
1921 std::vector<DebugLoc> LoopUsesLocs;
1922 for (auto U : LoopUses)
1923 LoopUsesLocs.push_back(U->getDebugLoc());
1924 auto DL = DebugLoc::getMergedLocations(LoopUsesLocs);
1925
1926 // We use the SSAUpdater interface to insert phi nodes as required.
1928 SSAUpdater SSA(&NewPHIs);
1929 LoopPromoter Promoter(SomePtr, LoopUses, SSA, ExitBlocks, InsertPts,
1930 MSSAInsertPts, PIC, Deps.MSSAU, Deps.LI, DL, Alignment,
1931 SawUnorderedAtomic,
1932 StoreIsGuaranteedToExecute ? AATags : AAMDNodes(),
1933 Deps.SafetyInfo, StoreSafety == StoreSafe);
1934
1935 // Set up the preheader to have a definition of the value. It is the live-out
1936 // value from the preheader that uses in the loop will use.
1937 LoadInst *PreheaderLoad = nullptr;
1938 if (FoundLoadToPromote || !StoreIsGuaranteedToExecute) {
1939 PreheaderLoad =
1940 new LoadInst(AccessTy, SomePtr, SomePtr->getName() + ".promoted",
1941 Preheader->getTerminator()->getIterator());
1942 if (SawUnorderedAtomic)
1943 PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
1944 PreheaderLoad->setAlignment(Alignment);
1945 PreheaderLoad->setDebugLoc(DebugLoc::getDropped());
1946 if (AATags && LoadIsGuaranteedToExecute)
1947 PreheaderLoad->setAAMetadata(AATags);
1948
1949 MemoryAccess *PreheaderLoadMemoryAccess = Deps.MSSAU.createMemoryAccessInBB(
1950 PreheaderLoad, nullptr, PreheaderLoad->getParent(), MemorySSA::End);
1951 MemoryUse *NewMemUse = cast<MemoryUse>(PreheaderLoadMemoryAccess);
1952 Deps.MSSAU.insertUse(NewMemUse, /*RenameUses=*/true);
1953 SSA.AddAvailableValue(Preheader, PreheaderLoad);
1954 } else {
1955 SSA.AddAvailableValue(Preheader, PoisonValue::get(AccessTy));
1956 }
1957
1958 if (VerifyMemorySSA)
1960 // Rewrite all the loads in the loop and remember all the definitions from
1961 // stores in the loop.
1962 Promoter.run(LoopUses);
1963
1964 if (VerifyMemorySSA)
1966 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1967 if (PreheaderLoad && PreheaderLoad->use_empty())
1968 eraseInstruction(*PreheaderLoad, Deps);
1969
1970 return true;
1971}
1972
1973static void foreachMemoryAccess(MemorySSA *MSSA, Loop *L,
1974 function_ref<void(Instruction *)> Fn) {
1975 for (const BasicBlock *BB : L->blocks())
1976 if (const auto *Accesses = MSSA->getBlockAccesses(BB))
1977 for (const auto &Access : *Accesses)
1978 if (const auto *MUD = dyn_cast<MemoryUseOrDef>(&Access))
1979 Fn(MUD->getMemoryInst());
1980}
1981
1982/// Returns whether \p I is a memory access that may be a candidate for
1983/// promotion out of the loop \p L.
1984static bool isPotentiallyPromotable(const Instruction *I, const Loop *L) {
1985 if (const auto *SI = dyn_cast<StoreInst>(I)) {
1986 const Value *PtrOp = SI->getPointerOperand();
1987 if (isStrongerThanMonotonic(SI->getOrdering()))
1988 return false;
1989 return !isa<ConstantData>(PtrOp) && L->isLoopInvariant(PtrOp);
1990 }
1991 if (const auto *LI = dyn_cast<LoadInst>(I)) {
1992 const Value *PtrOp = LI->getPointerOperand();
1993 if (isStrongerThanMonotonic(LI->getOrdering()))
1994 return false;
1995 return !isa<ConstantData>(PtrOp) && L->isLoopInvariant(PtrOp);
1996 }
1997 return false;
1998}
1999
2000/// Returns whether \p N has any operand from the set \p Operands.
2001static bool
2004 return N && llvm::any_of(N->operands(), [&](const MDOperand &Op) {
2005 return Operands.contains(cast<MDNode>(Op.get()));
2006 });
2007}
2008
2009/// Returns the potentially promotable stores with AA tags that are valid along
2010/// all non-unwinding execution paths of the loop \p L, which allows for the AA
2011/// tags to be used when deciding promotions.
2013 MemorySSA *MSSA, DominatorTree *DT,
2014 const SmallPtrSetImpl<const MDNode *> &LoopLocalAliasScopes, Loop *L) {
2016 StoresByLoc;
2017 foreachMemoryAccess(MSSA, L, [&](Instruction *I) {
2018 const auto *SI = dyn_cast<StoreInst>(I);
2019 if (SI && SI->getAAMetadata() && isPotentiallyPromotable(SI, L))
2020 StoresByLoc[MemoryLocation::get(SI)].push_back(SI);
2021 });
2022
2023 // This only looks at explicit exiting blocks. If we ever start sinking
2024 // stores into unwind edges, this will break.
2025 SmallVector<BasicBlock *, 4> ExitingBlocks;
2026 L->getExitingBlocks(ExitingBlocks);
2027
2028 SmallPtrSet<const StoreInst *, 8> StoresWithInvariantAATags;
2029 for (const auto &Pair : StoresByLoc) {
2030 const MemoryLocation &Loc = Pair.first;
2031 const SmallVector<const StoreInst *, 1> &Stores = Pair.second;
2032
2033 // A scope declared inside the loop denotes a different scope on each
2034 // iteration, and thus should not be preserved.
2035 if (hasAnyMDOperandsFrom(Loc.AATags.Scope, LoopLocalAliasScopes) ||
2036 hasAnyMDOperandsFrom(Loc.AATags.NoAlias, LoopLocalAliasScopes))
2037 continue;
2038
2039 // Without exiting blocks the loop is never left, and promotion has no
2040 // exit block to insert a store into either.
2041 if (llvm::all_of(ExitingBlocks, [&](BasicBlock *ExitingBB) {
2042 return llvm::any_of(Stores, [&](const StoreInst *SI) {
2043 return DT->dominates(SI->getParent(), ExitingBB);
2044 });
2045 }))
2046 StoresWithInvariantAATags.insert_range(Stores);
2047 }
2048 return StoresWithInvariantAATags;
2049}
2050
2051// The bool indicates whether there might be reads outside the set, in which
2052// case only loads may be promoted.
2055 ICFLoopSafetyInfo *SafetyInfo,
2056 const SmallPtrSetImpl<const MDNode *> &LoopLocalAliasScopes, Loop *L) {
2057 BatchAAResults BatchAA(*AA);
2058 AliasSetTracker AST(BatchAA);
2059
2060 // Only conditionally executed stores need this, so compute it on demand to
2061 // keep the common case free.
2062 std::optional<SmallPtrSet<const StoreInst *, 8>> StoresWithInvariantAATags;
2063 auto HasInvariantAATags = [&](const StoreInst *SI) {
2064 if (!StoresWithInvariantAATags)
2065 StoresWithInvariantAATags =
2066 collectStoresWithInvariantAATags(MSSA, DT, LoopLocalAliasScopes, L);
2067 return StoresWithInvariantAATags->contains(SI);
2068 };
2069
2070 // Populate AST with potentially promotable accesses.
2071 SmallPtrSet<Value *, 16> AttemptingPromotion;
2072 foreachMemoryAccess(MSSA, L, [&](Instruction *I) {
2073 if (isPotentiallyPromotable(I, L)) {
2074 AttemptingPromotion.insert(I);
2076 SI && SI->getAAMetadata() &&
2077 !SafetyInfo->isGuaranteedToExecute(*SI, DT) &&
2078 !HasInvariantAATags(SI)) {
2079 // Promotion requires inserting a new store at the loop exits; we need
2080 // to prove that store doesn't alias anything, in addition to proving
2081 // aliasing for the stores we're removing. The new store is executed
2082 // unconditionally, so when we're proving aliasing for that store, we
2083 // can only rely on AA tags that likewise hold unconditionally.
2084 AST.addWithoutAATags(SI);
2085 } else {
2086 AST.add(I);
2087 }
2088 }
2089 });
2090
2091 // We're only interested in must-alias sets that contain a mod.
2093 for (AliasSet &AS : AST)
2094 if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias())
2095 Sets.push_back({&AS, false});
2096
2097 if (Sets.empty())
2098 return {}; // Nothing to promote...
2099
2100 // Discard any sets for which there is an aliasing non-promotable access.
2101 foreachMemoryAccess(MSSA, L, [&](Instruction *I) {
2102 if (AttemptingPromotion.contains(I))
2103 return;
2104
2106 ModRefInfo MR = Pair.getPointer()->aliasesUnknownInst(I, BatchAA);
2107 // Cannot promote if there are writes outside the set.
2108 if (isModSet(MR))
2109 return true;
2110 if (isRefSet(MR)) {
2111 // Remember reads outside the set.
2112 Pair.setInt(true);
2113 // If this is a mod-only set and there are reads outside the set,
2114 // we will not be able to promote, so bail out early.
2115 return !Pair.getPointer()->isRef();
2116 }
2117 return false;
2118 });
2119 });
2120
2122 for (auto [Set, HasReadsOutsideSet] : Sets) {
2123 SmallSetVector<Value *, 8> PointerMustAliases;
2124 for (const auto &MemLoc : *Set)
2125 PointerMustAliases.insert(const_cast<Value *>(MemLoc.Ptr));
2126 Result.emplace_back(std::move(PointerMustAliases), HasReadsOutsideSet);
2127 }
2128
2129 return Result;
2130}
2131
2132// For a given store instruction or writeonly call instruction, this function
2133// checks that there are no read or writes that conflict with the memory
2134// access in the instruction
2136 AAResults *AA, Loop *CurLoop,
2137 SinkAndHoistLICMFlags &Flags) {
2139 // If there are more accesses than the Promotion cap, then give up as we're
2140 // not walking a list that long.
2141 if (Flags.tooManyMemoryAccesses())
2142 return false;
2143
2144 auto *IMD = MSSA->getMemoryAccess(I);
2145 BatchAAResults BAA(*AA);
2146 auto *Source = getClobberingMemoryAccess(*MSSA, BAA, Flags, IMD);
2147 // Make sure there are no clobbers inside the loop.
2148 if (!MSSA->isLiveOnEntryDef(Source) && CurLoop->contains(Source->getBlock()))
2149 return false;
2150
2151 // If there are interfering Uses don't move this store.
2152 // TODO: Cache set of Uses on the first walk in runOnLoop, update when
2153 // moving accesses. Can also extend to dominating uses.
2154 for (auto *BB : CurLoop->getBlocks()) {
2155 auto *Accesses = MSSA->getBlockAccesses(BB);
2156 if (!Accesses)
2157 continue;
2158 for (const auto &MA : *Accesses) {
2159 // Accesses are ordered. If we find one that I dominates we can stop.
2160 if (!Flags.getIsSink() && MSSA->dominates(IMD, &MA))
2161 break;
2162
2163 if (const auto *MemUseOrDef = dyn_cast<MemoryUseOrDef>(&MA)) {
2164 // Skip unrelated accesses.
2165 if (isNoModRef(BAA.getModRefInfo(MemUseOrDef->getMemoryInst(), I)))
2166 continue;
2167
2168 return false;
2169 }
2170 }
2171 }
2172 return true;
2173}
2174
2176 MemoryUse *MU, Loop *CurLoop,
2177 Instruction &I,
2178 SinkAndHoistLICMFlags &Flags,
2179 bool InvariantGroup) {
2180 MemorySSA *MSSA = Deps.MSSAU.getMemorySSA();
2181 // For hoisting, use the walker to determine safety
2182 if (!Flags.getIsSink()) {
2183 // If hoisting an invariant group, we only need to check that there
2184 // is no store to the loaded pointer between the start of the loop,
2185 // and the load (since all values must be the same).
2186
2187 // This can be checked in two conditions:
2188 // 1) if the memoryaccess is outside the loop
2189 // 2) the earliest access is at the loop header,
2190 // if the memory loaded is the phi node
2191
2192 BatchAAResults BAA(MSSA->getAA());
2193 MemoryAccess *Source = getClobberingMemoryAccess(*MSSA, BAA, Flags, MU);
2194 return !MSSA->isLiveOnEntryDef(Source) &&
2195 CurLoop->contains(Source->getBlock()) &&
2196 !(InvariantGroup && Source->getBlock() == CurLoop->getHeader() && isa<MemoryPhi>(Source));
2197 }
2198
2199 // For sinking, we'd need to check all Defs below this use. The getClobbering
2200 // call will look on the backedge of the loop, but will check aliasing with
2201 // the instructions on the previous iteration.
2202 // For example:
2203 // for (i ... )
2204 // load a[i] ( Use (LoE)
2205 // store a[i] ( 1 = Def (2), with 2 = Phi for the loop.
2206 // i++;
2207 // The load sees no clobbering inside the loop, as the backedge alias check
2208 // does phi translation, and will check aliasing against store a[i-1].
2209 // However sinking the load outside the loop, below the store is incorrect.
2210
2211 // For now, only sink if there are no Defs in the loop, and the existing ones
2212 // precede the use and are in the same block.
2213 // FIXME: Increase precision: Safe to sink if Use post dominates the Def;
2214 // needs PostDominatorTreeAnalysis.
2215 // FIXME: More precise: no Defs that alias this Use.
2216 if (Flags.tooManyMemoryAccesses())
2217 return true;
2218 for (auto *BB : CurLoop->getBlocks())
2219 if (pointerInvalidatedByBlock(*BB, *MSSA, *MU))
2220 return true;
2221 // When sinking, the source block may not be part of the loop so check it.
2222 if (!CurLoop->contains(&I))
2223 return pointerInvalidatedByBlock(*I.getParent(), *MSSA, *MU);
2224
2225 return false;
2226}
2227
2229 if (const auto *Accesses = MSSA.getBlockDefs(&BB))
2230 for (const auto &MA : *Accesses)
2231 if (const auto *MD = dyn_cast<MemoryDef>(&MA))
2232 if (MU.getBlock() != MD->getBlock() || !MSSA.locallyDominates(MD, &MU))
2233 return true;
2234 return false;
2235}
2236
2237/// Try to simplify things like (A < INV_1 AND icmp A < INV_2) into (A <
2238/// min(INV_1, INV_2)), if INV_1 and INV_2 are both loop invariants and their
2239/// minimun can be computed outside of loop, and X is not a loop-invariant.
2240static bool hoistMinMax(Instruction &I, Loop &L, const LICMDependencies &Deps) {
2241 bool Inverse = false;
2242 using namespace PatternMatch;
2243 Value *Cond1, *Cond2;
2244 if (match(&I, m_LogicalOr(m_Value(Cond1), m_Value(Cond2)))) {
2245 Inverse = true;
2246 } else if (match(&I, m_LogicalAnd(m_Value(Cond1), m_Value(Cond2)))) {
2247 // Do nothing
2248 } else
2249 return false;
2250
2251 auto MatchICmpAgainstInvariant = [&](Value *C, CmpPredicate &P, Value *&LHS,
2252 Value *&RHS) {
2253 if (!match(C, m_OneUse(m_ICmp(P, m_Value(LHS), m_Value(RHS)))))
2254 return false;
2255 if (!LHS->getType()->isIntegerTy())
2256 return false;
2258 return false;
2259 if (L.isLoopInvariant(LHS)) {
2260 std::swap(LHS, RHS);
2262 }
2263 if (L.isLoopInvariant(LHS) || !L.isLoopInvariant(RHS))
2264 return false;
2265 if (Inverse)
2267 return true;
2268 };
2269 CmpPredicate P1, P2;
2270 Value *LHS1, *LHS2, *RHS1, *RHS2;
2271 if (!MatchICmpAgainstInvariant(Cond1, P1, LHS1, RHS1) ||
2272 !MatchICmpAgainstInvariant(Cond2, P2, LHS2, RHS2))
2273 return false;
2274 auto MatchingPred = CmpPredicate::getMatching(P1, P2);
2275 if (!MatchingPred || LHS1 != LHS2)
2276 return false;
2277
2278 // Everything is fine, we can do the transform.
2279 bool UseMin = ICmpInst::isLT(*MatchingPred) || ICmpInst::isLE(*MatchingPred);
2280 assert(
2281 (UseMin || ICmpInst::isGT(*MatchingPred) ||
2282 ICmpInst::isGE(*MatchingPred)) &&
2283 "Relational predicate is either less (or equal) or greater (or equal)!");
2284 Intrinsic::ID id = ICmpInst::isSigned(*MatchingPred)
2285 ? (UseMin ? Intrinsic::smin : Intrinsic::smax)
2286 : (UseMin ? Intrinsic::umin : Intrinsic::umax);
2287 auto *Preheader = L.getLoopPreheader();
2288 assert(Preheader && "Loop is not in simplify form?");
2289 IRBuilder<> Builder(Preheader->getTerminator());
2290 // We are about to create a new guaranteed use for RHS2 which might not exist
2291 // before (if it was a non-taken input of logical and/or instruction). If it
2292 // was poison, we need to freeze it. Note that no new use for LHS and RHS1 are
2293 // introduced, so they don't need this.
2294 if (isa<SelectInst>(I))
2295 RHS2 = Builder.CreateFreeze(RHS2, RHS2->getName() + ".fr");
2296 Value *NewRHS = Builder.CreateBinaryIntrinsic(
2297 id, RHS1, RHS2, nullptr,
2298 StringRef("invariant.") +
2299 (ICmpInst::isSigned(*MatchingPred) ? "s" : "u") +
2300 (UseMin ? "min" : "max"));
2301 Builder.SetInsertPoint(&I);
2302 ICmpInst::Predicate P = *MatchingPred;
2303 if (Inverse)
2305 Value *NewCond = Builder.CreateICmp(P, LHS1, NewRHS);
2306 NewCond->takeName(&I);
2307 I.replaceAllUsesWith(NewCond);
2308 eraseInstruction(I, Deps);
2309 Instruction &CondI1 = *cast<Instruction>(Cond1);
2310 Instruction &CondI2 = *cast<Instruction>(Cond2);
2311 salvageDebugInfo(CondI1);
2312 salvageDebugInfo(CondI2);
2313 eraseInstruction(CondI1, Deps);
2314 eraseInstruction(CondI2, Deps);
2315 return true;
2316}
2317
2318/// Reassociate gep (gep ptr, idx1), idx2 to gep (gep ptr, idx2), idx1 if
2319/// this allows hoisting the inner GEP.
2320static bool hoistGEP(Instruction &I, Loop &L, const LICMDependencies &Deps) {
2322 if (!GEP)
2323 return false;
2324
2325 // Do not try to hoist a constant GEP out of the loop via reassociation.
2326 // Constant GEPs can often be folded into addressing modes, and reassociating
2327 // them may inhibit CSE of a common base.
2328 if (GEP->hasAllConstantIndices())
2329 return false;
2330
2331 auto *Src = dyn_cast<GetElementPtrInst>(GEP->getPointerOperand());
2332 if (!Src || !Src->hasOneUse() || !L.contains(Src))
2333 return false;
2334
2335 Value *SrcPtr = Src->getPointerOperand();
2336 auto LoopInvariant = [&](Value *V) { return L.isLoopInvariant(V); };
2337 if (!L.isLoopInvariant(SrcPtr) || !all_of(GEP->indices(), LoopInvariant))
2338 return false;
2339
2340 // This can only happen if !AllowSpeculation, otherwise this would already be
2341 // handled.
2342 // FIXME: Should we respect AllowSpeculation in these reassociation folds?
2343 // The flag exists to prevent metadata dropping, which is not relevant here.
2344 if (all_of(Src->indices(), LoopInvariant))
2345 return false;
2346
2347 // The swapped GEPs are inbounds if both original GEPs are inbounds
2348 // and the sign of the offsets is the same. For simplicity, only
2349 // handle both offsets being non-negative.
2350 const DataLayout &DL = GEP->getDataLayout();
2351 auto NonNegative = [&](Value *V) {
2352 return isKnownNonNegative(V, SimplifyQuery(DL, &Deps.DT, &Deps.AC, GEP));
2353 };
2354 bool IsInBounds = Src->isInBounds() && GEP->isInBounds() &&
2355 all_of(Src->indices(), NonNegative) &&
2356 all_of(GEP->indices(), NonNegative);
2357
2358 BasicBlock *Preheader = L.getLoopPreheader();
2359 IRBuilder<> Builder(Preheader->getTerminator());
2360 Value *NewSrc = Builder.CreateGEP(GEP->getSourceElementType(), SrcPtr,
2361 SmallVector<Value *>(GEP->indices()),
2362 "invariant.gep", IsInBounds);
2363 Builder.SetInsertPoint(GEP);
2364 Value *NewGEP = Builder.CreateGEP(Src->getSourceElementType(), NewSrc,
2365 SmallVector<Value *>(Src->indices()), "gep",
2366 IsInBounds);
2367 GEP->replaceAllUsesWith(NewGEP);
2368 eraseInstruction(*GEP, Deps);
2369 salvageDebugInfo(*Src);
2370 eraseInstruction(*Src, Deps);
2371 return true;
2372}
2373
2374/// Try to turn things like "LV + C1 < C2" into "LV < C2 - C1". Here
2375/// C1 and C2 are loop invariants and LV is a loop-variant.
2376static bool hoistAdd(ICmpInst::Predicate Pred, Value *VariantLHS,
2377 Value *InvariantRHS, ICmpInst &ICmp, Loop &L,
2378 const LICMDependencies &Deps) {
2379 assert(!L.isLoopInvariant(VariantLHS) && "Precondition.");
2380 assert(L.isLoopInvariant(InvariantRHS) && "Precondition.");
2381
2382 bool IsSigned = ICmpInst::isSigned(Pred);
2383
2384 // Try to represent VariantLHS as sum of invariant and variant operands.
2385 using namespace PatternMatch;
2386 Value *VariantOp, *InvariantOp;
2387 if (IsSigned && !match(VariantLHS, m_NSWAddLike(m_Value(VariantOp),
2388 m_Value(InvariantOp))))
2389 return false;
2390 if (!IsSigned && !match(VariantLHS, m_NUWAddLike(m_Value(VariantOp),
2391 m_Value(InvariantOp))))
2392 return false;
2393
2394 // LHS itself is a loop-variant, try to represent it in the form:
2395 // "VariantOp + InvariantOp". If it is possible, then we can reassociate.
2396 if (L.isLoopInvariant(VariantOp))
2397 std::swap(VariantOp, InvariantOp);
2398 if (L.isLoopInvariant(VariantOp) || !L.isLoopInvariant(InvariantOp))
2399 return false;
2400
2401 // In order to turn "LV + C1 < C2" into "LV < C2 - C1", we need to be able to
2402 // freely move values from left side of inequality to right side (just as in
2403 // normal linear arithmetics). Overflows make things much more complicated, so
2404 // we want to avoid this.
2405 auto &DL = L.getHeader()->getDataLayout();
2406 SimplifyQuery SQ(DL, &Deps.DT, &Deps.AC, &ICmp);
2407 if (IsSigned && computeOverflowForSignedSub(InvariantRHS, InvariantOp, SQ) !=
2409 return false;
2410 if (!IsSigned &&
2411 computeOverflowForUnsignedSub(InvariantRHS, InvariantOp, SQ) !=
2413 return false;
2414 auto *Preheader = L.getLoopPreheader();
2415 assert(Preheader && "Loop is not in simplify form?");
2416 IRBuilder<> Builder(Preheader->getTerminator());
2417 Value *NewCmpOp =
2418 Builder.CreateSub(InvariantRHS, InvariantOp, "invariant.op",
2419 /*HasNUW*/ !IsSigned, /*HasNSW*/ IsSigned);
2420 ICmp.setPredicate(Pred);
2421 ICmp.setOperand(0, VariantOp);
2422 ICmp.setOperand(1, NewCmpOp);
2423 // The new LHS is a different value, so a samesign (or any other
2424 // poison-generating) flag asserted about the old operands may no longer hold.
2426
2427 Instruction &DeadI = cast<Instruction>(*VariantLHS);
2428 salvageDebugInfo(DeadI);
2429 eraseInstruction(DeadI, Deps);
2430 return true;
2431}
2432
2433/// Try to reassociate and hoist the following two patterns:
2434/// LV - C1 < C2 --> LV < C1 + C2,
2435/// C1 - LV < C2 --> LV > C1 - C2.
2436static bool hoistSub(ICmpInst::Predicate Pred, Value *VariantLHS,
2437 Value *InvariantRHS, ICmpInst &ICmp, Loop &L,
2438 const LICMDependencies &Deps) {
2439 assert(!L.isLoopInvariant(VariantLHS) && "Precondition.");
2440 assert(L.isLoopInvariant(InvariantRHS) && "Precondition.");
2441
2442 bool IsSigned = ICmpInst::isSigned(Pred);
2443
2444 // Try to represent VariantLHS as sum of invariant and variant operands.
2445 using namespace PatternMatch;
2446 Value *VariantOp, *InvariantOp;
2447 if (IsSigned &&
2448 !match(VariantLHS, m_NSWSub(m_Value(VariantOp), m_Value(InvariantOp))))
2449 return false;
2450 if (!IsSigned &&
2451 !match(VariantLHS, m_NUWSub(m_Value(VariantOp), m_Value(InvariantOp))))
2452 return false;
2453
2454 bool VariantSubtracted = false;
2455 // LHS itself is a loop-variant, try to represent it in the form:
2456 // "VariantOp + InvariantOp". If it is possible, then we can reassociate. If
2457 // the variant operand goes with minus, we use a slightly different scheme.
2458 if (L.isLoopInvariant(VariantOp)) {
2459 std::swap(VariantOp, InvariantOp);
2460 VariantSubtracted = true;
2461 Pred = ICmpInst::getSwappedPredicate(Pred);
2462 }
2463 if (L.isLoopInvariant(VariantOp) || !L.isLoopInvariant(InvariantOp))
2464 return false;
2465
2466 // In order to turn "LV - C1 < C2" into "LV < C2 + C1", we need to be able to
2467 // freely move values from left side of inequality to right side (just as in
2468 // normal linear arithmetics). Overflows make things much more complicated, so
2469 // we want to avoid this. Likewise, for "C1 - LV < C2" we need to prove that
2470 // "C1 - C2" does not overflow.
2471 auto &DL = L.getHeader()->getDataLayout();
2472 SimplifyQuery SQ(DL, &Deps.DT, &Deps.AC, &ICmp);
2473 if (VariantSubtracted && IsSigned) {
2474 // C1 - LV < C2 --> LV > C1 - C2
2475 if (computeOverflowForSignedSub(InvariantOp, InvariantRHS, SQ) !=
2477 return false;
2478 } else if (VariantSubtracted && !IsSigned) {
2479 // C1 - LV < C2 --> LV > C1 - C2
2480 if (computeOverflowForUnsignedSub(InvariantOp, InvariantRHS, SQ) !=
2482 return false;
2483 } else if (!VariantSubtracted && IsSigned) {
2484 // LV - C1 < C2 --> LV < C1 + C2
2485 if (computeOverflowForSignedAdd(InvariantOp, InvariantRHS, SQ) !=
2487 return false;
2488 } else { // !VariantSubtracted && !IsSigned
2489 // LV - C1 < C2 --> LV < C1 + C2
2490 if (computeOverflowForUnsignedAdd(InvariantOp, InvariantRHS, SQ) !=
2492 return false;
2493 }
2494 auto *Preheader = L.getLoopPreheader();
2495 assert(Preheader && "Loop is not in simplify form?");
2496 IRBuilder<> Builder(Preheader->getTerminator());
2497 Value *NewCmpOp =
2498 VariantSubtracted
2499 ? Builder.CreateSub(InvariantOp, InvariantRHS, "invariant.op",
2500 /*HasNUW*/ !IsSigned, /*HasNSW*/ IsSigned)
2501 : Builder.CreateAdd(InvariantOp, InvariantRHS, "invariant.op",
2502 /*HasNUW*/ !IsSigned, /*HasNSW*/ IsSigned);
2503 ICmp.setPredicate(Pred);
2504 ICmp.setOperand(0, VariantOp);
2505 ICmp.setOperand(1, NewCmpOp);
2506 // The new LHS is a different value, so a samesign (or any other
2507 // poison-generating) flag asserted about the old operands may no longer hold.
2509
2510 Instruction &DeadI = cast<Instruction>(*VariantLHS);
2511 salvageDebugInfo(DeadI);
2512 eraseInstruction(DeadI, Deps);
2513 return true;
2514}
2515
2516/// Reassociate and hoist add/sub expressions.
2517static bool hoistAddSub(Instruction &I, Loop &L, const LICMDependencies &Deps) {
2518 using namespace PatternMatch;
2519 CmpPredicate Pred;
2520 Value *LHS, *RHS;
2521 if (!match(&I, m_ICmp(Pred, m_Value(LHS), m_Value(RHS))))
2522 return false;
2523
2524 // Put variant operand to LHS position.
2525 if (L.isLoopInvariant(LHS)) {
2526 std::swap(LHS, RHS);
2527 Pred = ICmpInst::getSwappedPredicate(Pred);
2528 }
2529 // We want to delete the initial operation after reassociation, so only do it
2530 // if it has no other uses.
2531 if (L.isLoopInvariant(LHS) || !L.isLoopInvariant(RHS) || !LHS->hasOneUse())
2532 return false;
2533
2534 // TODO: We could go with smarter context, taking common dominator of all I's
2535 // users instead of I itself.
2536 if (hoistAdd(Pred, LHS, RHS, cast<ICmpInst>(I), L, Deps))
2537 return true;
2538
2539 if (hoistSub(Pred, LHS, RHS, cast<ICmpInst>(I), L, Deps))
2540 return true;
2541
2542 return false;
2543}
2544
2545static bool isReassociableOp(Instruction *I, unsigned IntOpcode,
2546 unsigned FPOpcode) {
2547 if (I->getOpcode() == IntOpcode)
2548 return true;
2549 if (I->getOpcode() == FPOpcode && I->hasAllowReassoc() &&
2550 I->hasNoSignedZeros())
2551 return true;
2552 return false;
2553}
2554
2555/// Try to reassociate expressions like ((A1 * B1) + (A2 * B2) + ...) * C where
2556/// A1, A2, ... and C are loop invariants into expressions like
2557/// ((A1 * C * B1) + (A2 * C * B2) + ...) and hoist the (A1 * C), (A2 * C), ...
2558/// invariant expressions. This functions returns true only if any hoisting has
2559/// actually occurred.
2560static bool hoistMulAddAssociation(const ScalarOptions &Opts, Instruction &I,
2561 Loop &L, const LICMDependencies &Deps) {
2562 if (!isReassociableOp(&I, Instruction::Mul, Instruction::FMul))
2563 return false;
2564 Value *VariantOp = I.getOperand(0);
2565 Value *InvariantOp = I.getOperand(1);
2566 if (L.isLoopInvariant(VariantOp))
2567 std::swap(VariantOp, InvariantOp);
2568 if (L.isLoopInvariant(VariantOp) || !L.isLoopInvariant(InvariantOp))
2569 return false;
2570 Value *Factor = InvariantOp;
2571
2572 // First, we need to make sure we should do the transformation.
2573 SmallVector<Use *> Changes;
2576 if (BinaryOperator *VariantBinOp = dyn_cast<BinaryOperator>(VariantOp))
2577 Worklist.push_back(VariantBinOp);
2578 while (!Worklist.empty()) {
2579 BinaryOperator *BO = Worklist.pop_back_val();
2580 if (!BO->hasOneUse())
2581 return false;
2582 if (isReassociableOp(BO, Instruction::Add, Instruction::FAdd) &&
2585 Worklist.push_back(cast<BinaryOperator>(BO->getOperand(0)));
2586 Worklist.push_back(cast<BinaryOperator>(BO->getOperand(1)));
2587 Adds.push_back(BO);
2588 continue;
2589 }
2590 if (!isReassociableOp(BO, Instruction::Mul, Instruction::FMul) ||
2591 L.isLoopInvariant(BO))
2592 return false;
2593 Use &U0 = BO->getOperandUse(0);
2594 Use &U1 = BO->getOperandUse(1);
2595 if (L.isLoopInvariant(U0))
2596 Changes.push_back(&U0);
2597 else if (L.isLoopInvariant(U1))
2598 Changes.push_back(&U1);
2599 else
2600 return false;
2601 unsigned Limit = I.getType()->isIntOrIntVectorTy()
2602 ? Opts.licm_max_num_int_reassociations
2603 : Opts.licm_max_num_fp_reassociations;
2604 if (Changes.size() > Limit)
2605 return false;
2606 }
2607 if (Changes.empty())
2608 return false;
2609
2610 // Drop the poison flags for any adds we looked through.
2611 if (I.getType()->isIntOrIntVectorTy()) {
2612 for (auto *Add : Adds)
2613 Add->dropPoisonGeneratingFlags();
2614 }
2615
2616 // We know we should do it so let's do the transformation.
2617 auto *Preheader = L.getLoopPreheader();
2618 assert(Preheader && "Loop is not in simplify form?");
2619 IRBuilder<> Builder(Preheader->getTerminator());
2620 for (auto *U : Changes) {
2621 assert(L.isLoopInvariant(U->get()));
2622 auto *Ins = cast<BinaryOperator>(U->getUser());
2623 Value *Mul;
2624 if (I.getType()->isIntOrIntVectorTy()) {
2625 Mul = Builder.CreateMul(U->get(), Factor, "factor.op.mul");
2626 // Drop the poison flags on the original multiply.
2627 Ins->dropPoisonGeneratingFlags();
2628 } else
2629 Mul = Builder.CreateFMulFMF(U->get(), Factor, Ins, "factor.op.fmul");
2630
2631 // Rewrite the reassociable instruction.
2632 unsigned OpIdx = U->getOperandNo();
2633 auto *LHS = OpIdx == 0 ? Mul : Ins->getOperand(0);
2634 auto *RHS = OpIdx == 1 ? Mul : Ins->getOperand(1);
2635 auto *NewBO =
2636 BinaryOperator::Create(Ins->getOpcode(), LHS, RHS,
2637 Ins->getName() + ".reass", Ins->getIterator());
2638 NewBO->setDebugLoc(DebugLoc::getDropped());
2639 NewBO->copyIRFlags(Ins);
2640 if (VariantOp == Ins)
2641 VariantOp = NewBO;
2642 Ins->replaceAllUsesWith(NewBO);
2643 eraseInstruction(*Ins, Deps);
2644 }
2645
2646 I.replaceAllUsesWith(VariantOp);
2647 eraseInstruction(I, Deps);
2648 return true;
2649}
2650
2651/// Reassociate associative binary expressions of the form
2652///
2653/// 1. "(LV op C1) op C2" ==> "LV op (C1 op C2)"
2654/// 2. "(C1 op LV) op C2" ==> "LV op (C1 op C2)"
2655/// 3. "C2 op (C1 op LV)" ==> "LV op (C1 op C2)"
2656/// 4. "C2 op (LV op C1)" ==> "LV op (C1 op C2)"
2657///
2658/// where op is an associative BinOp, LV is a loop variant, and C1 and C2 are
2659/// loop invariants that we want to hoist, noting that associativity implies
2660/// commutativity.
2662 const LICMDependencies &Deps) {
2663 auto *BO = dyn_cast<BinaryOperator>(&I);
2664 if (!BO || !BO->isAssociative())
2665 return false;
2666
2667 Instruction::BinaryOps Opcode = BO->getOpcode();
2668 bool LVInRHS = L.isLoopInvariant(BO->getOperand(0));
2669 auto *BO0 = dyn_cast<BinaryOperator>(BO->getOperand(LVInRHS));
2670 if (!BO0 || BO0->getOpcode() != Opcode || !BO0->isAssociative() ||
2671 BO0->hasNUsesOrMore(BO0->getType()->isIntegerTy() ? 2 : 3))
2672 return false;
2673
2674 Value *LV = BO0->getOperand(0);
2675 Value *C1 = BO0->getOperand(1);
2676 Value *C2 = BO->getOperand(!LVInRHS);
2677
2678 assert(BO->isCommutative() && BO0->isCommutative() &&
2679 "Associativity implies commutativity");
2680 if (L.isLoopInvariant(LV) && !L.isLoopInvariant(C1))
2681 std::swap(LV, C1);
2682 if (L.isLoopInvariant(LV) || !L.isLoopInvariant(C1) || !L.isLoopInvariant(C2))
2683 return false;
2684
2685 auto *Preheader = L.getLoopPreheader();
2686 assert(Preheader && "Loop is not in simplify form?");
2687
2688 IRBuilder<> Builder(Preheader->getTerminator());
2689 auto *Inv = Builder.CreateBinOp(Opcode, C1, C2, "invariant.op");
2690
2691 auto *NewBO = BinaryOperator::Create(
2692 Opcode, LV, Inv, BO->getName() + ".reass", BO->getIterator());
2693 NewBO->setDebugLoc(DebugLoc::getDropped());
2694
2695 if (Opcode == Instruction::FAdd || Opcode == Instruction::FMul) {
2696 // Intersect FMF flags for FADD and FMUL.
2697 FastMathFlags Intersect = BO->getFastMathFlags() & BO0->getFastMathFlags();
2698 if (auto *I = dyn_cast<Instruction>(Inv))
2699 I->setFastMathFlags(Intersect);
2700 NewBO->setFastMathFlags(Intersect);
2701 } else {
2702 OverflowTracking Flags;
2703 Flags.AllKnownNonNegative = false;
2704 Flags.AllKnownNonZero = false;
2705 Flags.mergeFlags(*BO);
2706 Flags.mergeFlags(*BO0);
2707 // If `Inv` was not constant-folded, a new Instruction has been created.
2708 auto *InvI = dyn_cast<Instruction>(Inv);
2709 if (InvI)
2710 Flags.applyFlags(*InvI);
2711 Flags.applyFlags(*NewBO);
2712
2713 // The original nsw flags guarantee that LV + C1 + C2 is representable.
2714 // If C1 + C2 is representable too, both reassociated adds keep nsw.
2715 SimplifyQuery SQ(L.getHeader()->getDataLayout(), &Deps.DT, &Deps.AC,
2716 Preheader->getTerminator());
2717 if (Opcode == Instruction::Add && Flags.HasNSW && !Flags.HasNUW &&
2720 if (InvI)
2721 InvI->setHasNoSignedWrap();
2722 NewBO->setHasNoSignedWrap();
2723 }
2724 }
2725
2726 BO->replaceAllUsesWith(NewBO);
2727 eraseInstruction(*BO, Deps);
2728
2729 // (LV op C1) might not be erased if it has more uses than the one we just
2730 // replaced.
2731 if (BO0->use_empty()) {
2732 salvageDebugInfo(*BO0);
2733 eraseInstruction(*BO0, Deps);
2734 }
2735
2736 return true;
2737}
2738
2739/// Reassociate add/sub expressions of the form:
2740///
2741/// 1. "(LV + C1) - C2" ==> "LV + (C1 - C2)"
2742/// 2. "(LV - C1) - C2" ==> "LV - (C1 + C2)"
2743/// 3. "(LV - C1) + C2" ==> "LV + (C2 - C1)"
2744///
2745/// where LV is a loop variant, and C1 and C2 are loop invariants.
2746/// Sub is not associative, but these algebraic identities allow hoisting
2747/// invariant computations out of the loop.
2749 const LICMDependencies &Deps) {
2750 using namespace PatternMatch;
2751
2752 Instruction *BO;
2753 Value *LV, *C1, *C2;
2754 Instruction::BinaryOps InvOp, ResultOp;
2755
2756 // Try to match one of three reassociation patterns involving sub.
2757 //
2758 // 1. (LV + C1) - C2 ==> LV + (C1 - C2)
2759 // 2. (LV - C1) - C2 ==> LV - (C1 + C2)
2760 // 3. (LV - C1) + C2 ==> LV + (C2 - C1)
2761 // ^ ^
2762 // \ \___ InvOp
2763 // \
2764 // \____ ResultOp
2765 //
2766 if (match(&I,
2768 m_Value(C2)))) {
2769 // Case 1.
2770 //
2771 // Depending on which of the addition is invariant, we might need to swap
2772 // the arguments
2773 if (L.isLoopInvariant(LV) && !L.isLoopInvariant(C1))
2774 std::swap(LV, C1);
2775 InvOp = Instruction::Sub;
2776 ResultOp = Instruction::Add;
2777 } else if (match(&I, m_Sub(m_OneUse(m_Instruction(
2778 BO, m_Sub(m_Value(LV), m_Value(C1)))),
2779 m_Value(C2)))) {
2780 // Case 2.
2781 InvOp = Instruction::Add;
2782 ResultOp = Instruction::Sub;
2783 } else if (match(&I, m_c_Add(m_OneUse(m_Instruction(
2784 BO, m_Sub(m_Value(LV), m_Value(C1)))),
2785 m_Value(C2)))) {
2786 // Case 3.
2787 //
2788 // We use (C2 - C1) as the invariant as opposed to case 1, but instead of
2789 // adding a special case in invariant creation, we can just swap the
2790 // operands here.
2791 std::swap(C1, C2);
2792 InvOp = Instruction::Sub;
2793 ResultOp = Instruction::Add;
2794 } else {
2795 return false;
2796 }
2797
2798 if (L.isLoopInvariant(LV) || !L.isLoopInvariant(C1) || !L.isLoopInvariant(C2))
2799 return false;
2800
2801 auto *Preheader = L.getLoopPreheader();
2802 assert(Preheader && "Loop is not in simplify form?");
2803
2804 IRBuilder<> Builder(Preheader->getTerminator());
2805 auto *Inv = Builder.CreateBinOp(InvOp, C1, C2, "invariant.op");
2806
2807 auto *NewBO = BinaryOperator::Create(ResultOp, LV, Inv,
2808 I.getName() + ".reass", I.getIterator());
2809 NewBO->setDebugLoc(DebugLoc::getDropped());
2810
2811 // No overflow flags are set on the new instructions -- reassociation
2812 // involving sub does not preserve nsw/nuw in general.
2813
2814 I.replaceAllUsesWith(NewBO);
2815 eraseInstruction(I, Deps);
2816
2817 salvageDebugInfo(*BO);
2818 eraseInstruction(*BO, Deps);
2819
2820 return true;
2821}
2822
2823static bool hoistArithmetics(const ScalarOptions &Opts, Instruction &I, Loop &L,
2824 const LICMDependencies &Deps) {
2825 // Optimize complex patterns, such as (x < INV1 && x < INV2), turning them
2826 // into (x < min(INV1, INV2)), and hoisting the invariant part of this
2827 // expression out of the loop.
2828 if (hoistMinMax(I, L, Deps)) {
2829 ++NumHoisted;
2830 ++NumMinMaxHoisted;
2831 return true;
2832 }
2833
2834 // Try to hoist GEPs by reassociation.
2835 if (hoistGEP(I, L, Deps)) {
2836 ++NumHoisted;
2837 ++NumGEPsHoisted;
2838 return true;
2839 }
2840
2841 // Try to hoist add/sub's by reassociation.
2842 if (hoistAddSub(I, L, Deps)) {
2843 ++NumHoisted;
2844 ++NumAddSubHoisted;
2845 return true;
2846 }
2847
2848 bool IsInt = I.getType()->isIntOrIntVectorTy();
2849 if (hoistMulAddAssociation(Opts, I, L, Deps)) {
2850 ++NumHoisted;
2851 if (IsInt)
2852 ++NumIntAssociationsHoisted;
2853 else
2854 ++NumFPAssociationsHoisted;
2855 return true;
2856 }
2857
2858 if (hoistBOAssociation(I, L, Deps)) {
2859 ++NumHoisted;
2860 ++NumBOAssociationsHoisted;
2861 return true;
2862 }
2863
2864 if (hoistSubAddAssociation(I, L, Deps)) {
2865 ++NumHoisted;
2866 ++NumBOAssociationsHoisted;
2867 return true;
2868 }
2869
2870 return false;
2871}
2872
2873/// Little predicate that returns true if the specified basic block is in
2874/// a subloop of the current one, not the current one itself.
2875///
2876static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
2877 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
2878 return LI->getLoopFor(BB) != CurLoop;
2879}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Forward Handle Accesses
DXIL Resource Access
This file defines the DenseMap class.
early cse Early CSE w MemorySSA
#define DEBUG_TYPE
Hexagon Common GEP
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
iv Induction Variable Users
Definition IVUsers.cpp:48
static bool hoistMulAddAssociation(const ScalarOptions &Opts, Instruction &I, Loop &L, const LICMDependencies &Deps)
Try to reassociate expressions like ((A1 * B1) + (A2 * B2) + ...) * C where A1, A2,...
Definition LICM.cpp:2560
static bool isReassociableOp(Instruction *I, unsigned IntOpcode, unsigned FPOpcode)
Definition LICM.cpp:2545
static bool isNotUsedOrFoldableInLoop(const Instruction &I, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo, TargetTransformInfo *TTI, bool &FoldableInLoop, bool LoopNestMode)
Return true if the only users of this instruction are outside of the loop.
Definition LICM.cpp:1070
static bool hoistAdd(ICmpInst::Predicate Pred, Value *VariantLHS, Value *InvariantRHS, ICmpInst &ICmp, Loop &L, const LICMDependencies &Deps)
Try to turn things like "LV + C1 < C2" into "LV < C2 - C1".
Definition LICM.cpp:2376
static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT, LoopInfo *LI, const Loop *CurLoop, LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU)
Definition LICM.cpp:1244
static bool isFoldableInLoop(const Instruction &I, const Loop *CurLoop, const TargetTransformInfo *TTI)
Return true if the instruction is foldable in the loop.
Definition LICM.cpp:1040
static void moveInstructionBefore(Instruction &I, BasicBlock::iterator Dest, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, ScalarEvolution *SE)
Definition LICM.cpp:1196
static Instruction * cloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI, const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU)
Definition LICM.cpp:1113
static MemoryAccess * getClobberingMemoryAccess(MemorySSA &MSSA, BatchAAResults &BAA, SinkAndHoistLICMFlags &Flags, MemoryUseOrDef *MA)
Definition LICM.cpp:885
static bool pointerInvalidatedByLoop(const SinkAndHoistDependencies &Deps, MemoryUse *MU, Loop *CurLoop, Instruction &I, SinkAndHoistLICMFlags &Flags, bool InvariantGroup)
Definition LICM.cpp:2175
static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU, ScalarEvolution *SE, OptimizationRemarkEmitter *ORE)
When an instruction is found to only use loop invariant operands that is safe to hoist,...
Definition LICM.cpp:1423
static bool sink(Instruction &I, const LICMDependencies &Deps, const Loop *CurLoop)
When an instruction is found to only be used outside of the loop, this function moves it to the exit ...
Definition LICM.cpp:1316
static SmallVector< PointersAndHasReadsOutsideSet, 0 > collectPromotionCandidates(MemorySSA *MSSA, AliasAnalysis *AA, DominatorTree *DT, ICFLoopSafetyInfo *SafetyInfo, const SmallPtrSetImpl< const MDNode * > &LoopLocalAliasScopes, Loop *L)
Definition LICM.cpp:2053
static bool hoistGEP(Instruction &I, Loop &L, const LICMDependencies &Deps)
Reassociate gep (gep ptr, idx1), idx2 to gep (gep ptr, idx2), idx1 if this allows hoisting the inner ...
Definition LICM.cpp:2320
static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo)
Definition LICM.cpp:1226
static bool isPotentiallyPromotable(const Instruction *I, const Loop *L)
Returns whether I is a memory access that may be a candidate for promotion out of the loop L.
Definition LICM.cpp:1984
static SmallPtrSet< const StoreInst *, 8 > collectStoresWithInvariantAATags(MemorySSA *MSSA, DominatorTree *DT, const SmallPtrSetImpl< const MDNode * > &LoopLocalAliasScopes, Loop *L)
Returns the potentially promotable stores with AA tags that are valid along all non-unwinding executi...
Definition LICM.cpp:2012
static bool isOnlyMemoryAccess(const Instruction *I, const Loop *L, const MemorySSAUpdater &MSSAU)
Return true if I is the only Instruction with a MemoryAccess in L.
Definition LICM.cpp:869
static void foreachMemoryAccess(MemorySSA *MSSA, Loop *L, function_ref< void(Instruction *)> Fn)
Definition LICM.cpp:1973
static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT, Loop *CurLoop)
Definition LICM.cpp:799
static bool hoistInsertPastInsert(InsertElementInst *Ins, Loop *CurLoop, DominatorTree *DT, BasicBlock *HoistDest, ICFLoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU, ScalarEvolution *SE, OptimizationRemarkEmitter *ORE)
Definition LICM.cpp:740
static bool isHoistableAndSinkableInst(Instruction &I)
Return true if-and-only-if we know how to (mechanically) both hoist and sink a given instruction out ...
Definition LICM.cpp:857
static Instruction * sinkThroughTriviallyReplaceablePHI(PHINode *TPN, Instruction *I, LoopInfo *LI, SmallDenseMap< BasicBlock *, Instruction *, 32 > &SunkCopies, const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop, MemorySSAUpdater &MSSAU)
Definition LICM.cpp:1211
static bool hasAnyMDOperandsFrom(const MDNode *N, const SmallPtrSetImpl< const MDNode * > &Operands)
Returns whether N has any operand from the set Operands.
Definition LICM.cpp:2002
static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI)
Little predicate that returns true if the specified basic block is in a subloop of the current one,...
Definition LICM.cpp:2876
static bool hoistArithmetics(const ScalarOptions &Opts, Instruction &I, Loop &L, const LICMDependencies &Deps)
Aggregates various functions for hoisting computations out of loop.
Definition LICM.cpp:2823
static bool isSafeToExecuteUnconditionally(Instruction &Inst, const DominatorTree *DT, const TargetLibraryInfo *TLI, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE, const Instruction *CtxI, AssumptionCache *AC, bool AllowSpeculation)
Only sink or hoist an instruction if it is not a trapping instruction, or if the instruction is known...
Definition LICM.cpp:1470
static void eraseInstruction(Instruction &I, const LICMDependencies &Deps)
Definition LICM.cpp:1190
static bool noConflictingReadWrites(Instruction *I, MemorySSA *MSSA, AAResults *AA, Loop *CurLoop, SinkAndHoistLICMFlags &Flags)
Definition LICM.cpp:2135
static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I)
Returns true if a PHINode is a trivially replaceable with an Instruction.
Definition LICM.cpp:1031
std::pair< SmallSetVector< Value *, 8 >, bool > PointersAndHasReadsOutsideSet
Definition LICM.cpp:177
static bool hoistMinMax(Instruction &I, Loop &L, const LICMDependencies &Deps)
Try to simplify things like (A < INV_1 AND icmp A < INV_2) into (A < min(INV_1, INV_2)),...
Definition LICM.cpp:2240
static bool hoistSubAddAssociation(Instruction &I, Loop &L, const LICMDependencies &Deps)
Reassociate add/sub expressions of the form:
Definition LICM.cpp:2748
static bool hoistAddSub(Instruction &I, Loop &L, const LICMDependencies &Deps)
Reassociate and hoist add/sub expressions.
Definition LICM.cpp:2517
static bool hoistSub(ICmpInst::Predicate Pred, Value *VariantLHS, Value *InvariantRHS, ICmpInst &ICmp, Loop &L, const LICMDependencies &Deps)
Try to reassociate and hoist the following two patterns: LV - C1 < C2 --> LV < C1 + C2,...
Definition LICM.cpp:2436
static std::optional< uint64_t > getConstantInsertionIndex(InsertElementInst *Ins)
Definition LICM.cpp:725
static bool pointerInvalidatedByBlock(BasicBlock &BB, MemorySSA &MSSA, MemoryUse &MU)
Definition LICM.cpp:2228
static bool hoistBOAssociation(Instruction &I, Loop &L, const LICMDependencies &Deps)
Reassociate associative binary expressions of the form.
Definition LICM.cpp:2661
This file defines the interface for the loop nest analysis.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
Memory SSA
Definition MemorySSA.cpp:69
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
This file contains the declarations for metadata subclasses.
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
uint64_t IntrinsicInst * II
#define P(N)
if(PassOpts->AAPipeline)
PassInstrumentationCallbacks PIC
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file provides a priority worklist.
int64_t C1
Remove Loads Into Fake Uses
SI Fold Operands
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
BinaryOperator * Mul
LLVM_ABI ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, bool IgnoreLocals=false)
Returns a bitmask that should be unconditionally applied to the ModRef info of a memory location.
LLVM_ABI MemoryEffects getMemoryEffects(const CallBase *Call)
Return the behavior of the given call site.
LLVM_ABI void addWithoutAATags(StoreInst *SI)
LLVM_ABI void add(const MemoryLocation &Loc)
These methods are used to add different types of instructions to the alias sets.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI bool canSplitPredecessors() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Definition InstrTypes.h:831
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isNegative() const
Definition Constants.h:214
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:579
static LLVM_ABI DebugLoc getMergedLocations(ArrayRef< DebugLoc > Locs)
Try to combine the vector of locations passed as input in a single one.
Definition DebugLoc.cpp:173
static DebugLoc getDropped()
Definition DebugLoc.h:155
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
This implementation of LoopSafetyInfo use ImplicitControlFlowTracking to give precise answers on "may...
bool doesNotWriteMemoryBefore(const BasicBlock *BB) const
Returns true if we could not execute a memory-modifying instruction before we enter BB under assumpti...
bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT) const override
Returns true if the instruction in a loop is guaranteed to execute at least once (under the assumptio...
void removeInstruction(const Instruction *Inst)
Inform safety info that we are planning to remove the instruction Inst from its block.
bool anyBlockMayThrow() const override
Returns true iff any block of the loop for which this info is contains an instruction that may throw ...
void insertInstructionTo(const Instruction *Inst, const BasicBlock *BB)
Inform the safety info that we are planning to insert a new instruction Inst into the basic block BB.
This instruction compares its operands according to the predicate given to the constructor.
static bool isGE(Predicate P)
Return true if the predicate is SGE or UGE.
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
This instruction inserts a single (scalar) element into a VectorType value.
VectorType * getType() const
Overload to return most specific vector type.
LLVM_ABI void mergeDIAssignID(ArrayRef< const Instruction * > SourceInstructions)
Merge the DIAssignID metadata from this instruction and those attached to instructions in SourceInstr...
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
user_iterator_impl< Instruction > user_iterator
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
Instruction * user_back()
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition LICM.cpp:285
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
Definition LICM.cpp:260
LLVM_ABI PreservedAnalyses run(LoopNest &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
Definition LICM.cpp:295
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition LICM.cpp:328
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
static void getLazyBFIAnalysisUsage(AnalysisUsage &AU)
Helper for client passes to set up the analysis usage on behalf of this pass.
Helper class for promoting a collection of loads and stores into SSA Form using the SSAUpdater.
Definition SSAUpdater.h:149
An instruction for reading from memory.
void setAlignment(Align Align)
Value * getPointerOperand()
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this load instruction.
bool isUnordered() const
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getHeader() const
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
void getUniqueExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all unique successor blocks of this loop.
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI bool wouldBeOutOfLoopUseRequiringLCSSA(const Value *V, const BasicBlock *ExitBB) const
This class represents a loop nest and can be used to query its properties.
Function * getParent() const
Return the function to which the loop-nest belongs.
Loop & getOutermostLoop() const
Return the outermost loop in the loop nest.
Captures loop safety information.
Definition MustExecute.h:55
LLVM_ABI void copyColors(BasicBlock *New, BasicBlock *Old)
Copy colors of block Old into the block New.
LLVM_ABI const DenseMap< BasicBlock *, ColorVector > & getBlockColors() const
Returns block colors map that is used to update funclet operand bundles.
virtual bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT) const =0
Returns true if the instruction in a loop is guaranteed to execute at least once (under the assumptio...
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
Definition LoopInfo.cpp:74
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:68
Metadata node.
Definition Metadata.h:1081
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
BasicBlock * getBlock() const
Definition MemorySSA.h:163
bool onlyWritesMemory() const
Whether this function only (at most) writes memory.
Definition ModRef.h:252
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:246
bool onlyReadsMemory() const
Whether this function only (at most) reads memory.
Definition ModRef.h:249
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:917
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
LLVM_ABI void insertDef(MemoryDef *Def, bool RenameUses=false)
Insert a definition into the MemorySSA IR.
LLVM_ABI void insertUse(MemoryUse *Use, bool RenameUses=false)
LLVM_ABI MemoryAccess * createMemoryAccessInBB(Instruction *I, MemoryAccess *Definition, const BasicBlock *BB, MemorySSA::InsertionPlace Point, bool CreationMustSucceed=true)
Create a MemoryAccess in MemorySSA at a specified point in a block.
LLVM_ABI void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
LLVM_ABI MemoryUseOrDef * createMemoryAccessAfter(Instruction *I, MemoryAccess *Definition, MemoryAccess *InsertPt)
Create a MemoryAccess in MemorySSA after an existing MemoryAccess.
LLVM_ABI void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, MemorySSA::InsertionPlace Where)
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Definition MemorySSA.h:1030
Legacy analysis pass which computes MemorySSA.
Definition MemorySSA.h:970
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:696
AliasAnalysis & getAA()
Definition MemorySSA.h:794
DefsList * getBlockDefs(const BasicBlock *BB) const
Return the list of MemoryDef's and MemoryPhi's for a given basic block.
Definition MemorySSA.h:759
LLVM_ABI MemorySSAWalker * getSkipSelfWalker()
AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
Definition MemorySSA.h:752
LLVM_ABI bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:714
LLVM_ABI bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in the same basic block, determine whether MemoryAccess A dominates MemoryA...
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Definition MemorySSA.h:734
Class that has the common methods + fields of memory uses/defs.
Definition MemorySSA.h:251
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
Definition MemorySSA.h:261
Represents read-only accesses to memory.
Definition MemorySSA.h:311
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
PointerIntPair - This class implements a pair of a pointer and small integer.
void setInt(IntType IntVal) &
PointerTy getPointer() const
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
PredIteratorCache - This class is an extremely trivial cache for predecessor iterator queries.
size_t size(BasicBlock *BB)
ArrayRef< BasicBlock * > get(BasicBlock *BB)
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
bool empty() const
Determine if the PriorityWorklist is empty or not.
bool insert(const T &X)
Insert a new element into the PriorityWorklist.
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition SSAUpdater.h:39
The main scalar evolution driver.
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI void forgetLoopDispositions()
Called when the client has changed the disposition of values in this loop.
bool remove(const value_type &X)
Remove an item from the set vector.
Definition SetVector.h:187
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
iterator begin()
Get an iterator to the beginning of the SetVector.
Definition SetVector.h:112
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
Flags controlling how much is checked when sinking or hoisting instructions.
Definition LoopUtils.h:126
LLVM_ABI SinkAndHoistLICMFlags(unsigned LicmMssaOptCap, unsigned LicmMssaNoAccForPromotionCap, bool IsSink, Loop &L, MemorySSA &MSSA)
Definition LICM.cpp:357
unsigned LicmMssaNoAccForPromotionCap
Definition LoopUtils.h:145
A version of PriorityWorklist that selects small size optimized data structures for the vector and ma...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
void setAlignment(Align Align)
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this store instruction.
static unsigned getPointerOperandIndex()
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Provides information about what library functions are available for the current target.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCC_Free
Expected to fold away in lowering.
EltTy front() const
unsigned size() const
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
const Use & getOperandUse(unsigned i) const
Definition User.h:220
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
Definition Value.cpp:159
LLVM_ABI std::string getNameOrAsOperand() const
Definition Value.cpp:457
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
iterator_range< user_iterator > users()
Definition Value.h:428
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Abstract Attribute helper functions.
Definition Attributor.h:164
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
constexpr MCPhysReg SP
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
DiagnosticInfoOptimizationBase::Argument NV
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ NeverOverflows
Never overflows.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI unsigned getLicmMssaNoAccForPromotionCap(const cl::LibraryOptionsContext *LibraryOptions)
Returns -licm-mssa-max-acc-promotion of LibraryOptions, or its global value if null.
Definition LICM.cpp:125
LLVM_ABI bool sinkRegionForLoopNest(DomTreeNode *, const LICMDependencies &, Loop *, SinkAndHoistLICMFlags &)
Call sinkRegion on loops contained within the specified loop in order from innermost to outermost.
Definition LICM.cpp:593
auto pred_end(const MachineBasicBlock *BB)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isStrongerThanMonotonic(AtomicOrdering AO)
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1697
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
constexpr from_range_t from_range
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition LCSSA.cpp:469
LLVM_ABI bool canHoistLoad(LoadInst &LI, const SinkAndHoistDependencies &Deps, Loop *CurLoop, bool TargetExecutesOncePerLoop, SinkAndHoistLICMFlags &LICMFlags)
Returns true if it is legal to hoist LI out of CurLoop.
Definition LICM.cpp:899
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
auto cast_or_null(const Y &Val)
Definition Casting.h:714
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
const ScalarOptions & getScalarOptions(const LLVMContext &C)
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI bool PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures, const Instruction *I, const DominatorTree *DT, bool IncludeI=false, unsigned MaxUsesToExplore=0, const LoopInfo *LI=nullptr)
PointerMayBeCapturedBefore - Return true if this pointer value may be captured by the enclosing funct...
LLVM_ABI Pass * createLICMPass()
Definition LICM.cpp:349
LLVM_ABI SmallVector< BasicBlock *, 16 > collectChildrenInLoop(DominatorTree *DT, DomTreeNode *N, const Loop *CurLoop)
Does a BFS from a given node to all of its children inside a given loop.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:408
LLVM_ABI unsigned getLicmMssaOptCap(const cl::LibraryOptionsContext *LibraryOptions)
Returns -licm-mssa-optimization-cap of LibraryOptions, or its global value if null.
Definition LICM.cpp:120
LLVM_ABI bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI void initializeLegacyLICMPassPass(PassRegistry &)
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool canSinkOrHoistInst(Instruction &I, const SinkAndHoistDependencies &Deps, Loop *CurLoop, bool TargetExecutesOncePerLoop, SinkAndHoistLICMFlags &LICMFlags)
Returns true if is legal to hoist or sink this instruction disregarding the possible introduction of ...
Definition LICM.cpp:939
LLVM_TEMPLATE_ABI void appendLoopsToWorklist(RangeT &&, SmallPriorityWorklist< Loop *, 4 > &)
Utility that implements appending of loops onto a worklist given a range.
LLVM_ABI bool sinkRegion(DomTreeNode *, const LICMDependencies &, Loop *CurLoop, SinkAndHoistLICMFlags &, Loop *OutermostLoop=nullptr)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block,...
Definition LICM.cpp:530
LLVM_ABI bool isNotVisibleOnUnwind(const Value *Object, bool &RequiresNoCaptureBeforeUnwind)
Return true if Object memory is not visible after an unwind, in the sense that program semantics cann...
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:76
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
TargetTransformInfo TTI
LLVM_ABI bool salvageKnowledge(Instruction *I, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Calls BuildAssumeFromInst and if the resulting llvm.assume is valid insert if before I.
LLVM_ABI bool hasDisableLICMTransformsHint(const Loop *L)
Look for the loop attribute that disables the LICM transformation heuristics.
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
@ Add
Sum of integers.
DWARFExpression::Operation Op
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:246
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool isIdentifiedFunctionLocal(const Value *V)
Return true if V is umabigously identified at the function-level.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
TinyPtrVector< BasicBlock * > ColorVector
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
auto predecessors(const MachineBasicBlock *BB)
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
LLVM_ABI OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const SimplifyQuery &Q, bool IgnoreFree=false)
Equivalent to isDereferenceableAndAlignedPointer with an alignment of 1.
Definition Loads.cpp:266
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
bool isNoModRef(const ModRefInfo MRI)
Definition ModRef.h:40
LLVM_ABI bool promoteLoopAccessesToScalars(const SmallSetVector< Value *, 8 > &, SmallVectorImpl< BasicBlock * > &, SmallVectorImpl< BasicBlock::iterator > &, SmallVectorImpl< MemoryAccess * > &, PredIteratorCache &, const LICMDependencies &, Loop *, bool AllowSpeculation, bool HasReadsOutsideSet)
Try to promote memory values to scalars by sinking stores out of the loop and moving loads to before ...
Definition LICM.cpp:1655
LLVM_ABI bool hoistRegion(DomTreeNode *, const LICMDependencies &, Loop *, SinkAndHoistLICMFlags &, bool LoopNestMode, bool AllowSpeculation)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block,...
Definition LICM.cpp:613
bool isRefSet(const ModRefInfo MRI)
Definition ModRef.h:52
LLVM_ABI bool isWritableObject(const Value *Object, bool &ExplicitlyDereferenceableOnly)
Return true if the Object is writable, in the sense that any location based on this pointer that can ...
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:774
LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Dependencies required by LICM transforms.
Definition LoopUtils.h:158
ICFLoopSafetyInfo & SafetyInfo
Definition LoopUtils.h:164
TargetTransformInfo & TTI
Definition LoopUtils.h:162
ScalarEvolution * SE
Definition LoopUtils.h:163
TargetLibraryInfo & TLI
Definition LoopUtils.h:161
AssumptionCache & AC
Definition LoopUtils.h:159
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
A lightweight accessor for an operand bundle meant to be passed around by value.
uint32_t getTagID() const
Return the tag of this operand bundle as an integer.
Dependencies required to check legality of sinking and hoisting.
Definition LoopUtils.h:150
OptimizationRemarkEmitter * ORE
Definition LoopUtils.h:154
MemorySSAUpdater & MSSAU
Definition LoopUtils.h:153