1 //===- HexagonGenMux.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 // During instruction selection, MUX instructions are generated for
11 // conditional assignments. Since such assignments often present an
12 // opportunity to predicate instructions, HexagonExpandCondsets
13 // expands MUXes into pairs of conditional transfers, and then proceeds
14 // with predication of the producers/consumers of the registers involved.
15 // This happens after exiting from the SSA form, but before the machine
16 // instruction scheduler. After the scheduler and after the register
17 // allocation there can be cases of pairs of conditional transfers
18 // resulting from a MUX where neither of them was further predicated. If
19 // these transfers are now placed far enough from the instruction defining
20 // the predicate register, they cannot use the .new form. In such cases it
21 // is better to collapse them back to a single MUX instruction.
22 
23 #define DEBUG_TYPE "hexmux"
24 
25 #include "HexagonInstrInfo.h"
26 #include "HexagonRegisterInfo.h"
27 #include "HexagonSubtarget.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/CodeGen/LivePhysRegs.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineFunctionPass.h"
36 #include "llvm/CodeGen/MachineInstr.h"
37 #include "llvm/CodeGen/MachineInstrBuilder.h"
38 #include "llvm/CodeGen/MachineOperand.h"
39 #include "llvm/IR/DebugLoc.h"
40 #include "llvm/MC/MCInstrDesc.h"
41 #include "llvm/MC/MCRegisterInfo.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/MathExtras.h"
44 #include <algorithm>
45 #include <cassert>
46 #include <iterator>
47 #include <limits>
48 #include <utility>
49 
50 using namespace llvm;
51 
52 namespace llvm {
53 
54   FunctionPass *createHexagonGenMux();
55   void initializeHexagonGenMuxPass(PassRegistry& Registry);
56 
57 } // end namespace llvm
58 
59 namespace {
60 
61   class HexagonGenMux : public MachineFunctionPass {
62   public:
63     static char ID;
64 
65     HexagonGenMux() : MachineFunctionPass(ID) {}
66 
67     StringRef getPassName() const override {
68       return "Hexagon generate mux instructions";
69     }
70 
71     void getAnalysisUsage(AnalysisUsage &AU) const override {
72       MachineFunctionPass::getAnalysisUsage(AU);
73     }
74 
75     bool runOnMachineFunction(MachineFunction &MF) override;
76 
77     MachineFunctionProperties getRequiredProperties() const override {
78       return MachineFunctionProperties().set(
79           MachineFunctionProperties::Property::NoVRegs);
80     }
81 
82   private:
83     const HexagonInstrInfo *HII = nullptr;
84     const HexagonRegisterInfo *HRI = nullptr;
85 
86     struct CondsetInfo {
87       unsigned PredR = 0;
88       unsigned TrueX = std::numeric_limits<unsigned>::max();
89       unsigned FalseX = std::numeric_limits<unsigned>::max();
90 
91       CondsetInfo() = default;
92     };
93 
94     struct DefUseInfo {
95       BitVector Defs, Uses;
96 
97       DefUseInfo() = default;
98       DefUseInfo(const BitVector &D, const BitVector &U) : Defs(D), Uses(U) {}
99     };
100 
101     struct MuxInfo {
102       MachineBasicBlock::iterator At;
103       unsigned DefR, PredR;
104       MachineOperand *SrcT, *SrcF;
105       MachineInstr *Def1, *Def2;
106 
107       MuxInfo(MachineBasicBlock::iterator It, unsigned DR, unsigned PR,
108               MachineOperand *TOp, MachineOperand *FOp, MachineInstr &D1,
109               MachineInstr &D2)
110           : At(It), DefR(DR), PredR(PR), SrcT(TOp), SrcF(FOp), Def1(&D1),
111             Def2(&D2) {}
112     };
113 
114     using InstrIndexMap = DenseMap<MachineInstr *, unsigned>;
115     using DefUseInfoMap = DenseMap<unsigned, DefUseInfo>;
116     using MuxInfoList = SmallVector<MuxInfo, 4>;
117 
118     bool isRegPair(unsigned Reg) const {
119       return Hexagon::DoubleRegsRegClass.contains(Reg);
120     }
121 
122     void getSubRegs(unsigned Reg, BitVector &SRs) const;
123     void expandReg(unsigned Reg, BitVector &Set) const;
124     void getDefsUses(const MachineInstr *MI, BitVector &Defs,
125           BitVector &Uses) const;
126     void buildMaps(MachineBasicBlock &B, InstrIndexMap &I2X,
127           DefUseInfoMap &DUM);
128     bool isCondTransfer(unsigned Opc) const;
129     unsigned getMuxOpcode(const MachineOperand &Src1,
130           const MachineOperand &Src2) const;
131     bool genMuxInBlock(MachineBasicBlock &B);
132   };
133 
134 } // end anonymous namespace
135 
136 char HexagonGenMux::ID = 0;
137 
138 INITIALIZE_PASS(HexagonGenMux, "hexagon-gen-mux",
139   "Hexagon generate mux instructions", false, false)
140 
141 void HexagonGenMux::getSubRegs(unsigned Reg, BitVector &SRs) const {
142   for (MCSubRegIterator I(Reg, HRI); I.isValid(); ++I)
143     SRs[*I] = true;
144 }
145 
146 void HexagonGenMux::expandReg(unsigned Reg, BitVector &Set) const {
147   if (isRegPair(Reg))
148     getSubRegs(Reg, Set);
149   else
150     Set[Reg] = true;
151 }
152 
153 void HexagonGenMux::getDefsUses(const MachineInstr *MI, BitVector &Defs,
154       BitVector &Uses) const {
155   // First, get the implicit defs and uses for this instruction.
156   unsigned Opc = MI->getOpcode();
157   const MCInstrDesc &D = HII->get(Opc);
158   if (const MCPhysReg *R = D.ImplicitDefs)
159     while (*R)
160       expandReg(*R++, Defs);
161   if (const MCPhysReg *R = D.ImplicitUses)
162     while (*R)
163       expandReg(*R++, Uses);
164 
165   // Look over all operands, and collect explicit defs and uses.
166   for (const MachineOperand &MO : MI->operands()) {
167     if (!MO.isReg() || MO.isImplicit())
168       continue;
169     unsigned R = MO.getReg();
170     BitVector &Set = MO.isDef() ? Defs : Uses;
171     expandReg(R, Set);
172   }
173 }
174 
175 void HexagonGenMux::buildMaps(MachineBasicBlock &B, InstrIndexMap &I2X,
176       DefUseInfoMap &DUM) {
177   unsigned Index = 0;
178   unsigned NR = HRI->getNumRegs();
179   BitVector Defs(NR), Uses(NR);
180 
181   for (MachineBasicBlock::iterator I = B.begin(), E = B.end(); I != E; ++I) {
182     MachineInstr *MI = &*I;
183     I2X.insert(std::make_pair(MI, Index));
184     Defs.reset();
185     Uses.reset();
186     getDefsUses(MI, Defs, Uses);
187     DUM.insert(std::make_pair(Index, DefUseInfo(Defs, Uses)));
188     Index++;
189   }
190 }
191 
192 bool HexagonGenMux::isCondTransfer(unsigned Opc) const {
193   switch (Opc) {
194     case Hexagon::A2_tfrt:
195     case Hexagon::A2_tfrf:
196     case Hexagon::C2_cmoveit:
197     case Hexagon::C2_cmoveif:
198       return true;
199   }
200   return false;
201 }
202 
203 unsigned HexagonGenMux::getMuxOpcode(const MachineOperand &Src1,
204       const MachineOperand &Src2) const {
205   bool IsReg1 = Src1.isReg(), IsReg2 = Src2.isReg();
206   if (IsReg1)
207     return IsReg2 ? Hexagon::C2_mux : Hexagon::C2_muxir;
208   if (IsReg2)
209     return Hexagon::C2_muxri;
210 
211   // Neither is a register. The first source is extendable, but the second
212   // is not (s8).
213   if (Src2.isImm() && isInt<8>(Src2.getImm()))
214     return Hexagon::C2_muxii;
215 
216   return 0;
217 }
218 
219 bool HexagonGenMux::genMuxInBlock(MachineBasicBlock &B) {
220   bool Changed = false;
221   InstrIndexMap I2X;
222   DefUseInfoMap DUM;
223   buildMaps(B, I2X, DUM);
224 
225   using CondsetMap = DenseMap<unsigned, CondsetInfo>;
226 
227   CondsetMap CM;
228   MuxInfoList ML;
229 
230   MachineBasicBlock::iterator NextI, End = B.end();
231   for (MachineBasicBlock::iterator I = B.begin(); I != End; I = NextI) {
232     MachineInstr *MI = &*I;
233     NextI = std::next(I);
234     unsigned Opc = MI->getOpcode();
235     if (!isCondTransfer(Opc))
236       continue;
237     unsigned DR = MI->getOperand(0).getReg();
238     if (isRegPair(DR))
239       continue;
240     MachineOperand &PredOp = MI->getOperand(1);
241     if (PredOp.isUndef())
242       continue;
243 
244     unsigned PR = PredOp.getReg();
245     unsigned Idx = I2X.lookup(MI);
246     CondsetMap::iterator F = CM.find(DR);
247     bool IfTrue = HII->isPredicatedTrue(Opc);
248 
249     // If there is no record of a conditional transfer for this register,
250     // or the predicate register differs, create a new record for it.
251     if (F != CM.end() && F->second.PredR != PR) {
252       CM.erase(F);
253       F = CM.end();
254     }
255     if (F == CM.end()) {
256       auto It = CM.insert(std::make_pair(DR, CondsetInfo()));
257       F = It.first;
258       F->second.PredR = PR;
259     }
260     CondsetInfo &CI = F->second;
261     if (IfTrue)
262       CI.TrueX = Idx;
263     else
264       CI.FalseX = Idx;
265     if (CI.TrueX == std::numeric_limits<unsigned>::max() ||
266         CI.FalseX == std::numeric_limits<unsigned>::max())
267       continue;
268 
269     // There is now a complete definition of DR, i.e. we have the predicate
270     // register, the definition if-true, and definition if-false.
271 
272     // First, check if both definitions are far enough from the definition
273     // of the predicate register.
274     unsigned MinX = std::min(CI.TrueX, CI.FalseX);
275     unsigned MaxX = std::max(CI.TrueX, CI.FalseX);
276     unsigned SearchX = (MaxX > 4) ? MaxX-4 : 0;
277     bool NearDef = false;
278     for (unsigned X = SearchX; X < MaxX; ++X) {
279       const DefUseInfo &DU = DUM.lookup(X);
280       if (!DU.Defs[PR])
281         continue;
282       NearDef = true;
283       break;
284     }
285     if (NearDef)
286       continue;
287 
288     // The predicate register is not defined in the last few instructions.
289     // Check if the conversion to MUX is possible (either "up", i.e. at the
290     // place of the earlier partial definition, or "down", where the later
291     // definition is located). Examine all defs and uses between these two
292     // definitions.
293     // SR1, SR2 - source registers from the first and the second definition.
294     MachineBasicBlock::iterator It1 = B.begin(), It2 = B.begin();
295     std::advance(It1, MinX);
296     std::advance(It2, MaxX);
297     MachineInstr &Def1 = *It1, &Def2 = *It2;
298     MachineOperand *Src1 = &Def1.getOperand(2), *Src2 = &Def2.getOperand(2);
299     unsigned SR1 = Src1->isReg() ? Src1->getReg() : 0;
300     unsigned SR2 = Src2->isReg() ? Src2->getReg() : 0;
301     bool Failure = false, CanUp = true, CanDown = true;
302     for (unsigned X = MinX+1; X < MaxX; X++) {
303       const DefUseInfo &DU = DUM.lookup(X);
304       if (DU.Defs[PR] || DU.Defs[DR] || DU.Uses[DR]) {
305         Failure = true;
306         break;
307       }
308       if (CanDown && DU.Defs[SR1])
309         CanDown = false;
310       if (CanUp && DU.Defs[SR2])
311         CanUp = false;
312     }
313     if (Failure || (!CanUp && !CanDown))
314       continue;
315 
316     MachineOperand *SrcT = (MinX == CI.TrueX) ? Src1 : Src2;
317     MachineOperand *SrcF = (MinX == CI.FalseX) ? Src1 : Src2;
318     // Prefer "down", since this will move the MUX farther away from the
319     // predicate definition.
320     MachineBasicBlock::iterator At = CanDown ? Def2 : Def1;
321     ML.push_back(MuxInfo(At, DR, PR, SrcT, SrcF, Def1, Def2));
322   }
323 
324   for (MuxInfo &MX : ML) {
325     unsigned MxOpc = getMuxOpcode(*MX.SrcT, *MX.SrcF);
326     if (!MxOpc)
327       continue;
328     MachineBasicBlock &B = *MX.At->getParent();
329     const DebugLoc &DL = B.findDebugLoc(MX.At);
330     auto NewMux = BuildMI(B, MX.At, DL, HII->get(MxOpc), MX.DefR)
331                       .addReg(MX.PredR)
332                       .add(*MX.SrcT)
333                       .add(*MX.SrcF);
334     NewMux->clearKillInfo();
335     B.erase(MX.Def1);
336     B.erase(MX.Def2);
337     Changed = true;
338   }
339 
340   // Fix up kill flags.
341 
342   LivePhysRegs LPR(*HRI);
343   LPR.addLiveOuts(B);
344   auto IsLive = [&LPR,this] (unsigned Reg) -> bool {
345     for (MCSubRegIterator S(Reg, HRI, true); S.isValid(); ++S)
346       if (LPR.contains(*S))
347         return true;
348     return false;
349   };
350   for (auto I = B.rbegin(), E = B.rend(); I != E; ++I) {
351     if (I->isDebugValue())
352       continue;
353     // This isn't 100% accurate, but it's safe.
354     // It won't detect (as a kill) a case like this
355     //   r0 = add r0, 1    <-- r0 should be "killed"
356     //   ... = r0
357     for (MachineOperand &Op : I->operands()) {
358       if (!Op.isReg() || !Op.isUse())
359         continue;
360       assert(Op.getSubReg() == 0 && "Should have physical registers only");
361       bool Live = IsLive(Op.getReg());
362       Op.setIsKill(!Live);
363     }
364     LPR.stepBackward(*I);
365   }
366 
367   return Changed;
368 }
369 
370 bool HexagonGenMux::runOnMachineFunction(MachineFunction &MF) {
371   if (skipFunction(*MF.getFunction()))
372     return false;
373   HII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
374   HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
375   bool Changed = false;
376   for (auto &I : MF)
377     Changed |= genMuxInBlock(I);
378   return Changed;
379 }
380 
381 FunctionPass *llvm::createHexagonGenMux() {
382   return new HexagonGenMux();
383 }
384