Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Transforms/Scalar/LICM.cpp
Line
Count
Source (jump to first uncovered line)
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
// This pass uses alias analysis for two purposes:
16
//
17
//  1. Moving loop invariant loads and calls out of loops.  If we can determine
18
//     that a load or call inside of a loop never aliases anything stored to,
19
//     we can hoist it or sink it like any other instruction.
20
//  2. Scalar Promotion of Memory - If there is a store instruction inside of
21
//     the loop, we try to move the store to happen AFTER the loop instead of
22
//     inside of the loop.  This can only happen if a few conditions are true:
23
//       A. The pointer stored through is loop invariant
24
//       B. There are no stores or loads in the loop which _may_ alias the
25
//          pointer.  There are no calls in the loop which mod/ref the pointer.
26
//     If these conditions are true, we can promote the loads and stores in the
27
//     loop of the pointer to use a temporary alloca'd variable.  We then use
28
//     the SSAUpdater to construct the appropriate SSA form for the value.
29
//
30
//===----------------------------------------------------------------------===//
31
32
#include "llvm/Transforms/Scalar/LICM.h"
33
#include "llvm/ADT/SetOperations.h"
34
#include "llvm/ADT/Statistic.h"
35
#include "llvm/Analysis/AliasAnalysis.h"
36
#include "llvm/Analysis/AliasSetTracker.h"
37
#include "llvm/Analysis/BasicAliasAnalysis.h"
38
#include "llvm/Analysis/CaptureTracking.h"
39
#include "llvm/Analysis/ConstantFolding.h"
40
#include "llvm/Analysis/GlobalsModRef.h"
41
#include "llvm/Analysis/GuardUtils.h"
42
#include "llvm/Analysis/Loads.h"
43
#include "llvm/Analysis/LoopInfo.h"
44
#include "llvm/Analysis/LoopIterator.h"
45
#include "llvm/Analysis/LoopPass.h"
46
#include "llvm/Analysis/MemoryBuiltins.h"
47
#include "llvm/Analysis/MemorySSA.h"
48
#include "llvm/Analysis/MemorySSAUpdater.h"
49
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
50
#include "llvm/Analysis/ScalarEvolution.h"
51
#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
52
#include "llvm/Analysis/TargetLibraryInfo.h"
53
#include "llvm/Analysis/ValueTracking.h"
54
#include "llvm/IR/CFG.h"
55
#include "llvm/IR/Constants.h"
56
#include "llvm/IR/DataLayout.h"
57
#include "llvm/IR/DebugInfoMetadata.h"
58
#include "llvm/IR/DerivedTypes.h"
59
#include "llvm/IR/Dominators.h"
60
#include "llvm/IR/Instructions.h"
61
#include "llvm/IR/IntrinsicInst.h"
62
#include "llvm/IR/LLVMContext.h"
63
#include "llvm/IR/Metadata.h"
64
#include "llvm/IR/PatternMatch.h"
65
#include "llvm/IR/PredIteratorCache.h"
66
#include "llvm/Support/CommandLine.h"
67
#include "llvm/Support/Debug.h"
68
#include "llvm/Support/raw_ostream.h"
69
#include "llvm/Transforms/Scalar.h"
70
#include "llvm/Transforms/Scalar/LoopPassManager.h"
71
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
72
#include "llvm/Transforms/Utils/Local.h"
73
#include "llvm/Transforms/Utils/LoopUtils.h"
74
#include "llvm/Transforms/Utils/SSAUpdater.h"
75
#include <algorithm>
76
#include <utility>
77
using namespace llvm;
78
79
143
#define DEBUG_TYPE "licm"
80
81
STATISTIC(NumCreatedBlocks, "Number of blocks created");
82
STATISTIC(NumClonedBranches, "Number of branches cloned");
83
STATISTIC(NumSunk, "Number of instructions sunk out of loop");
84
STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
85
STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
86
STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
87
STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
88
89
/// Memory promotion is enabled by default.
90
static cl::opt<bool>
91
    DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),
92
                     cl::desc("Disable memory promotion in LICM pass"));
93
94
static cl::opt<bool> ControlFlowHoisting(
95
    "licm-control-flow-hoisting", cl::Hidden, cl::init(false),
96
    cl::desc("Enable control flow (and PHI) hoisting in LICM"));
97
98
static cl::opt<uint32_t> MaxNumUsesTraversed(
99
    "licm-max-num-uses-traversed", cl::Hidden, cl::init(8),
100
    cl::desc("Max num uses visited for identifying load "
101
             "invariance in loop using invariant start (default = 8)"));
102
103
// Default value of zero implies we use the regular alias set tracker mechanism
104
// instead of the cross product using AA to identify aliasing of the memory
105
// location we are interested in.
106
static cl::opt<int>
107
LICMN2Theshold("licm-n2-threshold", cl::Hidden, cl::init(0),
108
               cl::desc("How many instruction to cross product using AA"));
109
110
// Experimental option to allow imprecision in LICM in pathological cases, in
111
// exchange for faster compile. This is to be removed if MemorySSA starts to
112
// address the same issue. This flag applies only when LICM uses MemorySSA
113
// instead on AliasSetTracker. LICM calls MemorySSAWalker's
114
// getClobberingMemoryAccess, up to the value of the Cap, getting perfect
115
// accuracy. Afterwards, LICM will call into MemorySSA's getDefiningAccess,
116
// which may not be precise, since optimizeUses is capped. The result is
117
// correct, but we may not get as "far up" as possible to get which access is
118
// clobbering the one queried.
119
cl::opt<unsigned> llvm::SetLicmMssaOptCap(
120
    "licm-mssa-optimization-cap", cl::init(100), cl::Hidden,
121
    cl::desc("Enable imprecision in LICM in pathological cases, in exchange "
122
             "for faster compile. Caps the MemorySSA clobbering calls."));
123
124
// Experimentally, memory promotion carries less importance than sinking and
125
// hoisting. Limit when we do promotion when using MemorySSA, in order to save
126
// compile time.
127
cl::opt<unsigned> llvm::SetLicmMssaNoAccForPromotionCap(
128
    "licm-mssa-max-acc-promotion", cl::init(250), cl::Hidden,
129
    cl::desc("[LICM & MemorySSA] When MSSA in LICM is disabled, this has no "
130
             "effect. When MSSA in LICM is enabled, then this is the maximum "
131
             "number of accesses allowed to be present in a loop in order to "
132
             "enable memory promotion."));
133
134
static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
135
static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
136
                                  const LoopSafetyInfo *SafetyInfo,
137
                                  TargetTransformInfo *TTI, bool &FreeInLoop);
138
static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
139
                  BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,
140
                  MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE);
141
static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
142
                 const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo,
143
                 MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE);
144
static bool isSafeToExecuteUnconditionally(Instruction &Inst,
145
                                           const DominatorTree *DT,
146
                                           const Loop *CurLoop,
147
                                           const LoopSafetyInfo *SafetyInfo,
148
                                           OptimizationRemarkEmitter *ORE,
149
                                           const Instruction *CtxI = nullptr);
150
static bool pointerInvalidatedByLoop(MemoryLocation MemLoc,
151
                                     AliasSetTracker *CurAST, Loop *CurLoop,
152
                                     AliasAnalysis *AA);
153
static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU,
154
                                             Loop *CurLoop,
155
                                             SinkAndHoistLICMFlags &Flags);
156
static Instruction *CloneInstructionInExitBlock(
157
    Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,
158
    const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU);
159
160
static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo,
161
                             AliasSetTracker *AST, MemorySSAUpdater *MSSAU);
162
163
static void moveInstructionBefore(Instruction &I, Instruction &Dest,
164
                                  ICFLoopSafetyInfo &SafetyInfo,
165
                                  MemorySSAUpdater *MSSAU);
166
167
namespace {
168
struct LoopInvariantCodeMotion {
169
  using ASTrackerMapTy = DenseMap<Loop *, std::unique_ptr<AliasSetTracker>>;
170
  bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
171
                 TargetLibraryInfo *TLI, TargetTransformInfo *TTI,
172
                 ScalarEvolution *SE, MemorySSA *MSSA,
173
                 OptimizationRemarkEmitter *ORE, bool DeleteAST);
174
175
312k
  ASTrackerMapTy &getLoopToAliasSetMap() { return LoopToAliasSetMap; }
176
  LoopInvariantCodeMotion(unsigned LicmMssaOptCap,
177
                          unsigned LicmMssaNoAccForPromotionCap)
178
      : LicmMssaOptCap(LicmMssaOptCap),
179
44.1k
        LicmMssaNoAccForPromotionCap(LicmMssaNoAccForPromotionCap) {}
180
181
private:
182
  ASTrackerMapTy LoopToAliasSetMap;
183
  unsigned LicmMssaOptCap;
184
  unsigned LicmMssaNoAccForPromotionCap;
185
186
  std::unique_ptr<AliasSetTracker>
187
  collectAliasInfoForLoop(Loop *L, LoopInfo *LI, AliasAnalysis *AA);
188
  std::unique_ptr<AliasSetTracker>
189
  collectAliasInfoForLoopWithMSSA(Loop *L, AliasAnalysis *AA,
190
                                  MemorySSAUpdater *MSSAU);
191
};
192
193
struct LegacyLICMPass : public LoopPass {
194
  static char ID; // Pass identification, replacement for typeid
195
  LegacyLICMPass(
196
      unsigned LicmMssaOptCap = SetLicmMssaOptCap,
197
      unsigned LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap)
198
43.6k
      : LoopPass(ID), LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap) {
199
43.6k
    initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
200
43.6k
  }
201
202
608k
  bool runOnLoop(Loop *L, LPPassManager &LPM) override {
203
608k
    if (skipLoop(L)) {
204
55
      // If we have run LICM on a previous loop but now we are skipping
205
55
      // (because we've hit the opt-bisect limit), we need to clear the
206
55
      // loop alias information.
207
55
      LICM.getLoopToAliasSetMap().clear();
208
55
      return false;
209
55
    }
210
608k
211
608k
    auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
212
608k
    MemorySSA *MSSA = EnableMSSALoopDependency
213
608k
                          ? 
(&getAnalysis<MemorySSAWrapperPass>().getMSSA())103
214
608k
                          : 
nullptr608k
;
215
608k
    // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
216
608k
    // pass.  Function analyses need to be preserved across loop transformations
217
608k
    // but ORE cannot be preserved (see comment before the pass definition).
218
608k
    OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
219
608k
    return LICM.runOnLoop(L,
220
608k
                          &getAnalysis<AAResultsWrapperPass>().getAAResults(),
221
608k
                          &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
222
608k
                          &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
223
608k
                          &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
224
608k
                          &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
225
608k
                              *L->getHeader()->getParent()),
226
608k
                          SE ? &SE->getSE() : 
nullptr0
, MSSA, &ORE, false);
227
608k
  }
228
229
  /// This transformation requires natural loop information & requires that
230
  /// loop preheaders be inserted into the CFG...
231
  ///
232
43.5k
  void getAnalysisUsage(AnalysisUsage &AU) const override {
233
43.5k
    AU.addPreserved<DominatorTreeWrapperPass>();
234
43.5k
    AU.addPreserved<LoopInfoWrapperPass>();
235
43.5k
    AU.addRequired<TargetLibraryInfoWrapperPass>();
236
43.5k
    if (EnableMSSALoopDependency) {
237
14
      AU.addRequired<MemorySSAWrapperPass>();
238
14
      AU.addPreserved<MemorySSAWrapperPass>();
239
14
    }
240
43.5k
    AU.addRequired<TargetTransformInfoWrapperPass>();
241
43.5k
    getLoopAnalysisUsage(AU);
242
43.5k
  }
243
244
  using llvm::Pass::doFinalization;
245
246
212k
  bool doFinalization() override {
247
212k
    auto &AliasSetMap = LICM.getLoopToAliasSetMap();
248
212k
    // All loops in the AliasSetMap should be cleaned up already. The only case
249
212k
    // where we fail to do so is if an outer loop gets deleted before LICM
250
212k
    // visits it.
251
212k
    assert(all_of(AliasSetMap,
252
212k
                  [](LoopInvariantCodeMotion::ASTrackerMapTy::value_type &KV) {
253
212k
                    return !KV.first->getParentLoop();
254
212k
                  }) &&
255
212k
           "Didn't free loop alias sets");
256
212k
    AliasSetMap.clear();
257
212k
    return false;
258
212k
  }
259
260
private:
261
  LoopInvariantCodeMotion LICM;
262
263
  /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
264
  void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
265
                               Loop *L) override;
266
267
  /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
268
  /// set.
269
  void deleteAnalysisValue(Value *V, Loop *L) override;
270
271
  /// Simple Analysis hook. Delete loop L from alias set map.
272
  void deleteAnalysisLoop(Loop *L) override;
273
};
274
} // namespace
275
276
PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM,
277
560
                                LoopStandardAnalysisResults &AR, LPMUpdater &) {
278
560
  const auto &FAM =
279
560
      AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
280
560
  Function *F = L.getHeader()->getParent();
281
560
282
560
  auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
283
560
  // FIXME: This should probably be optional rather than required.
284
560
  if (!ORE)
285
0
    report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not "
286
0
                       "cached at a higher level");
287
560
288
560
  LoopInvariantCodeMotion LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap);
289
560
  if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.TTI, &AR.SE,
290
560
                      AR.MSSA, ORE, true))
291
273
    return PreservedAnalyses::all();
292
287
293
287
  auto PA = getLoopPassPreservedAnalyses();
294
287
295
287
  PA.preserve<DominatorTreeAnalysis>();
296
287
  PA.preserve<LoopAnalysis>();
297
287
  if (EnableMSSALoopDependency)
298
48
    PA.preserve<MemorySSAAnalysis>();
299
287
300
287
  return PA;
301
287
}
302
303
char LegacyLICMPass::ID = 0;
304
48.9k
INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
305
48.9k
                      false, false)
306
48.9k
INITIALIZE_PASS_DEPENDENCY(LoopPass)
307
48.9k
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
308
48.9k
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
309
48.9k
INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
310
48.9k
INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
311
                    false)
312
313
4.32k
Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
314
Pass *llvm::createLICMPass(unsigned LicmMssaOptCap,
315
39.1k
                           unsigned LicmMssaNoAccForPromotionCap) {
316
39.1k
  return new LegacyLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap);
317
39.1k
}
318
319
/// Hoist expressions out of the specified loop. Note, alias info for inner
320
/// loop is not preserved so it is not a good idea to run LICM multiple
321
/// times on one loop.
322
/// We should delete AST for inner loops in the new pass manager to avoid
323
/// memory leak.
324
///
325
bool LoopInvariantCodeMotion::runOnLoop(
326
    Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
327
    TargetLibraryInfo *TLI, TargetTransformInfo *TTI, ScalarEvolution *SE,
328
608k
    MemorySSA *MSSA, OptimizationRemarkEmitter *ORE, bool DeleteAST) {
329
608k
  bool Changed = false;
330
608k
331
608k
  assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
332
608k
333
608k
  std::unique_ptr<AliasSetTracker> CurAST;
334
608k
  std::unique_ptr<MemorySSAUpdater> MSSAU;
335
608k
  bool NoOfMemAccTooLarge = false;
336
608k
  unsigned LicmMssaOptCounter = 0;
337
608k
338
608k
  if (!MSSA) {
339
608k
    LLVM_DEBUG(dbgs() << "LICM: Using Alias Set Tracker.\n");
340
608k
    CurAST = collectAliasInfoForLoop(L, LI, AA);
341
608k
  } else {
342
157
    LLVM_DEBUG(dbgs() << "LICM: Using MemorySSA.\n");
343
157
    MSSAU = make_unique<MemorySSAUpdater>(MSSA);
344
157
345
157
    unsigned AccessCapCount = 0;
346
464
    for (auto *BB : L->getBlocks()) {
347
464
      if (auto *Accesses = MSSA->getBlockAccesses(BB)) {
348
557
        for (const auto &MA : *Accesses) {
349
557
          (void)MA;
350
557
          AccessCapCount++;
351
557
          if (AccessCapCount > LicmMssaNoAccForPromotionCap) {
352
0
            NoOfMemAccTooLarge = true;
353
0
            break;
354
0
          }
355
557
        }
356
314
      }
357
464
      if (NoOfMemAccTooLarge)
358
0
        break;
359
464
    }
360
157
  }
361
608k
362
608k
  // Get the preheader block to move instructions into...
363
608k
  BasicBlock *Preheader = L->getLoopPreheader();
364
608k
365
608k
  // Compute loop safety information.
366
608k
  ICFLoopSafetyInfo SafetyInfo(DT);
367
608k
  SafetyInfo.computeLoopSafetyInfo(L);
368
608k
369
608k
  // We want to visit all of the instructions in this loop... that are not parts
370
608k
  // of our subloops (they have already had their invariants hoisted out of
371
608k
  // their loop, into this loop, so there is no need to process the BODIES of
372
608k
  // the subloops).
373
608k
  //
374
608k
  // Traverse the body of the loop in depth first order on the dominator tree so
375
608k
  // that we are guaranteed to see definitions before we see uses.  This allows
376
608k
  // us to sink instructions in one pass, without iteration.  After sinking
377
608k
  // instructions, we perform another pass to hoist them out of the loop.
378
608k
  SinkAndHoistLICMFlags Flags = {NoOfMemAccTooLarge, LicmMssaOptCounter,
379
608k
                                 LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
380
608k
                                 /*IsSink=*/true};
381
608k
  if (L->hasDedicatedExits())
382
608k
    Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L,
383
608k
                          CurAST.get(), MSSAU.get(), &SafetyInfo, Flags, ORE);
384
608k
  Flags.IsSink = false;
385
608k
  if (Preheader)
386
608k
    Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
387
608k
                           CurAST.get(), MSSAU.get(), &SafetyInfo, Flags, ORE);
388
608k
389
608k
  // Now that all loop invariants have been removed from the loop, promote any
390
608k
  // memory references to scalars that we can.
391
608k
  // Don't sink stores from loops without dedicated block exits. Exits
392
608k
  // containing indirect branches are not transformed by loop simplify,
393
608k
  // make sure we catch that. An additional load may be generated in the
394
608k
  // preheader for SSA updater, so also avoid sinking when no preheader
395
608k
  // is available.
396
608k
  if (!DisablePromotion && Preheader && 
L->hasDedicatedExits()608k
&&
397
608k
      
!NoOfMemAccTooLarge608k
) {
398
608k
    // Figure out the loop exits and their insertion points
399
608k
    SmallVector<BasicBlock *, 8> ExitBlocks;
400
608k
    L->getUniqueExitBlocks(ExitBlocks);
401
608k
402
608k
    // We can't insert into a catchswitch.
403
772k
    bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
404
772k
      return isa<CatchSwitchInst>(Exit->getTerminator());
405
772k
    });
406
608k
407
608k
    if (!HasCatchSwitch) {
408
608k
      SmallVector<Instruction *, 8> InsertPts;
409
608k
      SmallVector<MemoryAccess *, 8> MSSAInsertPts;
410
608k
      InsertPts.reserve(ExitBlocks.size());
411
608k
      if (MSSAU)
412
156
        MSSAInsertPts.reserve(ExitBlocks.size());
413
772k
      for (BasicBlock *ExitBlock : ExitBlocks) {
414
772k
        InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
415
772k
        if (MSSAU)
416
148
          MSSAInsertPts.push_back(nullptr);
417
772k
      }
418
608k
419
608k
      PredIteratorCache PIC;
420
608k
421
608k
      bool Promoted = false;
422
608k
423
608k
      // Build an AST using MSSA.
424
608k
      if (!CurAST.get())
425
156
        CurAST = collectAliasInfoForLoopWithMSSA(L, AA, MSSAU.get());
426
608k
427
608k
      // Loop over all of the alias sets in the tracker object.
428
1.05M
      for (AliasSet &AS : *CurAST) {
429
1.05M
        // We can promote this alias set if it has a store, if it is a "Must"
430
1.05M
        // alias set, if the pointer is loop invariant, and if we are not
431
1.05M
        // eliminating any volatile loads or stores.
432
1.05M
        if (AS.isForwardingAliasSet() || 
!AS.isMod()971k
||
!AS.isMustAlias()727k
||
433
1.05M
            
!L->isLoopInvariant(AS.begin()->getValue())330k
)
434
1.05M
          continue;
435
8.37k
436
8.37k
        assert(
437
8.37k
            !AS.empty() &&
438
8.37k
            "Must alias set should have at least one pointer element in it!");
439
8.37k
440
8.37k
        SmallSetVector<Value *, 8> PointerMustAliases;
441
8.37k
        for (const auto &ASI : AS)
442
8.86k
          PointerMustAliases.insert(ASI.getValue());
443
8.37k
444
8.37k
        Promoted |= promoteLoopAccessesToScalars(
445
8.37k
            PointerMustAliases, ExitBlocks, InsertPts, MSSAInsertPts, PIC, LI,
446
8.37k
            DT, TLI, L, CurAST.get(), MSSAU.get(), &SafetyInfo, ORE);
447
8.37k
      }
448
608k
449
608k
      // Once we have promoted values across the loop body we have to
450
608k
      // recursively reform LCSSA as any nested loop may now have values defined
451
608k
      // within the loop used in the outer loop.
452
608k
      // FIXME: This is really heavy handed. It would be a bit better to use an
453
608k
      // SSAUpdater strategy during promotion that was LCSSA aware and reformed
454
608k
      // it as it went.
455
608k
      if (Promoted)
456
1.72k
        formLCSSARecursively(*L, *DT, LI, SE);
457
608k
458
608k
      Changed |= Promoted;
459
608k
    }
460
608k
  }
461
608k
462
608k
  // Check that neither this loop nor its parent have had LCSSA broken. LICM is
463
608k
  // specifically moving instructions across the loop boundary and so it is
464
608k
  // especially in need of sanity checking here.
465
608k
  assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
466
608k
  assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
467
608k
         "Parent loop not left in LCSSA form after LICM!");
468
608k
469
608k
  // If this loop is nested inside of another one, save the alias information
470
608k
  // for when we process the outer loop.
471
608k
  if (!MSSAU.get() && 
CurAST.get()608k
&&
L->getParentLoop()608k
&&
!DeleteAST166k
)
472
166k
    LoopToAliasSetMap[L] = std::move(CurAST);
473
608k
474
608k
  if (MSSAU.get() && 
VerifyMemorySSA157
)
475
135
    MSSAU->getMemorySSA()->verifyMemorySSA();
476
608k
477
608k
  if (Changed && 
SE45.9k
)
478
45.9k
    SE->forgetLoopDispositions(L);
479
608k
  return Changed;
480
608k
}
481
482
/// Walk the specified region of the CFG (defined by all blocks dominated by
483
/// the specified block, and that are in the current loop) in reverse depth
484
/// first order w.r.t the DominatorTree.  This allows us to visit uses before
485
/// definitions, allowing us to sink a loop body in one pass without iteration.
486
///
487
bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
488
                      DominatorTree *DT, TargetLibraryInfo *TLI,
489
                      TargetTransformInfo *TTI, Loop *CurLoop,
490
                      AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU,
491
                      ICFLoopSafetyInfo *SafetyInfo,
492
                      SinkAndHoistLICMFlags &Flags,
493
608k
                      OptimizationRemarkEmitter *ORE) {
494
608k
495
608k
  // Verify inputs.
496
608k
  assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
497
608k
         CurLoop != nullptr && SafetyInfo != nullptr &&
498
608k
         "Unexpected input to sinkRegion.");
499
608k
  assert(((CurAST != nullptr) ^ (MSSAU != nullptr)) &&
500
608k
         "Either AliasSetTracker or MemorySSA should be initialized.");
501
608k
502
608k
  // We want to visit children before parents. We will enque all the parents
503
608k
  // before their children in the worklist and process the worklist in reverse
504
608k
  // order.
505
608k
  SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
506
608k
507
608k
  bool Changed = false;
508
2.76M
  for (DomTreeNode *DTN : reverse(Worklist)) {
509
2.76M
    BasicBlock *BB = DTN->getBlock();
510
2.76M
    // Only need to process the contents of this block if it is not part of a
511
2.76M
    // subloop (which would already have been processed).
512
2.76M
    if (inSubLoop(BB, CurLoop, LI))
513
705k
      continue;
514
2.06M
515
15.2M
    
for (BasicBlock::iterator II = BB->end(); 2.06M
II != BB->begin();) {
516
13.2M
      Instruction &I = *--II;
517
13.2M
518
13.2M
      // If the instruction is dead, we would try to sink it because it isn't
519
13.2M
      // used in the loop, instead, just delete it.
520
13.2M
      if (isInstructionTriviallyDead(&I, TLI)) {
521
916
        LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
522
916
        salvageDebugInfo(I);
523
916
        ++II;
524
916
        eraseInstruction(I, *SafetyInfo, CurAST, MSSAU);
525
916
        Changed = true;
526
916
        continue;
527
916
      }
528
13.2M
529
13.2M
      // Check to see if we can sink this instruction to the exit blocks
530
13.2M
      // of the loop.  We can do this if the all users of the instruction are
531
13.2M
      // outside of the loop.  In this case, it doesn't even matter if the
532
13.2M
      // operands of the instruction are loop invariant.
533
13.2M
      //
534
13.2M
      bool FreeInLoop = false;
535
13.2M
      if (isNotUsedOrFreeInLoop(I, CurLoop, SafetyInfo, TTI, FreeInLoop) &&
536
13.2M
          canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, MSSAU, true, &Flags,
537
6.59M
                             ORE) &&
538
13.2M
          
!I.mayHaveSideEffects()2.30M
) {
539
2.03M
        if (sink(I, LI, DT, CurLoop, SafetyInfo, MSSAU, ORE)) {
540
17.7k
          if (!FreeInLoop) {
541
1.69k
            ++II;
542
1.69k
            eraseInstruction(I, *SafetyInfo, CurAST, MSSAU);
543
1.69k
          }
544
17.7k
          Changed = true;
545
17.7k
        }
546
2.03M
      }
547
13.2M
    }
548
2.06M
  }
549
608k
  if (MSSAU && 
VerifyMemorySSA157
)
550
135
    MSSAU->getMemorySSA()->verifyMemorySSA();
551
608k
  return Changed;
552
608k
}
553
554
namespace {
555
// This is a helper class for hoistRegion to make it able to hoist control flow
556
// in order to be able to hoist phis. The way this works is that we initially
557
// start hoisting to the loop preheader, and when we see a loop invariant branch
558
// we make note of this. When we then come to hoist an instruction that's
559
// conditional on such a branch we duplicate the branch and the relevant control
560
// flow, then hoist the instruction into the block corresponding to its original
561
// block in the duplicated control flow.
562
class ControlFlowHoister {
563
private:
564
  // Information about the loop we are hoisting from
565
  LoopInfo *LI;
566
  DominatorTree *DT;
567
  Loop *CurLoop;
568
  MemorySSAUpdater *MSSAU;
569
570
  // A map of blocks in the loop to the block their instructions will be hoisted
571
  // to.
572
  DenseMap<BasicBlock *, BasicBlock *> HoistDestinationMap;
573
574
  // The branches that we can hoist, mapped to the block that marks a
575
  // convergence point of their control flow.
576
  DenseMap<BranchInst *, BasicBlock *> HoistableBranches;
577
578
public:
579
  ControlFlowHoister(LoopInfo *LI, DominatorTree *DT, Loop *CurLoop,
580
                     MemorySSAUpdater *MSSAU)
581
608k
      : LI(LI), DT(DT), CurLoop(CurLoop), MSSAU(MSSAU) {}
582
583
2.01M
  void registerPossiblyHoistableBranch(BranchInst *BI) {
584
2.01M
    // We can only hoist conditional branches with loop invariant operands.
585
2.01M
    if (!ControlFlowHoisting || 
!BI->isConditional()573
||
586
2.01M
        
!CurLoop->hasLoopInvariantOperands(BI)283
)
587
2.01M
      return;
588
250
589
250
    // The branch destinations need to be in the loop, and we don't gain
590
250
    // anything by duplicating conditional branches with duplicate successors,
591
250
    // as it's essentially the same as an unconditional branch.
592
250
    BasicBlock *TrueDest = BI->getSuccessor(0);
593
250
    BasicBlock *FalseDest = BI->getSuccessor(1);
594
250
    if (!CurLoop->contains(TrueDest) || 
!CurLoop->contains(FalseDest)229
||
595
250
        
TrueDest == FalseDest193
)
596
63
      return;
597
187
598
187
    // We can hoist BI if one branch destination is the successor of the other,
599
187
    // or both have common successor which we check by seeing if the
600
187
    // intersection of their successors is non-empty.
601
187
    // TODO: This could be expanded to allowing branches where both ends
602
187
    // eventually converge to a single block.
603
187
    SmallPtrSet<BasicBlock *, 4> TrueDestSucc, FalseDestSucc;
604
187
    TrueDestSucc.insert(succ_begin(TrueDest), succ_end(TrueDest));
605
187
    FalseDestSucc.insert(succ_begin(FalseDest), succ_end(FalseDest));
606
187
    BasicBlock *CommonSucc = nullptr;
607
187
    if (TrueDestSucc.count(FalseDest)) {
608
58
      CommonSucc = FalseDest;
609
129
    } else if (FalseDestSucc.count(TrueDest)) {
610
39
      CommonSucc = TrueDest;
611
90
    } else {
612
90
      set_intersect(TrueDestSucc, FalseDestSucc);
613
90
      // If there's one common successor use that.
614
90
      if (TrueDestSucc.size() == 1)
615
57
        CommonSucc = *TrueDestSucc.begin();
616
33
      // If there's more than one pick whichever appears first in the block list
617
33
      // (we can't use the value returned by TrueDestSucc.begin() as it's
618
33
      // unpredicatable which element gets returned).
619
33
      else if (!TrueDestSucc.empty()) {
620
6
        Function *F = TrueDest->getParent();
621
30
        auto IsSucc = [&](BasicBlock &BB) { return TrueDestSucc.count(&BB); };
622
6
        auto It = std::find_if(F->begin(), F->end(), IsSucc);
623
6
        assert(It != F->end() && "Could not find successor in function");
624
6
        CommonSucc = &*It;
625
6
      }
626
90
    }
627
187
    // The common successor has to be dominated by the branch, as otherwise
628
187
    // there will be some other path to the successor that will not be
629
187
    // controlled by this branch so any phi we hoist would be controlled by the
630
187
    // wrong condition. This also takes care of avoiding hoisting of loop back
631
187
    // edges.
632
187
    // TODO: In some cases this could be relaxed if the successor is dominated
633
187
    // by another block that's been hoisted and we can guarantee that the
634
187
    // control flow has been replicated exactly.
635
187
    if (CommonSucc && 
DT->dominates(BI, CommonSucc)160
)
636
130
      HoistableBranches[BI] = CommonSucc;
637
187
  }
638
639
1.27M
  bool canHoistPHI(PHINode *PN) {
640
1.27M
    // The phi must have loop invariant operands.
641
1.27M
    if (!ControlFlowHoisting || 
!CurLoop->hasLoopInvariantOperands(PN)117
)
642
1.27M
      return false;
643
90
    // We can hoist phis if the block they are in is the target of hoistable
644
90
    // branches which cover all of the predecessors of the block.
645
90
    SmallPtrSet<BasicBlock *, 8> PredecessorBlocks;
646
90
    BasicBlock *BB = PN->getParent();
647
90
    for (BasicBlock *PredBB : predecessors(BB))
648
201
      PredecessorBlocks.insert(PredBB);
649
90
    // If we have less predecessor blocks than predecessors then the phi will
650
90
    // have more than one incoming value for the same block which we can't
651
90
    // handle.
652
90
    // TODO: This could be handled be erasing some of the duplicate incoming
653
90
    // values.
654
90
    if (PredecessorBlocks.size() != pred_size(BB))
655
3
      return false;
656
93
    
for (auto &Pair : HoistableBranches)87
{
657
93
      if (Pair.second == BB) {
658
72
        // Which blocks are predecessors via this branch depends on if the
659
72
        // branch is triangle-like or diamond-like.
660
72
        if (Pair.first->getSuccessor(0) == BB) {
661
9
          PredecessorBlocks.erase(Pair.first->getParent());
662
9
          PredecessorBlocks.erase(Pair.first->getSuccessor(1));
663
63
        } else if (Pair.first->getSuccessor(1) == BB) {
664
30
          PredecessorBlocks.erase(Pair.first->getParent());
665
30
          PredecessorBlocks.erase(Pair.first->getSuccessor(0));
666
33
        } else {
667
33
          PredecessorBlocks.erase(Pair.first->getSuccessor(0));
668
33
          PredecessorBlocks.erase(Pair.first->getSuccessor(1));
669
33
        }
670
72
      }
671
93
    }
672
87
    // PredecessorBlocks will now be empty if for every predecessor of BB we
673
87
    // found a hoistable branch source.
674
87
    return PredecessorBlocks.empty();
675
87
  }
676
677
188k
  BasicBlock *getOrCreateHoistedBlock(BasicBlock *BB) {
678
188k
    if (!ControlFlowHoisting)
679
188k
      return CurLoop->getLoopPreheader();
680
579
    // If BB has already been hoisted, return that
681
579
    if (HoistDestinationMap.count(BB))
682
316
      return HoistDestinationMap[BB];
683
263
684
263
    // Check if this block is conditional based on a pending branch
685
263
    auto HasBBAsSuccessor =
686
263
        [&](DenseMap<BranchInst *, BasicBlock *>::value_type &Pair) {
687
199
          return BB != Pair.second && (Pair.first->getSuccessor(0) == BB ||
688
199
                                       
Pair.first->getSuccessor(1) == BB135
);
689
199
        };
690
263
    auto It = std::find_if(HoistableBranches.begin(), HoistableBranches.end(),
691
263
                           HasBBAsSuccessor);
692
263
693
263
    // If not involved in a pending branch, hoist to preheader
694
263
    BasicBlock *InitialPreheader = CurLoop->getLoopPreheader();
695
263
    if (It == HoistableBranches.end()) {
696
151
      LLVM_DEBUG(dbgs() << "LICM using " << InitialPreheader->getName()
697
151
                        << " as hoist destination for " << BB->getName()
698
151
                        << "\n");
699
151
      HoistDestinationMap[BB] = InitialPreheader;
700
151
      return InitialPreheader;
701
151
    }
702
112
    BranchInst *BI = It->first;
703
112
    assert(std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor) ==
704
112
               HoistableBranches.end() &&
705
112
           "BB is expected to be the target of at most one branch");
706
112
707
112
    LLVMContext &C = BB->getContext();
708
112
    BasicBlock *TrueDest = BI->getSuccessor(0);
709
112
    BasicBlock *FalseDest = BI->getSuccessor(1);
710
112
    BasicBlock *CommonSucc = HoistableBranches[BI];
711
112
    BasicBlock *HoistTarget = getOrCreateHoistedBlock(BI->getParent());
712
112
713
112
    // Create hoisted versions of blocks that currently don't have them
714
336
    auto CreateHoistedBlock = [&](BasicBlock *Orig) {
715
336
      if (HoistDestinationMap.count(Orig))
716
67
        return HoistDestinationMap[Orig];
717
269
      BasicBlock *New =
718
269
          BasicBlock::Create(C, Orig->getName() + ".licm", Orig->getParent());
719
269
      HoistDestinationMap[Orig] = New;
720
269
      DT->addNewBlock(New, HoistTarget);
721
269
      if (CurLoop->getParentLoop())
722
12
        CurLoop->getParentLoop()->addBasicBlockToLoop(New, *LI);
723
269
      ++NumCreatedBlocks;
724
269
      LLVM_DEBUG(dbgs() << "LICM created " << New->getName()
725
269
                        << " as hoist destination for " << Orig->getName()
726
269
                        << "\n");
727
269
      return New;
728
269
    };
729
112
    BasicBlock *HoistTrueDest = CreateHoistedBlock(TrueDest);
730
112
    BasicBlock *HoistFalseDest = CreateHoistedBlock(FalseDest);
731
112
    BasicBlock *HoistCommonSucc = CreateHoistedBlock(CommonSucc);
732
112
733
112
    // Link up these blocks with branches.
734
112
    if (!HoistCommonSucc->getTerminator()) {
735
112
      // The new common successor we've generated will branch to whatever that
736
112
      // hoist target branched to.
737
112
      BasicBlock *TargetSucc = HoistTarget->getSingleSuccessor();
738
112
      assert(TargetSucc && "Expected hoist target to have a single successor");
739
112
      HoistCommonSucc->moveBefore(TargetSucc);
740
112
      BranchInst::Create(TargetSucc, HoistCommonSucc);
741
112
    }
742
112
    if (!HoistTrueDest->getTerminator()) {
743
85
      HoistTrueDest->moveBefore(HoistCommonSucc);
744
85
      BranchInst::Create(HoistCommonSucc, HoistTrueDest);
745
85
    }
746
112
    if (!HoistFalseDest->getTerminator()) {
747
72
      HoistFalseDest->moveBefore(HoistCommonSucc);
748
72
      BranchInst::Create(HoistCommonSucc, HoistFalseDest);
749
72
    }
750
112
751
112
    // If BI is being cloned to what was originally the preheader then
752
112
    // HoistCommonSucc will now be the new preheader.
753
112
    if (HoistTarget == InitialPreheader) {
754
112
      // Phis in the loop header now need to use the new preheader.
755
112
      InitialPreheader->replaceSuccessorsPhiUsesWith(HoistCommonSucc);
756
112
      if (MSSAU)
757
38
        MSSAU->wireOldPredecessorsToNewImmediatePredecessor(
758
38
            HoistTarget->getSingleSuccessor(), HoistCommonSucc, {HoistTarget});
759
112
      // The new preheader dominates the loop header.
760
112
      DomTreeNode *PreheaderNode = DT->getNode(HoistCommonSucc);
761
112
      DomTreeNode *HeaderNode = DT->getNode(CurLoop->getHeader());
762
112
      DT->changeImmediateDominator(HeaderNode, PreheaderNode);
763
112
      // The preheader hoist destination is now the new preheader, with the
764
112
      // exception of the hoist destination of this branch.
765
112
      for (auto &Pair : HoistDestinationMap)
766
480
        if (Pair.second == InitialPreheader && 
Pair.first != BI->getParent()136
)
767
24
          Pair.second = HoistCommonSucc;
768
112
    }
769
112
770
112
    // Now finally clone BI.
771
112
    ReplaceInstWithInst(
772
112
        HoistTarget->getTerminator(),
773
112
        BranchInst::Create(HoistTrueDest, HoistFalseDest, BI->getCondition()));
774
112
    ++NumClonedBranches;
775
112
776
112
    assert(CurLoop->getLoopPreheader() &&
777
112
           "Hoisting blocks should not have destroyed preheader");
778
112
    return HoistDestinationMap[BB];
779
112
  }
780
};
781
} // namespace
782
783
/// Walk the specified region of the CFG (defined by all blocks dominated by
784
/// the specified block, and that are in the current loop) in depth first
785
/// order w.r.t the DominatorTree.  This allows us to visit definitions before
786
/// uses, allowing us to hoist a loop body in one pass without iteration.
787
///
788
bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
789
                       DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
790
                       AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU,
791
                       ICFLoopSafetyInfo *SafetyInfo,
792
                       SinkAndHoistLICMFlags &Flags,
793
608k
                       OptimizationRemarkEmitter *ORE) {
794
608k
  // Verify inputs.
795
608k
  assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
796
608k
         CurLoop != nullptr && SafetyInfo != nullptr &&
797
608k
         "Unexpected input to hoistRegion.");
798
608k
  assert(((CurAST != nullptr) ^ (MSSAU != nullptr)) &&
799
608k
         "Either AliasSetTracker or MemorySSA should be initialized.");
800
608k
801
608k
  ControlFlowHoister CFH(LI, DT, CurLoop, MSSAU);
802
608k
803
608k
  // Keep track of instructions that have been hoisted, as they may need to be
804
608k
  // re-hoisted if they end up not dominating all of their uses.
805
608k
  SmallVector<Instruction *, 16> HoistedInstructions;
806
608k
807
608k
  // For PHI hoisting to work we need to hoist blocks before their successors.
808
608k
  // We can do this by iterating through the blocks in the loop in reverse
809
608k
  // post-order.
810
608k
  LoopBlocksRPO Worklist(CurLoop);
811
608k
  Worklist.perform(LI);
812
608k
  bool Changed = false;
813
2.76M
  for (BasicBlock *BB : Worklist) {
814
2.76M
    // Only need to process the contents of this block if it is not part of a
815
2.76M
    // subloop (which would already have been processed).
816
2.76M
    if (inSubLoop(BB, CurLoop, LI))
817
705k
      continue;
818
2.06M
819
15.2M
    
for (BasicBlock::iterator II = BB->begin(), E = BB->end(); 2.06M
II != E;) {
820
13.2M
      Instruction &I = *II++;
821
13.2M
      // Try constant folding this instruction.  If all the operands are
822
13.2M
      // constants, it is technically hoistable, but it would be better to
823
13.2M
      // just fold it.
824
13.2M
      if (Constant *C = ConstantFoldInstruction(
825
302
              &I, I.getModule()->getDataLayout(), TLI)) {
826
302
        LLVM_DEBUG(dbgs() << "LICM folding inst: " << I << "  --> " << *C
827
302
                          << '\n');
828
302
        if (CurAST)
829
301
          CurAST->copyValue(&I, C);
830
302
        // FIXME MSSA: Such replacements may make accesses unoptimized (D51960).
831
302
        I.replaceAllUsesWith(C);
832
302
        if (isInstructionTriviallyDead(&I, TLI))
833
302
          eraseInstruction(I, *SafetyInfo, CurAST, MSSAU);
834
302
        Changed = true;
835
302
        continue;
836
302
      }
837
13.2M
838
13.2M
      // Try hoisting the instruction out to the preheader.  We can only do
839
13.2M
      // this if all of the operands of the instruction are loop invariant and
840
13.2M
      // if it is safe to hoist the instruction.
841
13.2M
      // TODO: It may be safe to hoist if we are hoisting to a conditional block
842
13.2M
      // and we have accurately duplicated the control flow from the loop header
843
13.2M
      // to that block.
844
13.2M
      if (CurLoop->hasLoopInvariantOperands(&I) &&
845
13.2M
          canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, MSSAU, true, &Flags,
846
1.81M
                             ORE) &&
847
13.2M
          isSafeToExecuteUnconditionally(
848
200k
              I, DT, CurLoop, SafetyInfo, ORE,
849
200k
              CurLoop->getLoopPreheader()->getTerminator())) {
850
188k
        hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
851
188k
              MSSAU, ORE);
852
188k
        HoistedInstructions.push_back(&I);
853
188k
        Changed = true;
854
188k
        continue;
855
188k
      }
856
13.0M
857
13.0M
      // Attempt to remove floating point division out of the loop by
858
13.0M
      // converting it to a reciprocal multiplication.
859
13.0M
      if (I.getOpcode() == Instruction::FDiv &&
860
13.0M
          
CurLoop->isLoopInvariant(I.getOperand(1))69.6k
&&
861
13.0M
          
I.hasAllowReciprocal()10.4k
) {
862
2
        auto Divisor = I.getOperand(1);
863
2
        auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
864
2
        auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
865
2
        ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
866
2
        SafetyInfo->insertInstructionTo(ReciprocalDivisor, I.getParent());
867
2
        ReciprocalDivisor->insertBefore(&I);
868
2
869
2
        auto Product =
870
2
            BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
871
2
        Product->setFastMathFlags(I.getFastMathFlags());
872
2
        SafetyInfo->insertInstructionTo(Product, I.getParent());
873
2
        Product->insertAfter(&I);
874
2
        I.replaceAllUsesWith(Product);
875
2
        eraseInstruction(I, *SafetyInfo, CurAST, MSSAU);
876
2
877
2
        hoist(*ReciprocalDivisor, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB),
878
2
              SafetyInfo, MSSAU, ORE);
879
2
        HoistedInstructions.push_back(ReciprocalDivisor);
880
2
        Changed = true;
881
2
        continue;
882
2
      }
883
13.0M
884
13.0M
      auto IsInvariantStart = [&](Instruction &I) {
885
13.0M
        using namespace PatternMatch;
886
13.0M
        return I.use_empty() &&
887
13.0M
               
match(&I, m_Intrinsic<Intrinsic::invariant_start>())3.28M
;
888
13.0M
      };
889
13.0M
      auto MustExecuteWithoutWritesBefore = [&](Instruction &I) {
890
32
        return SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop) &&
891
32
               
SafetyInfo->doesNotWriteMemoryBefore(I, CurLoop)19
;
892
32
      };
893
13.0M
      if ((IsInvariantStart(I) || 
isGuard(&I)13.0M
) &&
894
13.0M
          
CurLoop->hasLoopInvariantOperands(&I)36
&&
895
13.0M
          
MustExecuteWithoutWritesBefore(I)32
) {
896
12
        hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
897
12
              MSSAU, ORE);
898
12
        HoistedInstructions.push_back(&I);
899
12
        Changed = true;
900
12
        continue;
901
12
      }
902
13.0M
903
13.0M
      if (PHINode *PN = dyn_cast<PHINode>(&I)) {
904
1.27M
        if (CFH.canHoistPHI(PN)) {
905
69
          // Redirect incoming blocks first to ensure that we create hoisted
906
69
          // versions of those blocks before we hoist the phi.
907
207
          for (unsigned int i = 0; i < PN->getNumIncomingValues(); 
++i138
)
908
138
            PN->setIncomingBlock(
909
138
                i, CFH.getOrCreateHoistedBlock(PN->getIncomingBlock(i)));
910
69
          hoist(*PN, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
911
69
                MSSAU, ORE);
912
69
          assert(DT->dominates(PN, BB) && "Conditional PHIs not expected");
913
69
          Changed = true;
914
69
          continue;
915
69
        }
916
13.0M
      }
917
13.0M
918
13.0M
      // Remember possibly hoistable branches so we can actually hoist them
919
13.0M
      // later if needed.
920
13.0M
      if (BranchInst *BI = dyn_cast<BranchInst>(&I))
921
2.01M
        CFH.registerPossiblyHoistableBranch(BI);
922
13.0M
    }
923
2.06M
  }
924
608k
925
608k
  // If we hoisted instructions to a conditional block they may not dominate
926
608k
  // their uses that weren't hoisted (such as phis where some operands are not
927
608k
  // loop invariant). If so make them unconditional by moving them to their
928
608k
  // immediate dominator. We iterate through the instructions in reverse order
929
608k
  // which ensures that when we rehoist an instruction we rehoist its operands,
930
608k
  // and also keep track of where in the block we are rehoisting to to make sure
931
608k
  // that we rehoist instructions before the instructions that use them.
932
608k
  Instruction *HoistPoint = nullptr;
933
608k
  if (ControlFlowHoisting) {
934
260
    for (Instruction *I : reverse(HoistedInstructions)) {
935
260
      if (!llvm::all_of(I->uses(),
936
321
                        [&](Use &U) { return DT->dominates(I, U); })) {
937
94
        BasicBlock *Dominator =
938
94
            DT->getNode(I->getParent())->getIDom()->getBlock();
939
94
        if (!HoistPoint || 
!DT->dominates(HoistPoint->getParent(), Dominator)39
) {
940
64
          if (HoistPoint)
941
64
            assert(DT->dominates(Dominator, HoistPoint->getParent()) &&
942
64
                   "New hoist point expected to dominate old hoist point");
943
64
          HoistPoint = Dominator->getTerminator();
944
64
        }
945
94
        LLVM_DEBUG(dbgs() << "LICM rehoisting to "
946
94
                          << HoistPoint->getParent()->getName()
947
94
                          << ": " << *I << "\n");
948
94
        moveInstructionBefore(*I, *HoistPoint, *SafetyInfo, MSSAU);
949
94
        HoistPoint = I;
950
94
        Changed = true;
951
94
      }
952
260
    }
953
112
  }
954
608k
  if (MSSAU && 
VerifyMemorySSA156
)
955
134
    MSSAU->getMemorySSA()->verifyMemorySSA();
956
608k
957
608k
    // Now that we've finished hoisting make sure that LI and DT are still
958
608k
    // valid.
959
#ifndef NDEBUG
960
  if (Changed) {
961
    assert(DT->verify(DominatorTree::VerificationLevel::Fast) &&
962
           "Dominator tree verification failed");
963
    LI->verify(*DT);
964
  }
965
#endif
966
967
608k
  return Changed;
968
608k
}
969
970
// Return true if LI is invariant within scope of the loop. LI is invariant if
971
// CurLoop is dominated by an invariant.start representing the same memory
972
// location and size as the memory location LI loads from, and also the
973
// invariant.start has no uses.
974
static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT,
975
574k
                                  Loop *CurLoop) {
976
574k
  Value *Addr = LI->getOperand(0);
977
574k
  const DataLayout &DL = LI->getModule()->getDataLayout();
978
574k
  const uint32_t LocSizeInBits = DL.getTypeSizeInBits(LI->getType());
979
574k
980
574k
  // if the type is i8 addrspace(x)*, we know this is the type of
981
574k
  // llvm.invariant.start operand
982
574k
  auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()),
983
574k
                                     LI->getPointerAddressSpace());
984
574k
  unsigned BitcastsVisited = 0;
985
574k
  // Look through bitcasts until we reach the i8* type (this is invariant.start
986
574k
  // operand type).
987
640k
  while (Addr->getType() != PtrInt8Ty) {
988
593k
    auto *BC = dyn_cast<BitCastInst>(Addr);
989
593k
    // Avoid traversing high number of bitcast uses.
990
593k
    if (++BitcastsVisited > MaxNumUsesTraversed || !BC)
991
526k
      return false;
992
66.5k
    Addr = BC->getOperand(0);
993
66.5k
  }
994
574k
995
574k
  unsigned UsesVisited = 0;
996
47.5k
  // Traverse all uses of the load operand value, to see if invariant.start is
997
47.5k
  // one of the uses, and whether it dominates the load instruction.
998
145k
  for (auto *U : Addr->users()) {
999
145k
    // Avoid traversing for Load operand with high number of users.
1000
145k
    if (++UsesVisited > MaxNumUsesTraversed)
1001
6.01k
      return false;
1002
139k
    IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
1003
139k
    // If there are escaping uses of invariant.start instruction, the load maybe
1004
139k
    // non-invariant.
1005
139k
    if (!II || 
II->getIntrinsicID() != Intrinsic::invariant_start4.32k
||
1006
139k
        
!II->use_empty()9
)
1007
139k
      continue;
1008
3
    unsigned InvariantSizeInBits =
1009
3
        cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8;
1010
3
    // Confirm the invariant.start location size contains the load operand size
1011
3
    // in bits. Also, the invariant.start should dominate the load, and we
1012
3
    // should not hoist the load out of a loop that contains this dominating
1013
3
    // invariant.start.
1014
3
    if (LocSizeInBits <= InvariantSizeInBits &&
1015
3
        DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
1016
3
      return true;
1017
3
  }
1018
47.5k
1019
47.5k
  
return false41.4k
;
1020
47.5k
}
1021
1022
namespace {
1023
/// Return true if-and-only-if we know how to (mechanically) both hoist and
1024
/// sink a given instruction out of a loop.  Does not address legality
1025
/// concerns such as aliasing or speculation safety.
1026
8.40M
bool isHoistableAndSinkableInst(Instruction &I) {
1027
8.40M
  // Only these instructions are hoistable/sinkable.
1028
8.40M
  return (isa<LoadInst>(I) || 
isa<StoreInst>(I)7.82M
||
isa<CallInst>(I)6.92M
||
1029
8.40M
          
isa<FenceInst>(I)6.30M
||
isa<BinaryOperator>(I)6.29M
||
isa<CastInst>(I)6.27M
||
1030
8.40M
          
isa<SelectInst>(I)5.03M
||
isa<GetElementPtrInst>(I)5.03M
||
isa<CmpInst>(I)4.11M
||
1031
8.40M
          
isa<InsertElementInst>(I)4.09M
||
isa<ExtractElementInst>(I)4.09M
||
1032
8.40M
          
isa<ShuffleVectorInst>(I)4.09M
||
isa<ExtractValueInst>(I)4.08M
||
1033
8.40M
          
isa<InsertValueInst>(I)4.08M
);
1034
8.40M
}
1035
/// Return true if all of the alias sets within this AST are known not to
1036
/// contain a Mod, or if MSSA knows thare are no MemoryDefs in the loop.
1037
bool isReadOnly(AliasSetTracker *CurAST, const MemorySSAUpdater *MSSAU,
1038
1.52k
                const Loop *L) {
1039
1.52k
  if (CurAST) {
1040
1.63k
    for (AliasSet &AS : *CurAST) {
1041
1.63k
      if (!AS.isForwardingAliasSet() && 
AS.isMod()1.52k
) {
1042
1.49k
        return false;
1043
1.49k
      }
1044
1.63k
    }
1045
1.52k
    
return true31
;
1046
3
  } else { /*MSSAU*/
1047
3
    for (auto *BB : L->getBlocks())
1048
4
      if (MSSAU->getMemorySSA()->getBlockDefs(BB))
1049
1
        return false;
1050
3
    
return true2
;
1051
3
  }
1052
1.52k
}
1053
1054
/// Return true if I is the only Instruction with a MemoryAccess in L.
1055
bool isOnlyMemoryAccess(const Instruction *I, const Loop *L,
1056
167
                        const MemorySSAUpdater *MSSAU) {
1057
167
  for (auto *BB : L->getBlocks())
1058
357
    if (auto *Accs = MSSAU->getMemorySSA()->getBlockAccesses(BB)) {
1059
254
      int NotAPhi = 0;
1060
378
      for (const auto &Acc : *Accs) {
1061
378
        if (isa<MemoryPhi>(&Acc))
1062
182
          continue;
1063
196
        const auto *MUD = cast<MemoryUseOrDef>(&Acc);
1064
196
        if (MUD->getMemoryInst() != I || 
NotAPhi++ == 171
)
1065
125
          return false;
1066
196
      }
1067
254
    }
1068
167
  
return true42
;
1069
167
}
1070
}
1071
1072
bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
1073
                              Loop *CurLoop, AliasSetTracker *CurAST,
1074
                              MemorySSAUpdater *MSSAU,
1075
                              bool TargetExecutesOncePerLoop,
1076
                              SinkAndHoistLICMFlags *Flags,
1077
8.40M
                              OptimizationRemarkEmitter *ORE) {
1078
8.40M
  // If we don't understand the instruction, bail early.
1079
8.40M
  if (!isHoistableAndSinkableInst(I))
1080
4.08M
    return false;
1081
4.31M
1082
4.31M
  MemorySSA *MSSA = MSSAU ? 
MSSAU->getMemorySSA()586
:
nullptr4.31M
;
1083
4.31M
  if (MSSA)
1084
4.31M
    assert(Flags != nullptr && "Flags cannot be null.");
1085
4.31M
1086
4.31M
  // Loads have extra constraints we have to verify before we can hoist them.
1087
4.31M
  if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
1088
579k
    if (!LI->isUnordered())
1089
4.34k
      return false; // Don't sink/hoist volatile or ordered atomic loads!
1090
574k
1091
574k
    // Loads from constant memory are always safe to move, even if they end up
1092
574k
    // in the same alias set as something that ends up being modified.
1093
574k
    if (AA->pointsToConstantMemory(LI->getOperand(0)))
1094
579
      return true;
1095
574k
    if (LI->getMetadata(LLVMContext::MD_invariant_load))
1096
15
      return true;
1097
574k
1098
574k
    if (LI->isAtomic() && 
!TargetExecutesOncePerLoop40
)
1099
2
      return false; // Don't risk duplicating unordered loads
1100
574k
1101
574k
    // This checks for an invariant.start dominating the load.
1102
574k
    if (isLoadInvariantInLoop(LI, DT, CurLoop))
1103
3
      return true;
1104
574k
1105
574k
    bool Invalidated;
1106
574k
    if (CurAST)
1107
574k
      Invalidated = pointerInvalidatedByLoop(MemoryLocation::get(LI), CurAST,
1108
574k
                                             CurLoop, AA);
1109
81
    else
1110
81
      Invalidated = pointerInvalidatedByLoopWithMSSA(
1111
81
          MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(LI)), CurLoop, *Flags);
1112
574k
    // Check loop-invariant address because this may also be a sinkable load
1113
574k
    // whose address is not necessarily loop-invariant.
1114
574k
    if (ORE && 
Invalidated574k
&&
CurLoop->isLoopInvariant(LI->getPointerOperand())546k
)
1115
545k
      ORE->emit([&]() {
1116
22
        return OptimizationRemarkMissed(
1117
22
                   DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI)
1118
22
               << "failed to move load with loop-invariant address "
1119
22
                  "because the loop may invalidate its value";
1120
22
      });
1121
574k
1122
574k
    return !Invalidated;
1123
3.73M
  } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1124
627k
    // Don't sink or hoist dbg info; it's legal, but not useful.
1125
627k
    if (isa<DbgInfoIntrinsic>(I))
1126
186
      return false;
1127
627k
1128
627k
    // Don't sink calls which can throw.
1129
627k
    if (CI->mayThrow())
1130
13.9k
      return false;
1131
613k
1132
613k
    using namespace PatternMatch;
1133
613k
    if (match(CI, m_Intrinsic<Intrinsic::assume>()))
1134
25
      // Assumes don't actually alias anything or throw
1135
25
      return true;
1136
613k
1137
613k
    // Handle simple cases by querying alias analysis.
1138
613k
    FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
1139
613k
    if (Behavior == FMRB_DoesNotAccessMemory)
1140
6.62k
      return true;
1141
607k
    if (AliasAnalysis::onlyReadsMemory(Behavior)) {
1142
2.26k
      // A readonly argmemonly function only reads from memory pointed to by
1143
2.26k
      // it's arguments with arbitrary offsets.  If we can prove there are no
1144
2.26k
      // writes to this memory in the loop, we can hoist or sink.
1145
2.26k
      if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
1146
734
        // TODO: expand to writeable arguments
1147
734
        for (Value *Op : CI->arg_operands())
1148
725
          if (Op->getType()->isPointerTy()) {
1149
725
            bool Invalidated;
1150
725
            if (CurAST)
1151
721
              Invalidated = pointerInvalidatedByLoop(
1152
721
                  MemoryLocation(Op, LocationSize::unknown(), AAMDNodes()),
1153
721
                  CurAST, CurLoop, AA);
1154
4
            else
1155
4
              Invalidated = pointerInvalidatedByLoopWithMSSA(
1156
4
                  MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(CI)), CurLoop,
1157
4
                  *Flags);
1158
725
            if (Invalidated)
1159
687
              return false;
1160
725
          }
1161
734
        
return true47
;
1162
1.52k
      }
1163
1.52k
1164
1.52k
      // If this call only reads from memory and there are no writes to memory
1165
1.52k
      // in the loop, we can hoist or sink the call as appropriate.
1166
1.52k
      if (isReadOnly(CurAST, MSSAU, CurLoop))
1167
33
        return true;
1168
606k
    }
1169
606k
1170
606k
    // FIXME: This should use mod/ref information to see if we can hoist or
1171
606k
    // sink the call.
1172
606k
1173
606k
    return false;
1174
3.10M
  } else if (auto *FI = dyn_cast<FenceInst>(&I)) {
1175
10.0k
    // Fences alias (most) everything to provide ordering.  For the moment,
1176
10.0k
    // just give up if there are any other memory operations in the loop.
1177
10.0k
    if (CurAST) {
1178
10.0k
      auto Begin = CurAST->begin();
1179
10.0k
      assert(Begin != CurAST->end() && "must contain FI");
1180
10.0k
      if (std::next(Begin) != CurAST->end())
1181
342
        // constant memory for instance, TODO: handle better
1182
342
        return false;
1183
9.70k
      auto *UniqueI = Begin->getUniqueInstruction();
1184
9.70k
      if (!UniqueI)
1185
9.69k
        // other memory op, give up
1186
9.69k
        return false;
1187
16
      (void)FI; // suppress unused variable warning
1188
16
      assert(UniqueI == FI && "AS must contain FI");
1189
16
      return true;
1190
16
    } else // MSSAU
1191
14
      return isOnlyMemoryAccess(FI, CurLoop, MSSAU);
1192
3.09M
  } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
1193
898k
    if (!SI->isUnordered())
1194
3.39k
      return false; // Don't sink/hoist volatile or ordered atomic store!
1195
894k
1196
894k
    // We can only hoist a store that we can prove writes a value which is not
1197
894k
    // read or overwritten within the loop.  For those cases, we fallback to
1198
894k
    // load store promotion instead.  TODO: We can extend this to cases where
1199
894k
    // there is exactly one write to the location and that write dominates an
1200
894k
    // arbitrary number of reads in the loop.
1201
894k
    if (CurAST) {
1202
894k
      auto &AS = CurAST->getAliasSetFor(MemoryLocation::get(SI));
1203
894k
1204
894k
      if (AS.isRef() || 
!AS.isMustAlias()286k
)
1205
617k
        // Quick exit test, handled by the full path below as well.
1206
617k
        return false;
1207
276k
      auto *UniqueI = AS.getUniqueInstruction();
1208
276k
      if (!UniqueI)
1209
11.3k
        // other memory op, give up
1210
11.3k
        return false;
1211
265k
      assert(UniqueI == SI && "AS must contain SI");
1212
265k
      return true;
1213
265k
    } else { // MSSAU
1214
153
      if (isOnlyMemoryAccess(SI, CurLoop, MSSAU))
1215
42
        return true;
1216
111
      // If there are more accesses than the Promotion cap, give up, we're not
1217
111
      // walking a list that long.
1218
111
      if (Flags->NoOfMemAccTooLarge)
1219
0
        return false;
1220
111
      // Check store only if there's still "quota" to check clobber.
1221
111
      if (Flags->LicmMssaOptCounter >= Flags->LicmMssaOptCap)
1222
0
        return false;
1223
111
      // If there are interfering Uses (i.e. their defining access is in the
1224
111
      // loop), or ordered loads (stored as Defs!), don't move this store.
1225
111
      // Could do better here, but this is conservatively correct.
1226
111
      // TODO: Cache set of Uses on the first walk in runOnLoop, update when
1227
111
      // moving accesses. Can also extend to dominating uses.
1228
111
      auto *SIMD = MSSA->getMemoryAccess(SI);
1229
111
      for (auto *BB : CurLoop->getBlocks())
1230
303
        if (auto *Accesses = MSSA->getBlockAccesses(BB)) {
1231
253
          for (const auto &MA : *Accesses)
1232
369
            if (const auto *MU = dyn_cast<MemoryUse>(&MA)) {
1233
70
              auto *MD = MU->getDefiningAccess();
1234
70
              if (!MSSA->isLiveOnEntryDef(MD) &&
1235
70
                  
CurLoop->contains(MD->getBlock())62
)
1236
62
                return false;
1237
8
              // Disable hoisting past potentially interfering loads. Optimized
1238
8
              // Uses may point to an access outside the loop, as getClobbering
1239
8
              // checks the previous iteration when walking the backedge.
1240
8
              // FIXME: More precise: no Uses that alias SI.
1241
8
              if (!Flags->IsSink && 
!MSSA->dominates(SIMD, MU)0
)
1242
0
                return false;
1243
299
            } else if (const auto *MD = dyn_cast<MemoryDef>(&MA))
1244
125
              if (auto *LI = dyn_cast<LoadInst>(MD->getMemoryInst())) {
1245
2
                (void)LI; // Silence warning.
1246
2
                assert(!LI->isUnordered() && "Expected unordered load");
1247
2
                return false;
1248
2
              }
1249
253
        }
1250
111
1251
111
      auto *Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(SI);
1252
47
      Flags->LicmMssaOptCounter++;
1253
47
      // If there are no clobbering Defs in the loop, store is safe to hoist.
1254
47
      return MSSA->isLiveOnEntryDef(Source) ||
1255
47
             
!CurLoop->contains(Source->getBlock())37
;
1256
2.20M
    }
1257
894k
  }
1258
2.20M
1259
2.20M
  assert(!I.mayReadOrWriteMemory() && "unhandled aliasing");
1260
2.20M
1261
2.20M
  // We've established mechanical ability and aliasing, it's up to the caller
1262
2.20M
  // to check fault safety
1263
2.20M
  return true;
1264
2.20M
}
1265
1266
/// Returns true if a PHINode is a trivially replaceable with an
1267
/// Instruction.
1268
/// This is true when all incoming values are that instruction.
1269
/// This pattern occurs most often with LCSSA PHI nodes.
1270
///
1271
24.5k
static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) {
1272
24.5k
  for (const Value *IncValue : PN.incoming_values())
1273
32.3k
    if (IncValue != &I)
1274
504
      return false;
1275
24.5k
1276
24.5k
  
return true24.0k
;
1277
24.5k
}
1278
1279
/// Return true if the instruction is free in the loop.
1280
static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop,
1281
13.2M
                         const TargetTransformInfo *TTI) {
1282
13.2M
1283
13.2M
  if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1284
1.80M
    if (TTI->getUserCost(GEP) != TargetTransformInfo::TCC_Free)
1285
366k
      return false;
1286
1.43M
    // For a GEP, we cannot simply use getUserCost because currently it
1287
1.43M
    // optimistically assume that a GEP will fold into addressing mode
1288
1.43M
    // regardless of its users.
1289
1.43M
    const BasicBlock *BB = GEP->getParent();
1290
1.52M
    for (const User *U : GEP->users()) {
1291
1.52M
      const Instruction *UI = cast<Instruction>(U);
1292
1.52M
      if (CurLoop->contains(UI) &&
1293
1.52M
          
(1.48M
BB != UI->getParent()1.48M
||
1294
1.48M
           
(1.31M
!isa<StoreInst>(UI)1.31M
&&
!isa<LoadInst>(UI)1.12M
)))
1295
599k
        return false;
1296
1.52M
    }
1297
1.43M
    
return true838k
;
1298
11.4M
  } else
1299
11.4M
    return TTI->getUserCost(&I) == TargetTransformInfo::TCC_Free;
1300
13.2M
}
1301
1302
/// Return true if the only users of this instruction are outside of
1303
/// the loop. If this is true, we can sink the instruction to the exit
1304
/// blocks of the loop.
1305
///
1306
/// We also return true if the instruction could be folded away in lowering.
1307
/// (e.g.,  a GEP can be folded into a load as an addressing mode in the loop).
1308
static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
1309
                                  const LoopSafetyInfo *SafetyInfo,
1310
13.2M
                                  TargetTransformInfo *TTI, bool &FreeInLoop) {
1311
13.2M
  const auto &BlockColors = SafetyInfo->getBlockColors();
1312
13.2M
  bool IsFree = isFreeInLoop(I, CurLoop, TTI);
1313
13.2M
  for (const User *U : I.users()) {
1314
12.2M
    const Instruction *UI = cast<Instruction>(U);
1315
12.2M
    if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
1316
1.77M
      const BasicBlock *BB = PN->getParent();
1317
1.77M
      // We cannot sink uses in catchswitches.
1318
1.77M
      if (isa<CatchSwitchInst>(BB->getTerminator()))
1319
2
        return false;
1320
1.77M
1321
1.77M
      // We need to sink a callsite to a unique funclet.  Avoid sinking if the
1322
1.77M
      // phi use is too muddled.
1323
1.77M
      if (isa<CallInst>(I))
1324
164k
        if (!BlockColors.empty() &&
1325
164k
            
BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 15
)
1326
0
          return false;
1327
12.2M
    }
1328
12.2M
1329
12.2M
    if (CurLoop->contains(UI)) {
1330
11.8M
      if (IsFree) {
1331
5.22M
        FreeInLoop = true;
1332
5.22M
        continue;
1333
5.22M
      }
1334
6.63M
      return false;
1335
6.63M
    }
1336
12.2M
  }
1337
13.2M
  
return true6.59M
;
1338
13.2M
}
1339
1340
static Instruction *CloneInstructionInExitBlock(
1341
    Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,
1342
23.9k
    const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU) {
1343
23.9k
  Instruction *New;
1344
23.9k
  if (auto *CI = dyn_cast<CallInst>(&I)) {
1345
18
    const auto &BlockColors = SafetyInfo->getBlockColors();
1346
18
1347
18
    // Sinking call-sites need to be handled differently from other
1348
18
    // instructions.  The cloned call-site needs a funclet bundle operand
1349
18
    // appropriate for its location in the CFG.
1350
18
    SmallVector<OperandBundleDef, 1> OpBundles;
1351
18
    for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
1352
18
         BundleIdx != BundleEnd; 
++BundleIdx0
) {
1353
0
      OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
1354
0
      if (Bundle.getTagID() == LLVMContext::OB_funclet)
1355
0
        continue;
1356
0
1357
0
      OpBundles.emplace_back(Bundle);
1358
0
    }
1359
18
1360
18
    if (!BlockColors.empty()) {
1361
5
      const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
1362
5
      assert(CV.size() == 1 && "non-unique color for exit block!");
1363
5
      BasicBlock *BBColor = CV.front();
1364
5
      Instruction *EHPad = BBColor->getFirstNonPHI();
1365
5
      if (EHPad->isEHPad())
1366
2
        OpBundles.emplace_back("funclet", EHPad);
1367
5
    }
1368
18
1369
18
    New = CallInst::Create(CI, OpBundles);
1370
23.9k
  } else {
1371
23.9k
    New = I.clone();
1372
23.9k
  }
1373
23.9k
1374
23.9k
  ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
1375
23.9k
  if (!I.getName().empty())
1376
2.94k
    New->setName(I.getName() + ".le");
1377
23.9k
1378
23.9k
  MemoryAccess *OldMemAcc;
1379
23.9k
  if (MSSAU && 
(OldMemAcc = MSSAU->getMemorySSA()->getMemoryAccess(&I))36
) {
1380
6
    // Create a new MemoryAccess and let MemorySSA set its defining access.
1381
6
    MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1382
6
        New, nullptr, New->getParent(), MemorySSA::Beginning);
1383
6
    if (NewMemAcc) {
1384
6
      if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc))
1385
0
        MSSAU->insertDef(MemDef, /*RenameUses=*/true);
1386
6
      else {
1387
6
        auto *MemUse = cast<MemoryUse>(NewMemAcc);
1388
6
        MSSAU->insertUse(MemUse);
1389
6
      }
1390
6
    }
1391
6
  }
1392
23.9k
1393
23.9k
  // Build LCSSA PHI nodes for any in-loop operands. Note that this is
1394
23.9k
  // particularly cheap because we can rip off the PHI node that we're
1395
23.9k
  // replacing for the number and blocks of the predecessors.
1396
23.9k
  // OPT: If this shows up in a profile, we can instead finish sinking all
1397
23.9k
  // invariant instructions, and then walk their operands to re-establish
1398
23.9k
  // LCSSA. That will eliminate creating PHI nodes just to nuke them when
1399
23.9k
  // sinking bottom-up.
1400
55.1k
  for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
1401
31.1k
       ++OI)
1402
31.1k
    if (Instruction *OInst = dyn_cast<Instruction>(*OI))
1403
24.1k
      if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
1404
17.1k
        if (!OLoop->contains(&PN)) {
1405
16.9k
          PHINode *OpPN =
1406
16.9k
              PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
1407
16.9k
                              OInst->getName() + ".lcssa", &ExitBlock.front());
1408
35.8k
          for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; 
++i18.9k
)
1409
18.9k
            OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
1410
16.9k
          *OI = OpPN;
1411
16.9k
        }
1412
23.9k
  return New;
1413
23.9k
}
1414
1415
static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo,
1416
28.0k
                             AliasSetTracker *AST, MemorySSAUpdater *MSSAU) {
1417
28.0k
  if (AST)
1418
3.99k
    AST->deleteValue(&I);
1419
28.0k
  if (MSSAU)
1420
40
    MSSAU->removeMemoryAccess(&I);
1421
28.0k
  SafetyInfo.removeInstruction(&I);
1422
28.0k
  I.eraseFromParent();
1423
28.0k
}
1424
1425
static void moveInstructionBefore(Instruction &I, Instruction &Dest,
1426
                                  ICFLoopSafetyInfo &SafetyInfo,
1427
188k
                                  MemorySSAUpdater *MSSAU) {
1428
188k
  SafetyInfo.removeInstruction(&I);
1429
188k
  SafetyInfo.insertInstructionTo(&I, Dest.getParent());
1430
188k
  I.moveBefore(&Dest);
1431
188k
  if (MSSAU)
1432
233
    if (MemoryUseOrDef *OldMemAcc = cast_or_null<MemoryUseOrDef>(
1433
51
            MSSAU->getMemorySSA()->getMemoryAccess(&I)))
1434
51
      MSSAU->moveToPlace(OldMemAcc, Dest.getParent(), MemorySSA::End);
1435
188k
}
1436
1437
static Instruction *sinkThroughTriviallyReplaceablePHI(
1438
    PHINode *TPN, Instruction *I, LoopInfo *LI,
1439
    SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies,
1440
    const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop,
1441
24.0k
    MemorySSAUpdater *MSSAU) {
1442
24.0k
  assert(isTriviallyReplaceablePHI(*TPN, *I) &&
1443
24.0k
         "Expect only trivially replaceable PHI");
1444
24.0k
  BasicBlock *ExitBlock = TPN->getParent();
1445
24.0k
  Instruction *New;
1446
24.0k
  auto It = SunkCopies.find(ExitBlock);
1447
24.0k
  if (It != SunkCopies.end())
1448
76
    New = It->second;
1449
23.9k
  else
1450
23.9k
    New = SunkCopies[ExitBlock] = CloneInstructionInExitBlock(
1451
23.9k
        *I, *ExitBlock, *TPN, LI, SafetyInfo, MSSAU);
1452
24.0k
  return New;
1453
24.0k
}
1454
1455
504
static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) {
1456
504
  BasicBlock *BB = PN->getParent();
1457
504
  if (!BB->canSplitPredecessors())
1458
6
    return false;
1459
498
  // It's not impossible to split EHPad blocks, but if BlockColors already exist
1460
498
  // it require updating BlockColors for all offspring blocks accordingly. By
1461
498
  // skipping such corner case, we can make updating BlockColors after splitting
1462
498
  // predecessor fairly simple.
1463
498
  if (!SafetyInfo->getBlockColors().empty() && 
BB->getFirstNonPHI()->isEHPad()6
)
1464
3
    return false;
1465
1.69k
  
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); 495
PI != E;
++PI1.20k
) {
1466
1.20k
    BasicBlock *BBPred = *PI;
1467
1.20k
    if (isa<IndirectBrInst>(BBPred->getTerminator()))
1468
6
      return false;
1469
1.20k
  }
1470
495
  
return true489
;
1471
495
}
1472
1473
static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT,
1474
                                        LoopInfo *LI, const Loop *CurLoop,
1475
                                        LoopSafetyInfo *SafetyInfo,
1476
489
                                        MemorySSAUpdater *MSSAU) {
1477
#ifndef NDEBUG
1478
  SmallVector<BasicBlock *, 32> ExitBlocks;
1479
  CurLoop->getUniqueExitBlocks(ExitBlocks);
1480
  SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
1481
                                             ExitBlocks.end());
1482
#endif
1483
  BasicBlock *ExitBB = PN->getParent();
1484
489
  assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.");
1485
489
1486
489
  // Split predecessors of the loop exit to make instructions in the loop are
1487
489
  // exposed to exit blocks through trivially replaceable PHIs while keeping the
1488
489
  // loop in the canonical form where each predecessor of each exit block should
1489
489
  // be contained within the loop. For example, this will convert the loop below
1490
489
  // from
1491
489
  //
1492
489
  // LB1:
1493
489
  //   %v1 =
1494
489
  //   br %LE, %LB2
1495
489
  // LB2:
1496
489
  //   %v2 =
1497
489
  //   br %LE, %LB1
1498
489
  // LE:
1499
489
  //   %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable
1500
489
  //
1501
489
  // to
1502
489
  //
1503
489
  // LB1:
1504
489
  //   %v1 =
1505
489
  //   br %LE.split, %LB2
1506
489
  // LB2:
1507
489
  //   %v2 =
1508
489
  //   br %LE.split2, %LB1
1509
489
  // LE.split:
1510
489
  //   %p1 = phi [%v1, %LB1]  <-- trivially replaceable
1511
489
  //   br %LE
1512
489
  // LE.split2:
1513
489
  //   %p2 = phi [%v2, %LB2]  <-- trivially replaceable
1514
489
  //   br %LE
1515
489
  // LE:
1516
489
  //   %p = phi [%p1, %LE.split], [%p2, %LE.split2]
1517
489
  //
1518
489
  const auto &BlockColors = SafetyInfo->getBlockColors();
1519
489
  SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));
1520
1.68k
  while (!PredBBs.empty()) {
1521
1.19k
    BasicBlock *PredBB = *PredBBs.begin();
1522
1.19k
    assert(CurLoop->contains(PredBB) &&
1523
1.19k
           "Expect all predecessors are in the loop");
1524
1.19k
    if (PN->getBasicBlockIndex(PredBB) >= 0) {
1525
1.15k
      BasicBlock *NewPred = SplitBlockPredecessors(
1526
1.15k
          ExitBB, PredBB, ".split.loop.exit", DT, LI, MSSAU, true);
1527
1.15k
      // Since we do not allow splitting EH-block with BlockColors in
1528
1.15k
      // canSplitPredecessors(), we can simply assign predecessor's color to
1529
1.15k
      // the new block.
1530
1.15k
      if (!BlockColors.empty())
1531
6
        // Grab a reference to the ColorVector to be inserted before getting the
1532
6
        // reference to the vector we are copying because inserting the new
1533
6
        // element in BlockColors might cause the map to be reallocated.
1534
6
        SafetyInfo->copyColors(NewPred, PredBB);
1535
1.15k
    }
1536
1.19k
    PredBBs.remove(PredBB);
1537
1.19k
  }
1538
489
}
1539
1540
/// When an instruction is found to only be used outside of the loop, this
1541
/// function moves it to the exit blocks and patches up SSA form as needed.
1542
/// This method is guaranteed to remove the original instruction from its
1543
/// position, and may either delete it or move it to outside of the loop.
1544
///
1545
static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
1546
                 const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo,
1547
2.03M
                 MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE) {
1548
2.03M
  LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
1549
2.03M
  ORE->emit([&]() {
1550
93
    return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
1551
93
           << "sinking " << ore::NV("Inst", &I);
1552
93
  });
1553
2.03M
  bool Changed = false;
1554
2.03M
  if (isa<LoadInst>(I))
1555
97
    ++NumMovedLoads;
1556
2.03M
  else if (isa<CallInst>(I))
1557
3.26k
    ++NumMovedCalls;
1558
2.03M
  ++NumSunk;
1559
2.03M
1560
2.03M
  // Iterate over users to be ready for actual sinking. Replace users via
1561
2.03M
  // unreachable blocks with undef and make all user PHIs trivially replaceable.
1562
2.03M
  SmallPtrSet<Instruction *, 8> VisitedUsers;
1563
4.30M
  for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) {
1564
2.26M
    auto *User = cast<Instruction>(*UI);
1565
2.26M
    Use &U = UI.getUse();
1566
2.26M
    ++UI;
1567
2.26M
1568
2.26M
    if (VisitedUsers.count(User) || 
CurLoop->contains(User)2.25M
)
1569
2.24M
      continue;
1570
24.5k
1571
24.5k
    if (!DT->isReachableFromEntry(User->getParent())) {
1572
3
      U = UndefValue::get(I.getType());
1573
3
      Changed = true;
1574
3
      continue;
1575
3
    }
1576
24.5k
1577
24.5k
    // The user must be a PHI node.
1578
24.5k
    PHINode *PN = cast<PHINode>(User);
1579
24.5k
1580
24.5k
    // Surprisingly, instructions can be used outside of loops without any
1581
24.5k
    // exits.  This can only happen in PHI nodes if the incoming block is
1582
24.5k
    // unreachable.
1583
24.5k
    BasicBlock *BB = PN->getIncomingBlock(U);
1584
24.5k
    if (!DT->isReachableFromEntry(BB)) {
1585
1
      U = UndefValue::get(I.getType());
1586
1
      Changed = true;
1587
1
      continue;
1588
1
    }
1589
24.5k
1590
24.5k
    VisitedUsers.insert(PN);
1591
24.5k
    if (isTriviallyReplaceablePHI(*PN, I))
1592
24.0k
      continue;
1593
504
1594
504
    if (!canSplitPredecessors(PN, SafetyInfo))
1595
15
      return Changed;
1596
489
1597
489
    // Split predecessors of the PHI so that we can make users trivially
1598
489
    // replaceable.
1599
489
    splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo, MSSAU);
1600
489
1601
489
    // Should rebuild the iterators, as they may be invalidated by
1602
489
    // splitPredecessorsOfLoopExit().
1603
489
    UI = I.user_begin();
1604
489
    UE = I.user_end();
1605
489
  }
1606
2.03M
1607
2.03M
  
if (2.03M
VisitedUsers.empty()2.03M
)
1608
2.01M
    return Changed;
1609
17.7k
1610
#ifndef NDEBUG
1611
  SmallVector<BasicBlock *, 32> ExitBlocks;
1612
  CurLoop->getUniqueExitBlocks(ExitBlocks);
1613
  SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
1614
                                             ExitBlocks.end());
1615
#endif
1616
1617
17.7k
  // Clones of this instruction. Don't create more than one per exit block!
1618
17.7k
  SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
1619
17.7k
1620
17.7k
  // If this instruction is only used outside of the loop, then all users are
1621
17.7k
  // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
1622
17.7k
  // the instruction.
1623
17.7k
  SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end());
1624
44.8k
  for (auto *UI : Users) {
1625
44.8k
    auto *User = cast<Instruction>(UI);
1626
44.8k
1627
44.8k
    if (CurLoop->contains(User))
1628
20.8k
      continue;
1629
24.0k
1630
24.0k
    PHINode *PN = cast<PHINode>(User);
1631
24.0k
    assert(ExitBlockSet.count(PN->getParent()) &&
1632
24.0k
           "The LCSSA PHI is not in an exit block!");
1633
24.0k
    // The PHI must be trivially replaceable.
1634
24.0k
    Instruction *New = sinkThroughTriviallyReplaceablePHI(
1635
24.0k
        PN, &I, LI, SunkCopies, SafetyInfo, CurLoop, MSSAU);
1636
24.0k
    PN->replaceAllUsesWith(New);
1637
24.0k
    eraseInstruction(*PN, *SafetyInfo, nullptr, nullptr);
1638
24.0k
    Changed = true;
1639
24.0k
  }
1640
17.7k
  return Changed;
1641
17.7k
}
1642
1643
/// When an instruction is found to only use loop invariant operands that
1644
/// is safe to hoist, this instruction is called to do the dirty work.
1645
///
1646
static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
1647
                  BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,
1648
188k
                  MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE) {
1649
188k
  LLVM_DEBUG(dbgs() << "LICM hoisting to " << Dest->getName() << ": " << I
1650
188k
                    << "\n");
1651
188k
  ORE->emit([&]() {
1652
18
    return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting "
1653
18
                                                         << ore::NV("Inst", &I);
1654
18
  });
1655
188k
1656
188k
  // Metadata can be dependent on conditions we are hoisting above.
1657
188k
  // Conservatively strip all metadata on the instruction unless we were
1658
188k
  // guaranteed to execute I if we entered the loop, in which case the metadata
1659
188k
  // is valid in the loop preheader.
1660
188k
  if (I.hasMetadataOtherThanDebugLoc() &&
1661
188k
      // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
1662
188k
      // time in isGuaranteedToExecute if we don't actually have anything to
1663
188k
      // drop.  It is a compile time optimization, not required for correctness.
1664
188k
      
!SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop)17.5k
)
1665
1.87k
    I.dropUnknownNonDebugMetadata();
1666
188k
1667
188k
  if (isa<PHINode>(I))
1668
69
    // Move the new node to the end of the phi list in the destination block.
1669
69
    moveInstructionBefore(I, *Dest->getFirstNonPHI(), *SafetyInfo, MSSAU);
1670
188k
  else
1671
188k
    // Move the new node to the destination block, before its terminator.
1672
188k
    moveInstructionBefore(I, *Dest->getTerminator(), *SafetyInfo, MSSAU);
1673
188k
1674
188k
  // Apply line 0 debug locations when we are moving instructions to different
1675
188k
  // basic blocks because we want to avoid jumpy line tables.
1676
188k
  if (const DebugLoc &DL = I.getDebugLoc())
1677
25.6k
    I.setDebugLoc(DebugLoc::get(0, 0, DL.getScope(), DL.getInlinedAt()));
1678
188k
1679
188k
  if (isa<LoadInst>(I))
1680
19.0k
    ++NumMovedLoads;
1681
169k
  else if (isa<CallInst>(I))
1682
829
    ++NumMovedCalls;
1683
188k
  ++NumHoisted;
1684
188k
}
1685
1686
/// Only sink or hoist an instruction if it is not a trapping instruction,
1687
/// or if the instruction is known not to trap when moved to the preheader.
1688
/// or if it is a trapping instruction and is guaranteed to execute.
1689
static bool isSafeToExecuteUnconditionally(Instruction &Inst,
1690
                                           const DominatorTree *DT,
1691
                                           const Loop *CurLoop,
1692
                                           const LoopSafetyInfo *SafetyInfo,
1693
                                           OptimizationRemarkEmitter *ORE,
1694
203k
                                           const Instruction *CtxI) {
1695
203k
  if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
1696
178k
    return true;
1697
24.9k
1698
24.9k
  bool GuaranteedToExecute =
1699
24.9k
      SafetyInfo->isGuaranteedToExecute(Inst, DT, CurLoop);
1700
24.9k
1701
24.9k
  if (!GuaranteedToExecute) {
1702
13.6k
    auto *LI = dyn_cast<LoadInst>(&Inst);
1703
13.6k
    if (LI && 
CurLoop->isLoopInvariant(LI->getPointerOperand())10.7k
)
1704
10.7k
      ORE->emit([&]() {
1705
2
        return OptimizationRemarkMissed(
1706
2
                   DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
1707
2
               << "failed to hoist load with loop-invariant address "
1708
2
                  "because load is conditionally executed";
1709
2
      });
1710
13.6k
  }
1711
24.9k
1712
24.9k
  return GuaranteedToExecute;
1713
24.9k
}
1714
1715
namespace {
1716
class LoopPromoter : public LoadAndStorePromoter {
1717
  Value *SomePtr; // Designated pointer to store to.
1718
  const SmallSetVector<Value *, 8> &PointerMustAliases;
1719
  SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
1720
  SmallVectorImpl<Instruction *> &LoopInsertPts;
1721
  SmallVectorImpl<MemoryAccess *> &MSSAInsertPts;
1722
  PredIteratorCache &PredCache;
1723
  AliasSetTracker &AST;
1724
  MemorySSAUpdater *MSSAU;
1725
  LoopInfo &LI;
1726
  DebugLoc DL;
1727
  int Alignment;
1728
  bool UnorderedAtomic;
1729
  AAMDNodes AATags;
1730
  ICFLoopSafetyInfo &SafetyInfo;
1731
1732
5.36k
  Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
1733
5.36k
    if (Instruction *I = dyn_cast<Instruction>(V))
1734
4.30k
      if (Loop *L = LI.getLoopFor(I->getParent()))
1735
2.76k
        if (!L->contains(BB)) {
1736
2.52k
          // We need to create an LCSSA PHI node for the incoming value and
1737
2.52k
          // store that.
1738
2.52k
          PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
1739
2.52k
                                        I->getName() + ".lcssa", &BB->front());
1740
2.52k
          for (BasicBlock *Pred : PredCache.get(BB))
1741
2.54k
            PN->addIncoming(I, Pred);
1742
2.52k
          return PN;
1743
2.52k
        }
1744
2.84k
    return V;
1745
2.84k
  }
1746
1747
public:
1748
  LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
1749
               const SmallSetVector<Value *, 8> &PMA,
1750
               SmallVectorImpl<BasicBlock *> &LEB,
1751
               SmallVectorImpl<Instruction *> &LIP,
1752
               SmallVectorImpl<MemoryAccess *> &MSSAIP, PredIteratorCache &PIC,
1753
               AliasSetTracker &ast, MemorySSAUpdater *MSSAU, LoopInfo &li,
1754
               DebugLoc dl, int alignment, bool UnorderedAtomic,
1755
               const AAMDNodes &AATags, ICFLoopSafetyInfo &SafetyInfo)
1756
      : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
1757
        LoopExitBlocks(LEB), LoopInsertPts(LIP), MSSAInsertPts(MSSAIP),
1758
        PredCache(PIC), AST(ast), MSSAU(MSSAU), LI(li), DL(std::move(dl)),
1759
        Alignment(alignment), UnorderedAtomic(UnorderedAtomic), AATags(AATags),
1760
2.46k
        SafetyInfo(SafetyInfo) {}
1761
1762
  bool isInstInList(Instruction *I,
1763
18.2k
                    const SmallVectorImpl<Instruction *> &) const override {
1764
18.2k
    Value *Ptr;
1765
18.2k
    if (LoadInst *LI = dyn_cast<LoadInst>(I))
1766
12.0k
      Ptr = LI->getOperand(0);
1767
6.24k
    else
1768
6.24k
      Ptr = cast<StoreInst>(I)->getPointerOperand();
1769
18.2k
    return PointerMustAliases.count(Ptr);
1770
18.2k
  }
1771
1772
2.46k
  void doExtraRewritesBeforeFinalDeletion() override {
1773
2.46k
    // Insert stores after in the loop exit blocks.  Each exit block gets a
1774
2.46k
    // store of the live-out values that feed them.  Since we've already told
1775
2.46k
    // the SSA updater about the defs in the loop and the preheader
1776
2.46k
    // definition, it is all set and we can start using it.
1777
5.15k
    for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; 
++i2.68k
) {
1778
2.68k
      BasicBlock *ExitBlock = LoopExitBlocks[i];
1779
2.68k
      Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1780
2.68k
      LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1781
2.68k
      Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1782
2.68k
      Instruction *InsertPos = LoopInsertPts[i];
1783
2.68k
      StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
1784
2.68k
      if (UnorderedAtomic)
1785
8
        NewSI->setOrdering(AtomicOrdering::Unordered);
1786
2.68k
      NewSI->setAlignment(Alignment);
1787
2.68k
      NewSI->setDebugLoc(DL);
1788
2.68k
      if (AATags)
1789
2.46k
        NewSI->setAAMetadata(AATags);
1790
2.68k
1791
2.68k
      if (MSSAU) {
1792
11
        MemoryAccess *MSSAInsertPoint = MSSAInsertPts[i];
1793
11
        MemoryAccess *NewMemAcc;
1794
11
        if (!MSSAInsertPoint) {
1795
11
          NewMemAcc = MSSAU->createMemoryAccessInBB(
1796
11
              NewSI, nullptr, NewSI->getParent(), MemorySSA::Beginning);
1797
11
        } else {
1798
0
          NewMemAcc =
1799
0
              MSSAU->createMemoryAccessAfter(NewSI, nullptr, MSSAInsertPoint);
1800
0
        }
1801
11
        MSSAInsertPts[i] = NewMemAcc;
1802
11
        MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
1803
11
        // FIXME: true for safety, false may still be correct.
1804
11
      }
1805
2.68k
    }
1806
2.46k
  }
1807
1808
1.86k
  void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
1809
1.86k
    // Update alias analysis.
1810
1.86k
    AST.copyValue(LI, V);
1811
1.86k
  }
1812
4.76k
  void instructionDeleted(Instruction *I) const override {
1813
4.76k
    SafetyInfo.removeInstruction(I);
1814
4.76k
    AST.deleteValue(I);
1815
4.76k
    if (MSSAU)
1816
13
      MSSAU->removeMemoryAccess(I);
1817
4.76k
  }
1818
};
1819
1820
1821
/// Return true iff we can prove that a caller of this function can not inspect
1822
/// the contents of the provided object in a well defined program.
1823
964
bool isKnownNonEscaping(Value *Object, const TargetLibraryInfo *TLI) {
1824
964
  if (isa<AllocaInst>(Object))
1825
749
    // Since the alloca goes out of scope, we know the caller can't retain a
1826
749
    // reference to it and be well defined.  Thus, we don't need to check for
1827
749
    // capture.
1828
749
    return true;
1829
215
1830
215
  // For all other objects we need to know that the caller can't possibly
1831
215
  // have gotten a reference to the object.  There are two components of
1832
215
  // that:
1833
215
  //   1) Object can't be escaped by this function.  This is what
1834
215
  //      PointerMayBeCaptured checks.
1835
215
  //   2) Object can't have been captured at definition site.  For this, we
1836
215
  //      need to know the return value is noalias.  At the moment, we use a
1837
215
  //      weaker condition and handle only AllocLikeFunctions (which are
1838
215
  //      known to be noalias).  TODO
1839
215
  return isAllocLikeFn(Object, TLI) &&
1840
215
    
!PointerMayBeCaptured(Object, true, true)47
;
1841
215
}
1842
1843
} // namespace
1844
1845
/// Try to promote memory values to scalars by sinking stores out of the
1846
/// loop and moving loads to before the loop.  We do this by looping over
1847
/// the stores in the loop, looking for stores to Must pointers which are
1848
/// loop invariant.
1849
///
1850
bool llvm::promoteLoopAccessesToScalars(
1851
    const SmallSetVector<Value *, 8> &PointerMustAliases,
1852
    SmallVectorImpl<BasicBlock *> &ExitBlocks,
1853
    SmallVectorImpl<Instruction *> &InsertPts,
1854
    SmallVectorImpl<MemoryAccess *> &MSSAInsertPts, PredIteratorCache &PIC,
1855
    LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
1856
    Loop *CurLoop, AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU,
1857
8.37k
    ICFLoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE) {
1858
8.37k
  // Verify inputs.
1859
8.37k
  assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
1860
8.37k
         CurAST != nullptr && SafetyInfo != nullptr &&
1861
8.37k
         "Unexpected Input to promoteLoopAccessesToScalars");
1862
8.37k
1863
8.37k
  Value *SomePtr = *PointerMustAliases.begin();
1864
8.37k
  BasicBlock *Preheader = CurLoop->getLoopPreheader();
1865
8.37k
1866
8.37k
  // It is not safe to promote a load/store from the loop if the load/store is
1867
8.37k
  // conditional.  For example, turning:
1868
8.37k
  //
1869
8.37k
  //    for () { if (c) *P += 1; }
1870
8.37k
  //
1871
8.37k
  // into:
1872
8.37k
  //
1873
8.37k
  //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
1874
8.37k
  //
1875
8.37k
  // is not safe, because *P may only be valid to access if 'c' is true.
1876
8.37k
  //
1877
8.37k
  // The safety property divides into two parts:
1878
8.37k
  // p1) The memory may not be dereferenceable on entry to the loop.  In this
1879
8.37k
  //    case, we can't insert the required load in the preheader.
1880
8.37k
  // p2) The memory model does not allow us to insert a store along any dynamic
1881
8.37k
  //    path which did not originally have one.
1882
8.37k
  //
1883
8.37k
  // If at least one store is guaranteed to execute, both properties are
1884
8.37k
  // satisfied, and promotion is legal.
1885
8.37k
  //
1886
8.37k
  // This, however, is not a necessary condition. Even if no store/load is
1887
8.37k
  // guaranteed to execute, we can still establish these properties.
1888
8.37k
  // We can establish (p1) by proving that hoisting the load into the preheader
1889
8.37k
  // is safe (i.e. proving dereferenceability on all paths through the loop). We
1890
8.37k
  // can use any access within the alias set to prove dereferenceability,
1891
8.37k
  // since they're all must alias.
1892
8.37k
  //
1893
8.37k
  // There are two ways establish (p2):
1894
8.37k
  // a) Prove the location is thread-local. In this case the memory model
1895
8.37k
  // requirement does not apply, and stores are safe to insert.
1896
8.37k
  // b) Prove a store dominates every exit block. In this case, if an exit
1897
8.37k
  // blocks is reached, the original dynamic path would have taken us through
1898
8.37k
  // the store, so inserting a store into the exit block is safe. Note that this
1899
8.37k
  // is different from the store being guaranteed to execute. For instance,
1900
8.37k
  // if an exception is thrown on the first iteration of the loop, the original
1901
8.37k
  // store is never executed, but the exit blocks are not executed either.
1902
8.37k
1903
8.37k
  bool DereferenceableInPH = false;
1904
8.37k
  bool SafeToInsertStore = false;
1905
8.37k
1906
8.37k
  SmallVector<Instruction *, 64> LoopUses;
1907
8.37k
1908
8.37k
  // We start with an alignment of one and try to find instructions that allow
1909
8.37k
  // us to prove better alignment.
1910
8.37k
  unsigned Alignment = 1;
1911
8.37k
  // Keep track of which types of access we see
1912
8.37k
  bool SawUnorderedAtomic = false;
1913
8.37k
  bool SawNotAtomic = false;
1914
8.37k
  AAMDNodes AATags;
1915
8.37k
1916
8.37k
  const DataLayout &MDL = Preheader->getModule()->getDataLayout();
1917
8.37k
1918
8.37k
  bool IsKnownThreadLocalObject = false;
1919
8.37k
  if (SafetyInfo->anyBlockMayThrow()) {
1920
964
    // If a loop can throw, we have to insert a store along each unwind edge.
1921
964
    // That said, we can't actually make the unwind edge explicit. Therefore,
1922
964
    // we have to prove that the store is dead along the unwind edge.  We do
1923
964
    // this by proving that the caller can't have a reference to the object
1924
964
    // after return and thus can't possibly load from the object.
1925
964
    Value *Object = GetUnderlyingObject(SomePtr, MDL);
1926
964
    if (!isKnownNonEscaping(Object, TLI))
1927
173
      return false;
1928
791
    // Subtlety: Alloca's aren't visible to callers, but *are* potentially
1929
791
    // visible to other threads if captured and used during their lifetimes.
1930
791
    IsKnownThreadLocalObject = !isa<AllocaInst>(Object);
1931
791
  }
1932
8.37k
1933
8.37k
  // Check that all of the pointers in the alias set have the same type.  We
1934
8.37k
  // cannot (yet) promote a memory location that is loaded and stored in
1935
8.37k
  // different sizes.  While we are at it, collect alignment and AA info.
1936
8.58k
  
for (Value *ASIV : PointerMustAliases)8.20k
{
1937
8.58k
    // Check that all of the pointers in the alias set have the same type.  We
1938
8.58k
    // cannot (yet) promote a memory location that is loaded and stored in
1939
8.58k
    // different sizes.
1940
8.58k
    if (SomePtr->getType() != ASIV->getType())
1941
247
      return false;
1942
8.34k
1943
70.9k
    
for (User *U : ASIV->users())8.34k
{
1944
70.9k
      // Ignore instructions that are outside the loop.
1945
70.9k
      Instruction *UI = dyn_cast<Instruction>(U);
1946
70.9k
      if (!UI || 
!CurLoop->contains(UI)70.8k
)
1947
57.7k
        continue;
1948
13.2k
1949
13.2k
      // If there is an non-load/store instruction in the loop, we can't promote
1950
13.2k
      // it.
1951
13.2k
      if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
1952
4.23k
        if (!Load->isUnordered())
1953
246
          return false;
1954
3.98k
1955
3.98k
        SawUnorderedAtomic |= Load->isAtomic();
1956
3.98k
        SawNotAtomic |= !Load->isAtomic();
1957
3.98k
1958
3.98k
        unsigned InstAlignment = Load->getAlignment();
1959
3.98k
        if (!InstAlignment)
1960
70
          InstAlignment =
1961
70
              MDL.getABITypeAlignment(Load->getType());
1962
3.98k
1963
3.98k
        // Note that proving a load safe to speculate requires proving
1964
3.98k
        // sufficient alignment at the target location.  Proving it guaranteed
1965
3.98k
        // to execute does as well.  Thus we can increase our guaranteed
1966
3.98k
        // alignment as well. 
1967
3.98k
        if (!DereferenceableInPH || 
(InstAlignment > Alignment)1.95k
)
1968
2.50k
          if (isSafeToExecuteUnconditionally(*Load, DT, CurLoop, SafetyInfo,
1969
2.50k
                                             ORE, Preheader->getTerminator())) {
1970
1.26k
            DereferenceableInPH = true;
1971
1.26k
            Alignment = std::max(Alignment, InstAlignment);
1972
1.26k
          }
1973
9.00k
      } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
1974
7.42k
        // Stores *of* the pointer are not interesting, only stores *to* the
1975
7.42k
        // pointer.
1976
7.42k
        if (UI->getOperand(1) != ASIV)
1977
6
          continue;
1978
7.41k
        if (!Store->isUnordered())
1979
88
          return false;
1980
7.33k
1981
7.33k
        SawUnorderedAtomic |= Store->isAtomic();
1982
7.33k
        SawNotAtomic |= !Store->isAtomic();
1983
7.33k
1984
7.33k
        // If the store is guaranteed to execute, both properties are satisfied.
1985
7.33k
        // We may want to check if a store is guaranteed to execute even if we
1986
7.33k
        // already know that promotion is safe, since it may have higher
1987
7.33k
        // alignment than any other guaranteed stores, in which case we can
1988
7.33k
        // raise the alignment on the promoted store.
1989
7.33k
        unsigned InstAlignment = Store->getAlignment();
1990
7.33k
        if (!InstAlignment)
1991
221
          InstAlignment =
1992
221
              MDL.getABITypeAlignment(Store->getValueOperand()->getType());
1993
7.33k
1994
7.33k
        if (!DereferenceableInPH || 
!SafeToInsertStore1.65k
||
1995
7.33k
            
(InstAlignment > Alignment)345
) {
1996
6.98k
          if (SafetyInfo->isGuaranteedToExecute(*UI, DT, CurLoop)) {
1997
2.31k
            DereferenceableInPH = true;
1998
2.31k
            SafeToInsertStore = true;
1999
2.31k
            Alignment = std::max(Alignment, InstAlignment);
2000
2.31k
          }
2001
6.98k
        }
2002
7.33k
2003
7.33k
        // If a store dominates all exit blocks, it is safe to sink.
2004
7.33k
        // As explained above, if an exit block was executed, a dominating
2005
7.33k
        // store must have been executed at least once, so we are not
2006
7.33k
        // introducing stores on paths that did not have them.
2007
7.33k
        // Note that this only looks at explicit exit blocks. If we ever
2008
7.33k
        // start sinking stores into unwind edges (see above), this will break.
2009
7.33k
        if (!SafeToInsertStore)
2010
4.67k
          
SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) 4.65k
{
2011
4.67k
            return DT->dominates(Store->getParent(), Exit);
2012
4.67k
          });
2013
7.33k
2014
7.33k
        // If the store is not guaranteed to execute, we may still get
2015
7.33k
        // deref info through it.
2016
7.33k
        if (!DereferenceableInPH) {
2017
3.87k
          DereferenceableInPH = isDereferenceableAndAlignedPointer(
2018
3.87k
              Store->getPointerOperand(), Store->getValueOperand()->getType(),
2019
3.87k
              Store->getAlignment(), MDL, Preheader->getTerminator(), DT);
2020
3.87k
        }
2021
7.33k
      } else
2022
1.58k
        return false; // Not a load or store.
2023
11.3k
2024
11.3k
      // Merge the AA tags.
2025
11.3k
      if (LoopUses.empty()) {
2026
6.22k
        // On the first load/store, just take its AA tags.
2027
6.22k
        UI->getAAMetadata(AATags);
2028
6.22k
      } else 
if (5.08k
AATags5.08k
) {
2029
4.74k
        UI->getAAMetadata(AATags, /* Merge = */ true);
2030
4.74k
      }
2031
11.3k
2032
11.3k
      LoopUses.push_back(UI);
2033
11.3k
    }
2034
8.34k
  }
2035
8.20k
2036
8.20k
  // If we found both an unordered atomic instruction and a non-atomic memory
2037
8.20k
  // access, bail.  We can't blindly promote non-atomic to atomic since we
2038
8.20k
  // might not be able to lower the result.  We can't downgrade since that
2039
8.20k
  // would violate memory model.  Also, align 0 is an error for atomics.
2040
8.20k
  
if (6.04k
SawUnorderedAtomic6.04k
&&
SawNotAtomic10
)
2041
2
    return false;
2042
6.04k
2043
6.04k
  // If we're inserting an atomic load in the preheader, we must be able to
2044
6.04k
  // lower it.  We're only guaranteed to be able to lower naturally aligned
2045
6.04k
  // atomics.
2046
6.04k
  auto *SomePtrElemType = SomePtr->getType()->getPointerElementType();
2047
6.04k
  if (SawUnorderedAtomic &&
2048
6.04k
      
Alignment < MDL.getTypeStoreSize(SomePtrElemType)8
)
2049
0
    return false;
2050
6.04k
2051
6.04k
  // If we couldn't prove we can hoist the load, bail.
2052
6.04k
  if (!DereferenceableInPH)
2053
2.36k
    return false;
2054
3.68k
2055
3.68k
  // We know we can hoist the load, but don't have a guaranteed store.
2056
3.68k
  // Check whether the location is thread-local. If it is, then we can insert
2057
3.68k
  // stores along paths which originally didn't have them without violating the
2058
3.68k
  // memory model.
2059
3.68k
  if (!SafeToInsertStore) {
2060
1.34k
    if (IsKnownThreadLocalObject)
2061
0
      SafeToInsertStore = true;
2062
1.34k
    else {
2063
1.34k
      Value *Object = GetUnderlyingObject(SomePtr, MDL);
2064
1.34k
      SafeToInsertStore =
2065
1.34k
          (isAllocLikeFn(Object, TLI) || 
isa<AllocaInst>(Object)1.33k
) &&
2066
1.34k
          
!PointerMayBeCaptured(Object, true, true)385
;
2067
1.34k
    }
2068
1.34k
  }
2069
3.68k
2070
3.68k
  // If we've still failed to prove we can sink the store, give up.
2071
3.68k
  if (!SafeToInsertStore)
2072
1.21k
    return false;
2073
2.46k
2074
2.46k
  // Otherwise, this is safe to promote, lets do it!
2075
2.46k
  LLVM_DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
2076
2.46k
                    << '\n');
2077
2.46k
  ORE->emit([&]() {
2078
8
    return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar",
2079
8
                              LoopUses[0])
2080
8
           << "Moving accesses to memory location out of the loop";
2081
8
  });
2082
2.46k
  ++NumPromoted;
2083
2.46k
2084
2.46k
  // Grab a debug location for the inserted loads/stores; given that the
2085
2.46k
  // inserted loads/stores have little relation to the original loads/stores,
2086
2.46k
  // this code just arbitrarily picks a location from one, since any debug
2087
2.46k
  // location is better than none.
2088
2.46k
  DebugLoc DL = LoopUses[0]->getDebugLoc();
2089
2.46k
2090
2.46k
  // We use the SSAUpdater interface to insert phi nodes as required.
2091
2.46k
  SmallVector<PHINode *, 16> NewPHIs;
2092
2.46k
  SSAUpdater SSA(&NewPHIs);
2093
2.46k
  LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
2094
2.46k
                        InsertPts, MSSAInsertPts, PIC, *CurAST, MSSAU, *LI, DL,
2095
2.46k
                        Alignment, SawUnorderedAtomic, AATags, *SafetyInfo);
2096
2.46k
2097
2.46k
  // Set up the preheader to have a definition of the value.  It is the live-out
2098
2.46k
  // value from the preheader that uses in the loop will use.
2099
2.46k
  LoadInst *PreheaderLoad = new LoadInst(
2100
2.46k
      SomePtr->getType()->getPointerElementType(), SomePtr,
2101
2.46k
      SomePtr->getName() + ".promoted", Preheader->getTerminator());
2102
2.46k
  if (SawUnorderedAtomic)
2103
8
    PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
2104
2.46k
  PreheaderLoad->setAlignment(Alignment);
2105
2.46k
  PreheaderLoad->setDebugLoc(DL);
2106
2.46k
  if (AATags)
2107
2.26k
    PreheaderLoad->setAAMetadata(AATags);
2108
2.46k
  SSA.AddAvailableValue(Preheader, PreheaderLoad);
2109
2.46k
2110
2.46k
  MemoryAccess *PreheaderLoadMemoryAccess;
2111
2.46k
  if (MSSAU) {
2112
9
    PreheaderLoadMemoryAccess = MSSAU->createMemoryAccessInBB(
2113
9
        PreheaderLoad, nullptr, PreheaderLoad->getParent(), MemorySSA::End);
2114
9
    MemoryUse *NewMemUse = cast<MemoryUse>(PreheaderLoadMemoryAccess);
2115
9
    MSSAU->insertUse(NewMemUse);
2116
9
  }
2117
2.46k
2118
2.46k
  // Rewrite all the loads in the loop and remember all the definitions from
2119
2.46k
  // stores in the loop.
2120
2.46k
  Promoter.run(LoopUses);
2121
2.46k
2122
2.46k
  if (MSSAU && 
VerifyMemorySSA9
)
2123
4
    MSSAU->getMemorySSA()->verifyMemorySSA();
2124
2.46k
  // If the SSAUpdater didn't use the load in the preheader, just zap it now.
2125
2.46k
  if (PreheaderLoad->use_empty())
2126
1.11k
    eraseInstruction(*PreheaderLoad, *SafetyInfo, CurAST, MSSAU);
2127
2.46k
2128
2.46k
  return true;
2129
2.46k
}
2130
2131
/// Returns an owning pointer to an alias set which incorporates aliasing info
2132
/// from L and all subloops of L.
2133
/// FIXME: In new pass manager, there is no helper function to handle loop
2134
/// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed
2135
/// from scratch for every loop. Hook up with the helper functions when
2136
/// available in the new pass manager to avoid redundant computation.
2137
std::unique_ptr<AliasSetTracker>
2138
LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
2139
608k
                                                 AliasAnalysis *AA) {
2140
608k
  std::unique_ptr<AliasSetTracker> CurAST;
2141
608k
  SmallVector<Loop *, 4> RecomputeLoops;
2142
608k
  for (Loop *InnerL : L->getSubLoops()) {
2143
166k
    auto MapI = LoopToAliasSetMap.find(InnerL);
2144
166k
    // If the AST for this inner loop is missing it may have been merged into
2145
166k
    // some other loop's AST and then that loop unrolled, and so we need to
2146
166k
    // recompute it.
2147
166k
    if (MapI == LoopToAliasSetMap.end()) {
2148
27
      RecomputeLoops.push_back(InnerL);
2149
27
      continue;
2150
27
    }
2151
166k
    std::unique_ptr<AliasSetTracker> InnerAST = std::move(MapI->second);
2152
166k
2153
166k
    if (CurAST) {
2154
57.9k
      // What if InnerLoop was modified by other passes ?
2155
57.9k
      // Once we've incorporated the inner loop's AST into ours, we don't need
2156
57.9k
      // the subloop's anymore.
2157
57.9k
      CurAST->add(*InnerAST);
2158
108k
    } else {
2159
108k
      CurAST = std::move(InnerAST);
2160
108k
    }
2161
166k
    LoopToAliasSetMap.erase(MapI);
2162
166k
  }
2163
608k
  if (!CurAST)
2164
500k
    CurAST = make_unique<AliasSetTracker>(*AA);
2165
608k
2166
608k
  // Add everything from the sub loops that are no longer directly available.
2167
608k
  for (Loop *InnerL : RecomputeLoops)
2168
27
    for (BasicBlock *BB : InnerL->blocks())
2169
68
      CurAST->add(*BB);
2170
608k
2171
608k
  // And merge in this loop (without anything from inner loops).
2172
608k
  for (BasicBlock *BB : L->blocks())
2173
2.76M
    if (LI->getLoopFor(BB) == L)
2174
2.06M
      CurAST->add(*BB);
2175
608k
2176
608k
  return CurAST;
2177
608k
}
2178
2179
std::unique_ptr<AliasSetTracker>
2180
LoopInvariantCodeMotion::collectAliasInfoForLoopWithMSSA(
2181
156
    Loop *L, AliasAnalysis *AA, MemorySSAUpdater *MSSAU) {
2182
156
  auto *MSSA = MSSAU->getMemorySSA();
2183
156
  auto CurAST = make_unique<AliasSetTracker>(*AA, MSSA, L);
2184
156
  CurAST->addAllInstructionsInLoopUsingMSSA();
2185
156
  return CurAST;
2186
156
}
2187
2188
/// Simple analysis hook. Clone alias set info.
2189
///
2190
void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
2191
44.9k
                                             Loop *L) {
2192
44.9k
  auto ASTIt = LICM.getLoopToAliasSetMap().find(L);
2193
44.9k
  if (ASTIt == LICM.getLoopToAliasSetMap().end())
2194
30.6k
    return;
2195
14.2k
2196
14.2k
  ASTIt->second->copyValue(From, To);
2197
14.2k
}
2198
2199
/// Simple Analysis hook. Delete value V from alias set
2200
///
2201
4.93k
void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
2202
4.93k
  auto ASTIt = LICM.getLoopToAliasSetMap().find(L);
2203
4.93k
  if (ASTIt == LICM.getLoopToAliasSetMap().end())
2204
3.55k
    return;
2205
1.38k
2206
1.38k
  ASTIt->second->deleteValue(V);
2207
1.38k
}
2208
2209
/// Simple Analysis hook. Delete value L from alias set map.
2210
///
2211
19
void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
2212
19
  if (!LICM.getLoopToAliasSetMap().count(L))
2213
9
    return;
2214
10
2215
10
  LICM.getLoopToAliasSetMap().erase(L);
2216
10
}
2217
2218
static bool pointerInvalidatedByLoop(MemoryLocation MemLoc,
2219
                                     AliasSetTracker *CurAST, Loop *CurLoop,
2220
574k
                                     AliasAnalysis *AA) {
2221
574k
  // First check to see if any of the basic blocks in CurLoop invalidate *V.
2222
574k
  bool isInvalidatedAccordingToAST = CurAST->getAliasSetFor(MemLoc).isMod();
2223
574k
2224
574k
  if (!isInvalidatedAccordingToAST || 
!LICMN2Theshold546k
)
2225
574k
    return isInvalidatedAccordingToAST;
2226
12
2227
12
  // Check with a diagnostic analysis if we can refine the information above.
2228
12
  // This is to identify the limitations of using the AST.
2229
12
  // The alias set mechanism used by LICM has a major weakness in that it
2230
12
  // combines all things which may alias into a single set *before* asking
2231
12
  // modref questions. As a result, a single readonly call within a loop will
2232
12
  // collapse all loads and stores into a single alias set and report
2233
12
  // invalidation if the loop contains any store. For example, readonly calls
2234
12
  // with deopt states have this form and create a general alias set with all
2235
12
  // loads and stores.  In order to get any LICM in loops containing possible
2236
12
  // deopt states we need a more precise invalidation of checking the mod ref
2237
12
  // info of each instruction within the loop and LI. This has a complexity of
2238
12
  // O(N^2), so currently, it is used only as a diagnostic tool since the
2239
12
  // default value of LICMN2Threshold is zero.
2240
12
2241
12
  // Don't look at nested loops.
2242
12
  if (CurLoop->begin() != CurLoop->end())
2243
0
    return true;
2244
12
2245
12
  int N = 0;
2246
12
  for (BasicBlock *BB : CurLoop->getBlocks())
2247
40
    
for (Instruction &I : *BB)12
{
2248
40
      if (N >= LICMN2Theshold) {
2249
0
        LLVM_DEBUG(dbgs() << "Alasing N2 threshold exhausted for "
2250
0
                          << *(MemLoc.Ptr) << "\n");
2251
0
        return true;
2252
0
      }
2253
40
      N++;
2254
40
      auto Res = AA->getModRefInfo(&I, MemLoc);
2255
40
      if (isModSet(Res)) {
2256
8
        LLVM_DEBUG(dbgs() << "Aliasing failed on " << I << " for "
2257
8
                          << *(MemLoc.Ptr) << "\n");
2258
8
        return true;
2259
8
      }
2260
40
    }
2261
12
  
LLVM_DEBUG4
(dbgs() << "Aliasing okay for " << *(MemLoc.Ptr) << "\n");
2262
4
  return false;
2263
12
}
2264
2265
static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU,
2266
                                             Loop *CurLoop,
2267
85
                                             SinkAndHoistLICMFlags &Flags) {
2268
85
  // For hoisting, use the walker to determine safety
2269
85
  if (!Flags.IsSink) {
2270
81
    MemoryAccess *Source;
2271
81
    // See declaration of SetLicmMssaOptCap for usage details.
2272
81
    if (Flags.LicmMssaOptCounter >= Flags.LicmMssaOptCap)
2273
0
      Source = MU->getDefiningAccess();
2274
81
    else {
2275
81
      Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(MU);
2276
81
      Flags.LicmMssaOptCounter++;
2277
81
    }
2278
81
    return !MSSA->isLiveOnEntryDef(Source) &&
2279
81
           
CurLoop->contains(Source->getBlock())23
;
2280
81
  }
2281
4
2282
4
  // For sinking, we'd need to check all Defs below this use. The getClobbering
2283
4
  // call will look on the backedge of the loop, but will check aliasing with
2284
4
  // the instructions on the previous iteration.
2285
4
  // For example:
2286
4
  // for (i ... )
2287
4
  //   load a[i] ( Use (LoE)
2288
4
  //   store a[i] ( 1 = Def (2), with 2 = Phi for the loop.
2289
4
  //   i++;
2290
4
  // The load sees no clobbering inside the loop, as the backedge alias check
2291
4
  // does phi translation, and will check aliasing against store a[i-1].
2292
4
  // However sinking the load outside the loop, below the store is incorrect.
2293
4
2294
4
  // For now, only sink if there are no Defs in the loop, and the existing ones
2295
4
  // precede the use and are in the same block.
2296
4
  // FIXME: Increase precision: Safe to sink if Use post dominates the Def;
2297
4
  // needs PostDominatorTreeAnalysis.
2298
4
  // FIXME: More precise: no Defs that alias this Use.
2299
4
  if (Flags.NoOfMemAccTooLarge)
2300
0
    return true;
2301
4
  for (auto *BB : CurLoop->getBlocks())
2302
4
    if (auto *Accesses = MSSA->getBlockDefs(BB))
2303
2
      for (const auto &MA : *Accesses)
2304
4
        if (const auto *MD = dyn_cast<MemoryDef>(&MA))
2305
2
          if (MU->getBlock() != MD->getBlock() ||
2306
2
              !MSSA->locallyDominates(MD, MU))
2307
1
            return true;
2308
4
  
return false3
;
2309
4
}
2310
2311
/// Little predicate that returns true if the specified basic block is in
2312
/// a subloop of the current one, not the current one itself.
2313
///
2314
5.53M
static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
2315
5.53M
  assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
2316
5.53M
  return LI->getLoopFor(BB) != CurLoop;
2317
5.53M
}