xref: /freebsd/contrib/llvm-project/llvm/lib/Target/ARM/ARMConstantIslandPass.cpp (revision 480093f4440d54b30b3025afeac24b48f2ba7a2e)
10b57cec5SDimitry Andric //===- ARMConstantIslandPass.cpp - ARM constant islands -------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file contains a pass that splits the constant pool up into 'islands'
100b57cec5SDimitry Andric // which are scattered through-out the function.  This is required due to the
110b57cec5SDimitry Andric // limited pc-relative displacements that ARM has.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "ARM.h"
160b57cec5SDimitry Andric #include "ARMBaseInstrInfo.h"
170b57cec5SDimitry Andric #include "ARMBasicBlockInfo.h"
180b57cec5SDimitry Andric #include "ARMMachineFunctionInfo.h"
190b57cec5SDimitry Andric #include "ARMSubtarget.h"
200b57cec5SDimitry Andric #include "MCTargetDesc/ARMBaseInfo.h"
210b57cec5SDimitry Andric #include "Thumb2InstrInfo.h"
220b57cec5SDimitry Andric #include "Utils/ARMBaseInfo.h"
230b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
240b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
250b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
260b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
270b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
280b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
298bcb0991SDimitry Andric #include "llvm/CodeGen/LivePhysRegs.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/MachineConstantPool.h"
328bcb0991SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/MachineJumpTableInfo.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
390b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
400b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
410b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
420b57cec5SDimitry Andric #include "llvm/MC/MCInstrDesc.h"
430b57cec5SDimitry Andric #include "llvm/Pass.h"
440b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
450b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
460b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
470b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
480b57cec5SDimitry Andric #include "llvm/Support/Format.h"
490b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
500b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
510b57cec5SDimitry Andric #include <algorithm>
520b57cec5SDimitry Andric #include <cassert>
530b57cec5SDimitry Andric #include <cstdint>
540b57cec5SDimitry Andric #include <iterator>
550b57cec5SDimitry Andric #include <utility>
560b57cec5SDimitry Andric #include <vector>
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric using namespace llvm;
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric #define DEBUG_TYPE "arm-cp-islands"
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric #define ARM_CP_ISLANDS_OPT_NAME \
630b57cec5SDimitry Andric   "ARM constant island placement and branch shortening pass"
640b57cec5SDimitry Andric STATISTIC(NumCPEs,       "Number of constpool entries");
650b57cec5SDimitry Andric STATISTIC(NumSplit,      "Number of uncond branches inserted");
660b57cec5SDimitry Andric STATISTIC(NumCBrFixed,   "Number of cond branches fixed");
670b57cec5SDimitry Andric STATISTIC(NumUBrFixed,   "Number of uncond branches fixed");
680b57cec5SDimitry Andric STATISTIC(NumTBs,        "Number of table branches generated");
690b57cec5SDimitry Andric STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
700b57cec5SDimitry Andric STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
710b57cec5SDimitry Andric STATISTIC(NumCBZ,        "Number of CBZ / CBNZ formed");
720b57cec5SDimitry Andric STATISTIC(NumJTMoved,    "Number of jump table destination blocks moved");
730b57cec5SDimitry Andric STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
748bcb0991SDimitry Andric STATISTIC(NumLEInserted, "Number of LE backwards branches inserted");
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric static cl::opt<bool>
770b57cec5SDimitry Andric AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
780b57cec5SDimitry Andric           cl::desc("Adjust basic block layout to better use TB[BH]"));
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric static cl::opt<unsigned>
810b57cec5SDimitry Andric CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden, cl::init(30),
820b57cec5SDimitry Andric           cl::desc("The max number of iteration for converge"));
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric static cl::opt<bool> SynthesizeThumb1TBB(
850b57cec5SDimitry Andric     "arm-synthesize-thumb-1-tbb", cl::Hidden, cl::init(true),
860b57cec5SDimitry Andric     cl::desc("Use compressed jump tables in Thumb-1 by synthesizing an "
870b57cec5SDimitry Andric              "equivalent to the TBB/TBH instructions"));
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric namespace {
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric   /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
920b57cec5SDimitry Andric   /// requires constant pool entries to be scattered among the instructions
930b57cec5SDimitry Andric   /// inside a function.  To do this, it completely ignores the normal LLVM
940b57cec5SDimitry Andric   /// constant pool; instead, it places constants wherever it feels like with
950b57cec5SDimitry Andric   /// special instructions.
960b57cec5SDimitry Andric   ///
970b57cec5SDimitry Andric   /// The terminology used in this pass includes:
980b57cec5SDimitry Andric   ///   Islands - Clumps of constants placed in the function.
990b57cec5SDimitry Andric   ///   Water   - Potential places where an island could be formed.
1000b57cec5SDimitry Andric   ///   CPE     - A constant pool entry that has been placed somewhere, which
1010b57cec5SDimitry Andric   ///             tracks a list of users.
1020b57cec5SDimitry Andric   class ARMConstantIslands : public MachineFunctionPass {
1030b57cec5SDimitry Andric     std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric     /// WaterList - A sorted list of basic blocks where islands could be placed
1060b57cec5SDimitry Andric     /// (i.e. blocks that don't fall through to the following block, due
1070b57cec5SDimitry Andric     /// to a return, unreachable, or unconditional branch).
1080b57cec5SDimitry Andric     std::vector<MachineBasicBlock*> WaterList;
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric     /// NewWaterList - The subset of WaterList that was created since the
1110b57cec5SDimitry Andric     /// previous iteration by inserting unconditional branches.
1120b57cec5SDimitry Andric     SmallSet<MachineBasicBlock*, 4> NewWaterList;
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric     using water_iterator = std::vector<MachineBasicBlock *>::iterator;
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric     /// CPUser - One user of a constant pool, keeping the machine instruction
1170b57cec5SDimitry Andric     /// pointer, the constant pool being referenced, and the max displacement
1180b57cec5SDimitry Andric     /// allowed from the instruction to the CP.  The HighWaterMark records the
1190b57cec5SDimitry Andric     /// highest basic block where a new CPEntry can be placed.  To ensure this
1200b57cec5SDimitry Andric     /// pass terminates, the CP entries are initially placed at the end of the
1210b57cec5SDimitry Andric     /// function and then move monotonically to lower addresses.  The
1220b57cec5SDimitry Andric     /// exception to this rule is when the current CP entry for a particular
1230b57cec5SDimitry Andric     /// CPUser is out of range, but there is another CP entry for the same
1240b57cec5SDimitry Andric     /// constant value in range.  We want to use the existing in-range CP
1250b57cec5SDimitry Andric     /// entry, but if it later moves out of range, the search for new water
1260b57cec5SDimitry Andric     /// should resume where it left off.  The HighWaterMark is used to record
1270b57cec5SDimitry Andric     /// that point.
1280b57cec5SDimitry Andric     struct CPUser {
1290b57cec5SDimitry Andric       MachineInstr *MI;
1300b57cec5SDimitry Andric       MachineInstr *CPEMI;
1310b57cec5SDimitry Andric       MachineBasicBlock *HighWaterMark;
1320b57cec5SDimitry Andric       unsigned MaxDisp;
1330b57cec5SDimitry Andric       bool NegOk;
1340b57cec5SDimitry Andric       bool IsSoImm;
1350b57cec5SDimitry Andric       bool KnownAlignment = false;
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric       CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
1380b57cec5SDimitry Andric              bool neg, bool soimm)
1390b57cec5SDimitry Andric         : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
1400b57cec5SDimitry Andric         HighWaterMark = CPEMI->getParent();
1410b57cec5SDimitry Andric       }
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric       /// getMaxDisp - Returns the maximum displacement supported by MI.
1440b57cec5SDimitry Andric       /// Correct for unknown alignment.
1450b57cec5SDimitry Andric       /// Conservatively subtract 2 bytes to handle weird alignment effects.
1460b57cec5SDimitry Andric       unsigned getMaxDisp() const {
1470b57cec5SDimitry Andric         return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
1480b57cec5SDimitry Andric       }
1490b57cec5SDimitry Andric     };
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric     /// CPUsers - Keep track of all of the machine instructions that use various
1520b57cec5SDimitry Andric     /// constant pools and their max displacement.
1530b57cec5SDimitry Andric     std::vector<CPUser> CPUsers;
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric     /// CPEntry - One per constant pool entry, keeping the machine instruction
1560b57cec5SDimitry Andric     /// pointer, the constpool index, and the number of CPUser's which
1570b57cec5SDimitry Andric     /// reference this entry.
1580b57cec5SDimitry Andric     struct CPEntry {
1590b57cec5SDimitry Andric       MachineInstr *CPEMI;
1600b57cec5SDimitry Andric       unsigned CPI;
1610b57cec5SDimitry Andric       unsigned RefCount;
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric       CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
1640b57cec5SDimitry Andric         : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
1650b57cec5SDimitry Andric     };
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric     /// CPEntries - Keep track of all of the constant pool entry machine
1680b57cec5SDimitry Andric     /// instructions. For each original constpool index (i.e. those that existed
1690b57cec5SDimitry Andric     /// upon entry to this pass), it keeps a vector of entries.  Original
1700b57cec5SDimitry Andric     /// elements are cloned as we go along; the clones are put in the vector of
1710b57cec5SDimitry Andric     /// the original element, but have distinct CPIs.
1720b57cec5SDimitry Andric     ///
1730b57cec5SDimitry Andric     /// The first half of CPEntries contains generic constants, the second half
1740b57cec5SDimitry Andric     /// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up
1750b57cec5SDimitry Andric     /// which vector it will be in here.
1760b57cec5SDimitry Andric     std::vector<std::vector<CPEntry>> CPEntries;
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric     /// Maps a JT index to the offset in CPEntries containing copies of that
1790b57cec5SDimitry Andric     /// table. The equivalent map for a CONSTPOOL_ENTRY is the identity.
1800b57cec5SDimitry Andric     DenseMap<int, int> JumpTableEntryIndices;
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric     /// Maps a JT index to the LEA that actually uses the index to calculate its
1830b57cec5SDimitry Andric     /// base address.
1840b57cec5SDimitry Andric     DenseMap<int, int> JumpTableUserIndices;
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric     /// ImmBranch - One per immediate branch, keeping the machine instruction
1870b57cec5SDimitry Andric     /// pointer, conditional or unconditional, the max displacement,
1880b57cec5SDimitry Andric     /// and (if isCond is true) the corresponding unconditional branch
1890b57cec5SDimitry Andric     /// opcode.
1900b57cec5SDimitry Andric     struct ImmBranch {
1910b57cec5SDimitry Andric       MachineInstr *MI;
1920b57cec5SDimitry Andric       unsigned MaxDisp : 31;
1930b57cec5SDimitry Andric       bool isCond : 1;
1940b57cec5SDimitry Andric       unsigned UncondBr;
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric       ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr)
1970b57cec5SDimitry Andric         : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
1980b57cec5SDimitry Andric     };
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric     /// ImmBranches - Keep track of all the immediate branch instructions.
2010b57cec5SDimitry Andric     std::vector<ImmBranch> ImmBranches;
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric     /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
2040b57cec5SDimitry Andric     SmallVector<MachineInstr*, 4> PushPopMIs;
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric     /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
2070b57cec5SDimitry Andric     SmallVector<MachineInstr*, 4> T2JumpTables;
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric     /// HasFarJump - True if any far jump instruction has been emitted during
2100b57cec5SDimitry Andric     /// the branch fix up pass.
2110b57cec5SDimitry Andric     bool HasFarJump;
2120b57cec5SDimitry Andric 
2130b57cec5SDimitry Andric     MachineFunction *MF;
2140b57cec5SDimitry Andric     MachineConstantPool *MCP;
2150b57cec5SDimitry Andric     const ARMBaseInstrInfo *TII;
2160b57cec5SDimitry Andric     const ARMSubtarget *STI;
2170b57cec5SDimitry Andric     ARMFunctionInfo *AFI;
2188bcb0991SDimitry Andric     MachineDominatorTree *DT = nullptr;
2190b57cec5SDimitry Andric     bool isThumb;
2200b57cec5SDimitry Andric     bool isThumb1;
2210b57cec5SDimitry Andric     bool isThumb2;
2220b57cec5SDimitry Andric     bool isPositionIndependentOrROPI;
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric   public:
2250b57cec5SDimitry Andric     static char ID;
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric     ARMConstantIslands() : MachineFunctionPass(ID) {}
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric     bool runOnMachineFunction(MachineFunction &MF) override;
2300b57cec5SDimitry Andric 
2318bcb0991SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
2328bcb0991SDimitry Andric       AU.addRequired<MachineDominatorTree>();
2338bcb0991SDimitry Andric       MachineFunctionPass::getAnalysisUsage(AU);
2348bcb0991SDimitry Andric     }
2358bcb0991SDimitry Andric 
2360b57cec5SDimitry Andric     MachineFunctionProperties getRequiredProperties() const override {
2370b57cec5SDimitry Andric       return MachineFunctionProperties().set(
2380b57cec5SDimitry Andric           MachineFunctionProperties::Property::NoVRegs);
2390b57cec5SDimitry Andric     }
2400b57cec5SDimitry Andric 
2410b57cec5SDimitry Andric     StringRef getPassName() const override {
2420b57cec5SDimitry Andric       return ARM_CP_ISLANDS_OPT_NAME;
2430b57cec5SDimitry Andric     }
2440b57cec5SDimitry Andric 
2450b57cec5SDimitry Andric   private:
2460b57cec5SDimitry Andric     void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);
2470b57cec5SDimitry Andric     void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);
2480b57cec5SDimitry Andric     bool BBHasFallthrough(MachineBasicBlock *MBB);
2490b57cec5SDimitry Andric     CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
2508bcb0991SDimitry Andric     Align getCPEAlign(const MachineInstr *CPEMI);
2510b57cec5SDimitry Andric     void scanFunctionJumpTables();
2520b57cec5SDimitry Andric     void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
2530b57cec5SDimitry Andric     MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
2540b57cec5SDimitry Andric     void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
2550b57cec5SDimitry Andric     bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
2560b57cec5SDimitry Andric     unsigned getCombinedIndex(const MachineInstr *CPEMI);
2570b57cec5SDimitry Andric     int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
2580b57cec5SDimitry Andric     bool findAvailableWater(CPUser&U, unsigned UserOffset,
2590b57cec5SDimitry Andric                             water_iterator &WaterIter, bool CloserWater);
2600b57cec5SDimitry Andric     void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
2610b57cec5SDimitry Andric                         MachineBasicBlock *&NewMBB);
2620b57cec5SDimitry Andric     bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater);
2630b57cec5SDimitry Andric     void removeDeadCPEMI(MachineInstr *CPEMI);
2640b57cec5SDimitry Andric     bool removeUnusedCPEntries();
2650b57cec5SDimitry Andric     bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
2660b57cec5SDimitry Andric                           MachineInstr *CPEMI, unsigned Disp, bool NegOk,
2670b57cec5SDimitry Andric                           bool DoDump = false);
2680b57cec5SDimitry Andric     bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
2690b57cec5SDimitry Andric                         CPUser &U, unsigned &Growth);
2700b57cec5SDimitry Andric     bool fixupImmediateBr(ImmBranch &Br);
2710b57cec5SDimitry Andric     bool fixupConditionalBr(ImmBranch &Br);
2720b57cec5SDimitry Andric     bool fixupUnconditionalBr(ImmBranch &Br);
2730b57cec5SDimitry Andric     bool undoLRSpillRestore();
2740b57cec5SDimitry Andric     bool optimizeThumb2Instructions();
2750b57cec5SDimitry Andric     bool optimizeThumb2Branches();
2760b57cec5SDimitry Andric     bool reorderThumb2JumpTables();
2770b57cec5SDimitry Andric     bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
2780b57cec5SDimitry Andric                               unsigned &DeadSize, bool &CanDeleteLEA,
2790b57cec5SDimitry Andric                               bool &BaseRegKill);
2800b57cec5SDimitry Andric     bool optimizeThumb2JumpTables();
2810b57cec5SDimitry Andric     MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
2820b57cec5SDimitry Andric                                                   MachineBasicBlock *JTBB);
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric     unsigned getUserOffset(CPUser&) const;
2850b57cec5SDimitry Andric     void dumpBBs();
2860b57cec5SDimitry Andric     void verify();
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric     bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
2890b57cec5SDimitry Andric                          unsigned Disp, bool NegativeOK, bool IsSoImm = false);
2900b57cec5SDimitry Andric     bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
2910b57cec5SDimitry Andric                          const CPUser &U) {
2920b57cec5SDimitry Andric       return isOffsetInRange(UserOffset, TrialOffset,
2930b57cec5SDimitry Andric                              U.getMaxDisp(), U.NegOk, U.IsSoImm);
2940b57cec5SDimitry Andric     }
2950b57cec5SDimitry Andric   };
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric } // end anonymous namespace
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric char ARMConstantIslands::ID = 0;
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric /// verify - check BBOffsets, BBSizes, alignment of islands
3020b57cec5SDimitry Andric void ARMConstantIslands::verify() {
3030b57cec5SDimitry Andric #ifndef NDEBUG
3040b57cec5SDimitry Andric   BBInfoVector &BBInfo = BBUtils->getBBInfo();
3050b57cec5SDimitry Andric   assert(std::is_sorted(MF->begin(), MF->end(),
3060b57cec5SDimitry Andric                         [&BBInfo](const MachineBasicBlock &LHS,
3070b57cec5SDimitry Andric                                   const MachineBasicBlock &RHS) {
3080b57cec5SDimitry Andric                           return BBInfo[LHS.getNumber()].postOffset() <
3090b57cec5SDimitry Andric                                  BBInfo[RHS.getNumber()].postOffset();
3100b57cec5SDimitry Andric                         }));
3110b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
3120b57cec5SDimitry Andric   for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
3130b57cec5SDimitry Andric     CPUser &U = CPUsers[i];
3140b57cec5SDimitry Andric     unsigned UserOffset = getUserOffset(U);
3150b57cec5SDimitry Andric     // Verify offset using the real max displacement without the safety
3160b57cec5SDimitry Andric     // adjustment.
3170b57cec5SDimitry Andric     if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
3180b57cec5SDimitry Andric                          /* DoDump = */ true)) {
3190b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "OK\n");
3200b57cec5SDimitry Andric       continue;
3210b57cec5SDimitry Andric     }
3220b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Out of range.\n");
3230b57cec5SDimitry Andric     dumpBBs();
3240b57cec5SDimitry Andric     LLVM_DEBUG(MF->dump());
3250b57cec5SDimitry Andric     llvm_unreachable("Constant pool entry out of range!");
3260b57cec5SDimitry Andric   }
3270b57cec5SDimitry Andric #endif
3280b57cec5SDimitry Andric }
3290b57cec5SDimitry Andric 
3300b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3310b57cec5SDimitry Andric /// print block size and offset information - debugging
3320b57cec5SDimitry Andric LLVM_DUMP_METHOD void ARMConstantIslands::dumpBBs() {
3330b57cec5SDimitry Andric   BBInfoVector &BBInfo = BBUtils->getBBInfo();
3340b57cec5SDimitry Andric   LLVM_DEBUG({
3350b57cec5SDimitry Andric     for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
3360b57cec5SDimitry Andric       const BasicBlockInfo &BBI = BBInfo[J];
3370b57cec5SDimitry Andric       dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)
3380b57cec5SDimitry Andric              << " kb=" << unsigned(BBI.KnownBits)
3398bcb0991SDimitry Andric              << " ua=" << unsigned(BBI.Unalign) << " pa=" << Log2(BBI.PostAlign)
3400b57cec5SDimitry Andric              << format(" size=%#x\n", BBInfo[J].Size);
3410b57cec5SDimitry Andric     }
3420b57cec5SDimitry Andric   });
3430b57cec5SDimitry Andric }
3440b57cec5SDimitry Andric #endif
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
3470b57cec5SDimitry Andric   MF = &mf;
3480b57cec5SDimitry Andric   MCP = mf.getConstantPool();
3490b57cec5SDimitry Andric   BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(mf));
3500b57cec5SDimitry Andric 
3510b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "***** ARMConstantIslands: "
3520b57cec5SDimitry Andric                     << MCP->getConstants().size() << " CP entries, aligned to "
3530b57cec5SDimitry Andric                     << MCP->getConstantPoolAlignment() << " bytes *****\n");
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric   STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget());
3560b57cec5SDimitry Andric   TII = STI->getInstrInfo();
3570b57cec5SDimitry Andric   isPositionIndependentOrROPI =
3580b57cec5SDimitry Andric       STI->getTargetLowering()->isPositionIndependent() || STI->isROPI();
3590b57cec5SDimitry Andric   AFI = MF->getInfo<ARMFunctionInfo>();
3608bcb0991SDimitry Andric   DT = &getAnalysis<MachineDominatorTree>();
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   isThumb = AFI->isThumbFunction();
3630b57cec5SDimitry Andric   isThumb1 = AFI->isThumb1OnlyFunction();
3640b57cec5SDimitry Andric   isThumb2 = AFI->isThumb2Function();
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric   HasFarJump = false;
3670b57cec5SDimitry Andric   bool GenerateTBB = isThumb2 || (isThumb1 && SynthesizeThumb1TBB);
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric   // Renumber all of the machine basic blocks in the function, guaranteeing that
3700b57cec5SDimitry Andric   // the numbers agree with the position of the block in the function.
3710b57cec5SDimitry Andric   MF->RenumberBlocks();
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric   // Try to reorder and otherwise adjust the block layout to make good use
3740b57cec5SDimitry Andric   // of the TB[BH] instructions.
3750b57cec5SDimitry Andric   bool MadeChange = false;
3760b57cec5SDimitry Andric   if (GenerateTBB && AdjustJumpTableBlocks) {
3770b57cec5SDimitry Andric     scanFunctionJumpTables();
3780b57cec5SDimitry Andric     MadeChange |= reorderThumb2JumpTables();
3790b57cec5SDimitry Andric     // Data is out of date, so clear it. It'll be re-computed later.
3800b57cec5SDimitry Andric     T2JumpTables.clear();
3810b57cec5SDimitry Andric     // Blocks may have shifted around. Keep the numbering up to date.
3820b57cec5SDimitry Andric     MF->RenumberBlocks();
3830b57cec5SDimitry Andric   }
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric   // Perform the initial placement of the constant pool entries.  To start with,
3860b57cec5SDimitry Andric   // we put them all at the end of the function.
3870b57cec5SDimitry Andric   std::vector<MachineInstr*> CPEMIs;
3880b57cec5SDimitry Andric   if (!MCP->isEmpty())
3890b57cec5SDimitry Andric     doInitialConstPlacement(CPEMIs);
3900b57cec5SDimitry Andric 
3910b57cec5SDimitry Andric   if (MF->getJumpTableInfo())
3920b57cec5SDimitry Andric     doInitialJumpTablePlacement(CPEMIs);
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric   /// The next UID to take is the first unused one.
3950b57cec5SDimitry Andric   AFI->initPICLabelUId(CPEMIs.size());
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric   // Do the initial scan of the function, building up information about the
3980b57cec5SDimitry Andric   // sizes of each block, the location of all the water, and finding all of the
3990b57cec5SDimitry Andric   // constant pool users.
4000b57cec5SDimitry Andric   initializeFunctionInfo(CPEMIs);
4010b57cec5SDimitry Andric   CPEMIs.clear();
4020b57cec5SDimitry Andric   LLVM_DEBUG(dumpBBs());
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric   // Functions with jump tables need an alignment of 4 because they use the ADR
4050b57cec5SDimitry Andric   // instruction, which aligns the PC to 4 bytes before adding an offset.
4060b57cec5SDimitry Andric   if (!T2JumpTables.empty())
4078bcb0991SDimitry Andric     MF->ensureAlignment(Align(4));
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric   /// Remove dead constant pool entries.
4100b57cec5SDimitry Andric   MadeChange |= removeUnusedCPEntries();
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric   // Iteratively place constant pool entries and fix up branches until there
4130b57cec5SDimitry Andric   // is no change.
4140b57cec5SDimitry Andric   unsigned NoCPIters = 0, NoBRIters = 0;
4150b57cec5SDimitry Andric   while (true) {
4160b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
4170b57cec5SDimitry Andric     bool CPChange = false;
4180b57cec5SDimitry Andric     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
4190b57cec5SDimitry Andric       // For most inputs, it converges in no more than 5 iterations.
4200b57cec5SDimitry Andric       // If it doesn't end in 10, the input may have huge BB or many CPEs.
4210b57cec5SDimitry Andric       // In this case, we will try different heuristics.
4220b57cec5SDimitry Andric       CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2);
4230b57cec5SDimitry Andric     if (CPChange && ++NoCPIters > CPMaxIteration)
4240b57cec5SDimitry Andric       report_fatal_error("Constant Island pass failed to converge!");
4250b57cec5SDimitry Andric     LLVM_DEBUG(dumpBBs());
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric     // Clear NewWaterList now.  If we split a block for branches, it should
4280b57cec5SDimitry Andric     // appear as "new water" for the next iteration of constant pool placement.
4290b57cec5SDimitry Andric     NewWaterList.clear();
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
4320b57cec5SDimitry Andric     bool BRChange = false;
4330b57cec5SDimitry Andric     for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
4340b57cec5SDimitry Andric       BRChange |= fixupImmediateBr(ImmBranches[i]);
4350b57cec5SDimitry Andric     if (BRChange && ++NoBRIters > 30)
4360b57cec5SDimitry Andric       report_fatal_error("Branch Fix Up pass failed to converge!");
4370b57cec5SDimitry Andric     LLVM_DEBUG(dumpBBs());
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric     if (!CPChange && !BRChange)
4400b57cec5SDimitry Andric       break;
4410b57cec5SDimitry Andric     MadeChange = true;
4420b57cec5SDimitry Andric   }
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric   // Shrink 32-bit Thumb2 load and store instructions.
4450b57cec5SDimitry Andric   if (isThumb2 && !STI->prefers32BitThumb())
4460b57cec5SDimitry Andric     MadeChange |= optimizeThumb2Instructions();
4470b57cec5SDimitry Andric 
4480b57cec5SDimitry Andric   // Shrink 32-bit branch instructions.
4490b57cec5SDimitry Andric   if (isThumb && STI->hasV8MBaselineOps())
4500b57cec5SDimitry Andric     MadeChange |= optimizeThumb2Branches();
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric   // Optimize jump tables using TBB / TBH.
4530b57cec5SDimitry Andric   if (GenerateTBB && !STI->genExecuteOnly())
4540b57cec5SDimitry Andric     MadeChange |= optimizeThumb2JumpTables();
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric   // After a while, this might be made debug-only, but it is not expensive.
4570b57cec5SDimitry Andric   verify();
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric   // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
4600b57cec5SDimitry Andric   // undo the spill / restore of LR if possible.
4610b57cec5SDimitry Andric   if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
4620b57cec5SDimitry Andric     MadeChange |= undoLRSpillRestore();
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric   // Save the mapping between original and cloned constpool entries.
4650b57cec5SDimitry Andric   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
4660b57cec5SDimitry Andric     for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
4670b57cec5SDimitry Andric       const CPEntry & CPE = CPEntries[i][j];
4680b57cec5SDimitry Andric       if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())
4690b57cec5SDimitry Andric         AFI->recordCPEClone(i, CPE.CPI);
4700b57cec5SDimitry Andric     }
4710b57cec5SDimitry Andric   }
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric   BBUtils->clear();
4760b57cec5SDimitry Andric   WaterList.clear();
4770b57cec5SDimitry Andric   CPUsers.clear();
4780b57cec5SDimitry Andric   CPEntries.clear();
4790b57cec5SDimitry Andric   JumpTableEntryIndices.clear();
4800b57cec5SDimitry Andric   JumpTableUserIndices.clear();
4810b57cec5SDimitry Andric   ImmBranches.clear();
4820b57cec5SDimitry Andric   PushPopMIs.clear();
4830b57cec5SDimitry Andric   T2JumpTables.clear();
4840b57cec5SDimitry Andric 
4850b57cec5SDimitry Andric   return MadeChange;
4860b57cec5SDimitry Andric }
4870b57cec5SDimitry Andric 
4880b57cec5SDimitry Andric /// Perform the initial placement of the regular constant pool entries.
4890b57cec5SDimitry Andric /// To start with, we put them all at the end of the function.
4900b57cec5SDimitry Andric void
4910b57cec5SDimitry Andric ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
4920b57cec5SDimitry Andric   // Create the basic block to hold the CPE's.
4930b57cec5SDimitry Andric   MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
4940b57cec5SDimitry Andric   MF->push_back(BB);
4950b57cec5SDimitry Andric 
4968bcb0991SDimitry Andric   // MachineConstantPool measures alignment in bytes.
4978bcb0991SDimitry Andric   const Align MaxAlign(MCP->getConstantPoolAlignment());
4988bcb0991SDimitry Andric   const unsigned MaxLogAlign = Log2(MaxAlign);
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric   // Mark the basic block as required by the const-pool.
5010b57cec5SDimitry Andric   BB->setAlignment(MaxAlign);
5020b57cec5SDimitry Andric 
5030b57cec5SDimitry Andric   // The function needs to be as aligned as the basic blocks. The linker may
5040b57cec5SDimitry Andric   // move functions around based on their alignment.
5050b57cec5SDimitry Andric   MF->ensureAlignment(BB->getAlignment());
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric   // Order the entries in BB by descending alignment.  That ensures correct
5080b57cec5SDimitry Andric   // alignment of all entries as long as BB is sufficiently aligned.  Keep
5090b57cec5SDimitry Andric   // track of the insertion point for each alignment.  We are going to bucket
5100b57cec5SDimitry Andric   // sort the entries as they are created.
5118bcb0991SDimitry Andric   SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxLogAlign + 1,
5128bcb0991SDimitry Andric                                                        BB->end());
5130b57cec5SDimitry Andric 
5140b57cec5SDimitry Andric   // Add all of the constants from the constant pool to the end block, use an
5150b57cec5SDimitry Andric   // identity mapping of CPI's to CPE's.
5160b57cec5SDimitry Andric   const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   const DataLayout &TD = MF->getDataLayout();
5190b57cec5SDimitry Andric   for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
5200b57cec5SDimitry Andric     unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
5210b57cec5SDimitry Andric     unsigned Align = CPs[i].getAlignment();
5220b57cec5SDimitry Andric     assert(isPowerOf2_32(Align) && "Invalid alignment");
5230b57cec5SDimitry Andric     // Verify that all constant pool entries are a multiple of their alignment.
5240b57cec5SDimitry Andric     // If not, we would have to pad them out so that instructions stay aligned.
5250b57cec5SDimitry Andric     assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric     // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
5280b57cec5SDimitry Andric     unsigned LogAlign = Log2_32(Align);
5290b57cec5SDimitry Andric     MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
5300b57cec5SDimitry Andric     MachineInstr *CPEMI =
5310b57cec5SDimitry Andric       BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
5320b57cec5SDimitry Andric         .addImm(i).addConstantPoolIndex(i).addImm(Size);
5330b57cec5SDimitry Andric     CPEMIs.push_back(CPEMI);
5340b57cec5SDimitry Andric 
5350b57cec5SDimitry Andric     // Ensure that future entries with higher alignment get inserted before
5360b57cec5SDimitry Andric     // CPEMI. This is bucket sort with iterators.
5378bcb0991SDimitry Andric     for (unsigned a = LogAlign + 1; a <= MaxLogAlign; ++a)
5380b57cec5SDimitry Andric       if (InsPoint[a] == InsAt)
5390b57cec5SDimitry Andric         InsPoint[a] = CPEMI;
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric     // Add a new CPEntry, but no corresponding CPUser yet.
5420b57cec5SDimitry Andric     CPEntries.emplace_back(1, CPEntry(CPEMI, i));
5430b57cec5SDimitry Andric     ++NumCPEs;
5440b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
5450b57cec5SDimitry Andric                       << Size << ", align = " << Align << '\n');
5460b57cec5SDimitry Andric   }
5470b57cec5SDimitry Andric   LLVM_DEBUG(BB->dump());
5480b57cec5SDimitry Andric }
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric /// Do initial placement of the jump tables. Because Thumb2's TBB and TBH
5510b57cec5SDimitry Andric /// instructions can be made more efficient if the jump table immediately
5520b57cec5SDimitry Andric /// follows the instruction, it's best to place them immediately next to their
5530b57cec5SDimitry Andric /// jumps to begin with. In almost all cases they'll never be moved from that
5540b57cec5SDimitry Andric /// position.
5550b57cec5SDimitry Andric void ARMConstantIslands::doInitialJumpTablePlacement(
5560b57cec5SDimitry Andric     std::vector<MachineInstr *> &CPEMIs) {
5570b57cec5SDimitry Andric   unsigned i = CPEntries.size();
5580b57cec5SDimitry Andric   auto MJTI = MF->getJumpTableInfo();
5590b57cec5SDimitry Andric   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
5600b57cec5SDimitry Andric 
5610b57cec5SDimitry Andric   MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
5620b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : *MF) {
5630b57cec5SDimitry Andric     auto MI = MBB.getLastNonDebugInstr();
5640b57cec5SDimitry Andric     if (MI == MBB.end())
5650b57cec5SDimitry Andric       continue;
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric     unsigned JTOpcode;
5680b57cec5SDimitry Andric     switch (MI->getOpcode()) {
5690b57cec5SDimitry Andric     default:
5700b57cec5SDimitry Andric       continue;
5710b57cec5SDimitry Andric     case ARM::BR_JTadd:
5720b57cec5SDimitry Andric     case ARM::BR_JTr:
5730b57cec5SDimitry Andric     case ARM::tBR_JTr:
5740b57cec5SDimitry Andric     case ARM::BR_JTm_i12:
5750b57cec5SDimitry Andric     case ARM::BR_JTm_rs:
5760b57cec5SDimitry Andric       JTOpcode = ARM::JUMPTABLE_ADDRS;
5770b57cec5SDimitry Andric       break;
5780b57cec5SDimitry Andric     case ARM::t2BR_JT:
5790b57cec5SDimitry Andric       JTOpcode = ARM::JUMPTABLE_INSTS;
5800b57cec5SDimitry Andric       break;
5810b57cec5SDimitry Andric     case ARM::tTBB_JT:
5820b57cec5SDimitry Andric     case ARM::t2TBB_JT:
5830b57cec5SDimitry Andric       JTOpcode = ARM::JUMPTABLE_TBB;
5840b57cec5SDimitry Andric       break;
5850b57cec5SDimitry Andric     case ARM::tTBH_JT:
5860b57cec5SDimitry Andric     case ARM::t2TBH_JT:
5870b57cec5SDimitry Andric       JTOpcode = ARM::JUMPTABLE_TBH;
5880b57cec5SDimitry Andric       break;
5890b57cec5SDimitry Andric     }
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric     unsigned NumOps = MI->getDesc().getNumOperands();
5920b57cec5SDimitry Andric     MachineOperand JTOp =
5930b57cec5SDimitry Andric       MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1));
5940b57cec5SDimitry Andric     unsigned JTI = JTOp.getIndex();
5950b57cec5SDimitry Andric     unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t);
5960b57cec5SDimitry Andric     MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock();
5970b57cec5SDimitry Andric     MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB);
5980b57cec5SDimitry Andric     MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(),
5990b57cec5SDimitry Andric                                   DebugLoc(), TII->get(JTOpcode))
6000b57cec5SDimitry Andric                               .addImm(i++)
6010b57cec5SDimitry Andric                               .addJumpTableIndex(JTI)
6020b57cec5SDimitry Andric                               .addImm(Size);
6030b57cec5SDimitry Andric     CPEMIs.push_back(CPEMI);
6040b57cec5SDimitry Andric     CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));
6050b57cec5SDimitry Andric     JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));
6060b57cec5SDimitry Andric     if (!LastCorrectlyNumberedBB)
6070b57cec5SDimitry Andric       LastCorrectlyNumberedBB = &MBB;
6080b57cec5SDimitry Andric   }
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric   // If we did anything then we need to renumber the subsequent blocks.
6110b57cec5SDimitry Andric   if (LastCorrectlyNumberedBB)
6120b57cec5SDimitry Andric     MF->RenumberBlocks(LastCorrectlyNumberedBB);
6130b57cec5SDimitry Andric }
6140b57cec5SDimitry Andric 
6150b57cec5SDimitry Andric /// BBHasFallthrough - Return true if the specified basic block can fallthrough
6160b57cec5SDimitry Andric /// into the block immediately after it.
6170b57cec5SDimitry Andric bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
6180b57cec5SDimitry Andric   // Get the next machine basic block in the function.
6190b57cec5SDimitry Andric   MachineFunction::iterator MBBI = MBB->getIterator();
6200b57cec5SDimitry Andric   // Can't fall off end of function.
6210b57cec5SDimitry Andric   if (std::next(MBBI) == MBB->getParent()->end())
6220b57cec5SDimitry Andric     return false;
6230b57cec5SDimitry Andric 
6240b57cec5SDimitry Andric   MachineBasicBlock *NextBB = &*std::next(MBBI);
6250b57cec5SDimitry Andric   if (!MBB->isSuccessor(NextBB))
6260b57cec5SDimitry Andric     return false;
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric   // Try to analyze the end of the block. A potential fallthrough may already
6290b57cec5SDimitry Andric   // have an unconditional branch for whatever reason.
6300b57cec5SDimitry Andric   MachineBasicBlock *TBB, *FBB;
6310b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
6320b57cec5SDimitry Andric   bool TooDifficult = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
6330b57cec5SDimitry Andric   return TooDifficult || FBB == nullptr;
6340b57cec5SDimitry Andric }
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
6370b57cec5SDimitry Andric /// look up the corresponding CPEntry.
6380b57cec5SDimitry Andric ARMConstantIslands::CPEntry *
6390b57cec5SDimitry Andric ARMConstantIslands::findConstPoolEntry(unsigned CPI,
6400b57cec5SDimitry Andric                                        const MachineInstr *CPEMI) {
6410b57cec5SDimitry Andric   std::vector<CPEntry> &CPEs = CPEntries[CPI];
6420b57cec5SDimitry Andric   // Number of entries per constpool index should be small, just do a
6430b57cec5SDimitry Andric   // linear search.
6440b57cec5SDimitry Andric   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
6450b57cec5SDimitry Andric     if (CPEs[i].CPEMI == CPEMI)
6460b57cec5SDimitry Andric       return &CPEs[i];
6470b57cec5SDimitry Andric   }
6480b57cec5SDimitry Andric   return nullptr;
6490b57cec5SDimitry Andric }
6500b57cec5SDimitry Andric 
6518bcb0991SDimitry Andric /// getCPEAlign - Returns the required alignment of the constant pool entry
6528bcb0991SDimitry Andric /// represented by CPEMI.
6538bcb0991SDimitry Andric Align ARMConstantIslands::getCPEAlign(const MachineInstr *CPEMI) {
6540b57cec5SDimitry Andric   switch (CPEMI->getOpcode()) {
6550b57cec5SDimitry Andric   case ARM::CONSTPOOL_ENTRY:
6560b57cec5SDimitry Andric     break;
6570b57cec5SDimitry Andric   case ARM::JUMPTABLE_TBB:
6588bcb0991SDimitry Andric     return isThumb1 ? Align(4) : Align(1);
6590b57cec5SDimitry Andric   case ARM::JUMPTABLE_TBH:
6608bcb0991SDimitry Andric     return isThumb1 ? Align(4) : Align(2);
6610b57cec5SDimitry Andric   case ARM::JUMPTABLE_INSTS:
6628bcb0991SDimitry Andric     return Align(2);
6630b57cec5SDimitry Andric   case ARM::JUMPTABLE_ADDRS:
6648bcb0991SDimitry Andric     return Align(4);
6650b57cec5SDimitry Andric   default:
6660b57cec5SDimitry Andric     llvm_unreachable("unknown constpool entry kind");
6670b57cec5SDimitry Andric   }
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric   unsigned CPI = getCombinedIndex(CPEMI);
6700b57cec5SDimitry Andric   assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
6718bcb0991SDimitry Andric   return Align(MCP->getConstants()[CPI].getAlignment());
6720b57cec5SDimitry Andric }
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric /// scanFunctionJumpTables - Do a scan of the function, building up
6750b57cec5SDimitry Andric /// information about the sizes of each block and the locations of all
6760b57cec5SDimitry Andric /// the jump tables.
6770b57cec5SDimitry Andric void ARMConstantIslands::scanFunctionJumpTables() {
6780b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : *MF) {
6790b57cec5SDimitry Andric     for (MachineInstr &I : MBB)
6800b57cec5SDimitry Andric       if (I.isBranch() &&
6810b57cec5SDimitry Andric           (I.getOpcode() == ARM::t2BR_JT || I.getOpcode() == ARM::tBR_JTr))
6820b57cec5SDimitry Andric         T2JumpTables.push_back(&I);
6830b57cec5SDimitry Andric   }
6840b57cec5SDimitry Andric }
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric /// initializeFunctionInfo - Do the initial scan of the function, building up
6870b57cec5SDimitry Andric /// information about the sizes of each block, the location of all the water,
6880b57cec5SDimitry Andric /// and finding all of the constant pool users.
6890b57cec5SDimitry Andric void ARMConstantIslands::
6900b57cec5SDimitry Andric initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
6910b57cec5SDimitry Andric 
6920b57cec5SDimitry Andric   BBUtils->computeAllBlockSizes();
6930b57cec5SDimitry Andric   BBInfoVector &BBInfo = BBUtils->getBBInfo();
6940b57cec5SDimitry Andric   // The known bits of the entry block offset are determined by the function
6950b57cec5SDimitry Andric   // alignment.
6968bcb0991SDimitry Andric   BBInfo.front().KnownBits = Log2(MF->getAlignment());
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric   // Compute block offsets and known bits.
6990b57cec5SDimitry Andric   BBUtils->adjustBBOffsetsAfter(&MF->front());
7000b57cec5SDimitry Andric 
7010b57cec5SDimitry Andric   // Now go back through the instructions and build up our data structures.
7020b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : *MF) {
7030b57cec5SDimitry Andric     // If this block doesn't fall through into the next MBB, then this is
7040b57cec5SDimitry Andric     // 'water' that a constant pool island could be placed.
7050b57cec5SDimitry Andric     if (!BBHasFallthrough(&MBB))
7060b57cec5SDimitry Andric       WaterList.push_back(&MBB);
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric     for (MachineInstr &I : MBB) {
7090b57cec5SDimitry Andric       if (I.isDebugInstr())
7100b57cec5SDimitry Andric         continue;
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric       unsigned Opc = I.getOpcode();
7130b57cec5SDimitry Andric       if (I.isBranch()) {
7140b57cec5SDimitry Andric         bool isCond = false;
7150b57cec5SDimitry Andric         unsigned Bits = 0;
7160b57cec5SDimitry Andric         unsigned Scale = 1;
7170b57cec5SDimitry Andric         int UOpc = Opc;
7180b57cec5SDimitry Andric         switch (Opc) {
7190b57cec5SDimitry Andric         default:
7200b57cec5SDimitry Andric           continue;  // Ignore other JT branches
7210b57cec5SDimitry Andric         case ARM::t2BR_JT:
7220b57cec5SDimitry Andric         case ARM::tBR_JTr:
7230b57cec5SDimitry Andric           T2JumpTables.push_back(&I);
7240b57cec5SDimitry Andric           continue;   // Does not get an entry in ImmBranches
7250b57cec5SDimitry Andric         case ARM::Bcc:
7260b57cec5SDimitry Andric           isCond = true;
7270b57cec5SDimitry Andric           UOpc = ARM::B;
7280b57cec5SDimitry Andric           LLVM_FALLTHROUGH;
7290b57cec5SDimitry Andric         case ARM::B:
7300b57cec5SDimitry Andric           Bits = 24;
7310b57cec5SDimitry Andric           Scale = 4;
7320b57cec5SDimitry Andric           break;
7330b57cec5SDimitry Andric         case ARM::tBcc:
7340b57cec5SDimitry Andric           isCond = true;
7350b57cec5SDimitry Andric           UOpc = ARM::tB;
7360b57cec5SDimitry Andric           Bits = 8;
7370b57cec5SDimitry Andric           Scale = 2;
7380b57cec5SDimitry Andric           break;
7390b57cec5SDimitry Andric         case ARM::tB:
7400b57cec5SDimitry Andric           Bits = 11;
7410b57cec5SDimitry Andric           Scale = 2;
7420b57cec5SDimitry Andric           break;
7430b57cec5SDimitry Andric         case ARM::t2Bcc:
7440b57cec5SDimitry Andric           isCond = true;
7450b57cec5SDimitry Andric           UOpc = ARM::t2B;
7460b57cec5SDimitry Andric           Bits = 20;
7470b57cec5SDimitry Andric           Scale = 2;
7480b57cec5SDimitry Andric           break;
7490b57cec5SDimitry Andric         case ARM::t2B:
7500b57cec5SDimitry Andric           Bits = 24;
7510b57cec5SDimitry Andric           Scale = 2;
7520b57cec5SDimitry Andric           break;
7530b57cec5SDimitry Andric         }
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric         // Record this immediate branch.
7560b57cec5SDimitry Andric         unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
7570b57cec5SDimitry Andric         ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc));
7580b57cec5SDimitry Andric       }
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric       if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
7610b57cec5SDimitry Andric         PushPopMIs.push_back(&I);
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric       if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
7640b57cec5SDimitry Andric           Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
7650b57cec5SDimitry Andric           Opc == ARM::JUMPTABLE_TBH)
7660b57cec5SDimitry Andric         continue;
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric       // Scan the instructions for constant pool operands.
7690b57cec5SDimitry Andric       for (unsigned op = 0, e = I.getNumOperands(); op != e; ++op)
7700b57cec5SDimitry Andric         if (I.getOperand(op).isCPI() || I.getOperand(op).isJTI()) {
7710b57cec5SDimitry Andric           // We found one.  The addressing mode tells us the max displacement
7720b57cec5SDimitry Andric           // from the PC that this instruction permits.
7730b57cec5SDimitry Andric 
7740b57cec5SDimitry Andric           // Basic size info comes from the TSFlags field.
7750b57cec5SDimitry Andric           unsigned Bits = 0;
7760b57cec5SDimitry Andric           unsigned Scale = 1;
7770b57cec5SDimitry Andric           bool NegOk = false;
7780b57cec5SDimitry Andric           bool IsSoImm = false;
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric           switch (Opc) {
7810b57cec5SDimitry Andric           default:
7820b57cec5SDimitry Andric             llvm_unreachable("Unknown addressing mode for CP reference!");
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric           // Taking the address of a CP entry.
7850b57cec5SDimitry Andric           case ARM::LEApcrel:
7860b57cec5SDimitry Andric           case ARM::LEApcrelJT:
7870b57cec5SDimitry Andric             // This takes a SoImm, which is 8 bit immediate rotated. We'll
7880b57cec5SDimitry Andric             // pretend the maximum offset is 255 * 4. Since each instruction
7890b57cec5SDimitry Andric             // 4 byte wide, this is always correct. We'll check for other
7900b57cec5SDimitry Andric             // displacements that fits in a SoImm as well.
7910b57cec5SDimitry Andric             Bits = 8;
7920b57cec5SDimitry Andric             Scale = 4;
7930b57cec5SDimitry Andric             NegOk = true;
7940b57cec5SDimitry Andric             IsSoImm = true;
7950b57cec5SDimitry Andric             break;
7960b57cec5SDimitry Andric           case ARM::t2LEApcrel:
7970b57cec5SDimitry Andric           case ARM::t2LEApcrelJT:
7980b57cec5SDimitry Andric             Bits = 12;
7990b57cec5SDimitry Andric             NegOk = true;
8000b57cec5SDimitry Andric             break;
8010b57cec5SDimitry Andric           case ARM::tLEApcrel:
8020b57cec5SDimitry Andric           case ARM::tLEApcrelJT:
8030b57cec5SDimitry Andric             Bits = 8;
8040b57cec5SDimitry Andric             Scale = 4;
8050b57cec5SDimitry Andric             break;
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric           case ARM::LDRBi12:
8080b57cec5SDimitry Andric           case ARM::LDRi12:
8090b57cec5SDimitry Andric           case ARM::LDRcp:
8100b57cec5SDimitry Andric           case ARM::t2LDRpci:
8110b57cec5SDimitry Andric           case ARM::t2LDRHpci:
8120b57cec5SDimitry Andric           case ARM::t2LDRBpci:
8130b57cec5SDimitry Andric             Bits = 12;  // +-offset_12
8140b57cec5SDimitry Andric             NegOk = true;
8150b57cec5SDimitry Andric             break;
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric           case ARM::tLDRpci:
8180b57cec5SDimitry Andric             Bits = 8;
8190b57cec5SDimitry Andric             Scale = 4;  // +(offset_8*4)
8200b57cec5SDimitry Andric             break;
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric           case ARM::VLDRD:
8230b57cec5SDimitry Andric           case ARM::VLDRS:
8240b57cec5SDimitry Andric             Bits = 8;
8250b57cec5SDimitry Andric             Scale = 4;  // +-(offset_8*4)
8260b57cec5SDimitry Andric             NegOk = true;
8270b57cec5SDimitry Andric             break;
8280b57cec5SDimitry Andric           case ARM::VLDRH:
8290b57cec5SDimitry Andric             Bits = 8;
8300b57cec5SDimitry Andric             Scale = 2;  // +-(offset_8*2)
8310b57cec5SDimitry Andric             NegOk = true;
8320b57cec5SDimitry Andric             break;
8330b57cec5SDimitry Andric           }
8340b57cec5SDimitry Andric 
8350b57cec5SDimitry Andric           // Remember that this is a user of a CP entry.
8360b57cec5SDimitry Andric           unsigned CPI = I.getOperand(op).getIndex();
8370b57cec5SDimitry Andric           if (I.getOperand(op).isJTI()) {
8380b57cec5SDimitry Andric             JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
8390b57cec5SDimitry Andric             CPI = JumpTableEntryIndices[CPI];
8400b57cec5SDimitry Andric           }
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric           MachineInstr *CPEMI = CPEMIs[CPI];
8430b57cec5SDimitry Andric           unsigned MaxOffs = ((1 << Bits)-1) * Scale;
8440b57cec5SDimitry Andric           CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm));
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric           // Increment corresponding CPEntry reference count.
8470b57cec5SDimitry Andric           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
8480b57cec5SDimitry Andric           assert(CPE && "Cannot find a corresponding CPEntry!");
8490b57cec5SDimitry Andric           CPE->RefCount++;
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric           // Instructions can only use one CP entry, don't bother scanning the
8520b57cec5SDimitry Andric           // rest of the operands.
8530b57cec5SDimitry Andric           break;
8540b57cec5SDimitry Andric         }
8550b57cec5SDimitry Andric     }
8560b57cec5SDimitry Andric   }
8570b57cec5SDimitry Andric }
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
8600b57cec5SDimitry Andric /// ID.
8610b57cec5SDimitry Andric static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
8620b57cec5SDimitry Andric                               const MachineBasicBlock *RHS) {
8630b57cec5SDimitry Andric   return LHS->getNumber() < RHS->getNumber();
8640b57cec5SDimitry Andric }
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric /// updateForInsertedWaterBlock - When a block is newly inserted into the
8670b57cec5SDimitry Andric /// machine function, it upsets all of the block numbers.  Renumber the blocks
8680b57cec5SDimitry Andric /// and update the arrays that parallel this numbering.
8690b57cec5SDimitry Andric void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
8700b57cec5SDimitry Andric   // Renumber the MBB's to keep them consecutive.
8710b57cec5SDimitry Andric   NewBB->getParent()->RenumberBlocks(NewBB);
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric   // Insert an entry into BBInfo to align it properly with the (newly
8740b57cec5SDimitry Andric   // renumbered) block numbers.
8750b57cec5SDimitry Andric   BBUtils->insert(NewBB->getNumber(), BasicBlockInfo());
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric   // Next, update WaterList.  Specifically, we need to add NewMBB as having
8780b57cec5SDimitry Andric   // available water after it.
8790b57cec5SDimitry Andric   water_iterator IP = llvm::lower_bound(WaterList, NewBB, CompareMBBNumbers);
8800b57cec5SDimitry Andric   WaterList.insert(IP, NewBB);
8810b57cec5SDimitry Andric }
8820b57cec5SDimitry Andric 
8830b57cec5SDimitry Andric /// Split the basic block containing MI into two blocks, which are joined by
8840b57cec5SDimitry Andric /// an unconditional branch.  Update data structures and renumber blocks to
8850b57cec5SDimitry Andric /// account for this change and returns the newly created block.
8860b57cec5SDimitry Andric MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
8870b57cec5SDimitry Andric   MachineBasicBlock *OrigBB = MI->getParent();
8880b57cec5SDimitry Andric 
8898bcb0991SDimitry Andric   // Collect liveness information at MI.
8908bcb0991SDimitry Andric   LivePhysRegs LRs(*MF->getSubtarget().getRegisterInfo());
8918bcb0991SDimitry Andric   LRs.addLiveOuts(*OrigBB);
8928bcb0991SDimitry Andric   auto LivenessEnd = ++MachineBasicBlock::iterator(MI).getReverse();
8938bcb0991SDimitry Andric   for (MachineInstr &LiveMI : make_range(OrigBB->rbegin(), LivenessEnd))
8948bcb0991SDimitry Andric     LRs.stepBackward(LiveMI);
8958bcb0991SDimitry Andric 
8960b57cec5SDimitry Andric   // Create a new MBB for the code after the OrigBB.
8970b57cec5SDimitry Andric   MachineBasicBlock *NewBB =
8980b57cec5SDimitry Andric     MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
8990b57cec5SDimitry Andric   MachineFunction::iterator MBBI = ++OrigBB->getIterator();
9000b57cec5SDimitry Andric   MF->insert(MBBI, NewBB);
9010b57cec5SDimitry Andric 
9020b57cec5SDimitry Andric   // Splice the instructions starting with MI over to NewBB.
9030b57cec5SDimitry Andric   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric   // Add an unconditional branch from OrigBB to NewBB.
9060b57cec5SDimitry Andric   // Note the new unconditional branch is not being recorded.
9070b57cec5SDimitry Andric   // There doesn't seem to be meaningful DebugInfo available; this doesn't
9080b57cec5SDimitry Andric   // correspond to anything in the source.
9090b57cec5SDimitry Andric   unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
9100b57cec5SDimitry Andric   if (!isThumb)
9110b57cec5SDimitry Andric     BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
9120b57cec5SDimitry Andric   else
9130b57cec5SDimitry Andric     BuildMI(OrigBB, DebugLoc(), TII->get(Opc))
9140b57cec5SDimitry Andric         .addMBB(NewBB)
9150b57cec5SDimitry Andric         .add(predOps(ARMCC::AL));
9160b57cec5SDimitry Andric   ++NumSplit;
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
9190b57cec5SDimitry Andric   NewBB->transferSuccessors(OrigBB);
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric   // OrigBB branches to NewBB.
9220b57cec5SDimitry Andric   OrigBB->addSuccessor(NewBB);
9230b57cec5SDimitry Andric 
9248bcb0991SDimitry Andric   // Update live-in information in the new block.
9258bcb0991SDimitry Andric   MachineRegisterInfo &MRI = MF->getRegInfo();
9268bcb0991SDimitry Andric   for (MCPhysReg L : LRs)
9278bcb0991SDimitry Andric     if (!MRI.isReserved(L))
9288bcb0991SDimitry Andric       NewBB->addLiveIn(L);
9298bcb0991SDimitry Andric 
9300b57cec5SDimitry Andric   // Update internal data structures to account for the newly inserted MBB.
9310b57cec5SDimitry Andric   // This is almost the same as updateForInsertedWaterBlock, except that
9320b57cec5SDimitry Andric   // the Water goes after OrigBB, not NewBB.
9330b57cec5SDimitry Andric   MF->RenumberBlocks(NewBB);
9340b57cec5SDimitry Andric 
9350b57cec5SDimitry Andric   // Insert an entry into BBInfo to align it properly with the (newly
9360b57cec5SDimitry Andric   // renumbered) block numbers.
9370b57cec5SDimitry Andric   BBUtils->insert(NewBB->getNumber(), BasicBlockInfo());
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric   // Next, update WaterList.  Specifically, we need to add OrigMBB as having
9400b57cec5SDimitry Andric   // available water after it (but not if it's already there, which happens
9410b57cec5SDimitry Andric   // when splitting before a conditional branch that is followed by an
9420b57cec5SDimitry Andric   // unconditional branch - in that case we want to insert NewBB).
9430b57cec5SDimitry Andric   water_iterator IP = llvm::lower_bound(WaterList, OrigBB, CompareMBBNumbers);
9440b57cec5SDimitry Andric   MachineBasicBlock* WaterBB = *IP;
9450b57cec5SDimitry Andric   if (WaterBB == OrigBB)
9460b57cec5SDimitry Andric     WaterList.insert(std::next(IP), NewBB);
9470b57cec5SDimitry Andric   else
9480b57cec5SDimitry Andric     WaterList.insert(IP, OrigBB);
9490b57cec5SDimitry Andric   NewWaterList.insert(OrigBB);
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric   // Figure out how large the OrigBB is.  As the first half of the original
9520b57cec5SDimitry Andric   // block, it cannot contain a tablejump.  The size includes
9530b57cec5SDimitry Andric   // the new jump we added.  (It should be possible to do this without
9540b57cec5SDimitry Andric   // recounting everything, but it's very confusing, and this is rarely
9550b57cec5SDimitry Andric   // executed.)
9560b57cec5SDimitry Andric   BBUtils->computeBlockSize(OrigBB);
9570b57cec5SDimitry Andric 
9580b57cec5SDimitry Andric   // Figure out how large the NewMBB is.  As the second half of the original
9590b57cec5SDimitry Andric   // block, it may contain a tablejump.
9600b57cec5SDimitry Andric   BBUtils->computeBlockSize(NewBB);
9610b57cec5SDimitry Andric 
9620b57cec5SDimitry Andric   // All BBOffsets following these blocks must be modified.
9630b57cec5SDimitry Andric   BBUtils->adjustBBOffsetsAfter(OrigBB);
9640b57cec5SDimitry Andric 
9650b57cec5SDimitry Andric   return NewBB;
9660b57cec5SDimitry Andric }
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric /// getUserOffset - Compute the offset of U.MI as seen by the hardware
9690b57cec5SDimitry Andric /// displacement computation.  Update U.KnownAlignment to match its current
9700b57cec5SDimitry Andric /// basic block location.
9710b57cec5SDimitry Andric unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
9720b57cec5SDimitry Andric   unsigned UserOffset = BBUtils->getOffsetOf(U.MI);
9730b57cec5SDimitry Andric 
9740b57cec5SDimitry Andric   SmallVectorImpl<BasicBlockInfo> &BBInfo = BBUtils->getBBInfo();
9750b57cec5SDimitry Andric   const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
9760b57cec5SDimitry Andric   unsigned KnownBits = BBI.internalKnownBits();
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric   // The value read from PC is offset from the actual instruction address.
9790b57cec5SDimitry Andric   UserOffset += (isThumb ? 4 : 8);
9800b57cec5SDimitry Andric 
9810b57cec5SDimitry Andric   // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
9820b57cec5SDimitry Andric   // Make sure U.getMaxDisp() returns a constrained range.
9830b57cec5SDimitry Andric   U.KnownAlignment = (KnownBits >= 2);
9840b57cec5SDimitry Andric 
9850b57cec5SDimitry Andric   // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
9860b57cec5SDimitry Andric   // purposes of the displacement computation; compensate for that here.
9870b57cec5SDimitry Andric   // For unknown alignments, getMaxDisp() constrains the range instead.
9880b57cec5SDimitry Andric   if (isThumb && U.KnownAlignment)
9890b57cec5SDimitry Andric     UserOffset &= ~3u;
9900b57cec5SDimitry Andric 
9910b57cec5SDimitry Andric   return UserOffset;
9920b57cec5SDimitry Andric }
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
9950b57cec5SDimitry Andric /// reference) is within MaxDisp of TrialOffset (a proposed location of a
9960b57cec5SDimitry Andric /// constant pool entry).
9970b57cec5SDimitry Andric /// UserOffset is computed by getUserOffset above to include PC adjustments. If
9980b57cec5SDimitry Andric /// the mod 4 alignment of UserOffset is not known, the uncertainty must be
9990b57cec5SDimitry Andric /// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
10000b57cec5SDimitry Andric bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
10010b57cec5SDimitry Andric                                          unsigned TrialOffset, unsigned MaxDisp,
10020b57cec5SDimitry Andric                                          bool NegativeOK, bool IsSoImm) {
10030b57cec5SDimitry Andric   if (UserOffset <= TrialOffset) {
10040b57cec5SDimitry Andric     // User before the Trial.
10050b57cec5SDimitry Andric     if (TrialOffset - UserOffset <= MaxDisp)
10060b57cec5SDimitry Andric       return true;
10070b57cec5SDimitry Andric     // FIXME: Make use full range of soimm values.
10080b57cec5SDimitry Andric   } else if (NegativeOK) {
10090b57cec5SDimitry Andric     if (UserOffset - TrialOffset <= MaxDisp)
10100b57cec5SDimitry Andric       return true;
10110b57cec5SDimitry Andric     // FIXME: Make use full range of soimm values.
10120b57cec5SDimitry Andric   }
10130b57cec5SDimitry Andric   return false;
10140b57cec5SDimitry Andric }
10150b57cec5SDimitry Andric 
10160b57cec5SDimitry Andric /// isWaterInRange - Returns true if a CPE placed after the specified
10170b57cec5SDimitry Andric /// Water (a basic block) will be in range for the specific MI.
10180b57cec5SDimitry Andric ///
10190b57cec5SDimitry Andric /// Compute how much the function will grow by inserting a CPE after Water.
10200b57cec5SDimitry Andric bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
10210b57cec5SDimitry Andric                                         MachineBasicBlock* Water, CPUser &U,
10220b57cec5SDimitry Andric                                         unsigned &Growth) {
10230b57cec5SDimitry Andric   BBInfoVector &BBInfo = BBUtils->getBBInfo();
10248bcb0991SDimitry Andric   const Align CPEAlign = getCPEAlign(U.CPEMI);
10258bcb0991SDimitry Andric   const unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPEAlign);
10268bcb0991SDimitry Andric   unsigned NextBlockOffset;
10278bcb0991SDimitry Andric   Align NextBlockAlignment;
10280b57cec5SDimitry Andric   MachineFunction::const_iterator NextBlock = Water->getIterator();
10290b57cec5SDimitry Andric   if (++NextBlock == MF->end()) {
10300b57cec5SDimitry Andric     NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
10310b57cec5SDimitry Andric   } else {
10320b57cec5SDimitry Andric     NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
10330b57cec5SDimitry Andric     NextBlockAlignment = NextBlock->getAlignment();
10340b57cec5SDimitry Andric   }
10350b57cec5SDimitry Andric   unsigned Size = U.CPEMI->getOperand(2).getImm();
10360b57cec5SDimitry Andric   unsigned CPEEnd = CPEOffset + Size;
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric   // The CPE may be able to hide in the alignment padding before the next
10390b57cec5SDimitry Andric   // block. It may also cause more padding to be required if it is more aligned
10400b57cec5SDimitry Andric   // that the next block.
10410b57cec5SDimitry Andric   if (CPEEnd > NextBlockOffset) {
10420b57cec5SDimitry Andric     Growth = CPEEnd - NextBlockOffset;
10430b57cec5SDimitry Andric     // Compute the padding that would go at the end of the CPE to align the next
10440b57cec5SDimitry Andric     // block.
10458bcb0991SDimitry Andric     Growth += offsetToAlignment(CPEEnd, NextBlockAlignment);
10460b57cec5SDimitry Andric 
10470b57cec5SDimitry Andric     // If the CPE is to be inserted before the instruction, that will raise
10480b57cec5SDimitry Andric     // the offset of the instruction. Also account for unknown alignment padding
10490b57cec5SDimitry Andric     // in blocks between CPE and the user.
10500b57cec5SDimitry Andric     if (CPEOffset < UserOffset)
10518bcb0991SDimitry Andric       UserOffset += Growth + UnknownPadding(MF->getAlignment(), Log2(CPEAlign));
10520b57cec5SDimitry Andric   } else
10530b57cec5SDimitry Andric     // CPE fits in existing padding.
10540b57cec5SDimitry Andric     Growth = 0;
10550b57cec5SDimitry Andric 
10560b57cec5SDimitry Andric   return isOffsetInRange(UserOffset, CPEOffset, U);
10570b57cec5SDimitry Andric }
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric /// isCPEntryInRange - Returns true if the distance between specific MI and
10600b57cec5SDimitry Andric /// specific ConstPool entry instruction can fit in MI's displacement field.
10610b57cec5SDimitry Andric bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
10620b57cec5SDimitry Andric                                       MachineInstr *CPEMI, unsigned MaxDisp,
10630b57cec5SDimitry Andric                                       bool NegOk, bool DoDump) {
10640b57cec5SDimitry Andric   unsigned CPEOffset = BBUtils->getOffsetOf(CPEMI);
10650b57cec5SDimitry Andric 
10660b57cec5SDimitry Andric   if (DoDump) {
10670b57cec5SDimitry Andric     LLVM_DEBUG({
10680b57cec5SDimitry Andric         BBInfoVector &BBInfo = BBUtils->getBBInfo();
10690b57cec5SDimitry Andric       unsigned Block = MI->getParent()->getNumber();
10700b57cec5SDimitry Andric       const BasicBlockInfo &BBI = BBInfo[Block];
10710b57cec5SDimitry Andric       dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
10720b57cec5SDimitry Andric              << " max delta=" << MaxDisp
10730b57cec5SDimitry Andric              << format(" insn address=%#x", UserOffset) << " in "
10740b57cec5SDimitry Andric              << printMBBReference(*MI->getParent()) << ": "
10750b57cec5SDimitry Andric              << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
10760b57cec5SDimitry Andric              << format("CPE address=%#x offset=%+d: ", CPEOffset,
10770b57cec5SDimitry Andric                        int(CPEOffset - UserOffset));
10780b57cec5SDimitry Andric     });
10790b57cec5SDimitry Andric   }
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric   return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
10820b57cec5SDimitry Andric }
10830b57cec5SDimitry Andric 
10840b57cec5SDimitry Andric #ifndef NDEBUG
10850b57cec5SDimitry Andric /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
10860b57cec5SDimitry Andric /// unconditionally branches to its only successor.
10870b57cec5SDimitry Andric static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
10880b57cec5SDimitry Andric   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
10890b57cec5SDimitry Andric     return false;
10900b57cec5SDimitry Andric 
10910b57cec5SDimitry Andric   MachineBasicBlock *Succ = *MBB->succ_begin();
10920b57cec5SDimitry Andric   MachineBasicBlock *Pred = *MBB->pred_begin();
10930b57cec5SDimitry Andric   MachineInstr *PredMI = &Pred->back();
10940b57cec5SDimitry Andric   if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
10950b57cec5SDimitry Andric       || PredMI->getOpcode() == ARM::t2B)
10960b57cec5SDimitry Andric     return PredMI->getOperand(0).getMBB() == Succ;
10970b57cec5SDimitry Andric   return false;
10980b57cec5SDimitry Andric }
10990b57cec5SDimitry Andric #endif // NDEBUG
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric /// decrementCPEReferenceCount - find the constant pool entry with index CPI
11020b57cec5SDimitry Andric /// and instruction CPEMI, and decrement its refcount.  If the refcount
11030b57cec5SDimitry Andric /// becomes 0 remove the entry and instruction.  Returns true if we removed
11040b57cec5SDimitry Andric /// the entry, false if we didn't.
11050b57cec5SDimitry Andric bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
11060b57cec5SDimitry Andric                                                     MachineInstr *CPEMI) {
11070b57cec5SDimitry Andric   // Find the old entry. Eliminate it if it is no longer used.
11080b57cec5SDimitry Andric   CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
11090b57cec5SDimitry Andric   assert(CPE && "Unexpected!");
11100b57cec5SDimitry Andric   if (--CPE->RefCount == 0) {
11110b57cec5SDimitry Andric     removeDeadCPEMI(CPEMI);
11120b57cec5SDimitry Andric     CPE->CPEMI = nullptr;
11130b57cec5SDimitry Andric     --NumCPEs;
11140b57cec5SDimitry Andric     return true;
11150b57cec5SDimitry Andric   }
11160b57cec5SDimitry Andric   return false;
11170b57cec5SDimitry Andric }
11180b57cec5SDimitry Andric 
11190b57cec5SDimitry Andric unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
11200b57cec5SDimitry Andric   if (CPEMI->getOperand(1).isCPI())
11210b57cec5SDimitry Andric     return CPEMI->getOperand(1).getIndex();
11220b57cec5SDimitry Andric 
11230b57cec5SDimitry Andric   return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
11240b57cec5SDimitry Andric }
11250b57cec5SDimitry Andric 
11260b57cec5SDimitry Andric /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
11270b57cec5SDimitry Andric /// if not, see if an in-range clone of the CPE is in range, and if so,
11280b57cec5SDimitry Andric /// change the data structures so the user references the clone.  Returns:
11290b57cec5SDimitry Andric /// 0 = no existing entry found
11300b57cec5SDimitry Andric /// 1 = entry found, and there were no code insertions or deletions
11310b57cec5SDimitry Andric /// 2 = entry found, and there were code insertions or deletions
11320b57cec5SDimitry Andric int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset) {
11330b57cec5SDimitry Andric   MachineInstr *UserMI = U.MI;
11340b57cec5SDimitry Andric   MachineInstr *CPEMI  = U.CPEMI;
11350b57cec5SDimitry Andric 
11360b57cec5SDimitry Andric   // Check to see if the CPE is already in-range.
11370b57cec5SDimitry Andric   if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
11380b57cec5SDimitry Andric                        true)) {
11390b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "In range\n");
11400b57cec5SDimitry Andric     return 1;
11410b57cec5SDimitry Andric   }
11420b57cec5SDimitry Andric 
11430b57cec5SDimitry Andric   // No.  Look for previously created clones of the CPE that are in range.
11440b57cec5SDimitry Andric   unsigned CPI = getCombinedIndex(CPEMI);
11450b57cec5SDimitry Andric   std::vector<CPEntry> &CPEs = CPEntries[CPI];
11460b57cec5SDimitry Andric   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
11470b57cec5SDimitry Andric     // We already tried this one
11480b57cec5SDimitry Andric     if (CPEs[i].CPEMI == CPEMI)
11490b57cec5SDimitry Andric       continue;
11500b57cec5SDimitry Andric     // Removing CPEs can leave empty entries, skip
11510b57cec5SDimitry Andric     if (CPEs[i].CPEMI == nullptr)
11520b57cec5SDimitry Andric       continue;
11530b57cec5SDimitry Andric     if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
11540b57cec5SDimitry Andric                      U.NegOk)) {
11550b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
11560b57cec5SDimitry Andric                         << CPEs[i].CPI << "\n");
11570b57cec5SDimitry Andric       // Point the CPUser node to the replacement
11580b57cec5SDimitry Andric       U.CPEMI = CPEs[i].CPEMI;
11590b57cec5SDimitry Andric       // Change the CPI in the instruction operand to refer to the clone.
11600b57cec5SDimitry Andric       for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
11610b57cec5SDimitry Andric         if (UserMI->getOperand(j).isCPI()) {
11620b57cec5SDimitry Andric           UserMI->getOperand(j).setIndex(CPEs[i].CPI);
11630b57cec5SDimitry Andric           break;
11640b57cec5SDimitry Andric         }
11650b57cec5SDimitry Andric       // Adjust the refcount of the clone...
11660b57cec5SDimitry Andric       CPEs[i].RefCount++;
11670b57cec5SDimitry Andric       // ...and the original.  If we didn't remove the old entry, none of the
11680b57cec5SDimitry Andric       // addresses changed, so we don't need another pass.
11690b57cec5SDimitry Andric       return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
11700b57cec5SDimitry Andric     }
11710b57cec5SDimitry Andric   }
11720b57cec5SDimitry Andric   return 0;
11730b57cec5SDimitry Andric }
11740b57cec5SDimitry Andric 
11750b57cec5SDimitry Andric /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
11760b57cec5SDimitry Andric /// the specific unconditional branch instruction.
11770b57cec5SDimitry Andric static inline unsigned getUnconditionalBrDisp(int Opc) {
11780b57cec5SDimitry Andric   switch (Opc) {
11790b57cec5SDimitry Andric   case ARM::tB:
11800b57cec5SDimitry Andric     return ((1<<10)-1)*2;
11810b57cec5SDimitry Andric   case ARM::t2B:
11820b57cec5SDimitry Andric     return ((1<<23)-1)*2;
11830b57cec5SDimitry Andric   default:
11840b57cec5SDimitry Andric     break;
11850b57cec5SDimitry Andric   }
11860b57cec5SDimitry Andric 
11870b57cec5SDimitry Andric   return ((1<<23)-1)*4;
11880b57cec5SDimitry Andric }
11890b57cec5SDimitry Andric 
11900b57cec5SDimitry Andric /// findAvailableWater - Look for an existing entry in the WaterList in which
11910b57cec5SDimitry Andric /// we can place the CPE referenced from U so it's within range of U's MI.
11920b57cec5SDimitry Andric /// Returns true if found, false if not.  If it returns true, WaterIter
11930b57cec5SDimitry Andric /// is set to the WaterList entry.  For Thumb, prefer water that will not
11940b57cec5SDimitry Andric /// introduce padding to water that will.  To ensure that this pass
11950b57cec5SDimitry Andric /// terminates, the CPE location for a particular CPUser is only allowed to
11960b57cec5SDimitry Andric /// move to a lower address, so search backward from the end of the list and
11970b57cec5SDimitry Andric /// prefer the first water that is in range.
11980b57cec5SDimitry Andric bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
11990b57cec5SDimitry Andric                                             water_iterator &WaterIter,
12000b57cec5SDimitry Andric                                             bool CloserWater) {
12010b57cec5SDimitry Andric   if (WaterList.empty())
12020b57cec5SDimitry Andric     return false;
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric   unsigned BestGrowth = ~0u;
12050b57cec5SDimitry Andric   // The nearest water without splitting the UserBB is right after it.
12060b57cec5SDimitry Andric   // If the distance is still large (we have a big BB), then we need to split it
12070b57cec5SDimitry Andric   // if we don't converge after certain iterations. This helps the following
12080b57cec5SDimitry Andric   // situation to converge:
12090b57cec5SDimitry Andric   //   BB0:
12100b57cec5SDimitry Andric   //      Big BB
12110b57cec5SDimitry Andric   //   BB1:
12120b57cec5SDimitry Andric   //      Constant Pool
12130b57cec5SDimitry Andric   // When a CP access is out of range, BB0 may be used as water. However,
12140b57cec5SDimitry Andric   // inserting islands between BB0 and BB1 makes other accesses out of range.
12150b57cec5SDimitry Andric   MachineBasicBlock *UserBB = U.MI->getParent();
12160b57cec5SDimitry Andric   BBInfoVector &BBInfo = BBUtils->getBBInfo();
12178bcb0991SDimitry Andric   const Align CPEAlign = getCPEAlign(U.CPEMI);
12188bcb0991SDimitry Andric   unsigned MinNoSplitDisp = BBInfo[UserBB->getNumber()].postOffset(CPEAlign);
12190b57cec5SDimitry Andric   if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
12200b57cec5SDimitry Andric     return false;
12210b57cec5SDimitry Andric   for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
12220b57cec5SDimitry Andric        --IP) {
12230b57cec5SDimitry Andric     MachineBasicBlock* WaterBB = *IP;
12240b57cec5SDimitry Andric     // Check if water is in range and is either at a lower address than the
12250b57cec5SDimitry Andric     // current "high water mark" or a new water block that was created since
12260b57cec5SDimitry Andric     // the previous iteration by inserting an unconditional branch.  In the
12270b57cec5SDimitry Andric     // latter case, we want to allow resetting the high water mark back to
12280b57cec5SDimitry Andric     // this new water since we haven't seen it before.  Inserting branches
12290b57cec5SDimitry Andric     // should be relatively uncommon and when it does happen, we want to be
12300b57cec5SDimitry Andric     // sure to take advantage of it for all the CPEs near that block, so that
12310b57cec5SDimitry Andric     // we don't insert more branches than necessary.
12320b57cec5SDimitry Andric     // When CloserWater is true, we try to find the lowest address after (or
12330b57cec5SDimitry Andric     // equal to) user MI's BB no matter of padding growth.
12340b57cec5SDimitry Andric     unsigned Growth;
12350b57cec5SDimitry Andric     if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
12360b57cec5SDimitry Andric         (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
12370b57cec5SDimitry Andric          NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
12380b57cec5SDimitry Andric         Growth < BestGrowth) {
12390b57cec5SDimitry Andric       // This is the least amount of required padding seen so far.
12400b57cec5SDimitry Andric       BestGrowth = Growth;
12410b57cec5SDimitry Andric       WaterIter = IP;
12420b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
12430b57cec5SDimitry Andric                         << " Growth=" << Growth << '\n');
12440b57cec5SDimitry Andric 
12450b57cec5SDimitry Andric       if (CloserWater && WaterBB == U.MI->getParent())
12460b57cec5SDimitry Andric         return true;
12470b57cec5SDimitry Andric       // Keep looking unless it is perfect and we're not looking for the lowest
12480b57cec5SDimitry Andric       // possible address.
12490b57cec5SDimitry Andric       if (!CloserWater && BestGrowth == 0)
12500b57cec5SDimitry Andric         return true;
12510b57cec5SDimitry Andric     }
12520b57cec5SDimitry Andric     if (IP == B)
12530b57cec5SDimitry Andric       break;
12540b57cec5SDimitry Andric   }
12550b57cec5SDimitry Andric   return BestGrowth != ~0u;
12560b57cec5SDimitry Andric }
12570b57cec5SDimitry Andric 
12580b57cec5SDimitry Andric /// createNewWater - No existing WaterList entry will work for
12590b57cec5SDimitry Andric /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
12600b57cec5SDimitry Andric /// block is used if in range, and the conditional branch munged so control
12610b57cec5SDimitry Andric /// flow is correct.  Otherwise the block is split to create a hole with an
12620b57cec5SDimitry Andric /// unconditional branch around it.  In either case NewMBB is set to a
12630b57cec5SDimitry Andric /// block following which the new island can be inserted (the WaterList
12640b57cec5SDimitry Andric /// is not adjusted).
12650b57cec5SDimitry Andric void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
12660b57cec5SDimitry Andric                                         unsigned UserOffset,
12670b57cec5SDimitry Andric                                         MachineBasicBlock *&NewMBB) {
12680b57cec5SDimitry Andric   CPUser &U = CPUsers[CPUserIndex];
12690b57cec5SDimitry Andric   MachineInstr *UserMI = U.MI;
12700b57cec5SDimitry Andric   MachineInstr *CPEMI  = U.CPEMI;
12718bcb0991SDimitry Andric   const Align CPEAlign = getCPEAlign(CPEMI);
12720b57cec5SDimitry Andric   MachineBasicBlock *UserMBB = UserMI->getParent();
12730b57cec5SDimitry Andric   BBInfoVector &BBInfo = BBUtils->getBBInfo();
12740b57cec5SDimitry Andric   const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
12750b57cec5SDimitry Andric 
12760b57cec5SDimitry Andric   // If the block does not end in an unconditional branch already, and if the
12770b57cec5SDimitry Andric   // end of the block is within range, make new water there.  (The addition
12780b57cec5SDimitry Andric   // below is for the unconditional branch we will be adding: 4 bytes on ARM +
12790b57cec5SDimitry Andric   // Thumb2, 2 on Thumb1.
12800b57cec5SDimitry Andric   if (BBHasFallthrough(UserMBB)) {
12810b57cec5SDimitry Andric     // Size of branch to insert.
12820b57cec5SDimitry Andric     unsigned Delta = isThumb1 ? 2 : 4;
12830b57cec5SDimitry Andric     // Compute the offset where the CPE will begin.
12848bcb0991SDimitry Andric     unsigned CPEOffset = UserBBI.postOffset(CPEAlign) + Delta;
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric     if (isOffsetInRange(UserOffset, CPEOffset, U)) {
12870b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)
12880b57cec5SDimitry Andric                         << format(", expected CPE offset %#x\n", CPEOffset));
12890b57cec5SDimitry Andric       NewMBB = &*++UserMBB->getIterator();
12900b57cec5SDimitry Andric       // Add an unconditional branch from UserMBB to fallthrough block.  Record
12910b57cec5SDimitry Andric       // it for branch lengthening; this new branch will not get out of range,
12920b57cec5SDimitry Andric       // but if the preceding conditional branch is out of range, the targets
12930b57cec5SDimitry Andric       // will be exchanged, and the altered branch may be out of range, so the
12940b57cec5SDimitry Andric       // machinery has to know about it.
12950b57cec5SDimitry Andric       int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
12960b57cec5SDimitry Andric       if (!isThumb)
12970b57cec5SDimitry Andric         BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
12980b57cec5SDimitry Andric       else
12990b57cec5SDimitry Andric         BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))
13000b57cec5SDimitry Andric             .addMBB(NewMBB)
13010b57cec5SDimitry Andric             .add(predOps(ARMCC::AL));
13020b57cec5SDimitry Andric       unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
13030b57cec5SDimitry Andric       ImmBranches.push_back(ImmBranch(&UserMBB->back(),
13040b57cec5SDimitry Andric                                       MaxDisp, false, UncondBr));
13050b57cec5SDimitry Andric       BBUtils->computeBlockSize(UserMBB);
13060b57cec5SDimitry Andric       BBUtils->adjustBBOffsetsAfter(UserMBB);
13070b57cec5SDimitry Andric       return;
13080b57cec5SDimitry Andric     }
13090b57cec5SDimitry Andric   }
13100b57cec5SDimitry Andric 
13110b57cec5SDimitry Andric   // What a big block.  Find a place within the block to split it.  This is a
13120b57cec5SDimitry Andric   // little tricky on Thumb1 since instructions are 2 bytes and constant pool
13130b57cec5SDimitry Andric   // entries are 4 bytes: if instruction I references island CPE, and
13140b57cec5SDimitry Andric   // instruction I+1 references CPE', it will not work well to put CPE as far
13150b57cec5SDimitry Andric   // forward as possible, since then CPE' cannot immediately follow it (that
13160b57cec5SDimitry Andric   // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
13170b57cec5SDimitry Andric   // need to create a new island.  So, we make a first guess, then walk through
13180b57cec5SDimitry Andric   // the instructions between the one currently being looked at and the
13190b57cec5SDimitry Andric   // possible insertion point, and make sure any other instructions that
13200b57cec5SDimitry Andric   // reference CPEs will be able to use the same island area; if not, we back
13210b57cec5SDimitry Andric   // up the insertion point.
13220b57cec5SDimitry Andric 
13230b57cec5SDimitry Andric   // Try to split the block so it's fully aligned.  Compute the latest split
13240b57cec5SDimitry Andric   // point where we can add a 4-byte branch instruction, and then align to
13258bcb0991SDimitry Andric   // Align which is the largest possible alignment in the function.
13268bcb0991SDimitry Andric   const Align Align = MF->getAlignment();
13278bcb0991SDimitry Andric   assert(Align >= CPEAlign && "Over-aligned constant pool entry");
13280b57cec5SDimitry Andric   unsigned KnownBits = UserBBI.internalKnownBits();
13298bcb0991SDimitry Andric   unsigned UPad = UnknownPadding(Align, KnownBits);
13300b57cec5SDimitry Andric   unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
13310b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
13320b57cec5SDimitry Andric                               BaseInsertOffset));
13330b57cec5SDimitry Andric 
13340b57cec5SDimitry Andric   // The 4 in the following is for the unconditional branch we'll be inserting
13350b57cec5SDimitry Andric   // (allows for long branch on Thumb1).  Alignment of the island is handled
13360b57cec5SDimitry Andric   // inside isOffsetInRange.
13370b57cec5SDimitry Andric   BaseInsertOffset -= 4;
13380b57cec5SDimitry Andric 
13390b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
13408bcb0991SDimitry Andric                     << " la=" << Log2(Align) << " kb=" << KnownBits
13410b57cec5SDimitry Andric                     << " up=" << UPad << '\n');
13420b57cec5SDimitry Andric 
13430b57cec5SDimitry Andric   // This could point off the end of the block if we've already got constant
13440b57cec5SDimitry Andric   // pool entries following this block; only the last one is in the water list.
13450b57cec5SDimitry Andric   // Back past any possible branches (allow for a conditional and a maximally
13460b57cec5SDimitry Andric   // long unconditional).
13470b57cec5SDimitry Andric   if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
13480b57cec5SDimitry Andric     // Ensure BaseInsertOffset is larger than the offset of the instruction
13490b57cec5SDimitry Andric     // following UserMI so that the loop which searches for the split point
13500b57cec5SDimitry Andric     // iterates at least once.
13510b57cec5SDimitry Andric     BaseInsertOffset =
13520b57cec5SDimitry Andric         std::max(UserBBI.postOffset() - UPad - 8,
13530b57cec5SDimitry Andric                  UserOffset + TII->getInstSizeInBytes(*UserMI) + 1);
13548bcb0991SDimitry Andric     // If the CP is referenced(ie, UserOffset) is in first four instructions
13558bcb0991SDimitry Andric     // after IT, this recalculated BaseInsertOffset could be in the middle of
13568bcb0991SDimitry Andric     // an IT block. If it is, change the BaseInsertOffset to just after the
13578bcb0991SDimitry Andric     // IT block. This still make the CP Entry is in range becuase of the
13588bcb0991SDimitry Andric     // following reasons.
13598bcb0991SDimitry Andric     //   1. The initial BaseseInsertOffset calculated is (UserOffset +
13608bcb0991SDimitry Andric     //   U.getMaxDisp() - UPad).
13618bcb0991SDimitry Andric     //   2. An IT block is only at most 4 instructions plus the "it" itself (18
13628bcb0991SDimitry Andric     //   bytes).
13638bcb0991SDimitry Andric     //   3. All the relevant instructions support much larger Maximum
13648bcb0991SDimitry Andric     //   displacement.
13658bcb0991SDimitry Andric     MachineBasicBlock::iterator I = UserMI;
13668bcb0991SDimitry Andric     ++I;
13678bcb0991SDimitry Andric     for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI),
13688bcb0991SDimitry Andric                   PredReg = 0;
13698bcb0991SDimitry Andric          I->getOpcode() != ARM::t2IT &&
13708bcb0991SDimitry Andric          getITInstrPredicate(*I, PredReg) != ARMCC::AL;
13718bcb0991SDimitry Andric          Offset += TII->getInstSizeInBytes(*I), I = std::next(I)) {
13728bcb0991SDimitry Andric       BaseInsertOffset =
13738bcb0991SDimitry Andric           std::max(BaseInsertOffset, Offset + TII->getInstSizeInBytes(*I) + 1);
13748bcb0991SDimitry Andric       assert(I != UserMBB->end() && "Fell off end of block");
13758bcb0991SDimitry Andric     }
13760b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
13770b57cec5SDimitry Andric   }
13780b57cec5SDimitry Andric   unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
13790b57cec5SDimitry Andric     CPEMI->getOperand(2).getImm();
13800b57cec5SDimitry Andric   MachineBasicBlock::iterator MI = UserMI;
13810b57cec5SDimitry Andric   ++MI;
13820b57cec5SDimitry Andric   unsigned CPUIndex = CPUserIndex+1;
13830b57cec5SDimitry Andric   unsigned NumCPUsers = CPUsers.size();
13840b57cec5SDimitry Andric   MachineInstr *LastIT = nullptr;
13850b57cec5SDimitry Andric   for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
13860b57cec5SDimitry Andric        Offset < BaseInsertOffset;
13870b57cec5SDimitry Andric        Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
13880b57cec5SDimitry Andric     assert(MI != UserMBB->end() && "Fell off end of block");
13890b57cec5SDimitry Andric     if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {
13900b57cec5SDimitry Andric       CPUser &U = CPUsers[CPUIndex];
13910b57cec5SDimitry Andric       if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
13920b57cec5SDimitry Andric         // Shift intertion point by one unit of alignment so it is within reach.
13938bcb0991SDimitry Andric         BaseInsertOffset -= Align.value();
13948bcb0991SDimitry Andric         EndInsertOffset -= Align.value();
13950b57cec5SDimitry Andric       }
13960b57cec5SDimitry Andric       // This is overly conservative, as we don't account for CPEMIs being
13970b57cec5SDimitry Andric       // reused within the block, but it doesn't matter much.  Also assume CPEs
13980b57cec5SDimitry Andric       // are added in order with alignment padding.  We may eventually be able
13990b57cec5SDimitry Andric       // to pack the aligned CPEs better.
14000b57cec5SDimitry Andric       EndInsertOffset += U.CPEMI->getOperand(2).getImm();
14010b57cec5SDimitry Andric       CPUIndex++;
14020b57cec5SDimitry Andric     }
14030b57cec5SDimitry Andric 
14040b57cec5SDimitry Andric     // Remember the last IT instruction.
14050b57cec5SDimitry Andric     if (MI->getOpcode() == ARM::t2IT)
14060b57cec5SDimitry Andric       LastIT = &*MI;
14070b57cec5SDimitry Andric   }
14080b57cec5SDimitry Andric 
14090b57cec5SDimitry Andric   --MI;
14100b57cec5SDimitry Andric 
14110b57cec5SDimitry Andric   // Avoid splitting an IT block.
14120b57cec5SDimitry Andric   if (LastIT) {
14130b57cec5SDimitry Andric     unsigned PredReg = 0;
14140b57cec5SDimitry Andric     ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
14150b57cec5SDimitry Andric     if (CC != ARMCC::AL)
14160b57cec5SDimitry Andric       MI = LastIT;
14170b57cec5SDimitry Andric   }
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric   // Avoid splitting a MOVW+MOVT pair with a relocation on Windows.
14200b57cec5SDimitry Andric   // On Windows, this instruction pair is covered by one single
14210b57cec5SDimitry Andric   // IMAGE_REL_ARM_MOV32T relocation which covers both instructions. If a
14220b57cec5SDimitry Andric   // constant island is injected inbetween them, the relocation will clobber
14230b57cec5SDimitry Andric   // the instruction and fail to update the MOVT instruction.
14240b57cec5SDimitry Andric   // (These instructions are bundled up until right before the ConstantIslands
14250b57cec5SDimitry Andric   // pass.)
14260b57cec5SDimitry Andric   if (STI->isTargetWindows() && isThumb && MI->getOpcode() == ARM::t2MOVTi16 &&
14270b57cec5SDimitry Andric       (MI->getOperand(2).getTargetFlags() & ARMII::MO_OPTION_MASK) ==
14280b57cec5SDimitry Andric           ARMII::MO_HI16) {
14290b57cec5SDimitry Andric     --MI;
14300b57cec5SDimitry Andric     assert(MI->getOpcode() == ARM::t2MOVi16 &&
14310b57cec5SDimitry Andric            (MI->getOperand(1).getTargetFlags() & ARMII::MO_OPTION_MASK) ==
14320b57cec5SDimitry Andric                ARMII::MO_LO16);
14330b57cec5SDimitry Andric   }
14340b57cec5SDimitry Andric 
14350b57cec5SDimitry Andric   // We really must not split an IT block.
14368bcb0991SDimitry Andric #ifndef NDEBUG
14378bcb0991SDimitry Andric   unsigned PredReg;
14388bcb0991SDimitry Andric   assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL);
14398bcb0991SDimitry Andric #endif
14400b57cec5SDimitry Andric   NewMBB = splitBlockBeforeInstr(&*MI);
14410b57cec5SDimitry Andric }
14420b57cec5SDimitry Andric 
14430b57cec5SDimitry Andric /// handleConstantPoolUser - Analyze the specified user, checking to see if it
14440b57cec5SDimitry Andric /// is out-of-range.  If so, pick up the constant pool value and move it some
14450b57cec5SDimitry Andric /// place in-range.  Return true if we changed any addresses (thus must run
14460b57cec5SDimitry Andric /// another pass of branch lengthening), false otherwise.
14470b57cec5SDimitry Andric bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
14480b57cec5SDimitry Andric                                                 bool CloserWater) {
14490b57cec5SDimitry Andric   CPUser &U = CPUsers[CPUserIndex];
14500b57cec5SDimitry Andric   MachineInstr *UserMI = U.MI;
14510b57cec5SDimitry Andric   MachineInstr *CPEMI  = U.CPEMI;
14520b57cec5SDimitry Andric   unsigned CPI = getCombinedIndex(CPEMI);
14530b57cec5SDimitry Andric   unsigned Size = CPEMI->getOperand(2).getImm();
14540b57cec5SDimitry Andric   // Compute this only once, it's expensive.
14550b57cec5SDimitry Andric   unsigned UserOffset = getUserOffset(U);
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric   // See if the current entry is within range, or there is a clone of it
14580b57cec5SDimitry Andric   // in range.
14590b57cec5SDimitry Andric   int result = findInRangeCPEntry(U, UserOffset);
14600b57cec5SDimitry Andric   if (result==1) return false;
14610b57cec5SDimitry Andric   else if (result==2) return true;
14620b57cec5SDimitry Andric 
14630b57cec5SDimitry Andric   // No existing clone of this CPE is within range.
14640b57cec5SDimitry Andric   // We will be generating a new clone.  Get a UID for it.
14650b57cec5SDimitry Andric   unsigned ID = AFI->createPICLabelUId();
14660b57cec5SDimitry Andric 
14670b57cec5SDimitry Andric   // Look for water where we can place this CPE.
14680b57cec5SDimitry Andric   MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
14690b57cec5SDimitry Andric   MachineBasicBlock *NewMBB;
14700b57cec5SDimitry Andric   water_iterator IP;
14710b57cec5SDimitry Andric   if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
14720b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Found water in range\n");
14730b57cec5SDimitry Andric     MachineBasicBlock *WaterBB = *IP;
14740b57cec5SDimitry Andric 
14750b57cec5SDimitry Andric     // If the original WaterList entry was "new water" on this iteration,
14760b57cec5SDimitry Andric     // propagate that to the new island.  This is just keeping NewWaterList
14770b57cec5SDimitry Andric     // updated to match the WaterList, which will be updated below.
14780b57cec5SDimitry Andric     if (NewWaterList.erase(WaterBB))
14790b57cec5SDimitry Andric       NewWaterList.insert(NewIsland);
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric     // The new CPE goes before the following block (NewMBB).
14820b57cec5SDimitry Andric     NewMBB = &*++WaterBB->getIterator();
14830b57cec5SDimitry Andric   } else {
14840b57cec5SDimitry Andric     // No water found.
14850b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "No water found\n");
14860b57cec5SDimitry Andric     createNewWater(CPUserIndex, UserOffset, NewMBB);
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric     // splitBlockBeforeInstr adds to WaterList, which is important when it is
14890b57cec5SDimitry Andric     // called while handling branches so that the water will be seen on the
14900b57cec5SDimitry Andric     // next iteration for constant pools, but in this context, we don't want
14910b57cec5SDimitry Andric     // it.  Check for this so it will be removed from the WaterList.
14920b57cec5SDimitry Andric     // Also remove any entry from NewWaterList.
14930b57cec5SDimitry Andric     MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
14940b57cec5SDimitry Andric     IP = find(WaterList, WaterBB);
14950b57cec5SDimitry Andric     if (IP != WaterList.end())
14960b57cec5SDimitry Andric       NewWaterList.erase(WaterBB);
14970b57cec5SDimitry Andric 
14980b57cec5SDimitry Andric     // We are adding new water.  Update NewWaterList.
14990b57cec5SDimitry Andric     NewWaterList.insert(NewIsland);
15000b57cec5SDimitry Andric   }
15010b57cec5SDimitry Andric   // Always align the new block because CP entries can be smaller than 4
15020b57cec5SDimitry Andric   // bytes. Be careful not to decrease the existing alignment, e.g. NewMBB may
15030b57cec5SDimitry Andric   // be an already aligned constant pool block.
15048bcb0991SDimitry Andric   const Align Alignment = isThumb ? Align(2) : Align(4);
15058bcb0991SDimitry Andric   if (NewMBB->getAlignment() < Alignment)
15068bcb0991SDimitry Andric     NewMBB->setAlignment(Alignment);
15070b57cec5SDimitry Andric 
15080b57cec5SDimitry Andric   // Remove the original WaterList entry; we want subsequent insertions in
15090b57cec5SDimitry Andric   // this vicinity to go after the one we're about to insert.  This
15100b57cec5SDimitry Andric   // considerably reduces the number of times we have to move the same CPE
15110b57cec5SDimitry Andric   // more than once and is also important to ensure the algorithm terminates.
15120b57cec5SDimitry Andric   if (IP != WaterList.end())
15130b57cec5SDimitry Andric     WaterList.erase(IP);
15140b57cec5SDimitry Andric 
15150b57cec5SDimitry Andric   // Okay, we know we can put an island before NewMBB now, do it!
15160b57cec5SDimitry Andric   MF->insert(NewMBB->getIterator(), NewIsland);
15170b57cec5SDimitry Andric 
15180b57cec5SDimitry Andric   // Update internal data structures to account for the newly inserted MBB.
15190b57cec5SDimitry Andric   updateForInsertedWaterBlock(NewIsland);
15200b57cec5SDimitry Andric 
15210b57cec5SDimitry Andric   // Now that we have an island to add the CPE to, clone the original CPE and
15220b57cec5SDimitry Andric   // add it to the island.
15230b57cec5SDimitry Andric   U.HighWaterMark = NewIsland;
15240b57cec5SDimitry Andric   U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
15250b57cec5SDimitry Andric                 .addImm(ID)
15260b57cec5SDimitry Andric                 .add(CPEMI->getOperand(1))
15270b57cec5SDimitry Andric                 .addImm(Size);
15280b57cec5SDimitry Andric   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
15290b57cec5SDimitry Andric   ++NumCPEs;
15300b57cec5SDimitry Andric 
15310b57cec5SDimitry Andric   // Decrement the old entry, and remove it if refcount becomes 0.
15320b57cec5SDimitry Andric   decrementCPEReferenceCount(CPI, CPEMI);
15330b57cec5SDimitry Andric 
15340b57cec5SDimitry Andric   // Mark the basic block as aligned as required by the const-pool entry.
15358bcb0991SDimitry Andric   NewIsland->setAlignment(getCPEAlign(U.CPEMI));
15360b57cec5SDimitry Andric 
15370b57cec5SDimitry Andric   // Increase the size of the island block to account for the new entry.
15380b57cec5SDimitry Andric   BBUtils->adjustBBSize(NewIsland, Size);
15390b57cec5SDimitry Andric   BBUtils->adjustBBOffsetsAfter(&*--NewIsland->getIterator());
15400b57cec5SDimitry Andric 
15410b57cec5SDimitry Andric   // Finally, change the CPI in the instruction operand to be ID.
15420b57cec5SDimitry Andric   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
15430b57cec5SDimitry Andric     if (UserMI->getOperand(i).isCPI()) {
15440b57cec5SDimitry Andric       UserMI->getOperand(i).setIndex(ID);
15450b57cec5SDimitry Andric       break;
15460b57cec5SDimitry Andric     }
15470b57cec5SDimitry Andric 
15480b57cec5SDimitry Andric   LLVM_DEBUG(
15490b57cec5SDimitry Andric       dbgs() << "  Moved CPE to #" << ID << " CPI=" << CPI
15500b57cec5SDimitry Andric              << format(" offset=%#x\n",
15510b57cec5SDimitry Andric                        BBUtils->getBBInfo()[NewIsland->getNumber()].Offset));
15520b57cec5SDimitry Andric 
15530b57cec5SDimitry Andric   return true;
15540b57cec5SDimitry Andric }
15550b57cec5SDimitry Andric 
15560b57cec5SDimitry Andric /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
15570b57cec5SDimitry Andric /// sizes and offsets of impacted basic blocks.
15580b57cec5SDimitry Andric void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
15590b57cec5SDimitry Andric   MachineBasicBlock *CPEBB = CPEMI->getParent();
15600b57cec5SDimitry Andric   unsigned Size = CPEMI->getOperand(2).getImm();
15610b57cec5SDimitry Andric   CPEMI->eraseFromParent();
15620b57cec5SDimitry Andric   BBInfoVector &BBInfo = BBUtils->getBBInfo();
15630b57cec5SDimitry Andric   BBUtils->adjustBBSize(CPEBB, -Size);
15640b57cec5SDimitry Andric   // All succeeding offsets have the current size value added in, fix this.
15650b57cec5SDimitry Andric   if (CPEBB->empty()) {
15660b57cec5SDimitry Andric     BBInfo[CPEBB->getNumber()].Size = 0;
15670b57cec5SDimitry Andric 
15680b57cec5SDimitry Andric     // This block no longer needs to be aligned.
15698bcb0991SDimitry Andric     CPEBB->setAlignment(Align::None());
15708bcb0991SDimitry Andric   } else {
15710b57cec5SDimitry Andric     // Entries are sorted by descending alignment, so realign from the front.
15728bcb0991SDimitry Andric     CPEBB->setAlignment(getCPEAlign(&*CPEBB->begin()));
15738bcb0991SDimitry Andric   }
15740b57cec5SDimitry Andric 
15750b57cec5SDimitry Andric   BBUtils->adjustBBOffsetsAfter(CPEBB);
15760b57cec5SDimitry Andric   // An island has only one predecessor BB and one successor BB. Check if
15770b57cec5SDimitry Andric   // this BB's predecessor jumps directly to this BB's successor. This
15780b57cec5SDimitry Andric   // shouldn't happen currently.
15790b57cec5SDimitry Andric   assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
15800b57cec5SDimitry Andric   // FIXME: remove the empty blocks after all the work is done?
15810b57cec5SDimitry Andric }
15820b57cec5SDimitry Andric 
15830b57cec5SDimitry Andric /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
15840b57cec5SDimitry Andric /// are zero.
15850b57cec5SDimitry Andric bool ARMConstantIslands::removeUnusedCPEntries() {
15860b57cec5SDimitry Andric   unsigned MadeChange = false;
15870b57cec5SDimitry Andric   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
15880b57cec5SDimitry Andric       std::vector<CPEntry> &CPEs = CPEntries[i];
15890b57cec5SDimitry Andric       for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
15900b57cec5SDimitry Andric         if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
15910b57cec5SDimitry Andric           removeDeadCPEMI(CPEs[j].CPEMI);
15920b57cec5SDimitry Andric           CPEs[j].CPEMI = nullptr;
15930b57cec5SDimitry Andric           MadeChange = true;
15940b57cec5SDimitry Andric         }
15950b57cec5SDimitry Andric       }
15960b57cec5SDimitry Andric   }
15970b57cec5SDimitry Andric   return MadeChange;
15980b57cec5SDimitry Andric }
15990b57cec5SDimitry Andric 
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
16020b57cec5SDimitry Andric /// away to fit in its displacement field.
16030b57cec5SDimitry Andric bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
16040b57cec5SDimitry Andric   MachineInstr *MI = Br.MI;
16050b57cec5SDimitry Andric   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
16060b57cec5SDimitry Andric 
16070b57cec5SDimitry Andric   // Check to see if the DestBB is already in-range.
16080b57cec5SDimitry Andric   if (BBUtils->isBBInRange(MI, DestBB, Br.MaxDisp))
16090b57cec5SDimitry Andric     return false;
16100b57cec5SDimitry Andric 
16110b57cec5SDimitry Andric   if (!Br.isCond)
16120b57cec5SDimitry Andric     return fixupUnconditionalBr(Br);
16130b57cec5SDimitry Andric   return fixupConditionalBr(Br);
16140b57cec5SDimitry Andric }
16150b57cec5SDimitry Andric 
16160b57cec5SDimitry Andric /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
16170b57cec5SDimitry Andric /// too far away to fit in its displacement field. If the LR register has been
16180b57cec5SDimitry Andric /// spilled in the epilogue, then we can use BL to implement a far jump.
16190b57cec5SDimitry Andric /// Otherwise, add an intermediate branch instruction to a branch.
16200b57cec5SDimitry Andric bool
16210b57cec5SDimitry Andric ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
16220b57cec5SDimitry Andric   MachineInstr *MI = Br.MI;
16230b57cec5SDimitry Andric   MachineBasicBlock *MBB = MI->getParent();
16240b57cec5SDimitry Andric   if (!isThumb1)
16250b57cec5SDimitry Andric     llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
16260b57cec5SDimitry Andric 
16270b57cec5SDimitry Andric   if (!AFI->isLRSpilled())
16280b57cec5SDimitry Andric     report_fatal_error("underestimated function size");
16290b57cec5SDimitry Andric 
16300b57cec5SDimitry Andric   // Use BL to implement far jump.
16310b57cec5SDimitry Andric   Br.MaxDisp = (1 << 21) * 2;
16320b57cec5SDimitry Andric   MI->setDesc(TII->get(ARM::tBfar));
16330b57cec5SDimitry Andric   BBInfoVector &BBInfo = BBUtils->getBBInfo();
16340b57cec5SDimitry Andric   BBInfo[MBB->getNumber()].Size += 2;
16350b57cec5SDimitry Andric   BBUtils->adjustBBOffsetsAfter(MBB);
16360b57cec5SDimitry Andric   HasFarJump = true;
16370b57cec5SDimitry Andric   ++NumUBrFixed;
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Changed B to long jump " << *MI);
16400b57cec5SDimitry Andric 
16410b57cec5SDimitry Andric   return true;
16420b57cec5SDimitry Andric }
16430b57cec5SDimitry Andric 
16440b57cec5SDimitry Andric /// fixupConditionalBr - Fix up a conditional branch whose destination is too
16450b57cec5SDimitry Andric /// far away to fit in its displacement field. It is converted to an inverse
16460b57cec5SDimitry Andric /// conditional branch + an unconditional branch to the destination.
16470b57cec5SDimitry Andric bool
16480b57cec5SDimitry Andric ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
16490b57cec5SDimitry Andric   MachineInstr *MI = Br.MI;
16500b57cec5SDimitry Andric   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
16510b57cec5SDimitry Andric 
16520b57cec5SDimitry Andric   // Add an unconditional branch to the destination and invert the branch
16530b57cec5SDimitry Andric   // condition to jump over it:
16540b57cec5SDimitry Andric   // blt L1
16550b57cec5SDimitry Andric   // =>
16560b57cec5SDimitry Andric   // bge L2
16570b57cec5SDimitry Andric   // b   L1
16580b57cec5SDimitry Andric   // L2:
16590b57cec5SDimitry Andric   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
16600b57cec5SDimitry Andric   CC = ARMCC::getOppositeCondition(CC);
16618bcb0991SDimitry Andric   Register CCReg = MI->getOperand(2).getReg();
16620b57cec5SDimitry Andric 
16630b57cec5SDimitry Andric   // If the branch is at the end of its MBB and that has a fall-through block,
16640b57cec5SDimitry Andric   // direct the updated conditional branch to the fall-through block. Otherwise,
16650b57cec5SDimitry Andric   // split the MBB before the next instruction.
16660b57cec5SDimitry Andric   MachineBasicBlock *MBB = MI->getParent();
16670b57cec5SDimitry Andric   MachineInstr *BMI = &MBB->back();
16680b57cec5SDimitry Andric   bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
16690b57cec5SDimitry Andric 
16700b57cec5SDimitry Andric   ++NumCBrFixed;
16710b57cec5SDimitry Andric   if (BMI != MI) {
16720b57cec5SDimitry Andric     if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
16730b57cec5SDimitry Andric         BMI->getOpcode() == Br.UncondBr) {
16740b57cec5SDimitry Andric       // Last MI in the BB is an unconditional branch. Can we simply invert the
16750b57cec5SDimitry Andric       // condition and swap destinations:
16760b57cec5SDimitry Andric       // beq L1
16770b57cec5SDimitry Andric       // b   L2
16780b57cec5SDimitry Andric       // =>
16790b57cec5SDimitry Andric       // bne L2
16800b57cec5SDimitry Andric       // b   L1
16810b57cec5SDimitry Andric       MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
16820b57cec5SDimitry Andric       if (BBUtils->isBBInRange(MI, NewDest, Br.MaxDisp)) {
16830b57cec5SDimitry Andric         LLVM_DEBUG(
16840b57cec5SDimitry Andric             dbgs() << "  Invert Bcc condition and swap its destination with "
16850b57cec5SDimitry Andric                    << *BMI);
16860b57cec5SDimitry Andric         BMI->getOperand(0).setMBB(DestBB);
16870b57cec5SDimitry Andric         MI->getOperand(0).setMBB(NewDest);
16880b57cec5SDimitry Andric         MI->getOperand(1).setImm(CC);
16890b57cec5SDimitry Andric         return true;
16900b57cec5SDimitry Andric       }
16910b57cec5SDimitry Andric     }
16920b57cec5SDimitry Andric   }
16930b57cec5SDimitry Andric 
16940b57cec5SDimitry Andric   if (NeedSplit) {
16950b57cec5SDimitry Andric     splitBlockBeforeInstr(MI);
16960b57cec5SDimitry Andric     // No need for the branch to the next block. We're adding an unconditional
16970b57cec5SDimitry Andric     // branch to the destination.
16980b57cec5SDimitry Andric     int delta = TII->getInstSizeInBytes(MBB->back());
16990b57cec5SDimitry Andric     BBUtils->adjustBBSize(MBB, -delta);
17000b57cec5SDimitry Andric     MBB->back().eraseFromParent();
17010b57cec5SDimitry Andric 
17020b57cec5SDimitry Andric     // The conditional successor will be swapped between the BBs after this, so
17030b57cec5SDimitry Andric     // update CFG.
17040b57cec5SDimitry Andric     MBB->addSuccessor(DestBB);
17050b57cec5SDimitry Andric     std::next(MBB->getIterator())->removeSuccessor(DestBB);
17060b57cec5SDimitry Andric 
17070b57cec5SDimitry Andric     // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
17080b57cec5SDimitry Andric   }
17090b57cec5SDimitry Andric   MachineBasicBlock *NextBB = &*++MBB->getIterator();
17100b57cec5SDimitry Andric 
17110b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Insert B to " << printMBBReference(*DestBB)
17120b57cec5SDimitry Andric                     << " also invert condition and change dest. to "
17130b57cec5SDimitry Andric                     << printMBBReference(*NextBB) << "\n");
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric   // Insert a new conditional branch and a new unconditional branch.
17160b57cec5SDimitry Andric   // Also update the ImmBranch as well as adding a new entry for the new branch.
17170b57cec5SDimitry Andric   BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
17180b57cec5SDimitry Andric     .addMBB(NextBB).addImm(CC).addReg(CCReg);
17190b57cec5SDimitry Andric   Br.MI = &MBB->back();
17200b57cec5SDimitry Andric   BBUtils->adjustBBSize(MBB, TII->getInstSizeInBytes(MBB->back()));
17210b57cec5SDimitry Andric   if (isThumb)
17220b57cec5SDimitry Andric     BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr))
17230b57cec5SDimitry Andric         .addMBB(DestBB)
17240b57cec5SDimitry Andric         .add(predOps(ARMCC::AL));
17250b57cec5SDimitry Andric   else
17260b57cec5SDimitry Andric     BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
17270b57cec5SDimitry Andric   BBUtils->adjustBBSize(MBB, TII->getInstSizeInBytes(MBB->back()));
17280b57cec5SDimitry Andric   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
17290b57cec5SDimitry Andric   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
17300b57cec5SDimitry Andric 
17310b57cec5SDimitry Andric   // Remove the old conditional branch.  It may or may not still be in MBB.
17320b57cec5SDimitry Andric   BBUtils->adjustBBSize(MI->getParent(), -TII->getInstSizeInBytes(*MI));
17330b57cec5SDimitry Andric   MI->eraseFromParent();
17340b57cec5SDimitry Andric   BBUtils->adjustBBOffsetsAfter(MBB);
17350b57cec5SDimitry Andric   return true;
17360b57cec5SDimitry Andric }
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric /// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
17390b57cec5SDimitry Andric /// LR / restores LR to pc. FIXME: This is done here because it's only possible
17400b57cec5SDimitry Andric /// to do this if tBfar is not used.
17410b57cec5SDimitry Andric bool ARMConstantIslands::undoLRSpillRestore() {
17420b57cec5SDimitry Andric   bool MadeChange = false;
17430b57cec5SDimitry Andric   for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
17440b57cec5SDimitry Andric     MachineInstr *MI = PushPopMIs[i];
17450b57cec5SDimitry Andric     // First two operands are predicates.
17460b57cec5SDimitry Andric     if (MI->getOpcode() == ARM::tPOP_RET &&
17470b57cec5SDimitry Andric         MI->getOperand(2).getReg() == ARM::PC &&
17480b57cec5SDimitry Andric         MI->getNumExplicitOperands() == 3) {
17490b57cec5SDimitry Andric       // Create the new insn and copy the predicate from the old.
17500b57cec5SDimitry Andric       BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
17510b57cec5SDimitry Andric           .add(MI->getOperand(0))
17520b57cec5SDimitry Andric           .add(MI->getOperand(1));
17530b57cec5SDimitry Andric       MI->eraseFromParent();
17540b57cec5SDimitry Andric       MadeChange = true;
17550b57cec5SDimitry Andric     } else if (MI->getOpcode() == ARM::tPUSH &&
17560b57cec5SDimitry Andric                MI->getOperand(2).getReg() == ARM::LR &&
17570b57cec5SDimitry Andric                MI->getNumExplicitOperands() == 3) {
17580b57cec5SDimitry Andric       // Just remove the push.
17590b57cec5SDimitry Andric       MI->eraseFromParent();
17600b57cec5SDimitry Andric       MadeChange = true;
17610b57cec5SDimitry Andric     }
17620b57cec5SDimitry Andric   }
17630b57cec5SDimitry Andric   return MadeChange;
17640b57cec5SDimitry Andric }
17650b57cec5SDimitry Andric 
17660b57cec5SDimitry Andric bool ARMConstantIslands::optimizeThumb2Instructions() {
17670b57cec5SDimitry Andric   bool MadeChange = false;
17680b57cec5SDimitry Andric 
17690b57cec5SDimitry Andric   // Shrink ADR and LDR from constantpool.
17700b57cec5SDimitry Andric   for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
17710b57cec5SDimitry Andric     CPUser &U = CPUsers[i];
17720b57cec5SDimitry Andric     unsigned Opcode = U.MI->getOpcode();
17730b57cec5SDimitry Andric     unsigned NewOpc = 0;
17740b57cec5SDimitry Andric     unsigned Scale = 1;
17750b57cec5SDimitry Andric     unsigned Bits = 0;
17760b57cec5SDimitry Andric     switch (Opcode) {
17770b57cec5SDimitry Andric     default: break;
17780b57cec5SDimitry Andric     case ARM::t2LEApcrel:
17790b57cec5SDimitry Andric       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
17800b57cec5SDimitry Andric         NewOpc = ARM::tLEApcrel;
17810b57cec5SDimitry Andric         Bits = 8;
17820b57cec5SDimitry Andric         Scale = 4;
17830b57cec5SDimitry Andric       }
17840b57cec5SDimitry Andric       break;
17850b57cec5SDimitry Andric     case ARM::t2LDRpci:
17860b57cec5SDimitry Andric       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
17870b57cec5SDimitry Andric         NewOpc = ARM::tLDRpci;
17880b57cec5SDimitry Andric         Bits = 8;
17890b57cec5SDimitry Andric         Scale = 4;
17900b57cec5SDimitry Andric       }
17910b57cec5SDimitry Andric       break;
17920b57cec5SDimitry Andric     }
17930b57cec5SDimitry Andric 
17940b57cec5SDimitry Andric     if (!NewOpc)
17950b57cec5SDimitry Andric       continue;
17960b57cec5SDimitry Andric 
17970b57cec5SDimitry Andric     unsigned UserOffset = getUserOffset(U);
17980b57cec5SDimitry Andric     unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
17990b57cec5SDimitry Andric 
18000b57cec5SDimitry Andric     // Be conservative with inline asm.
18010b57cec5SDimitry Andric     if (!U.KnownAlignment)
18020b57cec5SDimitry Andric       MaxOffs -= 2;
18030b57cec5SDimitry Andric 
18040b57cec5SDimitry Andric     // FIXME: Check if offset is multiple of scale if scale is not 4.
18050b57cec5SDimitry Andric     if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
18060b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Shrink: " << *U.MI);
18070b57cec5SDimitry Andric       U.MI->setDesc(TII->get(NewOpc));
18080b57cec5SDimitry Andric       MachineBasicBlock *MBB = U.MI->getParent();
18090b57cec5SDimitry Andric       BBUtils->adjustBBSize(MBB, -2);
18100b57cec5SDimitry Andric       BBUtils->adjustBBOffsetsAfter(MBB);
18110b57cec5SDimitry Andric       ++NumT2CPShrunk;
18120b57cec5SDimitry Andric       MadeChange = true;
18130b57cec5SDimitry Andric     }
18140b57cec5SDimitry Andric   }
18150b57cec5SDimitry Andric 
18160b57cec5SDimitry Andric   return MadeChange;
18170b57cec5SDimitry Andric }
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric 
18208bcb0991SDimitry Andric bool ARMConstantIslands::optimizeThumb2Branches() {
18218bcb0991SDimitry Andric 
18228bcb0991SDimitry Andric   auto TryShrinkBranch = [this](ImmBranch &Br) {
18230b57cec5SDimitry Andric     unsigned Opcode = Br.MI->getOpcode();
18240b57cec5SDimitry Andric     unsigned NewOpc = 0;
18250b57cec5SDimitry Andric     unsigned Scale = 1;
18260b57cec5SDimitry Andric     unsigned Bits = 0;
18270b57cec5SDimitry Andric     switch (Opcode) {
18280b57cec5SDimitry Andric     default: break;
18290b57cec5SDimitry Andric     case ARM::t2B:
18300b57cec5SDimitry Andric       NewOpc = ARM::tB;
18310b57cec5SDimitry Andric       Bits = 11;
18320b57cec5SDimitry Andric       Scale = 2;
18330b57cec5SDimitry Andric       break;
18340b57cec5SDimitry Andric     case ARM::t2Bcc:
18350b57cec5SDimitry Andric       NewOpc = ARM::tBcc;
18360b57cec5SDimitry Andric       Bits = 8;
18370b57cec5SDimitry Andric       Scale = 2;
18380b57cec5SDimitry Andric       break;
18390b57cec5SDimitry Andric     }
18400b57cec5SDimitry Andric     if (NewOpc) {
18410b57cec5SDimitry Andric       unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
18420b57cec5SDimitry Andric       MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
18430b57cec5SDimitry Andric       if (BBUtils->isBBInRange(Br.MI, DestBB, MaxOffs)) {
18440b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
18450b57cec5SDimitry Andric         Br.MI->setDesc(TII->get(NewOpc));
18460b57cec5SDimitry Andric         MachineBasicBlock *MBB = Br.MI->getParent();
18470b57cec5SDimitry Andric         BBUtils->adjustBBSize(MBB, -2);
18480b57cec5SDimitry Andric         BBUtils->adjustBBOffsetsAfter(MBB);
18490b57cec5SDimitry Andric         ++NumT2BrShrunk;
18508bcb0991SDimitry Andric         return true;
18510b57cec5SDimitry Andric       }
18520b57cec5SDimitry Andric     }
18538bcb0991SDimitry Andric     return false;
18548bcb0991SDimitry Andric   };
18550b57cec5SDimitry Andric 
18568bcb0991SDimitry Andric   struct ImmCompare {
18578bcb0991SDimitry Andric     MachineInstr* MI = nullptr;
18588bcb0991SDimitry Andric     unsigned NewOpc = 0;
18598bcb0991SDimitry Andric   };
18608bcb0991SDimitry Andric 
18618bcb0991SDimitry Andric   auto FindCmpForCBZ = [this](ImmBranch &Br, ImmCompare &ImmCmp,
18628bcb0991SDimitry Andric                               MachineBasicBlock *DestBB) {
18638bcb0991SDimitry Andric     ImmCmp.MI = nullptr;
18648bcb0991SDimitry Andric     ImmCmp.NewOpc = 0;
18650b57cec5SDimitry Andric 
18660b57cec5SDimitry Andric     // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
18670b57cec5SDimitry Andric     // so this transformation is not safe.
18680b57cec5SDimitry Andric     if (!Br.MI->killsRegister(ARM::CPSR))
18698bcb0991SDimitry Andric       return false;
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric     unsigned PredReg = 0;
18728bcb0991SDimitry Andric     unsigned NewOpc = 0;
18730b57cec5SDimitry Andric     ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);
18740b57cec5SDimitry Andric     if (Pred == ARMCC::EQ)
18750b57cec5SDimitry Andric       NewOpc = ARM::tCBZ;
18760b57cec5SDimitry Andric     else if (Pred == ARMCC::NE)
18770b57cec5SDimitry Andric       NewOpc = ARM::tCBNZ;
18788bcb0991SDimitry Andric     else
18798bcb0991SDimitry Andric       return false;
18808bcb0991SDimitry Andric 
18810b57cec5SDimitry Andric     // Check if the distance is within 126. Subtract starting offset by 2
18820b57cec5SDimitry Andric     // because the cmp will be eliminated.
18830b57cec5SDimitry Andric     unsigned BrOffset = BBUtils->getOffsetOf(Br.MI) + 4 - 2;
18840b57cec5SDimitry Andric     BBInfoVector &BBInfo = BBUtils->getBBInfo();
18850b57cec5SDimitry Andric     unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
18860b57cec5SDimitry Andric     if (BrOffset >= DestOffset || (DestOffset - BrOffset) > 126)
18878bcb0991SDimitry Andric       return false;
18880b57cec5SDimitry Andric 
18890b57cec5SDimitry Andric     // Search backwards to find a tCMPi8
18900b57cec5SDimitry Andric     auto *TRI = STI->getRegisterInfo();
18910b57cec5SDimitry Andric     MachineInstr *CmpMI = findCMPToFoldIntoCBZ(Br.MI, TRI);
18920b57cec5SDimitry Andric     if (!CmpMI || CmpMI->getOpcode() != ARM::tCMPi8)
18938bcb0991SDimitry Andric       return false;
18948bcb0991SDimitry Andric 
18958bcb0991SDimitry Andric     ImmCmp.MI = CmpMI;
18968bcb0991SDimitry Andric     ImmCmp.NewOpc = NewOpc;
18978bcb0991SDimitry Andric     return true;
18988bcb0991SDimitry Andric   };
18998bcb0991SDimitry Andric 
19008bcb0991SDimitry Andric   auto TryConvertToLE = [this](ImmBranch &Br, ImmCompare &Cmp) {
19018bcb0991SDimitry Andric     if (Br.MI->getOpcode() != ARM::t2Bcc || !STI->hasLOB() ||
19028bcb0991SDimitry Andric         STI->hasMinSize())
19038bcb0991SDimitry Andric       return false;
19048bcb0991SDimitry Andric 
19058bcb0991SDimitry Andric     MachineBasicBlock *MBB = Br.MI->getParent();
19068bcb0991SDimitry Andric     MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
19078bcb0991SDimitry Andric     if (BBUtils->getOffsetOf(MBB) < BBUtils->getOffsetOf(DestBB) ||
19088bcb0991SDimitry Andric         !BBUtils->isBBInRange(Br.MI, DestBB, 4094))
19098bcb0991SDimitry Andric       return false;
19108bcb0991SDimitry Andric 
19118bcb0991SDimitry Andric     if (!DT->dominates(DestBB, MBB))
19128bcb0991SDimitry Andric       return false;
19138bcb0991SDimitry Andric 
19148bcb0991SDimitry Andric     // We queried for the CBN?Z opcode based upon the 'ExitBB', the opposite
19158bcb0991SDimitry Andric     // target of Br. So now we need to reverse the condition.
19168bcb0991SDimitry Andric     Cmp.NewOpc = Cmp.NewOpc == ARM::tCBZ ? ARM::tCBNZ : ARM::tCBZ;
19178bcb0991SDimitry Andric 
19188bcb0991SDimitry Andric     MachineInstrBuilder MIB = BuildMI(*MBB, Br.MI, Br.MI->getDebugLoc(),
19198bcb0991SDimitry Andric                                       TII->get(ARM::t2LE));
1920*480093f4SDimitry Andric     // Swapped a t2Bcc for a t2LE, so no need to update the size of the block.
19218bcb0991SDimitry Andric     MIB.add(Br.MI->getOperand(0));
19228bcb0991SDimitry Andric     Br.MI->eraseFromParent();
19238bcb0991SDimitry Andric     Br.MI = MIB;
19248bcb0991SDimitry Andric     ++NumLEInserted;
19258bcb0991SDimitry Andric     return true;
19268bcb0991SDimitry Andric   };
19278bcb0991SDimitry Andric 
19288bcb0991SDimitry Andric   bool MadeChange = false;
19298bcb0991SDimitry Andric 
19308bcb0991SDimitry Andric   // The order in which branches appear in ImmBranches is approximately their
19318bcb0991SDimitry Andric   // order within the function body. By visiting later branches first, we reduce
19328bcb0991SDimitry Andric   // the distance between earlier forward branches and their targets, making it
19338bcb0991SDimitry Andric   // more likely that the cbn?z optimization, which can only apply to forward
19348bcb0991SDimitry Andric   // branches, will succeed.
19358bcb0991SDimitry Andric   for (ImmBranch &Br : reverse(ImmBranches)) {
19368bcb0991SDimitry Andric     MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
19378bcb0991SDimitry Andric     MachineBasicBlock *MBB = Br.MI->getParent();
19388bcb0991SDimitry Andric     MachineBasicBlock *ExitBB = &MBB->back() == Br.MI ?
19398bcb0991SDimitry Andric       MBB->getFallThrough() :
19408bcb0991SDimitry Andric       MBB->back().getOperand(0).getMBB();
19418bcb0991SDimitry Andric 
19428bcb0991SDimitry Andric     ImmCompare Cmp;
19438bcb0991SDimitry Andric     if (FindCmpForCBZ(Br, Cmp, ExitBB) && TryConvertToLE(Br, Cmp)) {
19448bcb0991SDimitry Andric       DestBB = ExitBB;
19458bcb0991SDimitry Andric       MadeChange = true;
19468bcb0991SDimitry Andric     } else {
19478bcb0991SDimitry Andric       FindCmpForCBZ(Br, Cmp, DestBB);
19488bcb0991SDimitry Andric       MadeChange |= TryShrinkBranch(Br);
19498bcb0991SDimitry Andric     }
19508bcb0991SDimitry Andric 
19518bcb0991SDimitry Andric     unsigned Opcode = Br.MI->getOpcode();
19528bcb0991SDimitry Andric     if ((Opcode != ARM::tBcc && Opcode != ARM::t2LE) || !Cmp.NewOpc)
19530b57cec5SDimitry Andric       continue;
19540b57cec5SDimitry Andric 
19558bcb0991SDimitry Andric     Register Reg = Cmp.MI->getOperand(0).getReg();
19560b57cec5SDimitry Andric 
19570b57cec5SDimitry Andric     // Check for Kill flags on Reg. If they are present remove them and set kill
19580b57cec5SDimitry Andric     // on the new CBZ.
19598bcb0991SDimitry Andric     auto *TRI = STI->getRegisterInfo();
19600b57cec5SDimitry Andric     MachineBasicBlock::iterator KillMI = Br.MI;
19610b57cec5SDimitry Andric     bool RegKilled = false;
19620b57cec5SDimitry Andric     do {
19630b57cec5SDimitry Andric       --KillMI;
19640b57cec5SDimitry Andric       if (KillMI->killsRegister(Reg, TRI)) {
19650b57cec5SDimitry Andric         KillMI->clearRegisterKills(Reg, TRI);
19660b57cec5SDimitry Andric         RegKilled = true;
19670b57cec5SDimitry Andric         break;
19680b57cec5SDimitry Andric       }
19698bcb0991SDimitry Andric     } while (KillMI != Cmp.MI);
19700b57cec5SDimitry Andric 
19710b57cec5SDimitry Andric     // Create the new CBZ/CBNZ
19728bcb0991SDimitry Andric     LLVM_DEBUG(dbgs() << "Fold: " << *Cmp.MI << " and: " << *Br.MI);
19730b57cec5SDimitry Andric     MachineInstr *NewBR =
19748bcb0991SDimitry Andric         BuildMI(*MBB, Br.MI, Br.MI->getDebugLoc(), TII->get(Cmp.NewOpc))
19750b57cec5SDimitry Andric             .addReg(Reg, getKillRegState(RegKilled))
19760b57cec5SDimitry Andric             .addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
19778bcb0991SDimitry Andric 
19788bcb0991SDimitry Andric     Cmp.MI->eraseFromParent();
19798bcb0991SDimitry Andric 
19808bcb0991SDimitry Andric     if (Br.MI->getOpcode() == ARM::tBcc) {
19810b57cec5SDimitry Andric       Br.MI->eraseFromParent();
19820b57cec5SDimitry Andric       Br.MI = NewBR;
1983*480093f4SDimitry Andric       BBUtils->adjustBBSize(MBB, -2);
1984*480093f4SDimitry Andric     } else if (MBB->back().getOpcode() != ARM::t2LE) {
1985*480093f4SDimitry Andric       // An LE has been generated, but it's not the terminator - that is an
1986*480093f4SDimitry Andric       // unconditional branch. However, the logic has now been reversed with the
1987*480093f4SDimitry Andric       // CBN?Z being the conditional branch and the LE being the unconditional
1988*480093f4SDimitry Andric       // branch. So this means we can remove the redundant unconditional branch
1989*480093f4SDimitry Andric       // at the end of the block.
19908bcb0991SDimitry Andric       MachineInstr *LastMI = &MBB->back();
1991*480093f4SDimitry Andric       BBUtils->adjustBBSize(MBB, -LastMI->getDesc().getSize());
19928bcb0991SDimitry Andric       LastMI->eraseFromParent();
19938bcb0991SDimitry Andric     }
19940b57cec5SDimitry Andric     BBUtils->adjustBBOffsetsAfter(MBB);
19950b57cec5SDimitry Andric     ++NumCBZ;
19960b57cec5SDimitry Andric     MadeChange = true;
19970b57cec5SDimitry Andric   }
19980b57cec5SDimitry Andric 
19990b57cec5SDimitry Andric   return MadeChange;
20000b57cec5SDimitry Andric }
20010b57cec5SDimitry Andric 
20020b57cec5SDimitry Andric static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
20030b57cec5SDimitry Andric                               unsigned BaseReg) {
20040b57cec5SDimitry Andric   if (I.getOpcode() != ARM::t2ADDrs)
20050b57cec5SDimitry Andric     return false;
20060b57cec5SDimitry Andric 
20070b57cec5SDimitry Andric   if (I.getOperand(0).getReg() != EntryReg)
20080b57cec5SDimitry Andric     return false;
20090b57cec5SDimitry Andric 
20100b57cec5SDimitry Andric   if (I.getOperand(1).getReg() != BaseReg)
20110b57cec5SDimitry Andric     return false;
20120b57cec5SDimitry Andric 
20130b57cec5SDimitry Andric   // FIXME: what about CC and IdxReg?
20140b57cec5SDimitry Andric   return true;
20150b57cec5SDimitry Andric }
20160b57cec5SDimitry Andric 
20170b57cec5SDimitry Andric /// While trying to form a TBB/TBH instruction, we may (if the table
20180b57cec5SDimitry Andric /// doesn't immediately follow the BR_JT) need access to the start of the
20190b57cec5SDimitry Andric /// jump-table. We know one instruction that produces such a register; this
20200b57cec5SDimitry Andric /// function works out whether that definition can be preserved to the BR_JT,
20210b57cec5SDimitry Andric /// possibly by removing an intervening addition (which is usually needed to
20220b57cec5SDimitry Andric /// calculate the actual entry to jump to).
20230b57cec5SDimitry Andric bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
20240b57cec5SDimitry Andric                                               MachineInstr *LEAMI,
20250b57cec5SDimitry Andric                                               unsigned &DeadSize,
20260b57cec5SDimitry Andric                                               bool &CanDeleteLEA,
20270b57cec5SDimitry Andric                                               bool &BaseRegKill) {
20280b57cec5SDimitry Andric   if (JumpMI->getParent() != LEAMI->getParent())
20290b57cec5SDimitry Andric     return false;
20300b57cec5SDimitry Andric 
20310b57cec5SDimitry Andric   // Now we hope that we have at least these instructions in the basic block:
20320b57cec5SDimitry Andric   //     BaseReg = t2LEA ...
20330b57cec5SDimitry Andric   //     [...]
20340b57cec5SDimitry Andric   //     EntryReg = t2ADDrs BaseReg, ...
20350b57cec5SDimitry Andric   //     [...]
20360b57cec5SDimitry Andric   //     t2BR_JT EntryReg
20370b57cec5SDimitry Andric   //
20380b57cec5SDimitry Andric   // We have to be very conservative about what we recognise here though. The
20390b57cec5SDimitry Andric   // main perturbing factors to watch out for are:
20400b57cec5SDimitry Andric   //    + Spills at any point in the chain: not direct problems but we would
20410b57cec5SDimitry Andric   //      expect a blocking Def of the spilled register so in practice what we
20420b57cec5SDimitry Andric   //      can do is limited.
20430b57cec5SDimitry Andric   //    + EntryReg == BaseReg: this is the one situation we should allow a Def
20440b57cec5SDimitry Andric   //      of BaseReg, but only if the t2ADDrs can be removed.
20450b57cec5SDimitry Andric   //    + Some instruction other than t2ADDrs computing the entry. Not seen in
20460b57cec5SDimitry Andric   //      the wild, but we should be careful.
20478bcb0991SDimitry Andric   Register EntryReg = JumpMI->getOperand(0).getReg();
20488bcb0991SDimitry Andric   Register BaseReg = LEAMI->getOperand(0).getReg();
20490b57cec5SDimitry Andric 
20500b57cec5SDimitry Andric   CanDeleteLEA = true;
20510b57cec5SDimitry Andric   BaseRegKill = false;
20520b57cec5SDimitry Andric   MachineInstr *RemovableAdd = nullptr;
20530b57cec5SDimitry Andric   MachineBasicBlock::iterator I(LEAMI);
20540b57cec5SDimitry Andric   for (++I; &*I != JumpMI; ++I) {
20550b57cec5SDimitry Andric     if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
20560b57cec5SDimitry Andric       RemovableAdd = &*I;
20570b57cec5SDimitry Andric       break;
20580b57cec5SDimitry Andric     }
20590b57cec5SDimitry Andric 
20600b57cec5SDimitry Andric     for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
20610b57cec5SDimitry Andric       const MachineOperand &MO = I->getOperand(K);
20620b57cec5SDimitry Andric       if (!MO.isReg() || !MO.getReg())
20630b57cec5SDimitry Andric         continue;
20640b57cec5SDimitry Andric       if (MO.isDef() && MO.getReg() == BaseReg)
20650b57cec5SDimitry Andric         return false;
20660b57cec5SDimitry Andric       if (MO.isUse() && MO.getReg() == BaseReg) {
20670b57cec5SDimitry Andric         BaseRegKill = BaseRegKill || MO.isKill();
20680b57cec5SDimitry Andric         CanDeleteLEA = false;
20690b57cec5SDimitry Andric       }
20700b57cec5SDimitry Andric     }
20710b57cec5SDimitry Andric   }
20720b57cec5SDimitry Andric 
20730b57cec5SDimitry Andric   if (!RemovableAdd)
20740b57cec5SDimitry Andric     return true;
20750b57cec5SDimitry Andric 
20760b57cec5SDimitry Andric   // Check the add really is removable, and that nothing else in the block
20770b57cec5SDimitry Andric   // clobbers BaseReg.
20780b57cec5SDimitry Andric   for (++I; &*I != JumpMI; ++I) {
20790b57cec5SDimitry Andric     for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
20800b57cec5SDimitry Andric       const MachineOperand &MO = I->getOperand(K);
20810b57cec5SDimitry Andric       if (!MO.isReg() || !MO.getReg())
20820b57cec5SDimitry Andric         continue;
20830b57cec5SDimitry Andric       if (MO.isDef() && MO.getReg() == BaseReg)
20840b57cec5SDimitry Andric         return false;
20850b57cec5SDimitry Andric       if (MO.isUse() && MO.getReg() == EntryReg)
20860b57cec5SDimitry Andric         RemovableAdd = nullptr;
20870b57cec5SDimitry Andric     }
20880b57cec5SDimitry Andric   }
20890b57cec5SDimitry Andric 
20900b57cec5SDimitry Andric   if (RemovableAdd) {
20910b57cec5SDimitry Andric     RemovableAdd->eraseFromParent();
20920b57cec5SDimitry Andric     DeadSize += isThumb2 ? 4 : 2;
20930b57cec5SDimitry Andric   } else if (BaseReg == EntryReg) {
20940b57cec5SDimitry Andric     // The add wasn't removable, but clobbered the base for the TBB. So we can't
20950b57cec5SDimitry Andric     // preserve it.
20960b57cec5SDimitry Andric     return false;
20970b57cec5SDimitry Andric   }
20980b57cec5SDimitry Andric 
20990b57cec5SDimitry Andric   // We reached the end of the block without seeing another definition of
21000b57cec5SDimitry Andric   // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
21010b57cec5SDimitry Andric   // used in the TBB/TBH if necessary.
21020b57cec5SDimitry Andric   return true;
21030b57cec5SDimitry Andric }
21040b57cec5SDimitry Andric 
21050b57cec5SDimitry Andric /// Returns whether CPEMI is the first instruction in the block
21060b57cec5SDimitry Andric /// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
21070b57cec5SDimitry Andric /// we can switch the first register to PC and usually remove the address
21080b57cec5SDimitry Andric /// calculation that preceded it.
21090b57cec5SDimitry Andric static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {
21100b57cec5SDimitry Andric   MachineFunction::iterator MBB = JTMI->getParent()->getIterator();
21110b57cec5SDimitry Andric   MachineFunction *MF = MBB->getParent();
21120b57cec5SDimitry Andric   ++MBB;
21130b57cec5SDimitry Andric 
21140b57cec5SDimitry Andric   return MBB != MF->end() && MBB->begin() != MBB->end() &&
21150b57cec5SDimitry Andric          &*MBB->begin() == CPEMI;
21160b57cec5SDimitry Andric }
21170b57cec5SDimitry Andric 
21180b57cec5SDimitry Andric static void RemoveDeadAddBetweenLEAAndJT(MachineInstr *LEAMI,
21190b57cec5SDimitry Andric                                          MachineInstr *JumpMI,
21200b57cec5SDimitry Andric                                          unsigned &DeadSize) {
21210b57cec5SDimitry Andric   // Remove a dead add between the LEA and JT, which used to compute EntryReg,
21220b57cec5SDimitry Andric   // but the JT now uses PC. Finds the last ADD (if any) that def's EntryReg
21230b57cec5SDimitry Andric   // and is not clobbered / used.
21240b57cec5SDimitry Andric   MachineInstr *RemovableAdd = nullptr;
21258bcb0991SDimitry Andric   Register EntryReg = JumpMI->getOperand(0).getReg();
21260b57cec5SDimitry Andric 
21270b57cec5SDimitry Andric   // Find the last ADD to set EntryReg
21280b57cec5SDimitry Andric   MachineBasicBlock::iterator I(LEAMI);
21290b57cec5SDimitry Andric   for (++I; &*I != JumpMI; ++I) {
21300b57cec5SDimitry Andric     if (I->getOpcode() == ARM::t2ADDrs && I->getOperand(0).getReg() == EntryReg)
21310b57cec5SDimitry Andric       RemovableAdd = &*I;
21320b57cec5SDimitry Andric   }
21330b57cec5SDimitry Andric 
21340b57cec5SDimitry Andric   if (!RemovableAdd)
21350b57cec5SDimitry Andric     return;
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric   // Ensure EntryReg is not clobbered or used.
21380b57cec5SDimitry Andric   MachineBasicBlock::iterator J(RemovableAdd);
21390b57cec5SDimitry Andric   for (++J; &*J != JumpMI; ++J) {
21400b57cec5SDimitry Andric     for (unsigned K = 0, E = J->getNumOperands(); K != E; ++K) {
21410b57cec5SDimitry Andric       const MachineOperand &MO = J->getOperand(K);
21420b57cec5SDimitry Andric       if (!MO.isReg() || !MO.getReg())
21430b57cec5SDimitry Andric         continue;
21440b57cec5SDimitry Andric       if (MO.isDef() && MO.getReg() == EntryReg)
21450b57cec5SDimitry Andric         return;
21460b57cec5SDimitry Andric       if (MO.isUse() && MO.getReg() == EntryReg)
21470b57cec5SDimitry Andric         return;
21480b57cec5SDimitry Andric     }
21490b57cec5SDimitry Andric   }
21500b57cec5SDimitry Andric 
21510b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Removing Dead Add: " << *RemovableAdd);
21520b57cec5SDimitry Andric   RemovableAdd->eraseFromParent();
21530b57cec5SDimitry Andric   DeadSize += 4;
21540b57cec5SDimitry Andric }
21550b57cec5SDimitry Andric 
21560b57cec5SDimitry Andric /// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
21570b57cec5SDimitry Andric /// jumptables when it's possible.
21580b57cec5SDimitry Andric bool ARMConstantIslands::optimizeThumb2JumpTables() {
21590b57cec5SDimitry Andric   bool MadeChange = false;
21600b57cec5SDimitry Andric 
21610b57cec5SDimitry Andric   // FIXME: After the tables are shrunk, can we get rid some of the
21620b57cec5SDimitry Andric   // constantpool tables?
21630b57cec5SDimitry Andric   MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
21640b57cec5SDimitry Andric   if (!MJTI) return false;
21650b57cec5SDimitry Andric 
21660b57cec5SDimitry Andric   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
21670b57cec5SDimitry Andric   for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
21680b57cec5SDimitry Andric     MachineInstr *MI = T2JumpTables[i];
21690b57cec5SDimitry Andric     const MCInstrDesc &MCID = MI->getDesc();
21700b57cec5SDimitry Andric     unsigned NumOps = MCID.getNumOperands();
21710b57cec5SDimitry Andric     unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
21720b57cec5SDimitry Andric     MachineOperand JTOP = MI->getOperand(JTOpIdx);
21730b57cec5SDimitry Andric     unsigned JTI = JTOP.getIndex();
21740b57cec5SDimitry Andric     assert(JTI < JT.size());
21750b57cec5SDimitry Andric 
21760b57cec5SDimitry Andric     bool ByteOk = true;
21770b57cec5SDimitry Andric     bool HalfWordOk = true;
21780b57cec5SDimitry Andric     unsigned JTOffset = BBUtils->getOffsetOf(MI) + 4;
21790b57cec5SDimitry Andric     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
21800b57cec5SDimitry Andric     BBInfoVector &BBInfo = BBUtils->getBBInfo();
21810b57cec5SDimitry Andric     for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
21820b57cec5SDimitry Andric       MachineBasicBlock *MBB = JTBBs[j];
21830b57cec5SDimitry Andric       unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
21840b57cec5SDimitry Andric       // Negative offset is not ok. FIXME: We should change BB layout to make
21850b57cec5SDimitry Andric       // sure all the branches are forward.
21860b57cec5SDimitry Andric       if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
21870b57cec5SDimitry Andric         ByteOk = false;
21880b57cec5SDimitry Andric       unsigned TBHLimit = ((1<<16)-1)*2;
21890b57cec5SDimitry Andric       if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
21900b57cec5SDimitry Andric         HalfWordOk = false;
21910b57cec5SDimitry Andric       if (!ByteOk && !HalfWordOk)
21920b57cec5SDimitry Andric         break;
21930b57cec5SDimitry Andric     }
21940b57cec5SDimitry Andric 
21950b57cec5SDimitry Andric     if (!ByteOk && !HalfWordOk)
21960b57cec5SDimitry Andric       continue;
21970b57cec5SDimitry Andric 
21980b57cec5SDimitry Andric     CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
21990b57cec5SDimitry Andric     MachineBasicBlock *MBB = MI->getParent();
22000b57cec5SDimitry Andric     if (!MI->getOperand(0).isKill()) // FIXME: needed now?
22010b57cec5SDimitry Andric       continue;
22020b57cec5SDimitry Andric 
22030b57cec5SDimitry Andric     unsigned DeadSize = 0;
22040b57cec5SDimitry Andric     bool CanDeleteLEA = false;
22050b57cec5SDimitry Andric     bool BaseRegKill = false;
22060b57cec5SDimitry Andric 
22070b57cec5SDimitry Andric     unsigned IdxReg = ~0U;
22080b57cec5SDimitry Andric     bool IdxRegKill = true;
22090b57cec5SDimitry Andric     if (isThumb2) {
22100b57cec5SDimitry Andric       IdxReg = MI->getOperand(1).getReg();
22110b57cec5SDimitry Andric       IdxRegKill = MI->getOperand(1).isKill();
22120b57cec5SDimitry Andric 
22130b57cec5SDimitry Andric       bool PreservedBaseReg =
22140b57cec5SDimitry Andric         preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
22150b57cec5SDimitry Andric       if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
22160b57cec5SDimitry Andric         continue;
22170b57cec5SDimitry Andric     } else {
22180b57cec5SDimitry Andric       // We're in thumb-1 mode, so we must have something like:
22190b57cec5SDimitry Andric       //   %idx = tLSLri %idx, 2
22200b57cec5SDimitry Andric       //   %base = tLEApcrelJT
22210b57cec5SDimitry Andric       //   %t = tLDRr %base, %idx
22228bcb0991SDimitry Andric       Register BaseReg = User.MI->getOperand(0).getReg();
22230b57cec5SDimitry Andric 
22240b57cec5SDimitry Andric       if (User.MI->getIterator() == User.MI->getParent()->begin())
22250b57cec5SDimitry Andric         continue;
22260b57cec5SDimitry Andric       MachineInstr *Shift = User.MI->getPrevNode();
22270b57cec5SDimitry Andric       if (Shift->getOpcode() != ARM::tLSLri ||
22280b57cec5SDimitry Andric           Shift->getOperand(3).getImm() != 2 ||
22290b57cec5SDimitry Andric           !Shift->getOperand(2).isKill())
22300b57cec5SDimitry Andric         continue;
22310b57cec5SDimitry Andric       IdxReg = Shift->getOperand(2).getReg();
22328bcb0991SDimitry Andric       Register ShiftedIdxReg = Shift->getOperand(0).getReg();
22330b57cec5SDimitry Andric 
22340b57cec5SDimitry Andric       // It's important that IdxReg is live until the actual TBB/TBH. Most of
22350b57cec5SDimitry Andric       // the range is checked later, but the LEA might still clobber it and not
22360b57cec5SDimitry Andric       // actually get removed.
22370b57cec5SDimitry Andric       if (BaseReg == IdxReg && !jumpTableFollowsTB(MI, User.CPEMI))
22380b57cec5SDimitry Andric         continue;
22390b57cec5SDimitry Andric 
22400b57cec5SDimitry Andric       MachineInstr *Load = User.MI->getNextNode();
22410b57cec5SDimitry Andric       if (Load->getOpcode() != ARM::tLDRr)
22420b57cec5SDimitry Andric         continue;
22430b57cec5SDimitry Andric       if (Load->getOperand(1).getReg() != BaseReg ||
22440b57cec5SDimitry Andric           Load->getOperand(2).getReg() != ShiftedIdxReg ||
22450b57cec5SDimitry Andric           !Load->getOperand(2).isKill())
22460b57cec5SDimitry Andric         continue;
22470b57cec5SDimitry Andric 
22480b57cec5SDimitry Andric       // If we're in PIC mode, there should be another ADD following.
22490b57cec5SDimitry Andric       auto *TRI = STI->getRegisterInfo();
22500b57cec5SDimitry Andric 
22510b57cec5SDimitry Andric       // %base cannot be redefined after the load as it will appear before
22520b57cec5SDimitry Andric       // TBB/TBH like:
22530b57cec5SDimitry Andric       //      %base =
22540b57cec5SDimitry Andric       //      %base =
22550b57cec5SDimitry Andric       //      tBB %base, %idx
22560b57cec5SDimitry Andric       if (registerDefinedBetween(BaseReg, Load->getNextNode(), MBB->end(), TRI))
22570b57cec5SDimitry Andric         continue;
22580b57cec5SDimitry Andric 
22590b57cec5SDimitry Andric       if (isPositionIndependentOrROPI) {
22600b57cec5SDimitry Andric         MachineInstr *Add = Load->getNextNode();
22610b57cec5SDimitry Andric         if (Add->getOpcode() != ARM::tADDrr ||
22620b57cec5SDimitry Andric             Add->getOperand(2).getReg() != BaseReg ||
22630b57cec5SDimitry Andric             Add->getOperand(3).getReg() != Load->getOperand(0).getReg() ||
22640b57cec5SDimitry Andric             !Add->getOperand(3).isKill())
22650b57cec5SDimitry Andric           continue;
22660b57cec5SDimitry Andric         if (Add->getOperand(0).getReg() != MI->getOperand(0).getReg())
22670b57cec5SDimitry Andric           continue;
22680b57cec5SDimitry Andric         if (registerDefinedBetween(IdxReg, Add->getNextNode(), MI, TRI))
22690b57cec5SDimitry Andric           // IdxReg gets redefined in the middle of the sequence.
22700b57cec5SDimitry Andric           continue;
22710b57cec5SDimitry Andric         Add->eraseFromParent();
22720b57cec5SDimitry Andric         DeadSize += 2;
22730b57cec5SDimitry Andric       } else {
22740b57cec5SDimitry Andric         if (Load->getOperand(0).getReg() != MI->getOperand(0).getReg())
22750b57cec5SDimitry Andric           continue;
22760b57cec5SDimitry Andric         if (registerDefinedBetween(IdxReg, Load->getNextNode(), MI, TRI))
22770b57cec5SDimitry Andric           // IdxReg gets redefined in the middle of the sequence.
22780b57cec5SDimitry Andric           continue;
22790b57cec5SDimitry Andric       }
22800b57cec5SDimitry Andric 
22810b57cec5SDimitry Andric       // Now safe to delete the load and lsl. The LEA will be removed later.
22820b57cec5SDimitry Andric       CanDeleteLEA = true;
22830b57cec5SDimitry Andric       Shift->eraseFromParent();
22840b57cec5SDimitry Andric       Load->eraseFromParent();
22850b57cec5SDimitry Andric       DeadSize += 4;
22860b57cec5SDimitry Andric     }
22870b57cec5SDimitry Andric 
22880b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Shrink JT: " << *MI);
22890b57cec5SDimitry Andric     MachineInstr *CPEMI = User.CPEMI;
22900b57cec5SDimitry Andric     unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
22910b57cec5SDimitry Andric     if (!isThumb2)
22920b57cec5SDimitry Andric       Opc = ByteOk ? ARM::tTBB_JT : ARM::tTBH_JT;
22930b57cec5SDimitry Andric 
22940b57cec5SDimitry Andric     MachineBasicBlock::iterator MI_JT = MI;
22950b57cec5SDimitry Andric     MachineInstr *NewJTMI =
22960b57cec5SDimitry Andric         BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
22970b57cec5SDimitry Andric             .addReg(User.MI->getOperand(0).getReg(),
22980b57cec5SDimitry Andric                     getKillRegState(BaseRegKill))
22990b57cec5SDimitry Andric             .addReg(IdxReg, getKillRegState(IdxRegKill))
23000b57cec5SDimitry Andric             .addJumpTableIndex(JTI, JTOP.getTargetFlags())
23010b57cec5SDimitry Andric             .addImm(CPEMI->getOperand(0).getImm());
23020b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": " << *NewJTMI);
23030b57cec5SDimitry Andric 
23040b57cec5SDimitry Andric     unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
23050b57cec5SDimitry Andric     CPEMI->setDesc(TII->get(JTOpc));
23060b57cec5SDimitry Andric 
23070b57cec5SDimitry Andric     if (jumpTableFollowsTB(MI, User.CPEMI)) {
23080b57cec5SDimitry Andric       NewJTMI->getOperand(0).setReg(ARM::PC);
23090b57cec5SDimitry Andric       NewJTMI->getOperand(0).setIsKill(false);
23100b57cec5SDimitry Andric 
23110b57cec5SDimitry Andric       if (CanDeleteLEA) {
23120b57cec5SDimitry Andric         if (isThumb2)
23130b57cec5SDimitry Andric           RemoveDeadAddBetweenLEAAndJT(User.MI, MI, DeadSize);
23140b57cec5SDimitry Andric 
23150b57cec5SDimitry Andric         User.MI->eraseFromParent();
23160b57cec5SDimitry Andric         DeadSize += isThumb2 ? 4 : 2;
23170b57cec5SDimitry Andric 
23180b57cec5SDimitry Andric         // The LEA was eliminated, the TBB instruction becomes the only new user
23190b57cec5SDimitry Andric         // of the jump table.
23200b57cec5SDimitry Andric         User.MI = NewJTMI;
23210b57cec5SDimitry Andric         User.MaxDisp = 4;
23220b57cec5SDimitry Andric         User.NegOk = false;
23230b57cec5SDimitry Andric         User.IsSoImm = false;
23240b57cec5SDimitry Andric         User.KnownAlignment = false;
23250b57cec5SDimitry Andric       } else {
23260b57cec5SDimitry Andric         // The LEA couldn't be eliminated, so we must add another CPUser to
23270b57cec5SDimitry Andric         // record the TBB or TBH use.
23280b57cec5SDimitry Andric         int CPEntryIdx = JumpTableEntryIndices[JTI];
23290b57cec5SDimitry Andric         auto &CPEs = CPEntries[CPEntryIdx];
23300b57cec5SDimitry Andric         auto Entry =
23310b57cec5SDimitry Andric             find_if(CPEs, [&](CPEntry &E) { return E.CPEMI == User.CPEMI; });
23320b57cec5SDimitry Andric         ++Entry->RefCount;
23330b57cec5SDimitry Andric         CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
23340b57cec5SDimitry Andric       }
23350b57cec5SDimitry Andric     }
23360b57cec5SDimitry Andric 
23370b57cec5SDimitry Andric     unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI);
23380b57cec5SDimitry Andric     unsigned OrigSize = TII->getInstSizeInBytes(*MI);
23390b57cec5SDimitry Andric     MI->eraseFromParent();
23400b57cec5SDimitry Andric 
23410b57cec5SDimitry Andric     int Delta = OrigSize - NewSize + DeadSize;
23420b57cec5SDimitry Andric     BBInfo[MBB->getNumber()].Size -= Delta;
23430b57cec5SDimitry Andric     BBUtils->adjustBBOffsetsAfter(MBB);
23440b57cec5SDimitry Andric 
23450b57cec5SDimitry Andric     ++NumTBs;
23460b57cec5SDimitry Andric     MadeChange = true;
23470b57cec5SDimitry Andric   }
23480b57cec5SDimitry Andric 
23490b57cec5SDimitry Andric   return MadeChange;
23500b57cec5SDimitry Andric }
23510b57cec5SDimitry Andric 
23520b57cec5SDimitry Andric /// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
23530b57cec5SDimitry Andric /// jump tables always branch forwards, since that's what tbb and tbh need.
23540b57cec5SDimitry Andric bool ARMConstantIslands::reorderThumb2JumpTables() {
23550b57cec5SDimitry Andric   bool MadeChange = false;
23560b57cec5SDimitry Andric 
23570b57cec5SDimitry Andric   MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
23580b57cec5SDimitry Andric   if (!MJTI) return false;
23590b57cec5SDimitry Andric 
23600b57cec5SDimitry Andric   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
23610b57cec5SDimitry Andric   for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
23620b57cec5SDimitry Andric     MachineInstr *MI = T2JumpTables[i];
23630b57cec5SDimitry Andric     const MCInstrDesc &MCID = MI->getDesc();
23640b57cec5SDimitry Andric     unsigned NumOps = MCID.getNumOperands();
23650b57cec5SDimitry Andric     unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
23660b57cec5SDimitry Andric     MachineOperand JTOP = MI->getOperand(JTOpIdx);
23670b57cec5SDimitry Andric     unsigned JTI = JTOP.getIndex();
23680b57cec5SDimitry Andric     assert(JTI < JT.size());
23690b57cec5SDimitry Andric 
23700b57cec5SDimitry Andric     // We prefer if target blocks for the jump table come after the jump
23710b57cec5SDimitry Andric     // instruction so we can use TB[BH]. Loop through the target blocks
23720b57cec5SDimitry Andric     // and try to adjust them such that that's true.
23730b57cec5SDimitry Andric     int JTNumber = MI->getParent()->getNumber();
23740b57cec5SDimitry Andric     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
23750b57cec5SDimitry Andric     for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
23760b57cec5SDimitry Andric       MachineBasicBlock *MBB = JTBBs[j];
23770b57cec5SDimitry Andric       int DTNumber = MBB->getNumber();
23780b57cec5SDimitry Andric 
23790b57cec5SDimitry Andric       if (DTNumber < JTNumber) {
23800b57cec5SDimitry Andric         // The destination precedes the switch. Try to move the block forward
23810b57cec5SDimitry Andric         // so we have a positive offset.
23820b57cec5SDimitry Andric         MachineBasicBlock *NewBB =
23830b57cec5SDimitry Andric           adjustJTTargetBlockForward(MBB, MI->getParent());
23840b57cec5SDimitry Andric         if (NewBB)
23850b57cec5SDimitry Andric           MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
23860b57cec5SDimitry Andric         MadeChange = true;
23870b57cec5SDimitry Andric       }
23880b57cec5SDimitry Andric     }
23890b57cec5SDimitry Andric   }
23900b57cec5SDimitry Andric 
23910b57cec5SDimitry Andric   return MadeChange;
23920b57cec5SDimitry Andric }
23930b57cec5SDimitry Andric 
23940b57cec5SDimitry Andric MachineBasicBlock *ARMConstantIslands::
23950b57cec5SDimitry Andric adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
23960b57cec5SDimitry Andric   // If the destination block is terminated by an unconditional branch,
23970b57cec5SDimitry Andric   // try to move it; otherwise, create a new block following the jump
23980b57cec5SDimitry Andric   // table that branches back to the actual target. This is a very simple
23990b57cec5SDimitry Andric   // heuristic. FIXME: We can definitely improve it.
24000b57cec5SDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
24010b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
24020b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> CondPrior;
24030b57cec5SDimitry Andric   MachineFunction::iterator BBi = BB->getIterator();
24040b57cec5SDimitry Andric   MachineFunction::iterator OldPrior = std::prev(BBi);
24050b57cec5SDimitry Andric 
24060b57cec5SDimitry Andric   // If the block terminator isn't analyzable, don't try to move the block
24070b57cec5SDimitry Andric   bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond);
24080b57cec5SDimitry Andric 
24090b57cec5SDimitry Andric   // If the block ends in an unconditional branch, move it. The prior block
24100b57cec5SDimitry Andric   // has to have an analyzable terminator for us to move this one. Be paranoid
24110b57cec5SDimitry Andric   // and make sure we're not trying to move the entry block of the function.
24120b57cec5SDimitry Andric   if (!B && Cond.empty() && BB != &MF->front() &&
24130b57cec5SDimitry Andric       !TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
24140b57cec5SDimitry Andric     BB->moveAfter(JTBB);
24150b57cec5SDimitry Andric     OldPrior->updateTerminator();
24160b57cec5SDimitry Andric     BB->updateTerminator();
24170b57cec5SDimitry Andric     // Update numbering to account for the block being moved.
24180b57cec5SDimitry Andric     MF->RenumberBlocks();
24190b57cec5SDimitry Andric     ++NumJTMoved;
24200b57cec5SDimitry Andric     return nullptr;
24210b57cec5SDimitry Andric   }
24220b57cec5SDimitry Andric 
24230b57cec5SDimitry Andric   // Create a new MBB for the code after the jump BB.
24240b57cec5SDimitry Andric   MachineBasicBlock *NewBB =
24250b57cec5SDimitry Andric     MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
24260b57cec5SDimitry Andric   MachineFunction::iterator MBBI = ++JTBB->getIterator();
24270b57cec5SDimitry Andric   MF->insert(MBBI, NewBB);
24280b57cec5SDimitry Andric 
24298bcb0991SDimitry Andric   // Copy live-in information to new block.
24308bcb0991SDimitry Andric   for (const MachineBasicBlock::RegisterMaskPair &RegMaskPair : BB->liveins())
24318bcb0991SDimitry Andric     NewBB->addLiveIn(RegMaskPair);
24328bcb0991SDimitry Andric 
24330b57cec5SDimitry Andric   // Add an unconditional branch from NewBB to BB.
24340b57cec5SDimitry Andric   // There doesn't seem to be meaningful DebugInfo available; this doesn't
24350b57cec5SDimitry Andric   // correspond directly to anything in the source.
24360b57cec5SDimitry Andric   if (isThumb2)
24370b57cec5SDimitry Andric     BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B))
24380b57cec5SDimitry Andric         .addMBB(BB)
24390b57cec5SDimitry Andric         .add(predOps(ARMCC::AL));
24400b57cec5SDimitry Andric   else
24410b57cec5SDimitry Andric     BuildMI(NewBB, DebugLoc(), TII->get(ARM::tB))
24420b57cec5SDimitry Andric         .addMBB(BB)
24430b57cec5SDimitry Andric         .add(predOps(ARMCC::AL));
24440b57cec5SDimitry Andric 
24450b57cec5SDimitry Andric   // Update internal data structures to account for the newly inserted MBB.
24460b57cec5SDimitry Andric   MF->RenumberBlocks(NewBB);
24470b57cec5SDimitry Andric 
24480b57cec5SDimitry Andric   // Update the CFG.
24490b57cec5SDimitry Andric   NewBB->addSuccessor(BB);
24500b57cec5SDimitry Andric   JTBB->replaceSuccessor(BB, NewBB);
24510b57cec5SDimitry Andric 
24520b57cec5SDimitry Andric   ++NumJTInserted;
24530b57cec5SDimitry Andric   return NewBB;
24540b57cec5SDimitry Andric }
24550b57cec5SDimitry Andric 
24560b57cec5SDimitry Andric /// createARMConstantIslandPass - returns an instance of the constpool
24570b57cec5SDimitry Andric /// island pass.
24580b57cec5SDimitry Andric FunctionPass *llvm::createARMConstantIslandPass() {
24590b57cec5SDimitry Andric   return new ARMConstantIslands();
24600b57cec5SDimitry Andric }
24610b57cec5SDimitry Andric 
24620b57cec5SDimitry Andric INITIALIZE_PASS(ARMConstantIslands, "arm-cp-islands", ARM_CP_ISLANDS_OPT_NAME,
24630b57cec5SDimitry Andric                 false, false)
2464