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