1 //===-- EarlyIfConversion.cpp - If-conversion on SSA form machine code ----===//
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 // Early if-conversion is for out-of-order CPUs that don't have a lot of
11 // predicable instructions. The goal is to eliminate conditional branches that
14 // Instructions from both sides of the branch are executed specutatively, and a
15 // cmov instruction selects the result.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "early-ifcvt"
20 #include "llvm/Function.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SparseSet.h"
25 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
38 // Absolute maximum number of instructions allowed per speculated block.
39 // This bypasses all other heuristics, so it should be set fairly high.
40 static cl::opt<unsigned>
41 BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden,
42 cl::desc("Maximum number of instructions per speculated block."));
44 // Stress testing mode - disable heuristics.
45 static cl::opt<bool> Stress("stress-early-ifcvt", cl::Hidden,
46 cl::desc("Turn all knobs to 11"));
48 typedef SmallSetVector<MachineBasicBlock*, 8> BlockSetVector;
50 //===----------------------------------------------------------------------===//
52 //===----------------------------------------------------------------------===//
54 // The SSAIfConv class performs if-conversion on SSA form machine code after
55 // determining if it is possible. The class contains no heuristics, external
56 // code should be used to determine when if-conversion is a good idea.
58 // SSAIfConv con convert both triangles and diamonds:
60 // Triangle: Head Diamond: Head
68 // Instructions in the conditional blocks TBB and/or FBB are spliced into the
69 // Head block, and phis in the Tail black are converted to select instruction.
73 const TargetInstrInfo *TII;
74 const TargetRegisterInfo *TRI;
75 MachineRegisterInfo *MRI;
77 /// The block containing the conditional branch.
78 MachineBasicBlock *Head;
80 /// The block containing phis after the if-then-else.
81 MachineBasicBlock *Tail;
83 /// The 'true' conditional block as determined by AnalyzeBranch.
84 MachineBasicBlock *TBB;
86 /// The 'false' conditional block as determined by AnalyzeBranch.
87 MachineBasicBlock *FBB;
89 /// isTriangle - When there is no 'else' block, either TBB or FBB will be
91 bool isTriangle() const { return TBB == Tail || FBB == Tail; }
93 /// The branch condition determined by AnalyzeBranch.
94 SmallVector<MachineOperand, 4> Cond;
96 /// Information about each phi in the Tail block.
100 // Latencies from Cond+Branch, TReg, and FReg to DstReg.
101 int CondCycles, TCycles, FCycles;
103 PHIInfo(MachineInstr *phi)
104 : PHI(phi), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
107 SmallVector<PHIInfo, 8> PHIs;
109 /// Instructions in Head that define values used by the conditional blocks.
110 /// The hoisted instructions must be inserted after these instructions.
111 SmallPtrSet<MachineInstr*, 8> InsertAfter;
113 /// Register units clobbered by the conditional blocks.
114 BitVector ClobberedRegUnits;
116 // Scratch pad for findInsertionPoint.
117 SparseSet<unsigned> LiveRegUnits;
119 /// Insertion point in Head for speculatively executed instructions form TBB
121 MachineBasicBlock::iterator InsertionPoint;
123 /// Return true if all non-terminator instructions in MBB can be safely
125 bool canSpeculateInstrs(MachineBasicBlock *MBB);
127 /// Find a valid insertion point in Head.
128 bool findInsertionPoint();
131 /// runOnMachineFunction - Initialize per-function data structures.
132 void runOnMachineFunction(MachineFunction &MF) {
133 TII = MF.getTarget().getInstrInfo();
134 TRI = MF.getTarget().getRegisterInfo();
135 MRI = &MF.getRegInfo();
136 LiveRegUnits.clear();
137 LiveRegUnits.setUniverse(TRI->getNumRegUnits());
138 ClobberedRegUnits.clear();
139 ClobberedRegUnits.resize(TRI->getNumRegUnits());
142 /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
143 /// initialize the internal state, and return true.
144 bool canConvertIf(MachineBasicBlock *MBB);
146 /// convertIf - If-convert the last block passed to canConvertIf(), assuming
147 /// it is possible. Remove any erased blocks from WorkList
148 void convertIf(BlockSetVector &WorkList);
150 } // end anonymous namespace
153 /// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
154 /// be speculated. The terminators are not considered.
156 /// If instructions use any values that are defined in the head basic block,
157 /// the defining instructions are added to InsertAfter.
159 /// Any clobbered regunits are added to ClobberedRegUnits.
161 bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
162 // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
164 if (!MBB->livein_empty()) {
165 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has live-ins.\n");
169 unsigned InstrCount = 0;
170 for (MachineBasicBlock::iterator I = MBB->begin(),
171 E = MBB->getFirstTerminator(); I != E; ++I) {
172 if (I->isDebugValue())
175 if (++InstrCount > BlockInstrLimit && !Stress) {
176 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has more than "
177 << BlockInstrLimit << " instructions.\n");
181 // There shouldn't normally be any phis in a single-predecessor block.
183 DEBUG(dbgs() << "Can't hoist: " << *I);
187 // Don't speculate loads. Note that it may be possible and desirable to
188 // speculate GOT or constant pool loads that are guaranteed not to trap,
189 // but we don't support that for now.
191 DEBUG(dbgs() << "Won't speculate load: " << *I);
195 // We never speculate stores, so an AA pointer isn't necessary.
196 bool DontMoveAcrossStore = true;
197 if (!I->isSafeToMove(TII, 0, DontMoveAcrossStore)) {
198 DEBUG(dbgs() << "Can't speculate: " << *I);
202 // Check for any dependencies on Head instructions.
203 for (MIOperands MO(I); MO.isValid(); ++MO) {
204 if (MO->isRegMask()) {
205 DEBUG(dbgs() << "Won't speculate regmask: " << *I);
210 unsigned Reg = MO->getReg();
212 // Remember clobbered regunits.
213 if (MO->isDef() && TargetRegisterInfo::isPhysicalRegister(Reg))
214 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
215 ClobberedRegUnits.set(*Units);
217 if (!MO->readsReg() || !TargetRegisterInfo::isVirtualRegister(Reg))
219 MachineInstr *DefMI = MRI->getVRegDef(Reg);
220 if (!DefMI || DefMI->getParent() != Head)
222 if (InsertAfter.insert(DefMI))
223 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " depends on " << *DefMI);
224 if (DefMI->isTerminator()) {
225 DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
234 /// Find an insertion point in Head for the speculated instructions. The
235 /// insertion point must be:
237 /// 1. Before any terminators.
238 /// 2. After any instructions in InsertAfter.
239 /// 3. Not have any clobbered regunits live.
241 /// This function sets InsertionPoint and returns true when successful, it
242 /// returns false if no valid insertion point could be found.
244 bool SSAIfConv::findInsertionPoint() {
245 // Keep track of live regunits before the current position.
246 // Only track RegUnits that are also in ClobberedRegUnits.
247 LiveRegUnits.clear();
248 SmallVector<unsigned, 8> Reads;
249 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
250 MachineBasicBlock::iterator I = Head->end();
251 MachineBasicBlock::iterator B = Head->begin();
254 // Some of the conditional code depends in I.
255 if (InsertAfter.count(I)) {
256 DEBUG(dbgs() << "Can't insert code after " << *I);
260 // Update live regunits.
261 for (MIOperands MO(I); MO.isValid(); ++MO) {
262 // We're ignoring regmask operands. That is conservatively correct.
265 unsigned Reg = MO->getReg();
266 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
268 // I clobbers Reg, so it isn't live before I.
270 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
271 LiveRegUnits.erase(*Units);
272 // Unless I reads Reg.
274 Reads.push_back(Reg);
276 // Anything read by I is live before I.
277 while (!Reads.empty())
278 for (MCRegUnitIterator Units(Reads.pop_back_val(), TRI); Units.isValid();
280 if (ClobberedRegUnits.test(*Units))
281 LiveRegUnits.insert(*Units);
283 // We can't insert before a terminator.
284 if (I != FirstTerm && I->isTerminator())
287 // Some of the clobbered registers are live before I, not a valid insertion
289 if (!LiveRegUnits.empty()) {
291 dbgs() << "Would clobber";
292 for (SparseSet<unsigned>::const_iterator
293 i = LiveRegUnits.begin(), e = LiveRegUnits.end(); i != e; ++i)
294 dbgs() << ' ' << PrintRegUnit(*i, TRI);
295 dbgs() << " live before " << *I;
300 // This is a valid insertion point.
302 DEBUG(dbgs() << "Can insert before " << *I);
305 DEBUG(dbgs() << "No legal insertion point found.\n");
311 /// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
312 /// a potential candidate for if-conversion. Fill out the internal state.
314 bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB) {
316 TBB = FBB = Tail = 0;
318 if (Head->succ_size() != 2)
320 MachineBasicBlock *Succ0 = Head->succ_begin()[0];
321 MachineBasicBlock *Succ1 = Head->succ_begin()[1];
323 // Canonicalize so Succ0 has MBB as its single predecessor.
324 if (Succ0->pred_size() != 1)
325 std::swap(Succ0, Succ1);
327 if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
330 // We could support additional Tail predecessors by updating phis instead of
331 // eliminating them. Let's see an example where it matters first.
332 Tail = Succ0->succ_begin()[0];
333 if (Tail->pred_size() != 2)
336 // This is not a triangle.
338 // Check for a diamond. We won't deal with any critical edges.
339 if (Succ1->pred_size() != 1 || Succ1->succ_size() != 1 ||
340 Succ1->succ_begin()[0] != Tail)
342 DEBUG(dbgs() << "\nDiamond: BB#" << Head->getNumber()
343 << " -> BB#" << Succ0->getNumber()
344 << "/BB#" << Succ1->getNumber()
345 << " -> BB#" << Tail->getNumber() << '\n');
347 // Live-in physregs are tricky to get right when speculating code.
348 if (!Tail->livein_empty()) {
349 DEBUG(dbgs() << "Tail has live-ins.\n");
353 DEBUG(dbgs() << "\nTriangle: BB#" << Head->getNumber()
354 << " -> BB#" << Succ0->getNumber()
355 << " -> BB#" << Tail->getNumber() << '\n');
358 // This is a triangle or a diamond.
359 // If Tail doesn't have any phis, there must be side effects.
360 if (Tail->empty() || !Tail->front().isPHI()) {
361 DEBUG(dbgs() << "No phis in tail.\n");
365 // The branch we're looking to eliminate must be analyzable.
367 if (TII->AnalyzeBranch(*Head, TBB, FBB, Cond)) {
368 DEBUG(dbgs() << "Branch not analyzable.\n");
372 // This is weird, probably some sort of degenerate CFG.
374 DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch.\n");
378 // AnalyzeBranch doesn't set FBB on a fall-through branch.
379 // Make sure it is always set.
380 FBB = TBB == Succ0 ? Succ1 : Succ0;
382 // Any phis in the tail block must be convertible to selects.
384 MachineBasicBlock *TPred = TBB == Tail ? Head : TBB;
385 MachineBasicBlock *FPred = FBB == Tail ? Head : FBB;
386 for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
387 I != E && I->isPHI(); ++I) {
389 PHIInfo &PI = PHIs.back();
390 // Find PHI operands corresponding to TPred and FPred.
391 for (unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
392 if (PI.PHI->getOperand(i+1).getMBB() == TPred)
393 PI.TReg = PI.PHI->getOperand(i).getReg();
394 if (PI.PHI->getOperand(i+1).getMBB() == FPred)
395 PI.FReg = PI.PHI->getOperand(i).getReg();
397 assert(TargetRegisterInfo::isVirtualRegister(PI.TReg) && "Bad PHI");
398 assert(TargetRegisterInfo::isVirtualRegister(PI.FReg) && "Bad PHI");
400 // Get target information.
401 if (!TII->canInsertSelect(*Head, Cond, PI.TReg, PI.FReg,
402 PI.CondCycles, PI.TCycles, PI.FCycles)) {
403 DEBUG(dbgs() << "Can't convert: " << *PI.PHI);
408 // Check that the conditional instructions can be speculated.
410 ClobberedRegUnits.reset();
411 if (TBB != Tail && !canSpeculateInstrs(TBB))
413 if (FBB != Tail && !canSpeculateInstrs(FBB))
416 // Try to find a valid insertion point for the speculated instructions in the
418 if (!findInsertionPoint())
425 static void eraseBlock(BlockSetVector &WorkList, MachineBasicBlock *MBB) {
426 WorkList.remove(MBB);
427 MBB->eraseFromParent();
431 /// convertIf - Execute the if conversion after canConvertIf has determined the
434 /// Any basic blocks erased will also be removed from WorkList.
436 void SSAIfConv::convertIf(BlockSetVector &WorkList) {
437 assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
439 // Move all instructions into Head, except for the terminators.
441 Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
443 Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
445 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
446 assert(FirstTerm != Head->end() && "No terminators");
447 DebugLoc HeadDL = FirstTerm->getDebugLoc();
449 // Convert all PHIs to select instructions inserted before FirstTerm.
450 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
451 PHIInfo &PI = PHIs[i];
452 DEBUG(dbgs() << "If-converting " << *PI.PHI);
453 assert(PI.PHI->getNumOperands() == 5 && "Unexpected PHI operands.");
454 unsigned DstReg = PI.PHI->getOperand(0).getReg();
455 TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
456 DEBUG(dbgs() << " --> " << *llvm::prior(FirstTerm));
457 PI.PHI->eraseFromParent();
461 // Fix up the CFG, temporarily leave Head without any successors.
462 Head->removeSuccessor(TBB);
463 Head->removeSuccessor(FBB);
465 TBB->removeSuccessor(Tail);
467 FBB->removeSuccessor(Tail);
469 // Fix up Head's terminators.
470 // It should become a single branch or a fallthrough.
471 TII->RemoveBranch(*Head);
473 // Erase the now empty conditional blocks. It is likely that Head can fall
474 // through to Tail, and we can join the two blocks.
476 eraseBlock(WorkList, TBB);
478 eraseBlock(WorkList, FBB);
480 assert(Head->succ_empty() && "Additional head successors?");
481 if (Head->isLayoutSuccessor(Tail)) {
482 // Splice Tail onto the end of Head.
483 DEBUG(dbgs() << "Joining tail BB#" << Tail->getNumber()
484 << " into head BB#" << Head->getNumber() << '\n');
485 Head->splice(Head->end(), Tail,
486 Tail->begin(), Tail->end());
487 Head->transferSuccessorsAndUpdatePHIs(Tail);
488 eraseBlock(WorkList, Tail);
491 // We need a branch to Tail, let code placement work it out later.
492 DEBUG(dbgs() << "Converting to unconditional branch.\n");
493 SmallVector<MachineOperand, 0> EmptyCond;
494 TII->InsertBranch(*Head, Tail, 0, EmptyCond, HeadDL);
495 Head->addSuccessor(Tail);
497 DEBUG(dbgs() << *Head);
501 //===----------------------------------------------------------------------===//
502 // EarlyIfConverter Pass
503 //===----------------------------------------------------------------------===//
506 class EarlyIfConverter : public MachineFunctionPass {
507 const TargetInstrInfo *TII;
508 const TargetRegisterInfo *TRI;
509 MachineRegisterInfo *MRI;
512 // Worklist of head blocks to try for if-conversion.
513 BlockSetVector WorkList;
517 EarlyIfConverter() : MachineFunctionPass(ID) {}
518 void getAnalysisUsage(AnalysisUsage &AU) const;
519 bool runOnMachineFunction(MachineFunction &MF);
522 bool tryConvertIf(MachineBasicBlock*);
524 } // end anonymous namespace
526 char EarlyIfConverter::ID = 0;
527 char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
529 INITIALIZE_PASS_BEGIN(EarlyIfConverter,
530 "early-ifcvt", "Early If Converter", false, false)
531 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
532 INITIALIZE_PASS_END(EarlyIfConverter,
533 "early-ifcvt", "Early If Converter", false, false)
535 void EarlyIfConverter::getAnalysisUsage(AnalysisUsage &AU) const {
536 AU.addRequired<MachineBranchProbabilityInfo>();
537 MachineFunctionPass::getAnalysisUsage(AU);
540 /// Attempt repeated if-conversion on MBB, return true if successful.
541 /// Update WorkList with new opportunities.
543 bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
544 if (!IfConv.canConvertIf(MBB))
547 // Repeatedly if-convert MBB, joining Head and Tail may expose more
549 do IfConv.convertIf(WorkList);
550 while (IfConv.canConvertIf(MBB));
552 // It is possible that MBB is now itself a conditional block that can be
554 if (MBB->pred_size() == 1 && MBB->succ_size() == 1)
555 WorkList.insert(MBB->pred_begin()[0]);
556 WorkList.remove(MBB);
561 bool EarlyIfConverter::runOnMachineFunction(MachineFunction &MF) {
562 DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
563 << "********** Function: "
564 << ((Value*)MF.getFunction())->getName() << '\n');
565 TII = MF.getTarget().getInstrInfo();
566 TRI = MF.getTarget().getRegisterInfo();
567 MRI = &MF.getRegInfo();
569 bool Changed = false;
570 IfConv.runOnMachineFunction(MF);
572 for (MachineFunction::iterator MFI = MF.begin(), MFE = MF.end(); MFI != MFE;
574 if (tryConvertIf(MFI))
577 DEBUG(dbgs() << "Revisiting " << WorkList.size() << " blocks.\n");
578 while (!WorkList.empty())
579 tryConvertIf(WorkList.pop_back_val());
581 MF.verify(this, "After early if-conversion");