blob: c1891674721265f3fd27d0e9eb37f5bb34278dac [file] [log] [blame]
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +00001//===--- HexagonEarlyIfConv.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// This implements a Hexagon-specific if-conversion pass that runs on the
11// SSA form.
12// In SSA it is not straightforward to represent instructions that condi-
13// tionally define registers, since a conditionally-defined register may
14// only be used under the same condition on which the definition was based.
15// To avoid complications of this nature, this patch will only generate
16// predicated stores, and speculate other instructions from the "if-conver-
17// ted" block.
18// The code will recognize CFG patterns where a block with a conditional
19// branch "splits" into a "true block" and a "false block". Either of these
20// could be omitted (in case of a triangle, for example).
21// If after conversion of the side block(s) the CFG allows it, the resul-
22// ting blocks may be merged. If the "join" block contained PHI nodes, they
23// will be replaced with MUX (or MUX-like) instructions to maintain the
24// semantics of the PHI.
25//
26// Example:
27//
28// %vreg40<def> = L2_loadrub_io %vreg39<kill>, 1
29// %vreg41<def> = S2_tstbit_i %vreg40<kill>, 0
30// J2_jumpt %vreg41<kill>, <BB#5>, %PC<imp-def,dead>
31// J2_jump <BB#4>, %PC<imp-def,dead>
32// Successors according to CFG: BB#4(62) BB#5(62)
33//
34// BB#4: derived from LLVM BB %if.then
35// Predecessors according to CFG: BB#3
36// %vreg11<def> = A2_addp %vreg6, %vreg10
37// S2_storerd_io %vreg32, 16, %vreg11
38// Successors according to CFG: BB#5
39//
40// BB#5: derived from LLVM BB %if.end
41// Predecessors according to CFG: BB#3 BB#4
42// %vreg12<def> = PHI %vreg6, <BB#3>, %vreg11, <BB#4>
43// %vreg13<def> = A2_addp %vreg7, %vreg12
44// %vreg42<def> = C2_cmpeqi %vreg9, 10
45// J2_jumpf %vreg42<kill>, <BB#3>, %PC<imp-def,dead>
46// J2_jump <BB#6>, %PC<imp-def,dead>
47// Successors according to CFG: BB#6(4) BB#3(124)
48//
49// would become:
50//
51// %vreg40<def> = L2_loadrub_io %vreg39<kill>, 1
52// %vreg41<def> = S2_tstbit_i %vreg40<kill>, 0
53// spec-> %vreg11<def> = A2_addp %vreg6, %vreg10
54// pred-> S2_pstorerdf_io %vreg41, %vreg32, 16, %vreg11
Krzysztof Parzyszek258af192016-08-11 19:12:18 +000055// %vreg46<def> = PS_pselect %vreg41, %vreg6, %vreg11
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000056// %vreg13<def> = A2_addp %vreg7, %vreg46
57// %vreg42<def> = C2_cmpeqi %vreg9, 10
58// J2_jumpf %vreg42<kill>, <BB#3>, %PC<imp-def,dead>
59// J2_jump <BB#6>, %PC<imp-def,dead>
60// Successors according to CFG: BB#6 BB#3
61
62#define DEBUG_TYPE "hexagon-eif"
63
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000064#include "Hexagon.h"
65#include "HexagonInstrInfo.h"
66#include "HexagonSubtarget.h"
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000067#include "llvm/ADT/DenseSet.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000068#include "llvm/ADT/iterator_range.h"
69#include "llvm/ADT/SmallVector.h"
70#include "llvm/ADT/StringRef.h"
71#include "llvm/CodeGen/MachineBasicBlock.h"
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000072#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
73#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000074#include "llvm/CodeGen/MachineFunction.h"
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000075#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000076#include "llvm/CodeGen/MachineInstr.h"
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000077#include "llvm/CodeGen/MachineInstrBuilder.h"
78#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000079#include "llvm/CodeGen/MachineOperand.h"
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000080#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000081#include "llvm/IR/DebugLoc.h"
82#include "llvm/Pass.h"
83#include "llvm/Support/BranchProbability.h"
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000084#include "llvm/Support/CommandLine.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000085#include "llvm/Support/Compiler.h"
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000086#include "llvm/Support/Debug.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000087#include "llvm/Support/ErrorHandling.h"
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000088#include "llvm/Support/raw_ostream.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000089#include "llvm/Target/TargetRegisterInfo.h"
90#include <cassert>
91#include <iterator>
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000092
93using namespace llvm;
94
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000095namespace llvm {
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000096
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000097 FunctionPass *createHexagonEarlyIfConversion();
98 void initializeHexagonEarlyIfConversionPass(PassRegistry& Registry);
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000099
100} // end namespace llvm
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000101
102namespace {
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000103
Krzysztof Parzyszek8d2b2cf2015-10-06 18:29:36 +0000104 cl::opt<bool> EnableHexagonBP("enable-hexagon-br-prob", cl::Hidden,
105 cl::init(false), cl::desc("Enable branch probability info"));
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000106 cl::opt<unsigned> SizeLimit("eif-limit", cl::init(6), cl::Hidden,
Krzysztof Parzyszek8d2b2cf2015-10-06 18:29:36 +0000107 cl::desc("Size limit in Hexagon early if-conversion"));
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000108
109 struct PrintMB {
110 PrintMB(const MachineBasicBlock *B) : MB(B) {}
111 const MachineBasicBlock *MB;
112 };
113 raw_ostream &operator<< (raw_ostream &OS, const PrintMB &P) {
114 if (!P.MB)
115 return OS << "<none>";
116 return OS << '#' << P.MB->getNumber();
117 }
118
119 struct FlowPattern {
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000120 FlowPattern() = default;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000121 FlowPattern(MachineBasicBlock *B, unsigned PR, MachineBasicBlock *TB,
122 MachineBasicBlock *FB, MachineBasicBlock *JB)
123 : SplitB(B), TrueB(TB), FalseB(FB), JoinB(JB), PredR(PR) {}
124
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000125 MachineBasicBlock *SplitB = nullptr;
126 MachineBasicBlock *TrueB = nullptr;
127 MachineBasicBlock *FalseB = nullptr;
128 MachineBasicBlock *JoinB = nullptr;
129 unsigned PredR = 0;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000130 };
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000131
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000132 struct PrintFP {
133 PrintFP(const FlowPattern &P, const TargetRegisterInfo &T)
134 : FP(P), TRI(T) {}
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000135
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000136 const FlowPattern &FP;
137 const TargetRegisterInfo &TRI;
138 friend raw_ostream &operator<< (raw_ostream &OS, const PrintFP &P);
139 };
140 raw_ostream &operator<<(raw_ostream &OS,
141 const PrintFP &P) LLVM_ATTRIBUTE_UNUSED;
142 raw_ostream &operator<<(raw_ostream &OS, const PrintFP &P) {
143 OS << "{ SplitB:" << PrintMB(P.FP.SplitB)
144 << ", PredR:" << PrintReg(P.FP.PredR, &P.TRI)
145 << ", TrueB:" << PrintMB(P.FP.TrueB) << ", FalseB:"
146 << PrintMB(P.FP.FalseB)
147 << ", JoinB:" << PrintMB(P.FP.JoinB) << " }";
148 return OS;
149 }
150
151 class HexagonEarlyIfConversion : public MachineFunctionPass {
152 public:
153 static char ID;
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000154
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000155 HexagonEarlyIfConversion() : MachineFunctionPass(ID),
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000156 HII(nullptr), TRI(nullptr), MFN(nullptr), MRI(nullptr), MDT(nullptr),
157 MLI(nullptr) {
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000158 initializeHexagonEarlyIfConversionPass(*PassRegistry::getPassRegistry());
159 }
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000160
Mehdi Amini117296c2016-10-01 02:56:57 +0000161 StringRef getPassName() const override {
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000162 return "Hexagon early if conversion";
163 }
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000164
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000165 void getAnalysisUsage(AnalysisUsage &AU) const override {
166 AU.addRequired<MachineBranchProbabilityInfo>();
167 AU.addRequired<MachineDominatorTree>();
168 AU.addPreserved<MachineDominatorTree>();
169 AU.addRequired<MachineLoopInfo>();
170 MachineFunctionPass::getAnalysisUsage(AU);
171 }
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000172
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000173 bool runOnMachineFunction(MachineFunction &MF) override;
174
175 private:
176 typedef DenseSet<MachineBasicBlock*> BlockSetType;
177
178 bool isPreheader(const MachineBasicBlock *B) const;
179 bool matchFlowPattern(MachineBasicBlock *B, MachineLoop *L,
180 FlowPattern &FP);
181 bool visitBlock(MachineBasicBlock *B, MachineLoop *L);
182 bool visitLoop(MachineLoop *L);
183
184 bool hasEHLabel(const MachineBasicBlock *B) const;
185 bool hasUncondBranch(const MachineBasicBlock *B) const;
186 bool isValidCandidate(const MachineBasicBlock *B) const;
187 bool usesUndefVReg(const MachineInstr *MI) const;
188 bool isValid(const FlowPattern &FP) const;
189 unsigned countPredicateDefs(const MachineBasicBlock *B) const;
190 unsigned computePhiCost(MachineBasicBlock *B) const;
191 bool isProfitable(const FlowPattern &FP) const;
192 bool isPredicableStore(const MachineInstr *MI) const;
193 bool isSafeToSpeculate(const MachineInstr *MI) const;
194
195 unsigned getCondStoreOpcode(unsigned Opc, bool IfTrue) const;
196 void predicateInstr(MachineBasicBlock *ToB, MachineBasicBlock::iterator At,
197 MachineInstr *MI, unsigned PredR, bool IfTrue);
198 void predicateBlockNB(MachineBasicBlock *ToB,
199 MachineBasicBlock::iterator At, MachineBasicBlock *FromB,
200 unsigned PredR, bool IfTrue);
201
202 void updatePhiNodes(MachineBasicBlock *WhereB, const FlowPattern &FP);
203 void convert(const FlowPattern &FP);
204
205 void removeBlock(MachineBasicBlock *B);
206 void eliminatePhis(MachineBasicBlock *B);
207 void replacePhiEdges(MachineBasicBlock *OldB, MachineBasicBlock *NewB);
208 void mergeBlocks(MachineBasicBlock *PredB, MachineBasicBlock *SuccB);
209 void simplifyFlowGraph(const FlowPattern &FP);
210
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000211 const HexagonInstrInfo *HII;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000212 const TargetRegisterInfo *TRI;
213 MachineFunction *MFN;
214 MachineRegisterInfo *MRI;
215 MachineDominatorTree *MDT;
216 MachineLoopInfo *MLI;
217 BlockSetType Deleted;
218 const MachineBranchProbabilityInfo *MBPI;
219 };
220
221 char HexagonEarlyIfConversion::ID = 0;
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000222
223} // end anonymous namespace
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000224
225INITIALIZE_PASS(HexagonEarlyIfConversion, "hexagon-eif",
226 "Hexagon early if conversion", false, false)
227
228bool HexagonEarlyIfConversion::isPreheader(const MachineBasicBlock *B) const {
229 if (B->succ_size() != 1)
230 return false;
231 MachineBasicBlock *SB = *B->succ_begin();
232 MachineLoop *L = MLI->getLoopFor(SB);
233 return L && SB == L->getHeader();
234}
235
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000236bool HexagonEarlyIfConversion::matchFlowPattern(MachineBasicBlock *B,
237 MachineLoop *L, FlowPattern &FP) {
238 DEBUG(dbgs() << "Checking flow pattern at BB#" << B->getNumber() << "\n");
239
240 // Interested only in conditional branches, no .new, no new-value, etc.
241 // Check the terminators directly, it's easier than handling all responses
242 // from AnalyzeBranch.
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000243 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000244 MachineBasicBlock::const_iterator T1I = B->getFirstTerminator();
245 if (T1I == B->end())
246 return false;
247 unsigned Opc = T1I->getOpcode();
248 if (Opc != Hexagon::J2_jumpt && Opc != Hexagon::J2_jumpf)
249 return false;
250 unsigned PredR = T1I->getOperand(0).getReg();
251
252 // Get the layout successor, or 0 if B does not have one.
253 MachineFunction::iterator NextBI = std::next(MachineFunction::iterator(B));
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000254 MachineBasicBlock *NextB = (NextBI != MFN->end()) ? &*NextBI : nullptr;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000255
256 MachineBasicBlock *T1B = T1I->getOperand(1).getMBB();
257 MachineBasicBlock::const_iterator T2I = std::next(T1I);
258 // The second terminator should be an unconditional branch.
259 assert(T2I == B->end() || T2I->getOpcode() == Hexagon::J2_jump);
260 MachineBasicBlock *T2B = (T2I == B->end()) ? NextB
261 : T2I->getOperand(0).getMBB();
262 if (T1B == T2B) {
263 // XXX merge if T1B == NextB, or convert branch to unconditional.
264 // mark as diamond with both sides equal?
265 return false;
266 }
267 // Loop could be null for both.
268 if (MLI->getLoopFor(T1B) != L || MLI->getLoopFor(T2B) != L)
269 return false;
270
271 // Record the true/false blocks in such a way that "true" means "if (PredR)",
272 // and "false" means "if (!PredR)".
273 if (Opc == Hexagon::J2_jumpt)
274 TB = T1B, FB = T2B;
275 else
276 TB = T2B, FB = T1B;
277
278 if (!MDT->properlyDominates(B, TB) || !MDT->properlyDominates(B, FB))
279 return false;
280
281 // Detect triangle first. In case of a triangle, one of the blocks TB/FB
282 // can fall through into the other, in other words, it will be executed
283 // in both cases. We only want to predicate the block that is executed
284 // conditionally.
285 unsigned TNP = TB->pred_size(), FNP = FB->pred_size();
286 unsigned TNS = TB->succ_size(), FNS = FB->succ_size();
287
288 // A block is predicable if it has one predecessor (it must be B), and
289 // it has a single successor. In fact, the block has to end either with
290 // an unconditional branch (which can be predicated), or with a fall-
291 // through.
292 bool TOk = (TNP == 1) && (TNS == 1);
293 bool FOk = (FNP == 1) && (FNS == 1);
294
295 // If neither is predicable, there is nothing interesting.
296 if (!TOk && !FOk)
297 return false;
298
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000299 MachineBasicBlock *TSB = (TNS > 0) ? *TB->succ_begin() : nullptr;
300 MachineBasicBlock *FSB = (FNS > 0) ? *FB->succ_begin() : nullptr;
301 MachineBasicBlock *JB = nullptr;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000302
303 if (TOk) {
304 if (FOk) {
305 if (TSB == FSB)
306 JB = TSB;
307 // Diamond: "if (P) then TB; else FB;".
308 } else {
309 // TOk && !FOk
310 if (TSB == FB) {
311 JB = FB;
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000312 FB = nullptr;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000313 }
314 }
315 } else {
316 // !TOk && FOk (at least one must be true by now).
317 if (FSB == TB) {
318 JB = TB;
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000319 TB = nullptr;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000320 }
321 }
322 // Don't try to predicate loop preheaders.
323 if ((TB && isPreheader(TB)) || (FB && isPreheader(FB))) {
324 DEBUG(dbgs() << "One of blocks " << PrintMB(TB) << ", " << PrintMB(FB)
325 << " is a loop preheader. Skipping.\n");
326 return false;
327 }
328
329 FP = FlowPattern(B, PredR, TB, FB, JB);
330 DEBUG(dbgs() << "Detected " << PrintFP(FP, *TRI) << "\n");
331 return true;
332}
333
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000334// KLUDGE: HexagonInstrInfo::AnalyzeBranch won't work on a block that
335// contains EH_LABEL.
336bool HexagonEarlyIfConversion::hasEHLabel(const MachineBasicBlock *B) const {
337 for (auto &I : *B)
338 if (I.isEHLabel())
339 return true;
340 return false;
341}
342
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000343// KLUDGE: HexagonInstrInfo::AnalyzeBranch may be unable to recognize
344// that a block can never fall-through.
345bool HexagonEarlyIfConversion::hasUncondBranch(const MachineBasicBlock *B)
346 const {
347 MachineBasicBlock::const_iterator I = B->getFirstTerminator(), E = B->end();
348 while (I != E) {
349 if (I->isBarrier())
350 return true;
351 ++I;
352 }
353 return false;
354}
355
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000356bool HexagonEarlyIfConversion::isValidCandidate(const MachineBasicBlock *B)
357 const {
358 if (!B)
359 return true;
360 if (B->isEHPad() || B->hasAddressTaken())
361 return false;
362 if (B->succ_size() == 0)
363 return false;
364
365 for (auto &MI : *B) {
366 if (MI.isDebugValue())
367 continue;
368 if (MI.isConditionalBranch())
369 return false;
370 unsigned Opc = MI.getOpcode();
371 bool IsJMP = (Opc == Hexagon::J2_jump);
372 if (!isPredicableStore(&MI) && !IsJMP && !isSafeToSpeculate(&MI))
373 return false;
374 // Look for predicate registers defined by this instruction. It's ok
375 // to speculate such an instruction, but the predicate register cannot
376 // be used outside of this block (or else it won't be possible to
377 // update the use of it after predication). PHI uses will be updated
378 // to use a result of a MUX, and a MUX cannot be created for predicate
379 // registers.
Matthias Braunfc371552016-10-24 21:36:43 +0000380 for (const MachineOperand &MO : MI.operands()) {
381 if (!MO.isReg() || !MO.isDef())
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000382 continue;
Matthias Braunfc371552016-10-24 21:36:43 +0000383 unsigned R = MO.getReg();
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000384 if (!TargetRegisterInfo::isVirtualRegister(R))
385 continue;
Krzysztof Parzyszek056c9452017-03-02 18:10:59 +0000386 switch (MRI->getRegClass(R)->getID()) {
387 case Hexagon::PredRegsRegClassID:
388 case Hexagon::VecPredRegsRegClassID:
389 case Hexagon::VecPredRegs128BRegClassID:
390 break;
391 default:
392 continue;
393 }
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000394 for (auto U = MRI->use_begin(R); U != MRI->use_end(); ++U)
395 if (U->getParent()->isPHI())
396 return false;
397 }
398 }
399 return true;
400}
401
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000402bool HexagonEarlyIfConversion::usesUndefVReg(const MachineInstr *MI) const {
Matthias Braunfc371552016-10-24 21:36:43 +0000403 for (const MachineOperand &MO : MI->operands()) {
404 if (!MO.isReg() || !MO.isUse())
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000405 continue;
Matthias Braunfc371552016-10-24 21:36:43 +0000406 unsigned R = MO.getReg();
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000407 if (!TargetRegisterInfo::isVirtualRegister(R))
408 continue;
409 const MachineInstr *DefI = MRI->getVRegDef(R);
410 // "Undefined" virtual registers are actually defined via IMPLICIT_DEF.
411 assert(DefI && "Expecting a reaching def in MRI");
412 if (DefI->isImplicitDef())
413 return true;
414 }
415 return false;
416}
417
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000418bool HexagonEarlyIfConversion::isValid(const FlowPattern &FP) const {
419 if (hasEHLabel(FP.SplitB)) // KLUDGE: see function definition
420 return false;
421 if (FP.TrueB && !isValidCandidate(FP.TrueB))
422 return false;
423 if (FP.FalseB && !isValidCandidate(FP.FalseB))
424 return false;
425 // Check the PHIs in the join block. If any of them use a register
426 // that is defined as IMPLICIT_DEF, do not convert this. This can
427 // legitimately happen if one side of the split never executes, but
428 // the compiler is unable to prove it. That side may then seem to
429 // provide an "undef" value to the join block, however it will never
430 // execute at run-time. If we convert this case, the "undef" will
431 // be used in a MUX instruction, and that may seem like actually
432 // using an undefined value to other optimizations. This could lead
433 // to trouble further down the optimization stream, cause assertions
434 // to fail, etc.
435 if (FP.JoinB) {
436 const MachineBasicBlock &B = *FP.JoinB;
437 for (auto &MI : B) {
438 if (!MI.isPHI())
439 break;
440 if (usesUndefVReg(&MI))
441 return false;
442 unsigned DefR = MI.getOperand(0).getReg();
443 const TargetRegisterClass *RC = MRI->getRegClass(DefR);
444 if (RC == &Hexagon::PredRegsRegClass)
445 return false;
446 }
447 }
448 return true;
449}
450
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000451unsigned HexagonEarlyIfConversion::computePhiCost(MachineBasicBlock *B) const {
452 assert(B->pred_size() <= 2);
453 if (B->pred_size() < 2)
454 return 0;
455
456 unsigned Cost = 0;
457 MachineBasicBlock::const_iterator I, E = B->getFirstNonPHI();
458 for (I = B->begin(); I != E; ++I) {
459 const MachineOperand &RO1 = I->getOperand(1);
460 const MachineOperand &RO3 = I->getOperand(3);
461 assert(RO1.isReg() && RO3.isReg());
462 // Must have a MUX if the phi uses a subregister.
463 if (RO1.getSubReg() != 0 || RO3.getSubReg() != 0) {
464 Cost++;
465 continue;
466 }
467 MachineInstr *Def1 = MRI->getVRegDef(RO1.getReg());
468 MachineInstr *Def3 = MRI->getVRegDef(RO3.getReg());
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000469 if (!HII->isPredicable(*Def1) || !HII->isPredicable(*Def3))
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000470 Cost++;
471 }
472 return Cost;
473}
474
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000475unsigned HexagonEarlyIfConversion::countPredicateDefs(
476 const MachineBasicBlock *B) const {
477 unsigned PredDefs = 0;
478 for (auto &MI : *B) {
Matthias Braunfc371552016-10-24 21:36:43 +0000479 for (const MachineOperand &MO : MI.operands()) {
480 if (!MO.isReg() || !MO.isDef())
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000481 continue;
Matthias Braunfc371552016-10-24 21:36:43 +0000482 unsigned R = MO.getReg();
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000483 if (!TargetRegisterInfo::isVirtualRegister(R))
484 continue;
485 if (MRI->getRegClass(R) == &Hexagon::PredRegsRegClass)
486 PredDefs++;
487 }
488 }
489 return PredDefs;
490}
491
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000492bool HexagonEarlyIfConversion::isProfitable(const FlowPattern &FP) const {
493 if (FP.TrueB && FP.FalseB) {
494
495 // Do not IfCovert if the branch is one sided.
496 if (MBPI) {
497 BranchProbability Prob(9, 10);
498 if (MBPI->getEdgeProbability(FP.SplitB, FP.TrueB) > Prob)
499 return false;
500 if (MBPI->getEdgeProbability(FP.SplitB, FP.FalseB) > Prob)
501 return false;
502 }
503
504 // If both sides are predicable, convert them if they join, and the
505 // join block has no other predecessors.
506 MachineBasicBlock *TSB = *FP.TrueB->succ_begin();
507 MachineBasicBlock *FSB = *FP.FalseB->succ_begin();
508 if (TSB != FSB)
509 return false;
510 if (TSB->pred_size() != 2)
511 return false;
512 }
513
514 // Calculate the total size of the predicated blocks.
515 // Assume instruction counts without branches to be the approximation of
516 // the code size. If the predicated blocks are smaller than a packet size,
517 // approximate the spare room in the packet that could be filled with the
518 // predicated/speculated instructions.
519 unsigned TS = 0, FS = 0, Spare = 0;
520 if (FP.TrueB) {
521 TS = std::distance(FP.TrueB->begin(), FP.TrueB->getFirstTerminator());
522 if (TS < HEXAGON_PACKET_SIZE)
523 Spare += HEXAGON_PACKET_SIZE-TS;
524 }
525 if (FP.FalseB) {
526 FS = std::distance(FP.FalseB->begin(), FP.FalseB->getFirstTerminator());
527 if (FS < HEXAGON_PACKET_SIZE)
528 Spare += HEXAGON_PACKET_SIZE-TS;
529 }
530 unsigned TotalIn = TS+FS;
531 DEBUG(dbgs() << "Total number of instructions to be predicated/speculated: "
532 << TotalIn << ", spare room: " << Spare << "\n");
533 if (TotalIn >= SizeLimit+Spare)
534 return false;
535
536 // Count the number of PHI nodes that will need to be updated (converted
537 // to MUX). Those can be later converted to predicated instructions, so
538 // they aren't always adding extra cost.
539 // KLUDGE: Also, count the number of predicate register definitions in
540 // each block. The scheduler may increase the pressure of these and cause
541 // expensive spills (e.g. bitmnp01).
542 unsigned TotalPh = 0;
543 unsigned PredDefs = countPredicateDefs(FP.SplitB);
544 if (FP.JoinB) {
545 TotalPh = computePhiCost(FP.JoinB);
546 PredDefs += countPredicateDefs(FP.JoinB);
547 } else {
548 if (FP.TrueB && FP.TrueB->succ_size() > 0) {
549 MachineBasicBlock *SB = *FP.TrueB->succ_begin();
550 TotalPh += computePhiCost(SB);
551 PredDefs += countPredicateDefs(SB);
552 }
553 if (FP.FalseB && FP.FalseB->succ_size() > 0) {
554 MachineBasicBlock *SB = *FP.FalseB->succ_begin();
555 TotalPh += computePhiCost(SB);
556 PredDefs += countPredicateDefs(SB);
557 }
558 }
559 DEBUG(dbgs() << "Total number of extra muxes from converted phis: "
560 << TotalPh << "\n");
561 if (TotalIn+TotalPh >= SizeLimit+Spare)
562 return false;
563
564 DEBUG(dbgs() << "Total number of predicate registers: " << PredDefs << "\n");
565 if (PredDefs > 4)
566 return false;
567
568 return true;
569}
570
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000571bool HexagonEarlyIfConversion::visitBlock(MachineBasicBlock *B,
572 MachineLoop *L) {
573 bool Changed = false;
574
575 // Visit all dominated blocks from the same loop first, then process B.
576 MachineDomTreeNode *N = MDT->getNode(B);
577 typedef GraphTraits<MachineDomTreeNode*> GTN;
578 // We will change CFG/DT during this traversal, so take precautions to
579 // avoid problems related to invalidated iterators. In fact, processing
580 // a child C of B cannot cause another child to be removed, but it can
581 // cause a new child to be added (which was a child of C before C itself
582 // was removed. This new child C, however, would have been processed
583 // prior to processing B, so there is no need to process it again.
584 // Simply keep a list of children of B, and traverse that list.
585 typedef SmallVector<MachineDomTreeNode*,4> DTNodeVectType;
586 DTNodeVectType Cn(GTN::child_begin(N), GTN::child_end(N));
587 for (DTNodeVectType::iterator I = Cn.begin(), E = Cn.end(); I != E; ++I) {
588 MachineBasicBlock *SB = (*I)->getBlock();
589 if (!Deleted.count(SB))
590 Changed |= visitBlock(SB, L);
591 }
592 // When walking down the dominator tree, we want to traverse through
593 // blocks from nested (other) loops, because they can dominate blocks
594 // that are in L. Skip the non-L blocks only after the tree traversal.
595 if (MLI->getLoopFor(B) != L)
596 return Changed;
597
598 FlowPattern FP;
599 if (!matchFlowPattern(B, L, FP))
600 return Changed;
601
602 if (!isValid(FP)) {
603 DEBUG(dbgs() << "Conversion is not valid\n");
604 return Changed;
605 }
606 if (!isProfitable(FP)) {
607 DEBUG(dbgs() << "Conversion is not profitable\n");
608 return Changed;
609 }
610
611 convert(FP);
612 simplifyFlowGraph(FP);
613 return true;
614}
615
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000616bool HexagonEarlyIfConversion::visitLoop(MachineLoop *L) {
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000617 MachineBasicBlock *HB = L ? L->getHeader() : nullptr;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000618 DEBUG((L ? dbgs() << "Visiting loop H:" << PrintMB(HB)
619 : dbgs() << "Visiting function") << "\n");
620 bool Changed = false;
621 if (L) {
622 for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
623 Changed |= visitLoop(*I);
624 }
625
626 MachineBasicBlock *EntryB = GraphTraits<MachineFunction*>::getEntryNode(MFN);
627 Changed |= visitBlock(L ? HB : EntryB, L);
628 return Changed;
629}
630
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000631bool HexagonEarlyIfConversion::isPredicableStore(const MachineInstr *MI)
632 const {
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000633 // HexagonInstrInfo::isPredicable will consider these stores are non-
634 // -predicable if the offset would become constant-extended after
635 // predication.
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000636 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000637 switch (Opc) {
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000638 case Hexagon::S2_storerb_io:
639 case Hexagon::S2_storerbnew_io:
640 case Hexagon::S2_storerh_io:
641 case Hexagon::S2_storerhnew_io:
642 case Hexagon::S2_storeri_io:
643 case Hexagon::S2_storerinew_io:
644 case Hexagon::S2_storerd_io:
645 case Hexagon::S4_storeirb_io:
646 case Hexagon::S4_storeirh_io:
647 case Hexagon::S4_storeiri_io:
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000648 return true;
649 }
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000650
651 // TargetInstrInfo::isPredicable takes a non-const pointer.
652 return MI->mayStore() && HII->isPredicable(const_cast<MachineInstr&>(*MI));
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000653}
654
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000655bool HexagonEarlyIfConversion::isSafeToSpeculate(const MachineInstr *MI)
656 const {
657 if (MI->mayLoad() || MI->mayStore())
658 return false;
659 if (MI->isCall() || MI->isBarrier() || MI->isBranch())
660 return false;
661 if (MI->hasUnmodeledSideEffects())
662 return false;
663
664 return true;
665}
666
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000667unsigned HexagonEarlyIfConversion::getCondStoreOpcode(unsigned Opc,
668 bool IfTrue) const {
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000669 return HII->getCondOpcode(Opc, !IfTrue);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000670}
671
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000672void HexagonEarlyIfConversion::predicateInstr(MachineBasicBlock *ToB,
673 MachineBasicBlock::iterator At, MachineInstr *MI,
674 unsigned PredR, bool IfTrue) {
675 DebugLoc DL;
676 if (At != ToB->end())
677 DL = At->getDebugLoc();
678 else if (!ToB->empty())
679 DL = ToB->back().getDebugLoc();
680
681 unsigned Opc = MI->getOpcode();
682
683 if (isPredicableStore(MI)) {
684 unsigned COpc = getCondStoreOpcode(Opc, IfTrue);
685 assert(COpc);
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000686 MachineInstrBuilder MIB = BuildMI(*ToB, At, DL, HII->get(COpc));
Matthias Braunfc371552016-10-24 21:36:43 +0000687 MachineInstr::mop_iterator MOI = MI->operands_begin();
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +0000688 if (HII->isPostIncrement(*MI)) {
Diana Picus116bbab2017-01-13 09:58:52 +0000689 MIB.add(*MOI);
Matthias Braunfc371552016-10-24 21:36:43 +0000690 ++MOI;
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000691 }
692 MIB.addReg(PredR);
Matthias Braunfc371552016-10-24 21:36:43 +0000693 for (const MachineOperand &MO : make_range(MOI, MI->operands_end()))
Diana Picus116bbab2017-01-13 09:58:52 +0000694 MIB.add(MO);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000695
696 // Set memory references.
697 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
698 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
699 MIB.setMemRefs(MMOBegin, MMOEnd);
700
701 MI->eraseFromParent();
702 return;
703 }
704
705 if (Opc == Hexagon::J2_jump) {
706 MachineBasicBlock *TB = MI->getOperand(0).getMBB();
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000707 const MCInstrDesc &D = HII->get(IfTrue ? Hexagon::J2_jumpt
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000708 : Hexagon::J2_jumpf);
709 BuildMI(*ToB, At, DL, D)
710 .addReg(PredR)
711 .addMBB(TB);
712 MI->eraseFromParent();
713 return;
714 }
715
716 // Print the offending instruction unconditionally as we are about to
717 // abort.
718 dbgs() << *MI;
719 llvm_unreachable("Unexpected instruction");
720}
721
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000722// Predicate/speculate non-branch instructions from FromB into block ToB.
723// Leave the branches alone, they will be handled later. Btw, at this point
724// FromB should have at most one branch, and it should be unconditional.
725void HexagonEarlyIfConversion::predicateBlockNB(MachineBasicBlock *ToB,
726 MachineBasicBlock::iterator At, MachineBasicBlock *FromB,
727 unsigned PredR, bool IfTrue) {
728 DEBUG(dbgs() << "Predicating block " << PrintMB(FromB) << "\n");
729 MachineBasicBlock::iterator End = FromB->getFirstTerminator();
730 MachineBasicBlock::iterator I, NextI;
731
732 for (I = FromB->begin(); I != End; I = NextI) {
733 assert(!I->isPHI());
734 NextI = std::next(I);
735 if (isSafeToSpeculate(&*I))
736 ToB->splice(At, FromB, I);
737 else
738 predicateInstr(ToB, At, &*I, PredR, IfTrue);
739 }
740}
741
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000742void HexagonEarlyIfConversion::updatePhiNodes(MachineBasicBlock *WhereB,
743 const FlowPattern &FP) {
744 // Visit all PHI nodes in the WhereB block and generate MUX instructions
745 // in the split block. Update the PHI nodes with the values of the MUX.
746 auto NonPHI = WhereB->getFirstNonPHI();
747 for (auto I = WhereB->begin(); I != NonPHI; ++I) {
748 MachineInstr *PN = &*I;
749 // Registers and subregisters corresponding to TrueB, FalseB and SplitB.
750 unsigned TR = 0, TSR = 0, FR = 0, FSR = 0, SR = 0, SSR = 0;
751 for (int i = PN->getNumOperands()-2; i > 0; i -= 2) {
752 const MachineOperand &RO = PN->getOperand(i), &BO = PN->getOperand(i+1);
753 if (BO.getMBB() == FP.SplitB)
754 SR = RO.getReg(), SSR = RO.getSubReg();
755 else if (BO.getMBB() == FP.TrueB)
756 TR = RO.getReg(), TSR = RO.getSubReg();
757 else if (BO.getMBB() == FP.FalseB)
758 FR = RO.getReg(), FSR = RO.getSubReg();
759 else
760 continue;
761 PN->RemoveOperand(i+1);
762 PN->RemoveOperand(i);
763 }
764 if (TR == 0)
765 TR = SR, TSR = SSR;
766 else if (FR == 0)
767 FR = SR, FSR = SSR;
768 assert(TR && FR);
769
770 using namespace Hexagon;
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000771
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000772 unsigned DR = PN->getOperand(0).getReg();
773 const TargetRegisterClass *RC = MRI->getRegClass(DR);
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000774 unsigned Opc = 0;
775 if (RC == &IntRegsRegClass)
776 Opc = C2_mux;
777 else if (RC == &DoubleRegsRegClass)
Krzysztof Parzyszek258af192016-08-11 19:12:18 +0000778 Opc = PS_pselect;
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000779 else if (RC == &VectorRegsRegClass)
Krzysztof Parzyszek258af192016-08-11 19:12:18 +0000780 Opc = PS_vselect;
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000781 else if (RC == &VecDblRegsRegClass)
Krzysztof Parzyszek258af192016-08-11 19:12:18 +0000782 Opc = PS_wselect;
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000783 else if (RC == &VectorRegs128BRegClass)
Krzysztof Parzyszek258af192016-08-11 19:12:18 +0000784 Opc = PS_vselect_128B;
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000785 else if (RC == &VecDblRegs128BRegClass)
Krzysztof Parzyszek258af192016-08-11 19:12:18 +0000786 Opc = PS_wselect_128B;
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000787 else
788 llvm_unreachable("unexpected register type");
789 const MCInstrDesc &D = HII->get(Opc);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000790
791 MachineBasicBlock::iterator MuxAt = FP.SplitB->getFirstTerminator();
792 DebugLoc DL;
793 if (MuxAt != FP.SplitB->end())
794 DL = MuxAt->getDebugLoc();
795 unsigned MuxR = MRI->createVirtualRegister(RC);
796 BuildMI(*FP.SplitB, MuxAt, DL, D, MuxR)
797 .addReg(FP.PredR)
798 .addReg(TR, 0, TSR)
799 .addReg(FR, 0, FSR);
800
801 PN->addOperand(MachineOperand::CreateReg(MuxR, false));
802 PN->addOperand(MachineOperand::CreateMBB(FP.SplitB));
803 }
804}
805
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000806void HexagonEarlyIfConversion::convert(const FlowPattern &FP) {
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000807 MachineBasicBlock *TSB = nullptr, *FSB = nullptr;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000808 MachineBasicBlock::iterator OldTI = FP.SplitB->getFirstTerminator();
809 assert(OldTI != FP.SplitB->end());
810 DebugLoc DL = OldTI->getDebugLoc();
811
812 if (FP.TrueB) {
813 TSB = *FP.TrueB->succ_begin();
814 predicateBlockNB(FP.SplitB, OldTI, FP.TrueB, FP.PredR, true);
815 }
816 if (FP.FalseB) {
817 FSB = *FP.FalseB->succ_begin();
818 MachineBasicBlock::iterator At = FP.SplitB->getFirstTerminator();
819 predicateBlockNB(FP.SplitB, At, FP.FalseB, FP.PredR, false);
820 }
821
822 // Regenerate new terminators in the split block and update the successors.
823 // First, remember any information that may be needed later and remove the
824 // existing terminators/successors from the split block.
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000825 MachineBasicBlock *SSB = nullptr;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000826 FP.SplitB->erase(OldTI, FP.SplitB->end());
827 while (FP.SplitB->succ_size() > 0) {
828 MachineBasicBlock *T = *FP.SplitB->succ_begin();
829 // It's possible that the split block had a successor that is not a pre-
830 // dicated block. This could only happen if there was only one block to
831 // be predicated. Example:
832 // split_b:
833 // if (p) jump true_b
834 // jump unrelated2_b
835 // unrelated1_b:
836 // ...
837 // unrelated2_b: ; can have other predecessors, so it's not "false_b"
838 // jump other_b
839 // true_b: ; only reachable from split_b, can be predicated
840 // ...
841 //
842 // Find this successor (SSB) if it exists.
843 if (T != FP.TrueB && T != FP.FalseB) {
844 assert(!SSB);
845 SSB = T;
846 }
847 FP.SplitB->removeSuccessor(FP.SplitB->succ_begin());
848 }
849
850 // Insert new branches and update the successors of the split block. This
851 // may create unconditional branches to the layout successor, etc., but
852 // that will be cleaned up later. For now, make sure that correct code is
853 // generated.
854 if (FP.JoinB) {
855 assert(!SSB || SSB == FP.JoinB);
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000856 BuildMI(*FP.SplitB, FP.SplitB->end(), DL, HII->get(Hexagon::J2_jump))
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000857 .addMBB(FP.JoinB);
858 FP.SplitB->addSuccessor(FP.JoinB);
859 } else {
860 bool HasBranch = false;
861 if (TSB) {
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000862 BuildMI(*FP.SplitB, FP.SplitB->end(), DL, HII->get(Hexagon::J2_jumpt))
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000863 .addReg(FP.PredR)
864 .addMBB(TSB);
865 FP.SplitB->addSuccessor(TSB);
866 HasBranch = true;
867 }
868 if (FSB) {
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000869 const MCInstrDesc &D = HasBranch ? HII->get(Hexagon::J2_jump)
870 : HII->get(Hexagon::J2_jumpf);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000871 MachineInstrBuilder MIB = BuildMI(*FP.SplitB, FP.SplitB->end(), DL, D);
872 if (!HasBranch)
873 MIB.addReg(FP.PredR);
874 MIB.addMBB(FSB);
875 FP.SplitB->addSuccessor(FSB);
876 }
877 if (SSB) {
878 // This cannot happen if both TSB and FSB are set. [TF]SB are the
879 // successor blocks of the TrueB and FalseB (or null of the TrueB
880 // or FalseB block is null). SSB is the potential successor block
881 // of the SplitB that is neither TrueB nor FalseB.
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000882 BuildMI(*FP.SplitB, FP.SplitB->end(), DL, HII->get(Hexagon::J2_jump))
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000883 .addMBB(SSB);
884 FP.SplitB->addSuccessor(SSB);
885 }
886 }
887
888 // What is left to do is to update the PHI nodes that could have entries
889 // referring to predicated blocks.
890 if (FP.JoinB) {
891 updatePhiNodes(FP.JoinB, FP);
892 } else {
893 if (TSB)
894 updatePhiNodes(TSB, FP);
895 if (FSB)
896 updatePhiNodes(FSB, FP);
897 // Nothing to update in SSB, since SSB's predecessors haven't changed.
898 }
899}
900
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000901void HexagonEarlyIfConversion::removeBlock(MachineBasicBlock *B) {
902 DEBUG(dbgs() << "Removing block " << PrintMB(B) << "\n");
903
904 // Transfer the immediate dominator information from B to its descendants.
905 MachineDomTreeNode *N = MDT->getNode(B);
906 MachineDomTreeNode *IDN = N->getIDom();
907 if (IDN) {
908 MachineBasicBlock *IDB = IDN->getBlock();
909 typedef GraphTraits<MachineDomTreeNode*> GTN;
910 typedef SmallVector<MachineDomTreeNode*,4> DTNodeVectType;
911 DTNodeVectType Cn(GTN::child_begin(N), GTN::child_end(N));
912 for (DTNodeVectType::iterator I = Cn.begin(), E = Cn.end(); I != E; ++I) {
913 MachineBasicBlock *SB = (*I)->getBlock();
914 MDT->changeImmediateDominator(SB, IDB);
915 }
916 }
917
918 while (B->succ_size() > 0)
919 B->removeSuccessor(B->succ_begin());
920
921 for (auto I = B->pred_begin(), E = B->pred_end(); I != E; ++I)
Cong Houc1069892015-12-13 09:26:17 +0000922 (*I)->removeSuccessor(B, true);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000923
924 Deleted.insert(B);
925 MDT->eraseNode(B);
Duncan P. N. Exon Smitha72c6e22015-10-20 00:46:39 +0000926 MFN->erase(B->getIterator());
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000927}
928
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000929void HexagonEarlyIfConversion::eliminatePhis(MachineBasicBlock *B) {
930 DEBUG(dbgs() << "Removing phi nodes from block " << PrintMB(B) << "\n");
931 MachineBasicBlock::iterator I, NextI, NonPHI = B->getFirstNonPHI();
932 for (I = B->begin(); I != NonPHI; I = NextI) {
933 NextI = std::next(I);
934 MachineInstr *PN = &*I;
935 assert(PN->getNumOperands() == 3 && "Invalid phi node");
936 MachineOperand &UO = PN->getOperand(1);
937 unsigned UseR = UO.getReg(), UseSR = UO.getSubReg();
938 unsigned DefR = PN->getOperand(0).getReg();
939 unsigned NewR = UseR;
940 if (UseSR) {
941 // MRI.replaceVregUsesWith does not allow to update the subregister,
942 // so instead of doing the use-iteration here, create a copy into a
943 // "non-subregistered" register.
Benjamin Kramer4ca41fd2016-06-12 17:30:47 +0000944 const DebugLoc &DL = PN->getDebugLoc();
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000945 const TargetRegisterClass *RC = MRI->getRegClass(DefR);
946 NewR = MRI->createVirtualRegister(RC);
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000947 NonPHI = BuildMI(*B, NonPHI, DL, HII->get(TargetOpcode::COPY), NewR)
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000948 .addReg(UseR, 0, UseSR);
949 }
950 MRI->replaceRegWith(DefR, NewR);
951 B->erase(I);
952 }
953}
954
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000955void HexagonEarlyIfConversion::replacePhiEdges(MachineBasicBlock *OldB,
956 MachineBasicBlock *NewB) {
957 for (auto I = OldB->succ_begin(), E = OldB->succ_end(); I != E; ++I) {
958 MachineBasicBlock *SB = *I;
959 MachineBasicBlock::iterator P, N = SB->getFirstNonPHI();
960 for (P = SB->begin(); P != N; ++P) {
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +0000961 MachineInstr &PN = *P;
Matthias Braunfc371552016-10-24 21:36:43 +0000962 for (MachineOperand &MO : PN.operands())
963 if (MO.isMBB() && MO.getMBB() == OldB)
964 MO.setMBB(NewB);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000965 }
966 }
967}
968
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000969void HexagonEarlyIfConversion::mergeBlocks(MachineBasicBlock *PredB,
970 MachineBasicBlock *SuccB) {
971 DEBUG(dbgs() << "Merging blocks " << PrintMB(PredB) << " and "
972 << PrintMB(SuccB) << "\n");
973 bool TermOk = hasUncondBranch(SuccB);
974 eliminatePhis(SuccB);
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000975 HII->removeBranch(*PredB);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000976 PredB->removeSuccessor(SuccB);
977 PredB->splice(PredB->end(), SuccB, SuccB->begin(), SuccB->end());
978 MachineBasicBlock::succ_iterator I, E = SuccB->succ_end();
979 for (I = SuccB->succ_begin(); I != E; ++I)
980 PredB->addSuccessor(*I);
Cong Houc1069892015-12-13 09:26:17 +0000981 PredB->normalizeSuccProbs();
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000982 replacePhiEdges(SuccB, PredB);
983 removeBlock(SuccB);
984 if (!TermOk)
985 PredB->updateTerminator();
986}
987
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000988void HexagonEarlyIfConversion::simplifyFlowGraph(const FlowPattern &FP) {
989 if (FP.TrueB)
990 removeBlock(FP.TrueB);
991 if (FP.FalseB)
992 removeBlock(FP.FalseB);
993
994 FP.SplitB->updateTerminator();
995 if (FP.SplitB->succ_size() != 1)
996 return;
997
998 MachineBasicBlock *SB = *FP.SplitB->succ_begin();
999 if (SB->pred_size() != 1)
1000 return;
1001
1002 // By now, the split block has only one successor (SB), and SB has only
1003 // one predecessor. We can try to merge them. We will need to update ter-
1004 // minators in FP.Split+SB, and that requires working AnalyzeBranch, which
1005 // fails on Hexagon for blocks that have EH_LABELs. However, if SB ends
1006 // with an unconditional branch, we won't need to touch the terminators.
1007 if (!hasEHLabel(SB) || hasUncondBranch(SB))
1008 mergeBlocks(FP.SplitB, SB);
1009}
1010
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +00001011bool HexagonEarlyIfConversion::runOnMachineFunction(MachineFunction &MF) {
Andrew Kaylor5b444a22016-04-26 19:46:28 +00001012 if (skipFunction(*MF.getFunction()))
1013 return false;
1014
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +00001015 auto &ST = MF.getSubtarget<HexagonSubtarget>();
1016 HII = ST.getInstrInfo();
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +00001017 TRI = ST.getRegisterInfo();
1018 MFN = &MF;
1019 MRI = &MF.getRegInfo();
1020 MDT = &getAnalysis<MachineDominatorTree>();
1021 MLI = &getAnalysis<MachineLoopInfo>();
1022 MBPI = EnableHexagonBP ? &getAnalysis<MachineBranchProbabilityInfo>() :
1023 nullptr;
1024
1025 Deleted.clear();
1026 bool Changed = false;
1027
1028 for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end(); I != E; ++I)
1029 Changed |= visitLoop(*I);
Eugene Zelenkof9f8c682016-12-14 22:50:46 +00001030 Changed |= visitLoop(nullptr);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +00001031
1032 return Changed;
1033}
1034
1035//===----------------------------------------------------------------------===//
1036// Public Constructor Functions
1037//===----------------------------------------------------------------------===//
1038FunctionPass *llvm::createHexagonEarlyIfConversion() {
1039 return new HexagonEarlyIfConversion();
1040}