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