blob: f40e53a34d825b2d1d23de27ba1e113df57e5dcc [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;
347 unsigned ABI;
348 const MipsSubtarget *STI;
Reed Kotler5c8ae092013-11-13 04:37:52 +0000349 const Mips16InstrInfo *TII;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000350 MipsFunctionInfo *MFI;
351 MachineFunction *MF;
352 MachineConstantPool *MCP;
353
354 unsigned PICLabelUId;
355 bool PrescannedForConstants;
356
357 void initPICLabelUId(unsigned UId) {
358 PICLabelUId = UId;
359 }
360
361
362 unsigned createPICLabelUId() {
363 return PICLabelUId++;
364 }
365
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000366 public:
367 static char ID;
368 MipsConstantIslands(TargetMachine &tm)
Eric Christopher4e7d1e72014-07-18 23:41:32 +0000369 : MachineFunctionPass(ID), TM(tm),
370 IsPIC(TM.getRelocationModel() == Reloc::PIC_),
371 ABI(TM.getSubtarget<MipsSubtarget>().getTargetABI()), STI(nullptr),
372 MF(nullptr), MCP(nullptr), PrescannedForConstants(false) {}
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000373
Craig Topper56c590a2014-04-29 07:58:02 +0000374 const char *getPassName() const override {
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000375 return "Mips Constant Islands";
376 }
377
Craig Topper56c590a2014-04-29 07:58:02 +0000378 bool runOnMachineFunction(MachineFunction &F) override;
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000379
Reed Kotler91ae9822013-10-27 21:57:36 +0000380 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000381 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
382 unsigned getCPELogAlign(const MachineInstr *CPEMI);
383 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
384 unsigned getOffsetOf(MachineInstr *MI) const;
385 unsigned getUserOffset(CPUser&) const;
386 void dumpBBs();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000387
388 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000389 unsigned Disp, bool NegativeOK);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000390 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
391 const CPUser &U);
392
Reed Kotler0f007fc2013-11-05 08:14:14 +0000393 void computeBlockSize(MachineBasicBlock *MBB);
394 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
395 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
396 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
397 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
398 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
399 int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
400 bool findAvailableWater(CPUser&U, unsigned UserOffset,
401 water_iterator &WaterIter);
402 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
403 MachineBasicBlock *&NewMBB);
404 bool handleConstantPoolUser(unsigned CPUserIndex);
405 void removeDeadCPEMI(MachineInstr *CPEMI);
406 bool removeUnusedCPEntries();
407 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
408 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
409 bool DoDump = false);
410 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
411 CPUser &U, unsigned &Growth);
412 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
413 bool fixupImmediateBr(ImmBranch &Br);
414 bool fixupConditionalBr(ImmBranch &Br);
415 bool fixupUnconditionalBr(ImmBranch &Br);
Reed Kotler91ae9822013-10-27 21:57:36 +0000416
417 void prescanForConstants();
418
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000419 private:
Reed Kotler91ae9822013-10-27 21:57:36 +0000420
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000421 };
422
423 char MipsConstantIslands::ID = 0;
424} // end of anonymous namespace
425
Reed Kotler0f007fc2013-11-05 08:14:14 +0000426bool MipsConstantIslands::isOffsetInRange
427 (unsigned UserOffset, unsigned TrialOffset,
428 const CPUser &U) {
429 return isOffsetInRange(UserOffset, TrialOffset,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000430 U.getMaxDisp(), U.NegOk);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000431}
432/// print block size and offset information - debugging
433void MipsConstantIslands::dumpBBs() {
434 DEBUG({
435 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
436 const BasicBlockInfo &BBI = BBInfo[J];
437 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
Reed Kotler0f007fc2013-11-05 08:14:14 +0000438 << format(" size=%#x\n", BBInfo[J].Size);
439 }
440 });
441}
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000442/// createMipsLongBranchPass - Returns a pass that converts branches to long
443/// branches.
444FunctionPass *llvm::createMipsConstantIslandPass(MipsTargetMachine &tm) {
445 return new MipsConstantIslands(tm);
446}
447
Reed Kotler91ae9822013-10-27 21:57:36 +0000448bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
Reed Kotler1595f362013-04-09 19:46:01 +0000449 // The intention is for this to be a mips16 only pass for now
450 // FIXME:
Reed Kotler91ae9822013-10-27 21:57:36 +0000451 MF = &mf;
452 MCP = mf.getConstantPool();
Eric Christopher4e7d1e72014-07-18 23:41:32 +0000453 STI = &mf.getTarget().getSubtarget<MipsSubtarget>();
Reed Kotler91ae9822013-10-27 21:57:36 +0000454 DEBUG(dbgs() << "constant island machine function " << "\n");
Eric Christopher4e7d1e72014-07-18 23:41:32 +0000455 if (!STI->inMips16Mode() || !MipsSubtarget::useConstantIslands()) {
Reed Kotler91ae9822013-10-27 21:57:36 +0000456 return false;
457 }
Eric Christopherd9134482014-08-04 21:25:23 +0000458 TII = (const Mips16InstrInfo *)MF->getTarget()
459 .getSubtargetImpl()
460 ->getInstrInfo();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000461 MFI = MF->getInfo<MipsFunctionInfo>();
Reed Kotler91ae9822013-10-27 21:57:36 +0000462 DEBUG(dbgs() << "constant island processing " << "\n");
463 //
464 // will need to make predermination if there is any constants we need to
465 // put in constant islands. TBD.
466 //
Reed Kotler0f007fc2013-11-05 08:14:14 +0000467 if (!PrescannedForConstants) prescanForConstants();
Reed Kotler91ae9822013-10-27 21:57:36 +0000468
Reed Kotler0f007fc2013-11-05 08:14:14 +0000469 HasFarJump = false;
Reed Kotler91ae9822013-10-27 21:57:36 +0000470 // This pass invalidates liveness information when it splits basic blocks.
471 MF->getRegInfo().invalidateLiveness();
472
473 // Renumber all of the machine basic blocks in the function, guaranteeing that
474 // the numbers agree with the position of the block in the function.
475 MF->RenumberBlocks();
476
Reed Kotler0f007fc2013-11-05 08:14:14 +0000477 bool MadeChange = false;
478
Reed Kotler91ae9822013-10-27 21:57:36 +0000479 // Perform the initial placement of the constant pool entries. To start with,
480 // we put them all at the end of the function.
481 std::vector<MachineInstr*> CPEMIs;
482 if (!MCP->isEmpty())
483 doInitialPlacement(CPEMIs);
484
Reed Kotler0f007fc2013-11-05 08:14:14 +0000485 /// The next UID to take is the first unused one.
486 initPICLabelUId(CPEMIs.size());
487
488 // Do the initial scan of the function, building up information about the
489 // sizes of each block, the location of all the water, and finding all of the
490 // constant pool users.
491 initializeFunctionInfo(CPEMIs);
492 CPEMIs.clear();
493 DEBUG(dumpBBs());
494
495 /// Remove dead constant pool entries.
496 MadeChange |= removeUnusedCPEntries();
497
498 // Iteratively place constant pool entries and fix up branches until there
499 // is no change.
500 unsigned NoCPIters = 0, NoBRIters = 0;
501 (void)NoBRIters;
502 while (true) {
503 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
504 bool CPChange = false;
505 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
506 CPChange |= handleConstantPoolUser(i);
507 if (CPChange && ++NoCPIters > 30)
508 report_fatal_error("Constant Island pass failed to converge!");
509 DEBUG(dumpBBs());
510
511 // Clear NewWaterList now. If we split a block for branches, it should
512 // appear as "new water" for the next iteration of constant pool placement.
513 NewWaterList.clear();
514
515 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
516 bool BRChange = false;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000517 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
518 BRChange |= fixupImmediateBr(ImmBranches[i]);
519 if (BRChange && ++NoBRIters > 30)
520 report_fatal_error("Branch Fix Up pass failed to converge!");
521 DEBUG(dumpBBs());
Reed Kotler0f007fc2013-11-05 08:14:14 +0000522 if (!CPChange && !BRChange)
523 break;
524 MadeChange = true;
525 }
526
527 DEBUG(dbgs() << '\n'; dumpBBs());
528
529 BBInfo.clear();
530 WaterList.clear();
531 CPUsers.clear();
532 CPEntries.clear();
533 ImmBranches.clear();
534 return MadeChange;
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000535}
536
Reed Kotler91ae9822013-10-27 21:57:36 +0000537/// doInitialPlacement - Perform the initial placement of the constant pool
538/// entries. To start with, we put them all at the end of the function.
539void
540MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
541 // Create the basic block to hold the CPE's.
542 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
543 MF->push_back(BB);
544
545
546 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
547 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
548
549 // Mark the basic block as required by the const-pool.
550 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
551 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
552
553 // The function needs to be as aligned as the basic blocks. The linker may
554 // move functions around based on their alignment.
555 MF->ensureAlignment(BB->getAlignment());
556
557 // Order the entries in BB by descending alignment. That ensures correct
558 // alignment of all entries as long as BB is sufficiently aligned. Keep
559 // track of the insertion point for each alignment. We are going to bucket
560 // sort the entries as they are created.
561 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
562
563 // Add all of the constants from the constant pool to the end block, use an
564 // identity mapping of CPI's to CPE's.
565 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
566
Eric Christopherfc6de422014-08-05 02:39:49 +0000567 const DataLayout &TD = *MF->getSubtarget().getDataLayout();
Reed Kotler91ae9822013-10-27 21:57:36 +0000568 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
569 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
570 assert(Size >= 4 && "Too small constant pool entry");
571 unsigned Align = CPs[i].getAlignment();
572 assert(isPowerOf2_32(Align) && "Invalid alignment");
573 // Verify that all constant pool entries are a multiple of their alignment.
574 // If not, we would have to pad them out so that instructions stay aligned.
575 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
576
577 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
578 unsigned LogAlign = Log2_32(Align);
579 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
580
581 MachineInstr *CPEMI =
582 BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
583 .addImm(i).addConstantPoolIndex(i).addImm(Size);
584
585 CPEMIs.push_back(CPEMI);
586
587 // Ensure that future entries with higher alignment get inserted before
588 // CPEMI. This is bucket sort with iterators.
589 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
590 if (InsPoint[a] == InsAt)
591 InsPoint[a] = CPEMI;
592 // Add a new CPEntry, but no corresponding CPUser yet.
593 std::vector<CPEntry> CPEs;
594 CPEs.push_back(CPEntry(CPEMI, i));
595 CPEntries.push_back(CPEs);
596 ++NumCPEs;
597 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
598 << Size << ", align = " << Align <<'\n');
599 }
600 DEBUG(BB->dump());
601}
602
Reed Kotler0f007fc2013-11-05 08:14:14 +0000603/// BBHasFallthrough - Return true if the specified basic block can fallthrough
604/// into the block immediately after it.
605static bool BBHasFallthrough(MachineBasicBlock *MBB) {
606 // Get the next machine basic block in the function.
607 MachineFunction::iterator MBBI = MBB;
608 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000609 if (std::next(MBBI) == MBB->getParent()->end())
Reed Kotler0f007fc2013-11-05 08:14:14 +0000610 return false;
611
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000612 MachineBasicBlock *NextBB = std::next(MBBI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000613 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
614 E = MBB->succ_end(); I != E; ++I)
615 if (*I == NextBB)
616 return true;
617
618 return false;
619}
620
621/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
622/// look up the corresponding CPEntry.
623MipsConstantIslands::CPEntry
624*MipsConstantIslands::findConstPoolEntry(unsigned CPI,
625 const MachineInstr *CPEMI) {
626 std::vector<CPEntry> &CPEs = CPEntries[CPI];
627 // Number of entries per constpool index should be small, just do a
628 // linear search.
629 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
630 if (CPEs[i].CPEMI == CPEMI)
631 return &CPEs[i];
632 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000633 return nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000634}
635
636/// getCPELogAlign - Returns the required alignment of the constant pool entry
637/// represented by CPEMI. Alignment is measured in log2(bytes) units.
638unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
639 assert(CPEMI && CPEMI->getOpcode() == Mips::CONSTPOOL_ENTRY);
640
641 // Everything is 4-byte aligned unless AlignConstantIslands is set.
642 if (!AlignConstantIslands)
643 return 2;
644
645 unsigned CPI = CPEMI->getOperand(1).getIndex();
646 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
647 unsigned Align = MCP->getConstants()[CPI].getAlignment();
648 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
649 return Log2_32(Align);
650}
651
652/// initializeFunctionInfo - Do the initial scan of the function, building up
653/// information about the sizes of each block, the location of all the water,
654/// and finding all of the constant pool users.
655void MipsConstantIslands::
656initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
657 BBInfo.clear();
658 BBInfo.resize(MF->getNumBlockIDs());
659
660 // First thing, compute the size of all basic blocks, and see if the function
661 // has any inline assembly in it. If so, we have to be conservative about
662 // alignment assumptions, as we don't know for sure the size of any
663 // instructions in the inline assembly.
664 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
665 computeBlockSize(I);
666
Reed Kotler0f007fc2013-11-05 08:14:14 +0000667
668 // Compute block offsets.
669 adjustBBOffsetsAfter(MF->begin());
670
671 // Now go back through the instructions and build up our data structures.
672 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
673 MBBI != E; ++MBBI) {
674 MachineBasicBlock &MBB = *MBBI;
675
676 // If this block doesn't fall through into the next MBB, then this is
677 // 'water' that a constant pool island could be placed.
678 if (!BBHasFallthrough(&MBB))
679 WaterList.push_back(&MBB);
680 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
681 I != E; ++I) {
682 if (I->isDebugValue())
683 continue;
684
685 int Opc = I->getOpcode();
686 if (I->isBranch()) {
687 bool isCond = false;
688 unsigned Bits = 0;
689 unsigned Scale = 1;
690 int UOpc = Opc;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000691 switch (Opc) {
692 default:
Reed Kotler4b7afe52013-11-13 23:52:18 +0000693 continue; // Ignore other branches for now
694 case Mips::Bimm16:
695 Bits = 11;
696 Scale = 2;
697 isCond = false;
698 break;
699 case Mips::BimmX16:
700 Bits = 16;
701 Scale = 2;
702 isCond = false;
Reed Kotler0d409e22013-11-28 00:56:37 +0000703 break;
704 case Mips::BeqzRxImm16:
Reed Kotler59975c22013-12-03 23:42:51 +0000705 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000706 Bits = 8;
707 Scale = 2;
708 isCond = true;
709 break;
710 case Mips::BeqzRxImmX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000711 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000712 Bits = 16;
713 Scale = 2;
714 isCond = true;
715 break;
716 case Mips::BnezRxImm16:
Reed Kotler59975c22013-12-03 23:42:51 +0000717 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000718 Bits = 8;
719 Scale = 2;
720 isCond = true;
721 break;
722 case Mips::BnezRxImmX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000723 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000724 Bits = 16;
725 Scale = 2;
726 isCond = true;
727 break;
728 case Mips::Bteqz16:
Reed Kotler59975c22013-12-03 23:42:51 +0000729 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000730 Bits = 8;
731 Scale = 2;
732 isCond = true;
733 break;
734 case Mips::BteqzX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000735 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000736 Bits = 16;
737 Scale = 2;
738 isCond = true;
739 break;
740 case Mips::Btnez16:
Reed Kotler59975c22013-12-03 23:42:51 +0000741 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000742 Bits = 8;
743 Scale = 2;
744 isCond = true;
745 break;
746 case Mips::BtnezX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000747 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000748 Bits = 16;
749 Scale = 2;
750 isCond = true;
751 break;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000752 }
753 // Record this immediate branch.
754 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
755 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Reed Kotler0f007fc2013-11-05 08:14:14 +0000756 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000757
758 if (Opc == Mips::CONSTPOOL_ENTRY)
759 continue;
760
761
762 // Scan the instructions for constant pool operands.
763 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
764 if (I->getOperand(op).isCPI()) {
765
766 // We found one. The addressing mode tells us the max displacement
767 // from the PC that this instruction permits.
768
769 // Basic size info comes from the TSFlags field.
770 unsigned Bits = 0;
771 unsigned Scale = 1;
772 bool NegOk = false;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000773 unsigned LongFormBits = 0;
774 unsigned LongFormScale = 0;
775 unsigned LongFormOpcode = 0;
776 switch (Opc) {
777 default:
778 llvm_unreachable("Unknown addressing mode for CP reference!");
779 case Mips::LwRxPcTcp16:
780 Bits = 8;
Reed Kotler3d7b33f2013-11-06 04:29:52 +0000781 Scale = 4;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000782 LongFormOpcode = Mips::LwRxPcTcpX16;
Reed Kotler43788a22014-01-16 00:47:46 +0000783 LongFormBits = 14;
Reed Kotler45c59272013-11-10 00:09:26 +0000784 LongFormScale = 1;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000785 break;
786 case Mips::LwRxPcTcpX16:
Reed Kotler43788a22014-01-16 00:47:46 +0000787 Bits = 14;
Reed Kotler3d7b33f2013-11-06 04:29:52 +0000788 Scale = 1;
789 NegOk = true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000790 break;
791 }
792 // Remember that this is a user of a CP entry.
793 unsigned CPI = I->getOperand(op).getIndex();
794 MachineInstr *CPEMI = CPEMIs[CPI];
795 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
796 unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
797 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000798 LongFormMaxOffs, LongFormOpcode));
Reed Kotler0f007fc2013-11-05 08:14:14 +0000799
800 // Increment corresponding CPEntry reference count.
801 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
802 assert(CPE && "Cannot find a corresponding CPEntry!");
803 CPE->RefCount++;
804
805 // Instructions can only use one CP entry, don't bother scanning the
806 // rest of the operands.
807 break;
808
809 }
810
811 }
812 }
813
814}
815
816/// computeBlockSize - Compute the size and some alignment information for MBB.
817/// This function updates BBInfo directly.
818void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
819 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
820 BBI.Size = 0;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000821
822 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
823 ++I)
824 BBI.Size += TII->GetInstSizeInBytes(I);
825
826}
827
828/// getOffsetOf - Return the current offset of the specified machine instruction
829/// from the start of the function. This offset changes as stuff is moved
830/// around inside the function.
831unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
832 MachineBasicBlock *MBB = MI->getParent();
833
834 // The offset is composed of two things: the sum of the sizes of all MBB's
835 // before this instruction's block, and the offset from the start of the block
836 // it is in.
837 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
838
839 // Sum instructions before MI in MBB.
840 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
841 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
842 Offset += TII->GetInstSizeInBytes(I);
843 }
844 return Offset;
845}
846
847/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
848/// ID.
849static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
850 const MachineBasicBlock *RHS) {
851 return LHS->getNumber() < RHS->getNumber();
852}
853
854/// updateForInsertedWaterBlock - When a block is newly inserted into the
855/// machine function, it upsets all of the block numbers. Renumber the blocks
856/// and update the arrays that parallel this numbering.
857void MipsConstantIslands::updateForInsertedWaterBlock
858 (MachineBasicBlock *NewBB) {
859 // Renumber the MBB's to keep them consecutive.
860 NewBB->getParent()->RenumberBlocks(NewBB);
861
862 // Insert an entry into BBInfo to align it properly with the (newly
863 // renumbered) block numbers.
864 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
865
866 // Next, update WaterList. Specifically, we need to add NewMBB as having
867 // available water after it.
868 water_iterator IP =
869 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
870 CompareMBBNumbers);
871 WaterList.insert(IP, NewBB);
872}
873
Reed Kotler0f007fc2013-11-05 08:14:14 +0000874unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
Reed Kotler0eb87392013-11-05 21:39:57 +0000875 return getOffsetOf(U.MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000876}
877
878/// Split the basic block containing MI into two blocks, which are joined by
879/// an unconditional branch. Update data structures and renumber blocks to
880/// account for this change and returns the newly created block.
881MachineBasicBlock *MipsConstantIslands::splitBlockBeforeInstr
882 (MachineInstr *MI) {
883 MachineBasicBlock *OrigBB = MI->getParent();
884
885 // Create a new MBB for the code after the OrigBB.
886 MachineBasicBlock *NewBB =
887 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
888 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
889 MF->insert(MBBI, NewBB);
890
891 // Splice the instructions starting with MI over to NewBB.
892 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
893
894 // Add an unconditional branch from OrigBB to NewBB.
895 // Note the new unconditional branch is not being recorded.
896 // There doesn't seem to be meaningful DebugInfo available; this doesn't
897 // correspond to anything in the source.
Reed Kotlerf0e69682013-11-12 02:27:12 +0000898 BuildMI(OrigBB, DebugLoc(), TII->get(Mips::Bimm16)).addMBB(NewBB);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000899 ++NumSplit;
900
901 // Update the CFG. All succs of OrigBB are now succs of NewBB.
902 NewBB->transferSuccessors(OrigBB);
903
904 // OrigBB branches to NewBB.
905 OrigBB->addSuccessor(NewBB);
906
907 // Update internal data structures to account for the newly inserted MBB.
908 // This is almost the same as updateForInsertedWaterBlock, except that
909 // the Water goes after OrigBB, not NewBB.
910 MF->RenumberBlocks(NewBB);
911
912 // Insert an entry into BBInfo to align it properly with the (newly
913 // renumbered) block numbers.
914 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
915
916 // Next, update WaterList. Specifically, we need to add OrigMBB as having
917 // available water after it (but not if it's already there, which happens
918 // when splitting before a conditional branch that is followed by an
919 // unconditional branch - in that case we want to insert NewBB).
920 water_iterator IP =
921 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
922 CompareMBBNumbers);
923 MachineBasicBlock* WaterBB = *IP;
924 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000925 WaterList.insert(std::next(IP), NewBB);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000926 else
927 WaterList.insert(IP, OrigBB);
928 NewWaterList.insert(OrigBB);
929
930 // Figure out how large the OrigBB is. As the first half of the original
931 // block, it cannot contain a tablejump. The size includes
932 // the new jump we added. (It should be possible to do this without
933 // recounting everything, but it's very confusing, and this is rarely
934 // executed.)
935 computeBlockSize(OrigBB);
936
937 // Figure out how large the NewMBB is. As the second half of the original
938 // block, it may contain a tablejump.
939 computeBlockSize(NewBB);
940
941 // All BBOffsets following these blocks must be modified.
942 adjustBBOffsetsAfter(OrigBB);
943
944 return NewBB;
945}
946
947
948
949/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
950/// reference) is within MaxDisp of TrialOffset (a proposed location of a
951/// constant pool entry).
Reed Kotler0f007fc2013-11-05 08:14:14 +0000952bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
953 unsigned TrialOffset, unsigned MaxDisp,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000954 bool NegativeOK) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000955 if (UserOffset <= TrialOffset) {
956 // User before the Trial.
957 if (TrialOffset - UserOffset <= MaxDisp)
958 return true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000959 } else if (NegativeOK) {
960 if (UserOffset - TrialOffset <= MaxDisp)
961 return true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000962 }
963 return false;
964}
965
966/// isWaterInRange - Returns true if a CPE placed after the specified
967/// Water (a basic block) will be in range for the specific MI.
968///
969/// Compute how much the function will grow by inserting a CPE after Water.
970bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
971 MachineBasicBlock* Water, CPUser &U,
972 unsigned &Growth) {
973 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
974 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
975 unsigned NextBlockOffset, NextBlockAlignment;
976 MachineFunction::const_iterator NextBlock = Water;
977 if (++NextBlock == MF->end()) {
978 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
979 NextBlockAlignment = 0;
980 } else {
981 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
982 NextBlockAlignment = NextBlock->getAlignment();
983 }
984 unsigned Size = U.CPEMI->getOperand(2).getImm();
985 unsigned CPEEnd = CPEOffset + Size;
986
987 // The CPE may be able to hide in the alignment padding before the next
988 // block. It may also cause more padding to be required if it is more aligned
989 // that the next block.
990 if (CPEEnd > NextBlockOffset) {
991 Growth = CPEEnd - NextBlockOffset;
992 // Compute the padding that would go at the end of the CPE to align the next
993 // block.
994 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
995
996 // If the CPE is to be inserted before the instruction, that will raise
997 // the offset of the instruction. Also account for unknown alignment padding
998 // in blocks between CPE and the user.
999 if (CPEOffset < UserOffset)
Reed Kotler7ded5b62013-11-05 23:36:58 +00001000 UserOffset += Growth;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001001 } else
1002 // CPE fits in existing padding.
1003 Growth = 0;
1004
1005 return isOffsetInRange(UserOffset, CPEOffset, U);
1006}
1007
1008/// isCPEntryInRange - Returns true if the distance between specific MI and
1009/// specific ConstPool entry instruction can fit in MI's displacement field.
1010bool MipsConstantIslands::isCPEntryInRange
1011 (MachineInstr *MI, unsigned UserOffset,
1012 MachineInstr *CPEMI, unsigned MaxDisp,
1013 bool NegOk, bool DoDump) {
1014 unsigned CPEOffset = getOffsetOf(CPEMI);
1015
1016 if (DoDump) {
1017 DEBUG({
1018 unsigned Block = MI->getParent()->getNumber();
1019 const BasicBlockInfo &BBI = BBInfo[Block];
1020 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1021 << " max delta=" << MaxDisp
1022 << format(" insn address=%#x", UserOffset)
1023 << " in BB#" << Block << ": "
1024 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1025 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1026 int(CPEOffset-UserOffset));
1027 });
1028 }
1029
1030 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1031}
1032
1033#ifndef NDEBUG
1034/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1035/// unconditionally branches to its only successor.
1036static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1037 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1038 return false;
1039 MachineBasicBlock *Succ = *MBB->succ_begin();
1040 MachineBasicBlock *Pred = *MBB->pred_begin();
1041 MachineInstr *PredMI = &Pred->back();
Reed Kotlerf0e69682013-11-12 02:27:12 +00001042 if (PredMI->getOpcode() == Mips::Bimm16)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001043 return PredMI->getOperand(0).getMBB() == Succ;
1044 return false;
1045}
1046#endif
1047
1048void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1049 unsigned BBNum = BB->getNumber();
1050 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1051 // Get the offset and known bits at the end of the layout predecessor.
1052 // Include the alignment of the current block.
Reed Kotler7ded5b62013-11-05 23:36:58 +00001053 unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001054 BBInfo[i].Offset = Offset;
1055 }
1056}
1057
1058/// decrementCPEReferenceCount - find the constant pool entry with index CPI
1059/// and instruction CPEMI, and decrement its refcount. If the refcount
1060/// becomes 0 remove the entry and instruction. Returns true if we removed
1061/// the entry, false if we didn't.
1062
1063bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1064 MachineInstr *CPEMI) {
1065 // Find the old entry. Eliminate it if it is no longer used.
1066 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1067 assert(CPE && "Unexpected!");
1068 if (--CPE->RefCount == 0) {
1069 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001070 CPE->CPEMI = nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001071 --NumCPEs;
1072 return true;
1073 }
1074 return false;
1075}
1076
1077/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1078/// if not, see if an in-range clone of the CPE is in range, and if so,
1079/// change the data structures so the user references the clone. Returns:
1080/// 0 = no existing entry found
1081/// 1 = entry found, and there were no code insertions or deletions
1082/// 2 = entry found, and there were code insertions or deletions
1083int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1084{
1085 MachineInstr *UserMI = U.MI;
1086 MachineInstr *CPEMI = U.CPEMI;
1087
1088 // Check to see if the CPE is already in-range.
1089 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1090 true)) {
1091 DEBUG(dbgs() << "In range\n");
1092 return 1;
1093 }
1094
1095 // No. Look for previously created clones of the CPE that are in range.
1096 unsigned CPI = CPEMI->getOperand(1).getIndex();
1097 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1098 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1099 // We already tried this one
1100 if (CPEs[i].CPEMI == CPEMI)
1101 continue;
1102 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001103 if (CPEs[i].CPEMI == nullptr)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001104 continue;
1105 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1106 U.NegOk)) {
1107 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1108 << CPEs[i].CPI << "\n");
1109 // Point the CPUser node to the replacement
1110 U.CPEMI = CPEs[i].CPEMI;
1111 // Change the CPI in the instruction operand to refer to the clone.
1112 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1113 if (UserMI->getOperand(j).isCPI()) {
1114 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1115 break;
1116 }
1117 // Adjust the refcount of the clone...
1118 CPEs[i].RefCount++;
1119 // ...and the original. If we didn't remove the old entry, none of the
1120 // addresses changed, so we don't need another pass.
1121 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1122 }
1123 }
1124 return 0;
1125}
1126
1127/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1128/// This version checks if the longer form of the instruction can be used to
1129/// to satisfy things.
1130/// if not, see if an in-range clone of the CPE is in range, and if so,
1131/// change the data structures so the user references the clone. Returns:
1132/// 0 = no existing entry found
1133/// 1 = entry found, and there were no code insertions or deletions
1134/// 2 = entry found, and there were code insertions or deletions
1135int MipsConstantIslands::findLongFormInRangeCPEntry
1136 (CPUser& U, unsigned UserOffset)
1137{
1138 MachineInstr *UserMI = U.MI;
1139 MachineInstr *CPEMI = U.CPEMI;
1140
1141 // Check to see if the CPE is already in-range.
1142 if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
1143 U.getLongFormMaxDisp(), U.NegOk,
1144 true)) {
1145 DEBUG(dbgs() << "In range\n");
1146 UserMI->setDesc(TII->get(U.getLongFormOpcode()));
Reed Kotler45c59272013-11-10 00:09:26 +00001147 U.setMaxDisp(U.getLongFormMaxDisp());
Reed Kotler0f007fc2013-11-05 08:14:14 +00001148 return 2; // instruction is longer length now
1149 }
1150
1151 // No. Look for previously created clones of the CPE that are in range.
1152 unsigned CPI = CPEMI->getOperand(1).getIndex();
1153 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1154 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1155 // We already tried this one
1156 if (CPEs[i].CPEMI == CPEMI)
1157 continue;
1158 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001159 if (CPEs[i].CPEMI == nullptr)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001160 continue;
1161 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
1162 U.getLongFormMaxDisp(), U.NegOk)) {
1163 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1164 << CPEs[i].CPI << "\n");
1165 // Point the CPUser node to the replacement
1166 U.CPEMI = CPEs[i].CPEMI;
1167 // Change the CPI in the instruction operand to refer to the clone.
1168 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1169 if (UserMI->getOperand(j).isCPI()) {
1170 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1171 break;
1172 }
1173 // Adjust the refcount of the clone...
1174 CPEs[i].RefCount++;
1175 // ...and the original. If we didn't remove the old entry, none of the
1176 // addresses changed, so we don't need another pass.
1177 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1178 }
1179 }
1180 return 0;
1181}
1182
1183/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1184/// the specific unconditional branch instruction.
1185static inline unsigned getUnconditionalBrDisp(int Opc) {
1186 switch (Opc) {
Reed Kotlerf0e69682013-11-12 02:27:12 +00001187 case Mips::Bimm16:
1188 return ((1<<10)-1)*2;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001189 case Mips::BimmX16:
1190 return ((1<<16)-1)*2;
1191 default:
1192 break;
1193 }
1194 return ((1<<16)-1)*2;
1195}
1196
1197/// findAvailableWater - Look for an existing entry in the WaterList in which
1198/// we can place the CPE referenced from U so it's within range of U's MI.
1199/// Returns true if found, false if not. If it returns true, WaterIter
Reed Kotler4d0313d2013-11-05 12:04:37 +00001200/// is set to the WaterList entry.
1201/// To ensure that this pass
Reed Kotler0f007fc2013-11-05 08:14:14 +00001202/// terminates, the CPE location for a particular CPUser is only allowed to
1203/// move to a lower address, so search backward from the end of the list and
1204/// prefer the first water that is in range.
1205bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1206 water_iterator &WaterIter) {
1207 if (WaterList.empty())
1208 return false;
1209
1210 unsigned BestGrowth = ~0u;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001211 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001212 --IP) {
1213 MachineBasicBlock* WaterBB = *IP;
1214 // Check if water is in range and is either at a lower address than the
1215 // current "high water mark" or a new water block that was created since
1216 // the previous iteration by inserting an unconditional branch. In the
1217 // latter case, we want to allow resetting the high water mark back to
1218 // this new water since we haven't seen it before. Inserting branches
1219 // should be relatively uncommon and when it does happen, we want to be
1220 // sure to take advantage of it for all the CPEs near that block, so that
1221 // we don't insert more branches than necessary.
1222 unsigned Growth;
1223 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1224 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1225 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1226 // This is the least amount of required padding seen so far.
1227 BestGrowth = Growth;
1228 WaterIter = IP;
1229 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1230 << " Growth=" << Growth << '\n');
1231
1232 // Keep looking unless it is perfect.
1233 if (BestGrowth == 0)
1234 return true;
1235 }
1236 if (IP == B)
1237 break;
1238 }
1239 return BestGrowth != ~0u;
1240}
1241
1242/// createNewWater - No existing WaterList entry will work for
1243/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1244/// block is used if in range, and the conditional branch munged so control
1245/// flow is correct. Otherwise the block is split to create a hole with an
1246/// unconditional branch around it. In either case NewMBB is set to a
1247/// block following which the new island can be inserted (the WaterList
1248/// is not adjusted).
1249void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1250 unsigned UserOffset,
1251 MachineBasicBlock *&NewMBB) {
1252 CPUser &U = CPUsers[CPUserIndex];
1253 MachineInstr *UserMI = U.MI;
1254 MachineInstr *CPEMI = U.CPEMI;
1255 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1256 MachineBasicBlock *UserMBB = UserMI->getParent();
1257 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1258
1259 // If the block does not end in an unconditional branch already, and if the
Reed Kotler4d0313d2013-11-05 12:04:37 +00001260 // end of the block is within range, make new water there.
Reed Kotler0f007fc2013-11-05 08:14:14 +00001261 if (BBHasFallthrough(UserMBB)) {
1262 // Size of branch to insert.
1263 unsigned Delta = 2;
1264 // Compute the offset where the CPE will begin.
1265 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1266
1267 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1268 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1269 << format(", expected CPE offset %#x\n", CPEOffset));
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001270 NewMBB = std::next(MachineFunction::iterator(UserMBB));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001271 // Add an unconditional branch from UserMBB to fallthrough block. Record
1272 // it for branch lengthening; this new branch will not get out of range,
1273 // but if the preceding conditional branch is out of range, the targets
1274 // will be exchanged, and the altered branch may be out of range, so the
1275 // machinery has to know about it.
Reed Kotlerf0e69682013-11-12 02:27:12 +00001276 int UncondBr = Mips::Bimm16;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001277 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1278 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1279 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1280 MaxDisp, false, UncondBr));
1281 BBInfo[UserMBB->getNumber()].Size += Delta;
1282 adjustBBOffsetsAfter(UserMBB);
1283 return;
1284 }
1285 }
1286
Reed Kotler4d0313d2013-11-05 12:04:37 +00001287 // What a big block. Find a place within the block to split it.
Reed Kotler0f007fc2013-11-05 08:14:14 +00001288
1289 // Try to split the block so it's fully aligned. Compute the latest split
1290 // point where we can add a 4-byte branch instruction, and then align to
1291 // LogAlign which is the largest possible alignment in the function.
1292 unsigned LogAlign = MF->getAlignment();
1293 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
Reed Kotler7ded5b62013-11-05 23:36:58 +00001294 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001295 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1296 BaseInsertOffset));
1297
1298 // The 4 in the following is for the unconditional branch we'll be inserting
Reed Kotler4d0313d2013-11-05 12:04:37 +00001299 // Alignment of the island is handled
Reed Kotler0f007fc2013-11-05 08:14:14 +00001300 // inside isOffsetInRange.
1301 BaseInsertOffset -= 4;
1302
1303 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
Reed Kotler7ded5b62013-11-05 23:36:58 +00001304 << " la=" << LogAlign << '\n');
Reed Kotler0f007fc2013-11-05 08:14:14 +00001305
1306 // This could point off the end of the block if we've already got constant
1307 // pool entries following this block; only the last one is in the water list.
1308 // Back past any possible branches (allow for a conditional and a maximally
1309 // long unconditional).
1310 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Reed Kotler7ded5b62013-11-05 23:36:58 +00001311 BaseInsertOffset = UserBBI.postOffset() - 8;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001312 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1313 }
Reed Kotler7ded5b62013-11-05 23:36:58 +00001314 unsigned EndInsertOffset = BaseInsertOffset + 4 +
Reed Kotler0f007fc2013-11-05 08:14:14 +00001315 CPEMI->getOperand(2).getImm();
1316 MachineBasicBlock::iterator MI = UserMI;
1317 ++MI;
1318 unsigned CPUIndex = CPUserIndex+1;
1319 unsigned NumCPUsers = CPUsers.size();
1320 //MachineInstr *LastIT = 0;
1321 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1322 Offset < BaseInsertOffset;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001323 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001324 assert(MI != UserMBB->end() && "Fell off end of block");
1325 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1326 CPUser &U = CPUsers[CPUIndex];
1327 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1328 // Shift intertion point by one unit of alignment so it is within reach.
1329 BaseInsertOffset -= 1u << LogAlign;
1330 EndInsertOffset -= 1u << LogAlign;
1331 }
1332 // This is overly conservative, as we don't account for CPEMIs being
1333 // reused within the block, but it doesn't matter much. Also assume CPEs
1334 // are added in order with alignment padding. We may eventually be able
1335 // to pack the aligned CPEs better.
1336 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1337 CPUIndex++;
1338 }
1339 }
1340
1341 --MI;
1342 NewMBB = splitBlockBeforeInstr(MI);
1343}
1344
1345/// handleConstantPoolUser - Analyze the specified user, checking to see if it
1346/// is out-of-range. If so, pick up the constant pool value and move it some
1347/// place in-range. Return true if we changed any addresses (thus must run
1348/// another pass of branch lengthening), false otherwise.
1349bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1350 CPUser &U = CPUsers[CPUserIndex];
1351 MachineInstr *UserMI = U.MI;
1352 MachineInstr *CPEMI = U.CPEMI;
1353 unsigned CPI = CPEMI->getOperand(1).getIndex();
1354 unsigned Size = CPEMI->getOperand(2).getImm();
1355 // Compute this only once, it's expensive.
1356 unsigned UserOffset = getUserOffset(U);
1357
1358 // See if the current entry is within range, or there is a clone of it
1359 // in range.
1360 int result = findInRangeCPEntry(U, UserOffset);
1361 if (result==1) return false;
1362 else if (result==2) return true;
1363
1364
1365 // Look for water where we can place this CPE.
1366 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1367 MachineBasicBlock *NewMBB;
1368 water_iterator IP;
1369 if (findAvailableWater(U, UserOffset, IP)) {
1370 DEBUG(dbgs() << "Found water in range\n");
1371 MachineBasicBlock *WaterBB = *IP;
1372
1373 // If the original WaterList entry was "new water" on this iteration,
1374 // propagate that to the new island. This is just keeping NewWaterList
1375 // updated to match the WaterList, which will be updated below.
1376 if (NewWaterList.erase(WaterBB))
1377 NewWaterList.insert(NewIsland);
1378
1379 // The new CPE goes before the following block (NewMBB).
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001380 NewMBB = std::next(MachineFunction::iterator(WaterBB));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001381
1382 } else {
1383 // No water found.
1384 // we first see if a longer form of the instrucion could have reached
1385 // the constant. in that case we won't bother to split
Reed Kotler45c59272013-11-10 00:09:26 +00001386 if (!NoLoadRelaxation) {
1387 result = findLongFormInRangeCPEntry(U, UserOffset);
1388 if (result != 0) return true;
1389 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001390 DEBUG(dbgs() << "No water found\n");
1391 createNewWater(CPUserIndex, UserOffset, NewMBB);
1392
1393 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1394 // called while handling branches so that the water will be seen on the
1395 // next iteration for constant pools, but in this context, we don't want
1396 // it. Check for this so it will be removed from the WaterList.
1397 // Also remove any entry from NewWaterList.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001398 MachineBasicBlock *WaterBB = std::prev(MachineFunction::iterator(NewMBB));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001399 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1400 if (IP != WaterList.end())
1401 NewWaterList.erase(WaterBB);
1402
1403 // We are adding new water. Update NewWaterList.
1404 NewWaterList.insert(NewIsland);
1405 }
1406
1407 // Remove the original WaterList entry; we want subsequent insertions in
1408 // this vicinity to go after the one we're about to insert. This
1409 // considerably reduces the number of times we have to move the same CPE
1410 // more than once and is also important to ensure the algorithm terminates.
1411 if (IP != WaterList.end())
1412 WaterList.erase(IP);
1413
1414 // Okay, we know we can put an island before NewMBB now, do it!
1415 MF->insert(NewMBB, NewIsland);
1416
1417 // Update internal data structures to account for the newly inserted MBB.
1418 updateForInsertedWaterBlock(NewIsland);
1419
1420 // Decrement the old entry, and remove it if refcount becomes 0.
1421 decrementCPEReferenceCount(CPI, CPEMI);
1422
Reed Kotlerd3b28eb2013-11-24 02:53:09 +00001423 // No existing clone of this CPE is within range.
1424 // We will be generating a new clone. Get a UID for it.
1425 unsigned ID = createPICLabelUId();
1426
Reed Kotler0f007fc2013-11-05 08:14:14 +00001427 // Now that we have an island to add the CPE to, clone the original CPE and
1428 // add it to the island.
1429 U.HighWaterMark = NewIsland;
1430 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1431 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1432 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1433 ++NumCPEs;
1434
1435 // Mark the basic block as aligned as required by the const-pool entry.
1436 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1437
1438 // Increase the size of the island block to account for the new entry.
1439 BBInfo[NewIsland->getNumber()].Size += Size;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001440 adjustBBOffsetsAfter(std::prev(MachineFunction::iterator(NewIsland)));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001441
Reed Kotlerd3b28eb2013-11-24 02:53:09 +00001442
Reed Kotler0f007fc2013-11-05 08:14:14 +00001443
1444 // Finally, change the CPI in the instruction operand to be ID.
1445 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1446 if (UserMI->getOperand(i).isCPI()) {
1447 UserMI->getOperand(i).setIndex(ID);
1448 break;
1449 }
1450
1451 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1452 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1453
1454 return true;
1455}
1456
1457/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1458/// sizes and offsets of impacted basic blocks.
1459void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1460 MachineBasicBlock *CPEBB = CPEMI->getParent();
1461 unsigned Size = CPEMI->getOperand(2).getImm();
1462 CPEMI->eraseFromParent();
1463 BBInfo[CPEBB->getNumber()].Size -= Size;
1464 // All succeeding offsets have the current size value added in, fix this.
1465 if (CPEBB->empty()) {
1466 BBInfo[CPEBB->getNumber()].Size = 0;
1467
1468 // This block no longer needs to be aligned.
1469 CPEBB->setAlignment(0);
1470 } else
1471 // Entries are sorted by descending alignment, so realign from the front.
1472 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1473
1474 adjustBBOffsetsAfter(CPEBB);
1475 // An island has only one predecessor BB and one successor BB. Check if
1476 // this BB's predecessor jumps directly to this BB's successor. This
1477 // shouldn't happen currently.
1478 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1479 // FIXME: remove the empty blocks after all the work is done?
1480}
1481
1482/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1483/// are zero.
1484bool MipsConstantIslands::removeUnusedCPEntries() {
1485 unsigned MadeChange = false;
1486 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1487 std::vector<CPEntry> &CPEs = CPEntries[i];
1488 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1489 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1490 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001491 CPEs[j].CPEMI = nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001492 MadeChange = true;
1493 }
1494 }
1495 }
1496 return MadeChange;
1497}
1498
1499/// isBBInRange - Returns true if the distance between specific MI and
1500/// specific BB can fit in MI's displacement field.
1501bool MipsConstantIslands::isBBInRange
1502 (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
1503
1504unsigned PCAdj = 4;
1505
1506 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1507 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1508
1509 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1510 << " from BB#" << MI->getParent()->getNumber()
1511 << " max delta=" << MaxDisp
1512 << " from " << getOffsetOf(MI) << " to " << DestOffset
1513 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1514
1515 if (BrOffset <= DestOffset) {
1516 // Branch before the Dest.
1517 if (DestOffset-BrOffset <= MaxDisp)
1518 return true;
1519 } else {
1520 if (BrOffset-DestOffset <= MaxDisp)
1521 return true;
1522 }
1523 return false;
1524}
1525
1526/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1527/// away to fit in its displacement field.
1528bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1529 MachineInstr *MI = Br.MI;
Reed Kotler0d409e22013-11-28 00:56:37 +00001530 unsigned TargetOperand = branchTargetOperand(MI);
1531 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001532
1533 // Check to see if the DestBB is already in-range.
1534 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1535 return false;
1536
1537 if (!Br.isCond)
1538 return fixupUnconditionalBr(Br);
1539 return fixupConditionalBr(Br);
1540}
1541
1542/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1543/// too far away to fit in its displacement field. If the LR register has been
1544/// spilled in the epilogue, then we can use BL to implement a far jump.
1545/// Otherwise, add an intermediate branch instruction to a branch.
1546bool
1547MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1548 MachineInstr *MI = Br.MI;
1549 MachineBasicBlock *MBB = MI->getParent();
Reed Kotler2fc05be2013-11-21 05:13:23 +00001550 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001551 // Use BL to implement far jump.
Reed Kotler2fc05be2013-11-21 05:13:23 +00001552 unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2;
1553 if (isBBInRange(MI, DestBB, BimmX16MaxDisp)) {
1554 Br.MaxDisp = BimmX16MaxDisp;
1555 MI->setDesc(TII->get(Mips::BimmX16));
1556 }
1557 else {
1558 // need to give the math a more careful look here
1559 // this is really a segment address and not
1560 // a PC relative address. FIXME. But I think that
1561 // just reducing the bits by 1 as I've done is correct.
1562 // The basic block we are branching too much be longword aligned.
1563 // we know that RA is saved because we always save it right now.
1564 // this requirement will be relaxed later but we also have an alternate
1565 // way to implement this that I will implement that does not need jal.
1566 // We should have a way to back out this alignment restriction if we "can" later.
1567 // but it is not harmful.
1568 //
1569 DestBB->setAlignment(2);
1570 Br.MaxDisp = ((1<<24)-1) * 2;
Reed Kotlerad450f22013-11-29 22:32:56 +00001571 MI->setDesc(TII->get(Mips::JalB16));
Reed Kotler2fc05be2013-11-21 05:13:23 +00001572 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001573 BBInfo[MBB->getNumber()].Size += 2;
1574 adjustBBOffsetsAfter(MBB);
1575 HasFarJump = true;
1576 ++NumUBrFixed;
1577
1578 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1579
1580 return true;
1581}
1582
Reed Kotler0d409e22013-11-28 00:56:37 +00001583
Reed Kotler0f007fc2013-11-05 08:14:14 +00001584/// fixupConditionalBr - Fix up a conditional branch whose destination is too
1585/// far away to fit in its displacement field. It is converted to an inverse
1586/// conditional branch + an unconditional branch to the destination.
1587bool
1588MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1589 MachineInstr *MI = Br.MI;
Reed Kotler0d409e22013-11-28 00:56:37 +00001590 unsigned TargetOperand = branchTargetOperand(MI);
1591 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1592 unsigned Opcode = MI->getOpcode();
1593 unsigned LongFormOpcode = longformBranchOpcode(Opcode);
1594 unsigned LongFormMaxOff = branchMaxOffsets(LongFormOpcode);
1595
1596 // Check to see if the DestBB is already in-range.
1597 if (isBBInRange(MI, DestBB, LongFormMaxOff)) {
1598 Br.MaxDisp = LongFormMaxOff;
1599 MI->setDesc(TII->get(LongFormOpcode));
1600 return true;
1601 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001602
1603 // Add an unconditional branch to the destination and invert the branch
1604 // condition to jump over it:
Reed Kotlerad450f22013-11-29 22:32:56 +00001605 // bteqz L1
Reed Kotler0f007fc2013-11-05 08:14:14 +00001606 // =>
Reed Kotlerad450f22013-11-29 22:32:56 +00001607 // bnez L2
Reed Kotler0f007fc2013-11-05 08:14:14 +00001608 // b L1
1609 // L2:
Reed Kotler0f007fc2013-11-05 08:14:14 +00001610
1611 // If the branch is at the end of its MBB and that has a fall-through block,
1612 // direct the updated conditional branch to the fall-through block. Otherwise,
1613 // split the MBB before the next instruction.
1614 MachineBasicBlock *MBB = MI->getParent();
1615 MachineInstr *BMI = &MBB->back();
1616 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Reed Kotler47f3c64a2013-12-19 00:43:08 +00001617 unsigned OppositeBranchOpcode = TII->getOppositeBranchOpc(Opcode);
Reed Kotlerad450f22013-11-29 22:32:56 +00001618
Reed Kotler0f007fc2013-11-05 08:14:14 +00001619 ++NumCBrFixed;
1620 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001621 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Reed Kotlerad450f22013-11-29 22:32:56 +00001622 isUnconditionalBranch(BMI->getOpcode())) {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001623 // Last MI in the BB is an unconditional branch. Can we simply invert the
1624 // condition and swap destinations:
Reed Kotlerad450f22013-11-29 22:32:56 +00001625 // beqz L1
Reed Kotler0f007fc2013-11-05 08:14:14 +00001626 // b L2
1627 // =>
Reed Kotlerad450f22013-11-29 22:32:56 +00001628 // bnez L2
Reed Kotler0f007fc2013-11-05 08:14:14 +00001629 // b L1
Reed Kotlerad450f22013-11-29 22:32:56 +00001630 unsigned BMITargetOperand = branchTargetOperand(BMI);
1631 MachineBasicBlock *NewDest =
1632 BMI->getOperand(BMITargetOperand).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001633 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1634 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1635 << *BMI);
Reed Kotler59975c22013-12-03 23:42:51 +00001636 MI->setDesc(TII->get(OppositeBranchOpcode));
Reed Kotlerad450f22013-11-29 22:32:56 +00001637 BMI->getOperand(BMITargetOperand).setMBB(DestBB);
1638 MI->getOperand(TargetOperand).setMBB(NewDest);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001639 return true;
1640 }
1641 }
1642 }
1643
Reed Kotlerad450f22013-11-29 22:32:56 +00001644
Reed Kotler0f007fc2013-11-05 08:14:14 +00001645 if (NeedSplit) {
1646 splitBlockBeforeInstr(MI);
1647 // No need for the branch to the next block. We're adding an unconditional
1648 // branch to the destination.
1649 int delta = TII->GetInstSizeInBytes(&MBB->back());
1650 BBInfo[MBB->getNumber()].Size -= delta;
1651 MBB->back().eraseFromParent();
1652 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1653 }
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001654 MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001655
1656 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1657 << " also invert condition and change dest. to BB#"
1658 << NextBB->getNumber() << "\n");
1659
1660 // Insert a new conditional branch and a new unconditional branch.
1661 // Also update the ImmBranch as well as adding a new entry for the new branch.
Reed Kotler59975c22013-12-03 23:42:51 +00001662 if (MI->getNumExplicitOperands() == 2) {
1663 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1664 .addReg(MI->getOperand(0).getReg())
1665 .addMBB(NextBB);
Reed Kotler47f3c64a2013-12-19 00:43:08 +00001666 } else {
1667 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1668 .addMBB(NextBB);
Reed Kotler59975c22013-12-03 23:42:51 +00001669 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001670 Br.MI = &MBB->back();
1671 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1672 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1673 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1674 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1675 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1676
1677 // Remove the old conditional branch. It may or may not still be in MBB.
1678 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1679 MI->eraseFromParent();
1680 adjustBBOffsetsAfter(MBB);
1681 return true;
1682}
1683
Reed Kotler91ae9822013-10-27 21:57:36 +00001684
1685void MipsConstantIslands::prescanForConstants() {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001686 unsigned J = 0;
1687 (void)J;
Reed Kotler91ae9822013-10-27 21:57:36 +00001688 for (MachineFunction::iterator B =
1689 MF->begin(), E = MF->end(); B != E; ++B) {
1690 for (MachineBasicBlock::instr_iterator I =
1691 B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
1692 switch(I->getDesc().getOpcode()) {
1693 case Mips::LwConstant32: {
Reed Kotlera787aa22013-11-24 06:18:50 +00001694 PrescannedForConstants = true;
Reed Kotler91ae9822013-10-27 21:57:36 +00001695 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1696 J = I->getNumOperands();
1697 DEBUG(dbgs() << "num operands " << J << "\n");
1698 MachineOperand& Literal = I->getOperand(1);
1699 if (Literal.isImm()) {
1700 int64_t V = Literal.getImm();
1701 DEBUG(dbgs() << "literal " << V << "\n");
1702 Type *Int32Ty =
1703 Type::getInt32Ty(MF->getFunction()->getContext());
1704 const Constant *C = ConstantInt::get(Int32Ty, V);
1705 unsigned index = MCP->getConstantPoolIndex(C, 4);
1706 I->getOperand(2).ChangeToImmediate(index);
1707 DEBUG(dbgs() << "constant island constant " << *I << "\n");
Reed Kotler0f007fc2013-11-05 08:14:14 +00001708 I->setDesc(TII->get(Mips::LwRxPcTcp16));
Reed Kotler91ae9822013-10-27 21:57:36 +00001709 I->RemoveOperand(1);
1710 I->RemoveOperand(1);
1711 I->addOperand(MachineOperand::CreateCPI(index, 0));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001712 I->addOperand(MachineOperand::CreateImm(4));
Reed Kotler91ae9822013-10-27 21:57:36 +00001713 }
1714 break;
1715 }
1716 default:
1717 break;
1718 }
1719 }
1720 }
1721}
Reed Kotler0f007fc2013-11-05 08:14:14 +00001722