Add intelligence about where to break large blocks.
[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/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/Statistic.h"
30 using namespace llvm;
31
32 STATISTIC(NumCPEs,     "Number of constpool entries");
33 STATISTIC(NumSplit,    "Number of uncond branches inserted");
34 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
35 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
36
37 namespace {
38   /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
39   /// requires constant pool entries to be scattered among the instructions
40   /// inside a function.  To do this, it completely ignores the normal LLVM
41   /// constant pool; instead, it places constants wherever it feels like with
42   /// special instructions.
43   ///
44   /// The terminology used in this pass includes:
45   ///   Islands - Clumps of constants placed in the function.
46   ///   Water   - Potential places where an island could be formed.
47   ///   CPE     - A constant pool entry that has been placed somewhere, which
48   ///             tracks a list of users.
49   class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
50     /// NextUID - Assign unique ID's to CPE's.
51     unsigned NextUID;
52
53     /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
54     /// by MBB Number.
55     std::vector<unsigned> BBSizes;
56     
57     /// BBOffsets - the offset of each MBB in bytes, starting from 0.
58     std::vector<unsigned> BBOffsets;
59
60     /// WaterList - A sorted list of basic blocks where islands could be placed
61     /// (i.e. blocks that don't fall through to the following block, due
62     /// to a return, unreachable, or unconditional branch).
63     std::vector<MachineBasicBlock*> WaterList;
64
65     /// CPUser - One user of a constant pool, keeping the machine instruction
66     /// pointer, the constant pool being referenced, and the max displacement
67     /// allowed from the instruction to the CP.
68     struct CPUser {
69       MachineInstr *MI;
70       MachineInstr *CPEMI;
71       unsigned MaxDisp;
72       CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
73         : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
74     };
75     
76     /// CPUsers - Keep track of all of the machine instructions that use various
77     /// constant pools and their max displacement.
78     std::vector<CPUser> CPUsers;
79     
80     /// CPEntry - One per constant pool entry, keeping the machine instruction
81     /// pointer, the constpool index, and the number of CPUser's which
82     /// reference this entry.
83     struct CPEntry {
84       MachineInstr *CPEMI;
85       unsigned CPI;
86       unsigned RefCount;
87       CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
88         : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
89     };
90
91     /// CPEntries - Keep track of all of the constant pool entry machine
92     /// instructions. For each original constpool index (i.e. those that
93     /// existed upon entry to this pass), it keeps a vector of entries.
94     /// Original elements are cloned as we go along; the clones are
95     /// put in the vector of the original element, but have distinct CPIs.
96     std::vector<std::vector<CPEntry> > CPEntries;
97     
98     /// ImmBranch - One per immediate branch, keeping the machine instruction
99     /// pointer, conditional or unconditional, the max displacement,
100     /// and (if isCond is true) the corresponding unconditional branch
101     /// opcode.
102     struct ImmBranch {
103       MachineInstr *MI;
104       unsigned MaxDisp : 31;
105       bool isCond : 1;
106       int UncondBr;
107       ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
108         : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
109     };
110
111     /// Branches - Keep track of all the immediate branch instructions.
112     ///
113     std::vector<ImmBranch> ImmBranches;
114
115     /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
116     ///
117     SmallVector<MachineInstr*, 4> PushPopMIs;
118
119     /// HasFarJump - True if any far jump instruction has been emitted during
120     /// the branch fix up pass.
121     bool HasFarJump;
122
123     const TargetInstrInfo *TII;
124     const ARMFunctionInfo *AFI;
125   public:
126     virtual bool runOnMachineFunction(MachineFunction &Fn);
127
128     virtual const char *getPassName() const {
129       return "ARM constant island placement and branch shortening pass";
130     }
131     
132   private:
133     void DoInitialPlacement(MachineFunction &Fn,
134                             std::vector<MachineInstr*> &CPEMIs);
135     CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
136     void InitialFunctionScan(MachineFunction &Fn,
137                              const std::vector<MachineInstr*> &CPEMIs);
138     MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
139     void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
140     void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
141     bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI, unsigned Size);
142     int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
143     bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
144     bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset, 
145                       MachineInstr *CPEMI, unsigned Disp,
146                       bool DoDump);
147     bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
148                         unsigned Disp);
149     bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
150                         unsigned Disp, bool NegativeOK);
151     bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
152     bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
153     bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
154     bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
155     bool UndoLRSpillRestore();
156
157     unsigned GetOffsetOf(MachineInstr *MI) const;
158   };
159 }
160
161 /// createARMConstantIslandPass - returns an instance of the constpool
162 /// island pass.
163 FunctionPass *llvm::createARMConstantIslandPass() {
164   return new ARMConstantIslands();
165 }
166
167 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
168   MachineConstantPool &MCP = *Fn.getConstantPool();
169   
170   TII = Fn.getTarget().getInstrInfo();
171   AFI = Fn.getInfo<ARMFunctionInfo>();
172
173   HasFarJump = false;
174
175   // Renumber all of the machine basic blocks in the function, guaranteeing that
176   // the numbers agree with the position of the block in the function.
177   Fn.RenumberBlocks();
178
179   // Perform the initial placement of the constant pool entries.  To start with,
180   // we put them all at the end of the function.
181   std::vector<MachineInstr*> CPEMIs;
182   if (!MCP.isEmpty())
183     DoInitialPlacement(Fn, CPEMIs);
184   
185   /// The next UID to take is the first unused one.
186   NextUID = CPEMIs.size();
187   
188   // Do the initial scan of the function, building up information about the
189   // sizes of each block, the location of all the water, and finding all of the
190   // constant pool users.
191   InitialFunctionScan(Fn, CPEMIs);
192   CPEMIs.clear();
193   
194   // Iteratively place constant pool entries and fix up branches until there
195   // is no change.
196   bool MadeChange = false;
197   while (true) {
198     bool Change = false;
199     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
200       Change |= HandleConstantPoolUser(Fn, i);
201     for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
202       Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
203     if (!Change)
204       break;
205     MadeChange = true;
206   }
207   
208   // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
209   // Undo the spill / restore of LR if possible.
210   if (!HasFarJump && AFI->isLRForceSpilled() && AFI->isThumbFunction())
211     MadeChange |= UndoLRSpillRestore();
212
213   BBSizes.clear();
214   BBOffsets.clear();
215   WaterList.clear();
216   CPUsers.clear();
217   CPEntries.clear();
218   ImmBranches.clear();
219   PushPopMIs.clear();
220
221   return MadeChange;
222 }
223
224 /// DoInitialPlacement - Perform the initial placement of the constant pool
225 /// entries.  To start with, we put them all at the end of the function.
226 void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
227                                         std::vector<MachineInstr*> &CPEMIs){
228   // Create the basic block to hold the CPE's.
229   MachineBasicBlock *BB = new MachineBasicBlock();
230   Fn.getBasicBlockList().push_back(BB);
231   
232   // Add all of the constants from the constant pool to the end block, use an
233   // identity mapping of CPI's to CPE's.
234   const std::vector<MachineConstantPoolEntry> &CPs =
235     Fn.getConstantPool()->getConstants();
236   
237   const TargetData &TD = *Fn.getTarget().getTargetData();
238   for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
239     unsigned Size = TD.getTypeSize(CPs[i].getType());
240     // Verify that all constant pool entries are a multiple of 4 bytes.  If not,
241     // we would have to pad them out or something so that instructions stay
242     // aligned.
243     assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
244     MachineInstr *CPEMI =
245       BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
246                            .addImm(i).addConstantPoolIndex(i).addImm(Size);
247     CPEMIs.push_back(CPEMI);
248
249     // Add a new CPEntry, but no corresponding CPUser yet.
250     std::vector<CPEntry> CPEs;
251     CPEs.push_back(CPEntry(CPEMI, i));
252     CPEntries.push_back(CPEs);
253     NumCPEs++;
254     DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
255   }
256 }
257
258 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
259 /// into the block immediately after it.
260 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
261   // Get the next machine basic block in the function.
262   MachineFunction::iterator MBBI = MBB;
263   if (next(MBBI) == MBB->getParent()->end())  // Can't fall off end of function.
264     return false;
265   
266   MachineBasicBlock *NextBB = next(MBBI);
267   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
268        E = MBB->succ_end(); I != E; ++I)
269     if (*I == NextBB)
270       return true;
271   
272   return false;
273 }
274
275 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
276 /// look up the corresponding CPEntry.
277 ARMConstantIslands::CPEntry
278 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
279                                         const MachineInstr *CPEMI) {
280   std::vector<CPEntry> &CPEs = CPEntries[CPI];
281   // Number of entries per constpool index should be small, just do a
282   // linear search.
283   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
284     if (CPEs[i].CPEMI == CPEMI)
285       return &CPEs[i];
286   }
287   return NULL;
288 }
289
290 /// InitialFunctionScan - Do the initial scan of the function, building up
291 /// information about the sizes of each block, the location of all the water,
292 /// and finding all of the constant pool users.
293 void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
294                                  const std::vector<MachineInstr*> &CPEMIs) {
295   unsigned Offset = 0;
296   for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
297        MBBI != E; ++MBBI) {
298     MachineBasicBlock &MBB = *MBBI;
299     
300     // If this block doesn't fall through into the next MBB, then this is
301     // 'water' that a constant pool island could be placed.
302     if (!BBHasFallthrough(&MBB))
303       WaterList.push_back(&MBB);
304     
305     unsigned MBBSize = 0;
306     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
307          I != E; ++I) {
308       // Add instruction size to MBBSize.
309       MBBSize += ARM::GetInstSize(I);
310
311       int Opc = I->getOpcode();
312       if (TII->isBranch(Opc)) {
313         bool isCond = false;
314         unsigned Bits = 0;
315         unsigned Scale = 1;
316         int UOpc = Opc;
317         switch (Opc) {
318         default:
319           continue;  // Ignore JT branches
320         case ARM::Bcc:
321           isCond = true;
322           UOpc = ARM::B;
323           // Fallthrough
324         case ARM::B:
325           Bits = 24;
326           Scale = 4;
327           break;
328         case ARM::tBcc:
329           isCond = true;
330           UOpc = ARM::tB;
331           Bits = 8;
332           Scale = 2;
333           break;
334         case ARM::tB:
335           Bits = 11;
336           Scale = 2;
337           break;
338         }
339
340         // Record this immediate branch.
341         unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
342         ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
343       }
344
345       if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
346         PushPopMIs.push_back(I);
347
348       // Scan the instructions for constant pool operands.
349       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
350         if (I->getOperand(op).isConstantPoolIndex()) {
351           // We found one.  The addressing mode tells us the max displacement
352           // from the PC that this instruction permits.
353           
354           // Basic size info comes from the TSFlags field.
355           unsigned Bits = 0;
356           unsigned Scale = 1;
357           unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
358           switch (TSFlags & ARMII::AddrModeMask) {
359           default: 
360             // Constant pool entries can reach anything.
361             if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
362               continue;
363             assert(0 && "Unknown addressing mode for CP reference!");
364           case ARMII::AddrMode1: // AM1: 8 bits << 2
365             Bits = 8;
366             Scale = 4;  // Taking the address of a CP entry.
367             break;
368           case ARMII::AddrMode2:
369             Bits = 12;  // +-offset_12
370             break;
371           case ARMII::AddrMode3:
372             Bits = 8;   // +-offset_8
373             break;
374             // addrmode4 has no immediate offset.
375           case ARMII::AddrMode5:
376             Bits = 8;
377             Scale = 4;  // +-(offset_8*4)
378             break;
379           case ARMII::AddrModeT1:
380             Bits = 5;  // +offset_5
381             break;
382           case ARMII::AddrModeT2:
383             Bits = 5;
384             Scale = 2;  // +(offset_5*2)
385             break;
386           case ARMII::AddrModeT4:
387             Bits = 5;
388             Scale = 4;  // +(offset_5*4)
389             break;
390           case ARMII::AddrModeTs:
391             Bits = 8;
392             Scale = 4;  // +(offset_8*4)
393             break;
394           }
395
396           // Remember that this is a user of a CP entry.
397           unsigned CPI = I->getOperand(op).getConstantPoolIndex();
398           MachineInstr *CPEMI = CPEMIs[CPI];
399           unsigned MaxOffs = ((1 << Bits)-1) * Scale;          
400           CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
401
402           // Increment corresponding CPEntry reference count.
403           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
404           assert(CPE && "Cannot find a corresponding CPEntry!");
405           CPE->RefCount++;
406           
407           // Instructions can only use one CP entry, don't bother scanning the
408           // rest of the operands.
409           break;
410         }
411     }
412
413     // In thumb mode, if this block is a constpool island, pessimistically 
414     // assume it needs to be padded by two byte so it's aligned on 4 byte 
415     // boundary.
416     if (AFI->isThumbFunction() &&
417         !MBB.empty() &&
418         MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
419       MBBSize += 2;
420
421     BBSizes.push_back(MBBSize);
422     BBOffsets.push_back(Offset);
423     Offset += MBBSize;
424   }
425 }
426
427 /// GetOffsetOf - Return the current offset of the specified machine instruction
428 /// from the start of the function.  This offset changes as stuff is moved
429 /// around inside the function.
430 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
431   MachineBasicBlock *MBB = MI->getParent();
432   
433   // The offset is composed of two things: the sum of the sizes of all MBB's
434   // before this instruction's block, and the offset from the start of the block
435   // it is in.
436   unsigned Offset = BBOffsets[MBB->getNumber()];
437
438   // Sum instructions before MI in MBB.
439   for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
440     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
441     if (&*I == MI) return Offset;
442     Offset += ARM::GetInstSize(I);
443   }
444 }
445
446 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
447 /// ID.
448 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
449                               const MachineBasicBlock *RHS) {
450   return LHS->getNumber() < RHS->getNumber();
451 }
452
453 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
454 /// machine function, it upsets all of the block numbers.  Renumber the blocks
455 /// and update the arrays that parallel this numbering.
456 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
457   // Renumber the MBB's to keep them consequtive.
458   NewBB->getParent()->RenumberBlocks(NewBB);
459   
460   // Insert a size into BBSizes to align it properly with the (newly
461   // renumbered) block numbers.
462   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
463
464   // Likewise for BBOffsets.
465   BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
466   
467   // Next, update WaterList.  Specifically, we need to add NewMBB as having 
468   // available water after it.
469   std::vector<MachineBasicBlock*>::iterator IP =
470     std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
471                      CompareMBBNumbers);
472   WaterList.insert(IP, NewBB);
473 }
474
475
476 /// Split the basic block containing MI into two blocks, which are joined by
477 /// an unconditional branch.  Update datastructures and renumber blocks to
478 /// account for this change and returns the newly created block.
479 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
480   MachineBasicBlock *OrigBB = MI->getParent();
481   bool isThumb = AFI->isThumbFunction();
482
483   // Create a new MBB for the code after the OrigBB.
484   MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
485   MachineFunction::iterator MBBI = OrigBB; ++MBBI;
486   OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
487   
488   // Splice the instructions starting with MI over to NewBB.
489   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
490   
491   // Add an unconditional branch from OrigBB to NewBB.
492   // Note the new unconditional branch is not being recorded.
493   BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
494   NumSplit++;
495   
496   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
497   while (!OrigBB->succ_empty()) {
498     MachineBasicBlock *Succ = *OrigBB->succ_begin();
499     OrigBB->removeSuccessor(Succ);
500     NewBB->addSuccessor(Succ);
501     
502     // This pass should be run after register allocation, so there should be no
503     // PHI nodes to update.
504     assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
505            && "PHI nodes should be eliminated by now!");
506   }
507   
508   // OrigBB branches to NewBB.
509   OrigBB->addSuccessor(NewBB);
510   
511   // Update internal data structures to account for the newly inserted MBB.
512   // This is almost the same as UpdateForInsertedWaterBlock, except that
513   // the Water goes after OrigBB, not NewBB.
514   NewBB->getParent()->RenumberBlocks(NewBB);
515   
516   // Insert a size into BBSizes to align it properly with the (newly
517   // renumbered) block numbers.
518   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
519   
520   // Likewise for BBOffsets.
521   BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
522
523   // Next, update WaterList.  Specifically, we need to add OrigMBB as having 
524   // available water after it (but not if it's already there, which happens
525   // when splitting before a conditional branch that is followed by an
526   // unconditional branch - in that case we want to insert NewBB).
527   std::vector<MachineBasicBlock*>::iterator IP =
528     std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
529                      CompareMBBNumbers);
530   MachineBasicBlock* WaterBB = *IP;
531   if (WaterBB == OrigBB)
532     WaterList.insert(next(IP), NewBB);
533   else
534     WaterList.insert(IP, OrigBB);
535
536   // Figure out how large the first NewMBB is.
537   unsigned NewBBSize = 0;
538   for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
539        I != E; ++I)
540     NewBBSize += ARM::GetInstSize(I);
541   
542   unsigned OrigBBI = OrigBB->getNumber();
543   unsigned NewBBI = NewBB->getNumber();
544   // Set the size of NewBB in BBSizes.
545   BBSizes[NewBBI] = NewBBSize;
546   
547   // We removed instructions from UserMBB, subtract that off from its size.
548   // Add 2 or 4 to the block to count the unconditional branch we added to it.
549   unsigned delta = isThumb ? 2 : 4;
550   BBSizes[OrigBBI] -= NewBBSize - delta;
551
552   // ...and adjust BBOffsets for NewBB accordingly.
553   BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
554
555   // All BBOffsets following these blocks must be modified.
556   AdjustBBOffsetsAfter(NewBB, delta);
557
558   return NewBB;
559 }
560
561 /// OffsetIsInRange - Checks whether UserOffset is within MaxDisp of
562 /// TrialOffset.
563 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset, 
564                       unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
565   if (UserOffset <= TrialOffset) {
566     // User before the Trial.
567     if (TrialOffset-UserOffset <= MaxDisp)
568       return true;
569   } else if (NegativeOK) {
570     if (UserOffset-TrialOffset <= MaxDisp)
571       return true;
572   }
573   return false;
574 }
575
576 /// WaterIsInRange - Returns true if a CPE placed after the specified
577 /// Water (a basic block) will be in range for the specific MI.
578
579 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
580                          MachineBasicBlock* Water, unsigned MaxDisp)
581 {
582   bool isThumb = AFI->isThumbFunction();
583   unsigned CPEOffset = BBOffsets[Water->getNumber()] + 
584                        BBSizes[Water->getNumber()];
585   // If the Water is a constpool island, it has already been aligned.
586   // If not, align it.
587   if (isThumb &&
588       (Water->empty() ||
589        Water->begin()->getOpcode() != ARM::CONSTPOOL_ENTRY))
590     CPEOffset += 2;
591
592   return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
593 }
594
595 /// CPEIsInRange - Returns true if the distance between specific MI and
596 /// specific ConstPool entry instruction can fit in MI's displacement field.
597 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
598                                       MachineInstr *CPEMI,
599                                       unsigned MaxDisp, bool DoDump) {
600   // In thumb mode, pessimistically assumes the .align 2 before the first CPE
601   // in the island adds two byte padding.
602   bool isThumb = AFI->isThumbFunction();
603   unsigned AlignAdj   = isThumb ? 2 : 0;
604   unsigned CPEOffset  = GetOffsetOf(CPEMI) + AlignAdj;
605
606   if (DoDump) {
607     DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
608          << " max delta=" << MaxDisp
609          << " insn address=" << UserOffset
610          << " CPE address=" << CPEOffset
611          << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
612   }
613
614   return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
615 }
616
617 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
618 /// unconditionally branches to its only successor.
619 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
620   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
621     return false;
622
623   MachineBasicBlock *Succ = *MBB->succ_begin();
624   MachineBasicBlock *Pred = *MBB->pred_begin();
625   MachineInstr *PredMI = &Pred->back();
626   if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB)
627     return PredMI->getOperand(0).getMBB() == Succ;
628   return false;
629 }
630
631 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta)
632 {
633   MachineFunction::iterator MBBI = BB->getParent()->end();
634   for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++)
635     BBOffsets[i] += delta;
636 }
637
638 /// DecrementOldEntry - find the constant pool entry with index CPI
639 /// and instruction CPEMI, and decrement its refcount.  If the refcount
640 /// becomes 0 remove the entry and instruction.  Returns true if we removed 
641 /// the entry, false if we didn't.
642
643 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI, 
644                               unsigned Size) {
645   // Find the old entry. Eliminate it if it is no longer used.
646   CPEntry *OldCPE = findConstPoolEntry(CPI, CPEMI);
647   assert(OldCPE && "Unexpected!");
648   if (--OldCPE->RefCount == 0) {
649     MachineBasicBlock *OldCPEBB = OldCPE->CPEMI->getParent();
650     if (OldCPEBB->empty()) {
651       // In thumb mode, the size of island is padded by two to compensate for
652       // the alignment requirement.  Thus it will now be 2 when the block is
653       // empty, so fix this.
654       // All succeeding offsets have the current size value added in, fix this.
655       if (BBSizes[OldCPEBB->getNumber()] != 0) {
656         AdjustBBOffsetsAfter(OldCPEBB, -BBSizes[OldCPEBB->getNumber()]);
657         BBSizes[OldCPEBB->getNumber()] = 0;
658       }
659       // An island has only one predecessor BB and one successor BB. Check if
660       // this BB's predecessor jumps directly to this BB's successor. This
661       // shouldn't happen currently.
662       assert(!BBIsJumpedOver(OldCPEBB) && "How did this happen?");
663       // FIXME: remove the empty blocks after all the work is done?
664     } else {
665       BBSizes[OldCPEBB->getNumber()] -= Size;
666       // All succeeding offsets have the current size value added in, fix this.
667       AdjustBBOffsetsAfter(OldCPEBB, -Size);
668     }
669     OldCPE->CPEMI->eraseFromParent();
670     OldCPE->CPEMI = NULL;
671     NumCPEs--;
672     return true;
673   }
674   return false;
675 }
676
677 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
678 /// if not, see if an in-range clone of the CPE is in range, and if so,
679 /// change the data structures so the user references the clone.  Returns:
680 /// 0 = no existing entry found
681 /// 1 = entry found, and there were no code insertions or deletions
682 /// 2 = entry found, and there were code insertions or deletions
683 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
684 {
685   MachineInstr *UserMI = U.MI;
686   MachineInstr *CPEMI  = U.CPEMI;
687
688   // Check to see if the CPE is already in-range.
689   if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
690     DOUT << "In range\n";
691     return 1;
692   }
693
694   // No.  Look for previously created clones of the CPE that are in range.
695   unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
696   std::vector<CPEntry> &CPEs = CPEntries[CPI];
697   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
698     // We already tried this one
699     if (CPEs[i].CPEMI == CPEMI)
700       continue;
701     // Removing CPEs can leave empty entries, skip
702     if (CPEs[i].CPEMI == NULL)
703       continue;
704     if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
705       DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
706       // Point the CPUser node to the replacement
707       U.CPEMI = CPEs[i].CPEMI;
708       // Change the CPI in the instruction operand to refer to the clone.
709       for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
710         if (UserMI->getOperand(j).isConstantPoolIndex()) {
711           UserMI->getOperand(j).setConstantPoolIndex(CPEs[i].CPI);
712           break;
713         }
714       // Adjust the refcount of the clone...
715       CPEs[i].RefCount++;
716       // ...and the original.  If we didn't remove the old entry, none of the
717       // addresses changed, so we don't need another pass.
718       unsigned Size = CPEMI->getOperand(2).getImm();
719       return DecrementOldEntry(CPI, CPEMI, Size) ? 2 : 1;
720     }
721   }
722   return 0;
723 }
724
725 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
726 /// the specific unconditional branch instruction.
727 static inline unsigned getUnconditionalBrDisp(int Opc) {
728   return (Opc == ARM::tB) ? ((1<<10)-1)*2 : ((1<<23)-1)*4;
729 }
730
731 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
732 /// is out-of-range.  If so, pick it up the constant pool value and move it some
733 /// place in-range.  Return true if we changed any addresses (thus must run
734 /// another pass of branch lengthening), false otherwise.
735 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn, 
736                                                 unsigned CPUserIndex){
737   CPUser &U = CPUsers[CPUserIndex];
738   MachineInstr *UserMI = U.MI;
739   MachineInstr *CPEMI  = U.CPEMI;
740   unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
741   unsigned Size = CPEMI->getOperand(2).getImm();
742   bool isThumb = AFI->isThumbFunction();
743   MachineBasicBlock *NewMBB;
744   // Compute this only once, it's expensive
745   unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
746  
747   // See if the current entry is within range, or there is a clone of it
748   // in range.
749   int result = LookForExistingCPEntry(U, UserOffset);
750   if (result==1) return false;
751   else if (result==2) return true;
752
753   // No existing clone of this CPE is within range.
754   // We will be generating a new clone.  Get a UID for it.
755   unsigned ID  = NextUID++;
756
757   // Look for water where we can place this CPE.  We look for the farthest one
758   // away that will work.  Forward references only for now (although later
759   // we might find some that are backwards).
760   bool WaterFound = false;
761   bool PadNewWater = true;
762   if (!WaterList.empty()) {
763     for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
764         B = WaterList.begin();; --IP) {
765       MachineBasicBlock* WaterBB = *IP;
766       if (WaterIsInRange(UserOffset, WaterBB, U.MaxDisp)) {
767         WaterFound = true;
768         DOUT << "found water in range\n";
769         // CPE goes before following block (NewMBB).
770         NewMBB = next(MachineFunction::iterator(WaterBB));
771         // If WaterBB is an island, don't pad the new island.
772         // If WaterBB is empty, go backwards until we find something that
773         // isn't.  WaterBB may become empty if it's an island whose
774         // contents were moved farther back.
775         if (isThumb) {
776           MachineBasicBlock* BB = WaterBB;
777           while (BB->empty())
778             BB = BB->Prev;
779           if (BB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
780             PadNewWater = false;
781         }
782         // Remove the original WaterList entry; we want subsequent
783         // insertions in this vicinity to go after the one we're
784         // about to insert.  This considerably reduces the number
785         // of times we have to move the same CPE more than once.
786         WaterList.erase(IP);
787         break;
788       }
789       if (IP == B)
790         break;
791     }
792   }
793
794   if (!WaterFound) {
795     // No water found.
796
797     DOUT << "No water found\n";
798     MachineBasicBlock *UserMBB = UserMI->getParent();
799     unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] + 
800                                  BBSizes[UserMBB->getNumber()];
801     assert(OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()+1]);
802
803     // If the use is at the end of the block, or the end of the block
804     // is within range, make new water there.  (The +2 or 4 below is
805     // for the unconditional branch we will be adding.  If the block ends in
806     // an unconditional branch already, it is water, and is known to
807     // be out of range, so we'll always be adding one.)
808     if (&UserMBB->back() == UserMI ||
809         OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2 : 4),
810                         U.MaxDisp, !isThumb)) {
811       DOUT << "Split at end of block\n";
812       if (&UserMBB->back() == UserMI)
813         assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
814       NewMBB = next(MachineFunction::iterator(UserMBB));
815       // Add an unconditional branch from UserMBB to fallthrough block.
816       // Record it for branch lengthening; this new branch will not get out of
817       // range, but if the preceding conditional branch is out of range, the
818       // targets will be exchanged, and the altered branch may be out of
819       // range, so the machinery has to know about it.
820       int UncondBr = isThumb ? ARM::tB : ARM::B;
821       BuildMI(UserMBB, TII->get(UncondBr)).addMBB(NewMBB);
822       unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
823       ImmBranches.push_back(ImmBranch(&UserMBB->back(), 
824                             MaxDisp, false, UncondBr));
825       int delta = isThumb ? 2 : 4;
826       BBSizes[UserMBB->getNumber()] += delta;
827       AdjustBBOffsetsAfter(UserMBB, delta);
828     } else {
829       // What a big block.  Find a place within the block to split it.
830       // This is a little tricky on Thumb since instructions are 2 bytes
831       // and constant pool entries are 4 bytes: if instruction I references
832       // island CPE, and instruction I+1 references CPE', it will
833       // not work well to put CPE as far forward as possible, since then
834       // CPE' cannot immediately follow it (that location is 2 bytes
835       // farther away from I+1 than CPE was from I) and we'd need to create
836       // a new island.
837       // The 4 in the following is for the unconditional branch we'll be
838       // inserting (allows for long branch on Thumb).  The 2 or 0 is for
839       // alignment of the island.
840       unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4 + (isThumb ? 2 : 0);
841       // This could point off the end of the block if we've already got
842       // constant pool entries following this block; only the last one is
843       // in the water list.  Back past any possible branches.
844       if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
845         BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] - 6;
846       unsigned EndInsertOffset = BaseInsertOffset +
847              CPEMI->getOperand(2).getImm();
848       MachineBasicBlock::iterator MI = UserMI;  ++MI;
849       unsigned CPUIndex = CPUserIndex+1;
850       for (unsigned Offset = UserOffset+ARM::GetInstSize(UserMI);
851            Offset < BaseInsertOffset;
852            Offset += ARM::GetInstSize(MI),
853               MI = next(MI)) {
854         if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
855           if (!OffsetIsInRange(Offset, EndInsertOffset, 
856                 CPUsers[CPUIndex].MaxDisp, !isThumb)) {
857             BaseInsertOffset -= (isThumb ? 2 : 4);
858             EndInsertOffset -= (isThumb ? 2 : 4);
859           }
860           // This is overly conservative, as we don't account for CPEMIs
861           // being reused within the block, but it doesn't matter much.
862           EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
863           CPUIndex++;
864         }
865       }
866       DOUT << "Split in middle of big block\n";
867       NewMBB = SplitBlockBeforeInstr(prior(MI));
868     }
869   }
870
871   // Okay, we know we can put an island before NewMBB now, do it!
872   MachineBasicBlock *NewIsland = new MachineBasicBlock();
873   Fn.getBasicBlockList().insert(NewMBB, NewIsland);
874
875   // Update internal data structures to account for the newly inserted MBB.
876   UpdateForInsertedWaterBlock(NewIsland);
877
878   // Decrement the old entry, and remove it if refcount becomes 0.
879   DecrementOldEntry(CPI, CPEMI, Size);
880
881   // Now that we have an island to add the CPE to, clone the original CPE and
882   // add it to the island.
883   U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
884                 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
885   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
886   NumCPEs++;
887
888   // Compensate for .align 2 in thumb mode.
889   if (isThumb && PadNewWater) Size += 2;
890   // Increase the size of the island block to account for the new entry.
891   BBSizes[NewIsland->getNumber()] += Size;
892   BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
893   AdjustBBOffsetsAfter(NewIsland, Size);
894   
895   // Finally, change the CPI in the instruction operand to be ID.
896   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
897     if (UserMI->getOperand(i).isConstantPoolIndex()) {
898       UserMI->getOperand(i).setConstantPoolIndex(ID);
899       break;
900     }
901       
902   DOUT << "  Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
903       
904   return true;
905 }
906
907 /// BBIsInRange - Returns true if the distance between specific MI and
908 /// specific BB can fit in MI's displacement field.
909 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
910                                      unsigned MaxDisp) {
911   unsigned PCAdj      = AFI->isThumbFunction() ? 4 : 8;
912   unsigned BrOffset   = GetOffsetOf(MI) + PCAdj;
913   unsigned DestOffset = BBOffsets[DestBB->getNumber()];
914
915   DOUT << "Branch of destination BB#" << DestBB->getNumber()
916        << " from BB#" << MI->getParent()->getNumber()
917        << " max delta=" << MaxDisp
918        << " at offset " << int(DestOffset-BrOffset) << "\t" << *MI;
919
920   return OffsetIsInRange(BrOffset, DestOffset, MaxDisp, true);
921 }
922
923 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
924 /// away to fit in its displacement field.
925 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
926   MachineInstr *MI = Br.MI;
927   MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
928
929   // Check to see if the DestBB is already in-range.
930   if (BBIsInRange(MI, DestBB, Br.MaxDisp))
931     return false;
932
933   if (!Br.isCond)
934     return FixUpUnconditionalBr(Fn, Br);
935   return FixUpConditionalBr(Fn, Br);
936 }
937
938 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
939 /// too far away to fit in its displacement field. If the LR register has been
940 /// spilled in the epilogue, then we can use BL to implement a far jump.
941 /// Otherwise, add an intermediate branch instruction to to a branch.
942 bool
943 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
944   MachineInstr *MI = Br.MI;
945   MachineBasicBlock *MBB = MI->getParent();
946   assert(AFI->isThumbFunction() && "Expected a Thumb function!");
947
948   // Use BL to implement far jump.
949   Br.MaxDisp = (1 << 21) * 2;
950   MI->setInstrDescriptor(TII->get(ARM::tBfar));
951   BBSizes[MBB->getNumber()] += 2;
952   AdjustBBOffsetsAfter(MBB, 2);
953   HasFarJump = true;
954   NumUBrFixed++;
955
956   DOUT << "  Changed B to long jump " << *MI;
957
958   return true;
959 }
960
961 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
962 /// far away to fit in its displacement field. It is converted to an inverse
963 /// conditional branch + an unconditional branch to the destination.
964 bool
965 ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
966   MachineInstr *MI = Br.MI;
967   MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
968
969   // Add a unconditional branch to the destination and invert the branch
970   // condition to jump over it:
971   // blt L1
972   // =>
973   // bge L2
974   // b   L1
975   // L2:
976   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
977   CC = ARMCC::getOppositeCondition(CC);
978
979   // If the branch is at the end of its MBB and that has a fall-through block,
980   // direct the updated conditional branch to the fall-through block. Otherwise,
981   // split the MBB before the next instruction.
982   MachineBasicBlock *MBB = MI->getParent();
983   MachineInstr *BMI = &MBB->back();
984   bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
985
986   NumCBrFixed++;
987   if (BMI != MI) {
988     if (next(MachineBasicBlock::iterator(MI)) == MBB->back() &&
989         BMI->getOpcode() == Br.UncondBr) {
990       // Last MI in the BB is a unconditional branch. Can we simply invert the
991       // condition and swap destinations:
992       // beq L1
993       // b   L2
994       // =>
995       // bne L2
996       // b   L1
997       MachineBasicBlock *NewDest = BMI->getOperand(0).getMachineBasicBlock();
998       if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
999         DOUT << "  Invert Bcc condition and swap its destination with " << *BMI;
1000         BMI->getOperand(0).setMachineBasicBlock(DestBB);
1001         MI->getOperand(0).setMachineBasicBlock(NewDest);
1002         MI->getOperand(1).setImm(CC);
1003         return true;
1004       }
1005     }
1006   }
1007
1008   if (NeedSplit) {
1009     SplitBlockBeforeInstr(MI);
1010     // No need for the branch to the next block. We're adding a unconditional
1011     // branch to the destination.
1012     MBB->back().eraseFromParent();
1013   }
1014   MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1015  
1016   DOUT << "  Insert B to BB#" << DestBB->getNumber()
1017        << " also invert condition and change dest. to BB#"
1018        << NextBB->getNumber() << "\n";
1019
1020   // Insert a unconditional branch and replace the conditional branch.
1021   // Also update the ImmBranch as well as adding a new entry for the new branch.
1022   BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB).addImm(CC);
1023   Br.MI = &MBB->back();
1024   BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
1025   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1026   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1027   MI->eraseFromParent();
1028
1029   // Increase the size of MBB to account for the new unconditional branch.
1030   int delta = ARM::GetInstSize(&MBB->back());
1031   BBSizes[MBB->getNumber()] += delta;
1032   AdjustBBOffsetsAfter(MBB, delta);
1033   return true;
1034 }
1035
1036 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1037 /// LR / restores LR to pc.
1038 bool ARMConstantIslands::UndoLRSpillRestore() {
1039   bool MadeChange = false;
1040   for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1041     MachineInstr *MI = PushPopMIs[i];
1042     if (MI->getNumOperands() == 1) {
1043         if (MI->getOpcode() == ARM::tPOP_RET &&
1044             MI->getOperand(0).getReg() == ARM::PC)
1045           BuildMI(MI->getParent(), TII->get(ARM::tBX_RET));
1046         MI->eraseFromParent();
1047         MadeChange = true;
1048     }
1049   }
1050   return MadeChange;
1051 }