1 //===-- PPCBranchSelector.cpp - Emit long conditional branches ------------===// 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 scans a machine function to determine which 10 // conditional branches need more than 16 bits of displacement to reach their 11 // target basic block. It does this in two passes; a calculation of basic block 12 // positions pass, and a branch pseudo op to machine branch opcode pass. This 13 // pass should be run last, just before the assembly printer. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "MCTargetDesc/PPCPredicates.h" 18 #include "PPC.h" 19 #include "PPCInstrBuilder.h" 20 #include "PPCInstrInfo.h" 21 #include "PPCSubtarget.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/CodeGen/MachineFunctionPass.h" 24 #include "llvm/CodeGen/MachineRegisterInfo.h" 25 #include "llvm/CodeGen/TargetSubtargetInfo.h" 26 #include "llvm/Support/MathExtras.h" 27 #include "llvm/Target/TargetMachine.h" 28 #include <algorithm> 29 using namespace llvm; 30 31 #define DEBUG_TYPE "ppc-branch-select" 32 33 STATISTIC(NumExpanded, "Number of branches expanded to long format"); 34 35 namespace llvm { 36 void initializePPCBSelPass(PassRegistry&); 37 } 38 39 namespace { 40 struct PPCBSel : public MachineFunctionPass { 41 static char ID; 42 PPCBSel() : MachineFunctionPass(ID) { 43 initializePPCBSelPass(*PassRegistry::getPassRegistry()); 44 } 45 46 // The sizes of the basic blocks in the function (the first 47 // element of the pair); the second element of the pair is the amount of the 48 // size that is due to potential padding. 49 std::vector<std::pair<unsigned, unsigned>> BlockSizes; 50 51 // The first block number which has imprecise instruction address. 52 int FirstImpreciseBlock = -1; 53 54 unsigned GetAlignmentAdjustment(MachineBasicBlock &MBB, unsigned Offset); 55 unsigned ComputeBlockSizes(MachineFunction &Fn); 56 void modifyAdjustment(MachineFunction &Fn); 57 int computeBranchSize(MachineFunction &Fn, 58 const MachineBasicBlock *Src, 59 const MachineBasicBlock *Dest, 60 unsigned BrOffset); 61 62 bool runOnMachineFunction(MachineFunction &Fn) override; 63 64 MachineFunctionProperties getRequiredProperties() const override { 65 return MachineFunctionProperties().set( 66 MachineFunctionProperties::Property::NoVRegs); 67 } 68 69 StringRef getPassName() const override { return "PowerPC Branch Selector"; } 70 }; 71 char PPCBSel::ID = 0; 72 } 73 74 INITIALIZE_PASS(PPCBSel, "ppc-branch-select", "PowerPC Branch Selector", 75 false, false) 76 77 /// createPPCBranchSelectionPass - returns an instance of the Branch Selection 78 /// Pass 79 /// 80 FunctionPass *llvm::createPPCBranchSelectionPass() { 81 return new PPCBSel(); 82 } 83 84 /// In order to make MBB aligned, we need to add an adjustment value to the 85 /// original Offset. 86 unsigned PPCBSel::GetAlignmentAdjustment(MachineBasicBlock &MBB, 87 unsigned Offset) { 88 unsigned Align = MBB.getAlignment(); 89 if (!Align) 90 return 0; 91 92 unsigned AlignAmt = 1 << Align; 93 unsigned ParentAlign = MBB.getParent()->getAlignment(); 94 95 if (Align <= ParentAlign) 96 return OffsetToAlignment(Offset, AlignAmt); 97 98 // The alignment of this MBB is larger than the function's alignment, so we 99 // can't tell whether or not it will insert nops. Assume that it will. 100 if (FirstImpreciseBlock < 0) 101 FirstImpreciseBlock = MBB.getNumber(); 102 return AlignAmt + OffsetToAlignment(Offset, AlignAmt); 103 } 104 105 /// We need to be careful about the offset of the first block in the function 106 /// because it might not have the function's alignment. This happens because, 107 /// under the ELFv2 ABI, for functions which require a TOC pointer, we add a 108 /// two-instruction sequence to the start of the function. 109 /// Note: This needs to be synchronized with the check in 110 /// PPCLinuxAsmPrinter::EmitFunctionBodyStart. 111 static inline unsigned GetInitialOffset(MachineFunction &Fn) { 112 unsigned InitialOffset = 0; 113 if (Fn.getSubtarget<PPCSubtarget>().isELFv2ABI() && 114 !Fn.getRegInfo().use_empty(PPC::X2)) 115 InitialOffset = 8; 116 return InitialOffset; 117 } 118 119 /// Measure each MBB and compute a size for the entire function. 120 unsigned PPCBSel::ComputeBlockSizes(MachineFunction &Fn) { 121 const PPCInstrInfo *TII = 122 static_cast<const PPCInstrInfo *>(Fn.getSubtarget().getInstrInfo()); 123 unsigned FuncSize = GetInitialOffset(Fn); 124 125 for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E; 126 ++MFI) { 127 MachineBasicBlock *MBB = &*MFI; 128 129 // The end of the previous block may have extra nops if this block has an 130 // alignment requirement. 131 if (MBB->getNumber() > 0) { 132 unsigned AlignExtra = GetAlignmentAdjustment(*MBB, FuncSize); 133 134 auto &BS = BlockSizes[MBB->getNumber()-1]; 135 BS.first += AlignExtra; 136 BS.second = AlignExtra; 137 138 FuncSize += AlignExtra; 139 } 140 141 unsigned BlockSize = 0; 142 for (MachineInstr &MI : *MBB) { 143 BlockSize += TII->getInstSizeInBytes(MI); 144 if (MI.isInlineAsm() && (FirstImpreciseBlock < 0)) 145 FirstImpreciseBlock = MBB->getNumber(); 146 } 147 148 BlockSizes[MBB->getNumber()].first = BlockSize; 149 FuncSize += BlockSize; 150 } 151 152 return FuncSize; 153 } 154 155 /// Modify the basic block align adjustment. 156 void PPCBSel::modifyAdjustment(MachineFunction &Fn) { 157 unsigned Offset = GetInitialOffset(Fn); 158 for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E; 159 ++MFI) { 160 MachineBasicBlock *MBB = &*MFI; 161 162 if (MBB->getNumber() > 0) { 163 auto &BS = BlockSizes[MBB->getNumber()-1]; 164 BS.first -= BS.second; 165 Offset -= BS.second; 166 167 unsigned AlignExtra = GetAlignmentAdjustment(*MBB, Offset); 168 169 BS.first += AlignExtra; 170 BS.second = AlignExtra; 171 172 Offset += AlignExtra; 173 } 174 175 Offset += BlockSizes[MBB->getNumber()].first; 176 } 177 } 178 179 /// Determine the offset from the branch in Src block to the Dest block. 180 /// BrOffset is the offset of the branch instruction inside Src block. 181 int PPCBSel::computeBranchSize(MachineFunction &Fn, 182 const MachineBasicBlock *Src, 183 const MachineBasicBlock *Dest, 184 unsigned BrOffset) { 185 int BranchSize; 186 unsigned MaxAlign = 2; 187 bool NeedExtraAdjustment = false; 188 if (Dest->getNumber() <= Src->getNumber()) { 189 // If this is a backwards branch, the delta is the offset from the 190 // start of this block to this branch, plus the sizes of all blocks 191 // from this block to the dest. 192 BranchSize = BrOffset; 193 MaxAlign = std::max(MaxAlign, Src->getAlignment()); 194 195 int DestBlock = Dest->getNumber(); 196 BranchSize += BlockSizes[DestBlock].first; 197 for (unsigned i = DestBlock+1, e = Src->getNumber(); i < e; ++i) { 198 BranchSize += BlockSizes[i].first; 199 MaxAlign = std::max(MaxAlign, 200 Fn.getBlockNumbered(i)->getAlignment()); 201 } 202 203 NeedExtraAdjustment = (FirstImpreciseBlock >= 0) && 204 (DestBlock >= FirstImpreciseBlock); 205 } else { 206 // Otherwise, add the size of the blocks between this block and the 207 // dest to the number of bytes left in this block. 208 unsigned StartBlock = Src->getNumber(); 209 BranchSize = BlockSizes[StartBlock].first - BrOffset; 210 211 MaxAlign = std::max(MaxAlign, Dest->getAlignment()); 212 for (unsigned i = StartBlock+1, e = Dest->getNumber(); i != e; ++i) { 213 BranchSize += BlockSizes[i].first; 214 MaxAlign = std::max(MaxAlign, 215 Fn.getBlockNumbered(i)->getAlignment()); 216 } 217 218 NeedExtraAdjustment = (FirstImpreciseBlock >= 0) && 219 (Src->getNumber() >= FirstImpreciseBlock); 220 } 221 222 // We tend to over estimate code size due to large alignment and 223 // inline assembly. Usually it causes larger computed branch offset. 224 // But sometimes it may also causes smaller computed branch offset 225 // than actual branch offset. If the offset is close to the limit of 226 // encoding, it may cause problem at run time. 227 // Following is a simplified example. 228 // 229 // actual estimated 230 // address address 231 // ... 232 // bne Far 100 10c 233 // .p2align 4 234 // Near: 110 110 235 // ... 236 // Far: 8108 8108 237 // 238 // Actual offset: 0x8108 - 0x100 = 0x8008 239 // Computed offset: 0x8108 - 0x10c = 0x7ffc 240 // 241 // This example also shows when we can get the largest gap between 242 // estimated offset and actual offset. If there is an aligned block 243 // ABB between branch and target, assume its alignment is <align> 244 // bits. Now consider the accumulated function size FSIZE till the end 245 // of previous block PBB. If the estimated FSIZE is multiple of 246 // 2^<align>, we don't need any padding for the estimated address of 247 // ABB. If actual FSIZE at the end of PBB is 4 bytes more than 248 // multiple of 2^<align>, then we need (2^<align> - 4) bytes of 249 // padding. It also means the actual branch offset is (2^<align> - 4) 250 // larger than computed offset. Other actual FSIZE needs less padding 251 // bytes, so causes smaller gap between actual and computed offset. 252 // 253 // On the other hand, if the inline asm or large alignment occurs 254 // between the branch block and destination block, the estimated address 255 // can be <delta> larger than actual address. If padding bytes are 256 // needed for a later aligned block, the actual number of padding bytes 257 // is at most <delta> more than estimated padding bytes. So the actual 258 // aligned block address is less than or equal to the estimated aligned 259 // block address. So the actual branch offset is less than or equal to 260 // computed branch offset. 261 // 262 // The computed offset is at most ((1 << alignment) - 4) bytes smaller 263 // than actual offset. So we add this number to the offset for safety. 264 if (NeedExtraAdjustment) 265 BranchSize += (1 << MaxAlign) - 4; 266 267 return BranchSize; 268 } 269 270 bool PPCBSel::runOnMachineFunction(MachineFunction &Fn) { 271 const PPCInstrInfo *TII = 272 static_cast<const PPCInstrInfo *>(Fn.getSubtarget().getInstrInfo()); 273 // Give the blocks of the function a dense, in-order, numbering. 274 Fn.RenumberBlocks(); 275 BlockSizes.resize(Fn.getNumBlockIDs()); 276 FirstImpreciseBlock = -1; 277 278 // Measure each MBB and compute a size for the entire function. 279 unsigned FuncSize = ComputeBlockSizes(Fn); 280 281 // If the entire function is smaller than the displacement of a branch field, 282 // we know we don't need to shrink any branches in this function. This is a 283 // common case. 284 if (FuncSize < (1 << 15)) { 285 BlockSizes.clear(); 286 return false; 287 } 288 289 // For each conditional branch, if the offset to its destination is larger 290 // than the offset field allows, transform it into a long branch sequence 291 // like this: 292 // short branch: 293 // bCC MBB 294 // long branch: 295 // b!CC $PC+8 296 // b MBB 297 // 298 bool MadeChange = true; 299 bool EverMadeChange = false; 300 while (MadeChange) { 301 // Iteratively expand branches until we reach a fixed point. 302 MadeChange = false; 303 304 for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E; 305 ++MFI) { 306 MachineBasicBlock &MBB = *MFI; 307 unsigned MBBStartOffset = 0; 308 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); 309 I != E; ++I) { 310 MachineBasicBlock *Dest = nullptr; 311 if (I->getOpcode() == PPC::BCC && !I->getOperand(2).isImm()) 312 Dest = I->getOperand(2).getMBB(); 313 else if ((I->getOpcode() == PPC::BC || I->getOpcode() == PPC::BCn) && 314 !I->getOperand(1).isImm()) 315 Dest = I->getOperand(1).getMBB(); 316 else if ((I->getOpcode() == PPC::BDNZ8 || I->getOpcode() == PPC::BDNZ || 317 I->getOpcode() == PPC::BDZ8 || I->getOpcode() == PPC::BDZ) && 318 !I->getOperand(0).isImm()) 319 Dest = I->getOperand(0).getMBB(); 320 321 if (!Dest) { 322 MBBStartOffset += TII->getInstSizeInBytes(*I); 323 continue; 324 } 325 326 // Determine the offset from the current branch to the destination 327 // block. 328 int BranchSize = computeBranchSize(Fn, &MBB, Dest, MBBStartOffset); 329 330 // If this branch is in range, ignore it. 331 if (isInt<16>(BranchSize)) { 332 MBBStartOffset += 4; 333 continue; 334 } 335 336 // Otherwise, we have to expand it to a long branch. 337 MachineInstr &OldBranch = *I; 338 DebugLoc dl = OldBranch.getDebugLoc(); 339 340 if (I->getOpcode() == PPC::BCC) { 341 // The BCC operands are: 342 // 0. PPC branch predicate 343 // 1. CR register 344 // 2. Target MBB 345 PPC::Predicate Pred = (PPC::Predicate)I->getOperand(0).getImm(); 346 unsigned CRReg = I->getOperand(1).getReg(); 347 348 // Jump over the uncond branch inst (i.e. $PC+8) on opposite condition. 349 BuildMI(MBB, I, dl, TII->get(PPC::BCC)) 350 .addImm(PPC::InvertPredicate(Pred)).addReg(CRReg).addImm(2); 351 } else if (I->getOpcode() == PPC::BC) { 352 unsigned CRBit = I->getOperand(0).getReg(); 353 BuildMI(MBB, I, dl, TII->get(PPC::BCn)).addReg(CRBit).addImm(2); 354 } else if (I->getOpcode() == PPC::BCn) { 355 unsigned CRBit = I->getOperand(0).getReg(); 356 BuildMI(MBB, I, dl, TII->get(PPC::BC)).addReg(CRBit).addImm(2); 357 } else if (I->getOpcode() == PPC::BDNZ) { 358 BuildMI(MBB, I, dl, TII->get(PPC::BDZ)).addImm(2); 359 } else if (I->getOpcode() == PPC::BDNZ8) { 360 BuildMI(MBB, I, dl, TII->get(PPC::BDZ8)).addImm(2); 361 } else if (I->getOpcode() == PPC::BDZ) { 362 BuildMI(MBB, I, dl, TII->get(PPC::BDNZ)).addImm(2); 363 } else if (I->getOpcode() == PPC::BDZ8) { 364 BuildMI(MBB, I, dl, TII->get(PPC::BDNZ8)).addImm(2); 365 } else { 366 llvm_unreachable("Unhandled branch type!"); 367 } 368 369 // Uncond branch to the real destination. 370 I = BuildMI(MBB, I, dl, TII->get(PPC::B)).addMBB(Dest); 371 372 // Remove the old branch from the function. 373 OldBranch.eraseFromParent(); 374 375 // Remember that this instruction is 8-bytes, increase the size of the 376 // block by 4, remember to iterate. 377 BlockSizes[MBB.getNumber()].first += 4; 378 MBBStartOffset += 8; 379 ++NumExpanded; 380 MadeChange = true; 381 } 382 } 383 384 if (MadeChange) { 385 // If we're going to iterate again, make sure we've updated our 386 // padding-based contributions to the block sizes. 387 modifyAdjustment(Fn); 388 } 389 390 EverMadeChange |= MadeChange; 391 } 392 393 BlockSizes.clear(); 394 return true; 395 } 396