blob: 6d99caf1dff8bd87628fac41ef98f0bc7499c333 [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
11// to have multiple loops. For example, it turns the left into the right code:
12//
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
Chris Lattnerf48f7772004-04-19 18:07:02 +000029#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/Statistic.h"
James Molloyefbba722015-09-10 10:22:12 +000033#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000034#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Analysis/CodeMetrics.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Analysis/InstructionSimplify.h"
37#include "llvm/Analysis/LoopInfo.h"
38#include "llvm/Analysis/LoopPass.h"
39#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000040#include "llvm/Analysis/TargetTransformInfo.h"
Chen Li9f27fc02015-09-29 05:03:32 +000041#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
42#include "llvm/Analysis/BlockFrequencyInfo.h"
43#include "llvm/Analysis/BranchProbabilityInfo.h"
44#include "llvm/Support/BranchProbability.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000045#include "llvm/IR/Constants.h"
46#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000047#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/Function.h"
49#include "llvm/IR/Instructions.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000050#include "llvm/IR/Module.h"
Weiming Zhaof1abad52015-06-23 05:31:09 +000051#include "llvm/IR/MDBuilder.h"
Chris Lattner89762192006-02-09 20:15:48 +000052#include "llvm/Support/CommandLine.h"
Reid Spencer557ab152007-02-05 23:32:05 +000053#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000054#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000055#include "llvm/Transforms/Utils/BasicBlockUtils.h"
56#include "llvm/Transforms/Utils/Cloning.h"
57#include "llvm/Transforms/Utils/Local.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000058#include <algorithm>
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000059#include <map>
Chris Lattner2826e052006-02-09 19:14:52 +000060#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000061using namespace llvm;
62
Chandler Carruth964daaa2014-04-22 02:55:47 +000063#define DEBUG_TYPE "loop-unswitch"
64
Chris Lattner79a42ac2006-12-19 21:40:18 +000065STATISTIC(NumBranches, "Number of branches unswitched");
66STATISTIC(NumSwitches, "Number of switches unswitched");
67STATISTIC(NumSelects , "Number of selects unswitched");
68STATISTIC(NumTrivial , "Number of unswitches that are trivial");
69STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000070STATISTIC(TotalInsts, "Total number of instructions analyzed");
Chris Lattner79a42ac2006-12-19 21:40:18 +000071
Stepan Dyatkovskiy2931a592012-01-16 20:48:04 +000072// The specific value of 100 here was chosen based only on intuition and a
Dan Gohman71ca6522009-10-13 17:50:43 +000073// few specific examples.
Dan Gohmand78c4002008-05-13 00:00:25 +000074static cl::opt<unsigned>
75Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000076 cl::init(100), cl::Hidden);
Andrew Trick4104ed92012-04-10 05:14:37 +000077
Chen Li9f27fc02015-09-29 05:03:32 +000078static cl::opt<bool>
79LoopUnswitchWithBlockFrequency("loop-unswitch-with-block-frequency",
80 cl::init(false), cl::Hidden,
81 cl::desc("Enable the use of the block frequency analysis to access PGO "
82 "heuristics to minimize code growth in cold regions."));
83
84static cl::opt<unsigned>
85ColdnessThreshold("loop-unswitch-coldness-threshold", cl::init(1), cl::Hidden,
86 cl::desc("Coldness threshold in percentage. The loop header frequency "
87 "(relative to the entry frequency) is compared with this "
88 "threshold to determine if non-trivial unswitching should be "
89 "enabled."));
90
Dan Gohmand78c4002008-05-13 00:00:25 +000091namespace {
Andrew Trick4104ed92012-04-10 05:14:37 +000092
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000093 class LUAnalysisCache {
94
95 typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
96 UnswitchedValsMap;
Andrew Trick4104ed92012-04-10 05:14:37 +000097
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000098 typedef UnswitchedValsMap::iterator UnswitchedValsIt;
Andrew Trick4104ed92012-04-10 05:14:37 +000099
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000100 struct LoopProperties {
101 unsigned CanBeUnswitchedCount;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000102 unsigned WasUnswitchedCount;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000103 unsigned SizeEstimation;
104 UnswitchedValsMap UnswitchedVals;
105 };
Andrew Trick4104ed92012-04-10 05:14:37 +0000106
107 // Here we use std::map instead of DenseMap, since we need to keep valid
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000108 // LoopProperties pointer for current loop for better performance.
109 typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
110 typedef LoopPropsMap::iterator LoopPropsMapIt;
Andrew Trick4104ed92012-04-10 05:14:37 +0000111
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000112 LoopPropsMap LoopsProperties;
Jakub Staszak27da1232013-08-06 17:03:42 +0000113 UnswitchedValsMap *CurLoopInstructions;
114 LoopProperties *CurrentLoopProperties;
Andrew Trick4104ed92012-04-10 05:14:37 +0000115
Mark Heffernan9b536a62015-06-23 18:26:50 +0000116 // A loop unswitching with an estimated cost above this threshold
117 // is not performed. MaxSize is turned into unswitching quota for
118 // the current loop, and reduced correspondingly, though note that
119 // the quota is returned by releaseMemory() when the loop has been
120 // processed, so that MaxSize will return to its previous
121 // value. So in most cases MaxSize will equal the Threshold flag
122 // when a new loop is processed. An exception to that is that
123 // MaxSize will have a smaller value while processing nested loops
124 // that were introduced due to loop unswitching of an outer loop.
125 //
126 // FIXME: The way that MaxSize works is subtle and depends on the
127 // pass manager processing loops and calling releaseMemory() in a
128 // specific order. It would be good to find a more straightforward
129 // way of doing what MaxSize does.
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000130 unsigned MaxSize;
Andrew Trick4104ed92012-04-10 05:14:37 +0000131
Mark Heffernan9b536a62015-06-23 18:26:50 +0000132 public:
133 LUAnalysisCache()
134 : CurLoopInstructions(nullptr), CurrentLoopProperties(nullptr),
135 MaxSize(Threshold) {}
Andrew Trick4104ed92012-04-10 05:14:37 +0000136
Mark Heffernan9b536a62015-06-23 18:26:50 +0000137 // Analyze loop. Check its size, calculate is it possible to unswitch
138 // it. Returns true if we can unswitch this loop.
139 bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
140 AssumptionCache *AC);
Andrew Trick4104ed92012-04-10 05:14:37 +0000141
Mark Heffernan9b536a62015-06-23 18:26:50 +0000142 // Clean all data related to given loop.
143 void forgetLoop(const Loop *L);
Andrew Trick4104ed92012-04-10 05:14:37 +0000144
Mark Heffernan9b536a62015-06-23 18:26:50 +0000145 // Mark case value as unswitched.
146 // Since SI instruction can be partly unswitched, in order to avoid
147 // extra unswitching in cloned loops keep track all unswitched values.
148 void setUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000149
Mark Heffernan9b536a62015-06-23 18:26:50 +0000150 // Check was this case value unswitched before or not.
151 bool isUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000152
Mark Heffernan9b536a62015-06-23 18:26:50 +0000153 // Returns true if another unswitching could be done within the cost
154 // threshold.
155 bool CostAllowsUnswitching();
Andrew Trick4104ed92012-04-10 05:14:37 +0000156
Mark Heffernan9b536a62015-06-23 18:26:50 +0000157 // Clone all loop-unswitch related loop properties.
158 // Redistribute unswitching quotas.
159 // Note, that new loop data is stored inside the VMap.
160 void cloneData(const Loop *NewLoop, const Loop *OldLoop,
161 const ValueToValueMapTy &VMap);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000162 };
Andrew Trick4104ed92012-04-10 05:14:37 +0000163
Chris Lattner2dd09db2009-09-02 06:11:42 +0000164 class LoopUnswitch : public LoopPass {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000165 LoopInfo *LI; // Loop information
Devang Patel901a27d2007-03-07 00:26:10 +0000166 LPPassManager *LPM;
Chandler Carruth66b31302015-01-04 12:03:27 +0000167 AssumptionCache *AC;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000168
Sanjay Patel956e29c2015-08-11 21:24:04 +0000169 // Used to check if second loop needs processing after
170 // RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000171 std::vector<Loop*> LoopProcessWorklist;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000172
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000173 LUAnalysisCache BranchesInfo;
Andrew Trick4104ed92012-04-10 05:14:37 +0000174
Chen Li9f27fc02015-09-29 05:03:32 +0000175 bool EnabledPGO;
176
177 // BFI and ColdEntryFreq are only used when PGO and
178 // LoopUnswitchWithBlockFrequency are enabled.
179 BlockFrequencyInfo BFI;
180 BlockFrequency ColdEntryFreq;
181
Devang Patel506310d2007-06-06 00:21:03 +0000182 bool OptimizeForSize;
Devang Patel7d165e12007-07-30 23:07:10 +0000183 bool redoLoop;
Devang Patela69f9872007-10-05 22:29:34 +0000184
Devang Patele149d4e2008-07-02 01:18:13 +0000185 Loop *currentLoop;
Devang Patela69f9872007-10-05 22:29:34 +0000186 DominatorTree *DT;
Devang Patele149d4e2008-07-02 01:18:13 +0000187 BasicBlock *loopHeader;
188 BasicBlock *loopPreheader;
Andrew Trick4104ed92012-04-10 05:14:37 +0000189
Devang Pateled50fb52008-07-02 01:44:29 +0000190 // LoopBlocks contains all of the basic blocks of the loop, including the
Andrew Trick4104ed92012-04-10 05:14:37 +0000191 // preheader of the loop, the body of the loop, and the exit blocks of the
Devang Pateled50fb52008-07-02 01:44:29 +0000192 // loop, in that order.
193 std::vector<BasicBlock*> LoopBlocks;
194 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
195 std::vector<BasicBlock*> NewBlocks;
Devang Pateleb611dd2008-07-03 17:37:52 +0000196
Chris Lattnerf48f7772004-04-19 18:07:02 +0000197 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000198 static char ID; // Pass ID, replacement for typeid
Andrew Trick4104ed92012-04-10 05:14:37 +0000199 explicit LoopUnswitch(bool Os = false) :
200 LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
Craig Topperf40110f2014-04-25 05:29:35 +0000201 currentLoop(nullptr), DT(nullptr), loopHeader(nullptr),
202 loopPreheader(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000203 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
204 }
Devang Patel09f162c2007-05-01 21:15:47 +0000205
Craig Topper3e4c6972014-03-05 09:10:37 +0000206 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Devang Patele149d4e2008-07-02 01:18:13 +0000207 bool processCurrentLoop();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000208
209 /// This transformation requires natural loop information & requires that
Chris Lattnerbc1a65a2010-08-29 17:23:19 +0000210 /// loop preheaders be inserted into the CFG.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000211 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000212 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +0000213 AU.addRequired<AssumptionCacheTracker>();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000214 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +0000215 AU.addPreservedID(LoopSimplifyID);
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000216 AU.addRequired<LoopInfoWrapperPass>();
217 AU.addPreserved<LoopInfoWrapperPass>();
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000218 AU.addRequiredID(LCSSAID);
Devang Pateld4911982007-07-31 08:03:26 +0000219 AU.addPreservedID(LCSSAID);
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000220 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +0000221 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000222 AU.addPreserved<ScalarEvolutionWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000223 AU.addRequired<TargetTransformInfoWrapperPass>();
James Molloyefbba722015-09-10 10:22:12 +0000224 AU.addPreserved<GlobalsAAWrapperPass>();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000225 }
226
227 private:
Devang Pateld4911982007-07-31 08:03:26 +0000228
Craig Topper3e4c6972014-03-05 09:10:37 +0000229 void releaseMemory() override {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000230 BranchesInfo.forgetLoop(currentLoop);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000231 }
232
Devang Patele149d4e2008-07-02 01:18:13 +0000233 void initLoopData() {
234 loopHeader = currentLoop->getHeader();
235 loopPreheader = currentLoop->getLoopPreheader();
236 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000237
Chris Lattner559c8672008-04-21 00:25:49 +0000238 /// Split all of the edges from inside the loop to their exit blocks.
239 /// Update the appropriate Phi nodes as we do so.
Sanjay Patel41f3d952015-08-11 21:11:56 +0000240 void SplitExitEdges(Loop *L,
241 const SmallVectorImpl<BasicBlock *> &ExitBlocks);
Devang Patela69f9872007-10-05 22:29:34 +0000242
Chen Lic0f3a152015-07-22 05:26:29 +0000243 bool TryTrivialLoopUnswitch(bool &Changed);
244
Weiming Zhaof1abad52015-06-23 05:31:09 +0000245 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,
246 TerminatorInst *TI = nullptr);
Chris Lattner29f771b2006-02-18 01:27:45 +0000247 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000248 BasicBlock *ExitBlock, TerminatorInst *TI);
249 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
250 TerminatorInst *TI);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000251
252 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
253 Constant *Val, bool isEqual);
Devang Patel3304e462007-06-28 00:49:00 +0000254
255 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
Andrew Trick4104ed92012-04-10 05:14:37 +0000256 BasicBlock *TrueDest,
Devang Patel3304e462007-06-28 00:49:00 +0000257 BasicBlock *FalseDest,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000258 Instruction *InsertPt,
259 TerminatorInst *TI);
Devang Patel3304e462007-06-28 00:49:00 +0000260
Devang Pateld4911982007-07-31 08:03:26 +0000261 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000262 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000263}
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000264
265// Analyze loop. Check its size, calculate is it possible to unswitch
266// it. Returns true if we can unswitch this loop.
Hal Finkel57f03dd2014-09-07 13:49:57 +0000267bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000268 AssumptionCache *AC) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000269
Jakub Staszak27da1232013-08-06 17:03:42 +0000270 LoopPropsMapIt PropsIt;
271 bool Inserted;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000272 std::tie(PropsIt, Inserted) =
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000273 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
Andrew Trick4104ed92012-04-10 05:14:37 +0000274
Jakub Staszak27da1232013-08-06 17:03:42 +0000275 LoopProperties &Props = PropsIt->second;
Andrew Trick4104ed92012-04-10 05:14:37 +0000276
Jakub Staszak27da1232013-08-06 17:03:42 +0000277 if (Inserted) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000278 // New loop.
279
280 // Limit the number of instructions to avoid causing significant code
281 // expansion, and the number of basic blocks, to avoid loops with
282 // large numbers of branches which cause loop unswitching to go crazy.
283 // This is a very ad-hoc heuristic.
Andrew Trick4104ed92012-04-10 05:14:37 +0000284
Hal Finkel57f03dd2014-09-07 13:49:57 +0000285 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000286 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000287
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000288 // FIXME: This is overly conservative because it does not take into
289 // consideration code simplification opportunities and code that can
290 // be shared by the resultant unswitched loops.
291 CodeMetrics Metrics;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000292 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
293 ++I)
Hal Finkel57f03dd2014-09-07 13:49:57 +0000294 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000295
Mark Heffernan9b536a62015-06-23 18:26:50 +0000296 Props.SizeEstimation = Metrics.NumInsts;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000297 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
Mark Heffernan9b536a62015-06-23 18:26:50 +0000298 Props.WasUnswitchedCount = 0;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000299 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
James Molloy4f6fb952012-12-20 16:04:27 +0000300
301 if (Metrics.notDuplicatable) {
302 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak27da1232013-08-06 17:03:42 +0000303 << L->getHeader()->getName() << ", contents cannot be "
304 << "duplicated!\n");
James Molloy4f6fb952012-12-20 16:04:27 +0000305 return false;
306 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000307 }
308
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000309 // Be careful. This links are good only before new loop addition.
310 CurrentLoopProperties = &Props;
311 CurLoopInstructions = &Props.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000312
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000313 return true;
314}
315
316// Clean all data related to given loop.
Jakub Staszak27da1232013-08-06 17:03:42 +0000317void LUAnalysisCache::forgetLoop(const Loop *L) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000318
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000319 LoopPropsMapIt LIt = LoopsProperties.find(L);
320
321 if (LIt != LoopsProperties.end()) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000322 LoopProperties &Props = LIt->second;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000323 MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
324 Props.SizeEstimation;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000325 LoopsProperties.erase(LIt);
326 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000327
Craig Topperf40110f2014-04-25 05:29:35 +0000328 CurrentLoopProperties = nullptr;
329 CurLoopInstructions = nullptr;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000330}
331
332// Mark case value as unswitched.
333// Since SI instruction can be partly unswitched, in order to avoid
334// extra unswitching in cloned loops keep track all unswitched values.
Jakub Staszak27da1232013-08-06 17:03:42 +0000335void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000336 (*CurLoopInstructions)[SI].insert(V);
337}
338
339// Check was this case value unswitched before or not.
Jakub Staszak27da1232013-08-06 17:03:42 +0000340bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000341 return (*CurLoopInstructions)[SI].count(V);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000342}
343
Mark Heffernan9b536a62015-06-23 18:26:50 +0000344bool LUAnalysisCache::CostAllowsUnswitching() {
345 return CurrentLoopProperties->CanBeUnswitchedCount > 0;
346}
347
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000348// Clone all loop-unswitch related loop properties.
349// Redistribute unswitching quotas.
350// Note, that new loop data is stored inside the VMap.
Jakub Staszak27da1232013-08-06 17:03:42 +0000351void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
352 const ValueToValueMapTy &VMap) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000353
Jakub Staszak27da1232013-08-06 17:03:42 +0000354 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
355 LoopProperties &OldLoopProps = *CurrentLoopProperties;
356 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000357
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000358 // Reallocate "can-be-unswitched quota"
359
360 --OldLoopProps.CanBeUnswitchedCount;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000361 ++OldLoopProps.WasUnswitchedCount;
362 NewLoopProps.WasUnswitchedCount = 0;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000363 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
364 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
365 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
Andrew Trick4104ed92012-04-10 05:14:37 +0000366
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000367 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
Andrew Trick4104ed92012-04-10 05:14:37 +0000368
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000369 // Clone unswitched values info:
370 // for new loop switches we clone info about values that was
371 // already unswitched and has redundant successors.
372 for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000373 const SwitchInst *OldInst = I->first;
374 Value *NewI = VMap.lookup(OldInst);
375 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000376 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
Andrew Trick4104ed92012-04-10 05:14:37 +0000377
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000378 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
379 }
380}
381
Dan Gohmand78c4002008-05-13 00:00:25 +0000382char LoopUnswitch::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000383INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
384 false, false)
Chandler Carruth705b1852015-01-31 03:43:40 +0000385INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruth66b31302015-01-04 12:03:27 +0000386INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000387INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000388INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000389INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000390INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
391 false, false)
Chris Lattnerf48f7772004-04-19 18:07:02 +0000392
Andrew Trick4104ed92012-04-10 05:14:37 +0000393Pass *llvm::createLoopUnswitchPass(bool Os) {
394 return new LoopUnswitch(Os);
Devang Patel506310d2007-06-06 00:21:03 +0000395}
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000396
Sanjay Patel956e29c2015-08-11 21:24:04 +0000397/// Cond is a condition that occurs in L. If it is invariant in the loop, or has
398/// an invariant piece, return the invariant. Otherwise, return null.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000399static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000400
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000401 // We started analyze new instruction, increment scanned instructions counter.
402 ++TotalInsts;
Andrew Trick4104ed92012-04-10 05:14:37 +0000403
Chris Lattner302240d2010-02-02 02:26:54 +0000404 // We can never unswitch on vector conditions.
Duncan Sands19d0b472010-02-16 11:11:14 +0000405 if (Cond->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000406 return nullptr;
Chris Lattner302240d2010-02-02 02:26:54 +0000407
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000408 // Constants should be folded, not unswitched on!
Craig Topperf40110f2014-04-25 05:29:35 +0000409 if (isa<Constant>(Cond)) return nullptr;
Devang Patel3c723c82007-06-28 00:44:10 +0000410
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000411 // TODO: Handle: br (VARIANT|INVARIANT).
Devang Patelfe57d102008-11-03 19:38:07 +0000412
Dan Gohman4d6149f2009-07-14 01:37:59 +0000413 // Hoist simple values out.
Dan Gohmanc43e4792009-07-15 01:25:43 +0000414 if (L->makeLoopInvariant(Cond, Changed))
Dan Gohman4d6149f2009-07-14 01:37:59 +0000415 return Cond;
Dan Gohman4d6149f2009-07-14 01:37:59 +0000416
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000417 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
418 if (BO->getOpcode() == Instruction::And ||
419 BO->getOpcode() == Instruction::Or) {
420 // If either the left or right side is invariant, we can unswitch on this,
421 // which will cause the branch to go away in one loop and the condition to
422 // simplify in the other one.
423 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
424 return LHS;
425 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
426 return RHS;
427 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000428
Craig Topperf40110f2014-04-25 05:29:35 +0000429 return nullptr;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000430}
431
Devang Patel901a27d2007-03-07 00:26:10 +0000432bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000433 if (skipOptnoneFunction(L))
434 return false;
435
Chandler Carruth66b31302015-01-04 12:03:27 +0000436 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
437 *L->getHeader()->getParent());
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000438 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Devang Patel901a27d2007-03-07 00:26:10 +0000439 LPM = &LPM_Ref;
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000440 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Devang Patele149d4e2008-07-02 01:18:13 +0000441 currentLoop = L;
Devang Patel40519f02008-09-04 22:43:59 +0000442 Function *F = currentLoop->getHeader()->getParent();
Chen Li9f27fc02015-09-29 05:03:32 +0000443
444 EnabledPGO = F->getEntryCount().hasValue();
445
446 if (LoopUnswitchWithBlockFrequency && EnabledPGO) {
447 BranchProbabilityInfo BPI(*F, *LI);
448 BFI.calculate(*L->getHeader()->getParent(), BPI, *LI);
449
450 // Use BranchProbability to compute a minimum frequency based on
451 // function entry baseline frequency. Loops with headers below this
452 // frequency are considered as cold.
453 const BranchProbability ColdProb(ColdnessThreshold, 100);
454 ColdEntryFreq = BlockFrequency(BFI.getEntryFreq()) * ColdProb;
455 }
456
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000457 bool Changed = false;
Devang Patel7d165e12007-07-30 23:07:10 +0000458 do {
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000459 assert(currentLoop->isLCSSAForm(*DT));
Devang Patel7d165e12007-07-30 23:07:10 +0000460 redoLoop = false;
Devang Patele149d4e2008-07-02 01:18:13 +0000461 Changed |= processCurrentLoop();
Devang Patel7d165e12007-07-30 23:07:10 +0000462 } while(redoLoop);
463
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000464 // FIXME: Reconstruct dom info, because it is not preserved properly.
465 if (Changed)
466 DT->recalculate(*F);
Devang Patel7d165e12007-07-30 23:07:10 +0000467 return Changed;
468}
469
Sanjay Patel956e29c2015-08-11 21:24:04 +0000470/// Do actual work and unswitch loop if possible and profitable.
Devang Patele149d4e2008-07-02 01:18:13 +0000471bool LoopUnswitch::processCurrentLoop() {
Devang Patel7d165e12007-07-30 23:07:10 +0000472 bool Changed = false;
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000473
474 initLoopData();
Andrew Trick4104ed92012-04-10 05:14:37 +0000475
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000476 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
477 if (!loopPreheader)
478 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000479
Andrew Trick4442bfe2012-04-10 05:14:42 +0000480 // Loops with indirectbr cannot be cloned.
481 if (!currentLoop->isSafeToClone())
482 return false;
483
484 // Without dedicated exits, splitting the exit edge may fail.
485 if (!currentLoop->hasDedicatedExits())
486 return false;
487
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000488 LLVMContext &Context = loopHeader->getContext();
Andrew Trick4104ed92012-04-10 05:14:37 +0000489
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000490 // Probably we reach the quota of branches for this loop. If so
491 // stop unswitching.
Chandler Carruth705b1852015-01-31 03:43:40 +0000492 if (!BranchesInfo.countLoop(
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000493 currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
494 *currentLoop->getHeader()->getParent()),
Chandler Carruth705b1852015-01-31 03:43:40 +0000495 AC))
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000496 return false;
Devang Patel7d165e12007-07-30 23:07:10 +0000497
Chen Lic0f3a152015-07-22 05:26:29 +0000498 // Try trivial unswitch first before loop over other basic blocks in the loop.
499 if (TryTrivialLoopUnswitch(Changed)) {
500 return true;
501 }
502
Owen Anderson2c9978b2015-10-09 18:40:20 +0000503 // Do not unswitch loops containing convergent operations, as we might be
504 // making them control dependent on the unswitch value when they were not
505 // before.
506 // FIXME: This could be refined to only bail if the convergent operation is
507 // not already control-dependent on the unswitch value.
508 for (const auto BB : currentLoop->blocks()) {
509 for (const auto &I : *BB) {
510 const auto CI = dyn_cast<CallInst>(&I);
511 if (!CI) continue;
512 if (CI->isConvergent())
513 return false;
514 }
515 }
516
Chen Lif458c6f2015-08-13 05:24:29 +0000517 // Do not do non-trivial unswitch while optimizing for size.
518 // FIXME: Use Function::optForSize().
519 if (OptimizeForSize ||
520 loopHeader->getParent()->hasFnAttribute(Attribute::OptimizeForSize))
521 return false;
522
Chen Li9f27fc02015-09-29 05:03:32 +0000523 if (LoopUnswitchWithBlockFrequency && EnabledPGO) {
524 // Compute the weighted frequency of the hottest block in the
525 // loop (loopHeader in this case since inner loops should be
526 // processed before outer loop). If it is less than ColdFrequency,
527 // we should not unswitch.
528 BlockFrequency LoopEntryFreq = BFI.getBlockFreq(loopHeader);
529 if (LoopEntryFreq < ColdEntryFreq)
530 return false;
531 }
532
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000533 // Loop over all of the basic blocks in the loop. If we find an interior
534 // block that is branching on a loop-invariant condition, we can unswitch this
535 // loop.
Andrew Trick4104ed92012-04-10 05:14:37 +0000536 for (Loop::block_iterator I = currentLoop->block_begin(),
Chris Lattnerc832c1b2010-04-05 21:18:32 +0000537 E = currentLoop->block_end(); I != E; ++I) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000538 TerminatorInst *TI = (*I)->getTerminator();
539 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
540 // If this isn't branching on an invariant condition, we can't unswitch
541 // it.
542 if (BI->isConditional()) {
543 // See if this, or some part of it, is loop invariant. If so, we can
544 // unswitch on it if we desire.
Andrew Trick4104ed92012-04-10 05:14:37 +0000545 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000546 currentLoop, Changed);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000547 if (LoopCond &&
548 UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000549 ++NumBranches;
550 return true;
551 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000552 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000553 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000554 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000555 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000556 unsigned NumCases = SI->getNumCases();
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000557 if (LoopCond && NumCases) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000558 // Find a value to unswitch on:
559 // FIXME: this should chose the most expensive case!
Nick Lewycky61158242011-06-03 06:27:15 +0000560 // FIXME: scan for a case with a non-critical edge?
Craig Topperf40110f2014-04-25 05:29:35 +0000561 Constant *UnswitchVal = nullptr;
Andrew Trick4104ed92012-04-10 05:14:37 +0000562
Devang Patel967b84c2007-02-26 19:31:58 +0000563 // Do not process same value again and again.
Chad Rosier3ba90a12011-12-22 21:10:46 +0000564 // At this point we have some cases already unswitched and
565 // some not yet unswitched. Let's find the first not yet unswitched one.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +0000566 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000567 i != e; ++i) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000568 Constant *UnswitchValCandidate = i.getCaseValue();
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000569 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
Chad Rosier3ba90a12011-12-22 21:10:46 +0000570 UnswitchVal = UnswitchValCandidate;
571 break;
572 }
573 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000574
Chad Rosier3ba90a12011-12-22 21:10:46 +0000575 if (!UnswitchVal)
Devang Patel967b84c2007-02-26 19:31:58 +0000576 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000577
Devang Patele149d4e2008-07-02 01:18:13 +0000578 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000579 ++NumSwitches;
580 return true;
581 }
582 }
583 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000584
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000585 // Scan the instructions to check for unswitchable values.
Andrew Trick4104ed92012-04-10 05:14:37 +0000586 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000587 BBI != E; ++BBI)
588 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000589 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000590 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000591 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson23a204d2009-07-31 17:39:07 +0000592 ConstantInt::getTrue(Context))) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000593 ++NumSelects;
594 return true;
595 }
596 }
597 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000598 return Changed;
599}
600
Sanjay Patel956e29c2015-08-11 21:24:04 +0000601/// Check to see if all paths from BB exit the loop with no side effects
602/// (including infinite loops).
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000603///
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000604/// If true, we return true and set ExitBB to the block we
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000605/// exit through.
606///
607static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
608 BasicBlock *&ExitBB,
609 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000610 if (!Visited.insert(BB).second) {
Nick Lewyckyd9d1de42011-12-23 23:49:25 +0000611 // Already visited. Without more analysis, this could indicate an infinite
612 // loop.
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000613 return false;
Jakub Staszak27da1232013-08-06 17:03:42 +0000614 }
615 if (!L->contains(BB)) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000616 // Otherwise, this is a loop exit, this is fine so long as this is the
617 // first exit.
Craig Topperf40110f2014-04-25 05:29:35 +0000618 if (ExitBB) return false;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000619 ExitBB = BB;
Edward O'Callaghan2b8fed12009-11-25 05:38:41 +0000620 return true;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000621 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000622
Chris Lattnerbaddba42006-02-17 06:39:56 +0000623 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000624 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000625 // Check to see if the successor is a trivial loop exit.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000626 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
Chris Lattnerbaddba42006-02-17 06:39:56 +0000627 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000628 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000629
630 // Okay, everything after this looks good, check to make sure that this block
631 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000632 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Duncan Sands1efabaa2009-05-06 06:49:50 +0000633 if (I->mayHaveSideEffects())
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000634 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000635
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000636 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000637}
638
Sanjay Patel956e29c2015-08-11 21:24:04 +0000639/// Return true if the specified block unconditionally leads to an exit from
640/// the specified loop, and has no side-effects in the process. If so, return
641/// the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000642static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
643 std::set<BasicBlock*> Visited;
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000644 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
Craig Topperf40110f2014-04-25 05:29:35 +0000645 BasicBlock *ExitBB = nullptr;
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000646 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
647 return ExitBB;
Craig Topperf40110f2014-04-25 05:29:35 +0000648 return nullptr;
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000649}
Chris Lattner6e263152006-02-10 02:30:37 +0000650
Sanjay Patel956e29c2015-08-11 21:24:04 +0000651/// We have found that we can unswitch currentLoop when LoopCond == Val to
652/// simplify the loop. If we decide that this is profitable,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000653/// unswitch the loop, reprocess the pieces, then return true.
Weiming Zhaof1abad52015-06-23 05:31:09 +0000654bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,
655 TerminatorInst *TI) {
Evan Chenged66db32010-04-03 02:23:43 +0000656 // Check to see if it would be profitable to unswitch current loop.
Mark Heffernan9b536a62015-06-23 18:26:50 +0000657 if (!BranchesInfo.CostAllowsUnswitching()) {
658 DEBUG(dbgs() << "NOT unswitching loop %"
659 << currentLoop->getHeader()->getName()
660 << " at non-trivial condition '" << *Val
661 << "' == " << *LoopCond << "\n"
662 << ". Cost too high.\n");
663 return false;
664 }
Evan Chenged66db32010-04-03 02:23:43 +0000665
Weiming Zhaof1abad52015-06-23 05:31:09 +0000666 UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
Andrew Trick4442bfe2012-04-10 05:14:42 +0000667 return true;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000668}
669
Sanjay Patel956e29c2015-08-11 21:24:04 +0000670/// Recursively clone the specified loop and all of its children,
Chris Lattnerf48f7772004-04-19 18:07:02 +0000671/// mapping the blocks with the specified map.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000672static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000673 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000674 Loop *New = new Loop();
Devang Patel901a27d2007-03-07 00:26:10 +0000675 LPM->insertLoop(New, PL);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000676
677 // Add all of the blocks in L to the new loop.
678 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
679 I != E; ++I)
680 if (LI->getLoopFor(*I) == L)
Chandler Carruth691addc2015-01-18 01:25:51 +0000681 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000682
683 // Add all of the subloops to the new loop.
684 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel901a27d2007-03-07 00:26:10 +0000685 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000686
Chris Lattnerf48f7772004-04-19 18:07:02 +0000687 return New;
688}
689
Weiming Zhaof1abad52015-06-23 05:31:09 +0000690static void copyMetadata(Instruction *DstInst, const Instruction *SrcInst,
691 bool Swapped) {
692 if (!SrcInst || !SrcInst->hasMetadata())
693 return;
694
695 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
696 SrcInst->getAllMetadata(MDs);
697 for (auto &MD : MDs) {
698 switch (MD.first) {
699 default:
700 break;
701 case LLVMContext::MD_prof:
702 if (Swapped && MD.second->getNumOperands() == 3 &&
703 isa<MDString>(MD.second->getOperand(0))) {
704 MDString *MDName = cast<MDString>(MD.second->getOperand(0));
705 if (MDName->getString() == "branch_weights") {
706 auto *ValT = cast_or_null<ConstantAsMetadata>(
707 MD.second->getOperand(1))->getValue();
708 auto *ValF = cast_or_null<ConstantAsMetadata>(
709 MD.second->getOperand(2))->getValue();
710 assert(ValT && ValF && "Invalid Operands of branch_weights");
711 auto NewMD =
712 MDBuilder(DstInst->getParent()->getContext())
713 .createBranchWeights(cast<ConstantInt>(ValF)->getZExtValue(),
714 cast<ConstantInt>(ValT)->getZExtValue());
715 MD.second = NewMD;
716 }
717 }
718 // fallthrough.
Chen Li50efd922015-08-05 21:13:26 +0000719 case LLVMContext::MD_make_implicit:
Weiming Zhaof1abad52015-06-23 05:31:09 +0000720 case LLVMContext::MD_dbg:
721 DstInst->setMetadata(MD.first, MD.second);
722 }
723 }
724}
725
Sanjay Patel956e29c2015-08-11 21:24:04 +0000726/// Emit a conditional branch on two values if LIC == Val, branch to TrueDst,
727/// otherwise branch to FalseDest. Insert the code immediately before InsertPt.
Devang Patel3304e462007-06-28 00:49:00 +0000728void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
729 BasicBlock *TrueDest,
730 BasicBlock *FalseDest,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000731 Instruction *InsertPt,
732 TerminatorInst *TI) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000733 // Insert a conditional branch on LIC to the two preheaders. The original
734 // code is the true version and the new code is the false version.
735 Value *BranchVal = LIC;
Weiming Zhaof1abad52015-06-23 05:31:09 +0000736 bool Swapped = false;
Owen Anderson55f1c092009-08-13 21:58:54 +0000737 if (!isa<ConstantInt>(Val) ||
738 Val->getType() != Type::getInt1Ty(LIC->getContext()))
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000739 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000740 else if (Val != ConstantInt::getTrue(Val->getContext())) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000741 // We want to enter the new loop when the condition is true.
742 std::swap(TrueDest, FalseDest);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000743 Swapped = true;
744 }
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000745
746 // Insert the new branch.
Dan Gohman3ddbc242009-09-08 15:45:00 +0000747 BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000748 copyMetadata(BI, TI, Swapped);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000749
750 // If either edge is critical, split it. This helps preserve LoopSimplify
751 // form for enclosing loops.
Chandler Carruthf8753fc2015-01-19 12:12:00 +0000752 auto Options = CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA();
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000753 SplitCriticalEdge(BI, 0, Options);
754 SplitCriticalEdge(BI, 1, Options);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000755}
756
Sanjay Patel956e29c2015-08-11 21:24:04 +0000757/// Given a loop that has a trivial unswitchable condition in it (a cond branch
758/// from its header block to its latch block, where the path through the loop
759/// that doesn't execute its body has no side-effects), unswitch it. This
760/// doesn't involve any code duplication, just moving the conditional branch
761/// outside of the loop and updating loop info.
Weiming Zhaof1abad52015-06-23 05:31:09 +0000762void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
763 BasicBlock *ExitBlock,
764 TerminatorInst *TI) {
David Greened9c355d2010-01-05 01:27:04 +0000765 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
Weiming Zhaof1abad52015-06-23 05:31:09 +0000766 << loopHeader->getName() << " [" << L->getBlocks().size()
767 << " blocks] in Function "
768 << L->getHeader()->getParent()->getName() << " on cond: " << *Val
769 << " == " << *Cond << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +0000770
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000771 // First step, split the preheader, so that we know that there is a safe place
Devang Patele149d4e2008-07-02 01:18:13 +0000772 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattnered7a67b2006-02-10 01:24:09 +0000773 // conditional branch on Cond.
Chandler Carruthd4500562015-01-19 12:36:53 +0000774 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000775
776 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000777 // to branch to: this is the exit block out of the loop that we should
778 // short-circuit to.
Andrew Trick4104ed92012-04-10 05:14:37 +0000779
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000780 // Split this block now, so that the loop maintains its exit block, and so
781 // that the jump from the preheader can execute the contents of the exit block
782 // without actually branching to it (the exit block should be dominated by the
783 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000784 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chandler Carruth32c52c72015-01-18 02:39:37 +0000785 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), DT, LI);
Andrew Trick4104ed92012-04-10 05:14:37 +0000786
787 // Okay, now we have a position to branch from and a position to branch to,
Chris Lattnered7a67b2006-02-10 01:24:09 +0000788 // insert the new conditional branch.
Andrew Trick4104ed92012-04-10 05:14:37 +0000789 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000790 loopPreheader->getTerminator(), TI);
Devang Patele149d4e2008-07-02 01:18:13 +0000791 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
792 loopPreheader->getTerminator()->eraseFromParent();
Chris Lattnered7a67b2006-02-10 01:24:09 +0000793
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000794 // We need to reprocess this loop, it could be unswitched again.
Devang Patel7d165e12007-07-30 23:07:10 +0000795 redoLoop = true;
Andrew Trick4104ed92012-04-10 05:14:37 +0000796
Chris Lattnered7a67b2006-02-10 01:24:09 +0000797 // Now that we know that the loop is never entered when this condition is a
798 // particular value, rewrite the loop with this info. We know that this will
799 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000800 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000801 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000802}
803
Sanjay Patel41f3d952015-08-11 21:11:56 +0000804/// Check if the first non-constant condition starting from the loop header is
805/// a trivial unswitch condition: that is, a condition controls whether or not
806/// the loop does anything at all. If it is a trivial condition, unswitching
807/// produces no code duplications (equivalently, it produces a simpler loop and
808/// a new empty loop, which gets deleted). Therefore always unswitch trivial
809/// condition.
Chen Lic0f3a152015-07-22 05:26:29 +0000810bool LoopUnswitch::TryTrivialLoopUnswitch(bool &Changed) {
Chen Li145c2f52015-07-25 03:21:06 +0000811 BasicBlock *CurrentBB = currentLoop->getHeader();
812 TerminatorInst *CurrentTerm = CurrentBB->getTerminator();
813 LLVMContext &Context = CurrentBB->getContext();
Chen Lic0f3a152015-07-22 05:26:29 +0000814
Chen Li145c2f52015-07-25 03:21:06 +0000815 // If loop header has only one reachable successor (currently via an
816 // unconditional branch or constant foldable conditional branch, but
817 // should also consider adding constant foldable switch instruction in
818 // future), we should keep looking for trivial condition candidates in
819 // the successor as well. An alternative is to constant fold conditions
820 // and merge successors into loop header (then we only need to check header's
821 // terminator). The reason for not doing this in LoopUnswitch pass is that
822 // it could potentially break LoopPassManager's invariants. Folding dead
823 // branches could either eliminate the current loop or make other loops
Sanjay Patel41f3d952015-08-11 21:11:56 +0000824 // unreachable. LCSSA form might also not be preserved after deleting
825 // branches. The following code keeps traversing loop header's successors
826 // until it finds the trivial condition candidate (condition that is not a
827 // constant). Since unswitching generates branches with constant conditions,
828 // this scenario could be very common in practice.
Chen Li145c2f52015-07-25 03:21:06 +0000829 SmallSet<BasicBlock*, 8> Visited;
830
831 while (true) {
832 // If we exit loop or reach a previous visited block, then
833 // we can not reach any trivial condition candidates (unfoldable
834 // branch instructions or switch instructions) and no unswitch
835 // can happen. Exit and return false.
836 if (!currentLoop->contains(CurrentBB) || !Visited.insert(CurrentBB).second)
Chen Lic0f3a152015-07-22 05:26:29 +0000837 return false;
838
Chen Li145c2f52015-07-25 03:21:06 +0000839 // Check if this loop will execute any side-effecting instructions (e.g.
840 // stores, calls, volatile loads) in the part of the loop that the code
841 // *would* execute. Check the header first.
842 for (BasicBlock::iterator I : *CurrentBB)
843 if (I->mayHaveSideEffects())
844 return false;
845
846 // FIXME: add check for constant foldable switch instructions.
847 if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
848 if (BI->isUnconditional()) {
849 CurrentBB = BI->getSuccessor(0);
850 } else if (BI->getCondition() == ConstantInt::getTrue(Context)) {
851 CurrentBB = BI->getSuccessor(0);
852 } else if (BI->getCondition() == ConstantInt::getFalse(Context)) {
853 CurrentBB = BI->getSuccessor(1);
854 } else {
Sanjay Patel41f3d952015-08-11 21:11:56 +0000855 // Found a trivial condition candidate: non-foldable conditional branch.
Chen Li145c2f52015-07-25 03:21:06 +0000856 break;
857 }
858 } else {
859 break;
860 }
861
862 CurrentTerm = CurrentBB->getTerminator();
863 }
864
Chen Lic0f3a152015-07-22 05:26:29 +0000865 // CondVal is the condition that controls the trivial condition.
866 // LoopExitBB is the BasicBlock that loop exits when meets trivial condition.
867 Constant *CondVal = nullptr;
868 BasicBlock *LoopExitBB = nullptr;
869
Chen Li145c2f52015-07-25 03:21:06 +0000870 if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
Chen Lic0f3a152015-07-22 05:26:29 +0000871 // If this isn't branching on an invariant condition, we can't unswitch it.
872 if (!BI->isConditional())
873 return false;
874
875 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
876 currentLoop, Changed);
877
878 // Unswitch only if the trivial condition itself is an LIV (not
879 // partial LIV which could occur in and/or)
880 if (!LoopCond || LoopCond != BI->getCondition())
881 return false;
882
883 // Check to see if a successor of the branch is guaranteed to
884 // exit through a unique exit block without having any
885 // side-effects. If so, determine the value of Cond that causes
886 // it to do this.
887 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
888 BI->getSuccessor(0)))) {
889 CondVal = ConstantInt::getTrue(Context);
890 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
891 BI->getSuccessor(1)))) {
892 CondVal = ConstantInt::getFalse(Context);
893 }
894
Sanjay Patel41f3d952015-08-11 21:11:56 +0000895 // If we didn't find a single unique LoopExit block, or if the loop exit
896 // block contains phi nodes, this isn't trivial.
Chen Lic0f3a152015-07-22 05:26:29 +0000897 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
898 return false; // Can't handle this.
899
Sanjay Patel41f3d952015-08-11 21:11:56 +0000900 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
901 CurrentTerm);
Chen Lic0f3a152015-07-22 05:26:29 +0000902 ++NumBranches;
903 return true;
Chen Li145c2f52015-07-25 03:21:06 +0000904 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
Chen Lic0f3a152015-07-22 05:26:29 +0000905 // If this isn't switching on an invariant condition, we can't unswitch it.
906 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
907 currentLoop, Changed);
908
909 // Unswitch only if the trivial condition itself is an LIV (not
910 // partial LIV which could occur in and/or)
911 if (!LoopCond || LoopCond != SI->getCondition())
912 return false;
913
914 // Check to see if a successor of the switch is guaranteed to go to the
915 // latch block or exit through a one exit block without having any
916 // side-effects. If so, determine the value of Cond that causes it to do
917 // this.
918 // Note that we can't trivially unswitch on the default case or
919 // on already unswitched cases.
920 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
921 i != e; ++i) {
922 BasicBlock *LoopExitCandidate;
923 if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
924 i.getCaseSuccessor()))) {
925 // Okay, we found a trivial case, remember the value that is trivial.
926 ConstantInt *CaseVal = i.getCaseValue();
927
928 // Check that it was not unswitched before, since already unswitched
929 // trivial vals are looks trivial too.
930 if (BranchesInfo.isUnswitched(SI, CaseVal))
931 continue;
932 LoopExitBB = LoopExitCandidate;
933 CondVal = CaseVal;
934 break;
935 }
936 }
937
Sanjay Patel41f3d952015-08-11 21:11:56 +0000938 // If we didn't find a single unique LoopExit block, or if the loop exit
939 // block contains phi nodes, this isn't trivial.
Chen Lic0f3a152015-07-22 05:26:29 +0000940 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
941 return false; // Can't handle this.
942
Sanjay Patel41f3d952015-08-11 21:11:56 +0000943 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
944 nullptr);
Chen Lic0f3a152015-07-22 05:26:29 +0000945 ++NumSwitches;
946 return true;
947 }
948 return false;
949}
950
Sanjay Patel956e29c2015-08-11 21:24:04 +0000951/// Split all of the edges from inside the loop to their exit blocks.
952/// Update the appropriate Phi nodes as we do so.
Andrew Trick4104ed92012-04-10 05:14:37 +0000953void LoopUnswitch::SplitExitEdges(Loop *L,
Craig Topperb94011f2013-07-14 04:42:23 +0000954 const SmallVectorImpl<BasicBlock *> &ExitBlocks){
Devang Patela69f9872007-10-05 22:29:34 +0000955
Chris Lattnered7a67b2006-02-10 01:24:09 +0000956 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000957 BasicBlock *ExitBlock = ExitBlocks[i];
Dan Gohman3ddbc242009-09-08 15:45:00 +0000958 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
959 pred_end(ExitBlock));
Bill Wendling90f90da2011-09-27 00:59:31 +0000960
Nick Lewycky61158242011-06-03 06:27:15 +0000961 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
962 // general, if we call it on all predecessors of all exits then it does.
Chandler Carruth96ada252015-07-22 09:52:54 +0000963 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", DT, LI,
Philip Reames9198b332015-01-28 23:06:47 +0000964 /*PreserveLCSSA*/ true);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000965 }
Devang Patele192e3252007-10-03 21:16:08 +0000966}
967
Sanjay Patel956e29c2015-08-11 21:24:04 +0000968/// We determined that the loop is profitable to unswitch when LIC equal Val.
969/// Split it into loop versions and test the condition outside of either loop.
970/// Return the loops created as Out1/Out2.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000971void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000972 Loop *L, TerminatorInst *TI) {
Devang Patele149d4e2008-07-02 01:18:13 +0000973 Function *F = loopHeader->getParent();
David Greened9c355d2010-01-05 01:27:04 +0000974 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000975 << loopHeader->getName() << " [" << L->getBlocks().size()
976 << " blocks] in Function " << F->getName()
977 << " when '" << *Val << "' == " << *LIC << "\n");
Devang Patele192e3252007-10-03 21:16:08 +0000978
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000979 if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
980 SEWP->getSE().forgetLoop(L);
Cameron Zwarich99de19b2011-02-11 06:08:28 +0000981
Devang Pateled50fb52008-07-02 01:44:29 +0000982 LoopBlocks.clear();
983 NewBlocks.clear();
Devang Patele192e3252007-10-03 21:16:08 +0000984
985 // First step, split the preheader and exit blocks, and add these blocks to
986 // the LoopBlocks list.
Chandler Carruthd4500562015-01-19 12:36:53 +0000987 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, DT, LI);
Devang Patele192e3252007-10-03 21:16:08 +0000988 LoopBlocks.push_back(NewPreheader);
989
990 // We want the loop to come after the preheader, but before the exit blocks.
991 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
992
993 SmallVector<BasicBlock*, 8> ExitBlocks;
994 L->getUniqueExitBlocks(ExitBlocks);
995
996 // Split all of the edges from inside the loop to their exit blocks. Update
997 // the appropriate Phi nodes as we do so.
Devang Pateleb611dd2008-07-03 17:37:52 +0000998 SplitExitEdges(L, ExitBlocks);
Devang Patele192e3252007-10-03 21:16:08 +0000999
Chris Lattnerfe4151e2006-02-10 23:16:39 +00001000 // The exit blocks may have been changed due to edge splitting, recompute.
1001 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +00001002 L->getUniqueExitBlocks(ExitBlocks);
1003
Chris Lattnerfe4151e2006-02-10 23:16:39 +00001004 // Add exit blocks to the loop blocks.
1005 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +00001006
1007 // Next step, clone all of the basic blocks that make up the loop (including
1008 // the loop preheader and exit blocks), keeping track of the mapping between
1009 // the instructions and blocks.
Chris Lattnerf48f7772004-04-19 18:07:02 +00001010 NewBlocks.reserve(LoopBlocks.size());
Rafael Espindola229e38f2010-10-13 01:36:30 +00001011 ValueToValueMapTy VMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +00001012 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001013 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
Andrew Trick4104ed92012-04-10 05:14:37 +00001014
Evan Chengba930442010-04-05 21:16:25 +00001015 NewBlocks.push_back(NewBB);
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001016 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
Evan Chengba930442010-04-05 21:16:25 +00001017 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
Chris Lattnerf48f7772004-04-19 18:07:02 +00001018 }
1019
1020 // Splice the newly inserted blocks into the function right before the
1021 // original preheader.
Evan Chengba930442010-04-05 21:16:25 +00001022 F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
Chris Lattnerf48f7772004-04-19 18:07:02 +00001023 NewBlocks[0], F->end());
1024
Hal Finkel74c2f352014-09-07 12:44:26 +00001025 // FIXME: We could register any cloned assumptions instead of clearing the
1026 // whole function's cache.
Chandler Carruth66b31302015-01-04 12:03:27 +00001027 AC->clear();
Hal Finkel74c2f352014-09-07 12:44:26 +00001028
Chris Lattnerf48f7772004-04-19 18:07:02 +00001029 // Now we create the new Loop object for the versioned loop.
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001030 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +00001031
1032 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
1033 // Probably clone more loop-unswitch related loop properties.
1034 BranchesInfo.cloneData(NewLoop, L, VMap);
1035
Chris Lattnerf1b15162006-02-10 23:26:14 +00001036 Loop *ParentLoop = L->getParentLoop();
1037 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +00001038 // Make sure to add the cloned preheader and exit blocks to the parent loop
1039 // as well.
Chandler Carruth691addc2015-01-18 01:25:51 +00001040 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +00001041 }
Bill Wendling90f90da2011-09-27 00:59:31 +00001042
Chris Lattnerf1b15162006-02-10 23:26:14 +00001043 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001044 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +00001045 // The new exit block should be in the same loop as the old one.
1046 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Chandler Carruth691addc2015-01-18 01:25:51 +00001047 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Andrew Trick4104ed92012-04-10 05:14:37 +00001048
Chris Lattnerf1b15162006-02-10 23:26:14 +00001049 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
1050 "Exit block should have been split to have one successor!");
1051 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
Devang Pateleb611dd2008-07-03 17:37:52 +00001052
Chris Lattnerf1b15162006-02-10 23:26:14 +00001053 // If the successor of the exit block had PHI nodes, add an entry for
1054 // NewExit.
Jakub Staszak27da1232013-08-06 17:03:42 +00001055 for (BasicBlock::iterator I = ExitSucc->begin();
1056 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnerf1b15162006-02-10 23:26:14 +00001057 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Rafael Espindola229e38f2010-10-13 01:36:30 +00001058 ValueToValueMapTy::iterator It = VMap.find(V);
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001059 if (It != VMap.end()) V = It->second;
Chris Lattnerf1b15162006-02-10 23:26:14 +00001060 PN->addIncoming(V, NewExit);
1061 }
Bill Wendling90f90da2011-09-27 00:59:31 +00001062
1063 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
Jakub Staszak27da1232013-08-06 17:03:42 +00001064 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
1065 ExitSucc->getFirstInsertionPt());
Bill Wendling90f90da2011-09-27 00:59:31 +00001066
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001067 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
1068 I != E; ++I) {
1069 BasicBlock *BB = *I;
Bill Wendling90f90da2011-09-27 00:59:31 +00001070 LandingPadInst *LPI = BB->getLandingPadInst();
1071 LPI->replaceAllUsesWith(PN);
1072 PN->addIncoming(LPI, BB);
1073 }
1074 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001075 }
1076
1077 // Rewrite the code to refer to itself.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00001078 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
1079 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
1080 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner43f8d162011-01-08 08:15:20 +00001081 RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Trick4104ed92012-04-10 05:14:37 +00001082
Chris Lattnerf48f7772004-04-19 18:07:02 +00001083 // Rewrite the original preheader to select between versions of the loop.
Devang Patele149d4e2008-07-02 01:18:13 +00001084 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerb0cbe712006-02-15 00:07:43 +00001085 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +00001086 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +00001087
Chris Lattnerb0cbe712006-02-15 00:07:43 +00001088 // Emit the new branch that selects between the two versions of this loop.
Weiming Zhaof1abad52015-06-23 05:31:09 +00001089 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
1090 TI);
Devang Pateld4911982007-07-31 08:03:26 +00001091 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001092 OldBR->eraseFromParent();
Devang Patela8823282007-08-02 15:25:57 +00001093
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001094 LoopProcessWorklist.push_back(NewLoop);
Devang Patel7d165e12007-07-30 23:07:10 +00001095 redoLoop = true;
Chris Lattnerf48f7772004-04-19 18:07:02 +00001096
Chris Lattner5814d9d92010-04-20 05:09:16 +00001097 // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
1098 // deletes the instruction (for example by simplifying a PHI that feeds into
1099 // the condition that we're unswitching on), we don't rewrite the second
1100 // iteration.
1101 WeakVH LICHandle(LIC);
Andrew Trick4104ed92012-04-10 05:14:37 +00001102
Chris Lattnerf48f7772004-04-19 18:07:02 +00001103 // Now we rewrite the original code to know that the condition is true and the
1104 // new code to know that the condition is false.
Evan Chengba930442010-04-05 21:16:25 +00001105 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
Devang Pateleb611dd2008-07-03 17:37:52 +00001106
Chris Lattner5814d9d92010-04-20 05:09:16 +00001107 // It's possible that simplifying one loop could cause the other to be
1108 // changed to another value or a constant. If its a constant, don't simplify
1109 // it.
1110 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1111 LICHandle && !isa<Constant>(LICHandle))
1112 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +00001113}
1114
Sanjay Patel956e29c2015-08-11 21:24:04 +00001115/// Remove all instances of I from the worklist vector specified.
Andrew Trick4104ed92012-04-10 05:14:37 +00001116static void RemoveFromWorklist(Instruction *I,
Chris Lattner6fd13622006-02-17 00:31:07 +00001117 std::vector<Instruction*> &Worklist) {
Jakub Staszak8f46e912012-10-16 19:52:32 +00001118
1119 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
1120 Worklist.end());
Chris Lattner6fd13622006-02-17 00:31:07 +00001121}
1122
Sanjay Patel956e29c2015-08-11 21:24:04 +00001123/// When we find that I really equals V, remove I from the
Chris Lattner6fd13622006-02-17 00:31:07 +00001124/// program, replacing all uses with V and update the worklist.
Andrew Trick4104ed92012-04-10 05:14:37 +00001125static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Pateld4911982007-07-31 08:03:26 +00001126 std::vector<Instruction*> &Worklist,
1127 Loop *L, LPPassManager *LPM) {
David Greened9c355d2010-01-05 01:27:04 +00001128 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
Chris Lattner6fd13622006-02-17 00:31:07 +00001129
1130 // Add uses to the worklist, which may be dead now.
1131 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1132 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1133 Worklist.push_back(Use);
1134
1135 // Add users to the worklist which may be simplified now.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001136 for (User *U : I->users())
1137 Worklist.push_back(cast<Instruction>(U));
Devang Pateld4911982007-07-31 08:03:26 +00001138 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001139 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +00001140 I->replaceAllUsesWith(V);
1141 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001142 ++NumSimplify;
1143}
1144
Sanjay Patel956e29c2015-08-11 21:24:04 +00001145/// We know either that the value LIC has the value specified by Val in the
1146/// specified loop, or we know it does NOT have that value.
1147/// Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +00001148void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +00001149 Constant *Val,
1150 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +00001151 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Andrew Trick4104ed92012-04-10 05:14:37 +00001152
Chris Lattnerf48f7772004-04-19 18:07:02 +00001153 // FIXME: Support correlated properties, like:
1154 // for (...)
1155 // if (li1 < li2)
1156 // ...
1157 // if (li1 > li2)
1158 // ...
Andrew Trick4104ed92012-04-10 05:14:37 +00001159
Chris Lattner6e263152006-02-10 02:30:37 +00001160 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1161 // selects, switches.
Chris Lattner6fd13622006-02-17 00:31:07 +00001162 std::vector<Instruction*> Worklist;
Owen Anderson47db9412009-07-22 00:24:57 +00001163 LLVMContext &Context = Val->getContext();
1164
Chris Lattner6fd13622006-02-17 00:31:07 +00001165 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1166 // in the loop with the appropriate one directly.
Owen Anderson55f1c092009-08-13 21:58:54 +00001167 if (IsEqual || (isa<ConstantInt>(Val) &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001168 Val->getType()->isIntegerTy(1))) {
Chris Lattner8a5a3242006-02-22 06:37:14 +00001169 Value *Replacement;
1170 if (IsEqual)
1171 Replacement = Val;
1172 else
Andrew Trick4104ed92012-04-10 05:14:37 +00001173 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
Reid Spencercddc9df2007-01-12 04:24:46 +00001174 !cast<ConstantInt>(Val)->getZExtValue());
Andrew Trick4104ed92012-04-10 05:14:37 +00001175
Chandler Carruthcdf47882014-03-09 03:16:01 +00001176 for (User *U : LIC->users()) {
1177 Instruction *UI = dyn_cast<Instruction>(U);
1178 if (!UI || !L->contains(UI))
Evan Cheng1b55f562011-05-24 23:12:57 +00001179 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001180 Worklist.push_back(UI);
Evan Cheng1b55f562011-05-24 23:12:57 +00001181 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001182
Jakub Staszak27da1232013-08-06 17:03:42 +00001183 for (std::vector<Instruction*>::iterator UI = Worklist.begin(),
1184 UE = Worklist.end(); UI != UE; ++UI)
Andrew Trick4104ed92012-04-10 05:14:37 +00001185 (*UI)->replaceUsesOfWith(LIC, Replacement);
1186
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001187 SimplifyCode(Worklist, L);
1188 return;
1189 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001190
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001191 // Otherwise, we don't know the precise value of LIC, but we do know that it
1192 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1193 // can. This case occurs when we unswitch switch statements.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001194 for (User *U : LIC->users()) {
1195 Instruction *UI = dyn_cast<Instruction>(U);
1196 if (!UI || !L->contains(UI))
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001197 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001198
Chandler Carruthcdf47882014-03-09 03:16:01 +00001199 Worklist.push_back(UI);
Chris Lattner6fd13622006-02-17 00:31:07 +00001200
Andrew Trick4104ed92012-04-10 05:14:37 +00001201 // TODO: We could do other simplifications, for example, turning
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001202 // 'icmp eq LIC, Val' -> false.
1203
1204 // If we know that LIC is not Val, use this info to simplify code.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001205 SwitchInst *SI = dyn_cast<SwitchInst>(UI);
Craig Topperf40110f2014-04-25 05:29:35 +00001206 if (!SI || !isa<ConstantInt>(Val)) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001207
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001208 SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00001209 // Default case is live for multiple values.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001210 if (DeadCase == SI->case_default()) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001211
1212 // Found a dead case value. Don't remove PHI nodes in the
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001213 // successor if they become single-entry, those PHI nodes may
1214 // be in the Users list.
Nick Lewycky61158242011-06-03 06:27:15 +00001215
Evan Cheng1b55f562011-05-24 23:12:57 +00001216 BasicBlock *Switch = SI->getParent();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001217 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
Evan Cheng1b55f562011-05-24 23:12:57 +00001218 BasicBlock *Latch = L->getLoopLatch();
Andrew Trick4104ed92012-04-10 05:14:37 +00001219
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +00001220 BranchesInfo.setUnswitched(SI, Val);
Andrew Trick4104ed92012-04-10 05:14:37 +00001221
Nick Lewycky61158242011-06-03 06:27:15 +00001222 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
Evan Cheng9605a692011-05-25 18:17:13 +00001223 // If the DeadCase successor dominates the loop latch, then the
1224 // transformation isn't safe since it will delete the sole predecessor edge
1225 // to the latch.
1226 if (Latch && DT->dominates(SISucc, Latch))
1227 continue;
Evan Cheng1b55f562011-05-24 23:12:57 +00001228
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001229 // FIXME: This is a hack. We need to keep the successor around
1230 // and hooked up so as to preserve the loop structure, because
1231 // trying to update it is complicated. So instead we preserve the
1232 // loop structure and put the block on a dead code path.
Chandler Carruthd4500562015-01-19 12:36:53 +00001233 SplitEdge(Switch, SISucc, DT, LI);
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001234 // Compute the successors instead of relying on the return value
1235 // of SplitEdge, since it may have split the switch successor
1236 // after PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001237 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001238 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1239 // Create an "unreachable" destination.
1240 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1241 Switch->getParent(),
1242 OldSISucc);
1243 new UnreachableInst(Context, Abort);
1244 // Force the new case destination to branch to the "unreachable"
1245 // block while maintaining a (dead) CFG edge to the old block.
1246 NewSISucc->getTerminator()->eraseFromParent();
1247 BranchInst::Create(Abort, OldSISucc,
1248 ConstantInt::getTrue(Context), NewSISucc);
1249 // Release the PHI operands for this edge.
1250 for (BasicBlock::iterator II = NewSISucc->begin();
1251 PHINode *PN = dyn_cast<PHINode>(II); ++II)
1252 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1253 UndefValue::get(PN->getType()));
1254 // Tell the domtree about the new block. We don't fully update the
1255 // domtree here -- instead we force it to do a full recomputation
1256 // after the pass is complete -- but we do need to inform it of
1257 // new blocks.
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +00001258 DT->addNewBlock(Abort, NewSISucc);
Chris Lattner6fd13622006-02-17 00:31:07 +00001259 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001260
Devang Pateld4911982007-07-31 08:03:26 +00001261 SimplifyCode(Worklist, L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001262}
1263
Sanjay Patel956e29c2015-08-11 21:24:04 +00001264/// Now that we have simplified some instructions in the loop, walk over it and
1265/// constant prop, dce, and fold control flow where possible. Note that this is
1266/// effectively a very simple loop-structure-aware optimizer. During processing
1267/// of this loop, L could very well be deleted, so it must not be used.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001268///
1269/// FIXME: When the loop optimizer is more mature, separate this out to a new
1270/// pass.
1271///
Devang Pateld4911982007-07-31 08:03:26 +00001272void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001273 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Chris Lattner6fd13622006-02-17 00:31:07 +00001274 while (!Worklist.empty()) {
1275 Instruction *I = Worklist.back();
1276 Worklist.pop_back();
Duncan Sandsbb2cd022010-11-23 20:24:21 +00001277
Chris Lattner6fd13622006-02-17 00:31:07 +00001278 // Simple DCE.
1279 if (isInstructionTriviallyDead(I)) {
David Greened9c355d2010-01-05 01:27:04 +00001280 DEBUG(dbgs() << "Remove dead instruction '" << *I);
Andrew Trick4104ed92012-04-10 05:14:37 +00001281
Chris Lattner6fd13622006-02-17 00:31:07 +00001282 // Add uses to the worklist, which may be dead now.
1283 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1284 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1285 Worklist.push_back(Use);
Devang Pateld4911982007-07-31 08:03:26 +00001286 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001287 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +00001288 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001289 ++NumSimplify;
1290 continue;
1291 }
Duncan Sandsaef146b2010-11-18 19:59:41 +00001292
Chris Lattner66e809a2010-04-20 05:33:18 +00001293 // See if instruction simplification can hack this up. This is common for
1294 // things like "select false, X, Y" after unswitching made the condition be
Peter Collingbourne9a03c732012-05-20 01:32:09 +00001295 // 'false'. TODO: update the domtree properly so we can pass it here.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001296 if (Value *V = SimplifyInstruction(I, DL))
Duncan Sandsaef146b2010-11-18 19:59:41 +00001297 if (LI->replacementPreservesLCSSAForm(I, V)) {
1298 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1299 continue;
1300 }
1301
Chris Lattner6fd13622006-02-17 00:31:07 +00001302 // Special case hacks that appear commonly in unswitched code.
Chris Lattner66e809a2010-04-20 05:33:18 +00001303 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001304 if (BI->isUnconditional()) {
1305 // If BI's parent is the only pred of the successor, fold the two blocks
1306 // together.
1307 BasicBlock *Pred = BI->getParent();
1308 BasicBlock *Succ = BI->getSuccessor(0);
1309 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1310 if (!SinglePred) continue; // Nothing to do.
1311 assert(SinglePred == Pred && "CFG broken");
1312
Andrew Trick4104ed92012-04-10 05:14:37 +00001313 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001314 << Succ->getName() << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +00001315
Chris Lattner6fd13622006-02-17 00:31:07 +00001316 // Resolve any single entry PHI nodes in Succ.
1317 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Pateld4911982007-07-31 08:03:26 +00001318 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Andrew Trick4104ed92012-04-10 05:14:37 +00001319
Jay Foad61ea0e42011-06-23 09:09:15 +00001320 // If Succ has any successors with PHI nodes, update them to have
1321 // entries coming from Pred instead of Succ.
1322 Succ->replaceAllUsesWith(Pred);
Andrew Trick4104ed92012-04-10 05:14:37 +00001323
Chris Lattner6fd13622006-02-17 00:31:07 +00001324 // Move all of the successor contents from Succ to Pred.
1325 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1326 Succ->end());
Devang Pateld4911982007-07-31 08:03:26 +00001327 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001328 BI->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001329 RemoveFromWorklist(BI, Worklist);
Andrew Trick4104ed92012-04-10 05:14:37 +00001330
Chris Lattner6fd13622006-02-17 00:31:07 +00001331 // Remove Succ from the loop tree.
1332 LI->removeBlock(Succ);
Devang Pateld4911982007-07-31 08:03:26 +00001333 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001334 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001335 ++NumSimplify;
Chris Lattner66e809a2010-04-20 05:33:18 +00001336 continue;
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001337 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001338
Chris Lattner66e809a2010-04-20 05:33:18 +00001339 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001340 }
1341 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001342}