1 //===-- SystemZLongBranch.cpp - Branch lengthening for SystemZ ------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass makes sure that all branches are in range. There are several ways 11 // in which this could be done. One aggressive approach is to assume that all 12 // branches are in range and successively replace those that turn out not 13 // to be in range with a longer form (branch relaxation). A simple 14 // implementation is to continually walk through the function relaxing 15 // branches until no more changes are needed and a fixed point is reached. 16 // However, in the pathological worst case, this implementation is 17 // quadratic in the number of blocks; relaxing branch N can make branch N-1 18 // go out of range, which in turn can make branch N-2 go out of range, 19 // and so on. 20 // 21 // An alternative approach is to assume that all branches must be 22 // converted to their long forms, then reinstate the short forms of 23 // branches that, even under this pessimistic assumption, turn out to be 24 // in range (branch shortening). This too can be implemented as a function 25 // walk that is repeated until a fixed point is reached. In general, 26 // the result of shortening is not as good as that of relaxation, and 27 // shortening is also quadratic in the worst case; shortening branch N 28 // can bring branch N-1 in range of the short form, which in turn can do 29 // the same for branch N-2, and so on. The main advantage of shortening 30 // is that each walk through the function produces valid code, so it is 31 // possible to stop at any point after the first walk. The quadraticness 32 // could therefore be handled with a maximum pass count, although the 33 // question then becomes: what maximum count should be used? 34 // 35 // On SystemZ, long branches are only needed for functions bigger than 64k, 36 // which are relatively rare to begin with, and the long branch sequences 37 // are actually relatively cheap. It therefore doesn't seem worth spending 38 // much compilation time on the problem. Instead, the approach we take is: 39 // 40 // (1) Work out the address that each block would have if no branches 41 // need relaxing. Exit the pass early if all branches are in range 42 // according to this assumption. 43 // 44 // (2) Work out the address that each block would have if all branches 45 // need relaxing. 46 // 47 // (3) Walk through the block calculating the final address of each instruction 48 // and relaxing those that need to be relaxed. For backward branches, 49 // this check uses the final address of the target block, as calculated 50 // earlier in the walk. For forward branches, this check uses the 51 // address of the target block that was calculated in (2). Both checks 52 // give a conservatively-correct range. 53 // 54 //===----------------------------------------------------------------------===// 55 56 #include "SystemZTargetMachine.h" 57 #include "llvm/ADT/Statistic.h" 58 #include "llvm/CodeGen/MachineFunctionPass.h" 59 #include "llvm/CodeGen/MachineInstrBuilder.h" 60 #include "llvm/IR/Function.h" 61 #include "llvm/Support/CommandLine.h" 62 #include "llvm/Support/MathExtras.h" 63 #include "llvm/Target/TargetInstrInfo.h" 64 #include "llvm/Target/TargetMachine.h" 65 #include "llvm/Target/TargetRegisterInfo.h" 66 67 using namespace llvm; 68 69 #define DEBUG_TYPE "systemz-long-branch" 70 71 STATISTIC(LongBranches, "Number of long branches."); 72 73 namespace { 74 // Represents positional information about a basic block. 75 struct MBBInfo { 76 // The address that we currently assume the block has. 77 uint64_t Address; 78 79 // The size of the block in bytes, excluding terminators. 80 // This value never changes. 81 uint64_t Size; 82 83 // The minimum alignment of the block, as a log2 value. 84 // This value never changes. 85 unsigned Alignment; 86 87 // The number of terminators in this block. This value never changes. 88 unsigned NumTerminators; 89 90 MBBInfo() 91 : Address(0), Size(0), Alignment(0), NumTerminators(0) {} 92 }; 93 94 // Represents the state of a block terminator. 95 struct TerminatorInfo { 96 // If this terminator is a relaxable branch, this points to the branch 97 // instruction, otherwise it is null. 98 MachineInstr *Branch; 99 100 // The address that we currently assume the terminator has. 101 uint64_t Address; 102 103 // The current size of the terminator in bytes. 104 uint64_t Size; 105 106 // If Branch is nonnull, this is the number of the target block, 107 // otherwise it is unused. 108 unsigned TargetBlock; 109 110 // If Branch is nonnull, this is the length of the longest relaxed form, 111 // otherwise it is zero. 112 unsigned ExtraRelaxSize; 113 114 TerminatorInfo() : Branch(nullptr), Size(0), TargetBlock(0), 115 ExtraRelaxSize(0) {} 116 }; 117 118 // Used to keep track of the current position while iterating over the blocks. 119 struct BlockPosition { 120 // The address that we assume this position has. 121 uint64_t Address; 122 123 // The number of low bits in Address that are known to be the same 124 // as the runtime address. 125 unsigned KnownBits; 126 127 BlockPosition(unsigned InitialAlignment) 128 : Address(0), KnownBits(InitialAlignment) {} 129 }; 130 131 class SystemZLongBranch : public MachineFunctionPass { 132 public: 133 static char ID; 134 SystemZLongBranch(const SystemZTargetMachine &tm) 135 : MachineFunctionPass(ID), TII(nullptr) {} 136 137 const char *getPassName() const override { 138 return "SystemZ Long Branch"; 139 } 140 141 bool runOnMachineFunction(MachineFunction &F) override; 142 MachineFunctionProperties getRequiredProperties() const override { 143 return MachineFunctionProperties().set( 144 MachineFunctionProperties::Property::AllVRegsAllocated); 145 } 146 147 private: 148 void skipNonTerminators(BlockPosition &Position, MBBInfo &Block); 149 void skipTerminator(BlockPosition &Position, TerminatorInfo &Terminator, 150 bool AssumeRelaxed); 151 TerminatorInfo describeTerminator(MachineInstr *MI); 152 uint64_t initMBBInfo(); 153 bool mustRelaxBranch(const TerminatorInfo &Terminator, uint64_t Address); 154 bool mustRelaxABranch(); 155 void setWorstCaseAddresses(); 156 void splitBranchOnCount(MachineInstr *MI, unsigned AddOpcode); 157 void splitCompareBranch(MachineInstr *MI, unsigned CompareOpcode); 158 void relaxBranch(TerminatorInfo &Terminator); 159 void relaxBranches(); 160 161 const SystemZInstrInfo *TII; 162 MachineFunction *MF; 163 SmallVector<MBBInfo, 16> MBBs; 164 SmallVector<TerminatorInfo, 16> Terminators; 165 }; 166 167 char SystemZLongBranch::ID = 0; 168 169 const uint64_t MaxBackwardRange = 0x10000; 170 const uint64_t MaxForwardRange = 0xfffe; 171 } // end anonymous namespace 172 173 FunctionPass *llvm::createSystemZLongBranchPass(SystemZTargetMachine &TM) { 174 return new SystemZLongBranch(TM); 175 } 176 177 // Position describes the state immediately before Block. Update Block 178 // accordingly and move Position to the end of the block's non-terminator 179 // instructions. 180 void SystemZLongBranch::skipNonTerminators(BlockPosition &Position, 181 MBBInfo &Block) { 182 if (Block.Alignment > Position.KnownBits) { 183 // When calculating the address of Block, we need to conservatively 184 // assume that Block had the worst possible misalignment. 185 Position.Address += ((uint64_t(1) << Block.Alignment) - 186 (uint64_t(1) << Position.KnownBits)); 187 Position.KnownBits = Block.Alignment; 188 } 189 190 // Align the addresses. 191 uint64_t AlignMask = (uint64_t(1) << Block.Alignment) - 1; 192 Position.Address = (Position.Address + AlignMask) & ~AlignMask; 193 194 // Record the block's position. 195 Block.Address = Position.Address; 196 197 // Move past the non-terminators in the block. 198 Position.Address += Block.Size; 199 } 200 201 // Position describes the state immediately before Terminator. 202 // Update Terminator accordingly and move Position past it. 203 // Assume that Terminator will be relaxed if AssumeRelaxed. 204 void SystemZLongBranch::skipTerminator(BlockPosition &Position, 205 TerminatorInfo &Terminator, 206 bool AssumeRelaxed) { 207 Terminator.Address = Position.Address; 208 Position.Address += Terminator.Size; 209 if (AssumeRelaxed) 210 Position.Address += Terminator.ExtraRelaxSize; 211 } 212 213 // Return a description of terminator instruction MI. 214 TerminatorInfo SystemZLongBranch::describeTerminator(MachineInstr *MI) { 215 TerminatorInfo Terminator; 216 Terminator.Size = TII->getInstSizeInBytes(MI); 217 if (MI->isConditionalBranch() || MI->isUnconditionalBranch()) { 218 switch (MI->getOpcode()) { 219 case SystemZ::J: 220 // Relaxes to JG, which is 2 bytes longer. 221 Terminator.ExtraRelaxSize = 2; 222 break; 223 case SystemZ::BRC: 224 // Relaxes to BRCL, which is 2 bytes longer. 225 Terminator.ExtraRelaxSize = 2; 226 break; 227 case SystemZ::BRCT: 228 case SystemZ::BRCTG: 229 // Relaxes to A(G)HI and BRCL, which is 6 bytes longer. 230 Terminator.ExtraRelaxSize = 6; 231 break; 232 case SystemZ::CRJ: 233 case SystemZ::CLRJ: 234 // Relaxes to a C(L)R/BRCL sequence, which is 2 bytes longer. 235 Terminator.ExtraRelaxSize = 2; 236 break; 237 case SystemZ::CGRJ: 238 case SystemZ::CLGRJ: 239 // Relaxes to a C(L)GR/BRCL sequence, which is 4 bytes longer. 240 Terminator.ExtraRelaxSize = 4; 241 break; 242 case SystemZ::CIJ: 243 case SystemZ::CGIJ: 244 // Relaxes to a C(G)HI/BRCL sequence, which is 4 bytes longer. 245 Terminator.ExtraRelaxSize = 4; 246 break; 247 case SystemZ::CLIJ: 248 case SystemZ::CLGIJ: 249 // Relaxes to a CL(G)FI/BRCL sequence, which is 6 bytes longer. 250 Terminator.ExtraRelaxSize = 6; 251 break; 252 default: 253 llvm_unreachable("Unrecognized branch instruction"); 254 } 255 Terminator.Branch = MI; 256 Terminator.TargetBlock = 257 TII->getBranchInfo(MI).Target->getMBB()->getNumber(); 258 } 259 return Terminator; 260 } 261 262 // Fill MBBs and Terminators, setting the addresses on the assumption 263 // that no branches need relaxation. Return the size of the function under 264 // this assumption. 265 uint64_t SystemZLongBranch::initMBBInfo() { 266 MF->RenumberBlocks(); 267 unsigned NumBlocks = MF->size(); 268 269 MBBs.clear(); 270 MBBs.resize(NumBlocks); 271 272 Terminators.clear(); 273 Terminators.reserve(NumBlocks); 274 275 BlockPosition Position(MF->getAlignment()); 276 for (unsigned I = 0; I < NumBlocks; ++I) { 277 MachineBasicBlock *MBB = MF->getBlockNumbered(I); 278 MBBInfo &Block = MBBs[I]; 279 280 // Record the alignment, for quick access. 281 Block.Alignment = MBB->getAlignment(); 282 283 // Calculate the size of the fixed part of the block. 284 MachineBasicBlock::iterator MI = MBB->begin(); 285 MachineBasicBlock::iterator End = MBB->end(); 286 while (MI != End && !MI->isTerminator()) { 287 Block.Size += TII->getInstSizeInBytes(MI); 288 ++MI; 289 } 290 skipNonTerminators(Position, Block); 291 292 // Add the terminators. 293 while (MI != End) { 294 if (!MI->isDebugValue()) { 295 assert(MI->isTerminator() && "Terminator followed by non-terminator"); 296 Terminators.push_back(describeTerminator(MI)); 297 skipTerminator(Position, Terminators.back(), false); 298 ++Block.NumTerminators; 299 } 300 ++MI; 301 } 302 } 303 304 return Position.Address; 305 } 306 307 // Return true if, under current assumptions, Terminator would need to be 308 // relaxed if it were placed at address Address. 309 bool SystemZLongBranch::mustRelaxBranch(const TerminatorInfo &Terminator, 310 uint64_t Address) { 311 if (!Terminator.Branch) 312 return false; 313 314 const MBBInfo &Target = MBBs[Terminator.TargetBlock]; 315 if (Address >= Target.Address) { 316 if (Address - Target.Address <= MaxBackwardRange) 317 return false; 318 } else { 319 if (Target.Address - Address <= MaxForwardRange) 320 return false; 321 } 322 323 return true; 324 } 325 326 // Return true if, under current assumptions, any terminator needs 327 // to be relaxed. 328 bool SystemZLongBranch::mustRelaxABranch() { 329 for (auto &Terminator : Terminators) 330 if (mustRelaxBranch(Terminator, Terminator.Address)) 331 return true; 332 return false; 333 } 334 335 // Set the address of each block on the assumption that all branches 336 // must be long. 337 void SystemZLongBranch::setWorstCaseAddresses() { 338 SmallVector<TerminatorInfo, 16>::iterator TI = Terminators.begin(); 339 BlockPosition Position(MF->getAlignment()); 340 for (auto &Block : MBBs) { 341 skipNonTerminators(Position, Block); 342 for (unsigned BTI = 0, BTE = Block.NumTerminators; BTI != BTE; ++BTI) { 343 skipTerminator(Position, *TI, true); 344 ++TI; 345 } 346 } 347 } 348 349 // Split BRANCH ON COUNT MI into the addition given by AddOpcode followed 350 // by a BRCL on the result. 351 void SystemZLongBranch::splitBranchOnCount(MachineInstr *MI, 352 unsigned AddOpcode) { 353 MachineBasicBlock *MBB = MI->getParent(); 354 DebugLoc DL = MI->getDebugLoc(); 355 BuildMI(*MBB, MI, DL, TII->get(AddOpcode)) 356 .addOperand(MI->getOperand(0)) 357 .addOperand(MI->getOperand(1)) 358 .addImm(-1); 359 MachineInstr *BRCL = BuildMI(*MBB, MI, DL, TII->get(SystemZ::BRCL)) 360 .addImm(SystemZ::CCMASK_ICMP) 361 .addImm(SystemZ::CCMASK_CMP_NE) 362 .addOperand(MI->getOperand(2)); 363 // The implicit use of CC is a killing use. 364 BRCL->addRegisterKilled(SystemZ::CC, &TII->getRegisterInfo()); 365 MI->eraseFromParent(); 366 } 367 368 // Split MI into the comparison given by CompareOpcode followed 369 // a BRCL on the result. 370 void SystemZLongBranch::splitCompareBranch(MachineInstr *MI, 371 unsigned CompareOpcode) { 372 MachineBasicBlock *MBB = MI->getParent(); 373 DebugLoc DL = MI->getDebugLoc(); 374 BuildMI(*MBB, MI, DL, TII->get(CompareOpcode)) 375 .addOperand(MI->getOperand(0)) 376 .addOperand(MI->getOperand(1)); 377 MachineInstr *BRCL = BuildMI(*MBB, MI, DL, TII->get(SystemZ::BRCL)) 378 .addImm(SystemZ::CCMASK_ICMP) 379 .addOperand(MI->getOperand(2)) 380 .addOperand(MI->getOperand(3)); 381 // The implicit use of CC is a killing use. 382 BRCL->addRegisterKilled(SystemZ::CC, &TII->getRegisterInfo()); 383 MI->eraseFromParent(); 384 } 385 386 // Relax the branch described by Terminator. 387 void SystemZLongBranch::relaxBranch(TerminatorInfo &Terminator) { 388 MachineInstr *Branch = Terminator.Branch; 389 switch (Branch->getOpcode()) { 390 case SystemZ::J: 391 Branch->setDesc(TII->get(SystemZ::JG)); 392 break; 393 case SystemZ::BRC: 394 Branch->setDesc(TII->get(SystemZ::BRCL)); 395 break; 396 case SystemZ::BRCT: 397 splitBranchOnCount(Branch, SystemZ::AHI); 398 break; 399 case SystemZ::BRCTG: 400 splitBranchOnCount(Branch, SystemZ::AGHI); 401 break; 402 case SystemZ::CRJ: 403 splitCompareBranch(Branch, SystemZ::CR); 404 break; 405 case SystemZ::CGRJ: 406 splitCompareBranch(Branch, SystemZ::CGR); 407 break; 408 case SystemZ::CIJ: 409 splitCompareBranch(Branch, SystemZ::CHI); 410 break; 411 case SystemZ::CGIJ: 412 splitCompareBranch(Branch, SystemZ::CGHI); 413 break; 414 case SystemZ::CLRJ: 415 splitCompareBranch(Branch, SystemZ::CLR); 416 break; 417 case SystemZ::CLGRJ: 418 splitCompareBranch(Branch, SystemZ::CLGR); 419 break; 420 case SystemZ::CLIJ: 421 splitCompareBranch(Branch, SystemZ::CLFI); 422 break; 423 case SystemZ::CLGIJ: 424 splitCompareBranch(Branch, SystemZ::CLGFI); 425 break; 426 default: 427 llvm_unreachable("Unrecognized branch"); 428 } 429 430 Terminator.Size += Terminator.ExtraRelaxSize; 431 Terminator.ExtraRelaxSize = 0; 432 Terminator.Branch = nullptr; 433 434 ++LongBranches; 435 } 436 437 // Run a shortening pass and relax any branches that need to be relaxed. 438 void SystemZLongBranch::relaxBranches() { 439 SmallVector<TerminatorInfo, 16>::iterator TI = Terminators.begin(); 440 BlockPosition Position(MF->getAlignment()); 441 for (auto &Block : MBBs) { 442 skipNonTerminators(Position, Block); 443 for (unsigned BTI = 0, BTE = Block.NumTerminators; BTI != BTE; ++BTI) { 444 assert(Position.Address <= TI->Address && 445 "Addresses shouldn't go forwards"); 446 if (mustRelaxBranch(*TI, Position.Address)) 447 relaxBranch(*TI); 448 skipTerminator(Position, *TI, false); 449 ++TI; 450 } 451 } 452 } 453 454 bool SystemZLongBranch::runOnMachineFunction(MachineFunction &F) { 455 TII = static_cast<const SystemZInstrInfo *>(F.getSubtarget().getInstrInfo()); 456 MF = &F; 457 uint64_t Size = initMBBInfo(); 458 if (Size <= MaxForwardRange || !mustRelaxABranch()) 459 return false; 460 461 setWorstCaseAddresses(); 462 relaxBranches(); 463 return true; 464 } 465