1 //===- HexagonCFGOptimizer.cpp - CFG optimizations ------------------------===//
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 
9 #include "Hexagon.h"
10 #include "MCTargetDesc/HexagonMCTargetDesc.h"
11 #include "llvm/CodeGen/MachineBasicBlock.h"
12 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
13 #include "llvm/CodeGen/MachineFunction.h"
14 #include "llvm/CodeGen/MachineFunctionPass.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/CodeGen/MachineOperand.h"
17 #include "llvm/CodeGen/TargetInstrInfo.h"
18 #include "llvm/CodeGen/TargetSubtargetInfo.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include <cassert>
22 #include <vector>
23 
24 using namespace llvm;
25 
26 #define DEBUG_TYPE "hexagon_cfg"
27 
28 namespace llvm {
29 
30 FunctionPass *createHexagonCFGOptimizer();
31 void initializeHexagonCFGOptimizerPass(PassRegistry&);
32 
33 } // end namespace llvm
34 
35 namespace {
36 
37 class HexagonCFGOptimizer : public MachineFunctionPass {
38 private:
39   void InvertAndChangeJumpTarget(MachineInstr &, MachineBasicBlock *);
40   bool isOnFallThroughPath(MachineBasicBlock *MBB);
41 
42 public:
43   static char ID;
44 
45   HexagonCFGOptimizer() : MachineFunctionPass(ID) {
46     initializeHexagonCFGOptimizerPass(*PassRegistry::getPassRegistry());
47   }
48 
49   StringRef getPassName() const override { return "Hexagon CFG Optimizer"; }
50   bool runOnMachineFunction(MachineFunction &Fn) override;
51 
52   MachineFunctionProperties getRequiredProperties() const override {
53     return MachineFunctionProperties().set(
54         MachineFunctionProperties::Property::NoVRegs);
55   }
56 };
57 
58 } // end anonymous namespace
59 
60 char HexagonCFGOptimizer::ID = 0;
61 
62 static bool IsConditionalBranch(int Opc) {
63   switch (Opc) {
64     case Hexagon::J2_jumpt:
65     case Hexagon::J2_jumptpt:
66     case Hexagon::J2_jumpf:
67     case Hexagon::J2_jumpfpt:
68     case Hexagon::J2_jumptnew:
69     case Hexagon::J2_jumpfnew:
70     case Hexagon::J2_jumptnewpt:
71     case Hexagon::J2_jumpfnewpt:
72       return true;
73   }
74   return false;
75 }
76 
77 static bool IsUnconditionalJump(int Opc) {
78   return (Opc == Hexagon::J2_jump);
79 }
80 
81 void HexagonCFGOptimizer::InvertAndChangeJumpTarget(
82     MachineInstr &MI, MachineBasicBlock *NewTarget) {
83   const TargetInstrInfo *TII =
84       MI.getParent()->getParent()->getSubtarget().getInstrInfo();
85   int NewOpcode = 0;
86   switch (MI.getOpcode()) {
87   case Hexagon::J2_jumpt:
88     NewOpcode = Hexagon::J2_jumpf;
89     break;
90   case Hexagon::J2_jumpf:
91     NewOpcode = Hexagon::J2_jumpt;
92     break;
93   case Hexagon::J2_jumptnewpt:
94     NewOpcode = Hexagon::J2_jumpfnewpt;
95     break;
96   case Hexagon::J2_jumpfnewpt:
97     NewOpcode = Hexagon::J2_jumptnewpt;
98     break;
99   default:
100     llvm_unreachable("Cannot handle this case");
101   }
102 
103   MI.setDesc(TII->get(NewOpcode));
104   MI.getOperand(1).setMBB(NewTarget);
105 }
106 
107 bool HexagonCFGOptimizer::isOnFallThroughPath(MachineBasicBlock *MBB) {
108   if (MBB->canFallThrough())
109     return true;
110   for (MachineBasicBlock *PB : MBB->predecessors())
111     if (PB->isLayoutSuccessor(MBB) && PB->canFallThrough())
112       return true;
113   return false;
114 }
115 
116 bool HexagonCFGOptimizer::runOnMachineFunction(MachineFunction &Fn) {
117   if (skipFunction(Fn.getFunction()))
118     return false;
119 
120   // Loop over all of the basic blocks.
121   for (MachineFunction::iterator MBBb = Fn.begin(), MBBe = Fn.end();
122        MBBb != MBBe; ++MBBb) {
123     MachineBasicBlock *MBB = &*MBBb;
124 
125     // Traverse the basic block.
126     MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
127     if (MII != MBB->end()) {
128       MachineInstr &MI = *MII;
129       int Opc = MI.getOpcode();
130       if (IsConditionalBranch(Opc)) {
131         // (Case 1) Transform the code if the following condition occurs:
132         //   BB1: if (p0) jump BB3
133         //   ...falls-through to BB2 ...
134         //   BB2: jump BB4
135         //   ...next block in layout is BB3...
136         //   BB3: ...
137         //
138         //  Transform this to:
139         //  BB1: if (!p0) jump BB4
140         //  Remove BB2
141         //  BB3: ...
142         //
143         // (Case 2) A variation occurs when BB3 contains a JMP to BB4:
144         //   BB1: if (p0) jump BB3
145         //   ...falls-through to BB2 ...
146         //   BB2: jump BB4
147         //   ...other basic blocks ...
148         //   BB4:
149         //   ...not a fall-thru
150         //   BB3: ...
151         //     jump BB4
152         //
153         // Transform this to:
154         //   BB1: if (!p0) jump BB4
155         //   Remove BB2
156         //   BB3: ...
157         //   BB4: ...
158         unsigned NumSuccs = MBB->succ_size();
159         MachineBasicBlock::succ_iterator SI = MBB->succ_begin();
160         MachineBasicBlock* FirstSucc = *SI;
161         MachineBasicBlock* SecondSucc = *(++SI);
162         MachineBasicBlock* LayoutSucc = nullptr;
163         MachineBasicBlock* JumpAroundTarget = nullptr;
164 
165         if (MBB->isLayoutSuccessor(FirstSucc)) {
166           LayoutSucc = FirstSucc;
167           JumpAroundTarget = SecondSucc;
168         } else if (MBB->isLayoutSuccessor(SecondSucc)) {
169           LayoutSucc = SecondSucc;
170           JumpAroundTarget = FirstSucc;
171         } else {
172           // Odd case...cannot handle.
173         }
174 
175         // The target of the unconditional branch must be JumpAroundTarget.
176         // TODO: If not, we should not invert the unconditional branch.
177         MachineBasicBlock* CondBranchTarget = nullptr;
178         if (MI.getOpcode() == Hexagon::J2_jumpt ||
179             MI.getOpcode() == Hexagon::J2_jumpf) {
180           CondBranchTarget = MI.getOperand(1).getMBB();
181         }
182 
183         if (!LayoutSucc || (CondBranchTarget != JumpAroundTarget)) {
184           continue;
185         }
186 
187         if ((NumSuccs == 2) && LayoutSucc && (LayoutSucc->pred_size() == 1)) {
188           // Ensure that BB2 has one instruction -- an unconditional jump.
189           if ((LayoutSucc->size() == 1) &&
190               IsUnconditionalJump(LayoutSucc->front().getOpcode())) {
191             assert(JumpAroundTarget && "jump target is needed to process second basic block");
192             MachineBasicBlock* UncondTarget =
193               LayoutSucc->front().getOperand(0).getMBB();
194             // Check if the layout successor of BB2 is BB3.
195             bool case1 = LayoutSucc->isLayoutSuccessor(JumpAroundTarget);
196             bool case2 = JumpAroundTarget->isSuccessor(UncondTarget) &&
197               !JumpAroundTarget->empty() &&
198               IsUnconditionalJump(JumpAroundTarget->back().getOpcode()) &&
199               JumpAroundTarget->pred_size() == 1 &&
200               JumpAroundTarget->succ_size() == 1;
201 
202             if (case1 || case2) {
203               InvertAndChangeJumpTarget(MI, UncondTarget);
204               MBB->replaceSuccessor(JumpAroundTarget, UncondTarget);
205 
206               // Remove the unconditional branch in LayoutSucc.
207               LayoutSucc->erase(LayoutSucc->begin());
208               LayoutSucc->replaceSuccessor(UncondTarget, JumpAroundTarget);
209 
210               // This code performs the conversion for case 2, which moves
211               // the block to the fall-thru case (BB3 in the code above).
212               if (case2 && !case1) {
213                 JumpAroundTarget->moveAfter(LayoutSucc);
214                 // only move a block if it doesn't have a fall-thru. otherwise
215                 // the CFG will be incorrect.
216                 if (!isOnFallThroughPath(UncondTarget))
217                   UncondTarget->moveAfter(JumpAroundTarget);
218               }
219 
220               // Correct live-in information. Is used by post-RA scheduler
221               // The live-in to LayoutSucc is now all values live-in to
222               // JumpAroundTarget.
223               std::vector<MachineBasicBlock::RegisterMaskPair> OrigLiveIn(
224                   LayoutSucc->livein_begin(), LayoutSucc->livein_end());
225               std::vector<MachineBasicBlock::RegisterMaskPair> NewLiveIn(
226                   JumpAroundTarget->livein_begin(),
227                   JumpAroundTarget->livein_end());
228               for (const auto &OrigLI : OrigLiveIn)
229                 LayoutSucc->removeLiveIn(OrigLI.PhysReg);
230               for (const auto &NewLI : NewLiveIn)
231                 LayoutSucc->addLiveIn(NewLI);
232             }
233           }
234         }
235       }
236     }
237   }
238   return true;
239 }
240 
241 //===----------------------------------------------------------------------===//
242 //                         Public Constructor Functions
243 //===----------------------------------------------------------------------===//
244 
245 INITIALIZE_PASS(HexagonCFGOptimizer, "hexagon-cfg", "Hexagon CFG Optimizer",
246                 false, false)
247 
248 FunctionPass *llvm::createHexagonCFGOptimizer() {
249   return new HexagonCFGOptimizer();
250 }
251