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