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