1 //===- ARMConstantIslandPass.cpp - ARM constant islands -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains a pass that splits the constant pool up into 'islands' 10 // which are scattered through-out the function. This is required due to the 11 // limited pc-relative displacements that ARM has. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ARM.h" 16 #include "ARMBaseInstrInfo.h" 17 #include "ARMBasicBlockInfo.h" 18 #include "ARMMachineFunctionInfo.h" 19 #include "ARMSubtarget.h" 20 #include "MCTargetDesc/ARMBaseInfo.h" 21 #include "Thumb2InstrInfo.h" 22 #include "Utils/ARMBaseInfo.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/ADT/SmallSet.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/Statistic.h" 28 #include "llvm/ADT/StringRef.h" 29 #include "llvm/CodeGen/LivePhysRegs.h" 30 #include "llvm/CodeGen/MachineBasicBlock.h" 31 #include "llvm/CodeGen/MachineConstantPool.h" 32 #include "llvm/CodeGen/MachineDominators.h" 33 #include "llvm/CodeGen/MachineFunction.h" 34 #include "llvm/CodeGen/MachineFunctionPass.h" 35 #include "llvm/CodeGen/MachineInstr.h" 36 #include "llvm/CodeGen/MachineJumpTableInfo.h" 37 #include "llvm/CodeGen/MachineOperand.h" 38 #include "llvm/CodeGen/MachineRegisterInfo.h" 39 #include "llvm/Config/llvm-config.h" 40 #include "llvm/IR/DataLayout.h" 41 #include "llvm/IR/DebugLoc.h" 42 #include "llvm/MC/MCInstrDesc.h" 43 #include "llvm/Pass.h" 44 #include "llvm/Support/CommandLine.h" 45 #include "llvm/Support/Compiler.h" 46 #include "llvm/Support/Debug.h" 47 #include "llvm/Support/ErrorHandling.h" 48 #include "llvm/Support/Format.h" 49 #include "llvm/Support/MathExtras.h" 50 #include "llvm/Support/raw_ostream.h" 51 #include <algorithm> 52 #include <cassert> 53 #include <cstdint> 54 #include <iterator> 55 #include <utility> 56 #include <vector> 57 58 using namespace llvm; 59 60 #define DEBUG_TYPE "arm-cp-islands" 61 62 #define ARM_CP_ISLANDS_OPT_NAME \ 63 "ARM constant island placement and branch shortening pass" 64 STATISTIC(NumCPEs, "Number of constpool entries"); 65 STATISTIC(NumSplit, "Number of uncond branches inserted"); 66 STATISTIC(NumCBrFixed, "Number of cond branches fixed"); 67 STATISTIC(NumUBrFixed, "Number of uncond branches fixed"); 68 STATISTIC(NumTBs, "Number of table branches generated"); 69 STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk"); 70 STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk"); 71 STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed"); 72 STATISTIC(NumJTMoved, "Number of jump table destination blocks moved"); 73 STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted"); 74 STATISTIC(NumLEInserted, "Number of LE backwards branches inserted"); 75 76 static cl::opt<bool> 77 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true), 78 cl::desc("Adjust basic block layout to better use TB[BH]")); 79 80 static cl::opt<unsigned> 81 CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden, cl::init(30), 82 cl::desc("The max number of iteration for converge")); 83 84 static cl::opt<bool> SynthesizeThumb1TBB( 85 "arm-synthesize-thumb-1-tbb", cl::Hidden, cl::init(true), 86 cl::desc("Use compressed jump tables in Thumb-1 by synthesizing an " 87 "equivalent to the TBB/TBH instructions")); 88 89 namespace { 90 91 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM 92 /// requires constant pool entries to be scattered among the instructions 93 /// inside a function. To do this, it completely ignores the normal LLVM 94 /// constant pool; instead, it places constants wherever it feels like with 95 /// special instructions. 96 /// 97 /// The terminology used in this pass includes: 98 /// Islands - Clumps of constants placed in the function. 99 /// Water - Potential places where an island could be formed. 100 /// CPE - A constant pool entry that has been placed somewhere, which 101 /// tracks a list of users. 102 class ARMConstantIslands : public MachineFunctionPass { 103 std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr; 104 105 /// WaterList - A sorted list of basic blocks where islands could be placed 106 /// (i.e. blocks that don't fall through to the following block, due 107 /// to a return, unreachable, or unconditional branch). 108 std::vector<MachineBasicBlock*> WaterList; 109 110 /// NewWaterList - The subset of WaterList that was created since the 111 /// previous iteration by inserting unconditional branches. 112 SmallSet<MachineBasicBlock*, 4> NewWaterList; 113 114 using water_iterator = std::vector<MachineBasicBlock *>::iterator; 115 116 /// CPUser - One user of a constant pool, keeping the machine instruction 117 /// pointer, the constant pool being referenced, and the max displacement 118 /// allowed from the instruction to the CP. The HighWaterMark records the 119 /// highest basic block where a new CPEntry can be placed. To ensure this 120 /// pass terminates, the CP entries are initially placed at the end of the 121 /// function and then move monotonically to lower addresses. The 122 /// exception to this rule is when the current CP entry for a particular 123 /// CPUser is out of range, but there is another CP entry for the same 124 /// constant value in range. We want to use the existing in-range CP 125 /// entry, but if it later moves out of range, the search for new water 126 /// should resume where it left off. The HighWaterMark is used to record 127 /// that point. 128 struct CPUser { 129 MachineInstr *MI; 130 MachineInstr *CPEMI; 131 MachineBasicBlock *HighWaterMark; 132 unsigned MaxDisp; 133 bool NegOk; 134 bool IsSoImm; 135 bool KnownAlignment = false; 136 137 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp, 138 bool neg, bool soimm) 139 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) { 140 HighWaterMark = CPEMI->getParent(); 141 } 142 143 /// getMaxDisp - Returns the maximum displacement supported by MI. 144 /// Correct for unknown alignment. 145 /// Conservatively subtract 2 bytes to handle weird alignment effects. 146 unsigned getMaxDisp() const { 147 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2; 148 } 149 }; 150 151 /// CPUsers - Keep track of all of the machine instructions that use various 152 /// constant pools and their max displacement. 153 std::vector<CPUser> CPUsers; 154 155 /// CPEntry - One per constant pool entry, keeping the machine instruction 156 /// pointer, the constpool index, and the number of CPUser's which 157 /// reference this entry. 158 struct CPEntry { 159 MachineInstr *CPEMI; 160 unsigned CPI; 161 unsigned RefCount; 162 163 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0) 164 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {} 165 }; 166 167 /// CPEntries - Keep track of all of the constant pool entry machine 168 /// instructions. For each original constpool index (i.e. those that existed 169 /// upon entry to this pass), it keeps a vector of entries. Original 170 /// elements are cloned as we go along; the clones are put in the vector of 171 /// the original element, but have distinct CPIs. 172 /// 173 /// The first half of CPEntries contains generic constants, the second half 174 /// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up 175 /// which vector it will be in here. 176 std::vector<std::vector<CPEntry>> CPEntries; 177 178 /// Maps a JT index to the offset in CPEntries containing copies of that 179 /// table. The equivalent map for a CONSTPOOL_ENTRY is the identity. 180 DenseMap<int, int> JumpTableEntryIndices; 181 182 /// Maps a JT index to the LEA that actually uses the index to calculate its 183 /// base address. 184 DenseMap<int, int> JumpTableUserIndices; 185 186 /// ImmBranch - One per immediate branch, keeping the machine instruction 187 /// pointer, conditional or unconditional, the max displacement, 188 /// and (if isCond is true) the corresponding unconditional branch 189 /// opcode. 190 struct ImmBranch { 191 MachineInstr *MI; 192 unsigned MaxDisp : 31; 193 bool isCond : 1; 194 unsigned UncondBr; 195 196 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr) 197 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {} 198 }; 199 200 /// ImmBranches - Keep track of all the immediate branch instructions. 201 std::vector<ImmBranch> ImmBranches; 202 203 /// PushPopMIs - Keep track of all the Thumb push / pop instructions. 204 SmallVector<MachineInstr*, 4> PushPopMIs; 205 206 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions. 207 SmallVector<MachineInstr*, 4> T2JumpTables; 208 209 MachineFunction *MF; 210 MachineConstantPool *MCP; 211 const ARMBaseInstrInfo *TII; 212 const ARMSubtarget *STI; 213 ARMFunctionInfo *AFI; 214 MachineDominatorTree *DT = nullptr; 215 bool isThumb; 216 bool isThumb1; 217 bool isThumb2; 218 bool isPositionIndependentOrROPI; 219 220 public: 221 static char ID; 222 223 ARMConstantIslands() : MachineFunctionPass(ID) {} 224 225 bool runOnMachineFunction(MachineFunction &MF) override; 226 227 void getAnalysisUsage(AnalysisUsage &AU) const override { 228 AU.addRequired<MachineDominatorTree>(); 229 MachineFunctionPass::getAnalysisUsage(AU); 230 } 231 232 MachineFunctionProperties getRequiredProperties() const override { 233 return MachineFunctionProperties().set( 234 MachineFunctionProperties::Property::NoVRegs); 235 } 236 237 StringRef getPassName() const override { 238 return ARM_CP_ISLANDS_OPT_NAME; 239 } 240 241 private: 242 void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs); 243 void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs); 244 bool BBHasFallthrough(MachineBasicBlock *MBB); 245 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI); 246 Align getCPEAlign(const MachineInstr *CPEMI); 247 void scanFunctionJumpTables(); 248 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs); 249 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI); 250 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB); 251 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI); 252 unsigned getCombinedIndex(const MachineInstr *CPEMI); 253 int findInRangeCPEntry(CPUser& U, unsigned UserOffset); 254 bool findAvailableWater(CPUser&U, unsigned UserOffset, 255 water_iterator &WaterIter, bool CloserWater); 256 void createNewWater(unsigned CPUserIndex, unsigned UserOffset, 257 MachineBasicBlock *&NewMBB); 258 bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater); 259 void removeDeadCPEMI(MachineInstr *CPEMI); 260 bool removeUnusedCPEntries(); 261 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset, 262 MachineInstr *CPEMI, unsigned Disp, bool NegOk, 263 bool DoDump = false); 264 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water, 265 CPUser &U, unsigned &Growth); 266 bool fixupImmediateBr(ImmBranch &Br); 267 bool fixupConditionalBr(ImmBranch &Br); 268 bool fixupUnconditionalBr(ImmBranch &Br); 269 bool optimizeThumb2Instructions(); 270 bool optimizeThumb2Branches(); 271 bool reorderThumb2JumpTables(); 272 bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI, 273 unsigned &DeadSize, bool &CanDeleteLEA, 274 bool &BaseRegKill); 275 bool optimizeThumb2JumpTables(); 276 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB, 277 MachineBasicBlock *JTBB); 278 279 unsigned getUserOffset(CPUser&) const; 280 void dumpBBs(); 281 void verify(); 282 283 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset, 284 unsigned Disp, bool NegativeOK, bool IsSoImm = false); 285 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset, 286 const CPUser &U) { 287 return isOffsetInRange(UserOffset, TrialOffset, 288 U.getMaxDisp(), U.NegOk, U.IsSoImm); 289 } 290 }; 291 292 } // end anonymous namespace 293 294 char ARMConstantIslands::ID = 0; 295 296 /// verify - check BBOffsets, BBSizes, alignment of islands 297 void ARMConstantIslands::verify() { 298 #ifndef NDEBUG 299 BBInfoVector &BBInfo = BBUtils->getBBInfo(); 300 assert(std::is_sorted(MF->begin(), MF->end(), 301 [&BBInfo](const MachineBasicBlock &LHS, 302 const MachineBasicBlock &RHS) { 303 return BBInfo[LHS.getNumber()].postOffset() < 304 BBInfo[RHS.getNumber()].postOffset(); 305 })); 306 LLVM_DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n"); 307 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) { 308 CPUser &U = CPUsers[i]; 309 unsigned UserOffset = getUserOffset(U); 310 // Verify offset using the real max displacement without the safety 311 // adjustment. 312 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk, 313 /* DoDump = */ true)) { 314 LLVM_DEBUG(dbgs() << "OK\n"); 315 continue; 316 } 317 LLVM_DEBUG(dbgs() << "Out of range.\n"); 318 dumpBBs(); 319 LLVM_DEBUG(MF->dump()); 320 llvm_unreachable("Constant pool entry out of range!"); 321 } 322 #endif 323 } 324 325 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 326 /// print block size and offset information - debugging 327 LLVM_DUMP_METHOD void ARMConstantIslands::dumpBBs() { 328 LLVM_DEBUG({ 329 BBInfoVector &BBInfo = BBUtils->getBBInfo(); 330 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) { 331 const BasicBlockInfo &BBI = BBInfo[J]; 332 dbgs() << format("%08x %bb.%u\t", BBI.Offset, J) 333 << " kb=" << unsigned(BBI.KnownBits) 334 << " ua=" << unsigned(BBI.Unalign) << " pa=" << Log2(BBI.PostAlign) 335 << format(" size=%#x\n", BBInfo[J].Size); 336 } 337 }); 338 } 339 #endif 340 341 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) { 342 MF = &mf; 343 MCP = mf.getConstantPool(); 344 BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(mf)); 345 346 LLVM_DEBUG(dbgs() << "***** ARMConstantIslands: " 347 << MCP->getConstants().size() << " CP entries, aligned to " 348 << MCP->getConstantPoolAlign().value() << " bytes *****\n"); 349 350 STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget()); 351 TII = STI->getInstrInfo(); 352 isPositionIndependentOrROPI = 353 STI->getTargetLowering()->isPositionIndependent() || STI->isROPI(); 354 AFI = MF->getInfo<ARMFunctionInfo>(); 355 DT = &getAnalysis<MachineDominatorTree>(); 356 357 isThumb = AFI->isThumbFunction(); 358 isThumb1 = AFI->isThumb1OnlyFunction(); 359 isThumb2 = AFI->isThumb2Function(); 360 361 bool GenerateTBB = isThumb2 || (isThumb1 && SynthesizeThumb1TBB); 362 363 // Renumber all of the machine basic blocks in the function, guaranteeing that 364 // the numbers agree with the position of the block in the function. 365 MF->RenumberBlocks(); 366 367 // Try to reorder and otherwise adjust the block layout to make good use 368 // of the TB[BH] instructions. 369 bool MadeChange = false; 370 if (GenerateTBB && AdjustJumpTableBlocks) { 371 scanFunctionJumpTables(); 372 MadeChange |= reorderThumb2JumpTables(); 373 // Data is out of date, so clear it. It'll be re-computed later. 374 T2JumpTables.clear(); 375 // Blocks may have shifted around. Keep the numbering up to date. 376 MF->RenumberBlocks(); 377 } 378 379 // Perform the initial placement of the constant pool entries. To start with, 380 // we put them all at the end of the function. 381 std::vector<MachineInstr*> CPEMIs; 382 if (!MCP->isEmpty()) 383 doInitialConstPlacement(CPEMIs); 384 385 if (MF->getJumpTableInfo()) 386 doInitialJumpTablePlacement(CPEMIs); 387 388 /// The next UID to take is the first unused one. 389 AFI->initPICLabelUId(CPEMIs.size()); 390 391 // Do the initial scan of the function, building up information about the 392 // sizes of each block, the location of all the water, and finding all of the 393 // constant pool users. 394 initializeFunctionInfo(CPEMIs); 395 CPEMIs.clear(); 396 LLVM_DEBUG(dumpBBs()); 397 398 // Functions with jump tables need an alignment of 4 because they use the ADR 399 // instruction, which aligns the PC to 4 bytes before adding an offset. 400 if (!T2JumpTables.empty()) 401 MF->ensureAlignment(Align(4)); 402 403 /// Remove dead constant pool entries. 404 MadeChange |= removeUnusedCPEntries(); 405 406 // Iteratively place constant pool entries and fix up branches until there 407 // is no change. 408 unsigned NoCPIters = 0, NoBRIters = 0; 409 while (true) { 410 LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n'); 411 bool CPChange = false; 412 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) 413 // For most inputs, it converges in no more than 5 iterations. 414 // If it doesn't end in 10, the input may have huge BB or many CPEs. 415 // In this case, we will try different heuristics. 416 CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2); 417 if (CPChange && ++NoCPIters > CPMaxIteration) 418 report_fatal_error("Constant Island pass failed to converge!"); 419 LLVM_DEBUG(dumpBBs()); 420 421 // Clear NewWaterList now. If we split a block for branches, it should 422 // appear as "new water" for the next iteration of constant pool placement. 423 NewWaterList.clear(); 424 425 LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n'); 426 bool BRChange = false; 427 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) 428 BRChange |= fixupImmediateBr(ImmBranches[i]); 429 if (BRChange && ++NoBRIters > 30) 430 report_fatal_error("Branch Fix Up pass failed to converge!"); 431 LLVM_DEBUG(dumpBBs()); 432 433 if (!CPChange && !BRChange) 434 break; 435 MadeChange = true; 436 } 437 438 // Shrink 32-bit Thumb2 load and store instructions. 439 if (isThumb2 && !STI->prefers32BitThumb()) 440 MadeChange |= optimizeThumb2Instructions(); 441 442 // Shrink 32-bit branch instructions. 443 if (isThumb && STI->hasV8MBaselineOps()) 444 MadeChange |= optimizeThumb2Branches(); 445 446 // Optimize jump tables using TBB / TBH. 447 if (GenerateTBB && !STI->genExecuteOnly()) 448 MadeChange |= optimizeThumb2JumpTables(); 449 450 // After a while, this might be made debug-only, but it is not expensive. 451 verify(); 452 453 // Save the mapping between original and cloned constpool entries. 454 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) { 455 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) { 456 const CPEntry & CPE = CPEntries[i][j]; 457 if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI()) 458 AFI->recordCPEClone(i, CPE.CPI); 459 } 460 } 461 462 LLVM_DEBUG(dbgs() << '\n'; dumpBBs()); 463 464 BBUtils->clear(); 465 WaterList.clear(); 466 CPUsers.clear(); 467 CPEntries.clear(); 468 JumpTableEntryIndices.clear(); 469 JumpTableUserIndices.clear(); 470 ImmBranches.clear(); 471 PushPopMIs.clear(); 472 T2JumpTables.clear(); 473 474 return MadeChange; 475 } 476 477 /// Perform the initial placement of the regular constant pool entries. 478 /// To start with, we put them all at the end of the function. 479 void 480 ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) { 481 // Create the basic block to hold the CPE's. 482 MachineBasicBlock *BB = MF->CreateMachineBasicBlock(); 483 MF->push_back(BB); 484 485 // MachineConstantPool measures alignment in bytes. 486 const Align MaxAlign = MCP->getConstantPoolAlign(); 487 const unsigned MaxLogAlign = Log2(MaxAlign); 488 489 // Mark the basic block as required by the const-pool. 490 BB->setAlignment(MaxAlign); 491 492 // The function needs to be as aligned as the basic blocks. The linker may 493 // move functions around based on their alignment. 494 MF->ensureAlignment(BB->getAlignment()); 495 496 // Order the entries in BB by descending alignment. That ensures correct 497 // alignment of all entries as long as BB is sufficiently aligned. Keep 498 // track of the insertion point for each alignment. We are going to bucket 499 // sort the entries as they are created. 500 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxLogAlign + 1, 501 BB->end()); 502 503 // Add all of the constants from the constant pool to the end block, use an 504 // identity mapping of CPI's to CPE's. 505 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants(); 506 507 const DataLayout &TD = MF->getDataLayout(); 508 for (unsigned i = 0, e = CPs.size(); i != e; ++i) { 509 unsigned Size = TD.getTypeAllocSize(CPs[i].getType()); 510 Align Alignment = CPs[i].getAlign(); 511 // Verify that all constant pool entries are a multiple of their alignment. 512 // If not, we would have to pad them out so that instructions stay aligned. 513 assert(isAligned(Alignment, Size) && "CP Entry not multiple of 4 bytes!"); 514 515 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment. 516 unsigned LogAlign = Log2(Alignment); 517 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign]; 518 MachineInstr *CPEMI = 519 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY)) 520 .addImm(i).addConstantPoolIndex(i).addImm(Size); 521 CPEMIs.push_back(CPEMI); 522 523 // Ensure that future entries with higher alignment get inserted before 524 // CPEMI. This is bucket sort with iterators. 525 for (unsigned a = LogAlign + 1; a <= MaxLogAlign; ++a) 526 if (InsPoint[a] == InsAt) 527 InsPoint[a] = CPEMI; 528 529 // Add a new CPEntry, but no corresponding CPUser yet. 530 CPEntries.emplace_back(1, CPEntry(CPEMI, i)); 531 ++NumCPEs; 532 LLVM_DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = " 533 << Size << ", align = " << Alignment.value() << '\n'); 534 } 535 LLVM_DEBUG(BB->dump()); 536 } 537 538 /// Do initial placement of the jump tables. Because Thumb2's TBB and TBH 539 /// instructions can be made more efficient if the jump table immediately 540 /// follows the instruction, it's best to place them immediately next to their 541 /// jumps to begin with. In almost all cases they'll never be moved from that 542 /// position. 543 void ARMConstantIslands::doInitialJumpTablePlacement( 544 std::vector<MachineInstr *> &CPEMIs) { 545 unsigned i = CPEntries.size(); 546 auto MJTI = MF->getJumpTableInfo(); 547 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 548 549 MachineBasicBlock *LastCorrectlyNumberedBB = nullptr; 550 for (MachineBasicBlock &MBB : *MF) { 551 auto MI = MBB.getLastNonDebugInstr(); 552 if (MI == MBB.end()) 553 continue; 554 555 unsigned JTOpcode; 556 switch (MI->getOpcode()) { 557 default: 558 continue; 559 case ARM::BR_JTadd: 560 case ARM::BR_JTr: 561 case ARM::tBR_JTr: 562 case ARM::BR_JTm_i12: 563 case ARM::BR_JTm_rs: 564 JTOpcode = ARM::JUMPTABLE_ADDRS; 565 break; 566 case ARM::t2BR_JT: 567 JTOpcode = ARM::JUMPTABLE_INSTS; 568 break; 569 case ARM::tTBB_JT: 570 case ARM::t2TBB_JT: 571 JTOpcode = ARM::JUMPTABLE_TBB; 572 break; 573 case ARM::tTBH_JT: 574 case ARM::t2TBH_JT: 575 JTOpcode = ARM::JUMPTABLE_TBH; 576 break; 577 } 578 579 unsigned NumOps = MI->getDesc().getNumOperands(); 580 MachineOperand JTOp = 581 MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1)); 582 unsigned JTI = JTOp.getIndex(); 583 unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t); 584 MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock(); 585 MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB); 586 MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(), 587 DebugLoc(), TII->get(JTOpcode)) 588 .addImm(i++) 589 .addJumpTableIndex(JTI) 590 .addImm(Size); 591 CPEMIs.push_back(CPEMI); 592 CPEntries.emplace_back(1, CPEntry(CPEMI, JTI)); 593 JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1)); 594 if (!LastCorrectlyNumberedBB) 595 LastCorrectlyNumberedBB = &MBB; 596 } 597 598 // If we did anything then we need to renumber the subsequent blocks. 599 if (LastCorrectlyNumberedBB) 600 MF->RenumberBlocks(LastCorrectlyNumberedBB); 601 } 602 603 /// BBHasFallthrough - Return true if the specified basic block can fallthrough 604 /// into the block immediately after it. 605 bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) { 606 // Get the next machine basic block in the function. 607 MachineFunction::iterator MBBI = MBB->getIterator(); 608 // Can't fall off end of function. 609 if (std::next(MBBI) == MBB->getParent()->end()) 610 return false; 611 612 MachineBasicBlock *NextBB = &*std::next(MBBI); 613 if (!MBB->isSuccessor(NextBB)) 614 return false; 615 616 // Try to analyze the end of the block. A potential fallthrough may already 617 // have an unconditional branch for whatever reason. 618 MachineBasicBlock *TBB, *FBB; 619 SmallVector<MachineOperand, 4> Cond; 620 bool TooDifficult = TII->analyzeBranch(*MBB, TBB, FBB, Cond); 621 return TooDifficult || FBB == nullptr; 622 } 623 624 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI, 625 /// look up the corresponding CPEntry. 626 ARMConstantIslands::CPEntry * 627 ARMConstantIslands::findConstPoolEntry(unsigned CPI, 628 const MachineInstr *CPEMI) { 629 std::vector<CPEntry> &CPEs = CPEntries[CPI]; 630 // Number of entries per constpool index should be small, just do a 631 // linear search. 632 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) { 633 if (CPEs[i].CPEMI == CPEMI) 634 return &CPEs[i]; 635 } 636 return nullptr; 637 } 638 639 /// getCPEAlign - Returns the required alignment of the constant pool entry 640 /// represented by CPEMI. 641 Align ARMConstantIslands::getCPEAlign(const MachineInstr *CPEMI) { 642 switch (CPEMI->getOpcode()) { 643 case ARM::CONSTPOOL_ENTRY: 644 break; 645 case ARM::JUMPTABLE_TBB: 646 return isThumb1 ? Align(4) : Align(1); 647 case ARM::JUMPTABLE_TBH: 648 return isThumb1 ? Align(4) : Align(2); 649 case ARM::JUMPTABLE_INSTS: 650 return Align(2); 651 case ARM::JUMPTABLE_ADDRS: 652 return Align(4); 653 default: 654 llvm_unreachable("unknown constpool entry kind"); 655 } 656 657 unsigned CPI = getCombinedIndex(CPEMI); 658 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index."); 659 return MCP->getConstants()[CPI].getAlign(); 660 } 661 662 /// scanFunctionJumpTables - Do a scan of the function, building up 663 /// information about the sizes of each block and the locations of all 664 /// the jump tables. 665 void ARMConstantIslands::scanFunctionJumpTables() { 666 for (MachineBasicBlock &MBB : *MF) { 667 for (MachineInstr &I : MBB) 668 if (I.isBranch() && 669 (I.getOpcode() == ARM::t2BR_JT || I.getOpcode() == ARM::tBR_JTr)) 670 T2JumpTables.push_back(&I); 671 } 672 } 673 674 /// initializeFunctionInfo - Do the initial scan of the function, building up 675 /// information about the sizes of each block, the location of all the water, 676 /// and finding all of the constant pool users. 677 void ARMConstantIslands:: 678 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) { 679 680 BBUtils->computeAllBlockSizes(); 681 BBInfoVector &BBInfo = BBUtils->getBBInfo(); 682 // The known bits of the entry block offset are determined by the function 683 // alignment. 684 BBInfo.front().KnownBits = Log2(MF->getAlignment()); 685 686 // Compute block offsets and known bits. 687 BBUtils->adjustBBOffsetsAfter(&MF->front()); 688 689 // Now go back through the instructions and build up our data structures. 690 for (MachineBasicBlock &MBB : *MF) { 691 // If this block doesn't fall through into the next MBB, then this is 692 // 'water' that a constant pool island could be placed. 693 if (!BBHasFallthrough(&MBB)) 694 WaterList.push_back(&MBB); 695 696 for (MachineInstr &I : MBB) { 697 if (I.isDebugInstr()) 698 continue; 699 700 unsigned Opc = I.getOpcode(); 701 if (I.isBranch()) { 702 bool isCond = false; 703 unsigned Bits = 0; 704 unsigned Scale = 1; 705 int UOpc = Opc; 706 switch (Opc) { 707 default: 708 continue; // Ignore other JT branches 709 case ARM::t2BR_JT: 710 case ARM::tBR_JTr: 711 T2JumpTables.push_back(&I); 712 continue; // Does not get an entry in ImmBranches 713 case ARM::Bcc: 714 isCond = true; 715 UOpc = ARM::B; 716 LLVM_FALLTHROUGH; 717 case ARM::B: 718 Bits = 24; 719 Scale = 4; 720 break; 721 case ARM::tBcc: 722 isCond = true; 723 UOpc = ARM::tB; 724 Bits = 8; 725 Scale = 2; 726 break; 727 case ARM::tB: 728 Bits = 11; 729 Scale = 2; 730 break; 731 case ARM::t2Bcc: 732 isCond = true; 733 UOpc = ARM::t2B; 734 Bits = 20; 735 Scale = 2; 736 break; 737 case ARM::t2B: 738 Bits = 24; 739 Scale = 2; 740 break; 741 } 742 743 // Record this immediate branch. 744 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale; 745 ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc)); 746 } 747 748 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET) 749 PushPopMIs.push_back(&I); 750 751 if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS || 752 Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB || 753 Opc == ARM::JUMPTABLE_TBH) 754 continue; 755 756 // Scan the instructions for constant pool operands. 757 for (unsigned op = 0, e = I.getNumOperands(); op != e; ++op) 758 if (I.getOperand(op).isCPI() || I.getOperand(op).isJTI()) { 759 // We found one. The addressing mode tells us the max displacement 760 // from the PC that this instruction permits. 761 762 // Basic size info comes from the TSFlags field. 763 unsigned Bits = 0; 764 unsigned Scale = 1; 765 bool NegOk = false; 766 bool IsSoImm = false; 767 768 switch (Opc) { 769 default: 770 llvm_unreachable("Unknown addressing mode for CP reference!"); 771 772 // Taking the address of a CP entry. 773 case ARM::LEApcrel: 774 case ARM::LEApcrelJT: 775 // This takes a SoImm, which is 8 bit immediate rotated. We'll 776 // pretend the maximum offset is 255 * 4. Since each instruction 777 // 4 byte wide, this is always correct. We'll check for other 778 // displacements that fits in a SoImm as well. 779 Bits = 8; 780 Scale = 4; 781 NegOk = true; 782 IsSoImm = true; 783 break; 784 case ARM::t2LEApcrel: 785 case ARM::t2LEApcrelJT: 786 Bits = 12; 787 NegOk = true; 788 break; 789 case ARM::tLEApcrel: 790 case ARM::tLEApcrelJT: 791 Bits = 8; 792 Scale = 4; 793 break; 794 795 case ARM::LDRBi12: 796 case ARM::LDRi12: 797 case ARM::LDRcp: 798 case ARM::t2LDRpci: 799 case ARM::t2LDRHpci: 800 case ARM::t2LDRBpci: 801 Bits = 12; // +-offset_12 802 NegOk = true; 803 break; 804 805 case ARM::tLDRpci: 806 Bits = 8; 807 Scale = 4; // +(offset_8*4) 808 break; 809 810 case ARM::VLDRD: 811 case ARM::VLDRS: 812 Bits = 8; 813 Scale = 4; // +-(offset_8*4) 814 NegOk = true; 815 break; 816 case ARM::VLDRH: 817 Bits = 8; 818 Scale = 2; // +-(offset_8*2) 819 NegOk = true; 820 break; 821 } 822 823 // Remember that this is a user of a CP entry. 824 unsigned CPI = I.getOperand(op).getIndex(); 825 if (I.getOperand(op).isJTI()) { 826 JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size())); 827 CPI = JumpTableEntryIndices[CPI]; 828 } 829 830 MachineInstr *CPEMI = CPEMIs[CPI]; 831 unsigned MaxOffs = ((1 << Bits)-1) * Scale; 832 CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm)); 833 834 // Increment corresponding CPEntry reference count. 835 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI); 836 assert(CPE && "Cannot find a corresponding CPEntry!"); 837 CPE->RefCount++; 838 839 // Instructions can only use one CP entry, don't bother scanning the 840 // rest of the operands. 841 break; 842 } 843 } 844 } 845 } 846 847 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB 848 /// ID. 849 static bool CompareMBBNumbers(const MachineBasicBlock *LHS, 850 const MachineBasicBlock *RHS) { 851 return LHS->getNumber() < RHS->getNumber(); 852 } 853 854 /// updateForInsertedWaterBlock - When a block is newly inserted into the 855 /// machine function, it upsets all of the block numbers. Renumber the blocks 856 /// and update the arrays that parallel this numbering. 857 void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) { 858 // Renumber the MBB's to keep them consecutive. 859 NewBB->getParent()->RenumberBlocks(NewBB); 860 861 // Insert an entry into BBInfo to align it properly with the (newly 862 // renumbered) block numbers. 863 BBUtils->insert(NewBB->getNumber(), BasicBlockInfo()); 864 865 // Next, update WaterList. Specifically, we need to add NewMBB as having 866 // available water after it. 867 water_iterator IP = llvm::lower_bound(WaterList, NewBB, CompareMBBNumbers); 868 WaterList.insert(IP, NewBB); 869 } 870 871 /// Split the basic block containing MI into two blocks, which are joined by 872 /// an unconditional branch. Update data structures and renumber blocks to 873 /// account for this change and returns the newly created block. 874 MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) { 875 MachineBasicBlock *OrigBB = MI->getParent(); 876 877 // Collect liveness information at MI. 878 LivePhysRegs LRs(*MF->getSubtarget().getRegisterInfo()); 879 LRs.addLiveOuts(*OrigBB); 880 auto LivenessEnd = ++MachineBasicBlock::iterator(MI).getReverse(); 881 for (MachineInstr &LiveMI : make_range(OrigBB->rbegin(), LivenessEnd)) 882 LRs.stepBackward(LiveMI); 883 884 // Create a new MBB for the code after the OrigBB. 885 MachineBasicBlock *NewBB = 886 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock()); 887 MachineFunction::iterator MBBI = ++OrigBB->getIterator(); 888 MF->insert(MBBI, NewBB); 889 890 // Splice the instructions starting with MI over to NewBB. 891 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end()); 892 893 // Add an unconditional branch from OrigBB to NewBB. 894 // Note the new unconditional branch is not being recorded. 895 // There doesn't seem to be meaningful DebugInfo available; this doesn't 896 // correspond to anything in the source. 897 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B; 898 if (!isThumb) 899 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB); 900 else 901 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)) 902 .addMBB(NewBB) 903 .add(predOps(ARMCC::AL)); 904 ++NumSplit; 905 906 // Update the CFG. All succs of OrigBB are now succs of NewBB. 907 NewBB->transferSuccessors(OrigBB); 908 909 // OrigBB branches to NewBB. 910 OrigBB->addSuccessor(NewBB); 911 912 // Update live-in information in the new block. 913 MachineRegisterInfo &MRI = MF->getRegInfo(); 914 for (MCPhysReg L : LRs) 915 if (!MRI.isReserved(L)) 916 NewBB->addLiveIn(L); 917 918 // Update internal data structures to account for the newly inserted MBB. 919 // This is almost the same as updateForInsertedWaterBlock, except that 920 // the Water goes after OrigBB, not NewBB. 921 MF->RenumberBlocks(NewBB); 922 923 // Insert an entry into BBInfo to align it properly with the (newly 924 // renumbered) block numbers. 925 BBUtils->insert(NewBB->getNumber(), BasicBlockInfo()); 926 927 // Next, update WaterList. Specifically, we need to add OrigMBB as having 928 // available water after it (but not if it's already there, which happens 929 // when splitting before a conditional branch that is followed by an 930 // unconditional branch - in that case we want to insert NewBB). 931 water_iterator IP = llvm::lower_bound(WaterList, OrigBB, CompareMBBNumbers); 932 MachineBasicBlock* WaterBB = *IP; 933 if (WaterBB == OrigBB) 934 WaterList.insert(std::next(IP), NewBB); 935 else 936 WaterList.insert(IP, OrigBB); 937 NewWaterList.insert(OrigBB); 938 939 // Figure out how large the OrigBB is. As the first half of the original 940 // block, it cannot contain a tablejump. The size includes 941 // the new jump we added. (It should be possible to do this without 942 // recounting everything, but it's very confusing, and this is rarely 943 // executed.) 944 BBUtils->computeBlockSize(OrigBB); 945 946 // Figure out how large the NewMBB is. As the second half of the original 947 // block, it may contain a tablejump. 948 BBUtils->computeBlockSize(NewBB); 949 950 // All BBOffsets following these blocks must be modified. 951 BBUtils->adjustBBOffsetsAfter(OrigBB); 952 953 return NewBB; 954 } 955 956 /// getUserOffset - Compute the offset of U.MI as seen by the hardware 957 /// displacement computation. Update U.KnownAlignment to match its current 958 /// basic block location. 959 unsigned ARMConstantIslands::getUserOffset(CPUser &U) const { 960 unsigned UserOffset = BBUtils->getOffsetOf(U.MI); 961 962 SmallVectorImpl<BasicBlockInfo> &BBInfo = BBUtils->getBBInfo(); 963 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()]; 964 unsigned KnownBits = BBI.internalKnownBits(); 965 966 // The value read from PC is offset from the actual instruction address. 967 UserOffset += (isThumb ? 4 : 8); 968 969 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI. 970 // Make sure U.getMaxDisp() returns a constrained range. 971 U.KnownAlignment = (KnownBits >= 2); 972 973 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for 974 // purposes of the displacement computation; compensate for that here. 975 // For unknown alignments, getMaxDisp() constrains the range instead. 976 if (isThumb && U.KnownAlignment) 977 UserOffset &= ~3u; 978 979 return UserOffset; 980 } 981 982 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool 983 /// reference) is within MaxDisp of TrialOffset (a proposed location of a 984 /// constant pool entry). 985 /// UserOffset is computed by getUserOffset above to include PC adjustments. If 986 /// the mod 4 alignment of UserOffset is not known, the uncertainty must be 987 /// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that. 988 bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset, 989 unsigned TrialOffset, unsigned MaxDisp, 990 bool NegativeOK, bool IsSoImm) { 991 if (UserOffset <= TrialOffset) { 992 // User before the Trial. 993 if (TrialOffset - UserOffset <= MaxDisp) 994 return true; 995 // FIXME: Make use full range of soimm values. 996 } else if (NegativeOK) { 997 if (UserOffset - TrialOffset <= MaxDisp) 998 return true; 999 // FIXME: Make use full range of soimm values. 1000 } 1001 return false; 1002 } 1003 1004 /// isWaterInRange - Returns true if a CPE placed after the specified 1005 /// Water (a basic block) will be in range for the specific MI. 1006 /// 1007 /// Compute how much the function will grow by inserting a CPE after Water. 1008 bool ARMConstantIslands::isWaterInRange(unsigned UserOffset, 1009 MachineBasicBlock* Water, CPUser &U, 1010 unsigned &Growth) { 1011 BBInfoVector &BBInfo = BBUtils->getBBInfo(); 1012 const Align CPEAlign = getCPEAlign(U.CPEMI); 1013 const unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPEAlign); 1014 unsigned NextBlockOffset; 1015 Align NextBlockAlignment; 1016 MachineFunction::const_iterator NextBlock = Water->getIterator(); 1017 if (++NextBlock == MF->end()) { 1018 NextBlockOffset = BBInfo[Water->getNumber()].postOffset(); 1019 } else { 1020 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset; 1021 NextBlockAlignment = NextBlock->getAlignment(); 1022 } 1023 unsigned Size = U.CPEMI->getOperand(2).getImm(); 1024 unsigned CPEEnd = CPEOffset + Size; 1025 1026 // The CPE may be able to hide in the alignment padding before the next 1027 // block. It may also cause more padding to be required if it is more aligned 1028 // that the next block. 1029 if (CPEEnd > NextBlockOffset) { 1030 Growth = CPEEnd - NextBlockOffset; 1031 // Compute the padding that would go at the end of the CPE to align the next 1032 // block. 1033 Growth += offsetToAlignment(CPEEnd, NextBlockAlignment); 1034 1035 // If the CPE is to be inserted before the instruction, that will raise 1036 // the offset of the instruction. Also account for unknown alignment padding 1037 // in blocks between CPE and the user. 1038 if (CPEOffset < UserOffset) 1039 UserOffset += Growth + UnknownPadding(MF->getAlignment(), Log2(CPEAlign)); 1040 } else 1041 // CPE fits in existing padding. 1042 Growth = 0; 1043 1044 return isOffsetInRange(UserOffset, CPEOffset, U); 1045 } 1046 1047 /// isCPEntryInRange - Returns true if the distance between specific MI and 1048 /// specific ConstPool entry instruction can fit in MI's displacement field. 1049 bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset, 1050 MachineInstr *CPEMI, unsigned MaxDisp, 1051 bool NegOk, bool DoDump) { 1052 unsigned CPEOffset = BBUtils->getOffsetOf(CPEMI); 1053 1054 if (DoDump) { 1055 LLVM_DEBUG({ 1056 BBInfoVector &BBInfo = BBUtils->getBBInfo(); 1057 unsigned Block = MI->getParent()->getNumber(); 1058 const BasicBlockInfo &BBI = BBInfo[Block]; 1059 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm() 1060 << " max delta=" << MaxDisp 1061 << format(" insn address=%#x", UserOffset) << " in " 1062 << printMBBReference(*MI->getParent()) << ": " 1063 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI 1064 << format("CPE address=%#x offset=%+d: ", CPEOffset, 1065 int(CPEOffset - UserOffset)); 1066 }); 1067 } 1068 1069 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk); 1070 } 1071 1072 #ifndef NDEBUG 1073 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor 1074 /// unconditionally branches to its only successor. 1075 static bool BBIsJumpedOver(MachineBasicBlock *MBB) { 1076 if (MBB->pred_size() != 1 || MBB->succ_size() != 1) 1077 return false; 1078 1079 MachineBasicBlock *Succ = *MBB->succ_begin(); 1080 MachineBasicBlock *Pred = *MBB->pred_begin(); 1081 MachineInstr *PredMI = &Pred->back(); 1082 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB 1083 || PredMI->getOpcode() == ARM::t2B) 1084 return PredMI->getOperand(0).getMBB() == Succ; 1085 return false; 1086 } 1087 #endif // NDEBUG 1088 1089 /// decrementCPEReferenceCount - find the constant pool entry with index CPI 1090 /// and instruction CPEMI, and decrement its refcount. If the refcount 1091 /// becomes 0 remove the entry and instruction. Returns true if we removed 1092 /// the entry, false if we didn't. 1093 bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI, 1094 MachineInstr *CPEMI) { 1095 // Find the old entry. Eliminate it if it is no longer used. 1096 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI); 1097 assert(CPE && "Unexpected!"); 1098 if (--CPE->RefCount == 0) { 1099 removeDeadCPEMI(CPEMI); 1100 CPE->CPEMI = nullptr; 1101 --NumCPEs; 1102 return true; 1103 } 1104 return false; 1105 } 1106 1107 unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) { 1108 if (CPEMI->getOperand(1).isCPI()) 1109 return CPEMI->getOperand(1).getIndex(); 1110 1111 return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()]; 1112 } 1113 1114 /// LookForCPEntryInRange - see if the currently referenced CPE is in range; 1115 /// if not, see if an in-range clone of the CPE is in range, and if so, 1116 /// change the data structures so the user references the clone. Returns: 1117 /// 0 = no existing entry found 1118 /// 1 = entry found, and there were no code insertions or deletions 1119 /// 2 = entry found, and there were code insertions or deletions 1120 int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset) { 1121 MachineInstr *UserMI = U.MI; 1122 MachineInstr *CPEMI = U.CPEMI; 1123 1124 // Check to see if the CPE is already in-range. 1125 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk, 1126 true)) { 1127 LLVM_DEBUG(dbgs() << "In range\n"); 1128 return 1; 1129 } 1130 1131 // No. Look for previously created clones of the CPE that are in range. 1132 unsigned CPI = getCombinedIndex(CPEMI); 1133 std::vector<CPEntry> &CPEs = CPEntries[CPI]; 1134 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) { 1135 // We already tried this one 1136 if (CPEs[i].CPEMI == CPEMI) 1137 continue; 1138 // Removing CPEs can leave empty entries, skip 1139 if (CPEs[i].CPEMI == nullptr) 1140 continue; 1141 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(), 1142 U.NegOk)) { 1143 LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#" 1144 << CPEs[i].CPI << "\n"); 1145 // Point the CPUser node to the replacement 1146 U.CPEMI = CPEs[i].CPEMI; 1147 // Change the CPI in the instruction operand to refer to the clone. 1148 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j) 1149 if (UserMI->getOperand(j).isCPI()) { 1150 UserMI->getOperand(j).setIndex(CPEs[i].CPI); 1151 break; 1152 } 1153 // Adjust the refcount of the clone... 1154 CPEs[i].RefCount++; 1155 // ...and the original. If we didn't remove the old entry, none of the 1156 // addresses changed, so we don't need another pass. 1157 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1; 1158 } 1159 } 1160 return 0; 1161 } 1162 1163 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in 1164 /// the specific unconditional branch instruction. 1165 static inline unsigned getUnconditionalBrDisp(int Opc) { 1166 switch (Opc) { 1167 case ARM::tB: 1168 return ((1<<10)-1)*2; 1169 case ARM::t2B: 1170 return ((1<<23)-1)*2; 1171 default: 1172 break; 1173 } 1174 1175 return ((1<<23)-1)*4; 1176 } 1177 1178 /// findAvailableWater - Look for an existing entry in the WaterList in which 1179 /// we can place the CPE referenced from U so it's within range of U's MI. 1180 /// Returns true if found, false if not. If it returns true, WaterIter 1181 /// is set to the WaterList entry. For Thumb, prefer water that will not 1182 /// introduce padding to water that will. To ensure that this pass 1183 /// terminates, the CPE location for a particular CPUser is only allowed to 1184 /// move to a lower address, so search backward from the end of the list and 1185 /// prefer the first water that is in range. 1186 bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset, 1187 water_iterator &WaterIter, 1188 bool CloserWater) { 1189 if (WaterList.empty()) 1190 return false; 1191 1192 unsigned BestGrowth = ~0u; 1193 // The nearest water without splitting the UserBB is right after it. 1194 // If the distance is still large (we have a big BB), then we need to split it 1195 // if we don't converge after certain iterations. This helps the following 1196 // situation to converge: 1197 // BB0: 1198 // Big BB 1199 // BB1: 1200 // Constant Pool 1201 // When a CP access is out of range, BB0 may be used as water. However, 1202 // inserting islands between BB0 and BB1 makes other accesses out of range. 1203 MachineBasicBlock *UserBB = U.MI->getParent(); 1204 BBInfoVector &BBInfo = BBUtils->getBBInfo(); 1205 const Align CPEAlign = getCPEAlign(U.CPEMI); 1206 unsigned MinNoSplitDisp = BBInfo[UserBB->getNumber()].postOffset(CPEAlign); 1207 if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2) 1208 return false; 1209 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();; 1210 --IP) { 1211 MachineBasicBlock* WaterBB = *IP; 1212 // Check if water is in range and is either at a lower address than the 1213 // current "high water mark" or a new water block that was created since 1214 // the previous iteration by inserting an unconditional branch. In the 1215 // latter case, we want to allow resetting the high water mark back to 1216 // this new water since we haven't seen it before. Inserting branches 1217 // should be relatively uncommon and when it does happen, we want to be 1218 // sure to take advantage of it for all the CPEs near that block, so that 1219 // we don't insert more branches than necessary. 1220 // When CloserWater is true, we try to find the lowest address after (or 1221 // equal to) user MI's BB no matter of padding growth. 1222 unsigned Growth; 1223 if (isWaterInRange(UserOffset, WaterBB, U, Growth) && 1224 (WaterBB->getNumber() < U.HighWaterMark->getNumber() || 1225 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) && 1226 Growth < BestGrowth) { 1227 // This is the least amount of required padding seen so far. 1228 BestGrowth = Growth; 1229 WaterIter = IP; 1230 LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB) 1231 << " Growth=" << Growth << '\n'); 1232 1233 if (CloserWater && WaterBB == U.MI->getParent()) 1234 return true; 1235 // Keep looking unless it is perfect and we're not looking for the lowest 1236 // possible address. 1237 if (!CloserWater && BestGrowth == 0) 1238 return true; 1239 } 1240 if (IP == B) 1241 break; 1242 } 1243 return BestGrowth != ~0u; 1244 } 1245 1246 /// createNewWater - No existing WaterList entry will work for 1247 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the 1248 /// block is used if in range, and the conditional branch munged so control 1249 /// flow is correct. Otherwise the block is split to create a hole with an 1250 /// unconditional branch around it. In either case NewMBB is set to a 1251 /// block following which the new island can be inserted (the WaterList 1252 /// is not adjusted). 1253 void ARMConstantIslands::createNewWater(unsigned CPUserIndex, 1254 unsigned UserOffset, 1255 MachineBasicBlock *&NewMBB) { 1256 CPUser &U = CPUsers[CPUserIndex]; 1257 MachineInstr *UserMI = U.MI; 1258 MachineInstr *CPEMI = U.CPEMI; 1259 const Align CPEAlign = getCPEAlign(CPEMI); 1260 MachineBasicBlock *UserMBB = UserMI->getParent(); 1261 BBInfoVector &BBInfo = BBUtils->getBBInfo(); 1262 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()]; 1263 1264 // If the block does not end in an unconditional branch already, and if the 1265 // end of the block is within range, make new water there. (The addition 1266 // below is for the unconditional branch we will be adding: 4 bytes on ARM + 1267 // Thumb2, 2 on Thumb1. 1268 if (BBHasFallthrough(UserMBB)) { 1269 // Size of branch to insert. 1270 unsigned Delta = isThumb1 ? 2 : 4; 1271 // Compute the offset where the CPE will begin. 1272 unsigned CPEOffset = UserBBI.postOffset(CPEAlign) + Delta; 1273 1274 if (isOffsetInRange(UserOffset, CPEOffset, U)) { 1275 LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB) 1276 << format(", expected CPE offset %#x\n", CPEOffset)); 1277 NewMBB = &*++UserMBB->getIterator(); 1278 // Add an unconditional branch from UserMBB to fallthrough block. Record 1279 // it for branch lengthening; this new branch will not get out of range, 1280 // but if the preceding conditional branch is out of range, the targets 1281 // will be exchanged, and the altered branch may be out of range, so the 1282 // machinery has to know about it. 1283 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B; 1284 if (!isThumb) 1285 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB); 1286 else 1287 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)) 1288 .addMBB(NewMBB) 1289 .add(predOps(ARMCC::AL)); 1290 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr); 1291 ImmBranches.push_back(ImmBranch(&UserMBB->back(), 1292 MaxDisp, false, UncondBr)); 1293 BBUtils->computeBlockSize(UserMBB); 1294 BBUtils->adjustBBOffsetsAfter(UserMBB); 1295 return; 1296 } 1297 } 1298 1299 // What a big block. Find a place within the block to split it. This is a 1300 // little tricky on Thumb1 since instructions are 2 bytes and constant pool 1301 // entries are 4 bytes: if instruction I references island CPE, and 1302 // instruction I+1 references CPE', it will not work well to put CPE as far 1303 // forward as possible, since then CPE' cannot immediately follow it (that 1304 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd 1305 // need to create a new island. So, we make a first guess, then walk through 1306 // the instructions between the one currently being looked at and the 1307 // possible insertion point, and make sure any other instructions that 1308 // reference CPEs will be able to use the same island area; if not, we back 1309 // up the insertion point. 1310 1311 // Try to split the block so it's fully aligned. Compute the latest split 1312 // point where we can add a 4-byte branch instruction, and then align to 1313 // Align which is the largest possible alignment in the function. 1314 const Align Align = MF->getAlignment(); 1315 assert(Align >= CPEAlign && "Over-aligned constant pool entry"); 1316 unsigned KnownBits = UserBBI.internalKnownBits(); 1317 unsigned UPad = UnknownPadding(Align, KnownBits); 1318 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad; 1319 LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x", 1320 BaseInsertOffset)); 1321 1322 // The 4 in the following is for the unconditional branch we'll be inserting 1323 // (allows for long branch on Thumb1). Alignment of the island is handled 1324 // inside isOffsetInRange. 1325 BaseInsertOffset -= 4; 1326 1327 LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset) 1328 << " la=" << Log2(Align) << " kb=" << KnownBits 1329 << " up=" << UPad << '\n'); 1330 1331 // This could point off the end of the block if we've already got constant 1332 // pool entries following this block; only the last one is in the water list. 1333 // Back past any possible branches (allow for a conditional and a maximally 1334 // long unconditional). 1335 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) { 1336 // Ensure BaseInsertOffset is larger than the offset of the instruction 1337 // following UserMI so that the loop which searches for the split point 1338 // iterates at least once. 1339 BaseInsertOffset = 1340 std::max(UserBBI.postOffset() - UPad - 8, 1341 UserOffset + TII->getInstSizeInBytes(*UserMI) + 1); 1342 // If the CP is referenced(ie, UserOffset) is in first four instructions 1343 // after IT, this recalculated BaseInsertOffset could be in the middle of 1344 // an IT block. If it is, change the BaseInsertOffset to just after the 1345 // IT block. This still make the CP Entry is in range becuase of the 1346 // following reasons. 1347 // 1. The initial BaseseInsertOffset calculated is (UserOffset + 1348 // U.getMaxDisp() - UPad). 1349 // 2. An IT block is only at most 4 instructions plus the "it" itself (18 1350 // bytes). 1351 // 3. All the relevant instructions support much larger Maximum 1352 // displacement. 1353 MachineBasicBlock::iterator I = UserMI; 1354 ++I; 1355 Register PredReg; 1356 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI); 1357 I->getOpcode() != ARM::t2IT && 1358 getITInstrPredicate(*I, PredReg) != ARMCC::AL; 1359 Offset += TII->getInstSizeInBytes(*I), I = std::next(I)) { 1360 BaseInsertOffset = 1361 std::max(BaseInsertOffset, Offset + TII->getInstSizeInBytes(*I) + 1); 1362 assert(I != UserMBB->end() && "Fell off end of block"); 1363 } 1364 LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset)); 1365 } 1366 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad + 1367 CPEMI->getOperand(2).getImm(); 1368 MachineBasicBlock::iterator MI = UserMI; 1369 ++MI; 1370 unsigned CPUIndex = CPUserIndex+1; 1371 unsigned NumCPUsers = CPUsers.size(); 1372 MachineInstr *LastIT = nullptr; 1373 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI); 1374 Offset < BaseInsertOffset; 1375 Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) { 1376 assert(MI != UserMBB->end() && "Fell off end of block"); 1377 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) { 1378 CPUser &U = CPUsers[CPUIndex]; 1379 if (!isOffsetInRange(Offset, EndInsertOffset, U)) { 1380 // Shift intertion point by one unit of alignment so it is within reach. 1381 BaseInsertOffset -= Align.value(); 1382 EndInsertOffset -= Align.value(); 1383 } 1384 // This is overly conservative, as we don't account for CPEMIs being 1385 // reused within the block, but it doesn't matter much. Also assume CPEs 1386 // are added in order with alignment padding. We may eventually be able 1387 // to pack the aligned CPEs better. 1388 EndInsertOffset += U.CPEMI->getOperand(2).getImm(); 1389 CPUIndex++; 1390 } 1391 1392 // Remember the last IT instruction. 1393 if (MI->getOpcode() == ARM::t2IT) 1394 LastIT = &*MI; 1395 } 1396 1397 --MI; 1398 1399 // Avoid splitting an IT block. 1400 if (LastIT) { 1401 Register PredReg; 1402 ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg); 1403 if (CC != ARMCC::AL) 1404 MI = LastIT; 1405 } 1406 1407 // Avoid splitting a MOVW+MOVT pair with a relocation on Windows. 1408 // On Windows, this instruction pair is covered by one single 1409 // IMAGE_REL_ARM_MOV32T relocation which covers both instructions. If a 1410 // constant island is injected inbetween them, the relocation will clobber 1411 // the instruction and fail to update the MOVT instruction. 1412 // (These instructions are bundled up until right before the ConstantIslands 1413 // pass.) 1414 if (STI->isTargetWindows() && isThumb && MI->getOpcode() == ARM::t2MOVTi16 && 1415 (MI->getOperand(2).getTargetFlags() & ARMII::MO_OPTION_MASK) == 1416 ARMII::MO_HI16) { 1417 --MI; 1418 assert(MI->getOpcode() == ARM::t2MOVi16 && 1419 (MI->getOperand(1).getTargetFlags() & ARMII::MO_OPTION_MASK) == 1420 ARMII::MO_LO16); 1421 } 1422 1423 // We really must not split an IT block. 1424 #ifndef NDEBUG 1425 Register PredReg; 1426 assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL); 1427 #endif 1428 NewMBB = splitBlockBeforeInstr(&*MI); 1429 } 1430 1431 /// handleConstantPoolUser - Analyze the specified user, checking to see if it 1432 /// is out-of-range. If so, pick up the constant pool value and move it some 1433 /// place in-range. Return true if we changed any addresses (thus must run 1434 /// another pass of branch lengthening), false otherwise. 1435 bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex, 1436 bool CloserWater) { 1437 CPUser &U = CPUsers[CPUserIndex]; 1438 MachineInstr *UserMI = U.MI; 1439 MachineInstr *CPEMI = U.CPEMI; 1440 unsigned CPI = getCombinedIndex(CPEMI); 1441 unsigned Size = CPEMI->getOperand(2).getImm(); 1442 // Compute this only once, it's expensive. 1443 unsigned UserOffset = getUserOffset(U); 1444 1445 // See if the current entry is within range, or there is a clone of it 1446 // in range. 1447 int result = findInRangeCPEntry(U, UserOffset); 1448 if (result==1) return false; 1449 else if (result==2) return true; 1450 1451 // No existing clone of this CPE is within range. 1452 // We will be generating a new clone. Get a UID for it. 1453 unsigned ID = AFI->createPICLabelUId(); 1454 1455 // Look for water where we can place this CPE. 1456 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock(); 1457 MachineBasicBlock *NewMBB; 1458 water_iterator IP; 1459 if (findAvailableWater(U, UserOffset, IP, CloserWater)) { 1460 LLVM_DEBUG(dbgs() << "Found water in range\n"); 1461 MachineBasicBlock *WaterBB = *IP; 1462 1463 // If the original WaterList entry was "new water" on this iteration, 1464 // propagate that to the new island. This is just keeping NewWaterList 1465 // updated to match the WaterList, which will be updated below. 1466 if (NewWaterList.erase(WaterBB)) 1467 NewWaterList.insert(NewIsland); 1468 1469 // The new CPE goes before the following block (NewMBB). 1470 NewMBB = &*++WaterBB->getIterator(); 1471 } else { 1472 // No water found. 1473 LLVM_DEBUG(dbgs() << "No water found\n"); 1474 createNewWater(CPUserIndex, UserOffset, NewMBB); 1475 1476 // splitBlockBeforeInstr adds to WaterList, which is important when it is 1477 // called while handling branches so that the water will be seen on the 1478 // next iteration for constant pools, but in this context, we don't want 1479 // it. Check for this so it will be removed from the WaterList. 1480 // Also remove any entry from NewWaterList. 1481 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator(); 1482 IP = find(WaterList, WaterBB); 1483 if (IP != WaterList.end()) 1484 NewWaterList.erase(WaterBB); 1485 1486 // We are adding new water. Update NewWaterList. 1487 NewWaterList.insert(NewIsland); 1488 } 1489 // Always align the new block because CP entries can be smaller than 4 1490 // bytes. Be careful not to decrease the existing alignment, e.g. NewMBB may 1491 // be an already aligned constant pool block. 1492 const Align Alignment = isThumb ? Align(2) : Align(4); 1493 if (NewMBB->getAlignment() < Alignment) 1494 NewMBB->setAlignment(Alignment); 1495 1496 // Remove the original WaterList entry; we want subsequent insertions in 1497 // this vicinity to go after the one we're about to insert. This 1498 // considerably reduces the number of times we have to move the same CPE 1499 // more than once and is also important to ensure the algorithm terminates. 1500 if (IP != WaterList.end()) 1501 WaterList.erase(IP); 1502 1503 // Okay, we know we can put an island before NewMBB now, do it! 1504 MF->insert(NewMBB->getIterator(), NewIsland); 1505 1506 // Update internal data structures to account for the newly inserted MBB. 1507 updateForInsertedWaterBlock(NewIsland); 1508 1509 // Now that we have an island to add the CPE to, clone the original CPE and 1510 // add it to the island. 1511 U.HighWaterMark = NewIsland; 1512 U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc()) 1513 .addImm(ID) 1514 .add(CPEMI->getOperand(1)) 1515 .addImm(Size); 1516 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1)); 1517 ++NumCPEs; 1518 1519 // Decrement the old entry, and remove it if refcount becomes 0. 1520 decrementCPEReferenceCount(CPI, CPEMI); 1521 1522 // Mark the basic block as aligned as required by the const-pool entry. 1523 NewIsland->setAlignment(getCPEAlign(U.CPEMI)); 1524 1525 // Increase the size of the island block to account for the new entry. 1526 BBUtils->adjustBBSize(NewIsland, Size); 1527 BBUtils->adjustBBOffsetsAfter(&*--NewIsland->getIterator()); 1528 1529 // Finally, change the CPI in the instruction operand to be ID. 1530 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i) 1531 if (UserMI->getOperand(i).isCPI()) { 1532 UserMI->getOperand(i).setIndex(ID); 1533 break; 1534 } 1535 1536 LLVM_DEBUG( 1537 dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI 1538 << format(" offset=%#x\n", 1539 BBUtils->getBBInfo()[NewIsland->getNumber()].Offset)); 1540 1541 return true; 1542 } 1543 1544 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update 1545 /// sizes and offsets of impacted basic blocks. 1546 void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) { 1547 MachineBasicBlock *CPEBB = CPEMI->getParent(); 1548 unsigned Size = CPEMI->getOperand(2).getImm(); 1549 CPEMI->eraseFromParent(); 1550 BBInfoVector &BBInfo = BBUtils->getBBInfo(); 1551 BBUtils->adjustBBSize(CPEBB, -Size); 1552 // All succeeding offsets have the current size value added in, fix this. 1553 if (CPEBB->empty()) { 1554 BBInfo[CPEBB->getNumber()].Size = 0; 1555 1556 // This block no longer needs to be aligned. 1557 CPEBB->setAlignment(Align(1)); 1558 } else { 1559 // Entries are sorted by descending alignment, so realign from the front. 1560 CPEBB->setAlignment(getCPEAlign(&*CPEBB->begin())); 1561 } 1562 1563 BBUtils->adjustBBOffsetsAfter(CPEBB); 1564 // An island has only one predecessor BB and one successor BB. Check if 1565 // this BB's predecessor jumps directly to this BB's successor. This 1566 // shouldn't happen currently. 1567 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?"); 1568 // FIXME: remove the empty blocks after all the work is done? 1569 } 1570 1571 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts 1572 /// are zero. 1573 bool ARMConstantIslands::removeUnusedCPEntries() { 1574 unsigned MadeChange = false; 1575 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) { 1576 std::vector<CPEntry> &CPEs = CPEntries[i]; 1577 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) { 1578 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) { 1579 removeDeadCPEMI(CPEs[j].CPEMI); 1580 CPEs[j].CPEMI = nullptr; 1581 MadeChange = true; 1582 } 1583 } 1584 } 1585 return MadeChange; 1586 } 1587 1588 1589 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far 1590 /// away to fit in its displacement field. 1591 bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) { 1592 MachineInstr *MI = Br.MI; 1593 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB(); 1594 1595 // Check to see if the DestBB is already in-range. 1596 if (BBUtils->isBBInRange(MI, DestBB, Br.MaxDisp)) 1597 return false; 1598 1599 if (!Br.isCond) 1600 return fixupUnconditionalBr(Br); 1601 return fixupConditionalBr(Br); 1602 } 1603 1604 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is 1605 /// too far away to fit in its displacement field. If the LR register has been 1606 /// spilled in the epilogue, then we can use BL to implement a far jump. 1607 /// Otherwise, add an intermediate branch instruction to a branch. 1608 bool 1609 ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) { 1610 MachineInstr *MI = Br.MI; 1611 MachineBasicBlock *MBB = MI->getParent(); 1612 if (!isThumb1) 1613 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!"); 1614 1615 if (!AFI->isLRSpilled()) 1616 report_fatal_error("underestimated function size"); 1617 1618 // Use BL to implement far jump. 1619 Br.MaxDisp = (1 << 21) * 2; 1620 MI->setDesc(TII->get(ARM::tBfar)); 1621 BBInfoVector &BBInfo = BBUtils->getBBInfo(); 1622 BBInfo[MBB->getNumber()].Size += 2; 1623 BBUtils->adjustBBOffsetsAfter(MBB); 1624 ++NumUBrFixed; 1625 1626 LLVM_DEBUG(dbgs() << " Changed B to long jump " << *MI); 1627 1628 return true; 1629 } 1630 1631 /// fixupConditionalBr - Fix up a conditional branch whose destination is too 1632 /// far away to fit in its displacement field. It is converted to an inverse 1633 /// conditional branch + an unconditional branch to the destination. 1634 bool 1635 ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) { 1636 MachineInstr *MI = Br.MI; 1637 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB(); 1638 1639 // Add an unconditional branch to the destination and invert the branch 1640 // condition to jump over it: 1641 // blt L1 1642 // => 1643 // bge L2 1644 // b L1 1645 // L2: 1646 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm(); 1647 CC = ARMCC::getOppositeCondition(CC); 1648 Register CCReg = MI->getOperand(2).getReg(); 1649 1650 // If the branch is at the end of its MBB and that has a fall-through block, 1651 // direct the updated conditional branch to the fall-through block. Otherwise, 1652 // split the MBB before the next instruction. 1653 MachineBasicBlock *MBB = MI->getParent(); 1654 MachineInstr *BMI = &MBB->back(); 1655 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB); 1656 1657 ++NumCBrFixed; 1658 if (BMI != MI) { 1659 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) && 1660 BMI->getOpcode() == Br.UncondBr) { 1661 // Last MI in the BB is an unconditional branch. Can we simply invert the 1662 // condition and swap destinations: 1663 // beq L1 1664 // b L2 1665 // => 1666 // bne L2 1667 // b L1 1668 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB(); 1669 if (BBUtils->isBBInRange(MI, NewDest, Br.MaxDisp)) { 1670 LLVM_DEBUG( 1671 dbgs() << " Invert Bcc condition and swap its destination with " 1672 << *BMI); 1673 BMI->getOperand(0).setMBB(DestBB); 1674 MI->getOperand(0).setMBB(NewDest); 1675 MI->getOperand(1).setImm(CC); 1676 return true; 1677 } 1678 } 1679 } 1680 1681 if (NeedSplit) { 1682 splitBlockBeforeInstr(MI); 1683 // No need for the branch to the next block. We're adding an unconditional 1684 // branch to the destination. 1685 int delta = TII->getInstSizeInBytes(MBB->back()); 1686 BBUtils->adjustBBSize(MBB, -delta); 1687 MBB->back().eraseFromParent(); 1688 1689 // The conditional successor will be swapped between the BBs after this, so 1690 // update CFG. 1691 MBB->addSuccessor(DestBB); 1692 std::next(MBB->getIterator())->removeSuccessor(DestBB); 1693 1694 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below 1695 } 1696 MachineBasicBlock *NextBB = &*++MBB->getIterator(); 1697 1698 LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*DestBB) 1699 << " also invert condition and change dest. to " 1700 << printMBBReference(*NextBB) << "\n"); 1701 1702 // Insert a new conditional branch and a new unconditional branch. 1703 // Also update the ImmBranch as well as adding a new entry for the new branch. 1704 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode())) 1705 .addMBB(NextBB).addImm(CC).addReg(CCReg); 1706 Br.MI = &MBB->back(); 1707 BBUtils->adjustBBSize(MBB, TII->getInstSizeInBytes(MBB->back())); 1708 if (isThumb) 1709 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)) 1710 .addMBB(DestBB) 1711 .add(predOps(ARMCC::AL)); 1712 else 1713 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB); 1714 BBUtils->adjustBBSize(MBB, TII->getInstSizeInBytes(MBB->back())); 1715 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr); 1716 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr)); 1717 1718 // Remove the old conditional branch. It may or may not still be in MBB. 1719 BBUtils->adjustBBSize(MI->getParent(), -TII->getInstSizeInBytes(*MI)); 1720 MI->eraseFromParent(); 1721 BBUtils->adjustBBOffsetsAfter(MBB); 1722 return true; 1723 } 1724 1725 bool ARMConstantIslands::optimizeThumb2Instructions() { 1726 bool MadeChange = false; 1727 1728 // Shrink ADR and LDR from constantpool. 1729 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) { 1730 CPUser &U = CPUsers[i]; 1731 unsigned Opcode = U.MI->getOpcode(); 1732 unsigned NewOpc = 0; 1733 unsigned Scale = 1; 1734 unsigned Bits = 0; 1735 switch (Opcode) { 1736 default: break; 1737 case ARM::t2LEApcrel: 1738 if (isARMLowRegister(U.MI->getOperand(0).getReg())) { 1739 NewOpc = ARM::tLEApcrel; 1740 Bits = 8; 1741 Scale = 4; 1742 } 1743 break; 1744 case ARM::t2LDRpci: 1745 if (isARMLowRegister(U.MI->getOperand(0).getReg())) { 1746 NewOpc = ARM::tLDRpci; 1747 Bits = 8; 1748 Scale = 4; 1749 } 1750 break; 1751 } 1752 1753 if (!NewOpc) 1754 continue; 1755 1756 unsigned UserOffset = getUserOffset(U); 1757 unsigned MaxOffs = ((1 << Bits) - 1) * Scale; 1758 1759 // Be conservative with inline asm. 1760 if (!U.KnownAlignment) 1761 MaxOffs -= 2; 1762 1763 // FIXME: Check if offset is multiple of scale if scale is not 4. 1764 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) { 1765 LLVM_DEBUG(dbgs() << "Shrink: " << *U.MI); 1766 U.MI->setDesc(TII->get(NewOpc)); 1767 MachineBasicBlock *MBB = U.MI->getParent(); 1768 BBUtils->adjustBBSize(MBB, -2); 1769 BBUtils->adjustBBOffsetsAfter(MBB); 1770 ++NumT2CPShrunk; 1771 MadeChange = true; 1772 } 1773 } 1774 1775 return MadeChange; 1776 } 1777 1778 1779 bool ARMConstantIslands::optimizeThumb2Branches() { 1780 1781 auto TryShrinkBranch = [this](ImmBranch &Br) { 1782 unsigned Opcode = Br.MI->getOpcode(); 1783 unsigned NewOpc = 0; 1784 unsigned Scale = 1; 1785 unsigned Bits = 0; 1786 switch (Opcode) { 1787 default: break; 1788 case ARM::t2B: 1789 NewOpc = ARM::tB; 1790 Bits = 11; 1791 Scale = 2; 1792 break; 1793 case ARM::t2Bcc: 1794 NewOpc = ARM::tBcc; 1795 Bits = 8; 1796 Scale = 2; 1797 break; 1798 } 1799 if (NewOpc) { 1800 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale; 1801 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB(); 1802 if (BBUtils->isBBInRange(Br.MI, DestBB, MaxOffs)) { 1803 LLVM_DEBUG(dbgs() << "Shrink branch: " << *Br.MI); 1804 Br.MI->setDesc(TII->get(NewOpc)); 1805 MachineBasicBlock *MBB = Br.MI->getParent(); 1806 BBUtils->adjustBBSize(MBB, -2); 1807 BBUtils->adjustBBOffsetsAfter(MBB); 1808 ++NumT2BrShrunk; 1809 return true; 1810 } 1811 } 1812 return false; 1813 }; 1814 1815 struct ImmCompare { 1816 MachineInstr* MI = nullptr; 1817 unsigned NewOpc = 0; 1818 }; 1819 1820 auto FindCmpForCBZ = [this](ImmBranch &Br, ImmCompare &ImmCmp, 1821 MachineBasicBlock *DestBB) { 1822 ImmCmp.MI = nullptr; 1823 ImmCmp.NewOpc = 0; 1824 1825 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout 1826 // so this transformation is not safe. 1827 if (!Br.MI->killsRegister(ARM::CPSR)) 1828 return false; 1829 1830 Register PredReg; 1831 unsigned NewOpc = 0; 1832 ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg); 1833 if (Pred == ARMCC::EQ) 1834 NewOpc = ARM::tCBZ; 1835 else if (Pred == ARMCC::NE) 1836 NewOpc = ARM::tCBNZ; 1837 else 1838 return false; 1839 1840 // Check if the distance is within 126. Subtract starting offset by 2 1841 // because the cmp will be eliminated. 1842 unsigned BrOffset = BBUtils->getOffsetOf(Br.MI) + 4 - 2; 1843 BBInfoVector &BBInfo = BBUtils->getBBInfo(); 1844 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset; 1845 if (BrOffset >= DestOffset || (DestOffset - BrOffset) > 126) 1846 return false; 1847 1848 // Search backwards to find a tCMPi8 1849 auto *TRI = STI->getRegisterInfo(); 1850 MachineInstr *CmpMI = findCMPToFoldIntoCBZ(Br.MI, TRI); 1851 if (!CmpMI || CmpMI->getOpcode() != ARM::tCMPi8) 1852 return false; 1853 1854 ImmCmp.MI = CmpMI; 1855 ImmCmp.NewOpc = NewOpc; 1856 return true; 1857 }; 1858 1859 auto TryConvertToLE = [this](ImmBranch &Br, ImmCompare &Cmp) { 1860 if (Br.MI->getOpcode() != ARM::t2Bcc || !STI->hasLOB() || 1861 STI->hasMinSize()) 1862 return false; 1863 1864 MachineBasicBlock *MBB = Br.MI->getParent(); 1865 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB(); 1866 if (BBUtils->getOffsetOf(MBB) < BBUtils->getOffsetOf(DestBB) || 1867 !BBUtils->isBBInRange(Br.MI, DestBB, 4094)) 1868 return false; 1869 1870 if (!DT->dominates(DestBB, MBB)) 1871 return false; 1872 1873 // We queried for the CBN?Z opcode based upon the 'ExitBB', the opposite 1874 // target of Br. So now we need to reverse the condition. 1875 Cmp.NewOpc = Cmp.NewOpc == ARM::tCBZ ? ARM::tCBNZ : ARM::tCBZ; 1876 1877 MachineInstrBuilder MIB = BuildMI(*MBB, Br.MI, Br.MI->getDebugLoc(), 1878 TII->get(ARM::t2LE)); 1879 // Swapped a t2Bcc for a t2LE, so no need to update the size of the block. 1880 MIB.add(Br.MI->getOperand(0)); 1881 Br.MI->eraseFromParent(); 1882 Br.MI = MIB; 1883 ++NumLEInserted; 1884 return true; 1885 }; 1886 1887 bool MadeChange = false; 1888 1889 // The order in which branches appear in ImmBranches is approximately their 1890 // order within the function body. By visiting later branches first, we reduce 1891 // the distance between earlier forward branches and their targets, making it 1892 // more likely that the cbn?z optimization, which can only apply to forward 1893 // branches, will succeed. 1894 for (ImmBranch &Br : reverse(ImmBranches)) { 1895 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB(); 1896 MachineBasicBlock *MBB = Br.MI->getParent(); 1897 MachineBasicBlock *ExitBB = &MBB->back() == Br.MI ? 1898 MBB->getFallThrough() : 1899 MBB->back().getOperand(0).getMBB(); 1900 1901 ImmCompare Cmp; 1902 if (FindCmpForCBZ(Br, Cmp, ExitBB) && TryConvertToLE(Br, Cmp)) { 1903 DestBB = ExitBB; 1904 MadeChange = true; 1905 } else { 1906 FindCmpForCBZ(Br, Cmp, DestBB); 1907 MadeChange |= TryShrinkBranch(Br); 1908 } 1909 1910 unsigned Opcode = Br.MI->getOpcode(); 1911 if ((Opcode != ARM::tBcc && Opcode != ARM::t2LE) || !Cmp.NewOpc) 1912 continue; 1913 1914 Register Reg = Cmp.MI->getOperand(0).getReg(); 1915 1916 // Check for Kill flags on Reg. If they are present remove them and set kill 1917 // on the new CBZ. 1918 auto *TRI = STI->getRegisterInfo(); 1919 MachineBasicBlock::iterator KillMI = Br.MI; 1920 bool RegKilled = false; 1921 do { 1922 --KillMI; 1923 if (KillMI->killsRegister(Reg, TRI)) { 1924 KillMI->clearRegisterKills(Reg, TRI); 1925 RegKilled = true; 1926 break; 1927 } 1928 } while (KillMI != Cmp.MI); 1929 1930 // Create the new CBZ/CBNZ 1931 LLVM_DEBUG(dbgs() << "Fold: " << *Cmp.MI << " and: " << *Br.MI); 1932 MachineInstr *NewBR = 1933 BuildMI(*MBB, Br.MI, Br.MI->getDebugLoc(), TII->get(Cmp.NewOpc)) 1934 .addReg(Reg, getKillRegState(RegKilled)) 1935 .addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags()); 1936 1937 Cmp.MI->eraseFromParent(); 1938 1939 if (Br.MI->getOpcode() == ARM::tBcc) { 1940 Br.MI->eraseFromParent(); 1941 Br.MI = NewBR; 1942 BBUtils->adjustBBSize(MBB, -2); 1943 } else if (MBB->back().getOpcode() != ARM::t2LE) { 1944 // An LE has been generated, but it's not the terminator - that is an 1945 // unconditional branch. However, the logic has now been reversed with the 1946 // CBN?Z being the conditional branch and the LE being the unconditional 1947 // branch. So this means we can remove the redundant unconditional branch 1948 // at the end of the block. 1949 MachineInstr *LastMI = &MBB->back(); 1950 BBUtils->adjustBBSize(MBB, -LastMI->getDesc().getSize()); 1951 LastMI->eraseFromParent(); 1952 } 1953 BBUtils->adjustBBOffsetsAfter(MBB); 1954 ++NumCBZ; 1955 MadeChange = true; 1956 } 1957 1958 return MadeChange; 1959 } 1960 1961 static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg, 1962 unsigned BaseReg) { 1963 if (I.getOpcode() != ARM::t2ADDrs) 1964 return false; 1965 1966 if (I.getOperand(0).getReg() != EntryReg) 1967 return false; 1968 1969 if (I.getOperand(1).getReg() != BaseReg) 1970 return false; 1971 1972 // FIXME: what about CC and IdxReg? 1973 return true; 1974 } 1975 1976 /// While trying to form a TBB/TBH instruction, we may (if the table 1977 /// doesn't immediately follow the BR_JT) need access to the start of the 1978 /// jump-table. We know one instruction that produces such a register; this 1979 /// function works out whether that definition can be preserved to the BR_JT, 1980 /// possibly by removing an intervening addition (which is usually needed to 1981 /// calculate the actual entry to jump to). 1982 bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI, 1983 MachineInstr *LEAMI, 1984 unsigned &DeadSize, 1985 bool &CanDeleteLEA, 1986 bool &BaseRegKill) { 1987 if (JumpMI->getParent() != LEAMI->getParent()) 1988 return false; 1989 1990 // Now we hope that we have at least these instructions in the basic block: 1991 // BaseReg = t2LEA ... 1992 // [...] 1993 // EntryReg = t2ADDrs BaseReg, ... 1994 // [...] 1995 // t2BR_JT EntryReg 1996 // 1997 // We have to be very conservative about what we recognise here though. The 1998 // main perturbing factors to watch out for are: 1999 // + Spills at any point in the chain: not direct problems but we would 2000 // expect a blocking Def of the spilled register so in practice what we 2001 // can do is limited. 2002 // + EntryReg == BaseReg: this is the one situation we should allow a Def 2003 // of BaseReg, but only if the t2ADDrs can be removed. 2004 // + Some instruction other than t2ADDrs computing the entry. Not seen in 2005 // the wild, but we should be careful. 2006 Register EntryReg = JumpMI->getOperand(0).getReg(); 2007 Register BaseReg = LEAMI->getOperand(0).getReg(); 2008 2009 CanDeleteLEA = true; 2010 BaseRegKill = false; 2011 MachineInstr *RemovableAdd = nullptr; 2012 MachineBasicBlock::iterator I(LEAMI); 2013 for (++I; &*I != JumpMI; ++I) { 2014 if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) { 2015 RemovableAdd = &*I; 2016 break; 2017 } 2018 2019 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) { 2020 const MachineOperand &MO = I->getOperand(K); 2021 if (!MO.isReg() || !MO.getReg()) 2022 continue; 2023 if (MO.isDef() && MO.getReg() == BaseReg) 2024 return false; 2025 if (MO.isUse() && MO.getReg() == BaseReg) { 2026 BaseRegKill = BaseRegKill || MO.isKill(); 2027 CanDeleteLEA = false; 2028 } 2029 } 2030 } 2031 2032 if (!RemovableAdd) 2033 return true; 2034 2035 // Check the add really is removable, and that nothing else in the block 2036 // clobbers BaseReg. 2037 for (++I; &*I != JumpMI; ++I) { 2038 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) { 2039 const MachineOperand &MO = I->getOperand(K); 2040 if (!MO.isReg() || !MO.getReg()) 2041 continue; 2042 if (MO.isDef() && MO.getReg() == BaseReg) 2043 return false; 2044 if (MO.isUse() && MO.getReg() == EntryReg) 2045 RemovableAdd = nullptr; 2046 } 2047 } 2048 2049 if (RemovableAdd) { 2050 RemovableAdd->eraseFromParent(); 2051 DeadSize += isThumb2 ? 4 : 2; 2052 } else if (BaseReg == EntryReg) { 2053 // The add wasn't removable, but clobbered the base for the TBB. So we can't 2054 // preserve it. 2055 return false; 2056 } 2057 2058 // We reached the end of the block without seeing another definition of 2059 // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be 2060 // used in the TBB/TBH if necessary. 2061 return true; 2062 } 2063 2064 /// Returns whether CPEMI is the first instruction in the block 2065 /// immediately following JTMI (assumed to be a TBB or TBH terminator). If so, 2066 /// we can switch the first register to PC and usually remove the address 2067 /// calculation that preceded it. 2068 static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) { 2069 MachineFunction::iterator MBB = JTMI->getParent()->getIterator(); 2070 MachineFunction *MF = MBB->getParent(); 2071 ++MBB; 2072 2073 return MBB != MF->end() && MBB->begin() != MBB->end() && 2074 &*MBB->begin() == CPEMI; 2075 } 2076 2077 static void RemoveDeadAddBetweenLEAAndJT(MachineInstr *LEAMI, 2078 MachineInstr *JumpMI, 2079 unsigned &DeadSize) { 2080 // Remove a dead add between the LEA and JT, which used to compute EntryReg, 2081 // but the JT now uses PC. Finds the last ADD (if any) that def's EntryReg 2082 // and is not clobbered / used. 2083 MachineInstr *RemovableAdd = nullptr; 2084 Register EntryReg = JumpMI->getOperand(0).getReg(); 2085 2086 // Find the last ADD to set EntryReg 2087 MachineBasicBlock::iterator I(LEAMI); 2088 for (++I; &*I != JumpMI; ++I) { 2089 if (I->getOpcode() == ARM::t2ADDrs && I->getOperand(0).getReg() == EntryReg) 2090 RemovableAdd = &*I; 2091 } 2092 2093 if (!RemovableAdd) 2094 return; 2095 2096 // Ensure EntryReg is not clobbered or used. 2097 MachineBasicBlock::iterator J(RemovableAdd); 2098 for (++J; &*J != JumpMI; ++J) { 2099 for (unsigned K = 0, E = J->getNumOperands(); K != E; ++K) { 2100 const MachineOperand &MO = J->getOperand(K); 2101 if (!MO.isReg() || !MO.getReg()) 2102 continue; 2103 if (MO.isDef() && MO.getReg() == EntryReg) 2104 return; 2105 if (MO.isUse() && MO.getReg() == EntryReg) 2106 return; 2107 } 2108 } 2109 2110 LLVM_DEBUG(dbgs() << "Removing Dead Add: " << *RemovableAdd); 2111 RemovableAdd->eraseFromParent(); 2112 DeadSize += 4; 2113 } 2114 2115 /// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller 2116 /// jumptables when it's possible. 2117 bool ARMConstantIslands::optimizeThumb2JumpTables() { 2118 bool MadeChange = false; 2119 2120 // FIXME: After the tables are shrunk, can we get rid some of the 2121 // constantpool tables? 2122 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 2123 if (!MJTI) return false; 2124 2125 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 2126 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) { 2127 MachineInstr *MI = T2JumpTables[i]; 2128 const MCInstrDesc &MCID = MI->getDesc(); 2129 unsigned NumOps = MCID.getNumOperands(); 2130 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1); 2131 MachineOperand JTOP = MI->getOperand(JTOpIdx); 2132 unsigned JTI = JTOP.getIndex(); 2133 assert(JTI < JT.size()); 2134 2135 bool ByteOk = true; 2136 bool HalfWordOk = true; 2137 unsigned JTOffset = BBUtils->getOffsetOf(MI) + 4; 2138 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 2139 BBInfoVector &BBInfo = BBUtils->getBBInfo(); 2140 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) { 2141 MachineBasicBlock *MBB = JTBBs[j]; 2142 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset; 2143 // Negative offset is not ok. FIXME: We should change BB layout to make 2144 // sure all the branches are forward. 2145 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2) 2146 ByteOk = false; 2147 unsigned TBHLimit = ((1<<16)-1)*2; 2148 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit) 2149 HalfWordOk = false; 2150 if (!ByteOk && !HalfWordOk) 2151 break; 2152 } 2153 2154 if (!ByteOk && !HalfWordOk) 2155 continue; 2156 2157 CPUser &User = CPUsers[JumpTableUserIndices[JTI]]; 2158 MachineBasicBlock *MBB = MI->getParent(); 2159 if (!MI->getOperand(0).isKill()) // FIXME: needed now? 2160 continue; 2161 2162 unsigned DeadSize = 0; 2163 bool CanDeleteLEA = false; 2164 bool BaseRegKill = false; 2165 2166 unsigned IdxReg = ~0U; 2167 bool IdxRegKill = true; 2168 if (isThumb2) { 2169 IdxReg = MI->getOperand(1).getReg(); 2170 IdxRegKill = MI->getOperand(1).isKill(); 2171 2172 bool PreservedBaseReg = 2173 preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill); 2174 if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg) 2175 continue; 2176 } else { 2177 // We're in thumb-1 mode, so we must have something like: 2178 // %idx = tLSLri %idx, 2 2179 // %base = tLEApcrelJT 2180 // %t = tLDRr %base, %idx 2181 Register BaseReg = User.MI->getOperand(0).getReg(); 2182 2183 if (User.MI->getIterator() == User.MI->getParent()->begin()) 2184 continue; 2185 MachineInstr *Shift = User.MI->getPrevNode(); 2186 if (Shift->getOpcode() != ARM::tLSLri || 2187 Shift->getOperand(3).getImm() != 2 || 2188 !Shift->getOperand(2).isKill()) 2189 continue; 2190 IdxReg = Shift->getOperand(2).getReg(); 2191 Register ShiftedIdxReg = Shift->getOperand(0).getReg(); 2192 2193 // It's important that IdxReg is live until the actual TBB/TBH. Most of 2194 // the range is checked later, but the LEA might still clobber it and not 2195 // actually get removed. 2196 if (BaseReg == IdxReg && !jumpTableFollowsTB(MI, User.CPEMI)) 2197 continue; 2198 2199 MachineInstr *Load = User.MI->getNextNode(); 2200 if (Load->getOpcode() != ARM::tLDRr) 2201 continue; 2202 if (Load->getOperand(1).getReg() != BaseReg || 2203 Load->getOperand(2).getReg() != ShiftedIdxReg || 2204 !Load->getOperand(2).isKill()) 2205 continue; 2206 2207 // If we're in PIC mode, there should be another ADD following. 2208 auto *TRI = STI->getRegisterInfo(); 2209 2210 // %base cannot be redefined after the load as it will appear before 2211 // TBB/TBH like: 2212 // %base = 2213 // %base = 2214 // tBB %base, %idx 2215 if (registerDefinedBetween(BaseReg, Load->getNextNode(), MBB->end(), TRI)) 2216 continue; 2217 2218 if (isPositionIndependentOrROPI) { 2219 MachineInstr *Add = Load->getNextNode(); 2220 if (Add->getOpcode() != ARM::tADDrr || 2221 Add->getOperand(2).getReg() != BaseReg || 2222 Add->getOperand(3).getReg() != Load->getOperand(0).getReg() || 2223 !Add->getOperand(3).isKill()) 2224 continue; 2225 if (Add->getOperand(0).getReg() != MI->getOperand(0).getReg()) 2226 continue; 2227 if (registerDefinedBetween(IdxReg, Add->getNextNode(), MI, TRI)) 2228 // IdxReg gets redefined in the middle of the sequence. 2229 continue; 2230 Add->eraseFromParent(); 2231 DeadSize += 2; 2232 } else { 2233 if (Load->getOperand(0).getReg() != MI->getOperand(0).getReg()) 2234 continue; 2235 if (registerDefinedBetween(IdxReg, Load->getNextNode(), MI, TRI)) 2236 // IdxReg gets redefined in the middle of the sequence. 2237 continue; 2238 } 2239 2240 // Now safe to delete the load and lsl. The LEA will be removed later. 2241 CanDeleteLEA = true; 2242 Shift->eraseFromParent(); 2243 Load->eraseFromParent(); 2244 DeadSize += 4; 2245 } 2246 2247 LLVM_DEBUG(dbgs() << "Shrink JT: " << *MI); 2248 MachineInstr *CPEMI = User.CPEMI; 2249 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT; 2250 if (!isThumb2) 2251 Opc = ByteOk ? ARM::tTBB_JT : ARM::tTBH_JT; 2252 2253 MachineBasicBlock::iterator MI_JT = MI; 2254 MachineInstr *NewJTMI = 2255 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc)) 2256 .addReg(User.MI->getOperand(0).getReg(), 2257 getKillRegState(BaseRegKill)) 2258 .addReg(IdxReg, getKillRegState(IdxRegKill)) 2259 .addJumpTableIndex(JTI, JTOP.getTargetFlags()) 2260 .addImm(CPEMI->getOperand(0).getImm()); 2261 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": " << *NewJTMI); 2262 2263 unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH; 2264 CPEMI->setDesc(TII->get(JTOpc)); 2265 2266 if (jumpTableFollowsTB(MI, User.CPEMI)) { 2267 NewJTMI->getOperand(0).setReg(ARM::PC); 2268 NewJTMI->getOperand(0).setIsKill(false); 2269 2270 if (CanDeleteLEA) { 2271 if (isThumb2) 2272 RemoveDeadAddBetweenLEAAndJT(User.MI, MI, DeadSize); 2273 2274 User.MI->eraseFromParent(); 2275 DeadSize += isThumb2 ? 4 : 2; 2276 2277 // The LEA was eliminated, the TBB instruction becomes the only new user 2278 // of the jump table. 2279 User.MI = NewJTMI; 2280 User.MaxDisp = 4; 2281 User.NegOk = false; 2282 User.IsSoImm = false; 2283 User.KnownAlignment = false; 2284 } else { 2285 // The LEA couldn't be eliminated, so we must add another CPUser to 2286 // record the TBB or TBH use. 2287 int CPEntryIdx = JumpTableEntryIndices[JTI]; 2288 auto &CPEs = CPEntries[CPEntryIdx]; 2289 auto Entry = 2290 find_if(CPEs, [&](CPEntry &E) { return E.CPEMI == User.CPEMI; }); 2291 ++Entry->RefCount; 2292 CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false)); 2293 } 2294 } 2295 2296 unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI); 2297 unsigned OrigSize = TII->getInstSizeInBytes(*MI); 2298 MI->eraseFromParent(); 2299 2300 int Delta = OrigSize - NewSize + DeadSize; 2301 BBInfo[MBB->getNumber()].Size -= Delta; 2302 BBUtils->adjustBBOffsetsAfter(MBB); 2303 2304 ++NumTBs; 2305 MadeChange = true; 2306 } 2307 2308 return MadeChange; 2309 } 2310 2311 /// reorderThumb2JumpTables - Adjust the function's block layout to ensure that 2312 /// jump tables always branch forwards, since that's what tbb and tbh need. 2313 bool ARMConstantIslands::reorderThumb2JumpTables() { 2314 bool MadeChange = false; 2315 2316 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 2317 if (!MJTI) return false; 2318 2319 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 2320 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) { 2321 MachineInstr *MI = T2JumpTables[i]; 2322 const MCInstrDesc &MCID = MI->getDesc(); 2323 unsigned NumOps = MCID.getNumOperands(); 2324 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1); 2325 MachineOperand JTOP = MI->getOperand(JTOpIdx); 2326 unsigned JTI = JTOP.getIndex(); 2327 assert(JTI < JT.size()); 2328 2329 // We prefer if target blocks for the jump table come after the jump 2330 // instruction so we can use TB[BH]. Loop through the target blocks 2331 // and try to adjust them such that that's true. 2332 int JTNumber = MI->getParent()->getNumber(); 2333 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 2334 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) { 2335 MachineBasicBlock *MBB = JTBBs[j]; 2336 int DTNumber = MBB->getNumber(); 2337 2338 if (DTNumber < JTNumber) { 2339 // The destination precedes the switch. Try to move the block forward 2340 // so we have a positive offset. 2341 MachineBasicBlock *NewBB = 2342 adjustJTTargetBlockForward(MBB, MI->getParent()); 2343 if (NewBB) 2344 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB); 2345 MadeChange = true; 2346 } 2347 } 2348 } 2349 2350 return MadeChange; 2351 } 2352 2353 MachineBasicBlock *ARMConstantIslands:: 2354 adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) { 2355 // If the destination block is terminated by an unconditional branch, 2356 // try to move it; otherwise, create a new block following the jump 2357 // table that branches back to the actual target. This is a very simple 2358 // heuristic. FIXME: We can definitely improve it. 2359 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 2360 SmallVector<MachineOperand, 4> Cond; 2361 SmallVector<MachineOperand, 4> CondPrior; 2362 MachineFunction::iterator BBi = BB->getIterator(); 2363 MachineFunction::iterator OldPrior = std::prev(BBi); 2364 MachineFunction::iterator OldNext = std::next(BBi); 2365 2366 // If the block terminator isn't analyzable, don't try to move the block 2367 bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond); 2368 2369 // If the block ends in an unconditional branch, move it. The prior block 2370 // has to have an analyzable terminator for us to move this one. Be paranoid 2371 // and make sure we're not trying to move the entry block of the function. 2372 if (!B && Cond.empty() && BB != &MF->front() && 2373 !TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) { 2374 BB->moveAfter(JTBB); 2375 OldPrior->updateTerminator(BB); 2376 BB->updateTerminator(OldNext != MF->end() ? &*OldNext : nullptr); 2377 // Update numbering to account for the block being moved. 2378 MF->RenumberBlocks(); 2379 ++NumJTMoved; 2380 return nullptr; 2381 } 2382 2383 // Create a new MBB for the code after the jump BB. 2384 MachineBasicBlock *NewBB = 2385 MF->CreateMachineBasicBlock(JTBB->getBasicBlock()); 2386 MachineFunction::iterator MBBI = ++JTBB->getIterator(); 2387 MF->insert(MBBI, NewBB); 2388 2389 // Copy live-in information to new block. 2390 for (const MachineBasicBlock::RegisterMaskPair &RegMaskPair : BB->liveins()) 2391 NewBB->addLiveIn(RegMaskPair); 2392 2393 // Add an unconditional branch from NewBB to BB. 2394 // There doesn't seem to be meaningful DebugInfo available; this doesn't 2395 // correspond directly to anything in the source. 2396 if (isThumb2) 2397 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)) 2398 .addMBB(BB) 2399 .add(predOps(ARMCC::AL)); 2400 else 2401 BuildMI(NewBB, DebugLoc(), TII->get(ARM::tB)) 2402 .addMBB(BB) 2403 .add(predOps(ARMCC::AL)); 2404 2405 // Update internal data structures to account for the newly inserted MBB. 2406 MF->RenumberBlocks(NewBB); 2407 2408 // Update the CFG. 2409 NewBB->addSuccessor(BB); 2410 JTBB->replaceSuccessor(BB, NewBB); 2411 2412 ++NumJTInserted; 2413 return NewBB; 2414 } 2415 2416 /// createARMConstantIslandPass - returns an instance of the constpool 2417 /// island pass. 2418 FunctionPass *llvm::createARMConstantIslandPass() { 2419 return new ARMConstantIslands(); 2420 } 2421 2422 INITIALIZE_PASS(ARMConstantIslands, "arm-cp-islands", ARM_CP_ISLANDS_OPT_NAME, 2423 false, false) 2424