Detemplatize LOHDirective.
[oota-llvm.git] / lib / Target / ARM64 / ARM64AdvSIMDScalarPass.cpp
1 //===-- ARM64AdvSIMDScalar.cpp - Replace dead defs w/ zero reg --===//
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 // When profitable, replace GPR targeting i64 instructions with their
10 // AdvSIMD scalar equivalents. Generally speaking, "profitable" is defined
11 // as minimizing the number of cross-class register copies.
12 //===----------------------------------------------------------------------===//
13
14 //===----------------------------------------------------------------------===//
15 // TODO: Graph based predicate heuristics.
16 // Walking the instruction list linearly will get many, perhaps most, of
17 // the cases, but to do a truly throrough job of this, we need a more
18 // wholistic approach.
19 //
20 // This optimization is very similar in spirit to the register allocator's
21 // spill placement, only here we're determining where to place cross-class
22 // register copies rather than spills. As such, a similar approach is
23 // called for.
24 //
25 // We want to build up a set of graphs of all instructions which are candidates
26 // for transformation along with instructions which generate their inputs and
27 // consume their outputs. For each edge in the graph, we assign a weight
28 // based on whether there is a copy required there (weight zero if not) and
29 // the block frequency of the block containing the defining or using
30 // instruction, whichever is less. Our optimization is then a graph problem
31 // to minimize the total weight of all the graphs, then transform instructions
32 // and add or remove copy instructions as called for to implement the
33 // solution.
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "arm64-simd-scalar"
37 #include "ARM64.h"
38 #include "ARM64InstrInfo.h"
39 #include "ARM64RegisterInfo.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/CodeGen/MachineFunctionPass.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineRegisterInfo.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/raw_ostream.h"
49 using namespace llvm;
50
51 static cl::opt<bool>
52 AdvSIMDScalar("arm64-simd-scalar",
53               cl::desc("enable use of AdvSIMD scalar integer instructions"),
54               cl::init(false), cl::Hidden);
55 // Allow forcing all i64 operations with equivalent SIMD instructions to use
56 // them. For stress-testing the transformation function.
57 static cl::opt<bool>
58 TransformAll("arm64-simd-scalar-force-all",
59              cl::desc("Force use of AdvSIMD scalar instructions everywhere"),
60              cl::init(false), cl::Hidden);
61
62 STATISTIC(NumScalarInsnsUsed, "Number of scalar instructions used");
63 STATISTIC(NumCopiesDeleted, "Number of cross-class copies deleted");
64 STATISTIC(NumCopiesInserted, "Number of cross-class copies inserted");
65
66 namespace {
67 class ARM64AdvSIMDScalar : public MachineFunctionPass {
68   MachineRegisterInfo *MRI;
69   const ARM64InstrInfo *TII;
70
71 private:
72   // isProfitableToTransform - Predicate function to determine whether an
73   // instruction should be transformed to its equivalent AdvSIMD scalar
74   // instruction. "add Xd, Xn, Xm" ==> "add Dd, Da, Db", for example.
75   bool isProfitableToTransform(const MachineInstr *MI) const;
76
77   // tranformInstruction - Perform the transformation of an instruction
78   // to its equivalant AdvSIMD scalar instruction. Update inputs and outputs
79   // to be the correct register class, minimizing cross-class copies.
80   void transformInstruction(MachineInstr *MI);
81
82   // processMachineBasicBlock - Main optimzation loop.
83   bool processMachineBasicBlock(MachineBasicBlock *MBB);
84
85 public:
86   static char ID; // Pass identification, replacement for typeid.
87   explicit ARM64AdvSIMDScalar() : MachineFunctionPass(ID) {}
88
89   virtual bool runOnMachineFunction(MachineFunction &F);
90
91   const char *getPassName() const {
92     return "AdvSIMD scalar operation optimization";
93   }
94
95   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
96     AU.setPreservesCFG();
97     MachineFunctionPass::getAnalysisUsage(AU);
98   }
99 };
100 char ARM64AdvSIMDScalar::ID = 0;
101 } // end anonymous namespace
102
103 static bool isGPR64(unsigned Reg, unsigned SubReg,
104                     const MachineRegisterInfo *MRI) {
105   if (SubReg)
106     return false;
107   if (TargetRegisterInfo::isVirtualRegister(Reg))
108     return MRI->getRegClass(Reg)->hasSuperClassEq(&ARM64::GPR64RegClass);
109   return ARM64::GPR64RegClass.contains(Reg);
110 }
111
112 static bool isFPR64(unsigned Reg, unsigned SubReg,
113                     const MachineRegisterInfo *MRI) {
114   if (TargetRegisterInfo::isVirtualRegister(Reg))
115     return (MRI->getRegClass(Reg)->hasSuperClassEq(&ARM64::FPR64RegClass) &&
116             SubReg == 0) ||
117            (MRI->getRegClass(Reg)->hasSuperClassEq(&ARM64::FPR128RegClass) &&
118             SubReg == ARM64::dsub);
119   // Physical register references just check the regist class directly.
120   return (ARM64::FPR64RegClass.contains(Reg) && SubReg == 0) ||
121          (ARM64::FPR128RegClass.contains(Reg) && SubReg == ARM64::dsub);
122 }
123
124 // getSrcFromCopy - Get the original source register for a GPR64 <--> FPR64
125 // copy instruction. Return zero_reg if the instruction is not a copy.
126 static unsigned getSrcFromCopy(const MachineInstr *MI,
127                                const MachineRegisterInfo *MRI,
128                                unsigned &SubReg) {
129   SubReg = 0;
130   // The "FMOV Xd, Dn" instruction is the typical form.
131   if (MI->getOpcode() == ARM64::FMOVDXr || MI->getOpcode() == ARM64::FMOVXDr)
132     return MI->getOperand(1).getReg();
133   // A lane zero extract "UMOV.d Xd, Vn[0]" is equivalent. We shouldn't see
134   // these at this stage, but it's easy to check for.
135   if (MI->getOpcode() == ARM64::UMOVvi64 && MI->getOperand(2).getImm() == 0) {
136     SubReg = ARM64::dsub;
137     return MI->getOperand(1).getReg();
138   }
139   // Or just a plain COPY instruction. This can be directly to/from FPR64,
140   // or it can be a dsub subreg reference to an FPR128.
141   if (MI->getOpcode() == ARM64::COPY) {
142     if (isFPR64(MI->getOperand(0).getReg(), MI->getOperand(0).getSubReg(),
143                 MRI) &&
144         isGPR64(MI->getOperand(1).getReg(), MI->getOperand(1).getSubReg(), MRI))
145       return MI->getOperand(1).getReg();
146     if (isGPR64(MI->getOperand(0).getReg(), MI->getOperand(0).getSubReg(),
147                 MRI) &&
148         isFPR64(MI->getOperand(1).getReg(), MI->getOperand(1).getSubReg(),
149                 MRI)) {
150       SubReg = ARM64::dsub;
151       return MI->getOperand(1).getReg();
152     }
153   }
154
155   // Otherwise, this is some other kind of instruction.
156   return 0;
157 }
158
159 // getTransformOpcode - For any opcode for which there is an AdvSIMD equivalent
160 // that we're considering transforming to, return that AdvSIMD opcode. For all
161 // others, return the original opcode.
162 static int getTransformOpcode(unsigned Opc) {
163   switch (Opc) {
164   default:
165     break;
166   // FIXME: Lots more possibilities.
167   case ARM64::ADDXrr:
168     return ARM64::ADDv1i64;
169   case ARM64::SUBXrr:
170     return ARM64::SUBv1i64;
171   }
172   // No AdvSIMD equivalent, so just return the original opcode.
173   return Opc;
174 }
175
176 static bool isTransformable(const MachineInstr *MI) {
177   int Opc = MI->getOpcode();
178   return Opc != getTransformOpcode(Opc);
179 }
180
181 // isProfitableToTransform - Predicate function to determine whether an
182 // instruction should be transformed to its equivalent AdvSIMD scalar
183 // instruction. "add Xd, Xn, Xm" ==> "add Dd, Da, Db", for example.
184 bool ARM64AdvSIMDScalar::isProfitableToTransform(const MachineInstr *MI) const {
185   // If this instruction isn't eligible to be transformed (no SIMD equivalent),
186   // early exit since that's the common case.
187   if (!isTransformable(MI))
188     return false;
189
190   // Count the number of copies we'll need to add and approximate the number
191   // of copies that a transform will enable us to remove.
192   unsigned NumNewCopies = 3;
193   unsigned NumRemovableCopies = 0;
194
195   unsigned OrigSrc0 = MI->getOperand(1).getReg();
196   unsigned OrigSrc1 = MI->getOperand(2).getReg();
197   unsigned Src0 = 0, SubReg0;
198   unsigned Src1 = 0, SubReg1;
199   if (!MRI->def_empty(OrigSrc0)) {
200     MachineRegisterInfo::def_instr_iterator Def =
201         MRI->def_instr_begin(OrigSrc0);
202     assert(std::next(Def) == MRI->def_instr_end() && "Multiple def in SSA!");
203     Src0 = getSrcFromCopy(&*Def, MRI, SubReg0);
204     // If the source was from a copy, we don't need to insert a new copy.
205     if (Src0)
206       --NumNewCopies;
207     // If there are no other users of the original source, we can delete
208     // that instruction.
209     if (Src0 && MRI->hasOneNonDBGUse(OrigSrc0))
210       ++NumRemovableCopies;
211   }
212   if (!MRI->def_empty(OrigSrc1)) {
213     MachineRegisterInfo::def_instr_iterator Def =
214         MRI->def_instr_begin(OrigSrc1);
215     assert(std::next(Def) == MRI->def_instr_end() && "Multiple def in SSA!");
216     Src1 = getSrcFromCopy(&*Def, MRI, SubReg1);
217     if (Src1)
218       --NumNewCopies;
219     // If there are no other users of the original source, we can delete
220     // that instruction.
221     if (Src1 && MRI->hasOneNonDBGUse(OrigSrc1))
222       ++NumRemovableCopies;
223   }
224
225   // If any of the uses of the original instructions is a cross class copy,
226   // that's a copy that will be removable if we transform. Likewise, if
227   // any of the uses is a transformable instruction, it's likely the tranforms
228   // will chain, enabling us to save a copy there, too. This is an aggressive
229   // heuristic that approximates the graph based cost analysis described above.
230   unsigned Dst = MI->getOperand(0).getReg();
231   bool AllUsesAreCopies = true;
232   for (MachineRegisterInfo::use_instr_nodbg_iterator
233            Use = MRI->use_instr_nodbg_begin(Dst),
234            E = MRI->use_instr_nodbg_end();
235        Use != E; ++Use) {
236     unsigned SubReg;
237     if (getSrcFromCopy(&*Use, MRI, SubReg) || isTransformable(&*Use))
238       ++NumRemovableCopies;
239     // If the use is an INSERT_SUBREG, that's still something that can
240     // directly use the FPR64, so we don't invalidate AllUsesAreCopies. It's
241     // preferable to have it use the FPR64 in most cases, as if the source
242     // vector is an IMPLICIT_DEF, the INSERT_SUBREG just goes away entirely.
243     // Ditto for a lane insert.
244     else if (Use->getOpcode() == ARM64::INSERT_SUBREG ||
245              Use->getOpcode() == ARM64::INSvi64gpr)
246       ;
247     else
248       AllUsesAreCopies = false;
249   }
250   // If all of the uses of the original destination register are copies to
251   // FPR64, then we won't end up having a new copy back to GPR64 either.
252   if (AllUsesAreCopies)
253     --NumNewCopies;
254
255   // If a tranform will not increase the number of cross-class copies required,
256   // return true.
257   if (NumNewCopies <= NumRemovableCopies)
258     return true;
259
260   // Finally, even if we otherwise wouldn't transform, check if we're forcing
261   // transformation of everything.
262   return TransformAll;
263 }
264
265 static MachineInstr *insertCopy(const ARM64InstrInfo *TII, MachineInstr *MI,
266                                 unsigned Dst, unsigned Src, bool IsKill) {
267   MachineInstrBuilder MIB =
268       BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII->get(ARM64::COPY),
269               Dst)
270           .addReg(Src, getKillRegState(IsKill));
271   DEBUG(dbgs() << "    adding copy: " << *MIB);
272   ++NumCopiesInserted;
273   return MIB;
274 }
275
276 // tranformInstruction - Perform the transformation of an instruction
277 // to its equivalant AdvSIMD scalar instruction. Update inputs and outputs
278 // to be the correct register class, minimizing cross-class copies.
279 void ARM64AdvSIMDScalar::transformInstruction(MachineInstr *MI) {
280   DEBUG(dbgs() << "Scalar transform: " << *MI);
281
282   MachineBasicBlock *MBB = MI->getParent();
283   int OldOpc = MI->getOpcode();
284   int NewOpc = getTransformOpcode(OldOpc);
285   assert(OldOpc != NewOpc && "transform an instruction to itself?!");
286
287   // Check if we need a copy for the source registers.
288   unsigned OrigSrc0 = MI->getOperand(1).getReg();
289   unsigned OrigSrc1 = MI->getOperand(2).getReg();
290   unsigned Src0 = 0, SubReg0;
291   unsigned Src1 = 0, SubReg1;
292   if (!MRI->def_empty(OrigSrc0)) {
293     MachineRegisterInfo::def_instr_iterator Def =
294         MRI->def_instr_begin(OrigSrc0);
295     assert(std::next(Def) == MRI->def_instr_end() && "Multiple def in SSA!");
296     Src0 = getSrcFromCopy(&*Def, MRI, SubReg0);
297     // If there are no other users of the original source, we can delete
298     // that instruction.
299     if (Src0 && MRI->hasOneNonDBGUse(OrigSrc0)) {
300       assert(Src0 && "Can't delete copy w/o a valid original source!");
301       Def->eraseFromParent();
302       ++NumCopiesDeleted;
303     }
304   }
305   if (!MRI->def_empty(OrigSrc1)) {
306     MachineRegisterInfo::def_instr_iterator Def =
307         MRI->def_instr_begin(OrigSrc1);
308     assert(std::next(Def) == MRI->def_instr_end() && "Multiple def in SSA!");
309     Src1 = getSrcFromCopy(&*Def, MRI, SubReg1);
310     // If there are no other users of the original source, we can delete
311     // that instruction.
312     if (Src1 && MRI->hasOneNonDBGUse(OrigSrc1)) {
313       assert(Src1 && "Can't delete copy w/o a valid original source!");
314       Def->eraseFromParent();
315       ++NumCopiesDeleted;
316     }
317   }
318   // If we weren't able to reference the original source directly, create a
319   // copy.
320   if (!Src0) {
321     SubReg0 = 0;
322     Src0 = MRI->createVirtualRegister(&ARM64::FPR64RegClass);
323     insertCopy(TII, MI, Src0, OrigSrc0, true);
324   }
325   if (!Src1) {
326     SubReg1 = 0;
327     Src1 = MRI->createVirtualRegister(&ARM64::FPR64RegClass);
328     insertCopy(TII, MI, Src1, OrigSrc1, true);
329   }
330
331   // Create a vreg for the destination.
332   // FIXME: No need to do this if the ultimate user expects an FPR64.
333   // Check for that and avoid the copy if possible.
334   unsigned Dst = MRI->createVirtualRegister(&ARM64::FPR64RegClass);
335
336   // For now, all of the new instructions have the same simple three-register
337   // form, so no need to special case based on what instruction we're
338   // building.
339   BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(NewOpc), Dst)
340       .addReg(Src0, getKillRegState(true), SubReg0)
341       .addReg(Src1, getKillRegState(true), SubReg1);
342
343   // Now copy the result back out to a GPR.
344   // FIXME: Try to avoid this if all uses could actually just use the FPR64
345   // directly.
346   insertCopy(TII, MI, MI->getOperand(0).getReg(), Dst, true);
347
348   // Erase the old instruction.
349   MI->eraseFromParent();
350
351   ++NumScalarInsnsUsed;
352 }
353
354 // processMachineBasicBlock - Main optimzation loop.
355 bool ARM64AdvSIMDScalar::processMachineBasicBlock(MachineBasicBlock *MBB) {
356   bool Changed = false;
357   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;) {
358     MachineInstr *MI = I;
359     ++I;
360     if (isProfitableToTransform(MI)) {
361       transformInstruction(MI);
362       Changed = true;
363     }
364   }
365   return Changed;
366 }
367
368 // runOnMachineFunction - Pass entry point from PassManager.
369 bool ARM64AdvSIMDScalar::runOnMachineFunction(MachineFunction &mf) {
370   // Early exit if pass disabled.
371   if (!AdvSIMDScalar)
372     return false;
373
374   bool Changed = false;
375   DEBUG(dbgs() << "***** ARM64AdvSIMDScalar *****\n");
376
377   const TargetMachine &TM = mf.getTarget();
378   MRI = &mf.getRegInfo();
379   TII = static_cast<const ARM64InstrInfo *>(TM.getInstrInfo());
380
381   // Just check things on a one-block-at-a-time basis.
382   for (MachineFunction::iterator I = mf.begin(), E = mf.end(); I != E; ++I)
383     if (processMachineBasicBlock(I))
384       Changed = true;
385   return Changed;
386 }
387
388 // createARM64AdvSIMDScalar - Factory function used by ARM64TargetMachine
389 // to add the pass to the PassManager.
390 FunctionPass *llvm::createARM64AdvSIMDScalar() {
391   return new ARM64AdvSIMDScalar();
392 }