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 #include "llvm/Transforms/Scalar.h"
27 #include "PPC.h"
28 #include "PPCTargetMachine.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/Analysis/ScalarEvolutionExpander.h"
33 #include "llvm/Analysis/TargetLibraryInfo.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/InlineAsm.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/IR/ValueHandle.h"
42 #include "llvm/PassSupport.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Transforms/Utils/LoopUtils.h"
49 
50 #ifndef NDEBUG
51 #include "llvm/CodeGen/MachineDominators.h"
52 #include "llvm/CodeGen/MachineFunction.h"
53 #include "llvm/CodeGen/MachineFunctionPass.h"
54 #include "llvm/CodeGen/MachineRegisterInfo.h"
55 #endif
56 
57 using namespace llvm;
58 
59 #define DEBUG_TYPE "ctrloops"
60 
61 #ifndef NDEBUG
62 static cl::opt<int> CTRLoopLimit("ppc-max-ctrloop", cl::Hidden, cl::init(-1));
63 #endif
64 
65 STATISTIC(NumCTRLoops, "Number of loops converted to CTR loops");
66 
67 namespace llvm {
68   void initializePPCCTRLoopsPass(PassRegistry&);
69 #ifndef NDEBUG
70   void initializePPCCTRLoopsVerifyPass(PassRegistry&);
71 #endif
72 }
73 
74 namespace {
75   struct PPCCTRLoops : public FunctionPass {
76 
77 #ifndef NDEBUG
78     static int Counter;
79 #endif
80 
81   public:
82     static char ID;
83 
84     PPCCTRLoops() : FunctionPass(ID), TM(nullptr) {
85       initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
86     }
87     PPCCTRLoops(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
88       initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
89     }
90 
91     bool runOnFunction(Function &F) override;
92 
93     void getAnalysisUsage(AnalysisUsage &AU) const override {
94       AU.addRequired<LoopInfoWrapperPass>();
95       AU.addPreserved<LoopInfoWrapperPass>();
96       AU.addRequired<DominatorTreeWrapperPass>();
97       AU.addPreserved<DominatorTreeWrapperPass>();
98       AU.addRequired<ScalarEvolutionWrapperPass>();
99     }
100 
101   private:
102     bool mightUseCTR(const Triple &TT, BasicBlock *BB);
103     bool convertToCTRLoop(Loop *L);
104 
105   private:
106     PPCTargetMachine *TM;
107     LoopInfo *LI;
108     ScalarEvolution *SE;
109     const DataLayout *DL;
110     DominatorTree *DT;
111     const TargetLibraryInfo *LibInfo;
112     bool PreserveLCSSA;
113   };
114 
115   char PPCCTRLoops::ID = 0;
116 #ifndef NDEBUG
117   int PPCCTRLoops::Counter = 0;
118 #endif
119 
120 #ifndef NDEBUG
121   struct PPCCTRLoopsVerify : public MachineFunctionPass {
122   public:
123     static char ID;
124 
125     PPCCTRLoopsVerify() : MachineFunctionPass(ID) {
126       initializePPCCTRLoopsVerifyPass(*PassRegistry::getPassRegistry());
127     }
128 
129     void getAnalysisUsage(AnalysisUsage &AU) const override {
130       AU.addRequired<MachineDominatorTree>();
131       MachineFunctionPass::getAnalysisUsage(AU);
132     }
133 
134     bool runOnMachineFunction(MachineFunction &MF) override;
135 
136   private:
137     MachineDominatorTree *MDT;
138   };
139 
140   char PPCCTRLoopsVerify::ID = 0;
141 #endif // NDEBUG
142 } // end anonymous namespace
143 
144 INITIALIZE_PASS_BEGIN(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
145                       false, false)
146 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
147 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
148 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
149 INITIALIZE_PASS_END(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
150                     false, false)
151 
152 FunctionPass *llvm::createPPCCTRLoops(PPCTargetMachine &TM) {
153   return new PPCCTRLoops(TM);
154 }
155 
156 #ifndef NDEBUG
157 INITIALIZE_PASS_BEGIN(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
158                       "PowerPC CTR Loops Verify", false, false)
159 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
160 INITIALIZE_PASS_END(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
161                     "PowerPC CTR Loops Verify", false, false)
162 
163 FunctionPass *llvm::createPPCCTRLoopsVerify() {
164   return new PPCCTRLoopsVerify();
165 }
166 #endif // NDEBUG
167 
168 bool PPCCTRLoops::runOnFunction(Function &F) {
169   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
170   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
171   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
172   DL = &F.getParent()->getDataLayout();
173   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
174   LibInfo = TLIP ? &TLIP->getTLI() : nullptr;
175   PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
176 
177   bool MadeChange = false;
178 
179   for (LoopInfo::iterator I = LI->begin(), E = LI->end();
180        I != E; ++I) {
181     Loop *L = *I;
182     if (!L->getParentLoop())
183       MadeChange |= convertToCTRLoop(L);
184   }
185 
186   return MadeChange;
187 }
188 
189 static bool isLargeIntegerTy(bool Is32Bit, Type *Ty) {
190   if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
191     return ITy->getBitWidth() > (Is32Bit ? 32U : 64U);
192 
193   return false;
194 }
195 
196 // Determining the address of a TLS variable results in a function call in
197 // certain TLS models.
198 static bool memAddrUsesCTR(const PPCTargetMachine *TM,
199                            const Value *MemAddr) {
200   const auto *GV = dyn_cast<GlobalValue>(MemAddr);
201   if (!GV) {
202     // Recurse to check for constants that refer to TLS global variables.
203     if (const auto *CV = dyn_cast<Constant>(MemAddr))
204       for (const auto &CO : CV->operands())
205         if (memAddrUsesCTR(TM, CO))
206           return true;
207 
208     return false;
209   }
210 
211   if (!GV->isThreadLocal())
212     return false;
213   if (!TM)
214     return true;
215   TLSModel::Model Model = TM->getTLSModel(GV);
216   return Model == TLSModel::GeneralDynamic || Model == TLSModel::LocalDynamic;
217 }
218 
219 bool PPCCTRLoops::mightUseCTR(const Triple &TT, BasicBlock *BB) {
220   for (BasicBlock::iterator J = BB->begin(), JE = BB->end();
221        J != JE; ++J) {
222     if (CallInst *CI = dyn_cast<CallInst>(J)) {
223       if (InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue())) {
224         // Inline ASM is okay, unless it clobbers the ctr register.
225         InlineAsm::ConstraintInfoVector CIV = IA->ParseConstraints();
226         for (unsigned i = 0, ie = CIV.size(); i < ie; ++i) {
227           InlineAsm::ConstraintInfo &C = CIV[i];
228           if (C.Type != InlineAsm::isInput)
229             for (unsigned j = 0, je = C.Codes.size(); j < je; ++j)
230               if (StringRef(C.Codes[j]).equals_lower("{ctr}"))
231                 return true;
232         }
233 
234         continue;
235       }
236 
237       if (!TM)
238         return true;
239       const TargetLowering *TLI =
240           TM->getSubtargetImpl(*BB->getParent())->getTargetLowering();
241 
242       if (Function *F = CI->getCalledFunction()) {
243         // Most intrinsics don't become function calls, but some might.
244         // sin, cos, exp and log are always calls.
245         unsigned Opcode = 0;
246         if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
247           switch (F->getIntrinsicID()) {
248           default: continue;
249           // If we have a call to ppc_is_decremented_ctr_nonzero, or ppc_mtctr
250           // we're definitely using CTR.
251           case Intrinsic::ppc_is_decremented_ctr_nonzero:
252           case Intrinsic::ppc_mtctr:
253             return true;
254 
255 // VisualStudio defines setjmp as _setjmp
256 #if defined(_MSC_VER) && defined(setjmp) && \
257                        !defined(setjmp_undefined_for_msvc)
258 #  pragma push_macro("setjmp")
259 #  undef setjmp
260 #  define setjmp_undefined_for_msvc
261 #endif
262 
263           case Intrinsic::setjmp:
264 
265 #if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)
266  // let's return it to _setjmp state
267 #  pragma pop_macro("setjmp")
268 #  undef setjmp_undefined_for_msvc
269 #endif
270 
271           case Intrinsic::longjmp:
272 
273           // Exclude eh_sjlj_setjmp; we don't need to exclude eh_sjlj_longjmp
274           // because, although it does clobber the counter register, the
275           // control can't then return to inside the loop unless there is also
276           // an eh_sjlj_setjmp.
277           case Intrinsic::eh_sjlj_setjmp:
278 
279           case Intrinsic::memcpy:
280           case Intrinsic::memmove:
281           case Intrinsic::memset:
282           case Intrinsic::powi:
283           case Intrinsic::log:
284           case Intrinsic::log2:
285           case Intrinsic::log10:
286           case Intrinsic::exp:
287           case Intrinsic::exp2:
288           case Intrinsic::pow:
289           case Intrinsic::sin:
290           case Intrinsic::cos:
291             return true;
292           case Intrinsic::copysign:
293             if (CI->getArgOperand(0)->getType()->getScalarType()->
294                 isPPC_FP128Ty())
295               return true;
296             else
297               continue; // ISD::FCOPYSIGN is never a library call.
298           case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
299           case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
300           case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
301           case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
302           case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
303           case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
304           case Intrinsic::round:     Opcode = ISD::FROUND;     break;
305           case Intrinsic::minnum:    Opcode = ISD::FMINNUM;    break;
306           case Intrinsic::maxnum:    Opcode = ISD::FMAXNUM;    break;
307           }
308         }
309 
310         // PowerPC does not use [US]DIVREM or other library calls for
311         // operations on regular types which are not otherwise library calls
312         // (i.e. soft float or atomics). If adapting for targets that do,
313         // additional care is required here.
314 
315         LibFunc::Func Func;
316         if (!F->hasLocalLinkage() && F->hasName() && LibInfo &&
317             LibInfo->getLibFunc(F->getName(), Func) &&
318             LibInfo->hasOptimizedCodeGen(Func)) {
319           // Non-read-only functions are never treated as intrinsics.
320           if (!CI->onlyReadsMemory())
321             return true;
322 
323           // Conversion happens only for FP calls.
324           if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
325             return true;
326 
327           switch (Func) {
328           default: return true;
329           case LibFunc::copysign:
330           case LibFunc::copysignf:
331             continue; // ISD::FCOPYSIGN is never a library call.
332           case LibFunc::copysignl:
333             return true;
334           case LibFunc::fabs:
335           case LibFunc::fabsf:
336           case LibFunc::fabsl:
337             continue; // ISD::FABS is never a library call.
338           case LibFunc::sqrt:
339           case LibFunc::sqrtf:
340           case LibFunc::sqrtl:
341             Opcode = ISD::FSQRT; break;
342           case LibFunc::floor:
343           case LibFunc::floorf:
344           case LibFunc::floorl:
345             Opcode = ISD::FFLOOR; break;
346           case LibFunc::nearbyint:
347           case LibFunc::nearbyintf:
348           case LibFunc::nearbyintl:
349             Opcode = ISD::FNEARBYINT; break;
350           case LibFunc::ceil:
351           case LibFunc::ceilf:
352           case LibFunc::ceill:
353             Opcode = ISD::FCEIL; break;
354           case LibFunc::rint:
355           case LibFunc::rintf:
356           case LibFunc::rintl:
357             Opcode = ISD::FRINT; break;
358           case LibFunc::round:
359           case LibFunc::roundf:
360           case LibFunc::roundl:
361             Opcode = ISD::FROUND; break;
362           case LibFunc::trunc:
363           case LibFunc::truncf:
364           case LibFunc::truncl:
365             Opcode = ISD::FTRUNC; break;
366           case LibFunc::fmin:
367           case LibFunc::fminf:
368           case LibFunc::fminl:
369             Opcode = ISD::FMINNUM; break;
370           case LibFunc::fmax:
371           case LibFunc::fmaxf:
372           case LibFunc::fmaxl:
373             Opcode = ISD::FMAXNUM; break;
374           }
375         }
376 
377         if (Opcode) {
378           auto &DL = CI->getModule()->getDataLayout();
379           MVT VTy = TLI->getSimpleValueType(DL, CI->getArgOperand(0)->getType(),
380                                             true);
381           if (VTy == MVT::Other)
382             return true;
383 
384           if (TLI->isOperationLegalOrCustom(Opcode, VTy))
385             continue;
386           else if (VTy.isVector() &&
387                    TLI->isOperationLegalOrCustom(Opcode, VTy.getScalarType()))
388             continue;
389 
390           return true;
391         }
392       }
393 
394       return true;
395     } else if (isa<BinaryOperator>(J) &&
396                J->getType()->getScalarType()->isPPC_FP128Ty()) {
397       // Most operations on ppc_f128 values become calls.
398       return true;
399     } else if (isa<UIToFPInst>(J) || isa<SIToFPInst>(J) ||
400                isa<FPToUIInst>(J) || isa<FPToSIInst>(J)) {
401       CastInst *CI = cast<CastInst>(J);
402       if (CI->getSrcTy()->getScalarType()->isPPC_FP128Ty() ||
403           CI->getDestTy()->getScalarType()->isPPC_FP128Ty() ||
404           isLargeIntegerTy(TT.isArch32Bit(), CI->getSrcTy()->getScalarType()) ||
405           isLargeIntegerTy(TT.isArch32Bit(), CI->getDestTy()->getScalarType()))
406         return true;
407     } else if (isLargeIntegerTy(TT.isArch32Bit(),
408                                 J->getType()->getScalarType()) &&
409                (J->getOpcode() == Instruction::UDiv ||
410                 J->getOpcode() == Instruction::SDiv ||
411                 J->getOpcode() == Instruction::URem ||
412                 J->getOpcode() == Instruction::SRem)) {
413       return true;
414     } else if (TT.isArch32Bit() &&
415                isLargeIntegerTy(false, J->getType()->getScalarType()) &&
416                (J->getOpcode() == Instruction::Shl ||
417                 J->getOpcode() == Instruction::AShr ||
418                 J->getOpcode() == Instruction::LShr)) {
419       // Only on PPC32, for 128-bit integers (specifically not 64-bit
420       // integers), these might be runtime calls.
421       return true;
422     } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
423       // On PowerPC, indirect jumps use the counter register.
424       return true;
425     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
426       if (!TM)
427         return true;
428       const TargetLowering *TLI =
429           TM->getSubtargetImpl(*BB->getParent())->getTargetLowering();
430 
431       if (SI->getNumCases() + 1 >= (unsigned)TLI->getMinimumJumpTableEntries())
432         return true;
433     }
434 
435     if (TM->getSubtargetImpl(*BB->getParent())->getTargetLowering()->useSoftFloat()) {
436       switch(J->getOpcode()) {
437       case Instruction::FAdd:
438       case Instruction::FSub:
439       case Instruction::FMul:
440       case Instruction::FDiv:
441       case Instruction::FRem:
442       case Instruction::FPTrunc:
443       case Instruction::FPExt:
444       case Instruction::FPToUI:
445       case Instruction::FPToSI:
446       case Instruction::UIToFP:
447       case Instruction::SIToFP:
448       case Instruction::FCmp:
449         return true;
450       }
451     }
452 
453     for (Value *Operand : J->operands())
454       if (memAddrUsesCTR(TM, Operand))
455         return true;
456   }
457 
458   return false;
459 }
460 
461 bool PPCCTRLoops::convertToCTRLoop(Loop *L) {
462   bool MadeChange = false;
463 
464   const Triple TT =
465       Triple(L->getHeader()->getParent()->getParent()->getTargetTriple());
466   if (!TT.isArch32Bit() && !TT.isArch64Bit())
467     return MadeChange; // Unknown arch. type.
468 
469   // Process nested loops first.
470   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
471     MadeChange |= convertToCTRLoop(*I);
472     DEBUG(dbgs() << "Nested loop converted\n");
473   }
474 
475   // If a nested loop has been converted, then we can't convert this loop.
476   if (MadeChange)
477     return MadeChange;
478 
479 #ifndef NDEBUG
480   // Stop trying after reaching the limit (if any).
481   int Limit = CTRLoopLimit;
482   if (Limit >= 0) {
483     if (Counter >= CTRLoopLimit)
484       return false;
485     Counter++;
486   }
487 #endif
488 
489   // We don't want to spill/restore the counter register, and so we don't
490   // want to use the counter register if the loop contains calls.
491   for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
492        I != IE; ++I)
493     if (mightUseCTR(TT, *I))
494       return MadeChange;
495 
496   SmallVector<BasicBlock*, 4> ExitingBlocks;
497   L->getExitingBlocks(ExitingBlocks);
498 
499   BasicBlock *CountedExitBlock = nullptr;
500   const SCEV *ExitCount = nullptr;
501   BranchInst *CountedExitBranch = nullptr;
502   for (SmallVectorImpl<BasicBlock *>::iterator I = ExitingBlocks.begin(),
503        IE = ExitingBlocks.end(); I != IE; ++I) {
504     const SCEV *EC = SE->getExitCount(L, *I);
505     DEBUG(dbgs() << "Exit Count for " << *L << " from block " <<
506                     (*I)->getName() << ": " << *EC << "\n");
507     if (isa<SCEVCouldNotCompute>(EC))
508       continue;
509     if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
510       if (ConstEC->getValue()->isZero())
511         continue;
512     } else if (!SE->isLoopInvariant(EC, L))
513       continue;
514 
515     if (SE->getTypeSizeInBits(EC->getType()) > (TT.isArch64Bit() ? 64 : 32))
516       continue;
517 
518     // We now have a loop-invariant count of loop iterations (which is not the
519     // constant zero) for which we know that this loop will not exit via this
520     // exisiting block.
521 
522     // We need to make sure that this block will run on every loop iteration.
523     // For this to be true, we must dominate all blocks with backedges. Such
524     // blocks are in-loop predecessors to the header block.
525     bool NotAlways = false;
526     for (pred_iterator PI = pred_begin(L->getHeader()),
527          PIE = pred_end(L->getHeader()); PI != PIE; ++PI) {
528       if (!L->contains(*PI))
529         continue;
530 
531       if (!DT->dominates(*I, *PI)) {
532         NotAlways = true;
533         break;
534       }
535     }
536 
537     if (NotAlways)
538       continue;
539 
540     // Make sure this blocks ends with a conditional branch.
541     Instruction *TI = (*I)->getTerminator();
542     if (!TI)
543       continue;
544 
545     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
546       if (!BI->isConditional())
547         continue;
548 
549       CountedExitBranch = BI;
550     } else
551       continue;
552 
553     // Note that this block may not be the loop latch block, even if the loop
554     // has a latch block.
555     CountedExitBlock = *I;
556     ExitCount = EC;
557     break;
558   }
559 
560   if (!CountedExitBlock)
561     return MadeChange;
562 
563   BasicBlock *Preheader = L->getLoopPreheader();
564 
565   // If we don't have a preheader, then insert one. If we already have a
566   // preheader, then we can use it (except if the preheader contains a use of
567   // the CTR register because some such uses might be reordered by the
568   // selection DAG after the mtctr instruction).
569   if (!Preheader || mightUseCTR(TT, Preheader))
570     Preheader = InsertPreheaderForLoop(L, DT, LI, PreserveLCSSA);
571   if (!Preheader)
572     return MadeChange;
573 
574   DEBUG(dbgs() << "Preheader for exit count: " << Preheader->getName() << "\n");
575 
576   // Insert the count into the preheader and replace the condition used by the
577   // selected branch.
578   MadeChange = true;
579 
580   SCEVExpander SCEVE(*SE, Preheader->getModule()->getDataLayout(), "loopcnt");
581   LLVMContext &C = SE->getContext();
582   Type *CountType = TT.isArch64Bit() ? Type::getInt64Ty(C) :
583                                        Type::getInt32Ty(C);
584   if (!ExitCount->getType()->isPointerTy() &&
585       ExitCount->getType() != CountType)
586     ExitCount = SE->getZeroExtendExpr(ExitCount, CountType);
587   ExitCount = SE->getAddExpr(ExitCount, SE->getOne(CountType));
588   Value *ECValue =
589       SCEVE.expandCodeFor(ExitCount, CountType, Preheader->getTerminator());
590 
591   IRBuilder<> CountBuilder(Preheader->getTerminator());
592   Module *M = Preheader->getParent()->getParent();
593   Value *MTCTRFunc = Intrinsic::getDeclaration(M, Intrinsic::ppc_mtctr,
594                                                CountType);
595   CountBuilder.CreateCall(MTCTRFunc, ECValue);
596 
597   IRBuilder<> CondBuilder(CountedExitBranch);
598   Value *DecFunc =
599     Intrinsic::getDeclaration(M, Intrinsic::ppc_is_decremented_ctr_nonzero);
600   Value *NewCond = CondBuilder.CreateCall(DecFunc, {});
601   Value *OldCond = CountedExitBranch->getCondition();
602   CountedExitBranch->setCondition(NewCond);
603 
604   // The false branch must exit the loop.
605   if (!L->contains(CountedExitBranch->getSuccessor(0)))
606     CountedExitBranch->swapSuccessors();
607 
608   // The old condition may be dead now, and may have even created a dead PHI
609   // (the original induction variable).
610   RecursivelyDeleteTriviallyDeadInstructions(OldCond);
611   DeleteDeadPHIs(CountedExitBlock);
612 
613   ++NumCTRLoops;
614   return MadeChange;
615 }
616 
617 #ifndef NDEBUG
618 static bool clobbersCTR(const MachineInstr *MI) {
619   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
620     const MachineOperand &MO = MI->getOperand(i);
621     if (MO.isReg()) {
622       if (MO.isDef() && (MO.getReg() == PPC::CTR || MO.getReg() == PPC::CTR8))
623         return true;
624     } else if (MO.isRegMask()) {
625       if (MO.clobbersPhysReg(PPC::CTR) || MO.clobbersPhysReg(PPC::CTR8))
626         return true;
627     }
628   }
629 
630   return false;
631 }
632 
633 static bool verifyCTRBranch(MachineBasicBlock *MBB,
634                             MachineBasicBlock::iterator I) {
635   MachineBasicBlock::iterator BI = I;
636   SmallSet<MachineBasicBlock *, 16>   Visited;
637   SmallVector<MachineBasicBlock *, 8> Preds;
638   bool CheckPreds;
639 
640   if (I == MBB->begin()) {
641     Visited.insert(MBB);
642     goto queue_preds;
643   } else
644     --I;
645 
646 check_block:
647   Visited.insert(MBB);
648   if (I == MBB->end())
649     goto queue_preds;
650 
651   CheckPreds = true;
652   for (MachineBasicBlock::iterator IE = MBB->begin();; --I) {
653     unsigned Opc = I->getOpcode();
654     if (Opc == PPC::MTCTRloop || Opc == PPC::MTCTR8loop) {
655       CheckPreds = false;
656       break;
657     }
658 
659     if (I != BI && clobbersCTR(I)) {
660       DEBUG(dbgs() << "BB#" << MBB->getNumber() << " (" <<
661                       MBB->getFullName() << ") instruction " << *I <<
662                       " clobbers CTR, invalidating " << "BB#" <<
663                       BI->getParent()->getNumber() << " (" <<
664                       BI->getParent()->getFullName() << ") instruction " <<
665                       *BI << "\n");
666       return false;
667     }
668 
669     if (I == IE)
670       break;
671   }
672 
673   if (!CheckPreds && Preds.empty())
674     return true;
675 
676   if (CheckPreds) {
677 queue_preds:
678     if (MachineFunction::iterator(MBB) == MBB->getParent()->begin()) {
679       DEBUG(dbgs() << "Unable to find a MTCTR instruction for BB#" <<
680                       BI->getParent()->getNumber() << " (" <<
681                       BI->getParent()->getFullName() << ") instruction " <<
682                       *BI << "\n");
683       return false;
684     }
685 
686     for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
687          PIE = MBB->pred_end(); PI != PIE; ++PI)
688       Preds.push_back(*PI);
689   }
690 
691   do {
692     MBB = Preds.pop_back_val();
693     if (!Visited.count(MBB)) {
694       I = MBB->getLastNonDebugInstr();
695       goto check_block;
696     }
697   } while (!Preds.empty());
698 
699   return true;
700 }
701 
702 bool PPCCTRLoopsVerify::runOnMachineFunction(MachineFunction &MF) {
703   MDT = &getAnalysis<MachineDominatorTree>();
704 
705   // Verify that all bdnz/bdz instructions are dominated by a loop mtctr before
706   // any other instructions that might clobber the ctr register.
707   for (MachineFunction::iterator I = MF.begin(), IE = MF.end();
708        I != IE; ++I) {
709     MachineBasicBlock *MBB = &*I;
710     if (!MDT->isReachableFromEntry(MBB))
711       continue;
712 
713     for (MachineBasicBlock::iterator MII = MBB->getFirstTerminator(),
714       MIIE = MBB->end(); MII != MIIE; ++MII) {
715       unsigned Opc = MII->getOpcode();
716       if (Opc == PPC::BDNZ8 || Opc == PPC::BDNZ ||
717           Opc == PPC::BDZ8  || Opc == PPC::BDZ)
718         if (!verifyCTRBranch(MBB, MII))
719           llvm_unreachable("Invalid PPC CTR loop!");
720     }
721   }
722 
723   return false;
724 }
725 #endif // NDEBUG
726