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