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