assert(0) -> LLVM_UNREACHABLE.
[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 is distributed under the University of Illinois Open Source
6 // 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/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/Statistic.h"
31 using namespace llvm;
32
33 STATISTIC(NumCPEs,     "Number of constpool entries");
34 STATISTIC(NumSplit,    "Number of uncond branches inserted");
35 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
36 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
37
38 namespace {
39   /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
40   /// requires constant pool entries to be scattered among the instructions
41   /// inside a function.  To do this, it completely ignores the normal LLVM
42   /// constant pool; instead, it places constants wherever it feels like with
43   /// special instructions.
44   ///
45   /// The terminology used in this pass includes:
46   ///   Islands - Clumps of constants placed in the function.
47   ///   Water   - Potential places where an island could be formed.
48   ///   CPE     - A constant pool entry that has been placed somewhere, which
49   ///             tracks a list of users.
50   class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
51     /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
52     /// by MBB Number.  The two-byte pads required for Thumb alignment are
53     /// counted as part of the following block (i.e., the offset and size for
54     /// a padded block will both be ==2 mod 4).
55     std::vector<unsigned> BBSizes;
56
57     /// BBOffsets - the offset of each MBB in bytes, starting from 0.
58     /// The two-byte pads required for Thumb alignment are counted as part of
59     /// the following block.
60     std::vector<unsigned> BBOffsets;
61
62     /// WaterList - A sorted list of basic blocks where islands could be placed
63     /// (i.e. blocks that don't fall through to the following block, due
64     /// to a return, unreachable, or unconditional branch).
65     std::vector<MachineBasicBlock*> WaterList;
66
67     /// CPUser - One user of a constant pool, keeping the machine instruction
68     /// pointer, the constant pool being referenced, and the max displacement
69     /// allowed from the instruction to the CP.
70     struct CPUser {
71       MachineInstr *MI;
72       MachineInstr *CPEMI;
73       unsigned MaxDisp;
74       CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
75         : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
76     };
77
78     /// CPUsers - Keep track of all of the machine instructions that use various
79     /// constant pools and their max displacement.
80     std::vector<CPUser> CPUsers;
81
82     /// CPEntry - One per constant pool entry, keeping the machine instruction
83     /// pointer, the constpool index, and the number of CPUser's which
84     /// reference this entry.
85     struct CPEntry {
86       MachineInstr *CPEMI;
87       unsigned CPI;
88       unsigned RefCount;
89       CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
90         : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
91     };
92
93     /// CPEntries - Keep track of all of the constant pool entry machine
94     /// instructions. For each original constpool index (i.e. those that
95     /// existed upon entry to this pass), it keeps a vector of entries.
96     /// Original elements are cloned as we go along; the clones are
97     /// put in the vector of the original element, but have distinct CPIs.
98     std::vector<std::vector<CPEntry> > CPEntries;
99
100     /// ImmBranch - One per immediate branch, keeping the machine instruction
101     /// pointer, conditional or unconditional, the max displacement,
102     /// and (if isCond is true) the corresponding unconditional branch
103     /// opcode.
104     struct ImmBranch {
105       MachineInstr *MI;
106       unsigned MaxDisp : 31;
107       bool isCond : 1;
108       int UncondBr;
109       ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
110         : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
111     };
112
113     /// ImmBranches - Keep track of all the immediate branch instructions.
114     ///
115     std::vector<ImmBranch> ImmBranches;
116
117     /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
118     ///
119     SmallVector<MachineInstr*, 4> PushPopMIs;
120
121     /// HasFarJump - True if any far jump instruction has been emitted during
122     /// the branch fix up pass.
123     bool HasFarJump;
124
125     const TargetInstrInfo *TII;
126     ARMFunctionInfo *AFI;
127     bool isThumb;
128     bool isThumb1Only;
129     bool isThumb2;
130   public:
131     static char ID;
132     ARMConstantIslands() : MachineFunctionPass(&ID) {}
133
134     virtual bool runOnMachineFunction(MachineFunction &Fn);
135
136     virtual const char *getPassName() const {
137       return "ARM constant island placement and branch shortening pass";
138     }
139
140   private:
141     void DoInitialPlacement(MachineFunction &Fn,
142                             std::vector<MachineInstr*> &CPEMIs);
143     CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
144     void InitialFunctionScan(MachineFunction &Fn,
145                              const std::vector<MachineInstr*> &CPEMIs);
146     MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
147     void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
148     void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
149     bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
150     int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
151     bool LookForWater(CPUser&U, unsigned UserOffset,
152                       MachineBasicBlock** NewMBB);
153     MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
154                         std::vector<MachineBasicBlock*>::iterator IP);
155     void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
156                       MachineBasicBlock** NewMBB);
157     bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
158     void RemoveDeadCPEMI(MachineInstr *CPEMI);
159     bool RemoveUnusedCPEntries();
160     bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
161                       MachineInstr *CPEMI, unsigned Disp,
162                       bool DoDump);
163     bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
164                         CPUser &U);
165     bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
166                         unsigned Disp, bool NegativeOK);
167     bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
168     bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
169     bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
170     bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
171     bool UndoLRSpillRestore();
172
173     unsigned GetOffsetOf(MachineInstr *MI) const;
174     void dumpBBs();
175     void verify(MachineFunction &Fn);
176   };
177   char ARMConstantIslands::ID = 0;
178 }
179
180 /// verify - check BBOffsets, BBSizes, alignment of islands
181 void ARMConstantIslands::verify(MachineFunction &Fn) {
182   assert(BBOffsets.size() == BBSizes.size());
183   for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
184     assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
185   if (isThumb) {
186     for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
187          MBBI != E; ++MBBI) {
188       MachineBasicBlock *MBB = MBBI;
189       if (!MBB->empty() &&
190           MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
191         assert((BBOffsets[MBB->getNumber()]%4 == 0 &&
192                 BBSizes[MBB->getNumber()]%4 == 0) ||
193                (BBOffsets[MBB->getNumber()]%4 != 0 &&
194                 BBSizes[MBB->getNumber()]%4 != 0));
195     }
196   }
197 }
198
199 /// print block size and offset information - debugging
200 void ARMConstantIslands::dumpBBs() {
201   for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
202     DOUT << "block " << J << " offset " << BBOffsets[J] <<
203                             " size " << BBSizes[J] << "\n";
204   }
205 }
206
207 /// createARMConstantIslandPass - returns an instance of the constpool
208 /// island pass.
209 FunctionPass *llvm::createARMConstantIslandPass() {
210   return new ARMConstantIslands();
211 }
212
213 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
214   MachineConstantPool &MCP = *Fn.getConstantPool();
215
216   TII = Fn.getTarget().getInstrInfo();
217   AFI = Fn.getInfo<ARMFunctionInfo>();
218   isThumb = AFI->isThumbFunction();
219   isThumb1Only = AFI->isThumb1OnlyFunction();
220   isThumb2 = AFI->isThumb2Function();
221
222   HasFarJump = false;
223
224   // Renumber all of the machine basic blocks in the function, guaranteeing that
225   // the numbers agree with the position of the block in the function.
226   Fn.RenumberBlocks();
227
228   /// Thumb functions containing constant pools get 2-byte alignment.
229   /// This is so we can keep exact track of where the alignment padding goes.
230   /// Set default.
231   AFI->setAlign(isThumb ? 1U : 2U);
232
233   // Perform the initial placement of the constant pool entries.  To start with,
234   // we put them all at the end of the function.
235   std::vector<MachineInstr*> CPEMIs;
236   if (!MCP.isEmpty()) {
237     DoInitialPlacement(Fn, CPEMIs);
238     if (isThumb)
239       AFI->setAlign(2U);
240   }
241
242   /// The next UID to take is the first unused one.
243   AFI->initConstPoolEntryUId(CPEMIs.size());
244
245   // Do the initial scan of the function, building up information about the
246   // sizes of each block, the location of all the water, and finding all of the
247   // constant pool users.
248   InitialFunctionScan(Fn, CPEMIs);
249   CPEMIs.clear();
250
251   /// Remove dead constant pool entries.
252   RemoveUnusedCPEntries();
253
254   // Iteratively place constant pool entries and fix up branches until there
255   // is no change.
256   bool MadeChange = false;
257   while (true) {
258     bool Change = false;
259     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
260       Change |= HandleConstantPoolUser(Fn, i);
261     DEBUG(dumpBBs());
262     for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
263       Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
264     DEBUG(dumpBBs());
265     if (!Change)
266       break;
267     MadeChange = true;
268   }
269
270   // After a while, this might be made debug-only, but it is not expensive.
271   verify(Fn);
272
273   // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
274   // Undo the spill / restore of LR if possible.
275   if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
276     MadeChange |= UndoLRSpillRestore();
277
278   BBSizes.clear();
279   BBOffsets.clear();
280   WaterList.clear();
281   CPUsers.clear();
282   CPEntries.clear();
283   ImmBranches.clear();
284   PushPopMIs.clear();
285
286   return MadeChange;
287 }
288
289 /// DoInitialPlacement - Perform the initial placement of the constant pool
290 /// entries.  To start with, we put them all at the end of the function.
291 void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
292                                         std::vector<MachineInstr*> &CPEMIs) {
293   // Create the basic block to hold the CPE's.
294   MachineBasicBlock *BB = Fn.CreateMachineBasicBlock();
295   Fn.push_back(BB);
296
297   // Add all of the constants from the constant pool to the end block, use an
298   // identity mapping of CPI's to CPE's.
299   const std::vector<MachineConstantPoolEntry> &CPs =
300     Fn.getConstantPool()->getConstants();
301
302   const TargetData &TD = *Fn.getTarget().getTargetData();
303   for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
304     unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
305     // Verify that all constant pool entries are a multiple of 4 bytes.  If not,
306     // we would have to pad them out or something so that instructions stay
307     // aligned.
308     assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
309     MachineInstr *CPEMI =
310       BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
311                            .addImm(i).addConstantPoolIndex(i).addImm(Size);
312     CPEMIs.push_back(CPEMI);
313
314     // Add a new CPEntry, but no corresponding CPUser yet.
315     std::vector<CPEntry> CPEs;
316     CPEs.push_back(CPEntry(CPEMI, i));
317     CPEntries.push_back(CPEs);
318     NumCPEs++;
319     DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
320   }
321 }
322
323 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
324 /// into the block immediately after it.
325 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
326   // Get the next machine basic block in the function.
327   MachineFunction::iterator MBBI = MBB;
328   if (next(MBBI) == MBB->getParent()->end())  // Can't fall off end of function.
329     return false;
330
331   MachineBasicBlock *NextBB = next(MBBI);
332   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
333        E = MBB->succ_end(); I != E; ++I)
334     if (*I == NextBB)
335       return true;
336
337   return false;
338 }
339
340 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
341 /// look up the corresponding CPEntry.
342 ARMConstantIslands::CPEntry
343 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
344                                         const MachineInstr *CPEMI) {
345   std::vector<CPEntry> &CPEs = CPEntries[CPI];
346   // Number of entries per constpool index should be small, just do a
347   // linear search.
348   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
349     if (CPEs[i].CPEMI == CPEMI)
350       return &CPEs[i];
351   }
352   return NULL;
353 }
354
355 /// InitialFunctionScan - Do the initial scan of the function, building up
356 /// information about the sizes of each block, the location of all the water,
357 /// and finding all of the constant pool users.
358 void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
359                                  const std::vector<MachineInstr*> &CPEMIs) {
360   unsigned Offset = 0;
361   for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
362        MBBI != E; ++MBBI) {
363     MachineBasicBlock &MBB = *MBBI;
364
365     // If this block doesn't fall through into the next MBB, then this is
366     // 'water' that a constant pool island could be placed.
367     if (!BBHasFallthrough(&MBB))
368       WaterList.push_back(&MBB);
369
370     unsigned MBBSize = 0;
371     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
372          I != E; ++I) {
373       // Add instruction size to MBBSize.
374       MBBSize += TII->GetInstSizeInBytes(I);
375
376       int Opc = I->getOpcode();
377       if (I->getDesc().isBranch()) {
378         bool isCond = false;
379         unsigned Bits = 0;
380         unsigned Scale = 1;
381         int UOpc = Opc;
382         switch (Opc) {
383         case ARM::tBR_JTr:
384         case ARM::t2BR_JTr:
385         case ARM::t2BR_JTm:
386         case ARM::t2BR_JTadd:
387           // A Thumb table jump may involve padding; for the offsets to
388           // be right, functions containing these must be 4-byte aligned.
389           AFI->setAlign(2U);
390           if ((Offset+MBBSize)%4 != 0)
391             MBBSize += 2;           // padding
392           continue;   // Does not get an entry in ImmBranches
393         default:
394           continue;  // Ignore other JT branches
395         case ARM::Bcc:
396           isCond = true;
397           UOpc = ARM::B;
398           // Fallthrough
399         case ARM::B:
400           Bits = 24;
401           Scale = 4;
402           break;
403         case ARM::tBcc:
404           isCond = true;
405           UOpc = ARM::tB;
406           Bits = 8;
407           Scale = 2;
408           break;
409         case ARM::tB:
410           Bits = 11;
411           Scale = 2;
412           break;
413         case ARM::t2Bcc:
414           isCond = true;
415           UOpc = ARM::t2B;
416           Bits = 20;
417           Scale = 2;
418           break;
419         case ARM::t2B:
420           Bits = 24;
421           Scale = 2;
422           break;
423         }
424
425         // Record this immediate branch.
426         unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
427         ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
428       }
429
430       if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
431         PushPopMIs.push_back(I);
432
433       // Scan the instructions for constant pool operands.
434       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
435         if (I->getOperand(op).isCPI()) {
436           // We found one.  The addressing mode tells us the max displacement
437           // from the PC that this instruction permits.
438
439           // Basic size info comes from the TSFlags field.
440           unsigned Bits = 0;
441           unsigned Scale = 1;
442           unsigned TSFlags = I->getDesc().TSFlags;
443           switch (TSFlags & ARMII::AddrModeMask) {
444           default:
445             // Constant pool entries can reach anything.
446             if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
447               continue;
448             if (I->getOpcode() == ARM::tLEApcrel) {
449               Bits = 8;  // Taking the address of a CP entry.
450               break;
451             }
452             LLVM_UNREACHABLE("Unknown addressing mode for CP reference!");
453           case ARMII::AddrMode1: // AM1: 8 bits << 2
454             Bits = 8;
455             Scale = 4;  // Taking the address of a CP entry.
456             break;
457           case ARMII::AddrMode2:
458             Bits = 12;  // +-offset_12
459             break;
460           case ARMII::AddrMode3:
461             Bits = 8;   // +-offset_8
462             break;
463             // addrmode4 has no immediate offset.
464           case ARMII::AddrMode5:
465             Bits = 8;
466             Scale = 4;  // +-(offset_8*4)
467             break;
468             // addrmode6 has no immediate offset.
469           case ARMII::AddrModeT1_1:
470             Bits = 5;  // +offset_5
471             break;
472           case ARMII::AddrModeT1_2:
473             Bits = 5;
474             Scale = 2;  // +(offset_5*2)
475             break;
476           case ARMII::AddrModeT1_4:
477             Bits = 5;
478             Scale = 4;  // +(offset_5*4)
479             break;
480           case ARMII::AddrModeT1_s:
481             Bits = 8;
482             Scale = 4;  // +(offset_8*4)
483             break;
484           case ARMII::AddrModeT2_pc:
485             Bits = 12;  // +-offset_12
486             break;
487           }
488
489           // Remember that this is a user of a CP entry.
490           unsigned CPI = I->getOperand(op).getIndex();
491           MachineInstr *CPEMI = CPEMIs[CPI];
492           unsigned MaxOffs = ((1 << Bits)-1) * Scale;
493           CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
494
495           // Increment corresponding CPEntry reference count.
496           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
497           assert(CPE && "Cannot find a corresponding CPEntry!");
498           CPE->RefCount++;
499
500           // Instructions can only use one CP entry, don't bother scanning the
501           // rest of the operands.
502           break;
503         }
504     }
505
506     // In thumb mode, if this block is a constpool island, we may need padding
507     // so it's aligned on 4 byte boundary.
508     if (isThumb &&
509         !MBB.empty() &&
510         MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
511         (Offset%4) != 0)
512       MBBSize += 2;
513
514     BBSizes.push_back(MBBSize);
515     BBOffsets.push_back(Offset);
516     Offset += MBBSize;
517   }
518 }
519
520 /// GetOffsetOf - Return the current offset of the specified machine instruction
521 /// from the start of the function.  This offset changes as stuff is moved
522 /// around inside the function.
523 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
524   MachineBasicBlock *MBB = MI->getParent();
525
526   // The offset is composed of two things: the sum of the sizes of all MBB's
527   // before this instruction's block, and the offset from the start of the block
528   // it is in.
529   unsigned Offset = BBOffsets[MBB->getNumber()];
530
531   // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
532   // alignment padding, and compensate if so.
533   if (isThumb &&
534       MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
535       Offset%4 != 0)
536     Offset += 2;
537
538   // Sum instructions before MI in MBB.
539   for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
540     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
541     if (&*I == MI) return Offset;
542     Offset += TII->GetInstSizeInBytes(I);
543   }
544 }
545
546 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
547 /// ID.
548 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
549                               const MachineBasicBlock *RHS) {
550   return LHS->getNumber() < RHS->getNumber();
551 }
552
553 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
554 /// machine function, it upsets all of the block numbers.  Renumber the blocks
555 /// and update the arrays that parallel this numbering.
556 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
557   // Renumber the MBB's to keep them consequtive.
558   NewBB->getParent()->RenumberBlocks(NewBB);
559
560   // Insert a size into BBSizes to align it properly with the (newly
561   // renumbered) block numbers.
562   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
563
564   // Likewise for BBOffsets.
565   BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
566
567   // Next, update WaterList.  Specifically, we need to add NewMBB as having
568   // available water after it.
569   std::vector<MachineBasicBlock*>::iterator IP =
570     std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
571                      CompareMBBNumbers);
572   WaterList.insert(IP, NewBB);
573 }
574
575
576 /// Split the basic block containing MI into two blocks, which are joined by
577 /// an unconditional branch.  Update datastructures and renumber blocks to
578 /// account for this change and returns the newly created block.
579 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
580   MachineBasicBlock *OrigBB = MI->getParent();
581   MachineFunction &MF = *OrigBB->getParent();
582
583   // Create a new MBB for the code after the OrigBB.
584   MachineBasicBlock *NewBB =
585     MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
586   MachineFunction::iterator MBBI = OrigBB; ++MBBI;
587   MF.insert(MBBI, NewBB);
588
589   // Splice the instructions starting with MI over to NewBB.
590   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
591
592   // Add an unconditional branch from OrigBB to NewBB.
593   // Note the new unconditional branch is not being recorded.
594   // There doesn't seem to be meaningful DebugInfo available; this doesn't
595   // correspond to anything in the source.
596   unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
597   BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
598   NumSplit++;
599
600   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
601   while (!OrigBB->succ_empty()) {
602     MachineBasicBlock *Succ = *OrigBB->succ_begin();
603     OrigBB->removeSuccessor(Succ);
604     NewBB->addSuccessor(Succ);
605
606     // This pass should be run after register allocation, so there should be no
607     // PHI nodes to update.
608     assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
609            && "PHI nodes should be eliminated by now!");
610   }
611
612   // OrigBB branches to NewBB.
613   OrigBB->addSuccessor(NewBB);
614
615   // Update internal data structures to account for the newly inserted MBB.
616   // This is almost the same as UpdateForInsertedWaterBlock, except that
617   // the Water goes after OrigBB, not NewBB.
618   MF.RenumberBlocks(NewBB);
619
620   // Insert a size into BBSizes to align it properly with the (newly
621   // renumbered) block numbers.
622   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
623
624   // Likewise for BBOffsets.
625   BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
626
627   // Next, update WaterList.  Specifically, we need to add OrigMBB as having
628   // available water after it (but not if it's already there, which happens
629   // when splitting before a conditional branch that is followed by an
630   // unconditional branch - in that case we want to insert NewBB).
631   std::vector<MachineBasicBlock*>::iterator IP =
632     std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
633                      CompareMBBNumbers);
634   MachineBasicBlock* WaterBB = *IP;
635   if (WaterBB == OrigBB)
636     WaterList.insert(next(IP), NewBB);
637   else
638     WaterList.insert(IP, OrigBB);
639
640   // Figure out how large the first NewMBB is.  (It cannot
641   // contain a constpool_entry or tablejump.)
642   unsigned NewBBSize = 0;
643   for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
644        I != E; ++I)
645     NewBBSize += TII->GetInstSizeInBytes(I);
646
647   unsigned OrigBBI = OrigBB->getNumber();
648   unsigned NewBBI = NewBB->getNumber();
649   // Set the size of NewBB in BBSizes.
650   BBSizes[NewBBI] = NewBBSize;
651
652   // We removed instructions from UserMBB, subtract that off from its size.
653   // Add 2 or 4 to the block to count the unconditional branch we added to it.
654   unsigned delta = isThumb ? 2 : 4;
655   BBSizes[OrigBBI] -= NewBBSize - delta;
656
657   // ...and adjust BBOffsets for NewBB accordingly.
658   BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
659
660   // All BBOffsets following these blocks must be modified.
661   AdjustBBOffsetsAfter(NewBB, delta);
662
663   return NewBB;
664 }
665
666 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
667 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
668 /// constant pool entry).
669 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
670                       unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
671   // On Thumb offsets==2 mod 4 are rounded down by the hardware for
672   // purposes of the displacement computation; compensate for that here.
673   // Effectively, the valid range of displacements is 2 bytes smaller for such
674   // references.
675   if (isThumb && UserOffset%4 !=0)
676     UserOffset -= 2;
677   // CPEs will be rounded up to a multiple of 4.
678   if (isThumb && TrialOffset%4 != 0)
679     TrialOffset += 2;
680
681   if (UserOffset <= TrialOffset) {
682     // User before the Trial.
683     if (TrialOffset-UserOffset <= MaxDisp)
684       return true;
685   } else if (NegativeOK) {
686     if (UserOffset-TrialOffset <= MaxDisp)
687       return true;
688   }
689   return false;
690 }
691
692 /// WaterIsInRange - Returns true if a CPE placed after the specified
693 /// Water (a basic block) will be in range for the specific MI.
694
695 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
696                          MachineBasicBlock* Water, CPUser &U)
697 {
698   unsigned MaxDisp = U.MaxDisp;
699   MachineFunction::iterator I = next(MachineFunction::iterator(Water));
700   unsigned CPEOffset = BBOffsets[Water->getNumber()] +
701                        BBSizes[Water->getNumber()];
702
703   // If the CPE is to be inserted before the instruction, that will raise
704   // the offset of the instruction.  (Currently applies only to ARM, so
705   // no alignment compensation attempted here.)
706   if (CPEOffset < UserOffset)
707     UserOffset += U.CPEMI->getOperand(2).getImm();
708
709   return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
710 }
711
712 /// CPEIsInRange - Returns true if the distance between specific MI and
713 /// specific ConstPool entry instruction can fit in MI's displacement field.
714 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
715                                       MachineInstr *CPEMI,
716                                       unsigned MaxDisp, bool DoDump) {
717   unsigned CPEOffset  = GetOffsetOf(CPEMI);
718   assert(CPEOffset%4 == 0 && "Misaligned CPE");
719
720   if (DoDump) {
721     DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
722          << " max delta=" << MaxDisp
723          << " insn address=" << UserOffset
724          << " CPE address=" << CPEOffset
725          << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
726   }
727
728   return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
729 }
730
731 #ifndef NDEBUG
732 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
733 /// unconditionally branches to its only successor.
734 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
735   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
736     return false;
737
738   MachineBasicBlock *Succ = *MBB->succ_begin();
739   MachineBasicBlock *Pred = *MBB->pred_begin();
740   MachineInstr *PredMI = &Pred->back();
741   if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
742       || PredMI->getOpcode() == ARM::t2B)
743     return PredMI->getOperand(0).getMBB() == Succ;
744   return false;
745 }
746 #endif // NDEBUG
747
748 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
749                                               int delta) {
750   MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
751   for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++) {
752     BBOffsets[i] += delta;
753     // If some existing blocks have padding, adjust the padding as needed, a
754     // bit tricky.  delta can be negative so don't use % on that.
755     if (isThumb) {
756       MachineBasicBlock *MBB = MBBI;
757       if (!MBB->empty()) {
758         // Constant pool entries require padding.
759         if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
760           unsigned oldOffset = BBOffsets[i] - delta;
761           if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
762             // add new padding
763             BBSizes[i] += 2;
764             delta += 2;
765           } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
766             // remove existing padding
767             BBSizes[i] -=2;
768             delta -= 2;
769           }
770         }
771         // Thumb jump tables require padding.  They should be at the end;
772         // following unconditional branches are removed by AnalyzeBranch.
773         MachineInstr *ThumbJTMI = NULL;
774         if ((prior(MBB->end())->getOpcode() == ARM::tBR_JTr)
775             || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTr)
776             || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTm)
777             || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTadd))
778           ThumbJTMI = prior(MBB->end());
779         if (ThumbJTMI) {
780           unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
781           unsigned oldMIOffset = newMIOffset - delta;
782           if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
783             // remove existing padding
784             BBSizes[i] -= 2;
785             delta -= 2;
786           } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
787             // add new padding
788             BBSizes[i] += 2;
789             delta += 2;
790           }
791         }
792         if (delta==0)
793           return;
794       }
795       MBBI = next(MBBI);
796     }
797   }
798 }
799
800 /// DecrementOldEntry - find the constant pool entry with index CPI
801 /// and instruction CPEMI, and decrement its refcount.  If the refcount
802 /// becomes 0 remove the entry and instruction.  Returns true if we removed
803 /// the entry, false if we didn't.
804
805 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
806   // Find the old entry. Eliminate it if it is no longer used.
807   CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
808   assert(CPE && "Unexpected!");
809   if (--CPE->RefCount == 0) {
810     RemoveDeadCPEMI(CPEMI);
811     CPE->CPEMI = NULL;
812     NumCPEs--;
813     return true;
814   }
815   return false;
816 }
817
818 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
819 /// if not, see if an in-range clone of the CPE is in range, and if so,
820 /// change the data structures so the user references the clone.  Returns:
821 /// 0 = no existing entry found
822 /// 1 = entry found, and there were no code insertions or deletions
823 /// 2 = entry found, and there were code insertions or deletions
824 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
825 {
826   MachineInstr *UserMI = U.MI;
827   MachineInstr *CPEMI  = U.CPEMI;
828
829   // Check to see if the CPE is already in-range.
830   if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
831     DOUT << "In range\n";
832     return 1;
833   }
834
835   // No.  Look for previously created clones of the CPE that are in range.
836   unsigned CPI = CPEMI->getOperand(1).getIndex();
837   std::vector<CPEntry> &CPEs = CPEntries[CPI];
838   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
839     // We already tried this one
840     if (CPEs[i].CPEMI == CPEMI)
841       continue;
842     // Removing CPEs can leave empty entries, skip
843     if (CPEs[i].CPEMI == NULL)
844       continue;
845     if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
846       DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
847       // Point the CPUser node to the replacement
848       U.CPEMI = CPEs[i].CPEMI;
849       // Change the CPI in the instruction operand to refer to the clone.
850       for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
851         if (UserMI->getOperand(j).isCPI()) {
852           UserMI->getOperand(j).setIndex(CPEs[i].CPI);
853           break;
854         }
855       // Adjust the refcount of the clone...
856       CPEs[i].RefCount++;
857       // ...and the original.  If we didn't remove the old entry, none of the
858       // addresses changed, so we don't need another pass.
859       return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
860     }
861   }
862   return 0;
863 }
864
865 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
866 /// the specific unconditional branch instruction.
867 static inline unsigned getUnconditionalBrDisp(int Opc) {
868   switch (Opc) {
869   case ARM::tB:
870     return ((1<<10)-1)*2;
871   case ARM::t2B:
872     return ((1<<23)-1)*2;
873   default:
874     break;
875   }
876   
877   return ((1<<23)-1)*4;
878 }
879
880 /// AcceptWater - Small amount of common code factored out of the following.
881
882 MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
883                           std::vector<MachineBasicBlock*>::iterator IP) {
884   DOUT << "found water in range\n";
885   // Remove the original WaterList entry; we want subsequent
886   // insertions in this vicinity to go after the one we're
887   // about to insert.  This considerably reduces the number
888   // of times we have to move the same CPE more than once.
889   WaterList.erase(IP);
890   // CPE goes before following block (NewMBB).
891   return next(MachineFunction::iterator(WaterBB));
892 }
893
894 /// LookForWater - look for an existing entry in the WaterList in which
895 /// we can place the CPE referenced from U so it's within range of U's MI.
896 /// Returns true if found, false if not.  If it returns true, *NewMBB
897 /// is set to the WaterList entry.
898 /// For ARM, we prefer the water that's farthest away.  For Thumb, prefer
899 /// water that will not introduce padding to water that will; within each
900 /// group, prefer the water that's farthest away.
901
902 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
903                                       MachineBasicBlock** NewMBB) {
904   std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
905   MachineBasicBlock* WaterBBThatWouldPad = NULL;
906   if (!WaterList.empty()) {
907     for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
908         B = WaterList.begin();; --IP) {
909       MachineBasicBlock* WaterBB = *IP;
910       if (WaterIsInRange(UserOffset, WaterBB, U)) {
911         if (isThumb &&
912             (BBOffsets[WaterBB->getNumber()] +
913              BBSizes[WaterBB->getNumber()])%4 != 0) {
914           // This is valid Water, but would introduce padding.  Remember
915           // it in case we don't find any Water that doesn't do this.
916           if (!WaterBBThatWouldPad) {
917             WaterBBThatWouldPad = WaterBB;
918             IPThatWouldPad = IP;
919           }
920         } else {
921           *NewMBB = AcceptWater(WaterBB, IP);
922           return true;
923         }
924     }
925       if (IP == B)
926         break;
927     }
928   }
929   if (isThumb && WaterBBThatWouldPad) {
930     *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
931     return true;
932   }
933   return false;
934 }
935
936 /// CreateNewWater - No existing WaterList entry will work for
937 /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
938 /// block is used if in range, and the conditional branch munged so control
939 /// flow is correct.  Otherwise the block is split to create a hole with an
940 /// unconditional branch around it.  In either case *NewMBB is set to a
941 /// block following which the new island can be inserted (the WaterList
942 /// is not adjusted).
943
944 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
945                         unsigned UserOffset, MachineBasicBlock** NewMBB) {
946   CPUser &U = CPUsers[CPUserIndex];
947   MachineInstr *UserMI = U.MI;
948   MachineInstr *CPEMI  = U.CPEMI;
949   MachineBasicBlock *UserMBB = UserMI->getParent();
950   unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
951                                BBSizes[UserMBB->getNumber()];
952   assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
953
954   // If the use is at the end of the block, or the end of the block
955   // is within range, make new water there.  (The addition below is
956   // for the unconditional branch we will be adding:  4 bytes on ARM,
957   // 2 on Thumb.  Possible Thumb alignment padding is allowed for
958   // inside OffsetIsInRange.
959   // If the block ends in an unconditional branch already, it is water,
960   // and is known to be out of range, so we'll always be adding a branch.)
961   if (&UserMBB->back() == UserMI ||
962       OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2: 4),
963            U.MaxDisp, !isThumb)) {
964     DOUT << "Split at end of block\n";
965     if (&UserMBB->back() == UserMI)
966       assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
967     *NewMBB = next(MachineFunction::iterator(UserMBB));
968     // Add an unconditional branch from UserMBB to fallthrough block.
969     // Record it for branch lengthening; this new branch will not get out of
970     // range, but if the preceding conditional branch is out of range, the
971     // targets will be exchanged, and the altered branch may be out of
972     // range, so the machinery has to know about it.
973     int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
974     BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
975             TII->get(UncondBr)).addMBB(*NewMBB);
976     unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
977     ImmBranches.push_back(ImmBranch(&UserMBB->back(),
978                           MaxDisp, false, UncondBr));
979     int delta = isThumb ? 2 : 4;
980     BBSizes[UserMBB->getNumber()] += delta;
981     AdjustBBOffsetsAfter(UserMBB, delta);
982   } else {
983     // What a big block.  Find a place within the block to split it.
984     // This is a little tricky on Thumb since instructions are 2 bytes
985     // and constant pool entries are 4 bytes: if instruction I references
986     // island CPE, and instruction I+1 references CPE', it will
987     // not work well to put CPE as far forward as possible, since then
988     // CPE' cannot immediately follow it (that location is 2 bytes
989     // farther away from I+1 than CPE was from I) and we'd need to create
990     // a new island.  So, we make a first guess, then walk through the
991     // instructions between the one currently being looked at and the
992     // possible insertion point, and make sure any other instructions
993     // that reference CPEs will be able to use the same island area;
994     // if not, we back up the insertion point.
995
996     // The 4 in the following is for the unconditional branch we'll be
997     // inserting (allows for long branch on Thumb).  Alignment of the
998     // island is handled inside OffsetIsInRange.
999     unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1000     // This could point off the end of the block if we've already got
1001     // constant pool entries following this block; only the last one is
1002     // in the water list.  Back past any possible branches (allow for a
1003     // conditional and a maximally long unconditional).
1004     if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
1005       BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
1006                               (isThumb ? 6 : 8);
1007     unsigned EndInsertOffset = BaseInsertOffset +
1008            CPEMI->getOperand(2).getImm();
1009     MachineBasicBlock::iterator MI = UserMI;
1010     ++MI;
1011     unsigned CPUIndex = CPUserIndex+1;
1012     for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1013          Offset < BaseInsertOffset;
1014          Offset += TII->GetInstSizeInBytes(MI),
1015             MI = next(MI)) {
1016       if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
1017         if (!OffsetIsInRange(Offset, EndInsertOffset,
1018               CPUsers[CPUIndex].MaxDisp, !isThumb)) {
1019           BaseInsertOffset -= (isThumb ? 2 : 4);
1020           EndInsertOffset -= (isThumb ? 2 : 4);
1021         }
1022         // This is overly conservative, as we don't account for CPEMIs
1023         // being reused within the block, but it doesn't matter much.
1024         EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1025         CPUIndex++;
1026       }
1027     }
1028     DOUT << "Split in middle of big block\n";
1029     *NewMBB = SplitBlockBeforeInstr(prior(MI));
1030   }
1031 }
1032
1033 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1034 /// is out-of-range.  If so, pick up the constant pool value and move it some
1035 /// place in-range.  Return true if we changed any addresses (thus must run
1036 /// another pass of branch lengthening), false otherwise.
1037 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
1038                                                 unsigned CPUserIndex) {
1039   CPUser &U = CPUsers[CPUserIndex];
1040   MachineInstr *UserMI = U.MI;
1041   MachineInstr *CPEMI  = U.CPEMI;
1042   unsigned CPI = CPEMI->getOperand(1).getIndex();
1043   unsigned Size = CPEMI->getOperand(2).getImm();
1044   MachineBasicBlock *NewMBB;
1045   // Compute this only once, it's expensive.  The 4 or 8 is the value the
1046   // hardware keeps in the PC (2 insns ahead of the reference).
1047   unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1048
1049   // Special case: tLEApcrel are two instructions MI's. The actual user is the
1050   // second instruction.
1051   if (UserMI->getOpcode() == ARM::tLEApcrel)
1052     UserOffset += 2;
1053
1054   // See if the current entry is within range, or there is a clone of it
1055   // in range.
1056   int result = LookForExistingCPEntry(U, UserOffset);
1057   if (result==1) return false;
1058   else if (result==2) return true;
1059
1060   // No existing clone of this CPE is within range.
1061   // We will be generating a new clone.  Get a UID for it.
1062   unsigned ID = AFI->createConstPoolEntryUId();
1063
1064   // Look for water where we can place this CPE.  We look for the farthest one
1065   // away that will work.  Forward references only for now (although later
1066   // we might find some that are backwards).
1067
1068   if (!LookForWater(U, UserOffset, &NewMBB)) {
1069     // No water found.
1070     DOUT << "No water found\n";
1071     CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
1072   }
1073
1074   // Okay, we know we can put an island before NewMBB now, do it!
1075   MachineBasicBlock *NewIsland = Fn.CreateMachineBasicBlock();
1076   Fn.insert(NewMBB, NewIsland);
1077
1078   // Update internal data structures to account for the newly inserted MBB.
1079   UpdateForInsertedWaterBlock(NewIsland);
1080
1081   // Decrement the old entry, and remove it if refcount becomes 0.
1082   DecrementOldEntry(CPI, CPEMI);
1083
1084   // Now that we have an island to add the CPE to, clone the original CPE and
1085   // add it to the island.
1086   U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1087                     TII->get(ARM::CONSTPOOL_ENTRY))
1088                 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1089   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1090   NumCPEs++;
1091
1092   BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1093   // Compensate for .align 2 in thumb mode.
1094   if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
1095     Size += 2;
1096   // Increase the size of the island block to account for the new entry.
1097   BBSizes[NewIsland->getNumber()] += Size;
1098   AdjustBBOffsetsAfter(NewIsland, Size);
1099
1100   // Finally, change the CPI in the instruction operand to be ID.
1101   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1102     if (UserMI->getOperand(i).isCPI()) {
1103       UserMI->getOperand(i).setIndex(ID);
1104       break;
1105     }
1106
1107   DOUT << "  Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
1108
1109   return true;
1110 }
1111
1112 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1113 /// sizes and offsets of impacted basic blocks.
1114 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1115   MachineBasicBlock *CPEBB = CPEMI->getParent();
1116   unsigned Size = CPEMI->getOperand(2).getImm();
1117   CPEMI->eraseFromParent();
1118   BBSizes[CPEBB->getNumber()] -= Size;
1119   // All succeeding offsets have the current size value added in, fix this.
1120   if (CPEBB->empty()) {
1121     // In thumb mode, the size of island may be  padded by two to compensate for
1122     // the alignment requirement.  Then it will now be 2 when the block is
1123     // empty, so fix this.
1124     // All succeeding offsets have the current size value added in, fix this.
1125     if (BBSizes[CPEBB->getNumber()] != 0) {
1126       Size += BBSizes[CPEBB->getNumber()];
1127       BBSizes[CPEBB->getNumber()] = 0;
1128     }
1129   }
1130   AdjustBBOffsetsAfter(CPEBB, -Size);
1131   // An island has only one predecessor BB and one successor BB. Check if
1132   // this BB's predecessor jumps directly to this BB's successor. This
1133   // shouldn't happen currently.
1134   assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1135   // FIXME: remove the empty blocks after all the work is done?
1136 }
1137
1138 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1139 /// are zero.
1140 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1141   unsigned MadeChange = false;
1142   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1143       std::vector<CPEntry> &CPEs = CPEntries[i];
1144       for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1145         if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1146           RemoveDeadCPEMI(CPEs[j].CPEMI);
1147           CPEs[j].CPEMI = NULL;
1148           MadeChange = true;
1149         }
1150       }
1151   }
1152   return MadeChange;
1153 }
1154
1155 /// BBIsInRange - Returns true if the distance between specific MI and
1156 /// specific BB can fit in MI's displacement field.
1157 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1158                                      unsigned MaxDisp) {
1159   unsigned PCAdj      = isThumb ? 4 : 8;
1160   unsigned BrOffset   = GetOffsetOf(MI) + PCAdj;
1161   unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1162
1163   DOUT << "Branch of destination BB#" << DestBB->getNumber()
1164        << " from BB#" << MI->getParent()->getNumber()
1165        << " max delta=" << MaxDisp
1166        << " from " << GetOffsetOf(MI) << " to " << DestOffset
1167        << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
1168
1169   if (BrOffset <= DestOffset) {
1170     // Branch before the Dest.
1171     if (DestOffset-BrOffset <= MaxDisp)
1172       return true;
1173   } else {
1174     if (BrOffset-DestOffset <= MaxDisp)
1175       return true;
1176   }
1177   return false;
1178 }
1179
1180 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1181 /// away to fit in its displacement field.
1182 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
1183   MachineInstr *MI = Br.MI;
1184   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1185
1186   // Check to see if the DestBB is already in-range.
1187   if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1188     return false;
1189
1190   if (!Br.isCond)
1191     return FixUpUnconditionalBr(Fn, Br);
1192   return FixUpConditionalBr(Fn, Br);
1193 }
1194
1195 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1196 /// too far away to fit in its displacement field. If the LR register has been
1197 /// spilled in the epilogue, then we can use BL to implement a far jump.
1198 /// Otherwise, add an intermediate branch instruction to a branch.
1199 bool
1200 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1201   MachineInstr *MI = Br.MI;
1202   MachineBasicBlock *MBB = MI->getParent();
1203   assert(isThumb && !isThumb2 && "Expected a Thumb-1 function!");
1204
1205   // Use BL to implement far jump.
1206   Br.MaxDisp = (1 << 21) * 2;
1207   MI->setDesc(TII->get(ARM::tBfar));
1208   BBSizes[MBB->getNumber()] += 2;
1209   AdjustBBOffsetsAfter(MBB, 2);
1210   HasFarJump = true;
1211   NumUBrFixed++;
1212
1213   DOUT << "  Changed B to long jump " << *MI;
1214
1215   return true;
1216 }
1217
1218 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1219 /// far away to fit in its displacement field. It is converted to an inverse
1220 /// conditional branch + an unconditional branch to the destination.
1221 bool
1222 ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1223   MachineInstr *MI = Br.MI;
1224   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1225
1226   // Add an unconditional branch to the destination and invert the branch
1227   // condition to jump over it:
1228   // blt L1
1229   // =>
1230   // bge L2
1231   // b   L1
1232   // L2:
1233   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1234   CC = ARMCC::getOppositeCondition(CC);
1235   unsigned CCReg = MI->getOperand(2).getReg();
1236
1237   // If the branch is at the end of its MBB and that has a fall-through block,
1238   // direct the updated conditional branch to the fall-through block. Otherwise,
1239   // split the MBB before the next instruction.
1240   MachineBasicBlock *MBB = MI->getParent();
1241   MachineInstr *BMI = &MBB->back();
1242   bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1243
1244   NumCBrFixed++;
1245   if (BMI != MI) {
1246     if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1247         BMI->getOpcode() == Br.UncondBr) {
1248       // Last MI in the BB is an unconditional branch. Can we simply invert the
1249       // condition and swap destinations:
1250       // beq L1
1251       // b   L2
1252       // =>
1253       // bne L2
1254       // b   L1
1255       MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1256       if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1257         DOUT << "  Invert Bcc condition and swap its destination with " << *BMI;
1258         BMI->getOperand(0).setMBB(DestBB);
1259         MI->getOperand(0).setMBB(NewDest);
1260         MI->getOperand(1).setImm(CC);
1261         return true;
1262       }
1263     }
1264   }
1265
1266   if (NeedSplit) {
1267     SplitBlockBeforeInstr(MI);
1268     // No need for the branch to the next block. We're adding an unconditional
1269     // branch to the destination.
1270     int delta = TII->GetInstSizeInBytes(&MBB->back());
1271     BBSizes[MBB->getNumber()] -= delta;
1272     MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1273     AdjustBBOffsetsAfter(SplitBB, -delta);
1274     MBB->back().eraseFromParent();
1275     // BBOffsets[SplitBB] is wrong temporarily, fixed below
1276   }
1277   MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1278
1279   DOUT << "  Insert B to BB#" << DestBB->getNumber()
1280        << " also invert condition and change dest. to BB#"
1281        << NextBB->getNumber() << "\n";
1282
1283   // Insert a new conditional branch and a new unconditional branch.
1284   // Also update the ImmBranch as well as adding a new entry for the new branch.
1285   BuildMI(MBB, DebugLoc::getUnknownLoc(),
1286           TII->get(MI->getOpcode()))
1287     .addMBB(NextBB).addImm(CC).addReg(CCReg);
1288   Br.MI = &MBB->back();
1289   BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1290   BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1291   BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1292   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1293   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1294
1295   // Remove the old conditional branch.  It may or may not still be in MBB.
1296   BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
1297   MI->eraseFromParent();
1298
1299   // The net size change is an addition of one unconditional branch.
1300   int delta = TII->GetInstSizeInBytes(&MBB->back());
1301   AdjustBBOffsetsAfter(MBB, delta);
1302   return true;
1303 }
1304
1305 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1306 /// LR / restores LR to pc.
1307 bool ARMConstantIslands::UndoLRSpillRestore() {
1308   bool MadeChange = false;
1309   for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1310     MachineInstr *MI = PushPopMIs[i];
1311     if (MI->getOpcode() == ARM::tPOP_RET &&
1312         MI->getOperand(0).getReg() == ARM::PC &&
1313         MI->getNumExplicitOperands() == 1) {
1314       BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
1315       MI->eraseFromParent();
1316       MadeChange = true;
1317     }
1318   }
1319   return MadeChange;
1320 }