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