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