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