blob: db50bde3849bddccc8b2655fe33a90fd00829d5d [file] [log] [blame]
Evan Chenga8e29892007-01-19 07:51:42 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that splits the constant pool up into 'islands'
11// which are scattered through-out the function. This is required due to the
12// limited pc-relative displacements that ARM has.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "arm-cp-islands"
17#include "ARM.h"
Evan Chengaf5cbcb2007-01-25 03:12:46 +000018#include "ARMMachineFunctionInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000019#include "ARMInstrInfo.h"
20#include "llvm/CodeGen/MachineConstantPool.h"
21#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
23#include "llvm/CodeGen/MachineJumpTableInfo.h"
24#include "llvm/Target/TargetAsmInfo.h"
25#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/Statistic.h"
31#include <iostream>
32using namespace llvm;
33
34STATISTIC(NumSplit, "Number of uncond branches inserted");
35
36namespace {
37 /// ARMConstantIslands - Due to limited pc-relative displacements, ARM
38 /// requires constant pool entries to be scattered among the instructions
39 /// inside a function. To do this, it completely ignores the normal LLVM
40 /// constant pool, instead, it places constants where-ever it feels like with
41 /// special instructions.
42 ///
43 /// The terminology used in this pass includes:
44 /// Islands - Clumps of constants placed in the function.
45 /// Water - Potential places where an island could be formed.
46 /// CPE - A constant pool entry that has been placed somewhere, which
47 /// tracks a list of users.
48 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
49 /// NextUID - Assign unique ID's to CPE's.
50 unsigned NextUID;
51
52 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
53 /// by MBB Number.
54 std::vector<unsigned> BBSizes;
55
56 /// WaterList - A sorted list of basic blocks where islands could be placed
57 /// (i.e. blocks that don't fall through to the following block, due
58 /// to a return, unreachable, or unconditional branch).
59 std::vector<MachineBasicBlock*> WaterList;
60
61 /// CPUser - One user of a constant pool, keeping the machine instruction
62 /// pointer, the constant pool being referenced, and the max displacement
63 /// allowed from the instruction to the CP.
64 struct CPUser {
65 MachineInstr *MI;
66 MachineInstr *CPEMI;
67 unsigned MaxDisp;
68 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
69 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
70 };
71
72 /// CPUsers - Keep track of all of the machine instructions that use various
73 /// constant pools and their max displacement.
74 std::vector<CPUser> CPUsers;
75
Evan Chengaf5cbcb2007-01-25 03:12:46 +000076 /// ImmBranch - One per immediate branch, keeping the machine instruction
77 /// pointer, conditional or unconditional, the max displacement,
78 /// and (if isCond is true) the corresponding unconditional branch
79 /// opcode.
80 struct ImmBranch {
81 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +000082 unsigned MaxDisp : 31;
83 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +000084 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +000085 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
86 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +000087 };
88
Evan Chengc2854142007-01-25 23:18:59 +000089 /// Branches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +000090 ///
91 std::vector<ImmBranch> ImmBranches;
92
Evan Chenga8e29892007-01-19 07:51:42 +000093 const TargetInstrInfo *TII;
94 const TargetAsmInfo *TAI;
95 public:
96 virtual bool runOnMachineFunction(MachineFunction &Fn);
97
98 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +000099 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000100 }
101
102 private:
103 void DoInitialPlacement(MachineFunction &Fn,
104 std::vector<MachineInstr*> &CPEMIs);
105 void InitialFunctionScan(MachineFunction &Fn,
106 const std::vector<MachineInstr*> &CPEMIs);
107 void SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000108 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000109 bool HandleConstantPoolUser(MachineFunction &Fn, CPUser &U);
Evan Chengc2854142007-01-25 23:18:59 +0000110 bool FixUpImmediateBranch(MachineFunction &Fn, ImmBranch &Br);
Evan Chenga8e29892007-01-19 07:51:42 +0000111
112 unsigned GetInstSize(MachineInstr *MI) const;
113 unsigned GetOffsetOf(MachineInstr *MI) const;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000114 unsigned GetOffsetOf(MachineBasicBlock *MBB) const;
Evan Chenga8e29892007-01-19 07:51:42 +0000115 };
116}
117
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000118/// createARMConstantIslandPass - returns an instance of the constpool
119/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000120FunctionPass *llvm::createARMConstantIslandPass() {
121 return new ARMConstantIslands();
122}
123
124bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
Evan Chenga8e29892007-01-19 07:51:42 +0000125 MachineConstantPool &MCP = *Fn.getConstantPool();
Evan Chenga8e29892007-01-19 07:51:42 +0000126
127 TII = Fn.getTarget().getInstrInfo();
128 TAI = Fn.getTarget().getTargetAsmInfo();
129
130 // Renumber all of the machine basic blocks in the function, guaranteeing that
131 // the numbers agree with the position of the block in the function.
132 Fn.RenumberBlocks();
133
134 // Perform the initial placement of the constant pool entries. To start with,
135 // we put them all at the end of the function.
136 std::vector<MachineInstr*> CPEMIs;
Evan Cheng7755fac2007-01-26 01:04:44 +0000137 if (!MCP.isEmpty())
138 DoInitialPlacement(Fn, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000139
140 /// The next UID to take is the first unused one.
141 NextUID = CPEMIs.size();
142
143 // Do the initial scan of the function, building up information about the
144 // sizes of each block, the location of all the water, and finding all of the
145 // constant pool users.
146 InitialFunctionScan(Fn, CPEMIs);
147 CPEMIs.clear();
148
149 // Iteratively place constant pool entries until there is no change.
150 bool MadeChange;
151 do {
152 MadeChange = false;
153 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
154 MadeChange |= HandleConstantPoolUser(Fn, CPUsers[i]);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000155 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengc2854142007-01-25 23:18:59 +0000156 MadeChange |= FixUpImmediateBranch(Fn, ImmBranches[i]);
Evan Chenga8e29892007-01-19 07:51:42 +0000157 } while (MadeChange);
158
159 BBSizes.clear();
160 WaterList.clear();
161 CPUsers.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000162 ImmBranches.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000163
164 return true;
165}
166
167/// DoInitialPlacement - Perform the initial placement of the constant pool
168/// entries. To start with, we put them all at the end of the function.
169void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
170 std::vector<MachineInstr*> &CPEMIs){
171 // Create the basic block to hold the CPE's.
172 MachineBasicBlock *BB = new MachineBasicBlock();
173 Fn.getBasicBlockList().push_back(BB);
174
175 // Add all of the constants from the constant pool to the end block, use an
176 // identity mapping of CPI's to CPE's.
177 const std::vector<MachineConstantPoolEntry> &CPs =
178 Fn.getConstantPool()->getConstants();
179
180 const TargetData &TD = *Fn.getTarget().getTargetData();
181 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
182 unsigned Size = TD.getTypeSize(CPs[i].getType());
183 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
184 // we would have to pad them out or something so that instructions stay
185 // aligned.
186 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
187 MachineInstr *CPEMI =
188 BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
189 .addImm(i).addConstantPoolIndex(i).addImm(Size);
190 CPEMIs.push_back(CPEMI);
191 DEBUG(std::cerr << "Moved CPI#" << i << " to end of function as #"
192 << i << "\n");
193 }
194}
195
196/// BBHasFallthrough - Return true of the specified basic block can fallthrough
197/// into the block immediately after it.
198static bool BBHasFallthrough(MachineBasicBlock *MBB) {
199 // Get the next machine basic block in the function.
200 MachineFunction::iterator MBBI = MBB;
201 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
202 return false;
203
204 MachineBasicBlock *NextBB = next(MBBI);
205 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
206 E = MBB->succ_end(); I != E; ++I)
207 if (*I == NextBB)
208 return true;
209
210 return false;
211}
212
213/// InitialFunctionScan - Do the initial scan of the function, building up
214/// information about the sizes of each block, the location of all the water,
215/// and finding all of the constant pool users.
216void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
217 const std::vector<MachineInstr*> &CPEMIs) {
218 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
219 MBBI != E; ++MBBI) {
220 MachineBasicBlock &MBB = *MBBI;
221
222 // If this block doesn't fall through into the next MBB, then this is
223 // 'water' that a constant pool island could be placed.
224 if (!BBHasFallthrough(&MBB))
225 WaterList.push_back(&MBB);
226
227 unsigned MBBSize = 0;
228 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
229 I != E; ++I) {
230 // Add instruction size to MBBSize.
231 MBBSize += GetInstSize(I);
232
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000233 int Opc = I->getOpcode();
234 if (TII->isBranch(Opc)) {
235 bool isCond = false;
236 unsigned Bits = 0;
237 unsigned Scale = 1;
238 int UOpc = Opc;
239 switch (Opc) {
Evan Cheng743fa032007-01-25 19:43:52 +0000240 default:
241 continue; // Ignore JT branches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000242 case ARM::Bcc:
243 isCond = true;
244 UOpc = ARM::B;
245 // Fallthrough
246 case ARM::B:
247 Bits = 24;
248 Scale = 4;
249 break;
250 case ARM::tBcc:
251 isCond = true;
252 UOpc = ARM::tB;
253 Bits = 8;
254 Scale = 2;
255 break;
256 case ARM::tB:
257 Bits = 11;
258 Scale = 2;
259 break;
260 }
261 unsigned MaxDisp = (1 << (Bits-1)) * Scale;
Evan Chengc2854142007-01-25 23:18:59 +0000262 ImmBranches.push_back(ImmBranch(I, MaxDisp, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000263 }
264
Evan Chenga8e29892007-01-19 07:51:42 +0000265 // Scan the instructions for constant pool operands.
266 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
267 if (I->getOperand(op).isConstantPoolIndex()) {
268 // We found one. The addressing mode tells us the max displacement
269 // from the PC that this instruction permits.
270 unsigned MaxOffs = 0;
271
272 // Basic size info comes from the TSFlags field.
273 unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
274 switch (TSFlags & ARMII::AddrModeMask) {
275 default:
276 // Constant pool entries can reach anything.
277 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
278 continue;
279 assert(0 && "Unknown addressing mode for CP reference!");
280 case ARMII::AddrMode1: // AM1: 8 bits << 2
281 MaxOffs = 1 << (8+2); // Taking the address of a CP entry.
282 break;
283 case ARMII::AddrMode2:
284 MaxOffs = 1 << 12; // +-offset_12
285 break;
286 case ARMII::AddrMode3:
287 MaxOffs = 1 << 8; // +-offset_8
288 break;
289 // addrmode4 has no immediate offset.
290 case ARMII::AddrMode5:
291 MaxOffs = 1 << (8+2); // +-(offset_8*4)
292 break;
293 case ARMII::AddrModeT1:
294 MaxOffs = 1 << 5;
295 break;
296 case ARMII::AddrModeT2:
297 MaxOffs = 1 << (5+1);
298 break;
299 case ARMII::AddrModeT4:
300 MaxOffs = 1 << (5+2);
301 break;
Evan Cheng012f2d92007-01-24 08:53:17 +0000302 case ARMII::AddrModeTs:
303 MaxOffs = 1 << (8+2);
304 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000305 }
306
307 // Remember that this is a user of a CP entry.
308 MachineInstr *CPEMI =CPEMIs[I->getOperand(op).getConstantPoolIndex()];
309 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
310
311 // Instructions can only use one CP entry, don't bother scanning the
312 // rest of the operands.
313 break;
314 }
315 }
316 BBSizes.push_back(MBBSize);
317 }
318}
319
320/// FIXME: Works around a gcc miscompilation with -fstrict-aliasing
321static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
322 unsigned JTI) DISABLE_INLINE;
323static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
324 unsigned JTI) {
325 return JT[JTI].MBBs.size();
326}
327
328/// GetInstSize - Return the size of the specified MachineInstr.
329///
330unsigned ARMConstantIslands::GetInstSize(MachineInstr *MI) const {
331 // Basic size info comes from the TSFlags field.
332 unsigned TSFlags = MI->getInstrDescriptor()->TSFlags;
333
334 switch ((TSFlags & ARMII::SizeMask) >> ARMII::SizeShift) {
335 default:
336 // If this machine instr is an inline asm, measure it.
337 if (MI->getOpcode() == ARM::INLINEASM)
338 return TAI->getInlineAsmLength(MI->getOperand(0).getSymbolName());
339 assert(0 && "Unknown or unset size field for instr!");
340 break;
341 case ARMII::Size8Bytes: return 8; // Arm instruction x 2.
342 case ARMII::Size4Bytes: return 4; // Arm instruction.
343 case ARMII::Size2Bytes: return 2; // Thumb instruction.
344 case ARMII::SizeSpecial: {
345 switch (MI->getOpcode()) {
346 case ARM::CONSTPOOL_ENTRY:
347 // If this machine instr is a constant pool entry, its size is recorded as
348 // operand #2.
349 return MI->getOperand(2).getImm();
350 case ARM::BR_JTr:
351 case ARM::BR_JTm:
352 case ARM::BR_JTadd: {
353 // These are jumptable branches, i.e. a branch followed by an inlined
354 // jumptable. The size is 4 + 4 * number of entries.
355 unsigned JTI = MI->getOperand(MI->getNumOperands()-2).getJumpTableIndex();
356 const MachineFunction *MF = MI->getParent()->getParent();
357 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
358 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
359 assert(JTI < JT.size());
360 return getNumJTEntries(JT, JTI) * 4 + 4;
361 }
362 default:
363 // Otherwise, pseudo-instruction sizes are zero.
364 return 0;
365 }
366 }
367 }
368}
369
370/// GetOffsetOf - Return the current offset of the specified machine instruction
371/// from the start of the function. This offset changes as stuff is moved
372/// around inside the function.
373unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
374 MachineBasicBlock *MBB = MI->getParent();
375
376 // The offset is composed of two things: the sum of the sizes of all MBB's
377 // before this instruction's block, and the offset from the start of the block
378 // it is in.
379 unsigned Offset = 0;
380
381 // Sum block sizes before MBB.
382 for (unsigned BB = 0, e = MBB->getNumber(); BB != e; ++BB)
383 Offset += BBSizes[BB];
384
385 // Sum instructions before MI in MBB.
386 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
387 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
388 if (&*I == MI) return Offset;
389 Offset += GetInstSize(I);
390 }
391}
392
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000393/// GetOffsetOf - Return the current offset of the specified machine BB
394/// from the start of the function. This offset changes as stuff is moved
395/// around inside the function.
396unsigned ARMConstantIslands::GetOffsetOf(MachineBasicBlock *MBB) const {
397 // Sum block sizes before MBB.
398 unsigned Offset = 0;
399 for (unsigned BB = 0, e = MBB->getNumber(); BB != e; ++BB)
400 Offset += BBSizes[BB];
401
402 return Offset;
403}
404
Evan Chenga8e29892007-01-19 07:51:42 +0000405/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
406/// ID.
407static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
408 const MachineBasicBlock *RHS) {
409 return LHS->getNumber() < RHS->getNumber();
410}
411
412/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
413/// machine function, it upsets all of the block numbers. Renumber the blocks
414/// and update the arrays that parallel this numbering.
415void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
416 // Renumber the MBB's to keep them consequtive.
417 NewBB->getParent()->RenumberBlocks(NewBB);
418
419 // Insert a size into BBSizes to align it properly with the (newly
420 // renumbered) block numbers.
421 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
422
423 // Next, update WaterList. Specifically, we need to add NewMBB as having
424 // available water after it.
425 std::vector<MachineBasicBlock*>::iterator IP =
426 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
427 CompareMBBNumbers);
428 WaterList.insert(IP, NewBB);
429}
430
431
432/// Split the basic block containing MI into two blocks, which are joined by
433/// an unconditional branch. Update datastructures and renumber blocks to
434/// account for this change.
435void ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
436 MachineBasicBlock *OrigBB = MI->getParent();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000437 const ARMFunctionInfo *AFI = OrigBB->getParent()->getInfo<ARMFunctionInfo>();
438 bool isThumb = AFI->isThumbFunction();
Evan Chenga8e29892007-01-19 07:51:42 +0000439
440 // Create a new MBB for the code after the OrigBB.
441 MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
442 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
443 OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
444
445 // Splice the instructions starting with MI over to NewBB.
446 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
447
448 // Add an unconditional branch from OrigBB to NewBB.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000449 BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000450 NumSplit++;
451
452 // Update the CFG. All succs of OrigBB are now succs of NewBB.
453 while (!OrigBB->succ_empty()) {
454 MachineBasicBlock *Succ = *OrigBB->succ_begin();
455 OrigBB->removeSuccessor(Succ);
456 NewBB->addSuccessor(Succ);
457
458 // This pass should be run after register allocation, so there should be no
459 // PHI nodes to update.
460 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
461 && "PHI nodes should be eliminated by now!");
462 }
463
464 // OrigBB branches to NewBB.
465 OrigBB->addSuccessor(NewBB);
466
467 // Update internal data structures to account for the newly inserted MBB.
468 UpdateForInsertedWaterBlock(NewBB);
469
470 // Figure out how large the first NewMBB is.
471 unsigned NewBBSize = 0;
472 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
473 I != E; ++I)
474 NewBBSize += GetInstSize(I);
475
476 // Set the size of NewBB in BBSizes.
477 BBSizes[NewBB->getNumber()] = NewBBSize;
478
479 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000480 // Add 2 or 4 to the block to count the unconditional branch we added to it.
481 BBSizes[OrigBB->getNumber()] -= NewBBSize - (isThumb ? 2 : 4);
Evan Chenga8e29892007-01-19 07:51:42 +0000482}
483
484/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
485/// is out-of-range. If so, pick it up the constant pool value and move it some
486/// place in-range.
487bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn, CPUser &U){
488 MachineInstr *UserMI = U.MI;
489 MachineInstr *CPEMI = U.CPEMI;
490
491 unsigned UserOffset = GetOffsetOf(UserMI);
492 unsigned CPEOffset = GetOffsetOf(CPEMI);
493
494 DEBUG(std::cerr << "User of CPE#" << CPEMI->getOperand(0).getImm()
495 << " max delta=" << U.MaxDisp
496 << " at offset " << int(UserOffset-CPEOffset) << "\t"
497 << *UserMI);
498
499 // Check to see if the CPE is already in-range.
500 if (UserOffset < CPEOffset) {
501 // User before the CPE.
502 if (CPEOffset-UserOffset <= U.MaxDisp)
503 return false;
504 } else {
505 if (UserOffset-CPEOffset <= U.MaxDisp)
506 return false;
507 }
508
509
510 // Solution guaranteed to work: split the user's MBB right before the user and
511 // insert a clone the CPE into the newly created water.
512
513 // If the user isn't at the start of its MBB, or if there is a fall-through
514 // into the user's MBB, split the MBB before the User.
515 MachineBasicBlock *UserMBB = UserMI->getParent();
516 if (&UserMBB->front() != UserMI ||
517 UserMBB == &Fn.front() || // entry MBB of function.
518 BBHasFallthrough(prior(MachineFunction::iterator(UserMBB)))) {
519 // TODO: Search for the best place to split the code. In practice, using
520 // loop nesting information to insert these guys outside of loops would be
521 // sufficient.
522 SplitBlockBeforeInstr(UserMI);
523
524 // UserMI's BB may have changed.
525 UserMBB = UserMI->getParent();
526 }
527
528 // Okay, we know we can put an island before UserMBB now, do it!
529 MachineBasicBlock *NewIsland = new MachineBasicBlock();
530 Fn.getBasicBlockList().insert(UserMBB, NewIsland);
531
532 // Update internal data structures to account for the newly inserted MBB.
533 UpdateForInsertedWaterBlock(NewIsland);
534
535 // Now that we have an island to add the CPE to, clone the original CPE and
536 // add it to the island.
537 unsigned ID = NextUID++;
538 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
539 unsigned Size = CPEMI->getOperand(2).getImm();
540
541 // Build a new CPE for this user.
542 U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
543 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
544
545 // Increase the size of the island block to account for the new entry.
546 BBSizes[NewIsland->getNumber()] += Size;
547
548 // Finally, change the CPI in the instruction operand to be ID.
549 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
550 if (UserMI->getOperand(i).isConstantPoolIndex()) {
551 UserMI->getOperand(i).setConstantPoolIndex(ID);
552 break;
553 }
554
555 DEBUG(std::cerr << " Moved CPE to #" << ID << " CPI=" << CPI << "\t"
556 << *UserMI);
557
558
559 return true;
560}
561
Evan Chengc2854142007-01-25 23:18:59 +0000562/// FixUpImmediateBranch - Fix up immediate branches whose destination is too
563/// far away to fit in its displacement field. If it is a conditional branch,
564/// then it is converted to an inverse conditional branch + an unconditional
565/// branch to the destination. If it is an unconditional branch, then it is
566/// converted to a branch to a branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000567bool
Evan Chengc2854142007-01-25 23:18:59 +0000568ARMConstantIslands::FixUpImmediateBranch(MachineFunction &Fn, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000569 MachineInstr *MI = Br.MI;
570 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
571
572 unsigned BrOffset = GetOffsetOf(MI);
573 unsigned DestOffset = GetOffsetOf(DestBB);
574
575 // Check to see if the destination BB is in range.
576 if (BrOffset < DestOffset) {
577 if (DestOffset - BrOffset < Br.MaxDisp)
578 return false;
579 } else {
580 if (BrOffset - DestOffset <= Br.MaxDisp)
581 return false;
582 }
583
584 if (!Br.isCond) {
585 // Unconditional branch. We have to insert a branch somewhere to perform
586 // a two level branch (branch to branch). FIXME: not yet implemented.
587 assert(false && "Can't handle unconditional branch yet!");
588 return false;
589 }
590
591 // Otherwise, add a unconditional branch to the destination and
592 // invert the branch condition to jump over it:
593 // blt L1
594 // =>
595 // bge L2
596 // b L1
597 // L2:
598 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
599 CC = ARMCC::getOppositeCondition(CC);
600
601 // If the branch is at the end of its MBB and that has a fall-through block,
602 // direct the updated conditional branch to the fall-through block. Otherwise,
603 // split the MBB before the next instruction.
604 MachineBasicBlock *MBB = MI->getParent();
Evan Chengdd353b82007-01-26 02:02:39 +0000605 if (&MBB->back() != MI || !BBHasFallthrough(MBB)) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000606 SplitBlockBeforeInstr(MI);
Evan Chengdd353b82007-01-26 02:02:39 +0000607 // No need for the branch to the next block. We're adding a unconditional
608 // branch to the destination.
609 MBB->back().eraseFromParent();
610 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000611 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
612
613 // Insert a unconditional branch and replace the conditional branch.
614 // Also update the ImmBranch as well as adding a new entry for the new branch.
Evan Chengdd353b82007-01-26 02:02:39 +0000615 BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB).addImm(CC);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000616 Br.MI = &MBB->back();
617 BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
618 unsigned MaxDisp = (Br.UncondBr == ARM::tB) ? (1<<10)*2 : (1<<23)*4;
Evan Chenga0bf7942007-01-25 23:31:04 +0000619 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000620 MI->eraseFromParent();
621
622 // Increase the size of MBB to account for the new unconditional branch.
623 BBSizes[MBB->getNumber()] += GetInstSize(&MBB->back());
624 return true;
625}