blob: 5d001fc0725e65a7762a619527e27b27a5662978 [file] [log] [blame]
Hal Finkel96c2d4d2012-06-08 15:38:21 +00001//===-- PPCCTRLoops.cpp - Identify and generate CTR loops -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass identifies loops where we can generate the PPC branch instructions
11// that decrement and test the count register (CTR) (bdnz and friends).
Hal Finkel96c2d4d2012-06-08 15:38:21 +000012//
13// The pattern that defines the induction variable can changed depending on
14// prior optimizations. For example, the IndVarSimplify phase run by 'opt'
15// normalizes induction variables, and the Loop Strength Reduction pass
16// run by 'llc' may also make changes to the induction variable.
Hal Finkel96c2d4d2012-06-08 15:38:21 +000017//
18// Criteria for CTR loops:
19// - Countable loops (w/ ind. var for a trip count)
Hal Finkel96c2d4d2012-06-08 15:38:21 +000020// - Try inner-most loops first
21// - No nested CTR loops.
22// - No function calls in loops.
23//
Hal Finkel96c2d4d2012-06-08 15:38:21 +000024//===----------------------------------------------------------------------===//
25
26#define DEBUG_TYPE "ctrloops"
Hal Finkel25c19922013-05-15 21:37:41 +000027
28#include "llvm/Transforms/Scalar.h"
Hal Finkel96c2d4d2012-06-08 15:38:21 +000029#include "llvm/ADT/Statistic.h"
Hal Finkel25c19922013-05-15 21:37:41 +000030#include "llvm/ADT/STLExtras.h"
31#include "llvm/Analysis/Dominators.h"
32#include "llvm/Analysis/LoopInfo.h"
33#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Constants.h"
Hal Finkel25c19922013-05-15 21:37:41 +000035#include "llvm/IR/DerivedTypes.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/IntrinsicInst.h"
38#include "llvm/IR/Module.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000039#include "llvm/PassSupport.h"
Hal Finkel25c19922013-05-15 21:37:41 +000040#include "llvm/Support/CommandLine.h"
Hal Finkel96c2d4d2012-06-08 15:38:21 +000041#include "llvm/Support/Debug.h"
Hal Finkel25c19922013-05-15 21:37:41 +000042#include "llvm/Support/ValueHandle.h"
Hal Finkel96c2d4d2012-06-08 15:38:21 +000043#include "llvm/Support/raw_ostream.h"
Hal Finkel25c19922013-05-15 21:37:41 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
46#include "llvm/Target/TargetLibraryInfo.h"
47#include "PPCTargetMachine.h"
48#include "PPC.h"
49
Hal Finkel96c2d4d2012-06-08 15:38:21 +000050#include <algorithm>
Hal Finkel25c19922013-05-15 21:37:41 +000051#include <vector>
Hal Finkel96c2d4d2012-06-08 15:38:21 +000052
53using namespace llvm;
54
Hal Finkel25c19922013-05-15 21:37:41 +000055#ifndef NDEBUG
56static cl::opt<int> CTRLoopLimit("ppc-max-ctrloop", cl::Hidden, cl::init(-1));
57#endif
58
Hal Finkel96c2d4d2012-06-08 15:38:21 +000059STATISTIC(NumCTRLoops, "Number of loops converted to CTR loops");
60
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +000061namespace llvm {
62 void initializePPCCTRLoopsPass(PassRegistry&);
63}
64
Hal Finkel96c2d4d2012-06-08 15:38:21 +000065namespace {
Hal Finkel25c19922013-05-15 21:37:41 +000066 struct PPCCTRLoops : public FunctionPass {
67
68#ifndef NDEBUG
69 static int Counter;
70#endif
Hal Finkel96c2d4d2012-06-08 15:38:21 +000071
72 public:
Hal Finkel25c19922013-05-15 21:37:41 +000073 static char ID;
Hal Finkel96c2d4d2012-06-08 15:38:21 +000074
Hal Finkel25c19922013-05-15 21:37:41 +000075 PPCCTRLoops() : FunctionPass(ID), TM(0) {
76 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
77 }
78 PPCCTRLoops(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +000079 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
80 }
Hal Finkel96c2d4d2012-06-08 15:38:21 +000081
Hal Finkel25c19922013-05-15 21:37:41 +000082 virtual bool runOnFunction(Function &F);
Hal Finkel96c2d4d2012-06-08 15:38:21 +000083
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Hal Finkel25c19922013-05-15 21:37:41 +000085 AU.addRequired<LoopInfo>();
86 AU.addPreserved<LoopInfo>();
87 AU.addRequired<DominatorTree>();
88 AU.addPreserved<DominatorTree>();
89 AU.addRequired<ScalarEvolution>();
Hal Finkel96c2d4d2012-06-08 15:38:21 +000090 }
91
92 private:
Hal Finkel25c19922013-05-15 21:37:41 +000093 // FIXME: Copied from LoopSimplify.
94 BasicBlock *InsertPreheaderForLoop(Loop *L);
95 void PlaceSplitBlockCarefully(BasicBlock *NewBB,
96 SmallVectorImpl<BasicBlock*> &SplitPreds,
97 Loop *L);
Hal Finkel96c2d4d2012-06-08 15:38:21 +000098
Hal Finkel5f587c52013-05-16 19:58:38 +000099 bool mightUseCTR(const Triple &TT, BasicBlock *BB);
Hal Finkel25c19922013-05-15 21:37:41 +0000100 bool convertToCTRLoop(Loop *L);
101 private:
102 PPCTargetMachine *TM;
103 LoopInfo *LI;
104 ScalarEvolution *SE;
105 DataLayout *TD;
106 DominatorTree *DT;
107 const TargetLibraryInfo *LibInfo;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000108 };
109
110 char PPCCTRLoops::ID = 0;
Hal Finkel25c19922013-05-15 21:37:41 +0000111#ifndef NDEBUG
112 int PPCCTRLoops::Counter = 0;
113#endif
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000114} // end anonymous namespace
115
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +0000116INITIALIZE_PASS_BEGIN(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
117 false, false)
Hal Finkel25c19922013-05-15 21:37:41 +0000118INITIALIZE_PASS_DEPENDENCY(DominatorTree)
119INITIALIZE_PASS_DEPENDENCY(LoopInfo)
120INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +0000121INITIALIZE_PASS_END(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
122 false, false)
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000123
Hal Finkel25c19922013-05-15 21:37:41 +0000124FunctionPass *llvm::createPPCCTRLoops(PPCTargetMachine &TM) {
125 return new PPCCTRLoops(TM);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000126}
127
Hal Finkel25c19922013-05-15 21:37:41 +0000128bool PPCCTRLoops::runOnFunction(Function &F) {
129 LI = &getAnalysis<LoopInfo>();
130 SE = &getAnalysis<ScalarEvolution>();
131 DT = &getAnalysis<DominatorTree>();
132 TD = getAnalysisIfAvailable<DataLayout>();
133 LibInfo = getAnalysisIfAvailable<TargetLibraryInfo>();
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000134
Hal Finkel25c19922013-05-15 21:37:41 +0000135 bool MadeChange = false;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000136
Hal Finkel25c19922013-05-15 21:37:41 +0000137 for (LoopInfo::iterator I = LI->begin(), E = LI->end();
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000138 I != E; ++I) {
Hal Finkel25c19922013-05-15 21:37:41 +0000139 Loop *L = *I;
140 if (!L->getParentLoop())
141 MadeChange |= convertToCTRLoop(L);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000142 }
143
Hal Finkel25c19922013-05-15 21:37:41 +0000144 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000145}
146
Hal Finkel5f587c52013-05-16 19:58:38 +0000147bool PPCCTRLoops::mightUseCTR(const Triple &TT, BasicBlock *BB) {
148 for (BasicBlock::iterator J = BB->begin(), JE = BB->end();
149 J != JE; ++J) {
150 if (CallInst *CI = dyn_cast<CallInst>(J)) {
151 if (!TM)
152 return true;
153 const TargetLowering *TLI = TM->getTargetLowering();
154
155 if (Function *F = CI->getCalledFunction()) {
156 // Most intrinsics don't become function calls, but some might.
157 // sin, cos, exp and log are always calls.
158 unsigned Opcode;
159 if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
160 switch (F->getIntrinsicID()) {
161 default: continue;
162
163// VisualStudio defines setjmp as _setjmp
164#if defined(_MSC_VER) && defined(setjmp) && \
165 !defined(setjmp_undefined_for_msvc)
166# pragma push_macro("setjmp")
167# undef setjmp
168# define setjmp_undefined_for_msvc
169#endif
170
171 case Intrinsic::setjmp:
172
173#if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)
174 // let's return it to _setjmp state
175# pragma pop_macro("setjmp")
176# undef setjmp_undefined_for_msvc
177#endif
178
179 case Intrinsic::longjmp:
180 case Intrinsic::memcpy:
181 case Intrinsic::memmove:
182 case Intrinsic::memset:
183 case Intrinsic::powi:
184 case Intrinsic::log:
185 case Intrinsic::log2:
186 case Intrinsic::log10:
187 case Intrinsic::exp:
188 case Intrinsic::exp2:
189 case Intrinsic::pow:
190 case Intrinsic::sin:
191 case Intrinsic::cos:
192 return true;
193 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
194 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
195 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
196 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
197 case Intrinsic::rint: Opcode = ISD::FRINT; break;
198 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
199 }
200 }
201
202 // PowerPC does not use [US]DIVREM or other library calls for
203 // operations on regular types which are not otherwise library calls
204 // (i.e. soft float or atomics). If adapting for targets that do,
205 // additional care is required here.
206
207 LibFunc::Func Func;
208 if (!F->hasLocalLinkage() && F->hasName() && LibInfo &&
209 LibInfo->getLibFunc(F->getName(), Func) &&
210 LibInfo->hasOptimizedCodeGen(Func)) {
211 // Non-read-only functions are never treated as intrinsics.
212 if (!CI->onlyReadsMemory())
213 return true;
214
215 // Conversion happens only for FP calls.
216 if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
217 return true;
218
219 switch (Func) {
220 default: return true;
221 case LibFunc::copysign:
222 case LibFunc::copysignf:
223 case LibFunc::copysignl:
224 continue; // ISD::FCOPYSIGN is never a library call.
225 case LibFunc::fabs:
226 case LibFunc::fabsf:
227 case LibFunc::fabsl:
228 continue; // ISD::FABS is never a library call.
229 case LibFunc::sqrt:
230 case LibFunc::sqrtf:
231 case LibFunc::sqrtl:
232 Opcode = ISD::FSQRT; break;
233 case LibFunc::floor:
234 case LibFunc::floorf:
235 case LibFunc::floorl:
236 Opcode = ISD::FFLOOR; break;
237 case LibFunc::nearbyint:
238 case LibFunc::nearbyintf:
239 case LibFunc::nearbyintl:
240 Opcode = ISD::FNEARBYINT; break;
241 case LibFunc::ceil:
242 case LibFunc::ceilf:
243 case LibFunc::ceill:
244 Opcode = ISD::FCEIL; break;
245 case LibFunc::rint:
246 case LibFunc::rintf:
247 case LibFunc::rintl:
248 Opcode = ISD::FRINT; break;
249 case LibFunc::trunc:
250 case LibFunc::truncf:
251 case LibFunc::truncl:
252 Opcode = ISD::FTRUNC; break;
253 }
254
255 MVT VTy =
256 TLI->getSimpleValueType(CI->getArgOperand(0)->getType(), true);
257 if (VTy == MVT::Other)
258 return true;
259
260 if (TLI->isOperationLegalOrCustom(Opcode, VTy))
261 continue;
262 else if (VTy.isVector() &&
263 TLI->isOperationLegalOrCustom(Opcode, VTy.getScalarType()))
264 continue;
265
266 return true;
267 }
268 }
269
270 return true;
271 } else if (isa<BinaryOperator>(J) &&
272 J->getType()->getScalarType()->isPPC_FP128Ty()) {
273 // Most operations on ppc_f128 values become calls.
274 return true;
275 } else if (isa<UIToFPInst>(J) || isa<SIToFPInst>(J) ||
276 isa<FPToUIInst>(J) || isa<FPToSIInst>(J)) {
277 CastInst *CI = cast<CastInst>(J);
278 if (CI->getSrcTy()->getScalarType()->isPPC_FP128Ty() ||
279 CI->getDestTy()->getScalarType()->isPPC_FP128Ty() ||
280 (TT.isArch32Bit() &&
281 (CI->getSrcTy()->getScalarType()->isIntegerTy(64) ||
282 CI->getDestTy()->getScalarType()->isIntegerTy(64))
283 ))
284 return true;
285 } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
286 // On PowerPC, indirect jumps use the counter register.
287 return true;
288 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
289 if (!TM)
290 return true;
291 const TargetLowering *TLI = TM->getTargetLowering();
292
293 if (TLI->supportJumpTables() &&
294 SI->getNumCases()+1 >= (unsigned) TLI->getMinimumJumpTableEntries())
295 return true;
296 }
297 }
298
299 return false;
300}
301
Hal Finkel25c19922013-05-15 21:37:41 +0000302bool PPCCTRLoops::convertToCTRLoop(Loop *L) {
303 bool MadeChange = false;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000304
Hal Finkel25c19922013-05-15 21:37:41 +0000305 Triple TT = Triple(L->getHeader()->getParent()->getParent()->
306 getTargetTriple());
307 if (!TT.isArch32Bit() && !TT.isArch64Bit())
308 return MadeChange; // Unknown arch. type.
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000309
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000310 // Process nested loops first.
Hal Finkel25c19922013-05-15 21:37:41 +0000311 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
312 MadeChange |= convertToCTRLoop(*I);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000313 }
Hal Finkel25c19922013-05-15 21:37:41 +0000314
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000315 // If a nested loop has been converted, then we can't convert this loop.
Hal Finkel25c19922013-05-15 21:37:41 +0000316 if (MadeChange)
317 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000318
Hal Finkel25c19922013-05-15 21:37:41 +0000319#ifndef NDEBUG
320 // Stop trying after reaching the limit (if any).
321 int Limit = CTRLoopLimit;
322 if (Limit >= 0) {
323 if (Counter >= CTRLoopLimit)
Hal Finkel21f2a432013-03-18 17:40:44 +0000324 return false;
Hal Finkel25c19922013-05-15 21:37:41 +0000325 Counter++;
Hal Finkel21f2a432013-03-18 17:40:44 +0000326 }
Hal Finkel25c19922013-05-15 21:37:41 +0000327#endif
Hal Finkel21f2a432013-03-18 17:40:44 +0000328
Hal Finkel25c19922013-05-15 21:37:41 +0000329 // We don't want to spill/restore the counter register, and so we don't
330 // want to use the counter register if the loop contains calls.
331 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
Hal Finkel5f587c52013-05-16 19:58:38 +0000332 I != IE; ++I)
333 if (mightUseCTR(TT, *I))
334 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000335
Hal Finkel25c19922013-05-15 21:37:41 +0000336 SmallVector<BasicBlock*, 4> ExitingBlocks;
337 L->getExitingBlocks(ExitingBlocks);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000338
Hal Finkel25c19922013-05-15 21:37:41 +0000339 BasicBlock *CountedExitBlock = 0;
340 const SCEV *ExitCount = 0;
341 BranchInst *CountedExitBranch = 0;
342 for (SmallVector<BasicBlock*, 4>::iterator I = ExitingBlocks.begin(),
343 IE = ExitingBlocks.end(); I != IE; ++I) {
344 const SCEV *EC = SE->getExitCount(L, *I);
345 DEBUG(dbgs() << "Exit Count for " << *L << " from block " <<
346 (*I)->getName() << ": " << *EC << "\n");
347 if (isa<SCEVCouldNotCompute>(EC))
348 continue;
349 if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
350 if (ConstEC->getValue()->isZero())
351 continue;
352 } else if (!SE->isLoopInvariant(EC, L))
353 continue;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000354
Hal Finkel25c19922013-05-15 21:37:41 +0000355 // We now have a loop-invariant count of loop iterations (which is not the
356 // constant zero) for which we know that this loop will not exit via this
357 // exisiting block.
Hal Finkel6261c2d2012-06-16 20:34:07 +0000358
Hal Finkel25c19922013-05-15 21:37:41 +0000359 // We need to make sure that this block will run on every loop iteration.
360 // For this to be true, we must dominate all blocks with backedges. Such
361 // blocks are in-loop predecessors to the header block.
362 bool NotAlways = false;
363 for (pred_iterator PI = pred_begin(L->getHeader()),
364 PIE = pred_end(L->getHeader()); PI != PIE; ++PI) {
365 if (!L->contains(*PI))
366 continue;
367
368 if (!DT->dominates(*I, *PI)) {
369 NotAlways = true;
370 break;
371 }
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000372 }
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000373
Hal Finkel25c19922013-05-15 21:37:41 +0000374 if (NotAlways)
375 continue;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000376
Hal Finkel25c19922013-05-15 21:37:41 +0000377 // Make sure this blocks ends with a conditional branch.
378 Instruction *TI = (*I)->getTerminator();
379 if (!TI)
380 continue;
381
382 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
383 if (!BI->isConditional())
384 continue;
385
386 CountedExitBranch = BI;
387 } else
388 continue;
389
390 // Note that this block may not be the loop latch block, even if the loop
391 // has a latch block.
392 CountedExitBlock = *I;
393 ExitCount = EC;
394 break;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000395 }
396
Hal Finkel25c19922013-05-15 21:37:41 +0000397 if (!CountedExitBlock)
398 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000399
Hal Finkel25c19922013-05-15 21:37:41 +0000400 BasicBlock *Preheader = L->getLoopPreheader();
Hal Finkel5f587c52013-05-16 19:58:38 +0000401
402 // If we don't have a preheader, then insert one. If we already have a
403 // preheader, then we can use it (except if the preheader contains a use of
404 // the CTR register because some such uses might be reordered by the
405 // selection DAG after the mtctr instruction).
406 if (!Preheader || mightUseCTR(TT, Preheader))
Hal Finkel25c19922013-05-15 21:37:41 +0000407 Preheader = InsertPreheaderForLoop(L);
408 if (!Preheader)
409 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000410
Hal Finkel25c19922013-05-15 21:37:41 +0000411 DEBUG(dbgs() << "Preheader for exit count: " << Preheader->getName() << "\n");
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000412
Hal Finkel25c19922013-05-15 21:37:41 +0000413 // Insert the count into the preheader and replace the condition used by the
414 // selected branch.
415 MadeChange = true;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000416
Hal Finkel25c19922013-05-15 21:37:41 +0000417 SCEVExpander SCEVE(*SE, "loopcnt");
418 LLVMContext &C = SE->getContext();
419 Type *CountType = TT.isArch64Bit() ? Type::getInt64Ty(C) :
420 Type::getInt32Ty(C);
421 if (!ExitCount->getType()->isPointerTy() &&
422 ExitCount->getType() != CountType)
423 ExitCount = SE->getZeroExtendExpr(ExitCount, CountType);
424 ExitCount = SE->getAddExpr(ExitCount,
425 SE->getConstant(CountType, 1));
426 Value *ECValue = SCEVE.expandCodeFor(ExitCount, CountType,
427 Preheader->getTerminator());
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000428
Hal Finkel25c19922013-05-15 21:37:41 +0000429 IRBuilder<> CountBuilder(Preheader->getTerminator());
430 Module *M = Preheader->getParent()->getParent();
431 Value *MTCTRFunc = Intrinsic::getDeclaration(M, Intrinsic::ppc_mtctr,
432 CountType);
433 CountBuilder.CreateCall(MTCTRFunc, ECValue);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000434
Hal Finkel25c19922013-05-15 21:37:41 +0000435 IRBuilder<> CondBuilder(CountedExitBranch);
436 Value *DecFunc =
437 Intrinsic::getDeclaration(M, Intrinsic::ppc_is_decremented_ctr_nonzero);
438 Value *NewCond = CondBuilder.CreateCall(DecFunc);
439 Value *OldCond = CountedExitBranch->getCondition();
440 CountedExitBranch->setCondition(NewCond);
441
442 // The false branch must exit the loop.
443 if (!L->contains(CountedExitBranch->getSuccessor(0)))
444 CountedExitBranch->swapSuccessors();
445
446 // The old condition may be dead now, and may have even created a dead PHI
447 // (the original induction variable).
448 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
449 DeleteDeadPHIs(CountedExitBlock);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000450
451 ++NumCTRLoops;
Hal Finkel25c19922013-05-15 21:37:41 +0000452 return MadeChange;
453}
454
455// FIXME: Copied from LoopSimplify.
456BasicBlock *PPCCTRLoops::InsertPreheaderForLoop(Loop *L) {
457 BasicBlock *Header = L->getHeader();
458
459 // Compute the set of predecessors of the loop that are not in the loop.
460 SmallVector<BasicBlock*, 8> OutsideBlocks;
461 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
462 PI != PE; ++PI) {
463 BasicBlock *P = *PI;
464 if (!L->contains(P)) { // Coming in from outside the loop?
465 // If the loop is branched to from an indirect branch, we won't
466 // be able to fully transform the loop, because it prohibits
467 // edge splitting.
468 if (isa<IndirectBrInst>(P->getTerminator())) return 0;
469
470 // Keep track of it.
471 OutsideBlocks.push_back(P);
472 }
473 }
474
475 // Split out the loop pre-header.
476 BasicBlock *PreheaderBB;
477 if (!Header->isLandingPad()) {
478 PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader",
479 this);
480 } else {
481 SmallVector<BasicBlock*, 2> NewBBs;
482 SplitLandingPadPredecessors(Header, OutsideBlocks, ".preheader",
483 ".split-lp", this, NewBBs);
484 PreheaderBB = NewBBs[0];
485 }
486
487 PreheaderBB->getTerminator()->setDebugLoc(
488 Header->getFirstNonPHI()->getDebugLoc());
489 DEBUG(dbgs() << "Creating pre-header "
490 << PreheaderBB->getName() << "\n");
491
492 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
493 // code layout too horribly.
494 PlaceSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
495
496 return PreheaderBB;
497}
498
499void PPCCTRLoops::PlaceSplitBlockCarefully(BasicBlock *NewBB,
500 SmallVectorImpl<BasicBlock*> &SplitPreds,
501 Loop *L) {
502 // Check to see if NewBB is already well placed.
503 Function::iterator BBI = NewBB; --BBI;
504 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
505 if (&*BBI == SplitPreds[i])
506 return;
507 }
508
509 // If it isn't already after an outside block, move it after one. This is
510 // always good as it makes the uncond branch from the outside block into a
511 // fall-through.
512
513 // Figure out *which* outside block to put this after. Prefer an outside
514 // block that neighbors a BB actually in the loop.
515 BasicBlock *FoundBB = 0;
516 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
517 Function::iterator BBI = SplitPreds[i];
518 if (++BBI != NewBB->getParent()->end() &&
519 L->contains(BBI)) {
520 FoundBB = SplitPreds[i];
521 break;
522 }
523 }
524
525 // If our heuristic for a *good* bb to place this after doesn't find
526 // anything, just pick something. It's likely better than leaving it within
527 // the loop.
528 if (!FoundBB)
529 FoundBB = SplitPreds[0];
530 NewBB->moveAfter(FoundBB);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000531}
532