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