1 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass transforms loops that contain branches on loop-invariant conditions
11 // to multiple loops. For example, it turns the left into the right code:
20 // This can increase the size of the code exponentially (doubling it every time
21 // a loop is unswitched) so we only unswitch if the resultant code will be
22 // smaller than a threshold.
24 // This pass expects LICM to be run before it to hoist invariant conditions out
25 // of the loop, to make the unswitching opportunity obvious.
27 //===----------------------------------------------------------------------===//
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Analysis/GlobalsModRef.h"
34 #include "llvm/Analysis/AssumptionCache.h"
35 #include "llvm/Analysis/CodeMetrics.h"
36 #include "llvm/Analysis/DivergenceAnalysis.h"
37 #include "llvm/Analysis/InstructionSimplify.h"
38 #include "llvm/Analysis/LoopInfo.h"
39 #include "llvm/Analysis/LoopPass.h"
40 #include "llvm/Analysis/ScalarEvolution.h"
41 #include "llvm/Analysis/TargetTransformInfo.h"
42 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
43 #include "llvm/Analysis/BlockFrequencyInfo.h"
44 #include "llvm/Analysis/BranchProbabilityInfo.h"
45 #include "llvm/Support/BranchProbability.h"
46 #include "llvm/IR/Constants.h"
47 #include "llvm/IR/DerivedTypes.h"
48 #include "llvm/IR/Dominators.h"
49 #include "llvm/IR/Function.h"
50 #include "llvm/IR/Instructions.h"
51 #include "llvm/IR/InstrTypes.h"
52 #include "llvm/IR/Module.h"
53 #include "llvm/IR/MDBuilder.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
58 #include "llvm/Transforms/Utils/Cloning.h"
59 #include "llvm/Transforms/Utils/Local.h"
60 #include "llvm/Transforms/Utils/LoopUtils.h"
66 #define DEBUG_TYPE "loop-unswitch"
68 STATISTIC(NumBranches, "Number of branches unswitched");
69 STATISTIC(NumSwitches, "Number of switches unswitched");
70 STATISTIC(NumGuards, "Number of guards unswitched");
71 STATISTIC(NumSelects , "Number of selects unswitched");
72 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
73 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
74 STATISTIC(TotalInsts, "Total number of instructions analyzed");
76 // The specific value of 100 here was chosen based only on intuition and a
77 // few specific examples.
78 static cl::opt<unsigned>
79 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
80 cl::init(100), cl::Hidden);
84 class LUAnalysisCache {
86 typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
89 typedef UnswitchedValsMap::iterator UnswitchedValsIt;
91 struct LoopProperties {
92 unsigned CanBeUnswitchedCount;
93 unsigned WasUnswitchedCount;
94 unsigned SizeEstimation;
95 UnswitchedValsMap UnswitchedVals;
98 // Here we use std::map instead of DenseMap, since we need to keep valid
99 // LoopProperties pointer for current loop for better performance.
100 typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
101 typedef LoopPropsMap::iterator LoopPropsMapIt;
103 LoopPropsMap LoopsProperties;
104 UnswitchedValsMap *CurLoopInstructions;
105 LoopProperties *CurrentLoopProperties;
107 // A loop unswitching with an estimated cost above this threshold
108 // is not performed. MaxSize is turned into unswitching quota for
109 // the current loop, and reduced correspondingly, though note that
110 // the quota is returned by releaseMemory() when the loop has been
111 // processed, so that MaxSize will return to its previous
112 // value. So in most cases MaxSize will equal the Threshold flag
113 // when a new loop is processed. An exception to that is that
114 // MaxSize will have a smaller value while processing nested loops
115 // that were introduced due to loop unswitching of an outer loop.
117 // FIXME: The way that MaxSize works is subtle and depends on the
118 // pass manager processing loops and calling releaseMemory() in a
119 // specific order. It would be good to find a more straightforward
120 // way of doing what MaxSize does.
125 : CurLoopInstructions(nullptr), CurrentLoopProperties(nullptr),
126 MaxSize(Threshold) {}
128 // Analyze loop. Check its size, calculate is it possible to unswitch
129 // it. Returns true if we can unswitch this loop.
130 bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
131 AssumptionCache *AC);
133 // Clean all data related to given loop.
134 void forgetLoop(const Loop *L);
136 // Mark case value as unswitched.
137 // Since SI instruction can be partly unswitched, in order to avoid
138 // extra unswitching in cloned loops keep track all unswitched values.
139 void setUnswitched(const SwitchInst *SI, const Value *V);
141 // Check was this case value unswitched before or not.
142 bool isUnswitched(const SwitchInst *SI, const Value *V);
144 // Returns true if another unswitching could be done within the cost
146 bool CostAllowsUnswitching();
148 // Clone all loop-unswitch related loop properties.
149 // Redistribute unswitching quotas.
150 // Note, that new loop data is stored inside the VMap.
151 void cloneData(const Loop *NewLoop, const Loop *OldLoop,
152 const ValueToValueMapTy &VMap);
155 class LoopUnswitch : public LoopPass {
156 LoopInfo *LI; // Loop information
160 // Used to check if second loop needs processing after
161 // RewriteLoopBodyWithConditionConstant rewrites first loop.
162 std::vector<Loop*> LoopProcessWorklist;
164 LUAnalysisCache BranchesInfo;
166 bool OptimizeForSize;
171 BasicBlock *loopHeader;
172 BasicBlock *loopPreheader;
175 LoopSafetyInfo SafetyInfo;
177 // LoopBlocks contains all of the basic blocks of the loop, including the
178 // preheader of the loop, the body of the loop, and the exit blocks of the
179 // loop, in that order.
180 std::vector<BasicBlock*> LoopBlocks;
181 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
182 std::vector<BasicBlock*> NewBlocks;
184 bool hasBranchDivergence;
187 static char ID; // Pass ID, replacement for typeid
188 explicit LoopUnswitch(bool Os = false, bool hasBranchDivergence = false) :
189 LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
190 currentLoop(nullptr), DT(nullptr), loopHeader(nullptr),
191 loopPreheader(nullptr), hasBranchDivergence(hasBranchDivergence) {
192 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
195 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
196 bool processCurrentLoop();
197 bool isUnreachableDueToPreviousUnswitching(BasicBlock *);
198 /// This transformation requires natural loop information & requires that
199 /// loop preheaders be inserted into the CFG.
201 void getAnalysisUsage(AnalysisUsage &AU) const override {
202 AU.addRequired<AssumptionCacheTracker>();
203 AU.addRequired<TargetTransformInfoWrapperPass>();
204 if (hasBranchDivergence)
205 AU.addRequired<DivergenceAnalysis>();
206 getLoopAnalysisUsage(AU);
211 void releaseMemory() override {
212 BranchesInfo.forgetLoop(currentLoop);
215 void initLoopData() {
216 loopHeader = currentLoop->getHeader();
217 loopPreheader = currentLoop->getLoopPreheader();
220 /// Split all of the edges from inside the loop to their exit blocks.
221 /// Update the appropriate Phi nodes as we do so.
222 void SplitExitEdges(Loop *L,
223 const SmallVectorImpl<BasicBlock *> &ExitBlocks);
225 bool TryTrivialLoopUnswitch(bool &Changed);
227 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,
228 TerminatorInst *TI = nullptr);
229 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
230 BasicBlock *ExitBlock, TerminatorInst *TI);
231 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
234 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
235 Constant *Val, bool isEqual);
237 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
238 BasicBlock *TrueDest,
239 BasicBlock *FalseDest,
240 Instruction *InsertPt,
243 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
245 /// Given that the Invariant is not equal to Val. Simplify instructions
247 Value *SimplifyInstructionWithNotEqual(Instruction *Inst, Value *Invariant,
252 // Analyze loop. Check its size, calculate is it possible to unswitch
253 // it. Returns true if we can unswitch this loop.
254 bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
255 AssumptionCache *AC) {
257 LoopPropsMapIt PropsIt;
259 std::tie(PropsIt, Inserted) =
260 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
262 LoopProperties &Props = PropsIt->second;
267 // Limit the number of instructions to avoid causing significant code
268 // expansion, and the number of basic blocks, to avoid loops with
269 // large numbers of branches which cause loop unswitching to go crazy.
270 // This is a very ad-hoc heuristic.
272 SmallPtrSet<const Value *, 32> EphValues;
273 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
275 // FIXME: This is overly conservative because it does not take into
276 // consideration code simplification opportunities and code that can
277 // be shared by the resultant unswitched loops.
279 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
281 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
283 Props.SizeEstimation = Metrics.NumInsts;
284 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
285 Props.WasUnswitchedCount = 0;
286 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
288 if (Metrics.notDuplicatable) {
289 DEBUG(dbgs() << "NOT unswitching loop %"
290 << L->getHeader()->getName() << ", contents cannot be "
296 // Be careful. This links are good only before new loop addition.
297 CurrentLoopProperties = &Props;
298 CurLoopInstructions = &Props.UnswitchedVals;
303 // Clean all data related to given loop.
304 void LUAnalysisCache::forgetLoop(const Loop *L) {
306 LoopPropsMapIt LIt = LoopsProperties.find(L);
308 if (LIt != LoopsProperties.end()) {
309 LoopProperties &Props = LIt->second;
310 MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
311 Props.SizeEstimation;
312 LoopsProperties.erase(LIt);
315 CurrentLoopProperties = nullptr;
316 CurLoopInstructions = nullptr;
319 // Mark case value as unswitched.
320 // Since SI instruction can be partly unswitched, in order to avoid
321 // extra unswitching in cloned loops keep track all unswitched values.
322 void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
323 (*CurLoopInstructions)[SI].insert(V);
326 // Check was this case value unswitched before or not.
327 bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
328 return (*CurLoopInstructions)[SI].count(V);
331 bool LUAnalysisCache::CostAllowsUnswitching() {
332 return CurrentLoopProperties->CanBeUnswitchedCount > 0;
335 // Clone all loop-unswitch related loop properties.
336 // Redistribute unswitching quotas.
337 // Note, that new loop data is stored inside the VMap.
338 void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
339 const ValueToValueMapTy &VMap) {
341 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
342 LoopProperties &OldLoopProps = *CurrentLoopProperties;
343 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
345 // Reallocate "can-be-unswitched quota"
347 --OldLoopProps.CanBeUnswitchedCount;
348 ++OldLoopProps.WasUnswitchedCount;
349 NewLoopProps.WasUnswitchedCount = 0;
350 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
351 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
352 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
354 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
356 // Clone unswitched values info:
357 // for new loop switches we clone info about values that was
358 // already unswitched and has redundant successors.
359 for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
360 const SwitchInst *OldInst = I->first;
361 Value *NewI = VMap.lookup(OldInst);
362 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
363 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
365 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
369 char LoopUnswitch::ID = 0;
370 INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
372 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
373 INITIALIZE_PASS_DEPENDENCY(LoopPass)
374 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
375 INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis)
376 INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
379 Pass *llvm::createLoopUnswitchPass(bool Os, bool hasBranchDivergence) {
380 return new LoopUnswitch(Os, hasBranchDivergence);
383 /// Operator chain lattice.
385 OC_OpChainNone, ///< There is no operator.
386 OC_OpChainOr, ///< There are only ORs.
387 OC_OpChainAnd, ///< There are only ANDs.
388 OC_OpChainMixed ///< There are ANDs and ORs.
391 /// Cond is a condition that occurs in L. If it is invariant in the loop, or has
392 /// an invariant piece, return the invariant. Otherwise, return null.
394 /// NOTE: FindLIVLoopCondition will not return a partial LIV by walking up a
395 /// mixed operator chain, as we can not reliably find a value which will simplify
396 /// the operator chain. If the chain is AND-only or OR-only, we can use 0 or ~0
397 /// to simplify the chain.
399 /// NOTE: In case a partial LIV and a mixed operator chain, we may be able to
400 /// simplify the condition itself to a loop variant condition, but at the
401 /// cost of creating an entirely new loop.
402 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed,
403 OperatorChain &ParentChain,
404 DenseMap<Value *, Value *> &Cache) {
405 auto CacheIt = Cache.find(Cond);
406 if (CacheIt != Cache.end())
407 return CacheIt->second;
409 // We started analyze new instruction, increment scanned instructions counter.
412 // We can never unswitch on vector conditions.
413 if (Cond->getType()->isVectorTy())
416 // Constants should be folded, not unswitched on!
417 if (isa<Constant>(Cond)) return nullptr;
419 // TODO: Handle: br (VARIANT|INVARIANT).
421 // Hoist simple values out.
422 if (L->makeLoopInvariant(Cond, Changed)) {
427 // Walk up the operator chain to find partial invariant conditions.
428 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
429 if (BO->getOpcode() == Instruction::And ||
430 BO->getOpcode() == Instruction::Or) {
431 // Given the previous operator, compute the current operator chain status.
432 OperatorChain NewChain;
433 switch (ParentChain) {
435 NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
439 NewChain = BO->getOpcode() == Instruction::Or ? OC_OpChainOr :
443 NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
446 case OC_OpChainMixed:
447 NewChain = OC_OpChainMixed;
451 // If we reach a Mixed state, we do not want to keep walking up as we can not
452 // reliably find a value that will simplify the chain. With this check, we
453 // will return null on the first sight of mixed chain and the caller will
454 // either backtrack to find partial LIV in other operand or return null.
455 if (NewChain != OC_OpChainMixed) {
456 // Update the current operator chain type before we search up the chain.
457 ParentChain = NewChain;
458 // If either the left or right side is invariant, we can unswitch on this,
459 // which will cause the branch to go away in one loop and the condition to
460 // simplify in the other one.
461 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed,
462 ParentChain, Cache)) {
466 // We did not manage to find a partial LIV in operand(0). Backtrack and try
468 ParentChain = NewChain;
469 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed,
470 ParentChain, Cache)) {
477 Cache[Cond] = nullptr;
481 /// Cond is a condition that occurs in L. If it is invariant in the loop, or has
482 /// an invariant piece, return the invariant along with the operator chain type.
483 /// Otherwise, return null.
484 static std::pair<Value *, OperatorChain> FindLIVLoopCondition(Value *Cond,
487 DenseMap<Value *, Value *> Cache;
488 OperatorChain OpChain = OC_OpChainNone;
489 Value *FCond = FindLIVLoopCondition(Cond, L, Changed, OpChain, Cache);
491 // In case we do find a LIV, it can not be obtained by walking up a mixed
493 assert((!FCond || OpChain != OC_OpChainMixed) &&
494 "Do not expect a partial LIV with mixed operator chain");
495 return {FCond, OpChain};
498 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
502 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
503 *L->getHeader()->getParent());
504 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
506 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
508 Function *F = currentLoop->getHeader()->getParent();
510 SanitizeMemory = F->hasFnAttribute(Attribute::SanitizeMemory);
512 computeLoopSafetyInfo(&SafetyInfo, L);
514 bool Changed = false;
516 assert(currentLoop->isLCSSAForm(*DT));
518 Changed |= processCurrentLoop();
521 // FIXME: Reconstruct dom info, because it is not preserved properly.
527 // Return true if the BasicBlock BB is unreachable from the loop header.
528 // Return false, otherwise.
529 bool LoopUnswitch::isUnreachableDueToPreviousUnswitching(BasicBlock *BB) {
530 auto *Node = DT->getNode(BB)->getIDom();
531 BasicBlock *DomBB = Node->getBlock();
532 while (currentLoop->contains(DomBB)) {
533 BranchInst *BInst = dyn_cast<BranchInst>(DomBB->getTerminator());
535 Node = DT->getNode(DomBB)->getIDom();
536 DomBB = Node->getBlock();
538 if (!BInst || !BInst->isConditional())
541 Value *Cond = BInst->getCondition();
542 if (!isa<ConstantInt>(Cond))
545 BasicBlock *UnreachableSucc =
546 Cond == ConstantInt::getTrue(Cond->getContext())
547 ? BInst->getSuccessor(1)
548 : BInst->getSuccessor(0);
550 if (DT->dominates(UnreachableSucc, BB))
556 /// Do actual work and unswitch loop if possible and profitable.
557 bool LoopUnswitch::processCurrentLoop() {
558 bool Changed = false;
562 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
566 // Loops with indirectbr cannot be cloned.
567 if (!currentLoop->isSafeToClone())
570 // Without dedicated exits, splitting the exit edge may fail.
571 if (!currentLoop->hasDedicatedExits())
574 LLVMContext &Context = loopHeader->getContext();
576 // Analyze loop cost, and stop unswitching if loop content can not be duplicated.
577 if (!BranchesInfo.countLoop(
578 currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
579 *currentLoop->getHeader()->getParent()),
583 // Try trivial unswitch first before loop over other basic blocks in the loop.
584 if (TryTrivialLoopUnswitch(Changed)) {
588 // Run through the instructions in the loop, keeping track of three things:
590 // - That we do not unswitch loops containing convergent operations, as we
591 // might be making them control dependent on the unswitch value when they
593 // FIXME: This could be refined to only bail if the convergent operation is
594 // not already control-dependent on the unswitch value.
596 // - That basic blocks in the loop contain invokes whose predecessor edges we
599 // - The set of guard intrinsics encountered (these are non terminator
600 // instructions that are also profitable to be unswitched).
602 SmallVector<IntrinsicInst *, 4> Guards;
604 for (const auto BB : currentLoop->blocks()) {
605 for (auto &I : *BB) {
606 auto CS = CallSite(&I);
608 if (CS.hasFnAttr(Attribute::Convergent))
610 if (auto *II = dyn_cast<InvokeInst>(&I))
611 if (!II->getUnwindDest()->canSplitPredecessors())
613 if (auto *II = dyn_cast<IntrinsicInst>(&I))
614 if (II->getIntrinsicID() == Intrinsic::experimental_guard)
615 Guards.push_back(II);
619 // Do not do non-trivial unswitch while optimizing for size.
620 // FIXME: Use Function::optForSize().
621 if (OptimizeForSize ||
622 loopHeader->getParent()->hasFnAttribute(Attribute::OptimizeForSize))
625 for (IntrinsicInst *Guard : Guards) {
627 FindLIVLoopCondition(Guard->getOperand(0), currentLoop, Changed).first;
629 UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context))) {
630 // NB! Unswitching (if successful) could have erased some of the
631 // instructions in Guards leaving dangling pointers there. This is fine
632 // because we're returning now, and won't look at Guards again.
638 // Loop over all of the basic blocks in the loop. If we find an interior
639 // block that is branching on a loop-invariant condition, we can unswitch this
641 for (Loop::block_iterator I = currentLoop->block_begin(),
642 E = currentLoop->block_end(); I != E; ++I) {
643 TerminatorInst *TI = (*I)->getTerminator();
645 // Unswitching on a potentially uninitialized predicate is not
646 // MSan-friendly. Limit this to the cases when the original predicate is
647 // guaranteed to execute, to avoid creating a use-of-uninitialized-value
648 // in the code that did not have one.
649 // This is a workaround for the discrepancy between LLVM IR and MSan
650 // semantics. See PR28054 for more details.
651 if (SanitizeMemory &&
652 !isGuaranteedToExecute(*TI, DT, currentLoop, &SafetyInfo))
655 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
656 // Some branches may be rendered unreachable because of previous
658 // Unswitch only those branches that are reachable.
659 if (isUnreachableDueToPreviousUnswitching(*I))
662 // If this isn't branching on an invariant condition, we can't unswitch
664 if (BI->isConditional()) {
665 // See if this, or some part of it, is loop invariant. If so, we can
666 // unswitch on it if we desire.
667 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
668 currentLoop, Changed).first;
670 UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
675 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
676 Value *SC = SI->getCondition();
678 OperatorChain OpChain;
679 std::tie(LoopCond, OpChain) =
680 FindLIVLoopCondition(SC, currentLoop, Changed);
682 unsigned NumCases = SI->getNumCases();
683 if (LoopCond && NumCases) {
684 // Find a value to unswitch on:
685 // FIXME: this should chose the most expensive case!
686 // FIXME: scan for a case with a non-critical edge?
687 Constant *UnswitchVal = nullptr;
688 // Find a case value such that at least one case value is unswitched
690 if (OpChain == OC_OpChainAnd) {
691 // If the chain only has ANDs and the switch has a case value of 0.
692 // Dropping in a 0 to the chain will unswitch out the 0-casevalue.
693 auto *AllZero = cast<ConstantInt>(Constant::getNullValue(SC->getType()));
694 if (BranchesInfo.isUnswitched(SI, AllZero))
696 // We are unswitching 0 out.
697 UnswitchVal = AllZero;
698 } else if (OpChain == OC_OpChainOr) {
699 // If the chain only has ORs and the switch has a case value of ~0.
700 // Dropping in a ~0 to the chain will unswitch out the ~0-casevalue.
701 auto *AllOne = cast<ConstantInt>(Constant::getAllOnesValue(SC->getType()));
702 if (BranchesInfo.isUnswitched(SI, AllOne))
704 // We are unswitching ~0 out.
705 UnswitchVal = AllOne;
707 assert(OpChain == OC_OpChainNone &&
708 "Expect to unswitch on trivial chain");
709 // Do not process same value again and again.
710 // At this point we have some cases already unswitched and
711 // some not yet unswitched. Let's find the first not yet unswitched one.
712 for (auto Case : SI->cases()) {
713 Constant *UnswitchValCandidate = Case.getCaseValue();
714 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
715 UnswitchVal = UnswitchValCandidate;
724 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
726 // In case of a full LIV, UnswitchVal is the value we unswitched out.
727 // In case of a partial LIV, we only unswitch when its an AND-chain
728 // or OR-chain. In both cases switch input value simplifies to
730 BranchesInfo.setUnswitched(SI, UnswitchVal);
736 // Scan the instructions to check for unswitchable values.
737 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
739 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
740 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
741 currentLoop, Changed).first;
742 if (LoopCond && UnswitchIfProfitable(LoopCond,
743 ConstantInt::getTrue(Context))) {
752 /// Check to see if all paths from BB exit the loop with no side effects
753 /// (including infinite loops).
755 /// If true, we return true and set ExitBB to the block we
758 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
760 std::set<BasicBlock*> &Visited) {
761 if (!Visited.insert(BB).second) {
762 // Already visited. Without more analysis, this could indicate an infinite
766 if (!L->contains(BB)) {
767 // Otherwise, this is a loop exit, this is fine so long as this is the
769 if (ExitBB) return false;
774 // Otherwise, this is an unvisited intra-loop node. Check all successors.
775 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
776 // Check to see if the successor is a trivial loop exit.
777 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
781 // Okay, everything after this looks good, check to make sure that this block
782 // doesn't include any side effects.
783 for (Instruction &I : *BB)
784 if (I.mayHaveSideEffects())
790 /// Return true if the specified block unconditionally leads to an exit from
791 /// the specified loop, and has no side-effects in the process. If so, return
792 /// the block that is exited to, otherwise return null.
793 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
794 std::set<BasicBlock*> Visited;
795 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
796 BasicBlock *ExitBB = nullptr;
797 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
802 /// We have found that we can unswitch currentLoop when LoopCond == Val to
803 /// simplify the loop. If we decide that this is profitable,
804 /// unswitch the loop, reprocess the pieces, then return true.
805 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,
806 TerminatorInst *TI) {
807 // Check to see if it would be profitable to unswitch current loop.
808 if (!BranchesInfo.CostAllowsUnswitching()) {
809 DEBUG(dbgs() << "NOT unswitching loop %"
810 << currentLoop->getHeader()->getName()
811 << " at non-trivial condition '" << *Val
812 << "' == " << *LoopCond << "\n"
813 << ". Cost too high.\n");
816 if (hasBranchDivergence &&
817 getAnalysis<DivergenceAnalysis>().isDivergent(LoopCond)) {
818 DEBUG(dbgs() << "NOT unswitching loop %"
819 << currentLoop->getHeader()->getName()
820 << " at non-trivial condition '" << *Val
821 << "' == " << *LoopCond << "\n"
822 << ". Condition is divergent.\n");
826 UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
830 /// Recursively clone the specified loop and all of its children,
831 /// mapping the blocks with the specified map.
832 static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
833 LoopInfo *LI, LPPassManager *LPM) {
834 Loop &New = LPM->addLoop(PL);
836 // Add all of the blocks in L to the new loop.
837 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
839 if (LI->getLoopFor(*I) == L)
840 New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
842 // Add all of the subloops to the new loop.
844 CloneLoop(I, &New, VM, LI, LPM);
849 /// Emit a conditional branch on two values if LIC == Val, branch to TrueDst,
850 /// otherwise branch to FalseDest. Insert the code immediately before InsertPt.
851 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
852 BasicBlock *TrueDest,
853 BasicBlock *FalseDest,
854 Instruction *InsertPt,
855 TerminatorInst *TI) {
856 // Insert a conditional branch on LIC to the two preheaders. The original
857 // code is the true version and the new code is the false version.
858 Value *BranchVal = LIC;
859 bool Swapped = false;
860 if (!isa<ConstantInt>(Val) ||
861 Val->getType() != Type::getInt1Ty(LIC->getContext()))
862 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
863 else if (Val != ConstantInt::getTrue(Val->getContext())) {
864 // We want to enter the new loop when the condition is true.
865 std::swap(TrueDest, FalseDest);
869 // Insert the new branch.
871 IRBuilder<>(InsertPt).CreateCondBr(BranchVal, TrueDest, FalseDest, TI);
873 BI->swapProfMetadata();
875 // If either edge is critical, split it. This helps preserve LoopSimplify
876 // form for enclosing loops.
877 auto Options = CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA();
878 SplitCriticalEdge(BI, 0, Options);
879 SplitCriticalEdge(BI, 1, Options);
882 /// Given a loop that has a trivial unswitchable condition in it (a cond branch
883 /// from its header block to its latch block, where the path through the loop
884 /// that doesn't execute its body has no side-effects), unswitch it. This
885 /// doesn't involve any code duplication, just moving the conditional branch
886 /// outside of the loop and updating loop info.
887 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
888 BasicBlock *ExitBlock,
889 TerminatorInst *TI) {
890 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
891 << loopHeader->getName() << " [" << L->getBlocks().size()
892 << " blocks] in Function "
893 << L->getHeader()->getParent()->getName() << " on cond: " << *Val
894 << " == " << *Cond << "\n");
896 // First step, split the preheader, so that we know that there is a safe place
897 // to insert the conditional branch. We will change loopPreheader to have a
898 // conditional branch on Cond.
899 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI);
901 // Now that we have a place to insert the conditional branch, create a place
902 // to branch to: this is the exit block out of the loop that we should
905 // Split this block now, so that the loop maintains its exit block, and so
906 // that the jump from the preheader can execute the contents of the exit block
907 // without actually branching to it (the exit block should be dominated by the
908 // loop header, not the preheader).
909 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
910 BasicBlock *NewExit = SplitBlock(ExitBlock, &ExitBlock->front(), DT, LI);
912 // Okay, now we have a position to branch from and a position to branch to,
913 // insert the new conditional branch.
914 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
915 loopPreheader->getTerminator(), TI);
916 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
917 loopPreheader->getTerminator()->eraseFromParent();
919 // We need to reprocess this loop, it could be unswitched again.
922 // Now that we know that the loop is never entered when this condition is a
923 // particular value, rewrite the loop with this info. We know that this will
924 // at least eliminate the old branch.
925 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
929 /// Check if the first non-constant condition starting from the loop header is
930 /// a trivial unswitch condition: that is, a condition controls whether or not
931 /// the loop does anything at all. If it is a trivial condition, unswitching
932 /// produces no code duplications (equivalently, it produces a simpler loop and
933 /// a new empty loop, which gets deleted). Therefore always unswitch trivial
935 bool LoopUnswitch::TryTrivialLoopUnswitch(bool &Changed) {
936 BasicBlock *CurrentBB = currentLoop->getHeader();
937 TerminatorInst *CurrentTerm = CurrentBB->getTerminator();
938 LLVMContext &Context = CurrentBB->getContext();
940 // If loop header has only one reachable successor (currently via an
941 // unconditional branch or constant foldable conditional branch, but
942 // should also consider adding constant foldable switch instruction in
943 // future), we should keep looking for trivial condition candidates in
944 // the successor as well. An alternative is to constant fold conditions
945 // and merge successors into loop header (then we only need to check header's
946 // terminator). The reason for not doing this in LoopUnswitch pass is that
947 // it could potentially break LoopPassManager's invariants. Folding dead
948 // branches could either eliminate the current loop or make other loops
949 // unreachable. LCSSA form might also not be preserved after deleting
950 // branches. The following code keeps traversing loop header's successors
951 // until it finds the trivial condition candidate (condition that is not a
952 // constant). Since unswitching generates branches with constant conditions,
953 // this scenario could be very common in practice.
954 SmallSet<BasicBlock*, 8> Visited;
957 // If we exit loop or reach a previous visited block, then
958 // we can not reach any trivial condition candidates (unfoldable
959 // branch instructions or switch instructions) and no unswitch
960 // can happen. Exit and return false.
961 if (!currentLoop->contains(CurrentBB) || !Visited.insert(CurrentBB).second)
964 // Check if this loop will execute any side-effecting instructions (e.g.
965 // stores, calls, volatile loads) in the part of the loop that the code
966 // *would* execute. Check the header first.
967 for (Instruction &I : *CurrentBB)
968 if (I.mayHaveSideEffects())
971 if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
972 if (BI->isUnconditional()) {
973 CurrentBB = BI->getSuccessor(0);
974 } else if (BI->getCondition() == ConstantInt::getTrue(Context)) {
975 CurrentBB = BI->getSuccessor(0);
976 } else if (BI->getCondition() == ConstantInt::getFalse(Context)) {
977 CurrentBB = BI->getSuccessor(1);
979 // Found a trivial condition candidate: non-foldable conditional branch.
982 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
983 // At this point, any constant-foldable instructions should have probably
985 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
988 // Find the target block we are definitely going to.
989 CurrentBB = SI->findCaseValue(Cond)->getCaseSuccessor();
991 // We do not understand these terminator instructions.
995 CurrentTerm = CurrentBB->getTerminator();
998 // CondVal is the condition that controls the trivial condition.
999 // LoopExitBB is the BasicBlock that loop exits when meets trivial condition.
1000 Constant *CondVal = nullptr;
1001 BasicBlock *LoopExitBB = nullptr;
1003 if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1004 // If this isn't branching on an invariant condition, we can't unswitch it.
1005 if (!BI->isConditional())
1008 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
1009 currentLoop, Changed).first;
1011 // Unswitch only if the trivial condition itself is an LIV (not
1012 // partial LIV which could occur in and/or)
1013 if (!LoopCond || LoopCond != BI->getCondition())
1016 // Check to see if a successor of the branch is guaranteed to
1017 // exit through a unique exit block without having any
1018 // side-effects. If so, determine the value of Cond that causes
1020 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
1021 BI->getSuccessor(0)))) {
1022 CondVal = ConstantInt::getTrue(Context);
1023 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
1024 BI->getSuccessor(1)))) {
1025 CondVal = ConstantInt::getFalse(Context);
1028 // If we didn't find a single unique LoopExit block, or if the loop exit
1029 // block contains phi nodes, this isn't trivial.
1030 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
1031 return false; // Can't handle this.
1033 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1037 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1038 // If this isn't switching on an invariant condition, we can't unswitch it.
1039 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
1040 currentLoop, Changed).first;
1042 // Unswitch only if the trivial condition itself is an LIV (not
1043 // partial LIV which could occur in and/or)
1044 if (!LoopCond || LoopCond != SI->getCondition())
1047 // Check to see if a successor of the switch is guaranteed to go to the
1048 // latch block or exit through a one exit block without having any
1049 // side-effects. If so, determine the value of Cond that causes it to do
1051 // Note that we can't trivially unswitch on the default case or
1052 // on already unswitched cases.
1053 for (auto Case : SI->cases()) {
1054 BasicBlock *LoopExitCandidate;
1055 if ((LoopExitCandidate =
1056 isTrivialLoopExitBlock(currentLoop, Case.getCaseSuccessor()))) {
1057 // Okay, we found a trivial case, remember the value that is trivial.
1058 ConstantInt *CaseVal = Case.getCaseValue();
1060 // Check that it was not unswitched before, since already unswitched
1061 // trivial vals are looks trivial too.
1062 if (BranchesInfo.isUnswitched(SI, CaseVal))
1064 LoopExitBB = LoopExitCandidate;
1070 // If we didn't find a single unique LoopExit block, or if the loop exit
1071 // block contains phi nodes, this isn't trivial.
1072 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
1073 return false; // Can't handle this.
1075 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1078 // We are only unswitching full LIV.
1079 BranchesInfo.setUnswitched(SI, CondVal);
1086 /// Split all of the edges from inside the loop to their exit blocks.
1087 /// Update the appropriate Phi nodes as we do so.
1088 void LoopUnswitch::SplitExitEdges(Loop *L,
1089 const SmallVectorImpl<BasicBlock *> &ExitBlocks){
1091 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
1092 BasicBlock *ExitBlock = ExitBlocks[i];
1093 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
1094 pred_end(ExitBlock));
1096 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
1097 // general, if we call it on all predecessors of all exits then it does.
1098 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", DT, LI,
1099 /*PreserveLCSSA*/ true);
1103 /// We determined that the loop is profitable to unswitch when LIC equal Val.
1104 /// Split it into loop versions and test the condition outside of either loop.
1105 /// Return the loops created as Out1/Out2.
1106 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
1107 Loop *L, TerminatorInst *TI) {
1108 Function *F = loopHeader->getParent();
1109 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
1110 << loopHeader->getName() << " [" << L->getBlocks().size()
1111 << " blocks] in Function " << F->getName()
1112 << " when '" << *Val << "' == " << *LIC << "\n");
1114 if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1115 SEWP->getSE().forgetLoop(L);
1120 // First step, split the preheader and exit blocks, and add these blocks to
1121 // the LoopBlocks list.
1122 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, DT, LI);
1123 LoopBlocks.push_back(NewPreheader);
1125 // We want the loop to come after the preheader, but before the exit blocks.
1126 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
1128 SmallVector<BasicBlock*, 8> ExitBlocks;
1129 L->getUniqueExitBlocks(ExitBlocks);
1131 // Split all of the edges from inside the loop to their exit blocks. Update
1132 // the appropriate Phi nodes as we do so.
1133 SplitExitEdges(L, ExitBlocks);
1135 // The exit blocks may have been changed due to edge splitting, recompute.
1137 L->getUniqueExitBlocks(ExitBlocks);
1139 // Add exit blocks to the loop blocks.
1140 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
1142 // Next step, clone all of the basic blocks that make up the loop (including
1143 // the loop preheader and exit blocks), keeping track of the mapping between
1144 // the instructions and blocks.
1145 NewBlocks.reserve(LoopBlocks.size());
1146 ValueToValueMapTy VMap;
1147 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
1148 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
1150 NewBlocks.push_back(NewBB);
1151 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
1152 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
1155 // Splice the newly inserted blocks into the function right before the
1156 // original preheader.
1157 F->getBasicBlockList().splice(NewPreheader->getIterator(),
1158 F->getBasicBlockList(),
1159 NewBlocks[0]->getIterator(), F->end());
1161 // Now we create the new Loop object for the versioned loop.
1162 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
1164 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
1165 // Probably clone more loop-unswitch related loop properties.
1166 BranchesInfo.cloneData(NewLoop, L, VMap);
1168 Loop *ParentLoop = L->getParentLoop();
1170 // Make sure to add the cloned preheader and exit blocks to the parent loop
1172 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
1175 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
1176 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
1177 // The new exit block should be in the same loop as the old one.
1178 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
1179 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
1181 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
1182 "Exit block should have been split to have one successor!");
1183 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
1185 // If the successor of the exit block had PHI nodes, add an entry for
1187 for (BasicBlock::iterator I = ExitSucc->begin();
1188 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1189 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
1190 ValueToValueMapTy::iterator It = VMap.find(V);
1191 if (It != VMap.end()) V = It->second;
1192 PN->addIncoming(V, NewExit);
1195 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
1196 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
1197 &*ExitSucc->getFirstInsertionPt());
1199 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
1201 BasicBlock *BB = *I;
1202 LandingPadInst *LPI = BB->getLandingPadInst();
1203 LPI->replaceAllUsesWith(PN);
1204 PN->addIncoming(LPI, BB);
1209 // Rewrite the code to refer to itself.
1210 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
1211 for (Instruction &I : *NewBlocks[i]) {
1212 RemapInstruction(&I, VMap,
1213 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1214 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1215 if (II->getIntrinsicID() == Intrinsic::assume)
1216 AC->registerAssumption(II);
1220 // Rewrite the original preheader to select between versions of the loop.
1221 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
1222 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
1223 "Preheader splitting did not work correctly!");
1225 // Emit the new branch that selects between the two versions of this loop.
1226 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
1228 LPM->deleteSimpleAnalysisValue(OldBR, L);
1229 OldBR->eraseFromParent();
1231 LoopProcessWorklist.push_back(NewLoop);
1234 // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
1235 // deletes the instruction (for example by simplifying a PHI that feeds into
1236 // the condition that we're unswitching on), we don't rewrite the second
1238 WeakVH LICHandle(LIC);
1240 // Now we rewrite the original code to know that the condition is true and the
1241 // new code to know that the condition is false.
1242 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
1244 // It's possible that simplifying one loop could cause the other to be
1245 // changed to another value or a constant. If its a constant, don't simplify
1247 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1248 LICHandle && !isa<Constant>(LICHandle))
1249 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
1252 /// Remove all instances of I from the worklist vector specified.
1253 static void RemoveFromWorklist(Instruction *I,
1254 std::vector<Instruction*> &Worklist) {
1256 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
1260 /// When we find that I really equals V, remove I from the
1261 /// program, replacing all uses with V and update the worklist.
1262 static void ReplaceUsesOfWith(Instruction *I, Value *V,
1263 std::vector<Instruction*> &Worklist,
1264 Loop *L, LPPassManager *LPM) {
1265 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
1267 // Add uses to the worklist, which may be dead now.
1268 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1269 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1270 Worklist.push_back(Use);
1272 // Add users to the worklist which may be simplified now.
1273 for (User *U : I->users())
1274 Worklist.push_back(cast<Instruction>(U));
1275 LPM->deleteSimpleAnalysisValue(I, L);
1276 RemoveFromWorklist(I, Worklist);
1277 I->replaceAllUsesWith(V);
1278 I->eraseFromParent();
1282 /// We know either that the value LIC has the value specified by Val in the
1283 /// specified loop, or we know it does NOT have that value.
1284 /// Rewrite any uses of LIC or of properties correlated to it.
1285 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
1288 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
1290 // FIXME: Support correlated properties, like:
1297 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1298 // selects, switches.
1299 std::vector<Instruction*> Worklist;
1300 LLVMContext &Context = Val->getContext();
1302 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1303 // in the loop with the appropriate one directly.
1304 if (IsEqual || (isa<ConstantInt>(Val) &&
1305 Val->getType()->isIntegerTy(1))) {
1310 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
1311 !cast<ConstantInt>(Val)->getZExtValue());
1313 for (User *U : LIC->users()) {
1314 Instruction *UI = dyn_cast<Instruction>(U);
1315 if (!UI || !L->contains(UI))
1317 Worklist.push_back(UI);
1320 for (Instruction *UI : Worklist)
1321 UI->replaceUsesOfWith(LIC, Replacement);
1323 SimplifyCode(Worklist, L);
1327 // Otherwise, we don't know the precise value of LIC, but we do know that it
1328 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1329 // can. This case occurs when we unswitch switch statements.
1330 for (User *U : LIC->users()) {
1331 Instruction *UI = dyn_cast<Instruction>(U);
1332 if (!UI || !L->contains(UI))
1335 // At this point, we know LIC is definitely not Val. Try to use some simple
1336 // logic to simplify the user w.r.t. to the context.
1337 if (Value *Replacement = SimplifyInstructionWithNotEqual(UI, LIC, Val)) {
1338 if (LI->replacementPreservesLCSSAForm(UI, Replacement)) {
1339 // This in-loop instruction has been simplified w.r.t. its context,
1340 // i.e. LIC != Val, make sure we propagate its replacement value to
1343 // We can not yet delete UI, the LIC user, yet, because that would invalidate
1344 // the LIC->users() iterator !. However, we can make this instruction
1345 // dead by replacing all its users and push it onto the worklist so that
1346 // it can be properly deleted and its operands simplified.
1347 UI->replaceAllUsesWith(Replacement);
1351 // This is a LIC user, push it into the worklist so that SimplifyCode can
1352 // attempt to simplify it.
1353 Worklist.push_back(UI);
1355 // If we know that LIC is not Val, use this info to simplify code.
1356 SwitchInst *SI = dyn_cast<SwitchInst>(UI);
1357 if (!SI || !isa<ConstantInt>(Val)) continue;
1359 // NOTE: if a case value for the switch is unswitched out, we record it
1360 // after the unswitch finishes. We can not record it here as the switch
1361 // is not a direct user of the partial LIV.
1362 SwitchInst::CaseHandle DeadCase =
1363 *SI->findCaseValue(cast<ConstantInt>(Val));
1364 // Default case is live for multiple values.
1365 if (DeadCase == *SI->case_default())
1368 // Found a dead case value. Don't remove PHI nodes in the
1369 // successor if they become single-entry, those PHI nodes may
1370 // be in the Users list.
1372 BasicBlock *Switch = SI->getParent();
1373 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
1374 BasicBlock *Latch = L->getLoopLatch();
1376 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
1377 // If the DeadCase successor dominates the loop latch, then the
1378 // transformation isn't safe since it will delete the sole predecessor edge
1380 if (Latch && DT->dominates(SISucc, Latch))
1383 // FIXME: This is a hack. We need to keep the successor around
1384 // and hooked up so as to preserve the loop structure, because
1385 // trying to update it is complicated. So instead we preserve the
1386 // loop structure and put the block on a dead code path.
1387 SplitEdge(Switch, SISucc, DT, LI);
1388 // Compute the successors instead of relying on the return value
1389 // of SplitEdge, since it may have split the switch successor
1391 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
1392 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1393 // Create an "unreachable" destination.
1394 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1395 Switch->getParent(),
1397 new UnreachableInst(Context, Abort);
1398 // Force the new case destination to branch to the "unreachable"
1399 // block while maintaining a (dead) CFG edge to the old block.
1400 NewSISucc->getTerminator()->eraseFromParent();
1401 BranchInst::Create(Abort, OldSISucc,
1402 ConstantInt::getTrue(Context), NewSISucc);
1403 // Release the PHI operands for this edge.
1404 for (BasicBlock::iterator II = NewSISucc->begin();
1405 PHINode *PN = dyn_cast<PHINode>(II); ++II)
1406 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1407 UndefValue::get(PN->getType()));
1408 // Tell the domtree about the new block. We don't fully update the
1409 // domtree here -- instead we force it to do a full recomputation
1410 // after the pass is complete -- but we do need to inform it of
1412 DT->addNewBlock(Abort, NewSISucc);
1415 SimplifyCode(Worklist, L);
1418 /// Now that we have simplified some instructions in the loop, walk over it and
1419 /// constant prop, dce, and fold control flow where possible. Note that this is
1420 /// effectively a very simple loop-structure-aware optimizer. During processing
1421 /// of this loop, L could very well be deleted, so it must not be used.
1423 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1426 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
1427 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
1428 while (!Worklist.empty()) {
1429 Instruction *I = Worklist.back();
1430 Worklist.pop_back();
1433 if (isInstructionTriviallyDead(I)) {
1434 DEBUG(dbgs() << "Remove dead instruction '" << *I);
1436 // Add uses to the worklist, which may be dead now.
1437 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1438 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1439 Worklist.push_back(Use);
1440 LPM->deleteSimpleAnalysisValue(I, L);
1441 RemoveFromWorklist(I, Worklist);
1442 I->eraseFromParent();
1447 // See if instruction simplification can hack this up. This is common for
1448 // things like "select false, X, Y" after unswitching made the condition be
1449 // 'false'. TODO: update the domtree properly so we can pass it here.
1450 if (Value *V = SimplifyInstruction(I, DL))
1451 if (LI->replacementPreservesLCSSAForm(I, V)) {
1452 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1456 // Special case hacks that appear commonly in unswitched code.
1457 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1458 if (BI->isUnconditional()) {
1459 // If BI's parent is the only pred of the successor, fold the two blocks
1461 BasicBlock *Pred = BI->getParent();
1462 BasicBlock *Succ = BI->getSuccessor(0);
1463 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1464 if (!SinglePred) continue; // Nothing to do.
1465 assert(SinglePred == Pred && "CFG broken");
1467 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
1468 << Succ->getName() << "\n");
1470 // Resolve any single entry PHI nodes in Succ.
1471 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1472 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
1474 // If Succ has any successors with PHI nodes, update them to have
1475 // entries coming from Pred instead of Succ.
1476 Succ->replaceAllUsesWith(Pred);
1478 // Move all of the successor contents from Succ to Pred.
1479 Pred->getInstList().splice(BI->getIterator(), Succ->getInstList(),
1480 Succ->begin(), Succ->end());
1481 LPM->deleteSimpleAnalysisValue(BI, L);
1482 RemoveFromWorklist(BI, Worklist);
1483 BI->eraseFromParent();
1485 // Remove Succ from the loop tree.
1486 LI->removeBlock(Succ);
1487 LPM->deleteSimpleAnalysisValue(Succ, L);
1488 Succ->eraseFromParent();
1498 /// Simple simplifications we can do given the information that Cond is
1499 /// definitely not equal to Val.
1500 Value *LoopUnswitch::SimplifyInstructionWithNotEqual(Instruction *Inst,
1503 // icmp eq cond, val -> false
1504 ICmpInst *CI = dyn_cast<ICmpInst>(Inst);
1505 if (CI && CI->isEquality()) {
1506 Value *Op0 = CI->getOperand(0);
1507 Value *Op1 = CI->getOperand(1);
1508 if ((Op0 == Invariant && Op1 == Val) || (Op0 == Val && Op1 == Invariant)) {
1509 LLVMContext &Ctx = Inst->getContext();
1510 if (CI->getPredicate() == CmpInst::ICMP_EQ)
1511 return ConstantInt::getFalse(Ctx);
1513 return ConstantInt::getTrue(Ctx);
1517 // FIXME: there may be other opportunities, e.g. comparison with floating
1518 // point, or Invariant - Val != 0, etc.