1 //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===// 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 /// \file 10 /// Replaces repeated sequences of instructions with function calls. 11 /// 12 /// This works by placing every instruction from every basic block in a 13 /// suffix tree, and repeatedly querying that tree for repeated sequences of 14 /// instructions. If a sequence of instructions appears often, then it ought 15 /// to be beneficial to pull out into a function. 16 /// 17 /// The MachineOutliner communicates with a given target using hooks defined in 18 /// TargetInstrInfo.h. The target supplies the outliner with information on how 19 /// a specific sequence of instructions should be outlined. This information 20 /// is used to deduce the number of instructions necessary to 21 /// 22 /// * Create an outlined function 23 /// * Call that outlined function 24 /// 25 /// Targets must implement 26 /// * getOutliningCandidateInfo 27 /// * buildOutlinedFrame 28 /// * insertOutlinedCall 29 /// * isFunctionSafeToOutlineFrom 30 /// 31 /// in order to make use of the MachineOutliner. 32 /// 33 /// This was originally presented at the 2016 LLVM Developers' Meeting in the 34 /// talk "Reducing Code Size Using Outlining". For a high-level overview of 35 /// how this pass works, the talk is available on YouTube at 36 /// 37 /// https://www.youtube.com/watch?v=yorld-WSOeU 38 /// 39 /// The slides for the talk are available at 40 /// 41 /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf 42 /// 43 /// The talk provides an overview of how the outliner finds candidates and 44 /// ultimately outlines them. It describes how the main data structure for this 45 /// pass, the suffix tree, is queried and purged for candidates. It also gives 46 /// a simplified suffix tree construction algorithm for suffix trees based off 47 /// of the algorithm actually used here, Ukkonen's algorithm. 48 /// 49 /// For the original RFC for this pass, please see 50 /// 51 /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html 52 /// 53 /// For more information on the suffix tree data structure, please see 54 /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf 55 /// 56 //===----------------------------------------------------------------------===// 57 #include "llvm/CodeGen/MachineOutliner.h" 58 #include "llvm/ADT/DenseMap.h" 59 #include "llvm/ADT/SmallSet.h" 60 #include "llvm/ADT/Statistic.h" 61 #include "llvm/ADT/Twine.h" 62 #include "llvm/CodeGen/MachineModuleInfo.h" 63 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" 64 #include "llvm/CodeGen/Passes.h" 65 #include "llvm/CodeGen/TargetInstrInfo.h" 66 #include "llvm/CodeGen/TargetSubtargetInfo.h" 67 #include "llvm/IR/DIBuilder.h" 68 #include "llvm/IR/IRBuilder.h" 69 #include "llvm/IR/Mangler.h" 70 #include "llvm/InitializePasses.h" 71 #include "llvm/Support/CommandLine.h" 72 #include "llvm/Support/Debug.h" 73 #include "llvm/Support/SuffixTree.h" 74 #include "llvm/Support/raw_ostream.h" 75 #include <functional> 76 #include <tuple> 77 #include <vector> 78 79 #define DEBUG_TYPE "machine-outliner" 80 81 using namespace llvm; 82 using namespace ore; 83 using namespace outliner; 84 85 // Statistics for outlined functions. 86 STATISTIC(NumOutlined, "Number of candidates outlined"); 87 STATISTIC(FunctionsCreated, "Number of functions created"); 88 89 // Statistics for instruction mapping. 90 STATISTIC(NumLegalInUnsignedVec, "Number of legal instrs in unsigned vector"); 91 STATISTIC(NumIllegalInUnsignedVec, 92 "Number of illegal instrs in unsigned vector"); 93 STATISTIC(NumInvisible, "Number of invisible instrs in unsigned vector"); 94 STATISTIC(UnsignedVecSize, "Size of unsigned vector"); 95 96 // Set to true if the user wants the outliner to run on linkonceodr linkage 97 // functions. This is false by default because the linker can dedupe linkonceodr 98 // functions. Since the outliner is confined to a single module (modulo LTO), 99 // this is off by default. It should, however, be the default behaviour in 100 // LTO. 101 static cl::opt<bool> EnableLinkOnceODROutlining( 102 "enable-linkonceodr-outlining", cl::Hidden, 103 cl::desc("Enable the machine outliner on linkonceodr functions"), 104 cl::init(false)); 105 106 /// Number of times to re-run the outliner. This is not the total number of runs 107 /// as the outliner will run at least one time. The default value is set to 0, 108 /// meaning the outliner will run one time and rerun zero times after that. 109 static cl::opt<unsigned> OutlinerReruns( 110 "machine-outliner-reruns", cl::init(0), cl::Hidden, 111 cl::desc( 112 "Number of times to rerun the outliner after the initial outline")); 113 114 namespace { 115 116 /// Maps \p MachineInstrs to unsigned integers and stores the mappings. 117 struct InstructionMapper { 118 119 /// The next available integer to assign to a \p MachineInstr that 120 /// cannot be outlined. 121 /// 122 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>. 123 unsigned IllegalInstrNumber = -3; 124 125 /// The next available integer to assign to a \p MachineInstr that can 126 /// be outlined. 127 unsigned LegalInstrNumber = 0; 128 129 /// Correspondence from \p MachineInstrs to unsigned integers. 130 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait> 131 InstructionIntegerMap; 132 133 /// Correspondence between \p MachineBasicBlocks and target-defined flags. 134 DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap; 135 136 /// The vector of unsigned integers that the module is mapped to. 137 std::vector<unsigned> UnsignedVec; 138 139 /// Stores the location of the instruction associated with the integer 140 /// at index i in \p UnsignedVec for each index i. 141 std::vector<MachineBasicBlock::iterator> InstrList; 142 143 // Set if we added an illegal number in the previous step. 144 // Since each illegal number is unique, we only need one of them between 145 // each range of legal numbers. This lets us make sure we don't add more 146 // than one illegal number per range. 147 bool AddedIllegalLastTime = false; 148 149 /// Maps \p *It to a legal integer. 150 /// 151 /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB, 152 /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber. 153 /// 154 /// \returns The integer that \p *It was mapped to. 155 unsigned mapToLegalUnsigned( 156 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr, 157 bool &HaveLegalRange, unsigned &NumLegalInBlock, 158 std::vector<unsigned> &UnsignedVecForMBB, 159 std::vector<MachineBasicBlock::iterator> &InstrListForMBB) { 160 // We added something legal, so we should unset the AddedLegalLastTime 161 // flag. 162 AddedIllegalLastTime = false; 163 164 // If we have at least two adjacent legal instructions (which may have 165 // invisible instructions in between), remember that. 166 if (CanOutlineWithPrevInstr) 167 HaveLegalRange = true; 168 CanOutlineWithPrevInstr = true; 169 170 // Keep track of the number of legal instructions we insert. 171 NumLegalInBlock++; 172 173 // Get the integer for this instruction or give it the current 174 // LegalInstrNumber. 175 InstrListForMBB.push_back(It); 176 MachineInstr &MI = *It; 177 bool WasInserted; 178 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator 179 ResultIt; 180 std::tie(ResultIt, WasInserted) = 181 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber)); 182 unsigned MINumber = ResultIt->second; 183 184 // There was an insertion. 185 if (WasInserted) 186 LegalInstrNumber++; 187 188 UnsignedVecForMBB.push_back(MINumber); 189 190 // Make sure we don't overflow or use any integers reserved by the DenseMap. 191 if (LegalInstrNumber >= IllegalInstrNumber) 192 report_fatal_error("Instruction mapping overflow!"); 193 194 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() && 195 "Tried to assign DenseMap tombstone or empty key to instruction."); 196 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() && 197 "Tried to assign DenseMap tombstone or empty key to instruction."); 198 199 // Statistics. 200 ++NumLegalInUnsignedVec; 201 return MINumber; 202 } 203 204 /// Maps \p *It to an illegal integer. 205 /// 206 /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p 207 /// IllegalInstrNumber. 208 /// 209 /// \returns The integer that \p *It was mapped to. 210 unsigned mapToIllegalUnsigned( 211 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr, 212 std::vector<unsigned> &UnsignedVecForMBB, 213 std::vector<MachineBasicBlock::iterator> &InstrListForMBB) { 214 // Can't outline an illegal instruction. Set the flag. 215 CanOutlineWithPrevInstr = false; 216 217 // Only add one illegal number per range of legal numbers. 218 if (AddedIllegalLastTime) 219 return IllegalInstrNumber; 220 221 // Remember that we added an illegal number last time. 222 AddedIllegalLastTime = true; 223 unsigned MINumber = IllegalInstrNumber; 224 225 InstrListForMBB.push_back(It); 226 UnsignedVecForMBB.push_back(IllegalInstrNumber); 227 IllegalInstrNumber--; 228 // Statistics. 229 ++NumIllegalInUnsignedVec; 230 231 assert(LegalInstrNumber < IllegalInstrNumber && 232 "Instruction mapping overflow!"); 233 234 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() && 235 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!"); 236 237 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() && 238 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!"); 239 240 return MINumber; 241 } 242 243 /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds 244 /// and appends it to \p UnsignedVec and \p InstrList. 245 /// 246 /// Two instructions are assigned the same integer if they are identical. 247 /// If an instruction is deemed unsafe to outline, then it will be assigned an 248 /// unique integer. The resulting mapping is placed into a suffix tree and 249 /// queried for candidates. 250 /// 251 /// \param MBB The \p MachineBasicBlock to be translated into integers. 252 /// \param TII \p TargetInstrInfo for the function. 253 void convertToUnsignedVec(MachineBasicBlock &MBB, 254 const TargetInstrInfo &TII) { 255 unsigned Flags = 0; 256 257 // Don't even map in this case. 258 if (!TII.isMBBSafeToOutlineFrom(MBB, Flags)) 259 return; 260 261 // Store info for the MBB for later outlining. 262 MBBFlagsMap[&MBB] = Flags; 263 264 MachineBasicBlock::iterator It = MBB.begin(); 265 266 // The number of instructions in this block that will be considered for 267 // outlining. 268 unsigned NumLegalInBlock = 0; 269 270 // True if we have at least two legal instructions which aren't separated 271 // by an illegal instruction. 272 bool HaveLegalRange = false; 273 274 // True if we can perform outlining given the last mapped (non-invisible) 275 // instruction. This lets us know if we have a legal range. 276 bool CanOutlineWithPrevInstr = false; 277 278 // FIXME: Should this all just be handled in the target, rather than using 279 // repeated calls to getOutliningType? 280 std::vector<unsigned> UnsignedVecForMBB; 281 std::vector<MachineBasicBlock::iterator> InstrListForMBB; 282 283 for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; ++It) { 284 // Keep track of where this instruction is in the module. 285 switch (TII.getOutliningType(It, Flags)) { 286 case InstrType::Illegal: 287 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB, 288 InstrListForMBB); 289 break; 290 291 case InstrType::Legal: 292 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange, 293 NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB); 294 break; 295 296 case InstrType::LegalTerminator: 297 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange, 298 NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB); 299 // The instruction also acts as a terminator, so we have to record that 300 // in the string. 301 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB, 302 InstrListForMBB); 303 break; 304 305 case InstrType::Invisible: 306 // Normally this is set by mapTo(Blah)Unsigned, but we just want to 307 // skip this instruction. So, unset the flag here. 308 ++NumInvisible; 309 AddedIllegalLastTime = false; 310 break; 311 } 312 } 313 314 // Are there enough legal instructions in the block for outlining to be 315 // possible? 316 if (HaveLegalRange) { 317 // After we're done every insertion, uniquely terminate this part of the 318 // "string". This makes sure we won't match across basic block or function 319 // boundaries since the "end" is encoded uniquely and thus appears in no 320 // repeated substring. 321 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB, 322 InstrListForMBB); 323 llvm::append_range(InstrList, InstrListForMBB); 324 llvm::append_range(UnsignedVec, UnsignedVecForMBB); 325 } 326 } 327 328 InstructionMapper() { 329 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't 330 // changed. 331 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 && 332 "DenseMapInfo<unsigned>'s empty key isn't -1!"); 333 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 && 334 "DenseMapInfo<unsigned>'s tombstone key isn't -2!"); 335 } 336 }; 337 338 /// An interprocedural pass which finds repeated sequences of 339 /// instructions and replaces them with calls to functions. 340 /// 341 /// Each instruction is mapped to an unsigned integer and placed in a string. 342 /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree 343 /// is then repeatedly queried for repeated sequences of instructions. Each 344 /// non-overlapping repeated sequence is then placed in its own 345 /// \p MachineFunction and each instance is then replaced with a call to that 346 /// function. 347 struct MachineOutliner : public ModulePass { 348 349 static char ID; 350 351 /// Set to true if the outliner should consider functions with 352 /// linkonceodr linkage. 353 bool OutlineFromLinkOnceODRs = false; 354 355 /// The current repeat number of machine outlining. 356 unsigned OutlineRepeatedNum = 0; 357 358 /// Set to true if the outliner should run on all functions in the module 359 /// considered safe for outlining. 360 /// Set to true by default for compatibility with llc's -run-pass option. 361 /// Set when the pass is constructed in TargetPassConfig. 362 bool RunOnAllFunctions = true; 363 364 StringRef getPassName() const override { return "Machine Outliner"; } 365 366 void getAnalysisUsage(AnalysisUsage &AU) const override { 367 AU.addRequired<MachineModuleInfoWrapperPass>(); 368 AU.addPreserved<MachineModuleInfoWrapperPass>(); 369 AU.setPreservesAll(); 370 ModulePass::getAnalysisUsage(AU); 371 } 372 373 MachineOutliner() : ModulePass(ID) { 374 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry()); 375 } 376 377 /// Remark output explaining that not outlining a set of candidates would be 378 /// better than outlining that set. 379 void emitNotOutliningCheaperRemark( 380 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq, 381 OutlinedFunction &OF); 382 383 /// Remark output explaining that a function was outlined. 384 void emitOutlinedFunctionRemark(OutlinedFunction &OF); 385 386 /// Find all repeated substrings that satisfy the outlining cost model by 387 /// constructing a suffix tree. 388 /// 389 /// If a substring appears at least twice, then it must be represented by 390 /// an internal node which appears in at least two suffixes. Each suffix 391 /// is represented by a leaf node. To do this, we visit each internal node 392 /// in the tree, using the leaf children of each internal node. If an 393 /// internal node represents a beneficial substring, then we use each of 394 /// its leaf children to find the locations of its substring. 395 /// 396 /// \param Mapper Contains outlining mapping information. 397 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions 398 /// each type of candidate. 399 void findCandidates(InstructionMapper &Mapper, 400 std::vector<OutlinedFunction> &FunctionList); 401 402 /// Replace the sequences of instructions represented by \p OutlinedFunctions 403 /// with calls to functions. 404 /// 405 /// \param M The module we are outlining from. 406 /// \param FunctionList A list of functions to be inserted into the module. 407 /// \param Mapper Contains the instruction mappings for the module. 408 bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList, 409 InstructionMapper &Mapper, unsigned &OutlinedFunctionNum); 410 411 /// Creates a function for \p OF and inserts it into the module. 412 MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF, 413 InstructionMapper &Mapper, 414 unsigned Name); 415 416 /// Calls 'doOutline()' 1 + OutlinerReruns times. 417 bool runOnModule(Module &M) override; 418 419 /// Construct a suffix tree on the instructions in \p M and outline repeated 420 /// strings from that tree. 421 bool doOutline(Module &M, unsigned &OutlinedFunctionNum); 422 423 /// Return a DISubprogram for OF if one exists, and null otherwise. Helper 424 /// function for remark emission. 425 DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) { 426 for (const Candidate &C : OF.Candidates) 427 if (MachineFunction *MF = C.getMF()) 428 if (DISubprogram *SP = MF->getFunction().getSubprogram()) 429 return SP; 430 return nullptr; 431 } 432 433 /// Populate and \p InstructionMapper with instruction-to-integer mappings. 434 /// These are used to construct a suffix tree. 435 void populateMapper(InstructionMapper &Mapper, Module &M, 436 MachineModuleInfo &MMI); 437 438 /// Initialize information necessary to output a size remark. 439 /// FIXME: This should be handled by the pass manager, not the outliner. 440 /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy 441 /// pass manager. 442 void initSizeRemarkInfo(const Module &M, const MachineModuleInfo &MMI, 443 StringMap<unsigned> &FunctionToInstrCount); 444 445 /// Emit the remark. 446 // FIXME: This should be handled by the pass manager, not the outliner. 447 void 448 emitInstrCountChangedRemark(const Module &M, const MachineModuleInfo &MMI, 449 const StringMap<unsigned> &FunctionToInstrCount); 450 }; 451 } // Anonymous namespace. 452 453 char MachineOutliner::ID = 0; 454 455 namespace llvm { 456 ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) { 457 MachineOutliner *OL = new MachineOutliner(); 458 OL->RunOnAllFunctions = RunOnAllFunctions; 459 return OL; 460 } 461 462 } // namespace llvm 463 464 INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false, 465 false) 466 467 void MachineOutliner::emitNotOutliningCheaperRemark( 468 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq, 469 OutlinedFunction &OF) { 470 // FIXME: Right now, we arbitrarily choose some Candidate from the 471 // OutlinedFunction. This isn't necessarily fixed, nor does it have to be. 472 // We should probably sort these by function name or something to make sure 473 // the remarks are stable. 474 Candidate &C = CandidatesForRepeatedSeq.front(); 475 MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr); 476 MORE.emit([&]() { 477 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper", 478 C.front()->getDebugLoc(), C.getMBB()); 479 R << "Did not outline " << NV("Length", StringLen) << " instructions" 480 << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size()) 481 << " locations." 482 << " Bytes from outlining all occurrences (" 483 << NV("OutliningCost", OF.getOutliningCost()) << ")" 484 << " >= Unoutlined instruction bytes (" 485 << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")" 486 << " (Also found at: "; 487 488 // Tell the user the other places the candidate was found. 489 for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) { 490 R << NV((Twine("OtherStartLoc") + Twine(i)).str(), 491 CandidatesForRepeatedSeq[i].front()->getDebugLoc()); 492 if (i != e - 1) 493 R << ", "; 494 } 495 496 R << ")"; 497 return R; 498 }); 499 } 500 501 void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) { 502 MachineBasicBlock *MBB = &*OF.MF->begin(); 503 MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr); 504 MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction", 505 MBB->findDebugLoc(MBB->begin()), MBB); 506 R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by " 507 << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions " 508 << "from " << NV("NumOccurrences", OF.getOccurrenceCount()) 509 << " locations. " 510 << "(Found at: "; 511 512 // Tell the user the other places the candidate was found. 513 for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) { 514 515 R << NV((Twine("StartLoc") + Twine(i)).str(), 516 OF.Candidates[i].front()->getDebugLoc()); 517 if (i != e - 1) 518 R << ", "; 519 } 520 521 R << ")"; 522 523 MORE.emit(R); 524 } 525 526 void MachineOutliner::findCandidates( 527 InstructionMapper &Mapper, std::vector<OutlinedFunction> &FunctionList) { 528 FunctionList.clear(); 529 SuffixTree ST(Mapper.UnsignedVec); 530 531 // First, find all of the repeated substrings in the tree of minimum length 532 // 2. 533 std::vector<Candidate> CandidatesForRepeatedSeq; 534 for (const SuffixTree::RepeatedSubstring &RS : ST) { 535 CandidatesForRepeatedSeq.clear(); 536 unsigned StringLen = RS.Length; 537 for (const unsigned &StartIdx : RS.StartIndices) { 538 unsigned EndIdx = StartIdx + StringLen - 1; 539 // Trick: Discard some candidates that would be incompatible with the 540 // ones we've already found for this sequence. This will save us some 541 // work in candidate selection. 542 // 543 // If two candidates overlap, then we can't outline them both. This 544 // happens when we have candidates that look like, say 545 // 546 // AA (where each "A" is an instruction). 547 // 548 // We might have some portion of the module that looks like this: 549 // AAAAAA (6 A's) 550 // 551 // In this case, there are 5 different copies of "AA" in this range, but 552 // at most 3 can be outlined. If only outlining 3 of these is going to 553 // be unbeneficial, then we ought to not bother. 554 // 555 // Note that two things DON'T overlap when they look like this: 556 // start1...end1 .... start2...end2 557 // That is, one must either 558 // * End before the other starts 559 // * Start after the other ends 560 if (llvm::all_of(CandidatesForRepeatedSeq, [&StartIdx, 561 &EndIdx](const Candidate &C) { 562 return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx()); 563 })) { 564 // It doesn't overlap with anything, so we can outline it. 565 // Each sequence is over [StartIt, EndIt]. 566 // Save the candidate and its location. 567 568 MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx]; 569 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx]; 570 MachineBasicBlock *MBB = StartIt->getParent(); 571 572 CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt, 573 EndIt, MBB, FunctionList.size(), 574 Mapper.MBBFlagsMap[MBB]); 575 } 576 } 577 578 // We've found something we might want to outline. 579 // Create an OutlinedFunction to store it and check if it'd be beneficial 580 // to outline. 581 if (CandidatesForRepeatedSeq.size() < 2) 582 continue; 583 584 // Arbitrarily choose a TII from the first candidate. 585 // FIXME: Should getOutliningCandidateInfo move to TargetMachine? 586 const TargetInstrInfo *TII = 587 CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo(); 588 589 OutlinedFunction OF = 590 TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq); 591 592 // If we deleted too many candidates, then there's nothing worth outlining. 593 // FIXME: This should take target-specified instruction sizes into account. 594 if (OF.Candidates.size() < 2) 595 continue; 596 597 // Is it better to outline this candidate than not? 598 if (OF.getBenefit() < 1) { 599 emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF); 600 continue; 601 } 602 603 FunctionList.push_back(OF); 604 } 605 } 606 607 MachineFunction *MachineOutliner::createOutlinedFunction( 608 Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) { 609 610 // Create the function name. This should be unique. 611 // FIXME: We should have a better naming scheme. This should be stable, 612 // regardless of changes to the outliner's cost model/traversal order. 613 std::string FunctionName = "OUTLINED_FUNCTION_"; 614 if (OutlineRepeatedNum > 0) 615 FunctionName += std::to_string(OutlineRepeatedNum + 1) + "_"; 616 FunctionName += std::to_string(Name); 617 618 // Create the function using an IR-level function. 619 LLVMContext &C = M.getContext(); 620 Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false), 621 Function::ExternalLinkage, FunctionName, M); 622 623 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping 624 // which gives us better results when we outline from linkonceodr functions. 625 F->setLinkage(GlobalValue::InternalLinkage); 626 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 627 628 // Set optsize/minsize, so we don't insert padding between outlined 629 // functions. 630 F->addFnAttr(Attribute::OptimizeForSize); 631 F->addFnAttr(Attribute::MinSize); 632 633 Candidate &FirstCand = OF.Candidates.front(); 634 const TargetInstrInfo &TII = 635 *FirstCand.getMF()->getSubtarget().getInstrInfo(); 636 637 TII.mergeOutliningCandidateAttributes(*F, OF.Candidates); 638 639 // Set uwtable, so we generate eh_frame. 640 UWTableKind UW = std::accumulate( 641 OF.Candidates.cbegin(), OF.Candidates.cend(), UWTableKind::None, 642 [](UWTableKind K, const outliner::Candidate &C) { 643 return std::max(K, C.getMF()->getFunction().getUWTableKind()); 644 }); 645 if (UW != UWTableKind::None) 646 F->setUWTableKind(UW); 647 648 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F); 649 IRBuilder<> Builder(EntryBB); 650 Builder.CreateRetVoid(); 651 652 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI(); 653 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F); 654 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock(); 655 656 // Insert the new function into the module. 657 MF.insert(MF.begin(), &MBB); 658 659 MachineFunction *OriginalMF = FirstCand.front()->getMF(); 660 const std::vector<MCCFIInstruction> &Instrs = 661 OriginalMF->getFrameInstructions(); 662 for (auto I = FirstCand.front(), E = std::next(FirstCand.back()); I != E; 663 ++I) { 664 if (I->isDebugInstr()) 665 continue; 666 MachineInstr *NewMI = MF.CloneMachineInstr(&*I); 667 if (I->isCFIInstruction()) { 668 unsigned CFIIndex = NewMI->getOperand(0).getCFIIndex(); 669 MCCFIInstruction CFI = Instrs[CFIIndex]; 670 (void)MF.addFrameInst(CFI); 671 } 672 NewMI->dropMemRefs(MF); 673 674 // Don't keep debug information for outlined instructions. 675 NewMI->setDebugLoc(DebugLoc()); 676 MBB.insert(MBB.end(), NewMI); 677 } 678 679 // Set normal properties for a late MachineFunction. 680 MF.getProperties().reset(MachineFunctionProperties::Property::IsSSA); 681 MF.getProperties().set(MachineFunctionProperties::Property::NoPHIs); 682 MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs); 683 MF.getProperties().set(MachineFunctionProperties::Property::TracksLiveness); 684 MF.getRegInfo().freezeReservedRegs(MF); 685 686 // Compute live-in set for outlined fn 687 const MachineRegisterInfo &MRI = MF.getRegInfo(); 688 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo(); 689 LivePhysRegs LiveIns(TRI); 690 for (auto &Cand : OF.Candidates) { 691 // Figure out live-ins at the first instruction. 692 MachineBasicBlock &OutlineBB = *Cand.front()->getParent(); 693 LivePhysRegs CandLiveIns(TRI); 694 CandLiveIns.addLiveOuts(OutlineBB); 695 for (const MachineInstr &MI : 696 reverse(make_range(Cand.front(), OutlineBB.end()))) 697 CandLiveIns.stepBackward(MI); 698 699 // The live-in set for the outlined function is the union of the live-ins 700 // from all the outlining points. 701 for (MCPhysReg Reg : CandLiveIns) 702 LiveIns.addReg(Reg); 703 } 704 addLiveIns(MBB, LiveIns); 705 706 TII.buildOutlinedFrame(MBB, MF, OF); 707 708 // If there's a DISubprogram associated with this outlined function, then 709 // emit debug info for the outlined function. 710 if (DISubprogram *SP = getSubprogramOrNull(OF)) { 711 // We have a DISubprogram. Get its DICompileUnit. 712 DICompileUnit *CU = SP->getUnit(); 713 DIBuilder DB(M, true, CU); 714 DIFile *Unit = SP->getFile(); 715 Mangler Mg; 716 // Get the mangled name of the function for the linkage name. 717 std::string Dummy; 718 llvm::raw_string_ostream MangledNameStream(Dummy); 719 Mg.getNameWithPrefix(MangledNameStream, F, false); 720 721 DISubprogram *OutlinedSP = DB.createFunction( 722 Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()), 723 Unit /* File */, 724 0 /* Line 0 is reserved for compiler-generated code. */, 725 DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */ 726 0, /* Line 0 is reserved for compiler-generated code. */ 727 DINode::DIFlags::FlagArtificial /* Compiler-generated code. */, 728 /* Outlined code is optimized code by definition. */ 729 DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized); 730 731 // Don't add any new variables to the subprogram. 732 DB.finalizeSubprogram(OutlinedSP); 733 734 // Attach subprogram to the function. 735 F->setSubprogram(OutlinedSP); 736 // We're done with the DIBuilder. 737 DB.finalize(); 738 } 739 740 return &MF; 741 } 742 743 bool MachineOutliner::outline(Module &M, 744 std::vector<OutlinedFunction> &FunctionList, 745 InstructionMapper &Mapper, 746 unsigned &OutlinedFunctionNum) { 747 748 bool OutlinedSomething = false; 749 750 // Sort by benefit. The most beneficial functions should be outlined first. 751 llvm::stable_sort(FunctionList, [](const OutlinedFunction &LHS, 752 const OutlinedFunction &RHS) { 753 return LHS.getBenefit() > RHS.getBenefit(); 754 }); 755 756 // Walk over each function, outlining them as we go along. Functions are 757 // outlined greedily, based off the sort above. 758 for (OutlinedFunction &OF : FunctionList) { 759 // If we outlined something that overlapped with a candidate in a previous 760 // step, then we can't outline from it. 761 erase_if(OF.Candidates, [&Mapper](Candidate &C) { 762 return std::any_of( 763 Mapper.UnsignedVec.begin() + C.getStartIdx(), 764 Mapper.UnsignedVec.begin() + C.getEndIdx() + 1, 765 [](unsigned I) { return (I == static_cast<unsigned>(-1)); }); 766 }); 767 768 // If we made it unbeneficial to outline this function, skip it. 769 if (OF.getBenefit() < 1) 770 continue; 771 772 // It's beneficial. Create the function and outline its sequence's 773 // occurrences. 774 OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum); 775 emitOutlinedFunctionRemark(OF); 776 FunctionsCreated++; 777 OutlinedFunctionNum++; // Created a function, move to the next name. 778 MachineFunction *MF = OF.MF; 779 const TargetSubtargetInfo &STI = MF->getSubtarget(); 780 const TargetInstrInfo &TII = *STI.getInstrInfo(); 781 782 // Replace occurrences of the sequence with calls to the new function. 783 for (Candidate &C : OF.Candidates) { 784 MachineBasicBlock &MBB = *C.getMBB(); 785 MachineBasicBlock::iterator StartIt = C.front(); 786 MachineBasicBlock::iterator EndIt = C.back(); 787 788 // Insert the call. 789 auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C); 790 791 // If the caller tracks liveness, then we need to make sure that 792 // anything we outline doesn't break liveness assumptions. The outlined 793 // functions themselves currently don't track liveness, but we should 794 // make sure that the ranges we yank things out of aren't wrong. 795 if (MBB.getParent()->getProperties().hasProperty( 796 MachineFunctionProperties::Property::TracksLiveness)) { 797 // The following code is to add implicit def operands to the call 798 // instruction. It also updates call site information for moved 799 // code. 800 SmallSet<Register, 2> UseRegs, DefRegs; 801 // Copy over the defs in the outlined range. 802 // First inst in outlined range <-- Anything that's defined in this 803 // ... .. range has to be added as an 804 // implicit Last inst in outlined range <-- def to the call 805 // instruction. Also remove call site information for outlined block 806 // of code. The exposed uses need to be copied in the outlined range. 807 for (MachineBasicBlock::reverse_iterator 808 Iter = EndIt.getReverse(), 809 Last = std::next(CallInst.getReverse()); 810 Iter != Last; Iter++) { 811 MachineInstr *MI = &*Iter; 812 SmallSet<Register, 2> InstrUseRegs; 813 for (MachineOperand &MOP : MI->operands()) { 814 // Skip over anything that isn't a register. 815 if (!MOP.isReg()) 816 continue; 817 818 if (MOP.isDef()) { 819 // Introduce DefRegs set to skip the redundant register. 820 DefRegs.insert(MOP.getReg()); 821 if (UseRegs.count(MOP.getReg()) && 822 !InstrUseRegs.count(MOP.getReg())) 823 // Since the regiester is modeled as defined, 824 // it is not necessary to be put in use register set. 825 UseRegs.erase(MOP.getReg()); 826 } else if (!MOP.isUndef()) { 827 // Any register which is not undefined should 828 // be put in the use register set. 829 UseRegs.insert(MOP.getReg()); 830 InstrUseRegs.insert(MOP.getReg()); 831 } 832 } 833 if (MI->isCandidateForCallSiteEntry()) 834 MI->getMF()->eraseCallSiteInfo(MI); 835 } 836 837 for (const Register &I : DefRegs) 838 // If it's a def, add it to the call instruction. 839 CallInst->addOperand( 840 MachineOperand::CreateReg(I, true, /* isDef = true */ 841 true /* isImp = true */)); 842 843 for (const Register &I : UseRegs) 844 // If it's a exposed use, add it to the call instruction. 845 CallInst->addOperand( 846 MachineOperand::CreateReg(I, false, /* isDef = false */ 847 true /* isImp = true */)); 848 } 849 850 // Erase from the point after where the call was inserted up to, and 851 // including, the final instruction in the sequence. 852 // Erase needs one past the end, so we need std::next there too. 853 MBB.erase(std::next(StartIt), std::next(EndIt)); 854 855 // Keep track of what we removed by marking them all as -1. 856 std::for_each(Mapper.UnsignedVec.begin() + C.getStartIdx(), 857 Mapper.UnsignedVec.begin() + C.getEndIdx() + 1, 858 [](unsigned &I) { I = static_cast<unsigned>(-1); }); 859 OutlinedSomething = true; 860 861 // Statistics. 862 NumOutlined++; 863 } 864 } 865 866 LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";); 867 return OutlinedSomething; 868 } 869 870 void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M, 871 MachineModuleInfo &MMI) { 872 // Build instruction mappings for each function in the module. Start by 873 // iterating over each Function in M. 874 for (Function &F : M) { 875 876 // If there's nothing in F, then there's no reason to try and outline from 877 // it. 878 if (F.empty()) 879 continue; 880 881 // There's something in F. Check if it has a MachineFunction associated with 882 // it. 883 MachineFunction *MF = MMI.getMachineFunction(F); 884 885 // If it doesn't, then there's nothing to outline from. Move to the next 886 // Function. 887 if (!MF) 888 continue; 889 890 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 891 892 if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF)) 893 continue; 894 895 // We have a MachineFunction. Ask the target if it's suitable for outlining. 896 // If it isn't, then move on to the next Function in the module. 897 if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs)) 898 continue; 899 900 // We have a function suitable for outlining. Iterate over every 901 // MachineBasicBlock in MF and try to map its instructions to a list of 902 // unsigned integers. 903 for (MachineBasicBlock &MBB : *MF) { 904 // If there isn't anything in MBB, then there's no point in outlining from 905 // it. 906 // If there are fewer than 2 instructions in the MBB, then it can't ever 907 // contain something worth outlining. 908 // FIXME: This should be based off of the maximum size in B of an outlined 909 // call versus the size in B of the MBB. 910 if (MBB.empty() || MBB.size() < 2) 911 continue; 912 913 // Check if MBB could be the target of an indirect branch. If it is, then 914 // we don't want to outline from it. 915 if (MBB.hasAddressTaken()) 916 continue; 917 918 // MBB is suitable for outlining. Map it to a list of unsigneds. 919 Mapper.convertToUnsignedVec(MBB, *TII); 920 } 921 922 // Statistics. 923 UnsignedVecSize = Mapper.UnsignedVec.size(); 924 } 925 } 926 927 void MachineOutliner::initSizeRemarkInfo( 928 const Module &M, const MachineModuleInfo &MMI, 929 StringMap<unsigned> &FunctionToInstrCount) { 930 // Collect instruction counts for every function. We'll use this to emit 931 // per-function size remarks later. 932 for (const Function &F : M) { 933 MachineFunction *MF = MMI.getMachineFunction(F); 934 935 // We only care about MI counts here. If there's no MachineFunction at this 936 // point, then there won't be after the outliner runs, so let's move on. 937 if (!MF) 938 continue; 939 FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount(); 940 } 941 } 942 943 void MachineOutliner::emitInstrCountChangedRemark( 944 const Module &M, const MachineModuleInfo &MMI, 945 const StringMap<unsigned> &FunctionToInstrCount) { 946 // Iterate over each function in the module and emit remarks. 947 // Note that we won't miss anything by doing this, because the outliner never 948 // deletes functions. 949 for (const Function &F : M) { 950 MachineFunction *MF = MMI.getMachineFunction(F); 951 952 // The outliner never deletes functions. If we don't have a MF here, then we 953 // didn't have one prior to outlining either. 954 if (!MF) 955 continue; 956 957 std::string Fname = std::string(F.getName()); 958 unsigned FnCountAfter = MF->getInstructionCount(); 959 unsigned FnCountBefore = 0; 960 961 // Check if the function was recorded before. 962 auto It = FunctionToInstrCount.find(Fname); 963 964 // Did we have a previously-recorded size? If yes, then set FnCountBefore 965 // to that. 966 if (It != FunctionToInstrCount.end()) 967 FnCountBefore = It->second; 968 969 // Compute the delta and emit a remark if there was a change. 970 int64_t FnDelta = static_cast<int64_t>(FnCountAfter) - 971 static_cast<int64_t>(FnCountBefore); 972 if (FnDelta == 0) 973 continue; 974 975 MachineOptimizationRemarkEmitter MORE(*MF, nullptr); 976 MORE.emit([&]() { 977 MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange", 978 DiagnosticLocation(), &MF->front()); 979 R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner") 980 << ": Function: " 981 << DiagnosticInfoOptimizationBase::Argument("Function", F.getName()) 982 << ": MI instruction count changed from " 983 << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore", 984 FnCountBefore) 985 << " to " 986 << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter", 987 FnCountAfter) 988 << "; Delta: " 989 << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta); 990 return R; 991 }); 992 } 993 } 994 995 bool MachineOutliner::runOnModule(Module &M) { 996 // Check if there's anything in the module. If it's empty, then there's 997 // nothing to outline. 998 if (M.empty()) 999 return false; 1000 1001 // Number to append to the current outlined function. 1002 unsigned OutlinedFunctionNum = 0; 1003 1004 OutlineRepeatedNum = 0; 1005 if (!doOutline(M, OutlinedFunctionNum)) 1006 return false; 1007 1008 for (unsigned I = 0; I < OutlinerReruns; ++I) { 1009 OutlinedFunctionNum = 0; 1010 OutlineRepeatedNum++; 1011 if (!doOutline(M, OutlinedFunctionNum)) { 1012 LLVM_DEBUG({ 1013 dbgs() << "Did not outline on iteration " << I + 2 << " out of " 1014 << OutlinerReruns + 1 << "\n"; 1015 }); 1016 break; 1017 } 1018 } 1019 1020 return true; 1021 } 1022 1023 bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) { 1024 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI(); 1025 1026 // If the user passed -enable-machine-outliner=always or 1027 // -enable-machine-outliner, the pass will run on all functions in the module. 1028 // Otherwise, if the target supports default outlining, it will run on all 1029 // functions deemed by the target to be worth outlining from by default. Tell 1030 // the user how the outliner is running. 1031 LLVM_DEBUG({ 1032 dbgs() << "Machine Outliner: Running on "; 1033 if (RunOnAllFunctions) 1034 dbgs() << "all functions"; 1035 else 1036 dbgs() << "target-default functions"; 1037 dbgs() << "\n"; 1038 }); 1039 1040 // If the user specifies that they want to outline from linkonceodrs, set 1041 // it here. 1042 OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining; 1043 InstructionMapper Mapper; 1044 1045 // Prepare instruction mappings for the suffix tree. 1046 populateMapper(Mapper, M, MMI); 1047 std::vector<OutlinedFunction> FunctionList; 1048 1049 // Find all of the outlining candidates. 1050 findCandidates(Mapper, FunctionList); 1051 1052 // If we've requested size remarks, then collect the MI counts of every 1053 // function before outlining, and the MI counts after outlining. 1054 // FIXME: This shouldn't be in the outliner at all; it should ultimately be 1055 // the pass manager's responsibility. 1056 // This could pretty easily be placed in outline instead, but because we 1057 // really ultimately *don't* want this here, it's done like this for now 1058 // instead. 1059 1060 // Check if we want size remarks. 1061 bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark(); 1062 StringMap<unsigned> FunctionToInstrCount; 1063 if (ShouldEmitSizeRemarks) 1064 initSizeRemarkInfo(M, MMI, FunctionToInstrCount); 1065 1066 // Outline each of the candidates and return true if something was outlined. 1067 bool OutlinedSomething = 1068 outline(M, FunctionList, Mapper, OutlinedFunctionNum); 1069 1070 // If we outlined something, we definitely changed the MI count of the 1071 // module. If we've asked for size remarks, then output them. 1072 // FIXME: This should be in the pass manager. 1073 if (ShouldEmitSizeRemarks && OutlinedSomething) 1074 emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount); 1075 1076 LLVM_DEBUG({ 1077 if (!OutlinedSomething) 1078 dbgs() << "Stopped outlining at iteration " << OutlineRepeatedNum 1079 << " because no changes were found.\n"; 1080 }); 1081 1082 return OutlinedSomething; 1083 } 1084