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