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