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