blob: e05fe0abac09e17457f25a643d1a496ae7774861 [file] [log] [blame]
Reed Kotler5bf80202013-02-27 04:20:14 +00001//===-- MipsConstantIslandPass.cpp - Emit Pc Relative loads----------------===//
Reed Kotlerbb3094a2013-02-27 03:33:58 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//
11// This pass is used to make Pc relative loads of constants.
Reed Kotler4d0313d2013-11-05 12:04:37 +000012// For now, only Mips16 will use this.
Reed Kotlerbb3094a2013-02-27 03:33:58 +000013//
14// Loading constants inline is expensive on Mips16 and it's in general better
15// to place the constant nearby in code space and then it can be loaded with a
16// simple 16 bit load instruction.
17//
18// The constants can be not just numbers but addresses of functions and labels.
19// This can be particularly helpful in static relocation mode for embedded
20// non linux targets.
21//
22//
23
24#define DEBUG_TYPE "mips-constant-islands"
25
26#include "Mips.h"
27#include "MCTargetDesc/MipsBaseInfo.h"
Reed Kotler5c8ae092013-11-13 04:37:52 +000028#include "Mips16InstrInfo.h"
Reed Kotler0f007fc2013-11-05 08:14:14 +000029#include "MipsMachineFunction.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000030#include "MipsTargetMachine.h"
31#include "llvm/ADT/Statistic.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000032#include "llvm/CodeGen/MachineBasicBlock.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000033#include "llvm/CodeGen/MachineFunctionPass.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000035#include "llvm/CodeGen/MachineRegisterInfo.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000036#include "llvm/IR/Function.h"
37#include "llvm/Support/CommandLine.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000038#include "llvm/Support/Debug.h"
39#include "llvm/Support/InstIterator.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000040#include "llvm/Support/MathExtras.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000041#include "llvm/Support/raw_ostream.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000042#include "llvm/Target/TargetInstrInfo.h"
43#include "llvm/Target/TargetMachine.h"
44#include "llvm/Target/TargetRegisterInfo.h"
Reed Kotler0f007fc2013-11-05 08:14:14 +000045#include "llvm/Support/Format.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000046#include <algorithm>
Reed Kotlerbb3094a2013-02-27 03:33:58 +000047
48using namespace llvm;
49
Reed Kotler91ae9822013-10-27 21:57:36 +000050STATISTIC(NumCPEs, "Number of constpool entries");
Reed Kotler0f007fc2013-11-05 08:14:14 +000051STATISTIC(NumSplit, "Number of uncond branches inserted");
52STATISTIC(NumCBrFixed, "Number of cond branches fixed");
53STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
Reed Kotler91ae9822013-10-27 21:57:36 +000054
55// FIXME: This option should be removed once it has received sufficient testing.
56static cl::opt<bool>
57AlignConstantIslands("mips-align-constant-islands", cl::Hidden, cl::init(true),
58 cl::desc("Align constant islands in code"));
59
Reed Kotler0f007fc2013-11-05 08:14:14 +000060
61// Rather than do make check tests with huge amounts of code, we force
62// the test to use this amount.
63//
64static cl::opt<int> ConstantIslandsSmallOffset(
65 "mips-constant-islands-small-offset",
66 cl::init(0),
67 cl::desc("Make small offsets be this amount for testing purposes"),
68 cl::Hidden);
69
Reed Kotler45c59272013-11-10 00:09:26 +000070//
71// For testing purposes we tell it to not use relaxed load forms so that it
72// will split blocks.
73//
74static cl::opt<bool> NoLoadRelaxation(
75 "mips-constant-islands-no-load-relaxation",
76 cl::init(false),
77 cl::desc("Don't relax loads to long loads - for testing purposes"),
78 cl::Hidden);
79
Reed Kotler0d409e22013-11-28 00:56:37 +000080static unsigned int branchTargetOperand(MachineInstr *MI) {
81 switch (MI->getOpcode()) {
82 case Mips::Bimm16:
83 case Mips::BimmX16:
84 case Mips::Bteqz16:
85 case Mips::BteqzX16:
86 case Mips::Btnez16:
87 case Mips::BtnezX16:
Reed Kotlerad450f22013-11-29 22:32:56 +000088 case Mips::JalB16:
Reed Kotler0d409e22013-11-28 00:56:37 +000089 return 0;
90 case Mips::BeqzRxImm16:
91 case Mips::BeqzRxImmX16:
92 case Mips::BnezRxImm16:
93 case Mips::BnezRxImmX16:
94 return 1;
95 }
96 llvm_unreachable("Unknown branch type");
97}
98
Reed Kotlerad450f22013-11-29 22:32:56 +000099static bool isUnconditionalBranch(unsigned int Opcode) {
100 switch (Opcode) {
101 default: return false;
102 case Mips::Bimm16:
103 case Mips::BimmX16:
104 case Mips::JalB16:
105 return true;
106 }
107}
108
Reed Kotler0d409e22013-11-28 00:56:37 +0000109static unsigned int longformBranchOpcode(unsigned int Opcode) {
110 switch (Opcode) {
111 case Mips::Bimm16:
112 case Mips::BimmX16:
113 return Mips::BimmX16;
114 case Mips::Bteqz16:
115 case Mips::BteqzX16:
116 return Mips::BteqzX16;
117 case Mips::Btnez16:
118 case Mips::BtnezX16:
119 return Mips::BtnezX16;
Reed Kotlerad450f22013-11-29 22:32:56 +0000120 case Mips::JalB16:
121 return Mips::JalB16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000122 case Mips::BeqzRxImm16:
123 case Mips::BeqzRxImmX16:
124 return Mips::BeqzRxImmX16;
125 case Mips::BnezRxImm16:
126 case Mips::BnezRxImmX16:
127 return Mips::BnezRxImmX16;
128 }
129 llvm_unreachable("Unknown branch type");
130}
131
132//
133// FIXME: need to go through this whole constant islands port and check the math
134// for branch ranges and clean this up and make some functions to calculate things
135// that are done many times identically.
136// Need to refactor some of the code to call this routine.
137//
138static unsigned int branchMaxOffsets(unsigned int Opcode) {
139 unsigned Bits, Scale;
140 switch (Opcode) {
141 case Mips::Bimm16:
142 Bits = 11;
143 Scale = 2;
144 break;
145 case Mips::BimmX16:
146 Bits = 16;
147 Scale = 2;
148 break;
149 case Mips::BeqzRxImm16:
150 Bits = 8;
151 Scale = 2;
152 break;
153 case Mips::BeqzRxImmX16:
154 Bits = 16;
155 Scale = 2;
156 break;
157 case Mips::BnezRxImm16:
158 Bits = 8;
159 Scale = 2;
160 break;
161 case Mips::BnezRxImmX16:
162 Bits = 16;
163 Scale = 2;
164 break;
165 case Mips::Bteqz16:
166 Bits = 8;
167 Scale = 2;
168 break;
169 case Mips::BteqzX16:
170 Bits = 16;
171 Scale = 2;
172 break;
173 case Mips::Btnez16:
174 Bits = 8;
175 Scale = 2;
176 break;
177 case Mips::BtnezX16:
178 Bits = 16;
179 Scale = 2;
180 break;
181 default:
182 llvm_unreachable("Unknown branch type");
183 }
184 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
185 return MaxOffs;
186}
Reed Kotler0f007fc2013-11-05 08:14:14 +0000187
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000188namespace {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000189
190
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000191 typedef MachineBasicBlock::iterator Iter;
192 typedef MachineBasicBlock::reverse_iterator ReverseIter;
193
Reed Kotler0f007fc2013-11-05 08:14:14 +0000194 /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
195 /// requires constant pool entries to be scattered among the instructions
196 /// inside a function. To do this, it completely ignores the normal LLVM
197 /// constant pool; instead, it places constants wherever it feels like with
198 /// special instructions.
199 ///
200 /// The terminology used in this pass includes:
201 /// Islands - Clumps of constants placed in the function.
202 /// Water - Potential places where an island could be formed.
203 /// CPE - A constant pool entry that has been placed somewhere, which
204 /// tracks a list of users.
205
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000206 class MipsConstantIslands : public MachineFunctionPass {
207
Reed Kotler0f007fc2013-11-05 08:14:14 +0000208 /// BasicBlockInfo - Information about the offset and size of a single
209 /// basic block.
210 struct BasicBlockInfo {
211 /// Offset - Distance from the beginning of the function to the beginning
212 /// of this basic block.
213 ///
214 /// Offsets are computed assuming worst case padding before an aligned
215 /// block. This means that subtracting basic block offsets always gives a
216 /// conservative estimate of the real distance which may be smaller.
217 ///
218 /// Because worst case padding is used, the computed offset of an aligned
219 /// block may not actually be aligned.
220 unsigned Offset;
221
222 /// Size - Size of the basic block in bytes. If the block contains
223 /// inline assembly, this is a worst case estimate.
224 ///
225 /// The size does not include any alignment padding whether from the
226 /// beginning of the block, or from an aligned jump table at the end.
227 unsigned Size;
228
Reed Kotler7ded5b62013-11-05 23:36:58 +0000229 // FIXME: ignore LogAlign for this patch
230 //
Reed Kotler0f007fc2013-11-05 08:14:14 +0000231 unsigned postOffset(unsigned LogAlign = 0) const {
232 unsigned PO = Offset + Size;
233 return PO;
234 }
235
Reed Kotler7ded5b62013-11-05 23:36:58 +0000236 BasicBlockInfo() : Offset(0), Size(0) {}
237
Reed Kotler0f007fc2013-11-05 08:14:14 +0000238 };
239
240 std::vector<BasicBlockInfo> BBInfo;
241
242 /// WaterList - A sorted list of basic blocks where islands could be placed
243 /// (i.e. blocks that don't fall through to the following block, due
244 /// to a return, unreachable, or unconditional branch).
245 std::vector<MachineBasicBlock*> WaterList;
246
247 /// NewWaterList - The subset of WaterList that was created since the
248 /// previous iteration by inserting unconditional branches.
249 SmallSet<MachineBasicBlock*, 4> NewWaterList;
250
251 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
252
253 /// CPUser - One user of a constant pool, keeping the machine instruction
254 /// pointer, the constant pool being referenced, and the max displacement
255 /// allowed from the instruction to the CP. The HighWaterMark records the
256 /// highest basic block where a new CPEntry can be placed. To ensure this
257 /// pass terminates, the CP entries are initially placed at the end of the
258 /// function and then move monotonically to lower addresses. The
259 /// exception to this rule is when the current CP entry for a particular
260 /// CPUser is out of range, but there is another CP entry for the same
261 /// constant value in range. We want to use the existing in-range CP
262 /// entry, but if it later moves out of range, the search for new water
263 /// should resume where it left off. The HighWaterMark is used to record
264 /// that point.
265 struct CPUser {
266 MachineInstr *MI;
267 MachineInstr *CPEMI;
268 MachineBasicBlock *HighWaterMark;
269 private:
270 unsigned MaxDisp;
271 unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
272 // with different displacements
273 unsigned LongFormOpcode;
274 public:
275 bool NegOk;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000276 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000277 bool neg,
Reed Kotler0f007fc2013-11-05 08:14:14 +0000278 unsigned longformmaxdisp, unsigned longformopcode)
279 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
280 LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
Reed Kotler7ded5b62013-11-05 23:36:58 +0000281 NegOk(neg){
Reed Kotler0f007fc2013-11-05 08:14:14 +0000282 HighWaterMark = CPEMI->getParent();
283 }
284 /// getMaxDisp - Returns the maximum displacement supported by MI.
Reed Kotler0f007fc2013-11-05 08:14:14 +0000285 unsigned getMaxDisp() const {
286 unsigned xMaxDisp = ConstantIslandsSmallOffset?
287 ConstantIslandsSmallOffset: MaxDisp;
Reed Kotler7ded5b62013-11-05 23:36:58 +0000288 return xMaxDisp;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000289 }
Reed Kotler45c59272013-11-10 00:09:26 +0000290 void setMaxDisp(unsigned val) {
291 MaxDisp = val;
292 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000293 unsigned getLongFormMaxDisp() const {
Reed Kotler7ded5b62013-11-05 23:36:58 +0000294 return LongFormMaxDisp;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000295 }
296 unsigned getLongFormOpcode() const {
297 return LongFormOpcode;
298 }
299 };
300
301 /// CPUsers - Keep track of all of the machine instructions that use various
302 /// constant pools and their max displacement.
303 std::vector<CPUser> CPUsers;
Reed Kotler91ae9822013-10-27 21:57:36 +0000304
305 /// CPEntry - One per constant pool entry, keeping the machine instruction
306 /// pointer, the constpool index, and the number of CPUser's which
307 /// reference this entry.
308 struct CPEntry {
309 MachineInstr *CPEMI;
310 unsigned CPI;
311 unsigned RefCount;
312 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
313 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
314 };
315
316 /// CPEntries - Keep track of all of the constant pool entry machine
317 /// instructions. For each original constpool index (i.e. those that
318 /// existed upon entry to this pass), it keeps a vector of entries.
319 /// Original elements are cloned as we go along; the clones are
320 /// put in the vector of the original element, but have distinct CPIs.
321 std::vector<std::vector<CPEntry> > CPEntries;
322
Reed Kotler0f007fc2013-11-05 08:14:14 +0000323 /// ImmBranch - One per immediate branch, keeping the machine instruction
324 /// pointer, conditional or unconditional, the max displacement,
325 /// and (if isCond is true) the corresponding unconditional branch
326 /// opcode.
327 struct ImmBranch {
328 MachineInstr *MI;
329 unsigned MaxDisp : 31;
330 bool isCond : 1;
331 int UncondBr;
332 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
333 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
334 };
335
336 /// ImmBranches - Keep track of all the immediate branch instructions.
337 ///
338 std::vector<ImmBranch> ImmBranches;
339
340 /// HasFarJump - True if any far jump instruction has been emitted during
341 /// the branch fix up pass.
342 bool HasFarJump;
343
344 const TargetMachine &TM;
345 bool IsPIC;
346 unsigned ABI;
347 const MipsSubtarget *STI;
Reed Kotler5c8ae092013-11-13 04:37:52 +0000348 const Mips16InstrInfo *TII;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000349 MipsFunctionInfo *MFI;
350 MachineFunction *MF;
351 MachineConstantPool *MCP;
352
353 unsigned PICLabelUId;
354 bool PrescannedForConstants;
355
356 void initPICLabelUId(unsigned UId) {
357 PICLabelUId = UId;
358 }
359
360
361 unsigned createPICLabelUId() {
362 return PICLabelUId++;
363 }
364
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000365 public:
366 static char ID;
367 MipsConstantIslands(TargetMachine &tm)
368 : MachineFunctionPass(ID), TM(tm),
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000369 IsPIC(TM.getRelocationModel() == Reloc::PIC_),
Reed Kotler91ae9822013-10-27 21:57:36 +0000370 ABI(TM.getSubtarget<MipsSubtarget>().getTargetABI()),
Reed Kotler0f007fc2013-11-05 08:14:14 +0000371 STI(&TM.getSubtarget<MipsSubtarget>()), MF(0), MCP(0),
372 PrescannedForConstants(false){}
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000373
374 virtual const char *getPassName() const {
375 return "Mips Constant Islands";
376 }
377
378 bool runOnMachineFunction(MachineFunction &F);
379
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();
387 void verify();
388
389 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000390 unsigned Disp, bool NegativeOK);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000391 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
392 const CPUser &U);
393
394 bool isLongFormOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
395 const CPUser &U);
396
397 void computeBlockSize(MachineBasicBlock *MBB);
398 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
399 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
400 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
401 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
402 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
403 int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
404 bool findAvailableWater(CPUser&U, unsigned UserOffset,
405 water_iterator &WaterIter);
406 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
407 MachineBasicBlock *&NewMBB);
408 bool handleConstantPoolUser(unsigned CPUserIndex);
409 void removeDeadCPEMI(MachineInstr *CPEMI);
410 bool removeUnusedCPEntries();
411 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
412 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
413 bool DoDump = false);
414 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
415 CPUser &U, unsigned &Growth);
416 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
417 bool fixupImmediateBr(ImmBranch &Br);
418 bool fixupConditionalBr(ImmBranch &Br);
419 bool fixupUnconditionalBr(ImmBranch &Br);
Reed Kotler91ae9822013-10-27 21:57:36 +0000420
421 void prescanForConstants();
422
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000423 private:
Reed Kotler91ae9822013-10-27 21:57:36 +0000424
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000425 };
426
427 char MipsConstantIslands::ID = 0;
428} // end of anonymous namespace
429
Reed Kotler0f007fc2013-11-05 08:14:14 +0000430
431bool MipsConstantIslands::isLongFormOffsetInRange
432 (unsigned UserOffset, unsigned TrialOffset,
433 const CPUser &U) {
434 return isOffsetInRange(UserOffset, TrialOffset,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000435 U.getLongFormMaxDisp(), U.NegOk);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000436}
437
438bool MipsConstantIslands::isOffsetInRange
439 (unsigned UserOffset, unsigned TrialOffset,
440 const CPUser &U) {
441 return isOffsetInRange(UserOffset, TrialOffset,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000442 U.getMaxDisp(), U.NegOk);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000443}
444/// print block size and offset information - debugging
445void MipsConstantIslands::dumpBBs() {
446 DEBUG({
447 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
448 const BasicBlockInfo &BBI = BBInfo[J];
449 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
Reed Kotler0f007fc2013-11-05 08:14:14 +0000450 << format(" size=%#x\n", BBInfo[J].Size);
451 }
452 });
453}
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000454/// createMipsLongBranchPass - Returns a pass that converts branches to long
455/// branches.
456FunctionPass *llvm::createMipsConstantIslandPass(MipsTargetMachine &tm) {
457 return new MipsConstantIslands(tm);
458}
459
Reed Kotler91ae9822013-10-27 21:57:36 +0000460bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
Reed Kotler1595f362013-04-09 19:46:01 +0000461 // The intention is for this to be a mips16 only pass for now
462 // FIXME:
Reed Kotler91ae9822013-10-27 21:57:36 +0000463 MF = &mf;
464 MCP = mf.getConstantPool();
465 DEBUG(dbgs() << "constant island machine function " << "\n");
466 if (!TM.getSubtarget<MipsSubtarget>().inMips16Mode() ||
467 !MipsSubtarget::useConstantIslands()) {
468 return false;
469 }
Reed Kotler5c8ae092013-11-13 04:37:52 +0000470 TII = (const Mips16InstrInfo*)MF->getTarget().getInstrInfo();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000471 MFI = MF->getInfo<MipsFunctionInfo>();
Reed Kotler91ae9822013-10-27 21:57:36 +0000472 DEBUG(dbgs() << "constant island processing " << "\n");
473 //
474 // will need to make predermination if there is any constants we need to
475 // put in constant islands. TBD.
476 //
Reed Kotler0f007fc2013-11-05 08:14:14 +0000477 if (!PrescannedForConstants) prescanForConstants();
Reed Kotler91ae9822013-10-27 21:57:36 +0000478
Reed Kotler0f007fc2013-11-05 08:14:14 +0000479 HasFarJump = false;
Reed Kotler91ae9822013-10-27 21:57:36 +0000480 // This pass invalidates liveness information when it splits basic blocks.
481 MF->getRegInfo().invalidateLiveness();
482
483 // Renumber all of the machine basic blocks in the function, guaranteeing that
484 // the numbers agree with the position of the block in the function.
485 MF->RenumberBlocks();
486
Reed Kotler0f007fc2013-11-05 08:14:14 +0000487 bool MadeChange = false;
488
Reed Kotler91ae9822013-10-27 21:57:36 +0000489 // Perform the initial placement of the constant pool entries. To start with,
490 // we put them all at the end of the function.
491 std::vector<MachineInstr*> CPEMIs;
492 if (!MCP->isEmpty())
493 doInitialPlacement(CPEMIs);
494
Reed Kotler0f007fc2013-11-05 08:14:14 +0000495 /// The next UID to take is the first unused one.
496 initPICLabelUId(CPEMIs.size());
497
498 // Do the initial scan of the function, building up information about the
499 // sizes of each block, the location of all the water, and finding all of the
500 // constant pool users.
501 initializeFunctionInfo(CPEMIs);
502 CPEMIs.clear();
503 DEBUG(dumpBBs());
504
505 /// Remove dead constant pool entries.
506 MadeChange |= removeUnusedCPEntries();
507
508 // Iteratively place constant pool entries and fix up branches until there
509 // is no change.
510 unsigned NoCPIters = 0, NoBRIters = 0;
511 (void)NoBRIters;
512 while (true) {
513 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
514 bool CPChange = false;
515 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
516 CPChange |= handleConstantPoolUser(i);
517 if (CPChange && ++NoCPIters > 30)
518 report_fatal_error("Constant Island pass failed to converge!");
519 DEBUG(dumpBBs());
520
521 // Clear NewWaterList now. If we split a block for branches, it should
522 // appear as "new water" for the next iteration of constant pool placement.
523 NewWaterList.clear();
524
525 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
526 bool BRChange = false;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000527 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
528 BRChange |= fixupImmediateBr(ImmBranches[i]);
529 if (BRChange && ++NoBRIters > 30)
530 report_fatal_error("Branch Fix Up pass failed to converge!");
531 DEBUG(dumpBBs());
Reed Kotler0f007fc2013-11-05 08:14:14 +0000532 if (!CPChange && !BRChange)
533 break;
534 MadeChange = true;
535 }
536
537 DEBUG(dbgs() << '\n'; dumpBBs());
538
539 BBInfo.clear();
540 WaterList.clear();
541 CPUsers.clear();
542 CPEntries.clear();
543 ImmBranches.clear();
544 return MadeChange;
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000545}
546
Reed Kotler91ae9822013-10-27 21:57:36 +0000547/// doInitialPlacement - Perform the initial placement of the constant pool
548/// entries. To start with, we put them all at the end of the function.
549void
550MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
551 // Create the basic block to hold the CPE's.
552 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
553 MF->push_back(BB);
554
555
556 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
557 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
558
559 // Mark the basic block as required by the const-pool.
560 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
561 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
562
563 // The function needs to be as aligned as the basic blocks. The linker may
564 // move functions around based on their alignment.
565 MF->ensureAlignment(BB->getAlignment());
566
567 // Order the entries in BB by descending alignment. That ensures correct
568 // alignment of all entries as long as BB is sufficiently aligned. Keep
569 // track of the insertion point for each alignment. We are going to bucket
570 // sort the entries as they are created.
571 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
572
573 // Add all of the constants from the constant pool to the end block, use an
574 // identity mapping of CPI's to CPE's.
575 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
576
577 const DataLayout &TD = *MF->getTarget().getDataLayout();
578 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
579 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
580 assert(Size >= 4 && "Too small constant pool entry");
581 unsigned Align = CPs[i].getAlignment();
582 assert(isPowerOf2_32(Align) && "Invalid alignment");
583 // Verify that all constant pool entries are a multiple of their alignment.
584 // If not, we would have to pad them out so that instructions stay aligned.
585 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
586
587 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
588 unsigned LogAlign = Log2_32(Align);
589 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
590
591 MachineInstr *CPEMI =
592 BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
593 .addImm(i).addConstantPoolIndex(i).addImm(Size);
594
595 CPEMIs.push_back(CPEMI);
596
597 // Ensure that future entries with higher alignment get inserted before
598 // CPEMI. This is bucket sort with iterators.
599 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
600 if (InsPoint[a] == InsAt)
601 InsPoint[a] = CPEMI;
602 // Add a new CPEntry, but no corresponding CPUser yet.
603 std::vector<CPEntry> CPEs;
604 CPEs.push_back(CPEntry(CPEMI, i));
605 CPEntries.push_back(CPEs);
606 ++NumCPEs;
607 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
608 << Size << ", align = " << Align <<'\n');
609 }
610 DEBUG(BB->dump());
611}
612
Reed Kotler0f007fc2013-11-05 08:14:14 +0000613/// BBHasFallthrough - Return true if the specified basic block can fallthrough
614/// into the block immediately after it.
615static bool BBHasFallthrough(MachineBasicBlock *MBB) {
616 // Get the next machine basic block in the function.
617 MachineFunction::iterator MBBI = MBB;
618 // Can't fall off end of function.
619 if (llvm::next(MBBI) == MBB->getParent()->end())
620 return false;
621
622 MachineBasicBlock *NextBB = llvm::next(MBBI);
623 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
624 E = MBB->succ_end(); I != E; ++I)
625 if (*I == NextBB)
626 return true;
627
628 return false;
629}
630
631/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
632/// look up the corresponding CPEntry.
633MipsConstantIslands::CPEntry
634*MipsConstantIslands::findConstPoolEntry(unsigned CPI,
635 const MachineInstr *CPEMI) {
636 std::vector<CPEntry> &CPEs = CPEntries[CPI];
637 // Number of entries per constpool index should be small, just do a
638 // linear search.
639 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
640 if (CPEs[i].CPEMI == CPEMI)
641 return &CPEs[i];
642 }
643 return NULL;
644}
645
646/// getCPELogAlign - Returns the required alignment of the constant pool entry
647/// represented by CPEMI. Alignment is measured in log2(bytes) units.
648unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
649 assert(CPEMI && CPEMI->getOpcode() == Mips::CONSTPOOL_ENTRY);
650
651 // Everything is 4-byte aligned unless AlignConstantIslands is set.
652 if (!AlignConstantIslands)
653 return 2;
654
655 unsigned CPI = CPEMI->getOperand(1).getIndex();
656 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
657 unsigned Align = MCP->getConstants()[CPI].getAlignment();
658 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
659 return Log2_32(Align);
660}
661
662/// initializeFunctionInfo - Do the initial scan of the function, building up
663/// information about the sizes of each block, the location of all the water,
664/// and finding all of the constant pool users.
665void MipsConstantIslands::
666initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
667 BBInfo.clear();
668 BBInfo.resize(MF->getNumBlockIDs());
669
670 // First thing, compute the size of all basic blocks, and see if the function
671 // has any inline assembly in it. If so, we have to be conservative about
672 // alignment assumptions, as we don't know for sure the size of any
673 // instructions in the inline assembly.
674 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
675 computeBlockSize(I);
676
Reed Kotler0f007fc2013-11-05 08:14:14 +0000677
678 // Compute block offsets.
679 adjustBBOffsetsAfter(MF->begin());
680
681 // Now go back through the instructions and build up our data structures.
682 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
683 MBBI != E; ++MBBI) {
684 MachineBasicBlock &MBB = *MBBI;
685
686 // If this block doesn't fall through into the next MBB, then this is
687 // 'water' that a constant pool island could be placed.
688 if (!BBHasFallthrough(&MBB))
689 WaterList.push_back(&MBB);
690 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
691 I != E; ++I) {
692 if (I->isDebugValue())
693 continue;
694
695 int Opc = I->getOpcode();
696 if (I->isBranch()) {
697 bool isCond = false;
698 unsigned Bits = 0;
699 unsigned Scale = 1;
700 int UOpc = Opc;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000701 switch (Opc) {
702 default:
Reed Kotler4b7afe52013-11-13 23:52:18 +0000703 continue; // Ignore other branches for now
704 case Mips::Bimm16:
705 Bits = 11;
706 Scale = 2;
707 isCond = false;
708 break;
709 case Mips::BimmX16:
710 Bits = 16;
711 Scale = 2;
712 isCond = false;
Reed Kotler0d409e22013-11-28 00:56:37 +0000713 break;
714 case Mips::BeqzRxImm16:
715 Bits = 8;
716 Scale = 2;
717 isCond = true;
718 break;
719 case Mips::BeqzRxImmX16:
720 Bits = 16;
721 Scale = 2;
722 isCond = true;
723 break;
724 case Mips::BnezRxImm16:
725 Bits = 8;
726 Scale = 2;
727 isCond = true;
728 break;
729 case Mips::BnezRxImmX16:
730 Bits = 16;
731 Scale = 2;
732 isCond = true;
733 break;
734 case Mips::Bteqz16:
735 Bits = 8;
736 Scale = 2;
737 isCond = true;
738 break;
739 case Mips::BteqzX16:
740 Bits = 16;
741 Scale = 2;
742 isCond = true;
743 break;
744 case Mips::Btnez16:
745 Bits = 8;
746 Scale = 2;
747 isCond = true;
748 break;
749 case Mips::BtnezX16:
750 Bits = 16;
751 Scale = 2;
752 isCond = true;
753 break;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000754 }
755 // Record this immediate branch.
756 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
757 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Reed Kotler0f007fc2013-11-05 08:14:14 +0000758 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000759
760 if (Opc == Mips::CONSTPOOL_ENTRY)
761 continue;
762
763
764 // Scan the instructions for constant pool operands.
765 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
766 if (I->getOperand(op).isCPI()) {
767
768 // We found one. The addressing mode tells us the max displacement
769 // from the PC that this instruction permits.
770
771 // Basic size info comes from the TSFlags field.
772 unsigned Bits = 0;
773 unsigned Scale = 1;
774 bool NegOk = false;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000775 unsigned LongFormBits = 0;
776 unsigned LongFormScale = 0;
777 unsigned LongFormOpcode = 0;
778 switch (Opc) {
779 default:
780 llvm_unreachable("Unknown addressing mode for CP reference!");
781 case Mips::LwRxPcTcp16:
782 Bits = 8;
Reed Kotler3d7b33f2013-11-06 04:29:52 +0000783 Scale = 4;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000784 LongFormOpcode = Mips::LwRxPcTcpX16;
Reed Kotler45c59272013-11-10 00:09:26 +0000785 LongFormBits = 16;
786 LongFormScale = 1;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000787 break;
788 case Mips::LwRxPcTcpX16:
789 Bits = 16;
Reed Kotler3d7b33f2013-11-06 04:29:52 +0000790 Scale = 1;
791 NegOk = true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000792 break;
793 }
794 // Remember that this is a user of a CP entry.
795 unsigned CPI = I->getOperand(op).getIndex();
796 MachineInstr *CPEMI = CPEMIs[CPI];
797 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
798 unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
799 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000800 LongFormMaxOffs, LongFormOpcode));
Reed Kotler0f007fc2013-11-05 08:14:14 +0000801
802 // Increment corresponding CPEntry reference count.
803 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
804 assert(CPE && "Cannot find a corresponding CPEntry!");
805 CPE->RefCount++;
806
807 // Instructions can only use one CP entry, don't bother scanning the
808 // rest of the operands.
809 break;
810
811 }
812
813 }
814 }
815
816}
817
818/// computeBlockSize - Compute the size and some alignment information for MBB.
819/// This function updates BBInfo directly.
820void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
821 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
822 BBI.Size = 0;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000823
824 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
825 ++I)
826 BBI.Size += TII->GetInstSizeInBytes(I);
827
828}
829
830/// getOffsetOf - Return the current offset of the specified machine instruction
831/// from the start of the function. This offset changes as stuff is moved
832/// around inside the function.
833unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
834 MachineBasicBlock *MBB = MI->getParent();
835
836 // The offset is composed of two things: the sum of the sizes of all MBB's
837 // before this instruction's block, and the offset from the start of the block
838 // it is in.
839 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
840
841 // Sum instructions before MI in MBB.
842 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
843 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
844 Offset += TII->GetInstSizeInBytes(I);
845 }
846 return Offset;
847}
848
849/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
850/// ID.
851static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
852 const MachineBasicBlock *RHS) {
853 return LHS->getNumber() < RHS->getNumber();
854}
855
856/// updateForInsertedWaterBlock - When a block is newly inserted into the
857/// machine function, it upsets all of the block numbers. Renumber the blocks
858/// and update the arrays that parallel this numbering.
859void MipsConstantIslands::updateForInsertedWaterBlock
860 (MachineBasicBlock *NewBB) {
861 // Renumber the MBB's to keep them consecutive.
862 NewBB->getParent()->RenumberBlocks(NewBB);
863
864 // Insert an entry into BBInfo to align it properly with the (newly
865 // renumbered) block numbers.
866 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
867
868 // Next, update WaterList. Specifically, we need to add NewMBB as having
869 // available water after it.
870 water_iterator IP =
871 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
872 CompareMBBNumbers);
873 WaterList.insert(IP, NewBB);
874}
875
Reed Kotler0f007fc2013-11-05 08:14:14 +0000876unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
Reed Kotler0eb87392013-11-05 21:39:57 +0000877 return getOffsetOf(U.MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000878}
879
880/// Split the basic block containing MI into two blocks, which are joined by
881/// an unconditional branch. Update data structures and renumber blocks to
882/// account for this change and returns the newly created block.
883MachineBasicBlock *MipsConstantIslands::splitBlockBeforeInstr
884 (MachineInstr *MI) {
885 MachineBasicBlock *OrigBB = MI->getParent();
886
887 // Create a new MBB for the code after the OrigBB.
888 MachineBasicBlock *NewBB =
889 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
890 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
891 MF->insert(MBBI, NewBB);
892
893 // Splice the instructions starting with MI over to NewBB.
894 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
895
896 // Add an unconditional branch from OrigBB to NewBB.
897 // Note the new unconditional branch is not being recorded.
898 // There doesn't seem to be meaningful DebugInfo available; this doesn't
899 // correspond to anything in the source.
Reed Kotlerf0e69682013-11-12 02:27:12 +0000900 BuildMI(OrigBB, DebugLoc(), TII->get(Mips::Bimm16)).addMBB(NewBB);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000901 ++NumSplit;
902
903 // Update the CFG. All succs of OrigBB are now succs of NewBB.
904 NewBB->transferSuccessors(OrigBB);
905
906 // OrigBB branches to NewBB.
907 OrigBB->addSuccessor(NewBB);
908
909 // Update internal data structures to account for the newly inserted MBB.
910 // This is almost the same as updateForInsertedWaterBlock, except that
911 // the Water goes after OrigBB, not NewBB.
912 MF->RenumberBlocks(NewBB);
913
914 // Insert an entry into BBInfo to align it properly with the (newly
915 // renumbered) block numbers.
916 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
917
918 // Next, update WaterList. Specifically, we need to add OrigMBB as having
919 // available water after it (but not if it's already there, which happens
920 // when splitting before a conditional branch that is followed by an
921 // unconditional branch - in that case we want to insert NewBB).
922 water_iterator IP =
923 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
924 CompareMBBNumbers);
925 MachineBasicBlock* WaterBB = *IP;
926 if (WaterBB == OrigBB)
927 WaterList.insert(llvm::next(IP), NewBB);
928 else
929 WaterList.insert(IP, OrigBB);
930 NewWaterList.insert(OrigBB);
931
932 // Figure out how large the OrigBB is. As the first half of the original
933 // block, it cannot contain a tablejump. The size includes
934 // the new jump we added. (It should be possible to do this without
935 // recounting everything, but it's very confusing, and this is rarely
936 // executed.)
937 computeBlockSize(OrigBB);
938
939 // Figure out how large the NewMBB is. As the second half of the original
940 // block, it may contain a tablejump.
941 computeBlockSize(NewBB);
942
943 // All BBOffsets following these blocks must be modified.
944 adjustBBOffsetsAfter(OrigBB);
945
946 return NewBB;
947}
948
949
950
951/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
952/// reference) is within MaxDisp of TrialOffset (a proposed location of a
953/// constant pool entry).
Reed Kotler0f007fc2013-11-05 08:14:14 +0000954bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
955 unsigned TrialOffset, unsigned MaxDisp,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000956 bool NegativeOK) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000957 if (UserOffset <= TrialOffset) {
958 // User before the Trial.
959 if (TrialOffset - UserOffset <= MaxDisp)
960 return true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000961 } else if (NegativeOK) {
962 if (UserOffset - TrialOffset <= MaxDisp)
963 return true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000964 }
965 return false;
966}
967
968/// isWaterInRange - Returns true if a CPE placed after the specified
969/// Water (a basic block) will be in range for the specific MI.
970///
971/// Compute how much the function will grow by inserting a CPE after Water.
972bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
973 MachineBasicBlock* Water, CPUser &U,
974 unsigned &Growth) {
975 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
976 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
977 unsigned NextBlockOffset, NextBlockAlignment;
978 MachineFunction::const_iterator NextBlock = Water;
979 if (++NextBlock == MF->end()) {
980 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
981 NextBlockAlignment = 0;
982 } else {
983 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
984 NextBlockAlignment = NextBlock->getAlignment();
985 }
986 unsigned Size = U.CPEMI->getOperand(2).getImm();
987 unsigned CPEEnd = CPEOffset + Size;
988
989 // The CPE may be able to hide in the alignment padding before the next
990 // block. It may also cause more padding to be required if it is more aligned
991 // that the next block.
992 if (CPEEnd > NextBlockOffset) {
993 Growth = CPEEnd - NextBlockOffset;
994 // Compute the padding that would go at the end of the CPE to align the next
995 // block.
996 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
997
998 // If the CPE is to be inserted before the instruction, that will raise
999 // the offset of the instruction. Also account for unknown alignment padding
1000 // in blocks between CPE and the user.
1001 if (CPEOffset < UserOffset)
Reed Kotler7ded5b62013-11-05 23:36:58 +00001002 UserOffset += Growth;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001003 } else
1004 // CPE fits in existing padding.
1005 Growth = 0;
1006
1007 return isOffsetInRange(UserOffset, CPEOffset, U);
1008}
1009
1010/// isCPEntryInRange - Returns true if the distance between specific MI and
1011/// specific ConstPool entry instruction can fit in MI's displacement field.
1012bool MipsConstantIslands::isCPEntryInRange
1013 (MachineInstr *MI, unsigned UserOffset,
1014 MachineInstr *CPEMI, unsigned MaxDisp,
1015 bool NegOk, bool DoDump) {
1016 unsigned CPEOffset = getOffsetOf(CPEMI);
1017
1018 if (DoDump) {
1019 DEBUG({
1020 unsigned Block = MI->getParent()->getNumber();
1021 const BasicBlockInfo &BBI = BBInfo[Block];
1022 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1023 << " max delta=" << MaxDisp
1024 << format(" insn address=%#x", UserOffset)
1025 << " in BB#" << Block << ": "
1026 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1027 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1028 int(CPEOffset-UserOffset));
1029 });
1030 }
1031
1032 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1033}
1034
1035#ifndef NDEBUG
1036/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1037/// unconditionally branches to its only successor.
1038static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1039 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1040 return false;
1041 MachineBasicBlock *Succ = *MBB->succ_begin();
1042 MachineBasicBlock *Pred = *MBB->pred_begin();
1043 MachineInstr *PredMI = &Pred->back();
Reed Kotlerf0e69682013-11-12 02:27:12 +00001044 if (PredMI->getOpcode() == Mips::Bimm16)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001045 return PredMI->getOperand(0).getMBB() == Succ;
1046 return false;
1047}
1048#endif
1049
1050void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1051 unsigned BBNum = BB->getNumber();
1052 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1053 // Get the offset and known bits at the end of the layout predecessor.
1054 // Include the alignment of the current block.
Reed Kotler7ded5b62013-11-05 23:36:58 +00001055 unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001056 BBInfo[i].Offset = Offset;
1057 }
1058}
1059
1060/// decrementCPEReferenceCount - find the constant pool entry with index CPI
1061/// and instruction CPEMI, and decrement its refcount. If the refcount
1062/// becomes 0 remove the entry and instruction. Returns true if we removed
1063/// the entry, false if we didn't.
1064
1065bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1066 MachineInstr *CPEMI) {
1067 // Find the old entry. Eliminate it if it is no longer used.
1068 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1069 assert(CPE && "Unexpected!");
1070 if (--CPE->RefCount == 0) {
1071 removeDeadCPEMI(CPEMI);
1072 CPE->CPEMI = NULL;
1073 --NumCPEs;
1074 return true;
1075 }
1076 return false;
1077}
1078
1079/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1080/// if not, see if an in-range clone of the CPE is in range, and if so,
1081/// change the data structures so the user references the clone. Returns:
1082/// 0 = no existing entry found
1083/// 1 = entry found, and there were no code insertions or deletions
1084/// 2 = entry found, and there were code insertions or deletions
1085int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1086{
1087 MachineInstr *UserMI = U.MI;
1088 MachineInstr *CPEMI = U.CPEMI;
1089
1090 // Check to see if the CPE is already in-range.
1091 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1092 true)) {
1093 DEBUG(dbgs() << "In range\n");
1094 return 1;
1095 }
1096
1097 // No. Look for previously created clones of the CPE that are in range.
1098 unsigned CPI = CPEMI->getOperand(1).getIndex();
1099 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1100 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1101 // We already tried this one
1102 if (CPEs[i].CPEMI == CPEMI)
1103 continue;
1104 // Removing CPEs can leave empty entries, skip
1105 if (CPEs[i].CPEMI == NULL)
1106 continue;
1107 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1108 U.NegOk)) {
1109 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1110 << CPEs[i].CPI << "\n");
1111 // Point the CPUser node to the replacement
1112 U.CPEMI = CPEs[i].CPEMI;
1113 // Change the CPI in the instruction operand to refer to the clone.
1114 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1115 if (UserMI->getOperand(j).isCPI()) {
1116 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1117 break;
1118 }
1119 // Adjust the refcount of the clone...
1120 CPEs[i].RefCount++;
1121 // ...and the original. If we didn't remove the old entry, none of the
1122 // addresses changed, so we don't need another pass.
1123 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1124 }
1125 }
1126 return 0;
1127}
1128
1129/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1130/// This version checks if the longer form of the instruction can be used to
1131/// to satisfy things.
1132/// if not, see if an in-range clone of the CPE is in range, and if so,
1133/// change the data structures so the user references the clone. Returns:
1134/// 0 = no existing entry found
1135/// 1 = entry found, and there were no code insertions or deletions
1136/// 2 = entry found, and there were code insertions or deletions
1137int MipsConstantIslands::findLongFormInRangeCPEntry
1138 (CPUser& U, unsigned UserOffset)
1139{
1140 MachineInstr *UserMI = U.MI;
1141 MachineInstr *CPEMI = U.CPEMI;
1142
1143 // Check to see if the CPE is already in-range.
1144 if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
1145 U.getLongFormMaxDisp(), U.NegOk,
1146 true)) {
1147 DEBUG(dbgs() << "In range\n");
1148 UserMI->setDesc(TII->get(U.getLongFormOpcode()));
Reed Kotler45c59272013-11-10 00:09:26 +00001149 U.setMaxDisp(U.getLongFormMaxDisp());
Reed Kotler0f007fc2013-11-05 08:14:14 +00001150 return 2; // instruction is longer length now
1151 }
1152
1153 // No. Look for previously created clones of the CPE that are in range.
1154 unsigned CPI = CPEMI->getOperand(1).getIndex();
1155 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1156 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1157 // We already tried this one
1158 if (CPEs[i].CPEMI == CPEMI)
1159 continue;
1160 // Removing CPEs can leave empty entries, skip
1161 if (CPEs[i].CPEMI == NULL)
1162 continue;
1163 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
1164 U.getLongFormMaxDisp(), U.NegOk)) {
1165 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1166 << CPEs[i].CPI << "\n");
1167 // Point the CPUser node to the replacement
1168 U.CPEMI = CPEs[i].CPEMI;
1169 // Change the CPI in the instruction operand to refer to the clone.
1170 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1171 if (UserMI->getOperand(j).isCPI()) {
1172 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1173 break;
1174 }
1175 // Adjust the refcount of the clone...
1176 CPEs[i].RefCount++;
1177 // ...and the original. If we didn't remove the old entry, none of the
1178 // addresses changed, so we don't need another pass.
1179 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1180 }
1181 }
1182 return 0;
1183}
1184
1185/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1186/// the specific unconditional branch instruction.
1187static inline unsigned getUnconditionalBrDisp(int Opc) {
1188 switch (Opc) {
Reed Kotlerf0e69682013-11-12 02:27:12 +00001189 case Mips::Bimm16:
1190 return ((1<<10)-1)*2;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001191 case Mips::BimmX16:
1192 return ((1<<16)-1)*2;
1193 default:
1194 break;
1195 }
1196 return ((1<<16)-1)*2;
1197}
1198
1199/// findAvailableWater - Look for an existing entry in the WaterList in which
1200/// we can place the CPE referenced from U so it's within range of U's MI.
1201/// Returns true if found, false if not. If it returns true, WaterIter
Reed Kotler4d0313d2013-11-05 12:04:37 +00001202/// is set to the WaterList entry.
1203/// To ensure that this pass
Reed Kotler0f007fc2013-11-05 08:14:14 +00001204/// terminates, the CPE location for a particular CPUser is only allowed to
1205/// move to a lower address, so search backward from the end of the list and
1206/// prefer the first water that is in range.
1207bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1208 water_iterator &WaterIter) {
1209 if (WaterList.empty())
1210 return false;
1211
1212 unsigned BestGrowth = ~0u;
1213 for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1214 --IP) {
1215 MachineBasicBlock* WaterBB = *IP;
1216 // Check if water is in range and is either at a lower address than the
1217 // current "high water mark" or a new water block that was created since
1218 // the previous iteration by inserting an unconditional branch. In the
1219 // latter case, we want to allow resetting the high water mark back to
1220 // this new water since we haven't seen it before. Inserting branches
1221 // should be relatively uncommon and when it does happen, we want to be
1222 // sure to take advantage of it for all the CPEs near that block, so that
1223 // we don't insert more branches than necessary.
1224 unsigned Growth;
1225 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1226 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1227 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1228 // This is the least amount of required padding seen so far.
1229 BestGrowth = Growth;
1230 WaterIter = IP;
1231 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1232 << " Growth=" << Growth << '\n');
1233
1234 // Keep looking unless it is perfect.
1235 if (BestGrowth == 0)
1236 return true;
1237 }
1238 if (IP == B)
1239 break;
1240 }
1241 return BestGrowth != ~0u;
1242}
1243
1244/// createNewWater - No existing WaterList entry will work for
1245/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1246/// block is used if in range, and the conditional branch munged so control
1247/// flow is correct. Otherwise the block is split to create a hole with an
1248/// unconditional branch around it. In either case NewMBB is set to a
1249/// block following which the new island can be inserted (the WaterList
1250/// is not adjusted).
1251void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1252 unsigned UserOffset,
1253 MachineBasicBlock *&NewMBB) {
1254 CPUser &U = CPUsers[CPUserIndex];
1255 MachineInstr *UserMI = U.MI;
1256 MachineInstr *CPEMI = U.CPEMI;
1257 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1258 MachineBasicBlock *UserMBB = UserMI->getParent();
1259 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1260
1261 // If the block does not end in an unconditional branch already, and if the
Reed Kotler4d0313d2013-11-05 12:04:37 +00001262 // end of the block is within range, make new water there.
Reed Kotler0f007fc2013-11-05 08:14:14 +00001263 if (BBHasFallthrough(UserMBB)) {
1264 // Size of branch to insert.
1265 unsigned Delta = 2;
1266 // Compute the offset where the CPE will begin.
1267 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1268
1269 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1270 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1271 << format(", expected CPE offset %#x\n", CPEOffset));
1272 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1273 // Add an unconditional branch from UserMBB to fallthrough block. Record
1274 // it for branch lengthening; this new branch will not get out of range,
1275 // but if the preceding conditional branch is out of range, the targets
1276 // will be exchanged, and the altered branch may be out of range, so the
1277 // machinery has to know about it.
Reed Kotlerf0e69682013-11-12 02:27:12 +00001278 int UncondBr = Mips::Bimm16;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001279 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1280 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1281 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1282 MaxDisp, false, UncondBr));
1283 BBInfo[UserMBB->getNumber()].Size += Delta;
1284 adjustBBOffsetsAfter(UserMBB);
1285 return;
1286 }
1287 }
1288
Reed Kotler4d0313d2013-11-05 12:04:37 +00001289 // What a big block. Find a place within the block to split it.
Reed Kotler0f007fc2013-11-05 08:14:14 +00001290
1291 // Try to split the block so it's fully aligned. Compute the latest split
1292 // point where we can add a 4-byte branch instruction, and then align to
1293 // LogAlign which is the largest possible alignment in the function.
1294 unsigned LogAlign = MF->getAlignment();
1295 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
Reed Kotler7ded5b62013-11-05 23:36:58 +00001296 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001297 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1298 BaseInsertOffset));
1299
1300 // The 4 in the following is for the unconditional branch we'll be inserting
Reed Kotler4d0313d2013-11-05 12:04:37 +00001301 // Alignment of the island is handled
Reed Kotler0f007fc2013-11-05 08:14:14 +00001302 // inside isOffsetInRange.
1303 BaseInsertOffset -= 4;
1304
1305 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
Reed Kotler7ded5b62013-11-05 23:36:58 +00001306 << " la=" << LogAlign << '\n');
Reed Kotler0f007fc2013-11-05 08:14:14 +00001307
1308 // This could point off the end of the block if we've already got constant
1309 // pool entries following this block; only the last one is in the water list.
1310 // Back past any possible branches (allow for a conditional and a maximally
1311 // long unconditional).
1312 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Reed Kotler7ded5b62013-11-05 23:36:58 +00001313 BaseInsertOffset = UserBBI.postOffset() - 8;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001314 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1315 }
Reed Kotler7ded5b62013-11-05 23:36:58 +00001316 unsigned EndInsertOffset = BaseInsertOffset + 4 +
Reed Kotler0f007fc2013-11-05 08:14:14 +00001317 CPEMI->getOperand(2).getImm();
1318 MachineBasicBlock::iterator MI = UserMI;
1319 ++MI;
1320 unsigned CPUIndex = CPUserIndex+1;
1321 unsigned NumCPUsers = CPUsers.size();
1322 //MachineInstr *LastIT = 0;
1323 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1324 Offset < BaseInsertOffset;
1325 Offset += TII->GetInstSizeInBytes(MI),
1326 MI = llvm::next(MI)) {
1327 assert(MI != UserMBB->end() && "Fell off end of block");
1328 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1329 CPUser &U = CPUsers[CPUIndex];
1330 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1331 // Shift intertion point by one unit of alignment so it is within reach.
1332 BaseInsertOffset -= 1u << LogAlign;
1333 EndInsertOffset -= 1u << LogAlign;
1334 }
1335 // This is overly conservative, as we don't account for CPEMIs being
1336 // reused within the block, but it doesn't matter much. Also assume CPEs
1337 // are added in order with alignment padding. We may eventually be able
1338 // to pack the aligned CPEs better.
1339 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1340 CPUIndex++;
1341 }
1342 }
1343
1344 --MI;
1345 NewMBB = splitBlockBeforeInstr(MI);
1346}
1347
1348/// handleConstantPoolUser - Analyze the specified user, checking to see if it
1349/// is out-of-range. If so, pick up the constant pool value and move it some
1350/// place in-range. Return true if we changed any addresses (thus must run
1351/// another pass of branch lengthening), false otherwise.
1352bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1353 CPUser &U = CPUsers[CPUserIndex];
1354 MachineInstr *UserMI = U.MI;
1355 MachineInstr *CPEMI = U.CPEMI;
1356 unsigned CPI = CPEMI->getOperand(1).getIndex();
1357 unsigned Size = CPEMI->getOperand(2).getImm();
1358 // Compute this only once, it's expensive.
1359 unsigned UserOffset = getUserOffset(U);
1360
1361 // See if the current entry is within range, or there is a clone of it
1362 // in range.
1363 int result = findInRangeCPEntry(U, UserOffset);
1364 if (result==1) return false;
1365 else if (result==2) return true;
1366
1367
1368 // Look for water where we can place this CPE.
1369 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1370 MachineBasicBlock *NewMBB;
1371 water_iterator IP;
1372 if (findAvailableWater(U, UserOffset, IP)) {
1373 DEBUG(dbgs() << "Found water in range\n");
1374 MachineBasicBlock *WaterBB = *IP;
1375
1376 // If the original WaterList entry was "new water" on this iteration,
1377 // propagate that to the new island. This is just keeping NewWaterList
1378 // updated to match the WaterList, which will be updated below.
1379 if (NewWaterList.erase(WaterBB))
1380 NewWaterList.insert(NewIsland);
1381
1382 // The new CPE goes before the following block (NewMBB).
1383 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1384
1385 } else {
1386 // No water found.
1387 // we first see if a longer form of the instrucion could have reached
1388 // the constant. in that case we won't bother to split
Reed Kotler45c59272013-11-10 00:09:26 +00001389 if (!NoLoadRelaxation) {
1390 result = findLongFormInRangeCPEntry(U, UserOffset);
1391 if (result != 0) return true;
1392 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001393 DEBUG(dbgs() << "No water found\n");
1394 createNewWater(CPUserIndex, UserOffset, NewMBB);
1395
1396 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1397 // called while handling branches so that the water will be seen on the
1398 // next iteration for constant pools, but in this context, we don't want
1399 // it. Check for this so it will be removed from the WaterList.
1400 // Also remove any entry from NewWaterList.
1401 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1402 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1403 if (IP != WaterList.end())
1404 NewWaterList.erase(WaterBB);
1405
1406 // We are adding new water. Update NewWaterList.
1407 NewWaterList.insert(NewIsland);
1408 }
1409
1410 // Remove the original WaterList entry; we want subsequent insertions in
1411 // this vicinity to go after the one we're about to insert. This
1412 // considerably reduces the number of times we have to move the same CPE
1413 // more than once and is also important to ensure the algorithm terminates.
1414 if (IP != WaterList.end())
1415 WaterList.erase(IP);
1416
1417 // Okay, we know we can put an island before NewMBB now, do it!
1418 MF->insert(NewMBB, NewIsland);
1419
1420 // Update internal data structures to account for the newly inserted MBB.
1421 updateForInsertedWaterBlock(NewIsland);
1422
1423 // Decrement the old entry, and remove it if refcount becomes 0.
1424 decrementCPEReferenceCount(CPI, CPEMI);
1425
Reed Kotlerd3b28eb2013-11-24 02:53:09 +00001426 // No existing clone of this CPE is within range.
1427 // We will be generating a new clone. Get a UID for it.
1428 unsigned ID = createPICLabelUId();
1429
Reed Kotler0f007fc2013-11-05 08:14:14 +00001430 // Now that we have an island to add the CPE to, clone the original CPE and
1431 // add it to the island.
1432 U.HighWaterMark = NewIsland;
1433 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1434 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1435 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1436 ++NumCPEs;
1437
1438 // Mark the basic block as aligned as required by the const-pool entry.
1439 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1440
1441 // Increase the size of the island block to account for the new entry.
1442 BBInfo[NewIsland->getNumber()].Size += Size;
1443 adjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
1444
Reed Kotlerd3b28eb2013-11-24 02:53:09 +00001445
Reed Kotler0f007fc2013-11-05 08:14:14 +00001446
1447 // Finally, change the CPI in the instruction operand to be ID.
1448 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1449 if (UserMI->getOperand(i).isCPI()) {
1450 UserMI->getOperand(i).setIndex(ID);
1451 break;
1452 }
1453
1454 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1455 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1456
1457 return true;
1458}
1459
1460/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1461/// sizes and offsets of impacted basic blocks.
1462void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1463 MachineBasicBlock *CPEBB = CPEMI->getParent();
1464 unsigned Size = CPEMI->getOperand(2).getImm();
1465 CPEMI->eraseFromParent();
1466 BBInfo[CPEBB->getNumber()].Size -= Size;
1467 // All succeeding offsets have the current size value added in, fix this.
1468 if (CPEBB->empty()) {
1469 BBInfo[CPEBB->getNumber()].Size = 0;
1470
1471 // This block no longer needs to be aligned.
1472 CPEBB->setAlignment(0);
1473 } else
1474 // Entries are sorted by descending alignment, so realign from the front.
1475 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1476
1477 adjustBBOffsetsAfter(CPEBB);
1478 // An island has only one predecessor BB and one successor BB. Check if
1479 // this BB's predecessor jumps directly to this BB's successor. This
1480 // shouldn't happen currently.
1481 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1482 // FIXME: remove the empty blocks after all the work is done?
1483}
1484
1485/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1486/// are zero.
1487bool MipsConstantIslands::removeUnusedCPEntries() {
1488 unsigned MadeChange = false;
1489 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1490 std::vector<CPEntry> &CPEs = CPEntries[i];
1491 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1492 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1493 removeDeadCPEMI(CPEs[j].CPEMI);
1494 CPEs[j].CPEMI = NULL;
1495 MadeChange = true;
1496 }
1497 }
1498 }
1499 return MadeChange;
1500}
1501
1502/// isBBInRange - Returns true if the distance between specific MI and
1503/// specific BB can fit in MI's displacement field.
1504bool MipsConstantIslands::isBBInRange
1505 (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
1506
1507unsigned PCAdj = 4;
1508
1509 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1510 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1511
1512 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1513 << " from BB#" << MI->getParent()->getNumber()
1514 << " max delta=" << MaxDisp
1515 << " from " << getOffsetOf(MI) << " to " << DestOffset
1516 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1517
1518 if (BrOffset <= DestOffset) {
1519 // Branch before the Dest.
1520 if (DestOffset-BrOffset <= MaxDisp)
1521 return true;
1522 } else {
1523 if (BrOffset-DestOffset <= MaxDisp)
1524 return true;
1525 }
1526 return false;
1527}
1528
1529/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1530/// away to fit in its displacement field.
1531bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1532 MachineInstr *MI = Br.MI;
Reed Kotler0d409e22013-11-28 00:56:37 +00001533 unsigned TargetOperand = branchTargetOperand(MI);
1534 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001535
1536 // Check to see if the DestBB is already in-range.
1537 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1538 return false;
1539
1540 if (!Br.isCond)
1541 return fixupUnconditionalBr(Br);
1542 return fixupConditionalBr(Br);
1543}
1544
1545/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1546/// too far away to fit in its displacement field. If the LR register has been
1547/// spilled in the epilogue, then we can use BL to implement a far jump.
1548/// Otherwise, add an intermediate branch instruction to a branch.
1549bool
1550MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1551 MachineInstr *MI = Br.MI;
1552 MachineBasicBlock *MBB = MI->getParent();
Reed Kotler2fc05be2013-11-21 05:13:23 +00001553 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001554 // Use BL to implement far jump.
Reed Kotler2fc05be2013-11-21 05:13:23 +00001555 unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2;
1556 if (isBBInRange(MI, DestBB, BimmX16MaxDisp)) {
1557 Br.MaxDisp = BimmX16MaxDisp;
1558 MI->setDesc(TII->get(Mips::BimmX16));
1559 }
1560 else {
1561 // need to give the math a more careful look here
1562 // this is really a segment address and not
1563 // a PC relative address. FIXME. But I think that
1564 // just reducing the bits by 1 as I've done is correct.
1565 // The basic block we are branching too much be longword aligned.
1566 // we know that RA is saved because we always save it right now.
1567 // this requirement will be relaxed later but we also have an alternate
1568 // way to implement this that I will implement that does not need jal.
1569 // We should have a way to back out this alignment restriction if we "can" later.
1570 // but it is not harmful.
1571 //
1572 DestBB->setAlignment(2);
1573 Br.MaxDisp = ((1<<24)-1) * 2;
Reed Kotlerad450f22013-11-29 22:32:56 +00001574 MI->setDesc(TII->get(Mips::JalB16));
Reed Kotler2fc05be2013-11-21 05:13:23 +00001575 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001576 BBInfo[MBB->getNumber()].Size += 2;
1577 adjustBBOffsetsAfter(MBB);
1578 HasFarJump = true;
1579 ++NumUBrFixed;
1580
1581 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1582
1583 return true;
1584}
1585
Reed Kotler0d409e22013-11-28 00:56:37 +00001586
Reed Kotler0f007fc2013-11-05 08:14:14 +00001587/// fixupConditionalBr - Fix up a conditional branch whose destination is too
1588/// far away to fit in its displacement field. It is converted to an inverse
1589/// conditional branch + an unconditional branch to the destination.
1590bool
1591MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1592 MachineInstr *MI = Br.MI;
Reed Kotler0d409e22013-11-28 00:56:37 +00001593 unsigned TargetOperand = branchTargetOperand(MI);
1594 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1595 unsigned Opcode = MI->getOpcode();
1596 unsigned LongFormOpcode = longformBranchOpcode(Opcode);
1597 unsigned LongFormMaxOff = branchMaxOffsets(LongFormOpcode);
1598
1599 // Check to see if the DestBB is already in-range.
1600 if (isBBInRange(MI, DestBB, LongFormMaxOff)) {
1601 Br.MaxDisp = LongFormMaxOff;
1602 MI->setDesc(TII->get(LongFormOpcode));
1603 return true;
1604 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001605
1606 // Add an unconditional branch to the destination and invert the branch
1607 // condition to jump over it:
Reed Kotlerad450f22013-11-29 22:32:56 +00001608 // bteqz L1
Reed Kotler0f007fc2013-11-05 08:14:14 +00001609 // =>
Reed Kotlerad450f22013-11-29 22:32:56 +00001610 // bnez L2
Reed Kotler0f007fc2013-11-05 08:14:14 +00001611 // b L1
1612 // L2:
Reed Kotler0f007fc2013-11-05 08:14:14 +00001613
1614 // If the branch is at the end of its MBB and that has a fall-through block,
1615 // direct the updated conditional branch to the fall-through block. Otherwise,
1616 // split the MBB before the next instruction.
1617 MachineBasicBlock *MBB = MI->getParent();
1618 MachineInstr *BMI = &MBB->back();
1619 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1620
Reed Kotlerad450f22013-11-29 22:32:56 +00001621
Reed Kotler0f007fc2013-11-05 08:14:14 +00001622 ++NumCBrFixed;
1623 if (BMI != MI) {
1624 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Reed Kotlerad450f22013-11-29 22:32:56 +00001625 isUnconditionalBranch(BMI->getOpcode())) {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001626 // Last MI in the BB is an unconditional branch. Can we simply invert the
1627 // condition and swap destinations:
Reed Kotlerad450f22013-11-29 22:32:56 +00001628 // beqz L1
Reed Kotler0f007fc2013-11-05 08:14:14 +00001629 // b L2
1630 // =>
Reed Kotlerad450f22013-11-29 22:32:56 +00001631 // bnez L2
Reed Kotler0f007fc2013-11-05 08:14:14 +00001632 // b L1
Reed Kotlerad450f22013-11-29 22:32:56 +00001633 unsigned BMITargetOperand = branchTargetOperand(BMI);
1634 MachineBasicBlock *NewDest =
1635 BMI->getOperand(BMITargetOperand).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001636 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1637 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1638 << *BMI);
Reed Kotlerad450f22013-11-29 22:32:56 +00001639 MI->setDesc(TII->get(TII->getOppositeBranchOpc(Opcode)));
1640 BMI->getOperand(BMITargetOperand).setMBB(DestBB);
1641 MI->getOperand(TargetOperand).setMBB(NewDest);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001642 return true;
1643 }
1644 }
1645 }
1646
Reed Kotlerad450f22013-11-29 22:32:56 +00001647 llvm_unreachable("unsupported range of unconditional branch");
1648
Reed Kotler0f007fc2013-11-05 08:14:14 +00001649 if (NeedSplit) {
1650 splitBlockBeforeInstr(MI);
1651 // No need for the branch to the next block. We're adding an unconditional
1652 // branch to the destination.
1653 int delta = TII->GetInstSizeInBytes(&MBB->back());
1654 BBInfo[MBB->getNumber()].Size -= delta;
1655 MBB->back().eraseFromParent();
1656 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1657 }
1658 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1659
1660 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1661 << " also invert condition and change dest. to BB#"
1662 << NextBB->getNumber() << "\n");
1663
1664 // Insert a new conditional branch and a new unconditional branch.
1665 // Also update the ImmBranch as well as adding a new entry for the new branch.
1666 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Reed Kotlerad450f22013-11-29 22:32:56 +00001667 .addMBB(NextBB);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001668 Br.MI = &MBB->back();
1669 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1670 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1671 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1672 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1673 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1674
1675 // Remove the old conditional branch. It may or may not still be in MBB.
1676 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1677 MI->eraseFromParent();
1678 adjustBBOffsetsAfter(MBB);
1679 return true;
1680}
1681
Reed Kotler91ae9822013-10-27 21:57:36 +00001682
1683void MipsConstantIslands::prescanForConstants() {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001684 unsigned J = 0;
1685 (void)J;
Reed Kotler91ae9822013-10-27 21:57:36 +00001686 for (MachineFunction::iterator B =
1687 MF->begin(), E = MF->end(); B != E; ++B) {
1688 for (MachineBasicBlock::instr_iterator I =
1689 B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
1690 switch(I->getDesc().getOpcode()) {
1691 case Mips::LwConstant32: {
Reed Kotlera787aa22013-11-24 06:18:50 +00001692 PrescannedForConstants = true;
Reed Kotler91ae9822013-10-27 21:57:36 +00001693 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1694 J = I->getNumOperands();
1695 DEBUG(dbgs() << "num operands " << J << "\n");
1696 MachineOperand& Literal = I->getOperand(1);
1697 if (Literal.isImm()) {
1698 int64_t V = Literal.getImm();
1699 DEBUG(dbgs() << "literal " << V << "\n");
1700 Type *Int32Ty =
1701 Type::getInt32Ty(MF->getFunction()->getContext());
1702 const Constant *C = ConstantInt::get(Int32Ty, V);
1703 unsigned index = MCP->getConstantPoolIndex(C, 4);
1704 I->getOperand(2).ChangeToImmediate(index);
1705 DEBUG(dbgs() << "constant island constant " << *I << "\n");
Reed Kotler0f007fc2013-11-05 08:14:14 +00001706 I->setDesc(TII->get(Mips::LwRxPcTcp16));
Reed Kotler91ae9822013-10-27 21:57:36 +00001707 I->RemoveOperand(1);
1708 I->RemoveOperand(1);
1709 I->addOperand(MachineOperand::CreateCPI(index, 0));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001710 I->addOperand(MachineOperand::CreateImm(4));
Reed Kotler91ae9822013-10-27 21:57:36 +00001711 }
1712 break;
1713 }
1714 default:
1715 break;
1716 }
1717 }
1718 }
1719}
Reed Kotler0f007fc2013-11-05 08:14:14 +00001720