981954fa3b41123dfc207b5bc9950dca12cd23b2
[oota-llvm.git] / lib / Target / Mips / MipsLongBranch.cpp
1 //===-- MipsLongBranch.cpp - Emit long branches ---------------------------===//
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 pass expands a branch or jump instruction into a long branch if its
11 // offset is too large to fit into its immediate field.
12 //
13 // FIXME: Fix pc-region jump instructions which cross 256MB segment boundaries.
14 //===----------------------------------------------------------------------===//
15
16 #include "Mips.h"
17 #include "MCTargetDesc/MipsBaseInfo.h"
18 #include "MCTargetDesc/MipsMCNaCl.h"
19 #include "MipsMachineFunction.h"
20 #include "MipsTargetMachine.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30
31 using namespace llvm;
32
33 #define DEBUG_TYPE "mips-long-branch"
34
35 STATISTIC(LongBranches, "Number of long branches.");
36
37 static cl::opt<bool> SkipLongBranch(
38   "skip-mips-long-branch",
39   cl::init(false),
40   cl::desc("MIPS: Skip long branch pass."),
41   cl::Hidden);
42
43 static cl::opt<bool> ForceLongBranch(
44   "force-mips-long-branch",
45   cl::init(false),
46   cl::desc("MIPS: Expand all branches to long format."),
47   cl::Hidden);
48
49 namespace {
50   typedef MachineBasicBlock::iterator Iter;
51   typedef MachineBasicBlock::reverse_iterator ReverseIter;
52
53   struct MBBInfo {
54     uint64_t Size, Address;
55     bool HasLongBranch;
56     MachineInstr *Br;
57
58     MBBInfo() : Size(0), HasLongBranch(false), Br(nullptr) {}
59   };
60
61   class MipsLongBranch : public MachineFunctionPass {
62
63   public:
64     static char ID;
65     MipsLongBranch(TargetMachine &tm)
66         : MachineFunctionPass(ID), TM(tm),
67           IsPIC(TM.getRelocationModel() == Reloc::PIC_),
68           ABI(static_cast<const MipsTargetMachine &>(TM).getABI()),
69           LongBranchSeqSize(
70               !IsPIC ? 2
71                      : (ABI.IsN64()
72                             ? 10
73                             : (!TM.getSubtarget<MipsSubtarget>().isTargetNaCl()
74                                    ? 9
75                                    : 10))) {}
76
77     const char *getPassName() const override {
78       return "Mips Long Branch";
79     }
80
81     bool runOnMachineFunction(MachineFunction &F) override;
82
83   private:
84     void splitMBB(MachineBasicBlock *MBB);
85     void initMBBInfo();
86     int64_t computeOffset(const MachineInstr *Br);
87     void replaceBranch(MachineBasicBlock &MBB, Iter Br, DebugLoc DL,
88                        MachineBasicBlock *MBBOpnd);
89     void expandToLongBranch(MBBInfo &Info);
90
91     const TargetMachine &TM;
92     MachineFunction *MF;
93     SmallVector<MBBInfo, 16> MBBInfos;
94     bool IsPIC;
95     MipsABIInfo ABI;
96     unsigned LongBranchSeqSize;
97   };
98
99   char MipsLongBranch::ID = 0;
100 } // end of anonymous namespace
101
102 /// createMipsLongBranchPass - Returns a pass that converts branches to long
103 /// branches.
104 FunctionPass *llvm::createMipsLongBranchPass(MipsTargetMachine &tm) {
105   return new MipsLongBranch(tm);
106 }
107
108 /// Iterate over list of Br's operands and search for a MachineBasicBlock
109 /// operand.
110 static MachineBasicBlock *getTargetMBB(const MachineInstr &Br) {
111   for (unsigned I = 0, E = Br.getDesc().getNumOperands(); I < E; ++I) {
112     const MachineOperand &MO = Br.getOperand(I);
113
114     if (MO.isMBB())
115       return MO.getMBB();
116   }
117
118   llvm_unreachable("This instruction does not have an MBB operand.");
119 }
120
121 // Traverse the list of instructions backwards until a non-debug instruction is
122 // found or it reaches E.
123 static ReverseIter getNonDebugInstr(ReverseIter B, ReverseIter E) {
124   for (; B != E; ++B)
125     if (!B->isDebugValue())
126       return B;
127
128   return E;
129 }
130
131 // Split MBB if it has two direct jumps/branches.
132 void MipsLongBranch::splitMBB(MachineBasicBlock *MBB) {
133   ReverseIter End = MBB->rend();
134   ReverseIter LastBr = getNonDebugInstr(MBB->rbegin(), End);
135
136   // Return if MBB has no branch instructions.
137   if ((LastBr == End) ||
138       (!LastBr->isConditionalBranch() && !LastBr->isUnconditionalBranch()))
139     return;
140
141   ReverseIter FirstBr = getNonDebugInstr(std::next(LastBr), End);
142
143   // MBB has only one branch instruction if FirstBr is not a branch
144   // instruction.
145   if ((FirstBr == End) ||
146       (!FirstBr->isConditionalBranch() && !FirstBr->isUnconditionalBranch()))
147     return;
148
149   assert(!FirstBr->isIndirectBranch() && "Unexpected indirect branch found.");
150
151   // Create a new MBB. Move instructions in MBB to the newly created MBB.
152   MachineBasicBlock *NewMBB =
153     MF->CreateMachineBasicBlock(MBB->getBasicBlock());
154
155   // Insert NewMBB and fix control flow.
156   MachineBasicBlock *Tgt = getTargetMBB(*FirstBr);
157   NewMBB->transferSuccessors(MBB);
158   NewMBB->removeSuccessor(Tgt);
159   MBB->addSuccessor(NewMBB);
160   MBB->addSuccessor(Tgt);
161   MF->insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
162
163   NewMBB->splice(NewMBB->end(), MBB, (++LastBr).base(), MBB->end());
164 }
165
166 // Fill MBBInfos.
167 void MipsLongBranch::initMBBInfo() {
168   // Split the MBBs if they have two branches. Each basic block should have at
169   // most one branch after this loop is executed.
170   for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E;)
171     splitMBB(I++);
172
173   MF->RenumberBlocks();
174   MBBInfos.clear();
175   MBBInfos.resize(MF->size());
176
177   const MipsInstrInfo *TII =
178       static_cast<const MipsInstrInfo *>(TM.getSubtargetImpl()->getInstrInfo());
179   for (unsigned I = 0, E = MBBInfos.size(); I < E; ++I) {
180     MachineBasicBlock *MBB = MF->getBlockNumbered(I);
181
182     // Compute size of MBB.
183     for (MachineBasicBlock::instr_iterator MI = MBB->instr_begin();
184          MI != MBB->instr_end(); ++MI)
185       MBBInfos[I].Size += TII->GetInstSizeInBytes(&*MI);
186
187     // Search for MBB's branch instruction.
188     ReverseIter End = MBB->rend();
189     ReverseIter Br = getNonDebugInstr(MBB->rbegin(), End);
190
191     if ((Br != End) && !Br->isIndirectBranch() &&
192         (Br->isConditionalBranch() ||
193          (Br->isUnconditionalBranch() &&
194           TM.getRelocationModel() == Reloc::PIC_)))
195       MBBInfos[I].Br = (++Br).base();
196   }
197 }
198
199 // Compute offset of branch in number of bytes.
200 int64_t MipsLongBranch::computeOffset(const MachineInstr *Br) {
201   int64_t Offset = 0;
202   int ThisMBB = Br->getParent()->getNumber();
203   int TargetMBB = getTargetMBB(*Br)->getNumber();
204
205   // Compute offset of a forward branch.
206   if (ThisMBB < TargetMBB) {
207     for (int N = ThisMBB + 1; N < TargetMBB; ++N)
208       Offset += MBBInfos[N].Size;
209
210     return Offset + 4;
211   }
212
213   // Compute offset of a backward branch.
214   for (int N = ThisMBB; N >= TargetMBB; --N)
215     Offset += MBBInfos[N].Size;
216
217   return -Offset + 4;
218 }
219
220 // Replace Br with a branch which has the opposite condition code and a
221 // MachineBasicBlock operand MBBOpnd.
222 void MipsLongBranch::replaceBranch(MachineBasicBlock &MBB, Iter Br,
223                                    DebugLoc DL, MachineBasicBlock *MBBOpnd) {
224   const MipsInstrInfo *TII =
225       static_cast<const MipsInstrInfo *>(TM.getSubtargetImpl()->getInstrInfo());
226   unsigned NewOpc = TII->getOppositeBranchOpc(Br->getOpcode());
227   const MCInstrDesc &NewDesc = TII->get(NewOpc);
228
229   MachineInstrBuilder MIB = BuildMI(MBB, Br, DL, NewDesc);
230
231   for (unsigned I = 0, E = Br->getDesc().getNumOperands(); I < E; ++I) {
232     MachineOperand &MO = Br->getOperand(I);
233
234     if (!MO.isReg()) {
235       assert(MO.isMBB() && "MBB operand expected.");
236       break;
237     }
238
239     MIB.addReg(MO.getReg());
240   }
241
242   MIB.addMBB(MBBOpnd);
243
244   if (Br->hasDelaySlot()) {
245     // Bundle the instruction in the delay slot to the newly created branch
246     // and erase the original branch.
247     assert(Br->isBundledWithSucc());
248     MachineBasicBlock::instr_iterator II(Br);
249     MIBundleBuilder(&*MIB).append((++II)->removeFromBundle());
250   }
251   Br->eraseFromParent();
252 }
253
254 // Expand branch instructions to long branches.
255 // TODO: This function has to be fixed for beqz16 and bnez16, because it
256 // currently assumes that all branches have 16-bit offsets, and will produce
257 // wrong code if branches whose allowed offsets are [-128, -126, ..., 126]
258 // are present.
259 void MipsLongBranch::expandToLongBranch(MBBInfo &I) {
260   MachineBasicBlock::iterator Pos;
261   MachineBasicBlock *MBB = I.Br->getParent(), *TgtMBB = getTargetMBB(*I.Br);
262   DebugLoc DL = I.Br->getDebugLoc();
263   const BasicBlock *BB = MBB->getBasicBlock();
264   MachineFunction::iterator FallThroughMBB = ++MachineFunction::iterator(MBB);
265   MachineBasicBlock *LongBrMBB = MF->CreateMachineBasicBlock(BB);
266
267   const MipsInstrInfo *TII =
268       static_cast<const MipsInstrInfo *>(TM.getSubtargetImpl()->getInstrInfo());
269
270   MF->insert(FallThroughMBB, LongBrMBB);
271   MBB->removeSuccessor(TgtMBB);
272   MBB->addSuccessor(LongBrMBB);
273
274   if (IsPIC) {
275     MachineBasicBlock *BalTgtMBB = MF->CreateMachineBasicBlock(BB);
276     MF->insert(FallThroughMBB, BalTgtMBB);
277     LongBrMBB->addSuccessor(BalTgtMBB);
278     BalTgtMBB->addSuccessor(TgtMBB);
279
280     // We must select between the MIPS32r6/MIPS64r6 BAL (which is a normal
281     // instruction) and the pre-MIPS32r6/MIPS64r6 definition (which is an
282     // pseudo-instruction wrapping BGEZAL).
283
284     const MipsSubtarget &Subtarget = TM.getSubtarget<MipsSubtarget>();
285     unsigned BalOp = Subtarget.hasMips32r6() ? Mips::BAL : Mips::BAL_BR;
286
287     if (!ABI.IsN64()) {
288       // $longbr:
289       //  addiu $sp, $sp, -8
290       //  sw $ra, 0($sp)
291       //  lui $at, %hi($tgt - $baltgt)
292       //  bal $baltgt
293       //  addiu $at, $at, %lo($tgt - $baltgt)
294       // $baltgt:
295       //  addu $at, $ra, $at
296       //  lw $ra, 0($sp)
297       //  jr $at
298       //  addiu $sp, $sp, 8
299       // $fallthrough:
300       //
301
302       Pos = LongBrMBB->begin();
303
304       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::ADDiu), Mips::SP)
305         .addReg(Mips::SP).addImm(-8);
306       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::SW)).addReg(Mips::RA)
307         .addReg(Mips::SP).addImm(0);
308
309       // LUi and ADDiu instructions create 32-bit offset of the target basic
310       // block from the target of BAL instruction.  We cannot use immediate
311       // value for this offset because it cannot be determined accurately when
312       // the program has inline assembly statements.  We therefore use the
313       // relocation expressions %hi($tgt-$baltgt) and %lo($tgt-$baltgt) which
314       // are resolved during the fixup, so the values will always be correct.
315       //
316       // Since we cannot create %hi($tgt-$baltgt) and %lo($tgt-$baltgt)
317       // expressions at this point (it is possible only at the MC layer),
318       // we replace LUi and ADDiu with pseudo instructions
319       // LONG_BRANCH_LUi and LONG_BRANCH_ADDiu, and add both basic
320       // blocks as operands to these instructions.  When lowering these pseudo
321       // instructions to LUi and ADDiu in the MC layer, we will create
322       // %hi($tgt-$baltgt) and %lo($tgt-$baltgt) expressions and add them as
323       // operands to lowered instructions.
324
325       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_LUi), Mips::AT)
326         .addMBB(TgtMBB).addMBB(BalTgtMBB);
327       MIBundleBuilder(*LongBrMBB, Pos)
328           .append(BuildMI(*MF, DL, TII->get(BalOp)).addMBB(BalTgtMBB))
329           .append(BuildMI(*MF, DL, TII->get(Mips::LONG_BRANCH_ADDiu), Mips::AT)
330                       .addReg(Mips::AT)
331                       .addMBB(TgtMBB)
332                       .addMBB(BalTgtMBB));
333
334       Pos = BalTgtMBB->begin();
335
336       BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::ADDu), Mips::AT)
337         .addReg(Mips::RA).addReg(Mips::AT);
338       BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::LW), Mips::RA)
339         .addReg(Mips::SP).addImm(0);
340
341       if (!TM.getSubtarget<MipsSubtarget>().isTargetNaCl()) {
342         MIBundleBuilder(*BalTgtMBB, Pos)
343           .append(BuildMI(*MF, DL, TII->get(Mips::JR)).addReg(Mips::AT))
344           .append(BuildMI(*MF, DL, TII->get(Mips::ADDiu), Mips::SP)
345                   .addReg(Mips::SP).addImm(8));
346       } else {
347         // In NaCl, modifying the sp is not allowed in branch delay slot.
348         BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::ADDiu), Mips::SP)
349           .addReg(Mips::SP).addImm(8);
350
351         MIBundleBuilder(*BalTgtMBB, Pos)
352           .append(BuildMI(*MF, DL, TII->get(Mips::JR)).addReg(Mips::AT))
353           .append(BuildMI(*MF, DL, TII->get(Mips::NOP)));
354
355         // Bundle-align the target of indirect branch JR.
356         TgtMBB->setAlignment(MIPS_NACL_BUNDLE_ALIGN);
357       }
358     } else {
359       // $longbr:
360       //  daddiu $sp, $sp, -16
361       //  sd $ra, 0($sp)
362       //  daddiu $at, $zero, %hi($tgt - $baltgt)
363       //  dsll $at, $at, 16
364       //  bal $baltgt
365       //  daddiu $at, $at, %lo($tgt - $baltgt)
366       // $baltgt:
367       //  daddu $at, $ra, $at
368       //  ld $ra, 0($sp)
369       //  jr64 $at
370       //  daddiu $sp, $sp, 16
371       // $fallthrough:
372       //
373
374       // We assume the branch is within-function, and that offset is within
375       // +/- 2GB.  High 32 bits will therefore always be zero.
376
377       // Note that this will work even if the offset is negative, because
378       // of the +1 modification that's added in that case.  For example, if the
379       // offset is -1MB (0xFFFFFFFFFFF00000), the computation for %higher is
380       //
381       // 0xFFFFFFFFFFF00000 + 0x80008000 = 0x000000007FF08000
382       //
383       // and the bits [47:32] are zero.  For %highest
384       //
385       // 0xFFFFFFFFFFF00000 + 0x800080008000 = 0x000080007FF08000
386       //
387       // and the bits [63:48] are zero.
388
389       Pos = LongBrMBB->begin();
390
391       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DADDiu), Mips::SP_64)
392         .addReg(Mips::SP_64).addImm(-16);
393       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::SD)).addReg(Mips::RA_64)
394         .addReg(Mips::SP_64).addImm(0);
395       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu),
396               Mips::AT_64).addReg(Mips::ZERO_64)
397                           .addMBB(TgtMBB, MipsII::MO_ABS_HI).addMBB(BalTgtMBB);
398       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DSLL), Mips::AT_64)
399         .addReg(Mips::AT_64).addImm(16);
400
401       MIBundleBuilder(*LongBrMBB, Pos)
402           .append(BuildMI(*MF, DL, TII->get(BalOp)).addMBB(BalTgtMBB))
403           .append(
404               BuildMI(*MF, DL, TII->get(Mips::LONG_BRANCH_DADDiu), Mips::AT_64)
405                   .addReg(Mips::AT_64)
406                   .addMBB(TgtMBB, MipsII::MO_ABS_LO)
407                   .addMBB(BalTgtMBB));
408
409       Pos = BalTgtMBB->begin();
410
411       BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::DADDu), Mips::AT_64)
412         .addReg(Mips::RA_64).addReg(Mips::AT_64);
413       BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::LD), Mips::RA_64)
414         .addReg(Mips::SP_64).addImm(0);
415
416       MIBundleBuilder(*BalTgtMBB, Pos)
417         .append(BuildMI(*MF, DL, TII->get(Mips::JR64)).addReg(Mips::AT_64))
418         .append(BuildMI(*MF, DL, TII->get(Mips::DADDiu), Mips::SP_64)
419                 .addReg(Mips::SP_64).addImm(16));
420     }
421
422     assert(LongBrMBB->size() + BalTgtMBB->size() == LongBranchSeqSize);
423   } else {
424     // $longbr:
425     //  j $tgt
426     //  nop
427     // $fallthrough:
428     //
429     Pos = LongBrMBB->begin();
430     LongBrMBB->addSuccessor(TgtMBB);
431     MIBundleBuilder(*LongBrMBB, Pos)
432       .append(BuildMI(*MF, DL, TII->get(Mips::J)).addMBB(TgtMBB))
433       .append(BuildMI(*MF, DL, TII->get(Mips::NOP)));
434
435     assert(LongBrMBB->size() == LongBranchSeqSize);
436   }
437
438   if (I.Br->isUnconditionalBranch()) {
439     // Change branch destination.
440     assert(I.Br->getDesc().getNumOperands() == 1);
441     I.Br->RemoveOperand(0);
442     I.Br->addOperand(MachineOperand::CreateMBB(LongBrMBB));
443   } else
444     // Change branch destination and reverse condition.
445     replaceBranch(*MBB, I.Br, DL, FallThroughMBB);
446 }
447
448 static void emitGPDisp(MachineFunction &F, const MipsInstrInfo *TII) {
449   MachineBasicBlock &MBB = F.front();
450   MachineBasicBlock::iterator I = MBB.begin();
451   DebugLoc DL = MBB.findDebugLoc(MBB.begin());
452   BuildMI(MBB, I, DL, TII->get(Mips::LUi), Mips::V0)
453     .addExternalSymbol("_gp_disp", MipsII::MO_ABS_HI);
454   BuildMI(MBB, I, DL, TII->get(Mips::ADDiu), Mips::V0)
455     .addReg(Mips::V0).addExternalSymbol("_gp_disp", MipsII::MO_ABS_LO);
456   MBB.removeLiveIn(Mips::V0);
457 }
458
459 bool MipsLongBranch::runOnMachineFunction(MachineFunction &F) {
460   const MipsInstrInfo *TII =
461       static_cast<const MipsInstrInfo *>(TM.getSubtargetImpl()->getInstrInfo());
462
463   const MipsSubtarget &STI = TM.getSubtarget<MipsSubtarget>();
464   if (STI.inMips16Mode() || !STI.enableLongBranchPass())
465     return false;
466   if ((TM.getRelocationModel() == Reloc::PIC_) &&
467       TM.getSubtarget<MipsSubtarget>().isABI_O32() &&
468       F.getInfo<MipsFunctionInfo>()->globalBaseRegSet())
469     emitGPDisp(F, TII);
470
471   if (SkipLongBranch)
472     return true;
473
474   MF = &F;
475   initMBBInfo();
476
477   SmallVectorImpl<MBBInfo>::iterator I, E = MBBInfos.end();
478   bool EverMadeChange = false, MadeChange = true;
479
480   while (MadeChange) {
481     MadeChange = false;
482
483     for (I = MBBInfos.begin(); I != E; ++I) {
484       // Skip if this MBB doesn't have a branch or the branch has already been
485       // converted to a long branch.
486       if (!I->Br || I->HasLongBranch)
487         continue;
488
489       int ShVal = TM.getSubtarget<MipsSubtarget>().inMicroMipsMode() ? 2 : 4;
490       int64_t Offset = computeOffset(I->Br) / ShVal;
491
492       if (TM.getSubtarget<MipsSubtarget>().isTargetNaCl()) {
493         // The offset calculation does not include sandboxing instructions
494         // that will be added later in the MC layer.  Since at this point we
495         // don't know the exact amount of code that "sandboxing" will add, we
496         // conservatively estimate that code will not grow more than 100%.
497         Offset *= 2;
498       }
499
500       // Check if offset fits into 16-bit immediate field of branches.
501       if (!ForceLongBranch && isInt<16>(Offset))
502         continue;
503
504       I->HasLongBranch = true;
505       I->Size += LongBranchSeqSize * 4;
506       ++LongBranches;
507       EverMadeChange = MadeChange = true;
508     }
509   }
510
511   if (!EverMadeChange)
512     return true;
513
514   // Compute basic block addresses.
515   if (TM.getRelocationModel() == Reloc::PIC_) {
516     uint64_t Address = 0;
517
518     for (I = MBBInfos.begin(); I != E; Address += I->Size, ++I)
519       I->Address = Address;
520   }
521
522   // Do the expansion.
523   for (I = MBBInfos.begin(); I != E; ++I)
524     if (I->HasLongBranch)
525       expandToLongBranch(*I);
526
527   MF->RenumberBlocks();
528
529   return true;
530 }