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