1 //===- BranchRelaxation.cpp -----------------------------------------------===//
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 #include "llvm/ADT/SmallVector.h"
11 #include "llvm/ADT/Statistic.h"
12 #include "llvm/CodeGen/LivePhysRegs.h"
13 #include "llvm/CodeGen/MachineBasicBlock.h"
14 #include "llvm/CodeGen/MachineFunction.h"
15 #include "llvm/CodeGen/MachineFunctionPass.h"
16 #include "llvm/CodeGen/MachineInstr.h"
17 #include "llvm/CodeGen/RegisterScavenging.h"
18 #include "llvm/CodeGen/TargetInstrInfo.h"
19 #include "llvm/CodeGen/TargetRegisterInfo.h"
20 #include "llvm/CodeGen/TargetSubtargetInfo.h"
21 #include "llvm/IR/DebugLoc.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/Format.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <cassert>
29 #include <cstdint>
30 #include <iterator>
31 #include <memory>
32 
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "branch-relaxation"
36 
37 STATISTIC(NumSplit, "Number of basic blocks split");
38 STATISTIC(NumConditionalRelaxed, "Number of conditional branches relaxed");
39 STATISTIC(NumUnconditionalRelaxed, "Number of unconditional branches relaxed");
40 
41 #define BRANCH_RELAX_NAME "Branch relaxation pass"
42 
43 namespace {
44 
45 class BranchRelaxation : public MachineFunctionPass {
46   /// BasicBlockInfo - Information about the offset and size of a single
47   /// basic block.
48   struct BasicBlockInfo {
49     /// Offset - Distance from the beginning of the function to the beginning
50     /// of this basic block.
51     ///
52     /// The offset is always aligned as required by the basic block.
53     unsigned Offset = 0;
54 
55     /// Size - Size of the basic block in bytes.  If the block contains
56     /// inline assembly, this is a worst case estimate.
57     ///
58     /// The size does not include any alignment padding whether from the
59     /// beginning of the block, or from an aligned jump table at the end.
60     unsigned Size = 0;
61 
62     BasicBlockInfo() = default;
63 
64     /// Compute the offset immediately following this block. \p MBB is the next
65     /// block.
66     unsigned postOffset(const MachineBasicBlock &MBB) const {
67       unsigned PO = Offset + Size;
68       unsigned Align = MBB.getAlignment();
69       if (Align == 0)
70         return PO;
71 
72       unsigned AlignAmt = 1 << Align;
73       unsigned ParentAlign = MBB.getParent()->getAlignment();
74       if (Align <= ParentAlign)
75         return PO + OffsetToAlignment(PO, AlignAmt);
76 
77       // The alignment of this MBB is larger than the function's alignment, so we
78       // can't tell whether or not it will insert nops. Assume that it will.
79       return PO + AlignAmt + OffsetToAlignment(PO, AlignAmt);
80     }
81   };
82 
83   SmallVector<BasicBlockInfo, 16> BlockInfo;
84   std::unique_ptr<RegScavenger> RS;
85   LivePhysRegs LiveRegs;
86 
87   MachineFunction *MF;
88   const TargetRegisterInfo *TRI;
89   const TargetInstrInfo *TII;
90 
91   bool relaxBranchInstructions();
92   void scanFunction();
93 
94   MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &BB);
95 
96   MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI,
97                                            MachineBasicBlock *DestBB);
98   void adjustBlockOffsets(MachineBasicBlock &MBB);
99   bool isBlockInRange(const MachineInstr &MI, const MachineBasicBlock &BB) const;
100 
101   bool fixupConditionalBranch(MachineInstr &MI);
102   bool fixupUnconditionalBranch(MachineInstr &MI);
103   uint64_t computeBlockSize(const MachineBasicBlock &MBB) const;
104   unsigned getInstrOffset(const MachineInstr &MI) const;
105   void dumpBBs();
106   void verify();
107 
108 public:
109   static char ID;
110 
111   BranchRelaxation() : MachineFunctionPass(ID) {}
112 
113   bool runOnMachineFunction(MachineFunction &MF) override;
114 
115   StringRef getPassName() const override { return BRANCH_RELAX_NAME; }
116 };
117 
118 } // end anonymous namespace
119 
120 char BranchRelaxation::ID = 0;
121 
122 char &llvm::BranchRelaxationPassID = BranchRelaxation::ID;
123 
124 INITIALIZE_PASS(BranchRelaxation, DEBUG_TYPE, BRANCH_RELAX_NAME, false, false)
125 
126 /// verify - check BBOffsets, BBSizes, alignment of islands
127 void BranchRelaxation::verify() {
128 #ifndef NDEBUG
129   unsigned PrevNum = MF->begin()->getNumber();
130   for (MachineBasicBlock &MBB : *MF) {
131     unsigned Align = MBB.getAlignment();
132     unsigned Num = MBB.getNumber();
133     assert(BlockInfo[Num].Offset % (1u << Align) == 0);
134     assert(!Num || BlockInfo[PrevNum].postOffset(MBB) <= BlockInfo[Num].Offset);
135     assert(BlockInfo[Num].Size == computeBlockSize(MBB));
136     PrevNum = Num;
137   }
138 #endif
139 }
140 
141 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
142 /// print block size and offset information - debugging
143 LLVM_DUMP_METHOD void BranchRelaxation::dumpBBs() {
144   for (auto &MBB : *MF) {
145     const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];
146     dbgs() << format("%bb.%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)
147            << format("size=%#x\n", BBI.Size);
148   }
149 }
150 #endif
151 
152 /// scanFunction - Do the initial scan of the function, building up
153 /// information about each block.
154 void BranchRelaxation::scanFunction() {
155   BlockInfo.clear();
156   BlockInfo.resize(MF->getNumBlockIDs());
157 
158   // First thing, compute the size of all basic blocks, and see if the function
159   // has any inline assembly in it. If so, we have to be conservative about
160   // alignment assumptions, as we don't know for sure the size of any
161   // instructions in the inline assembly.
162   for (MachineBasicBlock &MBB : *MF)
163     BlockInfo[MBB.getNumber()].Size = computeBlockSize(MBB);
164 
165   // Compute block offsets and known bits.
166   adjustBlockOffsets(*MF->begin());
167 }
168 
169 /// computeBlockSize - Compute the size for MBB.
170 uint64_t BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) const {
171   uint64_t Size = 0;
172   for (const MachineInstr &MI : MBB)
173     Size += TII->getInstSizeInBytes(MI);
174   return Size;
175 }
176 
177 /// getInstrOffset - Return the current offset of the specified machine
178 /// instruction from the start of the function.  This offset changes as stuff is
179 /// moved around inside the function.
180 unsigned BranchRelaxation::getInstrOffset(const MachineInstr &MI) const {
181   const MachineBasicBlock *MBB = MI.getParent();
182 
183   // The offset is composed of two things: the sum of the sizes of all MBB's
184   // before this instruction's block, and the offset from the start of the block
185   // it is in.
186   unsigned Offset = BlockInfo[MBB->getNumber()].Offset;
187 
188   // Sum instructions before MI in MBB.
189   for (MachineBasicBlock::const_iterator I = MBB->begin(); &*I != &MI; ++I) {
190     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
191     Offset += TII->getInstSizeInBytes(*I);
192   }
193 
194   return Offset;
195 }
196 
197 void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
198   unsigned PrevNum = Start.getNumber();
199   for (auto &MBB : make_range(MachineFunction::iterator(Start), MF->end())) {
200     unsigned Num = MBB.getNumber();
201     if (!Num) // block zero is never changed from offset zero.
202       continue;
203     // Get the offset and known bits at the end of the layout predecessor.
204     // Include the alignment of the current block.
205     BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(MBB);
206 
207     PrevNum = Num;
208   }
209 }
210 
211 /// Insert a new empty basic block and insert it after \BB
212 MachineBasicBlock *BranchRelaxation::createNewBlockAfter(MachineBasicBlock &BB) {
213   // Create a new MBB for the code after the OrigBB.
214   MachineBasicBlock *NewBB =
215       MF->CreateMachineBasicBlock(BB.getBasicBlock());
216   MF->insert(++BB.getIterator(), NewBB);
217 
218   // Insert an entry into BlockInfo to align it properly with the block numbers.
219   BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
220 
221   return NewBB;
222 }
223 
224 /// Split the basic block containing MI into two blocks, which are joined by
225 /// an unconditional branch.  Update data structures and renumber blocks to
226 /// account for this change and returns the newly created block.
227 MachineBasicBlock *BranchRelaxation::splitBlockBeforeInstr(MachineInstr &MI,
228                                                            MachineBasicBlock *DestBB) {
229   MachineBasicBlock *OrigBB = MI.getParent();
230 
231   // Create a new MBB for the code after the OrigBB.
232   MachineBasicBlock *NewBB =
233       MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
234   MF->insert(++OrigBB->getIterator(), NewBB);
235 
236   // Splice the instructions starting with MI over to NewBB.
237   NewBB->splice(NewBB->end(), OrigBB, MI.getIterator(), OrigBB->end());
238 
239   // Add an unconditional branch from OrigBB to NewBB.
240   // Note the new unconditional branch is not being recorded.
241   // There doesn't seem to be meaningful DebugInfo available; this doesn't
242   // correspond to anything in the source.
243   TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());
244 
245   // Insert an entry into BlockInfo to align it properly with the block numbers.
246   BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
247 
248   NewBB->transferSuccessors(OrigBB);
249   OrigBB->addSuccessor(NewBB);
250   OrigBB->addSuccessor(DestBB);
251 
252   // Cleanup potential unconditional branch to successor block.
253   // Note that updateTerminator may change the size of the blocks.
254   NewBB->updateTerminator();
255   OrigBB->updateTerminator();
256 
257   // Figure out how large the OrigBB is.  As the first half of the original
258   // block, it cannot contain a tablejump.  The size includes
259   // the new jump we added.  (It should be possible to do this without
260   // recounting everything, but it's very confusing, and this is rarely
261   // executed.)
262   BlockInfo[OrigBB->getNumber()].Size = computeBlockSize(*OrigBB);
263 
264   // Figure out how large the NewMBB is. As the second half of the original
265   // block, it may contain a tablejump.
266   BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);
267 
268   // All BBOffsets following these blocks must be modified.
269   adjustBlockOffsets(*OrigBB);
270 
271   // Need to fix live-in lists if we track liveness.
272   if (TRI->trackLivenessAfterRegAlloc(*MF))
273     computeAndAddLiveIns(LiveRegs, *NewBB);
274 
275   ++NumSplit;
276 
277   return NewBB;
278 }
279 
280 /// isBlockInRange - Returns true if the distance between specific MI and
281 /// specific BB can fit in MI's displacement field.
282 bool BranchRelaxation::isBlockInRange(
283   const MachineInstr &MI, const MachineBasicBlock &DestBB) const {
284   int64_t BrOffset = getInstrOffset(MI);
285   int64_t DestOffset = BlockInfo[DestBB.getNumber()].Offset;
286 
287   if (TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - BrOffset))
288     return true;
289 
290   DEBUG(dbgs() << "Out of range branch to destination "
291                << printMBBReference(DestBB) << " from "
292                << printMBBReference(*MI.getParent()) << " to " << DestOffset
293                << " offset " << DestOffset - BrOffset << '\t' << MI);
294 
295   return false;
296 }
297 
298 /// fixupConditionalBranch - Fix up a conditional branch whose destination is
299 /// too far away to fit in its displacement field. It is converted to an inverse
300 /// conditional branch + an unconditional branch to the destination.
301 bool BranchRelaxation::fixupConditionalBranch(MachineInstr &MI) {
302   DebugLoc DL = MI.getDebugLoc();
303   MachineBasicBlock *MBB = MI.getParent();
304   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
305   MachineBasicBlock *NewBB = nullptr;
306   SmallVector<MachineOperand, 4> Cond;
307 
308   auto insertUncondBranch = [&](MachineBasicBlock *MBB,
309                                 MachineBasicBlock *DestBB) {
310     unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
311     int NewBrSize = 0;
312     TII->insertUnconditionalBranch(*MBB, DestBB, DL, &NewBrSize);
313     BBSize += NewBrSize;
314   };
315   auto insertBranch = [&](MachineBasicBlock *MBB, MachineBasicBlock *TBB,
316                           MachineBasicBlock *FBB,
317                           SmallVectorImpl<MachineOperand>& Cond) {
318     unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
319     int NewBrSize = 0;
320     TII->insertBranch(*MBB, TBB, FBB, Cond, DL, &NewBrSize);
321     BBSize += NewBrSize;
322   };
323   auto removeBranch = [&](MachineBasicBlock *MBB) {
324     unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
325     int RemovedSize = 0;
326     TII->removeBranch(*MBB, &RemovedSize);
327     BBSize -= RemovedSize;
328   };
329 
330   auto finalizeBlockChanges = [&](MachineBasicBlock *MBB,
331                                   MachineBasicBlock *NewBB) {
332     // Keep the block offsets up to date.
333     adjustBlockOffsets(*MBB);
334 
335     // Need to fix live-in lists if we track liveness.
336     if (NewBB && TRI->trackLivenessAfterRegAlloc(*MF))
337       computeAndAddLiveIns(LiveRegs, *NewBB);
338   };
339 
340   bool Fail = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
341   assert(!Fail && "branches to be relaxed must be analyzable");
342   (void)Fail;
343 
344   // Add an unconditional branch to the destination and invert the branch
345   // condition to jump over it:
346   // tbz L1
347   // =>
348   // tbnz L2
349   // b   L1
350   // L2:
351 
352   bool ReversedCond = !TII->reverseBranchCondition(Cond);
353   if (ReversedCond) {
354     if (FBB && isBlockInRange(MI, *FBB)) {
355       // Last MI in the BB is an unconditional branch. We can simply invert the
356       // condition and swap destinations:
357       // beq L1
358       // b   L2
359       // =>
360       // bne L2
361       // b   L1
362       DEBUG(dbgs() << "  Invert condition and swap "
363             "its destination with " << MBB->back());
364 
365       removeBranch(MBB);
366       insertBranch(MBB, FBB, TBB, Cond);
367       finalizeBlockChanges(MBB, nullptr);
368       return true;
369     }
370     if (FBB) {
371       // We need to split the basic block here to obtain two long-range
372       // unconditional branches.
373       NewBB = createNewBlockAfter(*MBB);
374 
375       insertUncondBranch(NewBB, FBB);
376       // Update the succesor lists according to the transformation to follow.
377       // Do it here since if there's no split, no update is needed.
378       MBB->replaceSuccessor(FBB, NewBB);
379       NewBB->addSuccessor(FBB);
380     }
381 
382     // We now have an appropriate fall-through block in place (either naturally or
383     // just created), so we can use the inverted the condition.
384     MachineBasicBlock &NextBB = *std::next(MachineFunction::iterator(MBB));
385 
386     DEBUG(dbgs() << "  Insert B to " << printMBBReference(*TBB)
387                  << ", invert condition and change dest. to "
388                  << printMBBReference(NextBB) << '\n');
389 
390     removeBranch(MBB);
391     // Insert a new conditional branch and a new unconditional branch.
392     insertBranch(MBB, &NextBB, TBB, Cond);
393 
394     finalizeBlockChanges(MBB, NewBB);
395     return true;
396   }
397   // Branch cond can't be inverted.
398   // In this case we always add a block after the MBB.
399   DEBUG(dbgs() << "  The branch condition can't be inverted. "
400                << "  Insert a new BB after " << MBB->back());
401 
402   if (!FBB)
403     FBB = &(*std::next(MachineFunction::iterator(MBB)));
404 
405   // This is the block with cond. branch and the distance to TBB is too long.
406   //    beq L1
407   // L2:
408 
409   // We do the following transformation:
410   //    beq NewBB
411   //    b L2
412   // NewBB:
413   //    b L1
414   // L2:
415 
416   NewBB = createNewBlockAfter(*MBB);
417   insertUncondBranch(NewBB, TBB);
418 
419   DEBUG(dbgs() << "  Insert cond B to the new BB " << printMBBReference(*NewBB)
420                << "  Keep the exiting condition.\n"
421                << "  Insert B to " << printMBBReference(*FBB) << ".\n"
422                << "  In the new BB: Insert B to "
423                << printMBBReference(*TBB) << ".\n");
424 
425   // Update the successor lists according to the transformation to follow.
426   MBB->replaceSuccessor(TBB, NewBB);
427   NewBB->addSuccessor(TBB);
428 
429   // Replace branch in the current (MBB) block.
430   removeBranch(MBB);
431   insertBranch(MBB, NewBB, FBB, Cond);
432 
433   finalizeBlockChanges(MBB, NewBB);
434   return true;
435 }
436 
437 bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &MI) {
438   MachineBasicBlock *MBB = MI.getParent();
439 
440   unsigned OldBrSize = TII->getInstSizeInBytes(MI);
441   MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
442 
443   int64_t DestOffset = BlockInfo[DestBB->getNumber()].Offset;
444   int64_t SrcOffset = getInstrOffset(MI);
445 
446   assert(!TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - SrcOffset));
447 
448   BlockInfo[MBB->getNumber()].Size -= OldBrSize;
449 
450   MachineBasicBlock *BranchBB = MBB;
451 
452   // If this was an expanded conditional branch, there is already a single
453   // unconditional branch in a block.
454   if (!MBB->empty()) {
455     BranchBB = createNewBlockAfter(*MBB);
456 
457     // Add live outs.
458     for (const MachineBasicBlock *Succ : MBB->successors()) {
459       for (const MachineBasicBlock::RegisterMaskPair &LiveIn : Succ->liveins())
460         BranchBB->addLiveIn(LiveIn);
461     }
462 
463     BranchBB->sortUniqueLiveIns();
464     BranchBB->addSuccessor(DestBB);
465     MBB->replaceSuccessor(DestBB, BranchBB);
466   }
467 
468   DebugLoc DL = MI.getDebugLoc();
469   MI.eraseFromParent();
470   BlockInfo[BranchBB->getNumber()].Size += TII->insertIndirectBranch(
471     *BranchBB, *DestBB, DL, DestOffset - SrcOffset, RS.get());
472 
473   adjustBlockOffsets(*MBB);
474   return true;
475 }
476 
477 bool BranchRelaxation::relaxBranchInstructions() {
478   bool Changed = false;
479 
480   // Relaxing branches involves creating new basic blocks, so re-eval
481   // end() for termination.
482   for (MachineFunction::iterator I = MF->begin(); I != MF->end(); ++I) {
483     MachineBasicBlock &MBB = *I;
484 
485     // Empty block?
486     MachineBasicBlock::iterator Last = MBB.getLastNonDebugInstr();
487     if (Last == MBB.end())
488       continue;
489 
490     // Expand the unconditional branch first if necessary. If there is a
491     // conditional branch, this will end up changing the branch destination of
492     // it to be over the newly inserted indirect branch block, which may avoid
493     // the need to try expanding the conditional branch first, saving an extra
494     // jump.
495     if (Last->isUnconditionalBranch()) {
496       // Unconditional branch destination might be unanalyzable, assume these
497       // are OK.
498       if (MachineBasicBlock *DestBB = TII->getBranchDestBlock(*Last)) {
499         if (!isBlockInRange(*Last, *DestBB)) {
500           fixupUnconditionalBranch(*Last);
501           ++NumUnconditionalRelaxed;
502           Changed = true;
503         }
504       }
505     }
506 
507     // Loop over the conditional branches.
508     MachineBasicBlock::iterator Next;
509     for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();
510          J != MBB.end(); J = Next) {
511       Next = std::next(J);
512       MachineInstr &MI = *J;
513 
514       if (MI.isConditionalBranch()) {
515         MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
516         if (!isBlockInRange(MI, *DestBB)) {
517           if (Next != MBB.end() && Next->isConditionalBranch()) {
518             // If there are multiple conditional branches, this isn't an
519             // analyzable block. Split later terminators into a new block so
520             // each one will be analyzable.
521 
522             splitBlockBeforeInstr(*Next, DestBB);
523           } else {
524             fixupConditionalBranch(MI);
525             ++NumConditionalRelaxed;
526           }
527 
528           Changed = true;
529 
530           // This may have modified all of the terminators, so start over.
531           Next = MBB.getFirstTerminator();
532         }
533       }
534     }
535   }
536 
537   return Changed;
538 }
539 
540 bool BranchRelaxation::runOnMachineFunction(MachineFunction &mf) {
541   MF = &mf;
542 
543   DEBUG(dbgs() << "***** BranchRelaxation *****\n");
544 
545   const TargetSubtargetInfo &ST = MF->getSubtarget();
546   TII = ST.getInstrInfo();
547 
548   TRI = ST.getRegisterInfo();
549   if (TRI->trackLivenessAfterRegAlloc(*MF))
550     RS.reset(new RegScavenger());
551 
552   // Renumber all of the machine basic blocks in the function, guaranteeing that
553   // the numbers agree with the position of the block in the function.
554   MF->RenumberBlocks();
555 
556   // Do the initial scan of the function, building up information about the
557   // sizes of each block.
558   scanFunction();
559 
560   DEBUG(dbgs() << "  Basic blocks before relaxation\n"; dumpBBs(););
561 
562   bool MadeChange = false;
563   while (relaxBranchInstructions())
564     MadeChange = true;
565 
566   // After a while, this might be made debug-only, but it is not expensive.
567   verify();
568 
569   DEBUG(dbgs() << "  Basic blocks after relaxation\n\n"; dumpBBs());
570 
571   BlockInfo.clear();
572 
573   return MadeChange;
574 }
575