1 //===--- HexagonEarlyIfConv.cpp -------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements a Hexagon-specific if-conversion pass that runs on the
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-
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.
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)
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
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)
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
55 // %vreg46<def> = PS_pselect %vreg41, %vreg6, %vreg11
56 // %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
62 #define DEBUG_TYPE "hexagon-eif"
65 #include "HexagonInstrInfo.h"
66 #include "HexagonSubtarget.h"
67 #include "llvm/ADT/DenseSet.h"
68 #include "llvm/ADT/iterator_range.h"
69 #include "llvm/ADT/SmallVector.h"
70 #include "llvm/ADT/StringRef.h"
71 #include "llvm/CodeGen/MachineBasicBlock.h"
72 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
73 #include "llvm/CodeGen/MachineDominators.h"
74 #include "llvm/CodeGen/MachineFunction.h"
75 #include "llvm/CodeGen/MachineFunctionPass.h"
76 #include "llvm/CodeGen/MachineInstr.h"
77 #include "llvm/CodeGen/MachineInstrBuilder.h"
78 #include "llvm/CodeGen/MachineLoopInfo.h"
79 #include "llvm/CodeGen/MachineOperand.h"
80 #include "llvm/CodeGen/MachineRegisterInfo.h"
81 #include "llvm/IR/DebugLoc.h"
82 #include "llvm/Pass.h"
83 #include "llvm/Support/BranchProbability.h"
84 #include "llvm/Support/CommandLine.h"
85 #include "llvm/Support/Compiler.h"
86 #include "llvm/Support/Debug.h"
87 #include "llvm/Support/ErrorHandling.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Target/TargetRegisterInfo.h"
97 FunctionPass *createHexagonEarlyIfConversion();
98 void initializeHexagonEarlyIfConversionPass(PassRegistry& Registry);
100 } // end namespace llvm
104 cl::opt<bool> EnableHexagonBP("enable-hexagon-br-prob", cl::Hidden,
105 cl::init(false), cl::desc("Enable branch probability info"));
106 cl::opt<unsigned> SizeLimit("eif-limit", cl::init(6), cl::Hidden,
107 cl::desc("Size limit in Hexagon early if-conversion"));
108 cl::opt<bool> SkipExitBranches("eif-no-loop-exit", cl::init(false),
109 cl::Hidden, cl::desc("Do not convert branches that may exit the loop"));
112 PrintMB(const MachineBasicBlock *B) : MB(B) {}
113 const MachineBasicBlock *MB;
115 raw_ostream &operator<< (raw_ostream &OS, const PrintMB &P) {
117 return OS << "<none>";
118 return OS << '#' << P.MB->getNumber();
122 FlowPattern() = default;
123 FlowPattern(MachineBasicBlock *B, unsigned PR, MachineBasicBlock *TB,
124 MachineBasicBlock *FB, MachineBasicBlock *JB)
125 : SplitB(B), TrueB(TB), FalseB(FB), JoinB(JB), PredR(PR) {}
127 MachineBasicBlock *SplitB = nullptr;
128 MachineBasicBlock *TrueB = nullptr;
129 MachineBasicBlock *FalseB = nullptr;
130 MachineBasicBlock *JoinB = nullptr;
135 PrintFP(const FlowPattern &P, const TargetRegisterInfo &T)
138 const FlowPattern &FP;
139 const TargetRegisterInfo &TRI;
140 friend raw_ostream &operator<< (raw_ostream &OS, const PrintFP &P);
142 raw_ostream &operator<<(raw_ostream &OS,
143 const PrintFP &P) LLVM_ATTRIBUTE_UNUSED;
144 raw_ostream &operator<<(raw_ostream &OS, const PrintFP &P) {
145 OS << "{ SplitB:" << PrintMB(P.FP.SplitB)
146 << ", PredR:" << PrintReg(P.FP.PredR, &P.TRI)
147 << ", TrueB:" << PrintMB(P.FP.TrueB)
148 << ", FalseB:" << PrintMB(P.FP.FalseB)
149 << ", JoinB:" << PrintMB(P.FP.JoinB) << " }";
153 class HexagonEarlyIfConversion : public MachineFunctionPass {
157 HexagonEarlyIfConversion() : MachineFunctionPass(ID),
158 HII(nullptr), TRI(nullptr), MFN(nullptr), MRI(nullptr), MDT(nullptr),
160 initializeHexagonEarlyIfConversionPass(*PassRegistry::getPassRegistry());
163 StringRef getPassName() const override {
164 return "Hexagon early if conversion";
167 void getAnalysisUsage(AnalysisUsage &AU) const override {
168 AU.addRequired<MachineBranchProbabilityInfo>();
169 AU.addRequired<MachineDominatorTree>();
170 AU.addPreserved<MachineDominatorTree>();
171 AU.addRequired<MachineLoopInfo>();
172 MachineFunctionPass::getAnalysisUsage(AU);
175 bool runOnMachineFunction(MachineFunction &MF) override;
178 typedef DenseSet<MachineBasicBlock*> BlockSetType;
180 bool isPreheader(const MachineBasicBlock *B) const;
181 bool matchFlowPattern(MachineBasicBlock *B, MachineLoop *L,
183 bool visitBlock(MachineBasicBlock *B, MachineLoop *L);
184 bool visitLoop(MachineLoop *L);
186 bool hasEHLabel(const MachineBasicBlock *B) const;
187 bool hasUncondBranch(const MachineBasicBlock *B) const;
188 bool isValidCandidate(const MachineBasicBlock *B) const;
189 bool usesUndefVReg(const MachineInstr *MI) const;
190 bool isValid(const FlowPattern &FP) const;
191 unsigned countPredicateDefs(const MachineBasicBlock *B) const;
192 unsigned computePhiCost(const MachineBasicBlock *B,
193 const FlowPattern &FP) const;
194 bool isProfitable(const FlowPattern &FP) const;
195 bool isPredicableStore(const MachineInstr *MI) const;
196 bool isSafeToSpeculate(const MachineInstr *MI) const;
198 unsigned getCondStoreOpcode(unsigned Opc, bool IfTrue) const;
199 void predicateInstr(MachineBasicBlock *ToB, MachineBasicBlock::iterator At,
200 MachineInstr *MI, unsigned PredR, bool IfTrue);
201 void predicateBlockNB(MachineBasicBlock *ToB,
202 MachineBasicBlock::iterator At, MachineBasicBlock *FromB,
203 unsigned PredR, bool IfTrue);
205 unsigned buildMux(MachineBasicBlock *B, MachineBasicBlock::iterator At,
206 const TargetRegisterClass *DRC, unsigned PredR, unsigned TR,
207 unsigned TSR, unsigned FR, unsigned FSR);
208 void updatePhiNodes(MachineBasicBlock *WhereB, const FlowPattern &FP);
209 void convert(const FlowPattern &FP);
211 void removeBlock(MachineBasicBlock *B);
212 void eliminatePhis(MachineBasicBlock *B);
213 void replacePhiEdges(MachineBasicBlock *OldB, MachineBasicBlock *NewB);
214 void mergeBlocks(MachineBasicBlock *PredB, MachineBasicBlock *SuccB);
215 void simplifyFlowGraph(const FlowPattern &FP);
217 const HexagonInstrInfo *HII;
218 const TargetRegisterInfo *TRI;
219 MachineFunction *MFN;
220 MachineRegisterInfo *MRI;
221 MachineDominatorTree *MDT;
222 MachineLoopInfo *MLI;
223 BlockSetType Deleted;
224 const MachineBranchProbabilityInfo *MBPI;
227 char HexagonEarlyIfConversion::ID = 0;
229 } // end anonymous namespace
231 INITIALIZE_PASS(HexagonEarlyIfConversion, "hexagon-eif",
232 "Hexagon early if conversion", false, false)
234 bool HexagonEarlyIfConversion::isPreheader(const MachineBasicBlock *B) const {
235 if (B->succ_size() != 1)
237 MachineBasicBlock *SB = *B->succ_begin();
238 MachineLoop *L = MLI->getLoopFor(SB);
239 return L && SB == L->getHeader() && MDT->dominates(B, SB);
242 bool HexagonEarlyIfConversion::matchFlowPattern(MachineBasicBlock *B,
243 MachineLoop *L, FlowPattern &FP) {
244 DEBUG(dbgs() << "Checking flow pattern at BB#" << B->getNumber() << "\n");
246 // Interested only in conditional branches, no .new, no new-value, etc.
247 // Check the terminators directly, it's easier than handling all responses
248 // from AnalyzeBranch.
249 MachineBasicBlock *TB = nullptr, *FB = nullptr;
250 MachineBasicBlock::const_iterator T1I = B->getFirstTerminator();
253 unsigned Opc = T1I->getOpcode();
254 if (Opc != Hexagon::J2_jumpt && Opc != Hexagon::J2_jumpf)
256 unsigned PredR = T1I->getOperand(0).getReg();
258 // Get the layout successor, or 0 if B does not have one.
259 MachineFunction::iterator NextBI = std::next(MachineFunction::iterator(B));
260 MachineBasicBlock *NextB = (NextBI != MFN->end()) ? &*NextBI : nullptr;
262 MachineBasicBlock *T1B = T1I->getOperand(1).getMBB();
263 MachineBasicBlock::const_iterator T2I = std::next(T1I);
264 // The second terminator should be an unconditional branch.
265 assert(T2I == B->end() || T2I->getOpcode() == Hexagon::J2_jump);
266 MachineBasicBlock *T2B = (T2I == B->end()) ? NextB
267 : T2I->getOperand(0).getMBB();
269 // XXX merge if T1B == NextB, or convert branch to unconditional.
270 // mark as diamond with both sides equal?
274 // Record the true/false blocks in such a way that "true" means "if (PredR)",
275 // and "false" means "if (!PredR)".
276 if (Opc == Hexagon::J2_jumpt)
281 if (!MDT->properlyDominates(B, TB) || !MDT->properlyDominates(B, FB))
284 // Detect triangle first. In case of a triangle, one of the blocks TB/FB
285 // can fall through into the other, in other words, it will be executed
286 // in both cases. We only want to predicate the block that is executed
288 unsigned TNP = TB->pred_size(), FNP = FB->pred_size();
289 unsigned TNS = TB->succ_size(), FNS = FB->succ_size();
291 // A block is predicable if it has one predecessor (it must be B), and
292 // it has a single successor. In fact, the block has to end either with
293 // an unconditional branch (which can be predicated), or with a fall-
295 // Also, skip blocks that do not belong to the same loop.
296 bool TOk = (TNP == 1 && TNS == 1 && MLI->getLoopFor(TB) == L);
297 bool FOk = (FNP == 1 && FNS == 1 && MLI->getLoopFor(FB) == L);
299 // If requested (via an option), do not consider branches where the
300 // true and false targets do not belong to the same loop.
301 if (SkipExitBranches && MLI->getLoopFor(TB) != MLI->getLoopFor(FB))
304 // If neither is predicable, there is nothing interesting.
308 MachineBasicBlock *TSB = (TNS > 0) ? *TB->succ_begin() : nullptr;
309 MachineBasicBlock *FSB = (FNS > 0) ? *FB->succ_begin() : nullptr;
310 MachineBasicBlock *JB = nullptr;
316 // Diamond: "if (P) then TB; else FB;".
324 // !TOk && FOk (at least one must be true by now).
329 // Don't try to predicate loop preheaders.
330 if ((TB && isPreheader(TB)) || (FB && isPreheader(FB))) {
331 DEBUG(dbgs() << "One of blocks " << PrintMB(TB) << ", " << PrintMB(FB)
332 << " is a loop preheader. Skipping.\n");
336 FP = FlowPattern(B, PredR, TB, FB, JB);
337 DEBUG(dbgs() << "Detected " << PrintFP(FP, *TRI) << "\n");
341 // KLUDGE: HexagonInstrInfo::AnalyzeBranch won't work on a block that
342 // contains EH_LABEL.
343 bool HexagonEarlyIfConversion::hasEHLabel(const MachineBasicBlock *B) const {
350 // KLUDGE: HexagonInstrInfo::AnalyzeBranch may be unable to recognize
351 // that a block can never fall-through.
352 bool HexagonEarlyIfConversion::hasUncondBranch(const MachineBasicBlock *B)
354 MachineBasicBlock::const_iterator I = B->getFirstTerminator(), E = B->end();
363 bool HexagonEarlyIfConversion::isValidCandidate(const MachineBasicBlock *B)
367 if (B->isEHPad() || B->hasAddressTaken())
369 if (B->succ_size() == 0)
372 for (auto &MI : *B) {
373 if (MI.isDebugValue())
375 if (MI.isConditionalBranch())
377 unsigned Opc = MI.getOpcode();
378 bool IsJMP = (Opc == Hexagon::J2_jump);
379 if (!isPredicableStore(&MI) && !IsJMP && !isSafeToSpeculate(&MI))
381 // Look for predicate registers defined by this instruction. It's ok
382 // to speculate such an instruction, but the predicate register cannot
383 // be used outside of this block (or else it won't be possible to
384 // update the use of it after predication). PHI uses will be updated
385 // to use a result of a MUX, and a MUX cannot be created for predicate
387 for (const MachineOperand &MO : MI.operands()) {
388 if (!MO.isReg() || !MO.isDef())
390 unsigned R = MO.getReg();
391 if (!TargetRegisterInfo::isVirtualRegister(R))
393 switch (MRI->getRegClass(R)->getID()) {
394 case Hexagon::PredRegsRegClassID:
395 case Hexagon::VecPredRegsRegClassID:
396 case Hexagon::VecPredRegs128BRegClassID:
401 for (auto U = MRI->use_begin(R); U != MRI->use_end(); ++U)
402 if (U->getParent()->isPHI())
409 bool HexagonEarlyIfConversion::usesUndefVReg(const MachineInstr *MI) const {
410 for (const MachineOperand &MO : MI->operands()) {
411 if (!MO.isReg() || !MO.isUse())
413 unsigned R = MO.getReg();
414 if (!TargetRegisterInfo::isVirtualRegister(R))
416 const MachineInstr *DefI = MRI->getVRegDef(R);
417 // "Undefined" virtual registers are actually defined via IMPLICIT_DEF.
418 assert(DefI && "Expecting a reaching def in MRI");
419 if (DefI->isImplicitDef())
425 bool HexagonEarlyIfConversion::isValid(const FlowPattern &FP) const {
426 if (hasEHLabel(FP.SplitB)) // KLUDGE: see function definition
428 if (FP.TrueB && !isValidCandidate(FP.TrueB))
430 if (FP.FalseB && !isValidCandidate(FP.FalseB))
432 // Check the PHIs in the join block. If any of them use a register
433 // that is defined as IMPLICIT_DEF, do not convert this. This can
434 // legitimately happen if one side of the split never executes, but
435 // the compiler is unable to prove it. That side may then seem to
436 // provide an "undef" value to the join block, however it will never
437 // execute at run-time. If we convert this case, the "undef" will
438 // be used in a MUX instruction, and that may seem like actually
439 // using an undefined value to other optimizations. This could lead
440 // to trouble further down the optimization stream, cause assertions
443 const MachineBasicBlock &B = *FP.JoinB;
447 if (usesUndefVReg(&MI))
449 unsigned DefR = MI.getOperand(0).getReg();
450 const TargetRegisterClass *RC = MRI->getRegClass(DefR);
451 if (RC == &Hexagon::PredRegsRegClass)
458 unsigned HexagonEarlyIfConversion::computePhiCost(const MachineBasicBlock *B,
459 const FlowPattern &FP) const {
460 if (B->pred_size() < 2)
464 for (const MachineInstr &MI : *B) {
467 // If both incoming blocks are one of the TrueB/FalseB/SplitB, then
468 // a MUX may be needed. Otherwise the PHI will need to be updated at
470 // Find the interesting PHI operands for further checks.
471 SmallVector<unsigned,2> Inc;
472 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
473 const MachineBasicBlock *BB = MI.getOperand(i+1).getMBB();
474 if (BB == FP.SplitB || BB == FP.TrueB || BB == FP.FalseB)
477 assert(Inc.size() <= 2);
481 const MachineOperand &RA = MI.getOperand(1);
482 const MachineOperand &RB = MI.getOperand(3);
483 assert(RA.isReg() && RB.isReg());
484 // Must have a MUX if the phi uses a subregister.
485 if (RA.getSubReg() != 0 || RB.getSubReg() != 0) {
489 const MachineInstr *Def1 = MRI->getVRegDef(RA.getReg());
490 const MachineInstr *Def3 = MRI->getVRegDef(RB.getReg());
491 if (!HII->isPredicable(*Def1) || !HII->isPredicable(*Def3))
497 unsigned HexagonEarlyIfConversion::countPredicateDefs(
498 const MachineBasicBlock *B) const {
499 unsigned PredDefs = 0;
500 for (auto &MI : *B) {
501 for (const MachineOperand &MO : MI.operands()) {
502 if (!MO.isReg() || !MO.isDef())
504 unsigned R = MO.getReg();
505 if (!TargetRegisterInfo::isVirtualRegister(R))
507 if (MRI->getRegClass(R) == &Hexagon::PredRegsRegClass)
514 bool HexagonEarlyIfConversion::isProfitable(const FlowPattern &FP) const {
515 if (FP.TrueB && FP.FalseB) {
516 // Do not IfCovert if the branch is one sided.
518 BranchProbability Prob(9, 10);
519 if (MBPI->getEdgeProbability(FP.SplitB, FP.TrueB) > Prob)
521 if (MBPI->getEdgeProbability(FP.SplitB, FP.FalseB) > Prob)
525 // If both sides are predicable, convert them if they join, and the
526 // join block has no other predecessors.
527 MachineBasicBlock *TSB = *FP.TrueB->succ_begin();
528 MachineBasicBlock *FSB = *FP.FalseB->succ_begin();
531 if (TSB->pred_size() != 2)
535 // Calculate the total size of the predicated blocks.
536 // Assume instruction counts without branches to be the approximation of
537 // the code size. If the predicated blocks are smaller than a packet size,
538 // approximate the spare room in the packet that could be filled with the
539 // predicated/speculated instructions.
540 auto TotalCount = [] (const MachineBasicBlock *B, unsigned &Spare) {
543 unsigned T = std::distance(B->begin(), B->getFirstTerminator());
544 if (T < HEXAGON_PACKET_SIZE)
545 Spare += HEXAGON_PACKET_SIZE-T;
549 unsigned TotalIn = TotalCount(FP.TrueB, Spare) + TotalCount(FP.FalseB, Spare);
550 DEBUG(dbgs() << "Total number of instructions to be predicated/speculated: "
551 << TotalIn << ", spare room: " << Spare << "\n");
552 if (TotalIn >= SizeLimit+Spare)
555 // Count the number of PHI nodes that will need to be updated (converted
556 // to MUX). Those can be later converted to predicated instructions, so
557 // they aren't always adding extra cost.
558 // KLUDGE: Also, count the number of predicate register definitions in
559 // each block. The scheduler may increase the pressure of these and cause
560 // expensive spills (e.g. bitmnp01).
561 unsigned TotalPh = 0;
562 unsigned PredDefs = countPredicateDefs(FP.SplitB);
564 TotalPh = computePhiCost(FP.JoinB, FP);
565 PredDefs += countPredicateDefs(FP.JoinB);
567 if (FP.TrueB && FP.TrueB->succ_size() > 0) {
568 MachineBasicBlock *SB = *FP.TrueB->succ_begin();
569 TotalPh += computePhiCost(SB, FP);
570 PredDefs += countPredicateDefs(SB);
572 if (FP.FalseB && FP.FalseB->succ_size() > 0) {
573 MachineBasicBlock *SB = *FP.FalseB->succ_begin();
574 TotalPh += computePhiCost(SB, FP);
575 PredDefs += countPredicateDefs(SB);
578 DEBUG(dbgs() << "Total number of extra muxes from converted phis: "
580 if (TotalIn+TotalPh >= SizeLimit+Spare)
583 DEBUG(dbgs() << "Total number of predicate registers: " << PredDefs << "\n");
590 bool HexagonEarlyIfConversion::visitBlock(MachineBasicBlock *B,
592 bool Changed = false;
594 // Visit all dominated blocks from the same loop first, then process B.
595 MachineDomTreeNode *N = MDT->getNode(B);
596 typedef GraphTraits<MachineDomTreeNode*> GTN;
597 // We will change CFG/DT during this traversal, so take precautions to
598 // avoid problems related to invalidated iterators. In fact, processing
599 // a child C of B cannot cause another child to be removed, but it can
600 // cause a new child to be added (which was a child of C before C itself
601 // was removed. This new child C, however, would have been processed
602 // prior to processing B, so there is no need to process it again.
603 // Simply keep a list of children of B, and traverse that list.
604 typedef SmallVector<MachineDomTreeNode*,4> DTNodeVectType;
605 DTNodeVectType Cn(GTN::child_begin(N), GTN::child_end(N));
606 for (DTNodeVectType::iterator I = Cn.begin(), E = Cn.end(); I != E; ++I) {
607 MachineBasicBlock *SB = (*I)->getBlock();
608 if (!Deleted.count(SB))
609 Changed |= visitBlock(SB, L);
611 // When walking down the dominator tree, we want to traverse through
612 // blocks from nested (other) loops, because they can dominate blocks
613 // that are in L. Skip the non-L blocks only after the tree traversal.
614 if (MLI->getLoopFor(B) != L)
618 if (!matchFlowPattern(B, L, FP))
622 DEBUG(dbgs() << "Conversion is not valid\n");
625 if (!isProfitable(FP)) {
626 DEBUG(dbgs() << "Conversion is not profitable\n");
631 simplifyFlowGraph(FP);
635 bool HexagonEarlyIfConversion::visitLoop(MachineLoop *L) {
636 MachineBasicBlock *HB = L ? L->getHeader() : nullptr;
637 DEBUG((L ? dbgs() << "Visiting loop H:" << PrintMB(HB)
638 : dbgs() << "Visiting function") << "\n");
639 bool Changed = false;
641 for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
642 Changed |= visitLoop(*I);
645 MachineBasicBlock *EntryB = GraphTraits<MachineFunction*>::getEntryNode(MFN);
646 Changed |= visitBlock(L ? HB : EntryB, L);
650 bool HexagonEarlyIfConversion::isPredicableStore(const MachineInstr *MI)
652 // HexagonInstrInfo::isPredicable will consider these stores are non-
653 // -predicable if the offset would become constant-extended after
655 unsigned Opc = MI->getOpcode();
657 case Hexagon::S2_storerb_io:
658 case Hexagon::S2_storerbnew_io:
659 case Hexagon::S2_storerh_io:
660 case Hexagon::S2_storerhnew_io:
661 case Hexagon::S2_storeri_io:
662 case Hexagon::S2_storerinew_io:
663 case Hexagon::S2_storerd_io:
664 case Hexagon::S4_storeirb_io:
665 case Hexagon::S4_storeirh_io:
666 case Hexagon::S4_storeiri_io:
670 // TargetInstrInfo::isPredicable takes a non-const pointer.
671 return MI->mayStore() && HII->isPredicable(const_cast<MachineInstr&>(*MI));
674 bool HexagonEarlyIfConversion::isSafeToSpeculate(const MachineInstr *MI)
676 if (MI->mayLoad() || MI->mayStore())
678 if (MI->isCall() || MI->isBarrier() || MI->isBranch())
680 if (MI->hasUnmodeledSideEffects())
686 unsigned HexagonEarlyIfConversion::getCondStoreOpcode(unsigned Opc,
688 return HII->getCondOpcode(Opc, !IfTrue);
691 void HexagonEarlyIfConversion::predicateInstr(MachineBasicBlock *ToB,
692 MachineBasicBlock::iterator At, MachineInstr *MI,
693 unsigned PredR, bool IfTrue) {
695 if (At != ToB->end())
696 DL = At->getDebugLoc();
697 else if (!ToB->empty())
698 DL = ToB->back().getDebugLoc();
700 unsigned Opc = MI->getOpcode();
702 if (isPredicableStore(MI)) {
703 unsigned COpc = getCondStoreOpcode(Opc, IfTrue);
705 MachineInstrBuilder MIB = BuildMI(*ToB, At, DL, HII->get(COpc));
706 MachineInstr::mop_iterator MOI = MI->operands_begin();
707 if (HII->isPostIncrement(*MI)) {
712 for (const MachineOperand &MO : make_range(MOI, MI->operands_end()))
715 // Set memory references.
716 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
717 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
718 MIB.setMemRefs(MMOBegin, MMOEnd);
720 MI->eraseFromParent();
724 if (Opc == Hexagon::J2_jump) {
725 MachineBasicBlock *TB = MI->getOperand(0).getMBB();
726 const MCInstrDesc &D = HII->get(IfTrue ? Hexagon::J2_jumpt
727 : Hexagon::J2_jumpf);
728 BuildMI(*ToB, At, DL, D)
731 MI->eraseFromParent();
735 // Print the offending instruction unconditionally as we are about to
738 llvm_unreachable("Unexpected instruction");
741 // Predicate/speculate non-branch instructions from FromB into block ToB.
742 // Leave the branches alone, they will be handled later. Btw, at this point
743 // FromB should have at most one branch, and it should be unconditional.
744 void HexagonEarlyIfConversion::predicateBlockNB(MachineBasicBlock *ToB,
745 MachineBasicBlock::iterator At, MachineBasicBlock *FromB,
746 unsigned PredR, bool IfTrue) {
747 DEBUG(dbgs() << "Predicating block " << PrintMB(FromB) << "\n");
748 MachineBasicBlock::iterator End = FromB->getFirstTerminator();
749 MachineBasicBlock::iterator I, NextI;
751 for (I = FromB->begin(); I != End; I = NextI) {
753 NextI = std::next(I);
754 if (isSafeToSpeculate(&*I))
755 ToB->splice(At, FromB, I);
757 predicateInstr(ToB, At, &*I, PredR, IfTrue);
761 unsigned HexagonEarlyIfConversion::buildMux(MachineBasicBlock *B,
762 MachineBasicBlock::iterator At, const TargetRegisterClass *DRC,
763 unsigned PredR, unsigned TR, unsigned TSR, unsigned FR, unsigned FSR) {
765 switch (DRC->getID()) {
766 case Hexagon::IntRegsRegClassID:
767 Opc = Hexagon::C2_mux;
769 case Hexagon::DoubleRegsRegClassID:
770 Opc = Hexagon::PS_pselect;
772 case Hexagon::VectorRegsRegClassID:
773 Opc = Hexagon::PS_vselect;
775 case Hexagon::VecDblRegsRegClassID:
776 Opc = Hexagon::PS_wselect;
778 case Hexagon::VectorRegs128BRegClassID:
779 Opc = Hexagon::PS_vselect_128B;
781 case Hexagon::VecDblRegs128BRegClassID:
782 Opc = Hexagon::PS_wselect_128B;
785 llvm_unreachable("unexpected register type");
787 const MCInstrDesc &D = HII->get(Opc);
789 DebugLoc DL = B->findBranchDebugLoc();
790 unsigned MuxR = MRI->createVirtualRegister(DRC);
791 BuildMI(*B, At, DL, D, MuxR)
798 void HexagonEarlyIfConversion::updatePhiNodes(MachineBasicBlock *WhereB,
799 const FlowPattern &FP) {
800 // Visit all PHI nodes in the WhereB block and generate MUX instructions
801 // in the split block. Update the PHI nodes with the values of the MUX.
802 auto NonPHI = WhereB->getFirstNonPHI();
803 for (auto I = WhereB->begin(); I != NonPHI; ++I) {
804 MachineInstr *PN = &*I;
805 // Registers and subregisters corresponding to TrueB, FalseB and SplitB.
806 unsigned TR = 0, TSR = 0, FR = 0, FSR = 0, SR = 0, SSR = 0;
807 for (int i = PN->getNumOperands()-2; i > 0; i -= 2) {
808 const MachineOperand &RO = PN->getOperand(i), &BO = PN->getOperand(i+1);
809 if (BO.getMBB() == FP.SplitB)
810 SR = RO.getReg(), SSR = RO.getSubReg();
811 else if (BO.getMBB() == FP.TrueB)
812 TR = RO.getReg(), TSR = RO.getSubReg();
813 else if (BO.getMBB() == FP.FalseB)
814 FR = RO.getReg(), FSR = RO.getSubReg();
817 PN->RemoveOperand(i+1);
818 PN->RemoveOperand(i);
826 unsigned MuxR = 0, MuxSR = 0;
829 unsigned DR = PN->getOperand(0).getReg();
830 const TargetRegisterClass *RC = MRI->getRegClass(DR);
831 MuxR = buildMux(FP.SplitB, FP.SplitB->getFirstTerminator(), RC,
832 FP.PredR, TR, TSR, FR, FSR);
841 PN->addOperand(MachineOperand::CreateReg(MuxR, false, false, false, false,
842 false, false, MuxSR));
843 PN->addOperand(MachineOperand::CreateMBB(FP.SplitB));
847 void HexagonEarlyIfConversion::convert(const FlowPattern &FP) {
848 MachineBasicBlock *TSB = nullptr, *FSB = nullptr;
849 MachineBasicBlock::iterator OldTI = FP.SplitB->getFirstTerminator();
850 assert(OldTI != FP.SplitB->end());
851 DebugLoc DL = OldTI->getDebugLoc();
854 TSB = *FP.TrueB->succ_begin();
855 predicateBlockNB(FP.SplitB, OldTI, FP.TrueB, FP.PredR, true);
858 FSB = *FP.FalseB->succ_begin();
859 MachineBasicBlock::iterator At = FP.SplitB->getFirstTerminator();
860 predicateBlockNB(FP.SplitB, At, FP.FalseB, FP.PredR, false);
863 // Regenerate new terminators in the split block and update the successors.
864 // First, remember any information that may be needed later and remove the
865 // existing terminators/successors from the split block.
866 MachineBasicBlock *SSB = nullptr;
867 FP.SplitB->erase(OldTI, FP.SplitB->end());
868 while (FP.SplitB->succ_size() > 0) {
869 MachineBasicBlock *T = *FP.SplitB->succ_begin();
870 // It's possible that the split block had a successor that is not a pre-
871 // dicated block. This could only happen if there was only one block to
872 // be predicated. Example:
874 // if (p) jump true_b
878 // unrelated2_b: ; can have other predecessors, so it's not "false_b"
880 // true_b: ; only reachable from split_b, can be predicated
883 // Find this successor (SSB) if it exists.
884 if (T != FP.TrueB && T != FP.FalseB) {
888 FP.SplitB->removeSuccessor(FP.SplitB->succ_begin());
891 // Insert new branches and update the successors of the split block. This
892 // may create unconditional branches to the layout successor, etc., but
893 // that will be cleaned up later. For now, make sure that correct code is
896 assert(!SSB || SSB == FP.JoinB);
897 BuildMI(*FP.SplitB, FP.SplitB->end(), DL, HII->get(Hexagon::J2_jump))
899 FP.SplitB->addSuccessor(FP.JoinB);
901 bool HasBranch = false;
903 BuildMI(*FP.SplitB, FP.SplitB->end(), DL, HII->get(Hexagon::J2_jumpt))
906 FP.SplitB->addSuccessor(TSB);
910 const MCInstrDesc &D = HasBranch ? HII->get(Hexagon::J2_jump)
911 : HII->get(Hexagon::J2_jumpf);
912 MachineInstrBuilder MIB = BuildMI(*FP.SplitB, FP.SplitB->end(), DL, D);
914 MIB.addReg(FP.PredR);
916 FP.SplitB->addSuccessor(FSB);
919 // This cannot happen if both TSB and FSB are set. [TF]SB are the
920 // successor blocks of the TrueB and FalseB (or null of the TrueB
921 // or FalseB block is null). SSB is the potential successor block
922 // of the SplitB that is neither TrueB nor FalseB.
923 BuildMI(*FP.SplitB, FP.SplitB->end(), DL, HII->get(Hexagon::J2_jump))
925 FP.SplitB->addSuccessor(SSB);
929 // What is left to do is to update the PHI nodes that could have entries
930 // referring to predicated blocks.
932 updatePhiNodes(FP.JoinB, FP);
935 updatePhiNodes(TSB, FP);
937 updatePhiNodes(FSB, FP);
938 // Nothing to update in SSB, since SSB's predecessors haven't changed.
942 void HexagonEarlyIfConversion::removeBlock(MachineBasicBlock *B) {
943 DEBUG(dbgs() << "Removing block " << PrintMB(B) << "\n");
945 // Transfer the immediate dominator information from B to its descendants.
946 MachineDomTreeNode *N = MDT->getNode(B);
947 MachineDomTreeNode *IDN = N->getIDom();
949 MachineBasicBlock *IDB = IDN->getBlock();
950 typedef GraphTraits<MachineDomTreeNode*> GTN;
951 typedef SmallVector<MachineDomTreeNode*,4> DTNodeVectType;
952 DTNodeVectType Cn(GTN::child_begin(N), GTN::child_end(N));
953 for (DTNodeVectType::iterator I = Cn.begin(), E = Cn.end(); I != E; ++I) {
954 MachineBasicBlock *SB = (*I)->getBlock();
955 MDT->changeImmediateDominator(SB, IDB);
959 while (B->succ_size() > 0)
960 B->removeSuccessor(B->succ_begin());
962 for (auto I = B->pred_begin(), E = B->pred_end(); I != E; ++I)
963 (*I)->removeSuccessor(B, true);
967 MFN->erase(B->getIterator());
970 void HexagonEarlyIfConversion::eliminatePhis(MachineBasicBlock *B) {
971 DEBUG(dbgs() << "Removing phi nodes from block " << PrintMB(B) << "\n");
972 MachineBasicBlock::iterator I, NextI, NonPHI = B->getFirstNonPHI();
973 for (I = B->begin(); I != NonPHI; I = NextI) {
974 NextI = std::next(I);
975 MachineInstr *PN = &*I;
976 assert(PN->getNumOperands() == 3 && "Invalid phi node");
977 MachineOperand &UO = PN->getOperand(1);
978 unsigned UseR = UO.getReg(), UseSR = UO.getSubReg();
979 unsigned DefR = PN->getOperand(0).getReg();
980 unsigned NewR = UseR;
982 // MRI.replaceVregUsesWith does not allow to update the subregister,
983 // so instead of doing the use-iteration here, create a copy into a
984 // "non-subregistered" register.
985 const DebugLoc &DL = PN->getDebugLoc();
986 const TargetRegisterClass *RC = MRI->getRegClass(DefR);
987 NewR = MRI->createVirtualRegister(RC);
988 NonPHI = BuildMI(*B, NonPHI, DL, HII->get(TargetOpcode::COPY), NewR)
989 .addReg(UseR, 0, UseSR);
991 MRI->replaceRegWith(DefR, NewR);
996 void HexagonEarlyIfConversion::replacePhiEdges(MachineBasicBlock *OldB,
997 MachineBasicBlock *NewB) {
998 for (auto I = OldB->succ_begin(), E = OldB->succ_end(); I != E; ++I) {
999 MachineBasicBlock *SB = *I;
1000 MachineBasicBlock::iterator P, N = SB->getFirstNonPHI();
1001 for (P = SB->begin(); P != N; ++P) {
1002 MachineInstr &PN = *P;
1003 for (MachineOperand &MO : PN.operands())
1004 if (MO.isMBB() && MO.getMBB() == OldB)
1010 void HexagonEarlyIfConversion::mergeBlocks(MachineBasicBlock *PredB,
1011 MachineBasicBlock *SuccB) {
1012 DEBUG(dbgs() << "Merging blocks " << PrintMB(PredB) << " and "
1013 << PrintMB(SuccB) << "\n");
1014 bool TermOk = hasUncondBranch(SuccB);
1015 eliminatePhis(SuccB);
1016 HII->removeBranch(*PredB);
1017 PredB->removeSuccessor(SuccB);
1018 PredB->splice(PredB->end(), SuccB, SuccB->begin(), SuccB->end());
1019 MachineBasicBlock::succ_iterator I, E = SuccB->succ_end();
1020 for (I = SuccB->succ_begin(); I != E; ++I)
1021 PredB->addSuccessor(*I);
1022 PredB->normalizeSuccProbs();
1023 replacePhiEdges(SuccB, PredB);
1026 PredB->updateTerminator();
1029 void HexagonEarlyIfConversion::simplifyFlowGraph(const FlowPattern &FP) {
1031 removeBlock(FP.TrueB);
1033 removeBlock(FP.FalseB);
1035 FP.SplitB->updateTerminator();
1036 if (FP.SplitB->succ_size() != 1)
1039 MachineBasicBlock *SB = *FP.SplitB->succ_begin();
1040 if (SB->pred_size() != 1)
1043 // By now, the split block has only one successor (SB), and SB has only
1044 // one predecessor. We can try to merge them. We will need to update ter-
1045 // minators in FP.Split+SB, and that requires working AnalyzeBranch, which
1046 // fails on Hexagon for blocks that have EH_LABELs. However, if SB ends
1047 // with an unconditional branch, we won't need to touch the terminators.
1048 if (!hasEHLabel(SB) || hasUncondBranch(SB))
1049 mergeBlocks(FP.SplitB, SB);
1052 bool HexagonEarlyIfConversion::runOnMachineFunction(MachineFunction &MF) {
1053 if (skipFunction(*MF.getFunction()))
1056 auto &ST = MF.getSubtarget<HexagonSubtarget>();
1057 HII = ST.getInstrInfo();
1058 TRI = ST.getRegisterInfo();
1060 MRI = &MF.getRegInfo();
1061 MDT = &getAnalysis<MachineDominatorTree>();
1062 MLI = &getAnalysis<MachineLoopInfo>();
1063 MBPI = EnableHexagonBP ? &getAnalysis<MachineBranchProbabilityInfo>() :
1067 bool Changed = false;
1069 for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end(); I != E; ++I)
1070 Changed |= visitLoop(*I);
1071 Changed |= visitLoop(nullptr);
1076 //===----------------------------------------------------------------------===//
1077 // Public Constructor Functions
1078 //===----------------------------------------------------------------------===//
1079 FunctionPass *llvm::createHexagonEarlyIfConversion() {
1080 return new HexagonEarlyIfConversion();