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/InlineAsm.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/PassSupport.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ValueHandle.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Target/TargetLibraryInfo.h"
48 #include "PPCTargetMachine.h"
52 #include "llvm/CodeGen/MachineDominators.h"
53 #include "llvm/CodeGen/MachineFunction.h"
54 #include "llvm/CodeGen/MachineFunctionPass.h"
55 #include "llvm/CodeGen/MachineRegisterInfo.h"
64 static cl::opt<int> CTRLoopLimit("ppc-max-ctrloop", cl::Hidden, cl::init(-1));
67 STATISTIC(NumCTRLoops, "Number of loops converted to CTR loops");
70 void initializePPCCTRLoopsPass(PassRegistry&);
72 void initializePPCCTRLoopsVerifyPass(PassRegistry&);
77 struct PPCCTRLoops : public FunctionPass {
86 PPCCTRLoops() : FunctionPass(ID), TM(0) {
87 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
89 PPCCTRLoops(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
90 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
93 virtual bool runOnFunction(Function &F);
95 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
96 AU.addRequired<LoopInfo>();
97 AU.addPreserved<LoopInfo>();
98 AU.addRequired<DominatorTree>();
99 AU.addPreserved<DominatorTree>();
100 AU.addRequired<ScalarEvolution>();
104 // FIXME: Copied from LoopSimplify.
105 BasicBlock *InsertPreheaderForLoop(Loop *L);
106 void PlaceSplitBlockCarefully(BasicBlock *NewBB,
107 SmallVectorImpl<BasicBlock*> &SplitPreds,
110 bool mightUseCTR(const Triple &TT, BasicBlock *BB);
111 bool convertToCTRLoop(Loop *L);
113 PPCTargetMachine *TM;
118 const TargetLibraryInfo *LibInfo;
121 char PPCCTRLoops::ID = 0;
123 int PPCCTRLoops::Counter = 0;
127 struct PPCCTRLoopsVerify : public MachineFunctionPass {
131 PPCCTRLoopsVerify() : MachineFunctionPass(ID) {
132 initializePPCCTRLoopsVerifyPass(*PassRegistry::getPassRegistry());
135 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
136 AU.addRequired<MachineDominatorTree>();
137 MachineFunctionPass::getAnalysisUsage(AU);
140 virtual bool runOnMachineFunction(MachineFunction &MF);
143 MachineDominatorTree *MDT;
146 char PPCCTRLoopsVerify::ID = 0;
148 } // end anonymous namespace
150 INITIALIZE_PASS_BEGIN(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
152 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
153 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
154 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
155 INITIALIZE_PASS_END(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
158 FunctionPass *llvm::createPPCCTRLoops(PPCTargetMachine &TM) {
159 return new PPCCTRLoops(TM);
163 INITIALIZE_PASS_BEGIN(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
164 "PowerPC CTR Loops Verify", false, false)
165 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
166 INITIALIZE_PASS_END(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
167 "PowerPC CTR Loops Verify", false, false)
169 FunctionPass *llvm::createPPCCTRLoopsVerify() {
170 return new PPCCTRLoopsVerify();
174 bool PPCCTRLoops::runOnFunction(Function &F) {
175 LI = &getAnalysis<LoopInfo>();
176 SE = &getAnalysis<ScalarEvolution>();
177 DT = &getAnalysis<DominatorTree>();
178 TD = getAnalysisIfAvailable<DataLayout>();
179 LibInfo = getAnalysisIfAvailable<TargetLibraryInfo>();
181 bool MadeChange = false;
183 for (LoopInfo::iterator I = LI->begin(), E = LI->end();
186 if (!L->getParentLoop())
187 MadeChange |= convertToCTRLoop(L);
193 bool PPCCTRLoops::mightUseCTR(const Triple &TT, BasicBlock *BB) {
194 for (BasicBlock::iterator J = BB->begin(), JE = BB->end();
196 if (CallInst *CI = dyn_cast<CallInst>(J)) {
197 if (InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue())) {
198 // Inline ASM is okay, unless it clobbers the ctr register.
199 InlineAsm::ConstraintInfoVector CIV = IA->ParseConstraints();
200 for (unsigned i = 0, ie = CIV.size(); i < ie; ++i) {
201 InlineAsm::ConstraintInfo &C = CIV[i];
202 if (C.Type != InlineAsm::isInput)
203 for (unsigned j = 0, je = C.Codes.size(); j < je; ++j)
204 if (StringRef(C.Codes[j]).equals_lower("{ctr}"))
213 const TargetLowering *TLI = TM->getTargetLowering();
215 if (Function *F = CI->getCalledFunction()) {
216 // Most intrinsics don't become function calls, but some might.
217 // sin, cos, exp and log are always calls.
219 if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
220 switch (F->getIntrinsicID()) {
223 // VisualStudio defines setjmp as _setjmp
224 #if defined(_MSC_VER) && defined(setjmp) && \
225 !defined(setjmp_undefined_for_msvc)
226 # pragma push_macro("setjmp")
228 # define setjmp_undefined_for_msvc
231 case Intrinsic::setjmp:
233 #if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)
234 // let's return it to _setjmp state
235 # pragma pop_macro("setjmp")
236 # undef setjmp_undefined_for_msvc
239 case Intrinsic::longjmp:
240 case Intrinsic::memcpy:
241 case Intrinsic::memmove:
242 case Intrinsic::memset:
243 case Intrinsic::powi:
245 case Intrinsic::log2:
246 case Intrinsic::log10:
248 case Intrinsic::exp2:
253 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
254 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
255 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
256 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
257 case Intrinsic::rint: Opcode = ISD::FRINT; break;
258 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
262 // PowerPC does not use [US]DIVREM or other library calls for
263 // operations on regular types which are not otherwise library calls
264 // (i.e. soft float or atomics). If adapting for targets that do,
265 // additional care is required here.
268 if (!F->hasLocalLinkage() && F->hasName() && LibInfo &&
269 LibInfo->getLibFunc(F->getName(), Func) &&
270 LibInfo->hasOptimizedCodeGen(Func)) {
271 // Non-read-only functions are never treated as intrinsics.
272 if (!CI->onlyReadsMemory())
275 // Conversion happens only for FP calls.
276 if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
280 default: return true;
281 case LibFunc::copysign:
282 case LibFunc::copysignf:
283 case LibFunc::copysignl:
284 continue; // ISD::FCOPYSIGN is never a library call.
288 continue; // ISD::FABS is never a library call.
292 Opcode = ISD::FSQRT; break;
294 case LibFunc::floorf:
295 case LibFunc::floorl:
296 Opcode = ISD::FFLOOR; break;
297 case LibFunc::nearbyint:
298 case LibFunc::nearbyintf:
299 case LibFunc::nearbyintl:
300 Opcode = ISD::FNEARBYINT; break;
304 Opcode = ISD::FCEIL; break;
308 Opcode = ISD::FRINT; break;
310 case LibFunc::truncf:
311 case LibFunc::truncl:
312 Opcode = ISD::FTRUNC; break;
316 TLI->getSimpleValueType(CI->getArgOperand(0)->getType(), true);
317 if (VTy == MVT::Other)
320 if (TLI->isOperationLegalOrCustom(Opcode, VTy))
322 else if (VTy.isVector() &&
323 TLI->isOperationLegalOrCustom(Opcode, VTy.getScalarType()))
331 } else if (isa<BinaryOperator>(J) &&
332 J->getType()->getScalarType()->isPPC_FP128Ty()) {
333 // Most operations on ppc_f128 values become calls.
335 } else if (isa<UIToFPInst>(J) || isa<SIToFPInst>(J) ||
336 isa<FPToUIInst>(J) || isa<FPToSIInst>(J)) {
337 CastInst *CI = cast<CastInst>(J);
338 if (CI->getSrcTy()->getScalarType()->isPPC_FP128Ty() ||
339 CI->getDestTy()->getScalarType()->isPPC_FP128Ty() ||
341 (CI->getSrcTy()->getScalarType()->isIntegerTy(64) ||
342 CI->getDestTy()->getScalarType()->isIntegerTy(64))
345 } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
346 // On PowerPC, indirect jumps use the counter register.
348 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
351 const TargetLowering *TLI = TM->getTargetLowering();
353 if (TLI->supportJumpTables() &&
354 SI->getNumCases()+1 >= (unsigned) TLI->getMinimumJumpTableEntries())
362 bool PPCCTRLoops::convertToCTRLoop(Loop *L) {
363 bool MadeChange = false;
365 Triple TT = Triple(L->getHeader()->getParent()->getParent()->
367 if (!TT.isArch32Bit() && !TT.isArch64Bit())
368 return MadeChange; // Unknown arch. type.
370 // Process nested loops first.
371 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
372 MadeChange |= convertToCTRLoop(*I);
375 // If a nested loop has been converted, then we can't convert this loop.
380 // Stop trying after reaching the limit (if any).
381 int Limit = CTRLoopLimit;
383 if (Counter >= CTRLoopLimit)
389 // We don't want to spill/restore the counter register, and so we don't
390 // want to use the counter register if the loop contains calls.
391 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
393 if (mightUseCTR(TT, *I))
396 SmallVector<BasicBlock*, 4> ExitingBlocks;
397 L->getExitingBlocks(ExitingBlocks);
399 BasicBlock *CountedExitBlock = 0;
400 const SCEV *ExitCount = 0;
401 BranchInst *CountedExitBranch = 0;
402 for (SmallVector<BasicBlock*, 4>::iterator I = ExitingBlocks.begin(),
403 IE = ExitingBlocks.end(); I != IE; ++I) {
404 const SCEV *EC = SE->getExitCount(L, *I);
405 DEBUG(dbgs() << "Exit Count for " << *L << " from block " <<
406 (*I)->getName() << ": " << *EC << "\n");
407 if (isa<SCEVCouldNotCompute>(EC))
409 if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
410 if (ConstEC->getValue()->isZero())
412 } else if (!SE->isLoopInvariant(EC, L))
415 // We now have a loop-invariant count of loop iterations (which is not the
416 // constant zero) for which we know that this loop will not exit via this
419 // We need to make sure that this block will run on every loop iteration.
420 // For this to be true, we must dominate all blocks with backedges. Such
421 // blocks are in-loop predecessors to the header block.
422 bool NotAlways = false;
423 for (pred_iterator PI = pred_begin(L->getHeader()),
424 PIE = pred_end(L->getHeader()); PI != PIE; ++PI) {
425 if (!L->contains(*PI))
428 if (!DT->dominates(*I, *PI)) {
437 // Make sure this blocks ends with a conditional branch.
438 Instruction *TI = (*I)->getTerminator();
442 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
443 if (!BI->isConditional())
446 CountedExitBranch = BI;
450 // Note that this block may not be the loop latch block, even if the loop
451 // has a latch block.
452 CountedExitBlock = *I;
457 if (!CountedExitBlock)
460 BasicBlock *Preheader = L->getLoopPreheader();
462 // If we don't have a preheader, then insert one. If we already have a
463 // preheader, then we can use it (except if the preheader contains a use of
464 // the CTR register because some such uses might be reordered by the
465 // selection DAG after the mtctr instruction).
466 if (!Preheader || mightUseCTR(TT, Preheader))
467 Preheader = InsertPreheaderForLoop(L);
471 DEBUG(dbgs() << "Preheader for exit count: " << Preheader->getName() << "\n");
473 // Insert the count into the preheader and replace the condition used by the
477 SCEVExpander SCEVE(*SE, "loopcnt");
478 LLVMContext &C = SE->getContext();
479 Type *CountType = TT.isArch64Bit() ? Type::getInt64Ty(C) :
481 if (!ExitCount->getType()->isPointerTy() &&
482 ExitCount->getType() != CountType)
483 ExitCount = SE->getZeroExtendExpr(ExitCount, CountType);
484 ExitCount = SE->getAddExpr(ExitCount,
485 SE->getConstant(CountType, 1));
486 Value *ECValue = SCEVE.expandCodeFor(ExitCount, CountType,
487 Preheader->getTerminator());
489 IRBuilder<> CountBuilder(Preheader->getTerminator());
490 Module *M = Preheader->getParent()->getParent();
491 Value *MTCTRFunc = Intrinsic::getDeclaration(M, Intrinsic::ppc_mtctr,
493 CountBuilder.CreateCall(MTCTRFunc, ECValue);
495 IRBuilder<> CondBuilder(CountedExitBranch);
497 Intrinsic::getDeclaration(M, Intrinsic::ppc_is_decremented_ctr_nonzero);
498 Value *NewCond = CondBuilder.CreateCall(DecFunc);
499 Value *OldCond = CountedExitBranch->getCondition();
500 CountedExitBranch->setCondition(NewCond);
502 // The false branch must exit the loop.
503 if (!L->contains(CountedExitBranch->getSuccessor(0)))
504 CountedExitBranch->swapSuccessors();
506 // The old condition may be dead now, and may have even created a dead PHI
507 // (the original induction variable).
508 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
509 DeleteDeadPHIs(CountedExitBlock);
515 // FIXME: Copied from LoopSimplify.
516 BasicBlock *PPCCTRLoops::InsertPreheaderForLoop(Loop *L) {
517 BasicBlock *Header = L->getHeader();
519 // Compute the set of predecessors of the loop that are not in the loop.
520 SmallVector<BasicBlock*, 8> OutsideBlocks;
521 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
524 if (!L->contains(P)) { // Coming in from outside the loop?
525 // If the loop is branched to from an indirect branch, we won't
526 // be able to fully transform the loop, because it prohibits
528 if (isa<IndirectBrInst>(P->getTerminator())) return 0;
531 OutsideBlocks.push_back(P);
535 // Split out the loop pre-header.
536 BasicBlock *PreheaderBB;
537 if (!Header->isLandingPad()) {
538 PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader",
541 SmallVector<BasicBlock*, 2> NewBBs;
542 SplitLandingPadPredecessors(Header, OutsideBlocks, ".preheader",
543 ".split-lp", this, NewBBs);
544 PreheaderBB = NewBBs[0];
547 PreheaderBB->getTerminator()->setDebugLoc(
548 Header->getFirstNonPHI()->getDebugLoc());
549 DEBUG(dbgs() << "Creating pre-header "
550 << PreheaderBB->getName() << "\n");
552 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
553 // code layout too horribly.
554 PlaceSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
559 void PPCCTRLoops::PlaceSplitBlockCarefully(BasicBlock *NewBB,
560 SmallVectorImpl<BasicBlock*> &SplitPreds,
562 // Check to see if NewBB is already well placed.
563 Function::iterator BBI = NewBB; --BBI;
564 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
565 if (&*BBI == SplitPreds[i])
569 // If it isn't already after an outside block, move it after one. This is
570 // always good as it makes the uncond branch from the outside block into a
573 // Figure out *which* outside block to put this after. Prefer an outside
574 // block that neighbors a BB actually in the loop.
575 BasicBlock *FoundBB = 0;
576 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
577 Function::iterator BBI = SplitPreds[i];
578 if (++BBI != NewBB->getParent()->end() &&
580 FoundBB = SplitPreds[i];
585 // If our heuristic for a *good* bb to place this after doesn't find
586 // anything, just pick something. It's likely better than leaving it within
589 FoundBB = SplitPreds[0];
590 NewBB->moveAfter(FoundBB);
594 static bool clobbersCTR(const MachineInstr *MI) {
595 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
596 const MachineOperand &MO = MI->getOperand(i);
598 if (MO.isDef() && (MO.getReg() == PPC::CTR || MO.getReg() == PPC::CTR8))
600 } else if (MO.isRegMask()) {
601 if (MO.clobbersPhysReg(PPC::CTR) || MO.clobbersPhysReg(PPC::CTR8))
609 static bool verifyCTRBranch(MachineBasicBlock *MBB,
610 MachineBasicBlock::iterator I) {
611 MachineBasicBlock::iterator BI = I;
612 SmallSet<MachineBasicBlock *, 16> Visited;
613 SmallVector<MachineBasicBlock *, 8> Preds;
616 if (I == MBB->begin()) {
628 for (MachineBasicBlock::iterator IE = MBB->begin();; --I) {
629 unsigned Opc = I->getOpcode();
630 if (Opc == PPC::MTCTRloop || Opc == PPC::MTCTR8loop) {
635 if (I != BI && clobbersCTR(I)) {
636 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " (" <<
637 MBB->getFullName() << ") instruction " << *I <<
638 " clobbers CTR, invalidating " << "BB#" <<
639 BI->getParent()->getNumber() << " (" <<
640 BI->getParent()->getFullName() << ") instruction " <<
649 if (!CheckPreds && Preds.empty())
654 if (MachineFunction::iterator(MBB) == MBB->getParent()->begin()) {
655 DEBUG(dbgs() << "Unable to find a MTCTR instruction for BB#" <<
656 BI->getParent()->getNumber() << " (" <<
657 BI->getParent()->getFullName() << ") instruction " <<
662 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
663 PIE = MBB->pred_end(); PI != PIE; ++PI)
664 Preds.push_back(*PI);
668 MBB = Preds.pop_back_val();
669 if (!Visited.count(MBB)) {
670 I = MBB->getLastNonDebugInstr();
673 } while (!Preds.empty());
678 bool PPCCTRLoopsVerify::runOnMachineFunction(MachineFunction &MF) {
679 MDT = &getAnalysis<MachineDominatorTree>();
681 // Verify that all bdnz/bdz instructions are dominated by a loop mtctr before
682 // any other instructions that might clobber the ctr register.
683 for (MachineFunction::iterator I = MF.begin(), IE = MF.end();
685 MachineBasicBlock *MBB = I;
686 if (!MDT->isReachableFromEntry(MBB))
689 for (MachineBasicBlock::iterator MII = MBB->getFirstTerminator(),
690 MIIE = MBB->end(); MII != MIIE; ++MII) {
691 unsigned Opc = MII->getOpcode();
692 if (Opc == PPC::BDNZ8 || Opc == PPC::BDNZ ||
693 Opc == PPC::BDZ8 || Opc == PPC::BDZ)
694 if (!verifyCTRBranch(MBB, MII))
695 llvm_unreachable("Invalid PPC CTR loop!");