LLVM API Documentation
00001 //===-- ARMConstantIslandPass.cpp - ARM constant islands ------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file contains a pass that splits the constant pool up into 'islands' 00011 // which are scattered through-out the function. This is required due to the 00012 // limited pc-relative displacements that ARM has. 00013 // 00014 //===----------------------------------------------------------------------===// 00015 00016 #include "ARM.h" 00017 #include "ARMMachineFunctionInfo.h" 00018 #include "MCTargetDesc/ARMAddressingModes.h" 00019 #include "Thumb2InstrInfo.h" 00020 #include "llvm/ADT/STLExtras.h" 00021 #include "llvm/ADT/SmallSet.h" 00022 #include "llvm/ADT/SmallVector.h" 00023 #include "llvm/ADT/Statistic.h" 00024 #include "llvm/CodeGen/MachineConstantPool.h" 00025 #include "llvm/CodeGen/MachineFunctionPass.h" 00026 #include "llvm/CodeGen/MachineJumpTableInfo.h" 00027 #include "llvm/CodeGen/MachineRegisterInfo.h" 00028 #include "llvm/IR/DataLayout.h" 00029 #include "llvm/Support/CommandLine.h" 00030 #include "llvm/Support/Debug.h" 00031 #include "llvm/Support/ErrorHandling.h" 00032 #include "llvm/Support/Format.h" 00033 #include "llvm/Support/raw_ostream.h" 00034 #include "llvm/Target/TargetMachine.h" 00035 #include <algorithm> 00036 using namespace llvm; 00037 00038 #define DEBUG_TYPE "arm-cp-islands" 00039 00040 STATISTIC(NumCPEs, "Number of constpool entries"); 00041 STATISTIC(NumSplit, "Number of uncond branches inserted"); 00042 STATISTIC(NumCBrFixed, "Number of cond branches fixed"); 00043 STATISTIC(NumUBrFixed, "Number of uncond branches fixed"); 00044 STATISTIC(NumTBs, "Number of table branches generated"); 00045 STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk"); 00046 STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk"); 00047 STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed"); 00048 STATISTIC(NumJTMoved, "Number of jump table destination blocks moved"); 00049 STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted"); 00050 00051 00052 static cl::opt<bool> 00053 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true), 00054 cl::desc("Adjust basic block layout to better use TB[BH]")); 00055 00056 // FIXME: This option should be removed once it has received sufficient testing. 00057 static cl::opt<bool> 00058 AlignConstantIslands("arm-align-constant-islands", cl::Hidden, cl::init(true), 00059 cl::desc("Align constant islands in code")); 00060 00061 /// UnknownPadding - Return the worst case padding that could result from 00062 /// unknown offset bits. This does not include alignment padding caused by 00063 /// known offset bits. 00064 /// 00065 /// @param LogAlign log2(alignment) 00066 /// @param KnownBits Number of known low offset bits. 00067 static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) { 00068 if (KnownBits < LogAlign) 00069 return (1u << LogAlign) - (1u << KnownBits); 00070 return 0; 00071 } 00072 00073 namespace { 00074 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM 00075 /// requires constant pool entries to be scattered among the instructions 00076 /// inside a function. To do this, it completely ignores the normal LLVM 00077 /// constant pool; instead, it places constants wherever it feels like with 00078 /// special instructions. 00079 /// 00080 /// The terminology used in this pass includes: 00081 /// Islands - Clumps of constants placed in the function. 00082 /// Water - Potential places where an island could be formed. 00083 /// CPE - A constant pool entry that has been placed somewhere, which 00084 /// tracks a list of users. 00085 class ARMConstantIslands : public MachineFunctionPass { 00086 /// BasicBlockInfo - Information about the offset and size of a single 00087 /// basic block. 00088 struct BasicBlockInfo { 00089 /// Offset - Distance from the beginning of the function to the beginning 00090 /// of this basic block. 00091 /// 00092 /// Offsets are computed assuming worst case padding before an aligned 00093 /// block. This means that subtracting basic block offsets always gives a 00094 /// conservative estimate of the real distance which may be smaller. 00095 /// 00096 /// Because worst case padding is used, the computed offset of an aligned 00097 /// block may not actually be aligned. 00098 unsigned Offset; 00099 00100 /// Size - Size of the basic block in bytes. If the block contains 00101 /// inline assembly, this is a worst case estimate. 00102 /// 00103 /// The size does not include any alignment padding whether from the 00104 /// beginning of the block, or from an aligned jump table at the end. 00105 unsigned Size; 00106 00107 /// KnownBits - The number of low bits in Offset that are known to be 00108 /// exact. The remaining bits of Offset are an upper bound. 00109 uint8_t KnownBits; 00110 00111 /// Unalign - When non-zero, the block contains instructions (inline asm) 00112 /// of unknown size. The real size may be smaller than Size bytes by a 00113 /// multiple of 1 << Unalign. 00114 uint8_t Unalign; 00115 00116 /// PostAlign - When non-zero, the block terminator contains a .align 00117 /// directive, so the end of the block is aligned to 1 << PostAlign 00118 /// bytes. 00119 uint8_t PostAlign; 00120 00121 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0), 00122 PostAlign(0) {} 00123 00124 /// Compute the number of known offset bits internally to this block. 00125 /// This number should be used to predict worst case padding when 00126 /// splitting the block. 00127 unsigned internalKnownBits() const { 00128 unsigned Bits = Unalign ? Unalign : KnownBits; 00129 // If the block size isn't a multiple of the known bits, assume the 00130 // worst case padding. 00131 if (Size & ((1u << Bits) - 1)) 00132 Bits = countTrailingZeros(Size); 00133 return Bits; 00134 } 00135 00136 /// Compute the offset immediately following this block. If LogAlign is 00137 /// specified, return the offset the successor block will get if it has 00138 /// this alignment. 00139 unsigned postOffset(unsigned LogAlign = 0) const { 00140 unsigned PO = Offset + Size; 00141 unsigned LA = std::max(unsigned(PostAlign), LogAlign); 00142 if (!LA) 00143 return PO; 00144 // Add alignment padding from the terminator. 00145 return PO + UnknownPadding(LA, internalKnownBits()); 00146 } 00147 00148 /// Compute the number of known low bits of postOffset. If this block 00149 /// contains inline asm, the number of known bits drops to the 00150 /// instruction alignment. An aligned terminator may increase the number 00151 /// of know bits. 00152 /// If LogAlign is given, also consider the alignment of the next block. 00153 unsigned postKnownBits(unsigned LogAlign = 0) const { 00154 return std::max(std::max(unsigned(PostAlign), LogAlign), 00155 internalKnownBits()); 00156 } 00157 }; 00158 00159 std::vector<BasicBlockInfo> BBInfo; 00160 00161 /// WaterList - A sorted list of basic blocks where islands could be placed 00162 /// (i.e. blocks that don't fall through to the following block, due 00163 /// to a return, unreachable, or unconditional branch). 00164 std::vector<MachineBasicBlock*> WaterList; 00165 00166 /// NewWaterList - The subset of WaterList that was created since the 00167 /// previous iteration by inserting unconditional branches. 00168 SmallSet<MachineBasicBlock*, 4> NewWaterList; 00169 00170 typedef std::vector<MachineBasicBlock*>::iterator water_iterator; 00171 00172 /// CPUser - One user of a constant pool, keeping the machine instruction 00173 /// pointer, the constant pool being referenced, and the max displacement 00174 /// allowed from the instruction to the CP. The HighWaterMark records the 00175 /// highest basic block where a new CPEntry can be placed. To ensure this 00176 /// pass terminates, the CP entries are initially placed at the end of the 00177 /// function and then move monotonically to lower addresses. The 00178 /// exception to this rule is when the current CP entry for a particular 00179 /// CPUser is out of range, but there is another CP entry for the same 00180 /// constant value in range. We want to use the existing in-range CP 00181 /// entry, but if it later moves out of range, the search for new water 00182 /// should resume where it left off. The HighWaterMark is used to record 00183 /// that point. 00184 struct CPUser { 00185 MachineInstr *MI; 00186 MachineInstr *CPEMI; 00187 MachineBasicBlock *HighWaterMark; 00188 private: 00189 unsigned MaxDisp; 00190 public: 00191 bool NegOk; 00192 bool IsSoImm; 00193 bool KnownAlignment; 00194 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp, 00195 bool neg, bool soimm) 00196 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm), 00197 KnownAlignment(false) { 00198 HighWaterMark = CPEMI->getParent(); 00199 } 00200 /// getMaxDisp - Returns the maximum displacement supported by MI. 00201 /// Correct for unknown alignment. 00202 /// Conservatively subtract 2 bytes to handle weird alignment effects. 00203 unsigned getMaxDisp() const { 00204 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2; 00205 } 00206 }; 00207 00208 /// CPUsers - Keep track of all of the machine instructions that use various 00209 /// constant pools and their max displacement. 00210 std::vector<CPUser> CPUsers; 00211 00212 /// CPEntry - One per constant pool entry, keeping the machine instruction 00213 /// pointer, the constpool index, and the number of CPUser's which 00214 /// reference this entry. 00215 struct CPEntry { 00216 MachineInstr *CPEMI; 00217 unsigned CPI; 00218 unsigned RefCount; 00219 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0) 00220 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {} 00221 }; 00222 00223 /// CPEntries - Keep track of all of the constant pool entry machine 00224 /// instructions. For each original constpool index (i.e. those that 00225 /// existed upon entry to this pass), it keeps a vector of entries. 00226 /// Original elements are cloned as we go along; the clones are 00227 /// put in the vector of the original element, but have distinct CPIs. 00228 std::vector<std::vector<CPEntry> > CPEntries; 00229 00230 /// ImmBranch - One per immediate branch, keeping the machine instruction 00231 /// pointer, conditional or unconditional, the max displacement, 00232 /// and (if isCond is true) the corresponding unconditional branch 00233 /// opcode. 00234 struct ImmBranch { 00235 MachineInstr *MI; 00236 unsigned MaxDisp : 31; 00237 bool isCond : 1; 00238 int UncondBr; 00239 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr) 00240 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {} 00241 }; 00242 00243 /// ImmBranches - Keep track of all the immediate branch instructions. 00244 /// 00245 std::vector<ImmBranch> ImmBranches; 00246 00247 /// PushPopMIs - Keep track of all the Thumb push / pop instructions. 00248 /// 00249 SmallVector<MachineInstr*, 4> PushPopMIs; 00250 00251 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions. 00252 SmallVector<MachineInstr*, 4> T2JumpTables; 00253 00254 /// HasFarJump - True if any far jump instruction has been emitted during 00255 /// the branch fix up pass. 00256 bool HasFarJump; 00257 00258 MachineFunction *MF; 00259 MachineConstantPool *MCP; 00260 const ARMBaseInstrInfo *TII; 00261 const ARMSubtarget *STI; 00262 ARMFunctionInfo *AFI; 00263 bool isThumb; 00264 bool isThumb1; 00265 bool isThumb2; 00266 public: 00267 static char ID; 00268 ARMConstantIslands() : MachineFunctionPass(ID) {} 00269 00270 bool runOnMachineFunction(MachineFunction &MF) override; 00271 00272 const char *getPassName() const override { 00273 return "ARM constant island placement and branch shortening pass"; 00274 } 00275 00276 private: 00277 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs); 00278 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI); 00279 unsigned getCPELogAlign(const MachineInstr *CPEMI); 00280 void scanFunctionJumpTables(); 00281 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs); 00282 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI); 00283 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB); 00284 void adjustBBOffsetsAfter(MachineBasicBlock *BB); 00285 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI); 00286 int findInRangeCPEntry(CPUser& U, unsigned UserOffset); 00287 bool findAvailableWater(CPUser&U, unsigned UserOffset, 00288 water_iterator &WaterIter); 00289 void createNewWater(unsigned CPUserIndex, unsigned UserOffset, 00290 MachineBasicBlock *&NewMBB); 00291 bool handleConstantPoolUser(unsigned CPUserIndex); 00292 void removeDeadCPEMI(MachineInstr *CPEMI); 00293 bool removeUnusedCPEntries(); 00294 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset, 00295 MachineInstr *CPEMI, unsigned Disp, bool NegOk, 00296 bool DoDump = false); 00297 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water, 00298 CPUser &U, unsigned &Growth); 00299 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp); 00300 bool fixupImmediateBr(ImmBranch &Br); 00301 bool fixupConditionalBr(ImmBranch &Br); 00302 bool fixupUnconditionalBr(ImmBranch &Br); 00303 bool undoLRSpillRestore(); 00304 bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const; 00305 bool optimizeThumb2Instructions(); 00306 bool optimizeThumb2Branches(); 00307 bool reorderThumb2JumpTables(); 00308 bool optimizeThumb2JumpTables(); 00309 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB, 00310 MachineBasicBlock *JTBB); 00311 00312 void computeBlockSize(MachineBasicBlock *MBB); 00313 unsigned getOffsetOf(MachineInstr *MI) const; 00314 unsigned getUserOffset(CPUser&) const; 00315 void dumpBBs(); 00316 void verify(); 00317 00318 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset, 00319 unsigned Disp, bool NegativeOK, bool IsSoImm = false); 00320 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset, 00321 const CPUser &U) { 00322 return isOffsetInRange(UserOffset, TrialOffset, 00323 U.getMaxDisp(), U.NegOk, U.IsSoImm); 00324 } 00325 }; 00326 char ARMConstantIslands::ID = 0; 00327 } 00328 00329 /// verify - check BBOffsets, BBSizes, alignment of islands 00330 void ARMConstantIslands::verify() { 00331 #ifndef NDEBUG 00332 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end(); 00333 MBBI != E; ++MBBI) { 00334 MachineBasicBlock *MBB = MBBI; 00335 unsigned MBBId = MBB->getNumber(); 00336 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset); 00337 } 00338 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n"); 00339 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) { 00340 CPUser &U = CPUsers[i]; 00341 unsigned UserOffset = getUserOffset(U); 00342 // Verify offset using the real max displacement without the safety 00343 // adjustment. 00344 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk, 00345 /* DoDump = */ true)) { 00346 DEBUG(dbgs() << "OK\n"); 00347 continue; 00348 } 00349 DEBUG(dbgs() << "Out of range.\n"); 00350 dumpBBs(); 00351 DEBUG(MF->dump()); 00352 llvm_unreachable("Constant pool entry out of range!"); 00353 } 00354 #endif 00355 } 00356 00357 /// print block size and offset information - debugging 00358 void ARMConstantIslands::dumpBBs() { 00359 DEBUG({ 00360 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) { 00361 const BasicBlockInfo &BBI = BBInfo[J]; 00362 dbgs() << format("%08x BB#%u\t", BBI.Offset, J) 00363 << " kb=" << unsigned(BBI.KnownBits) 00364 << " ua=" << unsigned(BBI.Unalign) 00365 << " pa=" << unsigned(BBI.PostAlign) 00366 << format(" size=%#x\n", BBInfo[J].Size); 00367 } 00368 }); 00369 } 00370 00371 /// createARMConstantIslandPass - returns an instance of the constpool 00372 /// island pass. 00373 FunctionPass *llvm::createARMConstantIslandPass() { 00374 return new ARMConstantIslands(); 00375 } 00376 00377 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) { 00378 MF = &mf; 00379 MCP = mf.getConstantPool(); 00380 00381 DEBUG(dbgs() << "***** ARMConstantIslands: " 00382 << MCP->getConstants().size() << " CP entries, aligned to " 00383 << MCP->getConstantPoolAlignment() << " bytes *****\n"); 00384 00385 TII = (const ARMBaseInstrInfo *)MF->getTarget() 00386 .getSubtargetImpl() 00387 ->getInstrInfo(); 00388 AFI = MF->getInfo<ARMFunctionInfo>(); 00389 STI = &MF->getTarget().getSubtarget<ARMSubtarget>(); 00390 00391 isThumb = AFI->isThumbFunction(); 00392 isThumb1 = AFI->isThumb1OnlyFunction(); 00393 isThumb2 = AFI->isThumb2Function(); 00394 00395 HasFarJump = false; 00396 00397 // This pass invalidates liveness information when it splits basic blocks. 00398 MF->getRegInfo().invalidateLiveness(); 00399 00400 // Renumber all of the machine basic blocks in the function, guaranteeing that 00401 // the numbers agree with the position of the block in the function. 00402 MF->RenumberBlocks(); 00403 00404 // Try to reorder and otherwise adjust the block layout to make good use 00405 // of the TB[BH] instructions. 00406 bool MadeChange = false; 00407 if (isThumb2 && AdjustJumpTableBlocks) { 00408 scanFunctionJumpTables(); 00409 MadeChange |= reorderThumb2JumpTables(); 00410 // Data is out of date, so clear it. It'll be re-computed later. 00411 T2JumpTables.clear(); 00412 // Blocks may have shifted around. Keep the numbering up to date. 00413 MF->RenumberBlocks(); 00414 } 00415 00416 // Thumb1 functions containing constant pools get 4-byte alignment. 00417 // This is so we can keep exact track of where the alignment padding goes. 00418 00419 // ARM and Thumb2 functions need to be 4-byte aligned. 00420 if (!isThumb1) 00421 MF->ensureAlignment(2); // 2 = log2(4) 00422 00423 // Perform the initial placement of the constant pool entries. To start with, 00424 // we put them all at the end of the function. 00425 std::vector<MachineInstr*> CPEMIs; 00426 if (!MCP->isEmpty()) 00427 doInitialPlacement(CPEMIs); 00428 00429 /// The next UID to take is the first unused one. 00430 AFI->initPICLabelUId(CPEMIs.size()); 00431 00432 // Do the initial scan of the function, building up information about the 00433 // sizes of each block, the location of all the water, and finding all of the 00434 // constant pool users. 00435 initializeFunctionInfo(CPEMIs); 00436 CPEMIs.clear(); 00437 DEBUG(dumpBBs()); 00438 00439 00440 /// Remove dead constant pool entries. 00441 MadeChange |= removeUnusedCPEntries(); 00442 00443 // Iteratively place constant pool entries and fix up branches until there 00444 // is no change. 00445 unsigned NoCPIters = 0, NoBRIters = 0; 00446 while (true) { 00447 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n'); 00448 bool CPChange = false; 00449 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) 00450 CPChange |= handleConstantPoolUser(i); 00451 if (CPChange && ++NoCPIters > 30) 00452 report_fatal_error("Constant Island pass failed to converge!"); 00453 DEBUG(dumpBBs()); 00454 00455 // Clear NewWaterList now. If we split a block for branches, it should 00456 // appear as "new water" for the next iteration of constant pool placement. 00457 NewWaterList.clear(); 00458 00459 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n'); 00460 bool BRChange = false; 00461 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) 00462 BRChange |= fixupImmediateBr(ImmBranches[i]); 00463 if (BRChange && ++NoBRIters > 30) 00464 report_fatal_error("Branch Fix Up pass failed to converge!"); 00465 DEBUG(dumpBBs()); 00466 00467 if (!CPChange && !BRChange) 00468 break; 00469 MadeChange = true; 00470 } 00471 00472 // Shrink 32-bit Thumb2 branch, load, and store instructions. 00473 if (isThumb2 && !STI->prefers32BitThumb()) 00474 MadeChange |= optimizeThumb2Instructions(); 00475 00476 // After a while, this might be made debug-only, but it is not expensive. 00477 verify(); 00478 00479 // If LR has been forced spilled and no far jump (i.e. BL) has been issued, 00480 // undo the spill / restore of LR if possible. 00481 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump()) 00482 MadeChange |= undoLRSpillRestore(); 00483 00484 // Save the mapping between original and cloned constpool entries. 00485 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) { 00486 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) { 00487 const CPEntry & CPE = CPEntries[i][j]; 00488 AFI->recordCPEClone(i, CPE.CPI); 00489 } 00490 } 00491 00492 DEBUG(dbgs() << '\n'; dumpBBs()); 00493 00494 BBInfo.clear(); 00495 WaterList.clear(); 00496 CPUsers.clear(); 00497 CPEntries.clear(); 00498 ImmBranches.clear(); 00499 PushPopMIs.clear(); 00500 T2JumpTables.clear(); 00501 00502 return MadeChange; 00503 } 00504 00505 /// doInitialPlacement - Perform the initial placement of the constant pool 00506 /// entries. To start with, we put them all at the end of the function. 00507 void 00508 ARMConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) { 00509 // Create the basic block to hold the CPE's. 00510 MachineBasicBlock *BB = MF->CreateMachineBasicBlock(); 00511 MF->push_back(BB); 00512 00513 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes). 00514 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment()); 00515 00516 // Mark the basic block as required by the const-pool. 00517 // If AlignConstantIslands isn't set, use 4-byte alignment for everything. 00518 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2); 00519 00520 // The function needs to be as aligned as the basic blocks. The linker may 00521 // move functions around based on their alignment. 00522 MF->ensureAlignment(BB->getAlignment()); 00523 00524 // Order the entries in BB by descending alignment. That ensures correct 00525 // alignment of all entries as long as BB is sufficiently aligned. Keep 00526 // track of the insertion point for each alignment. We are going to bucket 00527 // sort the entries as they are created. 00528 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end()); 00529 00530 // Add all of the constants from the constant pool to the end block, use an 00531 // identity mapping of CPI's to CPE's. 00532 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants(); 00533 00534 const DataLayout &TD = *MF->getSubtarget().getDataLayout(); 00535 for (unsigned i = 0, e = CPs.size(); i != e; ++i) { 00536 unsigned Size = TD.getTypeAllocSize(CPs[i].getType()); 00537 assert(Size >= 4 && "Too small constant pool entry"); 00538 unsigned Align = CPs[i].getAlignment(); 00539 assert(isPowerOf2_32(Align) && "Invalid alignment"); 00540 // Verify that all constant pool entries are a multiple of their alignment. 00541 // If not, we would have to pad them out so that instructions stay aligned. 00542 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!"); 00543 00544 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment. 00545 unsigned LogAlign = Log2_32(Align); 00546 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign]; 00547 MachineInstr *CPEMI = 00548 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY)) 00549 .addImm(i).addConstantPoolIndex(i).addImm(Size); 00550 CPEMIs.push_back(CPEMI); 00551 00552 // Ensure that future entries with higher alignment get inserted before 00553 // CPEMI. This is bucket sort with iterators. 00554 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a) 00555 if (InsPoint[a] == InsAt) 00556 InsPoint[a] = CPEMI; 00557 00558 // Add a new CPEntry, but no corresponding CPUser yet. 00559 std::vector<CPEntry> CPEs; 00560 CPEs.push_back(CPEntry(CPEMI, i)); 00561 CPEntries.push_back(CPEs); 00562 ++NumCPEs; 00563 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = " 00564 << Size << ", align = " << Align <<'\n'); 00565 } 00566 DEBUG(BB->dump()); 00567 } 00568 00569 /// BBHasFallthrough - Return true if the specified basic block can fallthrough 00570 /// into the block immediately after it. 00571 static bool BBHasFallthrough(MachineBasicBlock *MBB) { 00572 // Get the next machine basic block in the function. 00573 MachineFunction::iterator MBBI = MBB; 00574 // Can't fall off end of function. 00575 if (std::next(MBBI) == MBB->getParent()->end()) 00576 return false; 00577 00578 MachineBasicBlock *NextBB = std::next(MBBI); 00579 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 00580 E = MBB->succ_end(); I != E; ++I) 00581 if (*I == NextBB) 00582 return true; 00583 00584 return false; 00585 } 00586 00587 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI, 00588 /// look up the corresponding CPEntry. 00589 ARMConstantIslands::CPEntry 00590 *ARMConstantIslands::findConstPoolEntry(unsigned CPI, 00591 const MachineInstr *CPEMI) { 00592 std::vector<CPEntry> &CPEs = CPEntries[CPI]; 00593 // Number of entries per constpool index should be small, just do a 00594 // linear search. 00595 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) { 00596 if (CPEs[i].CPEMI == CPEMI) 00597 return &CPEs[i]; 00598 } 00599 return nullptr; 00600 } 00601 00602 /// getCPELogAlign - Returns the required alignment of the constant pool entry 00603 /// represented by CPEMI. Alignment is measured in log2(bytes) units. 00604 unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) { 00605 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY); 00606 00607 // Everything is 4-byte aligned unless AlignConstantIslands is set. 00608 if (!AlignConstantIslands) 00609 return 2; 00610 00611 unsigned CPI = CPEMI->getOperand(1).getIndex(); 00612 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index."); 00613 unsigned Align = MCP->getConstants()[CPI].getAlignment(); 00614 assert(isPowerOf2_32(Align) && "Invalid CPE alignment"); 00615 return Log2_32(Align); 00616 } 00617 00618 /// scanFunctionJumpTables - Do a scan of the function, building up 00619 /// information about the sizes of each block and the locations of all 00620 /// the jump tables. 00621 void ARMConstantIslands::scanFunctionJumpTables() { 00622 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end(); 00623 MBBI != E; ++MBBI) { 00624 MachineBasicBlock &MBB = *MBBI; 00625 00626 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); 00627 I != E; ++I) 00628 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT) 00629 T2JumpTables.push_back(I); 00630 } 00631 } 00632 00633 /// initializeFunctionInfo - Do the initial scan of the function, building up 00634 /// information about the sizes of each block, the location of all the water, 00635 /// and finding all of the constant pool users. 00636 void ARMConstantIslands:: 00637 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) { 00638 BBInfo.clear(); 00639 BBInfo.resize(MF->getNumBlockIDs()); 00640 00641 // First thing, compute the size of all basic blocks, and see if the function 00642 // has any inline assembly in it. If so, we have to be conservative about 00643 // alignment assumptions, as we don't know for sure the size of any 00644 // instructions in the inline assembly. 00645 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) 00646 computeBlockSize(I); 00647 00648 // The known bits of the entry block offset are determined by the function 00649 // alignment. 00650 BBInfo.front().KnownBits = MF->getAlignment(); 00651 00652 // Compute block offsets and known bits. 00653 adjustBBOffsetsAfter(MF->begin()); 00654 00655 // Now go back through the instructions and build up our data structures. 00656 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end(); 00657 MBBI != E; ++MBBI) { 00658 MachineBasicBlock &MBB = *MBBI; 00659 00660 // If this block doesn't fall through into the next MBB, then this is 00661 // 'water' that a constant pool island could be placed. 00662 if (!BBHasFallthrough(&MBB)) 00663 WaterList.push_back(&MBB); 00664 00665 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); 00666 I != E; ++I) { 00667 if (I->isDebugValue()) 00668 continue; 00669 00670 int Opc = I->getOpcode(); 00671 if (I->isBranch()) { 00672 bool isCond = false; 00673 unsigned Bits = 0; 00674 unsigned Scale = 1; 00675 int UOpc = Opc; 00676 switch (Opc) { 00677 default: 00678 continue; // Ignore other JT branches 00679 case ARM::t2BR_JT: 00680 T2JumpTables.push_back(I); 00681 continue; // Does not get an entry in ImmBranches 00682 case ARM::Bcc: 00683 isCond = true; 00684 UOpc = ARM::B; 00685 // Fallthrough 00686 case ARM::B: 00687 Bits = 24; 00688 Scale = 4; 00689 break; 00690 case ARM::tBcc: 00691 isCond = true; 00692 UOpc = ARM::tB; 00693 Bits = 8; 00694 Scale = 2; 00695 break; 00696 case ARM::tB: 00697 Bits = 11; 00698 Scale = 2; 00699 break; 00700 case ARM::t2Bcc: 00701 isCond = true; 00702 UOpc = ARM::t2B; 00703 Bits = 20; 00704 Scale = 2; 00705 break; 00706 case ARM::t2B: 00707 Bits = 24; 00708 Scale = 2; 00709 break; 00710 } 00711 00712 // Record this immediate branch. 00713 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale; 00714 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc)); 00715 } 00716 00717 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET) 00718 PushPopMIs.push_back(I); 00719 00720 if (Opc == ARM::CONSTPOOL_ENTRY) 00721 continue; 00722 00723 // Scan the instructions for constant pool operands. 00724 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) 00725 if (I->getOperand(op).isCPI()) { 00726 // We found one. The addressing mode tells us the max displacement 00727 // from the PC that this instruction permits. 00728 00729 // Basic size info comes from the TSFlags field. 00730 unsigned Bits = 0; 00731 unsigned Scale = 1; 00732 bool NegOk = false; 00733 bool IsSoImm = false; 00734 00735 switch (Opc) { 00736 default: 00737 llvm_unreachable("Unknown addressing mode for CP reference!"); 00738 00739 // Taking the address of a CP entry. 00740 case ARM::LEApcrel: 00741 // This takes a SoImm, which is 8 bit immediate rotated. We'll 00742 // pretend the maximum offset is 255 * 4. Since each instruction 00743 // 4 byte wide, this is always correct. We'll check for other 00744 // displacements that fits in a SoImm as well. 00745 Bits = 8; 00746 Scale = 4; 00747 NegOk = true; 00748 IsSoImm = true; 00749 break; 00750 case ARM::t2LEApcrel: 00751 Bits = 12; 00752 NegOk = true; 00753 break; 00754 case ARM::tLEApcrel: 00755 Bits = 8; 00756 Scale = 4; 00757 break; 00758 00759 case ARM::LDRBi12: 00760 case ARM::LDRi12: 00761 case ARM::LDRcp: 00762 case ARM::t2LDRpci: 00763 Bits = 12; // +-offset_12 00764 NegOk = true; 00765 break; 00766 00767 case ARM::tLDRpci: 00768 Bits = 8; 00769 Scale = 4; // +(offset_8*4) 00770 break; 00771 00772 case ARM::VLDRD: 00773 case ARM::VLDRS: 00774 Bits = 8; 00775 Scale = 4; // +-(offset_8*4) 00776 NegOk = true; 00777 break; 00778 } 00779 00780 // Remember that this is a user of a CP entry. 00781 unsigned CPI = I->getOperand(op).getIndex(); 00782 MachineInstr *CPEMI = CPEMIs[CPI]; 00783 unsigned MaxOffs = ((1 << Bits)-1) * Scale; 00784 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm)); 00785 00786 // Increment corresponding CPEntry reference count. 00787 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI); 00788 assert(CPE && "Cannot find a corresponding CPEntry!"); 00789 CPE->RefCount++; 00790 00791 // Instructions can only use one CP entry, don't bother scanning the 00792 // rest of the operands. 00793 break; 00794 } 00795 } 00796 } 00797 } 00798 00799 /// computeBlockSize - Compute the size and some alignment information for MBB. 00800 /// This function updates BBInfo directly. 00801 void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) { 00802 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()]; 00803 BBI.Size = 0; 00804 BBI.Unalign = 0; 00805 BBI.PostAlign = 0; 00806 00807 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; 00808 ++I) { 00809 BBI.Size += TII->GetInstSizeInBytes(I); 00810 // For inline asm, GetInstSizeInBytes returns a conservative estimate. 00811 // The actual size may be smaller, but still a multiple of the instr size. 00812 if (I->isInlineAsm()) 00813 BBI.Unalign = isThumb ? 1 : 2; 00814 // Also consider instructions that may be shrunk later. 00815 else if (isThumb && mayOptimizeThumb2Instruction(I)) 00816 BBI.Unalign = 1; 00817 } 00818 00819 // tBR_JTr contains a .align 2 directive. 00820 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) { 00821 BBI.PostAlign = 2; 00822 MBB->getParent()->ensureAlignment(2); 00823 } 00824 } 00825 00826 /// getOffsetOf - Return the current offset of the specified machine instruction 00827 /// from the start of the function. This offset changes as stuff is moved 00828 /// around inside the function. 00829 unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const { 00830 MachineBasicBlock *MBB = MI->getParent(); 00831 00832 // The offset is composed of two things: the sum of the sizes of all MBB's 00833 // before this instruction's block, and the offset from the start of the block 00834 // it is in. 00835 unsigned Offset = BBInfo[MBB->getNumber()].Offset; 00836 00837 // Sum instructions before MI in MBB. 00838 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) { 00839 assert(I != MBB->end() && "Didn't find MI in its own basic block?"); 00840 Offset += TII->GetInstSizeInBytes(I); 00841 } 00842 return Offset; 00843 } 00844 00845 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB 00846 /// ID. 00847 static bool CompareMBBNumbers(const MachineBasicBlock *LHS, 00848 const MachineBasicBlock *RHS) { 00849 return LHS->getNumber() < RHS->getNumber(); 00850 } 00851 00852 /// updateForInsertedWaterBlock - When a block is newly inserted into the 00853 /// machine function, it upsets all of the block numbers. Renumber the blocks 00854 /// and update the arrays that parallel this numbering. 00855 void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) { 00856 // Renumber the MBB's to keep them consecutive. 00857 NewBB->getParent()->RenumberBlocks(NewBB); 00858 00859 // Insert an entry into BBInfo to align it properly with the (newly 00860 // renumbered) block numbers. 00861 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo()); 00862 00863 // Next, update WaterList. Specifically, we need to add NewMBB as having 00864 // available water after it. 00865 water_iterator IP = 00866 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB, 00867 CompareMBBNumbers); 00868 WaterList.insert(IP, NewBB); 00869 } 00870 00871 00872 /// Split the basic block containing MI into two blocks, which are joined by 00873 /// an unconditional branch. Update data structures and renumber blocks to 00874 /// account for this change and returns the newly created block. 00875 MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) { 00876 MachineBasicBlock *OrigBB = MI->getParent(); 00877 00878 // Create a new MBB for the code after the OrigBB. 00879 MachineBasicBlock *NewBB = 00880 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock()); 00881 MachineFunction::iterator MBBI = OrigBB; ++MBBI; 00882 MF->insert(MBBI, NewBB); 00883 00884 // Splice the instructions starting with MI over to NewBB. 00885 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end()); 00886 00887 // Add an unconditional branch from OrigBB to NewBB. 00888 // Note the new unconditional branch is not being recorded. 00889 // There doesn't seem to be meaningful DebugInfo available; this doesn't 00890 // correspond to anything in the source. 00891 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B; 00892 if (!isThumb) 00893 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB); 00894 else 00895 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB) 00896 .addImm(ARMCC::AL).addReg(0); 00897 ++NumSplit; 00898 00899 // Update the CFG. All succs of OrigBB are now succs of NewBB. 00900 NewBB->transferSuccessors(OrigBB); 00901 00902 // OrigBB branches to NewBB. 00903 OrigBB->addSuccessor(NewBB); 00904 00905 // Update internal data structures to account for the newly inserted MBB. 00906 // This is almost the same as updateForInsertedWaterBlock, except that 00907 // the Water goes after OrigBB, not NewBB. 00908 MF->RenumberBlocks(NewBB); 00909 00910 // Insert an entry into BBInfo to align it properly with the (newly 00911 // renumbered) block numbers. 00912 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo()); 00913 00914 // Next, update WaterList. Specifically, we need to add OrigMBB as having 00915 // available water after it (but not if it's already there, which happens 00916 // when splitting before a conditional branch that is followed by an 00917 // unconditional branch - in that case we want to insert NewBB). 00918 water_iterator IP = 00919 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB, 00920 CompareMBBNumbers); 00921 MachineBasicBlock* WaterBB = *IP; 00922 if (WaterBB == OrigBB) 00923 WaterList.insert(std::next(IP), NewBB); 00924 else 00925 WaterList.insert(IP, OrigBB); 00926 NewWaterList.insert(OrigBB); 00927 00928 // Figure out how large the OrigBB is. As the first half of the original 00929 // block, it cannot contain a tablejump. The size includes 00930 // the new jump we added. (It should be possible to do this without 00931 // recounting everything, but it's very confusing, and this is rarely 00932 // executed.) 00933 computeBlockSize(OrigBB); 00934 00935 // Figure out how large the NewMBB is. As the second half of the original 00936 // block, it may contain a tablejump. 00937 computeBlockSize(NewBB); 00938 00939 // All BBOffsets following these blocks must be modified. 00940 adjustBBOffsetsAfter(OrigBB); 00941 00942 return NewBB; 00943 } 00944 00945 /// getUserOffset - Compute the offset of U.MI as seen by the hardware 00946 /// displacement computation. Update U.KnownAlignment to match its current 00947 /// basic block location. 00948 unsigned ARMConstantIslands::getUserOffset(CPUser &U) const { 00949 unsigned UserOffset = getOffsetOf(U.MI); 00950 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()]; 00951 unsigned KnownBits = BBI.internalKnownBits(); 00952 00953 // The value read from PC is offset from the actual instruction address. 00954 UserOffset += (isThumb ? 4 : 8); 00955 00956 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI. 00957 // Make sure U.getMaxDisp() returns a constrained range. 00958 U.KnownAlignment = (KnownBits >= 2); 00959 00960 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for 00961 // purposes of the displacement computation; compensate for that here. 00962 // For unknown alignments, getMaxDisp() constrains the range instead. 00963 if (isThumb && U.KnownAlignment) 00964 UserOffset &= ~3u; 00965 00966 return UserOffset; 00967 } 00968 00969 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool 00970 /// reference) is within MaxDisp of TrialOffset (a proposed location of a 00971 /// constant pool entry). 00972 /// UserOffset is computed by getUserOffset above to include PC adjustments. If 00973 /// the mod 4 alignment of UserOffset is not known, the uncertainty must be 00974 /// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that. 00975 bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset, 00976 unsigned TrialOffset, unsigned MaxDisp, 00977 bool NegativeOK, bool IsSoImm) { 00978 if (UserOffset <= TrialOffset) { 00979 // User before the Trial. 00980 if (TrialOffset - UserOffset <= MaxDisp) 00981 return true; 00982 // FIXME: Make use full range of soimm values. 00983 } else if (NegativeOK) { 00984 if (UserOffset - TrialOffset <= MaxDisp) 00985 return true; 00986 // FIXME: Make use full range of soimm values. 00987 } 00988 return false; 00989 } 00990 00991 /// isWaterInRange - Returns true if a CPE placed after the specified 00992 /// Water (a basic block) will be in range for the specific MI. 00993 /// 00994 /// Compute how much the function will grow by inserting a CPE after Water. 00995 bool ARMConstantIslands::isWaterInRange(unsigned UserOffset, 00996 MachineBasicBlock* Water, CPUser &U, 00997 unsigned &Growth) { 00998 unsigned CPELogAlign = getCPELogAlign(U.CPEMI); 00999 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign); 01000 unsigned NextBlockOffset, NextBlockAlignment; 01001 MachineFunction::const_iterator NextBlock = Water; 01002 if (++NextBlock == MF->end()) { 01003 NextBlockOffset = BBInfo[Water->getNumber()].postOffset(); 01004 NextBlockAlignment = 0; 01005 } else { 01006 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset; 01007 NextBlockAlignment = NextBlock->getAlignment(); 01008 } 01009 unsigned Size = U.CPEMI->getOperand(2).getImm(); 01010 unsigned CPEEnd = CPEOffset + Size; 01011 01012 // The CPE may be able to hide in the alignment padding before the next 01013 // block. It may also cause more padding to be required if it is more aligned 01014 // that the next block. 01015 if (CPEEnd > NextBlockOffset) { 01016 Growth = CPEEnd - NextBlockOffset; 01017 // Compute the padding that would go at the end of the CPE to align the next 01018 // block. 01019 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment); 01020 01021 // If the CPE is to be inserted before the instruction, that will raise 01022 // the offset of the instruction. Also account for unknown alignment padding 01023 // in blocks between CPE and the user. 01024 if (CPEOffset < UserOffset) 01025 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign); 01026 } else 01027 // CPE fits in existing padding. 01028 Growth = 0; 01029 01030 return isOffsetInRange(UserOffset, CPEOffset, U); 01031 } 01032 01033 /// isCPEntryInRange - Returns true if the distance between specific MI and 01034 /// specific ConstPool entry instruction can fit in MI's displacement field. 01035 bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset, 01036 MachineInstr *CPEMI, unsigned MaxDisp, 01037 bool NegOk, bool DoDump) { 01038 unsigned CPEOffset = getOffsetOf(CPEMI); 01039 01040 if (DoDump) { 01041 DEBUG({ 01042 unsigned Block = MI->getParent()->getNumber(); 01043 const BasicBlockInfo &BBI = BBInfo[Block]; 01044 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm() 01045 << " max delta=" << MaxDisp 01046 << format(" insn address=%#x", UserOffset) 01047 << " in BB#" << Block << ": " 01048 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI 01049 << format("CPE address=%#x offset=%+d: ", CPEOffset, 01050 int(CPEOffset-UserOffset)); 01051 }); 01052 } 01053 01054 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk); 01055 } 01056 01057 #ifndef NDEBUG 01058 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor 01059 /// unconditionally branches to its only successor. 01060 static bool BBIsJumpedOver(MachineBasicBlock *MBB) { 01061 if (MBB->pred_size() != 1 || MBB->succ_size() != 1) 01062 return false; 01063 01064 MachineBasicBlock *Succ = *MBB->succ_begin(); 01065 MachineBasicBlock *Pred = *MBB->pred_begin(); 01066 MachineInstr *PredMI = &Pred->back(); 01067 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB 01068 || PredMI->getOpcode() == ARM::t2B) 01069 return PredMI->getOperand(0).getMBB() == Succ; 01070 return false; 01071 } 01072 #endif // NDEBUG 01073 01074 void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) { 01075 unsigned BBNum = BB->getNumber(); 01076 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) { 01077 // Get the offset and known bits at the end of the layout predecessor. 01078 // Include the alignment of the current block. 01079 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment(); 01080 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign); 01081 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign); 01082 01083 // This is where block i begins. Stop if the offset is already correct, 01084 // and we have updated 2 blocks. This is the maximum number of blocks 01085 // changed before calling this function. 01086 if (i > BBNum + 2 && 01087 BBInfo[i].Offset == Offset && 01088 BBInfo[i].KnownBits == KnownBits) 01089 break; 01090 01091 BBInfo[i].Offset = Offset; 01092 BBInfo[i].KnownBits = KnownBits; 01093 } 01094 } 01095 01096 /// decrementCPEReferenceCount - find the constant pool entry with index CPI 01097 /// and instruction CPEMI, and decrement its refcount. If the refcount 01098 /// becomes 0 remove the entry and instruction. Returns true if we removed 01099 /// the entry, false if we didn't. 01100 01101 bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI, 01102 MachineInstr *CPEMI) { 01103 // Find the old entry. Eliminate it if it is no longer used. 01104 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI); 01105 assert(CPE && "Unexpected!"); 01106 if (--CPE->RefCount == 0) { 01107 removeDeadCPEMI(CPEMI); 01108 CPE->CPEMI = nullptr; 01109 --NumCPEs; 01110 return true; 01111 } 01112 return false; 01113 } 01114 01115 /// LookForCPEntryInRange - see if the currently referenced CPE is in range; 01116 /// if not, see if an in-range clone of the CPE is in range, and if so, 01117 /// change the data structures so the user references the clone. Returns: 01118 /// 0 = no existing entry found 01119 /// 1 = entry found, and there were no code insertions or deletions 01120 /// 2 = entry found, and there were code insertions or deletions 01121 int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset) 01122 { 01123 MachineInstr *UserMI = U.MI; 01124 MachineInstr *CPEMI = U.CPEMI; 01125 01126 // Check to see if the CPE is already in-range. 01127 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk, 01128 true)) { 01129 DEBUG(dbgs() << "In range\n"); 01130 return 1; 01131 } 01132 01133 // No. Look for previously created clones of the CPE that are in range. 01134 unsigned CPI = CPEMI->getOperand(1).getIndex(); 01135 std::vector<CPEntry> &CPEs = CPEntries[CPI]; 01136 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) { 01137 // We already tried this one 01138 if (CPEs[i].CPEMI == CPEMI) 01139 continue; 01140 // Removing CPEs can leave empty entries, skip 01141 if (CPEs[i].CPEMI == nullptr) 01142 continue; 01143 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(), 01144 U.NegOk)) { 01145 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#" 01146 << CPEs[i].CPI << "\n"); 01147 // Point the CPUser node to the replacement 01148 U.CPEMI = CPEs[i].CPEMI; 01149 // Change the CPI in the instruction operand to refer to the clone. 01150 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j) 01151 if (UserMI->getOperand(j).isCPI()) { 01152 UserMI->getOperand(j).setIndex(CPEs[i].CPI); 01153 break; 01154 } 01155 // Adjust the refcount of the clone... 01156 CPEs[i].RefCount++; 01157 // ...and the original. If we didn't remove the old entry, none of the 01158 // addresses changed, so we don't need another pass. 01159 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1; 01160 } 01161 } 01162 return 0; 01163 } 01164 01165 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in 01166 /// the specific unconditional branch instruction. 01167 static inline unsigned getUnconditionalBrDisp(int Opc) { 01168 switch (Opc) { 01169 case ARM::tB: 01170 return ((1<<10)-1)*2; 01171 case ARM::t2B: 01172 return ((1<<23)-1)*2; 01173 default: 01174 break; 01175 } 01176 01177 return ((1<<23)-1)*4; 01178 } 01179 01180 /// findAvailableWater - Look for an existing entry in the WaterList in which 01181 /// we can place the CPE referenced from U so it's within range of U's MI. 01182 /// Returns true if found, false if not. If it returns true, WaterIter 01183 /// is set to the WaterList entry. For Thumb, prefer water that will not 01184 /// introduce padding to water that will. To ensure that this pass 01185 /// terminates, the CPE location for a particular CPUser is only allowed to 01186 /// move to a lower address, so search backward from the end of the list and 01187 /// prefer the first water that is in range. 01188 bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset, 01189 water_iterator &WaterIter) { 01190 if (WaterList.empty()) 01191 return false; 01192 01193 unsigned BestGrowth = ~0u; 01194 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();; 01195 --IP) { 01196 MachineBasicBlock* WaterBB = *IP; 01197 // Check if water is in range and is either at a lower address than the 01198 // current "high water mark" or a new water block that was created since 01199 // the previous iteration by inserting an unconditional branch. In the 01200 // latter case, we want to allow resetting the high water mark back to 01201 // this new water since we haven't seen it before. Inserting branches 01202 // should be relatively uncommon and when it does happen, we want to be 01203 // sure to take advantage of it for all the CPEs near that block, so that 01204 // we don't insert more branches than necessary. 01205 unsigned Growth; 01206 if (isWaterInRange(UserOffset, WaterBB, U, Growth) && 01207 (WaterBB->getNumber() < U.HighWaterMark->getNumber() || 01208 NewWaterList.count(WaterBB)) && Growth < BestGrowth) { 01209 // This is the least amount of required padding seen so far. 01210 BestGrowth = Growth; 01211 WaterIter = IP; 01212 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber() 01213 << " Growth=" << Growth << '\n'); 01214 01215 // Keep looking unless it is perfect. 01216 if (BestGrowth == 0) 01217 return true; 01218 } 01219 if (IP == B) 01220 break; 01221 } 01222 return BestGrowth != ~0u; 01223 } 01224 01225 /// createNewWater - No existing WaterList entry will work for 01226 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the 01227 /// block is used if in range, and the conditional branch munged so control 01228 /// flow is correct. Otherwise the block is split to create a hole with an 01229 /// unconditional branch around it. In either case NewMBB is set to a 01230 /// block following which the new island can be inserted (the WaterList 01231 /// is not adjusted). 01232 void ARMConstantIslands::createNewWater(unsigned CPUserIndex, 01233 unsigned UserOffset, 01234 MachineBasicBlock *&NewMBB) { 01235 CPUser &U = CPUsers[CPUserIndex]; 01236 MachineInstr *UserMI = U.MI; 01237 MachineInstr *CPEMI = U.CPEMI; 01238 unsigned CPELogAlign = getCPELogAlign(CPEMI); 01239 MachineBasicBlock *UserMBB = UserMI->getParent(); 01240 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()]; 01241 01242 // If the block does not end in an unconditional branch already, and if the 01243 // end of the block is within range, make new water there. (The addition 01244 // below is for the unconditional branch we will be adding: 4 bytes on ARM + 01245 // Thumb2, 2 on Thumb1. 01246 if (BBHasFallthrough(UserMBB)) { 01247 // Size of branch to insert. 01248 unsigned Delta = isThumb1 ? 2 : 4; 01249 // Compute the offset where the CPE will begin. 01250 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta; 01251 01252 if (isOffsetInRange(UserOffset, CPEOffset, U)) { 01253 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber() 01254 << format(", expected CPE offset %#x\n", CPEOffset)); 01255 NewMBB = std::next(MachineFunction::iterator(UserMBB)); 01256 // Add an unconditional branch from UserMBB to fallthrough block. Record 01257 // it for branch lengthening; this new branch will not get out of range, 01258 // but if the preceding conditional branch is out of range, the targets 01259 // will be exchanged, and the altered branch may be out of range, so the 01260 // machinery has to know about it. 01261 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B; 01262 if (!isThumb) 01263 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB); 01264 else 01265 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB) 01266 .addImm(ARMCC::AL).addReg(0); 01267 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr); 01268 ImmBranches.push_back(ImmBranch(&UserMBB->back(), 01269 MaxDisp, false, UncondBr)); 01270 BBInfo[UserMBB->getNumber()].Size += Delta; 01271 adjustBBOffsetsAfter(UserMBB); 01272 return; 01273 } 01274 } 01275 01276 // What a big block. Find a place within the block to split it. This is a 01277 // little tricky on Thumb1 since instructions are 2 bytes and constant pool 01278 // entries are 4 bytes: if instruction I references island CPE, and 01279 // instruction I+1 references CPE', it will not work well to put CPE as far 01280 // forward as possible, since then CPE' cannot immediately follow it (that 01281 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd 01282 // need to create a new island. So, we make a first guess, then walk through 01283 // the instructions between the one currently being looked at and the 01284 // possible insertion point, and make sure any other instructions that 01285 // reference CPEs will be able to use the same island area; if not, we back 01286 // up the insertion point. 01287 01288 // Try to split the block so it's fully aligned. Compute the latest split 01289 // point where we can add a 4-byte branch instruction, and then align to 01290 // LogAlign which is the largest possible alignment in the function. 01291 unsigned LogAlign = MF->getAlignment(); 01292 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry"); 01293 unsigned KnownBits = UserBBI.internalKnownBits(); 01294 unsigned UPad = UnknownPadding(LogAlign, KnownBits); 01295 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad; 01296 DEBUG(dbgs() << format("Split in middle of big block before %#x", 01297 BaseInsertOffset)); 01298 01299 // The 4 in the following is for the unconditional branch we'll be inserting 01300 // (allows for long branch on Thumb1). Alignment of the island is handled 01301 // inside isOffsetInRange. 01302 BaseInsertOffset -= 4; 01303 01304 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset) 01305 << " la=" << LogAlign 01306 << " kb=" << KnownBits 01307 << " up=" << UPad << '\n'); 01308 01309 // This could point off the end of the block if we've already got constant 01310 // pool entries following this block; only the last one is in the water list. 01311 // Back past any possible branches (allow for a conditional and a maximally 01312 // long unconditional). 01313 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) { 01314 BaseInsertOffset = UserBBI.postOffset() - UPad - 8; 01315 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset)); 01316 } 01317 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad + 01318 CPEMI->getOperand(2).getImm(); 01319 MachineBasicBlock::iterator MI = UserMI; 01320 ++MI; 01321 unsigned CPUIndex = CPUserIndex+1; 01322 unsigned NumCPUsers = CPUsers.size(); 01323 MachineInstr *LastIT = nullptr; 01324 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI); 01325 Offset < BaseInsertOffset; 01326 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) { 01327 assert(MI != UserMBB->end() && "Fell off end of block"); 01328 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) { 01329 CPUser &U = CPUsers[CPUIndex]; 01330 if (!isOffsetInRange(Offset, EndInsertOffset, U)) { 01331 // Shift intertion point by one unit of alignment so it is within reach. 01332 BaseInsertOffset -= 1u << LogAlign; 01333 EndInsertOffset -= 1u << LogAlign; 01334 } 01335 // This is overly conservative, as we don't account for CPEMIs being 01336 // reused within the block, but it doesn't matter much. Also assume CPEs 01337 // are added in order with alignment padding. We may eventually be able 01338 // to pack the aligned CPEs better. 01339 EndInsertOffset += U.CPEMI->getOperand(2).getImm(); 01340 CPUIndex++; 01341 } 01342 01343 // Remember the last IT instruction. 01344 if (MI->getOpcode() == ARM::t2IT) 01345 LastIT = MI; 01346 } 01347 01348 --MI; 01349 01350 // Avoid splitting an IT block. 01351 if (LastIT) { 01352 unsigned PredReg = 0; 01353 ARMCC::CondCodes CC = getITInstrPredicate(MI, PredReg); 01354 if (CC != ARMCC::AL) 01355 MI = LastIT; 01356 } 01357 NewMBB = splitBlockBeforeInstr(MI); 01358 } 01359 01360 /// handleConstantPoolUser - Analyze the specified user, checking to see if it 01361 /// is out-of-range. If so, pick up the constant pool value and move it some 01362 /// place in-range. Return true if we changed any addresses (thus must run 01363 /// another pass of branch lengthening), false otherwise. 01364 bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) { 01365 CPUser &U = CPUsers[CPUserIndex]; 01366 MachineInstr *UserMI = U.MI; 01367 MachineInstr *CPEMI = U.CPEMI; 01368 unsigned CPI = CPEMI->getOperand(1).getIndex(); 01369 unsigned Size = CPEMI->getOperand(2).getImm(); 01370 // Compute this only once, it's expensive. 01371 unsigned UserOffset = getUserOffset(U); 01372 01373 // See if the current entry is within range, or there is a clone of it 01374 // in range. 01375 int result = findInRangeCPEntry(U, UserOffset); 01376 if (result==1) return false; 01377 else if (result==2) return true; 01378 01379 // No existing clone of this CPE is within range. 01380 // We will be generating a new clone. Get a UID for it. 01381 unsigned ID = AFI->createPICLabelUId(); 01382 01383 // Look for water where we can place this CPE. 01384 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock(); 01385 MachineBasicBlock *NewMBB; 01386 water_iterator IP; 01387 if (findAvailableWater(U, UserOffset, IP)) { 01388 DEBUG(dbgs() << "Found water in range\n"); 01389 MachineBasicBlock *WaterBB = *IP; 01390 01391 // If the original WaterList entry was "new water" on this iteration, 01392 // propagate that to the new island. This is just keeping NewWaterList 01393 // updated to match the WaterList, which will be updated below. 01394 if (NewWaterList.erase(WaterBB)) 01395 NewWaterList.insert(NewIsland); 01396 01397 // The new CPE goes before the following block (NewMBB). 01398 NewMBB = std::next(MachineFunction::iterator(WaterBB)); 01399 01400 } else { 01401 // No water found. 01402 DEBUG(dbgs() << "No water found\n"); 01403 createNewWater(CPUserIndex, UserOffset, NewMBB); 01404 01405 // splitBlockBeforeInstr adds to WaterList, which is important when it is 01406 // called while handling branches so that the water will be seen on the 01407 // next iteration for constant pools, but in this context, we don't want 01408 // it. Check for this so it will be removed from the WaterList. 01409 // Also remove any entry from NewWaterList. 01410 MachineBasicBlock *WaterBB = std::prev(MachineFunction::iterator(NewMBB)); 01411 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB); 01412 if (IP != WaterList.end()) 01413 NewWaterList.erase(WaterBB); 01414 01415 // We are adding new water. Update NewWaterList. 01416 NewWaterList.insert(NewIsland); 01417 } 01418 01419 // Remove the original WaterList entry; we want subsequent insertions in 01420 // this vicinity to go after the one we're about to insert. This 01421 // considerably reduces the number of times we have to move the same CPE 01422 // more than once and is also important to ensure the algorithm terminates. 01423 if (IP != WaterList.end()) 01424 WaterList.erase(IP); 01425 01426 // Okay, we know we can put an island before NewMBB now, do it! 01427 MF->insert(NewMBB, NewIsland); 01428 01429 // Update internal data structures to account for the newly inserted MBB. 01430 updateForInsertedWaterBlock(NewIsland); 01431 01432 // Decrement the old entry, and remove it if refcount becomes 0. 01433 decrementCPEReferenceCount(CPI, CPEMI); 01434 01435 // Now that we have an island to add the CPE to, clone the original CPE and 01436 // add it to the island. 01437 U.HighWaterMark = NewIsland; 01438 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY)) 01439 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size); 01440 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1)); 01441 ++NumCPEs; 01442 01443 // Mark the basic block as aligned as required by the const-pool entry. 01444 NewIsland->setAlignment(getCPELogAlign(U.CPEMI)); 01445 01446 // Increase the size of the island block to account for the new entry. 01447 BBInfo[NewIsland->getNumber()].Size += Size; 01448 adjustBBOffsetsAfter(std::prev(MachineFunction::iterator(NewIsland))); 01449 01450 // Finally, change the CPI in the instruction operand to be ID. 01451 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i) 01452 if (UserMI->getOperand(i).isCPI()) { 01453 UserMI->getOperand(i).setIndex(ID); 01454 break; 01455 } 01456 01457 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI 01458 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset)); 01459 01460 return true; 01461 } 01462 01463 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update 01464 /// sizes and offsets of impacted basic blocks. 01465 void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) { 01466 MachineBasicBlock *CPEBB = CPEMI->getParent(); 01467 unsigned Size = CPEMI->getOperand(2).getImm(); 01468 CPEMI->eraseFromParent(); 01469 BBInfo[CPEBB->getNumber()].Size -= Size; 01470 // All succeeding offsets have the current size value added in, fix this. 01471 if (CPEBB->empty()) { 01472 BBInfo[CPEBB->getNumber()].Size = 0; 01473 01474 // This block no longer needs to be aligned. 01475 CPEBB->setAlignment(0); 01476 } else 01477 // Entries are sorted by descending alignment, so realign from the front. 01478 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin())); 01479 01480 adjustBBOffsetsAfter(CPEBB); 01481 // An island has only one predecessor BB and one successor BB. Check if 01482 // this BB's predecessor jumps directly to this BB's successor. This 01483 // shouldn't happen currently. 01484 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?"); 01485 // FIXME: remove the empty blocks after all the work is done? 01486 } 01487 01488 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts 01489 /// are zero. 01490 bool ARMConstantIslands::removeUnusedCPEntries() { 01491 unsigned MadeChange = false; 01492 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) { 01493 std::vector<CPEntry> &CPEs = CPEntries[i]; 01494 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) { 01495 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) { 01496 removeDeadCPEMI(CPEs[j].CPEMI); 01497 CPEs[j].CPEMI = nullptr; 01498 MadeChange = true; 01499 } 01500 } 01501 } 01502 return MadeChange; 01503 } 01504 01505 /// isBBInRange - Returns true if the distance between specific MI and 01506 /// specific BB can fit in MI's displacement field. 01507 bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB, 01508 unsigned MaxDisp) { 01509 unsigned PCAdj = isThumb ? 4 : 8; 01510 unsigned BrOffset = getOffsetOf(MI) + PCAdj; 01511 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset; 01512 01513 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber() 01514 << " from BB#" << MI->getParent()->getNumber() 01515 << " max delta=" << MaxDisp 01516 << " from " << getOffsetOf(MI) << " to " << DestOffset 01517 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI); 01518 01519 if (BrOffset <= DestOffset) { 01520 // Branch before the Dest. 01521 if (DestOffset-BrOffset <= MaxDisp) 01522 return true; 01523 } else { 01524 if (BrOffset-DestOffset <= MaxDisp) 01525 return true; 01526 } 01527 return false; 01528 } 01529 01530 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far 01531 /// away to fit in its displacement field. 01532 bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) { 01533 MachineInstr *MI = Br.MI; 01534 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB(); 01535 01536 // Check to see if the DestBB is already in-range. 01537 if (isBBInRange(MI, DestBB, Br.MaxDisp)) 01538 return false; 01539 01540 if (!Br.isCond) 01541 return fixupUnconditionalBr(Br); 01542 return fixupConditionalBr(Br); 01543 } 01544 01545 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is 01546 /// too far away to fit in its displacement field. If the LR register has been 01547 /// spilled in the epilogue, then we can use BL to implement a far jump. 01548 /// Otherwise, add an intermediate branch instruction to a branch. 01549 bool 01550 ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) { 01551 MachineInstr *MI = Br.MI; 01552 MachineBasicBlock *MBB = MI->getParent(); 01553 if (!isThumb1) 01554 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!"); 01555 01556 // Use BL to implement far jump. 01557 Br.MaxDisp = (1 << 21) * 2; 01558 MI->setDesc(TII->get(ARM::tBfar)); 01559 BBInfo[MBB->getNumber()].Size += 2; 01560 adjustBBOffsetsAfter(MBB); 01561 HasFarJump = true; 01562 ++NumUBrFixed; 01563 01564 DEBUG(dbgs() << " Changed B to long jump " << *MI); 01565 01566 return true; 01567 } 01568 01569 /// fixupConditionalBr - Fix up a conditional branch whose destination is too 01570 /// far away to fit in its displacement field. It is converted to an inverse 01571 /// conditional branch + an unconditional branch to the destination. 01572 bool 01573 ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) { 01574 MachineInstr *MI = Br.MI; 01575 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB(); 01576 01577 // Add an unconditional branch to the destination and invert the branch 01578 // condition to jump over it: 01579 // blt L1 01580 // => 01581 // bge L2 01582 // b L1 01583 // L2: 01584 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm(); 01585 CC = ARMCC::getOppositeCondition(CC); 01586 unsigned CCReg = MI->getOperand(2).getReg(); 01587 01588 // If the branch is at the end of its MBB and that has a fall-through block, 01589 // direct the updated conditional branch to the fall-through block. Otherwise, 01590 // split the MBB before the next instruction. 01591 MachineBasicBlock *MBB = MI->getParent(); 01592 MachineInstr *BMI = &MBB->back(); 01593 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB); 01594 01595 ++NumCBrFixed; 01596 if (BMI != MI) { 01597 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) && 01598 BMI->getOpcode() == Br.UncondBr) { 01599 // Last MI in the BB is an unconditional branch. Can we simply invert the 01600 // condition and swap destinations: 01601 // beq L1 01602 // b L2 01603 // => 01604 // bne L2 01605 // b L1 01606 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB(); 01607 if (isBBInRange(MI, NewDest, Br.MaxDisp)) { 01608 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with " 01609 << *BMI); 01610 BMI->getOperand(0).setMBB(DestBB); 01611 MI->getOperand(0).setMBB(NewDest); 01612 MI->getOperand(1).setImm(CC); 01613 return true; 01614 } 01615 } 01616 } 01617 01618 if (NeedSplit) { 01619 splitBlockBeforeInstr(MI); 01620 // No need for the branch to the next block. We're adding an unconditional 01621 // branch to the destination. 01622 int delta = TII->GetInstSizeInBytes(&MBB->back()); 01623 BBInfo[MBB->getNumber()].Size -= delta; 01624 MBB->back().eraseFromParent(); 01625 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below 01626 } 01627 MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB)); 01628 01629 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber() 01630 << " also invert condition and change dest. to BB#" 01631 << NextBB->getNumber() << "\n"); 01632 01633 // Insert a new conditional branch and a new unconditional branch. 01634 // Also update the ImmBranch as well as adding a new entry for the new branch. 01635 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode())) 01636 .addMBB(NextBB).addImm(CC).addReg(CCReg); 01637 Br.MI = &MBB->back(); 01638 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back()); 01639 if (isThumb) 01640 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB) 01641 .addImm(ARMCC::AL).addReg(0); 01642 else 01643 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB); 01644 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back()); 01645 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr); 01646 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr)); 01647 01648 // Remove the old conditional branch. It may or may not still be in MBB. 01649 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI); 01650 MI->eraseFromParent(); 01651 adjustBBOffsetsAfter(MBB); 01652 return true; 01653 } 01654 01655 /// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills 01656 /// LR / restores LR to pc. FIXME: This is done here because it's only possible 01657 /// to do this if tBfar is not used. 01658 bool ARMConstantIslands::undoLRSpillRestore() { 01659 bool MadeChange = false; 01660 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) { 01661 MachineInstr *MI = PushPopMIs[i]; 01662 // First two operands are predicates. 01663 if (MI->getOpcode() == ARM::tPOP_RET && 01664 MI->getOperand(2).getReg() == ARM::PC && 01665 MI->getNumExplicitOperands() == 3) { 01666 // Create the new insn and copy the predicate from the old. 01667 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET)) 01668 .addOperand(MI->getOperand(0)) 01669 .addOperand(MI->getOperand(1)); 01670 MI->eraseFromParent(); 01671 MadeChange = true; 01672 } 01673 } 01674 return MadeChange; 01675 } 01676 01677 // mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions 01678 // below may shrink MI. 01679 bool 01680 ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const { 01681 switch(MI->getOpcode()) { 01682 // optimizeThumb2Instructions. 01683 case ARM::t2LEApcrel: 01684 case ARM::t2LDRpci: 01685 // optimizeThumb2Branches. 01686 case ARM::t2B: 01687 case ARM::t2Bcc: 01688 case ARM::tBcc: 01689 // optimizeThumb2JumpTables. 01690 case ARM::t2BR_JT: 01691 return true; 01692 } 01693 return false; 01694 } 01695 01696 bool ARMConstantIslands::optimizeThumb2Instructions() { 01697 bool MadeChange = false; 01698 01699 // Shrink ADR and LDR from constantpool. 01700 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) { 01701 CPUser &U = CPUsers[i]; 01702 unsigned Opcode = U.MI->getOpcode(); 01703 unsigned NewOpc = 0; 01704 unsigned Scale = 1; 01705 unsigned Bits = 0; 01706 switch (Opcode) { 01707 default: break; 01708 case ARM::t2LEApcrel: 01709 if (isARMLowRegister(U.MI->getOperand(0).getReg())) { 01710 NewOpc = ARM::tLEApcrel; 01711 Bits = 8; 01712 Scale = 4; 01713 } 01714 break; 01715 case ARM::t2LDRpci: 01716 if (isARMLowRegister(U.MI->getOperand(0).getReg())) { 01717 NewOpc = ARM::tLDRpci; 01718 Bits = 8; 01719 Scale = 4; 01720 } 01721 break; 01722 } 01723 01724 if (!NewOpc) 01725 continue; 01726 01727 unsigned UserOffset = getUserOffset(U); 01728 unsigned MaxOffs = ((1 << Bits) - 1) * Scale; 01729 01730 // Be conservative with inline asm. 01731 if (!U.KnownAlignment) 01732 MaxOffs -= 2; 01733 01734 // FIXME: Check if offset is multiple of scale if scale is not 4. 01735 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) { 01736 DEBUG(dbgs() << "Shrink: " << *U.MI); 01737 U.MI->setDesc(TII->get(NewOpc)); 01738 MachineBasicBlock *MBB = U.MI->getParent(); 01739 BBInfo[MBB->getNumber()].Size -= 2; 01740 adjustBBOffsetsAfter(MBB); 01741 ++NumT2CPShrunk; 01742 MadeChange = true; 01743 } 01744 } 01745 01746 MadeChange |= optimizeThumb2Branches(); 01747 MadeChange |= optimizeThumb2JumpTables(); 01748 return MadeChange; 01749 } 01750 01751 bool ARMConstantIslands::optimizeThumb2Branches() { 01752 bool MadeChange = false; 01753 01754 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) { 01755 ImmBranch &Br = ImmBranches[i]; 01756 unsigned Opcode = Br.MI->getOpcode(); 01757 unsigned NewOpc = 0; 01758 unsigned Scale = 1; 01759 unsigned Bits = 0; 01760 switch (Opcode) { 01761 default: break; 01762 case ARM::t2B: 01763 NewOpc = ARM::tB; 01764 Bits = 11; 01765 Scale = 2; 01766 break; 01767 case ARM::t2Bcc: { 01768 NewOpc = ARM::tBcc; 01769 Bits = 8; 01770 Scale = 2; 01771 break; 01772 } 01773 } 01774 if (NewOpc) { 01775 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale; 01776 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB(); 01777 if (isBBInRange(Br.MI, DestBB, MaxOffs)) { 01778 DEBUG(dbgs() << "Shrink branch: " << *Br.MI); 01779 Br.MI->setDesc(TII->get(NewOpc)); 01780 MachineBasicBlock *MBB = Br.MI->getParent(); 01781 BBInfo[MBB->getNumber()].Size -= 2; 01782 adjustBBOffsetsAfter(MBB); 01783 ++NumT2BrShrunk; 01784 MadeChange = true; 01785 } 01786 } 01787 01788 Opcode = Br.MI->getOpcode(); 01789 if (Opcode != ARM::tBcc) 01790 continue; 01791 01792 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout 01793 // so this transformation is not safe. 01794 if (!Br.MI->killsRegister(ARM::CPSR)) 01795 continue; 01796 01797 NewOpc = 0; 01798 unsigned PredReg = 0; 01799 ARMCC::CondCodes Pred = getInstrPredicate(Br.MI, PredReg); 01800 if (Pred == ARMCC::EQ) 01801 NewOpc = ARM::tCBZ; 01802 else if (Pred == ARMCC::NE) 01803 NewOpc = ARM::tCBNZ; 01804 if (!NewOpc) 01805 continue; 01806 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB(); 01807 // Check if the distance is within 126. Subtract starting offset by 2 01808 // because the cmp will be eliminated. 01809 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2; 01810 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset; 01811 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) { 01812 MachineBasicBlock::iterator CmpMI = Br.MI; 01813 if (CmpMI != Br.MI->getParent()->begin()) { 01814 --CmpMI; 01815 if (CmpMI->getOpcode() == ARM::tCMPi8) { 01816 unsigned Reg = CmpMI->getOperand(0).getReg(); 01817 Pred = getInstrPredicate(CmpMI, PredReg); 01818 if (Pred == ARMCC::AL && 01819 CmpMI->getOperand(1).getImm() == 0 && 01820 isARMLowRegister(Reg)) { 01821 MachineBasicBlock *MBB = Br.MI->getParent(); 01822 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI); 01823 MachineInstr *NewBR = 01824 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc)) 01825 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags()); 01826 CmpMI->eraseFromParent(); 01827 Br.MI->eraseFromParent(); 01828 Br.MI = NewBR; 01829 BBInfo[MBB->getNumber()].Size -= 2; 01830 adjustBBOffsetsAfter(MBB); 01831 ++NumCBZ; 01832 MadeChange = true; 01833 } 01834 } 01835 } 01836 } 01837 } 01838 01839 return MadeChange; 01840 } 01841 01842 /// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller 01843 /// jumptables when it's possible. 01844 bool ARMConstantIslands::optimizeThumb2JumpTables() { 01845 bool MadeChange = false; 01846 01847 // FIXME: After the tables are shrunk, can we get rid some of the 01848 // constantpool tables? 01849 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 01850 if (!MJTI) return false; 01851 01852 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 01853 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) { 01854 MachineInstr *MI = T2JumpTables[i]; 01855 const MCInstrDesc &MCID = MI->getDesc(); 01856 unsigned NumOps = MCID.getNumOperands(); 01857 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2); 01858 MachineOperand JTOP = MI->getOperand(JTOpIdx); 01859 unsigned JTI = JTOP.getIndex(); 01860 assert(JTI < JT.size()); 01861 01862 bool ByteOk = true; 01863 bool HalfWordOk = true; 01864 unsigned JTOffset = getOffsetOf(MI) + 4; 01865 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 01866 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) { 01867 MachineBasicBlock *MBB = JTBBs[j]; 01868 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset; 01869 // Negative offset is not ok. FIXME: We should change BB layout to make 01870 // sure all the branches are forward. 01871 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2) 01872 ByteOk = false; 01873 unsigned TBHLimit = ((1<<16)-1)*2; 01874 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit) 01875 HalfWordOk = false; 01876 if (!ByteOk && !HalfWordOk) 01877 break; 01878 } 01879 01880 if (ByteOk || HalfWordOk) { 01881 MachineBasicBlock *MBB = MI->getParent(); 01882 unsigned BaseReg = MI->getOperand(0).getReg(); 01883 bool BaseRegKill = MI->getOperand(0).isKill(); 01884 if (!BaseRegKill) 01885 continue; 01886 unsigned IdxReg = MI->getOperand(1).getReg(); 01887 bool IdxRegKill = MI->getOperand(1).isKill(); 01888 01889 // Scan backwards to find the instruction that defines the base 01890 // register. Due to post-RA scheduling, we can't count on it 01891 // immediately preceding the branch instruction. 01892 MachineBasicBlock::iterator PrevI = MI; 01893 MachineBasicBlock::iterator B = MBB->begin(); 01894 while (PrevI != B && !PrevI->definesRegister(BaseReg)) 01895 --PrevI; 01896 01897 // If for some reason we didn't find it, we can't do anything, so 01898 // just skip this one. 01899 if (!PrevI->definesRegister(BaseReg)) 01900 continue; 01901 01902 MachineInstr *AddrMI = PrevI; 01903 bool OptOk = true; 01904 // Examine the instruction that calculates the jumptable entry address. 01905 // Make sure it only defines the base register and kills any uses 01906 // other than the index register. 01907 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) { 01908 const MachineOperand &MO = AddrMI->getOperand(k); 01909 if (!MO.isReg() || !MO.getReg()) 01910 continue; 01911 if (MO.isDef() && MO.getReg() != BaseReg) { 01912 OptOk = false; 01913 break; 01914 } 01915 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) { 01916 OptOk = false; 01917 break; 01918 } 01919 } 01920 if (!OptOk) 01921 continue; 01922 01923 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction 01924 // that gave us the initial base register definition. 01925 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI) 01926 ; 01927 01928 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want 01929 // to delete it as well. 01930 MachineInstr *LeaMI = PrevI; 01931 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT && 01932 LeaMI->getOpcode() != ARM::t2LEApcrelJT) || 01933 LeaMI->getOperand(0).getReg() != BaseReg) 01934 OptOk = false; 01935 01936 if (!OptOk) 01937 continue; 01938 01939 DEBUG(dbgs() << "Shrink JT: " << *MI << " addr: " << *AddrMI 01940 << " lea: " << *LeaMI); 01941 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT; 01942 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc)) 01943 .addReg(IdxReg, getKillRegState(IdxRegKill)) 01944 .addJumpTableIndex(JTI, JTOP.getTargetFlags()) 01945 .addImm(MI->getOperand(JTOpIdx+1).getImm()); 01946 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI); 01947 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction 01948 // is 2-byte aligned. For now, asm printer will fix it up. 01949 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI); 01950 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI); 01951 OrigSize += TII->GetInstSizeInBytes(LeaMI); 01952 OrigSize += TII->GetInstSizeInBytes(MI); 01953 01954 AddrMI->eraseFromParent(); 01955 LeaMI->eraseFromParent(); 01956 MI->eraseFromParent(); 01957 01958 int delta = OrigSize - NewSize; 01959 BBInfo[MBB->getNumber()].Size -= delta; 01960 adjustBBOffsetsAfter(MBB); 01961 01962 ++NumTBs; 01963 MadeChange = true; 01964 } 01965 } 01966 01967 return MadeChange; 01968 } 01969 01970 /// reorderThumb2JumpTables - Adjust the function's block layout to ensure that 01971 /// jump tables always branch forwards, since that's what tbb and tbh need. 01972 bool ARMConstantIslands::reorderThumb2JumpTables() { 01973 bool MadeChange = false; 01974 01975 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 01976 if (!MJTI) return false; 01977 01978 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 01979 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) { 01980 MachineInstr *MI = T2JumpTables[i]; 01981 const MCInstrDesc &MCID = MI->getDesc(); 01982 unsigned NumOps = MCID.getNumOperands(); 01983 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2); 01984 MachineOperand JTOP = MI->getOperand(JTOpIdx); 01985 unsigned JTI = JTOP.getIndex(); 01986 assert(JTI < JT.size()); 01987 01988 // We prefer if target blocks for the jump table come after the jump 01989 // instruction so we can use TB[BH]. Loop through the target blocks 01990 // and try to adjust them such that that's true. 01991 int JTNumber = MI->getParent()->getNumber(); 01992 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 01993 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) { 01994 MachineBasicBlock *MBB = JTBBs[j]; 01995 int DTNumber = MBB->getNumber(); 01996 01997 if (DTNumber < JTNumber) { 01998 // The destination precedes the switch. Try to move the block forward 01999 // so we have a positive offset. 02000 MachineBasicBlock *NewBB = 02001 adjustJTTargetBlockForward(MBB, MI->getParent()); 02002 if (NewBB) 02003 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB); 02004 MadeChange = true; 02005 } 02006 } 02007 } 02008 02009 return MadeChange; 02010 } 02011 02012 MachineBasicBlock *ARMConstantIslands:: 02013 adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) { 02014 // If the destination block is terminated by an unconditional branch, 02015 // try to move it; otherwise, create a new block following the jump 02016 // table that branches back to the actual target. This is a very simple 02017 // heuristic. FIXME: We can definitely improve it. 02018 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 02019 SmallVector<MachineOperand, 4> Cond; 02020 SmallVector<MachineOperand, 4> CondPrior; 02021 MachineFunction::iterator BBi = BB; 02022 MachineFunction::iterator OldPrior = std::prev(BBi); 02023 02024 // If the block terminator isn't analyzable, don't try to move the block 02025 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond); 02026 02027 // If the block ends in an unconditional branch, move it. The prior block 02028 // has to have an analyzable terminator for us to move this one. Be paranoid 02029 // and make sure we're not trying to move the entry block of the function. 02030 if (!B && Cond.empty() && BB != MF->begin() && 02031 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) { 02032 BB->moveAfter(JTBB); 02033 OldPrior->updateTerminator(); 02034 BB->updateTerminator(); 02035 // Update numbering to account for the block being moved. 02036 MF->RenumberBlocks(); 02037 ++NumJTMoved; 02038 return nullptr; 02039 } 02040 02041 // Create a new MBB for the code after the jump BB. 02042 MachineBasicBlock *NewBB = 02043 MF->CreateMachineBasicBlock(JTBB->getBasicBlock()); 02044 MachineFunction::iterator MBBI = JTBB; ++MBBI; 02045 MF->insert(MBBI, NewBB); 02046 02047 // Add an unconditional branch from NewBB to BB. 02048 // There doesn't seem to be meaningful DebugInfo available; this doesn't 02049 // correspond directly to anything in the source. 02050 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?"); 02051 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB) 02052 .addImm(ARMCC::AL).addReg(0); 02053 02054 // Update internal data structures to account for the newly inserted MBB. 02055 MF->RenumberBlocks(NewBB); 02056 02057 // Update the CFG. 02058 NewBB->addSuccessor(BB); 02059 JTBB->removeSuccessor(BB); 02060 JTBB->addSuccessor(NewBB); 02061 02062 ++NumJTInserted; 02063 return NewBB; 02064 }