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