Rename PPC MTCTRse to MTCTRloop
[oota-llvm.git] / lib / Target / PowerPC / PPCCTRLoops.cpp
1 //===-- 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).
12 //
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.
17 //
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.
23 //
24 //===----------------------------------------------------------------------===//
25
26 #define DEBUG_TYPE "ctrloops"
27
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"
49 #include "PPC.h"
50
51 #ifndef NDEBUG
52 #include "llvm/CodeGen/MachineDominators.h"
53 #include "llvm/CodeGen/MachineFunction.h"
54 #include "llvm/CodeGen/MachineFunctionPass.h"
55 #include "llvm/CodeGen/MachineRegisterInfo.h"
56 #endif
57
58 #include <algorithm>
59 #include <vector>
60
61 using namespace llvm;
62
63 #ifndef NDEBUG
64 static cl::opt<int> CTRLoopLimit("ppc-max-ctrloop", cl::Hidden, cl::init(-1));
65 #endif
66
67 STATISTIC(NumCTRLoops, "Number of loops converted to CTR loops");
68
69 namespace llvm {
70   void initializePPCCTRLoopsPass(PassRegistry&);
71 #ifndef NDEBUG
72   void initializePPCCTRLoopsVerifyPass(PassRegistry&);
73 #endif
74 }
75
76 namespace {
77   struct PPCCTRLoops : public FunctionPass {
78
79 #ifndef NDEBUG
80     static int Counter;
81 #endif
82
83   public:
84     static char ID;
85
86     PPCCTRLoops() : FunctionPass(ID), TM(0) {
87       initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
88     }
89     PPCCTRLoops(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
90       initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
91     }
92
93     virtual bool runOnFunction(Function &F);
94
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>();
101     }
102
103   private:
104     // FIXME: Copied from LoopSimplify.
105     BasicBlock *InsertPreheaderForLoop(Loop *L);
106     void PlaceSplitBlockCarefully(BasicBlock *NewBB,
107                                   SmallVectorImpl<BasicBlock*> &SplitPreds,
108                                   Loop *L);
109
110     bool mightUseCTR(const Triple &TT, BasicBlock *BB);
111     bool convertToCTRLoop(Loop *L);
112   private:
113     PPCTargetMachine *TM;
114     LoopInfo *LI;
115     ScalarEvolution *SE;
116     DataLayout *TD;
117     DominatorTree *DT;
118     const TargetLibraryInfo *LibInfo;
119   };
120
121   char PPCCTRLoops::ID = 0;
122 #ifndef NDEBUG
123   int PPCCTRLoops::Counter = 0;
124 #endif
125
126 #ifndef NDEBUG
127   struct PPCCTRLoopsVerify : public MachineFunctionPass {
128   public:
129     static char ID;
130
131     PPCCTRLoopsVerify() : MachineFunctionPass(ID) {
132       initializePPCCTRLoopsVerifyPass(*PassRegistry::getPassRegistry());
133     }
134
135     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
136       AU.addRequired<MachineDominatorTree>();
137       MachineFunctionPass::getAnalysisUsage(AU);
138     }
139
140     virtual bool runOnMachineFunction(MachineFunction &MF);
141
142   private:
143     MachineDominatorTree *MDT;
144   };
145
146   char PPCCTRLoopsVerify::ID = 0;
147 #endif // NDEBUG
148 } // end anonymous namespace
149
150 INITIALIZE_PASS_BEGIN(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
151                       false, false)
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",
156                     false, false)
157
158 FunctionPass *llvm::createPPCCTRLoops(PPCTargetMachine &TM) {
159   return new PPCCTRLoops(TM);
160 }
161
162 #ifndef NDEBUG
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)
168
169 FunctionPass *llvm::createPPCCTRLoopsVerify() {
170   return new PPCCTRLoopsVerify();
171 }
172 #endif // NDEBUG
173
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>();
180
181   bool MadeChange = false;
182
183   for (LoopInfo::iterator I = LI->begin(), E = LI->end();
184        I != E; ++I) {
185     Loop *L = *I;
186     if (!L->getParentLoop())
187       MadeChange |= convertToCTRLoop(L);
188   }
189
190   return MadeChange;
191 }
192
193 bool PPCCTRLoops::mightUseCTR(const Triple &TT, BasicBlock *BB) {
194   for (BasicBlock::iterator J = BB->begin(), JE = BB->end();
195        J != JE; ++J) {
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}"))
205                 return true;
206         }
207
208         continue;
209       }
210
211       if (!TM)
212         return true;
213       const TargetLowering *TLI = TM->getTargetLowering();
214
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.
218         unsigned Opcode;
219         if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
220           switch (F->getIntrinsicID()) {
221           default: continue;
222
223 // VisualStudio defines setjmp as _setjmp
224 #if defined(_MSC_VER) && defined(setjmp) && \
225                        !defined(setjmp_undefined_for_msvc)
226 #  pragma push_macro("setjmp")
227 #  undef setjmp
228 #  define setjmp_undefined_for_msvc
229 #endif
230
231           case Intrinsic::setjmp:
232
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
237 #endif
238
239           case Intrinsic::longjmp:
240           case Intrinsic::memcpy:
241           case Intrinsic::memmove:
242           case Intrinsic::memset:
243           case Intrinsic::powi:
244           case Intrinsic::log:
245           case Intrinsic::log2:
246           case Intrinsic::log10:
247           case Intrinsic::exp:
248           case Intrinsic::exp2:
249           case Intrinsic::pow:
250           case Intrinsic::sin:
251           case Intrinsic::cos:
252             return true;
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;
259           }
260         }
261
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.
266
267         LibFunc::Func Func;
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())
273             return true;
274
275           // Conversion happens only for FP calls.
276           if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
277             return true;
278
279           switch (Func) {
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.
285           case LibFunc::fabs:
286           case LibFunc::fabsf:
287           case LibFunc::fabsl:
288             continue; // ISD::FABS is never a library call.
289           case LibFunc::sqrt:
290           case LibFunc::sqrtf:
291           case LibFunc::sqrtl:
292             Opcode = ISD::FSQRT; break;
293           case LibFunc::floor:
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;
301           case LibFunc::ceil:
302           case LibFunc::ceilf:
303           case LibFunc::ceill:
304             Opcode = ISD::FCEIL; break;
305           case LibFunc::rint:
306           case LibFunc::rintf:
307           case LibFunc::rintl:
308             Opcode = ISD::FRINT; break;
309           case LibFunc::trunc:
310           case LibFunc::truncf:
311           case LibFunc::truncl:
312             Opcode = ISD::FTRUNC; break;
313           }
314
315           MVT VTy =
316             TLI->getSimpleValueType(CI->getArgOperand(0)->getType(), true);
317           if (VTy == MVT::Other)
318             return true;
319           
320           if (TLI->isOperationLegalOrCustom(Opcode, VTy))
321             continue;
322           else if (VTy.isVector() &&
323                    TLI->isOperationLegalOrCustom(Opcode, VTy.getScalarType()))
324             continue;
325
326           return true;
327         }
328       }
329
330       return true;
331     } else if (isa<BinaryOperator>(J) &&
332                J->getType()->getScalarType()->isPPC_FP128Ty()) {
333       // Most operations on ppc_f128 values become calls.
334       return true;
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() ||
340           (TT.isArch32Bit() &&
341            (CI->getSrcTy()->getScalarType()->isIntegerTy(64) ||
342             CI->getDestTy()->getScalarType()->isIntegerTy(64))
343           ))
344         return true;
345     } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
346       // On PowerPC, indirect jumps use the counter register.
347       return true;
348     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
349       if (!TM)
350         return true;
351       const TargetLowering *TLI = TM->getTargetLowering();
352
353       if (TLI->supportJumpTables() &&
354           SI->getNumCases()+1 >= (unsigned) TLI->getMinimumJumpTableEntries())
355         return true;
356     }
357   }
358
359   return false;
360 }
361
362 bool PPCCTRLoops::convertToCTRLoop(Loop *L) {
363   bool MadeChange = false;
364
365   Triple TT = Triple(L->getHeader()->getParent()->getParent()->
366                      getTargetTriple());
367   if (!TT.isArch32Bit() && !TT.isArch64Bit())
368     return MadeChange; // Unknown arch. type.
369
370   // Process nested loops first.
371   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
372     MadeChange |= convertToCTRLoop(*I);
373   }
374
375   // If a nested loop has been converted, then we can't convert this loop.
376   if (MadeChange)
377     return MadeChange;
378
379 #ifndef NDEBUG
380   // Stop trying after reaching the limit (if any).
381   int Limit = CTRLoopLimit;
382   if (Limit >= 0) {
383     if (Counter >= CTRLoopLimit)
384       return false;
385     Counter++;
386   }
387 #endif
388
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();
392        I != IE; ++I)
393     if (mightUseCTR(TT, *I))
394       return MadeChange;
395
396   SmallVector<BasicBlock*, 4> ExitingBlocks;
397   L->getExitingBlocks(ExitingBlocks);
398
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))
408       continue;
409     if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
410       if (ConstEC->getValue()->isZero())
411         continue;
412     } else if (!SE->isLoopInvariant(EC, L))
413       continue;
414
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
417     // exisiting block.
418
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))
426         continue;
427
428       if (!DT->dominates(*I, *PI)) {
429         NotAlways = true;
430         break;
431       }
432     }
433
434     if (NotAlways)
435       continue;
436
437     // Make sure this blocks ends with a conditional branch.
438     Instruction *TI = (*I)->getTerminator();
439     if (!TI)
440       continue;
441
442     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
443       if (!BI->isConditional())
444         continue;
445
446       CountedExitBranch = BI;
447     } else
448       continue;
449
450     // Note that this block may not be the loop latch block, even if the loop
451     // has a latch block.
452     CountedExitBlock = *I;
453     ExitCount = EC;
454     break;
455   }
456
457   if (!CountedExitBlock)
458     return MadeChange;
459
460   BasicBlock *Preheader = L->getLoopPreheader();
461
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);
468   if (!Preheader)
469     return MadeChange;
470
471   DEBUG(dbgs() << "Preheader for exit count: " << Preheader->getName() << "\n");
472
473   // Insert the count into the preheader and replace the condition used by the
474   // selected branch.
475   MadeChange = true;
476
477   SCEVExpander SCEVE(*SE, "loopcnt");
478   LLVMContext &C = SE->getContext();
479   Type *CountType = TT.isArch64Bit() ? Type::getInt64Ty(C) :
480                                        Type::getInt32Ty(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());
488
489   IRBuilder<> CountBuilder(Preheader->getTerminator());
490   Module *M = Preheader->getParent()->getParent();
491   Value *MTCTRFunc = Intrinsic::getDeclaration(M, Intrinsic::ppc_mtctr,
492                                                CountType);
493   CountBuilder.CreateCall(MTCTRFunc, ECValue);
494
495   IRBuilder<> CondBuilder(CountedExitBranch);
496   Value *DecFunc =
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);
501
502   // The false branch must exit the loop.
503   if (!L->contains(CountedExitBranch->getSuccessor(0)))
504     CountedExitBranch->swapSuccessors();
505
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);
510
511   ++NumCTRLoops;
512   return MadeChange;
513 }
514
515 // FIXME: Copied from LoopSimplify.
516 BasicBlock *PPCCTRLoops::InsertPreheaderForLoop(Loop *L) {
517   BasicBlock *Header = L->getHeader();
518
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);
522        PI != PE; ++PI) {
523     BasicBlock *P = *PI;
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
527       // edge splitting.
528       if (isa<IndirectBrInst>(P->getTerminator())) return 0;
529
530       // Keep track of it.
531       OutsideBlocks.push_back(P);
532     }
533   }
534
535   // Split out the loop pre-header.
536   BasicBlock *PreheaderBB;
537   if (!Header->isLandingPad()) {
538     PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader",
539                                          this);
540   } else {
541     SmallVector<BasicBlock*, 2> NewBBs;
542     SplitLandingPadPredecessors(Header, OutsideBlocks, ".preheader",
543                                 ".split-lp", this, NewBBs);
544     PreheaderBB = NewBBs[0];
545   }
546
547   PreheaderBB->getTerminator()->setDebugLoc(
548                                       Header->getFirstNonPHI()->getDebugLoc());
549   DEBUG(dbgs() << "Creating pre-header "
550                << PreheaderBB->getName() << "\n");
551
552   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
553   // code layout too horribly.
554   PlaceSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
555
556   return PreheaderBB;
557 }
558
559 void PPCCTRLoops::PlaceSplitBlockCarefully(BasicBlock *NewBB,
560                                        SmallVectorImpl<BasicBlock*> &SplitPreds,
561                                             Loop *L) {
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])
566       return;
567   }
568
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
571   // fall-through.
572
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() &&
579         L->contains(BBI)) {
580       FoundBB = SplitPreds[i];
581       break;
582     }
583   }
584
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
587   // the loop.
588   if (!FoundBB)
589     FoundBB = SplitPreds[0];
590   NewBB->moveAfter(FoundBB);
591 }
592
593 #ifndef NDEBUG
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);
597     if (MO.isReg()) {
598       if (MO.isDef() && (MO.getReg() == PPC::CTR || MO.getReg() == PPC::CTR8))
599         return true;
600     } else if (MO.isRegMask()) {
601       if (MO.clobbersPhysReg(PPC::CTR) || MO.clobbersPhysReg(PPC::CTR8))
602         return true;
603     }
604   }
605
606   return false;
607 }
608
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;
614   bool CheckPreds;
615
616   if (I == MBB->begin()) {
617     Visited.insert(MBB);
618     goto queue_preds;
619   } else
620     --I;
621
622 check_block:
623   Visited.insert(MBB);
624   if (I == MBB->end())
625     goto queue_preds;
626
627   CheckPreds = true;
628   for (MachineBasicBlock::iterator IE = MBB->begin();; --I) {
629     unsigned Opc = I->getOpcode();
630     if (Opc == PPC::MTCTRloop || Opc == PPC::MTCTR8loop) {
631       CheckPreds = false;
632       break;
633     }
634
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 " <<
641                       *BI << "\n");
642       return false;
643     }
644
645     if (I == IE)
646       break;
647   }
648
649   if (!CheckPreds && Preds.empty())
650     return true;
651
652   if (CheckPreds) {
653 queue_preds:
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 " <<
658                       *BI << "\n");
659       return false;
660     }
661
662     for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
663          PIE = MBB->pred_end(); PI != PIE; ++PI)
664       Preds.push_back(*PI);
665   }
666
667   do {
668     MBB = Preds.pop_back_val();
669     if (!Visited.count(MBB)) {
670       I = MBB->getLastNonDebugInstr();
671       goto check_block;
672     }
673   } while (!Preds.empty());
674
675   return true;
676 }
677
678 bool PPCCTRLoopsVerify::runOnMachineFunction(MachineFunction &MF) {
679   MDT = &getAnalysis<MachineDominatorTree>();
680
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();
684        I != IE; ++I) {
685     MachineBasicBlock *MBB = I;
686     if (!MDT->isReachableFromEntry(MBB))
687       continue;
688
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!");
696     }
697   }
698
699   return false;
700 }
701 #endif // NDEBUG
702