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