blob: 80bf573a962505876b58cef7791dc4341bc74685 [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
Alp Tokerf907b892013-12-05 05:44:44 +000020// non-linux targets.
Reed Kotlerbb3094a2013-02-27 03:33:58 +000021//
22//
23
Reed Kotlerbb3094a2013-02-27 03:33:58 +000024#include "Mips.h"
25#include "MCTargetDesc/MipsBaseInfo.h"
Reed Kotler5c8ae092013-11-13 04:37:52 +000026#include "Mips16InstrInfo.h"
Reed Kotler0f007fc2013-11-05 08:14:14 +000027#include "MipsMachineFunction.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000028#include "MipsTargetMachine.h"
29#include "llvm/ADT/Statistic.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000030#include "llvm/CodeGen/MachineBasicBlock.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000031#include "llvm/CodeGen/MachineFunctionPass.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000033#include "llvm/CodeGen/MachineRegisterInfo.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000034#include "llvm/IR/Function.h"
Chandler Carruth83948572014-03-04 10:30:26 +000035#include "llvm/IR/InstIterator.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000036#include "llvm/Support/CommandLine.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000037#include "llvm/Support/Debug.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000038#include "llvm/Support/Format.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000039#include "llvm/Support/MathExtras.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000040#include "llvm/Support/raw_ostream.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000041#include "llvm/Target/TargetInstrInfo.h"
42#include "llvm/Target/TargetMachine.h"
43#include "llvm/Target/TargetRegisterInfo.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000044#include <algorithm>
Reed Kotlerbb3094a2013-02-27 03:33:58 +000045
46using namespace llvm;
47
Chandler Carruth84e68b22014-04-22 02:41:26 +000048#define DEBUG_TYPE "mips-constant-islands"
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 Kotler0d409e22013-11-28 00:56:37 +000080static unsigned int branchTargetOperand(MachineInstr *MI) {
81 switch (MI->getOpcode()) {
82 case Mips::Bimm16:
83 case Mips::BimmX16:
84 case Mips::Bteqz16:
85 case Mips::BteqzX16:
86 case Mips::Btnez16:
87 case Mips::BtnezX16:
Reed Kotlerad450f22013-11-29 22:32:56 +000088 case Mips::JalB16:
Reed Kotler0d409e22013-11-28 00:56:37 +000089 return 0;
90 case Mips::BeqzRxImm16:
91 case Mips::BeqzRxImmX16:
92 case Mips::BnezRxImm16:
93 case Mips::BnezRxImmX16:
94 return 1;
95 }
96 llvm_unreachable("Unknown branch type");
97}
98
Reed Kotlerad450f22013-11-29 22:32:56 +000099static bool isUnconditionalBranch(unsigned int Opcode) {
100 switch (Opcode) {
101 default: return false;
102 case Mips::Bimm16:
103 case Mips::BimmX16:
104 case Mips::JalB16:
105 return true;
106 }
107}
108
Reed Kotler0d409e22013-11-28 00:56:37 +0000109static unsigned int longformBranchOpcode(unsigned int Opcode) {
110 switch (Opcode) {
111 case Mips::Bimm16:
112 case Mips::BimmX16:
113 return Mips::BimmX16;
114 case Mips::Bteqz16:
115 case Mips::BteqzX16:
116 return Mips::BteqzX16;
117 case Mips::Btnez16:
118 case Mips::BtnezX16:
119 return Mips::BtnezX16;
Reed Kotlerad450f22013-11-29 22:32:56 +0000120 case Mips::JalB16:
121 return Mips::JalB16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000122 case Mips::BeqzRxImm16:
123 case Mips::BeqzRxImmX16:
124 return Mips::BeqzRxImmX16;
125 case Mips::BnezRxImm16:
126 case Mips::BnezRxImmX16:
127 return Mips::BnezRxImmX16;
128 }
129 llvm_unreachable("Unknown branch type");
130}
131
132//
133// FIXME: need to go through this whole constant islands port and check the math
134// for branch ranges and clean this up and make some functions to calculate things
135// that are done many times identically.
136// Need to refactor some of the code to call this routine.
137//
138static unsigned int branchMaxOffsets(unsigned int Opcode) {
139 unsigned Bits, Scale;
140 switch (Opcode) {
141 case Mips::Bimm16:
142 Bits = 11;
143 Scale = 2;
144 break;
145 case Mips::BimmX16:
146 Bits = 16;
147 Scale = 2;
148 break;
149 case Mips::BeqzRxImm16:
150 Bits = 8;
151 Scale = 2;
152 break;
153 case Mips::BeqzRxImmX16:
154 Bits = 16;
155 Scale = 2;
156 break;
157 case Mips::BnezRxImm16:
158 Bits = 8;
159 Scale = 2;
160 break;
161 case Mips::BnezRxImmX16:
162 Bits = 16;
163 Scale = 2;
164 break;
165 case Mips::Bteqz16:
166 Bits = 8;
167 Scale = 2;
168 break;
169 case Mips::BteqzX16:
170 Bits = 16;
171 Scale = 2;
172 break;
173 case Mips::Btnez16:
174 Bits = 8;
175 Scale = 2;
176 break;
177 case Mips::BtnezX16:
178 Bits = 16;
179 Scale = 2;
180 break;
181 default:
182 llvm_unreachable("Unknown branch type");
183 }
184 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
185 return MaxOffs;
186}
Reed Kotler0f007fc2013-11-05 08:14:14 +0000187
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000188namespace {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000189
190
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000191 typedef MachineBasicBlock::iterator Iter;
192 typedef MachineBasicBlock::reverse_iterator ReverseIter;
193
Reed Kotler0f007fc2013-11-05 08:14:14 +0000194 /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
195 /// requires constant pool entries to be scattered among the instructions
196 /// inside a function. To do this, it completely ignores the normal LLVM
197 /// constant pool; instead, it places constants wherever it feels like with
198 /// special instructions.
199 ///
200 /// The terminology used in this pass includes:
201 /// Islands - Clumps of constants placed in the function.
202 /// Water - Potential places where an island could be formed.
203 /// CPE - A constant pool entry that has been placed somewhere, which
204 /// tracks a list of users.
205
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000206 class MipsConstantIslands : public MachineFunctionPass {
207
Reed Kotler0f007fc2013-11-05 08:14:14 +0000208 /// BasicBlockInfo - Information about the offset and size of a single
209 /// basic block.
210 struct BasicBlockInfo {
211 /// Offset - Distance from the beginning of the function to the beginning
212 /// of this basic block.
213 ///
214 /// Offsets are computed assuming worst case padding before an aligned
215 /// block. This means that subtracting basic block offsets always gives a
216 /// conservative estimate of the real distance which may be smaller.
217 ///
218 /// Because worst case padding is used, the computed offset of an aligned
219 /// block may not actually be aligned.
220 unsigned Offset;
221
222 /// Size - Size of the basic block in bytes. If the block contains
223 /// inline assembly, this is a worst case estimate.
224 ///
225 /// The size does not include any alignment padding whether from the
226 /// beginning of the block, or from an aligned jump table at the end.
227 unsigned Size;
228
Reed Kotler7ded5b62013-11-05 23:36:58 +0000229 // FIXME: ignore LogAlign for this patch
230 //
Reed Kotler0f007fc2013-11-05 08:14:14 +0000231 unsigned postOffset(unsigned LogAlign = 0) const {
232 unsigned PO = Offset + Size;
233 return PO;
234 }
235
Reed Kotler7ded5b62013-11-05 23:36:58 +0000236 BasicBlockInfo() : Offset(0), Size(0) {}
237
Reed Kotler0f007fc2013-11-05 08:14:14 +0000238 };
239
240 std::vector<BasicBlockInfo> BBInfo;
241
242 /// WaterList - A sorted list of basic blocks where islands could be placed
243 /// (i.e. blocks that don't fall through to the following block, due
244 /// to a return, unreachable, or unconditional branch).
245 std::vector<MachineBasicBlock*> WaterList;
246
247 /// NewWaterList - The subset of WaterList that was created since the
248 /// previous iteration by inserting unconditional branches.
249 SmallSet<MachineBasicBlock*, 4> NewWaterList;
250
251 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
252
253 /// CPUser - One user of a constant pool, keeping the machine instruction
254 /// pointer, the constant pool being referenced, and the max displacement
255 /// allowed from the instruction to the CP. The HighWaterMark records the
256 /// highest basic block where a new CPEntry can be placed. To ensure this
257 /// pass terminates, the CP entries are initially placed at the end of the
258 /// function and then move monotonically to lower addresses. The
259 /// exception to this rule is when the current CP entry for a particular
260 /// CPUser is out of range, but there is another CP entry for the same
261 /// constant value in range. We want to use the existing in-range CP
262 /// entry, but if it later moves out of range, the search for new water
263 /// should resume where it left off. The HighWaterMark is used to record
264 /// that point.
265 struct CPUser {
266 MachineInstr *MI;
267 MachineInstr *CPEMI;
268 MachineBasicBlock *HighWaterMark;
269 private:
270 unsigned MaxDisp;
271 unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
272 // with different displacements
273 unsigned LongFormOpcode;
274 public:
275 bool NegOk;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000276 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000277 bool neg,
Reed Kotler0f007fc2013-11-05 08:14:14 +0000278 unsigned longformmaxdisp, unsigned longformopcode)
279 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
280 LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
Reed Kotler7ded5b62013-11-05 23:36:58 +0000281 NegOk(neg){
Reed Kotler0f007fc2013-11-05 08:14:14 +0000282 HighWaterMark = CPEMI->getParent();
283 }
284 /// getMaxDisp - Returns the maximum displacement supported by MI.
Reed Kotler0f007fc2013-11-05 08:14:14 +0000285 unsigned getMaxDisp() const {
286 unsigned xMaxDisp = ConstantIslandsSmallOffset?
287 ConstantIslandsSmallOffset: MaxDisp;
Reed Kotler7ded5b62013-11-05 23:36:58 +0000288 return xMaxDisp;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000289 }
Reed Kotler45c59272013-11-10 00:09:26 +0000290 void setMaxDisp(unsigned val) {
291 MaxDisp = val;
292 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000293 unsigned getLongFormMaxDisp() const {
Reed Kotler7ded5b62013-11-05 23:36:58 +0000294 return LongFormMaxDisp;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000295 }
296 unsigned getLongFormOpcode() const {
297 return LongFormOpcode;
298 }
299 };
300
301 /// CPUsers - Keep track of all of the machine instructions that use various
302 /// constant pools and their max displacement.
303 std::vector<CPUser> CPUsers;
Reed Kotler91ae9822013-10-27 21:57:36 +0000304
305 /// CPEntry - One per constant pool entry, keeping the machine instruction
306 /// pointer, the constpool index, and the number of CPUser's which
307 /// reference this entry.
308 struct CPEntry {
309 MachineInstr *CPEMI;
310 unsigned CPI;
311 unsigned RefCount;
312 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
313 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
314 };
315
316 /// CPEntries - Keep track of all of the constant pool entry machine
317 /// instructions. For each original constpool index (i.e. those that
318 /// existed upon entry to this pass), it keeps a vector of entries.
319 /// Original elements are cloned as we go along; the clones are
320 /// put in the vector of the original element, but have distinct CPIs.
321 std::vector<std::vector<CPEntry> > CPEntries;
322
Reed Kotler0f007fc2013-11-05 08:14:14 +0000323 /// ImmBranch - One per immediate branch, keeping the machine instruction
324 /// pointer, conditional or unconditional, the max displacement,
325 /// and (if isCond is true) the corresponding unconditional branch
326 /// opcode.
327 struct ImmBranch {
328 MachineInstr *MI;
329 unsigned MaxDisp : 31;
330 bool isCond : 1;
331 int UncondBr;
332 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
333 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
334 };
335
336 /// ImmBranches - Keep track of all the immediate branch instructions.
337 ///
338 std::vector<ImmBranch> ImmBranches;
339
340 /// HasFarJump - True if any far jump instruction has been emitted during
341 /// the branch fix up pass.
342 bool HasFarJump;
343
344 const TargetMachine &TM;
345 bool IsPIC;
346 unsigned ABI;
347 const MipsSubtarget *STI;
Reed Kotler5c8ae092013-11-13 04:37:52 +0000348 const Mips16InstrInfo *TII;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000349 MipsFunctionInfo *MFI;
350 MachineFunction *MF;
351 MachineConstantPool *MCP;
352
353 unsigned PICLabelUId;
354 bool PrescannedForConstants;
355
356 void initPICLabelUId(unsigned UId) {
357 PICLabelUId = UId;
358 }
359
360
361 unsigned createPICLabelUId() {
362 return PICLabelUId++;
363 }
364
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000365 public:
366 static char ID;
367 MipsConstantIslands(TargetMachine &tm)
Eric Christopher4e7d1e72014-07-18 23:41:32 +0000368 : MachineFunctionPass(ID), TM(tm),
369 IsPIC(TM.getRelocationModel() == Reloc::PIC_),
370 ABI(TM.getSubtarget<MipsSubtarget>().getTargetABI()), STI(nullptr),
371 MF(nullptr), MCP(nullptr), PrescannedForConstants(false) {}
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000372
Craig Topper56c590a2014-04-29 07:58:02 +0000373 const char *getPassName() const override {
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000374 return "Mips Constant Islands";
375 }
376
Craig Topper56c590a2014-04-29 07:58:02 +0000377 bool runOnMachineFunction(MachineFunction &F) override;
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000378
Reed Kotler91ae9822013-10-27 21:57:36 +0000379 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000380 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
381 unsigned getCPELogAlign(const MachineInstr *CPEMI);
382 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
383 unsigned getOffsetOf(MachineInstr *MI) const;
384 unsigned getUserOffset(CPUser&) const;
385 void dumpBBs();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000386
387 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000388 unsigned Disp, bool NegativeOK);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000389 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
390 const CPUser &U);
391
Reed Kotler0f007fc2013-11-05 08:14:14 +0000392 void computeBlockSize(MachineBasicBlock *MBB);
393 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
394 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
395 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
396 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
397 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
398 int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
399 bool findAvailableWater(CPUser&U, unsigned UserOffset,
400 water_iterator &WaterIter);
401 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
402 MachineBasicBlock *&NewMBB);
403 bool handleConstantPoolUser(unsigned CPUserIndex);
404 void removeDeadCPEMI(MachineInstr *CPEMI);
405 bool removeUnusedCPEntries();
406 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
407 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
408 bool DoDump = false);
409 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
410 CPUser &U, unsigned &Growth);
411 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
412 bool fixupImmediateBr(ImmBranch &Br);
413 bool fixupConditionalBr(ImmBranch &Br);
414 bool fixupUnconditionalBr(ImmBranch &Br);
Reed Kotler91ae9822013-10-27 21:57:36 +0000415
416 void prescanForConstants();
417
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000418 private:
Reed Kotler91ae9822013-10-27 21:57:36 +0000419
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000420 };
421
422 char MipsConstantIslands::ID = 0;
423} // end of anonymous namespace
424
Reed Kotler0f007fc2013-11-05 08:14:14 +0000425bool MipsConstantIslands::isOffsetInRange
426 (unsigned UserOffset, unsigned TrialOffset,
427 const CPUser &U) {
428 return isOffsetInRange(UserOffset, TrialOffset,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000429 U.getMaxDisp(), U.NegOk);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000430}
431/// print block size and offset information - debugging
432void MipsConstantIslands::dumpBBs() {
433 DEBUG({
434 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
435 const BasicBlockInfo &BBI = BBInfo[J];
436 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
Reed Kotler0f007fc2013-11-05 08:14:14 +0000437 << format(" size=%#x\n", BBInfo[J].Size);
438 }
439 });
440}
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000441/// createMipsLongBranchPass - Returns a pass that converts branches to long
442/// branches.
443FunctionPass *llvm::createMipsConstantIslandPass(MipsTargetMachine &tm) {
444 return new MipsConstantIslands(tm);
445}
446
Reed Kotler91ae9822013-10-27 21:57:36 +0000447bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
Reed Kotler1595f362013-04-09 19:46:01 +0000448 // The intention is for this to be a mips16 only pass for now
449 // FIXME:
Reed Kotler91ae9822013-10-27 21:57:36 +0000450 MF = &mf;
451 MCP = mf.getConstantPool();
Eric Christopher4e7d1e72014-07-18 23:41:32 +0000452 STI = &mf.getTarget().getSubtarget<MipsSubtarget>();
Reed Kotler91ae9822013-10-27 21:57:36 +0000453 DEBUG(dbgs() << "constant island machine function " << "\n");
Eric Christopher4e7d1e72014-07-18 23:41:32 +0000454 if (!STI->inMips16Mode() || !MipsSubtarget::useConstantIslands()) {
Reed Kotler91ae9822013-10-27 21:57:36 +0000455 return false;
456 }
Reed Kotler5c8ae092013-11-13 04:37:52 +0000457 TII = (const Mips16InstrInfo*)MF->getTarget().getInstrInfo();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000458 MFI = MF->getInfo<MipsFunctionInfo>();
Reed Kotler91ae9822013-10-27 21:57:36 +0000459 DEBUG(dbgs() << "constant island processing " << "\n");
460 //
461 // will need to make predermination if there is any constants we need to
462 // put in constant islands. TBD.
463 //
Reed Kotler0f007fc2013-11-05 08:14:14 +0000464 if (!PrescannedForConstants) prescanForConstants();
Reed Kotler91ae9822013-10-27 21:57:36 +0000465
Reed Kotler0f007fc2013-11-05 08:14:14 +0000466 HasFarJump = false;
Reed Kotler91ae9822013-10-27 21:57:36 +0000467 // This pass invalidates liveness information when it splits basic blocks.
468 MF->getRegInfo().invalidateLiveness();
469
470 // Renumber all of the machine basic blocks in the function, guaranteeing that
471 // the numbers agree with the position of the block in the function.
472 MF->RenumberBlocks();
473
Reed Kotler0f007fc2013-11-05 08:14:14 +0000474 bool MadeChange = false;
475
Reed Kotler91ae9822013-10-27 21:57:36 +0000476 // Perform the initial placement of the constant pool entries. To start with,
477 // we put them all at the end of the function.
478 std::vector<MachineInstr*> CPEMIs;
479 if (!MCP->isEmpty())
480 doInitialPlacement(CPEMIs);
481
Reed Kotler0f007fc2013-11-05 08:14:14 +0000482 /// The next UID to take is the first unused one.
483 initPICLabelUId(CPEMIs.size());
484
485 // Do the initial scan of the function, building up information about the
486 // sizes of each block, the location of all the water, and finding all of the
487 // constant pool users.
488 initializeFunctionInfo(CPEMIs);
489 CPEMIs.clear();
490 DEBUG(dumpBBs());
491
492 /// Remove dead constant pool entries.
493 MadeChange |= removeUnusedCPEntries();
494
495 // Iteratively place constant pool entries and fix up branches until there
496 // is no change.
497 unsigned NoCPIters = 0, NoBRIters = 0;
498 (void)NoBRIters;
499 while (true) {
500 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
501 bool CPChange = false;
502 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
503 CPChange |= handleConstantPoolUser(i);
504 if (CPChange && ++NoCPIters > 30)
505 report_fatal_error("Constant Island pass failed to converge!");
506 DEBUG(dumpBBs());
507
508 // Clear NewWaterList now. If we split a block for branches, it should
509 // appear as "new water" for the next iteration of constant pool placement.
510 NewWaterList.clear();
511
512 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
513 bool BRChange = false;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000514 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
515 BRChange |= fixupImmediateBr(ImmBranches[i]);
516 if (BRChange && ++NoBRIters > 30)
517 report_fatal_error("Branch Fix Up pass failed to converge!");
518 DEBUG(dumpBBs());
Reed Kotler0f007fc2013-11-05 08:14:14 +0000519 if (!CPChange && !BRChange)
520 break;
521 MadeChange = true;
522 }
523
524 DEBUG(dbgs() << '\n'; dumpBBs());
525
526 BBInfo.clear();
527 WaterList.clear();
528 CPUsers.clear();
529 CPEntries.clear();
530 ImmBranches.clear();
531 return MadeChange;
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000532}
533
Reed Kotler91ae9822013-10-27 21:57:36 +0000534/// doInitialPlacement - Perform the initial placement of the constant pool
535/// entries. To start with, we put them all at the end of the function.
536void
537MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
538 // Create the basic block to hold the CPE's.
539 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
540 MF->push_back(BB);
541
542
543 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
544 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
545
546 // Mark the basic block as required by the const-pool.
547 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
548 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
549
550 // The function needs to be as aligned as the basic blocks. The linker may
551 // move functions around based on their alignment.
552 MF->ensureAlignment(BB->getAlignment());
553
554 // Order the entries in BB by descending alignment. That ensures correct
555 // alignment of all entries as long as BB is sufficiently aligned. Keep
556 // track of the insertion point for each alignment. We are going to bucket
557 // sort the entries as they are created.
558 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
559
560 // Add all of the constants from the constant pool to the end block, use an
561 // identity mapping of CPI's to CPE's.
562 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
563
564 const DataLayout &TD = *MF->getTarget().getDataLayout();
565 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
566 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
567 assert(Size >= 4 && "Too small constant pool entry");
568 unsigned Align = CPs[i].getAlignment();
569 assert(isPowerOf2_32(Align) && "Invalid alignment");
570 // Verify that all constant pool entries are a multiple of their alignment.
571 // If not, we would have to pad them out so that instructions stay aligned.
572 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
573
574 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
575 unsigned LogAlign = Log2_32(Align);
576 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
577
578 MachineInstr *CPEMI =
579 BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
580 .addImm(i).addConstantPoolIndex(i).addImm(Size);
581
582 CPEMIs.push_back(CPEMI);
583
584 // Ensure that future entries with higher alignment get inserted before
585 // CPEMI. This is bucket sort with iterators.
586 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
587 if (InsPoint[a] == InsAt)
588 InsPoint[a] = CPEMI;
589 // Add a new CPEntry, but no corresponding CPUser yet.
590 std::vector<CPEntry> CPEs;
591 CPEs.push_back(CPEntry(CPEMI, i));
592 CPEntries.push_back(CPEs);
593 ++NumCPEs;
594 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
595 << Size << ", align = " << Align <<'\n');
596 }
597 DEBUG(BB->dump());
598}
599
Reed Kotler0f007fc2013-11-05 08:14:14 +0000600/// BBHasFallthrough - Return true if the specified basic block can fallthrough
601/// into the block immediately after it.
602static bool BBHasFallthrough(MachineBasicBlock *MBB) {
603 // Get the next machine basic block in the function.
604 MachineFunction::iterator MBBI = MBB;
605 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000606 if (std::next(MBBI) == MBB->getParent()->end())
Reed Kotler0f007fc2013-11-05 08:14:14 +0000607 return false;
608
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000609 MachineBasicBlock *NextBB = std::next(MBBI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000610 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
611 E = MBB->succ_end(); I != E; ++I)
612 if (*I == NextBB)
613 return true;
614
615 return false;
616}
617
618/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
619/// look up the corresponding CPEntry.
620MipsConstantIslands::CPEntry
621*MipsConstantIslands::findConstPoolEntry(unsigned CPI,
622 const MachineInstr *CPEMI) {
623 std::vector<CPEntry> &CPEs = CPEntries[CPI];
624 // Number of entries per constpool index should be small, just do a
625 // linear search.
626 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
627 if (CPEs[i].CPEMI == CPEMI)
628 return &CPEs[i];
629 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000630 return nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000631}
632
633/// getCPELogAlign - Returns the required alignment of the constant pool entry
634/// represented by CPEMI. Alignment is measured in log2(bytes) units.
635unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
636 assert(CPEMI && CPEMI->getOpcode() == Mips::CONSTPOOL_ENTRY);
637
638 // Everything is 4-byte aligned unless AlignConstantIslands is set.
639 if (!AlignConstantIslands)
640 return 2;
641
642 unsigned CPI = CPEMI->getOperand(1).getIndex();
643 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
644 unsigned Align = MCP->getConstants()[CPI].getAlignment();
645 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
646 return Log2_32(Align);
647}
648
649/// initializeFunctionInfo - Do the initial scan of the function, building up
650/// information about the sizes of each block, the location of all the water,
651/// and finding all of the constant pool users.
652void MipsConstantIslands::
653initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
654 BBInfo.clear();
655 BBInfo.resize(MF->getNumBlockIDs());
656
657 // First thing, compute the size of all basic blocks, and see if the function
658 // has any inline assembly in it. If so, we have to be conservative about
659 // alignment assumptions, as we don't know for sure the size of any
660 // instructions in the inline assembly.
661 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
662 computeBlockSize(I);
663
Reed Kotler0f007fc2013-11-05 08:14:14 +0000664
665 // Compute block offsets.
666 adjustBBOffsetsAfter(MF->begin());
667
668 // Now go back through the instructions and build up our data structures.
669 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
670 MBBI != E; ++MBBI) {
671 MachineBasicBlock &MBB = *MBBI;
672
673 // If this block doesn't fall through into the next MBB, then this is
674 // 'water' that a constant pool island could be placed.
675 if (!BBHasFallthrough(&MBB))
676 WaterList.push_back(&MBB);
677 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
678 I != E; ++I) {
679 if (I->isDebugValue())
680 continue;
681
682 int Opc = I->getOpcode();
683 if (I->isBranch()) {
684 bool isCond = false;
685 unsigned Bits = 0;
686 unsigned Scale = 1;
687 int UOpc = Opc;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000688 switch (Opc) {
689 default:
Reed Kotler4b7afe52013-11-13 23:52:18 +0000690 continue; // Ignore other branches for now
691 case Mips::Bimm16:
692 Bits = 11;
693 Scale = 2;
694 isCond = false;
695 break;
696 case Mips::BimmX16:
697 Bits = 16;
698 Scale = 2;
699 isCond = false;
Reed Kotler0d409e22013-11-28 00:56:37 +0000700 break;
701 case Mips::BeqzRxImm16:
Reed Kotler59975c22013-12-03 23:42:51 +0000702 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000703 Bits = 8;
704 Scale = 2;
705 isCond = true;
706 break;
707 case Mips::BeqzRxImmX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000708 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000709 Bits = 16;
710 Scale = 2;
711 isCond = true;
712 break;
713 case Mips::BnezRxImm16:
Reed Kotler59975c22013-12-03 23:42:51 +0000714 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000715 Bits = 8;
716 Scale = 2;
717 isCond = true;
718 break;
719 case Mips::BnezRxImmX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000720 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000721 Bits = 16;
722 Scale = 2;
723 isCond = true;
724 break;
725 case Mips::Bteqz16:
Reed Kotler59975c22013-12-03 23:42:51 +0000726 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000727 Bits = 8;
728 Scale = 2;
729 isCond = true;
730 break;
731 case Mips::BteqzX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000732 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000733 Bits = 16;
734 Scale = 2;
735 isCond = true;
736 break;
737 case Mips::Btnez16:
Reed Kotler59975c22013-12-03 23:42:51 +0000738 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000739 Bits = 8;
740 Scale = 2;
741 isCond = true;
742 break;
743 case Mips::BtnezX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000744 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000745 Bits = 16;
746 Scale = 2;
747 isCond = true;
748 break;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000749 }
750 // Record this immediate branch.
751 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
752 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Reed Kotler0f007fc2013-11-05 08:14:14 +0000753 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000754
755 if (Opc == Mips::CONSTPOOL_ENTRY)
756 continue;
757
758
759 // Scan the instructions for constant pool operands.
760 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
761 if (I->getOperand(op).isCPI()) {
762
763 // We found one. The addressing mode tells us the max displacement
764 // from the PC that this instruction permits.
765
766 // Basic size info comes from the TSFlags field.
767 unsigned Bits = 0;
768 unsigned Scale = 1;
769 bool NegOk = false;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000770 unsigned LongFormBits = 0;
771 unsigned LongFormScale = 0;
772 unsigned LongFormOpcode = 0;
773 switch (Opc) {
774 default:
775 llvm_unreachable("Unknown addressing mode for CP reference!");
776 case Mips::LwRxPcTcp16:
777 Bits = 8;
Reed Kotler3d7b33f2013-11-06 04:29:52 +0000778 Scale = 4;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000779 LongFormOpcode = Mips::LwRxPcTcpX16;
Reed Kotler43788a22014-01-16 00:47:46 +0000780 LongFormBits = 14;
Reed Kotler45c59272013-11-10 00:09:26 +0000781 LongFormScale = 1;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000782 break;
783 case Mips::LwRxPcTcpX16:
Reed Kotler43788a22014-01-16 00:47:46 +0000784 Bits = 14;
Reed Kotler3d7b33f2013-11-06 04:29:52 +0000785 Scale = 1;
786 NegOk = true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000787 break;
788 }
789 // Remember that this is a user of a CP entry.
790 unsigned CPI = I->getOperand(op).getIndex();
791 MachineInstr *CPEMI = CPEMIs[CPI];
792 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
793 unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
794 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000795 LongFormMaxOffs, LongFormOpcode));
Reed Kotler0f007fc2013-11-05 08:14:14 +0000796
797 // Increment corresponding CPEntry reference count.
798 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
799 assert(CPE && "Cannot find a corresponding CPEntry!");
800 CPE->RefCount++;
801
802 // Instructions can only use one CP entry, don't bother scanning the
803 // rest of the operands.
804 break;
805
806 }
807
808 }
809 }
810
811}
812
813/// computeBlockSize - Compute the size and some alignment information for MBB.
814/// This function updates BBInfo directly.
815void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
816 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
817 BBI.Size = 0;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000818
819 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
820 ++I)
821 BBI.Size += TII->GetInstSizeInBytes(I);
822
823}
824
825/// getOffsetOf - Return the current offset of the specified machine instruction
826/// from the start of the function. This offset changes as stuff is moved
827/// around inside the function.
828unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
829 MachineBasicBlock *MBB = MI->getParent();
830
831 // The offset is composed of two things: the sum of the sizes of all MBB's
832 // before this instruction's block, and the offset from the start of the block
833 // it is in.
834 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
835
836 // Sum instructions before MI in MBB.
837 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
838 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
839 Offset += TII->GetInstSizeInBytes(I);
840 }
841 return Offset;
842}
843
844/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
845/// ID.
846static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
847 const MachineBasicBlock *RHS) {
848 return LHS->getNumber() < RHS->getNumber();
849}
850
851/// updateForInsertedWaterBlock - When a block is newly inserted into the
852/// machine function, it upsets all of the block numbers. Renumber the blocks
853/// and update the arrays that parallel this numbering.
854void MipsConstantIslands::updateForInsertedWaterBlock
855 (MachineBasicBlock *NewBB) {
856 // Renumber the MBB's to keep them consecutive.
857 NewBB->getParent()->RenumberBlocks(NewBB);
858
859 // Insert an entry into BBInfo to align it properly with the (newly
860 // renumbered) block numbers.
861 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
862
863 // Next, update WaterList. Specifically, we need to add NewMBB as having
864 // available water after it.
865 water_iterator IP =
866 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
867 CompareMBBNumbers);
868 WaterList.insert(IP, NewBB);
869}
870
Reed Kotler0f007fc2013-11-05 08:14:14 +0000871unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
Reed Kotler0eb87392013-11-05 21:39:57 +0000872 return getOffsetOf(U.MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000873}
874
875/// Split the basic block containing MI into two blocks, which are joined by
876/// an unconditional branch. Update data structures and renumber blocks to
877/// account for this change and returns the newly created block.
878MachineBasicBlock *MipsConstantIslands::splitBlockBeforeInstr
879 (MachineInstr *MI) {
880 MachineBasicBlock *OrigBB = MI->getParent();
881
882 // Create a new MBB for the code after the OrigBB.
883 MachineBasicBlock *NewBB =
884 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
885 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
886 MF->insert(MBBI, NewBB);
887
888 // Splice the instructions starting with MI over to NewBB.
889 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
890
891 // Add an unconditional branch from OrigBB to NewBB.
892 // Note the new unconditional branch is not being recorded.
893 // There doesn't seem to be meaningful DebugInfo available; this doesn't
894 // correspond to anything in the source.
Reed Kotlerf0e69682013-11-12 02:27:12 +0000895 BuildMI(OrigBB, DebugLoc(), TII->get(Mips::Bimm16)).addMBB(NewBB);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000896 ++NumSplit;
897
898 // Update the CFG. All succs of OrigBB are now succs of NewBB.
899 NewBB->transferSuccessors(OrigBB);
900
901 // OrigBB branches to NewBB.
902 OrigBB->addSuccessor(NewBB);
903
904 // Update internal data structures to account for the newly inserted MBB.
905 // This is almost the same as updateForInsertedWaterBlock, except that
906 // the Water goes after OrigBB, not NewBB.
907 MF->RenumberBlocks(NewBB);
908
909 // Insert an entry into BBInfo to align it properly with the (newly
910 // renumbered) block numbers.
911 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
912
913 // Next, update WaterList. Specifically, we need to add OrigMBB as having
914 // available water after it (but not if it's already there, which happens
915 // when splitting before a conditional branch that is followed by an
916 // unconditional branch - in that case we want to insert NewBB).
917 water_iterator IP =
918 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
919 CompareMBBNumbers);
920 MachineBasicBlock* WaterBB = *IP;
921 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000922 WaterList.insert(std::next(IP), NewBB);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000923 else
924 WaterList.insert(IP, OrigBB);
925 NewWaterList.insert(OrigBB);
926
927 // Figure out how large the OrigBB is. As the first half of the original
928 // block, it cannot contain a tablejump. The size includes
929 // the new jump we added. (It should be possible to do this without
930 // recounting everything, but it's very confusing, and this is rarely
931 // executed.)
932 computeBlockSize(OrigBB);
933
934 // Figure out how large the NewMBB is. As the second half of the original
935 // block, it may contain a tablejump.
936 computeBlockSize(NewBB);
937
938 // All BBOffsets following these blocks must be modified.
939 adjustBBOffsetsAfter(OrigBB);
940
941 return NewBB;
942}
943
944
945
946/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
947/// reference) is within MaxDisp of TrialOffset (a proposed location of a
948/// constant pool entry).
Reed Kotler0f007fc2013-11-05 08:14:14 +0000949bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
950 unsigned TrialOffset, unsigned MaxDisp,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000951 bool NegativeOK) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000952 if (UserOffset <= TrialOffset) {
953 // User before the Trial.
954 if (TrialOffset - UserOffset <= MaxDisp)
955 return true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000956 } else if (NegativeOK) {
957 if (UserOffset - TrialOffset <= MaxDisp)
958 return true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000959 }
960 return false;
961}
962
963/// isWaterInRange - Returns true if a CPE placed after the specified
964/// Water (a basic block) will be in range for the specific MI.
965///
966/// Compute how much the function will grow by inserting a CPE after Water.
967bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
968 MachineBasicBlock* Water, CPUser &U,
969 unsigned &Growth) {
970 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
971 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
972 unsigned NextBlockOffset, NextBlockAlignment;
973 MachineFunction::const_iterator NextBlock = Water;
974 if (++NextBlock == MF->end()) {
975 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
976 NextBlockAlignment = 0;
977 } else {
978 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
979 NextBlockAlignment = NextBlock->getAlignment();
980 }
981 unsigned Size = U.CPEMI->getOperand(2).getImm();
982 unsigned CPEEnd = CPEOffset + Size;
983
984 // The CPE may be able to hide in the alignment padding before the next
985 // block. It may also cause more padding to be required if it is more aligned
986 // that the next block.
987 if (CPEEnd > NextBlockOffset) {
988 Growth = CPEEnd - NextBlockOffset;
989 // Compute the padding that would go at the end of the CPE to align the next
990 // block.
991 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
992
993 // If the CPE is to be inserted before the instruction, that will raise
994 // the offset of the instruction. Also account for unknown alignment padding
995 // in blocks between CPE and the user.
996 if (CPEOffset < UserOffset)
Reed Kotler7ded5b62013-11-05 23:36:58 +0000997 UserOffset += Growth;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000998 } else
999 // CPE fits in existing padding.
1000 Growth = 0;
1001
1002 return isOffsetInRange(UserOffset, CPEOffset, U);
1003}
1004
1005/// isCPEntryInRange - Returns true if the distance between specific MI and
1006/// specific ConstPool entry instruction can fit in MI's displacement field.
1007bool MipsConstantIslands::isCPEntryInRange
1008 (MachineInstr *MI, unsigned UserOffset,
1009 MachineInstr *CPEMI, unsigned MaxDisp,
1010 bool NegOk, bool DoDump) {
1011 unsigned CPEOffset = getOffsetOf(CPEMI);
1012
1013 if (DoDump) {
1014 DEBUG({
1015 unsigned Block = MI->getParent()->getNumber();
1016 const BasicBlockInfo &BBI = BBInfo[Block];
1017 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1018 << " max delta=" << MaxDisp
1019 << format(" insn address=%#x", UserOffset)
1020 << " in BB#" << Block << ": "
1021 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1022 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1023 int(CPEOffset-UserOffset));
1024 });
1025 }
1026
1027 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1028}
1029
1030#ifndef NDEBUG
1031/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1032/// unconditionally branches to its only successor.
1033static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1034 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1035 return false;
1036 MachineBasicBlock *Succ = *MBB->succ_begin();
1037 MachineBasicBlock *Pred = *MBB->pred_begin();
1038 MachineInstr *PredMI = &Pred->back();
Reed Kotlerf0e69682013-11-12 02:27:12 +00001039 if (PredMI->getOpcode() == Mips::Bimm16)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001040 return PredMI->getOperand(0).getMBB() == Succ;
1041 return false;
1042}
1043#endif
1044
1045void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1046 unsigned BBNum = BB->getNumber();
1047 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1048 // Get the offset and known bits at the end of the layout predecessor.
1049 // Include the alignment of the current block.
Reed Kotler7ded5b62013-11-05 23:36:58 +00001050 unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001051 BBInfo[i].Offset = Offset;
1052 }
1053}
1054
1055/// decrementCPEReferenceCount - find the constant pool entry with index CPI
1056/// and instruction CPEMI, and decrement its refcount. If the refcount
1057/// becomes 0 remove the entry and instruction. Returns true if we removed
1058/// the entry, false if we didn't.
1059
1060bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1061 MachineInstr *CPEMI) {
1062 // Find the old entry. Eliminate it if it is no longer used.
1063 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1064 assert(CPE && "Unexpected!");
1065 if (--CPE->RefCount == 0) {
1066 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001067 CPE->CPEMI = nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001068 --NumCPEs;
1069 return true;
1070 }
1071 return false;
1072}
1073
1074/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1075/// if not, see if an in-range clone of the CPE is in range, and if so,
1076/// change the data structures so the user references the clone. Returns:
1077/// 0 = no existing entry found
1078/// 1 = entry found, and there were no code insertions or deletions
1079/// 2 = entry found, and there were code insertions or deletions
1080int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1081{
1082 MachineInstr *UserMI = U.MI;
1083 MachineInstr *CPEMI = U.CPEMI;
1084
1085 // Check to see if the CPE is already in-range.
1086 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1087 true)) {
1088 DEBUG(dbgs() << "In range\n");
1089 return 1;
1090 }
1091
1092 // No. Look for previously created clones of the CPE that are in range.
1093 unsigned CPI = CPEMI->getOperand(1).getIndex();
1094 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1095 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1096 // We already tried this one
1097 if (CPEs[i].CPEMI == CPEMI)
1098 continue;
1099 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001100 if (CPEs[i].CPEMI == nullptr)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001101 continue;
1102 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1103 U.NegOk)) {
1104 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1105 << CPEs[i].CPI << "\n");
1106 // Point the CPUser node to the replacement
1107 U.CPEMI = CPEs[i].CPEMI;
1108 // Change the CPI in the instruction operand to refer to the clone.
1109 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1110 if (UserMI->getOperand(j).isCPI()) {
1111 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1112 break;
1113 }
1114 // Adjust the refcount of the clone...
1115 CPEs[i].RefCount++;
1116 // ...and the original. If we didn't remove the old entry, none of the
1117 // addresses changed, so we don't need another pass.
1118 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1119 }
1120 }
1121 return 0;
1122}
1123
1124/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1125/// This version checks if the longer form of the instruction can be used to
1126/// to satisfy things.
1127/// if not, see if an in-range clone of the CPE is in range, and if so,
1128/// change the data structures so the user references the clone. Returns:
1129/// 0 = no existing entry found
1130/// 1 = entry found, and there were no code insertions or deletions
1131/// 2 = entry found, and there were code insertions or deletions
1132int MipsConstantIslands::findLongFormInRangeCPEntry
1133 (CPUser& U, unsigned UserOffset)
1134{
1135 MachineInstr *UserMI = U.MI;
1136 MachineInstr *CPEMI = U.CPEMI;
1137
1138 // Check to see if the CPE is already in-range.
1139 if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
1140 U.getLongFormMaxDisp(), U.NegOk,
1141 true)) {
1142 DEBUG(dbgs() << "In range\n");
1143 UserMI->setDesc(TII->get(U.getLongFormOpcode()));
Reed Kotler45c59272013-11-10 00:09:26 +00001144 U.setMaxDisp(U.getLongFormMaxDisp());
Reed Kotler0f007fc2013-11-05 08:14:14 +00001145 return 2; // instruction is longer length now
1146 }
1147
1148 // No. Look for previously created clones of the CPE that are in range.
1149 unsigned CPI = CPEMI->getOperand(1).getIndex();
1150 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1151 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1152 // We already tried this one
1153 if (CPEs[i].CPEMI == CPEMI)
1154 continue;
1155 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001156 if (CPEs[i].CPEMI == nullptr)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001157 continue;
1158 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
1159 U.getLongFormMaxDisp(), U.NegOk)) {
1160 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1161 << CPEs[i].CPI << "\n");
1162 // Point the CPUser node to the replacement
1163 U.CPEMI = CPEs[i].CPEMI;
1164 // Change the CPI in the instruction operand to refer to the clone.
1165 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1166 if (UserMI->getOperand(j).isCPI()) {
1167 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1168 break;
1169 }
1170 // Adjust the refcount of the clone...
1171 CPEs[i].RefCount++;
1172 // ...and the original. If we didn't remove the old entry, none of the
1173 // addresses changed, so we don't need another pass.
1174 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1175 }
1176 }
1177 return 0;
1178}
1179
1180/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1181/// the specific unconditional branch instruction.
1182static inline unsigned getUnconditionalBrDisp(int Opc) {
1183 switch (Opc) {
Reed Kotlerf0e69682013-11-12 02:27:12 +00001184 case Mips::Bimm16:
1185 return ((1<<10)-1)*2;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001186 case Mips::BimmX16:
1187 return ((1<<16)-1)*2;
1188 default:
1189 break;
1190 }
1191 return ((1<<16)-1)*2;
1192}
1193
1194/// findAvailableWater - Look for an existing entry in the WaterList in which
1195/// we can place the CPE referenced from U so it's within range of U's MI.
1196/// Returns true if found, false if not. If it returns true, WaterIter
Reed Kotler4d0313d2013-11-05 12:04:37 +00001197/// is set to the WaterList entry.
1198/// To ensure that this pass
Reed Kotler0f007fc2013-11-05 08:14:14 +00001199/// terminates, the CPE location for a particular CPUser is only allowed to
1200/// move to a lower address, so search backward from the end of the list and
1201/// prefer the first water that is in range.
1202bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1203 water_iterator &WaterIter) {
1204 if (WaterList.empty())
1205 return false;
1206
1207 unsigned BestGrowth = ~0u;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001208 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001209 --IP) {
1210 MachineBasicBlock* WaterBB = *IP;
1211 // Check if water is in range and is either at a lower address than the
1212 // current "high water mark" or a new water block that was created since
1213 // the previous iteration by inserting an unconditional branch. In the
1214 // latter case, we want to allow resetting the high water mark back to
1215 // this new water since we haven't seen it before. Inserting branches
1216 // should be relatively uncommon and when it does happen, we want to be
1217 // sure to take advantage of it for all the CPEs near that block, so that
1218 // we don't insert more branches than necessary.
1219 unsigned Growth;
1220 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1221 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1222 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1223 // This is the least amount of required padding seen so far.
1224 BestGrowth = Growth;
1225 WaterIter = IP;
1226 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1227 << " Growth=" << Growth << '\n');
1228
1229 // Keep looking unless it is perfect.
1230 if (BestGrowth == 0)
1231 return true;
1232 }
1233 if (IP == B)
1234 break;
1235 }
1236 return BestGrowth != ~0u;
1237}
1238
1239/// createNewWater - No existing WaterList entry will work for
1240/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1241/// block is used if in range, and the conditional branch munged so control
1242/// flow is correct. Otherwise the block is split to create a hole with an
1243/// unconditional branch around it. In either case NewMBB is set to a
1244/// block following which the new island can be inserted (the WaterList
1245/// is not adjusted).
1246void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1247 unsigned UserOffset,
1248 MachineBasicBlock *&NewMBB) {
1249 CPUser &U = CPUsers[CPUserIndex];
1250 MachineInstr *UserMI = U.MI;
1251 MachineInstr *CPEMI = U.CPEMI;
1252 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1253 MachineBasicBlock *UserMBB = UserMI->getParent();
1254 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1255
1256 // If the block does not end in an unconditional branch already, and if the
Reed Kotler4d0313d2013-11-05 12:04:37 +00001257 // end of the block is within range, make new water there.
Reed Kotler0f007fc2013-11-05 08:14:14 +00001258 if (BBHasFallthrough(UserMBB)) {
1259 // Size of branch to insert.
1260 unsigned Delta = 2;
1261 // Compute the offset where the CPE will begin.
1262 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1263
1264 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1265 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1266 << format(", expected CPE offset %#x\n", CPEOffset));
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001267 NewMBB = std::next(MachineFunction::iterator(UserMBB));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001268 // Add an unconditional branch from UserMBB to fallthrough block. Record
1269 // it for branch lengthening; this new branch will not get out of range,
1270 // but if the preceding conditional branch is out of range, the targets
1271 // will be exchanged, and the altered branch may be out of range, so the
1272 // machinery has to know about it.
Reed Kotlerf0e69682013-11-12 02:27:12 +00001273 int UncondBr = Mips::Bimm16;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001274 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1275 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1276 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1277 MaxDisp, false, UncondBr));
1278 BBInfo[UserMBB->getNumber()].Size += Delta;
1279 adjustBBOffsetsAfter(UserMBB);
1280 return;
1281 }
1282 }
1283
Reed Kotler4d0313d2013-11-05 12:04:37 +00001284 // What a big block. Find a place within the block to split it.
Reed Kotler0f007fc2013-11-05 08:14:14 +00001285
1286 // Try to split the block so it's fully aligned. Compute the latest split
1287 // point where we can add a 4-byte branch instruction, and then align to
1288 // LogAlign which is the largest possible alignment in the function.
1289 unsigned LogAlign = MF->getAlignment();
1290 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
Reed Kotler7ded5b62013-11-05 23:36:58 +00001291 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001292 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1293 BaseInsertOffset));
1294
1295 // The 4 in the following is for the unconditional branch we'll be inserting
Reed Kotler4d0313d2013-11-05 12:04:37 +00001296 // Alignment of the island is handled
Reed Kotler0f007fc2013-11-05 08:14:14 +00001297 // inside isOffsetInRange.
1298 BaseInsertOffset -= 4;
1299
1300 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
Reed Kotler7ded5b62013-11-05 23:36:58 +00001301 << " la=" << LogAlign << '\n');
Reed Kotler0f007fc2013-11-05 08:14:14 +00001302
1303 // This could point off the end of the block if we've already got constant
1304 // pool entries following this block; only the last one is in the water list.
1305 // Back past any possible branches (allow for a conditional and a maximally
1306 // long unconditional).
1307 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Reed Kotler7ded5b62013-11-05 23:36:58 +00001308 BaseInsertOffset = UserBBI.postOffset() - 8;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001309 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1310 }
Reed Kotler7ded5b62013-11-05 23:36:58 +00001311 unsigned EndInsertOffset = BaseInsertOffset + 4 +
Reed Kotler0f007fc2013-11-05 08:14:14 +00001312 CPEMI->getOperand(2).getImm();
1313 MachineBasicBlock::iterator MI = UserMI;
1314 ++MI;
1315 unsigned CPUIndex = CPUserIndex+1;
1316 unsigned NumCPUsers = CPUsers.size();
1317 //MachineInstr *LastIT = 0;
1318 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1319 Offset < BaseInsertOffset;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001320 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001321 assert(MI != UserMBB->end() && "Fell off end of block");
1322 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1323 CPUser &U = CPUsers[CPUIndex];
1324 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1325 // Shift intertion point by one unit of alignment so it is within reach.
1326 BaseInsertOffset -= 1u << LogAlign;
1327 EndInsertOffset -= 1u << LogAlign;
1328 }
1329 // This is overly conservative, as we don't account for CPEMIs being
1330 // reused within the block, but it doesn't matter much. Also assume CPEs
1331 // are added in order with alignment padding. We may eventually be able
1332 // to pack the aligned CPEs better.
1333 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1334 CPUIndex++;
1335 }
1336 }
1337
1338 --MI;
1339 NewMBB = splitBlockBeforeInstr(MI);
1340}
1341
1342/// handleConstantPoolUser - Analyze the specified user, checking to see if it
1343/// is out-of-range. If so, pick up the constant pool value and move it some
1344/// place in-range. Return true if we changed any addresses (thus must run
1345/// another pass of branch lengthening), false otherwise.
1346bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1347 CPUser &U = CPUsers[CPUserIndex];
1348 MachineInstr *UserMI = U.MI;
1349 MachineInstr *CPEMI = U.CPEMI;
1350 unsigned CPI = CPEMI->getOperand(1).getIndex();
1351 unsigned Size = CPEMI->getOperand(2).getImm();
1352 // Compute this only once, it's expensive.
1353 unsigned UserOffset = getUserOffset(U);
1354
1355 // See if the current entry is within range, or there is a clone of it
1356 // in range.
1357 int result = findInRangeCPEntry(U, UserOffset);
1358 if (result==1) return false;
1359 else if (result==2) return true;
1360
1361
1362 // Look for water where we can place this CPE.
1363 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1364 MachineBasicBlock *NewMBB;
1365 water_iterator IP;
1366 if (findAvailableWater(U, UserOffset, IP)) {
1367 DEBUG(dbgs() << "Found water in range\n");
1368 MachineBasicBlock *WaterBB = *IP;
1369
1370 // If the original WaterList entry was "new water" on this iteration,
1371 // propagate that to the new island. This is just keeping NewWaterList
1372 // updated to match the WaterList, which will be updated below.
1373 if (NewWaterList.erase(WaterBB))
1374 NewWaterList.insert(NewIsland);
1375
1376 // The new CPE goes before the following block (NewMBB).
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001377 NewMBB = std::next(MachineFunction::iterator(WaterBB));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001378
1379 } else {
1380 // No water found.
1381 // we first see if a longer form of the instrucion could have reached
1382 // the constant. in that case we won't bother to split
Reed Kotler45c59272013-11-10 00:09:26 +00001383 if (!NoLoadRelaxation) {
1384 result = findLongFormInRangeCPEntry(U, UserOffset);
1385 if (result != 0) return true;
1386 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001387 DEBUG(dbgs() << "No water found\n");
1388 createNewWater(CPUserIndex, UserOffset, NewMBB);
1389
1390 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1391 // called while handling branches so that the water will be seen on the
1392 // next iteration for constant pools, but in this context, we don't want
1393 // it. Check for this so it will be removed from the WaterList.
1394 // Also remove any entry from NewWaterList.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001395 MachineBasicBlock *WaterBB = std::prev(MachineFunction::iterator(NewMBB));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001396 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1397 if (IP != WaterList.end())
1398 NewWaterList.erase(WaterBB);
1399
1400 // We are adding new water. Update NewWaterList.
1401 NewWaterList.insert(NewIsland);
1402 }
1403
1404 // Remove the original WaterList entry; we want subsequent insertions in
1405 // this vicinity to go after the one we're about to insert. This
1406 // considerably reduces the number of times we have to move the same CPE
1407 // more than once and is also important to ensure the algorithm terminates.
1408 if (IP != WaterList.end())
1409 WaterList.erase(IP);
1410
1411 // Okay, we know we can put an island before NewMBB now, do it!
1412 MF->insert(NewMBB, NewIsland);
1413
1414 // Update internal data structures to account for the newly inserted MBB.
1415 updateForInsertedWaterBlock(NewIsland);
1416
1417 // Decrement the old entry, and remove it if refcount becomes 0.
1418 decrementCPEReferenceCount(CPI, CPEMI);
1419
Reed Kotlerd3b28eb2013-11-24 02:53:09 +00001420 // No existing clone of this CPE is within range.
1421 // We will be generating a new clone. Get a UID for it.
1422 unsigned ID = createPICLabelUId();
1423
Reed Kotler0f007fc2013-11-05 08:14:14 +00001424 // Now that we have an island to add the CPE to, clone the original CPE and
1425 // add it to the island.
1426 U.HighWaterMark = NewIsland;
1427 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1428 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1429 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1430 ++NumCPEs;
1431
1432 // Mark the basic block as aligned as required by the const-pool entry.
1433 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1434
1435 // Increase the size of the island block to account for the new entry.
1436 BBInfo[NewIsland->getNumber()].Size += Size;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001437 adjustBBOffsetsAfter(std::prev(MachineFunction::iterator(NewIsland)));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001438
Reed Kotlerd3b28eb2013-11-24 02:53:09 +00001439
Reed Kotler0f007fc2013-11-05 08:14:14 +00001440
1441 // Finally, change the CPI in the instruction operand to be ID.
1442 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1443 if (UserMI->getOperand(i).isCPI()) {
1444 UserMI->getOperand(i).setIndex(ID);
1445 break;
1446 }
1447
1448 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1449 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1450
1451 return true;
1452}
1453
1454/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1455/// sizes and offsets of impacted basic blocks.
1456void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1457 MachineBasicBlock *CPEBB = CPEMI->getParent();
1458 unsigned Size = CPEMI->getOperand(2).getImm();
1459 CPEMI->eraseFromParent();
1460 BBInfo[CPEBB->getNumber()].Size -= Size;
1461 // All succeeding offsets have the current size value added in, fix this.
1462 if (CPEBB->empty()) {
1463 BBInfo[CPEBB->getNumber()].Size = 0;
1464
1465 // This block no longer needs to be aligned.
1466 CPEBB->setAlignment(0);
1467 } else
1468 // Entries are sorted by descending alignment, so realign from the front.
1469 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1470
1471 adjustBBOffsetsAfter(CPEBB);
1472 // An island has only one predecessor BB and one successor BB. Check if
1473 // this BB's predecessor jumps directly to this BB's successor. This
1474 // shouldn't happen currently.
1475 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1476 // FIXME: remove the empty blocks after all the work is done?
1477}
1478
1479/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1480/// are zero.
1481bool MipsConstantIslands::removeUnusedCPEntries() {
1482 unsigned MadeChange = false;
1483 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1484 std::vector<CPEntry> &CPEs = CPEntries[i];
1485 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1486 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1487 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001488 CPEs[j].CPEMI = nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001489 MadeChange = true;
1490 }
1491 }
1492 }
1493 return MadeChange;
1494}
1495
1496/// isBBInRange - Returns true if the distance between specific MI and
1497/// specific BB can fit in MI's displacement field.
1498bool MipsConstantIslands::isBBInRange
1499 (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
1500
1501unsigned PCAdj = 4;
1502
1503 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1504 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1505
1506 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1507 << " from BB#" << MI->getParent()->getNumber()
1508 << " max delta=" << MaxDisp
1509 << " from " << getOffsetOf(MI) << " to " << DestOffset
1510 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1511
1512 if (BrOffset <= DestOffset) {
1513 // Branch before the Dest.
1514 if (DestOffset-BrOffset <= MaxDisp)
1515 return true;
1516 } else {
1517 if (BrOffset-DestOffset <= MaxDisp)
1518 return true;
1519 }
1520 return false;
1521}
1522
1523/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1524/// away to fit in its displacement field.
1525bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1526 MachineInstr *MI = Br.MI;
Reed Kotler0d409e22013-11-28 00:56:37 +00001527 unsigned TargetOperand = branchTargetOperand(MI);
1528 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001529
1530 // Check to see if the DestBB is already in-range.
1531 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1532 return false;
1533
1534 if (!Br.isCond)
1535 return fixupUnconditionalBr(Br);
1536 return fixupConditionalBr(Br);
1537}
1538
1539/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1540/// too far away to fit in its displacement field. If the LR register has been
1541/// spilled in the epilogue, then we can use BL to implement a far jump.
1542/// Otherwise, add an intermediate branch instruction to a branch.
1543bool
1544MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1545 MachineInstr *MI = Br.MI;
1546 MachineBasicBlock *MBB = MI->getParent();
Reed Kotler2fc05be2013-11-21 05:13:23 +00001547 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001548 // Use BL to implement far jump.
Reed Kotler2fc05be2013-11-21 05:13:23 +00001549 unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2;
1550 if (isBBInRange(MI, DestBB, BimmX16MaxDisp)) {
1551 Br.MaxDisp = BimmX16MaxDisp;
1552 MI->setDesc(TII->get(Mips::BimmX16));
1553 }
1554 else {
1555 // need to give the math a more careful look here
1556 // this is really a segment address and not
1557 // a PC relative address. FIXME. But I think that
1558 // just reducing the bits by 1 as I've done is correct.
1559 // The basic block we are branching too much be longword aligned.
1560 // we know that RA is saved because we always save it right now.
1561 // this requirement will be relaxed later but we also have an alternate
1562 // way to implement this that I will implement that does not need jal.
1563 // We should have a way to back out this alignment restriction if we "can" later.
1564 // but it is not harmful.
1565 //
1566 DestBB->setAlignment(2);
1567 Br.MaxDisp = ((1<<24)-1) * 2;
Reed Kotlerad450f22013-11-29 22:32:56 +00001568 MI->setDesc(TII->get(Mips::JalB16));
Reed Kotler2fc05be2013-11-21 05:13:23 +00001569 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001570 BBInfo[MBB->getNumber()].Size += 2;
1571 adjustBBOffsetsAfter(MBB);
1572 HasFarJump = true;
1573 ++NumUBrFixed;
1574
1575 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1576
1577 return true;
1578}
1579
Reed Kotler0d409e22013-11-28 00:56:37 +00001580
Reed Kotler0f007fc2013-11-05 08:14:14 +00001581/// fixupConditionalBr - Fix up a conditional branch whose destination is too
1582/// far away to fit in its displacement field. It is converted to an inverse
1583/// conditional branch + an unconditional branch to the destination.
1584bool
1585MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1586 MachineInstr *MI = Br.MI;
Reed Kotler0d409e22013-11-28 00:56:37 +00001587 unsigned TargetOperand = branchTargetOperand(MI);
1588 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1589 unsigned Opcode = MI->getOpcode();
1590 unsigned LongFormOpcode = longformBranchOpcode(Opcode);
1591 unsigned LongFormMaxOff = branchMaxOffsets(LongFormOpcode);
1592
1593 // Check to see if the DestBB is already in-range.
1594 if (isBBInRange(MI, DestBB, LongFormMaxOff)) {
1595 Br.MaxDisp = LongFormMaxOff;
1596 MI->setDesc(TII->get(LongFormOpcode));
1597 return true;
1598 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001599
1600 // Add an unconditional branch to the destination and invert the branch
1601 // condition to jump over it:
Reed Kotlerad450f22013-11-29 22:32:56 +00001602 // bteqz L1
Reed Kotler0f007fc2013-11-05 08:14:14 +00001603 // =>
Reed Kotlerad450f22013-11-29 22:32:56 +00001604 // bnez L2
Reed Kotler0f007fc2013-11-05 08:14:14 +00001605 // b L1
1606 // L2:
Reed Kotler0f007fc2013-11-05 08:14:14 +00001607
1608 // If the branch is at the end of its MBB and that has a fall-through block,
1609 // direct the updated conditional branch to the fall-through block. Otherwise,
1610 // split the MBB before the next instruction.
1611 MachineBasicBlock *MBB = MI->getParent();
1612 MachineInstr *BMI = &MBB->back();
1613 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Reed Kotler47f3c64a2013-12-19 00:43:08 +00001614 unsigned OppositeBranchOpcode = TII->getOppositeBranchOpc(Opcode);
Reed Kotlerad450f22013-11-29 22:32:56 +00001615
Reed Kotler0f007fc2013-11-05 08:14:14 +00001616 ++NumCBrFixed;
1617 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001618 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Reed Kotlerad450f22013-11-29 22:32:56 +00001619 isUnconditionalBranch(BMI->getOpcode())) {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001620 // Last MI in the BB is an unconditional branch. Can we simply invert the
1621 // condition and swap destinations:
Reed Kotlerad450f22013-11-29 22:32:56 +00001622 // beqz L1
Reed Kotler0f007fc2013-11-05 08:14:14 +00001623 // b L2
1624 // =>
Reed Kotlerad450f22013-11-29 22:32:56 +00001625 // bnez L2
Reed Kotler0f007fc2013-11-05 08:14:14 +00001626 // b L1
Reed Kotlerad450f22013-11-29 22:32:56 +00001627 unsigned BMITargetOperand = branchTargetOperand(BMI);
1628 MachineBasicBlock *NewDest =
1629 BMI->getOperand(BMITargetOperand).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001630 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1631 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1632 << *BMI);
Reed Kotler59975c22013-12-03 23:42:51 +00001633 MI->setDesc(TII->get(OppositeBranchOpcode));
Reed Kotlerad450f22013-11-29 22:32:56 +00001634 BMI->getOperand(BMITargetOperand).setMBB(DestBB);
1635 MI->getOperand(TargetOperand).setMBB(NewDest);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001636 return true;
1637 }
1638 }
1639 }
1640
Reed Kotlerad450f22013-11-29 22:32:56 +00001641
Reed Kotler0f007fc2013-11-05 08:14:14 +00001642 if (NeedSplit) {
1643 splitBlockBeforeInstr(MI);
1644 // No need for the branch to the next block. We're adding an unconditional
1645 // branch to the destination.
1646 int delta = TII->GetInstSizeInBytes(&MBB->back());
1647 BBInfo[MBB->getNumber()].Size -= delta;
1648 MBB->back().eraseFromParent();
1649 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1650 }
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001651 MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001652
1653 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1654 << " also invert condition and change dest. to BB#"
1655 << NextBB->getNumber() << "\n");
1656
1657 // Insert a new conditional branch and a new unconditional branch.
1658 // Also update the ImmBranch as well as adding a new entry for the new branch.
Reed Kotler59975c22013-12-03 23:42:51 +00001659 if (MI->getNumExplicitOperands() == 2) {
1660 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1661 .addReg(MI->getOperand(0).getReg())
1662 .addMBB(NextBB);
Reed Kotler47f3c64a2013-12-19 00:43:08 +00001663 } else {
1664 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1665 .addMBB(NextBB);
Reed Kotler59975c22013-12-03 23:42:51 +00001666 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001667 Br.MI = &MBB->back();
1668 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1669 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1670 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1671 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1672 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1673
1674 // Remove the old conditional branch. It may or may not still be in MBB.
1675 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1676 MI->eraseFromParent();
1677 adjustBBOffsetsAfter(MBB);
1678 return true;
1679}
1680
Reed Kotler91ae9822013-10-27 21:57:36 +00001681
1682void MipsConstantIslands::prescanForConstants() {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001683 unsigned J = 0;
1684 (void)J;
Reed Kotler91ae9822013-10-27 21:57:36 +00001685 for (MachineFunction::iterator B =
1686 MF->begin(), E = MF->end(); B != E; ++B) {
1687 for (MachineBasicBlock::instr_iterator I =
1688 B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
1689 switch(I->getDesc().getOpcode()) {
1690 case Mips::LwConstant32: {
Reed Kotlera787aa22013-11-24 06:18:50 +00001691 PrescannedForConstants = true;
Reed Kotler91ae9822013-10-27 21:57:36 +00001692 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1693 J = I->getNumOperands();
1694 DEBUG(dbgs() << "num operands " << J << "\n");
1695 MachineOperand& Literal = I->getOperand(1);
1696 if (Literal.isImm()) {
1697 int64_t V = Literal.getImm();
1698 DEBUG(dbgs() << "literal " << V << "\n");
1699 Type *Int32Ty =
1700 Type::getInt32Ty(MF->getFunction()->getContext());
1701 const Constant *C = ConstantInt::get(Int32Ty, V);
1702 unsigned index = MCP->getConstantPoolIndex(C, 4);
1703 I->getOperand(2).ChangeToImmediate(index);
1704 DEBUG(dbgs() << "constant island constant " << *I << "\n");
Reed Kotler0f007fc2013-11-05 08:14:14 +00001705 I->setDesc(TII->get(Mips::LwRxPcTcp16));
Reed Kotler91ae9822013-10-27 21:57:36 +00001706 I->RemoveOperand(1);
1707 I->RemoveOperand(1);
1708 I->addOperand(MachineOperand::CreateCPI(index, 0));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001709 I->addOperand(MachineOperand::CreateImm(4));
Reed Kotler91ae9822013-10-27 21:57:36 +00001710 }
1711 break;
1712 }
1713 default:
1714 break;
1715 }
1716 }
1717 }
1718}
Reed Kotler0f007fc2013-11-05 08:14:14 +00001719