blob: 02b15207ba0189844a7a26e3ee8aec048b532d37 [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"
Evan Chenga8e29892007-01-19 07:51:42 +000023#include "llvm/Target/TargetData.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/Statistic.h"
29#include <iostream>
30using namespace llvm;
31
Evan Chengd1b2c1e2007-01-30 01:18:38 +000032STATISTIC(NumSplit, "Number of uncond branches inserted");
33STATISTIC(NumCBrFixed, "Number of cond branches fixed");
34STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
Evan Chenga8e29892007-01-19 07:51:42 +000035
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 Chengd1b2c1e2007-01-30 01:18:38 +000093 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
94 ///
95 std::vector<MachineInstr*> PushPopMIs;
96
97 /// HasFarJump - True if any far jump instruction has been emitted during
98 /// the branch fix up pass.
99 bool HasFarJump;
100
Evan Chenga8e29892007-01-19 07:51:42 +0000101 const TargetInstrInfo *TII;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000102 const ARMFunctionInfo *AFI;
Evan Chenga8e29892007-01-19 07:51:42 +0000103 public:
104 virtual bool runOnMachineFunction(MachineFunction &Fn);
105
106 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000107 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000108 }
109
110 private:
111 void DoInitialPlacement(MachineFunction &Fn,
112 std::vector<MachineInstr*> &CPEMIs);
113 void InitialFunctionScan(MachineFunction &Fn,
114 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000115 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000116 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000117 bool HandleConstantPoolUser(MachineFunction &Fn, CPUser &U);
Evan Chengc0dbec72007-01-31 19:57:44 +0000118 bool CPEIsInRange(MachineInstr *MI, MachineInstr *CPEMI, unsigned Disp);
119 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000120 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
121 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
122 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
123 bool UndoLRSpillRestore();
Evan Chenga8e29892007-01-19 07:51:42 +0000124
Evan Chenga8e29892007-01-19 07:51:42 +0000125 unsigned GetOffsetOf(MachineInstr *MI) const;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000126 unsigned GetOffsetOf(MachineBasicBlock *MBB) const;
Evan Chenga8e29892007-01-19 07:51:42 +0000127 };
128}
129
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000130/// createARMConstantIslandPass - returns an instance of the constpool
131/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000132FunctionPass *llvm::createARMConstantIslandPass() {
133 return new ARMConstantIslands();
134}
135
136bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
Evan Chenga8e29892007-01-19 07:51:42 +0000137 MachineConstantPool &MCP = *Fn.getConstantPool();
Evan Chenga8e29892007-01-19 07:51:42 +0000138
139 TII = Fn.getTarget().getInstrInfo();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000140 AFI = Fn.getInfo<ARMFunctionInfo>();
141
142 HasFarJump = false;
143
Evan Chenga8e29892007-01-19 07:51:42 +0000144 // Renumber all of the machine basic blocks in the function, guaranteeing that
145 // the numbers agree with the position of the block in the function.
146 Fn.RenumberBlocks();
147
148 // Perform the initial placement of the constant pool entries. To start with,
149 // we put them all at the end of the function.
150 std::vector<MachineInstr*> CPEMIs;
Evan Cheng7755fac2007-01-26 01:04:44 +0000151 if (!MCP.isEmpty())
152 DoInitialPlacement(Fn, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000153
154 /// The next UID to take is the first unused one.
155 NextUID = CPEMIs.size();
156
157 // Do the initial scan of the function, building up information about the
158 // sizes of each block, the location of all the water, and finding all of the
159 // constant pool users.
160 InitialFunctionScan(Fn, CPEMIs);
161 CPEMIs.clear();
162
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000163 // Iteratively place constant pool entries and fix up branches until there
164 // is no change.
165 bool MadeChange = false;
166 while (true) {
167 bool Change = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000168 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000169 Change |= HandleConstantPoolUser(Fn, CPUsers[i]);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000170 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000171 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
172 if (!Change)
173 break;
174 MadeChange = true;
175 }
Evan Chenga8e29892007-01-19 07:51:42 +0000176
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000177 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
178 // Undo the spill / restore of LR if possible.
179 if (!HasFarJump && AFI->isLRForceSpilled() && AFI->isThumbFunction())
180 MadeChange |= UndoLRSpillRestore();
181
Evan Chenga8e29892007-01-19 07:51:42 +0000182 BBSizes.clear();
183 WaterList.clear();
184 CPUsers.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000185 ImmBranches.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000186
187 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000188}
189
190/// DoInitialPlacement - Perform the initial placement of the constant pool
191/// entries. To start with, we put them all at the end of the function.
192void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
193 std::vector<MachineInstr*> &CPEMIs){
194 // Create the basic block to hold the CPE's.
195 MachineBasicBlock *BB = new MachineBasicBlock();
196 Fn.getBasicBlockList().push_back(BB);
197
198 // Add all of the constants from the constant pool to the end block, use an
199 // identity mapping of CPI's to CPE's.
200 const std::vector<MachineConstantPoolEntry> &CPs =
201 Fn.getConstantPool()->getConstants();
202
203 const TargetData &TD = *Fn.getTarget().getTargetData();
204 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
205 unsigned Size = TD.getTypeSize(CPs[i].getType());
206 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
207 // we would have to pad them out or something so that instructions stay
208 // aligned.
209 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
210 MachineInstr *CPEMI =
211 BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
212 .addImm(i).addConstantPoolIndex(i).addImm(Size);
213 CPEMIs.push_back(CPEMI);
214 DEBUG(std::cerr << "Moved CPI#" << i << " to end of function as #"
215 << i << "\n");
216 }
217}
218
219/// BBHasFallthrough - Return true of the specified basic block can fallthrough
220/// into the block immediately after it.
221static bool BBHasFallthrough(MachineBasicBlock *MBB) {
222 // Get the next machine basic block in the function.
223 MachineFunction::iterator MBBI = MBB;
224 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
225 return false;
226
227 MachineBasicBlock *NextBB = next(MBBI);
228 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
229 E = MBB->succ_end(); I != E; ++I)
230 if (*I == NextBB)
231 return true;
232
233 return false;
234}
235
236/// InitialFunctionScan - Do the initial scan of the function, building up
237/// information about the sizes of each block, the location of all the water,
238/// and finding all of the constant pool users.
239void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
240 const std::vector<MachineInstr*> &CPEMIs) {
241 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
242 MBBI != E; ++MBBI) {
243 MachineBasicBlock &MBB = *MBBI;
244
245 // If this block doesn't fall through into the next MBB, then this is
246 // 'water' that a constant pool island could be placed.
247 if (!BBHasFallthrough(&MBB))
248 WaterList.push_back(&MBB);
249
250 unsigned MBBSize = 0;
251 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
252 I != E; ++I) {
253 // Add instruction size to MBBSize.
Evan Cheng29836c32007-01-29 23:45:17 +0000254 MBBSize += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000255
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000256 int Opc = I->getOpcode();
257 if (TII->isBranch(Opc)) {
258 bool isCond = false;
259 unsigned Bits = 0;
260 unsigned Scale = 1;
261 int UOpc = Opc;
262 switch (Opc) {
Evan Cheng743fa032007-01-25 19:43:52 +0000263 default:
264 continue; // Ignore JT branches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000265 case ARM::Bcc:
266 isCond = true;
267 UOpc = ARM::B;
268 // Fallthrough
269 case ARM::B:
270 Bits = 24;
271 Scale = 4;
272 break;
273 case ARM::tBcc:
274 isCond = true;
275 UOpc = ARM::tB;
276 Bits = 8;
277 Scale = 2;
278 break;
279 case ARM::tB:
280 Bits = 11;
281 Scale = 2;
282 break;
283 }
Evan Chengb43216e2007-02-01 10:16:15 +0000284
285 // Record this immediate branch.
286 unsigned MaxOffs = (1 << (Bits-1)) * Scale;
287 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000288 }
289
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000290 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
291 PushPopMIs.push_back(I);
292
Evan Chenga8e29892007-01-19 07:51:42 +0000293 // Scan the instructions for constant pool operands.
294 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
295 if (I->getOperand(op).isConstantPoolIndex()) {
296 // We found one. The addressing mode tells us the max displacement
297 // from the PC that this instruction permits.
Evan Chenga8e29892007-01-19 07:51:42 +0000298
299 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000300 unsigned Bits = 0;
301 unsigned Scale = 1;
Evan Chenga8e29892007-01-19 07:51:42 +0000302 unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
303 switch (TSFlags & ARMII::AddrModeMask) {
304 default:
305 // Constant pool entries can reach anything.
306 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
307 continue;
308 assert(0 && "Unknown addressing mode for CP reference!");
309 case ARMII::AddrMode1: // AM1: 8 bits << 2
Evan Chengb43216e2007-02-01 10:16:15 +0000310 Bits = 8;
311 Scale = 4; // Taking the address of a CP entry.
Evan Chenga8e29892007-01-19 07:51:42 +0000312 break;
313 case ARMII::AddrMode2:
Evan Chengb43216e2007-02-01 10:16:15 +0000314 Bits = 12;
315 Scale = 2; // +-offset_12
Evan Chenga8e29892007-01-19 07:51:42 +0000316 break;
317 case ARMII::AddrMode3:
Evan Chengb43216e2007-02-01 10:16:15 +0000318 Bits = 8;
319 Scale = 2; // +-offset_8
Evan Chenga8e29892007-01-19 07:51:42 +0000320 break;
321 // addrmode4 has no immediate offset.
322 case ARMII::AddrMode5:
Evan Chengb43216e2007-02-01 10:16:15 +0000323 Bits = 8;
324 Scale = 4; // +-(offset_8*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000325 break;
326 case ARMII::AddrModeT1:
Evan Chengb43216e2007-02-01 10:16:15 +0000327 Bits = 5; // +offset_5
Evan Chenga8e29892007-01-19 07:51:42 +0000328 break;
329 case ARMII::AddrModeT2:
Evan Chengb43216e2007-02-01 10:16:15 +0000330 Bits = 5;
331 Scale = 2; // +(offset_5*2)
Evan Chenga8e29892007-01-19 07:51:42 +0000332 break;
333 case ARMII::AddrModeT4:
Evan Chengb43216e2007-02-01 10:16:15 +0000334 Bits = 5;
335 Scale = 4; // +(offset_5*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000336 break;
Evan Cheng012f2d92007-01-24 08:53:17 +0000337 case ARMII::AddrModeTs:
Evan Chengb43216e2007-02-01 10:16:15 +0000338 Bits = 8;
339 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000340 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000341 }
Evan Chengb43216e2007-02-01 10:16:15 +0000342
Evan Chenga8e29892007-01-19 07:51:42 +0000343 // Remember that this is a user of a CP entry.
344 MachineInstr *CPEMI =CPEMIs[I->getOperand(op).getConstantPoolIndex()];
Evan Chengb43216e2007-02-01 10:16:15 +0000345 unsigned MaxOffs = (1 << (Bits-1)) * Scale;
Evan Chenga8e29892007-01-19 07:51:42 +0000346 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
347
348 // Instructions can only use one CP entry, don't bother scanning the
349 // rest of the operands.
350 break;
351 }
352 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000353
354 // In thumb mode, if this block is a constpool island, pessmisticly assume
355 // it needs to be padded by two byte so it's aligned on 4 byte boundary.
356 if (AFI->isThumbFunction() &&
357 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
358 MBBSize += 2;
359
Evan Chenga8e29892007-01-19 07:51:42 +0000360 BBSizes.push_back(MBBSize);
361 }
362}
363
Evan Chenga8e29892007-01-19 07:51:42 +0000364/// GetOffsetOf - Return the current offset of the specified machine instruction
365/// from the start of the function. This offset changes as stuff is moved
366/// around inside the function.
367unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
368 MachineBasicBlock *MBB = MI->getParent();
369
370 // The offset is composed of two things: the sum of the sizes of all MBB's
371 // before this instruction's block, and the offset from the start of the block
372 // it is in.
373 unsigned Offset = 0;
374
375 // Sum block sizes before MBB.
376 for (unsigned BB = 0, e = MBB->getNumber(); BB != e; ++BB)
377 Offset += BBSizes[BB];
378
379 // Sum instructions before MI in MBB.
380 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
381 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
382 if (&*I == MI) return Offset;
Evan Cheng29836c32007-01-29 23:45:17 +0000383 Offset += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000384 }
385}
386
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000387/// GetOffsetOf - Return the current offset of the specified machine BB
388/// from the start of the function. This offset changes as stuff is moved
389/// around inside the function.
390unsigned ARMConstantIslands::GetOffsetOf(MachineBasicBlock *MBB) const {
391 // Sum block sizes before MBB.
392 unsigned Offset = 0;
393 for (unsigned BB = 0, e = MBB->getNumber(); BB != e; ++BB)
394 Offset += BBSizes[BB];
395
396 return Offset;
397}
398
Evan Chenga8e29892007-01-19 07:51:42 +0000399/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
400/// ID.
401static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
402 const MachineBasicBlock *RHS) {
403 return LHS->getNumber() < RHS->getNumber();
404}
405
406/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
407/// machine function, it upsets all of the block numbers. Renumber the blocks
408/// and update the arrays that parallel this numbering.
409void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
410 // Renumber the MBB's to keep them consequtive.
411 NewBB->getParent()->RenumberBlocks(NewBB);
412
413 // Insert a size into BBSizes to align it properly with the (newly
414 // renumbered) block numbers.
415 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
416
417 // Next, update WaterList. Specifically, we need to add NewMBB as having
418 // available water after it.
419 std::vector<MachineBasicBlock*>::iterator IP =
420 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
421 CompareMBBNumbers);
422 WaterList.insert(IP, NewBB);
423}
424
425
426/// Split the basic block containing MI into two blocks, which are joined by
427/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000428/// account for this change and returns the newly created block.
429MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000430 MachineBasicBlock *OrigBB = MI->getParent();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000431 bool isThumb = AFI->isThumbFunction();
Evan Chenga8e29892007-01-19 07:51:42 +0000432
433 // Create a new MBB for the code after the OrigBB.
434 MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
435 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
436 OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
437
438 // Splice the instructions starting with MI over to NewBB.
439 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
440
441 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000442 // Note the new unconditional branch is not being recorded.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000443 BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000444 NumSplit++;
445
446 // Update the CFG. All succs of OrigBB are now succs of NewBB.
447 while (!OrigBB->succ_empty()) {
448 MachineBasicBlock *Succ = *OrigBB->succ_begin();
449 OrigBB->removeSuccessor(Succ);
450 NewBB->addSuccessor(Succ);
451
452 // This pass should be run after register allocation, so there should be no
453 // PHI nodes to update.
454 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
455 && "PHI nodes should be eliminated by now!");
456 }
457
458 // OrigBB branches to NewBB.
459 OrigBB->addSuccessor(NewBB);
460
461 // Update internal data structures to account for the newly inserted MBB.
462 UpdateForInsertedWaterBlock(NewBB);
463
464 // Figure out how large the first NewMBB is.
465 unsigned NewBBSize = 0;
466 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
467 I != E; ++I)
Evan Cheng29836c32007-01-29 23:45:17 +0000468 NewBBSize += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000469
470 // Set the size of NewBB in BBSizes.
471 BBSizes[NewBB->getNumber()] = NewBBSize;
472
473 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000474 // Add 2 or 4 to the block to count the unconditional branch we added to it.
475 BBSizes[OrigBB->getNumber()] -= NewBBSize - (isThumb ? 2 : 4);
Evan Cheng0c615842007-01-31 02:22:22 +0000476
477 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000478}
479
Evan Chengc0dbec72007-01-31 19:57:44 +0000480/// CPEIsInRange - Returns true is the distance between specific MI and
481/// specific ConstPool entry instruction can fit in MI's displacement field.
482bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, MachineInstr *CPEMI,
483 unsigned MaxDisp) {
484 unsigned PCAdj = AFI->isThumbFunction() ? 4 : 8;
485 unsigned UserOffset = GetOffsetOf(MI) + PCAdj;
Evan Cheng2021abe2007-02-01 01:09:47 +0000486 // In thumb mode, pessmisticly assumes the .align 2 before the first CPE
487 // in the island adds two byte padding.
488 unsigned AlignAdj = AFI->isThumbFunction() ? 2 : 0;
489 unsigned CPEOffset = GetOffsetOf(CPEMI) + AlignAdj;
490
Evan Chengc0dbec72007-01-31 19:57:44 +0000491 DEBUG(std::cerr << "User of CPE#" << CPEMI->getOperand(0).getImm()
492 << " max delta=" << MaxDisp
493 << " at offset " << int(UserOffset-CPEOffset) << "\t"
494 << *MI);
495
Evan Chenga2e35582007-01-31 23:35:18 +0000496 if (UserOffset <= CPEOffset) {
Evan Chengc0dbec72007-01-31 19:57:44 +0000497 // User before the CPE.
498 if (CPEOffset-UserOffset <= MaxDisp)
499 return true;
500 } else if (!AFI->isThumbFunction()) {
501 // Thumb LDR cannot encode negative offset.
502 if (UserOffset-CPEOffset <= MaxDisp)
503 return true;
504 }
505 return false;
506}
507
Evan Chenga8e29892007-01-19 07:51:42 +0000508/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
509/// is out-of-range. If so, pick it up the constant pool value and move it some
510/// place in-range.
511bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn, CPUser &U){
512 MachineInstr *UserMI = U.MI;
513 MachineInstr *CPEMI = U.CPEMI;
514
Evan Chenga8e29892007-01-19 07:51:42 +0000515 // Check to see if the CPE is already in-range.
Evan Chengc0dbec72007-01-31 19:57:44 +0000516 if (CPEIsInRange(UserMI, CPEMI, U.MaxDisp))
517 return false;
Evan Cheng0c615842007-01-31 02:22:22 +0000518
519 // Solution guaranteed to work: split the user's MBB right after the user and
Evan Chenga8e29892007-01-19 07:51:42 +0000520 // insert a clone the CPE into the newly created water.
Evan Cheng0c615842007-01-31 02:22:22 +0000521
Evan Cheng934536d2007-01-31 18:19:07 +0000522 MachineBasicBlock *UserMBB = UserMI->getParent();
523 MachineBasicBlock *NewMBB;
524
Evan Cheng0c615842007-01-31 02:22:22 +0000525 // TODO: Search for the best place to split the code. In practice, using
526 // loop nesting information to insert these guys outside of loops would be
527 // sufficient.
Evan Chengb43216e2007-02-01 10:16:15 +0000528 bool isThumb = AFI->isThumbFunction();
Evan Cheng934536d2007-01-31 18:19:07 +0000529 if (&UserMBB->back() == UserMI) {
530 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
531 NewMBB = next(MachineFunction::iterator(UserMBB));
532 // Add an unconditional branch from UserMBB to fallthrough block.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000533 // Note the new unconditional branch is not being recorded.
Evan Cheng934536d2007-01-31 18:19:07 +0000534 BuildMI(UserMBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewMBB);
535 BBSizes[UserMBB->getNumber()] += isThumb ? 2 : 4;
536 } else {
537 MachineInstr *NextMI = next(MachineBasicBlock::iterator(UserMI));
538 NewMBB = SplitBlockBeforeInstr(NextMI);
539 }
Evan Cheng0c615842007-01-31 02:22:22 +0000540
Evan Chenga8e29892007-01-19 07:51:42 +0000541 // Okay, we know we can put an island before UserMBB now, do it!
542 MachineBasicBlock *NewIsland = new MachineBasicBlock();
Evan Cheng934536d2007-01-31 18:19:07 +0000543 Fn.getBasicBlockList().insert(NewMBB, NewIsland);
Evan Chenga8e29892007-01-19 07:51:42 +0000544
545 // Update internal data structures to account for the newly inserted MBB.
546 UpdateForInsertedWaterBlock(NewIsland);
547
548 // Now that we have an island to add the CPE to, clone the original CPE and
549 // add it to the island.
550 unsigned ID = NextUID++;
551 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
552 unsigned Size = CPEMI->getOperand(2).getImm();
Evan Chengb43216e2007-02-01 10:16:15 +0000553
Evan Chenga8e29892007-01-19 07:51:42 +0000554 // Build a new CPE for this user.
555 U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
556 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
557
Evan Chengb43216e2007-02-01 10:16:15 +0000558 // Compensate for .align 2 in thumb mode.
559 if (isThumb) Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +0000560 // Increase the size of the island block to account for the new entry.
561 BBSizes[NewIsland->getNumber()] += Size;
562
563 // Finally, change the CPI in the instruction operand to be ID.
564 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
565 if (UserMI->getOperand(i).isConstantPoolIndex()) {
566 UserMI->getOperand(i).setConstantPoolIndex(ID);
567 break;
568 }
569
570 DEBUG(std::cerr << " Moved CPE to #" << ID << " CPI=" << CPI << "\t"
571 << *UserMI);
Evan Chenga8e29892007-01-19 07:51:42 +0000572
573 return true;
574}
575
Evan Chengc0dbec72007-01-31 19:57:44 +0000576/// BBIsInRange - Returns true is the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +0000577/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +0000578bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
579 unsigned MaxDisp) {
580 unsigned PCAdj = AFI->isThumbFunction() ? 4 : 8;
581 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Evan Cheng43aeab62007-01-26 20:38:26 +0000582 unsigned DestOffset = GetOffsetOf(DestBB);
583
Evan Chengc0dbec72007-01-31 19:57:44 +0000584 DEBUG(std::cerr << "Branch of destination BB#" << DestBB->getNumber()
585 << " max delta=" << MaxDisp
586 << " at offset " << int(BrOffset-DestOffset) << "\t"
587 << *MI);
588
Evan Chenga2e35582007-01-31 23:35:18 +0000589 if (BrOffset <= DestOffset) {
Evan Chengb43216e2007-02-01 10:16:15 +0000590 if (DestOffset - BrOffset <= MaxDisp)
Evan Cheng43aeab62007-01-26 20:38:26 +0000591 return true;
592 } else {
593 if (BrOffset - DestOffset <= MaxDisp)
594 return true;
595 }
596 return false;
597}
598
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000599/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
600/// away to fit in its displacement field.
601bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000602 MachineInstr *MI = Br.MI;
603 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
604
Evan Chengc0dbec72007-01-31 19:57:44 +0000605 // Check to see if the DestBB is already in-range.
606 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +0000607 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000608
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000609 if (!Br.isCond)
610 return FixUpUnconditionalBr(Fn, Br);
611 return FixUpConditionalBr(Fn, Br);
612}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000613
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000614/// FixUpUnconditionalBr - Fix up an unconditional branches whose destination is
615/// too far away to fit in its displacement field. If LR register has been
616/// spilled in the epilogue, then we can use BL to implement a far jump.
617/// Otherwise, add a intermediate branch instruction to to a branch.
618bool
619ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
620 MachineInstr *MI = Br.MI;
621 MachineBasicBlock *MBB = MI->getParent();
622 assert(AFI->isThumbFunction() && "Expected a Thumb function!");
623
624 // Use BL to implement far jump.
625 Br.MaxDisp = (1 << 21) * 2;
626 MI->setInstrDescriptor(TII->get(ARM::tBfar));
627 BBSizes[MBB->getNumber()] += 2;
628 HasFarJump = true;
629 NumUBrFixed++;
630 return true;
631}
632
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000633/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in the
634/// specific unconditional branch instruction.
635static inline unsigned getUnconditionalBrDisp(int Opc) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000636 return (Opc == ARM::tB) ? (1<<10)*2 : (1<<23)*4;
637}
638
639/// FixUpConditionalBr - Fix up a conditional branches whose destination is too
640/// far away to fit in its displacement field. It is converted to an inverse
641/// conditional branch + an unconditional branch to the destination.
642bool
643ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
644 MachineInstr *MI = Br.MI;
645 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
646
647 // Add a unconditional branch to the destination and invert the branch
648 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000649 // blt L1
650 // =>
651 // bge L2
652 // b L1
653 // L2:
654 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
655 CC = ARMCC::getOppositeCondition(CC);
656
657 // If the branch is at the end of its MBB and that has a fall-through block,
658 // direct the updated conditional branch to the fall-through block. Otherwise,
659 // split the MBB before the next instruction.
660 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng43aeab62007-01-26 20:38:26 +0000661 MachineInstr *BackMI = &MBB->back();
662 bool NeedSplit = (BackMI != MI) || !BBHasFallthrough(MBB);
663
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000664 NumCBrFixed++;
Evan Cheng43aeab62007-01-26 20:38:26 +0000665 if (BackMI != MI) {
666 if (next(MachineBasicBlock::iterator(MI)) == MBB->back() &&
667 BackMI->getOpcode() == Br.UncondBr) {
668 // Last MI in the BB is a unconditional branch. Can we simply invert the
669 // condition and swap destinations:
670 // beq L1
671 // b L2
672 // =>
673 // bne L2
674 // b L1
675 MachineBasicBlock *NewDest = BackMI->getOperand(0).getMachineBasicBlock();
Evan Chengc0dbec72007-01-31 19:57:44 +0000676 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Evan Cheng43aeab62007-01-26 20:38:26 +0000677 BackMI->getOperand(0).setMachineBasicBlock(DestBB);
678 MI->getOperand(0).setMachineBasicBlock(NewDest);
679 MI->getOperand(1).setImm(CC);
680 return true;
681 }
682 }
683 }
684
685 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000686 SplitBlockBeforeInstr(MI);
Evan Chengdd353b82007-01-26 02:02:39 +0000687 // No need for the branch to the next block. We're adding a unconditional
688 // branch to the destination.
689 MBB->back().eraseFromParent();
690 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000691 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
692
693 // Insert a unconditional branch and replace the conditional branch.
694 // Also update the ImmBranch as well as adding a new entry for the new branch.
Evan Chengdd353b82007-01-26 02:02:39 +0000695 BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB).addImm(CC);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000696 Br.MI = &MBB->back();
697 BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000698 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +0000699 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000700 MI->eraseFromParent();
701
702 // Increase the size of MBB to account for the new unconditional branch.
Evan Cheng29836c32007-01-29 23:45:17 +0000703 BBSizes[MBB->getNumber()] += ARM::GetInstSize(&MBB->back());
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000704 return true;
705}
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000706
707
708/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
709/// LR / restores LR to pc.
710bool ARMConstantIslands::UndoLRSpillRestore() {
711 bool MadeChange = false;
712 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
713 MachineInstr *MI = PushPopMIs[i];
714 if (MI->getNumOperands() == 1) {
715 if (MI->getOpcode() == ARM::tPOP_RET &&
716 MI->getOperand(0).getReg() == ARM::PC)
717 BuildMI(MI->getParent(), TII->get(ARM::tBX_RET));
718 MI->eraseFromParent();
719 MadeChange = true;
720 }
721 }
722 return MadeChange;
723}