Add a postOffset() alignment argument.
[oota-llvm.git] / lib / Target / ARM / ARMConstantIslandPass.cpp
1 //===-- ARMConstantIslandPass.cpp - ARM constant islands ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a pass that splits the constant pool up into 'islands'
11 // which are scattered through-out the function.  This is required due to the
12 // limited pc-relative displacements that ARM has.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "arm-cp-islands"
17 #include "ARM.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMInstrInfo.h"
20 #include "Thumb2InstrInfo.h"
21 #include "MCTargetDesc/ARMAddressingModes.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/Format.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Support/CommandLine.h"
36 #include <algorithm>
37 using namespace llvm;
38
39 STATISTIC(NumCPEs,       "Number of constpool entries");
40 STATISTIC(NumSplit,      "Number of uncond branches inserted");
41 STATISTIC(NumCBrFixed,   "Number of cond branches fixed");
42 STATISTIC(NumUBrFixed,   "Number of uncond branches fixed");
43 STATISTIC(NumTBs,        "Number of table branches generated");
44 STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
45 STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
46 STATISTIC(NumCBZ,        "Number of CBZ / CBNZ formed");
47 STATISTIC(NumJTMoved,    "Number of jump table destination blocks moved");
48 STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
49
50
51 static cl::opt<bool>
52 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
53           cl::desc("Adjust basic block layout to better use TB[BH]"));
54
55 static cl::opt<bool>
56 AlignConstantIslands("arm-align-constant-island", cl::Hidden,
57           cl::desc("Align constant islands in code"));
58
59 /// UnknownPadding - Return the worst case padding that could result from
60 /// unknown offset bits.  This does not include alignment padding caused by
61 /// known offset bits.
62 ///
63 /// @param LogAlign log2(alignment)
64 /// @param KnownBits Number of known low offset bits.
65 static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
66   if (KnownBits < LogAlign)
67     return (1u << LogAlign) - (1u << KnownBits);
68   return 0;
69 }
70
71 /// WorstCaseAlign - Assuming only the low KnownBits bits in Offset are exact,
72 /// add padding such that:
73 ///
74 /// 1. The result is aligned to 1 << LogAlign.
75 ///
76 /// 2. No other value of the unknown bits would require more padding.
77 ///
78 /// This may add more padding than is required to satisfy just one of the
79 /// constraints.  It is necessary to compute alignment this way to guarantee
80 /// that we don't underestimate the padding before an aligned block.  If the
81 /// real padding before a block is larger than we think, constant pool entries
82 /// may go out of range.
83 static inline unsigned WorstCaseAlign(unsigned Offset, unsigned LogAlign,
84                                       unsigned KnownBits) {
85   // Add the worst possible padding that the unknown bits could cause.
86   Offset += UnknownPadding(LogAlign, KnownBits);
87
88   // Then align the result.
89   return RoundUpToAlignment(Offset, 1u << LogAlign);
90 }
91
92 namespace {
93   /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
94   /// requires constant pool entries to be scattered among the instructions
95   /// inside a function.  To do this, it completely ignores the normal LLVM
96   /// constant pool; instead, it places constants wherever it feels like with
97   /// special instructions.
98   ///
99   /// The terminology used in this pass includes:
100   ///   Islands - Clumps of constants placed in the function.
101   ///   Water   - Potential places where an island could be formed.
102   ///   CPE     - A constant pool entry that has been placed somewhere, which
103   ///             tracks a list of users.
104   class ARMConstantIslands : public MachineFunctionPass {
105     /// BasicBlockInfo - Information about the offset and size of a single
106     /// basic block.
107     struct BasicBlockInfo {
108       /// Offset - Distance from the beginning of the function to the beginning
109       /// of this basic block.
110       ///
111       /// The offset is always aligned as required by the basic block.
112       unsigned Offset;
113
114       /// Size - Size of the basic block in bytes.  If the block contains
115       /// inline assembly, this is a worst case estimate.
116       ///
117       /// The size does not include any alignment padding whether from the
118       /// beginning of the block, or from an aligned jump table at the end.
119       unsigned Size;
120
121       /// KnownBits - The number of low bits in Offset that are known to be
122       /// exact.  The remaining bits of Offset are an upper bound.
123       uint8_t KnownBits;
124
125       /// Unalign - When non-zero, the block contains instructions (inline asm)
126       /// of unknown size.  The real size may be smaller than Size bytes by a
127       /// multiple of 1 << Unalign.
128       uint8_t Unalign;
129
130       /// PostAlign - When non-zero, the block terminator contains a .align
131       /// directive, so the end of the block is aligned to 1 << PostAlign
132       /// bytes.
133       uint8_t PostAlign;
134
135       BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
136         PostAlign(0) {}
137
138       /// Compute the number of known offset bits internally to this block.
139       /// This number should be used to predict worst case padding when
140       /// splitting the block.
141       unsigned internalKnownBits() const {
142         return Unalign ? Unalign : KnownBits;
143       }
144
145       /// Compute the offset immediately following this block.  If LogAlign is
146       /// specified, return the offset the successor block will get if it has
147       /// this alignment.
148       unsigned postOffset(unsigned LogAlign = 0) const {
149         unsigned PO = Offset + Size;
150         unsigned LA = std::max(unsigned(PostAlign), LogAlign);
151         if (!LA)
152           return PO;
153         // Add alignment padding from the terminator.
154         return WorstCaseAlign(PO, LA, internalKnownBits());
155       }
156
157       /// Compute the number of known low bits of postOffset.  If this block
158       /// contains inline asm, the number of known bits drops to the
159       /// instruction alignment.  An aligned terminator may increase the number
160       /// of know bits.
161       /// If LogAlign is given, also consider the alignment of the next block.
162       unsigned postKnownBits(unsigned LogAlign = 0) const {
163         return std::max(std::max(unsigned(PostAlign), LogAlign),
164                         internalKnownBits());
165       }
166     };
167
168     std::vector<BasicBlockInfo> BBInfo;
169
170     /// WaterList - A sorted list of basic blocks where islands could be placed
171     /// (i.e. blocks that don't fall through to the following block, due
172     /// to a return, unreachable, or unconditional branch).
173     std::vector<MachineBasicBlock*> WaterList;
174
175     /// NewWaterList - The subset of WaterList that was created since the
176     /// previous iteration by inserting unconditional branches.
177     SmallSet<MachineBasicBlock*, 4> NewWaterList;
178
179     typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
180
181     /// CPUser - One user of a constant pool, keeping the machine instruction
182     /// pointer, the constant pool being referenced, and the max displacement
183     /// allowed from the instruction to the CP.  The HighWaterMark records the
184     /// highest basic block where a new CPEntry can be placed.  To ensure this
185     /// pass terminates, the CP entries are initially placed at the end of the
186     /// function and then move monotonically to lower addresses.  The
187     /// exception to this rule is when the current CP entry for a particular
188     /// CPUser is out of range, but there is another CP entry for the same
189     /// constant value in range.  We want to use the existing in-range CP
190     /// entry, but if it later moves out of range, the search for new water
191     /// should resume where it left off.  The HighWaterMark is used to record
192     /// that point.
193     struct CPUser {
194       MachineInstr *MI;
195       MachineInstr *CPEMI;
196       MachineBasicBlock *HighWaterMark;
197       unsigned MaxDisp;
198       bool NegOk;
199       bool IsSoImm;
200       CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
201              bool neg, bool soimm)
202         : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
203         HighWaterMark = CPEMI->getParent();
204       }
205     };
206
207     /// CPUsers - Keep track of all of the machine instructions that use various
208     /// constant pools and their max displacement.
209     std::vector<CPUser> CPUsers;
210
211     /// CPEntry - One per constant pool entry, keeping the machine instruction
212     /// pointer, the constpool index, and the number of CPUser's which
213     /// reference this entry.
214     struct CPEntry {
215       MachineInstr *CPEMI;
216       unsigned CPI;
217       unsigned RefCount;
218       CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
219         : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
220     };
221
222     /// CPEntries - Keep track of all of the constant pool entry machine
223     /// instructions. For each original constpool index (i.e. those that
224     /// existed upon entry to this pass), it keeps a vector of entries.
225     /// Original elements are cloned as we go along; the clones are
226     /// put in the vector of the original element, but have distinct CPIs.
227     std::vector<std::vector<CPEntry> > CPEntries;
228
229     /// ImmBranch - One per immediate branch, keeping the machine instruction
230     /// pointer, conditional or unconditional, the max displacement,
231     /// and (if isCond is true) the corresponding unconditional branch
232     /// opcode.
233     struct ImmBranch {
234       MachineInstr *MI;
235       unsigned MaxDisp : 31;
236       bool isCond : 1;
237       int UncondBr;
238       ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
239         : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
240     };
241
242     /// ImmBranches - Keep track of all the immediate branch instructions.
243     ///
244     std::vector<ImmBranch> ImmBranches;
245
246     /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
247     ///
248     SmallVector<MachineInstr*, 4> PushPopMIs;
249
250     /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
251     SmallVector<MachineInstr*, 4> T2JumpTables;
252
253     /// HasFarJump - True if any far jump instruction has been emitted during
254     /// the branch fix up pass.
255     bool HasFarJump;
256
257     MachineFunction *MF;
258     MachineConstantPool *MCP;
259     const ARMInstrInfo *TII;
260     const ARMSubtarget *STI;
261     ARMFunctionInfo *AFI;
262     bool isThumb;
263     bool isThumb1;
264     bool isThumb2;
265   public:
266     static char ID;
267     ARMConstantIslands() : MachineFunctionPass(ID) {}
268
269     virtual bool runOnMachineFunction(MachineFunction &MF);
270
271     virtual const char *getPassName() const {
272       return "ARM constant island placement and branch shortening pass";
273     }
274
275   private:
276     void DoInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
277     CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
278     unsigned getCPELogAlign(const MachineInstr *CPEMI);
279     void JumpTableFunctionScan();
280     void InitialFunctionScan(const std::vector<MachineInstr*> &CPEMIs);
281     MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
282     void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
283     void AdjustBBOffsetsAfter(MachineBasicBlock *BB);
284     bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
285     int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
286     bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
287     void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
288                         MachineBasicBlock *&NewMBB);
289     bool HandleConstantPoolUser(unsigned CPUserIndex);
290     void RemoveDeadCPEMI(MachineInstr *CPEMI);
291     bool RemoveUnusedCPEntries();
292     bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
293                       MachineInstr *CPEMI, unsigned Disp, bool NegOk,
294                       bool DoDump = false);
295     bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
296                         CPUser &U);
297     bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
298     bool FixUpImmediateBr(ImmBranch &Br);
299     bool FixUpConditionalBr(ImmBranch &Br);
300     bool FixUpUnconditionalBr(ImmBranch &Br);
301     bool UndoLRSpillRestore();
302     bool OptimizeThumb2Instructions();
303     bool OptimizeThumb2Branches();
304     bool ReorderThumb2JumpTables();
305     bool OptimizeThumb2JumpTables();
306     MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
307                                                   MachineBasicBlock *JTBB);
308
309     void ComputeBlockSize(MachineBasicBlock *MBB);
310     unsigned GetOffsetOf(MachineInstr *MI) const;
311     void dumpBBs();
312     void verify();
313
314     bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
315                          unsigned Disp, bool NegativeOK, bool IsSoImm = false);
316     bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
317                          const CPUser &U) {
318       return OffsetIsInRange(UserOffset, TrialOffset,
319                              U.MaxDisp, U.NegOk, U.IsSoImm);
320     }
321   };
322   char ARMConstantIslands::ID = 0;
323 }
324
325 /// verify - check BBOffsets, BBSizes, alignment of islands
326 void ARMConstantIslands::verify() {
327 #ifndef NDEBUG
328   for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
329        MBBI != E; ++MBBI) {
330     MachineBasicBlock *MBB = MBBI;
331     unsigned Align = MBB->getAlignment();
332     unsigned MBBId = MBB->getNumber();
333     assert(BBInfo[MBBId].Offset % (1u << Align) == 0);
334     assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
335   }
336   for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
337     CPUser &U = CPUsers[i];
338     unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
339     unsigned CPEOffset  = GetOffsetOf(U.CPEMI);
340     unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
341       UserOffset - CPEOffset;
342     assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
343   }
344 #endif
345 }
346
347 /// print block size and offset information - debugging
348 void ARMConstantIslands::dumpBBs() {
349   DEBUG({
350     for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
351       const BasicBlockInfo &BBI = BBInfo[J];
352       dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
353              << " kb=" << unsigned(BBI.KnownBits)
354              << " ua=" << unsigned(BBI.Unalign)
355              << " pa=" << unsigned(BBI.PostAlign)
356              << format(" size=%#x\n", BBInfo[J].Size);
357     }
358   });
359 }
360
361 /// createARMConstantIslandPass - returns an instance of the constpool
362 /// island pass.
363 FunctionPass *llvm::createARMConstantIslandPass() {
364   return new ARMConstantIslands();
365 }
366
367 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
368   MF = &mf;
369   MCP = mf.getConstantPool();
370
371   DEBUG(dbgs() << "***** ARMConstantIslands: "
372                << MCP->getConstants().size() << " CP entries, aligned to "
373                << MCP->getConstantPoolAlignment() << " bytes *****\n");
374
375   TII = (const ARMInstrInfo*)MF->getTarget().getInstrInfo();
376   AFI = MF->getInfo<ARMFunctionInfo>();
377   STI = &MF->getTarget().getSubtarget<ARMSubtarget>();
378
379   isThumb = AFI->isThumbFunction();
380   isThumb1 = AFI->isThumb1OnlyFunction();
381   isThumb2 = AFI->isThumb2Function();
382
383   HasFarJump = false;
384
385   // Renumber all of the machine basic blocks in the function, guaranteeing that
386   // the numbers agree with the position of the block in the function.
387   MF->RenumberBlocks();
388
389   // Try to reorder and otherwise adjust the block layout to make good use
390   // of the TB[BH] instructions.
391   bool MadeChange = false;
392   if (isThumb2 && AdjustJumpTableBlocks) {
393     JumpTableFunctionScan();
394     MadeChange |= ReorderThumb2JumpTables();
395     // Data is out of date, so clear it. It'll be re-computed later.
396     T2JumpTables.clear();
397     // Blocks may have shifted around. Keep the numbering up to date.
398     MF->RenumberBlocks();
399   }
400
401   // Thumb1 functions containing constant pools get 4-byte alignment.
402   // This is so we can keep exact track of where the alignment padding goes.
403
404   // ARM and Thumb2 functions need to be 4-byte aligned.
405   if (!isThumb1)
406     MF->EnsureAlignment(2);  // 2 = log2(4)
407
408   // Perform the initial placement of the constant pool entries.  To start with,
409   // we put them all at the end of the function.
410   std::vector<MachineInstr*> CPEMIs;
411   if (!MCP->isEmpty())
412     DoInitialPlacement(CPEMIs);
413
414   /// The next UID to take is the first unused one.
415   AFI->initPICLabelUId(CPEMIs.size());
416
417   // Do the initial scan of the function, building up information about the
418   // sizes of each block, the location of all the water, and finding all of the
419   // constant pool users.
420   InitialFunctionScan(CPEMIs);
421   CPEMIs.clear();
422   DEBUG(dumpBBs());
423
424
425   /// Remove dead constant pool entries.
426   MadeChange |= RemoveUnusedCPEntries();
427
428   // Iteratively place constant pool entries and fix up branches until there
429   // is no change.
430   unsigned NoCPIters = 0, NoBRIters = 0;
431   while (true) {
432     DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
433     bool CPChange = false;
434     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
435       CPChange |= HandleConstantPoolUser(i);
436     if (CPChange && ++NoCPIters > 30)
437       llvm_unreachable("Constant Island pass failed to converge!");
438     DEBUG(dumpBBs());
439
440     // Clear NewWaterList now.  If we split a block for branches, it should
441     // appear as "new water" for the next iteration of constant pool placement.
442     NewWaterList.clear();
443
444     DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
445     bool BRChange = false;
446     for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
447       BRChange |= FixUpImmediateBr(ImmBranches[i]);
448     if (BRChange && ++NoBRIters > 30)
449       llvm_unreachable("Branch Fix Up pass failed to converge!");
450     DEBUG(dumpBBs());
451
452     if (!CPChange && !BRChange)
453       break;
454     MadeChange = true;
455   }
456
457   // Shrink 32-bit Thumb2 branch, load, and store instructions.
458   if (isThumb2 && !STI->prefers32BitThumb())
459     MadeChange |= OptimizeThumb2Instructions();
460
461   // After a while, this might be made debug-only, but it is not expensive.
462   verify();
463
464   // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
465   // undo the spill / restore of LR if possible.
466   if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
467     MadeChange |= UndoLRSpillRestore();
468
469   // Save the mapping between original and cloned constpool entries.
470   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
471     for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
472       const CPEntry & CPE = CPEntries[i][j];
473       AFI->recordCPEClone(i, CPE.CPI);
474     }
475   }
476
477   DEBUG(dbgs() << '\n'; dumpBBs());
478
479   BBInfo.clear();
480   WaterList.clear();
481   CPUsers.clear();
482   CPEntries.clear();
483   ImmBranches.clear();
484   PushPopMIs.clear();
485   T2JumpTables.clear();
486
487   return MadeChange;
488 }
489
490 /// DoInitialPlacement - Perform the initial placement of the constant pool
491 /// entries.  To start with, we put them all at the end of the function.
492 void
493 ARMConstantIslands::DoInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
494   // Create the basic block to hold the CPE's.
495   MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
496   MF->push_back(BB);
497
498   // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
499   unsigned MaxAlign = Log2_32(MF->getConstantPool()->getConstantPoolAlignment());
500
501   // Mark the basic block as required by the const-pool.
502   // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
503   BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
504
505   // The function needs to be as aligned as the basic blocks. The linker may
506   // move functions around based on their alignment.
507   MF->EnsureAlignment(BB->getAlignment());
508
509   // Order the entries in BB by descending alignment.  That ensures correct
510   // alignment of all entries as long as BB is sufficiently aligned.  Keep
511   // track of the insertion point for each alignment.  We are going to bucket
512   // sort the entries as they are created.
513   SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
514
515   // Add all of the constants from the constant pool to the end block, use an
516   // identity mapping of CPI's to CPE's.
517   const std::vector<MachineConstantPoolEntry> &CPs =
518     MF->getConstantPool()->getConstants();
519
520   const TargetData &TD = *MF->getTarget().getTargetData();
521   for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
522     unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
523     assert(Size >= 4 && "Too small constant pool entry");
524     unsigned Align = CPs[i].getAlignment();
525     assert(isPowerOf2_32(Align) && "Invalid alignment");
526     // Verify that all constant pool entries are a multiple of their alignment.
527     // If not, we would have to pad them out so that instructions stay aligned.
528     assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
529
530     // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
531     unsigned LogAlign = Log2_32(Align);
532     MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
533     MachineInstr *CPEMI =
534       BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
535         .addImm(i).addConstantPoolIndex(i).addImm(Size);
536     CPEMIs.push_back(CPEMI);
537
538     // Ensure that future entries with higher alignment get inserted before
539     // CPEMI. This is bucket sort with iterators.
540     for (unsigned a = LogAlign + 1; a < MaxAlign; ++a)
541       if (InsPoint[a] == InsAt)
542         InsPoint[a] = CPEMI;
543
544     // Add a new CPEntry, but no corresponding CPUser yet.
545     std::vector<CPEntry> CPEs;
546     CPEs.push_back(CPEntry(CPEMI, i));
547     CPEntries.push_back(CPEs);
548     ++NumCPEs;
549     DEBUG(dbgs() << "Moved CPI#" << i << " to end of function\n");
550   }
551   DEBUG(BB->dump());
552 }
553
554 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
555 /// into the block immediately after it.
556 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
557   // Get the next machine basic block in the function.
558   MachineFunction::iterator MBBI = MBB;
559   // Can't fall off end of function.
560   if (llvm::next(MBBI) == MBB->getParent()->end())
561     return false;
562
563   MachineBasicBlock *NextBB = llvm::next(MBBI);
564   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
565        E = MBB->succ_end(); I != E; ++I)
566     if (*I == NextBB)
567       return true;
568
569   return false;
570 }
571
572 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
573 /// look up the corresponding CPEntry.
574 ARMConstantIslands::CPEntry
575 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
576                                         const MachineInstr *CPEMI) {
577   std::vector<CPEntry> &CPEs = CPEntries[CPI];
578   // Number of entries per constpool index should be small, just do a
579   // linear search.
580   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
581     if (CPEs[i].CPEMI == CPEMI)
582       return &CPEs[i];
583   }
584   return NULL;
585 }
586
587 /// getCPELogAlign - Returns the required alignment of the constant pool entry
588 /// represented by CPEMI.  Alignment is measured in log2(bytes) units.
589 unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
590   assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
591
592   // Everything is 4-byte aligned unless AlignConstantIslands is set.
593   if (!AlignConstantIslands)
594     return 2;
595
596   unsigned CPI = CPEMI->getOperand(1).getIndex();
597   assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
598   unsigned Align = MCP->getConstants()[CPI].getAlignment();
599   assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
600   return Log2_32(Align);
601 }
602
603 /// JumpTableFunctionScan - Do a scan of the function, building up
604 /// information about the sizes of each block and the locations of all
605 /// the jump tables.
606 void ARMConstantIslands::JumpTableFunctionScan() {
607   for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
608        MBBI != E; ++MBBI) {
609     MachineBasicBlock &MBB = *MBBI;
610
611     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
612          I != E; ++I)
613       if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
614         T2JumpTables.push_back(I);
615   }
616 }
617
618 /// InitialFunctionScan - Do the initial scan of the function, building up
619 /// information about the sizes of each block, the location of all the water,
620 /// and finding all of the constant pool users.
621 void ARMConstantIslands::
622 InitialFunctionScan(const std::vector<MachineInstr*> &CPEMIs) {
623   BBInfo.clear();
624   BBInfo.resize(MF->getNumBlockIDs());
625
626   // First thing, compute the size of all basic blocks, and see if the function
627   // has any inline assembly in it. If so, we have to be conservative about
628   // alignment assumptions, as we don't know for sure the size of any
629   // instructions in the inline assembly.
630   for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
631     ComputeBlockSize(I);
632
633   // The known bits of the entry block offset are determined by the function
634   // alignment.
635   BBInfo.front().KnownBits = MF->getAlignment();
636
637   // Compute block offsets and known bits.
638   AdjustBBOffsetsAfter(MF->begin());
639
640   // Now go back through the instructions and build up our data structures.
641   for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
642        MBBI != E; ++MBBI) {
643     MachineBasicBlock &MBB = *MBBI;
644
645     // If this block doesn't fall through into the next MBB, then this is
646     // 'water' that a constant pool island could be placed.
647     if (!BBHasFallthrough(&MBB))
648       WaterList.push_back(&MBB);
649
650     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
651          I != E; ++I) {
652       if (I->isDebugValue())
653         continue;
654
655       int Opc = I->getOpcode();
656       if (I->isBranch()) {
657         bool isCond = false;
658         unsigned Bits = 0;
659         unsigned Scale = 1;
660         int UOpc = Opc;
661         switch (Opc) {
662         default:
663           continue;  // Ignore other JT branches
664         case ARM::t2BR_JT:
665           T2JumpTables.push_back(I);
666           continue;   // Does not get an entry in ImmBranches
667         case ARM::Bcc:
668           isCond = true;
669           UOpc = ARM::B;
670           // Fallthrough
671         case ARM::B:
672           Bits = 24;
673           Scale = 4;
674           break;
675         case ARM::tBcc:
676           isCond = true;
677           UOpc = ARM::tB;
678           Bits = 8;
679           Scale = 2;
680           break;
681         case ARM::tB:
682           Bits = 11;
683           Scale = 2;
684           break;
685         case ARM::t2Bcc:
686           isCond = true;
687           UOpc = ARM::t2B;
688           Bits = 20;
689           Scale = 2;
690           break;
691         case ARM::t2B:
692           Bits = 24;
693           Scale = 2;
694           break;
695         }
696
697         // Record this immediate branch.
698         unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
699         ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
700       }
701
702       if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
703         PushPopMIs.push_back(I);
704
705       if (Opc == ARM::CONSTPOOL_ENTRY)
706         continue;
707
708       // Scan the instructions for constant pool operands.
709       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
710         if (I->getOperand(op).isCPI()) {
711           // We found one.  The addressing mode tells us the max displacement
712           // from the PC that this instruction permits.
713
714           // Basic size info comes from the TSFlags field.
715           unsigned Bits = 0;
716           unsigned Scale = 1;
717           bool NegOk = false;
718           bool IsSoImm = false;
719
720           switch (Opc) {
721           default:
722             llvm_unreachable("Unknown addressing mode for CP reference!");
723             break;
724
725           // Taking the address of a CP entry.
726           case ARM::LEApcrel:
727             // This takes a SoImm, which is 8 bit immediate rotated. We'll
728             // pretend the maximum offset is 255 * 4. Since each instruction
729             // 4 byte wide, this is always correct. We'll check for other
730             // displacements that fits in a SoImm as well.
731             Bits = 8;
732             Scale = 4;
733             NegOk = true;
734             IsSoImm = true;
735             break;
736           case ARM::t2LEApcrel:
737             Bits = 12;
738             NegOk = true;
739             break;
740           case ARM::tLEApcrel:
741             Bits = 8;
742             Scale = 4;
743             break;
744
745           case ARM::LDRi12:
746           case ARM::LDRcp:
747           case ARM::t2LDRpci:
748             Bits = 12;  // +-offset_12
749             NegOk = true;
750             break;
751
752           case ARM::tLDRpci:
753             Bits = 8;
754             Scale = 4;  // +(offset_8*4)
755             break;
756
757           case ARM::VLDRD:
758           case ARM::VLDRS:
759             Bits = 8;
760             Scale = 4;  // +-(offset_8*4)
761             NegOk = true;
762             break;
763           }
764
765           // Remember that this is a user of a CP entry.
766           unsigned CPI = I->getOperand(op).getIndex();
767           MachineInstr *CPEMI = CPEMIs[CPI];
768           unsigned MaxOffs = ((1 << Bits)-1) * Scale;
769           CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
770
771           // Increment corresponding CPEntry reference count.
772           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
773           assert(CPE && "Cannot find a corresponding CPEntry!");
774           CPE->RefCount++;
775
776           // Instructions can only use one CP entry, don't bother scanning the
777           // rest of the operands.
778           break;
779         }
780     }
781   }
782 }
783
784 /// ComputeBlockSize - Compute the size and some alignment information for MBB.
785 /// This function updates BBInfo directly.
786 void ARMConstantIslands::ComputeBlockSize(MachineBasicBlock *MBB) {
787   BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
788   BBI.Size = 0;
789   BBI.Unalign = 0;
790   BBI.PostAlign = 0;
791
792   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
793        ++I) {
794     BBI.Size += TII->GetInstSizeInBytes(I);
795     // For inline asm, GetInstSizeInBytes returns a conservative estimate.
796     // The actual size may be smaller, but still a multiple of the instr size.
797     if (I->isInlineAsm())
798       BBI.Unalign = isThumb ? 1 : 2;
799   }
800
801   // tBR_JTr contains a .align 2 directive.
802   if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
803     BBI.PostAlign = 2;
804     MBB->getParent()->EnsureAlignment(2);
805   }
806 }
807
808 /// GetOffsetOf - Return the current offset of the specified machine instruction
809 /// from the start of the function.  This offset changes as stuff is moved
810 /// around inside the function.
811 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
812   MachineBasicBlock *MBB = MI->getParent();
813
814   // The offset is composed of two things: the sum of the sizes of all MBB's
815   // before this instruction's block, and the offset from the start of the block
816   // it is in.
817   unsigned Offset = BBInfo[MBB->getNumber()].Offset;
818
819   // Sum instructions before MI in MBB.
820   for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
821     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
822     if (&*I == MI) return Offset;
823     Offset += TII->GetInstSizeInBytes(I);
824   }
825 }
826
827 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
828 /// ID.
829 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
830                               const MachineBasicBlock *RHS) {
831   return LHS->getNumber() < RHS->getNumber();
832 }
833
834 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
835 /// machine function, it upsets all of the block numbers.  Renumber the blocks
836 /// and update the arrays that parallel this numbering.
837 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
838   // Renumber the MBB's to keep them consecutive.
839   NewBB->getParent()->RenumberBlocks(NewBB);
840
841   // Insert an entry into BBInfo to align it properly with the (newly
842   // renumbered) block numbers.
843   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
844
845   // Next, update WaterList.  Specifically, we need to add NewMBB as having
846   // available water after it.
847   water_iterator IP =
848     std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
849                      CompareMBBNumbers);
850   WaterList.insert(IP, NewBB);
851 }
852
853
854 /// Split the basic block containing MI into two blocks, which are joined by
855 /// an unconditional branch.  Update data structures and renumber blocks to
856 /// account for this change and returns the newly created block.
857 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
858   MachineBasicBlock *OrigBB = MI->getParent();
859
860   // Create a new MBB for the code after the OrigBB.
861   MachineBasicBlock *NewBB =
862     MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
863   MachineFunction::iterator MBBI = OrigBB; ++MBBI;
864   MF->insert(MBBI, NewBB);
865
866   // Splice the instructions starting with MI over to NewBB.
867   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
868
869   // Add an unconditional branch from OrigBB to NewBB.
870   // Note the new unconditional branch is not being recorded.
871   // There doesn't seem to be meaningful DebugInfo available; this doesn't
872   // correspond to anything in the source.
873   unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
874   if (!isThumb)
875     BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
876   else
877     BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
878             .addImm(ARMCC::AL).addReg(0);
879   ++NumSplit;
880
881   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
882   NewBB->transferSuccessors(OrigBB);
883
884   // OrigBB branches to NewBB.
885   OrigBB->addSuccessor(NewBB);
886
887   // Update internal data structures to account for the newly inserted MBB.
888   // This is almost the same as UpdateForInsertedWaterBlock, except that
889   // the Water goes after OrigBB, not NewBB.
890   MF->RenumberBlocks(NewBB);
891
892   // Insert an entry into BBInfo to align it properly with the (newly
893   // renumbered) block numbers.
894   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
895
896   // Next, update WaterList.  Specifically, we need to add OrigMBB as having
897   // available water after it (but not if it's already there, which happens
898   // when splitting before a conditional branch that is followed by an
899   // unconditional branch - in that case we want to insert NewBB).
900   water_iterator IP =
901     std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
902                      CompareMBBNumbers);
903   MachineBasicBlock* WaterBB = *IP;
904   if (WaterBB == OrigBB)
905     WaterList.insert(llvm::next(IP), NewBB);
906   else
907     WaterList.insert(IP, OrigBB);
908   NewWaterList.insert(OrigBB);
909
910   // Figure out how large the OrigBB is.  As the first half of the original
911   // block, it cannot contain a tablejump.  The size includes
912   // the new jump we added.  (It should be possible to do this without
913   // recounting everything, but it's very confusing, and this is rarely
914   // executed.)
915   ComputeBlockSize(OrigBB);
916
917   // Figure out how large the NewMBB is.  As the second half of the original
918   // block, it may contain a tablejump.
919   ComputeBlockSize(NewBB);
920
921   // All BBOffsets following these blocks must be modified.
922   AdjustBBOffsetsAfter(OrigBB);
923
924   return NewBB;
925 }
926
927 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
928 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
929 /// constant pool entry).
930 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
931                                          unsigned TrialOffset, unsigned MaxDisp,
932                                          bool NegativeOK, bool IsSoImm) {
933   // On Thumb offsets==2 mod 4 are rounded down by the hardware for
934   // purposes of the displacement computation; compensate for that here.
935   // Effectively, the valid range of displacements is 2 bytes smaller for such
936   // references.
937   unsigned TotalAdj = 0;
938   if (isThumb && UserOffset%4 !=0) {
939     UserOffset -= 2;
940     TotalAdj = 2;
941   }
942   // CPEs will be rounded up to a multiple of 4.
943   if (isThumb && TrialOffset%4 != 0) {
944     TrialOffset += 2;
945     TotalAdj += 2;
946   }
947
948   // In Thumb2 mode, later branch adjustments can shift instructions up and
949   // cause alignment change. In the worst case scenario this can cause the
950   // user's effective address to be subtracted by 2 and the CPE's address to
951   // be plus 2.
952   if (isThumb2 && TotalAdj != 4)
953     MaxDisp -= (4 - TotalAdj);
954
955   if (UserOffset <= TrialOffset) {
956     // User before the Trial.
957     if (TrialOffset - UserOffset <= MaxDisp)
958       return true;
959     // FIXME: Make use full range of soimm values.
960   } else if (NegativeOK) {
961     if (UserOffset - TrialOffset <= MaxDisp)
962       return true;
963     // FIXME: Make use full range of soimm values.
964   }
965   return false;
966 }
967
968 /// WaterIsInRange - Returns true if a CPE placed after the specified
969 /// Water (a basic block) will be in range for the specific MI.
970
971 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
972                                         MachineBasicBlock* Water, CPUser &U) {
973   unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
974
975   // If the CPE is to be inserted before the instruction, that will raise
976   // the offset of the instruction.
977   if (CPEOffset < UserOffset)
978     UserOffset += U.CPEMI->getOperand(2).getImm();
979
980   return OffsetIsInRange(UserOffset, CPEOffset, U);
981 }
982
983 /// CPEIsInRange - Returns true if the distance between specific MI and
984 /// specific ConstPool entry instruction can fit in MI's displacement field.
985 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
986                                       MachineInstr *CPEMI, unsigned MaxDisp,
987                                       bool NegOk, bool DoDump) {
988   unsigned CPEOffset  = GetOffsetOf(CPEMI);
989   assert(CPEOffset % 4 == 0 && "Misaligned CPE");
990
991   if (DoDump) {
992     DEBUG({
993       unsigned Block = MI->getParent()->getNumber();
994       const BasicBlockInfo &BBI = BBInfo[Block];
995       dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
996              << " max delta=" << MaxDisp
997              << format(" insn address=%#x", UserOffset)
998              << " in BB#" << Block << ": "
999              << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1000              << format("CPE address=%#x offset=%+d: ", CPEOffset,
1001                        int(CPEOffset-UserOffset));
1002     });
1003   }
1004
1005   return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1006 }
1007
1008 #ifndef NDEBUG
1009 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1010 /// unconditionally branches to its only successor.
1011 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1012   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1013     return false;
1014
1015   MachineBasicBlock *Succ = *MBB->succ_begin();
1016   MachineBasicBlock *Pred = *MBB->pred_begin();
1017   MachineInstr *PredMI = &Pred->back();
1018   if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1019       || PredMI->getOpcode() == ARM::t2B)
1020     return PredMI->getOperand(0).getMBB() == Succ;
1021   return false;
1022 }
1023 #endif // NDEBUG
1024
1025 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB) {
1026   for(unsigned i = BB->getNumber() + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1027     // Get the offset and known bits at the end of the layout predecessor.
1028     // Include the alignment of the current block.
1029     unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1030     unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1031     unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
1032
1033     // This is where block i begins.
1034     BBInfo[i].Offset = Offset;
1035     BBInfo[i].KnownBits = KnownBits;
1036   }
1037 }
1038
1039 /// DecrementOldEntry - find the constant pool entry with index CPI
1040 /// and instruction CPEMI, and decrement its refcount.  If the refcount
1041 /// becomes 0 remove the entry and instruction.  Returns true if we removed
1042 /// the entry, false if we didn't.
1043
1044 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
1045   // Find the old entry. Eliminate it if it is no longer used.
1046   CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1047   assert(CPE && "Unexpected!");
1048   if (--CPE->RefCount == 0) {
1049     RemoveDeadCPEMI(CPEMI);
1050     CPE->CPEMI = NULL;
1051     --NumCPEs;
1052     return true;
1053   }
1054   return false;
1055 }
1056
1057 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1058 /// if not, see if an in-range clone of the CPE is in range, and if so,
1059 /// change the data structures so the user references the clone.  Returns:
1060 /// 0 = no existing entry found
1061 /// 1 = entry found, and there were no code insertions or deletions
1062 /// 2 = entry found, and there were code insertions or deletions
1063 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1064 {
1065   MachineInstr *UserMI = U.MI;
1066   MachineInstr *CPEMI  = U.CPEMI;
1067
1068   // Check to see if the CPE is already in-range.
1069   if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
1070     DEBUG(dbgs() << "In range\n");
1071     return 1;
1072   }
1073
1074   // No.  Look for previously created clones of the CPE that are in range.
1075   unsigned CPI = CPEMI->getOperand(1).getIndex();
1076   std::vector<CPEntry> &CPEs = CPEntries[CPI];
1077   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1078     // We already tried this one
1079     if (CPEs[i].CPEMI == CPEMI)
1080       continue;
1081     // Removing CPEs can leave empty entries, skip
1082     if (CPEs[i].CPEMI == NULL)
1083       continue;
1084     if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
1085       DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1086                    << CPEs[i].CPI << "\n");
1087       // Point the CPUser node to the replacement
1088       U.CPEMI = CPEs[i].CPEMI;
1089       // Change the CPI in the instruction operand to refer to the clone.
1090       for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1091         if (UserMI->getOperand(j).isCPI()) {
1092           UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1093           break;
1094         }
1095       // Adjust the refcount of the clone...
1096       CPEs[i].RefCount++;
1097       // ...and the original.  If we didn't remove the old entry, none of the
1098       // addresses changed, so we don't need another pass.
1099       return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
1100     }
1101   }
1102   return 0;
1103 }
1104
1105 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1106 /// the specific unconditional branch instruction.
1107 static inline unsigned getUnconditionalBrDisp(int Opc) {
1108   switch (Opc) {
1109   case ARM::tB:
1110     return ((1<<10)-1)*2;
1111   case ARM::t2B:
1112     return ((1<<23)-1)*2;
1113   default:
1114     break;
1115   }
1116
1117   return ((1<<23)-1)*4;
1118 }
1119
1120 /// LookForWater - Look for an existing entry in the WaterList in which
1121 /// we can place the CPE referenced from U so it's within range of U's MI.
1122 /// Returns true if found, false if not.  If it returns true, WaterIter
1123 /// is set to the WaterList entry.  For Thumb, prefer water that will not
1124 /// introduce padding to water that will.  To ensure that this pass
1125 /// terminates, the CPE location for a particular CPUser is only allowed to
1126 /// move to a lower address, so search backward from the end of the list and
1127 /// prefer the first water that is in range.
1128 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
1129                                       water_iterator &WaterIter) {
1130   if (WaterList.empty())
1131     return false;
1132
1133   bool FoundWaterThatWouldPad = false;
1134   water_iterator IPThatWouldPad;
1135   for (water_iterator IP = prior(WaterList.end()),
1136          B = WaterList.begin();; --IP) {
1137     MachineBasicBlock* WaterBB = *IP;
1138     // Check if water is in range and is either at a lower address than the
1139     // current "high water mark" or a new water block that was created since
1140     // the previous iteration by inserting an unconditional branch.  In the
1141     // latter case, we want to allow resetting the high water mark back to
1142     // this new water since we haven't seen it before.  Inserting branches
1143     // should be relatively uncommon and when it does happen, we want to be
1144     // sure to take advantage of it for all the CPEs near that block, so that
1145     // we don't insert more branches than necessary.
1146     if (WaterIsInRange(UserOffset, WaterBB, U) &&
1147         (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1148          NewWaterList.count(WaterBB))) {
1149       unsigned WBBId = WaterBB->getNumber();
1150       if (isThumb && BBInfo[WBBId].postOffset()%4 != 0) {
1151         // This is valid Water, but would introduce padding.  Remember
1152         // it in case we don't find any Water that doesn't do this.
1153         if (!FoundWaterThatWouldPad) {
1154           FoundWaterThatWouldPad = true;
1155           IPThatWouldPad = IP;
1156         }
1157       } else {
1158         WaterIter = IP;
1159         return true;
1160       }
1161     }
1162     if (IP == B)
1163       break;
1164   }
1165   if (FoundWaterThatWouldPad) {
1166     WaterIter = IPThatWouldPad;
1167     return true;
1168   }
1169   return false;
1170 }
1171
1172 /// CreateNewWater - No existing WaterList entry will work for
1173 /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
1174 /// block is used if in range, and the conditional branch munged so control
1175 /// flow is correct.  Otherwise the block is split to create a hole with an
1176 /// unconditional branch around it.  In either case NewMBB is set to a
1177 /// block following which the new island can be inserted (the WaterList
1178 /// is not adjusted).
1179 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
1180                                         unsigned UserOffset,
1181                                         MachineBasicBlock *&NewMBB) {
1182   CPUser &U = CPUsers[CPUserIndex];
1183   MachineInstr *UserMI = U.MI;
1184   MachineInstr *CPEMI  = U.CPEMI;
1185   MachineBasicBlock *UserMBB = UserMI->getParent();
1186   const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1187   unsigned OffsetOfNextBlock = UserBBI.postOffset();
1188
1189   // If the block does not end in an unconditional branch already, and if the
1190   // end of the block is within range, make new water there.  (The addition
1191   // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1192   // Thumb2, 2 on Thumb1.  Possible Thumb1 alignment padding is allowed for
1193   // inside OffsetIsInRange.
1194   if (BBHasFallthrough(UserMBB) &&
1195       OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4), U)) {
1196     DEBUG(dbgs() << "Split at end of block\n");
1197     if (&UserMBB->back() == UserMI)
1198       assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1199     NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1200     // Add an unconditional branch from UserMBB to fallthrough block.
1201     // Record it for branch lengthening; this new branch will not get out of
1202     // range, but if the preceding conditional branch is out of range, the
1203     // targets will be exchanged, and the altered branch may be out of
1204     // range, so the machinery has to know about it.
1205     int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1206     if (!isThumb)
1207       BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1208     else
1209       BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1210               .addImm(ARMCC::AL).addReg(0);
1211     unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1212     ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1213                           MaxDisp, false, UncondBr));
1214     int delta = isThumb1 ? 2 : 4;
1215     BBInfo[UserMBB->getNumber()].Size += delta;
1216     AdjustBBOffsetsAfter(UserMBB);
1217   } else {
1218     // What a big block.  Find a place within the block to split it.
1219     // This is a little tricky on Thumb1 since instructions are 2 bytes
1220     // and constant pool entries are 4 bytes: if instruction I references
1221     // island CPE, and instruction I+1 references CPE', it will
1222     // not work well to put CPE as far forward as possible, since then
1223     // CPE' cannot immediately follow it (that location is 2 bytes
1224     // farther away from I+1 than CPE was from I) and we'd need to create
1225     // a new island.  So, we make a first guess, then walk through the
1226     // instructions between the one currently being looked at and the
1227     // possible insertion point, and make sure any other instructions
1228     // that reference CPEs will be able to use the same island area;
1229     // if not, we back up the insertion point.
1230
1231     // Try to split the block so it's fully aligned.  Compute the latest split
1232     // point where we can add a 4-byte branch instruction, and then
1233     // WorstCaseAlign to LogAlign.
1234     unsigned LogAlign = UserMBB->getParent()->getAlignment();
1235     unsigned KnownBits = UserBBI.internalKnownBits();
1236     unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1237     unsigned BaseInsertOffset = UserOffset + U.MaxDisp;
1238     DEBUG(dbgs() << format("Split in middle of big block before %#x",
1239                            BaseInsertOffset));
1240
1241     // Account for alignment and unknown padding.
1242     BaseInsertOffset &= ~((1u << LogAlign) - 1);
1243     BaseInsertOffset -= UPad;
1244
1245     // The 4 in the following is for the unconditional branch we'll be
1246     // inserting (allows for long branch on Thumb1).  Alignment of the
1247     // island is handled inside OffsetIsInRange.
1248     BaseInsertOffset -= 4;
1249
1250     DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1251                  << " la=" << LogAlign
1252                  << " kb=" << KnownBits
1253                  << " up=" << UPad << '\n');
1254
1255     // This could point off the end of the block if we've already got
1256     // constant pool entries following this block; only the last one is
1257     // in the water list.  Back past any possible branches (allow for a
1258     // conditional and a maximally long unconditional).
1259     if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1260       BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
1261                               (isThumb1 ? 6 : 8);
1262     unsigned EndInsertOffset =
1263       WorstCaseAlign(BaseInsertOffset + 4, LogAlign, KnownBits) +
1264       CPEMI->getOperand(2).getImm();
1265     MachineBasicBlock::iterator MI = UserMI;
1266     ++MI;
1267     unsigned CPUIndex = CPUserIndex+1;
1268     unsigned NumCPUsers = CPUsers.size();
1269     MachineInstr *LastIT = 0;
1270     for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1271          Offset < BaseInsertOffset;
1272          Offset += TII->GetInstSizeInBytes(MI),
1273            MI = llvm::next(MI)) {
1274       if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1275         CPUser &U = CPUsers[CPUIndex];
1276         if (!OffsetIsInRange(Offset, EndInsertOffset, U)) {
1277           BaseInsertOffset -= 1u << LogAlign;
1278           EndInsertOffset  -= 1u << LogAlign;
1279         }
1280         // This is overly conservative, as we don't account for CPEMIs
1281         // being reused within the block, but it doesn't matter much.
1282         EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1283         CPUIndex++;
1284       }
1285
1286       // Remember the last IT instruction.
1287       if (MI->getOpcode() == ARM::t2IT)
1288         LastIT = MI;
1289     }
1290
1291     --MI;
1292
1293     // Avoid splitting an IT block.
1294     if (LastIT) {
1295       unsigned PredReg = 0;
1296       ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1297       if (CC != ARMCC::AL)
1298         MI = LastIT;
1299     }
1300     NewMBB = SplitBlockBeforeInstr(MI);
1301   }
1302 }
1303
1304 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1305 /// is out-of-range.  If so, pick up the constant pool value and move it some
1306 /// place in-range.  Return true if we changed any addresses (thus must run
1307 /// another pass of branch lengthening), false otherwise.
1308 bool ARMConstantIslands::HandleConstantPoolUser(unsigned CPUserIndex) {
1309   CPUser &U = CPUsers[CPUserIndex];
1310   MachineInstr *UserMI = U.MI;
1311   MachineInstr *CPEMI  = U.CPEMI;
1312   unsigned CPI = CPEMI->getOperand(1).getIndex();
1313   unsigned Size = CPEMI->getOperand(2).getImm();
1314   // Compute this only once, it's expensive.  The 4 or 8 is the value the
1315   // hardware keeps in the PC.
1316   unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1317
1318   // See if the current entry is within range, or there is a clone of it
1319   // in range.
1320   int result = LookForExistingCPEntry(U, UserOffset);
1321   if (result==1) return false;
1322   else if (result==2) return true;
1323
1324   // No existing clone of this CPE is within range.
1325   // We will be generating a new clone.  Get a UID for it.
1326   unsigned ID = AFI->createPICLabelUId();
1327
1328   // Look for water where we can place this CPE.
1329   MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1330   MachineBasicBlock *NewMBB;
1331   water_iterator IP;
1332   if (LookForWater(U, UserOffset, IP)) {
1333     DEBUG(dbgs() << "Found water in range\n");
1334     MachineBasicBlock *WaterBB = *IP;
1335
1336     // If the original WaterList entry was "new water" on this iteration,
1337     // propagate that to the new island.  This is just keeping NewWaterList
1338     // updated to match the WaterList, which will be updated below.
1339     if (NewWaterList.count(WaterBB)) {
1340       NewWaterList.erase(WaterBB);
1341       NewWaterList.insert(NewIsland);
1342     }
1343     // The new CPE goes before the following block (NewMBB).
1344     NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1345
1346   } else {
1347     // No water found.
1348     DEBUG(dbgs() << "No water found\n");
1349     CreateNewWater(CPUserIndex, UserOffset, NewMBB);
1350
1351     // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1352     // called while handling branches so that the water will be seen on the
1353     // next iteration for constant pools, but in this context, we don't want
1354     // it.  Check for this so it will be removed from the WaterList.
1355     // Also remove any entry from NewWaterList.
1356     MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1357     IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1358     if (IP != WaterList.end())
1359       NewWaterList.erase(WaterBB);
1360
1361     // We are adding new water.  Update NewWaterList.
1362     NewWaterList.insert(NewIsland);
1363   }
1364
1365   // Remove the original WaterList entry; we want subsequent insertions in
1366   // this vicinity to go after the one we're about to insert.  This
1367   // considerably reduces the number of times we have to move the same CPE
1368   // more than once and is also important to ensure the algorithm terminates.
1369   if (IP != WaterList.end())
1370     WaterList.erase(IP);
1371
1372   // Okay, we know we can put an island before NewMBB now, do it!
1373   MF->insert(NewMBB, NewIsland);
1374
1375   // Update internal data structures to account for the newly inserted MBB.
1376   UpdateForInsertedWaterBlock(NewIsland);
1377
1378   // Decrement the old entry, and remove it if refcount becomes 0.
1379   DecrementOldEntry(CPI, CPEMI);
1380
1381   // Now that we have an island to add the CPE to, clone the original CPE and
1382   // add it to the island.
1383   U.HighWaterMark = NewIsland;
1384   U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1385                 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1386   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1387   ++NumCPEs;
1388
1389   // Mark the basic block as aligned as required by the const-pool entry.
1390   NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1391
1392   // Increase the size of the island block to account for the new entry.
1393   BBInfo[NewIsland->getNumber()].Size += Size;
1394   AdjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
1395
1396   // Finally, change the CPI in the instruction operand to be ID.
1397   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1398     if (UserMI->getOperand(i).isCPI()) {
1399       UserMI->getOperand(i).setIndex(ID);
1400       break;
1401     }
1402
1403   DEBUG(dbgs() << "  Moved CPE to #" << ID << " CPI=" << CPI
1404         << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1405
1406   return true;
1407 }
1408
1409 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1410 /// sizes and offsets of impacted basic blocks.
1411 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1412   MachineBasicBlock *CPEBB = CPEMI->getParent();
1413   unsigned Size = CPEMI->getOperand(2).getImm();
1414   CPEMI->eraseFromParent();
1415   BBInfo[CPEBB->getNumber()].Size -= Size;
1416   // All succeeding offsets have the current size value added in, fix this.
1417   if (CPEBB->empty()) {
1418     BBInfo[CPEBB->getNumber()].Size = 0;
1419
1420     // This block no longer needs to be aligned. <rdar://problem/10534709>.
1421     CPEBB->setAlignment(0);
1422   } else
1423     // Entries are sorted by descending alignment, so realign from the front.
1424     CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1425
1426   AdjustBBOffsetsAfter(CPEBB);
1427   // An island has only one predecessor BB and one successor BB. Check if
1428   // this BB's predecessor jumps directly to this BB's successor. This
1429   // shouldn't happen currently.
1430   assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1431   // FIXME: remove the empty blocks after all the work is done?
1432 }
1433
1434 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1435 /// are zero.
1436 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1437   unsigned MadeChange = false;
1438   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1439       std::vector<CPEntry> &CPEs = CPEntries[i];
1440       for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1441         if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1442           RemoveDeadCPEMI(CPEs[j].CPEMI);
1443           CPEs[j].CPEMI = NULL;
1444           MadeChange = true;
1445         }
1446       }
1447   }
1448   return MadeChange;
1449 }
1450
1451 /// BBIsInRange - Returns true if the distance between specific MI and
1452 /// specific BB can fit in MI's displacement field.
1453 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1454                                      unsigned MaxDisp) {
1455   unsigned PCAdj      = isThumb ? 4 : 8;
1456   unsigned BrOffset   = GetOffsetOf(MI) + PCAdj;
1457   unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1458
1459   DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1460                << " from BB#" << MI->getParent()->getNumber()
1461                << " max delta=" << MaxDisp
1462                << " from " << GetOffsetOf(MI) << " to " << DestOffset
1463                << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1464
1465   if (BrOffset <= DestOffset) {
1466     // Branch before the Dest.
1467     if (DestOffset-BrOffset <= MaxDisp)
1468       return true;
1469   } else {
1470     if (BrOffset-DestOffset <= MaxDisp)
1471       return true;
1472   }
1473   return false;
1474 }
1475
1476 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1477 /// away to fit in its displacement field.
1478 bool ARMConstantIslands::FixUpImmediateBr(ImmBranch &Br) {
1479   MachineInstr *MI = Br.MI;
1480   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1481
1482   // Check to see if the DestBB is already in-range.
1483   if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1484     return false;
1485
1486   if (!Br.isCond)
1487     return FixUpUnconditionalBr(Br);
1488   return FixUpConditionalBr(Br);
1489 }
1490
1491 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1492 /// too far away to fit in its displacement field. If the LR register has been
1493 /// spilled in the epilogue, then we can use BL to implement a far jump.
1494 /// Otherwise, add an intermediate branch instruction to a branch.
1495 bool
1496 ARMConstantIslands::FixUpUnconditionalBr(ImmBranch &Br) {
1497   MachineInstr *MI = Br.MI;
1498   MachineBasicBlock *MBB = MI->getParent();
1499   if (!isThumb1)
1500     llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
1501
1502   // Use BL to implement far jump.
1503   Br.MaxDisp = (1 << 21) * 2;
1504   MI->setDesc(TII->get(ARM::tBfar));
1505   BBInfo[MBB->getNumber()].Size += 2;
1506   AdjustBBOffsetsAfter(MBB);
1507   HasFarJump = true;
1508   ++NumUBrFixed;
1509
1510   DEBUG(dbgs() << "  Changed B to long jump " << *MI);
1511
1512   return true;
1513 }
1514
1515 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1516 /// far away to fit in its displacement field. It is converted to an inverse
1517 /// conditional branch + an unconditional branch to the destination.
1518 bool
1519 ARMConstantIslands::FixUpConditionalBr(ImmBranch &Br) {
1520   MachineInstr *MI = Br.MI;
1521   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1522
1523   // Add an unconditional branch to the destination and invert the branch
1524   // condition to jump over it:
1525   // blt L1
1526   // =>
1527   // bge L2
1528   // b   L1
1529   // L2:
1530   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1531   CC = ARMCC::getOppositeCondition(CC);
1532   unsigned CCReg = MI->getOperand(2).getReg();
1533
1534   // If the branch is at the end of its MBB and that has a fall-through block,
1535   // direct the updated conditional branch to the fall-through block. Otherwise,
1536   // split the MBB before the next instruction.
1537   MachineBasicBlock *MBB = MI->getParent();
1538   MachineInstr *BMI = &MBB->back();
1539   bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1540
1541   ++NumCBrFixed;
1542   if (BMI != MI) {
1543     if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1544         BMI->getOpcode() == Br.UncondBr) {
1545       // Last MI in the BB is an unconditional branch. Can we simply invert the
1546       // condition and swap destinations:
1547       // beq L1
1548       // b   L2
1549       // =>
1550       // bne L2
1551       // b   L1
1552       MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1553       if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1554         DEBUG(dbgs() << "  Invert Bcc condition and swap its destination with "
1555                      << *BMI);
1556         BMI->getOperand(0).setMBB(DestBB);
1557         MI->getOperand(0).setMBB(NewDest);
1558         MI->getOperand(1).setImm(CC);
1559         return true;
1560       }
1561     }
1562   }
1563
1564   if (NeedSplit) {
1565     SplitBlockBeforeInstr(MI);
1566     // No need for the branch to the next block. We're adding an unconditional
1567     // branch to the destination.
1568     int delta = TII->GetInstSizeInBytes(&MBB->back());
1569     BBInfo[MBB->getNumber()].Size -= delta;
1570     MBB->back().eraseFromParent();
1571     // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1572   }
1573   MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1574
1575   DEBUG(dbgs() << "  Insert B to BB#" << DestBB->getNumber()
1576                << " also invert condition and change dest. to BB#"
1577                << NextBB->getNumber() << "\n");
1578
1579   // Insert a new conditional branch and a new unconditional branch.
1580   // Also update the ImmBranch as well as adding a new entry for the new branch.
1581   BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1582     .addMBB(NextBB).addImm(CC).addReg(CCReg);
1583   Br.MI = &MBB->back();
1584   BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1585   if (isThumb)
1586     BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1587             .addImm(ARMCC::AL).addReg(0);
1588   else
1589     BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1590   BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1591   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1592   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1593
1594   // Remove the old conditional branch.  It may or may not still be in MBB.
1595   BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1596   MI->eraseFromParent();
1597   AdjustBBOffsetsAfter(MBB);
1598   return true;
1599 }
1600
1601 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1602 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1603 /// to do this if tBfar is not used.
1604 bool ARMConstantIslands::UndoLRSpillRestore() {
1605   bool MadeChange = false;
1606   for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1607     MachineInstr *MI = PushPopMIs[i];
1608     // First two operands are predicates.
1609     if (MI->getOpcode() == ARM::tPOP_RET &&
1610         MI->getOperand(2).getReg() == ARM::PC &&
1611         MI->getNumExplicitOperands() == 3) {
1612       // Create the new insn and copy the predicate from the old.
1613       BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1614         .addOperand(MI->getOperand(0))
1615         .addOperand(MI->getOperand(1));
1616       MI->eraseFromParent();
1617       MadeChange = true;
1618     }
1619   }
1620   return MadeChange;
1621 }
1622
1623 bool ARMConstantIslands::OptimizeThumb2Instructions() {
1624   bool MadeChange = false;
1625
1626   // Shrink ADR and LDR from constantpool.
1627   for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1628     CPUser &U = CPUsers[i];
1629     unsigned Opcode = U.MI->getOpcode();
1630     unsigned NewOpc = 0;
1631     unsigned Scale = 1;
1632     unsigned Bits = 0;
1633     switch (Opcode) {
1634     default: break;
1635     case ARM::t2LEApcrel:
1636       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1637         NewOpc = ARM::tLEApcrel;
1638         Bits = 8;
1639         Scale = 4;
1640       }
1641       break;
1642     case ARM::t2LDRpci:
1643       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1644         NewOpc = ARM::tLDRpci;
1645         Bits = 8;
1646         Scale = 4;
1647       }
1648       break;
1649     }
1650
1651     if (!NewOpc)
1652       continue;
1653
1654     unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1655     unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1656     // FIXME: Check if offset is multiple of scale if scale is not 4.
1657     if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1658       U.MI->setDesc(TII->get(NewOpc));
1659       MachineBasicBlock *MBB = U.MI->getParent();
1660       BBInfo[MBB->getNumber()].Size -= 2;
1661       AdjustBBOffsetsAfter(MBB);
1662       ++NumT2CPShrunk;
1663       MadeChange = true;
1664     }
1665   }
1666
1667   MadeChange |= OptimizeThumb2Branches();
1668   MadeChange |= OptimizeThumb2JumpTables();
1669   return MadeChange;
1670 }
1671
1672 bool ARMConstantIslands::OptimizeThumb2Branches() {
1673   bool MadeChange = false;
1674
1675   for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1676     ImmBranch &Br = ImmBranches[i];
1677     unsigned Opcode = Br.MI->getOpcode();
1678     unsigned NewOpc = 0;
1679     unsigned Scale = 1;
1680     unsigned Bits = 0;
1681     switch (Opcode) {
1682     default: break;
1683     case ARM::t2B:
1684       NewOpc = ARM::tB;
1685       Bits = 11;
1686       Scale = 2;
1687       break;
1688     case ARM::t2Bcc: {
1689       NewOpc = ARM::tBcc;
1690       Bits = 8;
1691       Scale = 2;
1692       break;
1693     }
1694     }
1695     if (NewOpc) {
1696       unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1697       MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1698       if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1699         Br.MI->setDesc(TII->get(NewOpc));
1700         MachineBasicBlock *MBB = Br.MI->getParent();
1701         BBInfo[MBB->getNumber()].Size -= 2;
1702         AdjustBBOffsetsAfter(MBB);
1703         ++NumT2BrShrunk;
1704         MadeChange = true;
1705       }
1706     }
1707
1708     Opcode = Br.MI->getOpcode();
1709     if (Opcode != ARM::tBcc)
1710       continue;
1711
1712     NewOpc = 0;
1713     unsigned PredReg = 0;
1714     ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1715     if (Pred == ARMCC::EQ)
1716       NewOpc = ARM::tCBZ;
1717     else if (Pred == ARMCC::NE)
1718       NewOpc = ARM::tCBNZ;
1719     if (!NewOpc)
1720       continue;
1721     MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1722     // Check if the distance is within 126. Subtract starting offset by 2
1723     // because the cmp will be eliminated.
1724     unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1725     unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1726     if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1727       MachineBasicBlock::iterator CmpMI = Br.MI;
1728       if (CmpMI != Br.MI->getParent()->begin()) {
1729         --CmpMI;
1730         if (CmpMI->getOpcode() == ARM::tCMPi8) {
1731           unsigned Reg = CmpMI->getOperand(0).getReg();
1732           Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1733           if (Pred == ARMCC::AL &&
1734               CmpMI->getOperand(1).getImm() == 0 &&
1735               isARMLowRegister(Reg)) {
1736             MachineBasicBlock *MBB = Br.MI->getParent();
1737             MachineInstr *NewBR =
1738               BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1739               .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1740             CmpMI->eraseFromParent();
1741             Br.MI->eraseFromParent();
1742             Br.MI = NewBR;
1743             BBInfo[MBB->getNumber()].Size -= 2;
1744             AdjustBBOffsetsAfter(MBB);
1745             ++NumCBZ;
1746             MadeChange = true;
1747           }
1748         }
1749       }
1750     }
1751   }
1752
1753   return MadeChange;
1754 }
1755
1756 /// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1757 /// jumptables when it's possible.
1758 bool ARMConstantIslands::OptimizeThumb2JumpTables() {
1759   bool MadeChange = false;
1760
1761   // FIXME: After the tables are shrunk, can we get rid some of the
1762   // constantpool tables?
1763   MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1764   if (MJTI == 0) return false;
1765
1766   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1767   for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1768     MachineInstr *MI = T2JumpTables[i];
1769     const MCInstrDesc &MCID = MI->getDesc();
1770     unsigned NumOps = MCID.getNumOperands();
1771     unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1772     MachineOperand JTOP = MI->getOperand(JTOpIdx);
1773     unsigned JTI = JTOP.getIndex();
1774     assert(JTI < JT.size());
1775
1776     bool ByteOk = true;
1777     bool HalfWordOk = true;
1778     unsigned JTOffset = GetOffsetOf(MI) + 4;
1779     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1780     for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1781       MachineBasicBlock *MBB = JTBBs[j];
1782       unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
1783       // Negative offset is not ok. FIXME: We should change BB layout to make
1784       // sure all the branches are forward.
1785       if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1786         ByteOk = false;
1787       unsigned TBHLimit = ((1<<16)-1)*2;
1788       if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1789         HalfWordOk = false;
1790       if (!ByteOk && !HalfWordOk)
1791         break;
1792     }
1793
1794     if (ByteOk || HalfWordOk) {
1795       MachineBasicBlock *MBB = MI->getParent();
1796       unsigned BaseReg = MI->getOperand(0).getReg();
1797       bool BaseRegKill = MI->getOperand(0).isKill();
1798       if (!BaseRegKill)
1799         continue;
1800       unsigned IdxReg = MI->getOperand(1).getReg();
1801       bool IdxRegKill = MI->getOperand(1).isKill();
1802
1803       // Scan backwards to find the instruction that defines the base
1804       // register. Due to post-RA scheduling, we can't count on it
1805       // immediately preceding the branch instruction.
1806       MachineBasicBlock::iterator PrevI = MI;
1807       MachineBasicBlock::iterator B = MBB->begin();
1808       while (PrevI != B && !PrevI->definesRegister(BaseReg))
1809         --PrevI;
1810
1811       // If for some reason we didn't find it, we can't do anything, so
1812       // just skip this one.
1813       if (!PrevI->definesRegister(BaseReg))
1814         continue;
1815
1816       MachineInstr *AddrMI = PrevI;
1817       bool OptOk = true;
1818       // Examine the instruction that calculates the jumptable entry address.
1819       // Make sure it only defines the base register and kills any uses
1820       // other than the index register.
1821       for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1822         const MachineOperand &MO = AddrMI->getOperand(k);
1823         if (!MO.isReg() || !MO.getReg())
1824           continue;
1825         if (MO.isDef() && MO.getReg() != BaseReg) {
1826           OptOk = false;
1827           break;
1828         }
1829         if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1830           OptOk = false;
1831           break;
1832         }
1833       }
1834       if (!OptOk)
1835         continue;
1836
1837       // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1838       // that gave us the initial base register definition.
1839       for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1840         ;
1841
1842       // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
1843       // to delete it as well.
1844       MachineInstr *LeaMI = PrevI;
1845       if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1846            LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1847           LeaMI->getOperand(0).getReg() != BaseReg)
1848         OptOk = false;
1849
1850       if (!OptOk)
1851         continue;
1852
1853       unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
1854       MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1855         .addReg(IdxReg, getKillRegState(IdxRegKill))
1856         .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1857         .addImm(MI->getOperand(JTOpIdx+1).getImm());
1858       // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1859       // is 2-byte aligned. For now, asm printer will fix it up.
1860       unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1861       unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1862       OrigSize += TII->GetInstSizeInBytes(LeaMI);
1863       OrigSize += TII->GetInstSizeInBytes(MI);
1864
1865       AddrMI->eraseFromParent();
1866       LeaMI->eraseFromParent();
1867       MI->eraseFromParent();
1868
1869       int delta = OrigSize - NewSize;
1870       BBInfo[MBB->getNumber()].Size -= delta;
1871       AdjustBBOffsetsAfter(MBB);
1872
1873       ++NumTBs;
1874       MadeChange = true;
1875     }
1876   }
1877
1878   return MadeChange;
1879 }
1880
1881 /// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1882 /// jump tables always branch forwards, since that's what tbb and tbh need.
1883 bool ARMConstantIslands::ReorderThumb2JumpTables() {
1884   bool MadeChange = false;
1885
1886   MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1887   if (MJTI == 0) return false;
1888
1889   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1890   for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1891     MachineInstr *MI = T2JumpTables[i];
1892     const MCInstrDesc &MCID = MI->getDesc();
1893     unsigned NumOps = MCID.getNumOperands();
1894     unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1895     MachineOperand JTOP = MI->getOperand(JTOpIdx);
1896     unsigned JTI = JTOP.getIndex();
1897     assert(JTI < JT.size());
1898
1899     // We prefer if target blocks for the jump table come after the jump
1900     // instruction so we can use TB[BH]. Loop through the target blocks
1901     // and try to adjust them such that that's true.
1902     int JTNumber = MI->getParent()->getNumber();
1903     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1904     for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1905       MachineBasicBlock *MBB = JTBBs[j];
1906       int DTNumber = MBB->getNumber();
1907
1908       if (DTNumber < JTNumber) {
1909         // The destination precedes the switch. Try to move the block forward
1910         // so we have a positive offset.
1911         MachineBasicBlock *NewBB =
1912           AdjustJTTargetBlockForward(MBB, MI->getParent());
1913         if (NewBB)
1914           MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
1915         MadeChange = true;
1916       }
1917     }
1918   }
1919
1920   return MadeChange;
1921 }
1922
1923 MachineBasicBlock *ARMConstantIslands::
1924 AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1925 {
1926   // If the destination block is terminated by an unconditional branch,
1927   // try to move it; otherwise, create a new block following the jump
1928   // table that branches back to the actual target. This is a very simple
1929   // heuristic. FIXME: We can definitely improve it.
1930   MachineBasicBlock *TBB = 0, *FBB = 0;
1931   SmallVector<MachineOperand, 4> Cond;
1932   SmallVector<MachineOperand, 4> CondPrior;
1933   MachineFunction::iterator BBi = BB;
1934   MachineFunction::iterator OldPrior = prior(BBi);
1935
1936   // If the block terminator isn't analyzable, don't try to move the block
1937   bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
1938
1939   // If the block ends in an unconditional branch, move it. The prior block
1940   // has to have an analyzable terminator for us to move this one. Be paranoid
1941   // and make sure we're not trying to move the entry block of the function.
1942   if (!B && Cond.empty() && BB != MF->begin() &&
1943       !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
1944     BB->moveAfter(JTBB);
1945     OldPrior->updateTerminator();
1946     BB->updateTerminator();
1947     // Update numbering to account for the block being moved.
1948     MF->RenumberBlocks();
1949     ++NumJTMoved;
1950     return NULL;
1951   }
1952
1953   // Create a new MBB for the code after the jump BB.
1954   MachineBasicBlock *NewBB =
1955     MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
1956   MachineFunction::iterator MBBI = JTBB; ++MBBI;
1957   MF->insert(MBBI, NewBB);
1958
1959   // Add an unconditional branch from NewBB to BB.
1960   // There doesn't seem to be meaningful DebugInfo available; this doesn't
1961   // correspond directly to anything in the source.
1962   assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
1963   BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
1964           .addImm(ARMCC::AL).addReg(0);
1965
1966   // Update internal data structures to account for the newly inserted MBB.
1967   MF->RenumberBlocks(NewBB);
1968
1969   // Update the CFG.
1970   NewBB->addSuccessor(BB);
1971   JTBB->removeSuccessor(BB);
1972   JTBB->addSuccessor(NewBB);
1973
1974   ++NumJTInserted;
1975   return NewBB;
1976 }