1 //===-- PPCCTRLoops.cpp - Identify and generate CTR loops -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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).
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.
18 // Criteria for CTR loops:
19 // - Countable loops (w/ ind. var for a trip count)
20 // - Try inner-most loops first
21 // - No nested CTR loops.
22 // - No function calls in loops.
24 //===----------------------------------------------------------------------===//
26 #define DEBUG_TYPE "ctrloops"
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Analysis/Dominators.h"
32 #include "llvm/Analysis/LoopInfo.h"
33 #include "llvm/Analysis/ScalarEvolutionExpander.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/PassSupport.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ValueHandle.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Target/TargetLibraryInfo.h"
47 #include "PPCTargetMachine.h"
56 static cl::opt<int> CTRLoopLimit("ppc-max-ctrloop", cl::Hidden, cl::init(-1));
59 STATISTIC(NumCTRLoops, "Number of loops converted to CTR loops");
62 void initializePPCCTRLoopsPass(PassRegistry&);
66 struct PPCCTRLoops : public FunctionPass {
75 PPCCTRLoops() : FunctionPass(ID), TM(0) {
76 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
78 PPCCTRLoops(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
79 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
82 virtual bool runOnFunction(Function &F);
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<LoopInfo>();
86 AU.addPreserved<LoopInfo>();
87 AU.addRequired<DominatorTree>();
88 AU.addPreserved<DominatorTree>();
89 AU.addRequired<ScalarEvolution>();
93 // FIXME: Copied from LoopSimplify.
94 BasicBlock *InsertPreheaderForLoop(Loop *L);
95 void PlaceSplitBlockCarefully(BasicBlock *NewBB,
96 SmallVectorImpl<BasicBlock*> &SplitPreds,
99 bool mightUseCTR(const Triple &TT, BasicBlock *BB);
100 bool convertToCTRLoop(Loop *L);
102 PPCTargetMachine *TM;
107 const TargetLibraryInfo *LibInfo;
110 char PPCCTRLoops::ID = 0;
112 int PPCCTRLoops::Counter = 0;
114 } // end anonymous namespace
116 INITIALIZE_PASS_BEGIN(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
118 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
119 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
120 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
121 INITIALIZE_PASS_END(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
124 FunctionPass *llvm::createPPCCTRLoops(PPCTargetMachine &TM) {
125 return new PPCCTRLoops(TM);
128 bool PPCCTRLoops::runOnFunction(Function &F) {
129 LI = &getAnalysis<LoopInfo>();
130 SE = &getAnalysis<ScalarEvolution>();
131 DT = &getAnalysis<DominatorTree>();
132 TD = getAnalysisIfAvailable<DataLayout>();
133 LibInfo = getAnalysisIfAvailable<TargetLibraryInfo>();
135 bool MadeChange = false;
137 for (LoopInfo::iterator I = LI->begin(), E = LI->end();
140 if (!L->getParentLoop())
141 MadeChange |= convertToCTRLoop(L);
147 bool PPCCTRLoops::mightUseCTR(const Triple &TT, BasicBlock *BB) {
148 for (BasicBlock::iterator J = BB->begin(), JE = BB->end();
150 if (CallInst *CI = dyn_cast<CallInst>(J)) {
153 const TargetLowering *TLI = TM->getTargetLowering();
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.
159 if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
160 switch (F->getIntrinsicID()) {
163 // VisualStudio defines setjmp as _setjmp
164 #if defined(_MSC_VER) && defined(setjmp) && \
165 !defined(setjmp_undefined_for_msvc)
166 # pragma push_macro("setjmp")
168 # define setjmp_undefined_for_msvc
171 case Intrinsic::setjmp:
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
179 case Intrinsic::longjmp:
180 case Intrinsic::memcpy:
181 case Intrinsic::memmove:
182 case Intrinsic::memset:
183 case Intrinsic::powi:
185 case Intrinsic::log2:
186 case Intrinsic::log10:
188 case Intrinsic::exp2:
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;
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.
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())
215 // Conversion happens only for FP calls.
216 if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
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.
228 continue; // ISD::FABS is never a library call.
232 Opcode = ISD::FSQRT; break;
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;
244 Opcode = ISD::FCEIL; break;
248 Opcode = ISD::FRINT; break;
250 case LibFunc::truncf:
251 case LibFunc::truncl:
252 Opcode = ISD::FTRUNC; break;
256 TLI->getSimpleValueType(CI->getArgOperand(0)->getType(), true);
257 if (VTy == MVT::Other)
260 if (TLI->isOperationLegalOrCustom(Opcode, VTy))
262 else if (VTy.isVector() &&
263 TLI->isOperationLegalOrCustom(Opcode, VTy.getScalarType()))
271 } else if (isa<BinaryOperator>(J) &&
272 J->getType()->getScalarType()->isPPC_FP128Ty()) {
273 // Most operations on ppc_f128 values become calls.
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() ||
281 (CI->getSrcTy()->getScalarType()->isIntegerTy(64) ||
282 CI->getDestTy()->getScalarType()->isIntegerTy(64))
285 } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
286 // On PowerPC, indirect jumps use the counter register.
288 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
291 const TargetLowering *TLI = TM->getTargetLowering();
293 if (TLI->supportJumpTables() &&
294 SI->getNumCases()+1 >= (unsigned) TLI->getMinimumJumpTableEntries())
302 bool PPCCTRLoops::convertToCTRLoop(Loop *L) {
303 bool MadeChange = false;
305 Triple TT = Triple(L->getHeader()->getParent()->getParent()->
307 if (!TT.isArch32Bit() && !TT.isArch64Bit())
308 return MadeChange; // Unknown arch. type.
310 // Process nested loops first.
311 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
312 MadeChange |= convertToCTRLoop(*I);
315 // If a nested loop has been converted, then we can't convert this loop.
320 // Stop trying after reaching the limit (if any).
321 int Limit = CTRLoopLimit;
323 if (Counter >= CTRLoopLimit)
329 // 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();
333 if (mightUseCTR(TT, *I))
336 SmallVector<BasicBlock*, 4> ExitingBlocks;
337 L->getExitingBlocks(ExitingBlocks);
339 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))
349 if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
350 if (ConstEC->getValue()->isZero())
352 } else if (!SE->isLoopInvariant(EC, L))
355 // 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
359 // 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))
368 if (!DT->dominates(*I, *PI)) {
377 // Make sure this blocks ends with a conditional branch.
378 Instruction *TI = (*I)->getTerminator();
382 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
383 if (!BI->isConditional())
386 CountedExitBranch = BI;
390 // Note that this block may not be the loop latch block, even if the loop
391 // has a latch block.
392 CountedExitBlock = *I;
397 if (!CountedExitBlock)
400 BasicBlock *Preheader = L->getLoopPreheader();
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))
407 Preheader = InsertPreheaderForLoop(L);
411 DEBUG(dbgs() << "Preheader for exit count: " << Preheader->getName() << "\n");
413 // Insert the count into the preheader and replace the condition used by the
417 SCEVExpander SCEVE(*SE, "loopcnt");
418 LLVMContext &C = SE->getContext();
419 Type *CountType = TT.isArch64Bit() ? Type::getInt64Ty(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());
429 IRBuilder<> CountBuilder(Preheader->getTerminator());
430 Module *M = Preheader->getParent()->getParent();
431 Value *MTCTRFunc = Intrinsic::getDeclaration(M, Intrinsic::ppc_mtctr,
433 CountBuilder.CreateCall(MTCTRFunc, ECValue);
435 IRBuilder<> CondBuilder(CountedExitBranch);
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);
442 // The false branch must exit the loop.
443 if (!L->contains(CountedExitBranch->getSuccessor(0)))
444 CountedExitBranch->swapSuccessors();
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);
455 // FIXME: Copied from LoopSimplify.
456 BasicBlock *PPCCTRLoops::InsertPreheaderForLoop(Loop *L) {
457 BasicBlock *Header = L->getHeader();
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);
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
468 if (isa<IndirectBrInst>(P->getTerminator())) return 0;
471 OutsideBlocks.push_back(P);
475 // Split out the loop pre-header.
476 BasicBlock *PreheaderBB;
477 if (!Header->isLandingPad()) {
478 PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader",
481 SmallVector<BasicBlock*, 2> NewBBs;
482 SplitLandingPadPredecessors(Header, OutsideBlocks, ".preheader",
483 ".split-lp", this, NewBBs);
484 PreheaderBB = NewBBs[0];
487 PreheaderBB->getTerminator()->setDebugLoc(
488 Header->getFirstNonPHI()->getDebugLoc());
489 DEBUG(dbgs() << "Creating pre-header "
490 << PreheaderBB->getName() << "\n");
492 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
493 // code layout too horribly.
494 PlaceSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
499 void PPCCTRLoops::PlaceSplitBlockCarefully(BasicBlock *NewBB,
500 SmallVectorImpl<BasicBlock*> &SplitPreds,
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])
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
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() &&
520 FoundBB = SplitPreds[i];
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
529 FoundBB = SplitPreds[0];
530 NewBB->moveAfter(FoundBB);