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