Pass to replace tranfer/copy instructions into combine instruction where possible.
[oota-llvm.git] / lib / Target / Hexagon / HexagonCopyToCombine.cpp
1 //===------- HexagonCopyToCombine.cpp - Hexagon Copy-To-Combine Pass ------===//
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 // This pass replaces transfer instructions by combine instructions.
10 // We walk along a basic block and look for two combinable instructions and try
11 // to move them together. If we can move them next to each other we do so and
12 // replace them with a combine instruction.
13 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "hexagon-copy-combine"
15
16 #include "llvm/PassSupport.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27
28 #include "Hexagon.h"
29 #include "HexagonInstrInfo.h"
30 #include "HexagonRegisterInfo.h"
31 #include "HexagonSubtarget.h"
32 #include "HexagonTargetMachine.h"
33 #include "HexagonMachineFunctionInfo.h"
34
35 using namespace llvm;
36
37 static
38 cl::opt<bool> IsCombinesDisabled("disable-merge-into-combines",
39                                  cl::Hidden, cl::ZeroOrMore,
40                                  cl::init(false),
41                                  cl::desc("Disable merging into combines"));
42
43 namespace {
44
45 class HexagonCopyToCombine : public MachineFunctionPass  {
46   const HexagonInstrInfo *TII;
47   const TargetRegisterInfo *TRI;
48 public:
49   static char ID;
50
51   HexagonCopyToCombine() : MachineFunctionPass(ID) { }
52
53   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54     MachineFunctionPass::getAnalysisUsage(AU);
55   }
56
57   const char *getPassName() const {
58     return "Hexagon Copy-To-Combine Pass";
59   }
60
61   virtual bool runOnMachineFunction(MachineFunction &Fn);
62
63 private:
64   MachineInstr *findPairable(MachineInstr *I1, bool &DoInsertAtI1);
65
66   void combine(MachineInstr *I1, MachineInstr *I2,
67                MachineBasicBlock::iterator &MI, bool DoInsertAtI1);
68
69   bool isSafeToMoveTogether(MachineInstr *I1, MachineInstr *I2,
70                             unsigned I1DestReg, unsigned I2DestReg,
71                             bool &DoInsertAtI1);
72
73   void emitCombineRR(MachineBasicBlock::iterator &Before, unsigned DestReg,
74                      MachineOperand &HiOperand, MachineOperand &LoOperand);
75
76   void emitCombineRI(MachineBasicBlock::iterator &Before, unsigned DestReg,
77                      MachineOperand &HiOperand, MachineOperand &LoOperand);
78
79   void emitCombineIR(MachineBasicBlock::iterator &Before, unsigned DestReg,
80                      MachineOperand &HiOperand, MachineOperand &LoOperand);
81
82   void emitCombineII(MachineBasicBlock::iterator &Before, unsigned DestReg,
83                      MachineOperand &HiOperand, MachineOperand &LoOperand);
84 };
85
86 } // End anonymous namespace.
87
88 char HexagonCopyToCombine::ID = 0;
89
90 static bool isCombinableInstType(MachineInstr *MI,
91                                  const HexagonInstrInfo *TII) {
92   switch(MI->getOpcode()) {
93   case Hexagon::TFR: {
94     // A COPY instruction can be combined if its arguments are IntRegs (32bit).
95     assert(MI->getOperand(0).isReg() && MI->getOperand(1).isReg());
96
97     unsigned DestReg = MI->getOperand(0).getReg();
98     unsigned SrcReg = MI->getOperand(1).getReg();
99     return Hexagon::IntRegsRegClass.contains(DestReg) &&
100       Hexagon::IntRegsRegClass.contains(SrcReg);
101   }
102
103   case Hexagon::TFRI: {
104     // A transfer-immediate can be combined if its argument is a signed 8bit
105     // value.
106     assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm());
107     unsigned DestReg = MI->getOperand(0).getReg();
108     return Hexagon::IntRegsRegClass.contains(DestReg) &&
109       isInt<8>(MI->getOperand(1).getImm());
110   }
111   default:
112     break;
113   }
114
115   return false;
116 }
117
118
119 /// areCombinableOperations - Returns true if the two instruction can be merge
120 /// into a combine (ignoring register constraints).
121 static bool areCombinableOperations(const TargetRegisterInfo *TRI,
122                                     MachineInstr *I1, MachineInstr *I2) {
123   assert((I1->getOpcode() == Hexagon::TFR ||
124           I1->getOpcode() == Hexagon::TFRI) &&
125          (I2->getOpcode() == Hexagon::TFR ||
126           I2->getOpcode() == Hexagon::TFRI) &&
127          "Assume individual instructions are of a combinable type");
128
129   const HexagonRegisterInfo *QRI =
130     static_cast<const HexagonRegisterInfo *>(TRI);
131
132   // V4 added some combine variations (mixed immediate and register source
133   // operands), if we are on < V4 we can only combine 2 register-to-register
134   // moves and 2 immediate-to-register moves.
135   if (QRI->Subtarget.getHexagonArchVersion() < HexagonSubtarget::V4)
136     return I1->getOpcode() == I2->getOpcode();
137
138   return true;
139 }
140
141 static bool isEvenReg(unsigned Reg) {
142   assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
143          Hexagon::IntRegsRegClass.contains(Reg));
144   return (Reg - Hexagon::R0) % 2 == 0;
145 }
146
147 static void removeKillInfo(MachineInstr *MI, unsigned RegNotKilled) {
148   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
149     MachineOperand &Op = MI->getOperand(I);
150     if (!Op.isReg() || Op.getReg() != RegNotKilled || !Op.isKill())
151       continue;
152     Op.setIsKill(false);
153   }
154 }
155
156 /// isUnsafeToMoveAccross - Returns true if it is unsafe to move a copy
157 /// instruction from \p UseReg to \p DestReg over the instruction \p I.
158 bool isUnsafeToMoveAccross(MachineInstr *I, unsigned UseReg, unsigned DestReg,
159                             const TargetRegisterInfo *TRI) {
160   return (UseReg && (I->modifiesRegister(UseReg, TRI))) ||
161           I->modifiesRegister(DestReg, TRI) ||
162           I->readsRegister(DestReg, TRI) ||
163           I->hasUnmodeledSideEffects() ||
164           I->isInlineAsm() || I->isDebugValue();
165 }
166
167 /// isSafeToMoveTogether - Returns true if it is safe to move I1 next to I2 such
168 /// that the two instructions can be paired in a combine.
169 bool HexagonCopyToCombine::isSafeToMoveTogether(MachineInstr *I1,
170                                                 MachineInstr *I2,
171                                                 unsigned I1DestReg,
172                                                 unsigned I2DestReg,
173                                                 bool &DoInsertAtI1) {
174   bool isSafe = true;
175
176   // First try to move I2 towards I1.
177   {
178     // A reverse_iterator instantiated like below starts before I2, and I1
179     // respectively.
180     // Look at instructions I in between I2 and (including) I1.
181     MachineBasicBlock::reverse_iterator I(I2),
182       End = MachineBasicBlock::reverse_iterator(I1);
183     bool IsImmUseReg = I2->getOperand(1).isImm();
184     unsigned I2UseReg = IsImmUseReg ? 0 : I2->getOperand(1).getReg();
185
186     // If I2 kills its operand and we move I2 over an instruction that also
187     // uses I2's use reg we need to modify that (first) instruction to now kill
188     // this reg.
189     unsigned KilledOperand = 0;
190     if (I2->killsRegister(I2UseReg))
191       KilledOperand = I2UseReg;
192     MachineInstr *KillingInstr = 0;
193
194     for (; I != End; ++I) {
195       // If the intervening instruction I:
196       //   * modifies I2's use reg
197       //   * modifies I2's def reg
198       //   * reads I2's def reg
199       //   * or has unmodelled side effects
200       // we can't move I2 across it.
201       if (isUnsafeToMoveAccross(&*I, I2UseReg, I2DestReg, TRI)) {
202         isSafe = false;
203         break;
204       }
205
206       // Update first use of the killed operand.
207       if (!KillingInstr && KilledOperand &&
208           I->readsRegister(KilledOperand, TRI))
209         KillingInstr = &*I;
210     }
211     if (isSafe) {
212       // Update the intermediate instruction to with the kill flag.
213       if (KillingInstr) {
214         bool Added = KillingInstr->addRegisterKilled(KilledOperand, TRI, true);
215         assert(Added && "Must successfully update kill flag");
216         removeKillInfo(I2, KilledOperand);
217       }
218       DoInsertAtI1 = true;
219       return true;
220     }
221   }
222
223   // Try to move I1 towards I2.
224   {
225     // Look at instructions I in between I1 and (including) I2.
226     MachineBasicBlock::iterator I(I1),
227       End(next(MachineBasicBlock::iterator(I2)));
228     bool IsImmUseReg = I1->getOperand(1).isImm();
229     unsigned I1UseReg = IsImmUseReg ? 0 : I1->getOperand(1).getReg();
230     // Track killed operands. If we move accross an instruction that kills our
231     // operand, we need to update the kill information on the moved I1. It kills
232     // the operand now.
233     MachineInstr *KillingInstr = 0;
234     unsigned KilledOperand = 0;
235
236     while(++I != End) {
237       // If the intervening instruction I:
238       //   * modifies I1's use reg
239       //   * modifies I1's def reg
240       //   * reads I1's def reg
241       //   * or has unmodelled side effects
242       //   We introduce this special case because llvm has no api to remove a
243       //   kill flag for a register (a removeRegisterKilled() analogous to
244       //   addRegisterKilled) that handles aliased register correctly.
245       //   * or has a killed aliased register use of I1's use reg
246       //           %D4<def> = TFRI64 16
247       //           %R6<def> = TFR %R9
248       //           %R8<def> = KILL %R8, %D4<imp-use,kill>
249       //      If we want to move R6 = across the KILL instruction we would have
250       //      to remove the %D4<imp-use,kill> operand. For now, we are
251       //      conservative and disallow the move.
252       // we can't move I1 across it.
253       if (isUnsafeToMoveAccross(I, I1UseReg, I1DestReg, TRI) ||
254           // Check for an aliased register kill. Bail out if we see one.
255           (!I->killsRegister(I1UseReg) && I->killsRegister(I1UseReg, TRI)))
256         return false;
257
258       // Check for an exact kill (registers match).
259       if (I1UseReg && I->killsRegister(I1UseReg)) {
260         assert(KillingInstr == 0 && "Should only see one killing instruction");
261         KilledOperand = I1UseReg;
262         KillingInstr = &*I;
263       }
264     }
265     if (KillingInstr) {
266       removeKillInfo(KillingInstr, KilledOperand);
267       // Update I1 to set the kill flag. This flag will later be picked up by
268       // the new COMBINE instruction.
269       bool Added = I1->addRegisterKilled(KilledOperand, TRI);
270       assert(Added && "Must successfully update kill flag");
271     }
272     DoInsertAtI1 = false;
273   }
274
275   return true;
276 }
277
278 bool HexagonCopyToCombine::runOnMachineFunction(MachineFunction &MF) {
279
280   if (IsCombinesDisabled) return false;
281
282   bool HasChanged = false;
283
284   // Get target info.
285   TRI = MF.getTarget().getRegisterInfo();
286   TII = static_cast<const HexagonInstrInfo *>(MF.getTarget().getInstrInfo());
287
288   // Traverse basic blocks.
289   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE;
290        ++BI) {
291     // Traverse instructions in basic block.
292     for(MachineBasicBlock::iterator MI = BI->begin(), End = BI->end();
293         MI != End;) {
294       MachineInstr *I1 = MI++;
295
296       // Ignore instructions that are not combinable.
297       if (!isCombinableInstType(I1, TII))
298         continue;
299
300       // Find a second instruction that can be merged into a combine
301       // instruction.
302       bool DoInsertAtI1 = false;
303       MachineInstr *I2 = findPairable(I1, DoInsertAtI1);
304       if (I2) {
305         HasChanged = true;
306         combine(I1, I2, MI, DoInsertAtI1);
307       }
308     }
309   }
310
311   return HasChanged;
312 }
313
314 /// findPairable - Returns an instruction that can be merged with \p I1 into a
315 /// COMBINE instruction or 0 if no such instruction can be found. Returns true
316 /// in \p DoInsertAtI1 if the combine must be inserted at instruction \p I1
317 /// false if the combine must be inserted at the returned instruction.
318 MachineInstr *HexagonCopyToCombine::findPairable(MachineInstr *I1,
319                                                  bool &DoInsertAtI1) {
320   MachineBasicBlock::iterator I2 = next(MachineBasicBlock::iterator(I1));
321   unsigned I1DestReg = I1->getOperand(0).getReg();
322
323   for (MachineBasicBlock::iterator End = I1->getParent()->end(); I2 != End;
324        ++I2) {
325     // Bail out early if we see a second definition of I1DestReg.
326     if (I2->modifiesRegister(I1DestReg, TRI))
327       break;
328
329     // Ignore non-combinable instructions.
330     if (!isCombinableInstType(I2, TII))
331       continue;
332
333     unsigned I2DestReg = I2->getOperand(0).getReg();
334
335     // Check that registers are adjacent and that the first destination register
336     // is even.
337     bool IsI1BeforeI2 = (I2DestReg - I1DestReg) == 1;
338     bool IsI2BeforeI1 = (I1DestReg - I2DestReg) == 1;
339     unsigned FirstRegIndex = IsI1BeforeI2 ? I1DestReg : I2DestReg;
340     if ((!IsI1BeforeI2 && !IsI2BeforeI1) || !isEvenReg(FirstRegIndex))
341       continue;
342
343     // Check that the two instructions are combinable. V4 allows more
344     // instructions to be merged into a combine.
345     if (!areCombinableOperations(TRI, I1, I2))
346       break;
347
348     if (isSafeToMoveTogether(I1, I2, I1DestReg, I2DestReg,
349                              DoInsertAtI1))
350       return I2;
351
352     // Not safe. Stop searching.
353     break;
354   }
355   return 0;
356 }
357
358 void HexagonCopyToCombine::combine(MachineInstr *I1, MachineInstr *I2,
359                                    MachineBasicBlock::iterator &MI,
360                                    bool DoInsertAtI1) {
361   // We are going to delete I2. If MI points to I2 advance it to the next
362   // instruction.
363   if ((MachineInstr *)MI == I2) ++MI;
364
365   // Figure out whether I1 or I2 goes into the lowreg part.
366   unsigned I1DestReg = I1->getOperand(0).getReg();
367   unsigned I2DestReg = I2->getOperand(0).getReg();
368   bool IsI1Loreg = (I2DestReg - I1DestReg) == 1;
369   unsigned LoRegDef = IsI1Loreg ? I1DestReg : I2DestReg;
370
371   // Get the double word register.
372   unsigned DoubleRegDest =
373     TRI->getMatchingSuperReg(LoRegDef, Hexagon::subreg_loreg,
374                              Hexagon::DoubleRegsRegisterClass);
375   assert(DoubleRegDest != 0 && "Expect a valid register");
376
377
378   // Setup source operands.
379   MachineOperand &LoOperand = IsI1Loreg ? I1->getOperand(1) :
380     I2->getOperand(1);
381   MachineOperand &HiOperand = IsI1Loreg ? I2->getOperand(1) :
382     I1->getOperand(1);
383
384   // Figure out which source is a register and which a constant.
385   bool IsHiReg = HiOperand.isReg();
386   bool IsLoReg = LoOperand.isReg();
387
388   MachineBasicBlock::iterator InsertPt(DoInsertAtI1 ? I1 : I2);
389   // Emit combine.
390   if (IsHiReg && IsLoReg)
391     emitCombineRR(InsertPt, DoubleRegDest, HiOperand, LoOperand);
392   else if (IsHiReg)
393     emitCombineRI(InsertPt, DoubleRegDest, HiOperand, LoOperand);
394   else if (IsLoReg)
395     emitCombineIR(InsertPt, DoubleRegDest, HiOperand, LoOperand);
396   else
397     emitCombineII(InsertPt, DoubleRegDest, HiOperand, LoOperand);
398
399   I1->eraseFromParent();
400   I2->eraseFromParent();
401 }
402
403 void HexagonCopyToCombine::emitCombineII(MachineBasicBlock::iterator &InsertPt,
404                                          unsigned DoubleDestReg,
405                                          MachineOperand &HiOperand,
406                                          MachineOperand &LoOperand) {
407   DebugLoc DL = InsertPt->getDebugLoc();
408   MachineBasicBlock *BB = InsertPt->getParent();
409
410   // Insert new combine instruction.
411   //  DoubleRegDest = combine #HiImm, #LoImm
412   BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::COMBINE_ii), DoubleDestReg)
413     .addImm(HiOperand.getImm())
414     .addImm(LoOperand.getImm());
415 }
416
417 void HexagonCopyToCombine::emitCombineIR(MachineBasicBlock::iterator &InsertPt,
418                                          unsigned DoubleDestReg,
419                                          MachineOperand &HiOperand,
420                                          MachineOperand &LoOperand) {
421   unsigned LoReg = LoOperand.getReg();
422   unsigned LoRegKillFlag = getKillRegState(LoOperand.isKill());
423
424   DebugLoc DL = InsertPt->getDebugLoc();
425   MachineBasicBlock *BB = InsertPt->getParent();
426
427   // Insert new combine instruction.
428   //  DoubleRegDest = combine #HiImm, LoReg
429   BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::COMBINE_ir_V4), DoubleDestReg)
430     .addImm(HiOperand.getImm())
431     .addReg(LoReg, LoRegKillFlag);
432 }
433
434 void HexagonCopyToCombine::emitCombineRI(MachineBasicBlock::iterator &InsertPt,
435                                          unsigned DoubleDestReg,
436                                          MachineOperand &HiOperand,
437                                          MachineOperand &LoOperand) {
438   unsigned HiRegKillFlag = getKillRegState(HiOperand.isKill());
439   unsigned HiReg = HiOperand.getReg();
440
441   DebugLoc DL = InsertPt->getDebugLoc();
442   MachineBasicBlock *BB = InsertPt->getParent();
443
444   // Insert new combine instruction.
445   //  DoubleRegDest = combine HiReg, #LoImm
446   BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::COMBINE_ri_V4), DoubleDestReg)
447     .addReg(HiReg, HiRegKillFlag)
448     .addImm(LoOperand.getImm());
449 }
450
451 void HexagonCopyToCombine::emitCombineRR(MachineBasicBlock::iterator &InsertPt,
452                                          unsigned DoubleDestReg,
453                                          MachineOperand &HiOperand,
454                                          MachineOperand &LoOperand) {
455   unsigned LoRegKillFlag = getKillRegState(LoOperand.isKill());
456   unsigned HiRegKillFlag = getKillRegState(HiOperand.isKill());
457   unsigned LoReg = LoOperand.getReg();
458   unsigned HiReg = HiOperand.getReg();
459
460   DebugLoc DL = InsertPt->getDebugLoc();
461   MachineBasicBlock *BB = InsertPt->getParent();
462
463   // Insert new combine instruction.
464   //  DoubleRegDest = combine HiReg, LoReg
465   BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::COMBINE_rr), DoubleDestReg)
466     .addReg(HiReg, HiRegKillFlag)
467     .addReg(LoReg, LoRegKillFlag);
468 }
469
470 FunctionPass *llvm::createHexagonCopyToCombine() {
471   return new HexagonCopyToCombine();
472 }
473