blob: a3ea1526629f8201e4a81230950a3c252b33eb61 [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"
Eric Christopher79cc1e32014-09-02 22:28:02 +000031#include "llvm/CodeGen/MachineConstantPool.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000032#include "llvm/CodeGen/MachineFunctionPass.h"
33#include "llvm/CodeGen/MachineInstrBuilder.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000034#include "llvm/CodeGen/MachineRegisterInfo.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000035#include "llvm/IR/Function.h"
Chandler Carruth83948572014-03-04 10:30:26 +000036#include "llvm/IR/InstIterator.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000037#include "llvm/Support/CommandLine.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000038#include "llvm/Support/Debug.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000039#include "llvm/Support/Format.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 Kotler91ae9822013-10-27 21:57:36 +000045#include <algorithm>
Reed Kotlerbb3094a2013-02-27 03:33:58 +000046
47using namespace llvm;
48
Chandler Carruth84e68b22014-04-22 02:41:26 +000049#define DEBUG_TYPE "mips-constant-islands"
50
Reed Kotler91ae9822013-10-27 21:57:36 +000051STATISTIC(NumCPEs, "Number of constpool entries");
Reed Kotler0f007fc2013-11-05 08:14:14 +000052STATISTIC(NumSplit, "Number of uncond branches inserted");
53STATISTIC(NumCBrFixed, "Number of cond branches fixed");
54STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
Reed Kotler91ae9822013-10-27 21:57:36 +000055
56// FIXME: This option should be removed once it has received sufficient testing.
57static cl::opt<bool>
58AlignConstantIslands("mips-align-constant-islands", cl::Hidden, cl::init(true),
59 cl::desc("Align constant islands in code"));
60
Reed Kotler0f007fc2013-11-05 08:14:14 +000061
62// Rather than do make check tests with huge amounts of code, we force
63// the test to use this amount.
64//
65static cl::opt<int> ConstantIslandsSmallOffset(
66 "mips-constant-islands-small-offset",
67 cl::init(0),
68 cl::desc("Make small offsets be this amount for testing purposes"),
69 cl::Hidden);
70
Reed Kotler45c59272013-11-10 00:09:26 +000071//
72// For testing purposes we tell it to not use relaxed load forms so that it
73// will split blocks.
74//
75static cl::opt<bool> NoLoadRelaxation(
76 "mips-constant-islands-no-load-relaxation",
77 cl::init(false),
78 cl::desc("Don't relax loads to long loads - for testing purposes"),
79 cl::Hidden);
80
Reed Kotler0d409e22013-11-28 00:56:37 +000081static unsigned int branchTargetOperand(MachineInstr *MI) {
82 switch (MI->getOpcode()) {
83 case Mips::Bimm16:
84 case Mips::BimmX16:
85 case Mips::Bteqz16:
86 case Mips::BteqzX16:
87 case Mips::Btnez16:
88 case Mips::BtnezX16:
Reed Kotlerad450f22013-11-29 22:32:56 +000089 case Mips::JalB16:
Reed Kotler0d409e22013-11-28 00:56:37 +000090 return 0;
91 case Mips::BeqzRxImm16:
92 case Mips::BeqzRxImmX16:
93 case Mips::BnezRxImm16:
94 case Mips::BnezRxImmX16:
95 return 1;
96 }
97 llvm_unreachable("Unknown branch type");
98}
99
Reed Kotlerad450f22013-11-29 22:32:56 +0000100static bool isUnconditionalBranch(unsigned int Opcode) {
101 switch (Opcode) {
102 default: return false;
103 case Mips::Bimm16:
104 case Mips::BimmX16:
105 case Mips::JalB16:
106 return true;
107 }
108}
109
Reed Kotler0d409e22013-11-28 00:56:37 +0000110static unsigned int longformBranchOpcode(unsigned int Opcode) {
111 switch (Opcode) {
112 case Mips::Bimm16:
113 case Mips::BimmX16:
114 return Mips::BimmX16;
115 case Mips::Bteqz16:
116 case Mips::BteqzX16:
117 return Mips::BteqzX16;
118 case Mips::Btnez16:
119 case Mips::BtnezX16:
120 return Mips::BtnezX16;
Reed Kotlerad450f22013-11-29 22:32:56 +0000121 case Mips::JalB16:
122 return Mips::JalB16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000123 case Mips::BeqzRxImm16:
124 case Mips::BeqzRxImmX16:
125 return Mips::BeqzRxImmX16;
126 case Mips::BnezRxImm16:
127 case Mips::BnezRxImmX16:
128 return Mips::BnezRxImmX16;
129 }
130 llvm_unreachable("Unknown branch type");
131}
132
133//
134// FIXME: need to go through this whole constant islands port and check the math
135// for branch ranges and clean this up and make some functions to calculate things
136// that are done many times identically.
137// Need to refactor some of the code to call this routine.
138//
139static unsigned int branchMaxOffsets(unsigned int Opcode) {
140 unsigned Bits, Scale;
141 switch (Opcode) {
142 case Mips::Bimm16:
143 Bits = 11;
144 Scale = 2;
145 break;
146 case Mips::BimmX16:
147 Bits = 16;
148 Scale = 2;
149 break;
150 case Mips::BeqzRxImm16:
151 Bits = 8;
152 Scale = 2;
153 break;
154 case Mips::BeqzRxImmX16:
155 Bits = 16;
156 Scale = 2;
157 break;
158 case Mips::BnezRxImm16:
159 Bits = 8;
160 Scale = 2;
161 break;
162 case Mips::BnezRxImmX16:
163 Bits = 16;
164 Scale = 2;
165 break;
166 case Mips::Bteqz16:
167 Bits = 8;
168 Scale = 2;
169 break;
170 case Mips::BteqzX16:
171 Bits = 16;
172 Scale = 2;
173 break;
174 case Mips::Btnez16:
175 Bits = 8;
176 Scale = 2;
177 break;
178 case Mips::BtnezX16:
179 Bits = 16;
180 Scale = 2;
181 break;
182 default:
183 llvm_unreachable("Unknown branch type");
184 }
185 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
186 return MaxOffs;
187}
Reed Kotler0f007fc2013-11-05 08:14:14 +0000188
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000189namespace {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000190
191
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000192 typedef MachineBasicBlock::iterator Iter;
193 typedef MachineBasicBlock::reverse_iterator ReverseIter;
194
Reed Kotler0f007fc2013-11-05 08:14:14 +0000195 /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
196 /// requires constant pool entries to be scattered among the instructions
197 /// inside a function. To do this, it completely ignores the normal LLVM
198 /// constant pool; instead, it places constants wherever it feels like with
199 /// special instructions.
200 ///
201 /// The terminology used in this pass includes:
202 /// Islands - Clumps of constants placed in the function.
203 /// Water - Potential places where an island could be formed.
204 /// CPE - A constant pool entry that has been placed somewhere, which
205 /// tracks a list of users.
206
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000207 class MipsConstantIslands : public MachineFunctionPass {
208
Reed Kotler0f007fc2013-11-05 08:14:14 +0000209 /// BasicBlockInfo - Information about the offset and size of a single
210 /// basic block.
211 struct BasicBlockInfo {
212 /// Offset - Distance from the beginning of the function to the beginning
213 /// of this basic block.
214 ///
215 /// Offsets are computed assuming worst case padding before an aligned
216 /// block. This means that subtracting basic block offsets always gives a
217 /// conservative estimate of the real distance which may be smaller.
218 ///
219 /// Because worst case padding is used, the computed offset of an aligned
220 /// block may not actually be aligned.
221 unsigned Offset;
222
223 /// Size - Size of the basic block in bytes. If the block contains
224 /// inline assembly, this is a worst case estimate.
225 ///
226 /// The size does not include any alignment padding whether from the
227 /// beginning of the block, or from an aligned jump table at the end.
228 unsigned Size;
229
Reed Kotler7ded5b62013-11-05 23:36:58 +0000230 // FIXME: ignore LogAlign for this patch
231 //
Reed Kotler0f007fc2013-11-05 08:14:14 +0000232 unsigned postOffset(unsigned LogAlign = 0) const {
233 unsigned PO = Offset + Size;
234 return PO;
235 }
236
Reed Kotler7ded5b62013-11-05 23:36:58 +0000237 BasicBlockInfo() : Offset(0), Size(0) {}
238
Reed Kotler0f007fc2013-11-05 08:14:14 +0000239 };
240
241 std::vector<BasicBlockInfo> BBInfo;
242
243 /// WaterList - A sorted list of basic blocks where islands could be placed
244 /// (i.e. blocks that don't fall through to the following block, due
245 /// to a return, unreachable, or unconditional branch).
246 std::vector<MachineBasicBlock*> WaterList;
247
248 /// NewWaterList - The subset of WaterList that was created since the
249 /// previous iteration by inserting unconditional branches.
250 SmallSet<MachineBasicBlock*, 4> NewWaterList;
251
252 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
253
254 /// CPUser - One user of a constant pool, keeping the machine instruction
255 /// pointer, the constant pool being referenced, and the max displacement
256 /// allowed from the instruction to the CP. The HighWaterMark records the
257 /// highest basic block where a new CPEntry can be placed. To ensure this
258 /// pass terminates, the CP entries are initially placed at the end of the
259 /// function and then move monotonically to lower addresses. The
260 /// exception to this rule is when the current CP entry for a particular
261 /// CPUser is out of range, but there is another CP entry for the same
262 /// constant value in range. We want to use the existing in-range CP
263 /// entry, but if it later moves out of range, the search for new water
264 /// should resume where it left off. The HighWaterMark is used to record
265 /// that point.
266 struct CPUser {
267 MachineInstr *MI;
268 MachineInstr *CPEMI;
269 MachineBasicBlock *HighWaterMark;
270 private:
271 unsigned MaxDisp;
272 unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
273 // with different displacements
274 unsigned LongFormOpcode;
275 public:
276 bool NegOk;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000277 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000278 bool neg,
Reed Kotler0f007fc2013-11-05 08:14:14 +0000279 unsigned longformmaxdisp, unsigned longformopcode)
280 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
281 LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
Reed Kotler7ded5b62013-11-05 23:36:58 +0000282 NegOk(neg){
Reed Kotler0f007fc2013-11-05 08:14:14 +0000283 HighWaterMark = CPEMI->getParent();
284 }
285 /// getMaxDisp - Returns the maximum displacement supported by MI.
Reed Kotler0f007fc2013-11-05 08:14:14 +0000286 unsigned getMaxDisp() const {
287 unsigned xMaxDisp = ConstantIslandsSmallOffset?
288 ConstantIslandsSmallOffset: MaxDisp;
Reed Kotler7ded5b62013-11-05 23:36:58 +0000289 return xMaxDisp;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000290 }
Reed Kotler45c59272013-11-10 00:09:26 +0000291 void setMaxDisp(unsigned val) {
292 MaxDisp = val;
293 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000294 unsigned getLongFormMaxDisp() const {
Reed Kotler7ded5b62013-11-05 23:36:58 +0000295 return LongFormMaxDisp;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000296 }
297 unsigned getLongFormOpcode() const {
298 return LongFormOpcode;
299 }
300 };
301
302 /// CPUsers - Keep track of all of the machine instructions that use various
303 /// constant pools and their max displacement.
304 std::vector<CPUser> CPUsers;
Reed Kotler91ae9822013-10-27 21:57:36 +0000305
306 /// CPEntry - One per constant pool entry, keeping the machine instruction
307 /// pointer, the constpool index, and the number of CPUser's which
308 /// reference this entry.
309 struct CPEntry {
310 MachineInstr *CPEMI;
311 unsigned CPI;
312 unsigned RefCount;
313 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
314 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
315 };
316
317 /// CPEntries - Keep track of all of the constant pool entry machine
318 /// instructions. For each original constpool index (i.e. those that
319 /// existed upon entry to this pass), it keeps a vector of entries.
320 /// Original elements are cloned as we go along; the clones are
321 /// put in the vector of the original element, but have distinct CPIs.
322 std::vector<std::vector<CPEntry> > CPEntries;
323
Reed Kotler0f007fc2013-11-05 08:14:14 +0000324 /// ImmBranch - One per immediate branch, keeping the machine instruction
325 /// pointer, conditional or unconditional, the max displacement,
326 /// and (if isCond is true) the corresponding unconditional branch
327 /// opcode.
328 struct ImmBranch {
329 MachineInstr *MI;
330 unsigned MaxDisp : 31;
331 bool isCond : 1;
332 int UncondBr;
333 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
334 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
335 };
336
337 /// ImmBranches - Keep track of all the immediate branch instructions.
338 ///
339 std::vector<ImmBranch> ImmBranches;
340
341 /// HasFarJump - True if any far jump instruction has been emitted during
342 /// the branch fix up pass.
343 bool HasFarJump;
344
345 const TargetMachine &TM;
346 bool IsPIC;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000347 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),
Daniel Sanderse2e25da2014-10-24 16:15:27 +0000369 IsPIC(TM.getRelocationModel() == Reloc::PIC_), STI(nullptr),
Eric Christopher4e7d1e72014-07-18 23:41:32 +0000370 MF(nullptr), MCP(nullptr), PrescannedForConstants(false) {}
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000371
Craig Topper56c590a2014-04-29 07:58:02 +0000372 const char *getPassName() const override {
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000373 return "Mips Constant Islands";
374 }
375
Craig Topper56c590a2014-04-29 07:58:02 +0000376 bool runOnMachineFunction(MachineFunction &F) override;
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000377
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000378 MachineFunctionProperties getRequiredProperties() const override {
379 return MachineFunctionProperties().set(
380 MachineFunctionProperties::Property::AllVRegsAllocated);
381 }
382
Reed Kotler91ae9822013-10-27 21:57:36 +0000383 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000384 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
385 unsigned getCPELogAlign(const MachineInstr *CPEMI);
386 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
387 unsigned getOffsetOf(MachineInstr *MI) const;
388 unsigned getUserOffset(CPUser&) const;
389 void dumpBBs();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000390
391 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000392 unsigned Disp, bool NegativeOK);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000393 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
394 const CPUser &U);
395
Reed Kotler0f007fc2013-11-05 08:14:14 +0000396 void computeBlockSize(MachineBasicBlock *MBB);
397 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
398 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
399 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
400 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
401 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
402 int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
403 bool findAvailableWater(CPUser&U, unsigned UserOffset,
404 water_iterator &WaterIter);
405 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
406 MachineBasicBlock *&NewMBB);
407 bool handleConstantPoolUser(unsigned CPUserIndex);
408 void removeDeadCPEMI(MachineInstr *CPEMI);
409 bool removeUnusedCPEntries();
410 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
411 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
412 bool DoDump = false);
413 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
414 CPUser &U, unsigned &Growth);
415 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
416 bool fixupImmediateBr(ImmBranch &Br);
417 bool fixupConditionalBr(ImmBranch &Br);
418 bool fixupUnconditionalBr(ImmBranch &Br);
Reed Kotler91ae9822013-10-27 21:57:36 +0000419
420 void prescanForConstants();
421
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000422 private:
Reed Kotler91ae9822013-10-27 21:57:36 +0000423
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000424 };
425
426 char MipsConstantIslands::ID = 0;
427} // end of anonymous namespace
428
Reed Kotler0f007fc2013-11-05 08:14:14 +0000429bool MipsConstantIslands::isOffsetInRange
430 (unsigned UserOffset, unsigned TrialOffset,
431 const CPUser &U) {
432 return isOffsetInRange(UserOffset, TrialOffset,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000433 U.getMaxDisp(), U.NegOk);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000434}
435/// print block size and offset information - debugging
436void MipsConstantIslands::dumpBBs() {
437 DEBUG({
438 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
439 const BasicBlockInfo &BBI = BBInfo[J];
440 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
Reed Kotler0f007fc2013-11-05 08:14:14 +0000441 << format(" size=%#x\n", BBInfo[J].Size);
442 }
443 });
444}
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000445/// createMipsLongBranchPass - Returns a pass that converts branches to long
446/// branches.
447FunctionPass *llvm::createMipsConstantIslandPass(MipsTargetMachine &tm) {
448 return new MipsConstantIslands(tm);
449}
450
Reed Kotler91ae9822013-10-27 21:57:36 +0000451bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
Reed Kotler1595f362013-04-09 19:46:01 +0000452 // The intention is for this to be a mips16 only pass for now
453 // FIXME:
Reed Kotler91ae9822013-10-27 21:57:36 +0000454 MF = &mf;
455 MCP = mf.getConstantPool();
Eric Christopher96e72c62015-01-29 23:27:36 +0000456 STI = &static_cast<const MipsSubtarget &>(mf.getSubtarget());
Reed Kotler91ae9822013-10-27 21:57:36 +0000457 DEBUG(dbgs() << "constant island machine function " << "\n");
Eric Christopher4e7d1e72014-07-18 23:41:32 +0000458 if (!STI->inMips16Mode() || !MipsSubtarget::useConstantIslands()) {
Reed Kotler91ae9822013-10-27 21:57:36 +0000459 return false;
460 }
Eric Christopher96e72c62015-01-29 23:27:36 +0000461 TII = (const Mips16InstrInfo *)STI->getInstrInfo();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000462 MFI = MF->getInfo<MipsFunctionInfo>();
Reed Kotler91ae9822013-10-27 21:57:36 +0000463 DEBUG(dbgs() << "constant island processing " << "\n");
464 //
465 // will need to make predermination if there is any constants we need to
466 // put in constant islands. TBD.
467 //
Reed Kotler0f007fc2013-11-05 08:14:14 +0000468 if (!PrescannedForConstants) prescanForConstants();
Reed Kotler91ae9822013-10-27 21:57:36 +0000469
Reed Kotler0f007fc2013-11-05 08:14:14 +0000470 HasFarJump = false;
Reed Kotler91ae9822013-10-27 21:57:36 +0000471 // This pass invalidates liveness information when it splits basic blocks.
472 MF->getRegInfo().invalidateLiveness();
473
474 // Renumber all of the machine basic blocks in the function, guaranteeing that
475 // the numbers agree with the position of the block in the function.
476 MF->RenumberBlocks();
477
Reed Kotler0f007fc2013-11-05 08:14:14 +0000478 bool MadeChange = false;
479
Reed Kotler91ae9822013-10-27 21:57:36 +0000480 // Perform the initial placement of the constant pool entries. To start with,
481 // we put them all at the end of the function.
482 std::vector<MachineInstr*> CPEMIs;
483 if (!MCP->isEmpty())
484 doInitialPlacement(CPEMIs);
485
Reed Kotler0f007fc2013-11-05 08:14:14 +0000486 /// The next UID to take is the first unused one.
487 initPICLabelUId(CPEMIs.size());
488
489 // Do the initial scan of the function, building up information about the
490 // sizes of each block, the location of all the water, and finding all of the
491 // constant pool users.
492 initializeFunctionInfo(CPEMIs);
493 CPEMIs.clear();
494 DEBUG(dumpBBs());
495
496 /// Remove dead constant pool entries.
497 MadeChange |= removeUnusedCPEntries();
498
499 // Iteratively place constant pool entries and fix up branches until there
500 // is no change.
501 unsigned NoCPIters = 0, NoBRIters = 0;
502 (void)NoBRIters;
503 while (true) {
504 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
505 bool CPChange = false;
506 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
507 CPChange |= handleConstantPoolUser(i);
508 if (CPChange && ++NoCPIters > 30)
509 report_fatal_error("Constant Island pass failed to converge!");
510 DEBUG(dumpBBs());
511
512 // Clear NewWaterList now. If we split a block for branches, it should
513 // appear as "new water" for the next iteration of constant pool placement.
514 NewWaterList.clear();
515
516 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
517 bool BRChange = false;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000518 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
519 BRChange |= fixupImmediateBr(ImmBranches[i]);
520 if (BRChange && ++NoBRIters > 30)
521 report_fatal_error("Branch Fix Up pass failed to converge!");
522 DEBUG(dumpBBs());
Reed Kotler0f007fc2013-11-05 08:14:14 +0000523 if (!CPChange && !BRChange)
524 break;
525 MadeChange = true;
526 }
527
528 DEBUG(dbgs() << '\n'; dumpBBs());
529
530 BBInfo.clear();
531 WaterList.clear();
532 CPUsers.clear();
533 CPEntries.clear();
534 ImmBranches.clear();
535 return MadeChange;
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000536}
537
Reed Kotler91ae9822013-10-27 21:57:36 +0000538/// doInitialPlacement - Perform the initial placement of the constant pool
539/// entries. To start with, we put them all at the end of the function.
540void
541MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
542 // Create the basic block to hold the CPE's.
543 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
544 MF->push_back(BB);
545
546
547 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
548 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
549
550 // Mark the basic block as required by the const-pool.
551 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
552 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
553
554 // The function needs to be as aligned as the basic blocks. The linker may
555 // move functions around based on their alignment.
556 MF->ensureAlignment(BB->getAlignment());
557
558 // Order the entries in BB by descending alignment. That ensures correct
559 // alignment of all entries as long as BB is sufficiently aligned. Keep
560 // track of the insertion point for each alignment. We are going to bucket
561 // sort the entries as they are created.
562 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
563
564 // Add all of the constants from the constant pool to the end block, use an
565 // identity mapping of CPI's to CPE's.
566 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
567
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000568 const DataLayout &TD = MF->getDataLayout();
Reed Kotler91ae9822013-10-27 21:57:36 +0000569 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
570 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
571 assert(Size >= 4 && "Too small constant pool entry");
572 unsigned Align = CPs[i].getAlignment();
573 assert(isPowerOf2_32(Align) && "Invalid alignment");
574 // Verify that all constant pool entries are a multiple of their alignment.
575 // If not, we would have to pad them out so that instructions stay aligned.
576 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
577
578 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
579 unsigned LogAlign = Log2_32(Align);
580 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
581
582 MachineInstr *CPEMI =
583 BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
584 .addImm(i).addConstantPoolIndex(i).addImm(Size);
585
586 CPEMIs.push_back(CPEMI);
587
588 // Ensure that future entries with higher alignment get inserted before
589 // CPEMI. This is bucket sort with iterators.
590 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
591 if (InsPoint[a] == InsAt)
592 InsPoint[a] = CPEMI;
593 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000594 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Reed Kotler91ae9822013-10-27 21:57:36 +0000595 ++NumCPEs;
596 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
597 << Size << ", align = " << Align <<'\n');
598 }
599 DEBUG(BB->dump());
600}
601
Reed Kotler0f007fc2013-11-05 08:14:14 +0000602/// BBHasFallthrough - Return true if the specified basic block can fallthrough
603/// into the block immediately after it.
604static bool BBHasFallthrough(MachineBasicBlock *MBB) {
605 // Get the next machine basic block in the function.
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000606 MachineFunction::iterator MBBI = MBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000607 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000608 if (std::next(MBBI) == MBB->getParent()->end())
Reed Kotler0f007fc2013-11-05 08:14:14 +0000609 return false;
610
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000611 MachineBasicBlock *NextBB = &*std::next(MBBI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000612 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
613 E = MBB->succ_end(); I != E; ++I)
614 if (*I == NextBB)
615 return true;
616
617 return false;
618}
619
620/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
621/// look up the corresponding CPEntry.
622MipsConstantIslands::CPEntry
623*MipsConstantIslands::findConstPoolEntry(unsigned CPI,
624 const MachineInstr *CPEMI) {
625 std::vector<CPEntry> &CPEs = CPEntries[CPI];
626 // Number of entries per constpool index should be small, just do a
627 // linear search.
628 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
629 if (CPEs[i].CPEMI == CPEMI)
630 return &CPEs[i];
631 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000632 return nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000633}
634
635/// getCPELogAlign - Returns the required alignment of the constant pool entry
636/// represented by CPEMI. Alignment is measured in log2(bytes) units.
637unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
638 assert(CPEMI && CPEMI->getOpcode() == Mips::CONSTPOOL_ENTRY);
639
640 // Everything is 4-byte aligned unless AlignConstantIslands is set.
641 if (!AlignConstantIslands)
642 return 2;
643
644 unsigned CPI = CPEMI->getOperand(1).getIndex();
645 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
646 unsigned Align = MCP->getConstants()[CPI].getAlignment();
647 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
648 return Log2_32(Align);
649}
650
651/// initializeFunctionInfo - Do the initial scan of the function, building up
652/// information about the sizes of each block, the location of all the water,
653/// and finding all of the constant pool users.
654void MipsConstantIslands::
655initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
656 BBInfo.clear();
657 BBInfo.resize(MF->getNumBlockIDs());
658
659 // First thing, compute the size of all basic blocks, and see if the function
660 // has any inline assembly in it. If so, we have to be conservative about
661 // alignment assumptions, as we don't know for sure the size of any
662 // instructions in the inline assembly.
663 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000664 computeBlockSize(&*I);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000665
Reed Kotler0f007fc2013-11-05 08:14:14 +0000666
667 // Compute block offsets.
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000668 adjustBBOffsetsAfter(&MF->front());
Reed Kotler0f007fc2013-11-05 08:14:14 +0000669
670 // Now go back through the instructions and build up our data structures.
671 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
672 MBBI != E; ++MBBI) {
673 MachineBasicBlock &MBB = *MBBI;
674
675 // If this block doesn't fall through into the next MBB, then this is
676 // 'water' that a constant pool island could be placed.
677 if (!BBHasFallthrough(&MBB))
678 WaterList.push_back(&MBB);
679 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
680 I != E; ++I) {
681 if (I->isDebugValue())
682 continue;
683
684 int Opc = I->getOpcode();
685 if (I->isBranch()) {
686 bool isCond = false;
687 unsigned Bits = 0;
688 unsigned Scale = 1;
689 int UOpc = Opc;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000690 switch (Opc) {
691 default:
Reed Kotler4b7afe52013-11-13 23:52:18 +0000692 continue; // Ignore other branches for now
693 case Mips::Bimm16:
694 Bits = 11;
695 Scale = 2;
696 isCond = false;
697 break;
698 case Mips::BimmX16:
699 Bits = 16;
700 Scale = 2;
701 isCond = false;
Reed Kotler0d409e22013-11-28 00:56:37 +0000702 break;
703 case Mips::BeqzRxImm16:
Reed Kotler59975c22013-12-03 23:42:51 +0000704 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000705 Bits = 8;
706 Scale = 2;
707 isCond = true;
708 break;
709 case Mips::BeqzRxImmX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000710 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000711 Bits = 16;
712 Scale = 2;
713 isCond = true;
714 break;
715 case Mips::BnezRxImm16:
Reed Kotler59975c22013-12-03 23:42:51 +0000716 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000717 Bits = 8;
718 Scale = 2;
719 isCond = true;
720 break;
721 case Mips::BnezRxImmX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000722 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000723 Bits = 16;
724 Scale = 2;
725 isCond = true;
726 break;
727 case Mips::Bteqz16:
Reed Kotler59975c22013-12-03 23:42:51 +0000728 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000729 Bits = 8;
730 Scale = 2;
731 isCond = true;
732 break;
733 case Mips::BteqzX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000734 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000735 Bits = 16;
736 Scale = 2;
737 isCond = true;
738 break;
739 case Mips::Btnez16:
Reed Kotler59975c22013-12-03 23:42:51 +0000740 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000741 Bits = 8;
742 Scale = 2;
743 isCond = true;
744 break;
745 case Mips::BtnezX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000746 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000747 Bits = 16;
748 Scale = 2;
749 isCond = true;
750 break;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000751 }
752 // Record this immediate branch.
753 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
754 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Reed Kotler0f007fc2013-11-05 08:14:14 +0000755 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000756
757 if (Opc == Mips::CONSTPOOL_ENTRY)
758 continue;
759
760
761 // Scan the instructions for constant pool operands.
762 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
763 if (I->getOperand(op).isCPI()) {
764
765 // We found one. The addressing mode tells us the max displacement
766 // from the PC that this instruction permits.
767
768 // Basic size info comes from the TSFlags field.
769 unsigned Bits = 0;
770 unsigned Scale = 1;
771 bool NegOk = false;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000772 unsigned LongFormBits = 0;
773 unsigned LongFormScale = 0;
774 unsigned LongFormOpcode = 0;
775 switch (Opc) {
776 default:
777 llvm_unreachable("Unknown addressing mode for CP reference!");
778 case Mips::LwRxPcTcp16:
779 Bits = 8;
Reed Kotler3d7b33f2013-11-06 04:29:52 +0000780 Scale = 4;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000781 LongFormOpcode = Mips::LwRxPcTcpX16;
Reed Kotler43788a22014-01-16 00:47:46 +0000782 LongFormBits = 14;
Reed Kotler45c59272013-11-10 00:09:26 +0000783 LongFormScale = 1;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000784 break;
785 case Mips::LwRxPcTcpX16:
Reed Kotler43788a22014-01-16 00:47:46 +0000786 Bits = 14;
Reed Kotler3d7b33f2013-11-06 04:29:52 +0000787 Scale = 1;
788 NegOk = true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000789 break;
790 }
791 // Remember that this is a user of a CP entry.
792 unsigned CPI = I->getOperand(op).getIndex();
793 MachineInstr *CPEMI = CPEMIs[CPI];
794 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
795 unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
796 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000797 LongFormMaxOffs, LongFormOpcode));
Reed Kotler0f007fc2013-11-05 08:14:14 +0000798
799 // Increment corresponding CPEntry reference count.
800 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
801 assert(CPE && "Cannot find a corresponding CPEntry!");
802 CPE->RefCount++;
803
804 // Instructions can only use one CP entry, don't bother scanning the
805 // rest of the operands.
806 break;
807
808 }
809
810 }
811 }
812
813}
814
815/// computeBlockSize - Compute the size and some alignment information for MBB.
816/// This function updates BBInfo directly.
817void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
818 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
819 BBI.Size = 0;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000820
821 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
822 ++I)
823 BBI.Size += TII->GetInstSizeInBytes(I);
824
825}
826
827/// getOffsetOf - Return the current offset of the specified machine instruction
828/// from the start of the function. This offset changes as stuff is moved
829/// around inside the function.
830unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
831 MachineBasicBlock *MBB = MI->getParent();
832
833 // The offset is composed of two things: the sum of the sizes of all MBB's
834 // before this instruction's block, and the offset from the start of the block
835 // it is in.
836 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
837
838 // Sum instructions before MI in MBB.
839 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
840 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
841 Offset += TII->GetInstSizeInBytes(I);
842 }
843 return Offset;
844}
845
846/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
847/// ID.
848static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
849 const MachineBasicBlock *RHS) {
850 return LHS->getNumber() < RHS->getNumber();
851}
852
853/// updateForInsertedWaterBlock - When a block is newly inserted into the
854/// machine function, it upsets all of the block numbers. Renumber the blocks
855/// and update the arrays that parallel this numbering.
856void MipsConstantIslands::updateForInsertedWaterBlock
857 (MachineBasicBlock *NewBB) {
858 // Renumber the MBB's to keep them consecutive.
859 NewBB->getParent()->RenumberBlocks(NewBB);
860
861 // Insert an entry into BBInfo to align it properly with the (newly
862 // renumbered) block numbers.
863 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
864
865 // Next, update WaterList. Specifically, we need to add NewMBB as having
866 // available water after it.
867 water_iterator IP =
868 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
869 CompareMBBNumbers);
870 WaterList.insert(IP, NewBB);
871}
872
Reed Kotler0f007fc2013-11-05 08:14:14 +0000873unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
Reed Kotler0eb87392013-11-05 21:39:57 +0000874 return getOffsetOf(U.MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000875}
876
877/// Split the basic block containing MI into two blocks, which are joined by
878/// an unconditional branch. Update data structures and renumber blocks to
879/// account for this change and returns the newly created block.
880MachineBasicBlock *MipsConstantIslands::splitBlockBeforeInstr
881 (MachineInstr *MI) {
882 MachineBasicBlock *OrigBB = MI->getParent();
883
884 // Create a new MBB for the code after the OrigBB.
885 MachineBasicBlock *NewBB =
886 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000887 MachineFunction::iterator MBBI = ++OrigBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000888 MF->insert(MBBI, NewBB);
889
890 // Splice the instructions starting with MI over to NewBB.
891 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
892
893 // Add an unconditional branch from OrigBB to NewBB.
894 // Note the new unconditional branch is not being recorded.
895 // There doesn't seem to be meaningful DebugInfo available; this doesn't
896 // correspond to anything in the source.
Reed Kotlerf0e69682013-11-12 02:27:12 +0000897 BuildMI(OrigBB, DebugLoc(), TII->get(Mips::Bimm16)).addMBB(NewBB);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000898 ++NumSplit;
899
900 // Update the CFG. All succs of OrigBB are now succs of NewBB.
901 NewBB->transferSuccessors(OrigBB);
902
903 // OrigBB branches to NewBB.
904 OrigBB->addSuccessor(NewBB);
905
906 // Update internal data structures to account for the newly inserted MBB.
907 // This is almost the same as updateForInsertedWaterBlock, except that
908 // the Water goes after OrigBB, not NewBB.
909 MF->RenumberBlocks(NewBB);
910
911 // Insert an entry into BBInfo to align it properly with the (newly
912 // renumbered) block numbers.
913 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
914
915 // Next, update WaterList. Specifically, we need to add OrigMBB as having
916 // available water after it (but not if it's already there, which happens
917 // when splitting before a conditional branch that is followed by an
918 // unconditional branch - in that case we want to insert NewBB).
919 water_iterator IP =
920 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
921 CompareMBBNumbers);
922 MachineBasicBlock* WaterBB = *IP;
923 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000924 WaterList.insert(std::next(IP), NewBB);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000925 else
926 WaterList.insert(IP, OrigBB);
927 NewWaterList.insert(OrigBB);
928
929 // Figure out how large the OrigBB is. As the first half of the original
930 // block, it cannot contain a tablejump. The size includes
931 // the new jump we added. (It should be possible to do this without
932 // recounting everything, but it's very confusing, and this is rarely
933 // executed.)
934 computeBlockSize(OrigBB);
935
936 // Figure out how large the NewMBB is. As the second half of the original
937 // block, it may contain a tablejump.
938 computeBlockSize(NewBB);
939
940 // All BBOffsets following these blocks must be modified.
941 adjustBBOffsetsAfter(OrigBB);
942
943 return NewBB;
944}
945
946
947
948/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
949/// reference) is within MaxDisp of TrialOffset (a proposed location of a
950/// constant pool entry).
Reed Kotler0f007fc2013-11-05 08:14:14 +0000951bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
952 unsigned TrialOffset, unsigned MaxDisp,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000953 bool NegativeOK) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000954 if (UserOffset <= TrialOffset) {
955 // User before the Trial.
956 if (TrialOffset - UserOffset <= MaxDisp)
957 return true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000958 } else if (NegativeOK) {
959 if (UserOffset - TrialOffset <= MaxDisp)
960 return true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000961 }
962 return false;
963}
964
965/// isWaterInRange - Returns true if a CPE placed after the specified
966/// Water (a basic block) will be in range for the specific MI.
967///
968/// Compute how much the function will grow by inserting a CPE after Water.
969bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
970 MachineBasicBlock* Water, CPUser &U,
971 unsigned &Growth) {
972 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
973 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
974 unsigned NextBlockOffset, NextBlockAlignment;
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000975 MachineFunction::const_iterator NextBlock = ++Water->getIterator();
976 if (NextBlock == MF->end()) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000977 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
978 NextBlockAlignment = 0;
979 } else {
980 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
981 NextBlockAlignment = NextBlock->getAlignment();
982 }
983 unsigned Size = U.CPEMI->getOperand(2).getImm();
984 unsigned CPEEnd = CPEOffset + Size;
985
986 // The CPE may be able to hide in the alignment padding before the next
987 // block. It may also cause more padding to be required if it is more aligned
988 // that the next block.
989 if (CPEEnd > NextBlockOffset) {
990 Growth = CPEEnd - NextBlockOffset;
991 // Compute the padding that would go at the end of the CPE to align the next
992 // block.
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +0000993 Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000994
995 // If the CPE is to be inserted before the instruction, that will raise
996 // the offset of the instruction. Also account for unknown alignment padding
997 // in blocks between CPE and the user.
998 if (CPEOffset < UserOffset)
Reed Kotler7ded5b62013-11-05 23:36:58 +0000999 UserOffset += Growth;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001000 } else
1001 // CPE fits in existing padding.
1002 Growth = 0;
1003
1004 return isOffsetInRange(UserOffset, CPEOffset, U);
1005}
1006
1007/// isCPEntryInRange - Returns true if the distance between specific MI and
1008/// specific ConstPool entry instruction can fit in MI's displacement field.
1009bool MipsConstantIslands::isCPEntryInRange
1010 (MachineInstr *MI, unsigned UserOffset,
1011 MachineInstr *CPEMI, unsigned MaxDisp,
1012 bool NegOk, bool DoDump) {
1013 unsigned CPEOffset = getOffsetOf(CPEMI);
1014
1015 if (DoDump) {
1016 DEBUG({
1017 unsigned Block = MI->getParent()->getNumber();
1018 const BasicBlockInfo &BBI = BBInfo[Block];
1019 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1020 << " max delta=" << MaxDisp
1021 << format(" insn address=%#x", UserOffset)
1022 << " in BB#" << Block << ": "
1023 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1024 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1025 int(CPEOffset-UserOffset));
1026 });
1027 }
1028
1029 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1030}
1031
1032#ifndef NDEBUG
1033/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1034/// unconditionally branches to its only successor.
1035static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1036 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1037 return false;
1038 MachineBasicBlock *Succ = *MBB->succ_begin();
1039 MachineBasicBlock *Pred = *MBB->pred_begin();
1040 MachineInstr *PredMI = &Pred->back();
Reed Kotlerf0e69682013-11-12 02:27:12 +00001041 if (PredMI->getOpcode() == Mips::Bimm16)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001042 return PredMI->getOperand(0).getMBB() == Succ;
1043 return false;
1044}
1045#endif
1046
1047void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1048 unsigned BBNum = BB->getNumber();
1049 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1050 // Get the offset and known bits at the end of the layout predecessor.
1051 // Include the alignment of the current block.
Reed Kotler7ded5b62013-11-05 23:36:58 +00001052 unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001053 BBInfo[i].Offset = Offset;
1054 }
1055}
1056
1057/// decrementCPEReferenceCount - find the constant pool entry with index CPI
1058/// and instruction CPEMI, and decrement its refcount. If the refcount
1059/// becomes 0 remove the entry and instruction. Returns true if we removed
1060/// the entry, false if we didn't.
1061
1062bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1063 MachineInstr *CPEMI) {
1064 // Find the old entry. Eliminate it if it is no longer used.
1065 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1066 assert(CPE && "Unexpected!");
1067 if (--CPE->RefCount == 0) {
1068 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001069 CPE->CPEMI = nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001070 --NumCPEs;
1071 return true;
1072 }
1073 return false;
1074}
1075
1076/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1077/// if not, see if an in-range clone of the CPE is in range, and if so,
1078/// change the data structures so the user references the clone. Returns:
1079/// 0 = no existing entry found
1080/// 1 = entry found, and there were no code insertions or deletions
1081/// 2 = entry found, and there were code insertions or deletions
1082int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1083{
1084 MachineInstr *UserMI = U.MI;
1085 MachineInstr *CPEMI = U.CPEMI;
1086
1087 // Check to see if the CPE is already in-range.
1088 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1089 true)) {
1090 DEBUG(dbgs() << "In range\n");
1091 return 1;
1092 }
1093
1094 // No. Look for previously created clones of the CPE that are in range.
1095 unsigned CPI = CPEMI->getOperand(1).getIndex();
1096 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1097 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1098 // We already tried this one
1099 if (CPEs[i].CPEMI == CPEMI)
1100 continue;
1101 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001102 if (CPEs[i].CPEMI == nullptr)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001103 continue;
1104 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1105 U.NegOk)) {
1106 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1107 << CPEs[i].CPI << "\n");
1108 // Point the CPUser node to the replacement
1109 U.CPEMI = CPEs[i].CPEMI;
1110 // Change the CPI in the instruction operand to refer to the clone.
1111 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1112 if (UserMI->getOperand(j).isCPI()) {
1113 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1114 break;
1115 }
1116 // Adjust the refcount of the clone...
1117 CPEs[i].RefCount++;
1118 // ...and the original. If we didn't remove the old entry, none of the
1119 // addresses changed, so we don't need another pass.
1120 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1121 }
1122 }
1123 return 0;
1124}
1125
1126/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1127/// This version checks if the longer form of the instruction can be used to
1128/// to satisfy things.
1129/// if not, see if an in-range clone of the CPE is in range, and if so,
1130/// change the data structures so the user references the clone. Returns:
1131/// 0 = no existing entry found
1132/// 1 = entry found, and there were no code insertions or deletions
1133/// 2 = entry found, and there were code insertions or deletions
1134int MipsConstantIslands::findLongFormInRangeCPEntry
1135 (CPUser& U, unsigned UserOffset)
1136{
1137 MachineInstr *UserMI = U.MI;
1138 MachineInstr *CPEMI = U.CPEMI;
1139
1140 // Check to see if the CPE is already in-range.
1141 if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
1142 U.getLongFormMaxDisp(), U.NegOk,
1143 true)) {
1144 DEBUG(dbgs() << "In range\n");
1145 UserMI->setDesc(TII->get(U.getLongFormOpcode()));
Reed Kotler45c59272013-11-10 00:09:26 +00001146 U.setMaxDisp(U.getLongFormMaxDisp());
Reed Kotler0f007fc2013-11-05 08:14:14 +00001147 return 2; // instruction is longer length now
1148 }
1149
1150 // No. Look for previously created clones of the CPE that are in range.
1151 unsigned CPI = CPEMI->getOperand(1).getIndex();
1152 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1153 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1154 // We already tried this one
1155 if (CPEs[i].CPEMI == CPEMI)
1156 continue;
1157 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001158 if (CPEs[i].CPEMI == nullptr)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001159 continue;
1160 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
1161 U.getLongFormMaxDisp(), U.NegOk)) {
1162 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1163 << CPEs[i].CPI << "\n");
1164 // Point the CPUser node to the replacement
1165 U.CPEMI = CPEs[i].CPEMI;
1166 // Change the CPI in the instruction operand to refer to the clone.
1167 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1168 if (UserMI->getOperand(j).isCPI()) {
1169 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1170 break;
1171 }
1172 // Adjust the refcount of the clone...
1173 CPEs[i].RefCount++;
1174 // ...and the original. If we didn't remove the old entry, none of the
1175 // addresses changed, so we don't need another pass.
1176 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1177 }
1178 }
1179 return 0;
1180}
1181
1182/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1183/// the specific unconditional branch instruction.
1184static inline unsigned getUnconditionalBrDisp(int Opc) {
1185 switch (Opc) {
Reed Kotlerf0e69682013-11-12 02:27:12 +00001186 case Mips::Bimm16:
1187 return ((1<<10)-1)*2;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001188 case Mips::BimmX16:
1189 return ((1<<16)-1)*2;
1190 default:
1191 break;
1192 }
1193 return ((1<<16)-1)*2;
1194}
1195
1196/// findAvailableWater - Look for an existing entry in the WaterList in which
1197/// we can place the CPE referenced from U so it's within range of U's MI.
1198/// Returns true if found, false if not. If it returns true, WaterIter
Reed Kotler4d0313d2013-11-05 12:04:37 +00001199/// is set to the WaterList entry.
1200/// To ensure that this pass
Reed Kotler0f007fc2013-11-05 08:14:14 +00001201/// terminates, the CPE location for a particular CPUser is only allowed to
1202/// move to a lower address, so search backward from the end of the list and
1203/// prefer the first water that is in range.
1204bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1205 water_iterator &WaterIter) {
1206 if (WaterList.empty())
1207 return false;
1208
1209 unsigned BestGrowth = ~0u;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001210 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001211 --IP) {
1212 MachineBasicBlock* WaterBB = *IP;
1213 // Check if water is in range and is either at a lower address than the
1214 // current "high water mark" or a new water block that was created since
1215 // the previous iteration by inserting an unconditional branch. In the
1216 // latter case, we want to allow resetting the high water mark back to
1217 // this new water since we haven't seen it before. Inserting branches
1218 // should be relatively uncommon and when it does happen, we want to be
1219 // sure to take advantage of it for all the CPEs near that block, so that
1220 // we don't insert more branches than necessary.
1221 unsigned Growth;
1222 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1223 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1224 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1225 // This is the least amount of required padding seen so far.
1226 BestGrowth = Growth;
1227 WaterIter = IP;
1228 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1229 << " Growth=" << Growth << '\n');
1230
1231 // Keep looking unless it is perfect.
1232 if (BestGrowth == 0)
1233 return true;
1234 }
1235 if (IP == B)
1236 break;
1237 }
1238 return BestGrowth != ~0u;
1239}
1240
1241/// createNewWater - No existing WaterList entry will work for
1242/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1243/// block is used if in range, and the conditional branch munged so control
1244/// flow is correct. Otherwise the block is split to create a hole with an
1245/// unconditional branch around it. In either case NewMBB is set to a
1246/// block following which the new island can be inserted (the WaterList
1247/// is not adjusted).
1248void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1249 unsigned UserOffset,
1250 MachineBasicBlock *&NewMBB) {
1251 CPUser &U = CPUsers[CPUserIndex];
1252 MachineInstr *UserMI = U.MI;
1253 MachineInstr *CPEMI = U.CPEMI;
1254 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1255 MachineBasicBlock *UserMBB = UserMI->getParent();
1256 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1257
1258 // If the block does not end in an unconditional branch already, and if the
Reed Kotler4d0313d2013-11-05 12:04:37 +00001259 // end of the block is within range, make new water there.
Reed Kotler0f007fc2013-11-05 08:14:14 +00001260 if (BBHasFallthrough(UserMBB)) {
1261 // Size of branch to insert.
1262 unsigned Delta = 2;
1263 // Compute the offset where the CPE will begin.
1264 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1265
1266 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1267 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1268 << format(", expected CPE offset %#x\n", CPEOffset));
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001269 NewMBB = &*++UserMBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001270 // Add an unconditional branch from UserMBB to fallthrough block. Record
1271 // it for branch lengthening; this new branch will not get out of range,
1272 // but if the preceding conditional branch is out of range, the targets
1273 // will be exchanged, and the altered branch may be out of range, so the
1274 // machinery has to know about it.
Reed Kotlerf0e69682013-11-12 02:27:12 +00001275 int UncondBr = Mips::Bimm16;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001276 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1277 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1278 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1279 MaxDisp, false, UncondBr));
1280 BBInfo[UserMBB->getNumber()].Size += Delta;
1281 adjustBBOffsetsAfter(UserMBB);
1282 return;
1283 }
1284 }
1285
Reed Kotler4d0313d2013-11-05 12:04:37 +00001286 // What a big block. Find a place within the block to split it.
Reed Kotler0f007fc2013-11-05 08:14:14 +00001287
1288 // Try to split the block so it's fully aligned. Compute the latest split
1289 // point where we can add a 4-byte branch instruction, and then align to
1290 // LogAlign which is the largest possible alignment in the function.
1291 unsigned LogAlign = MF->getAlignment();
1292 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
Reed Kotler7ded5b62013-11-05 23:36:58 +00001293 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001294 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1295 BaseInsertOffset));
1296
1297 // The 4 in the following is for the unconditional branch we'll be inserting
Reed Kotler4d0313d2013-11-05 12:04:37 +00001298 // Alignment of the island is handled
Reed Kotler0f007fc2013-11-05 08:14:14 +00001299 // inside isOffsetInRange.
1300 BaseInsertOffset -= 4;
1301
1302 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
Reed Kotler7ded5b62013-11-05 23:36:58 +00001303 << " la=" << LogAlign << '\n');
Reed Kotler0f007fc2013-11-05 08:14:14 +00001304
1305 // This could point off the end of the block if we've already got constant
1306 // pool entries following this block; only the last one is in the water list.
1307 // Back past any possible branches (allow for a conditional and a maximally
1308 // long unconditional).
1309 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Reed Kotler7ded5b62013-11-05 23:36:58 +00001310 BaseInsertOffset = UserBBI.postOffset() - 8;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001311 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1312 }
Reed Kotler7ded5b62013-11-05 23:36:58 +00001313 unsigned EndInsertOffset = BaseInsertOffset + 4 +
Reed Kotler0f007fc2013-11-05 08:14:14 +00001314 CPEMI->getOperand(2).getImm();
1315 MachineBasicBlock::iterator MI = UserMI;
1316 ++MI;
1317 unsigned CPUIndex = CPUserIndex+1;
1318 unsigned NumCPUsers = CPUsers.size();
1319 //MachineInstr *LastIT = 0;
1320 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1321 Offset < BaseInsertOffset;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001322 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001323 assert(MI != UserMBB->end() && "Fell off end of block");
1324 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1325 CPUser &U = CPUsers[CPUIndex];
1326 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1327 // Shift intertion point by one unit of alignment so it is within reach.
1328 BaseInsertOffset -= 1u << LogAlign;
1329 EndInsertOffset -= 1u << LogAlign;
1330 }
1331 // This is overly conservative, as we don't account for CPEMIs being
1332 // reused within the block, but it doesn't matter much. Also assume CPEs
1333 // are added in order with alignment padding. We may eventually be able
1334 // to pack the aligned CPEs better.
1335 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1336 CPUIndex++;
1337 }
1338 }
1339
1340 --MI;
1341 NewMBB = splitBlockBeforeInstr(MI);
1342}
1343
1344/// handleConstantPoolUser - Analyze the specified user, checking to see if it
1345/// is out-of-range. If so, pick up the constant pool value and move it some
1346/// place in-range. Return true if we changed any addresses (thus must run
1347/// another pass of branch lengthening), false otherwise.
1348bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1349 CPUser &U = CPUsers[CPUserIndex];
1350 MachineInstr *UserMI = U.MI;
1351 MachineInstr *CPEMI = U.CPEMI;
1352 unsigned CPI = CPEMI->getOperand(1).getIndex();
1353 unsigned Size = CPEMI->getOperand(2).getImm();
1354 // Compute this only once, it's expensive.
1355 unsigned UserOffset = getUserOffset(U);
1356
1357 // See if the current entry is within range, or there is a clone of it
1358 // in range.
1359 int result = findInRangeCPEntry(U, UserOffset);
1360 if (result==1) return false;
1361 else if (result==2) return true;
1362
1363
1364 // Look for water where we can place this CPE.
1365 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1366 MachineBasicBlock *NewMBB;
1367 water_iterator IP;
1368 if (findAvailableWater(U, UserOffset, IP)) {
1369 DEBUG(dbgs() << "Found water in range\n");
1370 MachineBasicBlock *WaterBB = *IP;
1371
1372 // If the original WaterList entry was "new water" on this iteration,
1373 // propagate that to the new island. This is just keeping NewWaterList
1374 // updated to match the WaterList, which will be updated below.
1375 if (NewWaterList.erase(WaterBB))
1376 NewWaterList.insert(NewIsland);
1377
1378 // The new CPE goes before the following block (NewMBB).
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001379 NewMBB = &*++WaterBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001380 } else {
1381 // No water found.
1382 // we first see if a longer form of the instrucion could have reached
1383 // the constant. in that case we won't bother to split
Reed Kotler45c59272013-11-10 00:09:26 +00001384 if (!NoLoadRelaxation) {
1385 result = findLongFormInRangeCPEntry(U, UserOffset);
1386 if (result != 0) return true;
1387 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001388 DEBUG(dbgs() << "No water found\n");
1389 createNewWater(CPUserIndex, UserOffset, NewMBB);
1390
1391 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1392 // called while handling branches so that the water will be seen on the
1393 // next iteration for constant pools, but in this context, we don't want
1394 // it. Check for this so it will be removed from the WaterList.
1395 // Also remove any entry from NewWaterList.
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001396 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001397 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1398 if (IP != WaterList.end())
1399 NewWaterList.erase(WaterBB);
1400
1401 // We are adding new water. Update NewWaterList.
1402 NewWaterList.insert(NewIsland);
1403 }
1404
1405 // Remove the original WaterList entry; we want subsequent insertions in
1406 // this vicinity to go after the one we're about to insert. This
1407 // considerably reduces the number of times we have to move the same CPE
1408 // more than once and is also important to ensure the algorithm terminates.
1409 if (IP != WaterList.end())
1410 WaterList.erase(IP);
1411
1412 // Okay, we know we can put an island before NewMBB now, do it!
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001413 MF->insert(NewMBB->getIterator(), NewIsland);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001414
1415 // Update internal data structures to account for the newly inserted MBB.
1416 updateForInsertedWaterBlock(NewIsland);
1417
1418 // Decrement the old entry, and remove it if refcount becomes 0.
1419 decrementCPEReferenceCount(CPI, CPEMI);
1420
Reed Kotlerd3b28eb2013-11-24 02:53:09 +00001421 // No existing clone of this CPE is within range.
1422 // We will be generating a new clone. Get a UID for it.
1423 unsigned ID = createPICLabelUId();
1424
Reed Kotler0f007fc2013-11-05 08:14:14 +00001425 // Now that we have an island to add the CPE to, clone the original CPE and
1426 // add it to the island.
1427 U.HighWaterMark = NewIsland;
1428 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1429 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1430 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1431 ++NumCPEs;
1432
1433 // Mark the basic block as aligned as required by the const-pool entry.
1434 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1435
1436 // Increase the size of the island block to account for the new entry.
1437 BBInfo[NewIsland->getNumber()].Size += Size;
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001438 adjustBBOffsetsAfter(&*--NewIsland->getIterator());
Reed Kotler0f007fc2013-11-05 08:14:14 +00001439
1440 // Finally, change the CPI in the instruction operand to be ID.
1441 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1442 if (UserMI->getOperand(i).isCPI()) {
1443 UserMI->getOperand(i).setIndex(ID);
1444 break;
1445 }
1446
1447 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1448 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1449
1450 return true;
1451}
1452
1453/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1454/// sizes and offsets of impacted basic blocks.
1455void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1456 MachineBasicBlock *CPEBB = CPEMI->getParent();
1457 unsigned Size = CPEMI->getOperand(2).getImm();
1458 CPEMI->eraseFromParent();
1459 BBInfo[CPEBB->getNumber()].Size -= Size;
1460 // All succeeding offsets have the current size value added in, fix this.
1461 if (CPEBB->empty()) {
1462 BBInfo[CPEBB->getNumber()].Size = 0;
1463
1464 // This block no longer needs to be aligned.
1465 CPEBB->setAlignment(0);
1466 } else
1467 // Entries are sorted by descending alignment, so realign from the front.
1468 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1469
1470 adjustBBOffsetsAfter(CPEBB);
1471 // An island has only one predecessor BB and one successor BB. Check if
1472 // this BB's predecessor jumps directly to this BB's successor. This
1473 // shouldn't happen currently.
1474 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1475 // FIXME: remove the empty blocks after all the work is done?
1476}
1477
1478/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1479/// are zero.
1480bool MipsConstantIslands::removeUnusedCPEntries() {
1481 unsigned MadeChange = false;
1482 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1483 std::vector<CPEntry> &CPEs = CPEntries[i];
1484 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1485 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1486 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001487 CPEs[j].CPEMI = nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001488 MadeChange = true;
1489 }
1490 }
1491 }
1492 return MadeChange;
1493}
1494
1495/// isBBInRange - Returns true if the distance between specific MI and
1496/// specific BB can fit in MI's displacement field.
1497bool MipsConstantIslands::isBBInRange
1498 (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
1499
1500unsigned PCAdj = 4;
1501
1502 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1503 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1504
1505 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1506 << " from BB#" << MI->getParent()->getNumber()
1507 << " max delta=" << MaxDisp
1508 << " from " << getOffsetOf(MI) << " to " << DestOffset
1509 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1510
1511 if (BrOffset <= DestOffset) {
1512 // Branch before the Dest.
1513 if (DestOffset-BrOffset <= MaxDisp)
1514 return true;
1515 } else {
1516 if (BrOffset-DestOffset <= MaxDisp)
1517 return true;
1518 }
1519 return false;
1520}
1521
1522/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1523/// away to fit in its displacement field.
1524bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1525 MachineInstr *MI = Br.MI;
Reed Kotler0d409e22013-11-28 00:56:37 +00001526 unsigned TargetOperand = branchTargetOperand(MI);
1527 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001528
1529 // Check to see if the DestBB is already in-range.
1530 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1531 return false;
1532
1533 if (!Br.isCond)
1534 return fixupUnconditionalBr(Br);
1535 return fixupConditionalBr(Br);
1536}
1537
1538/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1539/// too far away to fit in its displacement field. If the LR register has been
1540/// spilled in the epilogue, then we can use BL to implement a far jump.
1541/// Otherwise, add an intermediate branch instruction to a branch.
1542bool
1543MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1544 MachineInstr *MI = Br.MI;
1545 MachineBasicBlock *MBB = MI->getParent();
Reed Kotler2fc05be2013-11-21 05:13:23 +00001546 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001547 // Use BL to implement far jump.
Reed Kotler2fc05be2013-11-21 05:13:23 +00001548 unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2;
1549 if (isBBInRange(MI, DestBB, BimmX16MaxDisp)) {
1550 Br.MaxDisp = BimmX16MaxDisp;
1551 MI->setDesc(TII->get(Mips::BimmX16));
1552 }
1553 else {
1554 // need to give the math a more careful look here
1555 // this is really a segment address and not
1556 // a PC relative address. FIXME. But I think that
1557 // just reducing the bits by 1 as I've done is correct.
1558 // The basic block we are branching too much be longword aligned.
1559 // we know that RA is saved because we always save it right now.
1560 // this requirement will be relaxed later but we also have an alternate
1561 // way to implement this that I will implement that does not need jal.
1562 // We should have a way to back out this alignment restriction if we "can" later.
1563 // but it is not harmful.
1564 //
1565 DestBB->setAlignment(2);
1566 Br.MaxDisp = ((1<<24)-1) * 2;
Reed Kotlerad450f22013-11-29 22:32:56 +00001567 MI->setDesc(TII->get(Mips::JalB16));
Reed Kotler2fc05be2013-11-21 05:13:23 +00001568 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001569 BBInfo[MBB->getNumber()].Size += 2;
1570 adjustBBOffsetsAfter(MBB);
1571 HasFarJump = true;
1572 ++NumUBrFixed;
1573
1574 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1575
1576 return true;
1577}
1578
Reed Kotler0d409e22013-11-28 00:56:37 +00001579
Reed Kotler0f007fc2013-11-05 08:14:14 +00001580/// fixupConditionalBr - Fix up a conditional branch whose destination is too
1581/// far away to fit in its displacement field. It is converted to an inverse
1582/// conditional branch + an unconditional branch to the destination.
1583bool
1584MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1585 MachineInstr *MI = Br.MI;
Reed Kotler0d409e22013-11-28 00:56:37 +00001586 unsigned TargetOperand = branchTargetOperand(MI);
1587 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1588 unsigned Opcode = MI->getOpcode();
1589 unsigned LongFormOpcode = longformBranchOpcode(Opcode);
1590 unsigned LongFormMaxOff = branchMaxOffsets(LongFormOpcode);
1591
1592 // Check to see if the DestBB is already in-range.
1593 if (isBBInRange(MI, DestBB, LongFormMaxOff)) {
1594 Br.MaxDisp = LongFormMaxOff;
1595 MI->setDesc(TII->get(LongFormOpcode));
1596 return true;
1597 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001598
1599 // Add an unconditional branch to the destination and invert the branch
1600 // condition to jump over it:
Reed Kotlerad450f22013-11-29 22:32:56 +00001601 // bteqz L1
Reed Kotler0f007fc2013-11-05 08:14:14 +00001602 // =>
Reed Kotlerad450f22013-11-29 22:32:56 +00001603 // bnez L2
Reed Kotler0f007fc2013-11-05 08:14:14 +00001604 // b L1
1605 // L2:
Reed Kotler0f007fc2013-11-05 08:14:14 +00001606
1607 // If the branch is at the end of its MBB and that has a fall-through block,
1608 // direct the updated conditional branch to the fall-through block. Otherwise,
1609 // split the MBB before the next instruction.
1610 MachineBasicBlock *MBB = MI->getParent();
1611 MachineInstr *BMI = &MBB->back();
1612 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Reed Kotler47f3c64a2013-12-19 00:43:08 +00001613 unsigned OppositeBranchOpcode = TII->getOppositeBranchOpc(Opcode);
Reed Kotlerad450f22013-11-29 22:32:56 +00001614
Reed Kotler0f007fc2013-11-05 08:14:14 +00001615 ++NumCBrFixed;
1616 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001617 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Reed Kotlerad450f22013-11-29 22:32:56 +00001618 isUnconditionalBranch(BMI->getOpcode())) {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001619 // Last MI in the BB is an unconditional branch. Can we simply invert the
1620 // condition and swap destinations:
Reed Kotlerad450f22013-11-29 22:32:56 +00001621 // beqz L1
Reed Kotler0f007fc2013-11-05 08:14:14 +00001622 // b L2
1623 // =>
Reed Kotlerad450f22013-11-29 22:32:56 +00001624 // bnez L2
Reed Kotler0f007fc2013-11-05 08:14:14 +00001625 // b L1
Reed Kotlerad450f22013-11-29 22:32:56 +00001626 unsigned BMITargetOperand = branchTargetOperand(BMI);
1627 MachineBasicBlock *NewDest =
1628 BMI->getOperand(BMITargetOperand).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001629 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1630 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1631 << *BMI);
Reed Kotler59975c22013-12-03 23:42:51 +00001632 MI->setDesc(TII->get(OppositeBranchOpcode));
Reed Kotlerad450f22013-11-29 22:32:56 +00001633 BMI->getOperand(BMITargetOperand).setMBB(DestBB);
1634 MI->getOperand(TargetOperand).setMBB(NewDest);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001635 return true;
1636 }
1637 }
1638 }
1639
Reed Kotlerad450f22013-11-29 22:32:56 +00001640
Reed Kotler0f007fc2013-11-05 08:14:14 +00001641 if (NeedSplit) {
1642 splitBlockBeforeInstr(MI);
1643 // No need for the branch to the next block. We're adding an unconditional
1644 // branch to the destination.
1645 int delta = TII->GetInstSizeInBytes(&MBB->back());
1646 BBInfo[MBB->getNumber()].Size -= delta;
1647 MBB->back().eraseFromParent();
1648 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1649 }
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001650 MachineBasicBlock *NextBB = &*++MBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001651
1652 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1653 << " also invert condition and change dest. to BB#"
1654 << NextBB->getNumber() << "\n");
1655
1656 // Insert a new conditional branch and a new unconditional branch.
1657 // Also update the ImmBranch as well as adding a new entry for the new branch.
Reed Kotler59975c22013-12-03 23:42:51 +00001658 if (MI->getNumExplicitOperands() == 2) {
1659 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1660 .addReg(MI->getOperand(0).getReg())
1661 .addMBB(NextBB);
Reed Kotler47f3c64a2013-12-19 00:43:08 +00001662 } else {
1663 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1664 .addMBB(NextBB);
Reed Kotler59975c22013-12-03 23:42:51 +00001665 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001666 Br.MI = &MBB->back();
1667 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1668 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1669 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1670 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1671 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1672
1673 // Remove the old conditional branch. It may or may not still be in MBB.
1674 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1675 MI->eraseFromParent();
1676 adjustBBOffsetsAfter(MBB);
1677 return true;
1678}
1679
Reed Kotler91ae9822013-10-27 21:57:36 +00001680
1681void MipsConstantIslands::prescanForConstants() {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001682 unsigned J = 0;
1683 (void)J;
Reed Kotler91ae9822013-10-27 21:57:36 +00001684 for (MachineFunction::iterator B =
1685 MF->begin(), E = MF->end(); B != E; ++B) {
1686 for (MachineBasicBlock::instr_iterator I =
1687 B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
1688 switch(I->getDesc().getOpcode()) {
1689 case Mips::LwConstant32: {
Reed Kotlera787aa22013-11-24 06:18:50 +00001690 PrescannedForConstants = true;
Reed Kotler91ae9822013-10-27 21:57:36 +00001691 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1692 J = I->getNumOperands();
1693 DEBUG(dbgs() << "num operands " << J << "\n");
1694 MachineOperand& Literal = I->getOperand(1);
1695 if (Literal.isImm()) {
1696 int64_t V = Literal.getImm();
1697 DEBUG(dbgs() << "literal " << V << "\n");
1698 Type *Int32Ty =
1699 Type::getInt32Ty(MF->getFunction()->getContext());
1700 const Constant *C = ConstantInt::get(Int32Ty, V);
1701 unsigned index = MCP->getConstantPoolIndex(C, 4);
1702 I->getOperand(2).ChangeToImmediate(index);
1703 DEBUG(dbgs() << "constant island constant " << *I << "\n");
Reed Kotler0f007fc2013-11-05 08:14:14 +00001704 I->setDesc(TII->get(Mips::LwRxPcTcp16));
Reed Kotler91ae9822013-10-27 21:57:36 +00001705 I->RemoveOperand(1);
1706 I->RemoveOperand(1);
1707 I->addOperand(MachineOperand::CreateCPI(index, 0));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001708 I->addOperand(MachineOperand::CreateImm(4));
Reed Kotler91ae9822013-10-27 21:57:36 +00001709 }
1710 break;
1711 }
1712 default:
1713 break;
1714 }
1715 }
1716 }
1717}