blob: 4a48d90e71625ffd4a0a0231b1c66d583a619497 [file] [log] [blame]
Chris Lattnerf48f7772004-04-19 18:07:02 +00001//===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattnerf48f7772004-04-19 18:07:02 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattnerf48f7772004-04-19 18:07:02 +00008//===----------------------------------------------------------------------===//
9//
10// This pass transforms loops that contain branches on loop-invariant conditions
Xin Tongb7b08122017-04-23 17:36:25 +000011// to multiple loops. For example, it turns the left into the right code:
Chris Lattnerf48f7772004-04-19 18:07:02 +000012//
13// for (...) if (lic)
14// A for (...)
15// if (lic) A; B; C
16// B else
17// C for (...)
18// A; C
19//
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.
23//
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.
26//
27//===----------------------------------------------------------------------===//
28
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/Statistic.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000032#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000033#include "llvm/Analysis/BlockFrequencyInfo.h"
34#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
35#include "llvm/Analysis/BranchProbabilityInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Analysis/CodeMetrics.h"
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +000037#include "llvm/Analysis/DivergenceAnalysis.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000038#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000039#include "llvm/Analysis/InstructionSimplify.h"
40#include "llvm/Analysis/LoopInfo.h"
41#include "llvm/Analysis/LoopPass.h"
42#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000043#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Constants.h"
45#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000046#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Function.h"
Xin Tongec6f90b2017-02-23 23:42:19 +000048#include "llvm/IR/InstrTypes.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000049#include "llvm/IR/Instructions.h"
Weiming Zhaof1abad52015-06-23 05:31:09 +000050#include "llvm/IR/MDBuilder.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000051#include "llvm/IR/Module.h"
52#include "llvm/Support/BranchProbability.h"
Chris Lattner89762192006-02-09 20:15:48 +000053#include "llvm/Support/CommandLine.h"
Reid Spencer557ab152007-02-05 23:32:05 +000054#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000055#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000056#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000057#include "llvm/Transforms/Utils/BasicBlockUtils.h"
58#include "llvm/Transforms/Utils/Cloning.h"
59#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000060#include "llvm/Transforms/Utils/LoopUtils.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000061#include <algorithm>
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000062#include <map>
Chris Lattner2826e052006-02-09 19:14:52 +000063#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000064using namespace llvm;
65
Chandler Carruth964daaa2014-04-22 02:55:47 +000066#define DEBUG_TYPE "loop-unswitch"
67
Chris Lattner79a42ac2006-12-19 21:40:18 +000068STATISTIC(NumBranches, "Number of branches unswitched");
69STATISTIC(NumSwitches, "Number of switches unswitched");
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +000070STATISTIC(NumGuards, "Number of guards unswitched");
Chris Lattner79a42ac2006-12-19 21:40:18 +000071STATISTIC(NumSelects , "Number of selects unswitched");
72STATISTIC(NumTrivial , "Number of unswitches that are trivial");
73STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000074STATISTIC(TotalInsts, "Total number of instructions analyzed");
Chris Lattner79a42ac2006-12-19 21:40:18 +000075
Stepan Dyatkovskiy2931a592012-01-16 20:48:04 +000076// The specific value of 100 here was chosen based only on intuition and a
Dan Gohman71ca6522009-10-13 17:50:43 +000077// few specific examples.
Dan Gohmand78c4002008-05-13 00:00:25 +000078static cl::opt<unsigned>
79Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000080 cl::init(100), cl::Hidden);
Andrew Trick4104ed92012-04-10 05:14:37 +000081
Dan Gohmand78c4002008-05-13 00:00:25 +000082namespace {
Andrew Trick4104ed92012-04-10 05:14:37 +000083
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000084 class LUAnalysisCache {
85
86 typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
87 UnswitchedValsMap;
Andrew Trick4104ed92012-04-10 05:14:37 +000088
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000089 typedef UnswitchedValsMap::iterator UnswitchedValsIt;
Andrew Trick4104ed92012-04-10 05:14:37 +000090
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000091 struct LoopProperties {
92 unsigned CanBeUnswitchedCount;
Mark Heffernan9b536a62015-06-23 18:26:50 +000093 unsigned WasUnswitchedCount;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000094 unsigned SizeEstimation;
95 UnswitchedValsMap UnswitchedVals;
96 };
Andrew Trick4104ed92012-04-10 05:14:37 +000097
98 // Here we use std::map instead of DenseMap, since we need to keep valid
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000099 // LoopProperties pointer for current loop for better performance.
100 typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
101 typedef LoopPropsMap::iterator LoopPropsMapIt;
Andrew Trick4104ed92012-04-10 05:14:37 +0000102
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000103 LoopPropsMap LoopsProperties;
Jakub Staszak27da1232013-08-06 17:03:42 +0000104 UnswitchedValsMap *CurLoopInstructions;
105 LoopProperties *CurrentLoopProperties;
Andrew Trick4104ed92012-04-10 05:14:37 +0000106
Mark Heffernan9b536a62015-06-23 18:26:50 +0000107 // 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.
116 //
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.
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000121 unsigned MaxSize;
Andrew Trick4104ed92012-04-10 05:14:37 +0000122
Mark Heffernan9b536a62015-06-23 18:26:50 +0000123 public:
124 LUAnalysisCache()
125 : CurLoopInstructions(nullptr), CurrentLoopProperties(nullptr),
126 MaxSize(Threshold) {}
Andrew Trick4104ed92012-04-10 05:14:37 +0000127
Mark Heffernan9b536a62015-06-23 18:26:50 +0000128 // Analyze loop. Check its size, calculate is it possible to unswitch
129 // it. Returns true if we can unswitch this loop.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000130 bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
131 AssumptionCache *AC);
Andrew Trick4104ed92012-04-10 05:14:37 +0000132
Mark Heffernan9b536a62015-06-23 18:26:50 +0000133 // Clean all data related to given loop.
134 void forgetLoop(const Loop *L);
Andrew Trick4104ed92012-04-10 05:14:37 +0000135
Mark Heffernan9b536a62015-06-23 18:26:50 +0000136 // 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);
Andrew Trick4104ed92012-04-10 05:14:37 +0000140
Mark Heffernan9b536a62015-06-23 18:26:50 +0000141 // Check was this case value unswitched before or not.
142 bool isUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000143
Mark Heffernan9b536a62015-06-23 18:26:50 +0000144 // Returns true if another unswitching could be done within the cost
145 // threshold.
146 bool CostAllowsUnswitching();
Andrew Trick4104ed92012-04-10 05:14:37 +0000147
Mark Heffernan9b536a62015-06-23 18:26:50 +0000148 // 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);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000153 };
Andrew Trick4104ed92012-04-10 05:14:37 +0000154
Chris Lattner2dd09db2009-09-02 06:11:42 +0000155 class LoopUnswitch : public LoopPass {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000156 LoopInfo *LI; // Loop information
Devang Patel901a27d2007-03-07 00:26:10 +0000157 LPPassManager *LPM;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000158 AssumptionCache *AC;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000159
Sanjay Patel956e29c2015-08-11 21:24:04 +0000160 // Used to check if second loop needs processing after
161 // RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000162 std::vector<Loop*> LoopProcessWorklist;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000163
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000164 LUAnalysisCache BranchesInfo;
Andrew Trick4104ed92012-04-10 05:14:37 +0000165
Devang Patel506310d2007-06-06 00:21:03 +0000166 bool OptimizeForSize;
Devang Patel7d165e12007-07-30 23:07:10 +0000167 bool redoLoop;
Devang Patela69f9872007-10-05 22:29:34 +0000168
Devang Patele149d4e2008-07-02 01:18:13 +0000169 Loop *currentLoop;
Devang Patela69f9872007-10-05 22:29:34 +0000170 DominatorTree *DT;
Devang Patele149d4e2008-07-02 01:18:13 +0000171 BasicBlock *loopHeader;
172 BasicBlock *loopPreheader;
Andrew Trick4104ed92012-04-10 05:14:37 +0000173
Evgeniy Stepanoveaea2972016-06-10 20:03:20 +0000174 bool SanitizeMemory;
175 LoopSafetyInfo SafetyInfo;
176
Devang Pateled50fb52008-07-02 01:44:29 +0000177 // LoopBlocks contains all of the basic blocks of the loop, including the
Andrew Trick4104ed92012-04-10 05:14:37 +0000178 // preheader of the loop, the body of the loop, and the exit blocks of the
Devang Pateled50fb52008-07-02 01:44:29 +0000179 // loop, in that order.
180 std::vector<BasicBlock*> LoopBlocks;
181 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
182 std::vector<BasicBlock*> NewBlocks;
Devang Pateleb611dd2008-07-03 17:37:52 +0000183
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000184 bool hasBranchDivergence;
185
Chris Lattnerf48f7772004-04-19 18:07:02 +0000186 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000187 static char ID; // Pass ID, replacement for typeid
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000188 explicit LoopUnswitch(bool Os = false, bool hasBranchDivergence = false) :
Andrew Trick4104ed92012-04-10 05:14:37 +0000189 LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
Craig Topperf40110f2014-04-25 05:29:35 +0000190 currentLoop(nullptr), DT(nullptr), loopHeader(nullptr),
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000191 loopPreheader(nullptr), hasBranchDivergence(hasBranchDivergence) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000192 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
193 }
Devang Patel09f162c2007-05-01 21:15:47 +0000194
Craig Topper3e4c6972014-03-05 09:10:37 +0000195 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Devang Patele149d4e2008-07-02 01:18:13 +0000196 bool processCurrentLoop();
Abhilash Bhandari54e5a1a2016-11-25 14:07:44 +0000197 bool isUnreachableDueToPreviousUnswitching(BasicBlock *);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000198 /// This transformation requires natural loop information & requires that
Chris Lattnerbc1a65a2010-08-29 17:23:19 +0000199 /// loop preheaders be inserted into the CFG.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000200 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000201 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000202 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000203 AU.addRequired<TargetTransformInfoWrapperPass>();
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000204 if (hasBranchDivergence)
205 AU.addRequired<DivergenceAnalysis>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000206 getLoopAnalysisUsage(AU);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000207 }
208
209 private:
Devang Pateld4911982007-07-31 08:03:26 +0000210
Craig Topper3e4c6972014-03-05 09:10:37 +0000211 void releaseMemory() override {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000212 BranchesInfo.forgetLoop(currentLoop);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000213 }
214
Devang Patele149d4e2008-07-02 01:18:13 +0000215 void initLoopData() {
216 loopHeader = currentLoop->getHeader();
217 loopPreheader = currentLoop->getLoopPreheader();
218 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000219
Chris Lattner559c8672008-04-21 00:25:49 +0000220 /// Split all of the edges from inside the loop to their exit blocks.
221 /// Update the appropriate Phi nodes as we do so.
Sanjay Patel41f3d952015-08-11 21:11:56 +0000222 void SplitExitEdges(Loop *L,
223 const SmallVectorImpl<BasicBlock *> &ExitBlocks);
Devang Patela69f9872007-10-05 22:29:34 +0000224
Chen Lic0f3a152015-07-22 05:26:29 +0000225 bool TryTrivialLoopUnswitch(bool &Changed);
226
Weiming Zhaof1abad52015-06-23 05:31:09 +0000227 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,
228 TerminatorInst *TI = nullptr);
Chris Lattner29f771b2006-02-18 01:27:45 +0000229 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000230 BasicBlock *ExitBlock, TerminatorInst *TI);
231 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
232 TerminatorInst *TI);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000233
234 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
235 Constant *Val, bool isEqual);
Devang Patel3304e462007-06-28 00:49:00 +0000236
237 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
Andrew Trick4104ed92012-04-10 05:14:37 +0000238 BasicBlock *TrueDest,
Devang Patel3304e462007-06-28 00:49:00 +0000239 BasicBlock *FalseDest,
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000240 BranchInst *OldBranch,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000241 TerminatorInst *TI);
Devang Patel3304e462007-06-28 00:49:00 +0000242
Devang Pateld4911982007-07-31 08:03:26 +0000243 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Xin Tongec6f90b2017-02-23 23:42:19 +0000244
245 /// Given that the Invariant is not equal to Val. Simplify instructions
246 /// in the loop.
247 Value *SimplifyInstructionWithNotEqual(Instruction *Inst, Value *Invariant,
248 Constant *Val);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000249 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000250}
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000251
252// Analyze loop. Check its size, calculate is it possible to unswitch
253// it. Returns true if we can unswitch this loop.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000254bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
255 AssumptionCache *AC) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000256
Jakub Staszak27da1232013-08-06 17:03:42 +0000257 LoopPropsMapIt PropsIt;
258 bool Inserted;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000259 std::tie(PropsIt, Inserted) =
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000260 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
Andrew Trick4104ed92012-04-10 05:14:37 +0000261
Jakub Staszak27da1232013-08-06 17:03:42 +0000262 LoopProperties &Props = PropsIt->second;
Andrew Trick4104ed92012-04-10 05:14:37 +0000263
Jakub Staszak27da1232013-08-06 17:03:42 +0000264 if (Inserted) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000265 // New loop.
266
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.
Andrew Trick4104ed92012-04-10 05:14:37 +0000271
Hal Finkel57f03dd2014-09-07 13:49:57 +0000272 SmallPtrSet<const Value *, 32> EphValues;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000273 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000274
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000275 // 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.
278 CodeMetrics Metrics;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000279 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
280 ++I)
Hal Finkel57f03dd2014-09-07 13:49:57 +0000281 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000282
Mark Heffernan9b536a62015-06-23 18:26:50 +0000283 Props.SizeEstimation = Metrics.NumInsts;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000284 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
Mark Heffernan9b536a62015-06-23 18:26:50 +0000285 Props.WasUnswitchedCount = 0;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000286 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
James Molloy4f6fb952012-12-20 16:04:27 +0000287
288 if (Metrics.notDuplicatable) {
289 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak27da1232013-08-06 17:03:42 +0000290 << L->getHeader()->getName() << ", contents cannot be "
291 << "duplicated!\n");
James Molloy4f6fb952012-12-20 16:04:27 +0000292 return false;
293 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000294 }
295
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000296 // Be careful. This links are good only before new loop addition.
297 CurrentLoopProperties = &Props;
298 CurLoopInstructions = &Props.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000299
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000300 return true;
301}
302
303// Clean all data related to given loop.
Jakub Staszak27da1232013-08-06 17:03:42 +0000304void LUAnalysisCache::forgetLoop(const Loop *L) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000305
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000306 LoopPropsMapIt LIt = LoopsProperties.find(L);
307
308 if (LIt != LoopsProperties.end()) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000309 LoopProperties &Props = LIt->second;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000310 MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
311 Props.SizeEstimation;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000312 LoopsProperties.erase(LIt);
313 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000314
Craig Topperf40110f2014-04-25 05:29:35 +0000315 CurrentLoopProperties = nullptr;
316 CurLoopInstructions = nullptr;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000317}
318
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.
Jakub Staszak27da1232013-08-06 17:03:42 +0000322void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000323 (*CurLoopInstructions)[SI].insert(V);
324}
325
326// Check was this case value unswitched before or not.
Jakub Staszak27da1232013-08-06 17:03:42 +0000327bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000328 return (*CurLoopInstructions)[SI].count(V);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000329}
330
Mark Heffernan9b536a62015-06-23 18:26:50 +0000331bool LUAnalysisCache::CostAllowsUnswitching() {
332 return CurrentLoopProperties->CanBeUnswitchedCount > 0;
333}
334
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000335// Clone all loop-unswitch related loop properties.
336// Redistribute unswitching quotas.
337// Note, that new loop data is stored inside the VMap.
Jakub Staszak27da1232013-08-06 17:03:42 +0000338void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
339 const ValueToValueMapTy &VMap) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000340
Jakub Staszak27da1232013-08-06 17:03:42 +0000341 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
342 LoopProperties &OldLoopProps = *CurrentLoopProperties;
343 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000344
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000345 // Reallocate "can-be-unswitched quota"
346
347 --OldLoopProps.CanBeUnswitchedCount;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000348 ++OldLoopProps.WasUnswitchedCount;
349 NewLoopProps.WasUnswitchedCount = 0;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000350 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
351 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
352 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
Andrew Trick4104ed92012-04-10 05:14:37 +0000353
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000354 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
Andrew Trick4104ed92012-04-10 05:14:37 +0000355
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000356 // 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) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000360 const SwitchInst *OldInst = I->first;
361 Value *NewI = VMap.lookup(OldInst);
362 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000363 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
Andrew Trick4104ed92012-04-10 05:14:37 +0000364
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000365 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
366 }
367}
368
Dan Gohmand78c4002008-05-13 00:00:25 +0000369char LoopUnswitch::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000370INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
371 false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000372INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth31088a92016-02-19 10:45:18 +0000373INITIALIZE_PASS_DEPENDENCY(LoopPass)
374INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000375INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000376INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
377 false, false)
Chris Lattnerf48f7772004-04-19 18:07:02 +0000378
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000379Pass *llvm::createLoopUnswitchPass(bool Os, bool hasBranchDivergence) {
380 return new LoopUnswitch(Os, hasBranchDivergence);
Devang Patel506310d2007-06-06 00:21:03 +0000381}
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000382
Xin Tong16b85a62017-02-27 18:00:13 +0000383/// Operator chain lattice.
384enum OperatorChain {
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.
389};
390
Sanjay Patel956e29c2015-08-11 21:24:04 +0000391/// 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.
Xin Tong16b85a62017-02-27 18:00:13 +0000393//
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.
398///
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.
Sanjoy Dasd8500682016-06-25 01:14:19 +0000402static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed,
Xin Tong16b85a62017-02-27 18:00:13 +0000403 OperatorChain &ParentChain,
Sanjoy Dasd8500682016-06-25 01:14:19 +0000404 DenseMap<Value *, Value *> &Cache) {
405 auto CacheIt = Cache.find(Cond);
406 if (CacheIt != Cache.end())
407 return CacheIt->second;
Andrew Trick4104ed92012-04-10 05:14:37 +0000408
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000409 // We started analyze new instruction, increment scanned instructions counter.
410 ++TotalInsts;
Andrew Trick4104ed92012-04-10 05:14:37 +0000411
Chris Lattner302240d2010-02-02 02:26:54 +0000412 // We can never unswitch on vector conditions.
Duncan Sands19d0b472010-02-16 11:11:14 +0000413 if (Cond->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000414 return nullptr;
Chris Lattner302240d2010-02-02 02:26:54 +0000415
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000416 // Constants should be folded, not unswitched on!
Craig Topperf40110f2014-04-25 05:29:35 +0000417 if (isa<Constant>(Cond)) return nullptr;
Devang Patel3c723c82007-06-28 00:44:10 +0000418
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000419 // TODO: Handle: br (VARIANT|INVARIANT).
Devang Patelfe57d102008-11-03 19:38:07 +0000420
Dan Gohman4d6149f2009-07-14 01:37:59 +0000421 // Hoist simple values out.
Sanjoy Dasd8500682016-06-25 01:14:19 +0000422 if (L->makeLoopInvariant(Cond, Changed)) {
423 Cache[Cond] = Cond;
Dan Gohman4d6149f2009-07-14 01:37:59 +0000424 return Cond;
Sanjoy Dasd8500682016-06-25 01:14:19 +0000425 }
Dan Gohman4d6149f2009-07-14 01:37:59 +0000426
Xin Tong16b85a62017-02-27 18:00:13 +0000427 // Walk up the operator chain to find partial invariant conditions.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000428 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
429 if (BO->getOpcode() == Instruction::And ||
430 BO->getOpcode() == Instruction::Or) {
Xin Tong16b85a62017-02-27 18:00:13 +0000431 // Given the previous operator, compute the current operator chain status.
432 OperatorChain NewChain;
433 switch (ParentChain) {
434 case OC_OpChainNone:
435 NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
436 OC_OpChainOr;
437 break;
438 case OC_OpChainOr:
439 NewChain = BO->getOpcode() == Instruction::Or ? OC_OpChainOr :
440 OC_OpChainMixed;
441 break;
442 case OC_OpChainAnd:
443 NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
444 OC_OpChainMixed;
445 break;
446 case OC_OpChainMixed:
447 NewChain = OC_OpChainMixed;
448 break;
Sanjoy Dasd8500682016-06-25 01:14:19 +0000449 }
Xin Tong16b85a62017-02-27 18:00:13 +0000450
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)) {
463 Cache[Cond] = LHS;
464 return LHS;
465 }
466 // We did not manage to find a partial LIV in operand(0). Backtrack and try
467 // operand(1).
468 ParentChain = NewChain;
469 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed,
470 ParentChain, Cache)) {
471 Cache[Cond] = RHS;
472 return RHS;
473 }
Sanjoy Dasd8500682016-06-25 01:14:19 +0000474 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000475 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000476
Sanjoy Dasd8500682016-06-25 01:14:19 +0000477 Cache[Cond] = nullptr;
Craig Topperf40110f2014-04-25 05:29:35 +0000478 return nullptr;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000479}
480
Xin Tong16b85a62017-02-27 18:00:13 +0000481/// 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.
484static std::pair<Value *, OperatorChain> FindLIVLoopCondition(Value *Cond,
485 Loop *L,
486 bool &Changed) {
Sanjoy Dasd8500682016-06-25 01:14:19 +0000487 DenseMap<Value *, Value *> Cache;
Xin Tong16b85a62017-02-27 18:00:13 +0000488 OperatorChain OpChain = OC_OpChainNone;
489 Value *FCond = FindLIVLoopCondition(Cond, L, Changed, OpChain, Cache);
490
491 // In case we do find a LIV, it can not be obtained by walking up a mixed
492 // operator chain.
493 assert((!FCond || OpChain != OC_OpChainMixed) &&
494 "Do not expect a partial LIV with mixed operator chain");
495 return {FCond, OpChain};
Sanjoy Dasd8500682016-06-25 01:14:19 +0000496}
497
Devang Patel901a27d2007-03-07 00:26:10 +0000498bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000499 if (skipLoop(L))
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000500 return false;
501
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000502 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
503 *L->getHeader()->getParent());
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000504 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Devang Patel901a27d2007-03-07 00:26:10 +0000505 LPM = &LPM_Ref;
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000506 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Devang Patele149d4e2008-07-02 01:18:13 +0000507 currentLoop = L;
Devang Patel40519f02008-09-04 22:43:59 +0000508 Function *F = currentLoop->getHeader()->getParent();
Chen Li9f27fc02015-09-29 05:03:32 +0000509
Evgeniy Stepanoveaea2972016-06-10 20:03:20 +0000510 SanitizeMemory = F->hasFnAttribute(Attribute::SanitizeMemory);
511 if (SanitizeMemory)
512 computeLoopSafetyInfo(&SafetyInfo, L);
513
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000514 bool Changed = false;
Devang Patel7d165e12007-07-30 23:07:10 +0000515 do {
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000516 assert(currentLoop->isLCSSAForm(*DT));
Devang Patel7d165e12007-07-30 23:07:10 +0000517 redoLoop = false;
Devang Patele149d4e2008-07-02 01:18:13 +0000518 Changed |= processCurrentLoop();
Devang Patel7d165e12007-07-30 23:07:10 +0000519 } while(redoLoop);
520
521 return Changed;
522}
523
Abhilash Bhandari54e5a1a2016-11-25 14:07:44 +0000524// Return true if the BasicBlock BB is unreachable from the loop header.
525// Return false, otherwise.
526bool LoopUnswitch::isUnreachableDueToPreviousUnswitching(BasicBlock *BB) {
527 auto *Node = DT->getNode(BB)->getIDom();
528 BasicBlock *DomBB = Node->getBlock();
529 while (currentLoop->contains(DomBB)) {
530 BranchInst *BInst = dyn_cast<BranchInst>(DomBB->getTerminator());
531
532 Node = DT->getNode(DomBB)->getIDom();
533 DomBB = Node->getBlock();
534
535 if (!BInst || !BInst->isConditional())
536 continue;
537
538 Value *Cond = BInst->getCondition();
539 if (!isa<ConstantInt>(Cond))
540 continue;
541
542 BasicBlock *UnreachableSucc =
543 Cond == ConstantInt::getTrue(Cond->getContext())
544 ? BInst->getSuccessor(1)
545 : BInst->getSuccessor(0);
546
547 if (DT->dominates(UnreachableSucc, BB))
548 return true;
549 }
550 return false;
551}
552
Wei Mifc0e2452017-07-25 23:37:17 +0000553/// FIXME: Remove this workaround when freeze related patches are done.
554/// LoopUnswitch and Equality propagation in GVN have discrepancy about
555/// whether branch on undef/poison has undefine behavior. Here it is to
556/// rule out some common cases that we found such discrepancy already
557/// causing problems. Detail could be found in PR31652. Note if the
558/// func returns true, it is unsafe. But if it is false, it doesn't mean
559/// it is necessarily safe.
560static bool EqualityPropUnSafe(Value &LoopCond) {
561 ICmpInst *CI = dyn_cast<ICmpInst>(&LoopCond);
562 if (!CI || !CI->isEquality())
563 return false;
564
565 Value *LHS = CI->getOperand(0);
566 Value *RHS = CI->getOperand(1);
567 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
568 return true;
569
570 auto hasUndefInPHI = [](PHINode &PN) {
571 for (Value *Opd : PN.incoming_values()) {
572 if (isa<UndefValue>(Opd))
573 return true;
574 }
575 return false;
576 };
577 PHINode *LPHI = dyn_cast<PHINode>(LHS);
578 PHINode *RPHI = dyn_cast<PHINode>(RHS);
579 if ((LPHI && hasUndefInPHI(*LPHI)) || (RPHI && hasUndefInPHI(*RPHI)))
580 return true;
581
582 auto hasUndefInSelect = [](SelectInst &SI) {
583 if (isa<UndefValue>(SI.getTrueValue()) ||
584 isa<UndefValue>(SI.getFalseValue()))
585 return true;
586 return false;
587 };
588 SelectInst *LSI = dyn_cast<SelectInst>(LHS);
589 SelectInst *RSI = dyn_cast<SelectInst>(RHS);
590 if ((LSI && hasUndefInSelect(*LSI)) || (RSI && hasUndefInSelect(*RSI)))
591 return true;
592 return false;
593}
594
Sanjay Patel956e29c2015-08-11 21:24:04 +0000595/// Do actual work and unswitch loop if possible and profitable.
Devang Patele149d4e2008-07-02 01:18:13 +0000596bool LoopUnswitch::processCurrentLoop() {
Devang Patel7d165e12007-07-30 23:07:10 +0000597 bool Changed = false;
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000598
599 initLoopData();
Andrew Trick4104ed92012-04-10 05:14:37 +0000600
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000601 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
602 if (!loopPreheader)
603 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000604
Andrew Trick4442bfe2012-04-10 05:14:42 +0000605 // Loops with indirectbr cannot be cloned.
606 if (!currentLoop->isSafeToClone())
607 return false;
608
609 // Without dedicated exits, splitting the exit edge may fail.
610 if (!currentLoop->hasDedicatedExits())
611 return false;
612
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000613 LLVMContext &Context = loopHeader->getContext();
Andrew Trick4104ed92012-04-10 05:14:37 +0000614
Chen Li567aa7a2015-10-14 19:47:43 +0000615 // Analyze loop cost, and stop unswitching if loop content can not be duplicated.
Chandler Carruth705b1852015-01-31 03:43:40 +0000616 if (!BranchesInfo.countLoop(
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000617 currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000618 *currentLoop->getHeader()->getParent()),
619 AC))
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000620 return false;
Devang Patel7d165e12007-07-30 23:07:10 +0000621
Chen Lic0f3a152015-07-22 05:26:29 +0000622 // Try trivial unswitch first before loop over other basic blocks in the loop.
623 if (TryTrivialLoopUnswitch(Changed)) {
624 return true;
625 }
626
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +0000627 // Run through the instructions in the loop, keeping track of three things:
628 //
629 // - That we do not unswitch loops containing convergent operations, as we
630 // might be making them control dependent on the unswitch value when they
631 // were not before.
632 // FIXME: This could be refined to only bail if the convergent operation is
633 // not already control-dependent on the unswitch value.
634 //
635 // - That basic blocks in the loop contain invokes whose predecessor edges we
636 // cannot split.
637 //
638 // - The set of guard intrinsics encountered (these are non terminator
639 // instructions that are also profitable to be unswitched).
640
641 SmallVector<IntrinsicInst *, 4> Guards;
642
Owen Anderson2c9978b2015-10-09 18:40:20 +0000643 for (const auto BB : currentLoop->blocks()) {
Owen Anderson97ca0f32015-10-09 20:17:46 +0000644 for (auto &I : *BB) {
645 auto CS = CallSite(&I);
646 if (!CS) continue;
647 if (CS.hasFnAttr(Attribute::Convergent))
Owen Anderson2c9978b2015-10-09 18:40:20 +0000648 return false;
David Majnemer3d90bb72016-05-03 03:57:40 +0000649 if (auto *II = dyn_cast<InvokeInst>(&I))
650 if (!II->getUnwindDest()->canSplitPredecessors())
651 return false;
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +0000652 if (auto *II = dyn_cast<IntrinsicInst>(&I))
653 if (II->getIntrinsicID() == Intrinsic::experimental_guard)
654 Guards.push_back(II);
Owen Anderson2c9978b2015-10-09 18:40:20 +0000655 }
656 }
657
Chen Lif458c6f2015-08-13 05:24:29 +0000658 // Do not do non-trivial unswitch while optimizing for size.
659 // FIXME: Use Function::optForSize().
660 if (OptimizeForSize ||
661 loopHeader->getParent()->hasFnAttribute(Attribute::OptimizeForSize))
662 return false;
663
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +0000664 for (IntrinsicInst *Guard : Guards) {
665 Value *LoopCond =
Xin Tong16b85a62017-02-27 18:00:13 +0000666 FindLIVLoopCondition(Guard->getOperand(0), currentLoop, Changed).first;
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +0000667 if (LoopCond &&
668 UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context))) {
669 // NB! Unswitching (if successful) could have erased some of the
670 // instructions in Guards leaving dangling pointers there. This is fine
671 // because we're returning now, and won't look at Guards again.
672 ++NumGuards;
673 return true;
674 }
675 }
676
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000677 // Loop over all of the basic blocks in the loop. If we find an interior
678 // block that is branching on a loop-invariant condition, we can unswitch this
679 // loop.
Andrew Trick4104ed92012-04-10 05:14:37 +0000680 for (Loop::block_iterator I = currentLoop->block_begin(),
Chris Lattnerc832c1b2010-04-05 21:18:32 +0000681 E = currentLoop->block_end(); I != E; ++I) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000682 TerminatorInst *TI = (*I)->getTerminator();
Evgeniy Stepanoveaea2972016-06-10 20:03:20 +0000683
684 // Unswitching on a potentially uninitialized predicate is not
685 // MSan-friendly. Limit this to the cases when the original predicate is
686 // guaranteed to execute, to avoid creating a use-of-uninitialized-value
687 // in the code that did not have one.
688 // This is a workaround for the discrepancy between LLVM IR and MSan
689 // semantics. See PR28054 for more details.
690 if (SanitizeMemory &&
691 !isGuaranteedToExecute(*TI, DT, currentLoop, &SafetyInfo))
692 continue;
693
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000694 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Abhilash Bhandari54e5a1a2016-11-25 14:07:44 +0000695 // Some branches may be rendered unreachable because of previous
696 // unswitching.
697 // Unswitch only those branches that are reachable.
698 if (isUnreachableDueToPreviousUnswitching(*I))
699 continue;
700
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000701 // If this isn't branching on an invariant condition, we can't unswitch
702 // it.
703 if (BI->isConditional()) {
704 // See if this, or some part of it, is loop invariant. If so, we can
705 // unswitch on it if we desire.
Andrew Trick4104ed92012-04-10 05:14:37 +0000706 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
Xin Tong16b85a62017-02-27 18:00:13 +0000707 currentLoop, Changed).first;
Wei Mifc0e2452017-07-25 23:37:17 +0000708 if (!LoopCond || EqualityPropUnSafe(*LoopCond))
709 continue;
710
711 if (UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000712 ++NumBranches;
713 return true;
714 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000715 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000716 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Xin Tong16b85a62017-02-27 18:00:13 +0000717 Value *SC = SI->getCondition();
718 Value *LoopCond;
719 OperatorChain OpChain;
720 std::tie(LoopCond, OpChain) =
721 FindLIVLoopCondition(SC, currentLoop, Changed);
722
Andrew Trick4104ed92012-04-10 05:14:37 +0000723 unsigned NumCases = SI->getNumCases();
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000724 if (LoopCond && NumCases) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000725 // Find a value to unswitch on:
726 // FIXME: this should chose the most expensive case!
Nick Lewycky61158242011-06-03 06:27:15 +0000727 // FIXME: scan for a case with a non-critical edge?
Craig Topperf40110f2014-04-25 05:29:35 +0000728 Constant *UnswitchVal = nullptr;
Xin Tong16b85a62017-02-27 18:00:13 +0000729 // Find a case value such that at least one case value is unswitched
730 // out.
731 if (OpChain == OC_OpChainAnd) {
732 // If the chain only has ANDs and the switch has a case value of 0.
733 // Dropping in a 0 to the chain will unswitch out the 0-casevalue.
734 auto *AllZero = cast<ConstantInt>(Constant::getNullValue(SC->getType()));
735 if (BranchesInfo.isUnswitched(SI, AllZero))
736 continue;
737 // We are unswitching 0 out.
738 UnswitchVal = AllZero;
739 } else if (OpChain == OC_OpChainOr) {
740 // If the chain only has ORs and the switch has a case value of ~0.
741 // Dropping in a ~0 to the chain will unswitch out the ~0-casevalue.
742 auto *AllOne = cast<ConstantInt>(Constant::getAllOnesValue(SC->getType()));
743 if (BranchesInfo.isUnswitched(SI, AllOne))
744 continue;
745 // We are unswitching ~0 out.
746 UnswitchVal = AllOne;
747 } else {
748 assert(OpChain == OC_OpChainNone &&
749 "Expect to unswitch on trivial chain");
750 // Do not process same value again and again.
751 // At this point we have some cases already unswitched and
752 // some not yet unswitched. Let's find the first not yet unswitched one.
Chandler Carruth927d8e62017-04-12 07:27:28 +0000753 for (auto Case : SI->cases()) {
754 Constant *UnswitchValCandidate = Case.getCaseValue();
Xin Tong16b85a62017-02-27 18:00:13 +0000755 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
756 UnswitchVal = UnswitchValCandidate;
757 break;
758 }
Chad Rosier3ba90a12011-12-22 21:10:46 +0000759 }
760 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000761
Chad Rosier3ba90a12011-12-22 21:10:46 +0000762 if (!UnswitchVal)
Devang Patel967b84c2007-02-26 19:31:58 +0000763 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000764
Devang Patele149d4e2008-07-02 01:18:13 +0000765 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000766 ++NumSwitches;
Xin Tong16b85a62017-02-27 18:00:13 +0000767 // In case of a full LIV, UnswitchVal is the value we unswitched out.
768 // In case of a partial LIV, we only unswitch when its an AND-chain
769 // or OR-chain. In both cases switch input value simplifies to
770 // UnswitchVal.
771 BranchesInfo.setUnswitched(SI, UnswitchVal);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000772 return true;
773 }
774 }
775 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000776
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000777 // Scan the instructions to check for unswitchable values.
Andrew Trick4104ed92012-04-10 05:14:37 +0000778 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000779 BBI != E; ++BBI)
780 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000781 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Xin Tong16b85a62017-02-27 18:00:13 +0000782 currentLoop, Changed).first;
Andrew Trick4104ed92012-04-10 05:14:37 +0000783 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson23a204d2009-07-31 17:39:07 +0000784 ConstantInt::getTrue(Context))) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000785 ++NumSelects;
786 return true;
787 }
788 }
789 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000790 return Changed;
791}
792
Sanjay Patel956e29c2015-08-11 21:24:04 +0000793/// Check to see if all paths from BB exit the loop with no side effects
794/// (including infinite loops).
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000795///
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000796/// If true, we return true and set ExitBB to the block we
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000797/// exit through.
798///
799static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
800 BasicBlock *&ExitBB,
801 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000802 if (!Visited.insert(BB).second) {
Nick Lewyckyd9d1de42011-12-23 23:49:25 +0000803 // Already visited. Without more analysis, this could indicate an infinite
804 // loop.
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000805 return false;
Jakub Staszak27da1232013-08-06 17:03:42 +0000806 }
807 if (!L->contains(BB)) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000808 // Otherwise, this is a loop exit, this is fine so long as this is the
809 // first exit.
Craig Topperf40110f2014-04-25 05:29:35 +0000810 if (ExitBB) return false;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000811 ExitBB = BB;
Edward O'Callaghan2b8fed12009-11-25 05:38:41 +0000812 return true;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000813 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000814
Chris Lattnerbaddba42006-02-17 06:39:56 +0000815 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000816 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000817 // Check to see if the successor is a trivial loop exit.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000818 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
Chris Lattnerbaddba42006-02-17 06:39:56 +0000819 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000820 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000821
822 // Okay, everything after this looks good, check to make sure that this block
823 // doesn't include any side effects.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000824 for (Instruction &I : *BB)
825 if (I.mayHaveSideEffects())
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000826 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000827
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000828 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000829}
830
Sanjay Patel956e29c2015-08-11 21:24:04 +0000831/// Return true if the specified block unconditionally leads to an exit from
832/// the specified loop, and has no side-effects in the process. If so, return
833/// the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000834static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
835 std::set<BasicBlock*> Visited;
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000836 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
Craig Topperf40110f2014-04-25 05:29:35 +0000837 BasicBlock *ExitBB = nullptr;
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000838 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
839 return ExitBB;
Craig Topperf40110f2014-04-25 05:29:35 +0000840 return nullptr;
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000841}
Chris Lattner6e263152006-02-10 02:30:37 +0000842
Sanjay Patel956e29c2015-08-11 21:24:04 +0000843/// We have found that we can unswitch currentLoop when LoopCond == Val to
844/// simplify the loop. If we decide that this is profitable,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000845/// unswitch the loop, reprocess the pieces, then return true.
Weiming Zhaof1abad52015-06-23 05:31:09 +0000846bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,
847 TerminatorInst *TI) {
Evan Chenged66db32010-04-03 02:23:43 +0000848 // Check to see if it would be profitable to unswitch current loop.
Mark Heffernan9b536a62015-06-23 18:26:50 +0000849 if (!BranchesInfo.CostAllowsUnswitching()) {
850 DEBUG(dbgs() << "NOT unswitching loop %"
851 << currentLoop->getHeader()->getName()
852 << " at non-trivial condition '" << *Val
853 << "' == " << *LoopCond << "\n"
854 << ". Cost too high.\n");
855 return false;
856 }
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000857 if (hasBranchDivergence &&
858 getAnalysis<DivergenceAnalysis>().isDivergent(LoopCond)) {
859 DEBUG(dbgs() << "NOT unswitching loop %"
860 << currentLoop->getHeader()->getName()
861 << " at non-trivial condition '" << *Val
862 << "' == " << *LoopCond << "\n"
863 << ". Condition is divergent.\n");
864 return false;
865 }
Evan Chenged66db32010-04-03 02:23:43 +0000866
Weiming Zhaof1abad52015-06-23 05:31:09 +0000867 UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
Andrew Trick4442bfe2012-04-10 05:14:42 +0000868 return true;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000869}
870
Sanjay Patel956e29c2015-08-11 21:24:04 +0000871/// Recursively clone the specified loop and all of its children,
Chris Lattnerf48f7772004-04-19 18:07:02 +0000872/// mapping the blocks with the specified map.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000873static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000874 LoopInfo *LI, LPPassManager *LPM) {
Chandler Carruth29c22d22017-05-25 03:01:31 +0000875 Loop &New = *new Loop();
876 if (PL)
877 PL->addChildLoop(&New);
878 else
879 LI->addTopLevelLoop(&New);
880 LPM->addLoop(New);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000881
882 // Add all of the blocks in L to the new loop.
883 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
884 I != E; ++I)
885 if (LI->getLoopFor(*I) == L)
Justin Bogner35e46cd2015-10-22 21:21:32 +0000886 New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000887
888 // Add all of the subloops to the new loop.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000889 for (Loop *I : *L)
890 CloneLoop(I, &New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000891
Justin Bogner35e46cd2015-10-22 21:21:32 +0000892 return &New;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000893}
894
Sanjay Patel956e29c2015-08-11 21:24:04 +0000895/// Emit a conditional branch on two values if LIC == Val, branch to TrueDst,
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000896/// otherwise branch to FalseDest. Insert the code immediately before OldBranch
897/// and remove (but not erase!) it from the function.
Devang Patel3304e462007-06-28 00:49:00 +0000898void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
899 BasicBlock *TrueDest,
900 BasicBlock *FalseDest,
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000901 BranchInst *OldBranch,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000902 TerminatorInst *TI) {
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000903 assert(OldBranch->isUnconditional() && "Preheader is not split correctly");
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000904 // Insert a conditional branch on LIC to the two preheaders. The original
905 // code is the true version and the new code is the false version.
906 Value *BranchVal = LIC;
Weiming Zhaof1abad52015-06-23 05:31:09 +0000907 bool Swapped = false;
Owen Anderson55f1c092009-08-13 21:58:54 +0000908 if (!isa<ConstantInt>(Val) ||
909 Val->getType() != Type::getInt1Ty(LIC->getContext()))
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000910 BranchVal = new ICmpInst(OldBranch, ICmpInst::ICMP_EQ, LIC, Val);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000911 else if (Val != ConstantInt::getTrue(Val->getContext())) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000912 // We want to enter the new loop when the condition is true.
913 std::swap(TrueDest, FalseDest);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000914 Swapped = true;
915 }
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000916
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000917 // Old branch will be removed, so save its parent and successor to update the
918 // DomTree.
919 auto *OldBranchSucc = OldBranch->getSuccessor(0);
920 auto *OldBranchParent = OldBranch->getParent();
921
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000922 // Insert the new branch.
Xinliang David Li7a28a7f2016-09-03 22:26:11 +0000923 BranchInst *BI =
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000924 IRBuilder<>(OldBranch).CreateCondBr(BranchVal, TrueDest, FalseDest, TI);
Xinliang David Li7a28a7f2016-09-03 22:26:11 +0000925 if (Swapped)
926 BI->swapProfMetadata();
Dan Gohman3ddbc242009-09-08 15:45:00 +0000927
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000928 // Remove the old branch so there is only one branch at the end. This is
929 // needed to perform DomTree's internal DFS walk on the function's CFG.
930 OldBranch->removeFromParent();
931
932 // Inform the DT about the new branch.
933 if (DT) {
934 // First, add both successors.
935 SmallVector<DominatorTree::UpdateType, 3> Updates;
936 if (TrueDest != OldBranchParent)
937 Updates.push_back({DominatorTree::Insert, OldBranchParent, TrueDest});
938 if (FalseDest != OldBranchParent)
939 Updates.push_back({DominatorTree::Insert, OldBranchParent, FalseDest});
940 // If both of the new successors are different from the old one, inform the
941 // DT that the edge was deleted.
942 if (OldBranchSucc != TrueDest && OldBranchSucc != FalseDest) {
943 Updates.push_back({DominatorTree::Delete, OldBranchParent, OldBranchSucc});
944 }
945
946 DT->applyUpdates(Updates);
947 }
948
Dan Gohman3ddbc242009-09-08 15:45:00 +0000949 // If either edge is critical, split it. This helps preserve LoopSimplify
950 // form for enclosing loops.
Chandler Carruthf8753fc2015-01-19 12:12:00 +0000951 auto Options = CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA();
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000952 SplitCriticalEdge(BI, 0, Options);
953 SplitCriticalEdge(BI, 1, Options);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000954}
955
Sanjay Patel956e29c2015-08-11 21:24:04 +0000956/// Given a loop that has a trivial unswitchable condition in it (a cond branch
957/// from its header block to its latch block, where the path through the loop
958/// that doesn't execute its body has no side-effects), unswitch it. This
959/// doesn't involve any code duplication, just moving the conditional branch
960/// outside of the loop and updating loop info.
Weiming Zhaof1abad52015-06-23 05:31:09 +0000961void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
962 BasicBlock *ExitBlock,
963 TerminatorInst *TI) {
David Greened9c355d2010-01-05 01:27:04 +0000964 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
Weiming Zhaof1abad52015-06-23 05:31:09 +0000965 << loopHeader->getName() << " [" << L->getBlocks().size()
966 << " blocks] in Function "
967 << L->getHeader()->getParent()->getName() << " on cond: " << *Val
968 << " == " << *Cond << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +0000969
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000970 // First step, split the preheader, so that we know that there is a safe place
Devang Patele149d4e2008-07-02 01:18:13 +0000971 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattnered7a67b2006-02-10 01:24:09 +0000972 // conditional branch on Cond.
Chandler Carruthd4500562015-01-19 12:36:53 +0000973 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000974
975 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000976 // to branch to: this is the exit block out of the loop that we should
977 // short-circuit to.
Andrew Trick4104ed92012-04-10 05:14:37 +0000978
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000979 // Split this block now, so that the loop maintains its exit block, and so
980 // that the jump from the preheader can execute the contents of the exit block
981 // without actually branching to it (the exit block should be dominated by the
982 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000983 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000984 BasicBlock *NewExit = SplitBlock(ExitBlock, &ExitBlock->front(), DT, LI);
Andrew Trick4104ed92012-04-10 05:14:37 +0000985
986 // Okay, now we have a position to branch from and a position to branch to,
Chris Lattnered7a67b2006-02-10 01:24:09 +0000987 // insert the new conditional branch.
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000988 auto *OldBranch = dyn_cast<BranchInst>(loopPreheader->getTerminator());
989 assert(OldBranch && "Failed to split the preheader");
990 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, OldBranch, TI);
991 LPM->deleteSimpleAnalysisValue(OldBranch, L);
992
993 // EmitPreheaderBranchOnCondition removed the OldBranch from the function.
994 // Delete it, as it is no longer needed.
995 delete OldBranch;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000996
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000997 // We need to reprocess this loop, it could be unswitched again.
Devang Patel7d165e12007-07-30 23:07:10 +0000998 redoLoop = true;
Andrew Trick4104ed92012-04-10 05:14:37 +0000999
Chris Lattnered7a67b2006-02-10 01:24:09 +00001000 // Now that we know that the loop is never entered when this condition is a
1001 // particular value, rewrite the loop with this info. We know that this will
1002 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001003 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +00001004 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +00001005}
1006
Sanjay Patel41f3d952015-08-11 21:11:56 +00001007/// Check if the first non-constant condition starting from the loop header is
1008/// a trivial unswitch condition: that is, a condition controls whether or not
1009/// the loop does anything at all. If it is a trivial condition, unswitching
1010/// produces no code duplications (equivalently, it produces a simpler loop and
1011/// a new empty loop, which gets deleted). Therefore always unswitch trivial
1012/// condition.
Chen Lic0f3a152015-07-22 05:26:29 +00001013bool LoopUnswitch::TryTrivialLoopUnswitch(bool &Changed) {
Chen Li145c2f52015-07-25 03:21:06 +00001014 BasicBlock *CurrentBB = currentLoop->getHeader();
1015 TerminatorInst *CurrentTerm = CurrentBB->getTerminator();
1016 LLVMContext &Context = CurrentBB->getContext();
Chen Lic0f3a152015-07-22 05:26:29 +00001017
Chen Li145c2f52015-07-25 03:21:06 +00001018 // If loop header has only one reachable successor (currently via an
1019 // unconditional branch or constant foldable conditional branch, but
1020 // should also consider adding constant foldable switch instruction in
1021 // future), we should keep looking for trivial condition candidates in
1022 // the successor as well. An alternative is to constant fold conditions
1023 // and merge successors into loop header (then we only need to check header's
1024 // terminator). The reason for not doing this in LoopUnswitch pass is that
1025 // it could potentially break LoopPassManager's invariants. Folding dead
1026 // branches could either eliminate the current loop or make other loops
Sanjay Patel41f3d952015-08-11 21:11:56 +00001027 // unreachable. LCSSA form might also not be preserved after deleting
1028 // branches. The following code keeps traversing loop header's successors
1029 // until it finds the trivial condition candidate (condition that is not a
1030 // constant). Since unswitching generates branches with constant conditions,
1031 // this scenario could be very common in practice.
Chen Li145c2f52015-07-25 03:21:06 +00001032 SmallSet<BasicBlock*, 8> Visited;
1033
1034 while (true) {
1035 // If we exit loop or reach a previous visited block, then
1036 // we can not reach any trivial condition candidates (unfoldable
1037 // branch instructions or switch instructions) and no unswitch
1038 // can happen. Exit and return false.
1039 if (!currentLoop->contains(CurrentBB) || !Visited.insert(CurrentBB).second)
Chen Lic0f3a152015-07-22 05:26:29 +00001040 return false;
1041
Chen Li145c2f52015-07-25 03:21:06 +00001042 // Check if this loop will execute any side-effecting instructions (e.g.
1043 // stores, calls, volatile loads) in the part of the loop that the code
1044 // *would* execute. Check the header first.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001045 for (Instruction &I : *CurrentBB)
1046 if (I.mayHaveSideEffects())
Chen Li145c2f52015-07-25 03:21:06 +00001047 return false;
1048
Chen Li145c2f52015-07-25 03:21:06 +00001049 if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1050 if (BI->isUnconditional()) {
1051 CurrentBB = BI->getSuccessor(0);
1052 } else if (BI->getCondition() == ConstantInt::getTrue(Context)) {
1053 CurrentBB = BI->getSuccessor(0);
1054 } else if (BI->getCondition() == ConstantInt::getFalse(Context)) {
1055 CurrentBB = BI->getSuccessor(1);
1056 } else {
Sanjay Patel41f3d952015-08-11 21:11:56 +00001057 // Found a trivial condition candidate: non-foldable conditional branch.
Chen Li145c2f52015-07-25 03:21:06 +00001058 break;
1059 }
Xin Tonge5f8d642017-01-27 01:42:20 +00001060 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1061 // At this point, any constant-foldable instructions should have probably
1062 // been folded.
1063 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
1064 if (!Cond)
1065 break;
1066 // Find the target block we are definitely going to.
Chandler Carruth927d8e62017-04-12 07:27:28 +00001067 CurrentBB = SI->findCaseValue(Cond)->getCaseSuccessor();
Karl-Johan Karlsson38cbf582017-02-14 07:31:36 +00001068 } else {
Xin Tonge5f8d642017-01-27 01:42:20 +00001069 // We do not understand these terminator instructions.
Chen Li145c2f52015-07-25 03:21:06 +00001070 break;
1071 }
1072
1073 CurrentTerm = CurrentBB->getTerminator();
1074 }
1075
Chen Lic0f3a152015-07-22 05:26:29 +00001076 // CondVal is the condition that controls the trivial condition.
1077 // LoopExitBB is the BasicBlock that loop exits when meets trivial condition.
1078 Constant *CondVal = nullptr;
1079 BasicBlock *LoopExitBB = nullptr;
1080
Chen Li145c2f52015-07-25 03:21:06 +00001081 if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
Chen Lic0f3a152015-07-22 05:26:29 +00001082 // If this isn't branching on an invariant condition, we can't unswitch it.
1083 if (!BI->isConditional())
1084 return false;
1085
1086 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
Xin Tong16b85a62017-02-27 18:00:13 +00001087 currentLoop, Changed).first;
Chen Lic0f3a152015-07-22 05:26:29 +00001088
1089 // Unswitch only if the trivial condition itself is an LIV (not
1090 // partial LIV which could occur in and/or)
1091 if (!LoopCond || LoopCond != BI->getCondition())
1092 return false;
1093
1094 // Check to see if a successor of the branch is guaranteed to
1095 // exit through a unique exit block without having any
1096 // side-effects. If so, determine the value of Cond that causes
1097 // it to do this.
1098 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
1099 BI->getSuccessor(0)))) {
1100 CondVal = ConstantInt::getTrue(Context);
1101 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
1102 BI->getSuccessor(1)))) {
1103 CondVal = ConstantInt::getFalse(Context);
1104 }
1105
Sanjay Patel41f3d952015-08-11 21:11:56 +00001106 // If we didn't find a single unique LoopExit block, or if the loop exit
1107 // block contains phi nodes, this isn't trivial.
Chen Lic0f3a152015-07-22 05:26:29 +00001108 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
1109 return false; // Can't handle this.
1110
Wei Mifc0e2452017-07-25 23:37:17 +00001111 if (EqualityPropUnSafe(*LoopCond))
1112 return false;
1113
Sanjay Patel41f3d952015-08-11 21:11:56 +00001114 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1115 CurrentTerm);
Chen Lic0f3a152015-07-22 05:26:29 +00001116 ++NumBranches;
1117 return true;
Chen Li145c2f52015-07-25 03:21:06 +00001118 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
Chen Lic0f3a152015-07-22 05:26:29 +00001119 // If this isn't switching on an invariant condition, we can't unswitch it.
1120 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Xin Tong16b85a62017-02-27 18:00:13 +00001121 currentLoop, Changed).first;
Chen Lic0f3a152015-07-22 05:26:29 +00001122
1123 // Unswitch only if the trivial condition itself is an LIV (not
1124 // partial LIV which could occur in and/or)
1125 if (!LoopCond || LoopCond != SI->getCondition())
1126 return false;
1127
1128 // Check to see if a successor of the switch is guaranteed to go to the
1129 // latch block or exit through a one exit block without having any
1130 // side-effects. If so, determine the value of Cond that causes it to do
1131 // this.
1132 // Note that we can't trivially unswitch on the default case or
1133 // on already unswitched cases.
Chandler Carruth927d8e62017-04-12 07:27:28 +00001134 for (auto Case : SI->cases()) {
Chen Lic0f3a152015-07-22 05:26:29 +00001135 BasicBlock *LoopExitCandidate;
Chandler Carruth927d8e62017-04-12 07:27:28 +00001136 if ((LoopExitCandidate =
1137 isTrivialLoopExitBlock(currentLoop, Case.getCaseSuccessor()))) {
Chen Lic0f3a152015-07-22 05:26:29 +00001138 // Okay, we found a trivial case, remember the value that is trivial.
Chandler Carruth927d8e62017-04-12 07:27:28 +00001139 ConstantInt *CaseVal = Case.getCaseValue();
Chen Lic0f3a152015-07-22 05:26:29 +00001140
1141 // Check that it was not unswitched before, since already unswitched
1142 // trivial vals are looks trivial too.
1143 if (BranchesInfo.isUnswitched(SI, CaseVal))
1144 continue;
1145 LoopExitBB = LoopExitCandidate;
1146 CondVal = CaseVal;
1147 break;
1148 }
1149 }
1150
Sanjay Patel41f3d952015-08-11 21:11:56 +00001151 // If we didn't find a single unique LoopExit block, or if the loop exit
1152 // block contains phi nodes, this isn't trivial.
Chen Lic0f3a152015-07-22 05:26:29 +00001153 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
1154 return false; // Can't handle this.
1155
Sanjay Patel41f3d952015-08-11 21:11:56 +00001156 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1157 nullptr);
Xin Tong16b85a62017-02-27 18:00:13 +00001158
1159 // We are only unswitching full LIV.
1160 BranchesInfo.setUnswitched(SI, CondVal);
Chen Lic0f3a152015-07-22 05:26:29 +00001161 ++NumSwitches;
1162 return true;
1163 }
1164 return false;
1165}
1166
Sanjay Patel956e29c2015-08-11 21:24:04 +00001167/// Split all of the edges from inside the loop to their exit blocks.
1168/// Update the appropriate Phi nodes as we do so.
Andrew Trick4104ed92012-04-10 05:14:37 +00001169void LoopUnswitch::SplitExitEdges(Loop *L,
Craig Topperb94011f2013-07-14 04:42:23 +00001170 const SmallVectorImpl<BasicBlock *> &ExitBlocks){
Devang Patela69f9872007-10-05 22:29:34 +00001171
Chris Lattnered7a67b2006-02-10 01:24:09 +00001172 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +00001173 BasicBlock *ExitBlock = ExitBlocks[i];
Dan Gohman3ddbc242009-09-08 15:45:00 +00001174 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
1175 pred_end(ExitBlock));
Bill Wendling90f90da2011-09-27 00:59:31 +00001176
Nick Lewycky61158242011-06-03 06:27:15 +00001177 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
1178 // general, if we call it on all predecessors of all exits then it does.
Chandler Carruth96ada252015-07-22 09:52:54 +00001179 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", DT, LI,
Philip Reames9198b332015-01-28 23:06:47 +00001180 /*PreserveLCSSA*/ true);
Chris Lattnered7a67b2006-02-10 01:24:09 +00001181 }
Devang Patele192e3252007-10-03 21:16:08 +00001182}
1183
Sanjay Patel956e29c2015-08-11 21:24:04 +00001184/// We determined that the loop is profitable to unswitch when LIC equal Val.
1185/// Split it into loop versions and test the condition outside of either loop.
1186/// Return the loops created as Out1/Out2.
Andrew Trick4442bfe2012-04-10 05:14:42 +00001187void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
Weiming Zhaof1abad52015-06-23 05:31:09 +00001188 Loop *L, TerminatorInst *TI) {
Devang Patele149d4e2008-07-02 01:18:13 +00001189 Function *F = loopHeader->getParent();
David Greened9c355d2010-01-05 01:27:04 +00001190 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001191 << loopHeader->getName() << " [" << L->getBlocks().size()
1192 << " blocks] in Function " << F->getName()
1193 << " when '" << *Val << "' == " << *LIC << "\n");
Devang Patele192e3252007-10-03 21:16:08 +00001194
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001195 if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1196 SEWP->getSE().forgetLoop(L);
Cameron Zwarich99de19b2011-02-11 06:08:28 +00001197
Devang Pateled50fb52008-07-02 01:44:29 +00001198 LoopBlocks.clear();
1199 NewBlocks.clear();
Devang Patele192e3252007-10-03 21:16:08 +00001200
1201 // First step, split the preheader and exit blocks, and add these blocks to
1202 // the LoopBlocks list.
Chandler Carruthd4500562015-01-19 12:36:53 +00001203 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, DT, LI);
Devang Patele192e3252007-10-03 21:16:08 +00001204 LoopBlocks.push_back(NewPreheader);
1205
1206 // We want the loop to come after the preheader, but before the exit blocks.
1207 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
1208
1209 SmallVector<BasicBlock*, 8> ExitBlocks;
1210 L->getUniqueExitBlocks(ExitBlocks);
1211
1212 // Split all of the edges from inside the loop to their exit blocks. Update
1213 // the appropriate Phi nodes as we do so.
Devang Pateleb611dd2008-07-03 17:37:52 +00001214 SplitExitEdges(L, ExitBlocks);
Devang Patele192e3252007-10-03 21:16:08 +00001215
Chris Lattnerfe4151e2006-02-10 23:16:39 +00001216 // The exit blocks may have been changed due to edge splitting, recompute.
1217 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +00001218 L->getUniqueExitBlocks(ExitBlocks);
1219
Chris Lattnerfe4151e2006-02-10 23:16:39 +00001220 // Add exit blocks to the loop blocks.
1221 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +00001222
1223 // Next step, clone all of the basic blocks that make up the loop (including
1224 // the loop preheader and exit blocks), keeping track of the mapping between
1225 // the instructions and blocks.
Chris Lattnerf48f7772004-04-19 18:07:02 +00001226 NewBlocks.reserve(LoopBlocks.size());
Rafael Espindola229e38f2010-10-13 01:36:30 +00001227 ValueToValueMapTy VMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +00001228 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001229 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
Andrew Trick4104ed92012-04-10 05:14:37 +00001230
Evan Chengba930442010-04-05 21:16:25 +00001231 NewBlocks.push_back(NewBB);
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001232 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
Evan Chengba930442010-04-05 21:16:25 +00001233 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
Chris Lattnerf48f7772004-04-19 18:07:02 +00001234 }
1235
1236 // Splice the newly inserted blocks into the function right before the
1237 // original preheader.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001238 F->getBasicBlockList().splice(NewPreheader->getIterator(),
1239 F->getBasicBlockList(),
1240 NewBlocks[0]->getIterator(), F->end());
Chris Lattnerf48f7772004-04-19 18:07:02 +00001241
1242 // Now we create the new Loop object for the versioned loop.
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001243 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +00001244
1245 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
1246 // Probably clone more loop-unswitch related loop properties.
1247 BranchesInfo.cloneData(NewLoop, L, VMap);
1248
Chris Lattnerf1b15162006-02-10 23:26:14 +00001249 Loop *ParentLoop = L->getParentLoop();
1250 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +00001251 // Make sure to add the cloned preheader and exit blocks to the parent loop
1252 // as well.
Chandler Carruth691addc2015-01-18 01:25:51 +00001253 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +00001254 }
Bill Wendling90f90da2011-09-27 00:59:31 +00001255
Chris Lattnerf1b15162006-02-10 23:26:14 +00001256 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001257 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +00001258 // The new exit block should be in the same loop as the old one.
1259 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Chandler Carruth691addc2015-01-18 01:25:51 +00001260 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Andrew Trick4104ed92012-04-10 05:14:37 +00001261
Chris Lattnerf1b15162006-02-10 23:26:14 +00001262 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
1263 "Exit block should have been split to have one successor!");
1264 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
Devang Pateleb611dd2008-07-03 17:37:52 +00001265
Chris Lattnerf1b15162006-02-10 23:26:14 +00001266 // If the successor of the exit block had PHI nodes, add an entry for
1267 // NewExit.
Jakub Staszak27da1232013-08-06 17:03:42 +00001268 for (BasicBlock::iterator I = ExitSucc->begin();
1269 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnerf1b15162006-02-10 23:26:14 +00001270 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Rafael Espindola229e38f2010-10-13 01:36:30 +00001271 ValueToValueMapTy::iterator It = VMap.find(V);
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001272 if (It != VMap.end()) V = It->second;
Chris Lattnerf1b15162006-02-10 23:26:14 +00001273 PN->addIncoming(V, NewExit);
1274 }
Bill Wendling90f90da2011-09-27 00:59:31 +00001275
1276 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
Jakub Staszak27da1232013-08-06 17:03:42 +00001277 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001278 &*ExitSucc->getFirstInsertionPt());
Bill Wendling90f90da2011-09-27 00:59:31 +00001279
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001280 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
1281 I != E; ++I) {
1282 BasicBlock *BB = *I;
Bill Wendling90f90da2011-09-27 00:59:31 +00001283 LandingPadInst *LPI = BB->getLandingPadInst();
1284 LPI->replaceAllUsesWith(PN);
1285 PN->addIncoming(LPI, BB);
1286 }
1287 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001288 }
1289
1290 // Rewrite the code to refer to itself.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001291 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
1292 for (Instruction &I : *NewBlocks[i]) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001293 RemapInstruction(&I, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00001294 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001295 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1296 if (II->getIntrinsicID() == Intrinsic::assume)
1297 AC->registerAssumption(II);
1298 }
1299 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001300
Chris Lattnerf48f7772004-04-19 18:07:02 +00001301 // Rewrite the original preheader to select between versions of the loop.
Devang Patele149d4e2008-07-02 01:18:13 +00001302 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerb0cbe712006-02-15 00:07:43 +00001303 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +00001304 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +00001305
Chris Lattnerb0cbe712006-02-15 00:07:43 +00001306 // Emit the new branch that selects between the two versions of this loop.
Weiming Zhaof1abad52015-06-23 05:31:09 +00001307 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
1308 TI);
Devang Pateld4911982007-07-31 08:03:26 +00001309 LPM->deleteSimpleAnalysisValue(OldBR, L);
Jakub Kuderskie35a4492017-08-17 16:45:35 +00001310
1311 // The OldBr was replaced by a new one and removed (but not erased) by
1312 // EmitPreheaderBranchOnCondition. It is no longer needed, so delete it.
1313 delete OldBR;
Devang Patela8823282007-08-02 15:25:57 +00001314
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001315 LoopProcessWorklist.push_back(NewLoop);
Devang Patel7d165e12007-07-30 23:07:10 +00001316 redoLoop = true;
Chris Lattnerf48f7772004-04-19 18:07:02 +00001317
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001318 // Keep a WeakTrackingVH holding onto LIC. If the first call to
1319 // RewriteLoopBody
Sanjoy Das2cbeb002017-04-26 16:37:05 +00001320 // deletes the instruction (for example by simplifying a PHI that feeds into
1321 // the condition that we're unswitching on), we don't rewrite the second
1322 // iteration.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001323 WeakTrackingVH LICHandle(LIC);
Andrew Trick4104ed92012-04-10 05:14:37 +00001324
Chris Lattnerf48f7772004-04-19 18:07:02 +00001325 // Now we rewrite the original code to know that the condition is true and the
1326 // new code to know that the condition is false.
Evan Chengba930442010-04-05 21:16:25 +00001327 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
Devang Pateleb611dd2008-07-03 17:37:52 +00001328
Chris Lattner5814d9d92010-04-20 05:09:16 +00001329 // It's possible that simplifying one loop could cause the other to be
1330 // changed to another value or a constant. If its a constant, don't simplify
1331 // it.
1332 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1333 LICHandle && !isa<Constant>(LICHandle))
1334 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +00001335}
1336
Sanjay Patel956e29c2015-08-11 21:24:04 +00001337/// Remove all instances of I from the worklist vector specified.
Andrew Trick4104ed92012-04-10 05:14:37 +00001338static void RemoveFromWorklist(Instruction *I,
Chris Lattner6fd13622006-02-17 00:31:07 +00001339 std::vector<Instruction*> &Worklist) {
Jakub Staszak8f46e912012-10-16 19:52:32 +00001340
1341 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
1342 Worklist.end());
Chris Lattner6fd13622006-02-17 00:31:07 +00001343}
1344
Sanjay Patel956e29c2015-08-11 21:24:04 +00001345/// When we find that I really equals V, remove I from the
Chris Lattner6fd13622006-02-17 00:31:07 +00001346/// program, replacing all uses with V and update the worklist.
Andrew Trick4104ed92012-04-10 05:14:37 +00001347static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Pateld4911982007-07-31 08:03:26 +00001348 std::vector<Instruction*> &Worklist,
1349 Loop *L, LPPassManager *LPM) {
Davide Italianoe27cb872017-04-28 21:30:50 +00001350 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I << "\n");
Chris Lattner6fd13622006-02-17 00:31:07 +00001351
1352 // Add uses to the worklist, which may be dead now.
1353 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1354 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1355 Worklist.push_back(Use);
1356
1357 // Add users to the worklist which may be simplified now.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001358 for (User *U : I->users())
1359 Worklist.push_back(cast<Instruction>(U));
Devang Pateld4911982007-07-31 08:03:26 +00001360 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001361 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +00001362 I->replaceAllUsesWith(V);
Davide Italiano534e3142017-04-29 00:12:18 +00001363 if (!I->mayHaveSideEffects())
1364 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001365 ++NumSimplify;
1366}
1367
Sanjay Patel956e29c2015-08-11 21:24:04 +00001368/// We know either that the value LIC has the value specified by Val in the
1369/// specified loop, or we know it does NOT have that value.
1370/// Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +00001371void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +00001372 Constant *Val,
1373 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +00001374 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Andrew Trick4104ed92012-04-10 05:14:37 +00001375
Chris Lattnerf48f7772004-04-19 18:07:02 +00001376 // FIXME: Support correlated properties, like:
1377 // for (...)
1378 // if (li1 < li2)
1379 // ...
1380 // if (li1 > li2)
1381 // ...
Andrew Trick4104ed92012-04-10 05:14:37 +00001382
Chris Lattner6e263152006-02-10 02:30:37 +00001383 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1384 // selects, switches.
Chris Lattner6fd13622006-02-17 00:31:07 +00001385 std::vector<Instruction*> Worklist;
Owen Anderson47db9412009-07-22 00:24:57 +00001386 LLVMContext &Context = Val->getContext();
1387
Chris Lattner6fd13622006-02-17 00:31:07 +00001388 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1389 // in the loop with the appropriate one directly.
Owen Anderson55f1c092009-08-13 21:58:54 +00001390 if (IsEqual || (isa<ConstantInt>(Val) &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001391 Val->getType()->isIntegerTy(1))) {
Chris Lattner8a5a3242006-02-22 06:37:14 +00001392 Value *Replacement;
1393 if (IsEqual)
1394 Replacement = Val;
1395 else
Andrew Trick4104ed92012-04-10 05:14:37 +00001396 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
Reid Spencercddc9df2007-01-12 04:24:46 +00001397 !cast<ConstantInt>(Val)->getZExtValue());
Andrew Trick4104ed92012-04-10 05:14:37 +00001398
Chandler Carruthcdf47882014-03-09 03:16:01 +00001399 for (User *U : LIC->users()) {
1400 Instruction *UI = dyn_cast<Instruction>(U);
1401 if (!UI || !L->contains(UI))
Evan Cheng1b55f562011-05-24 23:12:57 +00001402 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001403 Worklist.push_back(UI);
Evan Cheng1b55f562011-05-24 23:12:57 +00001404 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001405
Benjamin Kramer135f7352016-06-26 12:28:59 +00001406 for (Instruction *UI : Worklist)
1407 UI->replaceUsesOfWith(LIC, Replacement);
Andrew Trick4104ed92012-04-10 05:14:37 +00001408
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001409 SimplifyCode(Worklist, L);
1410 return;
1411 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001412
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001413 // Otherwise, we don't know the precise value of LIC, but we do know that it
1414 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1415 // can. This case occurs when we unswitch switch statements.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001416 for (User *U : LIC->users()) {
1417 Instruction *UI = dyn_cast<Instruction>(U);
1418 if (!UI || !L->contains(UI))
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001419 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001420
Xin Tongec6f90b2017-02-23 23:42:19 +00001421 // At this point, we know LIC is definitely not Val. Try to use some simple
1422 // logic to simplify the user w.r.t. to the context.
1423 if (Value *Replacement = SimplifyInstructionWithNotEqual(UI, LIC, Val)) {
1424 if (LI->replacementPreservesLCSSAForm(UI, Replacement)) {
1425 // This in-loop instruction has been simplified w.r.t. its context,
1426 // i.e. LIC != Val, make sure we propagate its replacement value to
1427 // all its users.
Xin Tongf51d8042017-02-24 01:43:36 +00001428 //
1429 // We can not yet delete UI, the LIC user, yet, because that would invalidate
1430 // the LIC->users() iterator !. However, we can make this instruction
1431 // dead by replacing all its users and push it onto the worklist so that
1432 // it can be properly deleted and its operands simplified.
1433 UI->replaceAllUsesWith(Replacement);
Xin Tongec6f90b2017-02-23 23:42:19 +00001434 }
1435 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001436
Xin Tong01feb292017-02-28 03:32:41 +00001437 // This is a LIC user, push it into the worklist so that SimplifyCode can
1438 // attempt to simplify it.
Xin Tongec6f90b2017-02-23 23:42:19 +00001439 Worklist.push_back(UI);
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001440
1441 // If we know that LIC is not Val, use this info to simplify code.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001442 SwitchInst *SI = dyn_cast<SwitchInst>(UI);
Craig Topperf40110f2014-04-25 05:29:35 +00001443 if (!SI || !isa<ConstantInt>(Val)) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001444
Xin Tong16b85a62017-02-27 18:00:13 +00001445 // NOTE: if a case value for the switch is unswitched out, we record it
1446 // after the unswitch finishes. We can not record it here as the switch
1447 // is not a direct user of the partial LIV.
Chandler Carruth927d8e62017-04-12 07:27:28 +00001448 SwitchInst::CaseHandle DeadCase =
1449 *SI->findCaseValue(cast<ConstantInt>(Val));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00001450 // Default case is live for multiple values.
Chandler Carruth927d8e62017-04-12 07:27:28 +00001451 if (DeadCase == *SI->case_default())
1452 continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001453
1454 // Found a dead case value. Don't remove PHI nodes in the
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001455 // successor if they become single-entry, those PHI nodes may
1456 // be in the Users list.
Nick Lewycky61158242011-06-03 06:27:15 +00001457
Evan Cheng1b55f562011-05-24 23:12:57 +00001458 BasicBlock *Switch = SI->getParent();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001459 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
Evan Cheng1b55f562011-05-24 23:12:57 +00001460 BasicBlock *Latch = L->getLoopLatch();
Andrew Trick4104ed92012-04-10 05:14:37 +00001461
Nick Lewycky61158242011-06-03 06:27:15 +00001462 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
Evan Cheng9605a692011-05-25 18:17:13 +00001463 // If the DeadCase successor dominates the loop latch, then the
1464 // transformation isn't safe since it will delete the sole predecessor edge
1465 // to the latch.
1466 if (Latch && DT->dominates(SISucc, Latch))
1467 continue;
Evan Cheng1b55f562011-05-24 23:12:57 +00001468
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001469 // FIXME: This is a hack. We need to keep the successor around
1470 // and hooked up so as to preserve the loop structure, because
1471 // trying to update it is complicated. So instead we preserve the
1472 // loop structure and put the block on a dead code path.
Chandler Carruthd4500562015-01-19 12:36:53 +00001473 SplitEdge(Switch, SISucc, DT, LI);
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001474 // Compute the successors instead of relying on the return value
1475 // of SplitEdge, since it may have split the switch successor
1476 // after PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001477 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001478 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1479 // Create an "unreachable" destination.
1480 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1481 Switch->getParent(),
1482 OldSISucc);
1483 new UnreachableInst(Context, Abort);
1484 // Force the new case destination to branch to the "unreachable"
1485 // block while maintaining a (dead) CFG edge to the old block.
1486 NewSISucc->getTerminator()->eraseFromParent();
1487 BranchInst::Create(Abort, OldSISucc,
1488 ConstantInt::getTrue(Context), NewSISucc);
1489 // Release the PHI operands for this edge.
1490 for (BasicBlock::iterator II = NewSISucc->begin();
1491 PHINode *PN = dyn_cast<PHINode>(II); ++II)
1492 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1493 UndefValue::get(PN->getType()));
1494 // Tell the domtree about the new block. We don't fully update the
1495 // domtree here -- instead we force it to do a full recomputation
1496 // after the pass is complete -- but we do need to inform it of
1497 // new blocks.
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +00001498 DT->addNewBlock(Abort, NewSISucc);
Chris Lattner6fd13622006-02-17 00:31:07 +00001499 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001500
Devang Pateld4911982007-07-31 08:03:26 +00001501 SimplifyCode(Worklist, L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001502}
1503
Sanjay Patel956e29c2015-08-11 21:24:04 +00001504/// Now that we have simplified some instructions in the loop, walk over it and
1505/// constant prop, dce, and fold control flow where possible. Note that this is
1506/// effectively a very simple loop-structure-aware optimizer. During processing
1507/// of this loop, L could very well be deleted, so it must not be used.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001508///
1509/// FIXME: When the loop optimizer is more mature, separate this out to a new
1510/// pass.
1511///
Devang Pateld4911982007-07-31 08:03:26 +00001512void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001513 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Chris Lattner6fd13622006-02-17 00:31:07 +00001514 while (!Worklist.empty()) {
1515 Instruction *I = Worklist.back();
1516 Worklist.pop_back();
Duncan Sandsbb2cd022010-11-23 20:24:21 +00001517
Chris Lattner6fd13622006-02-17 00:31:07 +00001518 // Simple DCE.
1519 if (isInstructionTriviallyDead(I)) {
Davide Italiano0aaa96a2017-04-29 00:18:26 +00001520 DEBUG(dbgs() << "Remove dead instruction '" << *I << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +00001521
Chris Lattner6fd13622006-02-17 00:31:07 +00001522 // Add uses to the worklist, which may be dead now.
1523 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1524 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1525 Worklist.push_back(Use);
Devang Pateld4911982007-07-31 08:03:26 +00001526 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001527 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +00001528 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001529 ++NumSimplify;
1530 continue;
1531 }
Duncan Sandsaef146b2010-11-18 19:59:41 +00001532
Chris Lattner66e809a2010-04-20 05:33:18 +00001533 // See if instruction simplification can hack this up. This is common for
1534 // things like "select false, X, Y" after unswitching made the condition be
Peter Collingbourne9a03c732012-05-20 01:32:09 +00001535 // 'false'. TODO: update the domtree properly so we can pass it here.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001536 if (Value *V = SimplifyInstruction(I, DL))
Duncan Sandsaef146b2010-11-18 19:59:41 +00001537 if (LI->replacementPreservesLCSSAForm(I, V)) {
1538 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1539 continue;
1540 }
1541
Chris Lattner6fd13622006-02-17 00:31:07 +00001542 // Special case hacks that appear commonly in unswitched code.
Chris Lattner66e809a2010-04-20 05:33:18 +00001543 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001544 if (BI->isUnconditional()) {
1545 // If BI's parent is the only pred of the successor, fold the two blocks
1546 // together.
1547 BasicBlock *Pred = BI->getParent();
1548 BasicBlock *Succ = BI->getSuccessor(0);
1549 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1550 if (!SinglePred) continue; // Nothing to do.
1551 assert(SinglePred == Pred && "CFG broken");
1552
Andrew Trick4104ed92012-04-10 05:14:37 +00001553 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001554 << Succ->getName() << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +00001555
Chris Lattner6fd13622006-02-17 00:31:07 +00001556 // Resolve any single entry PHI nodes in Succ.
1557 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Pateld4911982007-07-31 08:03:26 +00001558 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Andrew Trick4104ed92012-04-10 05:14:37 +00001559
Jay Foad61ea0e42011-06-23 09:09:15 +00001560 // If Succ has any successors with PHI nodes, update them to have
1561 // entries coming from Pred instead of Succ.
1562 Succ->replaceAllUsesWith(Pred);
Andrew Trick4104ed92012-04-10 05:14:37 +00001563
Chris Lattner6fd13622006-02-17 00:31:07 +00001564 // Move all of the successor contents from Succ to Pred.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001565 Pred->getInstList().splice(BI->getIterator(), Succ->getInstList(),
1566 Succ->begin(), Succ->end());
Devang Pateld4911982007-07-31 08:03:26 +00001567 LPM->deleteSimpleAnalysisValue(BI, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001568 RemoveFromWorklist(BI, Worklist);
Xin Tong3caaa362017-01-06 21:49:08 +00001569 BI->eraseFromParent();
Andrew Trick4104ed92012-04-10 05:14:37 +00001570
Chris Lattner6fd13622006-02-17 00:31:07 +00001571 // Remove Succ from the loop tree.
1572 LI->removeBlock(Succ);
Devang Pateld4911982007-07-31 08:03:26 +00001573 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001574 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001575 ++NumSimplify;
Chris Lattner66e809a2010-04-20 05:33:18 +00001576 continue;
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001577 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001578
Chris Lattner66e809a2010-04-20 05:33:18 +00001579 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001580 }
1581 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001582}
Xin Tongec6f90b2017-02-23 23:42:19 +00001583
1584/// Simple simplifications we can do given the information that Cond is
1585/// definitely not equal to Val.
1586Value *LoopUnswitch::SimplifyInstructionWithNotEqual(Instruction *Inst,
1587 Value *Invariant,
1588 Constant *Val) {
1589 // icmp eq cond, val -> false
1590 ICmpInst *CI = dyn_cast<ICmpInst>(Inst);
1591 if (CI && CI->isEquality()) {
1592 Value *Op0 = CI->getOperand(0);
1593 Value *Op1 = CI->getOperand(1);
1594 if ((Op0 == Invariant && Op1 == Val) || (Op0 == Val && Op1 == Invariant)) {
1595 LLVMContext &Ctx = Inst->getContext();
1596 if (CI->getPredicate() == CmpInst::ICMP_EQ)
1597 return ConstantInt::getFalse(Ctx);
1598 else
1599 return ConstantInt::getTrue(Ctx);
1600 }
1601 }
1602
1603 // FIXME: there may be other opportunities, e.g. comparison with floating
1604 // point, or Invariant - Val != 0, etc.
1605 return nullptr;
1606}