blob: 42db079a5d9bd7f386d66520e2b96005eb5f2a1d [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"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000045#include "llvm/IR/Module.h"
Weiming Zhaof1abad52015-06-23 05:31:09 +000046#include "llvm/IR/MDBuilder.h"
Chris Lattner89762192006-02-09 20:15:48 +000047#include "llvm/Support/CommandLine.h"
Reid Spencer557ab152007-02-05 23:32:05 +000048#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000049#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000050#include "llvm/Transforms/Utils/BasicBlockUtils.h"
51#include "llvm/Transforms/Utils/Cloning.h"
52#include "llvm/Transforms/Utils/Local.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000053#include <algorithm>
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000054#include <map>
Chris Lattner2826e052006-02-09 19:14:52 +000055#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000056using namespace llvm;
57
Chandler Carruth964daaa2014-04-22 02:55:47 +000058#define DEBUG_TYPE "loop-unswitch"
59
Chris Lattner79a42ac2006-12-19 21:40:18 +000060STATISTIC(NumBranches, "Number of branches unswitched");
61STATISTIC(NumSwitches, "Number of switches unswitched");
62STATISTIC(NumSelects , "Number of selects unswitched");
63STATISTIC(NumTrivial , "Number of unswitches that are trivial");
64STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000065STATISTIC(TotalInsts, "Total number of instructions analyzed");
Chris Lattner79a42ac2006-12-19 21:40:18 +000066
Stepan Dyatkovskiy2931a592012-01-16 20:48:04 +000067// The specific value of 100 here was chosen based only on intuition and a
Dan Gohman71ca6522009-10-13 17:50:43 +000068// few specific examples.
Dan Gohmand78c4002008-05-13 00:00:25 +000069static cl::opt<unsigned>
70Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000071 cl::init(100), cl::Hidden);
Andrew Trick4104ed92012-04-10 05:14:37 +000072
Dan Gohmand78c4002008-05-13 00:00:25 +000073namespace {
Andrew Trick4104ed92012-04-10 05:14:37 +000074
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000075 class LUAnalysisCache {
76
77 typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
78 UnswitchedValsMap;
Andrew Trick4104ed92012-04-10 05:14:37 +000079
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000080 typedef UnswitchedValsMap::iterator UnswitchedValsIt;
Andrew Trick4104ed92012-04-10 05:14:37 +000081
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000082 struct LoopProperties {
83 unsigned CanBeUnswitchedCount;
84 unsigned SizeEstimation;
85 UnswitchedValsMap UnswitchedVals;
86 };
Andrew Trick4104ed92012-04-10 05:14:37 +000087
88 // Here we use std::map instead of DenseMap, since we need to keep valid
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000089 // LoopProperties pointer for current loop for better performance.
90 typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
91 typedef LoopPropsMap::iterator LoopPropsMapIt;
Andrew Trick4104ed92012-04-10 05:14:37 +000092
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000093 LoopPropsMap LoopsProperties;
Jakub Staszak27da1232013-08-06 17:03:42 +000094 UnswitchedValsMap *CurLoopInstructions;
95 LoopProperties *CurrentLoopProperties;
Andrew Trick4104ed92012-04-10 05:14:37 +000096
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000097 // Max size of code we can produce on remained iterations.
98 unsigned MaxSize;
Andrew Trick4104ed92012-04-10 05:14:37 +000099
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000100 public:
Andrew Trick4104ed92012-04-10 05:14:37 +0000101
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000102 LUAnalysisCache() :
Craig Topperf40110f2014-04-25 05:29:35 +0000103 CurLoopInstructions(nullptr), CurrentLoopProperties(nullptr),
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000104 MaxSize(Threshold)
105 {}
Andrew Trick4104ed92012-04-10 05:14:37 +0000106
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000107 // Analyze loop. Check its size, calculate is it possible to unswitch
108 // it. Returns true if we can unswitch this loop.
Hal Finkel57f03dd2014-09-07 13:49:57 +0000109 bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000110 AssumptionCache *AC);
Andrew Trick4104ed92012-04-10 05:14:37 +0000111
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000112 // Clean all data related to given loop.
Jakub Staszak27da1232013-08-06 17:03:42 +0000113 void forgetLoop(const Loop *L);
Andrew Trick4104ed92012-04-10 05:14:37 +0000114
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000115 // Mark case value as unswitched.
116 // Since SI instruction can be partly unswitched, in order to avoid
117 // extra unswitching in cloned loops keep track all unswitched values.
Jakub Staszak27da1232013-08-06 17:03:42 +0000118 void setUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000119
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000120 // Check was this case value unswitched before or not.
Jakub Staszak27da1232013-08-06 17:03:42 +0000121 bool isUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000122
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000123 // Clone all loop-unswitch related loop properties.
124 // Redistribute unswitching quotas.
125 // Note, that new loop data is stored inside the VMap.
Jakub Staszak27da1232013-08-06 17:03:42 +0000126 void cloneData(const Loop *NewLoop, const Loop *OldLoop,
127 const ValueToValueMapTy &VMap);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000128 };
Andrew Trick4104ed92012-04-10 05:14:37 +0000129
Chris Lattner2dd09db2009-09-02 06:11:42 +0000130 class LoopUnswitch : public LoopPass {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000131 LoopInfo *LI; // Loop information
Devang Patel901a27d2007-03-07 00:26:10 +0000132 LPPassManager *LPM;
Chandler Carruth66b31302015-01-04 12:03:27 +0000133 AssumptionCache *AC;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000134
Devang Patel901a27d2007-03-07 00:26:10 +0000135 // LoopProcessWorklist - Used to check if second loop needs processing
136 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000137 std::vector<Loop*> LoopProcessWorklist;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000138
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000139 LUAnalysisCache BranchesInfo;
Andrew Trick4104ed92012-04-10 05:14:37 +0000140
Devang Patel506310d2007-06-06 00:21:03 +0000141 bool OptimizeForSize;
Devang Patel7d165e12007-07-30 23:07:10 +0000142 bool redoLoop;
Devang Patela69f9872007-10-05 22:29:34 +0000143
Devang Patele149d4e2008-07-02 01:18:13 +0000144 Loop *currentLoop;
Devang Patela69f9872007-10-05 22:29:34 +0000145 DominatorTree *DT;
Devang Patele149d4e2008-07-02 01:18:13 +0000146 BasicBlock *loopHeader;
147 BasicBlock *loopPreheader;
Andrew Trick4104ed92012-04-10 05:14:37 +0000148
Devang Pateled50fb52008-07-02 01:44:29 +0000149 // LoopBlocks contains all of the basic blocks of the loop, including the
Andrew Trick4104ed92012-04-10 05:14:37 +0000150 // preheader of the loop, the body of the loop, and the exit blocks of the
Devang Pateled50fb52008-07-02 01:44:29 +0000151 // loop, in that order.
152 std::vector<BasicBlock*> LoopBlocks;
153 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
154 std::vector<BasicBlock*> NewBlocks;
Devang Pateleb611dd2008-07-03 17:37:52 +0000155
Chris Lattnerf48f7772004-04-19 18:07:02 +0000156 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000157 static char ID; // Pass ID, replacement for typeid
Andrew Trick4104ed92012-04-10 05:14:37 +0000158 explicit LoopUnswitch(bool Os = false) :
159 LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
Craig Topperf40110f2014-04-25 05:29:35 +0000160 currentLoop(nullptr), DT(nullptr), loopHeader(nullptr),
161 loopPreheader(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000162 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
163 }
Devang Patel09f162c2007-05-01 21:15:47 +0000164
Craig Topper3e4c6972014-03-05 09:10:37 +0000165 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Devang Patele149d4e2008-07-02 01:18:13 +0000166 bool processCurrentLoop();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000167
168 /// This transformation requires natural loop information & requires that
Chris Lattnerbc1a65a2010-08-29 17:23:19 +0000169 /// loop preheaders be inserted into the CFG.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000170 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000171 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +0000172 AU.addRequired<AssumptionCacheTracker>();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000173 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +0000174 AU.addPreservedID(LoopSimplifyID);
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000175 AU.addRequired<LoopInfoWrapperPass>();
176 AU.addPreserved<LoopInfoWrapperPass>();
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000177 AU.addRequiredID(LCSSAID);
Devang Pateld4911982007-07-31 08:03:26 +0000178 AU.addPreservedID(LCSSAID);
Chandler Carruth73523022014-01-13 13:07:17 +0000179 AU.addPreserved<DominatorTreeWrapperPass>();
Cameron Zwarich99de19b2011-02-11 06:08:28 +0000180 AU.addPreserved<ScalarEvolution>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000181 AU.addRequired<TargetTransformInfoWrapperPass>();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000182 }
183
184 private:
Devang Pateld4911982007-07-31 08:03:26 +0000185
Craig Topper3e4c6972014-03-05 09:10:37 +0000186 void releaseMemory() override {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000187 BranchesInfo.forgetLoop(currentLoop);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000188 }
189
Devang Patele149d4e2008-07-02 01:18:13 +0000190 void initLoopData() {
191 loopHeader = currentLoop->getHeader();
192 loopPreheader = currentLoop->getLoopPreheader();
193 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000194
Chris Lattner559c8672008-04-21 00:25:49 +0000195 /// Split all of the edges from inside the loop to their exit blocks.
196 /// Update the appropriate Phi nodes as we do so.
Craig Topperb94011f2013-07-14 04:42:23 +0000197 void SplitExitEdges(Loop *L, const SmallVectorImpl<BasicBlock *> &ExitBlocks);
Devang Patela69f9872007-10-05 22:29:34 +0000198
Weiming Zhaof1abad52015-06-23 05:31:09 +0000199 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,
200 TerminatorInst *TI = nullptr);
Chris Lattner29f771b2006-02-18 01:27:45 +0000201 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000202 BasicBlock *ExitBlock, TerminatorInst *TI);
203 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
204 TerminatorInst *TI);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000205
206 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
207 Constant *Val, bool isEqual);
Devang Patel3304e462007-06-28 00:49:00 +0000208
209 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
Andrew Trick4104ed92012-04-10 05:14:37 +0000210 BasicBlock *TrueDest,
Devang Patel3304e462007-06-28 00:49:00 +0000211 BasicBlock *FalseDest,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000212 Instruction *InsertPt,
213 TerminatorInst *TI);
Devang Patel3304e462007-06-28 00:49:00 +0000214
Devang Pateld4911982007-07-31 08:03:26 +0000215 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Craig Topperf40110f2014-04-25 05:29:35 +0000216 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = nullptr,
217 BasicBlock **LoopExit = nullptr);
Devang Patele149d4e2008-07-02 01:18:13 +0000218
Chris Lattnerf48f7772004-04-19 18:07:02 +0000219 };
Alexander Kornienko70bc5f12015-06-19 15:57:42 +0000220} // namespace
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000221
222// Analyze loop. Check its size, calculate is it possible to unswitch
223// it. Returns true if we can unswitch this loop.
Hal Finkel57f03dd2014-09-07 13:49:57 +0000224bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000225 AssumptionCache *AC) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000226
Jakub Staszak27da1232013-08-06 17:03:42 +0000227 LoopPropsMapIt PropsIt;
228 bool Inserted;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000229 std::tie(PropsIt, Inserted) =
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000230 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
Andrew Trick4104ed92012-04-10 05:14:37 +0000231
Jakub Staszak27da1232013-08-06 17:03:42 +0000232 LoopProperties &Props = PropsIt->second;
Andrew Trick4104ed92012-04-10 05:14:37 +0000233
Jakub Staszak27da1232013-08-06 17:03:42 +0000234 if (Inserted) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000235 // New loop.
236
237 // Limit the number of instructions to avoid causing significant code
238 // expansion, and the number of basic blocks, to avoid loops with
239 // large numbers of branches which cause loop unswitching to go crazy.
240 // This is a very ad-hoc heuristic.
Andrew Trick4104ed92012-04-10 05:14:37 +0000241
Hal Finkel57f03dd2014-09-07 13:49:57 +0000242 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000243 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000244
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000245 // FIXME: This is overly conservative because it does not take into
246 // consideration code simplification opportunities and code that can
247 // be shared by the resultant unswitched loops.
248 CodeMetrics Metrics;
Jakub Staszak27da1232013-08-06 17:03:42 +0000249 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000250 I != E; ++I)
Hal Finkel57f03dd2014-09-07 13:49:57 +0000251 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000252
253 Props.SizeEstimation = std::min(Metrics.NumInsts, Metrics.NumBlocks * 5);
254 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
255 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
James Molloy4f6fb952012-12-20 16:04:27 +0000256
257 if (Metrics.notDuplicatable) {
258 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak27da1232013-08-06 17:03:42 +0000259 << L->getHeader()->getName() << ", contents cannot be "
260 << "duplicated!\n");
James Molloy4f6fb952012-12-20 16:04:27 +0000261 return false;
262 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000263 }
264
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000265 if (!Props.CanBeUnswitchedCount) {
266 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak27da1232013-08-06 17:03:42 +0000267 << L->getHeader()->getName() << ", cost too high: "
268 << L->getBlocks().size() << "\n");
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000269 return false;
270 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000271
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000272 // Be careful. This links are good only before new loop addition.
273 CurrentLoopProperties = &Props;
274 CurLoopInstructions = &Props.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000275
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000276 return true;
277}
278
279// Clean all data related to given loop.
Jakub Staszak27da1232013-08-06 17:03:42 +0000280void LUAnalysisCache::forgetLoop(const Loop *L) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000281
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000282 LoopPropsMapIt LIt = LoopsProperties.find(L);
283
284 if (LIt != LoopsProperties.end()) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000285 LoopProperties &Props = LIt->second;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000286 MaxSize += Props.CanBeUnswitchedCount * Props.SizeEstimation;
287 LoopsProperties.erase(LIt);
288 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000289
Craig Topperf40110f2014-04-25 05:29:35 +0000290 CurrentLoopProperties = nullptr;
291 CurLoopInstructions = nullptr;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000292}
293
294// Mark case value as unswitched.
295// Since SI instruction can be partly unswitched, in order to avoid
296// extra unswitching in cloned loops keep track all unswitched values.
Jakub Staszak27da1232013-08-06 17:03:42 +0000297void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000298 (*CurLoopInstructions)[SI].insert(V);
299}
300
301// Check was this case value unswitched before or not.
Jakub Staszak27da1232013-08-06 17:03:42 +0000302bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000303 return (*CurLoopInstructions)[SI].count(V);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000304}
305
306// Clone all loop-unswitch related loop properties.
307// Redistribute unswitching quotas.
308// Note, that new loop data is stored inside the VMap.
Jakub Staszak27da1232013-08-06 17:03:42 +0000309void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
310 const ValueToValueMapTy &VMap) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000311
Jakub Staszak27da1232013-08-06 17:03:42 +0000312 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
313 LoopProperties &OldLoopProps = *CurrentLoopProperties;
314 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000315
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000316 // Reallocate "can-be-unswitched quota"
317
318 --OldLoopProps.CanBeUnswitchedCount;
319 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
320 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
321 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
Andrew Trick4104ed92012-04-10 05:14:37 +0000322
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000323 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
Andrew Trick4104ed92012-04-10 05:14:37 +0000324
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000325 // Clone unswitched values info:
326 // for new loop switches we clone info about values that was
327 // already unswitched and has redundant successors.
328 for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000329 const SwitchInst *OldInst = I->first;
330 Value *NewI = VMap.lookup(OldInst);
331 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000332 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
Andrew Trick4104ed92012-04-10 05:14:37 +0000333
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000334 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
335 }
336}
337
Dan Gohmand78c4002008-05-13 00:00:25 +0000338char LoopUnswitch::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000339INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
340 false, false)
Chandler Carruth705b1852015-01-31 03:43:40 +0000341INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruth66b31302015-01-04 12:03:27 +0000342INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000343INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000344INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000345INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000346INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
347 false, false)
Chris Lattnerf48f7772004-04-19 18:07:02 +0000348
Andrew Trick4104ed92012-04-10 05:14:37 +0000349Pass *llvm::createLoopUnswitchPass(bool Os) {
350 return new LoopUnswitch(Os);
Devang Patel506310d2007-06-06 00:21:03 +0000351}
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000352
353/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
354/// invariant in the loop, or has an invariant piece, return the invariant.
355/// Otherwise, return null.
356static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000357
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000358 // We started analyze new instruction, increment scanned instructions counter.
359 ++TotalInsts;
Andrew Trick4104ed92012-04-10 05:14:37 +0000360
Chris Lattner302240d2010-02-02 02:26:54 +0000361 // We can never unswitch on vector conditions.
Duncan Sands19d0b472010-02-16 11:11:14 +0000362 if (Cond->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000363 return nullptr;
Chris Lattner302240d2010-02-02 02:26:54 +0000364
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000365 // Constants should be folded, not unswitched on!
Craig Topperf40110f2014-04-25 05:29:35 +0000366 if (isa<Constant>(Cond)) return nullptr;
Devang Patel3c723c82007-06-28 00:44:10 +0000367
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000368 // TODO: Handle: br (VARIANT|INVARIANT).
Devang Patelfe57d102008-11-03 19:38:07 +0000369
Dan Gohman4d6149f2009-07-14 01:37:59 +0000370 // Hoist simple values out.
Dan Gohmanc43e4792009-07-15 01:25:43 +0000371 if (L->makeLoopInvariant(Cond, Changed))
Dan Gohman4d6149f2009-07-14 01:37:59 +0000372 return Cond;
Dan Gohman4d6149f2009-07-14 01:37:59 +0000373
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000374 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
375 if (BO->getOpcode() == Instruction::And ||
376 BO->getOpcode() == Instruction::Or) {
377 // If either the left or right side is invariant, we can unswitch on this,
378 // which will cause the branch to go away in one loop and the condition to
379 // simplify in the other one.
380 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
381 return LHS;
382 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
383 return RHS;
384 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000385
Craig Topperf40110f2014-04-25 05:29:35 +0000386 return nullptr;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000387}
388
Devang Patel901a27d2007-03-07 00:26:10 +0000389bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000390 if (skipOptnoneFunction(L))
391 return false;
392
Chandler Carruth66b31302015-01-04 12:03:27 +0000393 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
394 *L->getHeader()->getParent());
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000395 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Devang Patel901a27d2007-03-07 00:26:10 +0000396 LPM = &LPM_Ref;
Chandler Carruth73523022014-01-13 13:07:17 +0000397 DominatorTreeWrapperPass *DTWP =
398 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperf40110f2014-04-25 05:29:35 +0000399 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Devang Patele149d4e2008-07-02 01:18:13 +0000400 currentLoop = L;
Devang Patel40519f02008-09-04 22:43:59 +0000401 Function *F = currentLoop->getHeader()->getParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000402 bool Changed = false;
Devang Patel7d165e12007-07-30 23:07:10 +0000403 do {
Dan Gohman2734ebd2010-03-10 19:38:49 +0000404 assert(currentLoop->isLCSSAForm(*DT));
Devang Patel7d165e12007-07-30 23:07:10 +0000405 redoLoop = false;
Devang Patele149d4e2008-07-02 01:18:13 +0000406 Changed |= processCurrentLoop();
Devang Patel7d165e12007-07-30 23:07:10 +0000407 } while(redoLoop);
408
Devang Patel40519f02008-09-04 22:43:59 +0000409 if (Changed) {
410 // FIXME: Reconstruct dom info, because it is not preserved properly.
411 if (DT)
Chandler Carruth73523022014-01-13 13:07:17 +0000412 DT->recalculate(*F);
Devang Patel40519f02008-09-04 22:43:59 +0000413 }
Devang Patel7d165e12007-07-30 23:07:10 +0000414 return Changed;
415}
416
Andrew Trick4104ed92012-04-10 05:14:37 +0000417/// processCurrentLoop - Do actual work and unswitch loop if possible
Devang Patele149d4e2008-07-02 01:18:13 +0000418/// and profitable.
419bool LoopUnswitch::processCurrentLoop() {
Devang Patel7d165e12007-07-30 23:07:10 +0000420 bool Changed = false;
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000421
422 initLoopData();
Andrew Trick4104ed92012-04-10 05:14:37 +0000423
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000424 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
425 if (!loopPreheader)
426 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000427
Andrew Trick4442bfe2012-04-10 05:14:42 +0000428 // Loops with indirectbr cannot be cloned.
429 if (!currentLoop->isSafeToClone())
430 return false;
431
432 // Without dedicated exits, splitting the exit edge may fail.
433 if (!currentLoop->hasDedicatedExits())
434 return false;
435
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000436 LLVMContext &Context = loopHeader->getContext();
Andrew Trick4104ed92012-04-10 05:14:37 +0000437
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000438 // Probably we reach the quota of branches for this loop. If so
439 // stop unswitching.
Chandler Carruth705b1852015-01-31 03:43:40 +0000440 if (!BranchesInfo.countLoop(
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000441 currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
442 *currentLoop->getHeader()->getParent()),
Chandler Carruth705b1852015-01-31 03:43:40 +0000443 AC))
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000444 return false;
Devang Patel7d165e12007-07-30 23:07:10 +0000445
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000446 // Loop over all of the basic blocks in the loop. If we find an interior
447 // block that is branching on a loop-invariant condition, we can unswitch this
448 // loop.
Andrew Trick4104ed92012-04-10 05:14:37 +0000449 for (Loop::block_iterator I = currentLoop->block_begin(),
Chris Lattnerc832c1b2010-04-05 21:18:32 +0000450 E = currentLoop->block_end(); I != E; ++I) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000451 TerminatorInst *TI = (*I)->getTerminator();
452 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
453 // If this isn't branching on an invariant condition, we can't unswitch
454 // it.
455 if (BI->isConditional()) {
456 // See if this, or some part of it, is loop invariant. If so, we can
457 // unswitch on it if we desire.
Andrew Trick4104ed92012-04-10 05:14:37 +0000458 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000459 currentLoop, Changed);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000460 if (LoopCond &&
461 UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000462 ++NumBranches;
463 return true;
464 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000465 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000466 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000467 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000468 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000469 unsigned NumCases = SI->getNumCases();
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000470 if (LoopCond && NumCases) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000471 // Find a value to unswitch on:
472 // FIXME: this should chose the most expensive case!
Nick Lewycky61158242011-06-03 06:27:15 +0000473 // FIXME: scan for a case with a non-critical edge?
Craig Topperf40110f2014-04-25 05:29:35 +0000474 Constant *UnswitchVal = nullptr;
Andrew Trick4104ed92012-04-10 05:14:37 +0000475
Devang Patel967b84c2007-02-26 19:31:58 +0000476 // Do not process same value again and again.
Chad Rosier3ba90a12011-12-22 21:10:46 +0000477 // At this point we have some cases already unswitched and
478 // some not yet unswitched. Let's find the first not yet unswitched one.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +0000479 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000480 i != e; ++i) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000481 Constant *UnswitchValCandidate = i.getCaseValue();
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000482 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
Chad Rosier3ba90a12011-12-22 21:10:46 +0000483 UnswitchVal = UnswitchValCandidate;
484 break;
485 }
486 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000487
Chad Rosier3ba90a12011-12-22 21:10:46 +0000488 if (!UnswitchVal)
Devang Patel967b84c2007-02-26 19:31:58 +0000489 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000490
Devang Patele149d4e2008-07-02 01:18:13 +0000491 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000492 ++NumSwitches;
493 return true;
494 }
495 }
496 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000497
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000498 // Scan the instructions to check for unswitchable values.
Andrew Trick4104ed92012-04-10 05:14:37 +0000499 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000500 BBI != E; ++BBI)
501 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000502 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000503 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000504 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson23a204d2009-07-31 17:39:07 +0000505 ConstantInt::getTrue(Context))) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000506 ++NumSelects;
507 return true;
508 }
509 }
510 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000511 return Changed;
512}
513
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000514/// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
515/// loop with no side effects (including infinite loops).
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000516///
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000517/// If true, we return true and set ExitBB to the block we
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000518/// exit through.
519///
520static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
521 BasicBlock *&ExitBB,
522 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000523 if (!Visited.insert(BB).second) {
Nick Lewyckyd9d1de42011-12-23 23:49:25 +0000524 // Already visited. Without more analysis, this could indicate an infinite
525 // loop.
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000526 return false;
Jakub Staszak27da1232013-08-06 17:03:42 +0000527 }
528 if (!L->contains(BB)) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000529 // Otherwise, this is a loop exit, this is fine so long as this is the
530 // first exit.
Craig Topperf40110f2014-04-25 05:29:35 +0000531 if (ExitBB) return false;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000532 ExitBB = BB;
Edward O'Callaghan2b8fed12009-11-25 05:38:41 +0000533 return true;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000534 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000535
Chris Lattnerbaddba42006-02-17 06:39:56 +0000536 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000537 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000538 // Check to see if the successor is a trivial loop exit.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000539 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
Chris Lattnerbaddba42006-02-17 06:39:56 +0000540 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000541 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000542
543 // Okay, everything after this looks good, check to make sure that this block
544 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000545 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Duncan Sands1efabaa2009-05-06 06:49:50 +0000546 if (I->mayHaveSideEffects())
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000547 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000548
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000549 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000550}
551
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000552/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
Andrew Trick4104ed92012-04-10 05:14:37 +0000553/// leads to an exit from the specified loop, and has no side-effects in the
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000554/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000555static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
556 std::set<BasicBlock*> Visited;
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000557 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
Craig Topperf40110f2014-04-25 05:29:35 +0000558 BasicBlock *ExitBB = nullptr;
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000559 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
560 return ExitBB;
Craig Topperf40110f2014-04-25 05:29:35 +0000561 return nullptr;
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000562}
Chris Lattner6e263152006-02-10 02:30:37 +0000563
Chris Lattnered7a67b2006-02-10 01:24:09 +0000564/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
565/// trivial: that is, that the condition controls whether or not the loop does
566/// anything at all. If this is a trivial condition, unswitching produces no
567/// code duplications (equivalently, it produces a simpler loop and a new empty
568/// loop, which gets deleted).
569///
Chris Lattner8a5a3242006-02-22 06:37:14 +0000570/// If this is a trivial condition, return true, otherwise return false. When
571/// returning true, this sets Cond and Val to the condition that controls the
572/// trivial condition: when Cond dynamically equals Val, the loop is known to
573/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
574/// Cond == Val.
575///
Devang Patele149d4e2008-07-02 01:18:13 +0000576bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
577 BasicBlock **LoopExit) {
578 BasicBlock *Header = currentLoop->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000579 TerminatorInst *HeaderTerm = Header->getTerminator();
Owen Anderson47db9412009-07-22 00:24:57 +0000580 LLVMContext &Context = Header->getContext();
Andrew Trick4104ed92012-04-10 05:14:37 +0000581
Craig Topperf40110f2014-04-25 05:29:35 +0000582 BasicBlock *LoopExitBB = nullptr;
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000583 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
584 // If the header block doesn't end with a conditional branch on Cond, we
585 // can't handle it.
586 if (!BI->isConditional() || BI->getCondition() != Cond)
587 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000588
589 // Check to see if a successor of the branch is guaranteed to
590 // exit through a unique exit block without having any
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000591 // side-effects. If so, determine the value of Cond that causes it to do
592 // this.
Andrew Trick4104ed92012-04-10 05:14:37 +0000593 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
Devang Patele149d4e2008-07-02 01:18:13 +0000594 BI->getSuccessor(0)))) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000595 if (Val) *Val = ConstantInt::getTrue(Context);
Andrew Trick4104ed92012-04-10 05:14:37 +0000596 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
Devang Patele149d4e2008-07-02 01:18:13 +0000597 BI->getSuccessor(1)))) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000598 if (Val) *Val = ConstantInt::getFalse(Context);
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000599 }
600 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
601 // If this isn't a switch on Cond, we can't handle it.
602 if (SI->getCondition() != Cond) return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000603
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000604 // Check to see if a successor of the switch is guaranteed to go to the
Andrew Trick4104ed92012-04-10 05:14:37 +0000605 // latch block or exit through a one exit block without having any
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000606 // side-effects. If so, determine the value of Cond that causes it to do
Andrew Trick4104ed92012-04-10 05:14:37 +0000607 // this.
Chad Rosier3ba90a12011-12-22 21:10:46 +0000608 // Note that we can't trivially unswitch on the default case or
609 // on already unswitched cases.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +0000610 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000611 i != e; ++i) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000612 BasicBlock *LoopExitCandidate;
Andrew Trick4104ed92012-04-10 05:14:37 +0000613 if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000614 i.getCaseSuccessor()))) {
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000615 // Okay, we found a trivial case, remember the value that is trivial.
Jakub Staszak27da1232013-08-06 17:03:42 +0000616 ConstantInt *CaseVal = i.getCaseValue();
Chad Rosier3ba90a12011-12-22 21:10:46 +0000617
618 // Check that it was not unswitched before, since already unswitched
619 // trivial vals are looks trivial too.
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000620 if (BranchesInfo.isUnswitched(SI, CaseVal))
Chad Rosier3ba90a12011-12-22 21:10:46 +0000621 continue;
622 LoopExitBB = LoopExitCandidate;
623 if (Val) *Val = CaseVal;
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000624 break;
625 }
Chad Rosier3ba90a12011-12-22 21:10:46 +0000626 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000627 }
628
Chris Lattnere5521db2006-02-22 23:55:00 +0000629 // If we didn't find a single unique LoopExit block, or if the loop exit block
630 // contains phi nodes, this isn't trivial.
631 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000632 return false; // Can't handle this.
Andrew Trick4104ed92012-04-10 05:14:37 +0000633
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000634 if (LoopExit) *LoopExit = LoopExitBB;
Andrew Trick4104ed92012-04-10 05:14:37 +0000635
Chris Lattnered7a67b2006-02-10 01:24:09 +0000636 // We already know that nothing uses any scalar values defined inside of this
637 // loop. As such, we just have to check to see if this loop will execute any
638 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000639 // part of the loop that the code *would* execute. We already checked the
640 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000641 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
Duncan Sands1efabaa2009-05-06 06:49:50 +0000642 if (I->mayHaveSideEffects())
Chris Lattner49354172006-02-10 02:01:22 +0000643 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000644 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000645}
646
Devang Patele149d4e2008-07-02 01:18:13 +0000647/// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000648/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
649/// unswitch the loop, reprocess the pieces, then return true.
Weiming Zhaof1abad52015-06-23 05:31:09 +0000650bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,
651 TerminatorInst *TI) {
Dan Gohman72c367f2009-12-09 22:55:01 +0000652 Function *F = loopHeader->getParent();
Craig Topperf40110f2014-04-25 05:29:35 +0000653 Constant *CondVal = nullptr;
654 BasicBlock *ExitBlock = nullptr;
Bill Wendling712d85a2012-04-30 09:23:48 +0000655
Devang Patele149d4e2008-07-02 01:18:13 +0000656 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
Evan Chenged66db32010-04-03 02:23:43 +0000657 // If the condition is trivial, always unswitch. There is no code growth
658 // for this case.
Weiming Zhaof1abad52015-06-23 05:31:09 +0000659 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock, TI);
Evan Chenged66db32010-04-03 02:23:43 +0000660 return true;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000661 }
Devang Patelc4dcf822008-07-03 06:48:21 +0000662
Evan Chenged66db32010-04-03 02:23:43 +0000663 // Check to see if it would be profitable to unswitch current loop.
664
665 // Do not do non-trivial unswitch while optimizing for size.
Duncan P. N. Exon Smith2c79ad92015-02-14 01:11:29 +0000666 if (OptimizeForSize || F->hasFnAttribute(Attribute::OptimizeForSize))
Evan Chenged66db32010-04-03 02:23:43 +0000667 return false;
668
Weiming Zhaof1abad52015-06-23 05:31:09 +0000669 UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
Andrew Trick4442bfe2012-04-10 05:14:42 +0000670 return true;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000671}
672
Chris Lattnerf48f7772004-04-19 18:07:02 +0000673/// CloneLoop - Recursively clone the specified loop and all of its children,
674/// mapping the blocks with the specified map.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000675static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000676 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000677 Loop *New = new Loop();
Devang Patel901a27d2007-03-07 00:26:10 +0000678 LPM->insertLoop(New, PL);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000679
680 // Add all of the blocks in L to the new loop.
681 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
682 I != E; ++I)
683 if (LI->getLoopFor(*I) == L)
Chandler Carruth691addc2015-01-18 01:25:51 +0000684 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000685
686 // Add all of the subloops to the new loop.
687 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel901a27d2007-03-07 00:26:10 +0000688 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000689
Chris Lattnerf48f7772004-04-19 18:07:02 +0000690 return New;
691}
692
Weiming Zhaof1abad52015-06-23 05:31:09 +0000693static void copyMetadata(Instruction *DstInst, const Instruction *SrcInst,
694 bool Swapped) {
695 if (!SrcInst || !SrcInst->hasMetadata())
696 return;
697
698 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
699 SrcInst->getAllMetadata(MDs);
700 for (auto &MD : MDs) {
701 switch (MD.first) {
702 default:
703 break;
704 case LLVMContext::MD_prof:
705 if (Swapped && MD.second->getNumOperands() == 3 &&
706 isa<MDString>(MD.second->getOperand(0))) {
707 MDString *MDName = cast<MDString>(MD.second->getOperand(0));
708 if (MDName->getString() == "branch_weights") {
709 auto *ValT = cast_or_null<ConstantAsMetadata>(
710 MD.second->getOperand(1))->getValue();
711 auto *ValF = cast_or_null<ConstantAsMetadata>(
712 MD.second->getOperand(2))->getValue();
713 assert(ValT && ValF && "Invalid Operands of branch_weights");
714 auto NewMD =
715 MDBuilder(DstInst->getParent()->getContext())
716 .createBranchWeights(cast<ConstantInt>(ValF)->getZExtValue(),
717 cast<ConstantInt>(ValT)->getZExtValue());
718 MD.second = NewMD;
719 }
720 }
721 // fallthrough.
722 case LLVMContext::MD_dbg:
723 DstInst->setMetadata(MD.first, MD.second);
724 }
725 }
726}
727
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000728/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
729/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
730/// code immediately before InsertPt.
Devang Patel3304e462007-06-28 00:49:00 +0000731void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
732 BasicBlock *TrueDest,
733 BasicBlock *FalseDest,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000734 Instruction *InsertPt,
735 TerminatorInst *TI) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000736 // Insert a conditional branch on LIC to the two preheaders. The original
737 // code is the true version and the new code is the false version.
738 Value *BranchVal = LIC;
Weiming Zhaof1abad52015-06-23 05:31:09 +0000739 bool Swapped = false;
Owen Anderson55f1c092009-08-13 21:58:54 +0000740 if (!isa<ConstantInt>(Val) ||
741 Val->getType() != Type::getInt1Ty(LIC->getContext()))
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000742 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000743 else if (Val != ConstantInt::getTrue(Val->getContext())) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000744 // We want to enter the new loop when the condition is true.
745 std::swap(TrueDest, FalseDest);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000746 Swapped = true;
747 }
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000748
749 // Insert the new branch.
Dan Gohman3ddbc242009-09-08 15:45:00 +0000750 BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000751 copyMetadata(BI, TI, Swapped);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000752
753 // If either edge is critical, split it. This helps preserve LoopSimplify
754 // form for enclosing loops.
Chandler Carruthf8753fc2015-01-19 12:12:00 +0000755 auto Options = CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA();
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000756 SplitCriticalEdge(BI, 0, Options);
757 SplitCriticalEdge(BI, 1, Options);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000758}
759
Chris Lattnered7a67b2006-02-10 01:24:09 +0000760/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
761/// condition in it (a cond branch from its header block to its latch block,
Andrew Trick4104ed92012-04-10 05:14:37 +0000762/// where the path through the loop that doesn't execute its body has no
Chris Lattnered7a67b2006-02-10 01:24:09 +0000763/// side-effects), unswitch it. This doesn't involve any code duplication, just
764/// moving the conditional branch outside of the loop and updating loop info.
Weiming Zhaof1abad52015-06-23 05:31:09 +0000765void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
766 BasicBlock *ExitBlock,
767 TerminatorInst *TI) {
David Greened9c355d2010-01-05 01:27:04 +0000768 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
Weiming Zhaof1abad52015-06-23 05:31:09 +0000769 << loopHeader->getName() << " [" << L->getBlocks().size()
770 << " blocks] in Function "
771 << L->getHeader()->getParent()->getName() << " on cond: " << *Val
772 << " == " << *Cond << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +0000773
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000774 // First step, split the preheader, so that we know that there is a safe place
Devang Patele149d4e2008-07-02 01:18:13 +0000775 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattnered7a67b2006-02-10 01:24:09 +0000776 // conditional branch on Cond.
Chandler Carruthd4500562015-01-19 12:36:53 +0000777 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000778
779 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000780 // to branch to: this is the exit block out of the loop that we should
781 // short-circuit to.
Andrew Trick4104ed92012-04-10 05:14:37 +0000782
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000783 // Split this block now, so that the loop maintains its exit block, and so
784 // that the jump from the preheader can execute the contents of the exit block
785 // without actually branching to it (the exit block should be dominated by the
786 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000787 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chandler Carruth32c52c72015-01-18 02:39:37 +0000788 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), DT, LI);
Andrew Trick4104ed92012-04-10 05:14:37 +0000789
790 // Okay, now we have a position to branch from and a position to branch to,
Chris Lattnered7a67b2006-02-10 01:24:09 +0000791 // insert the new conditional branch.
Andrew Trick4104ed92012-04-10 05:14:37 +0000792 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000793 loopPreheader->getTerminator(), TI);
Devang Patele149d4e2008-07-02 01:18:13 +0000794 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
795 loopPreheader->getTerminator()->eraseFromParent();
Chris Lattnered7a67b2006-02-10 01:24:09 +0000796
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000797 // We need to reprocess this loop, it could be unswitched again.
Devang Patel7d165e12007-07-30 23:07:10 +0000798 redoLoop = true;
Andrew Trick4104ed92012-04-10 05:14:37 +0000799
Chris Lattnered7a67b2006-02-10 01:24:09 +0000800 // Now that we know that the loop is never entered when this condition is a
801 // particular value, rewrite the loop with this info. We know that this will
802 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000803 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000804 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000805}
806
Chris Lattner559c8672008-04-21 00:25:49 +0000807/// SplitExitEdges - Split all of the edges from inside the loop to their exit
808/// blocks. Update the appropriate Phi nodes as we do so.
Andrew Trick4104ed92012-04-10 05:14:37 +0000809void LoopUnswitch::SplitExitEdges(Loop *L,
Craig Topperb94011f2013-07-14 04:42:23 +0000810 const SmallVectorImpl<BasicBlock *> &ExitBlocks){
Devang Patela69f9872007-10-05 22:29:34 +0000811
Chris Lattnered7a67b2006-02-10 01:24:09 +0000812 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000813 BasicBlock *ExitBlock = ExitBlocks[i];
Dan Gohman3ddbc242009-09-08 15:45:00 +0000814 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
815 pred_end(ExitBlock));
Bill Wendling90f90da2011-09-27 00:59:31 +0000816
Nick Lewycky61158242011-06-03 06:27:15 +0000817 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
818 // general, if we call it on all predecessors of all exits then it does.
Philip Reames9198b332015-01-28 23:06:47 +0000819 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa",
820 /*AliasAnalysis*/ nullptr, DT, LI,
821 /*PreserveLCSSA*/ true);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000822 }
Devang Patele192e3252007-10-03 21:16:08 +0000823}
824
Andrew Trick4104ed92012-04-10 05:14:37 +0000825/// UnswitchNontrivialCondition - We determined that the loop is profitable
826/// to unswitch when LIC equal Val. Split it into loop versions and test the
Devang Patel35747592007-10-03 21:17:43 +0000827/// condition outside of either loop. Return the loops created as Out1/Out2.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000828void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000829 Loop *L, TerminatorInst *TI) {
Devang Patele149d4e2008-07-02 01:18:13 +0000830 Function *F = loopHeader->getParent();
David Greened9c355d2010-01-05 01:27:04 +0000831 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000832 << loopHeader->getName() << " [" << L->getBlocks().size()
833 << " blocks] in Function " << F->getName()
834 << " when '" << *Val << "' == " << *LIC << "\n");
Devang Patele192e3252007-10-03 21:16:08 +0000835
Cameron Zwarich99de19b2011-02-11 06:08:28 +0000836 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
837 SE->forgetLoop(L);
838
Devang Pateled50fb52008-07-02 01:44:29 +0000839 LoopBlocks.clear();
840 NewBlocks.clear();
Devang Patele192e3252007-10-03 21:16:08 +0000841
842 // First step, split the preheader and exit blocks, and add these blocks to
843 // the LoopBlocks list.
Chandler Carruthd4500562015-01-19 12:36:53 +0000844 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, DT, LI);
Devang Patele192e3252007-10-03 21:16:08 +0000845 LoopBlocks.push_back(NewPreheader);
846
847 // We want the loop to come after the preheader, but before the exit blocks.
848 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
849
850 SmallVector<BasicBlock*, 8> ExitBlocks;
851 L->getUniqueExitBlocks(ExitBlocks);
852
853 // Split all of the edges from inside the loop to their exit blocks. Update
854 // the appropriate Phi nodes as we do so.
Devang Pateleb611dd2008-07-03 17:37:52 +0000855 SplitExitEdges(L, ExitBlocks);
Devang Patele192e3252007-10-03 21:16:08 +0000856
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000857 // The exit blocks may have been changed due to edge splitting, recompute.
858 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +0000859 L->getUniqueExitBlocks(ExitBlocks);
860
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000861 // Add exit blocks to the loop blocks.
862 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000863
864 // Next step, clone all of the basic blocks that make up the loop (including
865 // the loop preheader and exit blocks), keeping track of the mapping between
866 // the instructions and blocks.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000867 NewBlocks.reserve(LoopBlocks.size());
Rafael Espindola229e38f2010-10-13 01:36:30 +0000868 ValueToValueMapTy VMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000869 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000870 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
Andrew Trick4104ed92012-04-10 05:14:37 +0000871
Evan Chengba930442010-04-05 21:16:25 +0000872 NewBlocks.push_back(NewBB);
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000873 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
Evan Chengba930442010-04-05 21:16:25 +0000874 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000875 }
876
877 // Splice the newly inserted blocks into the function right before the
878 // original preheader.
Evan Chengba930442010-04-05 21:16:25 +0000879 F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
Chris Lattnerf48f7772004-04-19 18:07:02 +0000880 NewBlocks[0], F->end());
881
Hal Finkel74c2f352014-09-07 12:44:26 +0000882 // FIXME: We could register any cloned assumptions instead of clearing the
883 // whole function's cache.
Chandler Carruth66b31302015-01-04 12:03:27 +0000884 AC->clear();
Hal Finkel74c2f352014-09-07 12:44:26 +0000885
Chris Lattnerf48f7772004-04-19 18:07:02 +0000886 // Now we create the new Loop object for the versioned loop.
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000887 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000888
889 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
890 // Probably clone more loop-unswitch related loop properties.
891 BranchesInfo.cloneData(NewLoop, L, VMap);
892
Chris Lattnerf1b15162006-02-10 23:26:14 +0000893 Loop *ParentLoop = L->getParentLoop();
894 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000895 // Make sure to add the cloned preheader and exit blocks to the parent loop
896 // as well.
Chandler Carruth691addc2015-01-18 01:25:51 +0000897 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000898 }
Bill Wendling90f90da2011-09-27 00:59:31 +0000899
Chris Lattnerf1b15162006-02-10 23:26:14 +0000900 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000901 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000902 // The new exit block should be in the same loop as the old one.
903 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Chandler Carruth691addc2015-01-18 01:25:51 +0000904 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Andrew Trick4104ed92012-04-10 05:14:37 +0000905
Chris Lattnerf1b15162006-02-10 23:26:14 +0000906 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
907 "Exit block should have been split to have one successor!");
908 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
Devang Pateleb611dd2008-07-03 17:37:52 +0000909
Chris Lattnerf1b15162006-02-10 23:26:14 +0000910 // If the successor of the exit block had PHI nodes, add an entry for
911 // NewExit.
Jakub Staszak27da1232013-08-06 17:03:42 +0000912 for (BasicBlock::iterator I = ExitSucc->begin();
913 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnerf1b15162006-02-10 23:26:14 +0000914 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Rafael Espindola229e38f2010-10-13 01:36:30 +0000915 ValueToValueMapTy::iterator It = VMap.find(V);
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000916 if (It != VMap.end()) V = It->second;
Chris Lattnerf1b15162006-02-10 23:26:14 +0000917 PN->addIncoming(V, NewExit);
918 }
Bill Wendling90f90da2011-09-27 00:59:31 +0000919
920 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000921 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
922 ExitSucc->getFirstInsertionPt());
Bill Wendling90f90da2011-09-27 00:59:31 +0000923
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000924 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
925 I != E; ++I) {
926 BasicBlock *BB = *I;
Bill Wendling90f90da2011-09-27 00:59:31 +0000927 LandingPadInst *LPI = BB->getLandingPadInst();
928 LPI->replaceAllUsesWith(PN);
929 PN->addIncoming(LPI, BB);
930 }
931 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000932 }
933
934 // Rewrite the code to refer to itself.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +0000935 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
936 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
937 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner43f8d162011-01-08 08:15:20 +0000938 RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Trick4104ed92012-04-10 05:14:37 +0000939
Chris Lattnerf48f7772004-04-19 18:07:02 +0000940 // Rewrite the original preheader to select between versions of the loop.
Devang Patele149d4e2008-07-02 01:18:13 +0000941 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000942 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000943 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000944
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000945 // Emit the new branch that selects between the two versions of this loop.
Weiming Zhaof1abad52015-06-23 05:31:09 +0000946 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
947 TI);
Devang Pateld4911982007-07-31 08:03:26 +0000948 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patel83cc3f82007-09-20 23:45:50 +0000949 OldBR->eraseFromParent();
Devang Patela8823282007-08-02 15:25:57 +0000950
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000951 LoopProcessWorklist.push_back(NewLoop);
Devang Patel7d165e12007-07-30 23:07:10 +0000952 redoLoop = true;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000953
Chris Lattner5814d9d92010-04-20 05:09:16 +0000954 // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
955 // deletes the instruction (for example by simplifying a PHI that feeds into
956 // the condition that we're unswitching on), we don't rewrite the second
957 // iteration.
958 WeakVH LICHandle(LIC);
Andrew Trick4104ed92012-04-10 05:14:37 +0000959
Chris Lattnerf48f7772004-04-19 18:07:02 +0000960 // Now we rewrite the original code to know that the condition is true and the
961 // new code to know that the condition is false.
Evan Chengba930442010-04-05 21:16:25 +0000962 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
Devang Pateleb611dd2008-07-03 17:37:52 +0000963
Chris Lattner5814d9d92010-04-20 05:09:16 +0000964 // It's possible that simplifying one loop could cause the other to be
965 // changed to another value or a constant. If its a constant, don't simplify
966 // it.
967 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
968 LICHandle && !isa<Constant>(LICHandle))
969 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000970}
971
Chris Lattner6fd13622006-02-17 00:31:07 +0000972/// RemoveFromWorklist - Remove all instances of I from the worklist vector
973/// specified.
Andrew Trick4104ed92012-04-10 05:14:37 +0000974static void RemoveFromWorklist(Instruction *I,
Chris Lattner6fd13622006-02-17 00:31:07 +0000975 std::vector<Instruction*> &Worklist) {
Jakub Staszak8f46e912012-10-16 19:52:32 +0000976
977 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
978 Worklist.end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000979}
980
981/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
982/// program, replacing all uses with V and update the worklist.
Andrew Trick4104ed92012-04-10 05:14:37 +0000983static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Pateld4911982007-07-31 08:03:26 +0000984 std::vector<Instruction*> &Worklist,
985 Loop *L, LPPassManager *LPM) {
David Greened9c355d2010-01-05 01:27:04 +0000986 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
Chris Lattner6fd13622006-02-17 00:31:07 +0000987
988 // Add uses to the worklist, which may be dead now.
989 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
990 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
991 Worklist.push_back(Use);
992
993 // Add users to the worklist which may be simplified now.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000994 for (User *U : I->users())
995 Worklist.push_back(cast<Instruction>(U));
Devang Pateld4911982007-07-31 08:03:26 +0000996 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +0000997 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +0000998 I->replaceAllUsesWith(V);
999 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001000 ++NumSimplify;
1001}
1002
Chris Lattnerfbadd7e2006-02-11 00:43:37 +00001003// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
1004// the value specified by Val in the specified loop, or we know it does NOT have
1005// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +00001006void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +00001007 Constant *Val,
1008 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +00001009 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Andrew Trick4104ed92012-04-10 05:14:37 +00001010
Chris Lattnerf48f7772004-04-19 18:07:02 +00001011 // FIXME: Support correlated properties, like:
1012 // for (...)
1013 // if (li1 < li2)
1014 // ...
1015 // if (li1 > li2)
1016 // ...
Andrew Trick4104ed92012-04-10 05:14:37 +00001017
Chris Lattner6e263152006-02-10 02:30:37 +00001018 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1019 // selects, switches.
Chris Lattner6fd13622006-02-17 00:31:07 +00001020 std::vector<Instruction*> Worklist;
Owen Anderson47db9412009-07-22 00:24:57 +00001021 LLVMContext &Context = Val->getContext();
1022
Chris Lattner6fd13622006-02-17 00:31:07 +00001023 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1024 // in the loop with the appropriate one directly.
Owen Anderson55f1c092009-08-13 21:58:54 +00001025 if (IsEqual || (isa<ConstantInt>(Val) &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001026 Val->getType()->isIntegerTy(1))) {
Chris Lattner8a5a3242006-02-22 06:37:14 +00001027 Value *Replacement;
1028 if (IsEqual)
1029 Replacement = Val;
1030 else
Andrew Trick4104ed92012-04-10 05:14:37 +00001031 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
Reid Spencercddc9df2007-01-12 04:24:46 +00001032 !cast<ConstantInt>(Val)->getZExtValue());
Andrew Trick4104ed92012-04-10 05:14:37 +00001033
Chandler Carruthcdf47882014-03-09 03:16:01 +00001034 for (User *U : LIC->users()) {
1035 Instruction *UI = dyn_cast<Instruction>(U);
1036 if (!UI || !L->contains(UI))
Evan Cheng1b55f562011-05-24 23:12:57 +00001037 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001038 Worklist.push_back(UI);
Evan Cheng1b55f562011-05-24 23:12:57 +00001039 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001040
Jakub Staszak27da1232013-08-06 17:03:42 +00001041 for (std::vector<Instruction*>::iterator UI = Worklist.begin(),
1042 UE = Worklist.end(); UI != UE; ++UI)
Andrew Trick4104ed92012-04-10 05:14:37 +00001043 (*UI)->replaceUsesOfWith(LIC, Replacement);
1044
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001045 SimplifyCode(Worklist, L);
1046 return;
1047 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001048
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001049 // Otherwise, we don't know the precise value of LIC, but we do know that it
1050 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1051 // can. This case occurs when we unswitch switch statements.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001052 for (User *U : LIC->users()) {
1053 Instruction *UI = dyn_cast<Instruction>(U);
1054 if (!UI || !L->contains(UI))
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001055 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001056
Chandler Carruthcdf47882014-03-09 03:16:01 +00001057 Worklist.push_back(UI);
Chris Lattner6fd13622006-02-17 00:31:07 +00001058
Andrew Trick4104ed92012-04-10 05:14:37 +00001059 // TODO: We could do other simplifications, for example, turning
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001060 // 'icmp eq LIC, Val' -> false.
1061
1062 // If we know that LIC is not Val, use this info to simplify code.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001063 SwitchInst *SI = dyn_cast<SwitchInst>(UI);
Craig Topperf40110f2014-04-25 05:29:35 +00001064 if (!SI || !isa<ConstantInt>(Val)) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001065
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001066 SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00001067 // Default case is live for multiple values.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001068 if (DeadCase == SI->case_default()) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001069
1070 // Found a dead case value. Don't remove PHI nodes in the
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001071 // successor if they become single-entry, those PHI nodes may
1072 // be in the Users list.
Nick Lewycky61158242011-06-03 06:27:15 +00001073
Evan Cheng1b55f562011-05-24 23:12:57 +00001074 BasicBlock *Switch = SI->getParent();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001075 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
Evan Cheng1b55f562011-05-24 23:12:57 +00001076 BasicBlock *Latch = L->getLoopLatch();
Andrew Trick4104ed92012-04-10 05:14:37 +00001077
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +00001078 BranchesInfo.setUnswitched(SI, Val);
Andrew Trick4104ed92012-04-10 05:14:37 +00001079
Nick Lewycky61158242011-06-03 06:27:15 +00001080 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
Evan Cheng9605a692011-05-25 18:17:13 +00001081 // If the DeadCase successor dominates the loop latch, then the
1082 // transformation isn't safe since it will delete the sole predecessor edge
1083 // to the latch.
1084 if (Latch && DT->dominates(SISucc, Latch))
1085 continue;
Evan Cheng1b55f562011-05-24 23:12:57 +00001086
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001087 // FIXME: This is a hack. We need to keep the successor around
1088 // and hooked up so as to preserve the loop structure, because
1089 // trying to update it is complicated. So instead we preserve the
1090 // loop structure and put the block on a dead code path.
Chandler Carruthd4500562015-01-19 12:36:53 +00001091 SplitEdge(Switch, SISucc, DT, LI);
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001092 // Compute the successors instead of relying on the return value
1093 // of SplitEdge, since it may have split the switch successor
1094 // after PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001095 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001096 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1097 // Create an "unreachable" destination.
1098 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1099 Switch->getParent(),
1100 OldSISucc);
1101 new UnreachableInst(Context, Abort);
1102 // Force the new case destination to branch to the "unreachable"
1103 // block while maintaining a (dead) CFG edge to the old block.
1104 NewSISucc->getTerminator()->eraseFromParent();
1105 BranchInst::Create(Abort, OldSISucc,
1106 ConstantInt::getTrue(Context), NewSISucc);
1107 // Release the PHI operands for this edge.
1108 for (BasicBlock::iterator II = NewSISucc->begin();
1109 PHINode *PN = dyn_cast<PHINode>(II); ++II)
1110 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1111 UndefValue::get(PN->getType()));
1112 // Tell the domtree about the new block. We don't fully update the
1113 // domtree here -- instead we force it to do a full recomputation
1114 // after the pass is complete -- but we do need to inform it of
1115 // new blocks.
1116 if (DT)
1117 DT->addNewBlock(Abort, NewSISucc);
Chris Lattner6fd13622006-02-17 00:31:07 +00001118 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001119
Devang Pateld4911982007-07-31 08:03:26 +00001120 SimplifyCode(Worklist, L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001121}
1122
Mike Stumpdeaf5722009-09-09 17:57:16 +00001123/// SimplifyCode - Okay, now that we have simplified some instructions in the
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001124/// loop, walk over it and constant prop, dce, and fold control flow where
1125/// possible. Note that this is effectively a very simple loop-structure-aware
1126/// optimizer. During processing of this loop, L could very well be deleted, so
1127/// it must not be used.
1128///
1129/// FIXME: When the loop optimizer is more mature, separate this out to a new
1130/// pass.
1131///
Devang Pateld4911982007-07-31 08:03:26 +00001132void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001133 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Chris Lattner6fd13622006-02-17 00:31:07 +00001134 while (!Worklist.empty()) {
1135 Instruction *I = Worklist.back();
1136 Worklist.pop_back();
Duncan Sandsbb2cd022010-11-23 20:24:21 +00001137
Chris Lattner6fd13622006-02-17 00:31:07 +00001138 // Simple DCE.
1139 if (isInstructionTriviallyDead(I)) {
David Greened9c355d2010-01-05 01:27:04 +00001140 DEBUG(dbgs() << "Remove dead instruction '" << *I);
Andrew Trick4104ed92012-04-10 05:14:37 +00001141
Chris Lattner6fd13622006-02-17 00:31:07 +00001142 // Add uses to the worklist, which may be dead now.
1143 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1144 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1145 Worklist.push_back(Use);
Devang Pateld4911982007-07-31 08:03:26 +00001146 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001147 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +00001148 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001149 ++NumSimplify;
1150 continue;
1151 }
Duncan Sandsaef146b2010-11-18 19:59:41 +00001152
Chris Lattner66e809a2010-04-20 05:33:18 +00001153 // See if instruction simplification can hack this up. This is common for
1154 // things like "select false, X, Y" after unswitching made the condition be
Peter Collingbourne9a03c732012-05-20 01:32:09 +00001155 // 'false'. TODO: update the domtree properly so we can pass it here.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001156 if (Value *V = SimplifyInstruction(I, DL))
Duncan Sandsaef146b2010-11-18 19:59:41 +00001157 if (LI->replacementPreservesLCSSAForm(I, V)) {
1158 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1159 continue;
1160 }
1161
Chris Lattner6fd13622006-02-17 00:31:07 +00001162 // Special case hacks that appear commonly in unswitched code.
Chris Lattner66e809a2010-04-20 05:33:18 +00001163 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001164 if (BI->isUnconditional()) {
1165 // If BI's parent is the only pred of the successor, fold the two blocks
1166 // together.
1167 BasicBlock *Pred = BI->getParent();
1168 BasicBlock *Succ = BI->getSuccessor(0);
1169 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1170 if (!SinglePred) continue; // Nothing to do.
1171 assert(SinglePred == Pred && "CFG broken");
1172
Andrew Trick4104ed92012-04-10 05:14:37 +00001173 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001174 << Succ->getName() << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +00001175
Chris Lattner6fd13622006-02-17 00:31:07 +00001176 // Resolve any single entry PHI nodes in Succ.
1177 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Pateld4911982007-07-31 08:03:26 +00001178 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Andrew Trick4104ed92012-04-10 05:14:37 +00001179
Jay Foad61ea0e42011-06-23 09:09:15 +00001180 // If Succ has any successors with PHI nodes, update them to have
1181 // entries coming from Pred instead of Succ.
1182 Succ->replaceAllUsesWith(Pred);
Andrew Trick4104ed92012-04-10 05:14:37 +00001183
Chris Lattner6fd13622006-02-17 00:31:07 +00001184 // Move all of the successor contents from Succ to Pred.
1185 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1186 Succ->end());
Devang Pateld4911982007-07-31 08:03:26 +00001187 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001188 BI->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001189 RemoveFromWorklist(BI, Worklist);
Andrew Trick4104ed92012-04-10 05:14:37 +00001190
Chris Lattner6fd13622006-02-17 00:31:07 +00001191 // Remove Succ from the loop tree.
1192 LI->removeBlock(Succ);
Devang Pateld4911982007-07-31 08:03:26 +00001193 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001194 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001195 ++NumSimplify;
Chris Lattner66e809a2010-04-20 05:33:18 +00001196 continue;
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001197 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001198
Chris Lattner66e809a2010-04-20 05:33:18 +00001199 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001200 }
1201 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001202}