23
23
#include " llvm/Pass.h"
24
24
#include " llvm/Support/Compiler.h"
25
25
#include " llvm/Support/Debug.h"
26
+ #include " llvm/Support/ErrorHandling.h"
26
27
#include " llvm/Support/Format.h"
27
28
#include " llvm/Support/raw_ostream.h"
28
29
#include < cassert>
@@ -431,7 +432,8 @@ bool BranchRelaxation::fixupConditionalBranch(MachineInstr &MI) {
431
432
432
433
bool BranchRelaxation::fixupUnconditionalBranch (MachineInstr &MI) {
433
434
MachineBasicBlock *MBB = MI.getParent ();
434
-
435
+ MachineBasicBlock *TBB = nullptr , *FBB = nullptr ;
436
+ SmallVector<MachineOperand, 4 > Cond;
435
437
unsigned OldBrSize = TII->getInstSizeInBytes (MI);
436
438
MachineBasicBlock *DestBB = TII->getBranchDestBlock (MI);
437
439
@@ -444,6 +446,20 @@ bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &MI) {
444
446
445
447
MachineBasicBlock *BranchBB = MBB;
446
448
449
+ auto RemoveBranch = [&](MachineBasicBlock *MBB) {
450
+ unsigned &BBSize = BlockInfo[MBB->getNumber ()].Size ;
451
+ int RemovedSize = 0 ;
452
+ TII->removeBranch (*MBB, &RemovedSize);
453
+ BBSize -= RemovedSize;
454
+ };
455
+
456
+ auto InsertUncondBranch = [&](MachineBasicBlock *MBB,
457
+ MachineBasicBlock *Dst) {
458
+ TII->insertUnconditionalBranch (*MBB, Dst, DebugLoc ());
459
+ // Recalculate the block size.
460
+ BlockInfo[MBB->getNumber ()].Size = computeBlockSize (*MBB);
461
+ };
462
+
447
463
// If this was an expanded conditional branch, there is already a single
448
464
// unconditional branch in a block.
449
465
if (!MBB->empty ()) {
@@ -482,11 +498,15 @@ bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &MI) {
482
498
// restore blocks are just duplicated for each far branch.
483
499
assert (!DestBB->isEntryBlock ());
484
500
MachineBasicBlock *PrevBB = &*std::prev (DestBB->getIterator ());
485
- if (auto *FT = PrevBB->getFallThrough ()) {
486
- assert (FT == DestBB);
487
- TII->insertUnconditionalBranch (*PrevBB, FT, DebugLoc ());
488
- // Recalculate the block size.
489
- BlockInfo[PrevBB->getNumber ()].Size = computeBlockSize (*PrevBB);
501
+ // Fall through only if PrevBB has no unconditional branch as one of its
502
+ // terminators.
503
+ if (TII->analyzeBranch (*PrevBB, TBB, FBB, Cond))
504
+ report_fatal_error (" Could not analyze terminators." );
505
+ if (!FBB) {
506
+ if (!Cond.empty () && TBB && TBB == DestBB)
507
+ RemoveBranch (PrevBB);
508
+ if (!TBB || (TBB && !Cond.empty ()))
509
+ InsertUncondBranch (PrevBB, DestBB);
490
510
}
491
511
// Now, RestoreBB could be placed directly before DestBB.
492
512
MF->splice (DestBB->getIterator (), RestoreBB->getIterator ());
0 commit comments