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