blob: 9cd6600f90517e995dd08dab4eba97dc95a1da71 [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
Craig Topper3e4c6972014-03-05 09:10:37 +0000159 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
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 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000165 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000166 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);
Chandler Carruth73523022014-01-13 13:07:17 +0000172 AU.addPreserved<DominatorTreeWrapperPass>();
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
Craig Topper3e4c6972014-03-05 09:10:37 +0000179 void releaseMemory() override {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000180 BranchesInfo.forgetLoop(currentLoop);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000181 }
182
Devang Patele149d4e2008-07-02 01:18:13 +0000183 void initLoopData() {
184 loopHeader = currentLoop->getHeader();
185 loopPreheader = currentLoop->getLoopPreheader();
186 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000187
Chris Lattner559c8672008-04-21 00:25:49 +0000188 /// Split all of the edges from inside the loop to their exit blocks.
189 /// Update the appropriate Phi nodes as we do so.
Craig Topperb94011f2013-07-14 04:42:23 +0000190 void SplitExitEdges(Loop *L, const SmallVectorImpl<BasicBlock *> &ExitBlocks);
Devang Patela69f9872007-10-05 22:29:34 +0000191
Devang Patele149d4e2008-07-02 01:18:13 +0000192 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
Chris Lattner29f771b2006-02-18 01:27:45 +0000193 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000194 BasicBlock *ExitBlock);
Andrew Trick4442bfe2012-04-10 05:14:42 +0000195 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000196
197 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
198 Constant *Val, bool isEqual);
Devang Patel3304e462007-06-28 00:49:00 +0000199
200 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
Andrew Trick4104ed92012-04-10 05:14:37 +0000201 BasicBlock *TrueDest,
Devang Patel3304e462007-06-28 00:49:00 +0000202 BasicBlock *FalseDest,
203 Instruction *InsertPt);
204
Devang Pateld4911982007-07-31 08:03:26 +0000205 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Devang Patele149d4e2008-07-02 01:18:13 +0000206 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
207 BasicBlock **LoopExit = 0);
208
Chris Lattnerf48f7772004-04-19 18:07:02 +0000209 };
Chris Lattnerf48f7772004-04-19 18:07:02 +0000210}
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000211
212// Analyze loop. Check its size, calculate is it possible to unswitch
213// it. Returns true if we can unswitch this loop.
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000214bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000215
Jakub Staszak27da1232013-08-06 17:03:42 +0000216 LoopPropsMapIt PropsIt;
217 bool Inserted;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000218 std::tie(PropsIt, Inserted) =
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000219 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
Andrew Trick4104ed92012-04-10 05:14:37 +0000220
Jakub Staszak27da1232013-08-06 17:03:42 +0000221 LoopProperties &Props = PropsIt->second;
Andrew Trick4104ed92012-04-10 05:14:37 +0000222
Jakub Staszak27da1232013-08-06 17:03:42 +0000223 if (Inserted) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000224 // New loop.
225
226 // Limit the number of instructions to avoid causing significant code
227 // expansion, and the number of basic blocks, to avoid loops with
228 // large numbers of branches which cause loop unswitching to go crazy.
229 // This is a very ad-hoc heuristic.
Andrew Trick4104ed92012-04-10 05:14:37 +0000230
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000231 // FIXME: This is overly conservative because it does not take into
232 // consideration code simplification opportunities and code that can
233 // be shared by the resultant unswitched loops.
234 CodeMetrics Metrics;
Jakub Staszak27da1232013-08-06 17:03:42 +0000235 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000236 I != E; ++I)
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000237 Metrics.analyzeBasicBlock(*I, TTI);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000238
239 Props.SizeEstimation = std::min(Metrics.NumInsts, Metrics.NumBlocks * 5);
240 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
241 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
James Molloy4f6fb952012-12-20 16:04:27 +0000242
243 if (Metrics.notDuplicatable) {
244 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak27da1232013-08-06 17:03:42 +0000245 << L->getHeader()->getName() << ", contents cannot be "
246 << "duplicated!\n");
James Molloy4f6fb952012-12-20 16:04:27 +0000247 return false;
248 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000249 }
250
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000251 if (!Props.CanBeUnswitchedCount) {
252 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak27da1232013-08-06 17:03:42 +0000253 << L->getHeader()->getName() << ", cost too high: "
254 << L->getBlocks().size() << "\n");
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000255 return false;
256 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000257
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000258 // Be careful. This links are good only before new loop addition.
259 CurrentLoopProperties = &Props;
260 CurLoopInstructions = &Props.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000261
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000262 return true;
263}
264
265// Clean all data related to given loop.
Jakub Staszak27da1232013-08-06 17:03:42 +0000266void LUAnalysisCache::forgetLoop(const Loop *L) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000267
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000268 LoopPropsMapIt LIt = LoopsProperties.find(L);
269
270 if (LIt != LoopsProperties.end()) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000271 LoopProperties &Props = LIt->second;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000272 MaxSize += Props.CanBeUnswitchedCount * Props.SizeEstimation;
273 LoopsProperties.erase(LIt);
274 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000275
Jakub Staszak27da1232013-08-06 17:03:42 +0000276 CurrentLoopProperties = 0;
277 CurLoopInstructions = 0;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000278}
279
280// Mark case value as unswitched.
281// Since SI instruction can be partly unswitched, in order to avoid
282// extra unswitching in cloned loops keep track all unswitched values.
Jakub Staszak27da1232013-08-06 17:03:42 +0000283void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000284 (*CurLoopInstructions)[SI].insert(V);
285}
286
287// Check was this case value unswitched before or not.
Jakub Staszak27da1232013-08-06 17:03:42 +0000288bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000289 return (*CurLoopInstructions)[SI].count(V);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000290}
291
292// Clone all loop-unswitch related loop properties.
293// Redistribute unswitching quotas.
294// Note, that new loop data is stored inside the VMap.
Jakub Staszak27da1232013-08-06 17:03:42 +0000295void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
296 const ValueToValueMapTy &VMap) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000297
Jakub Staszak27da1232013-08-06 17:03:42 +0000298 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
299 LoopProperties &OldLoopProps = *CurrentLoopProperties;
300 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000301
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000302 // Reallocate "can-be-unswitched quota"
303
304 --OldLoopProps.CanBeUnswitchedCount;
305 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
306 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
307 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
Andrew Trick4104ed92012-04-10 05:14:37 +0000308
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000309 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
Andrew Trick4104ed92012-04-10 05:14:37 +0000310
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000311 // Clone unswitched values info:
312 // for new loop switches we clone info about values that was
313 // already unswitched and has redundant successors.
314 for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000315 const SwitchInst *OldInst = I->first;
316 Value *NewI = VMap.lookup(OldInst);
317 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000318 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
Andrew Trick4104ed92012-04-10 05:14:37 +0000319
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000320 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
321 }
322}
323
Dan Gohmand78c4002008-05-13 00:00:25 +0000324char LoopUnswitch::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000325INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
326 false, false)
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000327INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000328INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
329INITIALIZE_PASS_DEPENDENCY(LoopInfo)
330INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000331INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
332 false, false)
Chris Lattnerf48f7772004-04-19 18:07:02 +0000333
Andrew Trick4104ed92012-04-10 05:14:37 +0000334Pass *llvm::createLoopUnswitchPass(bool Os) {
335 return new LoopUnswitch(Os);
Devang Patel506310d2007-06-06 00:21:03 +0000336}
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000337
338/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
339/// invariant in the loop, or has an invariant piece, return the invariant.
340/// Otherwise, return null.
341static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000342
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000343 // We started analyze new instruction, increment scanned instructions counter.
344 ++TotalInsts;
Andrew Trick4104ed92012-04-10 05:14:37 +0000345
Chris Lattner302240d2010-02-02 02:26:54 +0000346 // We can never unswitch on vector conditions.
Duncan Sands19d0b472010-02-16 11:11:14 +0000347 if (Cond->getType()->isVectorTy())
Chris Lattner302240d2010-02-02 02:26:54 +0000348 return 0;
349
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000350 // Constants should be folded, not unswitched on!
Dan Gohman215742a2008-10-17 00:56:52 +0000351 if (isa<Constant>(Cond)) return 0;
Devang Patel3c723c82007-06-28 00:44:10 +0000352
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000353 // TODO: Handle: br (VARIANT|INVARIANT).
Devang Patelfe57d102008-11-03 19:38:07 +0000354
Dan Gohman4d6149f2009-07-14 01:37:59 +0000355 // Hoist simple values out.
Dan Gohmanc43e4792009-07-15 01:25:43 +0000356 if (L->makeLoopInvariant(Cond, Changed))
Dan Gohman4d6149f2009-07-14 01:37:59 +0000357 return Cond;
Dan Gohman4d6149f2009-07-14 01:37:59 +0000358
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000359 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
360 if (BO->getOpcode() == Instruction::And ||
361 BO->getOpcode() == Instruction::Or) {
362 // If either the left or right side is invariant, we can unswitch on this,
363 // which will cause the branch to go away in one loop and the condition to
364 // simplify in the other one.
365 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
366 return LHS;
367 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
368 return RHS;
369 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000370
Devang Patela69f9872007-10-05 22:29:34 +0000371 return 0;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000372}
373
Devang Patel901a27d2007-03-07 00:26:10 +0000374bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000375 if (skipOptnoneFunction(L))
376 return false;
377
Devang Patel901a27d2007-03-07 00:26:10 +0000378 LI = &getAnalysis<LoopInfo>();
379 LPM = &LPM_Ref;
Chandler Carruth73523022014-01-13 13:07:17 +0000380 DominatorTreeWrapperPass *DTWP =
381 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
382 DT = DTWP ? &DTWP->getDomTree() : 0;
Devang Patele149d4e2008-07-02 01:18:13 +0000383 currentLoop = L;
Devang Patel40519f02008-09-04 22:43:59 +0000384 Function *F = currentLoop->getHeader()->getParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000385 bool Changed = false;
Devang Patel7d165e12007-07-30 23:07:10 +0000386 do {
Dan Gohman2734ebd2010-03-10 19:38:49 +0000387 assert(currentLoop->isLCSSAForm(*DT));
Devang Patel7d165e12007-07-30 23:07:10 +0000388 redoLoop = false;
Devang Patele149d4e2008-07-02 01:18:13 +0000389 Changed |= processCurrentLoop();
Devang Patel7d165e12007-07-30 23:07:10 +0000390 } while(redoLoop);
391
Devang Patel40519f02008-09-04 22:43:59 +0000392 if (Changed) {
393 // FIXME: Reconstruct dom info, because it is not preserved properly.
394 if (DT)
Chandler Carruth73523022014-01-13 13:07:17 +0000395 DT->recalculate(*F);
Devang Patel40519f02008-09-04 22:43:59 +0000396 }
Devang Patel7d165e12007-07-30 23:07:10 +0000397 return Changed;
398}
399
Andrew Trick4104ed92012-04-10 05:14:37 +0000400/// processCurrentLoop - Do actual work and unswitch loop if possible
Devang Patele149d4e2008-07-02 01:18:13 +0000401/// and profitable.
402bool LoopUnswitch::processCurrentLoop() {
Devang Patel7d165e12007-07-30 23:07:10 +0000403 bool Changed = false;
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000404
405 initLoopData();
Andrew Trick4104ed92012-04-10 05:14:37 +0000406
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000407 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
408 if (!loopPreheader)
409 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000410
Andrew Trick4442bfe2012-04-10 05:14:42 +0000411 // Loops with indirectbr cannot be cloned.
412 if (!currentLoop->isSafeToClone())
413 return false;
414
415 // Without dedicated exits, splitting the exit edge may fail.
416 if (!currentLoop->hasDedicatedExits())
417 return false;
418
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000419 LLVMContext &Context = loopHeader->getContext();
Andrew Trick4104ed92012-04-10 05:14:37 +0000420
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000421 // Probably we reach the quota of branches for this loop. If so
422 // stop unswitching.
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000423 if (!BranchesInfo.countLoop(currentLoop, getAnalysis<TargetTransformInfo>()))
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000424 return false;
Devang Patel7d165e12007-07-30 23:07:10 +0000425
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000426 // Loop over all of the basic blocks in the loop. If we find an interior
427 // block that is branching on a loop-invariant condition, we can unswitch this
428 // loop.
Andrew Trick4104ed92012-04-10 05:14:37 +0000429 for (Loop::block_iterator I = currentLoop->block_begin(),
Chris Lattnerc832c1b2010-04-05 21:18:32 +0000430 E = currentLoop->block_end(); I != E; ++I) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000431 TerminatorInst *TI = (*I)->getTerminator();
432 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
433 // If this isn't branching on an invariant condition, we can't unswitch
434 // it.
435 if (BI->isConditional()) {
436 // See if this, or some part of it, is loop invariant. If so, we can
437 // unswitch on it if we desire.
Andrew Trick4104ed92012-04-10 05:14:37 +0000438 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000439 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000440 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson23a204d2009-07-31 17:39:07 +0000441 ConstantInt::getTrue(Context))) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000442 ++NumBranches;
443 return true;
444 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000445 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000446 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000447 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000448 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000449 unsigned NumCases = SI->getNumCases();
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000450 if (LoopCond && NumCases) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000451 // Find a value to unswitch on:
452 // FIXME: this should chose the most expensive case!
Nick Lewycky61158242011-06-03 06:27:15 +0000453 // FIXME: scan for a case with a non-critical edge?
Jakub Staszak27da1232013-08-06 17:03:42 +0000454 Constant *UnswitchVal = 0;
Andrew Trick4104ed92012-04-10 05:14:37 +0000455
Devang Patel967b84c2007-02-26 19:31:58 +0000456 // Do not process same value again and again.
Chad Rosier3ba90a12011-12-22 21:10:46 +0000457 // At this point we have some cases already unswitched and
458 // some not yet unswitched. Let's find the first not yet unswitched one.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +0000459 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000460 i != e; ++i) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000461 Constant *UnswitchValCandidate = i.getCaseValue();
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000462 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
Chad Rosier3ba90a12011-12-22 21:10:46 +0000463 UnswitchVal = UnswitchValCandidate;
464 break;
465 }
466 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000467
Chad Rosier3ba90a12011-12-22 21:10:46 +0000468 if (!UnswitchVal)
Devang Patel967b84c2007-02-26 19:31:58 +0000469 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000470
Devang Patele149d4e2008-07-02 01:18:13 +0000471 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000472 ++NumSwitches;
473 return true;
474 }
475 }
476 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000477
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000478 // Scan the instructions to check for unswitchable values.
Andrew Trick4104ed92012-04-10 05:14:37 +0000479 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000480 BBI != E; ++BBI)
481 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000482 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000483 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000484 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson23a204d2009-07-31 17:39:07 +0000485 ConstantInt::getTrue(Context))) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000486 ++NumSelects;
487 return true;
488 }
489 }
490 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000491 return Changed;
492}
493
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000494/// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
495/// loop with no side effects (including infinite loops).
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000496///
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000497/// If true, we return true and set ExitBB to the block we
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000498/// exit through.
499///
500static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
501 BasicBlock *&ExitBB,
502 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000503 if (!Visited.insert(BB).second) {
Nick Lewyckyd9d1de42011-12-23 23:49:25 +0000504 // Already visited. Without more analysis, this could indicate an infinite
505 // loop.
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000506 return false;
Jakub Staszak27da1232013-08-06 17:03:42 +0000507 }
508 if (!L->contains(BB)) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000509 // Otherwise, this is a loop exit, this is fine so long as this is the
510 // first exit.
511 if (ExitBB != 0) return false;
512 ExitBB = BB;
Edward O'Callaghan2b8fed12009-11-25 05:38:41 +0000513 return true;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000514 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000515
Chris Lattnerbaddba42006-02-17 06:39:56 +0000516 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000517 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000518 // Check to see if the successor is a trivial loop exit.
519 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
520 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000521 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000522
523 // Okay, everything after this looks good, check to make sure that this block
524 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000525 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Duncan Sands1efabaa2009-05-06 06:49:50 +0000526 if (I->mayHaveSideEffects())
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000527 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000528
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000529 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000530}
531
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000532/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
Andrew Trick4104ed92012-04-10 05:14:37 +0000533/// leads to an exit from the specified loop, and has no side-effects in the
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000534/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000535static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
536 std::set<BasicBlock*> Visited;
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000537 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000538 BasicBlock *ExitBB = 0;
539 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
540 return ExitBB;
541 return 0;
542}
Chris Lattner6e263152006-02-10 02:30:37 +0000543
Chris Lattnered7a67b2006-02-10 01:24:09 +0000544/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
545/// trivial: that is, that the condition controls whether or not the loop does
546/// anything at all. If this is a trivial condition, unswitching produces no
547/// code duplications (equivalently, it produces a simpler loop and a new empty
548/// loop, which gets deleted).
549///
Chris Lattner8a5a3242006-02-22 06:37:14 +0000550/// If this is a trivial condition, return true, otherwise return false. When
551/// returning true, this sets Cond and Val to the condition that controls the
552/// trivial condition: when Cond dynamically equals Val, the loop is known to
553/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
554/// Cond == Val.
555///
Devang Patele149d4e2008-07-02 01:18:13 +0000556bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
557 BasicBlock **LoopExit) {
558 BasicBlock *Header = currentLoop->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000559 TerminatorInst *HeaderTerm = Header->getTerminator();
Owen Anderson47db9412009-07-22 00:24:57 +0000560 LLVMContext &Context = Header->getContext();
Andrew Trick4104ed92012-04-10 05:14:37 +0000561
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000562 BasicBlock *LoopExitBB = 0;
563 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
564 // If the header block doesn't end with a conditional branch on Cond, we
565 // can't handle it.
566 if (!BI->isConditional() || BI->getCondition() != Cond)
567 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000568
569 // Check to see if a successor of the branch is guaranteed to
570 // exit through a unique exit block without having any
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000571 // side-effects. If so, determine the value of Cond that causes it to do
572 // this.
Andrew Trick4104ed92012-04-10 05:14:37 +0000573 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
Devang Patele149d4e2008-07-02 01:18:13 +0000574 BI->getSuccessor(0)))) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000575 if (Val) *Val = ConstantInt::getTrue(Context);
Andrew Trick4104ed92012-04-10 05:14:37 +0000576 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
Devang Patele149d4e2008-07-02 01:18:13 +0000577 BI->getSuccessor(1)))) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000578 if (Val) *Val = ConstantInt::getFalse(Context);
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000579 }
580 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
581 // If this isn't a switch on Cond, we can't handle it.
582 if (SI->getCondition() != Cond) return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000583
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000584 // Check to see if a successor of the switch is guaranteed to go to the
Andrew Trick4104ed92012-04-10 05:14:37 +0000585 // latch block or exit through a one exit block without having any
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000586 // side-effects. If so, determine the value of Cond that causes it to do
Andrew Trick4104ed92012-04-10 05:14:37 +0000587 // this.
Chad Rosier3ba90a12011-12-22 21:10:46 +0000588 // Note that we can't trivially unswitch on the default case or
589 // on already unswitched cases.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +0000590 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000591 i != e; ++i) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000592 BasicBlock *LoopExitCandidate;
Andrew Trick4104ed92012-04-10 05:14:37 +0000593 if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000594 i.getCaseSuccessor()))) {
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000595 // Okay, we found a trivial case, remember the value that is trivial.
Jakub Staszak27da1232013-08-06 17:03:42 +0000596 ConstantInt *CaseVal = i.getCaseValue();
Chad Rosier3ba90a12011-12-22 21:10:46 +0000597
598 // Check that it was not unswitched before, since already unswitched
599 // trivial vals are looks trivial too.
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000600 if (BranchesInfo.isUnswitched(SI, CaseVal))
Chad Rosier3ba90a12011-12-22 21:10:46 +0000601 continue;
602 LoopExitBB = LoopExitCandidate;
603 if (Val) *Val = CaseVal;
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000604 break;
605 }
Chad Rosier3ba90a12011-12-22 21:10:46 +0000606 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000607 }
608
Chris Lattnere5521db2006-02-22 23:55:00 +0000609 // If we didn't find a single unique LoopExit block, or if the loop exit block
610 // contains phi nodes, this isn't trivial.
611 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000612 return false; // Can't handle this.
Andrew Trick4104ed92012-04-10 05:14:37 +0000613
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000614 if (LoopExit) *LoopExit = LoopExitBB;
Andrew Trick4104ed92012-04-10 05:14:37 +0000615
Chris Lattnered7a67b2006-02-10 01:24:09 +0000616 // We already know that nothing uses any scalar values defined inside of this
617 // loop. As such, we just have to check to see if this loop will execute any
618 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000619 // part of the loop that the code *would* execute. We already checked the
620 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000621 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
Duncan Sands1efabaa2009-05-06 06:49:50 +0000622 if (I->mayHaveSideEffects())
Chris Lattner49354172006-02-10 02:01:22 +0000623 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000624 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000625}
626
Devang Patele149d4e2008-07-02 01:18:13 +0000627/// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000628/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
629/// unswitch the loop, reprocess the pieces, then return true.
Chris Lattner302240d2010-02-02 02:26:54 +0000630bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val) {
Dan Gohman72c367f2009-12-09 22:55:01 +0000631 Function *F = loopHeader->getParent();
Evan Chenged66db32010-04-03 02:23:43 +0000632 Constant *CondVal = 0;
633 BasicBlock *ExitBlock = 0;
Bill Wendling712d85a2012-04-30 09:23:48 +0000634
Devang Patele149d4e2008-07-02 01:18:13 +0000635 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
Evan Chenged66db32010-04-03 02:23:43 +0000636 // If the condition is trivial, always unswitch. There is no code growth
637 // for this case.
Devang Patele149d4e2008-07-02 01:18:13 +0000638 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
Evan Chenged66db32010-04-03 02:23:43 +0000639 return true;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000640 }
Devang Patelc4dcf822008-07-03 06:48:21 +0000641
Evan Chenged66db32010-04-03 02:23:43 +0000642 // Check to see if it would be profitable to unswitch current loop.
643
644 // Do not do non-trivial unswitch while optimizing for size.
Bill Wendlingc9b22d72012-10-09 07:45:08 +0000645 if (OptimizeForSize ||
Bill Wendling698e84f2012-12-30 10:32:01 +0000646 F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
647 Attribute::OptimizeForSize))
Evan Chenged66db32010-04-03 02:23:43 +0000648 return false;
649
Andrew Trick4442bfe2012-04-10 05:14:42 +0000650 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
651 return true;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000652}
653
Chris Lattnerf48f7772004-04-19 18:07:02 +0000654/// CloneLoop - Recursively clone the specified loop and all of its children,
655/// mapping the blocks with the specified map.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000656static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000657 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000658 Loop *New = new Loop();
Devang Patel901a27d2007-03-07 00:26:10 +0000659 LPM->insertLoop(New, PL);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000660
661 // Add all of the blocks in L to the new loop.
662 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
663 I != E; ++I)
664 if (LI->getLoopFor(*I) == L)
Owen Andersonb0dd27e2007-11-27 03:43:35 +0000665 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000666
667 // Add all of the subloops to the new loop.
668 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel901a27d2007-03-07 00:26:10 +0000669 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000670
Chris Lattnerf48f7772004-04-19 18:07:02 +0000671 return New;
672}
673
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000674/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
675/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
676/// code immediately before InsertPt.
Devang Patel3304e462007-06-28 00:49:00 +0000677void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
678 BasicBlock *TrueDest,
679 BasicBlock *FalseDest,
680 Instruction *InsertPt) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000681 // Insert a conditional branch on LIC to the two preheaders. The original
682 // code is the true version and the new code is the false version.
683 Value *BranchVal = LIC;
Owen Anderson55f1c092009-08-13 21:58:54 +0000684 if (!isa<ConstantInt>(Val) ||
685 Val->getType() != Type::getInt1Ty(LIC->getContext()))
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000686 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
Owen Anderson23a204d2009-07-31 17:39:07 +0000687 else if (Val != ConstantInt::getTrue(Val->getContext()))
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000688 // We want to enter the new loop when the condition is true.
689 std::swap(TrueDest, FalseDest);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000690
691 // Insert the new branch.
Dan Gohman3ddbc242009-09-08 15:45:00 +0000692 BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
693
694 // If either edge is critical, split it. This helps preserve LoopSimplify
695 // form for enclosing loops.
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000696 SplitCriticalEdge(BI, 0, this, false, false, true);
697 SplitCriticalEdge(BI, 1, this, false, false, true);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000698}
699
Chris Lattnered7a67b2006-02-10 01:24:09 +0000700/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
701/// condition in it (a cond branch from its header block to its latch block,
Andrew Trick4104ed92012-04-10 05:14:37 +0000702/// where the path through the loop that doesn't execute its body has no
Chris Lattnered7a67b2006-02-10 01:24:09 +0000703/// side-effects), unswitch it. This doesn't involve any code duplication, just
704/// moving the conditional branch outside of the loop and updating loop info.
Andrew Trick4104ed92012-04-10 05:14:37 +0000705void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
706 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000707 BasicBlock *ExitBlock) {
David Greened9c355d2010-01-05 01:27:04 +0000708 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000709 << loopHeader->getName() << " [" << L->getBlocks().size()
710 << " blocks] in Function " << L->getHeader()->getParent()->getName()
711 << " on cond: " << *Val << " == " << *Cond << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +0000712
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000713 // First step, split the preheader, so that we know that there is a safe place
Devang Patele149d4e2008-07-02 01:18:13 +0000714 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattnered7a67b2006-02-10 01:24:09 +0000715 // conditional branch on Cond.
Devang Patele149d4e2008-07-02 01:18:13 +0000716 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000717
718 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000719 // to branch to: this is the exit block out of the loop that we should
720 // short-circuit to.
Andrew Trick4104ed92012-04-10 05:14:37 +0000721
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000722 // Split this block now, so that the loop maintains its exit block, and so
723 // that the jump from the preheader can execute the contents of the exit block
724 // without actually branching to it (the exit block should be dominated by the
725 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000726 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Devang Patel12358b42007-07-06 22:03:47 +0000727 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
Andrew Trick4104ed92012-04-10 05:14:37 +0000728
729 // Okay, now we have a position to branch from and a position to branch to,
Chris Lattnered7a67b2006-02-10 01:24:09 +0000730 // insert the new conditional branch.
Andrew Trick4104ed92012-04-10 05:14:37 +0000731 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Devang Patele149d4e2008-07-02 01:18:13 +0000732 loopPreheader->getTerminator());
Devang Patele149d4e2008-07-02 01:18:13 +0000733 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
734 loopPreheader->getTerminator()->eraseFromParent();
Chris Lattnered7a67b2006-02-10 01:24:09 +0000735
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000736 // We need to reprocess this loop, it could be unswitched again.
Devang Patel7d165e12007-07-30 23:07:10 +0000737 redoLoop = true;
Andrew Trick4104ed92012-04-10 05:14:37 +0000738
Chris Lattnered7a67b2006-02-10 01:24:09 +0000739 // Now that we know that the loop is never entered when this condition is a
740 // particular value, rewrite the loop with this info. We know that this will
741 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000742 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000743 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000744}
745
Chris Lattner559c8672008-04-21 00:25:49 +0000746/// SplitExitEdges - Split all of the edges from inside the loop to their exit
747/// blocks. Update the appropriate Phi nodes as we do so.
Andrew Trick4104ed92012-04-10 05:14:37 +0000748void LoopUnswitch::SplitExitEdges(Loop *L,
Craig Topperb94011f2013-07-14 04:42:23 +0000749 const SmallVectorImpl<BasicBlock *> &ExitBlocks){
Devang Patela69f9872007-10-05 22:29:34 +0000750
Chris Lattnered7a67b2006-02-10 01:24:09 +0000751 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000752 BasicBlock *ExitBlock = ExitBlocks[i];
Dan Gohman3ddbc242009-09-08 15:45:00 +0000753 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
754 pred_end(ExitBlock));
Bill Wendling90f90da2011-09-27 00:59:31 +0000755
Nick Lewycky61158242011-06-03 06:27:15 +0000756 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
757 // general, if we call it on all predecessors of all exits then it does.
Bill Wendling90f90da2011-09-27 00:59:31 +0000758 if (!ExitBlock->isLandingPad()) {
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000759 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", this);
Bill Wendling90f90da2011-09-27 00:59:31 +0000760 } else {
761 SmallVector<BasicBlock*, 2> NewBBs;
762 SplitLandingPadPredecessors(ExitBlock, Preds, ".us-lcssa", ".us-lcssa",
763 this, NewBBs);
764 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000765 }
Devang Patele192e3252007-10-03 21:16:08 +0000766}
767
Andrew Trick4104ed92012-04-10 05:14:37 +0000768/// UnswitchNontrivialCondition - We determined that the loop is profitable
769/// to unswitch when LIC equal Val. Split it into loop versions and test the
Devang Patel35747592007-10-03 21:17:43 +0000770/// condition outside of either loop. Return the loops created as Out1/Out2.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000771void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
Devang Patele192e3252007-10-03 21:16:08 +0000772 Loop *L) {
Devang Patele149d4e2008-07-02 01:18:13 +0000773 Function *F = loopHeader->getParent();
David Greened9c355d2010-01-05 01:27:04 +0000774 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000775 << loopHeader->getName() << " [" << L->getBlocks().size()
776 << " blocks] in Function " << F->getName()
777 << " when '" << *Val << "' == " << *LIC << "\n");
Devang Patele192e3252007-10-03 21:16:08 +0000778
Cameron Zwarich99de19b2011-02-11 06:08:28 +0000779 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
780 SE->forgetLoop(L);
781
Devang Pateled50fb52008-07-02 01:44:29 +0000782 LoopBlocks.clear();
783 NewBlocks.clear();
Devang Patele192e3252007-10-03 21:16:08 +0000784
785 // First step, split the preheader and exit blocks, and add these blocks to
786 // the LoopBlocks list.
Devang Patele149d4e2008-07-02 01:18:13 +0000787 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
Devang Patele192e3252007-10-03 21:16:08 +0000788 LoopBlocks.push_back(NewPreheader);
789
790 // We want the loop to come after the preheader, but before the exit blocks.
791 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
792
793 SmallVector<BasicBlock*, 8> ExitBlocks;
794 L->getUniqueExitBlocks(ExitBlocks);
795
796 // Split all of the edges from inside the loop to their exit blocks. Update
797 // the appropriate Phi nodes as we do so.
Devang Pateleb611dd2008-07-03 17:37:52 +0000798 SplitExitEdges(L, ExitBlocks);
Devang Patele192e3252007-10-03 21:16:08 +0000799
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000800 // The exit blocks may have been changed due to edge splitting, recompute.
801 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +0000802 L->getUniqueExitBlocks(ExitBlocks);
803
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000804 // Add exit blocks to the loop blocks.
805 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000806
807 // Next step, clone all of the basic blocks that make up the loop (including
808 // the loop preheader and exit blocks), keeping track of the mapping between
809 // the instructions and blocks.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000810 NewBlocks.reserve(LoopBlocks.size());
Rafael Espindola229e38f2010-10-13 01:36:30 +0000811 ValueToValueMapTy VMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000812 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000813 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
Andrew Trick4104ed92012-04-10 05:14:37 +0000814
Evan Chengba930442010-04-05 21:16:25 +0000815 NewBlocks.push_back(NewBB);
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000816 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
Evan Chengba930442010-04-05 21:16:25 +0000817 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000818 }
819
820 // Splice the newly inserted blocks into the function right before the
821 // original preheader.
Evan Chengba930442010-04-05 21:16:25 +0000822 F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
Chris Lattnerf48f7772004-04-19 18:07:02 +0000823 NewBlocks[0], F->end());
824
825 // Now we create the new Loop object for the versioned loop.
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000826 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000827
828 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
829 // Probably clone more loop-unswitch related loop properties.
830 BranchesInfo.cloneData(NewLoop, L, VMap);
831
Chris Lattnerf1b15162006-02-10 23:26:14 +0000832 Loop *ParentLoop = L->getParentLoop();
833 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000834 // Make sure to add the cloned preheader and exit blocks to the parent loop
835 // as well.
Owen Andersonb0dd27e2007-11-27 03:43:35 +0000836 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
Chris Lattnerf1b15162006-02-10 23:26:14 +0000837 }
Bill Wendling90f90da2011-09-27 00:59:31 +0000838
Chris Lattnerf1b15162006-02-10 23:26:14 +0000839 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000840 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000841 // The new exit block should be in the same loop as the old one.
842 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Owen Andersonb0dd27e2007-11-27 03:43:35 +0000843 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
Andrew Trick4104ed92012-04-10 05:14:37 +0000844
Chris Lattnerf1b15162006-02-10 23:26:14 +0000845 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
846 "Exit block should have been split to have one successor!");
847 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
Devang Pateleb611dd2008-07-03 17:37:52 +0000848
Chris Lattnerf1b15162006-02-10 23:26:14 +0000849 // If the successor of the exit block had PHI nodes, add an entry for
850 // NewExit.
Jakub Staszak27da1232013-08-06 17:03:42 +0000851 for (BasicBlock::iterator I = ExitSucc->begin();
852 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnerf1b15162006-02-10 23:26:14 +0000853 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Rafael Espindola229e38f2010-10-13 01:36:30 +0000854 ValueToValueMapTy::iterator It = VMap.find(V);
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000855 if (It != VMap.end()) V = It->second;
Chris Lattnerf1b15162006-02-10 23:26:14 +0000856 PN->addIncoming(V, NewExit);
857 }
Bill Wendling90f90da2011-09-27 00:59:31 +0000858
859 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000860 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
861 ExitSucc->getFirstInsertionPt());
Bill Wendling90f90da2011-09-27 00:59:31 +0000862
863 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
864 I != E; ++I) {
865 BasicBlock *BB = *I;
866 LandingPadInst *LPI = BB->getLandingPadInst();
867 LPI->replaceAllUsesWith(PN);
868 PN->addIncoming(LPI, BB);
869 }
870 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000871 }
872
873 // Rewrite the code to refer to itself.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +0000874 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
875 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
876 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner43f8d162011-01-08 08:15:20 +0000877 RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Trick4104ed92012-04-10 05:14:37 +0000878
Chris Lattnerf48f7772004-04-19 18:07:02 +0000879 // Rewrite the original preheader to select between versions of the loop.
Devang Patele149d4e2008-07-02 01:18:13 +0000880 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000881 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000882 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000883
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000884 // Emit the new branch that selects between the two versions of this loop.
885 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
Devang Pateld4911982007-07-31 08:03:26 +0000886 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patel83cc3f82007-09-20 23:45:50 +0000887 OldBR->eraseFromParent();
Devang Patela8823282007-08-02 15:25:57 +0000888
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000889 LoopProcessWorklist.push_back(NewLoop);
Devang Patel7d165e12007-07-30 23:07:10 +0000890 redoLoop = true;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000891
Chris Lattner5814d9d92010-04-20 05:09:16 +0000892 // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
893 // deletes the instruction (for example by simplifying a PHI that feeds into
894 // the condition that we're unswitching on), we don't rewrite the second
895 // iteration.
896 WeakVH LICHandle(LIC);
Andrew Trick4104ed92012-04-10 05:14:37 +0000897
Chris Lattnerf48f7772004-04-19 18:07:02 +0000898 // Now we rewrite the original code to know that the condition is true and the
899 // new code to know that the condition is false.
Evan Chengba930442010-04-05 21:16:25 +0000900 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
Devang Pateleb611dd2008-07-03 17:37:52 +0000901
Chris Lattner5814d9d92010-04-20 05:09:16 +0000902 // It's possible that simplifying one loop could cause the other to be
903 // changed to another value or a constant. If its a constant, don't simplify
904 // it.
905 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
906 LICHandle && !isa<Constant>(LICHandle))
907 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000908}
909
Chris Lattner6fd13622006-02-17 00:31:07 +0000910/// RemoveFromWorklist - Remove all instances of I from the worklist vector
911/// specified.
Andrew Trick4104ed92012-04-10 05:14:37 +0000912static void RemoveFromWorklist(Instruction *I,
Chris Lattner6fd13622006-02-17 00:31:07 +0000913 std::vector<Instruction*> &Worklist) {
Jakub Staszak8f46e912012-10-16 19:52:32 +0000914
915 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
916 Worklist.end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000917}
918
919/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
920/// program, replacing all uses with V and update the worklist.
Andrew Trick4104ed92012-04-10 05:14:37 +0000921static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Pateld4911982007-07-31 08:03:26 +0000922 std::vector<Instruction*> &Worklist,
923 Loop *L, LPPassManager *LPM) {
David Greened9c355d2010-01-05 01:27:04 +0000924 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
Chris Lattner6fd13622006-02-17 00:31:07 +0000925
926 // Add uses to the worklist, which may be dead now.
927 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
928 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
929 Worklist.push_back(Use);
930
931 // Add users to the worklist which may be simplified now.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000932 for (User *U : I->users())
933 Worklist.push_back(cast<Instruction>(U));
Devang Pateld4911982007-07-31 08:03:26 +0000934 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +0000935 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +0000936 I->replaceAllUsesWith(V);
937 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +0000938 ++NumSimplify;
939}
940
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000941// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
942// the value specified by Val in the specified loop, or we know it does NOT have
943// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000944void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000945 Constant *Val,
946 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000947 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Andrew Trick4104ed92012-04-10 05:14:37 +0000948
Chris Lattnerf48f7772004-04-19 18:07:02 +0000949 // FIXME: Support correlated properties, like:
950 // for (...)
951 // if (li1 < li2)
952 // ...
953 // if (li1 > li2)
954 // ...
Andrew Trick4104ed92012-04-10 05:14:37 +0000955
Chris Lattner6e263152006-02-10 02:30:37 +0000956 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
957 // selects, switches.
Chris Lattner6fd13622006-02-17 00:31:07 +0000958 std::vector<Instruction*> Worklist;
Owen Anderson47db9412009-07-22 00:24:57 +0000959 LLVMContext &Context = Val->getContext();
960
Chris Lattner6fd13622006-02-17 00:31:07 +0000961 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
962 // in the loop with the appropriate one directly.
Owen Anderson55f1c092009-08-13 21:58:54 +0000963 if (IsEqual || (isa<ConstantInt>(Val) &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000964 Val->getType()->isIntegerTy(1))) {
Chris Lattner8a5a3242006-02-22 06:37:14 +0000965 Value *Replacement;
966 if (IsEqual)
967 Replacement = Val;
968 else
Andrew Trick4104ed92012-04-10 05:14:37 +0000969 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
Reid Spencercddc9df2007-01-12 04:24:46 +0000970 !cast<ConstantInt>(Val)->getZExtValue());
Andrew Trick4104ed92012-04-10 05:14:37 +0000971
Chandler Carruthcdf47882014-03-09 03:16:01 +0000972 for (User *U : LIC->users()) {
973 Instruction *UI = dyn_cast<Instruction>(U);
974 if (!UI || !L->contains(UI))
Evan Cheng1b55f562011-05-24 23:12:57 +0000975 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000976 Worklist.push_back(UI);
Evan Cheng1b55f562011-05-24 23:12:57 +0000977 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000978
Jakub Staszak27da1232013-08-06 17:03:42 +0000979 for (std::vector<Instruction*>::iterator UI = Worklist.begin(),
980 UE = Worklist.end(); UI != UE; ++UI)
Andrew Trick4104ed92012-04-10 05:14:37 +0000981 (*UI)->replaceUsesOfWith(LIC, Replacement);
982
Chris Lattnerc832c1b2010-04-05 21:18:32 +0000983 SimplifyCode(Worklist, L);
984 return;
985 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000986
Chris Lattnerc832c1b2010-04-05 21:18:32 +0000987 // Otherwise, we don't know the precise value of LIC, but we do know that it
988 // is certainly NOT "Val". As such, simplify any uses in the loop that we
989 // can. This case occurs when we unswitch switch statements.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000990 for (User *U : LIC->users()) {
991 Instruction *UI = dyn_cast<Instruction>(U);
992 if (!UI || !L->contains(UI))
Chris Lattnerc832c1b2010-04-05 21:18:32 +0000993 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +0000994
Chandler Carruthcdf47882014-03-09 03:16:01 +0000995 Worklist.push_back(UI);
Chris Lattner6fd13622006-02-17 00:31:07 +0000996
Andrew Trick4104ed92012-04-10 05:14:37 +0000997 // TODO: We could do other simplifications, for example, turning
Chris Lattnerc832c1b2010-04-05 21:18:32 +0000998 // 'icmp eq LIC, Val' -> false.
999
1000 // If we know that LIC is not Val, use this info to simplify code.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001001 SwitchInst *SI = dyn_cast<SwitchInst>(UI);
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001002 if (SI == 0 || !isa<ConstantInt>(Val)) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001003
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001004 SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00001005 // Default case is live for multiple values.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001006 if (DeadCase == SI->case_default()) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001007
1008 // Found a dead case value. Don't remove PHI nodes in the
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001009 // successor if they become single-entry, those PHI nodes may
1010 // be in the Users list.
Nick Lewycky61158242011-06-03 06:27:15 +00001011
Evan Cheng1b55f562011-05-24 23:12:57 +00001012 BasicBlock *Switch = SI->getParent();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001013 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
Evan Cheng1b55f562011-05-24 23:12:57 +00001014 BasicBlock *Latch = L->getLoopLatch();
Andrew Trick4104ed92012-04-10 05:14:37 +00001015
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +00001016 BranchesInfo.setUnswitched(SI, Val);
Andrew Trick4104ed92012-04-10 05:14:37 +00001017
Nick Lewycky61158242011-06-03 06:27:15 +00001018 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
Evan Cheng9605a692011-05-25 18:17:13 +00001019 // If the DeadCase successor dominates the loop latch, then the
1020 // transformation isn't safe since it will delete the sole predecessor edge
1021 // to the latch.
1022 if (Latch && DT->dominates(SISucc, Latch))
1023 continue;
Evan Cheng1b55f562011-05-24 23:12:57 +00001024
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001025 // FIXME: This is a hack. We need to keep the successor around
1026 // and hooked up so as to preserve the loop structure, because
1027 // trying to update it is complicated. So instead we preserve the
1028 // loop structure and put the block on a dead code path.
Evan Cheng1b55f562011-05-24 23:12:57 +00001029 SplitEdge(Switch, SISucc, this);
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001030 // Compute the successors instead of relying on the return value
1031 // of SplitEdge, since it may have split the switch successor
1032 // after PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001033 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001034 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1035 // Create an "unreachable" destination.
1036 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1037 Switch->getParent(),
1038 OldSISucc);
1039 new UnreachableInst(Context, Abort);
1040 // Force the new case destination to branch to the "unreachable"
1041 // block while maintaining a (dead) CFG edge to the old block.
1042 NewSISucc->getTerminator()->eraseFromParent();
1043 BranchInst::Create(Abort, OldSISucc,
1044 ConstantInt::getTrue(Context), NewSISucc);
1045 // Release the PHI operands for this edge.
1046 for (BasicBlock::iterator II = NewSISucc->begin();
1047 PHINode *PN = dyn_cast<PHINode>(II); ++II)
1048 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1049 UndefValue::get(PN->getType()));
1050 // Tell the domtree about the new block. We don't fully update the
1051 // domtree here -- instead we force it to do a full recomputation
1052 // after the pass is complete -- but we do need to inform it of
1053 // new blocks.
1054 if (DT)
1055 DT->addNewBlock(Abort, NewSISucc);
Chris Lattner6fd13622006-02-17 00:31:07 +00001056 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001057
Devang Pateld4911982007-07-31 08:03:26 +00001058 SimplifyCode(Worklist, L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001059}
1060
Mike Stumpdeaf5722009-09-09 17:57:16 +00001061/// SimplifyCode - Okay, now that we have simplified some instructions in the
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001062/// loop, walk over it and constant prop, dce, and fold control flow where
1063/// possible. Note that this is effectively a very simple loop-structure-aware
1064/// optimizer. During processing of this loop, L could very well be deleted, so
1065/// it must not be used.
1066///
1067/// FIXME: When the loop optimizer is more mature, separate this out to a new
1068/// pass.
1069///
Devang Pateld4911982007-07-31 08:03:26 +00001070void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001071 while (!Worklist.empty()) {
1072 Instruction *I = Worklist.back();
1073 Worklist.pop_back();
Duncan Sandsbb2cd022010-11-23 20:24:21 +00001074
Chris Lattner6fd13622006-02-17 00:31:07 +00001075 // Simple DCE.
1076 if (isInstructionTriviallyDead(I)) {
David Greened9c355d2010-01-05 01:27:04 +00001077 DEBUG(dbgs() << "Remove dead instruction '" << *I);
Andrew Trick4104ed92012-04-10 05:14:37 +00001078
Chris Lattner6fd13622006-02-17 00:31:07 +00001079 // Add uses to the worklist, which may be dead now.
1080 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1081 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1082 Worklist.push_back(Use);
Devang Pateld4911982007-07-31 08:03:26 +00001083 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001084 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +00001085 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001086 ++NumSimplify;
1087 continue;
1088 }
Duncan Sandsaef146b2010-11-18 19:59:41 +00001089
Chris Lattner66e809a2010-04-20 05:33:18 +00001090 // See if instruction simplification can hack this up. This is common for
1091 // things like "select false, X, Y" after unswitching made the condition be
Peter Collingbourne9a03c732012-05-20 01:32:09 +00001092 // 'false'. TODO: update the domtree properly so we can pass it here.
1093 if (Value *V = SimplifyInstruction(I))
Duncan Sandsaef146b2010-11-18 19:59:41 +00001094 if (LI->replacementPreservesLCSSAForm(I, V)) {
1095 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1096 continue;
1097 }
1098
Chris Lattner6fd13622006-02-17 00:31:07 +00001099 // Special case hacks that appear commonly in unswitched code.
Chris Lattner66e809a2010-04-20 05:33:18 +00001100 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001101 if (BI->isUnconditional()) {
1102 // If BI's parent is the only pred of the successor, fold the two blocks
1103 // together.
1104 BasicBlock *Pred = BI->getParent();
1105 BasicBlock *Succ = BI->getSuccessor(0);
1106 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1107 if (!SinglePred) continue; // Nothing to do.
1108 assert(SinglePred == Pred && "CFG broken");
1109
Andrew Trick4104ed92012-04-10 05:14:37 +00001110 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001111 << Succ->getName() << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +00001112
Chris Lattner6fd13622006-02-17 00:31:07 +00001113 // Resolve any single entry PHI nodes in Succ.
1114 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Pateld4911982007-07-31 08:03:26 +00001115 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Andrew Trick4104ed92012-04-10 05:14:37 +00001116
Jay Foad61ea0e42011-06-23 09:09:15 +00001117 // If Succ has any successors with PHI nodes, update them to have
1118 // entries coming from Pred instead of Succ.
1119 Succ->replaceAllUsesWith(Pred);
Andrew Trick4104ed92012-04-10 05:14:37 +00001120
Chris Lattner6fd13622006-02-17 00:31:07 +00001121 // Move all of the successor contents from Succ to Pred.
1122 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1123 Succ->end());
Devang Pateld4911982007-07-31 08:03:26 +00001124 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001125 BI->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001126 RemoveFromWorklist(BI, Worklist);
Andrew Trick4104ed92012-04-10 05:14:37 +00001127
Chris Lattner6fd13622006-02-17 00:31:07 +00001128 // Remove Succ from the loop tree.
1129 LI->removeBlock(Succ);
Devang Pateld4911982007-07-31 08:03:26 +00001130 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001131 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001132 ++NumSimplify;
Chris Lattner66e809a2010-04-20 05:33:18 +00001133 continue;
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001134 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001135
Chris Lattner66e809a2010-04-20 05:33:18 +00001136 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001137 }
1138 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001139}