blob: 710255efec19a83fdadabc2aeb5104ef522b47dc [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
29#define DEBUG_TYPE "loop-unswitch"
30#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/Analysis/CodeMetrics.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Analysis/InstructionSimplify.h"
36#include "llvm/Analysis/LoopInfo.h"
37#include "llvm/Analysis/LoopPass.h"
38#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000039#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/Constants.h"
41#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000042#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Function.h"
44#include "llvm/IR/Instructions.h"
Chris Lattner89762192006-02-09 20:15:48 +000045#include "llvm/Support/CommandLine.h"
Reid Spencer557ab152007-02-05 23:32:05 +000046#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000047#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000048#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Cloning.h"
50#include "llvm/Transforms/Utils/Local.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000051#include <algorithm>
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000052#include <map>
Chris Lattner2826e052006-02-09 19:14:52 +000053#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000054using namespace llvm;
55
Chris Lattner79a42ac2006-12-19 21:40:18 +000056STATISTIC(NumBranches, "Number of branches unswitched");
57STATISTIC(NumSwitches, "Number of switches unswitched");
58STATISTIC(NumSelects , "Number of selects unswitched");
59STATISTIC(NumTrivial , "Number of unswitches that are trivial");
60STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000061STATISTIC(TotalInsts, "Total number of instructions analyzed");
Chris Lattner79a42ac2006-12-19 21:40:18 +000062
Stepan Dyatkovskiy2931a592012-01-16 20:48:04 +000063// The specific value of 100 here was chosen based only on intuition and a
Dan Gohman71ca6522009-10-13 17:50:43 +000064// few specific examples.
Dan Gohmand78c4002008-05-13 00:00:25 +000065static cl::opt<unsigned>
66Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000067 cl::init(100), cl::Hidden);
Andrew Trick4104ed92012-04-10 05:14:37 +000068
Dan Gohmand78c4002008-05-13 00:00:25 +000069namespace {
Andrew Trick4104ed92012-04-10 05:14:37 +000070
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000071 class LUAnalysisCache {
72
73 typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
74 UnswitchedValsMap;
Andrew Trick4104ed92012-04-10 05:14:37 +000075
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000076 typedef UnswitchedValsMap::iterator UnswitchedValsIt;
Andrew Trick4104ed92012-04-10 05:14:37 +000077
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000078 struct LoopProperties {
79 unsigned CanBeUnswitchedCount;
80 unsigned SizeEstimation;
81 UnswitchedValsMap UnswitchedVals;
82 };
Andrew Trick4104ed92012-04-10 05:14:37 +000083
84 // Here we use std::map instead of DenseMap, since we need to keep valid
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000085 // LoopProperties pointer for current loop for better performance.
86 typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
87 typedef LoopPropsMap::iterator LoopPropsMapIt;
Andrew Trick4104ed92012-04-10 05:14:37 +000088
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000089 LoopPropsMap LoopsProperties;
Jakub Staszak27da1232013-08-06 17:03:42 +000090 UnswitchedValsMap *CurLoopInstructions;
91 LoopProperties *CurrentLoopProperties;
Andrew Trick4104ed92012-04-10 05:14:37 +000092
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000093 // Max size of code we can produce on remained iterations.
94 unsigned MaxSize;
Andrew Trick4104ed92012-04-10 05:14:37 +000095
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000096 public:
Andrew Trick4104ed92012-04-10 05:14:37 +000097
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000098 LUAnalysisCache() :
Jakub Staszak27da1232013-08-06 17:03:42 +000099 CurLoopInstructions(0), CurrentLoopProperties(0),
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000100 MaxSize(Threshold)
101 {}
Andrew Trick4104ed92012-04-10 05:14:37 +0000102
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000103 // Analyze loop. Check its size, calculate is it possible to unswitch
104 // it. Returns true if we can unswitch this loop.
Jakub Staszak27da1232013-08-06 17:03:42 +0000105 bool countLoop(const Loop *L, const TargetTransformInfo &TTI);
Andrew Trick4104ed92012-04-10 05:14:37 +0000106
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000107 // Clean all data related to given loop.
Jakub Staszak27da1232013-08-06 17:03:42 +0000108 void forgetLoop(const Loop *L);
Andrew Trick4104ed92012-04-10 05:14:37 +0000109
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000110 // Mark case value as unswitched.
111 // Since SI instruction can be partly unswitched, in order to avoid
112 // extra unswitching in cloned loops keep track all unswitched values.
Jakub Staszak27da1232013-08-06 17:03:42 +0000113 void setUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000114
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000115 // Check was this case value unswitched before or not.
Jakub Staszak27da1232013-08-06 17:03:42 +0000116 bool isUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000117
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000118 // Clone all loop-unswitch related loop properties.
119 // Redistribute unswitching quotas.
120 // Note, that new loop data is stored inside the VMap.
Jakub Staszak27da1232013-08-06 17:03:42 +0000121 void cloneData(const Loop *NewLoop, const Loop *OldLoop,
122 const ValueToValueMapTy &VMap);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000123 };
Andrew Trick4104ed92012-04-10 05:14:37 +0000124
Chris Lattner2dd09db2009-09-02 06:11:42 +0000125 class LoopUnswitch : public LoopPass {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000126 LoopInfo *LI; // Loop information
Devang Patel901a27d2007-03-07 00:26:10 +0000127 LPPassManager *LPM;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000128
Devang Patel901a27d2007-03-07 00:26:10 +0000129 // LoopProcessWorklist - Used to check if second loop needs processing
130 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000131 std::vector<Loop*> LoopProcessWorklist;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000132
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000133 LUAnalysisCache BranchesInfo;
Andrew Trick4104ed92012-04-10 05:14:37 +0000134
Devang Patel506310d2007-06-06 00:21:03 +0000135 bool OptimizeForSize;
Devang Patel7d165e12007-07-30 23:07:10 +0000136 bool redoLoop;
Devang Patela69f9872007-10-05 22:29:34 +0000137
Devang Patele149d4e2008-07-02 01:18:13 +0000138 Loop *currentLoop;
Devang Patela69f9872007-10-05 22:29:34 +0000139 DominatorTree *DT;
Devang Patele149d4e2008-07-02 01:18:13 +0000140 BasicBlock *loopHeader;
141 BasicBlock *loopPreheader;
Andrew Trick4104ed92012-04-10 05:14:37 +0000142
Devang Pateled50fb52008-07-02 01:44:29 +0000143 // LoopBlocks contains all of the basic blocks of the loop, including the
Andrew Trick4104ed92012-04-10 05:14:37 +0000144 // preheader of the loop, the body of the loop, and the exit blocks of the
Devang Pateled50fb52008-07-02 01:44:29 +0000145 // loop, in that order.
146 std::vector<BasicBlock*> LoopBlocks;
147 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
148 std::vector<BasicBlock*> NewBlocks;
Devang Pateleb611dd2008-07-03 17:37:52 +0000149
Chris Lattnerf48f7772004-04-19 18:07:02 +0000150 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000151 static char ID; // Pass ID, replacement for typeid
Andrew Trick4104ed92012-04-10 05:14:37 +0000152 explicit LoopUnswitch(bool Os = false) :
153 LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
Jakub Staszak27da1232013-08-06 17:03:42 +0000154 currentLoop(0), DT(0), loopHeader(0),
155 loopPreheader(0) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000156 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
157 }
Devang Patel09f162c2007-05-01 21:15:47 +0000158
Devang Patel901a27d2007-03-07 00:26:10 +0000159 bool runOnLoop(Loop *L, LPPassManager &LPM);
Devang Patele149d4e2008-07-02 01:18:13 +0000160 bool processCurrentLoop();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000161
162 /// This transformation requires natural loop information & requires that
Chris Lattnerbc1a65a2010-08-29 17:23:19 +0000163 /// loop preheaders be inserted into the CFG.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000164 ///
165 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
166 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +0000167 AU.addPreservedID(LoopSimplifyID);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000168 AU.addRequired<LoopInfo>();
169 AU.addPreserved<LoopInfo>();
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000170 AU.addRequiredID(LCSSAID);
Devang Pateld4911982007-07-31 08:03:26 +0000171 AU.addPreservedID(LCSSAID);
Devang Patelc4dcf822008-07-03 06:48:21 +0000172 AU.addPreserved<DominatorTree>();
Cameron Zwarich99de19b2011-02-11 06:08:28 +0000173 AU.addPreserved<ScalarEvolution>();
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000174 AU.addRequired<TargetTransformInfo>();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000175 }
176
177 private:
Devang Pateld4911982007-07-31 08:03:26 +0000178
Dan Gohman3ddbc242009-09-08 15:45:00 +0000179 virtual void releaseMemory() {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000180 BranchesInfo.forgetLoop(currentLoop);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000181 }
182
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000183 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
184 /// remove it.
185 void RemoveLoopFromWorklist(Loop *L) {
186 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
187 LoopProcessWorklist.end(), L);
188 if (I != LoopProcessWorklist.end())
189 LoopProcessWorklist.erase(I);
190 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000191
Devang Patele149d4e2008-07-02 01:18:13 +0000192 void initLoopData() {
193 loopHeader = currentLoop->getHeader();
194 loopPreheader = currentLoop->getLoopPreheader();
195 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000196
Chris Lattner559c8672008-04-21 00:25:49 +0000197 /// Split all of the edges from inside the loop to their exit blocks.
198 /// Update the appropriate Phi nodes as we do so.
Craig Topperb94011f2013-07-14 04:42:23 +0000199 void SplitExitEdges(Loop *L, const SmallVectorImpl<BasicBlock *> &ExitBlocks);
Devang Patela69f9872007-10-05 22:29:34 +0000200
Devang Patele149d4e2008-07-02 01:18:13 +0000201 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
Chris Lattner29f771b2006-02-18 01:27:45 +0000202 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000203 BasicBlock *ExitBlock);
Andrew Trick4442bfe2012-04-10 05:14:42 +0000204 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000205
206 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
207 Constant *Val, bool isEqual);
Devang Patel3304e462007-06-28 00:49:00 +0000208
209 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
Andrew Trick4104ed92012-04-10 05:14:37 +0000210 BasicBlock *TrueDest,
Devang Patel3304e462007-06-28 00:49:00 +0000211 BasicBlock *FalseDest,
212 Instruction *InsertPt);
213
Devang Pateld4911982007-07-31 08:03:26 +0000214 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000215 void RemoveLoopFromHierarchy(Loop *L);
Devang Patele149d4e2008-07-02 01:18:13 +0000216 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
217 BasicBlock **LoopExit = 0);
218
Chris Lattnerf48f7772004-04-19 18:07:02 +0000219 };
Chris Lattnerf48f7772004-04-19 18:07:02 +0000220}
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000221
222// Analyze loop. Check its size, calculate is it possible to unswitch
223// it. Returns true if we can unswitch this loop.
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000224bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000225
Jakub Staszak27da1232013-08-06 17:03:42 +0000226 LoopPropsMapIt PropsIt;
227 bool Inserted;
228 llvm::tie(PropsIt, Inserted) =
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000229 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
Andrew Trick4104ed92012-04-10 05:14:37 +0000230
Jakub Staszak27da1232013-08-06 17:03:42 +0000231 LoopProperties &Props = PropsIt->second;
Andrew Trick4104ed92012-04-10 05:14:37 +0000232
Jakub Staszak27da1232013-08-06 17:03:42 +0000233 if (Inserted) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000234 // New loop.
235
236 // Limit the number of instructions to avoid causing significant code
237 // expansion, and the number of basic blocks, to avoid loops with
238 // large numbers of branches which cause loop unswitching to go crazy.
239 // This is a very ad-hoc heuristic.
Andrew Trick4104ed92012-04-10 05:14:37 +0000240
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000241 // FIXME: This is overly conservative because it does not take into
242 // consideration code simplification opportunities and code that can
243 // be shared by the resultant unswitched loops.
244 CodeMetrics Metrics;
Jakub Staszak27da1232013-08-06 17:03:42 +0000245 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000246 I != E; ++I)
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000247 Metrics.analyzeBasicBlock(*I, TTI);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000248
249 Props.SizeEstimation = std::min(Metrics.NumInsts, Metrics.NumBlocks * 5);
250 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
251 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
James Molloy4f6fb952012-12-20 16:04:27 +0000252
253 if (Metrics.notDuplicatable) {
254 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak27da1232013-08-06 17:03:42 +0000255 << L->getHeader()->getName() << ", contents cannot be "
256 << "duplicated!\n");
James Molloy4f6fb952012-12-20 16:04:27 +0000257 return false;
258 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000259 }
260
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000261 if (!Props.CanBeUnswitchedCount) {
262 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak27da1232013-08-06 17:03:42 +0000263 << L->getHeader()->getName() << ", cost too high: "
264 << L->getBlocks().size() << "\n");
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000265 return false;
266 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000267
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000268 // Be careful. This links are good only before new loop addition.
269 CurrentLoopProperties = &Props;
270 CurLoopInstructions = &Props.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000271
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000272 return true;
273}
274
275// Clean all data related to given loop.
Jakub Staszak27da1232013-08-06 17:03:42 +0000276void LUAnalysisCache::forgetLoop(const Loop *L) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000277
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000278 LoopPropsMapIt LIt = LoopsProperties.find(L);
279
280 if (LIt != LoopsProperties.end()) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000281 LoopProperties &Props = LIt->second;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000282 MaxSize += Props.CanBeUnswitchedCount * Props.SizeEstimation;
283 LoopsProperties.erase(LIt);
284 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000285
Jakub Staszak27da1232013-08-06 17:03:42 +0000286 CurrentLoopProperties = 0;
287 CurLoopInstructions = 0;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000288}
289
290// Mark case value as unswitched.
291// Since SI instruction can be partly unswitched, in order to avoid
292// extra unswitching in cloned loops keep track all unswitched values.
Jakub Staszak27da1232013-08-06 17:03:42 +0000293void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000294 (*CurLoopInstructions)[SI].insert(V);
295}
296
297// Check was this case value unswitched before or not.
Jakub Staszak27da1232013-08-06 17:03:42 +0000298bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000299 return (*CurLoopInstructions)[SI].count(V);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000300}
301
302// Clone all loop-unswitch related loop properties.
303// Redistribute unswitching quotas.
304// Note, that new loop data is stored inside the VMap.
Jakub Staszak27da1232013-08-06 17:03:42 +0000305void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
306 const ValueToValueMapTy &VMap) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000307
Jakub Staszak27da1232013-08-06 17:03:42 +0000308 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
309 LoopProperties &OldLoopProps = *CurrentLoopProperties;
310 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000311
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000312 // Reallocate "can-be-unswitched quota"
313
314 --OldLoopProps.CanBeUnswitchedCount;
315 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
316 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
317 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
Andrew Trick4104ed92012-04-10 05:14:37 +0000318
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000319 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
Andrew Trick4104ed92012-04-10 05:14:37 +0000320
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000321 // Clone unswitched values info:
322 // for new loop switches we clone info about values that was
323 // already unswitched and has redundant successors.
324 for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000325 const SwitchInst *OldInst = I->first;
326 Value *NewI = VMap.lookup(OldInst);
327 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000328 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
Andrew Trick4104ed92012-04-10 05:14:37 +0000329
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000330 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
331 }
332}
333
Dan Gohmand78c4002008-05-13 00:00:25 +0000334char LoopUnswitch::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000335INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
336 false, false)
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000337INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000338INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
339INITIALIZE_PASS_DEPENDENCY(LoopInfo)
340INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000341INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
342 false, false)
Chris Lattnerf48f7772004-04-19 18:07:02 +0000343
Andrew Trick4104ed92012-04-10 05:14:37 +0000344Pass *llvm::createLoopUnswitchPass(bool Os) {
345 return new LoopUnswitch(Os);
Devang Patel506310d2007-06-06 00:21:03 +0000346}
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000347
348/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
349/// invariant in the loop, or has an invariant piece, return the invariant.
350/// Otherwise, return null.
351static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000352
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000353 // We started analyze new instruction, increment scanned instructions counter.
354 ++TotalInsts;
Andrew Trick4104ed92012-04-10 05:14:37 +0000355
Chris Lattner302240d2010-02-02 02:26:54 +0000356 // We can never unswitch on vector conditions.
Duncan Sands19d0b472010-02-16 11:11:14 +0000357 if (Cond->getType()->isVectorTy())
Chris Lattner302240d2010-02-02 02:26:54 +0000358 return 0;
359
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000360 // Constants should be folded, not unswitched on!
Dan Gohman215742a2008-10-17 00:56:52 +0000361 if (isa<Constant>(Cond)) return 0;
Devang Patel3c723c82007-06-28 00:44:10 +0000362
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000363 // TODO: Handle: br (VARIANT|INVARIANT).
Devang Patelfe57d102008-11-03 19:38:07 +0000364
Dan Gohman4d6149f2009-07-14 01:37:59 +0000365 // Hoist simple values out.
Dan Gohmanc43e4792009-07-15 01:25:43 +0000366 if (L->makeLoopInvariant(Cond, Changed))
Dan Gohman4d6149f2009-07-14 01:37:59 +0000367 return Cond;
Dan Gohman4d6149f2009-07-14 01:37:59 +0000368
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000369 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
370 if (BO->getOpcode() == Instruction::And ||
371 BO->getOpcode() == Instruction::Or) {
372 // If either the left or right side is invariant, we can unswitch on this,
373 // which will cause the branch to go away in one loop and the condition to
374 // simplify in the other one.
375 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
376 return LHS;
377 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
378 return RHS;
379 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000380
Devang Patela69f9872007-10-05 22:29:34 +0000381 return 0;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000382}
383
Devang Patel901a27d2007-03-07 00:26:10 +0000384bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Devang Patel901a27d2007-03-07 00:26:10 +0000385 LI = &getAnalysis<LoopInfo>();
386 LPM = &LPM_Ref;
Duncan Sands5a913d62009-01-28 13:14:17 +0000387 DT = getAnalysisIfAvailable<DominatorTree>();
Devang Patele149d4e2008-07-02 01:18:13 +0000388 currentLoop = L;
Devang Patel40519f02008-09-04 22:43:59 +0000389 Function *F = currentLoop->getHeader()->getParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000390 bool Changed = false;
Devang Patel7d165e12007-07-30 23:07:10 +0000391 do {
Dan Gohman2734ebd2010-03-10 19:38:49 +0000392 assert(currentLoop->isLCSSAForm(*DT));
Devang Patel7d165e12007-07-30 23:07:10 +0000393 redoLoop = false;
Devang Patele149d4e2008-07-02 01:18:13 +0000394 Changed |= processCurrentLoop();
Devang Patel7d165e12007-07-30 23:07:10 +0000395 } while(redoLoop);
396
Devang Patel40519f02008-09-04 22:43:59 +0000397 if (Changed) {
398 // FIXME: Reconstruct dom info, because it is not preserved properly.
399 if (DT)
400 DT->runOnFunction(*F);
Devang Patel40519f02008-09-04 22:43:59 +0000401 }
Devang Patel7d165e12007-07-30 23:07:10 +0000402 return Changed;
403}
404
Andrew Trick4104ed92012-04-10 05:14:37 +0000405/// processCurrentLoop - Do actual work and unswitch loop if possible
Devang Patele149d4e2008-07-02 01:18:13 +0000406/// and profitable.
407bool LoopUnswitch::processCurrentLoop() {
Devang Patel7d165e12007-07-30 23:07:10 +0000408 bool Changed = false;
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000409
410 initLoopData();
Andrew Trick4104ed92012-04-10 05:14:37 +0000411
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000412 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
413 if (!loopPreheader)
414 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000415
Andrew Trick4442bfe2012-04-10 05:14:42 +0000416 // Loops with indirectbr cannot be cloned.
417 if (!currentLoop->isSafeToClone())
418 return false;
419
420 // Without dedicated exits, splitting the exit edge may fail.
421 if (!currentLoop->hasDedicatedExits())
422 return false;
423
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000424 LLVMContext &Context = loopHeader->getContext();
Andrew Trick4104ed92012-04-10 05:14:37 +0000425
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000426 // Probably we reach the quota of branches for this loop. If so
427 // stop unswitching.
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000428 if (!BranchesInfo.countLoop(currentLoop, getAnalysis<TargetTransformInfo>()))
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000429 return false;
Devang Patel7d165e12007-07-30 23:07:10 +0000430
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000431 // Loop over all of the basic blocks in the loop. If we find an interior
432 // block that is branching on a loop-invariant condition, we can unswitch this
433 // loop.
Andrew Trick4104ed92012-04-10 05:14:37 +0000434 for (Loop::block_iterator I = currentLoop->block_begin(),
Chris Lattnerc832c1b2010-04-05 21:18:32 +0000435 E = currentLoop->block_end(); I != E; ++I) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000436 TerminatorInst *TI = (*I)->getTerminator();
437 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
438 // If this isn't branching on an invariant condition, we can't unswitch
439 // it.
440 if (BI->isConditional()) {
441 // See if this, or some part of it, is loop invariant. If so, we can
442 // unswitch on it if we desire.
Andrew Trick4104ed92012-04-10 05:14:37 +0000443 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000444 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000445 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson23a204d2009-07-31 17:39:07 +0000446 ConstantInt::getTrue(Context))) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000447 ++NumBranches;
448 return true;
449 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000450 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000451 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000452 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000453 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000454 unsigned NumCases = SI->getNumCases();
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000455 if (LoopCond && NumCases) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000456 // Find a value to unswitch on:
457 // FIXME: this should chose the most expensive case!
Nick Lewycky61158242011-06-03 06:27:15 +0000458 // FIXME: scan for a case with a non-critical edge?
Jakub Staszak27da1232013-08-06 17:03:42 +0000459 Constant *UnswitchVal = 0;
Andrew Trick4104ed92012-04-10 05:14:37 +0000460
Devang Patel967b84c2007-02-26 19:31:58 +0000461 // Do not process same value again and again.
Chad Rosier3ba90a12011-12-22 21:10:46 +0000462 // At this point we have some cases already unswitched and
463 // some not yet unswitched. Let's find the first not yet unswitched one.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +0000464 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000465 i != e; ++i) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000466 Constant *UnswitchValCandidate = i.getCaseValue();
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000467 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
Chad Rosier3ba90a12011-12-22 21:10:46 +0000468 UnswitchVal = UnswitchValCandidate;
469 break;
470 }
471 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000472
Chad Rosier3ba90a12011-12-22 21:10:46 +0000473 if (!UnswitchVal)
Devang Patel967b84c2007-02-26 19:31:58 +0000474 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000475
Devang Patele149d4e2008-07-02 01:18:13 +0000476 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000477 ++NumSwitches;
478 return true;
479 }
480 }
481 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000482
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000483 // Scan the instructions to check for unswitchable values.
Andrew Trick4104ed92012-04-10 05:14:37 +0000484 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000485 BBI != E; ++BBI)
486 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000487 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000488 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000489 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson23a204d2009-07-31 17:39:07 +0000490 ConstantInt::getTrue(Context))) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000491 ++NumSelects;
492 return true;
493 }
494 }
495 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000496 return Changed;
497}
498
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000499/// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
500/// loop with no side effects (including infinite loops).
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000501///
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000502/// If true, we return true and set ExitBB to the block we
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000503/// exit through.
504///
505static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
506 BasicBlock *&ExitBB,
507 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000508 if (!Visited.insert(BB).second) {
Nick Lewyckyd9d1de42011-12-23 23:49:25 +0000509 // Already visited. Without more analysis, this could indicate an infinite
510 // loop.
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000511 return false;
Jakub Staszak27da1232013-08-06 17:03:42 +0000512 }
513 if (!L->contains(BB)) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000514 // Otherwise, this is a loop exit, this is fine so long as this is the
515 // first exit.
516 if (ExitBB != 0) return false;
517 ExitBB = BB;
Edward O'Callaghan2b8fed12009-11-25 05:38:41 +0000518 return true;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000519 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000520
Chris Lattnerbaddba42006-02-17 06:39:56 +0000521 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000522 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000523 // Check to see if the successor is a trivial loop exit.
524 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
525 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000526 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000527
528 // Okay, everything after this looks good, check to make sure that this block
529 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000530 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Duncan Sands1efabaa2009-05-06 06:49:50 +0000531 if (I->mayHaveSideEffects())
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000532 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000533
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000534 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000535}
536
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000537/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
Andrew Trick4104ed92012-04-10 05:14:37 +0000538/// leads to an exit from the specified loop, and has no side-effects in the
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000539/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000540static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
541 std::set<BasicBlock*> Visited;
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000542 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000543 BasicBlock *ExitBB = 0;
544 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
545 return ExitBB;
546 return 0;
547}
Chris Lattner6e263152006-02-10 02:30:37 +0000548
Chris Lattnered7a67b2006-02-10 01:24:09 +0000549/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
550/// trivial: that is, that the condition controls whether or not the loop does
551/// anything at all. If this is a trivial condition, unswitching produces no
552/// code duplications (equivalently, it produces a simpler loop and a new empty
553/// loop, which gets deleted).
554///
Chris Lattner8a5a3242006-02-22 06:37:14 +0000555/// If this is a trivial condition, return true, otherwise return false. When
556/// returning true, this sets Cond and Val to the condition that controls the
557/// trivial condition: when Cond dynamically equals Val, the loop is known to
558/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
559/// Cond == Val.
560///
Devang Patele149d4e2008-07-02 01:18:13 +0000561bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
562 BasicBlock **LoopExit) {
563 BasicBlock *Header = currentLoop->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000564 TerminatorInst *HeaderTerm = Header->getTerminator();
Owen Anderson47db9412009-07-22 00:24:57 +0000565 LLVMContext &Context = Header->getContext();
Andrew Trick4104ed92012-04-10 05:14:37 +0000566
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000567 BasicBlock *LoopExitBB = 0;
568 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
569 // If the header block doesn't end with a conditional branch on Cond, we
570 // can't handle it.
571 if (!BI->isConditional() || BI->getCondition() != Cond)
572 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000573
574 // Check to see if a successor of the branch is guaranteed to
575 // exit through a unique exit block without having any
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000576 // side-effects. If so, determine the value of Cond that causes it to do
577 // this.
Andrew Trick4104ed92012-04-10 05:14:37 +0000578 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
Devang Patele149d4e2008-07-02 01:18:13 +0000579 BI->getSuccessor(0)))) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000580 if (Val) *Val = ConstantInt::getTrue(Context);
Andrew Trick4104ed92012-04-10 05:14:37 +0000581 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
Devang Patele149d4e2008-07-02 01:18:13 +0000582 BI->getSuccessor(1)))) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000583 if (Val) *Val = ConstantInt::getFalse(Context);
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000584 }
585 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
586 // If this isn't a switch on Cond, we can't handle it.
587 if (SI->getCondition() != Cond) return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000588
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000589 // Check to see if a successor of the switch is guaranteed to go to the
Andrew Trick4104ed92012-04-10 05:14:37 +0000590 // latch block or exit through a one exit block without having any
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000591 // side-effects. If so, determine the value of Cond that causes it to do
Andrew Trick4104ed92012-04-10 05:14:37 +0000592 // this.
Chad Rosier3ba90a12011-12-22 21:10:46 +0000593 // Note that we can't trivially unswitch on the default case or
594 // on already unswitched cases.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +0000595 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000596 i != e; ++i) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000597 BasicBlock *LoopExitCandidate;
Andrew Trick4104ed92012-04-10 05:14:37 +0000598 if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000599 i.getCaseSuccessor()))) {
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000600 // Okay, we found a trivial case, remember the value that is trivial.
Jakub Staszak27da1232013-08-06 17:03:42 +0000601 ConstantInt *CaseVal = i.getCaseValue();
Chad Rosier3ba90a12011-12-22 21:10:46 +0000602
603 // Check that it was not unswitched before, since already unswitched
604 // trivial vals are looks trivial too.
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000605 if (BranchesInfo.isUnswitched(SI, CaseVal))
Chad Rosier3ba90a12011-12-22 21:10:46 +0000606 continue;
607 LoopExitBB = LoopExitCandidate;
608 if (Val) *Val = CaseVal;
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000609 break;
610 }
Chad Rosier3ba90a12011-12-22 21:10:46 +0000611 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000612 }
613
Chris Lattnere5521db2006-02-22 23:55:00 +0000614 // If we didn't find a single unique LoopExit block, or if the loop exit block
615 // contains phi nodes, this isn't trivial.
616 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000617 return false; // Can't handle this.
Andrew Trick4104ed92012-04-10 05:14:37 +0000618
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000619 if (LoopExit) *LoopExit = LoopExitBB;
Andrew Trick4104ed92012-04-10 05:14:37 +0000620
Chris Lattnered7a67b2006-02-10 01:24:09 +0000621 // We already know that nothing uses any scalar values defined inside of this
622 // loop. As such, we just have to check to see if this loop will execute any
623 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000624 // part of the loop that the code *would* execute. We already checked the
625 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000626 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
Duncan Sands1efabaa2009-05-06 06:49:50 +0000627 if (I->mayHaveSideEffects())
Chris Lattner49354172006-02-10 02:01:22 +0000628 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000629 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000630}
631
Devang Patele149d4e2008-07-02 01:18:13 +0000632/// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000633/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
634/// unswitch the loop, reprocess the pieces, then return true.
Chris Lattner302240d2010-02-02 02:26:54 +0000635bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val) {
Dan Gohman72c367f2009-12-09 22:55:01 +0000636 Function *F = loopHeader->getParent();
Evan Chenged66db32010-04-03 02:23:43 +0000637 Constant *CondVal = 0;
638 BasicBlock *ExitBlock = 0;
Bill Wendling712d85a2012-04-30 09:23:48 +0000639
Devang Patele149d4e2008-07-02 01:18:13 +0000640 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
Evan Chenged66db32010-04-03 02:23:43 +0000641 // If the condition is trivial, always unswitch. There is no code growth
642 // for this case.
Devang Patele149d4e2008-07-02 01:18:13 +0000643 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
Evan Chenged66db32010-04-03 02:23:43 +0000644 return true;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000645 }
Devang Patelc4dcf822008-07-03 06:48:21 +0000646
Evan Chenged66db32010-04-03 02:23:43 +0000647 // Check to see if it would be profitable to unswitch current loop.
648
649 // Do not do non-trivial unswitch while optimizing for size.
Bill Wendlingc9b22d72012-10-09 07:45:08 +0000650 if (OptimizeForSize ||
Bill Wendling698e84f2012-12-30 10:32:01 +0000651 F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
652 Attribute::OptimizeForSize))
Evan Chenged66db32010-04-03 02:23:43 +0000653 return false;
654
Andrew Trick4442bfe2012-04-10 05:14:42 +0000655 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
656 return true;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000657}
658
Chris Lattnerf48f7772004-04-19 18:07:02 +0000659/// CloneLoop - Recursively clone the specified loop and all of its children,
660/// mapping the blocks with the specified map.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000661static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000662 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000663 Loop *New = new Loop();
Devang Patel901a27d2007-03-07 00:26:10 +0000664 LPM->insertLoop(New, PL);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000665
666 // Add all of the blocks in L to the new loop.
667 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
668 I != E; ++I)
669 if (LI->getLoopFor(*I) == L)
Owen Andersonb0dd27e2007-11-27 03:43:35 +0000670 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000671
672 // Add all of the subloops to the new loop.
673 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel901a27d2007-03-07 00:26:10 +0000674 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000675
Chris Lattnerf48f7772004-04-19 18:07:02 +0000676 return New;
677}
678
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000679/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
680/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
681/// code immediately before InsertPt.
Devang Patel3304e462007-06-28 00:49:00 +0000682void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
683 BasicBlock *TrueDest,
684 BasicBlock *FalseDest,
685 Instruction *InsertPt) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000686 // Insert a conditional branch on LIC to the two preheaders. The original
687 // code is the true version and the new code is the false version.
688 Value *BranchVal = LIC;
Owen Anderson55f1c092009-08-13 21:58:54 +0000689 if (!isa<ConstantInt>(Val) ||
690 Val->getType() != Type::getInt1Ty(LIC->getContext()))
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000691 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
Owen Anderson23a204d2009-07-31 17:39:07 +0000692 else if (Val != ConstantInt::getTrue(Val->getContext()))
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000693 // We want to enter the new loop when the condition is true.
694 std::swap(TrueDest, FalseDest);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000695
696 // Insert the new branch.
Dan Gohman3ddbc242009-09-08 15:45:00 +0000697 BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
698
699 // If either edge is critical, split it. This helps preserve LoopSimplify
700 // form for enclosing loops.
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000701 SplitCriticalEdge(BI, 0, this, false, false, true);
702 SplitCriticalEdge(BI, 1, this, false, false, true);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000703}
704
Chris Lattnered7a67b2006-02-10 01:24:09 +0000705/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
706/// condition in it (a cond branch from its header block to its latch block,
Andrew Trick4104ed92012-04-10 05:14:37 +0000707/// where the path through the loop that doesn't execute its body has no
Chris Lattnered7a67b2006-02-10 01:24:09 +0000708/// side-effects), unswitch it. This doesn't involve any code duplication, just
709/// moving the conditional branch outside of the loop and updating loop info.
Andrew Trick4104ed92012-04-10 05:14:37 +0000710void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
711 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000712 BasicBlock *ExitBlock) {
David Greened9c355d2010-01-05 01:27:04 +0000713 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000714 << loopHeader->getName() << " [" << L->getBlocks().size()
715 << " blocks] in Function " << L->getHeader()->getParent()->getName()
716 << " on cond: " << *Val << " == " << *Cond << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +0000717
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000718 // First step, split the preheader, so that we know that there is a safe place
Devang Patele149d4e2008-07-02 01:18:13 +0000719 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattnered7a67b2006-02-10 01:24:09 +0000720 // conditional branch on Cond.
Devang Patele149d4e2008-07-02 01:18:13 +0000721 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000722
723 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000724 // to branch to: this is the exit block out of the loop that we should
725 // short-circuit to.
Andrew Trick4104ed92012-04-10 05:14:37 +0000726
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000727 // Split this block now, so that the loop maintains its exit block, and so
728 // that the jump from the preheader can execute the contents of the exit block
729 // without actually branching to it (the exit block should be dominated by the
730 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000731 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Devang Patel12358b42007-07-06 22:03:47 +0000732 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
Andrew Trick4104ed92012-04-10 05:14:37 +0000733
734 // Okay, now we have a position to branch from and a position to branch to,
Chris Lattnered7a67b2006-02-10 01:24:09 +0000735 // insert the new conditional branch.
Andrew Trick4104ed92012-04-10 05:14:37 +0000736 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Devang Patele149d4e2008-07-02 01:18:13 +0000737 loopPreheader->getTerminator());
Devang Patele149d4e2008-07-02 01:18:13 +0000738 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
739 loopPreheader->getTerminator()->eraseFromParent();
Chris Lattnered7a67b2006-02-10 01:24:09 +0000740
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000741 // We need to reprocess this loop, it could be unswitched again.
Devang Patel7d165e12007-07-30 23:07:10 +0000742 redoLoop = true;
Andrew Trick4104ed92012-04-10 05:14:37 +0000743
Chris Lattnered7a67b2006-02-10 01:24:09 +0000744 // Now that we know that the loop is never entered when this condition is a
745 // particular value, rewrite the loop with this info. We know that this will
746 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000747 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000748 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000749}
750
Chris Lattner559c8672008-04-21 00:25:49 +0000751/// SplitExitEdges - Split all of the edges from inside the loop to their exit
752/// blocks. Update the appropriate Phi nodes as we do so.
Andrew Trick4104ed92012-04-10 05:14:37 +0000753void LoopUnswitch::SplitExitEdges(Loop *L,
Craig Topperb94011f2013-07-14 04:42:23 +0000754 const SmallVectorImpl<BasicBlock *> &ExitBlocks){
Devang Patela69f9872007-10-05 22:29:34 +0000755
Chris Lattnered7a67b2006-02-10 01:24:09 +0000756 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000757 BasicBlock *ExitBlock = ExitBlocks[i];
Dan Gohman3ddbc242009-09-08 15:45:00 +0000758 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
759 pred_end(ExitBlock));
Bill Wendling90f90da2011-09-27 00:59:31 +0000760
Nick Lewycky61158242011-06-03 06:27:15 +0000761 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
762 // general, if we call it on all predecessors of all exits then it does.
Bill Wendling90f90da2011-09-27 00:59:31 +0000763 if (!ExitBlock->isLandingPad()) {
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000764 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", this);
Bill Wendling90f90da2011-09-27 00:59:31 +0000765 } else {
766 SmallVector<BasicBlock*, 2> NewBBs;
767 SplitLandingPadPredecessors(ExitBlock, Preds, ".us-lcssa", ".us-lcssa",
768 this, NewBBs);
769 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000770 }
Devang Patele192e3252007-10-03 21:16:08 +0000771}
772
Andrew Trick4104ed92012-04-10 05:14:37 +0000773/// UnswitchNontrivialCondition - We determined that the loop is profitable
774/// to unswitch when LIC equal Val. Split it into loop versions and test the
Devang Patel35747592007-10-03 21:17:43 +0000775/// condition outside of either loop. Return the loops created as Out1/Out2.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000776void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
Devang Patele192e3252007-10-03 21:16:08 +0000777 Loop *L) {
Devang Patele149d4e2008-07-02 01:18:13 +0000778 Function *F = loopHeader->getParent();
David Greened9c355d2010-01-05 01:27:04 +0000779 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000780 << loopHeader->getName() << " [" << L->getBlocks().size()
781 << " blocks] in Function " << F->getName()
782 << " when '" << *Val << "' == " << *LIC << "\n");
Devang Patele192e3252007-10-03 21:16:08 +0000783
Cameron Zwarich99de19b2011-02-11 06:08:28 +0000784 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
785 SE->forgetLoop(L);
786
Devang Pateled50fb52008-07-02 01:44:29 +0000787 LoopBlocks.clear();
788 NewBlocks.clear();
Devang Patele192e3252007-10-03 21:16:08 +0000789
790 // First step, split the preheader and exit blocks, and add these blocks to
791 // the LoopBlocks list.
Devang Patele149d4e2008-07-02 01:18:13 +0000792 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
Devang Patele192e3252007-10-03 21:16:08 +0000793 LoopBlocks.push_back(NewPreheader);
794
795 // We want the loop to come after the preheader, but before the exit blocks.
796 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
797
798 SmallVector<BasicBlock*, 8> ExitBlocks;
799 L->getUniqueExitBlocks(ExitBlocks);
800
801 // Split all of the edges from inside the loop to their exit blocks. Update
802 // the appropriate Phi nodes as we do so.
Devang Pateleb611dd2008-07-03 17:37:52 +0000803 SplitExitEdges(L, ExitBlocks);
Devang Patele192e3252007-10-03 21:16:08 +0000804
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000805 // The exit blocks may have been changed due to edge splitting, recompute.
806 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +0000807 L->getUniqueExitBlocks(ExitBlocks);
808
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000809 // Add exit blocks to the loop blocks.
810 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000811
812 // Next step, clone all of the basic blocks that make up the loop (including
813 // the loop preheader and exit blocks), keeping track of the mapping between
814 // the instructions and blocks.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000815 NewBlocks.reserve(LoopBlocks.size());
Rafael Espindola229e38f2010-10-13 01:36:30 +0000816 ValueToValueMapTy VMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000817 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000818 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
Andrew Trick4104ed92012-04-10 05:14:37 +0000819
Evan Chengba930442010-04-05 21:16:25 +0000820 NewBlocks.push_back(NewBB);
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000821 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
Evan Chengba930442010-04-05 21:16:25 +0000822 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000823 }
824
825 // Splice the newly inserted blocks into the function right before the
826 // original preheader.
Evan Chengba930442010-04-05 21:16:25 +0000827 F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
Chris Lattnerf48f7772004-04-19 18:07:02 +0000828 NewBlocks[0], F->end());
829
830 // Now we create the new Loop object for the versioned loop.
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000831 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000832
833 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
834 // Probably clone more loop-unswitch related loop properties.
835 BranchesInfo.cloneData(NewLoop, L, VMap);
836
Chris Lattnerf1b15162006-02-10 23:26:14 +0000837 Loop *ParentLoop = L->getParentLoop();
838 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000839 // Make sure to add the cloned preheader and exit blocks to the parent loop
840 // as well.
Owen Andersonb0dd27e2007-11-27 03:43:35 +0000841 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
Chris Lattnerf1b15162006-02-10 23:26:14 +0000842 }
Bill Wendling90f90da2011-09-27 00:59:31 +0000843
Chris Lattnerf1b15162006-02-10 23:26:14 +0000844 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000845 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000846 // The new exit block should be in the same loop as the old one.
847 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Owen Andersonb0dd27e2007-11-27 03:43:35 +0000848 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
Andrew Trick4104ed92012-04-10 05:14:37 +0000849
Chris Lattnerf1b15162006-02-10 23:26:14 +0000850 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
851 "Exit block should have been split to have one successor!");
852 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
Devang Pateleb611dd2008-07-03 17:37:52 +0000853
Chris Lattnerf1b15162006-02-10 23:26:14 +0000854 // If the successor of the exit block had PHI nodes, add an entry for
855 // NewExit.
Jakub Staszak27da1232013-08-06 17:03:42 +0000856 for (BasicBlock::iterator I = ExitSucc->begin();
857 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnerf1b15162006-02-10 23:26:14 +0000858 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Rafael Espindola229e38f2010-10-13 01:36:30 +0000859 ValueToValueMapTy::iterator It = VMap.find(V);
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000860 if (It != VMap.end()) V = It->second;
Chris Lattnerf1b15162006-02-10 23:26:14 +0000861 PN->addIncoming(V, NewExit);
862 }
Bill Wendling90f90da2011-09-27 00:59:31 +0000863
864 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000865 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
866 ExitSucc->getFirstInsertionPt());
Bill Wendling90f90da2011-09-27 00:59:31 +0000867
868 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
869 I != E; ++I) {
870 BasicBlock *BB = *I;
871 LandingPadInst *LPI = BB->getLandingPadInst();
872 LPI->replaceAllUsesWith(PN);
873 PN->addIncoming(LPI, BB);
874 }
875 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000876 }
877
878 // Rewrite the code to refer to itself.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +0000879 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
880 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
881 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner43f8d162011-01-08 08:15:20 +0000882 RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Trick4104ed92012-04-10 05:14:37 +0000883
Chris Lattnerf48f7772004-04-19 18:07:02 +0000884 // Rewrite the original preheader to select between versions of the loop.
Devang Patele149d4e2008-07-02 01:18:13 +0000885 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000886 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000887 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000888
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000889 // Emit the new branch that selects between the two versions of this loop.
890 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
Devang Pateld4911982007-07-31 08:03:26 +0000891 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patel83cc3f82007-09-20 23:45:50 +0000892 OldBR->eraseFromParent();
Devang Patela8823282007-08-02 15:25:57 +0000893
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000894 LoopProcessWorklist.push_back(NewLoop);
Devang Patel7d165e12007-07-30 23:07:10 +0000895 redoLoop = true;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000896
Chris Lattner5814d9d92010-04-20 05:09:16 +0000897 // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
898 // deletes the instruction (for example by simplifying a PHI that feeds into
899 // the condition that we're unswitching on), we don't rewrite the second
900 // iteration.
901 WeakVH LICHandle(LIC);
Andrew Trick4104ed92012-04-10 05:14:37 +0000902
Chris Lattnerf48f7772004-04-19 18:07:02 +0000903 // Now we rewrite the original code to know that the condition is true and the
904 // new code to know that the condition is false.
Evan Chengba930442010-04-05 21:16:25 +0000905 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
Devang Pateleb611dd2008-07-03 17:37:52 +0000906
Chris Lattner5814d9d92010-04-20 05:09:16 +0000907 // It's possible that simplifying one loop could cause the other to be
908 // changed to another value or a constant. If its a constant, don't simplify
909 // it.
910 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
911 LICHandle && !isa<Constant>(LICHandle))
912 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000913}
914
Chris Lattner6fd13622006-02-17 00:31:07 +0000915/// RemoveFromWorklist - Remove all instances of I from the worklist vector
916/// specified.
Andrew Trick4104ed92012-04-10 05:14:37 +0000917static void RemoveFromWorklist(Instruction *I,
Chris Lattner6fd13622006-02-17 00:31:07 +0000918 std::vector<Instruction*> &Worklist) {
Jakub Staszak8f46e912012-10-16 19:52:32 +0000919
920 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
921 Worklist.end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000922}
923
924/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
925/// program, replacing all uses with V and update the worklist.
Andrew Trick4104ed92012-04-10 05:14:37 +0000926static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Pateld4911982007-07-31 08:03:26 +0000927 std::vector<Instruction*> &Worklist,
928 Loop *L, LPPassManager *LPM) {
David Greened9c355d2010-01-05 01:27:04 +0000929 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
Chris Lattner6fd13622006-02-17 00:31:07 +0000930
931 // Add uses to the worklist, which may be dead now.
932 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
933 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
934 Worklist.push_back(Use);
935
936 // Add users to the worklist which may be simplified now.
937 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
938 UI != E; ++UI)
939 Worklist.push_back(cast<Instruction>(*UI));
Devang Pateld4911982007-07-31 08:03:26 +0000940 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +0000941 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +0000942 I->replaceAllUsesWith(V);
943 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +0000944 ++NumSimplify;
945}
946
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000947/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
948/// become unwrapped, either because the backedge was deleted, or because the
949/// edge into the header was removed. If the edge into the header from the
950/// latch block was removed, the loop is unwrapped but subloops are still alive,
951/// so they just reparent loops. If the loops are actually dead, they will be
952/// removed later.
953void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel901a27d2007-03-07 00:26:10 +0000954 LPM->deleteLoopFromQueue(L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000955 RemoveLoopFromWorklist(L);
956}
957
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000958// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
959// the value specified by Val in the specified loop, or we know it does NOT have
960// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000961void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000962 Constant *Val,
963 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000964 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Andrew Trick4104ed92012-04-10 05:14:37 +0000965
Chris Lattnerf48f7772004-04-19 18:07:02 +0000966 // FIXME: Support correlated properties, like:
967 // for (...)
968 // if (li1 < li2)
969 // ...
970 // if (li1 > li2)
971 // ...
Andrew Trick4104ed92012-04-10 05:14:37 +0000972
Chris Lattner6e263152006-02-10 02:30:37 +0000973 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
974 // selects, switches.
Chris Lattner6fd13622006-02-17 00:31:07 +0000975 std::vector<Instruction*> Worklist;
Owen Anderson47db9412009-07-22 00:24:57 +0000976 LLVMContext &Context = Val->getContext();
977
Chris Lattner6fd13622006-02-17 00:31:07 +0000978 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
979 // in the loop with the appropriate one directly.
Owen Anderson55f1c092009-08-13 21:58:54 +0000980 if (IsEqual || (isa<ConstantInt>(Val) &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000981 Val->getType()->isIntegerTy(1))) {
Chris Lattner8a5a3242006-02-22 06:37:14 +0000982 Value *Replacement;
983 if (IsEqual)
984 Replacement = Val;
985 else
Andrew Trick4104ed92012-04-10 05:14:37 +0000986 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
Reid Spencercddc9df2007-01-12 04:24:46 +0000987 !cast<ConstantInt>(Val)->getZExtValue());
Andrew Trick4104ed92012-04-10 05:14:37 +0000988
Evan Cheng1b55f562011-05-24 23:12:57 +0000989 for (Value::use_iterator UI = LIC->use_begin(), E = LIC->use_end();
990 UI != E; ++UI) {
Evan Cheng73e6c092011-05-24 23:47:50 +0000991 Instruction *U = dyn_cast<Instruction>(*UI);
992 if (!U || !L->contains(U))
Evan Cheng1b55f562011-05-24 23:12:57 +0000993 continue;
Evan Cheng1b55f562011-05-24 23:12:57 +0000994 Worklist.push_back(U);
995 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000996
Jakub Staszak27da1232013-08-06 17:03:42 +0000997 for (std::vector<Instruction*>::iterator UI = Worklist.begin(),
998 UE = Worklist.end(); UI != UE; ++UI)
Andrew Trick4104ed92012-04-10 05:14:37 +0000999 (*UI)->replaceUsesOfWith(LIC, Replacement);
1000
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001001 SimplifyCode(Worklist, L);
1002 return;
1003 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001004
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001005 // Otherwise, we don't know the precise value of LIC, but we do know that it
1006 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1007 // can. This case occurs when we unswitch switch statements.
Evan Cheng1b55f562011-05-24 23:12:57 +00001008 for (Value::use_iterator UI = LIC->use_begin(), E = LIC->use_end();
1009 UI != E; ++UI) {
Evan Cheng73e6c092011-05-24 23:47:50 +00001010 Instruction *U = dyn_cast<Instruction>(*UI);
1011 if (!U || !L->contains(U))
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001012 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001013
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001014 Worklist.push_back(U);
Chris Lattner6fd13622006-02-17 00:31:07 +00001015
Andrew Trick4104ed92012-04-10 05:14:37 +00001016 // TODO: We could do other simplifications, for example, turning
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001017 // 'icmp eq LIC, Val' -> false.
1018
1019 // If we know that LIC is not Val, use this info to simplify code.
1020 SwitchInst *SI = dyn_cast<SwitchInst>(U);
1021 if (SI == 0 || !isa<ConstantInt>(Val)) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001022
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001023 SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00001024 // Default case is live for multiple values.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001025 if (DeadCase == SI->case_default()) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001026
1027 // Found a dead case value. Don't remove PHI nodes in the
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001028 // successor if they become single-entry, those PHI nodes may
1029 // be in the Users list.
Nick Lewycky61158242011-06-03 06:27:15 +00001030
Evan Cheng1b55f562011-05-24 23:12:57 +00001031 BasicBlock *Switch = SI->getParent();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001032 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
Evan Cheng1b55f562011-05-24 23:12:57 +00001033 BasicBlock *Latch = L->getLoopLatch();
Andrew Trick4104ed92012-04-10 05:14:37 +00001034
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +00001035 BranchesInfo.setUnswitched(SI, Val);
Andrew Trick4104ed92012-04-10 05:14:37 +00001036
Nick Lewycky61158242011-06-03 06:27:15 +00001037 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
Evan Cheng9605a692011-05-25 18:17:13 +00001038 // If the DeadCase successor dominates the loop latch, then the
1039 // transformation isn't safe since it will delete the sole predecessor edge
1040 // to the latch.
1041 if (Latch && DT->dominates(SISucc, Latch))
1042 continue;
Evan Cheng1b55f562011-05-24 23:12:57 +00001043
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001044 // FIXME: This is a hack. We need to keep the successor around
1045 // and hooked up so as to preserve the loop structure, because
1046 // trying to update it is complicated. So instead we preserve the
1047 // loop structure and put the block on a dead code path.
Evan Cheng1b55f562011-05-24 23:12:57 +00001048 SplitEdge(Switch, SISucc, this);
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001049 // Compute the successors instead of relying on the return value
1050 // of SplitEdge, since it may have split the switch successor
1051 // after PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001052 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001053 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1054 // Create an "unreachable" destination.
1055 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1056 Switch->getParent(),
1057 OldSISucc);
1058 new UnreachableInst(Context, Abort);
1059 // Force the new case destination to branch to the "unreachable"
1060 // block while maintaining a (dead) CFG edge to the old block.
1061 NewSISucc->getTerminator()->eraseFromParent();
1062 BranchInst::Create(Abort, OldSISucc,
1063 ConstantInt::getTrue(Context), NewSISucc);
1064 // Release the PHI operands for this edge.
1065 for (BasicBlock::iterator II = NewSISucc->begin();
1066 PHINode *PN = dyn_cast<PHINode>(II); ++II)
1067 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1068 UndefValue::get(PN->getType()));
1069 // Tell the domtree about the new block. We don't fully update the
1070 // domtree here -- instead we force it to do a full recomputation
1071 // after the pass is complete -- but we do need to inform it of
1072 // new blocks.
1073 if (DT)
1074 DT->addNewBlock(Abort, NewSISucc);
Chris Lattner6fd13622006-02-17 00:31:07 +00001075 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001076
Devang Pateld4911982007-07-31 08:03:26 +00001077 SimplifyCode(Worklist, L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001078}
1079
Mike Stumpdeaf5722009-09-09 17:57:16 +00001080/// SimplifyCode - Okay, now that we have simplified some instructions in the
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001081/// loop, walk over it and constant prop, dce, and fold control flow where
1082/// possible. Note that this is effectively a very simple loop-structure-aware
1083/// optimizer. During processing of this loop, L could very well be deleted, so
1084/// it must not be used.
1085///
1086/// FIXME: When the loop optimizer is more mature, separate this out to a new
1087/// pass.
1088///
Devang Pateld4911982007-07-31 08:03:26 +00001089void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001090 while (!Worklist.empty()) {
1091 Instruction *I = Worklist.back();
1092 Worklist.pop_back();
Duncan Sandsbb2cd022010-11-23 20:24:21 +00001093
Chris Lattner6fd13622006-02-17 00:31:07 +00001094 // Simple DCE.
1095 if (isInstructionTriviallyDead(I)) {
David Greened9c355d2010-01-05 01:27:04 +00001096 DEBUG(dbgs() << "Remove dead instruction '" << *I);
Andrew Trick4104ed92012-04-10 05:14:37 +00001097
Chris Lattner6fd13622006-02-17 00:31:07 +00001098 // Add uses to the worklist, which may be dead now.
1099 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1100 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1101 Worklist.push_back(Use);
Devang Pateld4911982007-07-31 08:03:26 +00001102 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001103 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +00001104 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001105 ++NumSimplify;
1106 continue;
1107 }
Duncan Sandsaef146b2010-11-18 19:59:41 +00001108
Chris Lattner66e809a2010-04-20 05:33:18 +00001109 // See if instruction simplification can hack this up. This is common for
1110 // things like "select false, X, Y" after unswitching made the condition be
Peter Collingbourne9a03c732012-05-20 01:32:09 +00001111 // 'false'. TODO: update the domtree properly so we can pass it here.
1112 if (Value *V = SimplifyInstruction(I))
Duncan Sandsaef146b2010-11-18 19:59:41 +00001113 if (LI->replacementPreservesLCSSAForm(I, V)) {
1114 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1115 continue;
1116 }
1117
Chris Lattner6fd13622006-02-17 00:31:07 +00001118 // Special case hacks that appear commonly in unswitched code.
Chris Lattner66e809a2010-04-20 05:33:18 +00001119 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001120 if (BI->isUnconditional()) {
1121 // If BI's parent is the only pred of the successor, fold the two blocks
1122 // together.
1123 BasicBlock *Pred = BI->getParent();
1124 BasicBlock *Succ = BI->getSuccessor(0);
1125 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1126 if (!SinglePred) continue; // Nothing to do.
1127 assert(SinglePred == Pred && "CFG broken");
1128
Andrew Trick4104ed92012-04-10 05:14:37 +00001129 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001130 << Succ->getName() << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +00001131
Chris Lattner6fd13622006-02-17 00:31:07 +00001132 // Resolve any single entry PHI nodes in Succ.
1133 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Pateld4911982007-07-31 08:03:26 +00001134 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Andrew Trick4104ed92012-04-10 05:14:37 +00001135
Jay Foad61ea0e42011-06-23 09:09:15 +00001136 // If Succ has any successors with PHI nodes, update them to have
1137 // entries coming from Pred instead of Succ.
1138 Succ->replaceAllUsesWith(Pred);
Andrew Trick4104ed92012-04-10 05:14:37 +00001139
Chris Lattner6fd13622006-02-17 00:31:07 +00001140 // Move all of the successor contents from Succ to Pred.
1141 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1142 Succ->end());
Devang Pateld4911982007-07-31 08:03:26 +00001143 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001144 BI->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001145 RemoveFromWorklist(BI, Worklist);
Andrew Trick4104ed92012-04-10 05:14:37 +00001146
Chris Lattner6fd13622006-02-17 00:31:07 +00001147 // Remove Succ from the loop tree.
1148 LI->removeBlock(Succ);
Devang Pateld4911982007-07-31 08:03:26 +00001149 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001150 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001151 ++NumSimplify;
Chris Lattner66e809a2010-04-20 05:33:18 +00001152 continue;
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001153 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001154
Chris Lattner66e809a2010-04-20 05:33:18 +00001155 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001156 }
1157 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001158}