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