1 //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass forwards branches to unconditional branches to make them branch
11 // directly to the target block. This pass often results in dead MBB's, which
14 // Note that this pass must be run after register allocation, it cannot handle
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "branchfolding"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/RegisterScavenging.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/MRegisterInfo.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
35 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
36 STATISTIC(NumBranchOpts, "Number of branches optimized");
37 STATISTIC(NumTailMerge , "Number of block tails merged");
38 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
39 cl::init(cl::BOU_UNSET), cl::Hidden);
41 struct BranchFolder : public MachineFunctionPass {
43 BranchFolder(bool defaultEnableTailMerge) :
44 MachineFunctionPass((intptr_t)&ID) {
45 switch (FlagEnableTailMerge) {
46 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
47 case cl::BOU_TRUE: EnableTailMerge = true; break;
48 case cl::BOU_FALSE: EnableTailMerge = false; break;
52 virtual bool runOnMachineFunction(MachineFunction &MF);
53 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
54 const TargetInstrInfo *TII;
55 MachineModuleInfo *MMI;
60 bool TailMergeBlocks(MachineFunction &MF);
61 bool TryMergeBlocks(MachineBasicBlock* SuccBB,
62 MachineBasicBlock* PredBB);
63 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
64 MachineBasicBlock *NewDest);
65 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
66 MachineBasicBlock::iterator BBI1);
68 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
69 const MRegisterInfo *RegInfo;
72 bool OptimizeBranches(MachineFunction &MF);
73 void OptimizeBlock(MachineBasicBlock *MBB);
74 void RemoveDeadBlock(MachineBasicBlock *MBB);
76 bool CanFallThrough(MachineBasicBlock *CurBB);
77 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
78 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
79 const std::vector<MachineOperand> &Cond);
81 char BranchFolder::ID = 0;
84 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
85 MachineBasicBlock *DestA,
86 MachineBasicBlock *DestB,
88 MachineFunction::iterator FallThru);
90 FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
91 return new BranchFolder(DefaultEnableTailMerge); }
93 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
94 /// function, updating the CFG.
95 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
96 assert(MBB->pred_empty() && "MBB must be dead!");
97 DOUT << "\nRemoving MBB: " << *MBB;
99 MachineFunction *MF = MBB->getParent();
100 // drop all successors.
101 while (!MBB->succ_empty())
102 MBB->removeSuccessor(MBB->succ_end()-1);
104 // If there is DWARF info to active, check to see if there are any LABEL
105 // records in the basic block. If so, unregister them from MachineModuleInfo.
106 if (MMI && !MBB->empty()) {
107 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
109 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
110 // The label ID # is always operand #0, an immediate.
111 MMI->InvalidateLabel(I->getOperand(0).getImm());
117 MF->getBasicBlockList().erase(MBB);
120 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
121 TII = MF.getTarget().getInstrInfo();
122 if (!TII) return false;
124 // Fix CFG. The later algorithms expect it to be right.
125 bool EverMadeChange = false;
126 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
127 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
128 std::vector<MachineOperand> Cond;
129 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond))
130 EverMadeChange |= CorrectExtraCFGEdges(*MBB, TBB, FBB,
131 !Cond.empty(), next(I));
134 RegInfo = MF.getTarget().getRegisterInfo();
135 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
137 MMI = getAnalysisToUpdate<MachineModuleInfo>();
139 bool MadeChangeThisIteration = true;
140 while (MadeChangeThisIteration) {
141 MadeChangeThisIteration = false;
142 MadeChangeThisIteration |= TailMergeBlocks(MF);
143 MadeChangeThisIteration |= OptimizeBranches(MF);
144 EverMadeChange |= MadeChangeThisIteration;
147 // See if any jump tables have become mergable or dead as the code generator
149 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
150 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
152 // Figure out how these jump tables should be merged.
153 std::vector<unsigned> JTMapping;
154 JTMapping.reserve(JTs.size());
156 // We always keep the 0th jump table.
157 JTMapping.push_back(0);
159 // Scan the jump tables, seeing if there are any duplicates. Note that this
160 // is N^2, which should be fixed someday.
161 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
162 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
164 // If a jump table was merge with another one, walk the function rewriting
165 // references to jump tables to reference the new JT ID's. Keep track of
166 // whether we see a jump table idx, if not, we can delete the JT.
167 std::vector<bool> JTIsLive;
168 JTIsLive.resize(JTs.size());
169 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
171 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
173 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
174 MachineOperand &Op = I->getOperand(op);
175 if (!Op.isJumpTableIndex()) continue;
176 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
177 Op.setJumpTableIndex(NewIdx);
179 // Remember that this JT is live.
180 JTIsLive[NewIdx] = true;
184 // Finally, remove dead jump tables. This happens either because the
185 // indirect jump was unreachable (and thus deleted) or because the jump
186 // table was merged with some other one.
187 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
189 JTI->RemoveJumpTable(i);
190 EverMadeChange = true;
195 return EverMadeChange;
198 //===----------------------------------------------------------------------===//
199 // Tail Merging of Blocks
200 //===----------------------------------------------------------------------===//
202 /// HashMachineInstr - Compute a hash value for MI and its operands.
203 static unsigned HashMachineInstr(const MachineInstr *MI) {
204 unsigned Hash = MI->getOpcode();
205 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
206 const MachineOperand &Op = MI->getOperand(i);
208 // Merge in bits from the operand if easy.
209 unsigned OperandHash = 0;
210 switch (Op.getType()) {
211 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
212 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
213 case MachineOperand::MO_MachineBasicBlock:
214 OperandHash = Op.getMachineBasicBlock()->getNumber();
216 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
217 case MachineOperand::MO_ConstantPoolIndex:
218 OperandHash = Op.getConstantPoolIndex();
220 case MachineOperand::MO_JumpTableIndex:
221 OperandHash = Op.getJumpTableIndex();
223 case MachineOperand::MO_GlobalAddress:
224 case MachineOperand::MO_ExternalSymbol:
225 // Global address / external symbol are too hard, don't bother, but do
226 // pull in the offset.
227 OperandHash = Op.getOffset();
232 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
237 /// HashEndOfMBB - Hash the last few instructions in the MBB. For blocks
238 /// with no successors, we hash two instructions, because cross-jumping
239 /// only saves code when at least two instructions are removed (since a
240 /// branch must be inserted). For blocks with a successor, one of the
241 /// two blocks to be tail-merged will end with a branch already, so
242 /// it gains to cross-jump even for one instruction.
244 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
245 unsigned minCommonTailLength) {
246 MachineBasicBlock::const_iterator I = MBB->end();
247 if (I == MBB->begin())
248 return 0; // Empty MBB.
251 unsigned Hash = HashMachineInstr(I);
253 if (I == MBB->begin() || minCommonTailLength == 1)
254 return Hash; // Single instr MBB.
257 // Hash in the second-to-last instruction.
258 Hash ^= HashMachineInstr(I) << 2;
262 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
263 /// of instructions they actually have in common together at their end. Return
264 /// iterators for the first shared instruction in each block.
265 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
266 MachineBasicBlock *MBB2,
267 MachineBasicBlock::iterator &I1,
268 MachineBasicBlock::iterator &I2) {
272 unsigned TailLen = 0;
273 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
275 if (!I1->isIdenticalTo(I2)) {
284 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
285 /// after it, replacing it with an unconditional branch to NewDest. This
286 /// returns true if OldInst's block is modified, false if NewDest is modified.
287 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
288 MachineBasicBlock *NewDest) {
289 MachineBasicBlock *OldBB = OldInst->getParent();
291 // Remove all the old successors of OldBB from the CFG.
292 while (!OldBB->succ_empty())
293 OldBB->removeSuccessor(OldBB->succ_begin());
295 // Remove all the dead instructions from the end of OldBB.
296 OldBB->erase(OldInst, OldBB->end());
298 // If OldBB isn't immediately before OldBB, insert a branch to it.
299 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
300 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
301 OldBB->addSuccessor(NewDest);
305 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
306 /// MBB so that the part before the iterator falls into the part starting at the
307 /// iterator. This returns the new MBB.
308 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
309 MachineBasicBlock::iterator BBI1) {
310 // Create the fall-through block.
311 MachineFunction::iterator MBBI = &CurMBB;
312 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
313 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
315 // Move all the successors of this block to the specified block.
316 while (!CurMBB.succ_empty()) {
317 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
318 NewMBB->addSuccessor(S);
319 CurMBB.removeSuccessor(S);
322 // Add an edge from CurMBB to NewMBB for the fall-through.
323 CurMBB.addSuccessor(NewMBB);
325 // Splice the code over.
326 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
328 // For targets that use the register scavenger, we must maintain LiveIns.
330 RS->enterBasicBlock(&CurMBB);
332 RS->forward(prior(CurMBB.end()));
333 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
334 RS->getRegsUsed(RegsLiveAtExit, false);
335 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
336 if (RegsLiveAtExit[i])
337 NewMBB->addLiveIn(i);
343 /// EstimateRuntime - Make a rough estimate for how long it will take to run
344 /// the specified code.
345 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
346 MachineBasicBlock::iterator E,
347 const TargetInstrInfo *TII) {
349 for (; I != E; ++I) {
350 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
351 if (TID.Flags & M_CALL_FLAG)
353 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
361 /// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
362 /// MBB2I and then insert an unconditional branch in the other block. Determine
363 /// which is the best to split
364 static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
365 MachineBasicBlock::iterator MBB1I,
366 MachineBasicBlock *MBB2,
367 MachineBasicBlock::iterator MBB2I,
368 const TargetInstrInfo *TII,
369 MachineBasicBlock *PredBB) {
370 // If one block is the entry block, split the other one; we can't generate
371 // a branch to the entry block, as its label is not emitted.
372 MachineBasicBlock *Entry = MBB1->getParent()->begin();
378 // If one block falls through into the common successor, choose that
379 // one to split; it is one instruction less to do that.
383 else if (MBB2 == PredBB)
386 // TODO: if we had some notion of which block was hotter, we could split
387 // the hot block, so it is the fall-through. Since we don't have profile info
388 // make a decision based on which will hurt most to split.
389 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
390 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
392 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
393 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
394 // have a lower overall impact on the program execution.
395 return MBB1Time < MBB2Time;
398 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
399 // branches temporarily for tail merging). In the case where CurMBB ends
400 // with a conditional branch to the next block, optimize by reversing the
401 // test and conditionally branching to SuccMBB instead.
403 static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
404 const TargetInstrInfo *TII) {
405 MachineFunction *MF = CurMBB->getParent();
406 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
407 MachineBasicBlock *TBB = 0, *FBB = 0;
408 std::vector<MachineOperand> Cond;
409 if (I != MF->end() &&
410 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
411 MachineBasicBlock *NextBB = I;
412 if (TBB == NextBB && Cond.size() && !FBB) {
413 if (!TII->ReverseBranchCondition(Cond)) {
414 TII->RemoveBranch(*CurMBB);
415 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
420 TII->InsertBranch(*CurMBB, SuccBB, NULL, std::vector<MachineOperand>());
423 static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
424 const std::pair<unsigned,MachineBasicBlock*> &q) {
425 if (p.first < q.first)
427 else if (p.first > q.first)
429 else if (p.second->getNumber() < q.second->getNumber())
431 else if (p.second->getNumber() > q.second->getNumber())
434 assert(0 && "Predecessor appears twice");
437 // See if any of the blocks in MergePotentials (which all have a common single
438 // successor, or all have no successor) can be tail-merged. If there is a
439 // successor, any blocks in MergePotentials that are not tail-merged and
440 // are not immediately before Succ must have an unconditional branch to
441 // Succ added (but the predecessor/successor lists need no adjustment).
442 // The lone predecessor of Succ that falls through into Succ,
443 // if any, is given in PredBB.
445 bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
446 MachineBasicBlock* PredBB) {
447 unsigned minCommonTailLength = (SuccBB ? 1 : 2);
450 // Sort by hash value so that blocks with identical end sequences sort
452 std::stable_sort(MergePotentials.begin(), MergePotentials.end(), MergeCompare);
454 // Walk through equivalence sets looking for actual exact matches.
455 while (MergePotentials.size() > 1) {
456 unsigned CurHash = (MergePotentials.end()-1)->first;
457 unsigned PrevHash = (MergePotentials.end()-2)->first;
458 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
460 // If there is nothing that matches the hash of the current basic block,
462 if (CurHash != PrevHash) {
463 if (SuccBB && CurMBB != PredBB)
464 FixTail(CurMBB, SuccBB, TII);
465 MergePotentials.pop_back();
469 // Look through all the pairs of blocks that have the same hash as this
470 // one, and find the pair that has the largest number of instructions in
472 // Since instructions may get combined later (e.g. single stores into
473 // store multiple) this measure is not particularly accurate.
474 MachineBasicBlock::iterator BBI1, BBI2;
476 unsigned FoundI = ~0U, FoundJ = ~0U;
477 unsigned maxCommonTailLength = 0U;
478 for (int i = MergePotentials.size()-1;
479 i != -1 && MergePotentials[i].first == CurHash; --i) {
481 j != -1 && MergePotentials[j].first == CurHash; --j) {
482 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
483 unsigned CommonTailLen = ComputeCommonTailLength(
484 MergePotentials[i].second,
485 MergePotentials[j].second,
486 TrialBBI1, TrialBBI2);
487 if (CommonTailLen >= minCommonTailLength &&
488 CommonTailLen > maxCommonTailLength) {
491 maxCommonTailLength = CommonTailLen;
498 // If we didn't find any pair that has at least minCommonTailLength
499 // instructions in common, bail out. All entries with this
500 // hash code can go away now.
502 for (int i = MergePotentials.size()-1;
503 i != -1 && MergePotentials[i].first == CurHash; --i) {
504 // Put the unconditional branch back, if we need one.
505 CurMBB = MergePotentials[i].second;
506 if (SuccBB && CurMBB != PredBB)
507 FixTail(CurMBB, SuccBB, TII);
508 MergePotentials.pop_back();
513 // Otherwise, move the block(s) to the right position(s). So that
514 // BBI1/2 will be valid, the last must be I and the next-to-last J.
515 if (FoundI != MergePotentials.size()-1)
516 std::swap(MergePotentials[FoundI], *(MergePotentials.end()-1));
517 if (FoundJ != MergePotentials.size()-2)
518 std::swap(MergePotentials[FoundJ], *(MergePotentials.end()-2));
520 CurMBB = (MergePotentials.end()-1)->second;
521 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
523 // If neither block is the entire common tail, split the tail of one block
524 // to make it redundant with the other tail. Also, we cannot jump to the
525 // entry block, so if one block is the entry block, split the other one.
526 MachineBasicBlock *Entry = CurMBB->getParent()->begin();
527 if (CurMBB->begin() == BBI1 && CurMBB != Entry)
528 ; // CurMBB is common tail
529 else if (MBB2->begin() == BBI2 && MBB2 != Entry)
530 ; // MBB2 is common tail
532 if (0) { // Enable this to disable partial tail merges.
533 MergePotentials.pop_back();
537 // Decide whether we want to split CurMBB or MBB2.
538 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII, PredBB)) {
539 CurMBB = SplitMBBAt(*CurMBB, BBI1);
540 BBI1 = CurMBB->begin();
541 MergePotentials.back().second = CurMBB;
543 MBB2 = SplitMBBAt(*MBB2, BBI2);
544 BBI2 = MBB2->begin();
545 (MergePotentials.end()-2)->second = MBB2;
549 if (MBB2->begin() == BBI2 && MBB2 != Entry) {
550 // Hack the end off CurMBB, making it jump to MBBI@ instead.
551 ReplaceTailWithBranchTo(BBI1, MBB2);
552 // This modifies CurMBB, so remove it from the worklist.
553 MergePotentials.pop_back();
555 assert(CurMBB->begin() == BBI1 && CurMBB != Entry &&
556 "Didn't split block correctly?");
557 // Hack the end off MBB2, making it jump to CurMBB instead.
558 ReplaceTailWithBranchTo(BBI2, CurMBB);
559 // This modifies MBB2, so remove it from the worklist.
560 MergePotentials.erase(MergePotentials.end()-2);
567 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
569 if (!EnableTailMerge) return false;
573 // First find blocks with no successors.
574 MergePotentials.clear();
575 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
577 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
579 // See if we can do any tail merging on those.
580 MadeChange |= TryMergeBlocks(NULL, NULL);
582 // Look at blocks (IBB) with multiple predecessors (PBB).
583 // We change each predecessor to a canonical form, by
584 // (1) temporarily removing any unconditional branch from the predecessor
586 // (2) alter conditional branches so they branch to the other block
587 // not IBB; this may require adding back an unconditional branch to IBB
588 // later, where there wasn't one coming in. E.g.
590 // fallthrough to QBB
593 // with a conceptual B to IBB after that, which never actually exists.
594 // With those changes, we see whether the predecessors' tails match,
595 // and merge them if so. We change things out of canonical form and
596 // back to the way they were later in the process. (OptimizeBranches
597 // would undo some of this, but we can't use it, because we'd get into
598 // a compile-time infinite loop repeatedly doing and undoing the same
601 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
602 if (!I->succ_empty() && I->pred_size() >= 2) {
603 MachineBasicBlock *IBB = I;
604 MachineBasicBlock *PredBB = prior(I);
605 MergePotentials.clear();
606 for (MachineBasicBlock::pred_iterator P = I->pred_begin(), E2 = I->pred_end();
608 MachineBasicBlock* PBB = *P;
609 // Skip blocks that loop to themselves, can't tail merge these.
612 MachineBasicBlock *TBB = 0, *FBB = 0;
613 std::vector<MachineOperand> Cond;
614 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
615 // Failing case: IBB is the target of a cbr, and
616 // we cannot reverse the branch.
617 std::vector<MachineOperand> NewCond(Cond);
618 if (Cond.size() && TBB==IBB) {
619 if (TII->ReverseBranchCondition(NewCond))
621 // This is the QBB case described above
623 FBB = next(MachineFunction::iterator(PBB));
625 // Failing case: the only way IBB can be reached from PBB is via
626 // exception handling. Happens for landing pads. Would be nice
627 // to have a bit in the edge so we didn't have to do all this.
628 if (IBB->isLandingPad()) {
629 MachineFunction::iterator IP = PBB; IP++;
630 MachineBasicBlock* PredNextBB = NULL;
634 if (IBB!=PredNextBB) // fallthrough
637 if (TBB!=IBB && FBB!=IBB) // cbr then ubr
639 } else if (Cond.size() == 0) {
643 if (TBB!=IBB && IBB!=PredNextBB) // cbr
647 // Remove the unconditional branch at the end, if any.
648 if (TBB && (Cond.size()==0 || FBB)) {
649 TII->RemoveBranch(*PBB);
651 // reinsert conditional branch only, for now
652 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
654 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
657 if (MergePotentials.size() >= 2)
658 MadeChange |= TryMergeBlocks(I, PredBB);
659 // Reinsert an unconditional branch if needed.
660 // The 1 below can be either an original single predecessor, or a result
661 // of removing blocks in TryMergeBlocks.
662 PredBB = prior(I); // this may have been changed in TryMergeBlocks
663 if (MergePotentials.size()==1 &&
664 (MergePotentials.begin())->second != PredBB)
665 FixTail((MergePotentials.begin())->second, I, TII);
671 //===----------------------------------------------------------------------===//
672 // Branch Optimization
673 //===----------------------------------------------------------------------===//
675 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
678 // Make sure blocks are numbered in order
681 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
682 MachineBasicBlock *MBB = I++;
685 // If it is dead, remove it.
686 if (MBB->pred_empty()) {
687 RemoveDeadBlock(MBB);
696 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
697 /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
698 /// DestB, remove any other MBB successors from the CFG. DestA and DestB can
700 /// Besides DestA and DestB, retain other edges leading to LandingPads (currently
701 /// there can be only one; we don't check or require that here).
702 /// Note it is possible that DestA and/or DestB are LandingPads.
703 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
704 MachineBasicBlock *DestA,
705 MachineBasicBlock *DestB,
707 MachineFunction::iterator FallThru) {
708 bool MadeChange = false;
709 bool AddedFallThrough = false;
711 // If this block ends with a conditional branch that falls through to its
712 // successor, set DestB as the successor.
714 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
716 AddedFallThrough = true;
719 // If this is an unconditional branch with no explicit dest, it must just be
720 // a fallthrough into DestB.
721 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
723 AddedFallThrough = true;
727 MachineBasicBlock::succ_iterator SI = MBB.succ_begin();
728 MachineBasicBlock *OrigDestA = DestA, *OrigDestB = DestB;
729 while (SI != MBB.succ_end()) {
730 if (*SI == DestA && DestA == DestB) {
733 } else if (*SI == DestA) {
736 } else if (*SI == DestB) {
739 } else if ((*SI)->isLandingPad() &&
740 *SI!=OrigDestA && *SI!=OrigDestB) {
743 // Otherwise, this is a superfluous edge, remove it.
744 MBB.removeSuccessor(SI);
748 if (!AddedFallThrough) {
749 assert(DestA == 0 && DestB == 0 &&
750 "MachineCFG is missing edges!");
752 assert(DestA == 0 && "MachineCFG is missing edges!");
758 /// CanFallThrough - Return true if the specified block (with the specified
759 /// branch condition) can implicitly transfer control to the block after it by
760 /// falling off the end of it. This should return false if it can reach the
761 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
763 /// True is a conservative answer.
765 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
766 bool BranchUnAnalyzable,
767 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
768 const std::vector<MachineOperand> &Cond) {
769 MachineFunction::iterator Fallthrough = CurBB;
771 // If FallthroughBlock is off the end of the function, it can't fall through.
772 if (Fallthrough == CurBB->getParent()->end())
775 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
776 if (!CurBB->isSuccessor(Fallthrough))
779 // If we couldn't analyze the branch, assume it could fall through.
780 if (BranchUnAnalyzable) return true;
782 // If there is no branch, control always falls through.
783 if (TBB == 0) return true;
785 // If there is some explicit branch to the fallthrough block, it can obviously
786 // reach, even though the branch should get folded to fall through implicitly.
787 if (MachineFunction::iterator(TBB) == Fallthrough ||
788 MachineFunction::iterator(FBB) == Fallthrough)
791 // If it's an unconditional branch to some block not the fall through, it
792 // doesn't fall through.
793 if (Cond.empty()) return false;
795 // Otherwise, if it is conditional and has no explicit false block, it falls
800 /// CanFallThrough - Return true if the specified can implicitly transfer
801 /// control to the block after it by falling off the end of it. This should
802 /// return false if it can reach the block after it, but it uses an explicit
803 /// branch to do so (e.g. a table jump).
805 /// True is a conservative answer.
807 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
808 MachineBasicBlock *TBB = 0, *FBB = 0;
809 std::vector<MachineOperand> Cond;
810 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
811 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
814 /// IsBetterFallthrough - Return true if it would be clearly better to
815 /// fall-through to MBB1 than to fall through into MBB2. This has to return
816 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
817 /// result in infinite loops.
818 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
819 MachineBasicBlock *MBB2,
820 const TargetInstrInfo &TII) {
821 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
822 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
823 // optimize branches that branch to either a return block or an assert block
824 // into a fallthrough to the return.
825 if (MBB1->empty() || MBB2->empty()) return false;
827 MachineInstr *MBB1I = --MBB1->end();
828 MachineInstr *MBB2I = --MBB2->end();
829 return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
832 /// OptimizeBlock - Analyze and optimize control flow related to the specified
833 /// block. This is never called on the entry block.
834 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
835 MachineFunction::iterator FallThrough = MBB;
838 // If this block is empty, make everyone use its fall-through, not the block
839 // explicitly. Landing pads should not do this since the landing-pad table
840 // points to this block.
841 if (MBB->empty() && !MBB->isLandingPad()) {
842 // Dead block? Leave for cleanup later.
843 if (MBB->pred_empty()) return;
845 if (FallThrough == MBB->getParent()->end()) {
846 // TODO: Simplify preds to not branch here if possible!
848 // Rewrite all predecessors of the old block to go to the fallthrough
850 while (!MBB->pred_empty()) {
851 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
852 Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
855 // If MBB was the target of a jump table, update jump tables to go to the
856 // fallthrough instead.
857 MBB->getParent()->getJumpTableInfo()->
858 ReplaceMBBInJumpTables(MBB, FallThrough);
864 // Check to see if we can simplify the terminator of the block before this
866 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
868 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
869 std::vector<MachineOperand> PriorCond;
870 bool PriorUnAnalyzable =
871 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
872 if (!PriorUnAnalyzable) {
873 // If the CFG for the prior block has extra edges, remove them.
874 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
875 !PriorCond.empty(), MBB);
877 // If the previous branch is conditional and both conditions go to the same
878 // destination, remove the branch, replacing it with an unconditional one or
880 if (PriorTBB && PriorTBB == PriorFBB) {
881 TII->RemoveBranch(PrevBB);
884 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
887 return OptimizeBlock(MBB);
890 // If the previous branch *only* branches to *this* block (conditional or
891 // not) remove the branch.
892 if (PriorTBB == MBB && PriorFBB == 0) {
893 TII->RemoveBranch(PrevBB);
896 return OptimizeBlock(MBB);
899 // If the prior block branches somewhere else on the condition and here if
900 // the condition is false, remove the uncond second branch.
901 if (PriorFBB == MBB) {
902 TII->RemoveBranch(PrevBB);
903 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
906 return OptimizeBlock(MBB);
909 // If the prior block branches here on true and somewhere else on false, and
910 // if the branch condition is reversible, reverse the branch to create a
912 if (PriorTBB == MBB) {
913 std::vector<MachineOperand> NewPriorCond(PriorCond);
914 if (!TII->ReverseBranchCondition(NewPriorCond)) {
915 TII->RemoveBranch(PrevBB);
916 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
919 return OptimizeBlock(MBB);
923 // If this block doesn't fall through (e.g. it ends with an uncond branch or
924 // has no successors) and if the pred falls through into this block, and if
925 // it would otherwise fall through into the block after this, move this
926 // block to the end of the function.
928 // We consider it more likely that execution will stay in the function (e.g.
929 // due to loops) than it is to exit it. This asserts in loops etc, moving
930 // the assert condition out of the loop body.
931 if (!PriorCond.empty() && PriorFBB == 0 &&
932 MachineFunction::iterator(PriorTBB) == FallThrough &&
933 !CanFallThrough(MBB)) {
934 bool DoTransform = true;
936 // We have to be careful that the succs of PredBB aren't both no-successor
937 // blocks. If neither have successors and if PredBB is the second from
938 // last block in the function, we'd just keep swapping the two blocks for
939 // last. Only do the swap if one is clearly better to fall through than
941 if (FallThrough == --MBB->getParent()->end() &&
942 !IsBetterFallthrough(PriorTBB, MBB, *TII))
945 // We don't want to do this transformation if we have control flow like:
954 // In this case, we could actually be moving the return block *into* a
956 if (DoTransform && !MBB->succ_empty() &&
957 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
962 // Reverse the branch so we will fall through on the previous true cond.
963 std::vector<MachineOperand> NewPriorCond(PriorCond);
964 if (!TII->ReverseBranchCondition(NewPriorCond)) {
965 DOUT << "\nMoving MBB: " << *MBB;
966 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
968 TII->RemoveBranch(PrevBB);
969 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
971 // Move this block to the end of the function.
972 MBB->moveAfter(--MBB->getParent()->end());
981 // Analyze the branch in the current block.
982 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
983 std::vector<MachineOperand> CurCond;
984 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
985 if (!CurUnAnalyzable) {
986 // If the CFG for the prior block has extra edges, remove them.
987 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
989 ++MachineFunction::iterator(MBB));
991 // If this is a two-way branch, and the FBB branches to this block, reverse
992 // the condition so the single-basic-block loop is faster. Instead of:
993 // Loop: xxx; jcc Out; jmp Loop
995 // Loop: xxx; jncc Loop; jmp Out
996 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
997 std::vector<MachineOperand> NewCond(CurCond);
998 if (!TII->ReverseBranchCondition(NewCond)) {
999 TII->RemoveBranch(*MBB);
1000 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
1003 return OptimizeBlock(MBB);
1008 // If this branch is the only thing in its block, see if we can forward
1009 // other blocks across it.
1010 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
1011 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
1012 // This block may contain just an unconditional branch. Because there can
1013 // be 'non-branch terminators' in the block, try removing the branch and
1014 // then seeing if the block is empty.
1015 TII->RemoveBranch(*MBB);
1017 // If this block is just an unconditional branch to CurTBB, we can
1018 // usually completely eliminate the block. The only case we cannot
1019 // completely eliminate the block is when the block before this one
1020 // falls through into MBB and we can't understand the prior block's branch
1023 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
1024 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1025 !PrevBB.isSuccessor(MBB)) {
1026 // If the prior block falls through into us, turn it into an
1027 // explicit branch to us to make updates simpler.
1028 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1029 PriorTBB != MBB && PriorFBB != MBB) {
1030 if (PriorTBB == 0) {
1031 assert(PriorCond.empty() && PriorFBB == 0 &&
1032 "Bad branch analysis");
1035 assert(PriorFBB == 0 && "Machine CFG out of date!");
1038 TII->RemoveBranch(PrevBB);
1039 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
1042 // Iterate through all the predecessors, revectoring each in-turn.
1043 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
1044 bool DidChange = false;
1045 bool HasBranchToSelf = false;
1046 while (PI != MBB->pred_end()) {
1048 // If this block has an uncond branch to itself, leave it.
1050 HasBranchToSelf = true;
1053 (*PI)->ReplaceUsesOfBlockWith(MBB, CurTBB);
1057 // Change any jumptables to go to the new MBB.
1058 MBB->getParent()->getJumpTableInfo()->
1059 ReplaceMBBInJumpTables(MBB, CurTBB);
1063 if (!HasBranchToSelf) return;
1068 // Add the branch back if the block is more than just an uncond branch.
1069 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
1073 // If the prior block doesn't fall through into this block, and if this
1074 // block doesn't fall through into some other block, see if we can find a
1075 // place to move this block where a fall-through will happen.
1076 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1077 PriorTBB, PriorFBB, PriorCond)) {
1078 // Now we know that there was no fall-through into this block, check to
1079 // see if it has a fall-through into its successor.
1080 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
1083 if (!MBB->isLandingPad()) {
1084 // Check all the predecessors of this block. If one of them has no fall
1085 // throughs, move this block right after it.
1086 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1087 E = MBB->pred_end(); PI != E; ++PI) {
1088 // Analyze the branch at the end of the pred.
1089 MachineBasicBlock *PredBB = *PI;
1090 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1091 if (PredBB != MBB && !CanFallThrough(PredBB)
1092 && (!CurFallsThru || !CurTBB || !CurFBB)
1093 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1094 // If the current block doesn't fall through, just move it.
1095 // If the current block can fall through and does not end with a
1096 // conditional branch, we need to append an unconditional jump to
1097 // the (current) next block. To avoid a possible compile-time
1098 // infinite loop, move blocks only backward in this case.
1099 // Also, if there are already 2 branches here, we cannot add a third;
1100 // this means we have the case
1105 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1107 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1109 MBB->moveAfter(PredBB);
1111 return OptimizeBlock(MBB);
1116 if (!CurFallsThru) {
1117 // Check all successors to see if we can move this block before it.
1118 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1119 E = MBB->succ_end(); SI != E; ++SI) {
1120 // Analyze the branch at the end of the block before the succ.
1121 MachineBasicBlock *SuccBB = *SI;
1122 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1123 std::vector<MachineOperand> SuccPrevCond;
1125 // If this block doesn't already fall-through to that successor, and if
1126 // the succ doesn't already have a block that can fall through into it,
1127 // and if the successor isn't an EH destination, we can arrange for the
1128 // fallthrough to happen.
1129 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1130 !SuccBB->isLandingPad()) {
1131 MBB->moveBefore(SuccBB);
1133 return OptimizeBlock(MBB);
1137 // Okay, there is no really great place to put this block. If, however,
1138 // the block before this one would be a fall-through if this block were
1139 // removed, move this block to the end of the function.
1140 if (FallThrough != MBB->getParent()->end() &&
1141 PrevBB.isSuccessor(FallThrough)) {
1142 MBB->moveAfter(--MBB->getParent()->end());