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