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