blob: 987dc96fb14335832c013edfce9a6c9b0b8ae579 [file] [log] [blame]
Chris Lattnerf48f7772004-04-19 18:07:02 +00001//===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattnerf48f7772004-04-19 18:07:02 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattnerf48f7772004-04-19 18:07:02 +00008//===----------------------------------------------------------------------===//
9//
10// This pass transforms loops that contain branches on loop-invariant conditions
11// to have multiple loops. For example, it turns the left into the right code:
12//
13// for (...) if (lic)
14// A for (...)
15// if (lic) A; B; C
16// B else
17// C for (...)
18// A; C
19//
20// This can increase the size of the code exponentially (doubling it every time
21// a loop is unswitched) so we only unswitch if the resultant code will be
22// smaller than a threshold.
23//
24// This pass expects LICM to be run before it to hoist invariant conditions out
25// of the loop, to make the unswitching opportunity obvious.
26//
27//===----------------------------------------------------------------------===//
28
Chris Lattnerf48f7772004-04-19 18:07:02 +000029#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/Statistic.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000033#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#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
Chandler Carruth964daaa2014-04-22 02:55:47 +000056#define DEBUG_TYPE "loop-unswitch"
57
Chris Lattner79a42ac2006-12-19 21:40:18 +000058STATISTIC(NumBranches, "Number of branches unswitched");
59STATISTIC(NumSwitches, "Number of switches unswitched");
60STATISTIC(NumSelects , "Number of selects unswitched");
61STATISTIC(NumTrivial , "Number of unswitches that are trivial");
62STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000063STATISTIC(TotalInsts, "Total number of instructions analyzed");
Chris Lattner79a42ac2006-12-19 21:40:18 +000064
Stepan Dyatkovskiy2931a592012-01-16 20:48:04 +000065// The specific value of 100 here was chosen based only on intuition and a
Dan Gohman71ca6522009-10-13 17:50:43 +000066// few specific examples.
Dan Gohmand78c4002008-05-13 00:00:25 +000067static cl::opt<unsigned>
68Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000069 cl::init(100), cl::Hidden);
Andrew Trick4104ed92012-04-10 05:14:37 +000070
Dan Gohmand78c4002008-05-13 00:00:25 +000071namespace {
Andrew Trick4104ed92012-04-10 05:14:37 +000072
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000073 class LUAnalysisCache {
74
75 typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
76 UnswitchedValsMap;
Andrew Trick4104ed92012-04-10 05:14:37 +000077
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000078 typedef UnswitchedValsMap::iterator UnswitchedValsIt;
Andrew Trick4104ed92012-04-10 05:14:37 +000079
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000080 struct LoopProperties {
81 unsigned CanBeUnswitchedCount;
82 unsigned SizeEstimation;
83 UnswitchedValsMap UnswitchedVals;
84 };
Andrew Trick4104ed92012-04-10 05:14:37 +000085
86 // Here we use std::map instead of DenseMap, since we need to keep valid
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000087 // LoopProperties pointer for current loop for better performance.
88 typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
89 typedef LoopPropsMap::iterator LoopPropsMapIt;
Andrew Trick4104ed92012-04-10 05:14:37 +000090
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000091 LoopPropsMap LoopsProperties;
Jakub Staszak27da1232013-08-06 17:03:42 +000092 UnswitchedValsMap *CurLoopInstructions;
93 LoopProperties *CurrentLoopProperties;
Andrew Trick4104ed92012-04-10 05:14:37 +000094
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000095 // Max size of code we can produce on remained iterations.
96 unsigned MaxSize;
Andrew Trick4104ed92012-04-10 05:14:37 +000097
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000098 public:
Andrew Trick4104ed92012-04-10 05:14:37 +000099
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000100 LUAnalysisCache() :
Craig Topperf40110f2014-04-25 05:29:35 +0000101 CurLoopInstructions(nullptr), CurrentLoopProperties(nullptr),
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000102 MaxSize(Threshold)
103 {}
Andrew Trick4104ed92012-04-10 05:14:37 +0000104
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000105 // Analyze loop. Check its size, calculate is it possible to unswitch
106 // it. Returns true if we can unswitch this loop.
Hal Finkel57f03dd2014-09-07 13:49:57 +0000107 bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000108 AssumptionCache *AC);
Andrew Trick4104ed92012-04-10 05:14:37 +0000109
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000110 // Clean all data related to given loop.
Jakub Staszak27da1232013-08-06 17:03:42 +0000111 void forgetLoop(const Loop *L);
Andrew Trick4104ed92012-04-10 05:14:37 +0000112
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000113 // Mark case value as unswitched.
114 // Since SI instruction can be partly unswitched, in order to avoid
115 // extra unswitching in cloned loops keep track all unswitched values.
Jakub Staszak27da1232013-08-06 17:03:42 +0000116 void setUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000117
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000118 // Check was this case value unswitched before or not.
Jakub Staszak27da1232013-08-06 17:03:42 +0000119 bool isUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000120
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000121 // Clone all loop-unswitch related loop properties.
122 // Redistribute unswitching quotas.
123 // Note, that new loop data is stored inside the VMap.
Jakub Staszak27da1232013-08-06 17:03:42 +0000124 void cloneData(const Loop *NewLoop, const Loop *OldLoop,
125 const ValueToValueMapTy &VMap);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000126 };
Andrew Trick4104ed92012-04-10 05:14:37 +0000127
Chris Lattner2dd09db2009-09-02 06:11:42 +0000128 class LoopUnswitch : public LoopPass {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000129 LoopInfo *LI; // Loop information
Devang Patel901a27d2007-03-07 00:26:10 +0000130 LPPassManager *LPM;
Chandler Carruth66b31302015-01-04 12:03:27 +0000131 AssumptionCache *AC;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000132
Devang Patel901a27d2007-03-07 00:26:10 +0000133 // LoopProcessWorklist - Used to check if second loop needs processing
134 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000135 std::vector<Loop*> LoopProcessWorklist;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000136
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000137 LUAnalysisCache BranchesInfo;
Andrew Trick4104ed92012-04-10 05:14:37 +0000138
Devang Patel506310d2007-06-06 00:21:03 +0000139 bool OptimizeForSize;
Devang Patel7d165e12007-07-30 23:07:10 +0000140 bool redoLoop;
Devang Patela69f9872007-10-05 22:29:34 +0000141
Devang Patele149d4e2008-07-02 01:18:13 +0000142 Loop *currentLoop;
Devang Patela69f9872007-10-05 22:29:34 +0000143 DominatorTree *DT;
Devang Patele149d4e2008-07-02 01:18:13 +0000144 BasicBlock *loopHeader;
145 BasicBlock *loopPreheader;
Andrew Trick4104ed92012-04-10 05:14:37 +0000146
Devang Pateled50fb52008-07-02 01:44:29 +0000147 // LoopBlocks contains all of the basic blocks of the loop, including the
Andrew Trick4104ed92012-04-10 05:14:37 +0000148 // preheader of the loop, the body of the loop, and the exit blocks of the
Devang Pateled50fb52008-07-02 01:44:29 +0000149 // loop, in that order.
150 std::vector<BasicBlock*> LoopBlocks;
151 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
152 std::vector<BasicBlock*> NewBlocks;
Devang Pateleb611dd2008-07-03 17:37:52 +0000153
Chris Lattnerf48f7772004-04-19 18:07:02 +0000154 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000155 static char ID; // Pass ID, replacement for typeid
Andrew Trick4104ed92012-04-10 05:14:37 +0000156 explicit LoopUnswitch(bool Os = false) :
157 LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
Craig Topperf40110f2014-04-25 05:29:35 +0000158 currentLoop(nullptr), DT(nullptr), loopHeader(nullptr),
159 loopPreheader(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000160 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
161 }
Devang Patel09f162c2007-05-01 21:15:47 +0000162
Craig Topper3e4c6972014-03-05 09:10:37 +0000163 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Devang Patele149d4e2008-07-02 01:18:13 +0000164 bool processCurrentLoop();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000165
166 /// This transformation requires natural loop information & requires that
Chris Lattnerbc1a65a2010-08-29 17:23:19 +0000167 /// loop preheaders be inserted into the CFG.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000168 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000169 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +0000170 AU.addRequired<AssumptionCacheTracker>();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000171 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +0000172 AU.addPreservedID(LoopSimplifyID);
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000173 AU.addRequired<LoopInfoWrapperPass>();
174 AU.addPreserved<LoopInfoWrapperPass>();
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000175 AU.addRequiredID(LCSSAID);
Devang Pateld4911982007-07-31 08:03:26 +0000176 AU.addPreservedID(LCSSAID);
Chandler Carruth73523022014-01-13 13:07:17 +0000177 AU.addPreserved<DominatorTreeWrapperPass>();
Cameron Zwarich99de19b2011-02-11 06:08:28 +0000178 AU.addPreserved<ScalarEvolution>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000179 AU.addRequired<TargetTransformInfoWrapperPass>();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000180 }
181
182 private:
Devang Pateld4911982007-07-31 08:03:26 +0000183
Craig Topper3e4c6972014-03-05 09:10:37 +0000184 void releaseMemory() override {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000185 BranchesInfo.forgetLoop(currentLoop);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000186 }
187
Devang Patele149d4e2008-07-02 01:18:13 +0000188 void initLoopData() {
189 loopHeader = currentLoop->getHeader();
190 loopPreheader = currentLoop->getLoopPreheader();
191 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000192
Chris Lattner559c8672008-04-21 00:25:49 +0000193 /// Split all of the edges from inside the loop to their exit blocks.
194 /// Update the appropriate Phi nodes as we do so.
Craig Topperb94011f2013-07-14 04:42:23 +0000195 void SplitExitEdges(Loop *L, const SmallVectorImpl<BasicBlock *> &ExitBlocks);
Devang Patela69f9872007-10-05 22:29:34 +0000196
Devang Patele149d4e2008-07-02 01:18:13 +0000197 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
Chris Lattner29f771b2006-02-18 01:27:45 +0000198 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000199 BasicBlock *ExitBlock);
Andrew Trick4442bfe2012-04-10 05:14:42 +0000200 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000201
202 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
203 Constant *Val, bool isEqual);
Devang Patel3304e462007-06-28 00:49:00 +0000204
205 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
Andrew Trick4104ed92012-04-10 05:14:37 +0000206 BasicBlock *TrueDest,
Devang Patel3304e462007-06-28 00:49:00 +0000207 BasicBlock *FalseDest,
208 Instruction *InsertPt);
209
Devang Pateld4911982007-07-31 08:03:26 +0000210 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Craig Topperf40110f2014-04-25 05:29:35 +0000211 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = nullptr,
212 BasicBlock **LoopExit = nullptr);
Devang Patele149d4e2008-07-02 01:18:13 +0000213
Chris Lattnerf48f7772004-04-19 18:07:02 +0000214 };
Chris Lattnerf48f7772004-04-19 18:07:02 +0000215}
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000216
217// Analyze loop. Check its size, calculate is it possible to unswitch
218// it. Returns true if we can unswitch this loop.
Hal Finkel57f03dd2014-09-07 13:49:57 +0000219bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000220 AssumptionCache *AC) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000221
Jakub Staszak27da1232013-08-06 17:03:42 +0000222 LoopPropsMapIt PropsIt;
223 bool Inserted;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000224 std::tie(PropsIt, Inserted) =
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000225 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
Andrew Trick4104ed92012-04-10 05:14:37 +0000226
Jakub Staszak27da1232013-08-06 17:03:42 +0000227 LoopProperties &Props = PropsIt->second;
Andrew Trick4104ed92012-04-10 05:14:37 +0000228
Jakub Staszak27da1232013-08-06 17:03:42 +0000229 if (Inserted) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000230 // New loop.
231
232 // Limit the number of instructions to avoid causing significant code
233 // expansion, and the number of basic blocks, to avoid loops with
234 // large numbers of branches which cause loop unswitching to go crazy.
235 // This is a very ad-hoc heuristic.
Andrew Trick4104ed92012-04-10 05:14:37 +0000236
Hal Finkel57f03dd2014-09-07 13:49:57 +0000237 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000238 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000239
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000240 // FIXME: This is overly conservative because it does not take into
241 // consideration code simplification opportunities and code that can
242 // be shared by the resultant unswitched loops.
243 CodeMetrics Metrics;
Jakub Staszak27da1232013-08-06 17:03:42 +0000244 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000245 I != E; ++I)
Hal Finkel57f03dd2014-09-07 13:49:57 +0000246 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000247
248 Props.SizeEstimation = std::min(Metrics.NumInsts, Metrics.NumBlocks * 5);
249 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
250 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
James Molloy4f6fb952012-12-20 16:04:27 +0000251
252 if (Metrics.notDuplicatable) {
253 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak27da1232013-08-06 17:03:42 +0000254 << L->getHeader()->getName() << ", contents cannot be "
255 << "duplicated!\n");
James Molloy4f6fb952012-12-20 16:04:27 +0000256 return false;
257 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000258 }
259
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000260 if (!Props.CanBeUnswitchedCount) {
261 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak27da1232013-08-06 17:03:42 +0000262 << L->getHeader()->getName() << ", cost too high: "
263 << L->getBlocks().size() << "\n");
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000264 return false;
265 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000266
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000267 // Be careful. This links are good only before new loop addition.
268 CurrentLoopProperties = &Props;
269 CurLoopInstructions = &Props.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000270
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000271 return true;
272}
273
274// Clean all data related to given loop.
Jakub Staszak27da1232013-08-06 17:03:42 +0000275void LUAnalysisCache::forgetLoop(const Loop *L) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000276
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000277 LoopPropsMapIt LIt = LoopsProperties.find(L);
278
279 if (LIt != LoopsProperties.end()) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000280 LoopProperties &Props = LIt->second;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000281 MaxSize += Props.CanBeUnswitchedCount * Props.SizeEstimation;
282 LoopsProperties.erase(LIt);
283 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000284
Craig Topperf40110f2014-04-25 05:29:35 +0000285 CurrentLoopProperties = nullptr;
286 CurLoopInstructions = nullptr;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000287}
288
289// Mark case value as unswitched.
290// Since SI instruction can be partly unswitched, in order to avoid
291// extra unswitching in cloned loops keep track all unswitched values.
Jakub Staszak27da1232013-08-06 17:03:42 +0000292void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000293 (*CurLoopInstructions)[SI].insert(V);
294}
295
296// Check was this case value unswitched before or not.
Jakub Staszak27da1232013-08-06 17:03:42 +0000297bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000298 return (*CurLoopInstructions)[SI].count(V);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000299}
300
301// Clone all loop-unswitch related loop properties.
302// Redistribute unswitching quotas.
303// Note, that new loop data is stored inside the VMap.
Jakub Staszak27da1232013-08-06 17:03:42 +0000304void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
305 const ValueToValueMapTy &VMap) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000306
Jakub Staszak27da1232013-08-06 17:03:42 +0000307 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
308 LoopProperties &OldLoopProps = *CurrentLoopProperties;
309 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000310
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000311 // Reallocate "can-be-unswitched quota"
312
313 --OldLoopProps.CanBeUnswitchedCount;
314 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
315 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
316 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
Andrew Trick4104ed92012-04-10 05:14:37 +0000317
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000318 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
Andrew Trick4104ed92012-04-10 05:14:37 +0000319
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000320 // Clone unswitched values info:
321 // for new loop switches we clone info about values that was
322 // already unswitched and has redundant successors.
323 for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000324 const SwitchInst *OldInst = I->first;
325 Value *NewI = VMap.lookup(OldInst);
326 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000327 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
Andrew Trick4104ed92012-04-10 05:14:37 +0000328
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000329 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
330 }
331}
332
Dan Gohmand78c4002008-05-13 00:00:25 +0000333char LoopUnswitch::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000334INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
335 false, false)
Chandler Carruth705b1852015-01-31 03:43:40 +0000336INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruth66b31302015-01-04 12:03:27 +0000337INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000338INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000339INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000340INITIALIZE_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())
Craig Topperf40110f2014-04-25 05:29:35 +0000358 return nullptr;
Chris Lattner302240d2010-02-02 02:26:54 +0000359
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000360 // Constants should be folded, not unswitched on!
Craig Topperf40110f2014-04-25 05:29:35 +0000361 if (isa<Constant>(Cond)) return nullptr;
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
Craig Topperf40110f2014-04-25 05:29:35 +0000381 return nullptr;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000382}
383
Devang Patel901a27d2007-03-07 00:26:10 +0000384bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000385 if (skipOptnoneFunction(L))
386 return false;
387
Chandler Carruth66b31302015-01-04 12:03:27 +0000388 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
389 *L->getHeader()->getParent());
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000390 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Devang Patel901a27d2007-03-07 00:26:10 +0000391 LPM = &LPM_Ref;
Chandler Carruth73523022014-01-13 13:07:17 +0000392 DominatorTreeWrapperPass *DTWP =
393 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperf40110f2014-04-25 05:29:35 +0000394 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Devang Patele149d4e2008-07-02 01:18:13 +0000395 currentLoop = L;
Devang Patel40519f02008-09-04 22:43:59 +0000396 Function *F = currentLoop->getHeader()->getParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000397 bool Changed = false;
Devang Patel7d165e12007-07-30 23:07:10 +0000398 do {
Dan Gohman2734ebd2010-03-10 19:38:49 +0000399 assert(currentLoop->isLCSSAForm(*DT));
Devang Patel7d165e12007-07-30 23:07:10 +0000400 redoLoop = false;
Devang Patele149d4e2008-07-02 01:18:13 +0000401 Changed |= processCurrentLoop();
Devang Patel7d165e12007-07-30 23:07:10 +0000402 } while(redoLoop);
403
Devang Patel40519f02008-09-04 22:43:59 +0000404 if (Changed) {
405 // FIXME: Reconstruct dom info, because it is not preserved properly.
406 if (DT)
Chandler Carruth73523022014-01-13 13:07:17 +0000407 DT->recalculate(*F);
Devang Patel40519f02008-09-04 22:43:59 +0000408 }
Devang Patel7d165e12007-07-30 23:07:10 +0000409 return Changed;
410}
411
Andrew Trick4104ed92012-04-10 05:14:37 +0000412/// processCurrentLoop - Do actual work and unswitch loop if possible
Devang Patele149d4e2008-07-02 01:18:13 +0000413/// and profitable.
414bool LoopUnswitch::processCurrentLoop() {
Devang Patel7d165e12007-07-30 23:07:10 +0000415 bool Changed = false;
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000416
417 initLoopData();
Andrew Trick4104ed92012-04-10 05:14:37 +0000418
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000419 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
420 if (!loopPreheader)
421 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000422
Andrew Trick4442bfe2012-04-10 05:14:42 +0000423 // Loops with indirectbr cannot be cloned.
424 if (!currentLoop->isSafeToClone())
425 return false;
426
427 // Without dedicated exits, splitting the exit edge may fail.
428 if (!currentLoop->hasDedicatedExits())
429 return false;
430
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000431 LLVMContext &Context = loopHeader->getContext();
Andrew Trick4104ed92012-04-10 05:14:37 +0000432
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000433 // Probably we reach the quota of branches for this loop. If so
434 // stop unswitching.
Chandler Carruth705b1852015-01-31 03:43:40 +0000435 if (!BranchesInfo.countLoop(
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000436 currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
437 *currentLoop->getHeader()->getParent()),
Chandler Carruth705b1852015-01-31 03:43:40 +0000438 AC))
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000439 return false;
Devang Patel7d165e12007-07-30 23:07:10 +0000440
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000441 // Loop over all of the basic blocks in the loop. If we find an interior
442 // block that is branching on a loop-invariant condition, we can unswitch this
443 // loop.
Andrew Trick4104ed92012-04-10 05:14:37 +0000444 for (Loop::block_iterator I = currentLoop->block_begin(),
Chris Lattnerc832c1b2010-04-05 21:18:32 +0000445 E = currentLoop->block_end(); I != E; ++I) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000446 TerminatorInst *TI = (*I)->getTerminator();
447 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
448 // If this isn't branching on an invariant condition, we can't unswitch
449 // it.
450 if (BI->isConditional()) {
451 // See if this, or some part of it, is loop invariant. If so, we can
452 // unswitch on it if we desire.
Andrew Trick4104ed92012-04-10 05:14:37 +0000453 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000454 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000455 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson23a204d2009-07-31 17:39:07 +0000456 ConstantInt::getTrue(Context))) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000457 ++NumBranches;
458 return true;
459 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000460 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000461 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000462 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000463 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000464 unsigned NumCases = SI->getNumCases();
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000465 if (LoopCond && NumCases) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000466 // Find a value to unswitch on:
467 // FIXME: this should chose the most expensive case!
Nick Lewycky61158242011-06-03 06:27:15 +0000468 // FIXME: scan for a case with a non-critical edge?
Craig Topperf40110f2014-04-25 05:29:35 +0000469 Constant *UnswitchVal = nullptr;
Andrew Trick4104ed92012-04-10 05:14:37 +0000470
Devang Patel967b84c2007-02-26 19:31:58 +0000471 // Do not process same value again and again.
Chad Rosier3ba90a12011-12-22 21:10:46 +0000472 // At this point we have some cases already unswitched and
473 // some not yet unswitched. Let's find the first not yet unswitched one.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +0000474 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000475 i != e; ++i) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000476 Constant *UnswitchValCandidate = i.getCaseValue();
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000477 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
Chad Rosier3ba90a12011-12-22 21:10:46 +0000478 UnswitchVal = UnswitchValCandidate;
479 break;
480 }
481 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000482
Chad Rosier3ba90a12011-12-22 21:10:46 +0000483 if (!UnswitchVal)
Devang Patel967b84c2007-02-26 19:31:58 +0000484 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000485
Devang Patele149d4e2008-07-02 01:18:13 +0000486 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000487 ++NumSwitches;
488 return true;
489 }
490 }
491 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000492
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000493 // Scan the instructions to check for unswitchable values.
Andrew Trick4104ed92012-04-10 05:14:37 +0000494 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000495 BBI != E; ++BBI)
496 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000497 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000498 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000499 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson23a204d2009-07-31 17:39:07 +0000500 ConstantInt::getTrue(Context))) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000501 ++NumSelects;
502 return true;
503 }
504 }
505 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000506 return Changed;
507}
508
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000509/// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
510/// loop with no side effects (including infinite loops).
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000511///
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000512/// If true, we return true and set ExitBB to the block we
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000513/// exit through.
514///
515static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
516 BasicBlock *&ExitBB,
517 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000518 if (!Visited.insert(BB).second) {
Nick Lewyckyd9d1de42011-12-23 23:49:25 +0000519 // Already visited. Without more analysis, this could indicate an infinite
520 // loop.
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000521 return false;
Jakub Staszak27da1232013-08-06 17:03:42 +0000522 }
523 if (!L->contains(BB)) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000524 // Otherwise, this is a loop exit, this is fine so long as this is the
525 // first exit.
Craig Topperf40110f2014-04-25 05:29:35 +0000526 if (ExitBB) return false;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000527 ExitBB = BB;
Edward O'Callaghan2b8fed12009-11-25 05:38:41 +0000528 return true;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000529 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000530
Chris Lattnerbaddba42006-02-17 06:39:56 +0000531 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000532 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000533 // Check to see if the successor is a trivial loop exit.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000534 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
Chris Lattnerbaddba42006-02-17 06:39:56 +0000535 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000536 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000537
538 // Okay, everything after this looks good, check to make sure that this block
539 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000540 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Duncan Sands1efabaa2009-05-06 06:49:50 +0000541 if (I->mayHaveSideEffects())
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000542 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000543
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000544 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000545}
546
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000547/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
Andrew Trick4104ed92012-04-10 05:14:37 +0000548/// leads to an exit from the specified loop, and has no side-effects in the
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000549/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000550static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
551 std::set<BasicBlock*> Visited;
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000552 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
Craig Topperf40110f2014-04-25 05:29:35 +0000553 BasicBlock *ExitBB = nullptr;
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000554 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
555 return ExitBB;
Craig Topperf40110f2014-04-25 05:29:35 +0000556 return nullptr;
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000557}
Chris Lattner6e263152006-02-10 02:30:37 +0000558
Chris Lattnered7a67b2006-02-10 01:24:09 +0000559/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
560/// trivial: that is, that the condition controls whether or not the loop does
561/// anything at all. If this is a trivial condition, unswitching produces no
562/// code duplications (equivalently, it produces a simpler loop and a new empty
563/// loop, which gets deleted).
564///
Chris Lattner8a5a3242006-02-22 06:37:14 +0000565/// If this is a trivial condition, return true, otherwise return false. When
566/// returning true, this sets Cond and Val to the condition that controls the
567/// trivial condition: when Cond dynamically equals Val, the loop is known to
568/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
569/// Cond == Val.
570///
Devang Patele149d4e2008-07-02 01:18:13 +0000571bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
572 BasicBlock **LoopExit) {
573 BasicBlock *Header = currentLoop->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000574 TerminatorInst *HeaderTerm = Header->getTerminator();
Owen Anderson47db9412009-07-22 00:24:57 +0000575 LLVMContext &Context = Header->getContext();
Andrew Trick4104ed92012-04-10 05:14:37 +0000576
Craig Topperf40110f2014-04-25 05:29:35 +0000577 BasicBlock *LoopExitBB = nullptr;
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000578 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
579 // If the header block doesn't end with a conditional branch on Cond, we
580 // can't handle it.
581 if (!BI->isConditional() || BI->getCondition() != Cond)
582 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000583
584 // Check to see if a successor of the branch is guaranteed to
585 // exit through a unique 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
587 // this.
Andrew Trick4104ed92012-04-10 05:14:37 +0000588 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
Devang Patele149d4e2008-07-02 01:18:13 +0000589 BI->getSuccessor(0)))) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000590 if (Val) *Val = ConstantInt::getTrue(Context);
Andrew Trick4104ed92012-04-10 05:14:37 +0000591 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
Devang Patele149d4e2008-07-02 01:18:13 +0000592 BI->getSuccessor(1)))) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000593 if (Val) *Val = ConstantInt::getFalse(Context);
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000594 }
595 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
596 // If this isn't a switch on Cond, we can't handle it.
597 if (SI->getCondition() != Cond) return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000598
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000599 // Check to see if a successor of the switch is guaranteed to go to the
Andrew Trick4104ed92012-04-10 05:14:37 +0000600 // latch block or exit through a one exit block without having any
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000601 // side-effects. If so, determine the value of Cond that causes it to do
Andrew Trick4104ed92012-04-10 05:14:37 +0000602 // this.
Chad Rosier3ba90a12011-12-22 21:10:46 +0000603 // Note that we can't trivially unswitch on the default case or
604 // on already unswitched cases.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +0000605 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000606 i != e; ++i) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000607 BasicBlock *LoopExitCandidate;
Andrew Trick4104ed92012-04-10 05:14:37 +0000608 if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000609 i.getCaseSuccessor()))) {
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000610 // Okay, we found a trivial case, remember the value that is trivial.
Jakub Staszak27da1232013-08-06 17:03:42 +0000611 ConstantInt *CaseVal = i.getCaseValue();
Chad Rosier3ba90a12011-12-22 21:10:46 +0000612
613 // Check that it was not unswitched before, since already unswitched
614 // trivial vals are looks trivial too.
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000615 if (BranchesInfo.isUnswitched(SI, CaseVal))
Chad Rosier3ba90a12011-12-22 21:10:46 +0000616 continue;
617 LoopExitBB = LoopExitCandidate;
618 if (Val) *Val = CaseVal;
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000619 break;
620 }
Chad Rosier3ba90a12011-12-22 21:10:46 +0000621 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000622 }
623
Chris Lattnere5521db2006-02-22 23:55:00 +0000624 // If we didn't find a single unique LoopExit block, or if the loop exit block
625 // contains phi nodes, this isn't trivial.
626 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000627 return false; // Can't handle this.
Andrew Trick4104ed92012-04-10 05:14:37 +0000628
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000629 if (LoopExit) *LoopExit = LoopExitBB;
Andrew Trick4104ed92012-04-10 05:14:37 +0000630
Chris Lattnered7a67b2006-02-10 01:24:09 +0000631 // We already know that nothing uses any scalar values defined inside of this
632 // loop. As such, we just have to check to see if this loop will execute any
633 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000634 // part of the loop that the code *would* execute. We already checked the
635 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000636 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
Duncan Sands1efabaa2009-05-06 06:49:50 +0000637 if (I->mayHaveSideEffects())
Chris Lattner49354172006-02-10 02:01:22 +0000638 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000639 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000640}
641
Devang Patele149d4e2008-07-02 01:18:13 +0000642/// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000643/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
644/// unswitch the loop, reprocess the pieces, then return true.
Chris Lattner302240d2010-02-02 02:26:54 +0000645bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val) {
Dan Gohman72c367f2009-12-09 22:55:01 +0000646 Function *F = loopHeader->getParent();
Craig Topperf40110f2014-04-25 05:29:35 +0000647 Constant *CondVal = nullptr;
648 BasicBlock *ExitBlock = nullptr;
Bill Wendling712d85a2012-04-30 09:23:48 +0000649
Devang Patele149d4e2008-07-02 01:18:13 +0000650 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
Evan Chenged66db32010-04-03 02:23:43 +0000651 // If the condition is trivial, always unswitch. There is no code growth
652 // for this case.
Devang Patele149d4e2008-07-02 01:18:13 +0000653 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
Evan Chenged66db32010-04-03 02:23:43 +0000654 return true;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000655 }
Devang Patelc4dcf822008-07-03 06:48:21 +0000656
Evan Chenged66db32010-04-03 02:23:43 +0000657 // Check to see if it would be profitable to unswitch current loop.
658
659 // Do not do non-trivial unswitch while optimizing for size.
Duncan P. N. Exon Smith2c79ad92015-02-14 01:11:29 +0000660 if (OptimizeForSize || F->hasFnAttribute(Attribute::OptimizeForSize))
Evan Chenged66db32010-04-03 02:23:43 +0000661 return false;
662
Andrew Trick4442bfe2012-04-10 05:14:42 +0000663 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
664 return true;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000665}
666
Chris Lattnerf48f7772004-04-19 18:07:02 +0000667/// CloneLoop - Recursively clone the specified loop and all of its children,
668/// mapping the blocks with the specified map.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000669static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000670 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000671 Loop *New = new Loop();
Devang Patel901a27d2007-03-07 00:26:10 +0000672 LPM->insertLoop(New, PL);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000673
674 // Add all of the blocks in L to the new loop.
675 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
676 I != E; ++I)
677 if (LI->getLoopFor(*I) == L)
Chandler Carruth691addc2015-01-18 01:25:51 +0000678 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000679
680 // Add all of the subloops to the new loop.
681 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel901a27d2007-03-07 00:26:10 +0000682 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000683
Chris Lattnerf48f7772004-04-19 18:07:02 +0000684 return New;
685}
686
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000687/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
688/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
689/// code immediately before InsertPt.
Devang Patel3304e462007-06-28 00:49:00 +0000690void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
691 BasicBlock *TrueDest,
692 BasicBlock *FalseDest,
693 Instruction *InsertPt) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000694 // Insert a conditional branch on LIC to the two preheaders. The original
695 // code is the true version and the new code is the false version.
696 Value *BranchVal = LIC;
Owen Anderson55f1c092009-08-13 21:58:54 +0000697 if (!isa<ConstantInt>(Val) ||
698 Val->getType() != Type::getInt1Ty(LIC->getContext()))
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000699 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
Owen Anderson23a204d2009-07-31 17:39:07 +0000700 else if (Val != ConstantInt::getTrue(Val->getContext()))
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000701 // We want to enter the new loop when the condition is true.
702 std::swap(TrueDest, FalseDest);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000703
704 // Insert the new branch.
Dan Gohman3ddbc242009-09-08 15:45:00 +0000705 BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
706
707 // If either edge is critical, split it. This helps preserve LoopSimplify
708 // form for enclosing loops.
Chandler Carruthf8753fc2015-01-19 12:12:00 +0000709 auto Options = CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA();
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000710 SplitCriticalEdge(BI, 0, Options);
711 SplitCriticalEdge(BI, 1, Options);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000712}
713
Chris Lattnered7a67b2006-02-10 01:24:09 +0000714/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
715/// condition in it (a cond branch from its header block to its latch block,
Andrew Trick4104ed92012-04-10 05:14:37 +0000716/// where the path through the loop that doesn't execute its body has no
Chris Lattnered7a67b2006-02-10 01:24:09 +0000717/// side-effects), unswitch it. This doesn't involve any code duplication, just
718/// moving the conditional branch outside of the loop and updating loop info.
Andrew Trick4104ed92012-04-10 05:14:37 +0000719void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
720 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000721 BasicBlock *ExitBlock) {
David Greened9c355d2010-01-05 01:27:04 +0000722 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000723 << loopHeader->getName() << " [" << L->getBlocks().size()
724 << " blocks] in Function " << L->getHeader()->getParent()->getName()
725 << " on cond: " << *Val << " == " << *Cond << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +0000726
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000727 // First step, split the preheader, so that we know that there is a safe place
Devang Patele149d4e2008-07-02 01:18:13 +0000728 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattnered7a67b2006-02-10 01:24:09 +0000729 // conditional branch on Cond.
Chandler Carruthd4500562015-01-19 12:36:53 +0000730 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000731
732 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000733 // to branch to: this is the exit block out of the loop that we should
734 // short-circuit to.
Andrew Trick4104ed92012-04-10 05:14:37 +0000735
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000736 // Split this block now, so that the loop maintains its exit block, and so
737 // that the jump from the preheader can execute the contents of the exit block
738 // without actually branching to it (the exit block should be dominated by the
739 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000740 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chandler Carruth32c52c72015-01-18 02:39:37 +0000741 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), DT, LI);
Andrew Trick4104ed92012-04-10 05:14:37 +0000742
743 // Okay, now we have a position to branch from and a position to branch to,
Chris Lattnered7a67b2006-02-10 01:24:09 +0000744 // insert the new conditional branch.
Andrew Trick4104ed92012-04-10 05:14:37 +0000745 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Devang Patele149d4e2008-07-02 01:18:13 +0000746 loopPreheader->getTerminator());
Devang Patele149d4e2008-07-02 01:18:13 +0000747 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
748 loopPreheader->getTerminator()->eraseFromParent();
Chris Lattnered7a67b2006-02-10 01:24:09 +0000749
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000750 // We need to reprocess this loop, it could be unswitched again.
Devang Patel7d165e12007-07-30 23:07:10 +0000751 redoLoop = true;
Andrew Trick4104ed92012-04-10 05:14:37 +0000752
Chris Lattnered7a67b2006-02-10 01:24:09 +0000753 // Now that we know that the loop is never entered when this condition is a
754 // particular value, rewrite the loop with this info. We know that this will
755 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000756 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000757 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000758}
759
Chris Lattner559c8672008-04-21 00:25:49 +0000760/// SplitExitEdges - Split all of the edges from inside the loop to their exit
761/// blocks. Update the appropriate Phi nodes as we do so.
Andrew Trick4104ed92012-04-10 05:14:37 +0000762void LoopUnswitch::SplitExitEdges(Loop *L,
Craig Topperb94011f2013-07-14 04:42:23 +0000763 const SmallVectorImpl<BasicBlock *> &ExitBlocks){
Devang Patela69f9872007-10-05 22:29:34 +0000764
Chris Lattnered7a67b2006-02-10 01:24:09 +0000765 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000766 BasicBlock *ExitBlock = ExitBlocks[i];
Dan Gohman3ddbc242009-09-08 15:45:00 +0000767 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
768 pred_end(ExitBlock));
Bill Wendling90f90da2011-09-27 00:59:31 +0000769
Nick Lewycky61158242011-06-03 06:27:15 +0000770 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
771 // general, if we call it on all predecessors of all exits then it does.
Philip Reames9198b332015-01-28 23:06:47 +0000772 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa",
773 /*AliasAnalysis*/ nullptr, DT, LI,
774 /*PreserveLCSSA*/ true);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000775 }
Devang Patele192e3252007-10-03 21:16:08 +0000776}
777
Andrew Trick4104ed92012-04-10 05:14:37 +0000778/// UnswitchNontrivialCondition - We determined that the loop is profitable
779/// to unswitch when LIC equal Val. Split it into loop versions and test the
Devang Patel35747592007-10-03 21:17:43 +0000780/// condition outside of either loop. Return the loops created as Out1/Out2.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000781void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
Devang Patele192e3252007-10-03 21:16:08 +0000782 Loop *L) {
Devang Patele149d4e2008-07-02 01:18:13 +0000783 Function *F = loopHeader->getParent();
David Greened9c355d2010-01-05 01:27:04 +0000784 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000785 << loopHeader->getName() << " [" << L->getBlocks().size()
786 << " blocks] in Function " << F->getName()
787 << " when '" << *Val << "' == " << *LIC << "\n");
Devang Patele192e3252007-10-03 21:16:08 +0000788
Cameron Zwarich99de19b2011-02-11 06:08:28 +0000789 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
790 SE->forgetLoop(L);
791
Devang Pateled50fb52008-07-02 01:44:29 +0000792 LoopBlocks.clear();
793 NewBlocks.clear();
Devang Patele192e3252007-10-03 21:16:08 +0000794
795 // First step, split the preheader and exit blocks, and add these blocks to
796 // the LoopBlocks list.
Chandler Carruthd4500562015-01-19 12:36:53 +0000797 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, DT, LI);
Devang Patele192e3252007-10-03 21:16:08 +0000798 LoopBlocks.push_back(NewPreheader);
799
800 // We want the loop to come after the preheader, but before the exit blocks.
801 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
802
803 SmallVector<BasicBlock*, 8> ExitBlocks;
804 L->getUniqueExitBlocks(ExitBlocks);
805
806 // Split all of the edges from inside the loop to their exit blocks. Update
807 // the appropriate Phi nodes as we do so.
Devang Pateleb611dd2008-07-03 17:37:52 +0000808 SplitExitEdges(L, ExitBlocks);
Devang Patele192e3252007-10-03 21:16:08 +0000809
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000810 // The exit blocks may have been changed due to edge splitting, recompute.
811 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +0000812 L->getUniqueExitBlocks(ExitBlocks);
813
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000814 // Add exit blocks to the loop blocks.
815 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000816
817 // Next step, clone all of the basic blocks that make up the loop (including
818 // the loop preheader and exit blocks), keeping track of the mapping between
819 // the instructions and blocks.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000820 NewBlocks.reserve(LoopBlocks.size());
Rafael Espindola229e38f2010-10-13 01:36:30 +0000821 ValueToValueMapTy VMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000822 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000823 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
Andrew Trick4104ed92012-04-10 05:14:37 +0000824
Evan Chengba930442010-04-05 21:16:25 +0000825 NewBlocks.push_back(NewBB);
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000826 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
Evan Chengba930442010-04-05 21:16:25 +0000827 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000828 }
829
830 // Splice the newly inserted blocks into the function right before the
831 // original preheader.
Evan Chengba930442010-04-05 21:16:25 +0000832 F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
Chris Lattnerf48f7772004-04-19 18:07:02 +0000833 NewBlocks[0], F->end());
834
Hal Finkel74c2f352014-09-07 12:44:26 +0000835 // FIXME: We could register any cloned assumptions instead of clearing the
836 // whole function's cache.
Chandler Carruth66b31302015-01-04 12:03:27 +0000837 AC->clear();
Hal Finkel74c2f352014-09-07 12:44:26 +0000838
Chris Lattnerf48f7772004-04-19 18:07:02 +0000839 // Now we create the new Loop object for the versioned loop.
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000840 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000841
842 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
843 // Probably clone more loop-unswitch related loop properties.
844 BranchesInfo.cloneData(NewLoop, L, VMap);
845
Chris Lattnerf1b15162006-02-10 23:26:14 +0000846 Loop *ParentLoop = L->getParentLoop();
847 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000848 // Make sure to add the cloned preheader and exit blocks to the parent loop
849 // as well.
Chandler Carruth691addc2015-01-18 01:25:51 +0000850 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000851 }
Bill Wendling90f90da2011-09-27 00:59:31 +0000852
Chris Lattnerf1b15162006-02-10 23:26:14 +0000853 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000854 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000855 // The new exit block should be in the same loop as the old one.
856 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Chandler Carruth691addc2015-01-18 01:25:51 +0000857 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Andrew Trick4104ed92012-04-10 05:14:37 +0000858
Chris Lattnerf1b15162006-02-10 23:26:14 +0000859 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
860 "Exit block should have been split to have one successor!");
861 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
Devang Pateleb611dd2008-07-03 17:37:52 +0000862
Chris Lattnerf1b15162006-02-10 23:26:14 +0000863 // If the successor of the exit block had PHI nodes, add an entry for
864 // NewExit.
Jakub Staszak27da1232013-08-06 17:03:42 +0000865 for (BasicBlock::iterator I = ExitSucc->begin();
866 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnerf1b15162006-02-10 23:26:14 +0000867 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Rafael Espindola229e38f2010-10-13 01:36:30 +0000868 ValueToValueMapTy::iterator It = VMap.find(V);
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000869 if (It != VMap.end()) V = It->second;
Chris Lattnerf1b15162006-02-10 23:26:14 +0000870 PN->addIncoming(V, NewExit);
871 }
Bill Wendling90f90da2011-09-27 00:59:31 +0000872
873 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000874 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
875 ExitSucc->getFirstInsertionPt());
Bill Wendling90f90da2011-09-27 00:59:31 +0000876
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000877 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
878 I != E; ++I) {
879 BasicBlock *BB = *I;
Bill Wendling90f90da2011-09-27 00:59:31 +0000880 LandingPadInst *LPI = BB->getLandingPadInst();
881 LPI->replaceAllUsesWith(PN);
882 PN->addIncoming(LPI, BB);
883 }
884 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000885 }
886
887 // Rewrite the code to refer to itself.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +0000888 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
889 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
890 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner43f8d162011-01-08 08:15:20 +0000891 RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Trick4104ed92012-04-10 05:14:37 +0000892
Chris Lattnerf48f7772004-04-19 18:07:02 +0000893 // Rewrite the original preheader to select between versions of the loop.
Devang Patele149d4e2008-07-02 01:18:13 +0000894 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000895 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000896 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000897
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000898 // Emit the new branch that selects between the two versions of this loop.
899 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
Devang Pateld4911982007-07-31 08:03:26 +0000900 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patel83cc3f82007-09-20 23:45:50 +0000901 OldBR->eraseFromParent();
Devang Patela8823282007-08-02 15:25:57 +0000902
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000903 LoopProcessWorklist.push_back(NewLoop);
Devang Patel7d165e12007-07-30 23:07:10 +0000904 redoLoop = true;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000905
Chris Lattner5814d9d92010-04-20 05:09:16 +0000906 // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
907 // deletes the instruction (for example by simplifying a PHI that feeds into
908 // the condition that we're unswitching on), we don't rewrite the second
909 // iteration.
910 WeakVH LICHandle(LIC);
Andrew Trick4104ed92012-04-10 05:14:37 +0000911
Chris Lattnerf48f7772004-04-19 18:07:02 +0000912 // Now we rewrite the original code to know that the condition is true and the
913 // new code to know that the condition is false.
Evan Chengba930442010-04-05 21:16:25 +0000914 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
Devang Pateleb611dd2008-07-03 17:37:52 +0000915
Chris Lattner5814d9d92010-04-20 05:09:16 +0000916 // It's possible that simplifying one loop could cause the other to be
917 // changed to another value or a constant. If its a constant, don't simplify
918 // it.
919 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
920 LICHandle && !isa<Constant>(LICHandle))
921 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000922}
923
Chris Lattner6fd13622006-02-17 00:31:07 +0000924/// RemoveFromWorklist - Remove all instances of I from the worklist vector
925/// specified.
Andrew Trick4104ed92012-04-10 05:14:37 +0000926static void RemoveFromWorklist(Instruction *I,
Chris Lattner6fd13622006-02-17 00:31:07 +0000927 std::vector<Instruction*> &Worklist) {
Jakub Staszak8f46e912012-10-16 19:52:32 +0000928
929 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
930 Worklist.end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000931}
932
933/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
934/// program, replacing all uses with V and update the worklist.
Andrew Trick4104ed92012-04-10 05:14:37 +0000935static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Pateld4911982007-07-31 08:03:26 +0000936 std::vector<Instruction*> &Worklist,
937 Loop *L, LPPassManager *LPM) {
David Greened9c355d2010-01-05 01:27:04 +0000938 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
Chris Lattner6fd13622006-02-17 00:31:07 +0000939
940 // Add uses to the worklist, which may be dead now.
941 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
942 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
943 Worklist.push_back(Use);
944
945 // Add users to the worklist which may be simplified now.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000946 for (User *U : I->users())
947 Worklist.push_back(cast<Instruction>(U));
Devang Pateld4911982007-07-31 08:03:26 +0000948 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +0000949 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +0000950 I->replaceAllUsesWith(V);
951 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +0000952 ++NumSimplify;
953}
954
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000955// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
956// the value specified by Val in the specified loop, or we know it does NOT have
957// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000958void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000959 Constant *Val,
960 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000961 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Andrew Trick4104ed92012-04-10 05:14:37 +0000962
Chris Lattnerf48f7772004-04-19 18:07:02 +0000963 // FIXME: Support correlated properties, like:
964 // for (...)
965 // if (li1 < li2)
966 // ...
967 // if (li1 > li2)
968 // ...
Andrew Trick4104ed92012-04-10 05:14:37 +0000969
Chris Lattner6e263152006-02-10 02:30:37 +0000970 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
971 // selects, switches.
Chris Lattner6fd13622006-02-17 00:31:07 +0000972 std::vector<Instruction*> Worklist;
Owen Anderson47db9412009-07-22 00:24:57 +0000973 LLVMContext &Context = Val->getContext();
974
Chris Lattner6fd13622006-02-17 00:31:07 +0000975 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
976 // in the loop with the appropriate one directly.
Owen Anderson55f1c092009-08-13 21:58:54 +0000977 if (IsEqual || (isa<ConstantInt>(Val) &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000978 Val->getType()->isIntegerTy(1))) {
Chris Lattner8a5a3242006-02-22 06:37:14 +0000979 Value *Replacement;
980 if (IsEqual)
981 Replacement = Val;
982 else
Andrew Trick4104ed92012-04-10 05:14:37 +0000983 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
Reid Spencercddc9df2007-01-12 04:24:46 +0000984 !cast<ConstantInt>(Val)->getZExtValue());
Andrew Trick4104ed92012-04-10 05:14:37 +0000985
Chandler Carruthcdf47882014-03-09 03:16:01 +0000986 for (User *U : LIC->users()) {
987 Instruction *UI = dyn_cast<Instruction>(U);
988 if (!UI || !L->contains(UI))
Evan Cheng1b55f562011-05-24 23:12:57 +0000989 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000990 Worklist.push_back(UI);
Evan Cheng1b55f562011-05-24 23:12:57 +0000991 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000992
Jakub Staszak27da1232013-08-06 17:03:42 +0000993 for (std::vector<Instruction*>::iterator UI = Worklist.begin(),
994 UE = Worklist.end(); UI != UE; ++UI)
Andrew Trick4104ed92012-04-10 05:14:37 +0000995 (*UI)->replaceUsesOfWith(LIC, Replacement);
996
Chris Lattnerc832c1b2010-04-05 21:18:32 +0000997 SimplifyCode(Worklist, L);
998 return;
999 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001000
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001001 // Otherwise, we don't know the precise value of LIC, but we do know that it
1002 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1003 // can. This case occurs when we unswitch switch statements.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001004 for (User *U : LIC->users()) {
1005 Instruction *UI = dyn_cast<Instruction>(U);
1006 if (!UI || !L->contains(UI))
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001007 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001008
Chandler Carruthcdf47882014-03-09 03:16:01 +00001009 Worklist.push_back(UI);
Chris Lattner6fd13622006-02-17 00:31:07 +00001010
Andrew Trick4104ed92012-04-10 05:14:37 +00001011 // TODO: We could do other simplifications, for example, turning
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001012 // 'icmp eq LIC, Val' -> false.
1013
1014 // If we know that LIC is not Val, use this info to simplify code.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001015 SwitchInst *SI = dyn_cast<SwitchInst>(UI);
Craig Topperf40110f2014-04-25 05:29:35 +00001016 if (!SI || !isa<ConstantInt>(Val)) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001017
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001018 SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00001019 // Default case is live for multiple values.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001020 if (DeadCase == SI->case_default()) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001021
1022 // Found a dead case value. Don't remove PHI nodes in the
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001023 // successor if they become single-entry, those PHI nodes may
1024 // be in the Users list.
Nick Lewycky61158242011-06-03 06:27:15 +00001025
Evan Cheng1b55f562011-05-24 23:12:57 +00001026 BasicBlock *Switch = SI->getParent();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001027 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
Evan Cheng1b55f562011-05-24 23:12:57 +00001028 BasicBlock *Latch = L->getLoopLatch();
Andrew Trick4104ed92012-04-10 05:14:37 +00001029
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +00001030 BranchesInfo.setUnswitched(SI, Val);
Andrew Trick4104ed92012-04-10 05:14:37 +00001031
Nick Lewycky61158242011-06-03 06:27:15 +00001032 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
Evan Cheng9605a692011-05-25 18:17:13 +00001033 // If the DeadCase successor dominates the loop latch, then the
1034 // transformation isn't safe since it will delete the sole predecessor edge
1035 // to the latch.
1036 if (Latch && DT->dominates(SISucc, Latch))
1037 continue;
Evan Cheng1b55f562011-05-24 23:12:57 +00001038
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001039 // FIXME: This is a hack. We need to keep the successor around
1040 // and hooked up so as to preserve the loop structure, because
1041 // trying to update it is complicated. So instead we preserve the
1042 // loop structure and put the block on a dead code path.
Chandler Carruthd4500562015-01-19 12:36:53 +00001043 SplitEdge(Switch, SISucc, DT, LI);
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001044 // Compute the successors instead of relying on the return value
1045 // of SplitEdge, since it may have split the switch successor
1046 // after PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001047 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001048 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1049 // Create an "unreachable" destination.
1050 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1051 Switch->getParent(),
1052 OldSISucc);
1053 new UnreachableInst(Context, Abort);
1054 // Force the new case destination to branch to the "unreachable"
1055 // block while maintaining a (dead) CFG edge to the old block.
1056 NewSISucc->getTerminator()->eraseFromParent();
1057 BranchInst::Create(Abort, OldSISucc,
1058 ConstantInt::getTrue(Context), NewSISucc);
1059 // Release the PHI operands for this edge.
1060 for (BasicBlock::iterator II = NewSISucc->begin();
1061 PHINode *PN = dyn_cast<PHINode>(II); ++II)
1062 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1063 UndefValue::get(PN->getType()));
1064 // Tell the domtree about the new block. We don't fully update the
1065 // domtree here -- instead we force it to do a full recomputation
1066 // after the pass is complete -- but we do need to inform it of
1067 // new blocks.
1068 if (DT)
1069 DT->addNewBlock(Abort, NewSISucc);
Chris Lattner6fd13622006-02-17 00:31:07 +00001070 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001071
Devang Pateld4911982007-07-31 08:03:26 +00001072 SimplifyCode(Worklist, L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001073}
1074
Mike Stumpdeaf5722009-09-09 17:57:16 +00001075/// SimplifyCode - Okay, now that we have simplified some instructions in the
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001076/// loop, walk over it and constant prop, dce, and fold control flow where
1077/// possible. Note that this is effectively a very simple loop-structure-aware
1078/// optimizer. During processing of this loop, L could very well be deleted, so
1079/// it must not be used.
1080///
1081/// FIXME: When the loop optimizer is more mature, separate this out to a new
1082/// pass.
1083///
Devang Pateld4911982007-07-31 08:03:26 +00001084void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001085 while (!Worklist.empty()) {
1086 Instruction *I = Worklist.back();
1087 Worklist.pop_back();
Duncan Sandsbb2cd022010-11-23 20:24:21 +00001088
Chris Lattner6fd13622006-02-17 00:31:07 +00001089 // Simple DCE.
1090 if (isInstructionTriviallyDead(I)) {
David Greened9c355d2010-01-05 01:27:04 +00001091 DEBUG(dbgs() << "Remove dead instruction '" << *I);
Andrew Trick4104ed92012-04-10 05:14:37 +00001092
Chris Lattner6fd13622006-02-17 00:31:07 +00001093 // Add uses to the worklist, which may be dead now.
1094 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1095 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1096 Worklist.push_back(Use);
Devang Pateld4911982007-07-31 08:03:26 +00001097 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001098 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +00001099 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001100 ++NumSimplify;
1101 continue;
1102 }
Duncan Sandsaef146b2010-11-18 19:59:41 +00001103
Chris Lattner66e809a2010-04-20 05:33:18 +00001104 // See if instruction simplification can hack this up. This is common for
1105 // things like "select false, X, Y" after unswitching made the condition be
Peter Collingbourne9a03c732012-05-20 01:32:09 +00001106 // 'false'. TODO: update the domtree properly so we can pass it here.
1107 if (Value *V = SimplifyInstruction(I))
Duncan Sandsaef146b2010-11-18 19:59:41 +00001108 if (LI->replacementPreservesLCSSAForm(I, V)) {
1109 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1110 continue;
1111 }
1112
Chris Lattner6fd13622006-02-17 00:31:07 +00001113 // Special case hacks that appear commonly in unswitched code.
Chris Lattner66e809a2010-04-20 05:33:18 +00001114 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001115 if (BI->isUnconditional()) {
1116 // If BI's parent is the only pred of the successor, fold the two blocks
1117 // together.
1118 BasicBlock *Pred = BI->getParent();
1119 BasicBlock *Succ = BI->getSuccessor(0);
1120 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1121 if (!SinglePred) continue; // Nothing to do.
1122 assert(SinglePred == Pred && "CFG broken");
1123
Andrew Trick4104ed92012-04-10 05:14:37 +00001124 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001125 << Succ->getName() << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +00001126
Chris Lattner6fd13622006-02-17 00:31:07 +00001127 // Resolve any single entry PHI nodes in Succ.
1128 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Pateld4911982007-07-31 08:03:26 +00001129 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Andrew Trick4104ed92012-04-10 05:14:37 +00001130
Jay Foad61ea0e42011-06-23 09:09:15 +00001131 // If Succ has any successors with PHI nodes, update them to have
1132 // entries coming from Pred instead of Succ.
1133 Succ->replaceAllUsesWith(Pred);
Andrew Trick4104ed92012-04-10 05:14:37 +00001134
Chris Lattner6fd13622006-02-17 00:31:07 +00001135 // Move all of the successor contents from Succ to Pred.
1136 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1137 Succ->end());
Devang Pateld4911982007-07-31 08:03:26 +00001138 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001139 BI->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001140 RemoveFromWorklist(BI, Worklist);
Andrew Trick4104ed92012-04-10 05:14:37 +00001141
Chris Lattner6fd13622006-02-17 00:31:07 +00001142 // Remove Succ from the loop tree.
1143 LI->removeBlock(Succ);
Devang Pateld4911982007-07-31 08:03:26 +00001144 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001145 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001146 ++NumSimplify;
Chris Lattner66e809a2010-04-20 05:33:18 +00001147 continue;
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001148 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001149
Chris Lattner66e809a2010-04-20 05:33:18 +00001150 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001151 }
1152 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001153}