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