1*065e0324SZi Xuan Wu //===- CSKYConstantIslandPass.cpp - Emit PC Relative loads ----------------===//
2*065e0324SZi Xuan Wu //
3*065e0324SZi Xuan Wu // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*065e0324SZi Xuan Wu // See https://llvm.org/LICENSE.txt for license information.
5*065e0324SZi Xuan Wu // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*065e0324SZi Xuan Wu //
7*065e0324SZi Xuan Wu //===----------------------------------------------------------------------===//
8*065e0324SZi Xuan Wu //
9*065e0324SZi Xuan Wu //
10*065e0324SZi Xuan Wu // Loading constants inline is expensive on CSKY and it's in general better
11*065e0324SZi Xuan Wu // to place the constant nearby in code space and then it can be loaded with a
12*065e0324SZi Xuan Wu // simple 16/32 bit load instruction like lrw.
13*065e0324SZi Xuan Wu //
14*065e0324SZi Xuan Wu // The constants can be not just numbers but addresses of functions and labels.
15*065e0324SZi Xuan Wu // This can be particularly helpful in static relocation mode for embedded
16*065e0324SZi Xuan Wu // non-linux targets.
17*065e0324SZi Xuan Wu //
18*065e0324SZi Xuan Wu //===----------------------------------------------------------------------===//
19*065e0324SZi Xuan Wu 
20*065e0324SZi Xuan Wu #include "CSKY.h"
21*065e0324SZi Xuan Wu #include "CSKYConstantPoolValue.h"
22*065e0324SZi Xuan Wu #include "CSKYMachineFunctionInfo.h"
23*065e0324SZi Xuan Wu #include "CSKYSubtarget.h"
24*065e0324SZi Xuan Wu #include "llvm/ADT/STLExtras.h"
25*065e0324SZi Xuan Wu #include "llvm/ADT/SmallSet.h"
26*065e0324SZi Xuan Wu #include "llvm/ADT/SmallVector.h"
27*065e0324SZi Xuan Wu #include "llvm/ADT/Statistic.h"
28*065e0324SZi Xuan Wu #include "llvm/ADT/StringRef.h"
29*065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineBasicBlock.h"
30*065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineConstantPool.h"
31*065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineDominators.h"
32*065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineFunction.h"
33*065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineFunctionPass.h"
34*065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineInstr.h"
35*065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineInstrBuilder.h"
36*065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineOperand.h"
37*065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineRegisterInfo.h"
38*065e0324SZi Xuan Wu #include "llvm/Config/llvm-config.h"
39*065e0324SZi Xuan Wu #include "llvm/IR/Constants.h"
40*065e0324SZi Xuan Wu #include "llvm/IR/DataLayout.h"
41*065e0324SZi Xuan Wu #include "llvm/IR/DebugLoc.h"
42*065e0324SZi Xuan Wu #include "llvm/IR/Function.h"
43*065e0324SZi Xuan Wu #include "llvm/IR/Type.h"
44*065e0324SZi Xuan Wu #include "llvm/Support/CommandLine.h"
45*065e0324SZi Xuan Wu #include "llvm/Support/Compiler.h"
46*065e0324SZi Xuan Wu #include "llvm/Support/Debug.h"
47*065e0324SZi Xuan Wu #include "llvm/Support/ErrorHandling.h"
48*065e0324SZi Xuan Wu #include "llvm/Support/Format.h"
49*065e0324SZi Xuan Wu #include "llvm/Support/MathExtras.h"
50*065e0324SZi Xuan Wu #include "llvm/Support/raw_ostream.h"
51*065e0324SZi Xuan Wu #include <algorithm>
52*065e0324SZi Xuan Wu #include <cassert>
53*065e0324SZi Xuan Wu #include <cstdint>
54*065e0324SZi Xuan Wu #include <iterator>
55*065e0324SZi Xuan Wu #include <vector>
56*065e0324SZi Xuan Wu 
57*065e0324SZi Xuan Wu using namespace llvm;
58*065e0324SZi Xuan Wu 
59*065e0324SZi Xuan Wu #define DEBUG_TYPE "CSKY-constant-islands"
60*065e0324SZi Xuan Wu 
61*065e0324SZi Xuan Wu STATISTIC(NumCPEs, "Number of constpool entries");
62*065e0324SZi Xuan Wu STATISTIC(NumSplit, "Number of uncond branches inserted");
63*065e0324SZi Xuan Wu STATISTIC(NumCBrFixed, "Number of cond branches fixed");
64*065e0324SZi Xuan Wu STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
65*065e0324SZi Xuan Wu 
66*065e0324SZi Xuan Wu namespace {
67*065e0324SZi Xuan Wu 
68*065e0324SZi Xuan Wu using Iter = MachineBasicBlock::iterator;
69*065e0324SZi Xuan Wu using ReverseIter = MachineBasicBlock::reverse_iterator;
70*065e0324SZi Xuan Wu 
71*065e0324SZi Xuan Wu /// CSKYConstantIslands - Due to limited PC-relative displacements, CSKY
72*065e0324SZi Xuan Wu /// requires constant pool entries to be scattered among the instructions
73*065e0324SZi Xuan Wu /// inside a function.  To do this, it completely ignores the normal LLVM
74*065e0324SZi Xuan Wu /// constant pool; instead, it places constants wherever it feels like with
75*065e0324SZi Xuan Wu /// special instructions.
76*065e0324SZi Xuan Wu ///
77*065e0324SZi Xuan Wu /// The terminology used in this pass includes:
78*065e0324SZi Xuan Wu ///   Islands - Clumps of constants placed in the function.
79*065e0324SZi Xuan Wu ///   Water   - Potential places where an island could be formed.
80*065e0324SZi Xuan Wu ///   CPE     - A constant pool entry that has been placed somewhere, which
81*065e0324SZi Xuan Wu ///             tracks a list of users.
82*065e0324SZi Xuan Wu 
83*065e0324SZi Xuan Wu class CSKYConstantIslands : public MachineFunctionPass {
84*065e0324SZi Xuan Wu   /// BasicBlockInfo - Information about the offset and size of a single
85*065e0324SZi Xuan Wu   /// basic block.
86*065e0324SZi Xuan Wu   struct BasicBlockInfo {
87*065e0324SZi Xuan Wu     /// Offset - Distance from the beginning of the function to the beginning
88*065e0324SZi Xuan Wu     /// of this basic block.
89*065e0324SZi Xuan Wu     ///
90*065e0324SZi Xuan Wu     /// Offsets are computed assuming worst case padding before an aligned
91*065e0324SZi Xuan Wu     /// block. This means that subtracting basic block offsets always gives a
92*065e0324SZi Xuan Wu     /// conservative estimate of the real distance which may be smaller.
93*065e0324SZi Xuan Wu     ///
94*065e0324SZi Xuan Wu     /// Because worst case padding is used, the computed offset of an aligned
95*065e0324SZi Xuan Wu     /// block may not actually be aligned.
96*065e0324SZi Xuan Wu     unsigned Offset = 0;
97*065e0324SZi Xuan Wu 
98*065e0324SZi Xuan Wu     /// Size - Size of the basic block in bytes.  If the block contains
99*065e0324SZi Xuan Wu     /// inline assembly, this is a worst case estimate.
100*065e0324SZi Xuan Wu     ///
101*065e0324SZi Xuan Wu     /// The size does not include any alignment padding whether from the
102*065e0324SZi Xuan Wu     /// beginning of the block, or from an aligned jump table at the end.
103*065e0324SZi Xuan Wu     unsigned Size = 0;
104*065e0324SZi Xuan Wu 
105*065e0324SZi Xuan Wu     BasicBlockInfo() = default;
106*065e0324SZi Xuan Wu 
107*065e0324SZi Xuan Wu     unsigned postOffset() const { return Offset + Size; }
108*065e0324SZi Xuan Wu   };
109*065e0324SZi Xuan Wu 
110*065e0324SZi Xuan Wu   std::vector<BasicBlockInfo> BBInfo;
111*065e0324SZi Xuan Wu 
112*065e0324SZi Xuan Wu   /// WaterList - A sorted list of basic blocks where islands could be placed
113*065e0324SZi Xuan Wu   /// (i.e. blocks that don't fall through to the following block, due
114*065e0324SZi Xuan Wu   /// to a return, unreachable, or unconditional branch).
115*065e0324SZi Xuan Wu   std::vector<MachineBasicBlock *> WaterList;
116*065e0324SZi Xuan Wu 
117*065e0324SZi Xuan Wu   /// NewWaterList - The subset of WaterList that was created since the
118*065e0324SZi Xuan Wu   /// previous iteration by inserting unconditional branches.
119*065e0324SZi Xuan Wu   SmallSet<MachineBasicBlock *, 4> NewWaterList;
120*065e0324SZi Xuan Wu 
121*065e0324SZi Xuan Wu   using water_iterator = std::vector<MachineBasicBlock *>::iterator;
122*065e0324SZi Xuan Wu 
123*065e0324SZi Xuan Wu   /// CPUser - One user of a constant pool, keeping the machine instruction
124*065e0324SZi Xuan Wu   /// pointer, the constant pool being referenced, and the max displacement
125*065e0324SZi Xuan Wu   /// allowed from the instruction to the CP.  The HighWaterMark records the
126*065e0324SZi Xuan Wu   /// highest basic block where a new CPEntry can be placed.  To ensure this
127*065e0324SZi Xuan Wu   /// pass terminates, the CP entries are initially placed at the end of the
128*065e0324SZi Xuan Wu   /// function and then move monotonically to lower addresses.  The
129*065e0324SZi Xuan Wu   /// exception to this rule is when the current CP entry for a particular
130*065e0324SZi Xuan Wu   /// CPUser is out of range, but there is another CP entry for the same
131*065e0324SZi Xuan Wu   /// constant value in range.  We want to use the existing in-range CP
132*065e0324SZi Xuan Wu   /// entry, but if it later moves out of range, the search for new water
133*065e0324SZi Xuan Wu   /// should resume where it left off.  The HighWaterMark is used to record
134*065e0324SZi Xuan Wu   /// that point.
135*065e0324SZi Xuan Wu   struct CPUser {
136*065e0324SZi Xuan Wu     MachineInstr *MI;
137*065e0324SZi Xuan Wu     MachineInstr *CPEMI;
138*065e0324SZi Xuan Wu     MachineBasicBlock *HighWaterMark;
139*065e0324SZi Xuan Wu 
140*065e0324SZi Xuan Wu   private:
141*065e0324SZi Xuan Wu     unsigned MaxDisp;
142*065e0324SZi Xuan Wu 
143*065e0324SZi Xuan Wu   public:
144*065e0324SZi Xuan Wu     bool NegOk;
145*065e0324SZi Xuan Wu 
146*065e0324SZi Xuan Wu     CPUser(MachineInstr *Mi, MachineInstr *Cpemi, unsigned Maxdisp, bool Neg)
147*065e0324SZi Xuan Wu         : MI(Mi), CPEMI(Cpemi), MaxDisp(Maxdisp), NegOk(Neg) {
148*065e0324SZi Xuan Wu       HighWaterMark = CPEMI->getParent();
149*065e0324SZi Xuan Wu     }
150*065e0324SZi Xuan Wu 
151*065e0324SZi Xuan Wu     /// getMaxDisp - Returns the maximum displacement supported by MI.
152*065e0324SZi Xuan Wu     unsigned getMaxDisp() const { return MaxDisp - 16; }
153*065e0324SZi Xuan Wu 
154*065e0324SZi Xuan Wu     void setMaxDisp(unsigned Val) { MaxDisp = Val; }
155*065e0324SZi Xuan Wu   };
156*065e0324SZi Xuan Wu 
157*065e0324SZi Xuan Wu   /// CPUsers - Keep track of all of the machine instructions that use various
158*065e0324SZi Xuan Wu   /// constant pools and their max displacement.
159*065e0324SZi Xuan Wu   std::vector<CPUser> CPUsers;
160*065e0324SZi Xuan Wu 
161*065e0324SZi Xuan Wu   /// CPEntry - One per constant pool entry, keeping the machine instruction
162*065e0324SZi Xuan Wu   /// pointer, the constpool index, and the number of CPUser's which
163*065e0324SZi Xuan Wu   /// reference this entry.
164*065e0324SZi Xuan Wu   struct CPEntry {
165*065e0324SZi Xuan Wu     MachineInstr *CPEMI;
166*065e0324SZi Xuan Wu     unsigned CPI;
167*065e0324SZi Xuan Wu     unsigned RefCount;
168*065e0324SZi Xuan Wu 
169*065e0324SZi Xuan Wu     CPEntry(MachineInstr *Cpemi, unsigned Cpi, unsigned Rc = 0)
170*065e0324SZi Xuan Wu         : CPEMI(Cpemi), CPI(Cpi), RefCount(Rc) {}
171*065e0324SZi Xuan Wu   };
172*065e0324SZi Xuan Wu 
173*065e0324SZi Xuan Wu   /// CPEntries - Keep track of all of the constant pool entry machine
174*065e0324SZi Xuan Wu   /// instructions. For each original constpool index (i.e. those that
175*065e0324SZi Xuan Wu   /// existed upon entry to this pass), it keeps a vector of entries.
176*065e0324SZi Xuan Wu   /// Original elements are cloned as we go along; the clones are
177*065e0324SZi Xuan Wu   /// put in the vector of the original element, but have distinct CPIs.
178*065e0324SZi Xuan Wu   std::vector<std::vector<CPEntry>> CPEntries;
179*065e0324SZi Xuan Wu 
180*065e0324SZi Xuan Wu   /// ImmBranch - One per immediate branch, keeping the machine instruction
181*065e0324SZi Xuan Wu   /// pointer, conditional or unconditional, the max displacement,
182*065e0324SZi Xuan Wu   /// and (if isCond is true) the corresponding unconditional branch
183*065e0324SZi Xuan Wu   /// opcode.
184*065e0324SZi Xuan Wu   struct ImmBranch {
185*065e0324SZi Xuan Wu     MachineInstr *MI;
186*065e0324SZi Xuan Wu     unsigned MaxDisp : 31;
187*065e0324SZi Xuan Wu     bool IsCond : 1;
188*065e0324SZi Xuan Wu     int UncondBr;
189*065e0324SZi Xuan Wu 
190*065e0324SZi Xuan Wu     ImmBranch(MachineInstr *Mi, unsigned Maxdisp, bool Cond, int Ubr)
191*065e0324SZi Xuan Wu         : MI(Mi), MaxDisp(Maxdisp), IsCond(Cond), UncondBr(Ubr) {}
192*065e0324SZi Xuan Wu   };
193*065e0324SZi Xuan Wu 
194*065e0324SZi Xuan Wu   /// ImmBranches - Keep track of all the immediate branch instructions.
195*065e0324SZi Xuan Wu   ///
196*065e0324SZi Xuan Wu   std::vector<ImmBranch> ImmBranches;
197*065e0324SZi Xuan Wu 
198*065e0324SZi Xuan Wu   const CSKYSubtarget *STI = nullptr;
199*065e0324SZi Xuan Wu   const CSKYInstrInfo *TII;
200*065e0324SZi Xuan Wu   CSKYMachineFunctionInfo *MFI;
201*065e0324SZi Xuan Wu   MachineFunction *MF = nullptr;
202*065e0324SZi Xuan Wu   MachineConstantPool *MCP = nullptr;
203*065e0324SZi Xuan Wu 
204*065e0324SZi Xuan Wu   unsigned PICLabelUId;
205*065e0324SZi Xuan Wu 
206*065e0324SZi Xuan Wu   void initPICLabelUId(unsigned UId) { PICLabelUId = UId; }
207*065e0324SZi Xuan Wu 
208*065e0324SZi Xuan Wu   unsigned createPICLabelUId() { return PICLabelUId++; }
209*065e0324SZi Xuan Wu 
210*065e0324SZi Xuan Wu public:
211*065e0324SZi Xuan Wu   static char ID;
212*065e0324SZi Xuan Wu 
213*065e0324SZi Xuan Wu   CSKYConstantIslands() : MachineFunctionPass(ID) {}
214*065e0324SZi Xuan Wu 
215*065e0324SZi Xuan Wu   StringRef getPassName() const override { return "CSKY Constant Islands"; }
216*065e0324SZi Xuan Wu 
217*065e0324SZi Xuan Wu   bool runOnMachineFunction(MachineFunction &F) override;
218*065e0324SZi Xuan Wu 
219*065e0324SZi Xuan Wu   void getAnalysisUsage(AnalysisUsage &AU) const override {
220*065e0324SZi Xuan Wu     AU.addRequired<MachineDominatorTree>();
221*065e0324SZi Xuan Wu     MachineFunctionPass::getAnalysisUsage(AU);
222*065e0324SZi Xuan Wu   }
223*065e0324SZi Xuan Wu 
224*065e0324SZi Xuan Wu   MachineFunctionProperties getRequiredProperties() const override {
225*065e0324SZi Xuan Wu     return MachineFunctionProperties().set(
226*065e0324SZi Xuan Wu         MachineFunctionProperties::Property::NoVRegs);
227*065e0324SZi Xuan Wu   }
228*065e0324SZi Xuan Wu 
229*065e0324SZi Xuan Wu   void doInitialPlacement(std::vector<MachineInstr *> &CPEMIs);
230*065e0324SZi Xuan Wu   CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
231*065e0324SZi Xuan Wu   Align getCPEAlign(const MachineInstr &CPEMI);
232*065e0324SZi Xuan Wu   void initializeFunctionInfo(const std::vector<MachineInstr *> &CPEMIs);
233*065e0324SZi Xuan Wu   unsigned getOffsetOf(MachineInstr *MI) const;
234*065e0324SZi Xuan Wu   unsigned getUserOffset(CPUser &) const;
235*065e0324SZi Xuan Wu   void dumpBBs();
236*065e0324SZi Xuan Wu 
237*065e0324SZi Xuan Wu   bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset, unsigned Disp,
238*065e0324SZi Xuan Wu                        bool NegativeOK);
239*065e0324SZi Xuan Wu   bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
240*065e0324SZi Xuan Wu                        const CPUser &U);
241*065e0324SZi Xuan Wu 
242*065e0324SZi Xuan Wu   void computeBlockSize(MachineBasicBlock *MBB);
243*065e0324SZi Xuan Wu   MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI);
244*065e0324SZi Xuan Wu   void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
245*065e0324SZi Xuan Wu   void adjustBBOffsetsAfter(MachineBasicBlock *BB);
246*065e0324SZi Xuan Wu   bool decrementCPEReferenceCount(unsigned CPI, MachineInstr *CPEMI);
247*065e0324SZi Xuan Wu   int findInRangeCPEntry(CPUser &U, unsigned UserOffset);
248*065e0324SZi Xuan Wu   bool findAvailableWater(CPUser &U, unsigned UserOffset,
249*065e0324SZi Xuan Wu                           water_iterator &WaterIter);
250*065e0324SZi Xuan Wu   void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
251*065e0324SZi Xuan Wu                       MachineBasicBlock *&NewMBB);
252*065e0324SZi Xuan Wu   bool handleConstantPoolUser(unsigned CPUserIndex);
253*065e0324SZi Xuan Wu   void removeDeadCPEMI(MachineInstr *CPEMI);
254*065e0324SZi Xuan Wu   bool removeUnusedCPEntries();
255*065e0324SZi Xuan Wu   bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
256*065e0324SZi Xuan Wu                         MachineInstr *CPEMI, unsigned Disp, bool NegOk,
257*065e0324SZi Xuan Wu                         bool DoDump = false);
258*065e0324SZi Xuan Wu   bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water, CPUser &U,
259*065e0324SZi Xuan Wu                       unsigned &Growth);
260*065e0324SZi Xuan Wu   bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
261*065e0324SZi Xuan Wu   bool fixupImmediateBr(ImmBranch &Br);
262*065e0324SZi Xuan Wu   bool fixupConditionalBr(ImmBranch &Br);
263*065e0324SZi Xuan Wu   bool fixupUnconditionalBr(ImmBranch &Br);
264*065e0324SZi Xuan Wu };
265*065e0324SZi Xuan Wu } // end anonymous namespace
266*065e0324SZi Xuan Wu 
267*065e0324SZi Xuan Wu char CSKYConstantIslands::ID = 0;
268*065e0324SZi Xuan Wu 
269*065e0324SZi Xuan Wu bool CSKYConstantIslands::isOffsetInRange(unsigned UserOffset,
270*065e0324SZi Xuan Wu                                           unsigned TrialOffset,
271*065e0324SZi Xuan Wu                                           const CPUser &U) {
272*065e0324SZi Xuan Wu   return isOffsetInRange(UserOffset, TrialOffset, U.getMaxDisp(), U.NegOk);
273*065e0324SZi Xuan Wu }
274*065e0324SZi Xuan Wu 
275*065e0324SZi Xuan Wu #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
276*065e0324SZi Xuan Wu /// print block size and offset information - debugging
277*065e0324SZi Xuan Wu LLVM_DUMP_METHOD void CSKYConstantIslands::dumpBBs() {
278*065e0324SZi Xuan Wu   for (unsigned J = 0, E = BBInfo.size(); J != E; ++J) {
279*065e0324SZi Xuan Wu     const BasicBlockInfo &BBI = BBInfo[J];
280*065e0324SZi Xuan Wu     dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)
281*065e0324SZi Xuan Wu            << format(" size=%#x\n", BBInfo[J].Size);
282*065e0324SZi Xuan Wu   }
283*065e0324SZi Xuan Wu }
284*065e0324SZi Xuan Wu #endif
285*065e0324SZi Xuan Wu 
286*065e0324SZi Xuan Wu bool CSKYConstantIslands::runOnMachineFunction(MachineFunction &Mf) {
287*065e0324SZi Xuan Wu   MF = &Mf;
288*065e0324SZi Xuan Wu   MCP = Mf.getConstantPool();
289*065e0324SZi Xuan Wu   STI = &static_cast<const CSKYSubtarget &>(Mf.getSubtarget());
290*065e0324SZi Xuan Wu 
291*065e0324SZi Xuan Wu   LLVM_DEBUG(dbgs() << "***** CSKYConstantIslands: "
292*065e0324SZi Xuan Wu                     << MCP->getConstants().size() << " CP entries, aligned to "
293*065e0324SZi Xuan Wu                     << MCP->getConstantPoolAlign().value() << " bytes *****\n");
294*065e0324SZi Xuan Wu 
295*065e0324SZi Xuan Wu   TII = STI->getInstrInfo();
296*065e0324SZi Xuan Wu   MFI = MF->getInfo<CSKYMachineFunctionInfo>();
297*065e0324SZi Xuan Wu 
298*065e0324SZi Xuan Wu   // This pass invalidates liveness information when it splits basic blocks.
299*065e0324SZi Xuan Wu   MF->getRegInfo().invalidateLiveness();
300*065e0324SZi Xuan Wu 
301*065e0324SZi Xuan Wu   // Renumber all of the machine basic blocks in the function, guaranteeing that
302*065e0324SZi Xuan Wu   // the numbers agree with the position of the block in the function.
303*065e0324SZi Xuan Wu   MF->RenumberBlocks();
304*065e0324SZi Xuan Wu 
305*065e0324SZi Xuan Wu   bool MadeChange = false;
306*065e0324SZi Xuan Wu 
307*065e0324SZi Xuan Wu   // Perform the initial placement of the constant pool entries.  To start with,
308*065e0324SZi Xuan Wu   // we put them all at the end of the function.
309*065e0324SZi Xuan Wu   std::vector<MachineInstr *> CPEMIs;
310*065e0324SZi Xuan Wu   if (!MCP->isEmpty())
311*065e0324SZi Xuan Wu     doInitialPlacement(CPEMIs);
312*065e0324SZi Xuan Wu 
313*065e0324SZi Xuan Wu   /// The next UID to take is the first unused one.
314*065e0324SZi Xuan Wu   initPICLabelUId(CPEMIs.size());
315*065e0324SZi Xuan Wu 
316*065e0324SZi Xuan Wu   // Do the initial scan of the function, building up information about the
317*065e0324SZi Xuan Wu   // sizes of each block, the location of all the water, and finding all of the
318*065e0324SZi Xuan Wu   // constant pool users.
319*065e0324SZi Xuan Wu   initializeFunctionInfo(CPEMIs);
320*065e0324SZi Xuan Wu   CPEMIs.clear();
321*065e0324SZi Xuan Wu   LLVM_DEBUG(dumpBBs());
322*065e0324SZi Xuan Wu 
323*065e0324SZi Xuan Wu   /// Remove dead constant pool entries.
324*065e0324SZi Xuan Wu   MadeChange |= removeUnusedCPEntries();
325*065e0324SZi Xuan Wu 
326*065e0324SZi Xuan Wu   // Iteratively place constant pool entries and fix up branches until there
327*065e0324SZi Xuan Wu   // is no change.
328*065e0324SZi Xuan Wu   unsigned NoCPIters = 0, NoBRIters = 0;
329*065e0324SZi Xuan Wu   (void)NoBRIters;
330*065e0324SZi Xuan Wu   while (true) {
331*065e0324SZi Xuan Wu     LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
332*065e0324SZi Xuan Wu     bool CPChange = false;
333*065e0324SZi Xuan Wu     for (unsigned I = 0, E = CPUsers.size(); I != E; ++I)
334*065e0324SZi Xuan Wu       CPChange |= handleConstantPoolUser(I);
335*065e0324SZi Xuan Wu     if (CPChange && ++NoCPIters > 30)
336*065e0324SZi Xuan Wu       report_fatal_error("Constant Island pass failed to converge!");
337*065e0324SZi Xuan Wu     LLVM_DEBUG(dumpBBs());
338*065e0324SZi Xuan Wu 
339*065e0324SZi Xuan Wu     // Clear NewWaterList now.  If we split a block for branches, it should
340*065e0324SZi Xuan Wu     // appear as "new water" for the next iteration of constant pool placement.
341*065e0324SZi Xuan Wu     NewWaterList.clear();
342*065e0324SZi Xuan Wu 
343*065e0324SZi Xuan Wu     LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
344*065e0324SZi Xuan Wu     bool BRChange = false;
345*065e0324SZi Xuan Wu     for (unsigned I = 0, E = ImmBranches.size(); I != E; ++I)
346*065e0324SZi Xuan Wu       BRChange |= fixupImmediateBr(ImmBranches[I]);
347*065e0324SZi Xuan Wu     if (BRChange && ++NoBRIters > 30)
348*065e0324SZi Xuan Wu       report_fatal_error("Branch Fix Up pass failed to converge!");
349*065e0324SZi Xuan Wu     LLVM_DEBUG(dumpBBs());
350*065e0324SZi Xuan Wu     if (!CPChange && !BRChange)
351*065e0324SZi Xuan Wu       break;
352*065e0324SZi Xuan Wu     MadeChange = true;
353*065e0324SZi Xuan Wu   }
354*065e0324SZi Xuan Wu 
355*065e0324SZi Xuan Wu   LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
356*065e0324SZi Xuan Wu 
357*065e0324SZi Xuan Wu   BBInfo.clear();
358*065e0324SZi Xuan Wu   WaterList.clear();
359*065e0324SZi Xuan Wu   CPUsers.clear();
360*065e0324SZi Xuan Wu   CPEntries.clear();
361*065e0324SZi Xuan Wu   ImmBranches.clear();
362*065e0324SZi Xuan Wu   return MadeChange;
363*065e0324SZi Xuan Wu }
364*065e0324SZi Xuan Wu 
365*065e0324SZi Xuan Wu /// doInitialPlacement - Perform the initial placement of the constant pool
366*065e0324SZi Xuan Wu /// entries.  To start with, we put them all at the end of the function.
367*065e0324SZi Xuan Wu void CSKYConstantIslands::doInitialPlacement(
368*065e0324SZi Xuan Wu     std::vector<MachineInstr *> &CPEMIs) {
369*065e0324SZi Xuan Wu   // Create the basic block to hold the CPE's.
370*065e0324SZi Xuan Wu   MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
371*065e0324SZi Xuan Wu   MF->push_back(BB);
372*065e0324SZi Xuan Wu 
373*065e0324SZi Xuan Wu   // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
374*065e0324SZi Xuan Wu   const Align MaxAlign = MCP->getConstantPoolAlign();
375*065e0324SZi Xuan Wu 
376*065e0324SZi Xuan Wu   // Mark the basic block as required by the const-pool.
377*065e0324SZi Xuan Wu   BB->setAlignment(Align(2));
378*065e0324SZi Xuan Wu 
379*065e0324SZi Xuan Wu   // The function needs to be as aligned as the basic blocks. The linker may
380*065e0324SZi Xuan Wu   // move functions around based on their alignment.
381*065e0324SZi Xuan Wu   MF->ensureAlignment(BB->getAlignment());
382*065e0324SZi Xuan Wu 
383*065e0324SZi Xuan Wu   // Order the entries in BB by descending alignment.  That ensures correct
384*065e0324SZi Xuan Wu   // alignment of all entries as long as BB is sufficiently aligned.  Keep
385*065e0324SZi Xuan Wu   // track of the insertion point for each alignment.  We are going to bucket
386*065e0324SZi Xuan Wu   // sort the entries as they are created.
387*065e0324SZi Xuan Wu   SmallVector<MachineBasicBlock::iterator, 8> InsPoint(Log2(MaxAlign) + 1,
388*065e0324SZi Xuan Wu                                                        BB->end());
389*065e0324SZi Xuan Wu 
390*065e0324SZi Xuan Wu   // Add all of the constants from the constant pool to the end block, use an
391*065e0324SZi Xuan Wu   // identity mapping of CPI's to CPE's.
392*065e0324SZi Xuan Wu   const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
393*065e0324SZi Xuan Wu 
394*065e0324SZi Xuan Wu   const DataLayout &TD = MF->getDataLayout();
395*065e0324SZi Xuan Wu   for (unsigned I = 0, E = CPs.size(); I != E; ++I) {
396*065e0324SZi Xuan Wu     unsigned Size = CPs[I].getSizeInBytes(TD);
397*065e0324SZi Xuan Wu     assert(Size >= 4 && "Too small constant pool entry");
398*065e0324SZi Xuan Wu     Align Alignment = CPs[I].getAlign();
399*065e0324SZi Xuan Wu     // Verify that all constant pool entries are a multiple of their alignment.
400*065e0324SZi Xuan Wu     // If not, we would have to pad them out so that instructions stay aligned.
401*065e0324SZi Xuan Wu     assert(isAligned(Alignment, Size) && "CP Entry not multiple of 4 bytes!");
402*065e0324SZi Xuan Wu 
403*065e0324SZi Xuan Wu     // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
404*065e0324SZi Xuan Wu     unsigned LogAlign = Log2(Alignment);
405*065e0324SZi Xuan Wu     MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
406*065e0324SZi Xuan Wu 
407*065e0324SZi Xuan Wu     MachineInstr *CPEMI =
408*065e0324SZi Xuan Wu         BuildMI(*BB, InsAt, DebugLoc(), TII->get(CSKY::CONSTPOOL_ENTRY))
409*065e0324SZi Xuan Wu             .addImm(I)
410*065e0324SZi Xuan Wu             .addConstantPoolIndex(I)
411*065e0324SZi Xuan Wu             .addImm(Size);
412*065e0324SZi Xuan Wu 
413*065e0324SZi Xuan Wu     CPEMIs.push_back(CPEMI);
414*065e0324SZi Xuan Wu 
415*065e0324SZi Xuan Wu     // Ensure that future entries with higher alignment get inserted before
416*065e0324SZi Xuan Wu     // CPEMI. This is bucket sort with iterators.
417*065e0324SZi Xuan Wu     for (unsigned A = LogAlign + 1; A <= Log2(MaxAlign); ++A)
418*065e0324SZi Xuan Wu       if (InsPoint[A] == InsAt)
419*065e0324SZi Xuan Wu         InsPoint[A] = CPEMI;
420*065e0324SZi Xuan Wu     // Add a new CPEntry, but no corresponding CPUser yet.
421*065e0324SZi Xuan Wu     CPEntries.emplace_back(1, CPEntry(CPEMI, I));
422*065e0324SZi Xuan Wu     ++NumCPEs;
423*065e0324SZi Xuan Wu     LLVM_DEBUG(dbgs() << "Moved CPI#" << I << " to end of function, size = "
424*065e0324SZi Xuan Wu                       << Size << ", align = " << Alignment.value() << '\n');
425*065e0324SZi Xuan Wu   }
426*065e0324SZi Xuan Wu   LLVM_DEBUG(BB->dump());
427*065e0324SZi Xuan Wu }
428*065e0324SZi Xuan Wu 
429*065e0324SZi Xuan Wu /// BBHasFallthrough - Return true if the specified basic block can fallthrough
430*065e0324SZi Xuan Wu /// into the block immediately after it.
431*065e0324SZi Xuan Wu static bool bbHasFallthrough(MachineBasicBlock *MBB) {
432*065e0324SZi Xuan Wu   // Get the next machine basic block in the function.
433*065e0324SZi Xuan Wu   MachineFunction::iterator MBBI = MBB->getIterator();
434*065e0324SZi Xuan Wu   // Can't fall off end of function.
435*065e0324SZi Xuan Wu   if (std::next(MBBI) == MBB->getParent()->end())
436*065e0324SZi Xuan Wu     return false;
437*065e0324SZi Xuan Wu 
438*065e0324SZi Xuan Wu   MachineBasicBlock *NextBB = &*std::next(MBBI);
439*065e0324SZi Xuan Wu   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
440*065e0324SZi Xuan Wu                                         E = MBB->succ_end();
441*065e0324SZi Xuan Wu        I != E; ++I)
442*065e0324SZi Xuan Wu     if (*I == NextBB)
443*065e0324SZi Xuan Wu       return true;
444*065e0324SZi Xuan Wu 
445*065e0324SZi Xuan Wu   return false;
446*065e0324SZi Xuan Wu }
447*065e0324SZi Xuan Wu 
448*065e0324SZi Xuan Wu /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
449*065e0324SZi Xuan Wu /// look up the corresponding CPEntry.
450*065e0324SZi Xuan Wu CSKYConstantIslands::CPEntry *
451*065e0324SZi Xuan Wu CSKYConstantIslands::findConstPoolEntry(unsigned CPI,
452*065e0324SZi Xuan Wu                                         const MachineInstr *CPEMI) {
453*065e0324SZi Xuan Wu   std::vector<CPEntry> &CPEs = CPEntries[CPI];
454*065e0324SZi Xuan Wu   // Number of entries per constpool index should be small, just do a
455*065e0324SZi Xuan Wu   // linear search.
456*065e0324SZi Xuan Wu   for (unsigned I = 0, E = CPEs.size(); I != E; ++I) {
457*065e0324SZi Xuan Wu     if (CPEs[I].CPEMI == CPEMI)
458*065e0324SZi Xuan Wu       return &CPEs[I];
459*065e0324SZi Xuan Wu   }
460*065e0324SZi Xuan Wu   return nullptr;
461*065e0324SZi Xuan Wu }
462*065e0324SZi Xuan Wu 
463*065e0324SZi Xuan Wu /// getCPEAlign - Returns the required alignment of the constant pool entry
464*065e0324SZi Xuan Wu /// represented by CPEMI.  Alignment is measured in log2(bytes) units.
465*065e0324SZi Xuan Wu Align CSKYConstantIslands::getCPEAlign(const MachineInstr &CPEMI) {
466*065e0324SZi Xuan Wu   assert(CPEMI.getOpcode() == CSKY::CONSTPOOL_ENTRY);
467*065e0324SZi Xuan Wu 
468*065e0324SZi Xuan Wu   unsigned CPI = CPEMI.getOperand(1).getIndex();
469*065e0324SZi Xuan Wu   assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
470*065e0324SZi Xuan Wu   return MCP->getConstants()[CPI].getAlign();
471*065e0324SZi Xuan Wu }
472*065e0324SZi Xuan Wu 
473*065e0324SZi Xuan Wu /// initializeFunctionInfo - Do the initial scan of the function, building up
474*065e0324SZi Xuan Wu /// information about the sizes of each block, the location of all the water,
475*065e0324SZi Xuan Wu /// and finding all of the constant pool users.
476*065e0324SZi Xuan Wu void CSKYConstantIslands::initializeFunctionInfo(
477*065e0324SZi Xuan Wu     const std::vector<MachineInstr *> &CPEMIs) {
478*065e0324SZi Xuan Wu   BBInfo.clear();
479*065e0324SZi Xuan Wu   BBInfo.resize(MF->getNumBlockIDs());
480*065e0324SZi Xuan Wu 
481*065e0324SZi Xuan Wu   // First thing, compute the size of all basic blocks, and see if the function
482*065e0324SZi Xuan Wu   // has any inline assembly in it. If so, we have to be conservative about
483*065e0324SZi Xuan Wu   // alignment assumptions, as we don't know for sure the size of any
484*065e0324SZi Xuan Wu   // instructions in the inline assembly.
485*065e0324SZi Xuan Wu   for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
486*065e0324SZi Xuan Wu     computeBlockSize(&*I);
487*065e0324SZi Xuan Wu 
488*065e0324SZi Xuan Wu   // Compute block offsets.
489*065e0324SZi Xuan Wu   adjustBBOffsetsAfter(&MF->front());
490*065e0324SZi Xuan Wu 
491*065e0324SZi Xuan Wu   // Now go back through the instructions and build up our data structures.
492*065e0324SZi Xuan Wu   for (MachineBasicBlock &MBB : *MF) {
493*065e0324SZi Xuan Wu     // If this block doesn't fall through into the next MBB, then this is
494*065e0324SZi Xuan Wu     // 'water' that a constant pool island could be placed.
495*065e0324SZi Xuan Wu     if (!bbHasFallthrough(&MBB))
496*065e0324SZi Xuan Wu       WaterList.push_back(&MBB);
497*065e0324SZi Xuan Wu     for (MachineInstr &MI : MBB) {
498*065e0324SZi Xuan Wu       if (MI.isDebugInstr())
499*065e0324SZi Xuan Wu         continue;
500*065e0324SZi Xuan Wu 
501*065e0324SZi Xuan Wu       int Opc = MI.getOpcode();
502*065e0324SZi Xuan Wu       if (MI.isBranch() && !MI.isIndirectBranch()) {
503*065e0324SZi Xuan Wu         bool IsCond = MI.isConditionalBranch();
504*065e0324SZi Xuan Wu         unsigned Bits = 0;
505*065e0324SZi Xuan Wu         unsigned Scale = 1;
506*065e0324SZi Xuan Wu         int UOpc = CSKY::BR32;
507*065e0324SZi Xuan Wu 
508*065e0324SZi Xuan Wu         switch (MI.getOpcode()) {
509*065e0324SZi Xuan Wu         case CSKY::BR16:
510*065e0324SZi Xuan Wu         case CSKY::BF16:
511*065e0324SZi Xuan Wu         case CSKY::BT16:
512*065e0324SZi Xuan Wu           Bits = 10;
513*065e0324SZi Xuan Wu           Scale = 2;
514*065e0324SZi Xuan Wu           break;
515*065e0324SZi Xuan Wu         default:
516*065e0324SZi Xuan Wu           Bits = 16;
517*065e0324SZi Xuan Wu           Scale = 2;
518*065e0324SZi Xuan Wu           break;
519*065e0324SZi Xuan Wu         }
520*065e0324SZi Xuan Wu 
521*065e0324SZi Xuan Wu         // Record this immediate branch.
522*065e0324SZi Xuan Wu         unsigned MaxOffs = ((1 << (Bits - 1)) - 1) * Scale;
523*065e0324SZi Xuan Wu         ImmBranches.push_back(ImmBranch(&MI, MaxOffs, IsCond, UOpc));
524*065e0324SZi Xuan Wu       }
525*065e0324SZi Xuan Wu 
526*065e0324SZi Xuan Wu       if (Opc == CSKY::CONSTPOOL_ENTRY)
527*065e0324SZi Xuan Wu         continue;
528*065e0324SZi Xuan Wu 
529*065e0324SZi Xuan Wu       // Scan the instructions for constant pool operands.
530*065e0324SZi Xuan Wu       for (unsigned Op = 0, E = MI.getNumOperands(); Op != E; ++Op)
531*065e0324SZi Xuan Wu         if (MI.getOperand(Op).isCPI()) {
532*065e0324SZi Xuan Wu           // We found one.  The addressing mode tells us the max displacement
533*065e0324SZi Xuan Wu           // from the PC that this instruction permits.
534*065e0324SZi Xuan Wu 
535*065e0324SZi Xuan Wu           // Basic size info comes from the TSFlags field.
536*065e0324SZi Xuan Wu           unsigned Bits = 0;
537*065e0324SZi Xuan Wu           unsigned Scale = 1;
538*065e0324SZi Xuan Wu           bool NegOk = false;
539*065e0324SZi Xuan Wu 
540*065e0324SZi Xuan Wu           switch (Opc) {
541*065e0324SZi Xuan Wu           default:
542*065e0324SZi Xuan Wu             llvm_unreachable("Unknown addressing mode for CP reference!");
543*065e0324SZi Xuan Wu           case CSKY::MOVIH32:
544*065e0324SZi Xuan Wu           case CSKY::ORI32:
545*065e0324SZi Xuan Wu             continue;
546*065e0324SZi Xuan Wu           case CSKY::PseudoTLSLA32:
547*065e0324SZi Xuan Wu           case CSKY::JSRI32:
548*065e0324SZi Xuan Wu           case CSKY::JMPI32:
549*065e0324SZi Xuan Wu           case CSKY::LRW32:
550*065e0324SZi Xuan Wu           case CSKY::LRW32_Gen:
551*065e0324SZi Xuan Wu             Bits = 16;
552*065e0324SZi Xuan Wu             Scale = 4;
553*065e0324SZi Xuan Wu             break;
554*065e0324SZi Xuan Wu           case CSKY::GRS32:
555*065e0324SZi Xuan Wu             Bits = 17;
556*065e0324SZi Xuan Wu             Scale = 2;
557*065e0324SZi Xuan Wu             NegOk = true;
558*065e0324SZi Xuan Wu             break;
559*065e0324SZi Xuan Wu           }
560*065e0324SZi Xuan Wu           // Remember that this is a user of a CP entry.
561*065e0324SZi Xuan Wu           unsigned CPI = MI.getOperand(Op).getIndex();
562*065e0324SZi Xuan Wu           MachineInstr *CPEMI = CPEMIs[CPI];
563*065e0324SZi Xuan Wu           unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
564*065e0324SZi Xuan Wu           CPUsers.push_back(CPUser(&MI, CPEMI, MaxOffs, NegOk));
565*065e0324SZi Xuan Wu 
566*065e0324SZi Xuan Wu           // Increment corresponding CPEntry reference count.
567*065e0324SZi Xuan Wu           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
568*065e0324SZi Xuan Wu           assert(CPE && "Cannot find a corresponding CPEntry!");
569*065e0324SZi Xuan Wu           CPE->RefCount++;
570*065e0324SZi Xuan Wu 
571*065e0324SZi Xuan Wu           // Instructions can only use one CP entry, don't bother scanning the
572*065e0324SZi Xuan Wu           // rest of the operands.
573*065e0324SZi Xuan Wu           break;
574*065e0324SZi Xuan Wu         }
575*065e0324SZi Xuan Wu     }
576*065e0324SZi Xuan Wu   }
577*065e0324SZi Xuan Wu }
578*065e0324SZi Xuan Wu 
579*065e0324SZi Xuan Wu /// computeBlockSize - Compute the size and some alignment information for MBB.
580*065e0324SZi Xuan Wu /// This function updates BBInfo directly.
581*065e0324SZi Xuan Wu void CSKYConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
582*065e0324SZi Xuan Wu   BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
583*065e0324SZi Xuan Wu   BBI.Size = 0;
584*065e0324SZi Xuan Wu 
585*065e0324SZi Xuan Wu   for (const MachineInstr &MI : *MBB)
586*065e0324SZi Xuan Wu     BBI.Size += TII->getInstSizeInBytes(MI);
587*065e0324SZi Xuan Wu }
588*065e0324SZi Xuan Wu 
589*065e0324SZi Xuan Wu /// getOffsetOf - Return the current offset of the specified machine instruction
590*065e0324SZi Xuan Wu /// from the start of the function.  This offset changes as stuff is moved
591*065e0324SZi Xuan Wu /// around inside the function.
592*065e0324SZi Xuan Wu unsigned CSKYConstantIslands::getOffsetOf(MachineInstr *MI) const {
593*065e0324SZi Xuan Wu   MachineBasicBlock *MBB = MI->getParent();
594*065e0324SZi Xuan Wu 
595*065e0324SZi Xuan Wu   // The offset is composed of two things: the sum of the sizes of all MBB's
596*065e0324SZi Xuan Wu   // before this instruction's block, and the offset from the start of the block
597*065e0324SZi Xuan Wu   // it is in.
598*065e0324SZi Xuan Wu   unsigned Offset = BBInfo[MBB->getNumber()].Offset;
599*065e0324SZi Xuan Wu 
600*065e0324SZi Xuan Wu   // Sum instructions before MI in MBB.
601*065e0324SZi Xuan Wu   for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
602*065e0324SZi Xuan Wu     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
603*065e0324SZi Xuan Wu     Offset += TII->getInstSizeInBytes(*I);
604*065e0324SZi Xuan Wu   }
605*065e0324SZi Xuan Wu   return Offset;
606*065e0324SZi Xuan Wu }
607*065e0324SZi Xuan Wu 
608*065e0324SZi Xuan Wu /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
609*065e0324SZi Xuan Wu /// ID.
610*065e0324SZi Xuan Wu static bool compareMbbNumbers(const MachineBasicBlock *LHS,
611*065e0324SZi Xuan Wu                               const MachineBasicBlock *RHS) {
612*065e0324SZi Xuan Wu   return LHS->getNumber() < RHS->getNumber();
613*065e0324SZi Xuan Wu }
614*065e0324SZi Xuan Wu 
615*065e0324SZi Xuan Wu /// updateForInsertedWaterBlock - When a block is newly inserted into the
616*065e0324SZi Xuan Wu /// machine function, it upsets all of the block numbers.  Renumber the blocks
617*065e0324SZi Xuan Wu /// and update the arrays that parallel this numbering.
618*065e0324SZi Xuan Wu void CSKYConstantIslands::updateForInsertedWaterBlock(
619*065e0324SZi Xuan Wu     MachineBasicBlock *NewBB) {
620*065e0324SZi Xuan Wu   // Renumber the MBB's to keep them consecutive.
621*065e0324SZi Xuan Wu   NewBB->getParent()->RenumberBlocks(NewBB);
622*065e0324SZi Xuan Wu 
623*065e0324SZi Xuan Wu   // Insert an entry into BBInfo to align it properly with the (newly
624*065e0324SZi Xuan Wu   // renumbered) block numbers.
625*065e0324SZi Xuan Wu   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
626*065e0324SZi Xuan Wu 
627*065e0324SZi Xuan Wu   // Next, update WaterList.  Specifically, we need to add NewMBB as having
628*065e0324SZi Xuan Wu   // available water after it.
629*065e0324SZi Xuan Wu   water_iterator IP = llvm::lower_bound(WaterList, NewBB, compareMbbNumbers);
630*065e0324SZi Xuan Wu   WaterList.insert(IP, NewBB);
631*065e0324SZi Xuan Wu }
632*065e0324SZi Xuan Wu 
633*065e0324SZi Xuan Wu unsigned CSKYConstantIslands::getUserOffset(CPUser &U) const {
634*065e0324SZi Xuan Wu   unsigned UserOffset = getOffsetOf(U.MI);
635*065e0324SZi Xuan Wu 
636*065e0324SZi Xuan Wu   UserOffset &= ~3u;
637*065e0324SZi Xuan Wu 
638*065e0324SZi Xuan Wu   return UserOffset;
639*065e0324SZi Xuan Wu }
640*065e0324SZi Xuan Wu 
641*065e0324SZi Xuan Wu /// Split the basic block containing MI into two blocks, which are joined by
642*065e0324SZi Xuan Wu /// an unconditional branch.  Update data structures and renumber blocks to
643*065e0324SZi Xuan Wu /// account for this change and returns the newly created block.
644*065e0324SZi Xuan Wu MachineBasicBlock *
645*065e0324SZi Xuan Wu CSKYConstantIslands::splitBlockBeforeInstr(MachineInstr &MI) {
646*065e0324SZi Xuan Wu   MachineBasicBlock *OrigBB = MI.getParent();
647*065e0324SZi Xuan Wu 
648*065e0324SZi Xuan Wu   // Create a new MBB for the code after the OrigBB.
649*065e0324SZi Xuan Wu   MachineBasicBlock *NewBB =
650*065e0324SZi Xuan Wu       MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
651*065e0324SZi Xuan Wu   MachineFunction::iterator MBBI = ++OrigBB->getIterator();
652*065e0324SZi Xuan Wu   MF->insert(MBBI, NewBB);
653*065e0324SZi Xuan Wu 
654*065e0324SZi Xuan Wu   // Splice the instructions starting with MI over to NewBB.
655*065e0324SZi Xuan Wu   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
656*065e0324SZi Xuan Wu 
657*065e0324SZi Xuan Wu   // Add an unconditional branch from OrigBB to NewBB.
658*065e0324SZi Xuan Wu   // Note the new unconditional branch is not being recorded.
659*065e0324SZi Xuan Wu   // There doesn't seem to be meaningful DebugInfo available; this doesn't
660*065e0324SZi Xuan Wu   // correspond to anything in the source.
661*065e0324SZi Xuan Wu 
662*065e0324SZi Xuan Wu   // TODO: Add support for 16bit instr.
663*065e0324SZi Xuan Wu   BuildMI(OrigBB, DebugLoc(), TII->get(CSKY::BR32)).addMBB(NewBB);
664*065e0324SZi Xuan Wu   ++NumSplit;
665*065e0324SZi Xuan Wu 
666*065e0324SZi Xuan Wu   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
667*065e0324SZi Xuan Wu   NewBB->transferSuccessors(OrigBB);
668*065e0324SZi Xuan Wu 
669*065e0324SZi Xuan Wu   // OrigBB branches to NewBB.
670*065e0324SZi Xuan Wu   OrigBB->addSuccessor(NewBB);
671*065e0324SZi Xuan Wu 
672*065e0324SZi Xuan Wu   // Update internal data structures to account for the newly inserted MBB.
673*065e0324SZi Xuan Wu   // This is almost the same as updateForInsertedWaterBlock, except that
674*065e0324SZi Xuan Wu   // the Water goes after OrigBB, not NewBB.
675*065e0324SZi Xuan Wu   MF->RenumberBlocks(NewBB);
676*065e0324SZi Xuan Wu 
677*065e0324SZi Xuan Wu   // Insert an entry into BBInfo to align it properly with the (newly
678*065e0324SZi Xuan Wu   // renumbered) block numbers.
679*065e0324SZi Xuan Wu   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
680*065e0324SZi Xuan Wu 
681*065e0324SZi Xuan Wu   // Next, update WaterList.  Specifically, we need to add OrigMBB as having
682*065e0324SZi Xuan Wu   // available water after it (but not if it's already there, which happens
683*065e0324SZi Xuan Wu   // when splitting before a conditional branch that is followed by an
684*065e0324SZi Xuan Wu   // unconditional branch - in that case we want to insert NewBB).
685*065e0324SZi Xuan Wu   water_iterator IP = llvm::lower_bound(WaterList, OrigBB, compareMbbNumbers);
686*065e0324SZi Xuan Wu   MachineBasicBlock *WaterBB = *IP;
687*065e0324SZi Xuan Wu   if (WaterBB == OrigBB)
688*065e0324SZi Xuan Wu     WaterList.insert(std::next(IP), NewBB);
689*065e0324SZi Xuan Wu   else
690*065e0324SZi Xuan Wu     WaterList.insert(IP, OrigBB);
691*065e0324SZi Xuan Wu   NewWaterList.insert(OrigBB);
692*065e0324SZi Xuan Wu 
693*065e0324SZi Xuan Wu   // Figure out how large the OrigBB is.  As the first half of the original
694*065e0324SZi Xuan Wu   // block, it cannot contain a tablejump.  The size includes
695*065e0324SZi Xuan Wu   // the new jump we added.  (It should be possible to do this without
696*065e0324SZi Xuan Wu   // recounting everything, but it's very confusing, and this is rarely
697*065e0324SZi Xuan Wu   // executed.)
698*065e0324SZi Xuan Wu   computeBlockSize(OrigBB);
699*065e0324SZi Xuan Wu 
700*065e0324SZi Xuan Wu   // Figure out how large the NewMBB is.  As the second half of the original
701*065e0324SZi Xuan Wu   // block, it may contain a tablejump.
702*065e0324SZi Xuan Wu   computeBlockSize(NewBB);
703*065e0324SZi Xuan Wu 
704*065e0324SZi Xuan Wu   // All BBOffsets following these blocks must be modified.
705*065e0324SZi Xuan Wu   adjustBBOffsetsAfter(OrigBB);
706*065e0324SZi Xuan Wu 
707*065e0324SZi Xuan Wu   return NewBB;
708*065e0324SZi Xuan Wu }
709*065e0324SZi Xuan Wu 
710*065e0324SZi Xuan Wu /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
711*065e0324SZi Xuan Wu /// reference) is within MaxDisp of TrialOffset (a proposed location of a
712*065e0324SZi Xuan Wu /// constant pool entry).
713*065e0324SZi Xuan Wu bool CSKYConstantIslands::isOffsetInRange(unsigned UserOffset,
714*065e0324SZi Xuan Wu                                           unsigned TrialOffset,
715*065e0324SZi Xuan Wu                                           unsigned MaxDisp, bool NegativeOK) {
716*065e0324SZi Xuan Wu   if (UserOffset <= TrialOffset) {
717*065e0324SZi Xuan Wu     // User before the Trial.
718*065e0324SZi Xuan Wu     if (TrialOffset - UserOffset <= MaxDisp)
719*065e0324SZi Xuan Wu       return true;
720*065e0324SZi Xuan Wu   } else if (NegativeOK) {
721*065e0324SZi Xuan Wu     if (UserOffset - TrialOffset <= MaxDisp)
722*065e0324SZi Xuan Wu       return true;
723*065e0324SZi Xuan Wu   }
724*065e0324SZi Xuan Wu   return false;
725*065e0324SZi Xuan Wu }
726*065e0324SZi Xuan Wu 
727*065e0324SZi Xuan Wu /// isWaterInRange - Returns true if a CPE placed after the specified
728*065e0324SZi Xuan Wu /// Water (a basic block) will be in range for the specific MI.
729*065e0324SZi Xuan Wu ///
730*065e0324SZi Xuan Wu /// Compute how much the function will grow by inserting a CPE after Water.
731*065e0324SZi Xuan Wu bool CSKYConstantIslands::isWaterInRange(unsigned UserOffset,
732*065e0324SZi Xuan Wu                                          MachineBasicBlock *Water, CPUser &U,
733*065e0324SZi Xuan Wu                                          unsigned &Growth) {
734*065e0324SZi Xuan Wu   unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
735*065e0324SZi Xuan Wu   unsigned NextBlockOffset;
736*065e0324SZi Xuan Wu   Align NextBlockAlignment;
737*065e0324SZi Xuan Wu   MachineFunction::const_iterator NextBlock = ++Water->getIterator();
738*065e0324SZi Xuan Wu   if (NextBlock == MF->end()) {
739*065e0324SZi Xuan Wu     NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
740*065e0324SZi Xuan Wu     NextBlockAlignment = Align(4);
741*065e0324SZi Xuan Wu   } else {
742*065e0324SZi Xuan Wu     NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
743*065e0324SZi Xuan Wu     NextBlockAlignment = NextBlock->getAlignment();
744*065e0324SZi Xuan Wu   }
745*065e0324SZi Xuan Wu   unsigned Size = U.CPEMI->getOperand(2).getImm();
746*065e0324SZi Xuan Wu   unsigned CPEEnd = CPEOffset + Size;
747*065e0324SZi Xuan Wu 
748*065e0324SZi Xuan Wu   // The CPE may be able to hide in the alignment padding before the next
749*065e0324SZi Xuan Wu   // block. It may also cause more padding to be required if it is more aligned
750*065e0324SZi Xuan Wu   // that the next block.
751*065e0324SZi Xuan Wu   if (CPEEnd > NextBlockOffset) {
752*065e0324SZi Xuan Wu     Growth = CPEEnd - NextBlockOffset;
753*065e0324SZi Xuan Wu     // Compute the padding that would go at the end of the CPE to align the next
754*065e0324SZi Xuan Wu     // block.
755*065e0324SZi Xuan Wu     Growth += offsetToAlignment(CPEEnd, NextBlockAlignment);
756*065e0324SZi Xuan Wu 
757*065e0324SZi Xuan Wu     // If the CPE is to be inserted before the instruction, that will raise
758*065e0324SZi Xuan Wu     // the offset of the instruction. Also account for unknown alignment padding
759*065e0324SZi Xuan Wu     // in blocks between CPE and the user.
760*065e0324SZi Xuan Wu     if (CPEOffset < UserOffset)
761*065e0324SZi Xuan Wu       UserOffset += Growth;
762*065e0324SZi Xuan Wu   } else
763*065e0324SZi Xuan Wu     // CPE fits in existing padding.
764*065e0324SZi Xuan Wu     Growth = 0;
765*065e0324SZi Xuan Wu 
766*065e0324SZi Xuan Wu   return isOffsetInRange(UserOffset, CPEOffset, U);
767*065e0324SZi Xuan Wu }
768*065e0324SZi Xuan Wu 
769*065e0324SZi Xuan Wu /// isCPEntryInRange - Returns true if the distance between specific MI and
770*065e0324SZi Xuan Wu /// specific ConstPool entry instruction can fit in MI's displacement field.
771*065e0324SZi Xuan Wu bool CSKYConstantIslands::isCPEntryInRange(MachineInstr *MI,
772*065e0324SZi Xuan Wu                                            unsigned UserOffset,
773*065e0324SZi Xuan Wu                                            MachineInstr *CPEMI,
774*065e0324SZi Xuan Wu                                            unsigned MaxDisp, bool NegOk,
775*065e0324SZi Xuan Wu                                            bool DoDump) {
776*065e0324SZi Xuan Wu   unsigned CPEOffset = getOffsetOf(CPEMI);
777*065e0324SZi Xuan Wu 
778*065e0324SZi Xuan Wu   if (DoDump) {
779*065e0324SZi Xuan Wu     LLVM_DEBUG({
780*065e0324SZi Xuan Wu       unsigned Block = MI->getParent()->getNumber();
781*065e0324SZi Xuan Wu       const BasicBlockInfo &BBI = BBInfo[Block];
782*065e0324SZi Xuan Wu       dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
783*065e0324SZi Xuan Wu              << " max delta=" << MaxDisp
784*065e0324SZi Xuan Wu              << format(" insn address=%#x", UserOffset) << " in "
785*065e0324SZi Xuan Wu              << printMBBReference(*MI->getParent()) << ": "
786*065e0324SZi Xuan Wu              << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
787*065e0324SZi Xuan Wu              << format("CPE address=%#x offset=%+d: ", CPEOffset,
788*065e0324SZi Xuan Wu                        int(CPEOffset - UserOffset));
789*065e0324SZi Xuan Wu     });
790*065e0324SZi Xuan Wu   }
791*065e0324SZi Xuan Wu 
792*065e0324SZi Xuan Wu   return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
793*065e0324SZi Xuan Wu }
794*065e0324SZi Xuan Wu 
795*065e0324SZi Xuan Wu #ifndef NDEBUG
796*065e0324SZi Xuan Wu /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
797*065e0324SZi Xuan Wu /// unconditionally branches to its only successor.
798*065e0324SZi Xuan Wu static bool bbIsJumpedOver(MachineBasicBlock *MBB) {
799*065e0324SZi Xuan Wu   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
800*065e0324SZi Xuan Wu     return false;
801*065e0324SZi Xuan Wu   MachineBasicBlock *Succ = *MBB->succ_begin();
802*065e0324SZi Xuan Wu   MachineBasicBlock *Pred = *MBB->pred_begin();
803*065e0324SZi Xuan Wu   MachineInstr *PredMI = &Pred->back();
804*065e0324SZi Xuan Wu   if (PredMI->getOpcode() == CSKY::BR32 /*TODO: change to 16bit instr. */)
805*065e0324SZi Xuan Wu     return PredMI->getOperand(0).getMBB() == Succ;
806*065e0324SZi Xuan Wu   return false;
807*065e0324SZi Xuan Wu }
808*065e0324SZi Xuan Wu #endif
809*065e0324SZi Xuan Wu 
810*065e0324SZi Xuan Wu void CSKYConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
811*065e0324SZi Xuan Wu   unsigned BBNum = BB->getNumber();
812*065e0324SZi Xuan Wu   for (unsigned I = BBNum + 1, E = MF->getNumBlockIDs(); I < E; ++I) {
813*065e0324SZi Xuan Wu     // Get the offset and known bits at the end of the layout predecessor.
814*065e0324SZi Xuan Wu     // Include the alignment of the current block.
815*065e0324SZi Xuan Wu     unsigned Offset = BBInfo[I - 1].Offset + BBInfo[I - 1].Size;
816*065e0324SZi Xuan Wu     BBInfo[I].Offset = Offset;
817*065e0324SZi Xuan Wu   }
818*065e0324SZi Xuan Wu }
819*065e0324SZi Xuan Wu 
820*065e0324SZi Xuan Wu /// decrementCPEReferenceCount - find the constant pool entry with index CPI
821*065e0324SZi Xuan Wu /// and instruction CPEMI, and decrement its refcount.  If the refcount
822*065e0324SZi Xuan Wu /// becomes 0 remove the entry and instruction.  Returns true if we removed
823*065e0324SZi Xuan Wu /// the entry, false if we didn't.
824*065e0324SZi Xuan Wu bool CSKYConstantIslands::decrementCPEReferenceCount(unsigned CPI,
825*065e0324SZi Xuan Wu                                                      MachineInstr *CPEMI) {
826*065e0324SZi Xuan Wu   // Find the old entry. Eliminate it if it is no longer used.
827*065e0324SZi Xuan Wu   CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
828*065e0324SZi Xuan Wu   assert(CPE && "Unexpected!");
829*065e0324SZi Xuan Wu   if (--CPE->RefCount == 0) {
830*065e0324SZi Xuan Wu     removeDeadCPEMI(CPEMI);
831*065e0324SZi Xuan Wu     CPE->CPEMI = nullptr;
832*065e0324SZi Xuan Wu     --NumCPEs;
833*065e0324SZi Xuan Wu     return true;
834*065e0324SZi Xuan Wu   }
835*065e0324SZi Xuan Wu   return false;
836*065e0324SZi Xuan Wu }
837*065e0324SZi Xuan Wu 
838*065e0324SZi Xuan Wu /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
839*065e0324SZi Xuan Wu /// if not, see if an in-range clone of the CPE is in range, and if so,
840*065e0324SZi Xuan Wu /// change the data structures so the user references the clone.  Returns:
841*065e0324SZi Xuan Wu /// 0 = no existing entry found
842*065e0324SZi Xuan Wu /// 1 = entry found, and there were no code insertions or deletions
843*065e0324SZi Xuan Wu /// 2 = entry found, and there were code insertions or deletions
844*065e0324SZi Xuan Wu int CSKYConstantIslands::findInRangeCPEntry(CPUser &U, unsigned UserOffset) {
845*065e0324SZi Xuan Wu   MachineInstr *UserMI = U.MI;
846*065e0324SZi Xuan Wu   MachineInstr *CPEMI = U.CPEMI;
847*065e0324SZi Xuan Wu 
848*065e0324SZi Xuan Wu   // Check to see if the CPE is already in-range.
849*065e0324SZi Xuan Wu   if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
850*065e0324SZi Xuan Wu                        true)) {
851*065e0324SZi Xuan Wu     LLVM_DEBUG(dbgs() << "In range\n");
852*065e0324SZi Xuan Wu     return 1;
853*065e0324SZi Xuan Wu   }
854*065e0324SZi Xuan Wu 
855*065e0324SZi Xuan Wu   // No.  Look for previously created clones of the CPE that are in range.
856*065e0324SZi Xuan Wu   unsigned CPI = CPEMI->getOperand(1).getIndex();
857*065e0324SZi Xuan Wu   std::vector<CPEntry> &CPEs = CPEntries[CPI];
858*065e0324SZi Xuan Wu   for (unsigned I = 0, E = CPEs.size(); I != E; ++I) {
859*065e0324SZi Xuan Wu     // We already tried this one
860*065e0324SZi Xuan Wu     if (CPEs[I].CPEMI == CPEMI)
861*065e0324SZi Xuan Wu       continue;
862*065e0324SZi Xuan Wu     // Removing CPEs can leave empty entries, skip
863*065e0324SZi Xuan Wu     if (CPEs[I].CPEMI == nullptr)
864*065e0324SZi Xuan Wu       continue;
865*065e0324SZi Xuan Wu     if (isCPEntryInRange(UserMI, UserOffset, CPEs[I].CPEMI, U.getMaxDisp(),
866*065e0324SZi Xuan Wu                          U.NegOk)) {
867*065e0324SZi Xuan Wu       LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
868*065e0324SZi Xuan Wu                         << CPEs[I].CPI << "\n");
869*065e0324SZi Xuan Wu       // Point the CPUser node to the replacement
870*065e0324SZi Xuan Wu       U.CPEMI = CPEs[I].CPEMI;
871*065e0324SZi Xuan Wu       // Change the CPI in the instruction operand to refer to the clone.
872*065e0324SZi Xuan Wu       for (unsigned J = 0, E = UserMI->getNumOperands(); J != E; ++J)
873*065e0324SZi Xuan Wu         if (UserMI->getOperand(J).isCPI()) {
874*065e0324SZi Xuan Wu           UserMI->getOperand(J).setIndex(CPEs[I].CPI);
875*065e0324SZi Xuan Wu           break;
876*065e0324SZi Xuan Wu         }
877*065e0324SZi Xuan Wu       // Adjust the refcount of the clone...
878*065e0324SZi Xuan Wu       CPEs[I].RefCount++;
879*065e0324SZi Xuan Wu       // ...and the original.  If we didn't remove the old entry, none of the
880*065e0324SZi Xuan Wu       // addresses changed, so we don't need another pass.
881*065e0324SZi Xuan Wu       return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
882*065e0324SZi Xuan Wu     }
883*065e0324SZi Xuan Wu   }
884*065e0324SZi Xuan Wu   return 0;
885*065e0324SZi Xuan Wu }
886*065e0324SZi Xuan Wu 
887*065e0324SZi Xuan Wu /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
888*065e0324SZi Xuan Wu /// the specific unconditional branch instruction.
889*065e0324SZi Xuan Wu static inline unsigned getUnconditionalBrDisp(int Opc) {
890*065e0324SZi Xuan Wu   unsigned Bits, Scale;
891*065e0324SZi Xuan Wu 
892*065e0324SZi Xuan Wu   switch (Opc) {
893*065e0324SZi Xuan Wu   case CSKY::BR16:
894*065e0324SZi Xuan Wu     Bits = 10;
895*065e0324SZi Xuan Wu     Scale = 2;
896*065e0324SZi Xuan Wu     break;
897*065e0324SZi Xuan Wu   case CSKY::BR32:
898*065e0324SZi Xuan Wu     Bits = 16;
899*065e0324SZi Xuan Wu     Scale = 2;
900*065e0324SZi Xuan Wu     break;
901*065e0324SZi Xuan Wu   default:
902*065e0324SZi Xuan Wu     assert(0);
903*065e0324SZi Xuan Wu     break;
904*065e0324SZi Xuan Wu   }
905*065e0324SZi Xuan Wu 
906*065e0324SZi Xuan Wu   unsigned MaxOffs = ((1 << (Bits - 1)) - 1) * Scale;
907*065e0324SZi Xuan Wu   return MaxOffs;
908*065e0324SZi Xuan Wu }
909*065e0324SZi Xuan Wu 
910*065e0324SZi Xuan Wu /// findAvailableWater - Look for an existing entry in the WaterList in which
911*065e0324SZi Xuan Wu /// we can place the CPE referenced from U so it's within range of U's MI.
912*065e0324SZi Xuan Wu /// Returns true if found, false if not.  If it returns true, WaterIter
913*065e0324SZi Xuan Wu /// is set to the WaterList entry.
914*065e0324SZi Xuan Wu /// To ensure that this pass
915*065e0324SZi Xuan Wu /// terminates, the CPE location for a particular CPUser is only allowed to
916*065e0324SZi Xuan Wu /// move to a lower address, so search backward from the end of the list and
917*065e0324SZi Xuan Wu /// prefer the first water that is in range.
918*065e0324SZi Xuan Wu bool CSKYConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
919*065e0324SZi Xuan Wu                                              water_iterator &WaterIter) {
920*065e0324SZi Xuan Wu   if (WaterList.empty())
921*065e0324SZi Xuan Wu     return false;
922*065e0324SZi Xuan Wu 
923*065e0324SZi Xuan Wu   unsigned BestGrowth = ~0u;
924*065e0324SZi Xuan Wu   for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
925*065e0324SZi Xuan Wu        --IP) {
926*065e0324SZi Xuan Wu     MachineBasicBlock *WaterBB = *IP;
927*065e0324SZi Xuan Wu     // Check if water is in range and is either at a lower address than the
928*065e0324SZi Xuan Wu     // current "high water mark" or a new water block that was created since
929*065e0324SZi Xuan Wu     // the previous iteration by inserting an unconditional branch.  In the
930*065e0324SZi Xuan Wu     // latter case, we want to allow resetting the high water mark back to
931*065e0324SZi Xuan Wu     // this new water since we haven't seen it before.  Inserting branches
932*065e0324SZi Xuan Wu     // should be relatively uncommon and when it does happen, we want to be
933*065e0324SZi Xuan Wu     // sure to take advantage of it for all the CPEs near that block, so that
934*065e0324SZi Xuan Wu     // we don't insert more branches than necessary.
935*065e0324SZi Xuan Wu     unsigned Growth;
936*065e0324SZi Xuan Wu     if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
937*065e0324SZi Xuan Wu         (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
938*065e0324SZi Xuan Wu          NewWaterList.count(WaterBB)) &&
939*065e0324SZi Xuan Wu         Growth < BestGrowth) {
940*065e0324SZi Xuan Wu       // This is the least amount of required padding seen so far.
941*065e0324SZi Xuan Wu       BestGrowth = Growth;
942*065e0324SZi Xuan Wu       WaterIter = IP;
943*065e0324SZi Xuan Wu       LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
944*065e0324SZi Xuan Wu                         << " Growth=" << Growth << '\n');
945*065e0324SZi Xuan Wu 
946*065e0324SZi Xuan Wu       // Keep looking unless it is perfect.
947*065e0324SZi Xuan Wu       if (BestGrowth == 0)
948*065e0324SZi Xuan Wu         return true;
949*065e0324SZi Xuan Wu     }
950*065e0324SZi Xuan Wu     if (IP == B)
951*065e0324SZi Xuan Wu       break;
952*065e0324SZi Xuan Wu   }
953*065e0324SZi Xuan Wu   return BestGrowth != ~0u;
954*065e0324SZi Xuan Wu }
955*065e0324SZi Xuan Wu 
956*065e0324SZi Xuan Wu /// createNewWater - No existing WaterList entry will work for
957*065e0324SZi Xuan Wu /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
958*065e0324SZi Xuan Wu /// block is used if in range, and the conditional branch munged so control
959*065e0324SZi Xuan Wu /// flow is correct.  Otherwise the block is split to create a hole with an
960*065e0324SZi Xuan Wu /// unconditional branch around it.  In either case NewMBB is set to a
961*065e0324SZi Xuan Wu /// block following which the new island can be inserted (the WaterList
962*065e0324SZi Xuan Wu /// is not adjusted).
963*065e0324SZi Xuan Wu void CSKYConstantIslands::createNewWater(unsigned CPUserIndex,
964*065e0324SZi Xuan Wu                                          unsigned UserOffset,
965*065e0324SZi Xuan Wu                                          MachineBasicBlock *&NewMBB) {
966*065e0324SZi Xuan Wu   CPUser &U = CPUsers[CPUserIndex];
967*065e0324SZi Xuan Wu   MachineInstr *UserMI = U.MI;
968*065e0324SZi Xuan Wu   MachineInstr *CPEMI = U.CPEMI;
969*065e0324SZi Xuan Wu   MachineBasicBlock *UserMBB = UserMI->getParent();
970*065e0324SZi Xuan Wu   const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
971*065e0324SZi Xuan Wu 
972*065e0324SZi Xuan Wu   // If the block does not end in an unconditional branch already, and if the
973*065e0324SZi Xuan Wu   // end of the block is within range, make new water there.
974*065e0324SZi Xuan Wu   if (bbHasFallthrough(UserMBB)) {
975*065e0324SZi Xuan Wu     // Size of branch to insert.
976*065e0324SZi Xuan Wu     unsigned Delta = 4;
977*065e0324SZi Xuan Wu     // Compute the offset where the CPE will begin.
978*065e0324SZi Xuan Wu     unsigned CPEOffset = UserBBI.postOffset() + Delta;
979*065e0324SZi Xuan Wu 
980*065e0324SZi Xuan Wu     if (isOffsetInRange(UserOffset, CPEOffset, U)) {
981*065e0324SZi Xuan Wu       LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)
982*065e0324SZi Xuan Wu                         << format(", expected CPE offset %#x\n", CPEOffset));
983*065e0324SZi Xuan Wu       NewMBB = &*++UserMBB->getIterator();
984*065e0324SZi Xuan Wu       // Add an unconditional branch from UserMBB to fallthrough block.  Record
985*065e0324SZi Xuan Wu       // it for branch lengthening; this new branch will not get out of range,
986*065e0324SZi Xuan Wu       // but if the preceding conditional branch is out of range, the targets
987*065e0324SZi Xuan Wu       // will be exchanged, and the altered branch may be out of range, so the
988*065e0324SZi Xuan Wu       // machinery has to know about it.
989*065e0324SZi Xuan Wu 
990*065e0324SZi Xuan Wu       // TODO: Add support for 16bit instr.
991*065e0324SZi Xuan Wu       int UncondBr = CSKY::BR32;
992*065e0324SZi Xuan Wu       auto *NewMI = BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))
993*065e0324SZi Xuan Wu                         .addMBB(NewMBB)
994*065e0324SZi Xuan Wu                         .getInstr();
995*065e0324SZi Xuan Wu       unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
996*065e0324SZi Xuan Wu       ImmBranches.push_back(
997*065e0324SZi Xuan Wu           ImmBranch(&UserMBB->back(), MaxDisp, false, UncondBr));
998*065e0324SZi Xuan Wu       BBInfo[UserMBB->getNumber()].Size += TII->getInstSizeInBytes(*NewMI);
999*065e0324SZi Xuan Wu       adjustBBOffsetsAfter(UserMBB);
1000*065e0324SZi Xuan Wu       return;
1001*065e0324SZi Xuan Wu     }
1002*065e0324SZi Xuan Wu   }
1003*065e0324SZi Xuan Wu 
1004*065e0324SZi Xuan Wu   // What a big block.  Find a place within the block to split it.
1005*065e0324SZi Xuan Wu 
1006*065e0324SZi Xuan Wu   // Try to split the block so it's fully aligned.  Compute the latest split
1007*065e0324SZi Xuan Wu   // point where we can add a 4-byte branch instruction, and then align to
1008*065e0324SZi Xuan Wu   // Align which is the largest possible alignment in the function.
1009*065e0324SZi Xuan Wu   const Align Align = MF->getAlignment();
1010*065e0324SZi Xuan Wu   unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
1011*065e0324SZi Xuan Wu   LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
1012*065e0324SZi Xuan Wu                               BaseInsertOffset));
1013*065e0324SZi Xuan Wu 
1014*065e0324SZi Xuan Wu   // The 4 in the following is for the unconditional branch we'll be inserting
1015*065e0324SZi Xuan Wu   // Alignment of the island is handled
1016*065e0324SZi Xuan Wu   // inside isOffsetInRange.
1017*065e0324SZi Xuan Wu   BaseInsertOffset -= 4;
1018*065e0324SZi Xuan Wu 
1019*065e0324SZi Xuan Wu   LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1020*065e0324SZi Xuan Wu                     << " la=" << Log2(Align) << '\n');
1021*065e0324SZi Xuan Wu 
1022*065e0324SZi Xuan Wu   // This could point off the end of the block if we've already got constant
1023*065e0324SZi Xuan Wu   // pool entries following this block; only the last one is in the water list.
1024*065e0324SZi Xuan Wu   // Back past any possible branches (allow for a conditional and a maximally
1025*065e0324SZi Xuan Wu   // long unconditional).
1026*065e0324SZi Xuan Wu   if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1027*065e0324SZi Xuan Wu     BaseInsertOffset = UserBBI.postOffset() - 8;
1028*065e0324SZi Xuan Wu     LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1029*065e0324SZi Xuan Wu   }
1030*065e0324SZi Xuan Wu   unsigned EndInsertOffset =
1031*065e0324SZi Xuan Wu       BaseInsertOffset + 4 + CPEMI->getOperand(2).getImm();
1032*065e0324SZi Xuan Wu   MachineBasicBlock::iterator MI = UserMI;
1033*065e0324SZi Xuan Wu   ++MI;
1034*065e0324SZi Xuan Wu   unsigned CPUIndex = CPUserIndex + 1;
1035*065e0324SZi Xuan Wu   unsigned NumCPUsers = CPUsers.size();
1036*065e0324SZi Xuan Wu   for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
1037*065e0324SZi Xuan Wu        Offset < BaseInsertOffset;
1038*065e0324SZi Xuan Wu        Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
1039*065e0324SZi Xuan Wu     assert(MI != UserMBB->end() && "Fell off end of block");
1040*065e0324SZi Xuan Wu     if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1041*065e0324SZi Xuan Wu       CPUser &U = CPUsers[CPUIndex];
1042*065e0324SZi Xuan Wu       if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1043*065e0324SZi Xuan Wu         // Shift intertion point by one unit of alignment so it is within reach.
1044*065e0324SZi Xuan Wu         BaseInsertOffset -= Align.value();
1045*065e0324SZi Xuan Wu         EndInsertOffset -= Align.value();
1046*065e0324SZi Xuan Wu       }
1047*065e0324SZi Xuan Wu       // This is overly conservative, as we don't account for CPEMIs being
1048*065e0324SZi Xuan Wu       // reused within the block, but it doesn't matter much.  Also assume CPEs
1049*065e0324SZi Xuan Wu       // are added in order with alignment padding.  We may eventually be able
1050*065e0324SZi Xuan Wu       // to pack the aligned CPEs better.
1051*065e0324SZi Xuan Wu       EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1052*065e0324SZi Xuan Wu       CPUIndex++;
1053*065e0324SZi Xuan Wu     }
1054*065e0324SZi Xuan Wu   }
1055*065e0324SZi Xuan Wu 
1056*065e0324SZi Xuan Wu   NewMBB = splitBlockBeforeInstr(*--MI);
1057*065e0324SZi Xuan Wu }
1058*065e0324SZi Xuan Wu 
1059*065e0324SZi Xuan Wu /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1060*065e0324SZi Xuan Wu /// is out-of-range.  If so, pick up the constant pool value and move it some
1061*065e0324SZi Xuan Wu /// place in-range.  Return true if we changed any addresses (thus must run
1062*065e0324SZi Xuan Wu /// another pass of branch lengthening), false otherwise.
1063*065e0324SZi Xuan Wu bool CSKYConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1064*065e0324SZi Xuan Wu   CPUser &U = CPUsers[CPUserIndex];
1065*065e0324SZi Xuan Wu   MachineInstr *UserMI = U.MI;
1066*065e0324SZi Xuan Wu   MachineInstr *CPEMI = U.CPEMI;
1067*065e0324SZi Xuan Wu   unsigned CPI = CPEMI->getOperand(1).getIndex();
1068*065e0324SZi Xuan Wu   unsigned Size = CPEMI->getOperand(2).getImm();
1069*065e0324SZi Xuan Wu   // Compute this only once, it's expensive.
1070*065e0324SZi Xuan Wu   unsigned UserOffset = getUserOffset(U);
1071*065e0324SZi Xuan Wu 
1072*065e0324SZi Xuan Wu   // See if the current entry is within range, or there is a clone of it
1073*065e0324SZi Xuan Wu   // in range.
1074*065e0324SZi Xuan Wu   int result = findInRangeCPEntry(U, UserOffset);
1075*065e0324SZi Xuan Wu   if (result == 1)
1076*065e0324SZi Xuan Wu     return false;
1077*065e0324SZi Xuan Wu   if (result == 2)
1078*065e0324SZi Xuan Wu     return true;
1079*065e0324SZi Xuan Wu 
1080*065e0324SZi Xuan Wu   // Look for water where we can place this CPE.
1081*065e0324SZi Xuan Wu   MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1082*065e0324SZi Xuan Wu   MachineBasicBlock *NewMBB;
1083*065e0324SZi Xuan Wu   water_iterator IP;
1084*065e0324SZi Xuan Wu   if (findAvailableWater(U, UserOffset, IP)) {
1085*065e0324SZi Xuan Wu     LLVM_DEBUG(dbgs() << "Found water in range\n");
1086*065e0324SZi Xuan Wu     MachineBasicBlock *WaterBB = *IP;
1087*065e0324SZi Xuan Wu 
1088*065e0324SZi Xuan Wu     // If the original WaterList entry was "new water" on this iteration,
1089*065e0324SZi Xuan Wu     // propagate that to the new island.  This is just keeping NewWaterList
1090*065e0324SZi Xuan Wu     // updated to match the WaterList, which will be updated below.
1091*065e0324SZi Xuan Wu     if (NewWaterList.erase(WaterBB))
1092*065e0324SZi Xuan Wu       NewWaterList.insert(NewIsland);
1093*065e0324SZi Xuan Wu 
1094*065e0324SZi Xuan Wu     // The new CPE goes before the following block (NewMBB).
1095*065e0324SZi Xuan Wu     NewMBB = &*++WaterBB->getIterator();
1096*065e0324SZi Xuan Wu   } else {
1097*065e0324SZi Xuan Wu     LLVM_DEBUG(dbgs() << "No water found\n");
1098*065e0324SZi Xuan Wu     createNewWater(CPUserIndex, UserOffset, NewMBB);
1099*065e0324SZi Xuan Wu 
1100*065e0324SZi Xuan Wu     // splitBlockBeforeInstr adds to WaterList, which is important when it is
1101*065e0324SZi Xuan Wu     // called while handling branches so that the water will be seen on the
1102*065e0324SZi Xuan Wu     // next iteration for constant pools, but in this context, we don't want
1103*065e0324SZi Xuan Wu     // it.  Check for this so it will be removed from the WaterList.
1104*065e0324SZi Xuan Wu     // Also remove any entry from NewWaterList.
1105*065e0324SZi Xuan Wu     MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
1106*065e0324SZi Xuan Wu     IP = llvm::find(WaterList, WaterBB);
1107*065e0324SZi Xuan Wu     if (IP != WaterList.end())
1108*065e0324SZi Xuan Wu       NewWaterList.erase(WaterBB);
1109*065e0324SZi Xuan Wu 
1110*065e0324SZi Xuan Wu     // We are adding new water.  Update NewWaterList.
1111*065e0324SZi Xuan Wu     NewWaterList.insert(NewIsland);
1112*065e0324SZi Xuan Wu   }
1113*065e0324SZi Xuan Wu 
1114*065e0324SZi Xuan Wu   // Remove the original WaterList entry; we want subsequent insertions in
1115*065e0324SZi Xuan Wu   // this vicinity to go after the one we're about to insert.  This
1116*065e0324SZi Xuan Wu   // considerably reduces the number of times we have to move the same CPE
1117*065e0324SZi Xuan Wu   // more than once and is also important to ensure the algorithm terminates.
1118*065e0324SZi Xuan Wu   if (IP != WaterList.end())
1119*065e0324SZi Xuan Wu     WaterList.erase(IP);
1120*065e0324SZi Xuan Wu 
1121*065e0324SZi Xuan Wu   // Okay, we know we can put an island before NewMBB now, do it!
1122*065e0324SZi Xuan Wu   MF->insert(NewMBB->getIterator(), NewIsland);
1123*065e0324SZi Xuan Wu 
1124*065e0324SZi Xuan Wu   // Update internal data structures to account for the newly inserted MBB.
1125*065e0324SZi Xuan Wu   updateForInsertedWaterBlock(NewIsland);
1126*065e0324SZi Xuan Wu 
1127*065e0324SZi Xuan Wu   // Decrement the old entry, and remove it if refcount becomes 0.
1128*065e0324SZi Xuan Wu   decrementCPEReferenceCount(CPI, CPEMI);
1129*065e0324SZi Xuan Wu 
1130*065e0324SZi Xuan Wu   // No existing clone of this CPE is within range.
1131*065e0324SZi Xuan Wu   // We will be generating a new clone.  Get a UID for it.
1132*065e0324SZi Xuan Wu   unsigned ID = createPICLabelUId();
1133*065e0324SZi Xuan Wu 
1134*065e0324SZi Xuan Wu   // Now that we have an island to add the CPE to, clone the original CPE and
1135*065e0324SZi Xuan Wu   // add it to the island.
1136*065e0324SZi Xuan Wu   U.HighWaterMark = NewIsland;
1137*065e0324SZi Xuan Wu   U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(CSKY::CONSTPOOL_ENTRY))
1138*065e0324SZi Xuan Wu                 .addImm(ID)
1139*065e0324SZi Xuan Wu                 .addConstantPoolIndex(CPI)
1140*065e0324SZi Xuan Wu                 .addImm(Size);
1141*065e0324SZi Xuan Wu   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1142*065e0324SZi Xuan Wu   ++NumCPEs;
1143*065e0324SZi Xuan Wu 
1144*065e0324SZi Xuan Wu   // Mark the basic block as aligned as required by the const-pool entry.
1145*065e0324SZi Xuan Wu   NewIsland->setAlignment(getCPEAlign(*U.CPEMI));
1146*065e0324SZi Xuan Wu 
1147*065e0324SZi Xuan Wu   // Increase the size of the island block to account for the new entry.
1148*065e0324SZi Xuan Wu   BBInfo[NewIsland->getNumber()].Size += Size;
1149*065e0324SZi Xuan Wu   adjustBBOffsetsAfter(&*--NewIsland->getIterator());
1150*065e0324SZi Xuan Wu 
1151*065e0324SZi Xuan Wu   // Finally, change the CPI in the instruction operand to be ID.
1152*065e0324SZi Xuan Wu   for (unsigned I = 0, E = UserMI->getNumOperands(); I != E; ++I)
1153*065e0324SZi Xuan Wu     if (UserMI->getOperand(I).isCPI()) {
1154*065e0324SZi Xuan Wu       UserMI->getOperand(I).setIndex(ID);
1155*065e0324SZi Xuan Wu       break;
1156*065e0324SZi Xuan Wu     }
1157*065e0324SZi Xuan Wu 
1158*065e0324SZi Xuan Wu   LLVM_DEBUG(
1159*065e0324SZi Xuan Wu       dbgs() << "  Moved CPE to #" << ID << " CPI=" << CPI
1160*065e0324SZi Xuan Wu              << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1161*065e0324SZi Xuan Wu 
1162*065e0324SZi Xuan Wu   return true;
1163*065e0324SZi Xuan Wu }
1164*065e0324SZi Xuan Wu 
1165*065e0324SZi Xuan Wu /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1166*065e0324SZi Xuan Wu /// sizes and offsets of impacted basic blocks.
1167*065e0324SZi Xuan Wu void CSKYConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1168*065e0324SZi Xuan Wu   MachineBasicBlock *CPEBB = CPEMI->getParent();
1169*065e0324SZi Xuan Wu   unsigned Size = CPEMI->getOperand(2).getImm();
1170*065e0324SZi Xuan Wu   CPEMI->eraseFromParent();
1171*065e0324SZi Xuan Wu   BBInfo[CPEBB->getNumber()].Size -= Size;
1172*065e0324SZi Xuan Wu   // All succeeding offsets have the current size value added in, fix this.
1173*065e0324SZi Xuan Wu   if (CPEBB->empty()) {
1174*065e0324SZi Xuan Wu     BBInfo[CPEBB->getNumber()].Size = 0;
1175*065e0324SZi Xuan Wu 
1176*065e0324SZi Xuan Wu     // This block no longer needs to be aligned.
1177*065e0324SZi Xuan Wu     CPEBB->setAlignment(Align(4));
1178*065e0324SZi Xuan Wu   } else {
1179*065e0324SZi Xuan Wu     // Entries are sorted by descending alignment, so realign from the front.
1180*065e0324SZi Xuan Wu     CPEBB->setAlignment(getCPEAlign(*CPEBB->begin()));
1181*065e0324SZi Xuan Wu   }
1182*065e0324SZi Xuan Wu 
1183*065e0324SZi Xuan Wu   adjustBBOffsetsAfter(CPEBB);
1184*065e0324SZi Xuan Wu   // An island has only one predecessor BB and one successor BB. Check if
1185*065e0324SZi Xuan Wu   // this BB's predecessor jumps directly to this BB's successor. This
1186*065e0324SZi Xuan Wu   // shouldn't happen currently.
1187*065e0324SZi Xuan Wu   assert(!bbIsJumpedOver(CPEBB) && "How did this happen?");
1188*065e0324SZi Xuan Wu   // FIXME: remove the empty blocks after all the work is done?
1189*065e0324SZi Xuan Wu }
1190*065e0324SZi Xuan Wu 
1191*065e0324SZi Xuan Wu /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1192*065e0324SZi Xuan Wu /// are zero.
1193*065e0324SZi Xuan Wu bool CSKYConstantIslands::removeUnusedCPEntries() {
1194*065e0324SZi Xuan Wu   unsigned MadeChange = false;
1195*065e0324SZi Xuan Wu   for (unsigned I = 0, E = CPEntries.size(); I != E; ++I) {
1196*065e0324SZi Xuan Wu     std::vector<CPEntry> &CPEs = CPEntries[I];
1197*065e0324SZi Xuan Wu     for (unsigned J = 0, Ee = CPEs.size(); J != Ee; ++J) {
1198*065e0324SZi Xuan Wu       if (CPEs[J].RefCount == 0 && CPEs[J].CPEMI) {
1199*065e0324SZi Xuan Wu         removeDeadCPEMI(CPEs[J].CPEMI);
1200*065e0324SZi Xuan Wu         CPEs[J].CPEMI = nullptr;
1201*065e0324SZi Xuan Wu         MadeChange = true;
1202*065e0324SZi Xuan Wu       }
1203*065e0324SZi Xuan Wu     }
1204*065e0324SZi Xuan Wu   }
1205*065e0324SZi Xuan Wu   return MadeChange;
1206*065e0324SZi Xuan Wu }
1207*065e0324SZi Xuan Wu 
1208*065e0324SZi Xuan Wu /// isBBInRange - Returns true if the distance between specific MI and
1209*065e0324SZi Xuan Wu /// specific BB can fit in MI's displacement field.
1210*065e0324SZi Xuan Wu bool CSKYConstantIslands::isBBInRange(MachineInstr *MI,
1211*065e0324SZi Xuan Wu                                       MachineBasicBlock *DestBB,
1212*065e0324SZi Xuan Wu                                       unsigned MaxDisp) {
1213*065e0324SZi Xuan Wu   unsigned BrOffset = getOffsetOf(MI);
1214*065e0324SZi Xuan Wu   unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1215*065e0324SZi Xuan Wu 
1216*065e0324SZi Xuan Wu   LLVM_DEBUG(dbgs() << "Branch of destination " << printMBBReference(*DestBB)
1217*065e0324SZi Xuan Wu                     << " from " << printMBBReference(*MI->getParent())
1218*065e0324SZi Xuan Wu                     << " max delta=" << MaxDisp << " from " << getOffsetOf(MI)
1219*065e0324SZi Xuan Wu                     << " to " << DestOffset << " offset "
1220*065e0324SZi Xuan Wu                     << int(DestOffset - BrOffset) << "\t" << *MI);
1221*065e0324SZi Xuan Wu 
1222*065e0324SZi Xuan Wu   if (BrOffset <= DestOffset) {
1223*065e0324SZi Xuan Wu     // Branch before the Dest.
1224*065e0324SZi Xuan Wu     if (DestOffset - BrOffset <= MaxDisp)
1225*065e0324SZi Xuan Wu       return true;
1226*065e0324SZi Xuan Wu   } else {
1227*065e0324SZi Xuan Wu     if (BrOffset - DestOffset <= MaxDisp)
1228*065e0324SZi Xuan Wu       return true;
1229*065e0324SZi Xuan Wu   }
1230*065e0324SZi Xuan Wu   return false;
1231*065e0324SZi Xuan Wu }
1232*065e0324SZi Xuan Wu 
1233*065e0324SZi Xuan Wu /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1234*065e0324SZi Xuan Wu /// away to fit in its displacement field.
1235*065e0324SZi Xuan Wu bool CSKYConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1236*065e0324SZi Xuan Wu   MachineInstr *MI = Br.MI;
1237*065e0324SZi Xuan Wu   MachineBasicBlock *DestBB = TII->getBranchDestBlock(*MI);
1238*065e0324SZi Xuan Wu 
1239*065e0324SZi Xuan Wu   // Check to see if the DestBB is already in-range.
1240*065e0324SZi Xuan Wu   if (isBBInRange(MI, DestBB, Br.MaxDisp))
1241*065e0324SZi Xuan Wu     return false;
1242*065e0324SZi Xuan Wu 
1243*065e0324SZi Xuan Wu   if (!Br.IsCond)
1244*065e0324SZi Xuan Wu     return fixupUnconditionalBr(Br);
1245*065e0324SZi Xuan Wu   return fixupConditionalBr(Br);
1246*065e0324SZi Xuan Wu }
1247*065e0324SZi Xuan Wu 
1248*065e0324SZi Xuan Wu /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1249*065e0324SZi Xuan Wu /// too far away to fit in its displacement field. If the LR register has been
1250*065e0324SZi Xuan Wu /// spilled in the epilogue, then we can use BSR to implement a far jump.
1251*065e0324SZi Xuan Wu /// Otherwise, add an intermediate branch instruction to a branch.
1252*065e0324SZi Xuan Wu bool CSKYConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1253*065e0324SZi Xuan Wu   MachineInstr *MI = Br.MI;
1254*065e0324SZi Xuan Wu   MachineBasicBlock *MBB = MI->getParent();
1255*065e0324SZi Xuan Wu 
1256*065e0324SZi Xuan Wu   if (!MFI->isLRSpilled())
1257*065e0324SZi Xuan Wu     report_fatal_error("underestimated function size");
1258*065e0324SZi Xuan Wu 
1259*065e0324SZi Xuan Wu   // Use BSR to implement far jump.
1260*065e0324SZi Xuan Wu   Br.MaxDisp = ((1 << (26 - 1)) - 1) * 2;
1261*065e0324SZi Xuan Wu   MI->setDesc(TII->get(CSKY::BSR32_BR));
1262*065e0324SZi Xuan Wu   BBInfo[MBB->getNumber()].Size += 4;
1263*065e0324SZi Xuan Wu   adjustBBOffsetsAfter(MBB);
1264*065e0324SZi Xuan Wu   ++NumUBrFixed;
1265*065e0324SZi Xuan Wu 
1266*065e0324SZi Xuan Wu   LLVM_DEBUG(dbgs() << "  Changed B to long jump " << *MI);
1267*065e0324SZi Xuan Wu 
1268*065e0324SZi Xuan Wu   return true;
1269*065e0324SZi Xuan Wu }
1270*065e0324SZi Xuan Wu 
1271*065e0324SZi Xuan Wu /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1272*065e0324SZi Xuan Wu /// far away to fit in its displacement field. It is converted to an inverse
1273*065e0324SZi Xuan Wu /// conditional branch + an unconditional branch to the destination.
1274*065e0324SZi Xuan Wu bool CSKYConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1275*065e0324SZi Xuan Wu   MachineInstr *MI = Br.MI;
1276*065e0324SZi Xuan Wu   MachineBasicBlock *DestBB = TII->getBranchDestBlock(*MI);
1277*065e0324SZi Xuan Wu 
1278*065e0324SZi Xuan Wu   SmallVector<MachineOperand, 4> Cond;
1279*065e0324SZi Xuan Wu   Cond.push_back(MachineOperand::CreateImm(MI->getOpcode()));
1280*065e0324SZi Xuan Wu   Cond.push_back(MI->getOperand(0));
1281*065e0324SZi Xuan Wu   TII->reverseBranchCondition(Cond);
1282*065e0324SZi Xuan Wu 
1283*065e0324SZi Xuan Wu   // Add an unconditional branch to the destination and invert the branch
1284*065e0324SZi Xuan Wu   // condition to jump over it:
1285*065e0324SZi Xuan Wu   // bteqz L1
1286*065e0324SZi Xuan Wu   // =>
1287*065e0324SZi Xuan Wu   // bnez L2
1288*065e0324SZi Xuan Wu   // b   L1
1289*065e0324SZi Xuan Wu   // L2:
1290*065e0324SZi Xuan Wu 
1291*065e0324SZi Xuan Wu   // If the branch is at the end of its MBB and that has a fall-through block,
1292*065e0324SZi Xuan Wu   // direct the updated conditional branch to the fall-through block. Otherwise,
1293*065e0324SZi Xuan Wu   // split the MBB before the next instruction.
1294*065e0324SZi Xuan Wu   MachineBasicBlock *MBB = MI->getParent();
1295*065e0324SZi Xuan Wu   MachineInstr *BMI = &MBB->back();
1296*065e0324SZi Xuan Wu   bool NeedSplit = (BMI != MI) || !bbHasFallthrough(MBB);
1297*065e0324SZi Xuan Wu 
1298*065e0324SZi Xuan Wu   ++NumCBrFixed;
1299*065e0324SZi Xuan Wu   if (BMI != MI) {
1300*065e0324SZi Xuan Wu     if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1301*065e0324SZi Xuan Wu         BMI->isUnconditionalBranch()) {
1302*065e0324SZi Xuan Wu       // Last MI in the BB is an unconditional branch. Can we simply invert the
1303*065e0324SZi Xuan Wu       // condition and swap destinations:
1304*065e0324SZi Xuan Wu       // beqz L1
1305*065e0324SZi Xuan Wu       // b   L2
1306*065e0324SZi Xuan Wu       // =>
1307*065e0324SZi Xuan Wu       // bnez L2
1308*065e0324SZi Xuan Wu       // b   L1
1309*065e0324SZi Xuan Wu       MachineBasicBlock *NewDest = TII->getBranchDestBlock(*BMI);
1310*065e0324SZi Xuan Wu       if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1311*065e0324SZi Xuan Wu         LLVM_DEBUG(
1312*065e0324SZi Xuan Wu             dbgs() << "  Invert Bcc condition and swap its destination with "
1313*065e0324SZi Xuan Wu                    << *BMI);
1314*065e0324SZi Xuan Wu         BMI->getOperand(BMI->getNumExplicitOperands() - 1).setMBB(DestBB);
1315*065e0324SZi Xuan Wu         MI->getOperand(MI->getNumExplicitOperands() - 1).setMBB(NewDest);
1316*065e0324SZi Xuan Wu 
1317*065e0324SZi Xuan Wu         MI->setDesc(TII->get(Cond[0].getImm()));
1318*065e0324SZi Xuan Wu         return true;
1319*065e0324SZi Xuan Wu       }
1320*065e0324SZi Xuan Wu     }
1321*065e0324SZi Xuan Wu   }
1322*065e0324SZi Xuan Wu 
1323*065e0324SZi Xuan Wu   if (NeedSplit) {
1324*065e0324SZi Xuan Wu     splitBlockBeforeInstr(*MI);
1325*065e0324SZi Xuan Wu     // No need for the branch to the next block. We're adding an unconditional
1326*065e0324SZi Xuan Wu     // branch to the destination.
1327*065e0324SZi Xuan Wu     int Delta = TII->getInstSizeInBytes(MBB->back());
1328*065e0324SZi Xuan Wu     BBInfo[MBB->getNumber()].Size -= Delta;
1329*065e0324SZi Xuan Wu     MBB->back().eraseFromParent();
1330*065e0324SZi Xuan Wu     // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1331*065e0324SZi Xuan Wu 
1332*065e0324SZi Xuan Wu     // The conditional successor will be swapped between the BBs after this, so
1333*065e0324SZi Xuan Wu     // update CFG.
1334*065e0324SZi Xuan Wu     MBB->addSuccessor(DestBB);
1335*065e0324SZi Xuan Wu     std::next(MBB->getIterator())->removeSuccessor(DestBB);
1336*065e0324SZi Xuan Wu   }
1337*065e0324SZi Xuan Wu   MachineBasicBlock *NextBB = &*++MBB->getIterator();
1338*065e0324SZi Xuan Wu 
1339*065e0324SZi Xuan Wu   LLVM_DEBUG(dbgs() << "  Insert B to " << printMBBReference(*DestBB)
1340*065e0324SZi Xuan Wu                     << " also invert condition and change dest. to "
1341*065e0324SZi Xuan Wu                     << printMBBReference(*NextBB) << "\n");
1342*065e0324SZi Xuan Wu 
1343*065e0324SZi Xuan Wu   // Insert a new conditional branch and a new unconditional branch.
1344*065e0324SZi Xuan Wu   // Also update the ImmBranch as well as adding a new entry for the new branch.
1345*065e0324SZi Xuan Wu 
1346*065e0324SZi Xuan Wu   BuildMI(MBB, DebugLoc(), TII->get(Cond[0].getImm()))
1347*065e0324SZi Xuan Wu       .addReg(MI->getOperand(0).getReg())
1348*065e0324SZi Xuan Wu       .addMBB(NextBB);
1349*065e0324SZi Xuan Wu 
1350*065e0324SZi Xuan Wu   Br.MI = &MBB->back();
1351*065e0324SZi Xuan Wu   BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1352*065e0324SZi Xuan Wu   BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1353*065e0324SZi Xuan Wu   BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1354*065e0324SZi Xuan Wu   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1355*065e0324SZi Xuan Wu   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1356*065e0324SZi Xuan Wu 
1357*065e0324SZi Xuan Wu   // Remove the old conditional branch.  It may or may not still be in MBB.
1358*065e0324SZi Xuan Wu   BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
1359*065e0324SZi Xuan Wu   MI->eraseFromParent();
1360*065e0324SZi Xuan Wu   adjustBBOffsetsAfter(MBB);
1361*065e0324SZi Xuan Wu   return true;
1362*065e0324SZi Xuan Wu }
1363*065e0324SZi Xuan Wu 
1364*065e0324SZi Xuan Wu /// Returns a pass that converts branches to long branches.
1365*065e0324SZi Xuan Wu FunctionPass *llvm::createCSKYConstantIslandPass() {
1366*065e0324SZi Xuan Wu   return new CSKYConstantIslands();
1367*065e0324SZi Xuan Wu }
1368*065e0324SZi Xuan Wu 
1369*065e0324SZi Xuan Wu INITIALIZE_PASS(CSKYConstantIslands, DEBUG_TYPE,
1370*065e0324SZi Xuan Wu                 "CSKY constant island placement and branch shortening pass",
1371*065e0324SZi Xuan Wu                 false, false)
1372