LLVM 24.0.0git
BranchRelaxation.cpp
Go to the documentation of this file.
1//===- BranchRelaxation.cpp -----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
11#include "llvm/ADT/Statistic.h"
23#include "llvm/Config/llvm-config.h"
24#include "llvm/IR/DebugLoc.h"
26#include "llvm/Pass.h"
28#include "llvm/Support/Debug.h"
30#include "llvm/Support/Format.h"
33#include <cassert>
34#include <cstdint>
35#include <iterator>
36#include <memory>
37
38using namespace llvm;
39
40#define DEBUG_TYPE "branch-relaxation"
41
42STATISTIC(NumSplit, "Number of basic blocks split");
43STATISTIC(NumConditionalRelaxed, "Number of conditional branches relaxed");
44STATISTIC(NumUnconditionalRelaxed, "Number of unconditional branches relaxed");
45
46#define BRANCH_RELAX_NAME "Branch relaxation pass"
47
48namespace {
49
50class BranchRelaxation {
51 /// BasicBlockInfo - Information about the offset and size of a single
52 /// basic block.
53 struct BasicBlockInfo {
54 /// Offset - Distance from the beginning of the function to the beginning
55 /// of this basic block.
56 ///
57 /// The offset is always aligned as required by the basic block.
58 unsigned Offset = 0;
59
60 /// Size - Size of the basic block in bytes. If the block contains
61 /// inline assembly, this is a worst case estimate.
62 ///
63 /// The size does not include any alignment padding whether from the
64 /// beginning of the block, or from an aligned jump table at the end.
65 unsigned Size = 0;
66
67 BasicBlockInfo() = default;
68
69 /// Compute the offset immediately following this block. \p MBB is the next
70 /// block.
71 unsigned postOffset(const MachineBasicBlock &MBB) const {
72 const unsigned PO = Offset + Size;
73 const Align Alignment = MBB.getAlignment();
74 const Align ParentAlign = MBB.getParent()->getAlignment();
75 if (Alignment <= ParentAlign)
76 return alignTo(PO, Alignment);
77
78 // The alignment of this MBB is larger than the function's alignment, so
79 // we can't tell whether or not it will insert nops. Assume that it will.
80 return alignTo(PO, Alignment) + Alignment.value() - ParentAlign.value();
81 }
82 };
83
85
86 // The basic block after which trampolines are inserted. This is the last
87 // basic block that isn't in the cold section.
88 MachineBasicBlock *TrampolineInsertionPoint = nullptr;
90 RelaxedUnconditionals;
91 std::unique_ptr<RegScavenger> RS;
93
94 MachineFunction *MF = nullptr;
95 const TargetRegisterInfo *TRI = nullptr;
96 const TargetInstrInfo *TII = nullptr;
97 const TargetMachine *TM = nullptr;
98
99 bool relaxBranchInstructions();
100 void scanFunction();
101
102 MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &OrigMBB);
103 MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &OrigMBB,
104 const BasicBlock *BB);
105
106 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI,
107 MachineBasicBlock *DestBB);
108 void adjustBlockOffsets(MachineBasicBlock &Start);
109 // Computes basic block offsets for blocks in the range (Start, End),
110 // i.e. beginning with the block immediately following Start.
111 void adjustBlockOffsets(MachineBasicBlock &Start,
113 bool isBlockInRange(const MachineInstr &MI,
114 const MachineBasicBlock &BB) const;
115
116 bool fixupConditionalBranch(MachineInstr &MI);
117 bool fixupUnconditionalBranch(MachineInstr &MI);
118 uint64_t computeBlockSize(const MachineBasicBlock &MBB) const;
119 unsigned getInstrOffset(const MachineInstr &MI) const;
120 void dumpBBs();
121 void verify();
122
123public:
124 bool run(MachineFunction &MF);
125};
126
127class BranchRelaxationLegacy : public MachineFunctionPass {
128public:
129 static char ID;
130
131 BranchRelaxationLegacy() : MachineFunctionPass(ID) {}
132
133 bool runOnMachineFunction(MachineFunction &MF) override {
134 return BranchRelaxation().run(MF);
135 }
136
137 StringRef getPassName() const override { return BRANCH_RELAX_NAME; }
138};
139
140} // end anonymous namespace
141
142char BranchRelaxationLegacy::ID = 0;
143
144char &llvm::BranchRelaxationPassID = BranchRelaxationLegacy::ID;
145
146INITIALIZE_PASS(BranchRelaxationLegacy, DEBUG_TYPE, BRANCH_RELAX_NAME, false,
147 false)
148
149/// verify - check BBOffsets, BBSizes, alignment of islands
150void BranchRelaxation::verify() {
151#ifndef NDEBUG
152 unsigned PrevNum = MF->begin()->getNumber();
153 for (MachineBasicBlock &MBB : *MF) {
154 const unsigned Num = MBB.getNumber();
155 assert(!Num || BlockInfo[PrevNum].postOffset(MBB) <= BlockInfo[Num].Offset);
156 assert(BlockInfo[Num].Size == computeBlockSize(MBB));
157 PrevNum = Num;
158 }
159
160 for (MachineBasicBlock &MBB : *MF) {
161 for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();
162 J != MBB.end(); J = std::next(J)) {
163 MachineInstr &MI = *J;
164 if (!MI.isConditionalBranch() && !MI.isUnconditionalBranch())
165 continue;
166 if (MI.getOpcode() == TargetOpcode::FAULTING_OP)
167 continue;
168 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
169 assert(isBlockInRange(MI, *DestBB) ||
170 RelaxedUnconditionals.contains({&MBB, DestBB}));
171 }
172 }
173#endif
174}
175
176#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
177/// print block size and offset information - debugging
178LLVM_DUMP_METHOD void BranchRelaxation::dumpBBs() {
179 for (auto &MBB : *MF) {
180 const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];
181 dbgs() << format("%%bb.%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)
182 << format("size=%#x\n", BBI.Size);
183 }
184}
185#endif
186
187/// scanFunction - Do the initial scan of the function, building up
188/// information about each block.
189void BranchRelaxation::scanFunction() {
190 BlockInfo.clear();
191 BlockInfo.resize(MF->getNumBlockIDs());
192
193 TrampolineInsertionPoint = nullptr;
194 RelaxedUnconditionals.clear();
195
196 // First thing, compute the size of all basic blocks, and see if the function
197 // has any inline assembly in it. If so, we have to be conservative about
198 // alignment assumptions, as we don't know for sure the size of any
199 // instructions in the inline assembly. At the same time, place the
200 // trampoline insertion point at the end of the hot portion of the function.
201 for (MachineBasicBlock &MBB : *MF) {
202 BlockInfo[MBB.getNumber()].Size = computeBlockSize(MBB);
203
205 TrampolineInsertionPoint = &MBB;
206 }
207
208 // Compute block offsets and known bits.
209 adjustBlockOffsets(*MF->begin());
210
211 if (TrampolineInsertionPoint == nullptr) {
212 LLVM_DEBUG(dbgs() << " No suitable trampoline insertion point found in "
213 << MF->getName() << ".\n");
214 }
215}
216
217/// computeBlockSize - Compute the size for MBB.
218uint64_t
219BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) const {
220 uint64_t Size = 0;
221 for (const MachineInstr &MI : MBB)
222 Size += TII->getInstSizeInBytes(MI);
223 return Size;
224}
225
226/// getInstrOffset - Return the current offset of the specified machine
227/// instruction from the start of the function. This offset changes as stuff is
228/// moved around inside the function.
229unsigned BranchRelaxation::getInstrOffset(const MachineInstr &MI) const {
230 const MachineBasicBlock *MBB = MI.getParent();
231
232 // The offset is composed of two things: the sum of the sizes of all MBB's
233 // before this instruction's block, and the offset from the start of the block
234 // it is in.
235 unsigned Offset = BlockInfo[MBB->getNumber()].Offset;
236
237 // Sum instructions before MI in MBB.
238 for (MachineBasicBlock::const_iterator I = MBB->begin(); &*I != &MI; ++I) {
239 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
240 Offset += TII->getInstSizeInBytes(*I);
241 }
242
243 return Offset;
244}
245
246void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
247 adjustBlockOffsets(Start, MF->end());
248}
249
250void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start,
252 unsigned PrevNum = Start.getNumber();
253 for (auto &MBB :
254 make_range(std::next(MachineFunction::iterator(Start)), End)) {
255 unsigned Num = MBB.getNumber();
256 // Get the offset and known bits at the end of the layout predecessor.
257 // Include the alignment of the current block.
258 BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(MBB);
259
260 PrevNum = Num;
261 }
262}
263
264/// Insert a new empty MachineBasicBlock and insert it after \p OrigMBB
265MachineBasicBlock *
266BranchRelaxation::createNewBlockAfter(MachineBasicBlock &OrigBB) {
267 return createNewBlockAfter(OrigBB, OrigBB.getBasicBlock());
268}
269
270/// Insert a new empty MachineBasicBlock with \p BB as its BasicBlock
271/// and insert it after \p OrigMBB
272MachineBasicBlock *
273BranchRelaxation::createNewBlockAfter(MachineBasicBlock &OrigMBB,
274 const BasicBlock *BB) {
275 // Create a new MBB for the code after the OrigBB.
276 MachineBasicBlock *NewBB = MF->CreateMachineBasicBlock(BB);
277 MF->insert(++OrigMBB.getIterator(), NewBB);
278
279 // Place the new block in the same section as OrigBB
280 NewBB->setSectionID(OrigMBB.getSectionID());
281 NewBB->setIsEndSection(OrigMBB.isEndSection());
282 OrigMBB.setIsEndSection(false);
283
284 // Insert an entry into BlockInfo to align it properly with the block numbers.
285 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
286
287 // Keep the block offsets approximately up to date. While they will be
288 // slight underestimates, we will update them appropriately in the next
289 // scan through the function.
290 adjustBlockOffsets(OrigMBB, std::next(NewBB->getIterator()));
291
292 return NewBB;
293}
294
295/// Split the basic block containing MI into two blocks, which are joined by
296/// an unconditional branch. Update data structures and renumber blocks to
297/// account for this change and returns the newly created block.
298MachineBasicBlock *
299BranchRelaxation::splitBlockBeforeInstr(MachineInstr &MI,
300 MachineBasicBlock *DestBB) {
301 MachineBasicBlock *OrigBB = MI.getParent();
302
303 // Create a new MBB for the code after the OrigBB.
304 MachineBasicBlock *NewBB =
305 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
306 MF->insert(++OrigBB->getIterator(), NewBB);
307
308 // Place the new block in the same section as OrigBB.
309 NewBB->setSectionID(OrigBB->getSectionID());
310 NewBB->setIsEndSection(OrigBB->isEndSection());
311 OrigBB->setIsEndSection(false);
312
313 // Splice the instructions starting with MI over to NewBB.
314 NewBB->splice(NewBB->end(), OrigBB, MI.getIterator(), OrigBB->end());
315
316 // Add an unconditional branch from OrigBB to NewBB.
317 // Note the new unconditional branch is not being recorded.
318 // There doesn't seem to be meaningful DebugInfo available; this doesn't
319 // correspond to anything in the source.
320 TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());
321
322 // Insert an entry into BlockInfo to align it properly with the block numbers.
323 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
324
325 NewBB->transferSuccessors(OrigBB);
326 OrigBB->addSuccessor(NewBB);
327 OrigBB->addSuccessor(DestBB);
328
329 // Cleanup potential unconditional branch to successor block.
330 // Note that updateTerminator may change the size of the blocks.
331 OrigBB->updateTerminator(NewBB);
332
333 // Figure out how large the OrigBB is. As the first half of the original
334 // block, it cannot contain a tablejump. The size includes
335 // the new jump we added. (It should be possible to do this without
336 // recounting everything, but it's very confusing, and this is rarely
337 // executed.)
338 BlockInfo[OrigBB->getNumber()].Size = computeBlockSize(*OrigBB);
339
340 // Figure out how large the NewMBB is. As the second half of the original
341 // block, it may contain a tablejump.
342 BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);
343
344 // Update the offset of the new block.
345 adjustBlockOffsets(*OrigBB, std::next(NewBB->getIterator()));
346
347 // Need to fix live-in lists if we track liveness.
348 if (TRI->trackLivenessAfterRegAlloc(*MF))
349 computeAndAddLiveIns(LiveRegs, *NewBB);
350
351 ++NumSplit;
352
353 return NewBB;
354}
355
356/// isBlockInRange - Returns true if the distance between specific MI and
357/// specific BB can fit in MI's displacement field.
358bool BranchRelaxation::isBlockInRange(const MachineInstr &MI,
359 const MachineBasicBlock &DestBB) const {
360 int64_t BrOffset = getInstrOffset(MI);
361 int64_t DestOffset = BlockInfo[DestBB.getNumber()].Offset;
362
363 const MachineBasicBlock *SrcBB = MI.getParent();
364
365 if (TII->isBranchOffsetInRange(MI.getOpcode(),
366 SrcBB->getSectionID() != DestBB.getSectionID()
367 ? TM->getMaxCodeSize()
368 : DestOffset - BrOffset))
369 return true;
370
371 LLVM_DEBUG(dbgs() << "Out of range branch to destination "
372 << printMBBReference(DestBB) << " from "
373 << printMBBReference(*MI.getParent()) << " to "
374 << DestOffset << " offset " << DestOffset - BrOffset << '\t'
375 << MI);
376
377 return false;
378}
379
380/// fixupConditionalBranch - Fix up a conditional branch whose destination is
381/// too far away to fit in its displacement field. It is converted to an inverse
382/// conditional branch + an unconditional branch to the destination.
383bool BranchRelaxation::fixupConditionalBranch(MachineInstr &MI) {
384 DebugLoc DL = MI.getDebugLoc();
385 MachineBasicBlock *MBB = MI.getParent();
386 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
387 MachineBasicBlock *NewBB = nullptr;
389
390 auto insertUncondBranch = [&](MachineBasicBlock *MBB,
391 MachineBasicBlock *DestBB) {
392 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
393 int NewBrSize = 0;
394 TII->insertUnconditionalBranch(*MBB, DestBB, DL, &NewBrSize);
395 BBSize += NewBrSize;
396 };
397 auto insertBranch = [&](MachineBasicBlock *MBB, MachineBasicBlock *TBB,
398 MachineBasicBlock *FBB,
399 SmallVectorImpl<MachineOperand> &Cond) {
400 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
401 int NewBrSize = 0;
402 TII->insertBranch(*MBB, TBB, FBB, Cond, DL, &NewBrSize);
403 BBSize += NewBrSize;
404 };
405 auto removeBranch = [&](MachineBasicBlock *MBB) {
406 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
407 int RemovedSize = 0;
408 TII->removeBranch(*MBB, &RemovedSize);
409 BBSize -= RemovedSize;
410 };
411
412 // Populate the block offset and live-ins for a new basic block.
413 auto updateLiveness = [&](MachineBasicBlock *NewBB) {
414 assert(NewBB != nullptr && "can't update liveness for nullptr");
415
416 // Need to fix live-in lists if we track liveness.
417 if (TRI->trackLivenessAfterRegAlloc(*MF))
418 computeAndAddLiveIns(LiveRegs, *NewBB);
419 };
420
421 bool Fail = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
422 assert(!Fail && "branches to be relaxed must be analyzable");
423 (void)Fail;
424
425 // Since cross-section conditional branches to the cold section are rarely
426 // taken, try to avoid inverting the condition. Instead, add a "trampoline
427 // branch", which unconditionally branches to the branch destination. Place
428 // the trampoline branch at the end of the function and retarget the
429 // conditional branch to the trampoline.
430 // tbz L1
431 // =>
432 // tbz L1Trampoline
433 // ...
434 // L1Trampoline: b L1
435 if (MBB->getSectionID() != TBB->getSectionID() &&
437 TrampolineInsertionPoint != nullptr) {
438 // If the insertion point is out of range, we can't put a trampoline there.
439 NewBB =
440 createNewBlockAfter(*TrampolineInsertionPoint, MBB->getBasicBlock());
441
442 if (isBlockInRange(MI, *NewBB)) {
443 LLVM_DEBUG(dbgs() << " Retarget destination to trampoline at "
444 << NewBB->back());
445
446 insertUncondBranch(NewBB, TBB);
447
448 // Update the successor lists to include the trampoline.
449 MBB->replaceSuccessor(TBB, NewBB);
450 NewBB->addSuccessor(TBB);
451
452 // Replace branch in the current (MBB) block.
453 removeBranch(MBB);
454 insertBranch(MBB, NewBB, FBB, Cond);
455
456 TrampolineInsertionPoint = NewBB;
457 updateLiveness(NewBB);
458 return true;
459 }
460
462 dbgs() << " Trampoline insertion point out of range for Bcc from "
463 << printMBBReference(*MBB) << " to " << printMBBReference(*TBB)
464 << ".\n");
465 TrampolineInsertionPoint->setIsEndSection(NewBB->isEndSection());
466 MF->erase(NewBB);
467 NewBB = nullptr;
468 }
469
470 // Add an unconditional branch to the destination and invert the branch
471 // condition to jump over it:
472 // tbz L1
473 // =>
474 // tbnz L2
475 // b L1
476 // L2:
477
478 bool ReversedCond = !TII->reverseBranchCondition(Cond);
479 if (ReversedCond) {
480 if (FBB && isBlockInRange(MI, *FBB)) {
481 // Last MI in the BB is an unconditional branch. We can simply invert the
482 // condition and swap destinations:
483 // beq L1
484 // b L2
485 // =>
486 // bne L2
487 // b L1
488 LLVM_DEBUG(dbgs() << " Invert condition and swap "
489 "its destination with "
490 << MBB->back());
491
492 removeBranch(MBB);
493 insertBranch(MBB, FBB, TBB, Cond);
494 return true;
495 }
496 if (FBB) {
497 // If we get here with a MBB which ends like this:
498 //
499 // bb.1:
500 // successors: %bb.2;
501 // ...
502 // BNE $x1, $x0, %bb.2
503 // PseudoBR %bb.2
504 //
505 // Just remove conditional branch.
506 if (TBB == FBB) {
507 removeBranch(MBB);
508 insertUncondBranch(MBB, TBB);
509 return true;
510 }
511 // We need to split the basic block here to obtain two long-range
512 // unconditional branches.
513 NewBB = createNewBlockAfter(*MBB);
514
515 insertUncondBranch(NewBB, FBB);
516 // Update the succesor lists according to the transformation to follow.
517 // Do it here since if there's no split, no update is needed.
518 MBB->replaceSuccessor(FBB, NewBB);
519 NewBB->addSuccessor(FBB);
520 updateLiveness(NewBB);
521 }
522
523 // We now have an appropriate fall-through block in place (either naturally
524 // or just created), so we can use the inverted the condition.
525 MachineBasicBlock &NextBB = *std::next(MachineFunction::iterator(MBB));
526
527 LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*TBB)
528 << ", invert condition and change dest. to "
529 << printMBBReference(NextBB) << '\n');
530
531 removeBranch(MBB);
532 // Insert a new conditional branch and a new unconditional branch.
533 insertBranch(MBB, &NextBB, TBB, Cond);
534 return true;
535 }
536 // Branch cond can't be inverted.
537 // In this case we always add a block after the MBB.
538 LLVM_DEBUG(dbgs() << " The branch condition can't be inverted. "
539 << " Insert a new BB after " << MBB->back());
540
541 if (!FBB)
542 FBB = &(*std::next(MachineFunction::iterator(MBB)));
543
544 // This is the block with cond. branch and the distance to TBB is too long.
545 // beq L1
546 // L2:
547
548 // We do the following transformation:
549 // beq NewBB
550 // b L2
551 // NewBB:
552 // b L1
553 // L2:
554
555 NewBB = createNewBlockAfter(*MBB);
556 insertUncondBranch(NewBB, TBB);
557
558 LLVM_DEBUG(dbgs() << " Insert cond B to the new BB "
559 << printMBBReference(*NewBB)
560 << " Keep the exiting condition.\n"
561 << " Insert B to " << printMBBReference(*FBB) << ".\n"
562 << " In the new BB: Insert B to "
563 << printMBBReference(*TBB) << ".\n");
564
565 // Update the successor lists according to the transformation to follow.
566 MBB->replaceSuccessor(TBB, NewBB);
567 NewBB->addSuccessor(TBB);
568
569 // Replace branch in the current (MBB) block.
570 removeBranch(MBB);
571 insertBranch(MBB, NewBB, FBB, Cond);
572
573 updateLiveness(NewBB);
574 return true;
575}
576
577bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &MI) {
578 MachineBasicBlock *MBB = MI.getParent();
579 unsigned OldBrSize = TII->getInstSizeInBytes(MI);
580 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
581
582 int64_t DestOffset = BlockInfo[DestBB->getNumber()].Offset;
583 int64_t SrcOffset = getInstrOffset(MI);
584
585 assert(!TII->isBranchOffsetInRange(
586 MI.getOpcode(), MBB->getSectionID() != DestBB->getSectionID()
587 ? TM->getMaxCodeSize()
588 : DestOffset - SrcOffset));
589
590 BlockInfo[MBB->getNumber()].Size -= OldBrSize;
591
592 MachineBasicBlock *BranchBB = MBB;
593
594 // If this was an expanded conditional branch, there is already a single
595 // unconditional branch in a block.
596 if (!MBB->empty()) {
597 BranchBB = createNewBlockAfter(*MBB);
598
599 // Add live outs.
600 for (const MachineBasicBlock *Succ : MBB->successors()) {
601 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : Succ->liveins())
602 BranchBB->addLiveIn(LiveIn);
603 }
604
605 BranchBB->sortUniqueLiveIns();
606 BranchBB->addSuccessor(DestBB);
607 MBB->replaceSuccessor(DestBB, BranchBB);
608 if (TrampolineInsertionPoint == MBB)
609 TrampolineInsertionPoint = BranchBB;
610 }
611
612 DebugLoc DL = MI.getDebugLoc();
613 MI.eraseFromParent();
614
615 // Create the optional restore block and, initially, place it at the end of
616 // function. That block will be placed later if it's used; otherwise, it will
617 // be erased.
618 MachineBasicBlock *RestoreBB =
619 createNewBlockAfter(MF->back(), DestBB->getBasicBlock());
620 std::prev(RestoreBB->getIterator())
621 ->setIsEndSection(RestoreBB->isEndSection());
622 RestoreBB->setIsEndSection(false);
623
624 TII->insertIndirectBranch(*BranchBB, *DestBB, *RestoreBB, DL,
625 BranchBB->getSectionID() != DestBB->getSectionID()
626 ? TM->getMaxCodeSize()
627 : DestOffset - SrcOffset,
628 RS.get());
629
630 // Update the block size and offset for the BranchBB (which may be newly
631 // created).
632 BlockInfo[BranchBB->getNumber()].Size = computeBlockSize(*BranchBB);
633 adjustBlockOffsets(*MBB, std::next(BranchBB->getIterator()));
634
635 // If RestoreBB is required, place it appropriately.
636 if (!RestoreBB->empty()) {
637 // If the jump is Cold -> Hot, don't place the restore block (which is
638 // cold) in the middle of the function. Place it at the end.
641 MachineBasicBlock *NewBB = createNewBlockAfter(*TrampolineInsertionPoint);
642 TII->insertUnconditionalBranch(*NewBB, DestBB, DebugLoc());
643 BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);
644 adjustBlockOffsets(*TrampolineInsertionPoint,
645 std::next(NewBB->getIterator()));
646
647 // New trampolines should be inserted after NewBB.
648 TrampolineInsertionPoint = NewBB;
649
650 // Retarget the unconditional branch to the trampoline block.
651 BranchBB->replaceSuccessor(DestBB, NewBB);
652 NewBB->addSuccessor(DestBB);
653
654 DestBB = NewBB;
655 }
656
657 // In all other cases, try to place just before DestBB.
658
659 // TODO: For multiple far branches to the same destination, there are
660 // chances that some restore blocks could be shared if they clobber the
661 // same registers and share the same restore sequence. So far, those
662 // restore blocks are just duplicated for each far branch.
663 assert(!DestBB->isEntryBlock());
664 MachineBasicBlock *PrevBB = &*std::prev(DestBB->getIterator());
665 // Fall through only if PrevBB has no unconditional branch as one of its
666 // terminators.
667 if (auto *FT = PrevBB->getLogicalFallThrough()) {
668 assert(FT == DestBB);
669 TII->insertUnconditionalBranch(*PrevBB, FT, DebugLoc());
670 BlockInfo[PrevBB->getNumber()].Size = computeBlockSize(*PrevBB);
671 }
672 // Now, RestoreBB could be placed directly before DestBB.
673 MF->splice(DestBB->getIterator(), RestoreBB->getIterator());
674 // Update successors and predecessors.
675 RestoreBB->addSuccessor(DestBB);
676 BranchBB->replaceSuccessor(DestBB, RestoreBB);
677 if (TRI->trackLivenessAfterRegAlloc(*MF))
678 computeAndAddLiveIns(LiveRegs, *RestoreBB);
679 // Compute the restore block size.
680 BlockInfo[RestoreBB->getNumber()].Size = computeBlockSize(*RestoreBB);
681 // Update the estimated offset for the restore block.
682 adjustBlockOffsets(*PrevBB, DestBB->getIterator());
683
684 // Fix up section information for RestoreBB and DestBB
685 RestoreBB->setSectionID(DestBB->getSectionID());
686 RestoreBB->setIsBeginSection(DestBB->isBeginSection());
687 DestBB->setIsBeginSection(false);
688 RelaxedUnconditionals.insert({BranchBB, RestoreBB});
689 } else {
690 // Remove restore block if it's not required.
691 MF->erase(RestoreBB);
692 RelaxedUnconditionals.insert({BranchBB, DestBB});
693 }
694
695 return true;
696}
697
698bool BranchRelaxation::relaxBranchInstructions() {
699 bool Changed = false;
700
701 // Relaxing branches involves creating new basic blocks, so re-eval
702 // end() for termination.
703 for (MachineBasicBlock &MBB : *MF) {
704 // Empty block?
706 if (Last == MBB.end())
707 continue;
708
709 // Expand the unconditional branch first if necessary. If there is a
710 // conditional branch, this will end up changing the branch destination of
711 // it to be over the newly inserted indirect branch block, which may avoid
712 // the need to try expanding the conditional branch first, saving an extra
713 // jump.
714 if (Last->isUnconditionalBranch()) {
715 // Unconditional branch destination might be unanalyzable, assume these
716 // are OK.
717 if (MachineBasicBlock *DestBB = TII->getBranchDestBlock(*Last)) {
718 if (!isBlockInRange(*Last, *DestBB) && !TII->isTailCall(*Last) &&
719 !RelaxedUnconditionals.contains({&MBB, DestBB})) {
720 fixupUnconditionalBranch(*Last);
721 ++NumUnconditionalRelaxed;
722 Changed = true;
723 }
724 }
725 }
726
727 // Loop over the conditional branches.
730 J != MBB.end(); J = Next) {
731 Next = std::next(J);
732 MachineInstr &MI = *J;
733
734 if (!MI.isConditionalBranch())
735 continue;
736
737 if (MI.getOpcode() == TargetOpcode::FAULTING_OP)
738 // FAULTING_OP's destination is not encoded in the instruction stream
739 // and thus never needs relaxed.
740 continue;
741
742 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
743 if (!isBlockInRange(MI, *DestBB)) {
744 if (Next != MBB.end() && Next->isConditionalBranch()) {
745 // If there are multiple conditional branches, this isn't an
746 // analyzable block. Split later terminators into a new block so
747 // each one will be analyzable.
748
749 splitBlockBeforeInstr(*Next, DestBB);
750 } else {
751 fixupConditionalBranch(MI);
752 ++NumConditionalRelaxed;
753 }
754
755 Changed = true;
756
757 // This may have modified all of the terminators, so start over.
759 }
760 }
761 }
762
763 // If we relaxed a branch, we must recompute offsets for *all* basic blocks.
764 // Otherwise, we may underestimate branch distances and fail to relax a branch
765 // that has been pushed out of range.
766 if (Changed)
767 adjustBlockOffsets(MF->front());
768
769 return Changed;
770}
771
772PreservedAnalyses
779
780bool BranchRelaxation::run(MachineFunction &mf) {
781 MF = &mf;
782
783 LLVM_DEBUG(dbgs() << "***** BranchRelaxation *****\n");
784
785 const TargetSubtargetInfo &ST = MF->getSubtarget();
786 TII = ST.getInstrInfo();
787 TM = &MF->getTarget();
788
789 TRI = ST.getRegisterInfo();
790 if (TRI->trackLivenessAfterRegAlloc(*MF))
791 RS.reset(new RegScavenger());
792
793 // Renumber all of the machine basic blocks in the function, guaranteeing that
794 // the numbers agree with the position of the block in the function.
795 MF->RenumberBlocks();
796
797 // Do the initial scan of the function, building up information about the
798 // sizes of each block.
799 scanFunction();
800
801 LLVM_DEBUG(dbgs() << " Basic blocks before relaxation\n"; dumpBBs(););
802
803 bool MadeChange = false;
804 while (relaxBranchInstructions())
805 MadeChange = true;
806
807 // After a while, this might be made debug-only, but it is not expensive.
808 verify();
809
810 LLVM_DEBUG(dbgs() << " Basic blocks after relaxation\n\n"; dumpBBs());
811
812 BlockInfo.clear();
813 RelaxedUnconditionals.clear();
814
815 return MadeChange;
816}
#define Fail
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static cl::opt< bool > BranchRelaxation("aarch64-enable-branch-relax", cl::Hidden, cl::init(true), cl::desc("Relax out of range conditional branches"))
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define BRANCH_RELAX_NAME
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:672
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
ppc ctr loops verify
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static void updateLiveness(MachineFunction &MF)
Helper function to update the liveness information for the callee-saved registers.
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
This file declares the machine register scavenger class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
Remove the branching code at the end of the specific MBB.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
Reverses the branch condition of the specified condition list, returning false on success and true if...
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
Insert branch code into the end of the specified MachineBasicBlock.
bool isTailCall(const MachineInstr &MI) const override
A set of physical registers with utility functions to track liveness when walking backward/forward th...
void setIsEndSection(bool V=true)
MachineInstrBundleIterator< const MachineInstr > const_iterator
MachineBasicBlock * getLogicalFallThrough()
Return the fallthrough block if the block can implicitly transfer control to it's successor,...
LLVM_ABI void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New)
Replace successor OLD with NEW and update probability info.
LLVM_ABI void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void updateTerminator(MachineBasicBlock *PreviousLayoutSuccessor)
Update the terminator instructions in block to account for changes to block layout which may have bee...
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
MBBSectionID getSectionID() const
Returns the section ID of this basic block.
LLVM_ABI bool isEntryBlock() const
Returns true if this is the entry block of the function.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
void setSectionID(MBBSectionID V)
Sets the section ID for this basic block.
LLVM_ABI iterator getLastNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the last non-debug instruction in the basic block, or end().
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
bool isBeginSection() const
Returns true if this block begins any section.
iterator_range< succ_iterator > successors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
bool isEndSection() const
Returns true if this block ends any section.
MachineInstrBundleIterator< MachineInstr > iterator
void setIsBeginSection(bool V=true)
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
BasicBlockListType::iterator iterator
Representation of each machine instruction.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetInstrInfo - Interface to description of machine instruction set.
Primary interface to the complete machine description for the target machine.
uint64_t getMaxCodeSize() const
Returns the maximum code size possible under the code model.
const Target & getTarget() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
self_iterator getIterator()
Definition ilist_node.h:123
Changed
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI char & BranchRelaxationPassID
BranchRelaxation - This pass replaces branches that need to jump further than is supported by a branc...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:94
LLVM_ABI void computeAndAddLiveIns(LivePhysRegs &LiveRegs, MachineBasicBlock &MBB)
Convenience function combining computeLiveIns() and addLiveIns().
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
BasicBlockInfo - Information about the offset and size of a single basic block.
unsigned Size
Size - Size of the basic block in bytes.
unsigned Offset
Offset - Distance from the beginning of the function to the beginning of this basic block.
LLVM_ABI static const MBBSectionID ColdSectionID