Conditional branch being fixed up is not the last MI in the BB, there is a
[oota-llvm.git] / lib / Target / ARM / ARMConstantIslandPass.cpp
1 //===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a pass that splits the constant pool up into 'islands'
11 // which are scattered through-out the function.  This is required due to the
12 // limited pc-relative displacements that ARM has.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "arm-cp-islands"
17 #include "ARM.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMInstrInfo.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/Statistic.h"
31 #include <iostream>
32 using namespace llvm;
33
34 STATISTIC(NumSplit, "Number of uncond branches inserted");
35
36 namespace {
37   /// ARMConstantIslands - Due to limited pc-relative displacements, ARM
38   /// requires constant pool entries to be scattered among the instructions
39   /// inside a function.  To do this, it completely ignores the normal LLVM
40   /// constant pool, instead, it places constants where-ever it feels like with
41   /// special instructions.
42   ///
43   /// The terminology used in this pass includes:
44   ///   Islands - Clumps of constants placed in the function.
45   ///   Water   - Potential places where an island could be formed.
46   ///   CPE     - A constant pool entry that has been placed somewhere, which
47   ///             tracks a list of users.
48   class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
49     /// NextUID - Assign unique ID's to CPE's.
50     unsigned NextUID;
51     
52     /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
53     /// by MBB Number.
54     std::vector<unsigned> BBSizes;
55     
56     /// WaterList - A sorted list of basic blocks where islands could be placed
57     /// (i.e. blocks that don't fall through to the following block, due
58     /// to a return, unreachable, or unconditional branch).
59     std::vector<MachineBasicBlock*> WaterList;
60     
61     /// CPUser - One user of a constant pool, keeping the machine instruction
62     /// pointer, the constant pool being referenced, and the max displacement
63     /// allowed from the instruction to the CP.
64     struct CPUser {
65       MachineInstr *MI;
66       MachineInstr *CPEMI;
67       unsigned MaxDisp;
68       CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
69         : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
70     };
71     
72     /// CPUsers - Keep track of all of the machine instructions that use various
73     /// constant pools and their max displacement.
74     std::vector<CPUser> CPUsers;
75     
76     /// ImmBranch - One per immediate branch, keeping the machine instruction
77     /// pointer, conditional or unconditional, the max displacement,
78     /// and (if isCond is true) the corresponding unconditional branch
79     /// opcode.
80     struct ImmBranch {
81       MachineInstr *MI;
82       unsigned MaxDisp : 31;
83       bool isCond : 1;
84       int UncondBr;
85       ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
86         : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
87     };
88
89     /// Branches - Keep track of all the immediate branch instructions.
90     ///
91     std::vector<ImmBranch> ImmBranches;
92
93     const TargetInstrInfo *TII;
94     const TargetAsmInfo   *TAI;
95   public:
96     virtual bool runOnMachineFunction(MachineFunction &Fn);
97
98     virtual const char *getPassName() const {
99       return "ARM constant island placement and branch shortening pass";
100     }
101     
102   private:
103     void DoInitialPlacement(MachineFunction &Fn,
104                             std::vector<MachineInstr*> &CPEMIs);
105     void InitialFunctionScan(MachineFunction &Fn,
106                              const std::vector<MachineInstr*> &CPEMIs);
107     void SplitBlockBeforeInstr(MachineInstr *MI);
108     void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
109     bool HandleConstantPoolUser(MachineFunction &Fn, CPUser &U);
110     bool BBIsInBranchRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned D);
111     bool FixUpImmediateBranch(MachineFunction &Fn, ImmBranch &Br);
112
113     unsigned GetInstSize(MachineInstr *MI) const;
114     unsigned GetOffsetOf(MachineInstr *MI) const;
115     unsigned GetOffsetOf(MachineBasicBlock *MBB) const;
116   };
117 }
118
119 /// createARMConstantIslandPass - returns an instance of the constpool
120 /// island pass.
121 FunctionPass *llvm::createARMConstantIslandPass() {
122   return new ARMConstantIslands();
123 }
124
125 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
126   MachineConstantPool &MCP = *Fn.getConstantPool();
127   
128   TII = Fn.getTarget().getInstrInfo();
129   TAI = Fn.getTarget().getTargetAsmInfo();
130   
131   // Renumber all of the machine basic blocks in the function, guaranteeing that
132   // the numbers agree with the position of the block in the function.
133   Fn.RenumberBlocks();
134
135   // Perform the initial placement of the constant pool entries.  To start with,
136   // we put them all at the end of the function.
137   std::vector<MachineInstr*> CPEMIs;
138   if (!MCP.isEmpty())
139     DoInitialPlacement(Fn, CPEMIs);
140   
141   /// The next UID to take is the first unused one.
142   NextUID = CPEMIs.size();
143   
144   // Do the initial scan of the function, building up information about the
145   // sizes of each block, the location of all the water, and finding all of the
146   // constant pool users.
147   InitialFunctionScan(Fn, CPEMIs);
148   CPEMIs.clear();
149   
150   // Iteratively place constant pool entries until there is no change.
151   bool MadeChange;
152   do {
153     MadeChange = false;
154     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
155       MadeChange |= HandleConstantPoolUser(Fn, CPUsers[i]);
156     for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
157       MadeChange |= FixUpImmediateBranch(Fn, ImmBranches[i]);
158   } while (MadeChange);
159   
160   BBSizes.clear();
161   WaterList.clear();
162   CPUsers.clear();
163   ImmBranches.clear();
164     
165   return true;
166 }
167
168 /// DoInitialPlacement - Perform the initial placement of the constant pool
169 /// entries.  To start with, we put them all at the end of the function.
170 void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
171                                             std::vector<MachineInstr*> &CPEMIs){
172   // Create the basic block to hold the CPE's.
173   MachineBasicBlock *BB = new MachineBasicBlock();
174   Fn.getBasicBlockList().push_back(BB);
175   
176   // Add all of the constants from the constant pool to the end block, use an
177   // identity mapping of CPI's to CPE's.
178   const std::vector<MachineConstantPoolEntry> &CPs =
179     Fn.getConstantPool()->getConstants();
180   
181   const TargetData &TD = *Fn.getTarget().getTargetData();
182   for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
183     unsigned Size = TD.getTypeSize(CPs[i].getType());
184     // Verify that all constant pool entries are a multiple of 4 bytes.  If not,
185     // we would have to pad them out or something so that instructions stay
186     // aligned.
187     assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
188     MachineInstr *CPEMI =
189       BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
190                            .addImm(i).addConstantPoolIndex(i).addImm(Size);
191     CPEMIs.push_back(CPEMI);
192     DEBUG(std::cerr << "Moved CPI#" << i << " to end of function as #"
193                     << i << "\n");
194   }
195 }
196
197 /// BBHasFallthrough - Return true of the specified basic block can fallthrough
198 /// into the block immediately after it.
199 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
200   // Get the next machine basic block in the function.
201   MachineFunction::iterator MBBI = MBB;
202   if (next(MBBI) == MBB->getParent()->end())  // Can't fall off end of function.
203     return false;
204   
205   MachineBasicBlock *NextBB = next(MBBI);
206   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
207        E = MBB->succ_end(); I != E; ++I)
208     if (*I == NextBB)
209       return true;
210   
211   return false;
212 }
213
214 /// InitialFunctionScan - Do the initial scan of the function, building up
215 /// information about the sizes of each block, the location of all the water,
216 /// and finding all of the constant pool users.
217 void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
218                                      const std::vector<MachineInstr*> &CPEMIs) {
219   for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
220        MBBI != E; ++MBBI) {
221     MachineBasicBlock &MBB = *MBBI;
222     
223     // If this block doesn't fall through into the next MBB, then this is
224     // 'water' that a constant pool island could be placed.
225     if (!BBHasFallthrough(&MBB))
226       WaterList.push_back(&MBB);
227     
228     unsigned MBBSize = 0;
229     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
230          I != E; ++I) {
231       // Add instruction size to MBBSize.
232       MBBSize += GetInstSize(I);
233
234       int Opc = I->getOpcode();
235       if (TII->isBranch(Opc)) {
236         bool isCond = false;
237         unsigned Bits = 0;
238         unsigned Scale = 1;
239         int UOpc = Opc;
240         switch (Opc) {
241         default:
242           continue;  // Ignore JT branches
243         case ARM::Bcc:
244           isCond = true;
245           UOpc = ARM::B;
246           // Fallthrough
247         case ARM::B:
248           Bits = 24;
249           Scale = 4;
250           break;
251         case ARM::tBcc:
252           isCond = true;
253           UOpc = ARM::tB;
254           Bits = 8;
255           Scale = 2;
256           break;
257         case ARM::tB:
258           Bits = 11;
259           Scale = 2;
260           break;
261         }
262         unsigned MaxDisp = (1 << (Bits-1)) * Scale;
263         ImmBranches.push_back(ImmBranch(I, MaxDisp, isCond, UOpc));
264       }
265
266       // Scan the instructions for constant pool operands.
267       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
268         if (I->getOperand(op).isConstantPoolIndex()) {
269           // We found one.  The addressing mode tells us the max displacement
270           // from the PC that this instruction permits.
271           unsigned MaxOffs = 0;
272           
273           // Basic size info comes from the TSFlags field.
274           unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
275           switch (TSFlags & ARMII::AddrModeMask) {
276           default: 
277             // Constant pool entries can reach anything.
278             if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
279               continue;
280             assert(0 && "Unknown addressing mode for CP reference!");
281           case ARMII::AddrMode1: // AM1: 8 bits << 2
282             MaxOffs = 1 << (8+2);   // Taking the address of a CP entry.
283             break;
284           case ARMII::AddrMode2:
285             MaxOffs = 1 << 12;   // +-offset_12
286             break;
287           case ARMII::AddrMode3:
288             MaxOffs = 1 << 8;   // +-offset_8
289             break;
290             // addrmode4 has no immediate offset.
291           case ARMII::AddrMode5:
292             MaxOffs = 1 << (8+2);   // +-(offset_8*4)
293             break;
294           case ARMII::AddrModeT1:
295             MaxOffs = 1 << 5;
296             break;
297           case ARMII::AddrModeT2:
298             MaxOffs = 1 << (5+1);
299             break;
300           case ARMII::AddrModeT4:
301             MaxOffs = 1 << (5+2);
302             break;
303           case ARMII::AddrModeTs:
304             MaxOffs = 1 << (8+2);
305             break;
306           }
307           
308           // Remember that this is a user of a CP entry.
309           MachineInstr *CPEMI =CPEMIs[I->getOperand(op).getConstantPoolIndex()];
310           CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
311           
312           // Instructions can only use one CP entry, don't bother scanning the
313           // rest of the operands.
314           break;
315         }
316     }
317     BBSizes.push_back(MBBSize);
318   }
319 }
320
321 /// FIXME: Works around a gcc miscompilation with -fstrict-aliasing
322 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
323                                 unsigned JTI) DISABLE_INLINE;
324 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
325                                 unsigned JTI) {
326   return JT[JTI].MBBs.size();
327 }
328
329 /// GetInstSize - Return the size of the specified MachineInstr.
330 ///
331 unsigned ARMConstantIslands::GetInstSize(MachineInstr *MI) const {
332   // Basic size info comes from the TSFlags field.
333   unsigned TSFlags = MI->getInstrDescriptor()->TSFlags;
334   
335   switch ((TSFlags & ARMII::SizeMask) >> ARMII::SizeShift) {
336   default:
337     // If this machine instr is an inline asm, measure it.
338     if (MI->getOpcode() == ARM::INLINEASM)
339       return TAI->getInlineAsmLength(MI->getOperand(0).getSymbolName());
340     if (MI->getOpcode() == ARM::LABEL)
341       return 0;
342     assert(0 && "Unknown or unset size field for instr!");
343     break;
344   case ARMII::Size8Bytes: return 8;          // Arm instruction x 2.
345   case ARMII::Size4Bytes: return 4;          // Arm instruction.
346   case ARMII::Size2Bytes: return 2;          // Thumb instruction.
347   case ARMII::SizeSpecial: {
348     switch (MI->getOpcode()) {
349     case ARM::CONSTPOOL_ENTRY:
350       // If this machine instr is a constant pool entry, its size is recorded as
351       // operand #2.
352       return MI->getOperand(2).getImm();
353     case ARM::BR_JTr:
354     case ARM::BR_JTm:
355     case ARM::BR_JTadd: {
356       // These are jumptable branches, i.e. a branch followed by an inlined
357       // jumptable. The size is 4 + 4 * number of entries.
358       unsigned JTI = MI->getOperand(MI->getNumOperands()-2).getJumpTableIndex();
359       const MachineFunction *MF = MI->getParent()->getParent();
360       MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
361       const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
362       assert(JTI < JT.size());
363       return getNumJTEntries(JT, JTI) * 4 + 4;
364     }
365     default:
366       // Otherwise, pseudo-instruction sizes are zero.
367       return 0;
368     }
369   }
370   }
371 }
372
373 /// GetOffsetOf - Return the current offset of the specified machine instruction
374 /// from the start of the function.  This offset changes as stuff is moved
375 /// around inside the function.
376 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
377   MachineBasicBlock *MBB = MI->getParent();
378   
379   // The offset is composed of two things: the sum of the sizes of all MBB's
380   // before this instruction's block, and the offset from the start of the block
381   // it is in.
382   unsigned Offset = 0;
383   
384   // Sum block sizes before MBB.
385   for (unsigned BB = 0, e = MBB->getNumber(); BB != e; ++BB)
386     Offset += BBSizes[BB];
387
388   // Sum instructions before MI in MBB.
389   for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
390     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
391     if (&*I == MI) return Offset;
392     Offset += GetInstSize(I);
393   }
394 }
395
396 /// GetOffsetOf - Return the current offset of the specified machine BB
397 /// from the start of the function.  This offset changes as stuff is moved
398 /// around inside the function.
399 unsigned ARMConstantIslands::GetOffsetOf(MachineBasicBlock *MBB) const {
400   // Sum block sizes before MBB.
401   unsigned Offset = 0;  
402   for (unsigned BB = 0, e = MBB->getNumber(); BB != e; ++BB)
403     Offset += BBSizes[BB];
404
405   return Offset;
406 }
407
408 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
409 /// ID.
410 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
411                               const MachineBasicBlock *RHS) {
412   return LHS->getNumber() < RHS->getNumber();
413 }
414
415 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
416 /// machine function, it upsets all of the block numbers.  Renumber the blocks
417 /// and update the arrays that parallel this numbering.
418 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
419   // Renumber the MBB's to keep them consequtive.
420   NewBB->getParent()->RenumberBlocks(NewBB);
421   
422   // Insert a size into BBSizes to align it properly with the (newly
423   // renumbered) block numbers.
424   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
425   
426   // Next, update WaterList.  Specifically, we need to add NewMBB as having 
427   // available water after it.
428   std::vector<MachineBasicBlock*>::iterator IP =
429     std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
430                      CompareMBBNumbers);
431   WaterList.insert(IP, NewBB);
432 }
433
434
435 /// Split the basic block containing MI into two blocks, which are joined by
436 /// an unconditional branch.  Update datastructures and renumber blocks to
437 /// account for this change.
438 void ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
439   MachineBasicBlock *OrigBB = MI->getParent();
440   const ARMFunctionInfo *AFI = OrigBB->getParent()->getInfo<ARMFunctionInfo>();
441   bool isThumb = AFI->isThumbFunction();
442
443   // Create a new MBB for the code after the OrigBB.
444   MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
445   MachineFunction::iterator MBBI = OrigBB; ++MBBI;
446   OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
447   
448   // Splice the instructions starting with MI over to NewBB.
449   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
450   
451   // Add an unconditional branch from OrigBB to NewBB.
452   BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
453   NumSplit++;
454   
455   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
456   while (!OrigBB->succ_empty()) {
457     MachineBasicBlock *Succ = *OrigBB->succ_begin();
458     OrigBB->removeSuccessor(Succ);
459     NewBB->addSuccessor(Succ);
460     
461     // This pass should be run after register allocation, so there should be no
462     // PHI nodes to update.
463     assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
464            && "PHI nodes should be eliminated by now!");
465   }
466   
467   // OrigBB branches to NewBB.
468   OrigBB->addSuccessor(NewBB);
469   
470   // Update internal data structures to account for the newly inserted MBB.
471   UpdateForInsertedWaterBlock(NewBB);
472   
473   // Figure out how large the first NewMBB is.
474   unsigned NewBBSize = 0;
475   for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
476        I != E; ++I)
477     NewBBSize += GetInstSize(I);
478   
479   // Set the size of NewBB in BBSizes.
480   BBSizes[NewBB->getNumber()] = NewBBSize;
481   
482   // We removed instructions from UserMBB, subtract that off from its size.
483   // Add 2 or 4 to the block to count the unconditional branch we added to it.
484   BBSizes[OrigBB->getNumber()] -= NewBBSize - (isThumb ? 2 : 4);
485 }
486
487 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
488 /// is out-of-range.  If so, pick it up the constant pool value and move it some
489 /// place in-range.
490 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn, CPUser &U){
491   MachineInstr *UserMI = U.MI;
492   MachineInstr *CPEMI  = U.CPEMI;
493
494   unsigned UserOffset = GetOffsetOf(UserMI);
495   unsigned CPEOffset  = GetOffsetOf(CPEMI);
496   
497   DEBUG(std::cerr << "User of CPE#" << CPEMI->getOperand(0).getImm()
498                   << " max delta=" << U.MaxDisp
499                   << " at offset " << int(UserOffset-CPEOffset) << "\t"
500                   << *UserMI);
501
502   // Check to see if the CPE is already in-range.
503   if (UserOffset < CPEOffset) {
504     // User before the CPE.
505     if (CPEOffset-UserOffset <= U.MaxDisp)
506       return false;
507   } else {
508     if (UserOffset-CPEOffset <= U.MaxDisp)
509       return false;
510   }
511   
512  
513   // Solution guaranteed to work: split the user's MBB right before the user and
514   // insert a clone the CPE into the newly created water.
515   
516   // If the user isn't at the start of its MBB, or if there is a fall-through
517   // into the user's MBB, split the MBB before the User.
518   MachineBasicBlock *UserMBB = UserMI->getParent();
519   if (&UserMBB->front() != UserMI ||
520       UserMBB == &Fn.front() || // entry MBB of function.
521       BBHasFallthrough(prior(MachineFunction::iterator(UserMBB)))) {
522     // TODO: Search for the best place to split the code.  In practice, using
523     // loop nesting information to insert these guys outside of loops would be
524     // sufficient.    
525     SplitBlockBeforeInstr(UserMI);
526     
527     // UserMI's BB may have changed.
528     UserMBB = UserMI->getParent();
529   }
530   
531   // Okay, we know we can put an island before UserMBB now, do it!
532   MachineBasicBlock *NewIsland = new MachineBasicBlock();
533   Fn.getBasicBlockList().insert(UserMBB, NewIsland);
534
535   // Update internal data structures to account for the newly inserted MBB.
536   UpdateForInsertedWaterBlock(NewIsland);
537
538   // Now that we have an island to add the CPE to, clone the original CPE and
539   // add it to the island.
540   unsigned ID  = NextUID++;
541   unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
542   unsigned Size = CPEMI->getOperand(2).getImm();
543   
544   // Build a new CPE for this user.
545   U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
546                 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
547   
548   // Increase the size of the island block to account for the new entry.
549   BBSizes[NewIsland->getNumber()] += Size;
550   
551   // Finally, change the CPI in the instruction operand to be ID.
552   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
553     if (UserMI->getOperand(i).isConstantPoolIndex()) {
554       UserMI->getOperand(i).setConstantPoolIndex(ID);
555       break;
556     }
557       
558   DEBUG(std::cerr << "  Moved CPE to #" << ID << " CPI=" << CPI << "\t"
559                   << *UserMI);
560   
561       
562   return true;
563 }
564
565 /// BBIsInBranchRange - Returns true is the distance between specific MI and
566 /// specific BB can fit in MI's displacement field.
567 bool ARMConstantIslands::BBIsInBranchRange(MachineInstr *MI,
568                                            MachineBasicBlock *DestBB,
569                                            unsigned MaxDisp) {
570   unsigned BrOffset   = GetOffsetOf(MI);
571   unsigned DestOffset = GetOffsetOf(DestBB);
572
573   // Check to see if the destination BB is in range.
574   if (BrOffset < DestOffset) {
575     if (DestOffset - BrOffset < MaxDisp)
576       return true;
577   } else {
578     if (BrOffset - DestOffset <= MaxDisp)
579       return true;
580   }
581   return false;
582 }
583
584 static inline unsigned getUncondBranchDisp(int Opc) {
585   return (Opc == ARM::tB) ? (1<<10)*2 : (1<<23)*4;
586 }
587
588 /// FixUpImmediateBranch - Fix up immediate branches whose destination is too
589 /// far away to fit in its displacement field. If it is a conditional branch,
590 /// then it is converted to an inverse conditional branch + an unconditional
591 /// branch to the destination. If it is an unconditional branch, then it is
592 /// converted to a branch to a branch.
593 bool
594 ARMConstantIslands::FixUpImmediateBranch(MachineFunction &Fn, ImmBranch &Br) {
595   MachineInstr *MI = Br.MI;
596   MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
597
598   if (BBIsInBranchRange(MI, DestBB, Br.MaxDisp))
599     return false;
600
601   if (!Br.isCond) {
602     // Unconditional branch. We have to insert a branch somewhere to perform
603     // a two level branch (branch to branch). FIXME: not yet implemented.
604     assert(false && "Can't handle unconditional branch yet!");
605     return false;
606   }
607
608   // Otherwise, add a unconditional branch to the destination and 
609   // invert the branch condition to jump over it:
610   // blt L1
611   // =>
612   // bge L2
613   // b   L1
614   // L2:
615   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
616   CC = ARMCC::getOppositeCondition(CC);
617
618   // If the branch is at the end of its MBB and that has a fall-through block,
619   // direct the updated conditional branch to the fall-through block. Otherwise,
620   // split the MBB before the next instruction.
621   MachineBasicBlock *MBB = MI->getParent();
622   MachineInstr *BackMI = &MBB->back();
623   bool NeedSplit = (BackMI != MI) || !BBHasFallthrough(MBB);
624
625   if (BackMI != MI) {
626     if (next(MachineBasicBlock::iterator(MI)) == MBB->back() &&
627         BackMI->getOpcode() == Br.UncondBr) {
628       // Last MI in the BB is a unconditional branch. Can we simply invert the
629       // condition and swap destinations:
630       // beq L1
631       // b   L2
632       // =>
633       // bne L2
634       // b   L1
635       MachineBasicBlock *NewDest = BackMI->getOperand(0).getMachineBasicBlock();
636       if (BBIsInBranchRange(MI, NewDest, Br.MaxDisp)) {
637         BackMI->getOperand(0).setMachineBasicBlock(DestBB);
638         MI->getOperand(0).setMachineBasicBlock(NewDest);
639         MI->getOperand(1).setImm(CC);
640         return true;
641       }
642     }
643   }
644
645   if (NeedSplit) {
646     SplitBlockBeforeInstr(MI);
647     // No need for the branch to the next block. We're adding a unconditional
648     // branch to the destination.
649     MBB->back().eraseFromParent();
650   }
651   MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
652
653   // Insert a unconditional branch and replace the conditional branch.
654   // Also update the ImmBranch as well as adding a new entry for the new branch.
655   BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB).addImm(CC);
656   Br.MI = &MBB->back();
657   BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
658   unsigned MaxDisp = getUncondBranchDisp(Br.UncondBr);
659   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
660   MI->eraseFromParent();
661
662   // Increase the size of MBB to account for the new unconditional branch.
663   BBSizes[MBB->getNumber()] += GetInstSize(&MBB->back());
664   return true;
665 }