d9d7763eda2766de467ba45003ab69b195a8f765
[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     typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
74
75     /// CPUser - One user of a constant pool, keeping the machine instruction
76     /// pointer, the constant pool being referenced, and the max displacement
77     /// allowed from the instruction to the CP.
78     struct CPUser {
79       MachineInstr *MI;
80       MachineInstr *CPEMI;
81       unsigned MaxDisp;
82       bool NegOk;
83       bool IsSoImm;
84       CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
85              bool neg, bool soimm)
86         : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {}
87     };
88
89     /// CPUsers - Keep track of all of the machine instructions that use various
90     /// constant pools and their max displacement.
91     std::vector<CPUser> CPUsers;
92
93     /// CPEntry - One per constant pool entry, keeping the machine instruction
94     /// pointer, the constpool index, and the number of CPUser's which
95     /// reference this entry.
96     struct CPEntry {
97       MachineInstr *CPEMI;
98       unsigned CPI;
99       unsigned RefCount;
100       CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
101         : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
102     };
103
104     /// CPEntries - Keep track of all of the constant pool entry machine
105     /// instructions. For each original constpool index (i.e. those that
106     /// existed upon entry to this pass), it keeps a vector of entries.
107     /// Original elements are cloned as we go along; the clones are
108     /// put in the vector of the original element, but have distinct CPIs.
109     std::vector<std::vector<CPEntry> > CPEntries;
110
111     /// ImmBranch - One per immediate branch, keeping the machine instruction
112     /// pointer, conditional or unconditional, the max displacement,
113     /// and (if isCond is true) the corresponding unconditional branch
114     /// opcode.
115     struct ImmBranch {
116       MachineInstr *MI;
117       unsigned MaxDisp : 31;
118       bool isCond : 1;
119       int UncondBr;
120       ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
121         : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
122     };
123
124     /// ImmBranches - Keep track of all the immediate branch instructions.
125     ///
126     std::vector<ImmBranch> ImmBranches;
127
128     /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
129     ///
130     SmallVector<MachineInstr*, 4> PushPopMIs;
131
132     /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
133     SmallVector<MachineInstr*, 4> T2JumpTables;
134
135     /// HasFarJump - True if any far jump instruction has been emitted during
136     /// the branch fix up pass.
137     bool HasFarJump;
138
139     const TargetInstrInfo *TII;
140     const ARMSubtarget *STI;
141     ARMFunctionInfo *AFI;
142     bool isThumb;
143     bool isThumb1;
144     bool isThumb2;
145   public:
146     static char ID;
147     ARMConstantIslands() : MachineFunctionPass(&ID) {}
148
149     virtual bool runOnMachineFunction(MachineFunction &MF);
150
151     virtual const char *getPassName() const {
152       return "ARM constant island placement and branch shortening pass";
153     }
154
155   private:
156     void DoInitialPlacement(MachineFunction &MF,
157                             std::vector<MachineInstr*> &CPEMIs);
158     CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
159     void InitialFunctionScan(MachineFunction &MF,
160                              const std::vector<MachineInstr*> &CPEMIs);
161     MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
162     void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
163     void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
164     bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
165     int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
166     bool LookForWater(CPUser&U, unsigned UserOffset,
167                       MachineBasicBlock *&NewMBB);
168     MachineBasicBlock *AcceptWater(water_iterator IP);
169     void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
170                         MachineBasicBlock *&NewMBB);
171     bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
172     void RemoveDeadCPEMI(MachineInstr *CPEMI);
173     bool RemoveUnusedCPEntries();
174     bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
175                       MachineInstr *CPEMI, unsigned Disp, bool NegOk,
176                       bool DoDump = false);
177     bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
178                         CPUser &U);
179     bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
180                          unsigned Disp, bool NegativeOK, bool IsSoImm = false);
181     bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
182     bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
183     bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
184     bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
185     bool UndoLRSpillRestore();
186     bool OptimizeThumb2Instructions(MachineFunction &MF);
187     bool OptimizeThumb2Branches(MachineFunction &MF);
188     bool OptimizeThumb2JumpTables(MachineFunction &MF);
189
190     unsigned GetOffsetOf(MachineInstr *MI) const;
191     void dumpBBs();
192     void verify(MachineFunction &MF);
193   };
194   char ARMConstantIslands::ID = 0;
195 }
196
197 /// verify - check BBOffsets, BBSizes, alignment of islands
198 void ARMConstantIslands::verify(MachineFunction &MF) {
199   assert(BBOffsets.size() == BBSizes.size());
200   for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
201     assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
202   if (!isThumb)
203     return;
204 #ifndef NDEBUG
205   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
206        MBBI != E; ++MBBI) {
207     MachineBasicBlock *MBB = MBBI;
208     if (!MBB->empty() &&
209         MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
210       unsigned MBBId = MBB->getNumber();
211       assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
212              (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
213     }
214   }
215 #endif
216 }
217
218 /// print block size and offset information - debugging
219 void ARMConstantIslands::dumpBBs() {
220   for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
221     DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
222                  << " size " << BBSizes[J] << "\n");
223   }
224 }
225
226 /// createARMConstantIslandPass - returns an instance of the constpool
227 /// island pass.
228 FunctionPass *llvm::createARMConstantIslandPass() {
229   return new ARMConstantIslands();
230 }
231
232 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
233   MachineConstantPool &MCP = *MF.getConstantPool();
234
235   TII = MF.getTarget().getInstrInfo();
236   AFI = MF.getInfo<ARMFunctionInfo>();
237   STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
238
239   isThumb = AFI->isThumbFunction();
240   isThumb1 = AFI->isThumb1OnlyFunction();
241   isThumb2 = AFI->isThumb2Function();
242
243   HasFarJump = false;
244
245   // Renumber all of the machine basic blocks in the function, guaranteeing that
246   // the numbers agree with the position of the block in the function.
247   MF.RenumberBlocks();
248
249   // Thumb1 functions containing constant pools get 4-byte alignment.
250   // This is so we can keep exact track of where the alignment padding goes.
251
252   // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
253   // aligned.
254   AFI->setAlign(isThumb1 ? 1U : 2U);
255
256   // Perform the initial placement of the constant pool entries.  To start with,
257   // we put them all at the end of the function.
258   std::vector<MachineInstr*> CPEMIs;
259   if (!MCP.isEmpty()) {
260     DoInitialPlacement(MF, CPEMIs);
261     if (isThumb1)
262       AFI->setAlign(2U);
263   }
264
265   /// The next UID to take is the first unused one.
266   AFI->initConstPoolEntryUId(CPEMIs.size());
267
268   // Do the initial scan of the function, building up information about the
269   // sizes of each block, the location of all the water, and finding all of the
270   // constant pool users.
271   InitialFunctionScan(MF, CPEMIs);
272   CPEMIs.clear();
273
274   /// Remove dead constant pool entries.
275   RemoveUnusedCPEntries();
276
277   // Iteratively place constant pool entries and fix up branches until there
278   // is no change.
279   bool MadeChange = false;
280   unsigned NoCPIters = 0, NoBRIters = 0;
281   while (true) {
282     bool CPChange = false;
283     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
284       CPChange |= HandleConstantPoolUser(MF, i);
285     if (CPChange && ++NoCPIters > 30)
286       llvm_unreachable("Constant Island pass failed to converge!");
287     DEBUG(dumpBBs());
288
289     bool BRChange = false;
290     for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
291       BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
292     if (BRChange && ++NoBRIters > 30)
293       llvm_unreachable("Branch Fix Up pass failed to converge!");
294     DEBUG(dumpBBs());
295
296     if (!CPChange && !BRChange)
297       break;
298     MadeChange = true;
299   }
300
301   // Shrink 32-bit Thumb2 branch, load, and store instructions.
302   if (isThumb2)
303     MadeChange |= OptimizeThumb2Instructions(MF);
304
305   // After a while, this might be made debug-only, but it is not expensive.
306   verify(MF);
307
308   // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
309   // Undo the spill / restore of LR if possible.
310   if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
311     MadeChange |= UndoLRSpillRestore();
312
313   BBSizes.clear();
314   BBOffsets.clear();
315   WaterList.clear();
316   CPUsers.clear();
317   CPEntries.clear();
318   ImmBranches.clear();
319   PushPopMIs.clear();
320   T2JumpTables.clear();
321
322   return MadeChange;
323 }
324
325 /// DoInitialPlacement - Perform the initial placement of the constant pool
326 /// entries.  To start with, we put them all at the end of the function.
327 void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
328                                         std::vector<MachineInstr*> &CPEMIs) {
329   // Create the basic block to hold the CPE's.
330   MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
331   MF.push_back(BB);
332
333   // Add all of the constants from the constant pool to the end block, use an
334   // identity mapping of CPI's to CPE's.
335   const std::vector<MachineConstantPoolEntry> &CPs =
336     MF.getConstantPool()->getConstants();
337
338   const TargetData &TD = *MF.getTarget().getTargetData();
339   for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
340     unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
341     // Verify that all constant pool entries are a multiple of 4 bytes.  If not,
342     // we would have to pad them out or something so that instructions stay
343     // aligned.
344     assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
345     MachineInstr *CPEMI =
346       BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
347                            .addImm(i).addConstantPoolIndex(i).addImm(Size);
348     CPEMIs.push_back(CPEMI);
349
350     // Add a new CPEntry, but no corresponding CPUser yet.
351     std::vector<CPEntry> CPEs;
352     CPEs.push_back(CPEntry(CPEMI, i));
353     CPEntries.push_back(CPEs);
354     NumCPEs++;
355     DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
356                  << "\n");
357   }
358 }
359
360 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
361 /// into the block immediately after it.
362 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
363   // Get the next machine basic block in the function.
364   MachineFunction::iterator MBBI = MBB;
365   if (next(MBBI) == MBB->getParent()->end())  // Can't fall off end of function.
366     return false;
367
368   MachineBasicBlock *NextBB = next(MBBI);
369   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
370        E = MBB->succ_end(); I != E; ++I)
371     if (*I == NextBB)
372       return true;
373
374   return false;
375 }
376
377 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
378 /// look up the corresponding CPEntry.
379 ARMConstantIslands::CPEntry
380 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
381                                         const MachineInstr *CPEMI) {
382   std::vector<CPEntry> &CPEs = CPEntries[CPI];
383   // Number of entries per constpool index should be small, just do a
384   // linear search.
385   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
386     if (CPEs[i].CPEMI == CPEMI)
387       return &CPEs[i];
388   }
389   return NULL;
390 }
391
392 /// InitialFunctionScan - Do the initial scan of the function, building up
393 /// information about the sizes of each block, the location of all the water,
394 /// and finding all of the constant pool users.
395 void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
396                                  const std::vector<MachineInstr*> &CPEMIs) {
397   unsigned Offset = 0;
398   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
399        MBBI != E; ++MBBI) {
400     MachineBasicBlock &MBB = *MBBI;
401
402     // If this block doesn't fall through into the next MBB, then this is
403     // 'water' that a constant pool island could be placed.
404     if (!BBHasFallthrough(&MBB))
405       WaterList.push_back(&MBB);
406
407     unsigned MBBSize = 0;
408     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
409          I != E; ++I) {
410       // Add instruction size to MBBSize.
411       MBBSize += TII->GetInstSizeInBytes(I);
412
413       int Opc = I->getOpcode();
414       if (I->getDesc().isBranch()) {
415         bool isCond = false;
416         unsigned Bits = 0;
417         unsigned Scale = 1;
418         int UOpc = Opc;
419         switch (Opc) {
420         default:
421           continue;  // Ignore other JT branches
422         case ARM::tBR_JTr:
423           // A Thumb1 table jump may involve padding; for the offsets to
424           // be right, functions containing these must be 4-byte aligned.
425           AFI->setAlign(2U);
426           if ((Offset+MBBSize)%4 != 0)
427             // FIXME: Add a pseudo ALIGN instruction instead.
428             MBBSize += 2;           // padding
429           continue;   // Does not get an entry in ImmBranches
430         case ARM::t2BR_JT:
431           T2JumpTables.push_back(I);
432           continue;   // Does not get an entry in ImmBranches
433         case ARM::Bcc:
434           isCond = true;
435           UOpc = ARM::B;
436           // Fallthrough
437         case ARM::B:
438           Bits = 24;
439           Scale = 4;
440           break;
441         case ARM::tBcc:
442           isCond = true;
443           UOpc = ARM::tB;
444           Bits = 8;
445           Scale = 2;
446           break;
447         case ARM::tB:
448           Bits = 11;
449           Scale = 2;
450           break;
451         case ARM::t2Bcc:
452           isCond = true;
453           UOpc = ARM::t2B;
454           Bits = 20;
455           Scale = 2;
456           break;
457         case ARM::t2B:
458           Bits = 24;
459           Scale = 2;
460           break;
461         }
462
463         // Record this immediate branch.
464         unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
465         ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
466       }
467
468       if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
469         PushPopMIs.push_back(I);
470
471       if (Opc == ARM::CONSTPOOL_ENTRY)
472         continue;
473
474       // Scan the instructions for constant pool operands.
475       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
476         if (I->getOperand(op).isCPI()) {
477           // We found one.  The addressing mode tells us the max displacement
478           // from the PC that this instruction permits.
479
480           // Basic size info comes from the TSFlags field.
481           unsigned Bits = 0;
482           unsigned Scale = 1;
483           bool NegOk = false;
484           bool IsSoImm = false;
485
486           switch (Opc) {
487           default:
488             llvm_unreachable("Unknown addressing mode for CP reference!");
489             break;
490
491           // Taking the address of a CP entry.
492           case ARM::LEApcrel:
493             // This takes a SoImm, which is 8 bit immediate rotated. We'll
494             // pretend the maximum offset is 255 * 4. Since each instruction
495             // 4 byte wide, this is always correct. We'llc heck for other
496             // displacements that fits in a SoImm as well.
497             Bits = 8;
498             Scale = 4;
499             NegOk = true;
500             IsSoImm = true;
501             break;
502           case ARM::t2LEApcrel:
503             Bits = 12;
504             NegOk = true;
505             break;
506           case ARM::tLEApcrel:
507             Bits = 8;
508             Scale = 4;
509             break;
510
511           case ARM::LDR:
512           case ARM::LDRcp:
513           case ARM::t2LDRpci:
514             Bits = 12;  // +-offset_12
515             NegOk = true;
516             break;
517
518           case ARM::tLDRpci:
519           case ARM::tLDRcp:
520             Bits = 8;
521             Scale = 4;  // +(offset_8*4)
522             break;
523
524           case ARM::FLDD:
525           case ARM::FLDS:
526             Bits = 8;
527             Scale = 4;  // +-(offset_8*4)
528             NegOk = true;
529             break;
530           }
531
532           // Remember that this is a user of a CP entry.
533           unsigned CPI = I->getOperand(op).getIndex();
534           MachineInstr *CPEMI = CPEMIs[CPI];
535           unsigned MaxOffs = ((1 << Bits)-1) * Scale;
536           CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
537
538           // Increment corresponding CPEntry reference count.
539           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
540           assert(CPE && "Cannot find a corresponding CPEntry!");
541           CPE->RefCount++;
542
543           // Instructions can only use one CP entry, don't bother scanning the
544           // rest of the operands.
545           break;
546         }
547     }
548
549     // In thumb mode, if this block is a constpool island, we may need padding
550     // so it's aligned on 4 byte boundary.
551     if (isThumb &&
552         !MBB.empty() &&
553         MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
554         (Offset%4) != 0)
555       MBBSize += 2;
556
557     BBSizes.push_back(MBBSize);
558     BBOffsets.push_back(Offset);
559     Offset += MBBSize;
560   }
561 }
562
563 /// GetOffsetOf - Return the current offset of the specified machine instruction
564 /// from the start of the function.  This offset changes as stuff is moved
565 /// around inside the function.
566 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
567   MachineBasicBlock *MBB = MI->getParent();
568
569   // The offset is composed of two things: the sum of the sizes of all MBB's
570   // before this instruction's block, and the offset from the start of the block
571   // it is in.
572   unsigned Offset = BBOffsets[MBB->getNumber()];
573
574   // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
575   // alignment padding, and compensate if so.
576   if (isThumb &&
577       MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
578       Offset%4 != 0)
579     Offset += 2;
580
581   // Sum instructions before MI in MBB.
582   for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
583     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
584     if (&*I == MI) return Offset;
585     Offset += TII->GetInstSizeInBytes(I);
586   }
587 }
588
589 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
590 /// ID.
591 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
592                               const MachineBasicBlock *RHS) {
593   return LHS->getNumber() < RHS->getNumber();
594 }
595
596 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
597 /// machine function, it upsets all of the block numbers.  Renumber the blocks
598 /// and update the arrays that parallel this numbering.
599 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
600   // Renumber the MBB's to keep them consequtive.
601   NewBB->getParent()->RenumberBlocks(NewBB);
602
603   // Insert a size into BBSizes to align it properly with the (newly
604   // renumbered) block numbers.
605   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
606
607   // Likewise for BBOffsets.
608   BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
609
610   // Next, update WaterList.  Specifically, we need to add NewMBB as having
611   // available water after it.
612   water_iterator IP =
613     std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
614                      CompareMBBNumbers);
615   WaterList.insert(IP, NewBB);
616 }
617
618
619 /// Split the basic block containing MI into two blocks, which are joined by
620 /// an unconditional branch.  Update datastructures and renumber blocks to
621 /// account for this change and returns the newly created block.
622 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
623   MachineBasicBlock *OrigBB = MI->getParent();
624   MachineFunction &MF = *OrigBB->getParent();
625
626   // Create a new MBB for the code after the OrigBB.
627   MachineBasicBlock *NewBB =
628     MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
629   MachineFunction::iterator MBBI = OrigBB; ++MBBI;
630   MF.insert(MBBI, NewBB);
631
632   // Splice the instructions starting with MI over to NewBB.
633   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
634
635   // Add an unconditional branch from OrigBB to NewBB.
636   // Note the new unconditional branch is not being recorded.
637   // There doesn't seem to be meaningful DebugInfo available; this doesn't
638   // correspond to anything in the source.
639   unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
640   BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
641   NumSplit++;
642
643   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
644   while (!OrigBB->succ_empty()) {
645     MachineBasicBlock *Succ = *OrigBB->succ_begin();
646     OrigBB->removeSuccessor(Succ);
647     NewBB->addSuccessor(Succ);
648
649     // This pass should be run after register allocation, so there should be no
650     // PHI nodes to update.
651     assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
652            && "PHI nodes should be eliminated by now!");
653   }
654
655   // OrigBB branches to NewBB.
656   OrigBB->addSuccessor(NewBB);
657
658   // Update internal data structures to account for the newly inserted MBB.
659   // This is almost the same as UpdateForInsertedWaterBlock, except that
660   // the Water goes after OrigBB, not NewBB.
661   MF.RenumberBlocks(NewBB);
662
663   // Insert a size into BBSizes to align it properly with the (newly
664   // renumbered) block numbers.
665   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
666
667   // Likewise for BBOffsets.
668   BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
669
670   // Next, update WaterList.  Specifically, we need to add OrigMBB as having
671   // available water after it (but not if it's already there, which happens
672   // when splitting before a conditional branch that is followed by an
673   // unconditional branch - in that case we want to insert NewBB).
674   water_iterator IP =
675     std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
676                      CompareMBBNumbers);
677   MachineBasicBlock* WaterBB = *IP;
678   if (WaterBB == OrigBB)
679     WaterList.insert(next(IP), NewBB);
680   else
681     WaterList.insert(IP, OrigBB);
682
683   // Figure out how large the first NewMBB is.  (It cannot
684   // contain a constpool_entry or tablejump.)
685   unsigned NewBBSize = 0;
686   for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
687        I != E; ++I)
688     NewBBSize += TII->GetInstSizeInBytes(I);
689
690   unsigned OrigBBI = OrigBB->getNumber();
691   unsigned NewBBI = NewBB->getNumber();
692   // Set the size of NewBB in BBSizes.
693   BBSizes[NewBBI] = NewBBSize;
694
695   // We removed instructions from UserMBB, subtract that off from its size.
696   // Add 2 or 4 to the block to count the unconditional branch we added to it.
697   int delta = isThumb1 ? 2 : 4;
698   BBSizes[OrigBBI] -= NewBBSize - delta;
699
700   // ...and adjust BBOffsets for NewBB accordingly.
701   BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
702
703   // All BBOffsets following these blocks must be modified.
704   AdjustBBOffsetsAfter(NewBB, delta);
705
706   return NewBB;
707 }
708
709 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
710 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
711 /// constant pool entry).
712 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
713                                          unsigned TrialOffset, unsigned MaxDisp,
714                                          bool NegativeOK, bool IsSoImm) {
715   // On Thumb offsets==2 mod 4 are rounded down by the hardware for
716   // purposes of the displacement computation; compensate for that here.
717   // Effectively, the valid range of displacements is 2 bytes smaller for such
718   // references.
719   unsigned TotalAdj = 0;
720   if (isThumb && UserOffset%4 !=0) {
721     UserOffset -= 2;
722     TotalAdj = 2;
723   }
724   // CPEs will be rounded up to a multiple of 4.
725   if (isThumb && TrialOffset%4 != 0) {
726     TrialOffset += 2;
727     TotalAdj += 2;
728   }
729
730   // In Thumb2 mode, later branch adjustments can shift instructions up and
731   // cause alignment change. In the worst case scenario this can cause the
732   // user's effective address to be subtracted by 2 and the CPE's address to
733   // be plus 2.
734   if (isThumb2 && TotalAdj != 4)
735     MaxDisp -= (4 - TotalAdj);
736
737   if (UserOffset <= TrialOffset) {
738     // User before the Trial.
739     if (TrialOffset - UserOffset <= MaxDisp)
740       return true;
741     // FIXME: Make use full range of soimm values.
742   } else if (NegativeOK) {
743     if (UserOffset - TrialOffset <= MaxDisp)
744       return true;
745     // FIXME: Make use full range of soimm values.
746   }
747   return false;
748 }
749
750 /// WaterIsInRange - Returns true if a CPE placed after the specified
751 /// Water (a basic block) will be in range for the specific MI.
752
753 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
754                                         MachineBasicBlock* Water, CPUser &U) {
755   unsigned MaxDisp = U.MaxDisp;
756   unsigned CPEOffset = BBOffsets[Water->getNumber()] +
757                        BBSizes[Water->getNumber()];
758
759   // If the CPE is to be inserted before the instruction, that will raise
760   // the offset of the instruction.
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(water_iterator IP) {
935   DEBUG(errs() << "found water in range\n");
936   // Remove the original WaterList entry; we want subsequent
937   // insertions in this vicinity to go after the one we're
938   // about to insert.  This considerably reduces the number
939   // of times we have to move the same CPE more than once.
940   WaterList.erase(IP);
941   // CPE goes before following block (NewMBB).
942   return next(MachineFunction::iterator(*IP));
943 }
944
945 /// LookForWater - look for an existing entry in the WaterList in which
946 /// we can place the CPE referenced from U so it's within range of U's MI.
947 /// Returns true if found, false if not.  If it returns true, NewMBB
948 /// is set to the WaterList entry.  For Thumb, prefer water that will not
949 /// introduce padding to water that will.  To ensure that this pass
950 /// terminates, the CPE location for a particular CPUser is only allowed to
951 /// move to a lower address, so search backward from the end of the list and
952 /// prefer the first water that is in range.
953 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
954                                       MachineBasicBlock *&NewMBB) {
955   if (WaterList.empty())
956     return false;
957
958   bool FoundWaterThatWouldPad = false;
959   water_iterator IPThatWouldPad;
960   for (water_iterator IP = prior(WaterList.end()),
961          B = WaterList.begin();; --IP) {
962     MachineBasicBlock* WaterBB = *IP;
963     // Check if water is in range and at a lower address than the current one.
964     if (WaterIsInRange(UserOffset, WaterBB, U) &&
965         WaterBB->getNumber() < U.CPEMI->getParent()->getNumber()) {
966       unsigned WBBId = WaterBB->getNumber();
967       if (isThumb &&
968           (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
969         // This is valid Water, but would introduce padding.  Remember
970         // it in case we don't find any Water that doesn't do this.
971         if (!FoundWaterThatWouldPad) {
972           FoundWaterThatWouldPad = true;
973           IPThatWouldPad = IP;
974         }
975       } else {
976         NewMBB = AcceptWater(IP);
977         return true;
978       }
979     }
980     if (IP == B)
981       break;
982   }
983   if (FoundWaterThatWouldPad) {
984     NewMBB = AcceptWater(IPThatWouldPad);
985     return true;
986   }
987   return false;
988 }
989
990 /// CreateNewWater - No existing WaterList entry will work for
991 /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
992 /// block is used if in range, and the conditional branch munged so control
993 /// flow is correct.  Otherwise the block is split to create a hole with an
994 /// unconditional branch around it.  In either case NewMBB is set to a
995 /// block following which the new island can be inserted (the WaterList
996 /// is not adjusted).
997 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
998                                         unsigned UserOffset,
999                                         MachineBasicBlock *&NewMBB) {
1000   CPUser &U = CPUsers[CPUserIndex];
1001   MachineInstr *UserMI = U.MI;
1002   MachineInstr *CPEMI  = U.CPEMI;
1003   MachineBasicBlock *UserMBB = UserMI->getParent();
1004   unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
1005                                BBSizes[UserMBB->getNumber()];
1006   assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
1007
1008   // If the use is at the end of the block, or the end of the block
1009   // is within range, make new water there.  (The addition below is
1010   // for the unconditional branch we will be adding:  4 bytes on ARM + Thumb2,
1011   // 2 on Thumb1.  Possible Thumb1 alignment padding is allowed for
1012   // inside OffsetIsInRange.
1013   // If the block ends in an unconditional branch already, it is water,
1014   // and is known to be out of range, so we'll always be adding a branch.)
1015   if (&UserMBB->back() == UserMI ||
1016       OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1017                       U.MaxDisp, U.NegOk, U.IsSoImm)) {
1018     DEBUG(errs() << "Split at end of block\n");
1019     if (&UserMBB->back() == UserMI)
1020       assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1021     NewMBB = next(MachineFunction::iterator(UserMBB));
1022     // Add an unconditional branch from UserMBB to fallthrough block.
1023     // Record it for branch lengthening; this new branch will not get out of
1024     // range, but if the preceding conditional branch is out of range, the
1025     // targets will be exchanged, and the altered branch may be out of
1026     // range, so the machinery has to know about it.
1027     int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1028     BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
1029             TII->get(UncondBr)).addMBB(NewMBB);
1030     unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1031     ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1032                           MaxDisp, false, UncondBr));
1033     int delta = isThumb1 ? 2 : 4;
1034     BBSizes[UserMBB->getNumber()] += delta;
1035     AdjustBBOffsetsAfter(UserMBB, delta);
1036   } else {
1037     // What a big block.  Find a place within the block to split it.
1038     // This is a little tricky on Thumb1 since instructions are 2 bytes
1039     // and constant pool entries are 4 bytes: if instruction I references
1040     // island CPE, and instruction I+1 references CPE', it will
1041     // not work well to put CPE as far forward as possible, since then
1042     // CPE' cannot immediately follow it (that location is 2 bytes
1043     // farther away from I+1 than CPE was from I) and we'd need to create
1044     // a new island.  So, we make a first guess, then walk through the
1045     // instructions between the one currently being looked at and the
1046     // possible insertion point, and make sure any other instructions
1047     // that reference CPEs will be able to use the same island area;
1048     // if not, we back up the insertion point.
1049
1050     // The 4 in the following is for the unconditional branch we'll be
1051     // inserting (allows for long branch on Thumb1).  Alignment of the
1052     // island is handled inside OffsetIsInRange.
1053     unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1054     // This could point off the end of the block if we've already got
1055     // constant pool entries following this block; only the last one is
1056     // in the water list.  Back past any possible branches (allow for a
1057     // conditional and a maximally long unconditional).
1058     if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
1059       BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
1060                               (isThumb1 ? 6 : 8);
1061     unsigned EndInsertOffset = BaseInsertOffset +
1062            CPEMI->getOperand(2).getImm();
1063     MachineBasicBlock::iterator MI = UserMI;
1064     ++MI;
1065     unsigned CPUIndex = CPUserIndex+1;
1066     for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1067          Offset < BaseInsertOffset;
1068          Offset += TII->GetInstSizeInBytes(MI),
1069             MI = next(MI)) {
1070       if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
1071         CPUser &U = CPUsers[CPUIndex];
1072         if (!OffsetIsInRange(Offset, EndInsertOffset,
1073                              U.MaxDisp, U.NegOk, U.IsSoImm)) {
1074           BaseInsertOffset -= (isThumb1 ? 2 : 4);
1075           EndInsertOffset  -= (isThumb1 ? 2 : 4);
1076         }
1077         // This is overly conservative, as we don't account for CPEMIs
1078         // being reused within the block, but it doesn't matter much.
1079         EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1080         CPUIndex++;
1081       }
1082     }
1083     DEBUG(errs() << "Split in middle of big block\n");
1084     NewMBB = SplitBlockBeforeInstr(prior(MI));
1085   }
1086 }
1087
1088 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1089 /// is out-of-range.  If so, pick up the constant pool value and move it some
1090 /// place in-range.  Return true if we changed any addresses (thus must run
1091 /// another pass of branch lengthening), false otherwise.
1092 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
1093                                                 unsigned CPUserIndex) {
1094   CPUser &U = CPUsers[CPUserIndex];
1095   MachineInstr *UserMI = U.MI;
1096   MachineInstr *CPEMI  = U.CPEMI;
1097   unsigned CPI = CPEMI->getOperand(1).getIndex();
1098   unsigned Size = CPEMI->getOperand(2).getImm();
1099   MachineBasicBlock *NewMBB;
1100   // Compute this only once, it's expensive.  The 4 or 8 is the value the
1101   // hardware keeps in the PC.
1102   unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1103
1104   // See if the current entry is within range, or there is a clone of it
1105   // in range.
1106   int result = LookForExistingCPEntry(U, UserOffset);
1107   if (result==1) return false;
1108   else if (result==2) return true;
1109
1110   // No existing clone of this CPE is within range.
1111   // We will be generating a new clone.  Get a UID for it.
1112   unsigned ID = AFI->createConstPoolEntryUId();
1113
1114   // Look for water where we can place this CPE.
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     // First two operands are predicates, the third is a zero since there
1363     // is no writeback.
1364     if (MI->getOpcode() == ARM::tPOP_RET &&
1365         MI->getOperand(3).getReg() == ARM::PC &&
1366         MI->getNumExplicitOperands() == 4) {
1367       BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
1368       MI->eraseFromParent();
1369       MadeChange = true;
1370     }
1371   }
1372   return MadeChange;
1373 }
1374
1375 bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1376   bool MadeChange = false;
1377
1378   // Shrink ADR and LDR from constantpool.
1379   for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1380     CPUser &U = CPUsers[i];
1381     unsigned Opcode = U.MI->getOpcode();
1382     unsigned NewOpc = 0;
1383     unsigned Scale = 1;
1384     unsigned Bits = 0;
1385     switch (Opcode) {
1386     default: break;
1387     case ARM::t2LEApcrel:
1388       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1389         NewOpc = ARM::tLEApcrel;
1390         Bits = 8;
1391         Scale = 4;
1392       }
1393       break;
1394     case ARM::t2LDRpci:
1395       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1396         NewOpc = ARM::tLDRpci;
1397         Bits = 8;
1398         Scale = 4;
1399       }
1400       break;
1401     }
1402
1403     if (!NewOpc)
1404       continue;
1405
1406     unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1407     unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1408     // FIXME: Check if offset is multiple of scale if scale is not 4.
1409     if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1410       U.MI->setDesc(TII->get(NewOpc));
1411       MachineBasicBlock *MBB = U.MI->getParent();
1412       BBSizes[MBB->getNumber()] -= 2;
1413       AdjustBBOffsetsAfter(MBB, -2);
1414       ++NumT2CPShrunk;
1415       MadeChange = true;
1416     }
1417   }
1418
1419   MadeChange |= OptimizeThumb2Branches(MF);
1420   MadeChange |= OptimizeThumb2JumpTables(MF);
1421   return MadeChange;
1422 }
1423
1424 bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
1425   bool MadeChange = false;
1426
1427   for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1428     ImmBranch &Br = ImmBranches[i];
1429     unsigned Opcode = Br.MI->getOpcode();
1430     unsigned NewOpc = 0;
1431     unsigned Scale = 1;
1432     unsigned Bits = 0;
1433     switch (Opcode) {
1434     default: break;
1435     case ARM::t2B:
1436       NewOpc = ARM::tB;
1437       Bits = 11;
1438       Scale = 2;
1439       break;
1440     case ARM::t2Bcc:
1441       NewOpc = ARM::tBcc;
1442       Bits = 8;
1443       Scale = 2;      
1444       break;
1445     }
1446     if (!NewOpc)
1447       continue;
1448
1449     unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1450     MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1451     if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1452       Br.MI->setDesc(TII->get(NewOpc));
1453       MachineBasicBlock *MBB = Br.MI->getParent();
1454       BBSizes[MBB->getNumber()] -= 2;
1455       AdjustBBOffsetsAfter(MBB, -2);
1456       ++NumT2BrShrunk;
1457       MadeChange = true;
1458     }
1459   }
1460
1461   return MadeChange;
1462 }
1463
1464
1465 /// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1466 /// jumptables when it's possible.
1467 bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1468   bool MadeChange = false;
1469
1470   // FIXME: After the tables are shrunk, can we get rid some of the
1471   // constantpool tables?
1472   const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1473   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1474   for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1475     MachineInstr *MI = T2JumpTables[i];
1476     const TargetInstrDesc &TID = MI->getDesc();
1477     unsigned NumOps = TID.getNumOperands();
1478     unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1479     MachineOperand JTOP = MI->getOperand(JTOpIdx);
1480     unsigned JTI = JTOP.getIndex();
1481     assert(JTI < JT.size());
1482
1483     bool ByteOk = true;
1484     bool HalfWordOk = true;
1485     unsigned JTOffset = GetOffsetOf(MI) + 4;
1486     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1487     for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1488       MachineBasicBlock *MBB = JTBBs[j];
1489       unsigned DstOffset = BBOffsets[MBB->getNumber()];
1490       // Negative offset is not ok. FIXME: We should change BB layout to make
1491       // sure all the branches are forward.
1492       if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1493         ByteOk = false;
1494       unsigned TBHLimit = ((1<<16)-1)*2;
1495       if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1496         HalfWordOk = false;
1497       if (!ByteOk && !HalfWordOk)
1498         break;
1499     }
1500
1501     if (ByteOk || HalfWordOk) {
1502       MachineBasicBlock *MBB = MI->getParent();
1503       unsigned BaseReg = MI->getOperand(0).getReg();
1504       bool BaseRegKill = MI->getOperand(0).isKill();
1505       if (!BaseRegKill)
1506         continue;
1507       unsigned IdxReg = MI->getOperand(1).getReg();
1508       bool IdxRegKill = MI->getOperand(1).isKill();
1509       MachineBasicBlock::iterator PrevI = MI;
1510       if (PrevI == MBB->begin())
1511         continue;
1512
1513       MachineInstr *AddrMI = --PrevI;
1514       bool OptOk = true;
1515       // Examine the instruction that calculate the jumptable entry address.
1516       // If it's not the one just before the t2BR_JT, we won't delete it, then
1517       // it's not worth doing the optimization.
1518       for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1519         const MachineOperand &MO = AddrMI->getOperand(k);
1520         if (!MO.isReg() || !MO.getReg())
1521           continue;
1522         if (MO.isDef() && MO.getReg() != BaseReg) {
1523           OptOk = false;
1524           break;
1525         }
1526         if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1527           OptOk = false;
1528           break;
1529         }
1530       }
1531       if (!OptOk)
1532         continue;
1533
1534       // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1535       // to delete it as well.
1536       MachineInstr *LeaMI = --PrevI;
1537       if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1538            LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1539           LeaMI->getOperand(0).getReg() != BaseReg)
1540         OptOk = false;
1541
1542       if (!OptOk)
1543         continue;
1544
1545       unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1546       MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1547         .addReg(IdxReg, getKillRegState(IdxRegKill))
1548         .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1549         .addImm(MI->getOperand(JTOpIdx+1).getImm());
1550       // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1551       // is 2-byte aligned. For now, asm printer will fix it up.
1552       unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1553       unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1554       OrigSize += TII->GetInstSizeInBytes(LeaMI);
1555       OrigSize += TII->GetInstSizeInBytes(MI);
1556
1557       AddrMI->eraseFromParent();
1558       LeaMI->eraseFromParent();
1559       MI->eraseFromParent();
1560
1561       int delta = OrigSize - NewSize;
1562       BBSizes[MBB->getNumber()] -= delta;
1563       AdjustBBOffsetsAfter(MBB, -delta);
1564
1565       ++NumTBs;
1566       MadeChange = true;
1567     }
1568   }
1569
1570   return MadeChange;
1571 }