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