blob: b58c886c7fcacbce40b17800cf93fa445db33d62 [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
100static unsigned int longformBranchOpcode(unsigned int Opcode) {
101 switch (Opcode) {
102 case Mips::Bimm16:
103 case Mips::BimmX16:
104 return Mips::BimmX16;
105 case Mips::Bteqz16:
106 case Mips::BteqzX16:
107 return Mips::BteqzX16;
108 case Mips::Btnez16:
109 case Mips::BtnezX16:
110 return Mips::BtnezX16;
Reed Kotlerad450f22013-11-29 22:32:56 +0000111 case Mips::JalB16:
112 return Mips::JalB16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000113 case Mips::BeqzRxImm16:
114 case Mips::BeqzRxImmX16:
115 return Mips::BeqzRxImmX16;
116 case Mips::BnezRxImm16:
117 case Mips::BnezRxImmX16:
118 return Mips::BnezRxImmX16;
119 }
120 llvm_unreachable("Unknown branch type");
121}
122
123//
124// FIXME: need to go through this whole constant islands port and check the math
125// for branch ranges and clean this up and make some functions to calculate things
126// that are done many times identically.
127// Need to refactor some of the code to call this routine.
128//
129static unsigned int branchMaxOffsets(unsigned int Opcode) {
130 unsigned Bits, Scale;
131 switch (Opcode) {
132 case Mips::Bimm16:
133 Bits = 11;
134 Scale = 2;
135 break;
136 case Mips::BimmX16:
137 Bits = 16;
138 Scale = 2;
139 break;
140 case Mips::BeqzRxImm16:
141 Bits = 8;
142 Scale = 2;
143 break;
144 case Mips::BeqzRxImmX16:
145 Bits = 16;
146 Scale = 2;
147 break;
148 case Mips::BnezRxImm16:
149 Bits = 8;
150 Scale = 2;
151 break;
152 case Mips::BnezRxImmX16:
153 Bits = 16;
154 Scale = 2;
155 break;
156 case Mips::Bteqz16:
157 Bits = 8;
158 Scale = 2;
159 break;
160 case Mips::BteqzX16:
161 Bits = 16;
162 Scale = 2;
163 break;
164 case Mips::Btnez16:
165 Bits = 8;
166 Scale = 2;
167 break;
168 case Mips::BtnezX16:
169 Bits = 16;
170 Scale = 2;
171 break;
172 default:
173 llvm_unreachable("Unknown branch type");
174 }
175 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
176 return MaxOffs;
177}
Reed Kotler0f007fc2013-11-05 08:14:14 +0000178
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000179namespace {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000180
181
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000182 typedef MachineBasicBlock::iterator Iter;
183 typedef MachineBasicBlock::reverse_iterator ReverseIter;
184
Reed Kotler0f007fc2013-11-05 08:14:14 +0000185 /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
186 /// requires constant pool entries to be scattered among the instructions
187 /// inside a function. To do this, it completely ignores the normal LLVM
188 /// constant pool; instead, it places constants wherever it feels like with
189 /// special instructions.
190 ///
191 /// The terminology used in this pass includes:
192 /// Islands - Clumps of constants placed in the function.
193 /// Water - Potential places where an island could be formed.
194 /// CPE - A constant pool entry that has been placed somewhere, which
195 /// tracks a list of users.
196
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000197 class MipsConstantIslands : public MachineFunctionPass {
198
Reed Kotler0f007fc2013-11-05 08:14:14 +0000199 /// BasicBlockInfo - Information about the offset and size of a single
200 /// basic block.
201 struct BasicBlockInfo {
202 /// Offset - Distance from the beginning of the function to the beginning
203 /// of this basic block.
204 ///
205 /// Offsets are computed assuming worst case padding before an aligned
206 /// block. This means that subtracting basic block offsets always gives a
207 /// conservative estimate of the real distance which may be smaller.
208 ///
209 /// Because worst case padding is used, the computed offset of an aligned
210 /// block may not actually be aligned.
211 unsigned Offset;
212
213 /// Size - Size of the basic block in bytes. If the block contains
214 /// inline assembly, this is a worst case estimate.
215 ///
216 /// The size does not include any alignment padding whether from the
217 /// beginning of the block, or from an aligned jump table at the end.
218 unsigned Size;
219
Reed Kotler7ded5b62013-11-05 23:36:58 +0000220 // FIXME: ignore LogAlign for this patch
221 //
Reed Kotler0f007fc2013-11-05 08:14:14 +0000222 unsigned postOffset(unsigned LogAlign = 0) const {
223 unsigned PO = Offset + Size;
224 return PO;
225 }
226
Reed Kotler7ded5b62013-11-05 23:36:58 +0000227 BasicBlockInfo() : Offset(0), Size(0) {}
228
Reed Kotler0f007fc2013-11-05 08:14:14 +0000229 };
230
231 std::vector<BasicBlockInfo> BBInfo;
232
233 /// WaterList - A sorted list of basic blocks where islands could be placed
234 /// (i.e. blocks that don't fall through to the following block, due
235 /// to a return, unreachable, or unconditional branch).
236 std::vector<MachineBasicBlock*> WaterList;
237
238 /// NewWaterList - The subset of WaterList that was created since the
239 /// previous iteration by inserting unconditional branches.
240 SmallSet<MachineBasicBlock*, 4> NewWaterList;
241
242 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
243
244 /// CPUser - One user of a constant pool, keeping the machine instruction
245 /// pointer, the constant pool being referenced, and the max displacement
246 /// allowed from the instruction to the CP. The HighWaterMark records the
247 /// highest basic block where a new CPEntry can be placed. To ensure this
248 /// pass terminates, the CP entries are initially placed at the end of the
249 /// function and then move monotonically to lower addresses. The
250 /// exception to this rule is when the current CP entry for a particular
251 /// CPUser is out of range, but there is another CP entry for the same
252 /// constant value in range. We want to use the existing in-range CP
253 /// entry, but if it later moves out of range, the search for new water
254 /// should resume where it left off. The HighWaterMark is used to record
255 /// that point.
256 struct CPUser {
257 MachineInstr *MI;
258 MachineInstr *CPEMI;
259 MachineBasicBlock *HighWaterMark;
260 private:
261 unsigned MaxDisp;
262 unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
263 // with different displacements
264 unsigned LongFormOpcode;
265 public:
266 bool NegOk;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000267 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000268 bool neg,
Reed Kotler0f007fc2013-11-05 08:14:14 +0000269 unsigned longformmaxdisp, unsigned longformopcode)
270 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
271 LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
Reed Kotler7ded5b62013-11-05 23:36:58 +0000272 NegOk(neg){
Reed Kotler0f007fc2013-11-05 08:14:14 +0000273 HighWaterMark = CPEMI->getParent();
274 }
275 /// getMaxDisp - Returns the maximum displacement supported by MI.
Reed Kotler0f007fc2013-11-05 08:14:14 +0000276 unsigned getMaxDisp() const {
277 unsigned xMaxDisp = ConstantIslandsSmallOffset?
278 ConstantIslandsSmallOffset: MaxDisp;
Reed Kotler7ded5b62013-11-05 23:36:58 +0000279 return xMaxDisp;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000280 }
Reed Kotler45c59272013-11-10 00:09:26 +0000281 void setMaxDisp(unsigned val) {
282 MaxDisp = val;
283 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000284 unsigned getLongFormMaxDisp() const {
Reed Kotler7ded5b62013-11-05 23:36:58 +0000285 return LongFormMaxDisp;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000286 }
287 unsigned getLongFormOpcode() const {
288 return LongFormOpcode;
289 }
290 };
291
292 /// CPUsers - Keep track of all of the machine instructions that use various
293 /// constant pools and their max displacement.
294 std::vector<CPUser> CPUsers;
Reed Kotler91ae9822013-10-27 21:57:36 +0000295
296 /// CPEntry - One per constant pool entry, keeping the machine instruction
297 /// pointer, the constpool index, and the number of CPUser's which
298 /// reference this entry.
299 struct CPEntry {
300 MachineInstr *CPEMI;
301 unsigned CPI;
302 unsigned RefCount;
303 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
304 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
305 };
306
307 /// CPEntries - Keep track of all of the constant pool entry machine
308 /// instructions. For each original constpool index (i.e. those that
309 /// existed upon entry to this pass), it keeps a vector of entries.
310 /// Original elements are cloned as we go along; the clones are
311 /// put in the vector of the original element, but have distinct CPIs.
312 std::vector<std::vector<CPEntry> > CPEntries;
313
Reed Kotler0f007fc2013-11-05 08:14:14 +0000314 /// ImmBranch - One per immediate branch, keeping the machine instruction
315 /// pointer, conditional or unconditional, the max displacement,
316 /// and (if isCond is true) the corresponding unconditional branch
317 /// opcode.
318 struct ImmBranch {
319 MachineInstr *MI;
320 unsigned MaxDisp : 31;
321 bool isCond : 1;
322 int UncondBr;
323 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
324 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
325 };
326
327 /// ImmBranches - Keep track of all the immediate branch instructions.
328 ///
329 std::vector<ImmBranch> ImmBranches;
330
331 /// HasFarJump - True if any far jump instruction has been emitted during
332 /// the branch fix up pass.
333 bool HasFarJump;
334
Reed Kotler0f007fc2013-11-05 08:14:14 +0000335 const MipsSubtarget *STI;
Reed Kotler5c8ae092013-11-13 04:37:52 +0000336 const Mips16InstrInfo *TII;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000337 MipsFunctionInfo *MFI;
338 MachineFunction *MF;
339 MachineConstantPool *MCP;
340
341 unsigned PICLabelUId;
342 bool PrescannedForConstants;
343
344 void initPICLabelUId(unsigned UId) {
345 PICLabelUId = UId;
346 }
347
348
349 unsigned createPICLabelUId() {
350 return PICLabelUId++;
351 }
352
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000353 public:
354 static char ID;
Rafael Espindola6f7c2802016-06-28 14:26:39 +0000355 MipsConstantIslands()
356 : MachineFunctionPass(ID), STI(nullptr), MF(nullptr), MCP(nullptr),
357 PrescannedForConstants(false) {}
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000358
Craig Topper56c590a2014-04-29 07:58:02 +0000359 const char *getPassName() const override {
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000360 return "Mips Constant Islands";
361 }
362
Craig Topper56c590a2014-04-29 07:58:02 +0000363 bool runOnMachineFunction(MachineFunction &F) override;
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000364
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000365 MachineFunctionProperties getRequiredProperties() const override {
366 return MachineFunctionProperties().set(
367 MachineFunctionProperties::Property::AllVRegsAllocated);
368 }
369
Reed Kotler91ae9822013-10-27 21:57:36 +0000370 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000371 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
372 unsigned getCPELogAlign(const MachineInstr *CPEMI);
373 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
374 unsigned getOffsetOf(MachineInstr *MI) const;
375 unsigned getUserOffset(CPUser&) const;
376 void dumpBBs();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000377
378 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000379 unsigned Disp, bool NegativeOK);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000380 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
381 const CPUser &U);
382
Reed Kotler0f007fc2013-11-05 08:14:14 +0000383 void computeBlockSize(MachineBasicBlock *MBB);
384 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
385 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
386 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
387 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
388 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
389 int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
390 bool findAvailableWater(CPUser&U, unsigned UserOffset,
391 water_iterator &WaterIter);
392 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
393 MachineBasicBlock *&NewMBB);
394 bool handleConstantPoolUser(unsigned CPUserIndex);
395 void removeDeadCPEMI(MachineInstr *CPEMI);
396 bool removeUnusedCPEntries();
397 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
398 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
399 bool DoDump = false);
400 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
401 CPUser &U, unsigned &Growth);
402 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
403 bool fixupImmediateBr(ImmBranch &Br);
404 bool fixupConditionalBr(ImmBranch &Br);
405 bool fixupUnconditionalBr(ImmBranch &Br);
Reed Kotler91ae9822013-10-27 21:57:36 +0000406
407 void prescanForConstants();
408
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000409 private:
Reed Kotler91ae9822013-10-27 21:57:36 +0000410
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000411 };
412
413 char MipsConstantIslands::ID = 0;
414} // end of anonymous namespace
415
Reed Kotler0f007fc2013-11-05 08:14:14 +0000416bool MipsConstantIslands::isOffsetInRange
417 (unsigned UserOffset, unsigned TrialOffset,
418 const CPUser &U) {
419 return isOffsetInRange(UserOffset, TrialOffset,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000420 U.getMaxDisp(), U.NegOk);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000421}
422/// print block size and offset information - debugging
423void MipsConstantIslands::dumpBBs() {
424 DEBUG({
425 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
426 const BasicBlockInfo &BBI = BBInfo[J];
427 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
Reed Kotler0f007fc2013-11-05 08:14:14 +0000428 << format(" size=%#x\n", BBInfo[J].Size);
429 }
430 });
431}
Rafael Espindola6f7c2802016-06-28 14:26:39 +0000432/// Returns a pass that converts branches to long branches.
433FunctionPass *llvm::createMipsConstantIslandPass() {
434 return new MipsConstantIslands();
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000435}
436
Reed Kotler91ae9822013-10-27 21:57:36 +0000437bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
Reed Kotler1595f362013-04-09 19:46:01 +0000438 // The intention is for this to be a mips16 only pass for now
439 // FIXME:
Reed Kotler91ae9822013-10-27 21:57:36 +0000440 MF = &mf;
441 MCP = mf.getConstantPool();
Eric Christopher96e72c62015-01-29 23:27:36 +0000442 STI = &static_cast<const MipsSubtarget &>(mf.getSubtarget());
Reed Kotler91ae9822013-10-27 21:57:36 +0000443 DEBUG(dbgs() << "constant island machine function " << "\n");
Eric Christopher4e7d1e72014-07-18 23:41:32 +0000444 if (!STI->inMips16Mode() || !MipsSubtarget::useConstantIslands()) {
Reed Kotler91ae9822013-10-27 21:57:36 +0000445 return false;
446 }
Eric Christopher96e72c62015-01-29 23:27:36 +0000447 TII = (const Mips16InstrInfo *)STI->getInstrInfo();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000448 MFI = MF->getInfo<MipsFunctionInfo>();
Reed Kotler91ae9822013-10-27 21:57:36 +0000449 DEBUG(dbgs() << "constant island processing " << "\n");
450 //
451 // will need to make predermination if there is any constants we need to
452 // put in constant islands. TBD.
453 //
Reed Kotler0f007fc2013-11-05 08:14:14 +0000454 if (!PrescannedForConstants) prescanForConstants();
Reed Kotler91ae9822013-10-27 21:57:36 +0000455
Reed Kotler0f007fc2013-11-05 08:14:14 +0000456 HasFarJump = false;
Reed Kotler91ae9822013-10-27 21:57:36 +0000457 // This pass invalidates liveness information when it splits basic blocks.
458 MF->getRegInfo().invalidateLiveness();
459
460 // Renumber all of the machine basic blocks in the function, guaranteeing that
461 // the numbers agree with the position of the block in the function.
462 MF->RenumberBlocks();
463
Reed Kotler0f007fc2013-11-05 08:14:14 +0000464 bool MadeChange = false;
465
Reed Kotler91ae9822013-10-27 21:57:36 +0000466 // Perform the initial placement of the constant pool entries. To start with,
467 // we put them all at the end of the function.
468 std::vector<MachineInstr*> CPEMIs;
469 if (!MCP->isEmpty())
470 doInitialPlacement(CPEMIs);
471
Reed Kotler0f007fc2013-11-05 08:14:14 +0000472 /// The next UID to take is the first unused one.
473 initPICLabelUId(CPEMIs.size());
474
475 // Do the initial scan of the function, building up information about the
476 // sizes of each block, the location of all the water, and finding all of the
477 // constant pool users.
478 initializeFunctionInfo(CPEMIs);
479 CPEMIs.clear();
480 DEBUG(dumpBBs());
481
482 /// Remove dead constant pool entries.
483 MadeChange |= removeUnusedCPEntries();
484
485 // Iteratively place constant pool entries and fix up branches until there
486 // is no change.
487 unsigned NoCPIters = 0, NoBRIters = 0;
488 (void)NoBRIters;
489 while (true) {
490 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
491 bool CPChange = false;
492 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
493 CPChange |= handleConstantPoolUser(i);
494 if (CPChange && ++NoCPIters > 30)
495 report_fatal_error("Constant Island pass failed to converge!");
496 DEBUG(dumpBBs());
497
498 // Clear NewWaterList now. If we split a block for branches, it should
499 // appear as "new water" for the next iteration of constant pool placement.
500 NewWaterList.clear();
501
502 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
503 bool BRChange = false;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000504 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
505 BRChange |= fixupImmediateBr(ImmBranches[i]);
506 if (BRChange && ++NoBRIters > 30)
507 report_fatal_error("Branch Fix Up pass failed to converge!");
508 DEBUG(dumpBBs());
Reed Kotler0f007fc2013-11-05 08:14:14 +0000509 if (!CPChange && !BRChange)
510 break;
511 MadeChange = true;
512 }
513
514 DEBUG(dbgs() << '\n'; dumpBBs());
515
516 BBInfo.clear();
517 WaterList.clear();
518 CPUsers.clear();
519 CPEntries.clear();
520 ImmBranches.clear();
521 return MadeChange;
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000522}
523
Reed Kotler91ae9822013-10-27 21:57:36 +0000524/// doInitialPlacement - Perform the initial placement of the constant pool
525/// entries. To start with, we put them all at the end of the function.
526void
527MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
528 // Create the basic block to hold the CPE's.
529 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
530 MF->push_back(BB);
531
532
533 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
534 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
535
536 // Mark the basic block as required by the const-pool.
537 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
538 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
539
540 // The function needs to be as aligned as the basic blocks. The linker may
541 // move functions around based on their alignment.
542 MF->ensureAlignment(BB->getAlignment());
543
544 // Order the entries in BB by descending alignment. That ensures correct
545 // alignment of all entries as long as BB is sufficiently aligned. Keep
546 // track of the insertion point for each alignment. We are going to bucket
547 // sort the entries as they are created.
548 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
549
550 // Add all of the constants from the constant pool to the end block, use an
551 // identity mapping of CPI's to CPE's.
552 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
553
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000554 const DataLayout &TD = MF->getDataLayout();
Reed Kotler91ae9822013-10-27 21:57:36 +0000555 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
556 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
557 assert(Size >= 4 && "Too small constant pool entry");
558 unsigned Align = CPs[i].getAlignment();
559 assert(isPowerOf2_32(Align) && "Invalid alignment");
560 // Verify that all constant pool entries are a multiple of their alignment.
561 // If not, we would have to pad them out so that instructions stay aligned.
562 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
563
564 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
565 unsigned LogAlign = Log2_32(Align);
566 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
567
568 MachineInstr *CPEMI =
569 BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
570 .addImm(i).addConstantPoolIndex(i).addImm(Size);
571
572 CPEMIs.push_back(CPEMI);
573
574 // Ensure that future entries with higher alignment get inserted before
575 // CPEMI. This is bucket sort with iterators.
576 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
577 if (InsPoint[a] == InsAt)
578 InsPoint[a] = CPEMI;
579 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000580 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Reed Kotler91ae9822013-10-27 21:57:36 +0000581 ++NumCPEs;
582 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
583 << Size << ", align = " << Align <<'\n');
584 }
585 DEBUG(BB->dump());
586}
587
Reed Kotler0f007fc2013-11-05 08:14:14 +0000588/// BBHasFallthrough - Return true if the specified basic block can fallthrough
589/// into the block immediately after it.
590static bool BBHasFallthrough(MachineBasicBlock *MBB) {
591 // Get the next machine basic block in the function.
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000592 MachineFunction::iterator MBBI = MBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000593 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000594 if (std::next(MBBI) == MBB->getParent()->end())
Reed Kotler0f007fc2013-11-05 08:14:14 +0000595 return false;
596
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000597 MachineBasicBlock *NextBB = &*std::next(MBBI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000598 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
599 E = MBB->succ_end(); I != E; ++I)
600 if (*I == NextBB)
601 return true;
602
603 return false;
604}
605
606/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
607/// look up the corresponding CPEntry.
608MipsConstantIslands::CPEntry
609*MipsConstantIslands::findConstPoolEntry(unsigned CPI,
610 const MachineInstr *CPEMI) {
611 std::vector<CPEntry> &CPEs = CPEntries[CPI];
612 // Number of entries per constpool index should be small, just do a
613 // linear search.
614 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
615 if (CPEs[i].CPEMI == CPEMI)
616 return &CPEs[i];
617 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000618 return nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000619}
620
621/// getCPELogAlign - Returns the required alignment of the constant pool entry
622/// represented by CPEMI. Alignment is measured in log2(bytes) units.
623unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
624 assert(CPEMI && CPEMI->getOpcode() == Mips::CONSTPOOL_ENTRY);
625
626 // Everything is 4-byte aligned unless AlignConstantIslands is set.
627 if (!AlignConstantIslands)
628 return 2;
629
630 unsigned CPI = CPEMI->getOperand(1).getIndex();
631 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
632 unsigned Align = MCP->getConstants()[CPI].getAlignment();
633 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
634 return Log2_32(Align);
635}
636
637/// initializeFunctionInfo - Do the initial scan of the function, building up
638/// information about the sizes of each block, the location of all the water,
639/// and finding all of the constant pool users.
640void MipsConstantIslands::
641initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
642 BBInfo.clear();
643 BBInfo.resize(MF->getNumBlockIDs());
644
645 // First thing, compute the size of all basic blocks, and see if the function
646 // has any inline assembly in it. If so, we have to be conservative about
647 // alignment assumptions, as we don't know for sure the size of any
648 // instructions in the inline assembly.
649 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000650 computeBlockSize(&*I);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000651
Reed Kotler0f007fc2013-11-05 08:14:14 +0000652
653 // Compute block offsets.
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000654 adjustBBOffsetsAfter(&MF->front());
Reed Kotler0f007fc2013-11-05 08:14:14 +0000655
656 // Now go back through the instructions and build up our data structures.
657 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
658 MBBI != E; ++MBBI) {
659 MachineBasicBlock &MBB = *MBBI;
660
661 // If this block doesn't fall through into the next MBB, then this is
662 // 'water' that a constant pool island could be placed.
663 if (!BBHasFallthrough(&MBB))
664 WaterList.push_back(&MBB);
665 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
666 I != E; ++I) {
667 if (I->isDebugValue())
668 continue;
669
670 int Opc = I->getOpcode();
671 if (I->isBranch()) {
672 bool isCond = false;
673 unsigned Bits = 0;
674 unsigned Scale = 1;
675 int UOpc = Opc;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000676 switch (Opc) {
677 default:
Reed Kotler4b7afe52013-11-13 23:52:18 +0000678 continue; // Ignore other branches for now
679 case Mips::Bimm16:
680 Bits = 11;
681 Scale = 2;
682 isCond = false;
683 break;
684 case Mips::BimmX16:
685 Bits = 16;
686 Scale = 2;
687 isCond = false;
Reed Kotler0d409e22013-11-28 00:56:37 +0000688 break;
689 case Mips::BeqzRxImm16:
Reed Kotler59975c22013-12-03 23:42:51 +0000690 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000691 Bits = 8;
692 Scale = 2;
693 isCond = true;
694 break;
695 case Mips::BeqzRxImmX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000696 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000697 Bits = 16;
698 Scale = 2;
699 isCond = true;
700 break;
701 case Mips::BnezRxImm16:
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::BnezRxImmX16:
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::Bteqz16:
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::BteqzX16:
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::Btnez16:
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::BtnezX16:
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;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000737 }
738 // Record this immediate branch.
739 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
740 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Reed Kotler0f007fc2013-11-05 08:14:14 +0000741 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000742
743 if (Opc == Mips::CONSTPOOL_ENTRY)
744 continue;
745
746
747 // Scan the instructions for constant pool operands.
748 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
749 if (I->getOperand(op).isCPI()) {
750
751 // We found one. The addressing mode tells us the max displacement
752 // from the PC that this instruction permits.
753
754 // Basic size info comes from the TSFlags field.
755 unsigned Bits = 0;
756 unsigned Scale = 1;
757 bool NegOk = false;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000758 unsigned LongFormBits = 0;
759 unsigned LongFormScale = 0;
760 unsigned LongFormOpcode = 0;
761 switch (Opc) {
762 default:
763 llvm_unreachable("Unknown addressing mode for CP reference!");
764 case Mips::LwRxPcTcp16:
765 Bits = 8;
Reed Kotler3d7b33f2013-11-06 04:29:52 +0000766 Scale = 4;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000767 LongFormOpcode = Mips::LwRxPcTcpX16;
Reed Kotler43788a22014-01-16 00:47:46 +0000768 LongFormBits = 14;
Reed Kotler45c59272013-11-10 00:09:26 +0000769 LongFormScale = 1;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000770 break;
771 case Mips::LwRxPcTcpX16:
Reed Kotler43788a22014-01-16 00:47:46 +0000772 Bits = 14;
Reed Kotler3d7b33f2013-11-06 04:29:52 +0000773 Scale = 1;
774 NegOk = true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000775 break;
776 }
777 // Remember that this is a user of a CP entry.
778 unsigned CPI = I->getOperand(op).getIndex();
779 MachineInstr *CPEMI = CPEMIs[CPI];
780 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
781 unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
782 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000783 LongFormMaxOffs, LongFormOpcode));
Reed Kotler0f007fc2013-11-05 08:14:14 +0000784
785 // Increment corresponding CPEntry reference count.
786 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
787 assert(CPE && "Cannot find a corresponding CPEntry!");
788 CPE->RefCount++;
789
790 // Instructions can only use one CP entry, don't bother scanning the
791 // rest of the operands.
792 break;
793
794 }
795
796 }
797 }
798
799}
800
801/// computeBlockSize - Compute the size and some alignment information for MBB.
802/// This function updates BBInfo directly.
803void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
804 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
805 BBI.Size = 0;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000806
807 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
808 ++I)
809 BBI.Size += TII->GetInstSizeInBytes(I);
810
811}
812
813/// getOffsetOf - Return the current offset of the specified machine instruction
814/// from the start of the function. This offset changes as stuff is moved
815/// around inside the function.
816unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
817 MachineBasicBlock *MBB = MI->getParent();
818
819 // The offset is composed of two things: the sum of the sizes of all MBB's
820 // before this instruction's block, and the offset from the start of the block
821 // it is in.
822 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
823
824 // Sum instructions before MI in MBB.
825 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
826 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
827 Offset += TII->GetInstSizeInBytes(I);
828 }
829 return Offset;
830}
831
832/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
833/// ID.
834static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
835 const MachineBasicBlock *RHS) {
836 return LHS->getNumber() < RHS->getNumber();
837}
838
839/// updateForInsertedWaterBlock - When a block is newly inserted into the
840/// machine function, it upsets all of the block numbers. Renumber the blocks
841/// and update the arrays that parallel this numbering.
842void MipsConstantIslands::updateForInsertedWaterBlock
843 (MachineBasicBlock *NewBB) {
844 // Renumber the MBB's to keep them consecutive.
845 NewBB->getParent()->RenumberBlocks(NewBB);
846
847 // Insert an entry into BBInfo to align it properly with the (newly
848 // renumbered) block numbers.
849 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
850
851 // Next, update WaterList. Specifically, we need to add NewMBB as having
852 // available water after it.
853 water_iterator IP =
854 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
855 CompareMBBNumbers);
856 WaterList.insert(IP, NewBB);
857}
858
Reed Kotler0f007fc2013-11-05 08:14:14 +0000859unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
Reed Kotler0eb87392013-11-05 21:39:57 +0000860 return getOffsetOf(U.MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000861}
862
863/// Split the basic block containing MI into two blocks, which are joined by
864/// an unconditional branch. Update data structures and renumber blocks to
865/// account for this change and returns the newly created block.
866MachineBasicBlock *MipsConstantIslands::splitBlockBeforeInstr
867 (MachineInstr *MI) {
868 MachineBasicBlock *OrigBB = MI->getParent();
869
870 // Create a new MBB for the code after the OrigBB.
871 MachineBasicBlock *NewBB =
872 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000873 MachineFunction::iterator MBBI = ++OrigBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000874 MF->insert(MBBI, NewBB);
875
876 // Splice the instructions starting with MI over to NewBB.
877 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
878
879 // Add an unconditional branch from OrigBB to NewBB.
880 // Note the new unconditional branch is not being recorded.
881 // There doesn't seem to be meaningful DebugInfo available; this doesn't
882 // correspond to anything in the source.
Reed Kotlerf0e69682013-11-12 02:27:12 +0000883 BuildMI(OrigBB, DebugLoc(), TII->get(Mips::Bimm16)).addMBB(NewBB);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000884 ++NumSplit;
885
886 // Update the CFG. All succs of OrigBB are now succs of NewBB.
887 NewBB->transferSuccessors(OrigBB);
888
889 // OrigBB branches to NewBB.
890 OrigBB->addSuccessor(NewBB);
891
892 // Update internal data structures to account for the newly inserted MBB.
893 // This is almost the same as updateForInsertedWaterBlock, except that
894 // the Water goes after OrigBB, not NewBB.
895 MF->RenumberBlocks(NewBB);
896
897 // Insert an entry into BBInfo to align it properly with the (newly
898 // renumbered) block numbers.
899 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
900
901 // Next, update WaterList. Specifically, we need to add OrigMBB as having
902 // available water after it (but not if it's already there, which happens
903 // when splitting before a conditional branch that is followed by an
904 // unconditional branch - in that case we want to insert NewBB).
905 water_iterator IP =
906 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
907 CompareMBBNumbers);
908 MachineBasicBlock* WaterBB = *IP;
909 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000910 WaterList.insert(std::next(IP), NewBB);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000911 else
912 WaterList.insert(IP, OrigBB);
913 NewWaterList.insert(OrigBB);
914
915 // Figure out how large the OrigBB is. As the first half of the original
916 // block, it cannot contain a tablejump. The size includes
917 // the new jump we added. (It should be possible to do this without
918 // recounting everything, but it's very confusing, and this is rarely
919 // executed.)
920 computeBlockSize(OrigBB);
921
922 // Figure out how large the NewMBB is. As the second half of the original
923 // block, it may contain a tablejump.
924 computeBlockSize(NewBB);
925
926 // All BBOffsets following these blocks must be modified.
927 adjustBBOffsetsAfter(OrigBB);
928
929 return NewBB;
930}
931
932
933
934/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
935/// reference) is within MaxDisp of TrialOffset (a proposed location of a
936/// constant pool entry).
Reed Kotler0f007fc2013-11-05 08:14:14 +0000937bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
938 unsigned TrialOffset, unsigned MaxDisp,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000939 bool NegativeOK) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000940 if (UserOffset <= TrialOffset) {
941 // User before the Trial.
942 if (TrialOffset - UserOffset <= MaxDisp)
943 return true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000944 } else if (NegativeOK) {
945 if (UserOffset - TrialOffset <= MaxDisp)
946 return true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000947 }
948 return false;
949}
950
951/// isWaterInRange - Returns true if a CPE placed after the specified
952/// Water (a basic block) will be in range for the specific MI.
953///
954/// Compute how much the function will grow by inserting a CPE after Water.
955bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
956 MachineBasicBlock* Water, CPUser &U,
957 unsigned &Growth) {
958 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
959 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
960 unsigned NextBlockOffset, NextBlockAlignment;
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000961 MachineFunction::const_iterator NextBlock = ++Water->getIterator();
962 if (NextBlock == MF->end()) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000963 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
964 NextBlockAlignment = 0;
965 } else {
966 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
967 NextBlockAlignment = NextBlock->getAlignment();
968 }
969 unsigned Size = U.CPEMI->getOperand(2).getImm();
970 unsigned CPEEnd = CPEOffset + Size;
971
972 // The CPE may be able to hide in the alignment padding before the next
973 // block. It may also cause more padding to be required if it is more aligned
974 // that the next block.
975 if (CPEEnd > NextBlockOffset) {
976 Growth = CPEEnd - NextBlockOffset;
977 // Compute the padding that would go at the end of the CPE to align the next
978 // block.
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +0000979 Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000980
981 // If the CPE is to be inserted before the instruction, that will raise
982 // the offset of the instruction. Also account for unknown alignment padding
983 // in blocks between CPE and the user.
984 if (CPEOffset < UserOffset)
Reed Kotler7ded5b62013-11-05 23:36:58 +0000985 UserOffset += Growth;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000986 } else
987 // CPE fits in existing padding.
988 Growth = 0;
989
990 return isOffsetInRange(UserOffset, CPEOffset, U);
991}
992
993/// isCPEntryInRange - Returns true if the distance between specific MI and
994/// specific ConstPool entry instruction can fit in MI's displacement field.
995bool MipsConstantIslands::isCPEntryInRange
996 (MachineInstr *MI, unsigned UserOffset,
997 MachineInstr *CPEMI, unsigned MaxDisp,
998 bool NegOk, bool DoDump) {
999 unsigned CPEOffset = getOffsetOf(CPEMI);
1000
1001 if (DoDump) {
1002 DEBUG({
1003 unsigned Block = MI->getParent()->getNumber();
1004 const BasicBlockInfo &BBI = BBInfo[Block];
1005 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1006 << " max delta=" << MaxDisp
1007 << format(" insn address=%#x", UserOffset)
1008 << " in BB#" << Block << ": "
1009 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1010 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1011 int(CPEOffset-UserOffset));
1012 });
1013 }
1014
1015 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1016}
1017
1018#ifndef NDEBUG
1019/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1020/// unconditionally branches to its only successor.
1021static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1022 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1023 return false;
1024 MachineBasicBlock *Succ = *MBB->succ_begin();
1025 MachineBasicBlock *Pred = *MBB->pred_begin();
1026 MachineInstr *PredMI = &Pred->back();
Reed Kotlerf0e69682013-11-12 02:27:12 +00001027 if (PredMI->getOpcode() == Mips::Bimm16)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001028 return PredMI->getOperand(0).getMBB() == Succ;
1029 return false;
1030}
1031#endif
1032
1033void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1034 unsigned BBNum = BB->getNumber();
1035 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1036 // Get the offset and known bits at the end of the layout predecessor.
1037 // Include the alignment of the current block.
Reed Kotler7ded5b62013-11-05 23:36:58 +00001038 unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001039 BBInfo[i].Offset = Offset;
1040 }
1041}
1042
1043/// decrementCPEReferenceCount - find the constant pool entry with index CPI
1044/// and instruction CPEMI, and decrement its refcount. If the refcount
1045/// becomes 0 remove the entry and instruction. Returns true if we removed
1046/// the entry, false if we didn't.
1047
1048bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1049 MachineInstr *CPEMI) {
1050 // Find the old entry. Eliminate it if it is no longer used.
1051 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1052 assert(CPE && "Unexpected!");
1053 if (--CPE->RefCount == 0) {
1054 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001055 CPE->CPEMI = nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001056 --NumCPEs;
1057 return true;
1058 }
1059 return false;
1060}
1061
1062/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1063/// if not, see if an in-range clone of the CPE is in range, and if so,
1064/// change the data structures so the user references the clone. Returns:
1065/// 0 = no existing entry found
1066/// 1 = entry found, and there were no code insertions or deletions
1067/// 2 = entry found, and there were code insertions or deletions
1068int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1069{
1070 MachineInstr *UserMI = U.MI;
1071 MachineInstr *CPEMI = U.CPEMI;
1072
1073 // Check to see if the CPE is already in-range.
1074 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1075 true)) {
1076 DEBUG(dbgs() << "In range\n");
1077 return 1;
1078 }
1079
1080 // No. Look for previously created clones of the CPE that are in range.
1081 unsigned CPI = CPEMI->getOperand(1).getIndex();
1082 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1083 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1084 // We already tried this one
1085 if (CPEs[i].CPEMI == CPEMI)
1086 continue;
1087 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001088 if (CPEs[i].CPEMI == nullptr)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001089 continue;
1090 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1091 U.NegOk)) {
1092 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1093 << CPEs[i].CPI << "\n");
1094 // Point the CPUser node to the replacement
1095 U.CPEMI = CPEs[i].CPEMI;
1096 // Change the CPI in the instruction operand to refer to the clone.
1097 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1098 if (UserMI->getOperand(j).isCPI()) {
1099 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1100 break;
1101 }
1102 // Adjust the refcount of the clone...
1103 CPEs[i].RefCount++;
1104 // ...and the original. If we didn't remove the old entry, none of the
1105 // addresses changed, so we don't need another pass.
1106 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1107 }
1108 }
1109 return 0;
1110}
1111
1112/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1113/// This version checks if the longer form of the instruction can be used to
1114/// to satisfy things.
1115/// if not, see if an in-range clone of the CPE is in range, and if so,
1116/// change the data structures so the user references the clone. Returns:
1117/// 0 = no existing entry found
1118/// 1 = entry found, and there were no code insertions or deletions
1119/// 2 = entry found, and there were code insertions or deletions
1120int MipsConstantIslands::findLongFormInRangeCPEntry
1121 (CPUser& U, unsigned UserOffset)
1122{
1123 MachineInstr *UserMI = U.MI;
1124 MachineInstr *CPEMI = U.CPEMI;
1125
1126 // Check to see if the CPE is already in-range.
1127 if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
1128 U.getLongFormMaxDisp(), U.NegOk,
1129 true)) {
1130 DEBUG(dbgs() << "In range\n");
1131 UserMI->setDesc(TII->get(U.getLongFormOpcode()));
Reed Kotler45c59272013-11-10 00:09:26 +00001132 U.setMaxDisp(U.getLongFormMaxDisp());
Reed Kotler0f007fc2013-11-05 08:14:14 +00001133 return 2; // instruction is longer length now
1134 }
1135
1136 // No. Look for previously created clones of the CPE that are in range.
1137 unsigned CPI = CPEMI->getOperand(1).getIndex();
1138 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1139 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1140 // We already tried this one
1141 if (CPEs[i].CPEMI == CPEMI)
1142 continue;
1143 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001144 if (CPEs[i].CPEMI == nullptr)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001145 continue;
1146 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
1147 U.getLongFormMaxDisp(), U.NegOk)) {
1148 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1149 << CPEs[i].CPI << "\n");
1150 // Point the CPUser node to the replacement
1151 U.CPEMI = CPEs[i].CPEMI;
1152 // Change the CPI in the instruction operand to refer to the clone.
1153 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1154 if (UserMI->getOperand(j).isCPI()) {
1155 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1156 break;
1157 }
1158 // Adjust the refcount of the clone...
1159 CPEs[i].RefCount++;
1160 // ...and the original. If we didn't remove the old entry, none of the
1161 // addresses changed, so we don't need another pass.
1162 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1163 }
1164 }
1165 return 0;
1166}
1167
1168/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1169/// the specific unconditional branch instruction.
1170static inline unsigned getUnconditionalBrDisp(int Opc) {
1171 switch (Opc) {
Reed Kotlerf0e69682013-11-12 02:27:12 +00001172 case Mips::Bimm16:
1173 return ((1<<10)-1)*2;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001174 case Mips::BimmX16:
1175 return ((1<<16)-1)*2;
1176 default:
1177 break;
1178 }
1179 return ((1<<16)-1)*2;
1180}
1181
1182/// findAvailableWater - Look for an existing entry in the WaterList in which
1183/// we can place the CPE referenced from U so it's within range of U's MI.
1184/// Returns true if found, false if not. If it returns true, WaterIter
Reed Kotler4d0313d2013-11-05 12:04:37 +00001185/// is set to the WaterList entry.
1186/// To ensure that this pass
Reed Kotler0f007fc2013-11-05 08:14:14 +00001187/// terminates, the CPE location for a particular CPUser is only allowed to
1188/// move to a lower address, so search backward from the end of the list and
1189/// prefer the first water that is in range.
1190bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1191 water_iterator &WaterIter) {
1192 if (WaterList.empty())
1193 return false;
1194
1195 unsigned BestGrowth = ~0u;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001196 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001197 --IP) {
1198 MachineBasicBlock* WaterBB = *IP;
1199 // Check if water is in range and is either at a lower address than the
1200 // current "high water mark" or a new water block that was created since
1201 // the previous iteration by inserting an unconditional branch. In the
1202 // latter case, we want to allow resetting the high water mark back to
1203 // this new water since we haven't seen it before. Inserting branches
1204 // should be relatively uncommon and when it does happen, we want to be
1205 // sure to take advantage of it for all the CPEs near that block, so that
1206 // we don't insert more branches than necessary.
1207 unsigned Growth;
1208 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1209 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1210 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1211 // This is the least amount of required padding seen so far.
1212 BestGrowth = Growth;
1213 WaterIter = IP;
1214 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1215 << " Growth=" << Growth << '\n');
1216
1217 // Keep looking unless it is perfect.
1218 if (BestGrowth == 0)
1219 return true;
1220 }
1221 if (IP == B)
1222 break;
1223 }
1224 return BestGrowth != ~0u;
1225}
1226
1227/// createNewWater - No existing WaterList entry will work for
1228/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1229/// block is used if in range, and the conditional branch munged so control
1230/// flow is correct. Otherwise the block is split to create a hole with an
1231/// unconditional branch around it. In either case NewMBB is set to a
1232/// block following which the new island can be inserted (the WaterList
1233/// is not adjusted).
1234void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1235 unsigned UserOffset,
1236 MachineBasicBlock *&NewMBB) {
1237 CPUser &U = CPUsers[CPUserIndex];
1238 MachineInstr *UserMI = U.MI;
1239 MachineInstr *CPEMI = U.CPEMI;
1240 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1241 MachineBasicBlock *UserMBB = UserMI->getParent();
1242 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1243
1244 // If the block does not end in an unconditional branch already, and if the
Reed Kotler4d0313d2013-11-05 12:04:37 +00001245 // end of the block is within range, make new water there.
Reed Kotler0f007fc2013-11-05 08:14:14 +00001246 if (BBHasFallthrough(UserMBB)) {
1247 // Size of branch to insert.
1248 unsigned Delta = 2;
1249 // Compute the offset where the CPE will begin.
1250 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1251
1252 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1253 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1254 << format(", expected CPE offset %#x\n", CPEOffset));
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001255 NewMBB = &*++UserMBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001256 // Add an unconditional branch from UserMBB to fallthrough block. Record
1257 // it for branch lengthening; this new branch will not get out of range,
1258 // but if the preceding conditional branch is out of range, the targets
1259 // will be exchanged, and the altered branch may be out of range, so the
1260 // machinery has to know about it.
Reed Kotlerf0e69682013-11-12 02:27:12 +00001261 int UncondBr = Mips::Bimm16;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001262 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1263 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1264 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1265 MaxDisp, false, UncondBr));
1266 BBInfo[UserMBB->getNumber()].Size += Delta;
1267 adjustBBOffsetsAfter(UserMBB);
1268 return;
1269 }
1270 }
1271
Reed Kotler4d0313d2013-11-05 12:04:37 +00001272 // What a big block. Find a place within the block to split it.
Reed Kotler0f007fc2013-11-05 08:14:14 +00001273
1274 // Try to split the block so it's fully aligned. Compute the latest split
1275 // point where we can add a 4-byte branch instruction, and then align to
1276 // LogAlign which is the largest possible alignment in the function.
1277 unsigned LogAlign = MF->getAlignment();
1278 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
Reed Kotler7ded5b62013-11-05 23:36:58 +00001279 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001280 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1281 BaseInsertOffset));
1282
1283 // The 4 in the following is for the unconditional branch we'll be inserting
Reed Kotler4d0313d2013-11-05 12:04:37 +00001284 // Alignment of the island is handled
Reed Kotler0f007fc2013-11-05 08:14:14 +00001285 // inside isOffsetInRange.
1286 BaseInsertOffset -= 4;
1287
1288 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
Reed Kotler7ded5b62013-11-05 23:36:58 +00001289 << " la=" << LogAlign << '\n');
Reed Kotler0f007fc2013-11-05 08:14:14 +00001290
1291 // This could point off the end of the block if we've already got constant
1292 // pool entries following this block; only the last one is in the water list.
1293 // Back past any possible branches (allow for a conditional and a maximally
1294 // long unconditional).
1295 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Reed Kotler7ded5b62013-11-05 23:36:58 +00001296 BaseInsertOffset = UserBBI.postOffset() - 8;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001297 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1298 }
Reed Kotler7ded5b62013-11-05 23:36:58 +00001299 unsigned EndInsertOffset = BaseInsertOffset + 4 +
Reed Kotler0f007fc2013-11-05 08:14:14 +00001300 CPEMI->getOperand(2).getImm();
1301 MachineBasicBlock::iterator MI = UserMI;
1302 ++MI;
1303 unsigned CPUIndex = CPUserIndex+1;
1304 unsigned NumCPUsers = CPUsers.size();
1305 //MachineInstr *LastIT = 0;
1306 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1307 Offset < BaseInsertOffset;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001308 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001309 assert(MI != UserMBB->end() && "Fell off end of block");
1310 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1311 CPUser &U = CPUsers[CPUIndex];
1312 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1313 // Shift intertion point by one unit of alignment so it is within reach.
1314 BaseInsertOffset -= 1u << LogAlign;
1315 EndInsertOffset -= 1u << LogAlign;
1316 }
1317 // This is overly conservative, as we don't account for CPEMIs being
1318 // reused within the block, but it doesn't matter much. Also assume CPEs
1319 // are added in order with alignment padding. We may eventually be able
1320 // to pack the aligned CPEs better.
1321 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1322 CPUIndex++;
1323 }
1324 }
1325
1326 --MI;
1327 NewMBB = splitBlockBeforeInstr(MI);
1328}
1329
1330/// handleConstantPoolUser - Analyze the specified user, checking to see if it
1331/// is out-of-range. If so, pick up the constant pool value and move it some
1332/// place in-range. Return true if we changed any addresses (thus must run
1333/// another pass of branch lengthening), false otherwise.
1334bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1335 CPUser &U = CPUsers[CPUserIndex];
1336 MachineInstr *UserMI = U.MI;
1337 MachineInstr *CPEMI = U.CPEMI;
1338 unsigned CPI = CPEMI->getOperand(1).getIndex();
1339 unsigned Size = CPEMI->getOperand(2).getImm();
1340 // Compute this only once, it's expensive.
1341 unsigned UserOffset = getUserOffset(U);
1342
1343 // See if the current entry is within range, or there is a clone of it
1344 // in range.
1345 int result = findInRangeCPEntry(U, UserOffset);
1346 if (result==1) return false;
1347 else if (result==2) return true;
1348
1349
1350 // Look for water where we can place this CPE.
1351 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1352 MachineBasicBlock *NewMBB;
1353 water_iterator IP;
1354 if (findAvailableWater(U, UserOffset, IP)) {
1355 DEBUG(dbgs() << "Found water in range\n");
1356 MachineBasicBlock *WaterBB = *IP;
1357
1358 // If the original WaterList entry was "new water" on this iteration,
1359 // propagate that to the new island. This is just keeping NewWaterList
1360 // updated to match the WaterList, which will be updated below.
1361 if (NewWaterList.erase(WaterBB))
1362 NewWaterList.insert(NewIsland);
1363
1364 // The new CPE goes before the following block (NewMBB).
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001365 NewMBB = &*++WaterBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001366 } else {
1367 // No water found.
1368 // we first see if a longer form of the instrucion could have reached
1369 // the constant. in that case we won't bother to split
Reed Kotler45c59272013-11-10 00:09:26 +00001370 if (!NoLoadRelaxation) {
1371 result = findLongFormInRangeCPEntry(U, UserOffset);
1372 if (result != 0) return true;
1373 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001374 DEBUG(dbgs() << "No water found\n");
1375 createNewWater(CPUserIndex, UserOffset, NewMBB);
1376
1377 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1378 // called while handling branches so that the water will be seen on the
1379 // next iteration for constant pools, but in this context, we don't want
1380 // it. Check for this so it will be removed from the WaterList.
1381 // Also remove any entry from NewWaterList.
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001382 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001383 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1384 if (IP != WaterList.end())
1385 NewWaterList.erase(WaterBB);
1386
1387 // We are adding new water. Update NewWaterList.
1388 NewWaterList.insert(NewIsland);
1389 }
1390
1391 // Remove the original WaterList entry; we want subsequent insertions in
1392 // this vicinity to go after the one we're about to insert. This
1393 // considerably reduces the number of times we have to move the same CPE
1394 // more than once and is also important to ensure the algorithm terminates.
1395 if (IP != WaterList.end())
1396 WaterList.erase(IP);
1397
1398 // Okay, we know we can put an island before NewMBB now, do it!
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001399 MF->insert(NewMBB->getIterator(), NewIsland);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001400
1401 // Update internal data structures to account for the newly inserted MBB.
1402 updateForInsertedWaterBlock(NewIsland);
1403
1404 // Decrement the old entry, and remove it if refcount becomes 0.
1405 decrementCPEReferenceCount(CPI, CPEMI);
1406
Reed Kotlerd3b28eb2013-11-24 02:53:09 +00001407 // No existing clone of this CPE is within range.
1408 // We will be generating a new clone. Get a UID for it.
1409 unsigned ID = createPICLabelUId();
1410
Reed Kotler0f007fc2013-11-05 08:14:14 +00001411 // Now that we have an island to add the CPE to, clone the original CPE and
1412 // add it to the island.
1413 U.HighWaterMark = NewIsland;
1414 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1415 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1416 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1417 ++NumCPEs;
1418
1419 // Mark the basic block as aligned as required by the const-pool entry.
1420 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1421
1422 // Increase the size of the island block to account for the new entry.
1423 BBInfo[NewIsland->getNumber()].Size += Size;
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001424 adjustBBOffsetsAfter(&*--NewIsland->getIterator());
Reed Kotler0f007fc2013-11-05 08:14:14 +00001425
1426 // Finally, change the CPI in the instruction operand to be ID.
1427 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1428 if (UserMI->getOperand(i).isCPI()) {
1429 UserMI->getOperand(i).setIndex(ID);
1430 break;
1431 }
1432
1433 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1434 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1435
1436 return true;
1437}
1438
1439/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1440/// sizes and offsets of impacted basic blocks.
1441void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1442 MachineBasicBlock *CPEBB = CPEMI->getParent();
1443 unsigned Size = CPEMI->getOperand(2).getImm();
1444 CPEMI->eraseFromParent();
1445 BBInfo[CPEBB->getNumber()].Size -= Size;
1446 // All succeeding offsets have the current size value added in, fix this.
1447 if (CPEBB->empty()) {
1448 BBInfo[CPEBB->getNumber()].Size = 0;
1449
1450 // This block no longer needs to be aligned.
1451 CPEBB->setAlignment(0);
1452 } else
1453 // Entries are sorted by descending alignment, so realign from the front.
1454 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1455
1456 adjustBBOffsetsAfter(CPEBB);
1457 // An island has only one predecessor BB and one successor BB. Check if
1458 // this BB's predecessor jumps directly to this BB's successor. This
1459 // shouldn't happen currently.
1460 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1461 // FIXME: remove the empty blocks after all the work is done?
1462}
1463
1464/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1465/// are zero.
1466bool MipsConstantIslands::removeUnusedCPEntries() {
1467 unsigned MadeChange = false;
1468 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1469 std::vector<CPEntry> &CPEs = CPEntries[i];
1470 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1471 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1472 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001473 CPEs[j].CPEMI = nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001474 MadeChange = true;
1475 }
1476 }
1477 }
1478 return MadeChange;
1479}
1480
1481/// isBBInRange - Returns true if the distance between specific MI and
1482/// specific BB can fit in MI's displacement field.
1483bool MipsConstantIslands::isBBInRange
1484 (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
1485
1486unsigned PCAdj = 4;
1487
1488 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1489 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1490
1491 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1492 << " from BB#" << MI->getParent()->getNumber()
1493 << " max delta=" << MaxDisp
1494 << " from " << getOffsetOf(MI) << " to " << DestOffset
1495 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1496
1497 if (BrOffset <= DestOffset) {
1498 // Branch before the Dest.
1499 if (DestOffset-BrOffset <= MaxDisp)
1500 return true;
1501 } else {
1502 if (BrOffset-DestOffset <= MaxDisp)
1503 return true;
1504 }
1505 return false;
1506}
1507
1508/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1509/// away to fit in its displacement field.
1510bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1511 MachineInstr *MI = Br.MI;
Reed Kotler0d409e22013-11-28 00:56:37 +00001512 unsigned TargetOperand = branchTargetOperand(MI);
1513 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001514
1515 // Check to see if the DestBB is already in-range.
1516 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1517 return false;
1518
1519 if (!Br.isCond)
1520 return fixupUnconditionalBr(Br);
1521 return fixupConditionalBr(Br);
1522}
1523
1524/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1525/// too far away to fit in its displacement field. If the LR register has been
1526/// spilled in the epilogue, then we can use BL to implement a far jump.
1527/// Otherwise, add an intermediate branch instruction to a branch.
1528bool
1529MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1530 MachineInstr *MI = Br.MI;
1531 MachineBasicBlock *MBB = MI->getParent();
Reed Kotler2fc05be2013-11-21 05:13:23 +00001532 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001533 // Use BL to implement far jump.
Reed Kotler2fc05be2013-11-21 05:13:23 +00001534 unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2;
1535 if (isBBInRange(MI, DestBB, BimmX16MaxDisp)) {
1536 Br.MaxDisp = BimmX16MaxDisp;
1537 MI->setDesc(TII->get(Mips::BimmX16));
1538 }
1539 else {
1540 // need to give the math a more careful look here
1541 // this is really a segment address and not
1542 // a PC relative address. FIXME. But I think that
1543 // just reducing the bits by 1 as I've done is correct.
1544 // The basic block we are branching too much be longword aligned.
1545 // we know that RA is saved because we always save it right now.
1546 // this requirement will be relaxed later but we also have an alternate
1547 // way to implement this that I will implement that does not need jal.
1548 // We should have a way to back out this alignment restriction if we "can" later.
1549 // but it is not harmful.
1550 //
1551 DestBB->setAlignment(2);
1552 Br.MaxDisp = ((1<<24)-1) * 2;
Reed Kotlerad450f22013-11-29 22:32:56 +00001553 MI->setDesc(TII->get(Mips::JalB16));
Reed Kotler2fc05be2013-11-21 05:13:23 +00001554 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001555 BBInfo[MBB->getNumber()].Size += 2;
1556 adjustBBOffsetsAfter(MBB);
1557 HasFarJump = true;
1558 ++NumUBrFixed;
1559
1560 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1561
1562 return true;
1563}
1564
Reed Kotler0d409e22013-11-28 00:56:37 +00001565
Reed Kotler0f007fc2013-11-05 08:14:14 +00001566/// fixupConditionalBr - Fix up a conditional branch whose destination is too
1567/// far away to fit in its displacement field. It is converted to an inverse
1568/// conditional branch + an unconditional branch to the destination.
1569bool
1570MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1571 MachineInstr *MI = Br.MI;
Reed Kotler0d409e22013-11-28 00:56:37 +00001572 unsigned TargetOperand = branchTargetOperand(MI);
1573 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1574 unsigned Opcode = MI->getOpcode();
1575 unsigned LongFormOpcode = longformBranchOpcode(Opcode);
1576 unsigned LongFormMaxOff = branchMaxOffsets(LongFormOpcode);
1577
1578 // Check to see if the DestBB is already in-range.
1579 if (isBBInRange(MI, DestBB, LongFormMaxOff)) {
1580 Br.MaxDisp = LongFormMaxOff;
1581 MI->setDesc(TII->get(LongFormOpcode));
1582 return true;
1583 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001584
1585 // Add an unconditional branch to the destination and invert the branch
1586 // condition to jump over it:
Reed Kotlerad450f22013-11-29 22:32:56 +00001587 // bteqz L1
Reed Kotler0f007fc2013-11-05 08:14:14 +00001588 // =>
Reed Kotlerad450f22013-11-29 22:32:56 +00001589 // bnez L2
Reed Kotler0f007fc2013-11-05 08:14:14 +00001590 // b L1
1591 // L2:
Reed Kotler0f007fc2013-11-05 08:14:14 +00001592
1593 // If the branch is at the end of its MBB and that has a fall-through block,
1594 // direct the updated conditional branch to the fall-through block. Otherwise,
1595 // split the MBB before the next instruction.
1596 MachineBasicBlock *MBB = MI->getParent();
1597 MachineInstr *BMI = &MBB->back();
1598 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Reed Kotler47f3c64a2013-12-19 00:43:08 +00001599 unsigned OppositeBranchOpcode = TII->getOppositeBranchOpc(Opcode);
Reed Kotlerad450f22013-11-29 22:32:56 +00001600
Reed Kotler0f007fc2013-11-05 08:14:14 +00001601 ++NumCBrFixed;
1602 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001603 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Daniel Sandersf9d8b8c2016-05-06 13:23:51 +00001604 BMI->isUnconditionalBranch()) {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001605 // Last MI in the BB is an unconditional branch. Can we simply invert the
1606 // condition and swap destinations:
Reed Kotlerad450f22013-11-29 22:32:56 +00001607 // beqz L1
Reed Kotler0f007fc2013-11-05 08:14:14 +00001608 // b L2
1609 // =>
Reed Kotlerad450f22013-11-29 22:32:56 +00001610 // bnez L2
Reed Kotler0f007fc2013-11-05 08:14:14 +00001611 // b L1
Reed Kotlerad450f22013-11-29 22:32:56 +00001612 unsigned BMITargetOperand = branchTargetOperand(BMI);
1613 MachineBasicBlock *NewDest =
1614 BMI->getOperand(BMITargetOperand).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001615 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1616 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1617 << *BMI);
Reed Kotler59975c22013-12-03 23:42:51 +00001618 MI->setDesc(TII->get(OppositeBranchOpcode));
Reed Kotlerad450f22013-11-29 22:32:56 +00001619 BMI->getOperand(BMITargetOperand).setMBB(DestBB);
1620 MI->getOperand(TargetOperand).setMBB(NewDest);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001621 return true;
1622 }
1623 }
1624 }
1625
Reed Kotlerad450f22013-11-29 22:32:56 +00001626
Reed Kotler0f007fc2013-11-05 08:14:14 +00001627 if (NeedSplit) {
1628 splitBlockBeforeInstr(MI);
1629 // No need for the branch to the next block. We're adding an unconditional
1630 // branch to the destination.
1631 int delta = TII->GetInstSizeInBytes(&MBB->back());
1632 BBInfo[MBB->getNumber()].Size -= delta;
1633 MBB->back().eraseFromParent();
1634 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1635 }
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001636 MachineBasicBlock *NextBB = &*++MBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001637
1638 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1639 << " also invert condition and change dest. to BB#"
1640 << NextBB->getNumber() << "\n");
1641
1642 // Insert a new conditional branch and a new unconditional branch.
1643 // Also update the ImmBranch as well as adding a new entry for the new branch.
Reed Kotler59975c22013-12-03 23:42:51 +00001644 if (MI->getNumExplicitOperands() == 2) {
1645 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1646 .addReg(MI->getOperand(0).getReg())
1647 .addMBB(NextBB);
Reed Kotler47f3c64a2013-12-19 00:43:08 +00001648 } else {
1649 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1650 .addMBB(NextBB);
Reed Kotler59975c22013-12-03 23:42:51 +00001651 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001652 Br.MI = &MBB->back();
1653 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1654 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1655 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1656 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1657 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1658
1659 // Remove the old conditional branch. It may or may not still be in MBB.
1660 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1661 MI->eraseFromParent();
1662 adjustBBOffsetsAfter(MBB);
1663 return true;
1664}
1665
Reed Kotler91ae9822013-10-27 21:57:36 +00001666
1667void MipsConstantIslands::prescanForConstants() {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001668 unsigned J = 0;
1669 (void)J;
Reed Kotler91ae9822013-10-27 21:57:36 +00001670 for (MachineFunction::iterator B =
1671 MF->begin(), E = MF->end(); B != E; ++B) {
1672 for (MachineBasicBlock::instr_iterator I =
1673 B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
1674 switch(I->getDesc().getOpcode()) {
1675 case Mips::LwConstant32: {
Reed Kotlera787aa22013-11-24 06:18:50 +00001676 PrescannedForConstants = true;
Reed Kotler91ae9822013-10-27 21:57:36 +00001677 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1678 J = I->getNumOperands();
1679 DEBUG(dbgs() << "num operands " << J << "\n");
1680 MachineOperand& Literal = I->getOperand(1);
1681 if (Literal.isImm()) {
1682 int64_t V = Literal.getImm();
1683 DEBUG(dbgs() << "literal " << V << "\n");
1684 Type *Int32Ty =
1685 Type::getInt32Ty(MF->getFunction()->getContext());
1686 const Constant *C = ConstantInt::get(Int32Ty, V);
1687 unsigned index = MCP->getConstantPoolIndex(C, 4);
1688 I->getOperand(2).ChangeToImmediate(index);
1689 DEBUG(dbgs() << "constant island constant " << *I << "\n");
Reed Kotler0f007fc2013-11-05 08:14:14 +00001690 I->setDesc(TII->get(Mips::LwRxPcTcp16));
Reed Kotler91ae9822013-10-27 21:57:36 +00001691 I->RemoveOperand(1);
1692 I->RemoveOperand(1);
1693 I->addOperand(MachineOperand::CreateCPI(index, 0));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001694 I->addOperand(MachineOperand::CreateImm(4));
Reed Kotler91ae9822013-10-27 21:57:36 +00001695 }
1696 break;
1697 }
1698 default:
1699 break;
1700 }
1701 }
1702 }
1703}