LLVM 24.0.0git
MachineOutliner.cpp
Go to the documentation of this file.
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//===----------------------------------------------------------------------===//
58#include "CodeGenOptions.h"
59#include "llvm/ADT/BitVector.h"
60#include "llvm/ADT/DenseMap.h"
61#include "llvm/ADT/SmallSet.h"
62#include "llvm/ADT/Statistic.h"
63#include "llvm/ADT/Twine.h"
74#include "llvm/CodeGen/Passes.h"
78#include "llvm/IR/DIBuilder.h"
79#include "llvm/IR/IRBuilder.h"
80#include "llvm/IR/Mangler.h"
81#include "llvm/IR/Module.h"
83#include "llvm/Support/Debug.h"
88#include <tuple>
89#include <vector>
90
91#define DEBUG_TYPE "machine-outliner"
92
93using namespace llvm;
94using namespace ore;
95using namespace outliner;
96
97// Statistics for outlined functions.
98STATISTIC(NumOutlined, "Number of candidates outlined");
99STATISTIC(FunctionsCreated, "Number of functions created");
100
101// Statistics for instruction mapping.
102STATISTIC(NumLegalInUnsignedVec, "Outlinable instructions mapped");
103STATISTIC(NumIllegalInUnsignedVec,
104 "Unoutlinable instructions mapped + number of sentinel values");
105STATISTIC(NumSentinels, "Sentinel values inserted during mapping");
106STATISTIC(NumInvisible,
107 "Non-debug invisible instructions skipped during mapping");
108STATISTIC(UnsignedVecSize,
109 "Total number of instructions mapped and saved to mapping vector");
110STATISTIC(StableHashAttempts,
111 "Count of hashing attempts made for outlined functions");
112STATISTIC(StableHashDropped,
113 "Count of unsuccessful hashing attempts for outlined functions");
114STATISTIC(UnprofitableCandidateGroupsPublished,
115 "Number of locally unprofitable candidate groups published");
116STATISTIC(UnprofitableCandidateSitesPublished,
117 "Number of locally unprofitable candidate sites published");
118STATISTIC(NumRemovedLOHs, "Total number of Linker Optimization Hints removed");
119STATISTIC(NumPGOBlockedOutlined,
120 "Number of times outlining was blocked by PGO");
121STATISTIC(NumPGOAllowedCold,
122 "Number of times outlining was allowed from cold functions");
123STATISTIC(NumPGOConservativeBlockedOutlined,
124 "Number of times outlining was blocked conservatively when profile "
125 "counts were missing");
126STATISTIC(NumPGOOptimisticOutlined,
127 "Number of times outlining was allowed optimistically when profile "
128 "counts were missing");
129
130namespace {
131
132/// Maps \p MachineInstrs to unsigned integers and stores the mappings.
133struct InstructionMapper {
134 const MachineModuleInfo &MMI;
135
136 /// The next available integer to assign to a \p MachineInstr that
137 /// cannot be outlined.
138 ///
139 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
140 unsigned IllegalInstrNumber = -3;
141
142 /// The next available integer to assign to a \p MachineInstr that can
143 /// be outlined.
144 unsigned LegalInstrNumber = 0;
145
146 /// Correspondence from \p MachineInstrs to unsigned integers.
148 InstructionIntegerMap;
149
150 /// Correspondence between \p MachineBasicBlocks and target-defined flags.
152
153 /// The vector of unsigned integers that the module is mapped to.
154 SmallVector<unsigned> UnsignedVec;
155
156 /// Stores the location of the instruction associated with the integer
157 /// at index i in \p UnsignedVec for each index i.
159
160 // Set if we added an illegal number in the previous step.
161 // Since each illegal number is unique, we only need one of them between
162 // each range of legal numbers. This lets us make sure we don't add more
163 // than one illegal number per range.
164 bool AddedIllegalLastTime = false;
165
166 /// Maps \p *It to a legal integer.
167 ///
168 /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
169 /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
170 ///
171 /// \returns The integer that \p *It was mapped to.
172 unsigned mapToLegalUnsigned(
173 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
174 bool &HaveLegalRange, unsigned &NumLegalInBlock,
175 SmallVector<unsigned> &UnsignedVecForMBB,
177 // We added something legal, so we should unset the AddedLegalLastTime
178 // flag.
179 AddedIllegalLastTime = false;
180
181 // If we have at least two adjacent legal instructions (which may have
182 // invisible instructions in between), remember that.
183 if (CanOutlineWithPrevInstr)
184 HaveLegalRange = true;
185 CanOutlineWithPrevInstr = true;
186
187 // Keep track of the number of legal instructions we insert.
188 NumLegalInBlock++;
189
190 // Get the integer for this instruction or give it the current
191 // LegalInstrNumber.
192 InstrListForMBB.push_back(It);
193 MachineInstr &MI = *It;
194 bool WasInserted;
196 ResultIt;
197 std::tie(ResultIt, WasInserted) =
198 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
199 unsigned MINumber = ResultIt->second;
200
201 // There was an insertion.
202 if (WasInserted)
203 LegalInstrNumber++;
204
205 UnsignedVecForMBB.push_back(MINumber);
206
207 // Make sure we don't overflow or use any integers reserved by the DenseMap.
208 if (LegalInstrNumber >= IllegalInstrNumber)
209 report_fatal_error("Instruction mapping overflow!");
210
211 // Statistics.
212 ++NumLegalInUnsignedVec;
213 return MINumber;
214 }
215
216 /// Maps \p *It to an illegal integer.
217 ///
218 /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
219 /// IllegalInstrNumber.
220 ///
221 /// \returns The integer that \p *It was mapped to.
222 unsigned mapToIllegalUnsigned(
223 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
224 SmallVector<unsigned> &UnsignedVecForMBB,
226 // Can't outline an illegal instruction. Set the flag.
227 CanOutlineWithPrevInstr = false;
228
229 // Only add one illegal number per range of legal numbers.
230 if (AddedIllegalLastTime)
231 return IllegalInstrNumber;
232
233 // Remember that we added an illegal number last time.
234 AddedIllegalLastTime = true;
235 unsigned MINumber = IllegalInstrNumber;
236
237 InstrListForMBB.push_back(It);
238 UnsignedVecForMBB.push_back(IllegalInstrNumber);
239 IllegalInstrNumber--;
240 // Statistics.
241 ++NumIllegalInUnsignedVec;
242
243 assert(LegalInstrNumber < IllegalInstrNumber &&
244 "Instruction mapping overflow!");
245
246 return MINumber;
247 }
248
249 /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
250 /// and appends it to \p UnsignedVec and \p InstrList.
251 ///
252 /// Two instructions are assigned the same integer if they are identical.
253 /// If an instruction is deemed unsafe to outline, then it will be assigned an
254 /// unique integer. The resulting mapping is placed into a suffix tree and
255 /// queried for candidates.
256 ///
257 /// \param MBB The \p MachineBasicBlock to be translated into integers.
258 /// \param TII \p TargetInstrInfo for the function.
259 void convertToUnsignedVec(MachineBasicBlock &MBB,
260 const TargetInstrInfo &TII) {
261 LLVM_DEBUG(dbgs() << "*** Converting MBB '" << MBB.getName()
262 << "' to unsigned vector ***\n");
263 unsigned Flags = 0;
264
265 // Don't even map in this case.
266 if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
267 return;
268
269 auto OutlinableRanges = TII.getOutlinableRanges(MBB, Flags);
270 LLVM_DEBUG(dbgs() << MBB.getName() << ": " << OutlinableRanges.size()
271 << " outlinable range(s)\n");
272 if (OutlinableRanges.empty())
273 return;
274
275 // Store info for the MBB for later outlining.
276 MBBFlagsMap[&MBB] = Flags;
277
279
280 // The number of instructions in this block that will be considered for
281 // outlining.
282 unsigned NumLegalInBlock = 0;
283
284 // True if we have at least two legal instructions which aren't separated
285 // by an illegal instruction.
286 bool HaveLegalRange = false;
287
288 // True if we can perform outlining given the last mapped (non-invisible)
289 // instruction. This lets us know if we have a legal range.
290 bool CanOutlineWithPrevInstr = false;
291
292 // FIXME: Should this all just be handled in the target, rather than using
293 // repeated calls to getOutliningType?
294 SmallVector<unsigned> UnsignedVecForMBB;
296
297 LLVM_DEBUG(dbgs() << "*** Mapping outlinable ranges ***\n");
298 for (auto &OutlinableRange : OutlinableRanges) {
299 auto OutlinableRangeBegin = OutlinableRange.first;
300 auto OutlinableRangeEnd = OutlinableRange.second;
301#ifndef NDEBUG
303 dbgs() << "Mapping "
304 << std::distance(OutlinableRangeBegin, OutlinableRangeEnd)
305 << " instruction range\n");
306 // Everything outside of an outlinable range is illegal.
307 unsigned NumSkippedInRange = 0;
308#endif
309 for (; It != OutlinableRangeBegin; ++It) {
310 if (It->isDebugInstr())
311 continue;
312#ifndef NDEBUG
313 ++NumSkippedInRange;
314#endif
315 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
316 InstrListForMBB);
317 }
318#ifndef NDEBUG
319 LLVM_DEBUG(dbgs() << "Skipped " << NumSkippedInRange
320 << " instructions outside outlinable range\n");
321#endif
322 assert(It != MBB.end() && "Should still have instructions?");
323 // `It` is now positioned at the beginning of a range of instructions
324 // which may be outlinable. Check if each instruction is known to be safe.
325 for (; It != OutlinableRangeEnd; ++It) {
326 if (It->isDebugInstr())
327 continue;
328 // Keep track of where this instruction is in the module.
329 switch (TII.getOutliningType(MMI, It, Flags)) {
330 case InstrType::Illegal:
331 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
332 InstrListForMBB);
333 break;
334
335 case InstrType::Legal:
336 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
337 NumLegalInBlock, UnsignedVecForMBB,
338 InstrListForMBB);
339 break;
340
341 case InstrType::LegalTerminator:
342 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
343 NumLegalInBlock, UnsignedVecForMBB,
344 InstrListForMBB);
345 // The instruction also acts as a terminator, so we have to record
346 // that in the string.
347 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
348 InstrListForMBB);
349 break;
350
351 case InstrType::Invisible:
352 // Normally this is set by mapTo(Blah)Unsigned, but we just want to
353 // skip this instruction. So, unset the flag here.
354 ++NumInvisible;
355 AddedIllegalLastTime = false;
356 break;
357 }
358 }
359 }
360
361 LLVM_DEBUG(dbgs() << "HaveLegalRange = " << HaveLegalRange << "\n");
362
363 // Are there enough legal instructions in the block for outlining to be
364 // possible?
365 if (HaveLegalRange) {
366 // After we're done every insertion, uniquely terminate this part of the
367 // "string". This makes sure we won't match across basic block or function
368 // boundaries since the "end" is encoded uniquely and thus appears in no
369 // repeated substring.
370 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
371 InstrListForMBB);
372 ++NumSentinels;
373 append_range(InstrList, InstrListForMBB);
374 append_range(UnsignedVec, UnsignedVecForMBB);
375 }
376 }
377
378 InstructionMapper(const MachineModuleInfo &MMI_) : MMI(MMI_) {}
379};
380
381/// An interprocedural pass which finds repeated sequences of
382/// instructions and replaces them with calls to functions.
383///
384/// Each instruction is mapped to an unsigned integer and placed in a string.
385/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
386/// is then repeatedly queried for repeated sequences of instructions. Each
387/// non-overlapping repeated sequence is then placed in its own
388/// \p MachineFunction and each instance is then replaced with a call to that
389/// function.
390struct MachineOutliner : public ModulePass {
391
392 static char ID;
393
394 const CodeGenOptions *Opts = nullptr;
395 MachineModuleInfo *MMI = nullptr;
396 const TargetMachine *TM = nullptr;
397
398 /// Set to true if the outliner should consider functions with
399 /// linkonceodr linkage.
400 bool OutlineFromLinkOnceODRs = false;
401
402 /// The current repeat number of machine outlining.
403 unsigned OutlineRepeatedNum = 0;
404
405 /// The mode for whether to run the outliner
406 /// Set to always-outline by default for compatibility with llc's -run-pass
407 /// option.
408 RunOutliner RunOutlinerMode = RunOutliner::AlwaysOutline;
409
410 /// This is a compact representation of hash sequences of outlined functions.
411 /// It is used when OutlinerMode = CGDataMode::Write.
412 /// The resulting hash tree will be emitted into __llvm_outlined section
413 /// which will be dead-stripped not going to the final binary.
414 /// A post-process using llvm-cgdata, lld, or ThinLTO can merge them into
415 /// a global oulined hash tree for the subsequent codegen.
416 std::unique_ptr<OutlinedHashTree> LocalHashTree;
417
418 /// The mode of the outliner.
419 /// When is's CGDataMode::None, candidates are populated with the suffix tree
420 /// within a module and outlined.
421 /// When it's CGDataMode::Write, in addition to CGDataMode::None, the hash
422 /// sequences of outlined functions are published into LocalHashTree.
423 /// When it's CGDataMode::Read, candidates are populated with the global
424 /// outlined hash tree that has been built by the previous codegen.
425 CGDataMode OutlinerMode = CGDataMode::None;
426
427 /// Distinct locally unprofitable sequences discovered across all iterations.
428 /// Keep hashes rather than candidates, whose instruction iterators can be
429 /// invalidated by outlining. Their surviving sites are recounted at the end.
430 SmallVector<SmallVector<stable_hash>> UnprofitableCandidates;
431 // Terminals store one-based indices into UnprofitableCandidates.
432 OutlinedHashTree UnprofitableCandidateHashTree;
433
434 StringRef getPassName() const override { return "Machine Outliner"; }
435
436 void getAnalysisUsage(AnalysisUsage &AU) const override {
437 AU.addRequired<MachineModuleInfoWrapperPass>();
438 AU.addRequired<TargetPassConfig>();
439 AU.addPreserved<MachineModuleInfoWrapperPass>();
440 AU.addUsedIfAvailable<ImmutableModuleSummaryIndexWrapperPass>();
441 if (RunOutlinerMode == RunOutliner::OptimisticPGO ||
442 RunOutlinerMode == RunOutliner::ConservativePGO) {
443 AU.addRequired<BlockFrequencyInfoWrapperPass>();
444 AU.addRequired<ProfileSummaryInfoWrapperPass>();
445 }
446 AU.setPreservesAll();
447 ModulePass::getAnalysisUsage(AU);
448 }
449
450 MachineOutliner() : ModulePass(ID) {}
451
452 /// Remark output explaining that not outlining a set of candidates would be
453 /// better than outlining that set.
454 void emitNotOutliningCheaperRemark(
455 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
456 OutlinedFunction &OF);
457
458 /// Run the outlining cost model for a group of candidates and append the
459 /// resulting outlined function if it is profitable.
460 void createOutlinedFunctionIfBeneficial(
461 std::vector<Candidate> &Candidates, unsigned StringLen,
462 unsigned MinRepeats, const TargetInstrInfo &TII,
463 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList);
464
465 /// Remark output explaining that a function was outlined.
466 void emitOutlinedFunctionRemark(OutlinedFunction &OF);
467
468 /// Find all repeated substrings that satisfy the outlining cost model by
469 /// constructing a suffix tree.
470 ///
471 /// If a substring appears at least twice, then it must be represented by
472 /// an internal node which appears in at least two suffixes. Each suffix
473 /// is represented by a leaf node. To do this, we visit each internal node
474 /// in the tree, using the leaf children of each internal node. If an
475 /// internal node represents a beneficial substring, then we use each of
476 /// its leaf children to find the locations of its substring.
477 ///
478 /// \param Mapper Contains outlining mapping information.
479 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
480 /// each type of candidate.
481 void
482 findCandidates(InstructionMapper &Mapper,
483 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList);
484
485 /// Find all repeated substrings that match in the global outlined hash
486 /// tree built from the previous codegen.
487 ///
488 /// \param Mapper Contains outlining mapping information.
489 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
490 /// each type of candidate.
491 void findGlobalCandidates(
492 InstructionMapper &Mapper,
493 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList);
494
495 /// Replace the sequences of instructions represented by \p OutlinedFunctions
496 /// with calls to functions.
497 ///
498 /// \param M The module we are outlining from.
499 /// \param FunctionList A list of functions to be inserted into the module.
500 /// \param Mapper Contains the instruction mappings for the module.
501 /// \param[out] OutlinedFunctionNum The outlined function number.
502 bool outline(Module &M,
503 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList,
504 InstructionMapper &Mapper, unsigned &OutlinedFunctionNum);
505
506 /// Creates a function for \p OF and inserts it into the module.
507 MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
508 InstructionMapper &Mapper,
509 unsigned Name);
510
511 /// Compute and publish the stable hash sequence of instructions in the
512 /// outlined function, \p MF. The parameter \p CandSize represents the number
513 /// of candidates that have identical instruction sequences to \p MF.
514 void computeAndPublishHashSequence(MachineFunction &MF, unsigned CandSize);
515
516 /// Remember short sequences rejected by any iteration's profitability check.
517 void recordUnprofitableCandidate(OutlinedFunction &OF);
518
519 /// Recount surviving sites in the final mapper and publish their counts.
520 bool publishUnprofitableCandidates(InstructionMapper &Mapper);
521
522 /// Initialize the outliner mode.
523 void initializeOutlinerMode(const Module &M);
524
525 /// Emit the outlined hash tree into __llvm_outline section.
526 void emitOutlinedHashTree(Module &M);
527
528 /// Calls 'doOutline()' 1 + OutlinerReruns times.
529 bool runOnModule(Module &M) override;
530
531 /// Construct a suffix tree on the instructions in \p M and outline repeated
532 /// strings from that tree.
533 /// \p Mapper is reset with this iteration's instruction mapping.
534 bool doOutline(Module &M, std::optional<InstructionMapper> &Mapper,
535 unsigned &OutlinedFunctionNum);
536
537 /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
538 /// function for remark emission.
539 DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
540 for (const Candidate &C : OF.Candidates)
541 if (MachineFunction *MF = C.getMF())
542 if (DISubprogram *SP = MF->getFunction().getSubprogram())
543 return SP;
544 return nullptr;
545 }
546
547 /// Populate and \p InstructionMapper with instruction-to-integer mappings.
548 /// These are used to construct a suffix tree.
549 void populateMapper(InstructionMapper &Mapper, Module &M);
550
551 /// Initialize information necessary to output a size remark.
552 /// FIXME: This should be handled by the pass manager, not the outliner.
553 /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
554 /// pass manager.
555 void initSizeRemarkInfo(const Module &M,
556 StringMap<unsigned> &FunctionToInstrCount);
557
558 /// Emit the remark.
559 // FIXME: This should be handled by the pass manager, not the outliner.
560 void
561 emitInstrCountChangedRemark(const Module &M,
562 const StringMap<unsigned> &FunctionToInstrCount);
563};
564} // Anonymous namespace.
565
566char MachineOutliner::ID = 0;
567
569 MachineOutliner *OL = new MachineOutliner();
570 OL->RunOutlinerMode = RunOutlinerMode;
571 return OL;
572}
573
574INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
575 false)
576
577void MachineOutliner::emitNotOutliningCheaperRemark(
578 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
579 OutlinedFunction &OF) {
580 // FIXME: Right now, we arbitrarily choose some Candidate from the
581 // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
582 // We should probably sort these by function name or something to make sure
583 // the remarks are stable.
584 Candidate &C = CandidatesForRepeatedSeq.front();
585 MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
586 MORE.emit([&]() {
587 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
588 C.front().getDebugLoc(), C.getMBB());
589 R << "Did not outline " << NV("Length", StringLen) << " instructions"
590 << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
591 << " locations."
592 << " Bytes from outlining all occurrences ("
593 << NV("OutliningCost", OF.getOutliningCost()) << ")"
594 << " >= Unoutlined instruction bytes ("
595 << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
596 << " (Also found at: ";
597
598 // Tell the user the other places the candidate was found.
599 for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
600 R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
601 CandidatesForRepeatedSeq[i].front().getDebugLoc());
602 if (i != e - 1)
603 R << ", ";
604 }
605
606 R << ")";
607 return R;
608 });
609}
610
611void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
612 MachineBasicBlock *MBB = &*OF.MF->begin();
613 MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
614 MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
616 R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
617 << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
618 << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
619 << " locations. "
620 << "(Found at: ";
621
622 // Tell the user the other places the candidate was found.
623 for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
624
625 R << NV((Twine("StartLoc") + Twine(i)).str(),
626 OF.Candidates[i].front().getDebugLoc());
627 if (i != e - 1)
628 R << ", ";
629 }
630
631 R << ")";
632
633 MORE.emit(R);
634}
635
637 // Globals with local linkage are qualified with their module's source file
638 // name so that same-named locals in different modules do not match when hash
639 // sequences are compared across modules.
640 return stableHashValue(MI, /*HashVRegs=*/false,
641 /*HashConstantPoolIndices=*/false,
642 /*HashMemOperands=*/false,
643 /*SourceQualifyLocalGlobals=*/true);
644}
645
647 unsigned StartIdx;
648 unsigned EndIdx;
649 unsigned Count;
650 MatchedEntry(unsigned StartIdx, unsigned EndIdx, unsigned Count)
652 MatchedEntry() = delete;
653};
654
655// Find all matches in an outlined hash tree.
656// It's quadratic complexity in theory, but it's nearly linear in practice
657// since the length of outlined sequences are small within a block.
659getMatchedEntries(InstructionMapper &Mapper, const OutlinedHashTree &HashTree) {
660 auto &InstrList = Mapper.InstrList;
661 auto &UnsignedVec = Mapper.UnsignedVec;
662
663 SmallVector<MatchedEntry> MatchedEntries;
664 auto Size = UnsignedVec.size();
665
666 const auto *RootNode = HashTree.getRoot();
667
668 auto getValidInstr = [&](unsigned Index) -> const MachineInstr * {
669 if (UnsignedVec[Index] >= Mapper.LegalInstrNumber)
670 return nullptr;
671 return &(*InstrList[Index]);
672 };
673
674 auto getStableHashAndFollow =
675 [](const MachineInstr &MI, const HashNode *CurrNode) -> const HashNode * {
676 stable_hash StableHash = hashInstruction(MI);
677 if (!StableHash)
678 return nullptr;
679 auto It = CurrNode->Successors.find(StableHash);
680 return (It == CurrNode->Successors.end()) ? nullptr : It->second.get();
681 };
682
683 for (unsigned I = 0; I < Size; ++I) {
684 const MachineInstr *MI = getValidInstr(I);
685 if (!MI || MI->isDebugInstr())
686 continue;
687 const HashNode *CurrNode = getStableHashAndFollow(*MI, RootNode);
688 if (!CurrNode)
689 continue;
690
691 for (unsigned J = I + 1; J < Size; ++J) {
692 const MachineInstr *MJ = getValidInstr(J);
693 if (!MJ)
694 break;
695 // Skip debug instructions as we did for the outlined function.
696 if (MJ->isDebugInstr())
697 continue;
698 CurrNode = getStableHashAndFollow(*MJ, CurrNode);
699 if (!CurrNode)
700 break;
701 // Even with a match ending with a terminal, we continue finding
702 // matches to populate all candidates.
703 if (auto Count = CurrNode->Terminals)
704 MatchedEntries.emplace_back(I, J, *Count);
705 }
706 }
707
708 return MatchedEntries;
709}
710
711void MachineOutliner::findGlobalCandidates(
712 InstructionMapper &Mapper,
713 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList) {
714 FunctionList.clear();
715 auto &InstrList = Mapper.InstrList;
716 auto &MBBFlagsMap = Mapper.MBBFlagsMap;
717
718 const cl::LibraryOptionsContext &LibraryOptions =
719 Mapper.MMI.getModule()->getContext().getLibraryOptions();
720 assert(cgdata::hasOutlinedHashTree(LibraryOptions));
721 const auto &HashTree = *cgdata::getOutlinedHashTree(LibraryOptions);
722 std::vector<Candidate> CandidatesForRepeatedSeq;
723 for (auto &ME : getMatchedEntries(Mapper, HashTree)) {
724 CandidatesForRepeatedSeq.clear();
725 MachineBasicBlock::iterator StartIt = InstrList[ME.StartIdx];
726 MachineBasicBlock::iterator EndIt = InstrList[ME.EndIdx];
727 auto Length = ME.EndIdx - ME.StartIdx + 1;
728 MachineBasicBlock *MBB = StartIt->getParent();
729 CandidatesForRepeatedSeq.emplace_back(ME.StartIdx, Length, StartIt, EndIt,
730 MBB, MBBFlagsMap[MBB]);
731 const TargetInstrInfo *TII =
733 unsigned MinRepeats = 1;
734 std::optional<std::unique_ptr<OutlinedFunction>> OF =
735 TII->getOutliningCandidateInfo(*MMI, CandidatesForRepeatedSeq,
736 MinRepeats);
737 if (!OF.has_value() || OF.value()->Candidates.empty())
738 continue;
739 // We create a global candidate for each match.
740 assert(OF.value()->Candidates.size() == MinRepeats);
741 FunctionList.emplace_back(std::make_unique<GlobalOutlinedFunction>(
742 std::move(OF.value()), ME.Count));
743 }
744}
745
747 const Function &F = C.getMF()->getFunction();
748 return F.hasSection() ? F.getSection() : StringRef();
749}
750
752partitionCandidatesByInputSection(std::vector<Candidate> &Candidates) {
753 // Each candidate belongs to exactly one MachineFunction, so the partitions
754 // are disjoint and can be outlined independently.
756 SmallVector<StringRef> Sections;
757 for (Candidate &C : Candidates) {
759 auto It = llvm::find(Sections, Section);
760 if (It == Sections.end()) {
761 Sections.push_back(Section);
762 Partitions.emplace_back();
763 It = Sections.end() - 1;
764 }
765 Partitions[std::distance(Sections.begin(), It)].push_back(std::move(C));
766 }
767 return Partitions;
768}
769
770void MachineOutliner::createOutlinedFunctionIfBeneficial(
771 std::vector<Candidate> &Candidates, unsigned StringLen, unsigned MinRepeats,
772 const TargetInstrInfo &TII,
773 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList) {
774 if (Candidates.size() < MinRepeats)
775 return;
776
777 std::optional<std::unique_ptr<OutlinedFunction>> OF =
778 TII.getOutliningCandidateInfo(*MMI, Candidates, MinRepeats);
779
780 // If we deleted too many candidates, then there's nothing worth outlining.
781 // FIXME: This should take target-specified instruction sizes into account.
782 if (!OF.has_value() || OF.value()->Candidates.size() < MinRepeats)
783 return;
784
785 // Is it better to outline this candidate than not?
786 if (OF.value()->getBenefit() < Opts->outliner_benefit_threshold) {
787 recordUnprofitableCandidate(*OF.value());
788 emitNotOutliningCheaperRemark(StringLen, Candidates, *OF.value());
789 return;
790 }
791
792 FunctionList.emplace_back(std::move(OF.value()));
793}
794
795void MachineOutliner::findCandidates(
796 InstructionMapper &Mapper,
797 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList) {
798 FunctionList.clear();
799 // IllegalInstrNumber is decremented after assigning each unique separator.
800 SuffixTree ST(Mapper.UnsignedVec, Opts->outliner_leaf_descendants,
801 /*BoundaryStart=*/Mapper.IllegalInstrNumber + 1);
802
803 // First, find all of the repeated substrings in the tree of minimum length
804 // 2.
805 std::vector<Candidate> CandidatesForRepeatedSeq;
806 LLVM_DEBUG(dbgs() << "*** Discarding overlapping candidates *** \n");
808 dbgs() << "Searching for overlaps in all repeated sequences...\n");
809 for (SuffixTree::RepeatedSubstring &RS : ST) {
810 CandidatesForRepeatedSeq.clear();
811 unsigned StringLen = RS.Length;
812 LLVM_DEBUG(dbgs() << " Sequence length: " << StringLen << "\n");
813 // Debug code to keep track of how many candidates we removed.
814#ifndef NDEBUG
815 unsigned NumDiscarded = 0;
816 unsigned NumKept = 0;
817#endif
818 // Sort the start indices so that we can efficiently check if candidates
819 // overlap with the ones we've already found for this sequence.
820 llvm::sort(RS.StartIndices);
821 for (const unsigned &StartIdx : RS.StartIndices) {
822 // Trick: Discard some candidates that would be incompatible with the
823 // ones we've already found for this sequence. This will save us some
824 // work in candidate selection.
825 //
826 // If two candidates overlap, then we can't outline them both. This
827 // happens when we have candidates that look like, say
828 //
829 // AA (where each "A" is an instruction).
830 //
831 // We might have some portion of the module that looks like this:
832 // AAAAAA (6 A's)
833 //
834 // In this case, there are 5 different copies of "AA" in this range, but
835 // at most 3 can be outlined. If only outlining 3 of these is going to
836 // be unbeneficial, then we ought to not bother.
837 //
838 // Note that two things DON'T overlap when they look like this:
839 // start1...end1 .... start2...end2
840 // That is, one must either
841 // * End before the other starts
842 // * Start after the other ends
843 unsigned EndIdx = StartIdx + StringLen - 1;
844 if (!CandidatesForRepeatedSeq.empty() &&
845 StartIdx <= CandidatesForRepeatedSeq.back().getEndIdx()) {
846#ifndef NDEBUG
847 ++NumDiscarded;
848 LLVM_DEBUG(dbgs() << " .. DISCARD candidate @ [" << StartIdx << ", "
849 << EndIdx << "]; overlaps with candidate @ ["
850 << CandidatesForRepeatedSeq.back().getStartIdx()
851 << ", " << CandidatesForRepeatedSeq.back().getEndIdx()
852 << "]\n");
853#endif
854 continue;
855 }
856 // It doesn't overlap with anything, so we can outline it.
857 // Each sequence is over [StartIt, EndIt].
858 // Save the candidate and its location.
859#ifndef NDEBUG
860 ++NumKept;
861#endif
862 MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
863 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
864 MachineBasicBlock *MBB = StartIt->getParent();
865 CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt, EndIt,
866 MBB, Mapper.MBBFlagsMap[MBB]);
867 }
868#ifndef NDEBUG
869 LLVM_DEBUG(dbgs() << " Candidates discarded: " << NumDiscarded
870 << "\n");
871 LLVM_DEBUG(dbgs() << " Candidates kept: " << NumKept << "\n\n");
872#endif
873 unsigned MinRepeats = 2;
874
875 // We've found something we might want to outline.
876 // Create an OutlinedFunction to store it and check if it'd be beneficial
877 // to outline.
878 if (CandidatesForRepeatedSeq.size() < MinRepeats)
879 continue;
880
881 // Arbitrarily choose a TII from the first candidate.
882 // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
883 const TargetInstrInfo *TII =
884 CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
885
886 // Targets that do not opt in to section aware outlining never map
887 // functions with a section marking, so every candidate would land in a
888 // single partition. Skip partitioning entirely to avoid the allocation.
889 if (!TII->supportsSectionAwareOutlining()) {
890 createOutlinedFunctionIfBeneficial(CandidatesForRepeatedSeq, StringLen,
891 MinRepeats, *TII, FunctionList);
892 continue;
893 }
894
896 dbgs()
897 << "*** Section Aware Outlining is enabled for the target *** \n");
898
900 partitionCandidatesByInputSection(CandidatesForRepeatedSeq);
901 LLVM_DEBUG(dbgs() << " Input section partitions: " << Partitions.size()
902 << "\n");
903
904 for (std::vector<Candidate> &Partition : Partitions) {
905 LLVM_DEBUG({
906 StringRef Section = getCandidateInputSection(Partition.front());
907 dbgs() << " .. section '"
908 << (Section.empty() ? StringRef("<none>") : Section)
909 << "': " << Partition.size() << " candidates\n";
910 });
911 createOutlinedFunctionIfBeneficial(Partition, StringLen, MinRepeats, *TII,
912 FunctionList);
913 }
914 }
915}
916
917void MachineOutliner::computeAndPublishHashSequence(MachineFunction &MF,
918 unsigned CandSize) {
919 // Compute the hash sequence for the outlined function.
920 SmallVector<stable_hash> OutlinedHashSequence;
921 for (auto &MBB : MF) {
922 for (auto &NewMI : MBB) {
923 stable_hash Hash = hashInstruction(NewMI);
924 if (!Hash) {
925 OutlinedHashSequence.clear();
926 break;
927 }
928 OutlinedHashSequence.push_back(Hash);
929 }
930 }
931
932 // Append a unique name based on the non-empty hash sequence.
933 if (Opts->append_content_hash_outlined_name &&
934 !OutlinedHashSequence.empty()) {
935 auto CombinedHash = stable_hash_combine(OutlinedHashSequence);
936 auto NewName =
937 MF.getName().str() + ".content." + std::to_string(CombinedHash);
938 MF.getFunction().setName(NewName);
939 }
940
941 // Publish the non-empty hash sequence to the local hash tree.
942 if (OutlinerMode == CGDataMode::Write) {
943 StableHashAttempts++;
944 if (!OutlinedHashSequence.empty())
945 LocalHashTree->insert({OutlinedHashSequence, CandSize});
946 else
947 StableHashDropped++;
948 }
949}
950
951void MachineOutliner::recordUnprofitableCandidate(OutlinedFunction &OF) {
952 if (!Opts->machine_outliner_publish_unprofitable_candidates ||
953 OutlinerMode != CGDataMode::Write ||
954 OF.getNumInstrs() >
955 Opts->machine_outliner_unprofitable_candidate_max_instrs)
956 return;
957
958 // Read mode uses the merged count to check frame costs.
959 if (llvm::all_of(OF.Candidates, [&](const Candidate &C) {
960 return OF.SequenceSize <= C.getCallOverhead();
961 }))
962 return;
963
964 SmallVector<stable_hash> HashSequence;
965 for (MachineInstr &MI : OF.Candidates.front()) {
966 if (MI.isDebugInstr())
967 continue;
968 const stable_hash Hash = hashInstruction(MI);
969 if (!Hash)
970 return;
971 HashSequence.push_back(Hash);
972 }
973 if (HashSequence.empty() ||
974 UnprofitableCandidateHashTree.find(HashSequence).value_or(0))
975 return;
976
977 const unsigned SequenceID = UnprofitableCandidates.size();
978 // This temporary tree uses the terminal field for a one-based sequence ID,
979 // not an occurrence count. Reserve zero for sequences without a terminal.
980 UnprofitableCandidateHashTree.insert({HashSequence, SequenceID + 1});
981 UnprofitableCandidates.push_back(std::move(HashSequence));
982}
983
984bool MachineOutliner::publishUnprofitableCandidates(InstructionMapper &Mapper) {
985 if (!Opts->machine_outliner_publish_unprofitable_candidates ||
986 OutlinerMode != CGDataMode::Write || UnprofitableCandidates.empty())
987 return false;
988
989 SmallVector<std::vector<Candidate>> CandidateGroups(
990 UnprofitableCandidates.size());
991 BitVector ConflictingGroups(UnprofitableCandidates.size());
992 SmallVector<MatchedEntry> ActiveMatches;
993 for (const auto &ME :
994 getMatchedEntries(Mapper, UnprofitableCandidateHashTree)) {
995 assert(ME.Count && ME.Count <= CandidateGroups.size());
996 // Unlike the global tree, this tree stores SequenceID + 1 in its terminal
997 // field. Decode the sequence index; ME.Count is not an occurrence count.
998 const unsigned SequenceID = ME.Count - 1;
999
1000 // Matches arrive in start-index order. Keep the ranges overlapping this
1001 // match, including those rejected by the same-sequence overlap check below.
1002 llvm::erase_if(ActiveMatches, [&](const MatchedEntry &Other) {
1003 return Other.EndIdx < ME.StartIdx;
1004 });
1005 for (const MatchedEntry &Other : ActiveMatches) {
1006 if (Other.Count == ME.Count)
1007 continue;
1008 // A containing sequence already covers the instructions of a sequence
1009 // nested in it, so drop only the nested group. A partial overlap drops
1010 // both groups.
1011 const bool MEContained = ME.EndIdx <= Other.EndIdx;
1012 const bool OtherContained =
1013 Other.StartIdx == ME.StartIdx && Other.EndIdx <= ME.EndIdx;
1014 if (!OtherContained)
1015 ConflictingGroups.set(SequenceID);
1016 if (!MEContained)
1017 ConflictingGroups.set(Other.Count - 1);
1018 }
1019 ActiveMatches.push_back(ME);
1020
1021 auto &Candidates = CandidateGroups[SequenceID];
1022 if (!Candidates.empty() && ME.StartIdx <= Candidates.back().getEndIdx())
1023 continue;
1024
1025 auto StartIt = Mapper.InstrList[ME.StartIdx];
1026 auto EndIt = Mapper.InstrList[ME.EndIdx];
1027 auto *MBB = StartIt->getParent();
1028 Candidates.emplace_back(ME.StartIdx, ME.EndIdx - ME.StartIdx + 1, StartIt,
1029 EndIt, MBB, Mapper.MBBFlagsMap.lookup(MBB));
1030 }
1031
1032 bool Published = false;
1033 for (const auto &[SequenceID, Candidates] :
1034 llvm::enumerate(CandidateGroups)) {
1035 // Publishing overlapping sequences would count the same instructions twice.
1036 // Read mode prunes overlapping sites, but cannot reconcile their merged
1037 // counts across modules. Conservatively discard conflicting groups rather
1038 // than assigning sites using a local order that can differ from Read mode.
1039 if (Candidates.empty() || ConflictingGroups.test(SequenceID))
1040 continue;
1041
1042 unsigned NumSites = 0;
1043 for (auto &Partition : partitionCandidatesByInputSection(Candidates)) {
1044 const auto *TII =
1045 Partition.front().getMF()->getSubtarget().getInstrInfo();
1046 auto OF =
1047 TII->getOutliningCandidateInfo(*MMI, Partition, /*MinRepeats=*/1);
1048 if (!OF || OF.value()->Candidates.empty())
1049 continue;
1050 NumSites +=
1051 llvm::count_if(OF.value()->Candidates, [&](const Candidate &C) {
1052 return OF.value()->SequenceSize > C.getCallOverhead();
1053 });
1054 }
1055 if (!NumSites)
1056 continue;
1057
1058 LocalHashTree->insert({UnprofitableCandidates[SequenceID], NumSites});
1059 ++UnprofitableCandidateGroupsPublished;
1060 UnprofitableCandidateSitesPublished += NumSites;
1061 Published = true;
1062 }
1063 return Published;
1064}
1065
1066MachineFunction *MachineOutliner::createOutlinedFunction(
1067 Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
1068
1069 // Create the function name. This should be unique.
1070 // FIXME: We should have a better naming scheme. This should be stable,
1071 // regardless of changes to the outliner's cost model/traversal order.
1072 std::string FunctionName = "OUTLINED_FUNCTION_";
1073 if (OutlineRepeatedNum > 0)
1074 FunctionName += std::to_string(OutlineRepeatedNum + 1) + "_";
1075 FunctionName += std::to_string(Name);
1076 LLVM_DEBUG(dbgs() << "NEW FUNCTION: " << FunctionName << "\n");
1077
1078 // Create the function using an IR-level function.
1079 LLVMContext &C = M.getContext();
1080 Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false),
1081 Function::ExternalLinkage, FunctionName, M);
1082
1083 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1084 // which gives us better results when we outline from linkonceodr functions.
1085 F->setLinkage(GlobalValue::InternalLinkage);
1086 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1087
1088 // Set optsize/minsize, so we don't insert padding between outlined
1089 // functions.
1090 F->addFnAttr(Attribute::OptimizeForSize);
1091 F->addFnAttr(Attribute::MinSize);
1092
1093 Candidate &FirstCand = OF.Candidates.front();
1094 const TargetInstrInfo &TII =
1095 *FirstCand.getMF()->getSubtarget().getInstrInfo();
1096
1097 TII.mergeOutliningCandidateAttributes(*F, OF.Candidates);
1098
1099 if (TII.supportsSectionAwareOutlining()) {
1100 const Function &ParentFn = FirstCand.getMF()->getFunction();
1101 if (ParentFn.hasSection()) {
1102 F->setSection(ParentFn.getSection());
1103 LLVM_DEBUG(dbgs() << " INHERITED SECTION: " << ParentFn.getSection()
1104 << "\n");
1105 }
1106 }
1107
1108 // Set uwtable, so we generate eh_frame.
1109 UWTableKind UW = std::accumulate(
1110 OF.Candidates.cbegin(), OF.Candidates.cend(), UWTableKind::None,
1111 [](UWTableKind K, const outliner::Candidate &C) {
1112 return std::max(K, C.getMF()->getFunction().getUWTableKind());
1113 });
1114 F->setUWTableKind(UW);
1115
1116 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1117 IRBuilder<> Builder(EntryBB);
1118 Builder.CreateRetVoid();
1119
1120 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
1122 MF.setIsOutlined(true);
1123 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1124
1125 // Insert the new function into the module.
1126 MF.insert(MF.begin(), &MBB);
1127
1128 MachineFunction *OriginalMF = FirstCand.front().getMF();
1129 const std::vector<MCCFIInstruction> &Instrs =
1130 OriginalMF->getFrameInstructions();
1131 for (auto &MI : FirstCand) {
1132 if (MI.isDebugInstr())
1133 continue;
1134
1135 // Don't keep debug information for outlined instructions.
1136 auto DL = DebugLoc();
1137 if (MI.isCFIInstruction()) {
1138 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
1139 MCCFIInstruction CFI = Instrs[CFIIndex];
1140 BuildMI(MBB, MBB.end(), DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1141 .addCFIIndex(MF.addFrameInst(CFI));
1142 } else {
1143 MachineInstr &NewMI = TII.duplicate(MBB, MBB.end(), MI);
1144 NewMI.dropMemRefs(MF);
1145 NewMI.setDebugLoc(DL);
1146 NewMI.clearKillInfo();
1147 // Also clear debug locations and kill info on any bundled instructions.
1148 if (NewMI.isBundledWithSucc()) {
1149 auto BundleEnd = getBundleEnd(NewMI.getIterator());
1150 for (auto I = std::next(NewMI.getIterator()); I != BundleEnd; ++I) {
1151 I->setDebugLoc(DL);
1152 I->clearKillInfo();
1153 }
1154 }
1155 }
1156 }
1157
1158 if (OutlinerMode != CGDataMode::None)
1159 computeAndPublishHashSequence(MF, OF.Candidates.size());
1160
1161 // Set normal properties for a late MachineFunction.
1162 MF.getProperties().resetIsSSA();
1163 MF.getProperties().setNoPHIs();
1164 MF.getProperties().setNoVRegs();
1165 MF.getProperties().setTracksLiveness();
1167
1168 // Compute live-in set for outlined fn
1169 const MachineRegisterInfo &MRI = MF.getRegInfo();
1170 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
1171 LivePhysRegs LiveIns(TRI);
1172 for (auto &Cand : OF.Candidates) {
1173 // Figure out live-ins at the first instruction.
1174 MachineBasicBlock &OutlineBB = *Cand.front().getParent();
1175 LivePhysRegs CandLiveIns(TRI);
1176 CandLiveIns.addLiveOuts(OutlineBB);
1177 for (const MachineInstr &MI :
1178 reverse(make_range(Cand.begin(), OutlineBB.end())))
1179 CandLiveIns.stepBackward(MI);
1180
1181 // The live-in set for the outlined function is the union of the live-ins
1182 // from all the outlining points.
1183 for (MCPhysReg Reg : CandLiveIns)
1184 LiveIns.addReg(Reg);
1185 }
1186 addLiveIns(MBB, LiveIns);
1187
1188 TII.buildOutlinedFrame(MBB, MF, OF);
1189
1190 // If there's a DISubprogram associated with this outlined function, then
1191 // emit debug info for the outlined function.
1192 if (DISubprogram *SP = getSubprogramOrNull(OF)) {
1193 // We have a DISubprogram. Get its DICompileUnit.
1194 DICompileUnit *CU = SP->getUnit();
1195 DIBuilder DB(M, true, CU);
1196 DIFile *Unit = SP->getFile();
1197 Mangler Mg;
1198 // Get the mangled name of the function for the linkage name.
1199 std::string Dummy;
1200 raw_string_ostream MangledNameStream(Dummy);
1201 Mg.getNameWithPrefix(MangledNameStream, F, false);
1202
1203 DISubprogram *OutlinedSP = DB.createFunction(
1204 Unit /* Context */, F->getName(), StringRef(Dummy), Unit /* File */,
1205 0 /* Line 0 is reserved for compiler-generated code. */,
1206 DB.createSubroutineType(DB.getOrCreateTypeArray({})), /* void type */
1207 0, /* Line 0 is reserved for compiler-generated code. */
1208 DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
1209 /* Outlined code is optimized code by definition. */
1210 DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
1211
1212 // Attach subprogram to the function.
1213 F->setSubprogram(OutlinedSP);
1214 // We're done with the DIBuilder.
1215 DB.finalize();
1216 }
1217
1218 return &MF;
1219}
1220
1221bool MachineOutliner::outline(
1222 Module &M, std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList,
1223 InstructionMapper &Mapper, unsigned &OutlinedFunctionNum) {
1224 LLVM_DEBUG(dbgs() << "*** Outlining ***\n");
1225 LLVM_DEBUG(dbgs() << "NUMBER OF POTENTIAL FUNCTIONS: " << FunctionList.size()
1226 << "\n");
1227 bool OutlinedSomething = false;
1228
1229 // Sort by priority where priority := getNotOutlinedCost / getOutliningCost.
1230 // The function with highest priority should be outlined first.
1231 stable_sort(FunctionList, [](const std::unique_ptr<OutlinedFunction> &LHS,
1232 const std::unique_ptr<OutlinedFunction> &RHS) {
1233 return LHS->getNotOutlinedCost() * RHS->getOutliningCost() >
1234 RHS->getNotOutlinedCost() * LHS->getOutliningCost();
1235 });
1236
1237 // Walk over each function, outlining them as we go along. Functions are
1238 // outlined greedily, based off the sort above.
1239 auto *UnsignedVecBegin = Mapper.UnsignedVec.begin();
1240 LLVM_DEBUG(dbgs() << "WALKING FUNCTION LIST\n");
1241 for (auto &OF : FunctionList) {
1242#ifndef NDEBUG
1243 auto NumCandidatesBefore = OF->Candidates.size();
1244#endif
1245 // If we outlined something that overlapped with a candidate in a previous
1246 // step, then we can't outline from it.
1247 erase_if(OF->Candidates, [&UnsignedVecBegin](Candidate &C) {
1248 return std::any_of(UnsignedVecBegin + C.getStartIdx(),
1249 UnsignedVecBegin + C.getEndIdx() + 1, [](unsigned I) {
1250 return I == static_cast<unsigned>(-1);
1251 });
1252 });
1253
1254#ifndef NDEBUG
1255 auto NumCandidatesAfter = OF->Candidates.size();
1256 LLVM_DEBUG(dbgs() << "PRUNED: " << NumCandidatesBefore - NumCandidatesAfter
1257 << "/" << NumCandidatesBefore << " candidates\n");
1258#endif
1259
1260 // If we made it unbeneficial to outline this function, skip it.
1261 if (OF->getBenefit() < Opts->outliner_benefit_threshold) {
1262 // Overlap pruning can make a sequence that was profitable at discovery
1263 // locally unprofitable. Record it like one rejected at discovery.
1264 if (!OF->Candidates.empty())
1265 recordUnprofitableCandidate(*OF);
1266 LLVM_DEBUG(dbgs() << "SKIP: Expected benefit (" << OF->getBenefit()
1267 << " B) < threshold ("
1268 << Opts->outliner_benefit_threshold << " B)\n");
1269 continue;
1270 }
1271
1272 LLVM_DEBUG(dbgs() << "OUTLINE: Expected benefit (" << OF->getBenefit()
1273 << " B) > threshold (" << Opts->outliner_benefit_threshold
1274 << " B)\n");
1275
1276 // Remove all Linker Optimization Hints from the candidates.
1277 // TODO: The intersection of the LOHs from all candidates should be legal in
1278 // the outlined function.
1279 SmallPtrSet<MachineInstr *, 2> MIs;
1280 for (Candidate &C : OF->Candidates) {
1281 for (MachineInstr &MI : C)
1282 MIs.insert(&MI);
1283 NumRemovedLOHs += TM->clearLinkerOptimizationHints(MIs);
1284 MIs.clear();
1285 }
1286
1287 // It's beneficial. Create the function and outline its sequence's
1288 // occurrences.
1289 OF->MF = createOutlinedFunction(M, *OF, Mapper, OutlinedFunctionNum);
1290 emitOutlinedFunctionRemark(*OF);
1291 FunctionsCreated++;
1292 OutlinedFunctionNum++; // Created a function, move to the next name.
1293 MachineFunction *MF = OF->MF;
1294 const TargetSubtargetInfo &STI = MF->getSubtarget();
1295 const TargetInstrInfo &TII = *STI.getInstrInfo();
1296
1297 // Replace occurrences of the sequence with calls to the new function.
1298 LLVM_DEBUG(dbgs() << "CREATE OUTLINED CALLS\n");
1299 for (Candidate &C : OF->Candidates) {
1300 MachineBasicBlock &MBB = *C.getMBB();
1301 MachineBasicBlock::iterator StartIt = C.begin();
1302 MachineBasicBlock::iterator EndIt = std::prev(C.end());
1303
1304 // Find the first non-debug instruction with a non-zero source line, and
1305 // merge the locations of the calls in the candidate that have one.
1306 DebugLoc FirstLoc, MergedCallLoc;
1307 for (MachineInstr &MI : C) {
1308 if (MI.isDebugInstr())
1309 continue;
1310 const DebugLoc &DL = MI.getDebugLoc();
1311 if (!DL || !DL.getLine())
1312 continue;
1313 if (!FirstLoc)
1314 FirstLoc = DL;
1315 if (MI.isCall())
1316 MergedCallLoc = MergedCallLoc
1317 ? DebugLoc::getMergedLocation(MergedCallLoc, DL)
1318 : DL;
1319 }
1320
1321 // Remember the instruction the call sequence will be inserted after, so
1322 // we can find every instruction the target inserts below.
1324 StartIt == MBB.begin() ? MBB.end() : std::prev(StartIt);
1325
1326 // Insert the call.
1327 auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
1328
1329 // Unwinding through a call in the candidate symbolizes the caller frame
1330 // at the outlined call, so it should carry that call's location. With
1331 // multiple calls, every one of them is symbolized there, so use their
1332 // merged location: it may be less precise when the calls differ, but it
1333 // never attributes a call to an inlined scope it was not in. Nothing
1334 // returns to a tail branch, so it keeps the first location.
1335 DebugLoc CallLoc =
1336 !CallInst->isTerminator() && MergedCallLoc ? MergedCallLoc : FirstLoc;
1337
1338 // insertOutlinedCall may emit link register save/restore instructions
1339 // around the call, and leaves StartIt on the last instruction it
1340 // inserted. Give the whole sequence the same location. Otherwise, when
1341 // that location has a source line, a locationless save or restore can
1342 // introduce a line 0 row, including at the return address immediately
1343 // after the call.
1345 PrevIt == MBB.end() ? MBB.begin() : std::next(PrevIt);
1346 for (MachineInstr &MI : make_range(SeqBegin, std::next(StartIt)))
1347 MI.setDebugLoc(CallLoc);
1348
1349#ifndef NDEBUG
1350 auto MBBBeingOutlinedFromName =
1351 MBB.getName().empty() ? "<unknown>" : MBB.getName().str();
1352 auto MFBeingOutlinedFromName = MBB.getParent()->getName().empty()
1353 ? "<unknown>"
1354 : MBB.getParent()->getName().str();
1355 LLVM_DEBUG(dbgs() << " CALL: " << MF->getName() << " in "
1356 << MFBeingOutlinedFromName << ":"
1357 << MBBBeingOutlinedFromName << "\n");
1358 LLVM_DEBUG(dbgs() << " .. " << *CallInst);
1359#endif
1360
1361 // If the caller tracks liveness, then we need to make sure that
1362 // anything we outline doesn't break liveness assumptions. The outlined
1363 // functions themselves currently don't track liveness, but we should
1364 // make sure that the ranges we yank things out of aren't wrong.
1365 if (MBB.getParent()->getProperties().hasTracksLiveness()) {
1366 // The following code is to add implicit def and use operands to the
1367 // call instruction. It also updates call site information for moved
1368 // code.
1369 SmallSet<Register, 2> UseRegs, DefRegs;
1370 LiveRegUnits LiveUnits(
1372 // Copy over the defs in the outlined range.
1373 // First inst in outlined range <-- Anything that's defined in this
1374 // ... .. range has to be added as an
1375 // implicit Last inst in outlined range <-- def to the call
1376 // instruction. Also remove call site information for outlined block
1377 // of code. The exposed uses need to be copied in the outlined range.
1379 Iter = EndIt.getReverse(),
1380 Last = std::next(CallInst.getReverse());
1381 Iter != Last; Iter++) {
1382 MachineInstr *MI = &*Iter;
1383 if (MI->isDebugInstr())
1384 continue;
1385 LiveUnits.stepBackward(*MI);
1386 for (MachineOperand &MOP : MI->operands()) {
1387 if (!MOP.isReg() || !MOP.getReg())
1388 continue;
1389
1390 if (MOP.isDef())
1391 DefRegs.insert(MOP.getReg());
1392 else if (MOP.readsReg() && MOP.getReg().isPhysical())
1393 UseRegs.insert(MOP.getReg());
1394 }
1395 if (MI->isCandidateForAdditionalCallInfo())
1396 MI->getMF()->eraseAdditionalCallInfo(MI);
1397 }
1398
1399 // If it's a def, add it to the call instruction.
1400 for (const Register &I : DefRegs)
1401 CallInst->addOperand(
1402 MachineOperand::CreateReg(I, true, /* isDef = true */
1403 true /* isImp = true */));
1404
1405 // If it's live into the range, add it to the call instruction.
1406 for (const Register &I : UseRegs)
1407 if (!LiveUnits.available(I.asMCReg()))
1408 CallInst->addOperand(
1409 MachineOperand::CreateReg(I, false, /* isDef = false */
1410 true /* isImp = true */));
1411 }
1412
1413 // Erase from the point after where the call was inserted up to, and
1414 // including, the final instruction in the sequence.
1415 // Erase needs one past the end, so we need std::next there too.
1416 MBB.erase(std::next(StartIt), std::next(EndIt));
1417
1418 // Keep track of what we removed by marking them all as -1.
1419 for (unsigned &I : make_range(UnsignedVecBegin + C.getStartIdx(),
1420 UnsignedVecBegin + C.getEndIdx() + 1))
1421 I = static_cast<unsigned>(-1);
1422 OutlinedSomething = true;
1423
1424 // Statistics.
1425 NumOutlined++;
1426 }
1427 }
1428
1429 LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n");
1430 return OutlinedSomething;
1431}
1432
1433static bool allowPGOOutlining(RunOutliner RunOutlinerMode,
1434 const ProfileSummaryInfo *PSI,
1435 const BlockFrequencyInfo *BFI,
1437 if (RunOutlinerMode != RunOutliner::OptimisticPGO &&
1438 RunOutlinerMode != RunOutliner::ConservativePGO)
1439 return true;
1440 auto *MF = MBB.getParent();
1441 if (MF->getFunction().hasFnAttribute(Attribute::Cold)) {
1442 ++NumPGOAllowedCold;
1443 return true;
1444 }
1445
1446 auto *BB = MBB.getBasicBlock();
1447 if (BB && PSI && BFI)
1448 if (auto Count = BFI->getBlockProfileCount(BB))
1449 return *Count <= PSI->getOrCompColdCountThreshold();
1450
1451 if (RunOutlinerMode == RunOutliner::OptimisticPGO) {
1452 auto *TII = MF->getSubtarget().getInstrInfo();
1453 if (TII->shouldOutlineFromFunctionByDefault(*MF)) {
1454 // Profile data is unavailable, but we optimistically allow outlining
1455 ++NumPGOOptimisticOutlined;
1456 return true;
1457 }
1458 return false;
1459 }
1460 assert(RunOutlinerMode == RunOutliner::ConservativePGO);
1461 // Profile data is unavailable, so we conservatively block outlining
1462 ++NumPGOConservativeBlockedOutlined;
1463 return false;
1464}
1465
1466void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M) {
1467 // Build instruction mappings for each function in the module. Start by
1468 // iterating over each Function in M.
1469 LLVM_DEBUG(dbgs() << "*** Populating mapper ***\n");
1470 bool EnableProfileGuidedOutlining =
1471 RunOutlinerMode == RunOutliner::OptimisticPGO ||
1472 RunOutlinerMode == RunOutliner::ConservativePGO;
1473 ProfileSummaryInfo *PSI = nullptr;
1474 if (EnableProfileGuidedOutlining)
1475 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1476 for (Function &F : M) {
1477 LLVM_DEBUG(dbgs() << "MAPPING FUNCTION: " << F.getName() << "\n");
1478
1479 if (F.hasFnAttribute(Attribute::NoOutline)) {
1480 LLVM_DEBUG(dbgs() << "SKIP: Function has nooutline attribute\n");
1481 continue;
1482 }
1483
1484 // There's something in F. Check if it has a MachineFunction associated with
1485 // it.
1487
1488 // If it doesn't, then there's nothing to outline from. Move to the next
1489 // Function.
1490 if (!MF) {
1491 LLVM_DEBUG(dbgs() << "SKIP: Function does not have a MachineFunction\n");
1492 continue;
1493 }
1494
1495 // If the function returns twice, skip it.
1496 // The context saved by functions such as setjmp will be different if
1497 // they take place within an outlined function.
1498 // Ex: Saved stack pointer will be different.
1499 if (F.hasFnAttribute(Attribute::ReturnsTwice)) {
1500 LLVM_DEBUG(dbgs() << "SKIP: Function has returnstwice attribute\n");
1501 continue;
1502 }
1503
1504 // If the function calls a function that can return twice, skip it,
1505 // for the same reasons.
1506 if (MF->exposesReturnsTwice()) {
1507 LLVM_DEBUG(dbgs() << "SKIP: Function calls a function with "
1508 "returnstwice attribute\n");
1509 continue;
1510 }
1511
1512 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1513 BlockFrequencyInfo *BFI = nullptr;
1514 if (EnableProfileGuidedOutlining && F.hasProfileData())
1515 BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1516 if (RunOutlinerMode == RunOutliner::TargetDefault &&
1517 !TII->shouldOutlineFromFunctionByDefault(*MF)) {
1518 LLVM_DEBUG(dbgs() << "SKIP: Target does not want to outline from "
1519 "function by default\n");
1520 continue;
1521 }
1522
1523 // We have a MachineFunction. Ask the target if it's suitable for outlining.
1524 // If it isn't, then move on to the next Function in the module.
1525 if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs)) {
1526 LLVM_DEBUG(dbgs() << "SKIP: " << MF->getName()
1527 << ": unsafe to outline from\n");
1528 continue;
1529 }
1530
1531 // We have a function suitable for outlining. Iterate over every
1532 // MachineBasicBlock in MF and try to map its instructions to a list of
1533 // unsigned integers.
1534 const unsigned MinMBBSize = 2;
1535
1536 for (MachineBasicBlock &MBB : *MF) {
1537 LLVM_DEBUG(dbgs() << " MAPPING MBB: '" << MBB.getName() << "'\n");
1538 // If there isn't anything in MBB, then there's no point in outlining from
1539 // it.
1540 // If there are fewer than 2 non-debug instructions in the MBB, then it
1541 // can't ever contain something worth outlining. Count raw instructions,
1542 // including bundle interiors, to preserve MBB.size() behavior. Pseudo
1543 // probes also retain their historical treatment as ordinary
1544 // instructions.
1545 // FIXME: This should be based off of the maximum size in B of an outlined
1546 // call versus the size in B of the MBB.
1548 MBB.instr_end(),
1549 /* SkipPseudoOp */ false),
1550 MinMBBSize)) {
1551 LLVM_DEBUG(dbgs() << " SKIP: MBB size less than minimum size of "
1552 << MinMBBSize << "\n");
1553 continue;
1554 }
1555
1556 // Check if MBB could be the target of an indirect branch. If it is, then
1557 // we don't want to outline from it.
1558 if (MBB.hasAddressTaken()) {
1559 LLVM_DEBUG(dbgs() << " SKIP: MBB's address is taken\n");
1560 continue;
1561 }
1562
1563 if (!allowPGOOutlining(RunOutlinerMode, PSI, BFI, MBB)) {
1564 ++NumPGOBlockedOutlined;
1565 continue;
1566 }
1567
1568 // MBB is suitable for outlining. Map it to a list of unsigneds.
1569 Mapper.convertToUnsignedVec(MBB, *TII);
1570 }
1571 }
1572 // Statistics.
1573 UnsignedVecSize = Mapper.UnsignedVec.size();
1574}
1575
1576void MachineOutliner::initSizeRemarkInfo(
1577 const Module &M, StringMap<unsigned> &FunctionToInstrCount) {
1578 // Collect instruction counts for every function. We'll use this to emit
1579 // per-function size remarks later.
1580 for (const Function &F : M) {
1582
1583 // We only care about MI counts here. If there's no MachineFunction at this
1584 // point, then there won't be after the outliner runs, so let's move on.
1585 if (!MF)
1586 continue;
1587 FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
1588 }
1589}
1590
1591void MachineOutliner::emitInstrCountChangedRemark(
1592 const Module &M, const StringMap<unsigned> &FunctionToInstrCount) {
1593 // Iterate over each function in the module and emit remarks.
1594 // Note that we won't miss anything by doing this, because the outliner never
1595 // deletes functions.
1596 for (const Function &F : M) {
1598
1599 // The outliner never deletes functions. If we don't have a MF here, then we
1600 // didn't have one prior to outlining either.
1601 if (!MF)
1602 continue;
1603
1604 std::string Fname = std::string(F.getName());
1605 unsigned FnCountAfter = MF->getInstructionCount();
1606 unsigned FnCountBefore = 0;
1607
1608 // Check if the function was recorded before.
1609 auto It = FunctionToInstrCount.find(Fname);
1610
1611 // Did we have a previously-recorded size? If yes, then set FnCountBefore
1612 // to that.
1613 if (It != FunctionToInstrCount.end())
1614 FnCountBefore = It->second;
1615
1616 // Compute the delta and emit a remark if there was a change.
1617 int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
1618 static_cast<int64_t>(FnCountBefore);
1619 if (FnDelta == 0)
1620 continue;
1621
1622 MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
1623 MORE.emit([&]() {
1624 MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
1625 DiagnosticLocation(), &MF->front());
1626 R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
1627 << ": Function: "
1628 << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
1629 << ": MI instruction count changed from "
1630 << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
1631 FnCountBefore)
1632 << " to "
1633 << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
1634 FnCountAfter)
1635 << "; Delta: "
1636 << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
1637 return R;
1638 });
1639 }
1640}
1641
1642void MachineOutliner::initializeOutlinerMode(const Module &M) {
1643 if (!Opts->global_outlining)
1644 return;
1645
1646 if (auto *IndexWrapperPass =
1647 getAnalysisIfAvailable<ImmutableModuleSummaryIndexWrapperPass>()) {
1648 auto *TheIndex = IndexWrapperPass->getIndex();
1649 // (Full)LTO module does not have functions added to the index.
1650 // In this case, we run the outliner without using codegen data as usual.
1651 if (TheIndex && !TheIndex->hasExportedFunctions(M))
1652 return;
1653 }
1654
1655 // When codegen data write is enabled, we want to write the local outlined
1656 // hash tree to the custom section, `__llvm_outline`.
1657 // When the outlined hash tree is available from the previous codegen data,
1658 // we want to read it to optimistically create global outlining candidates.
1659 const cl::LibraryOptionsContext &LibraryOptions =
1660 M.getContext().getLibraryOptions();
1661 if (cgdata::emitCGData(LibraryOptions)) {
1662 OutlinerMode = CGDataMode::Write;
1663 // Create a local outlined hash tree to be published.
1664 LocalHashTree = std::make_unique<OutlinedHashTree>();
1665 // We don't need to read the outlined hash tree from the previous codegen
1666 } else if (cgdata::hasOutlinedHashTree(LibraryOptions))
1667 OutlinerMode = CGDataMode::Read;
1668}
1669
1670void MachineOutliner::emitOutlinedHashTree(Module &M) {
1671 assert(LocalHashTree);
1672 if (!LocalHashTree->empty()) {
1673 LLVM_DEBUG({
1674 dbgs() << "Emit outlined hash tree. Size: " << LocalHashTree->size()
1675 << "\n";
1676 });
1677 SmallVector<char> Buf;
1678 raw_svector_ostream OS(Buf);
1679
1680 OutlinedHashTreeRecord HTR(std::move(LocalHashTree));
1681 HTR.serialize(OS);
1682
1683 llvm::StringRef Data(Buf.data(), Buf.size());
1684 std::unique_ptr<MemoryBuffer> Buffer =
1685 MemoryBuffer::getMemBuffer(Data, "in-memory outlined hash tree", false);
1686
1687 Triple TT(M.getTargetTriple());
1689 M, *Buffer,
1690 getCodeGenDataSectionName(CG_outline, TT.getObjectFormat()));
1691 }
1692}
1693
1694bool MachineOutliner::runOnModule(Module &M) {
1695 if (skipModule(M))
1696 return false;
1697
1698 // Check if there's anything in the module. If it's empty, then there's
1699 // nothing to outline.
1700 if (M.empty())
1701 return false;
1702
1703 Opts = &getCodeGenOptions(M);
1704
1705 // Initialize the outliner mode.
1706 initializeOutlinerMode(M);
1707
1708 MMI = &getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
1709 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
1710
1711 // Number to append to the current outlined function.
1712 unsigned OutlinedFunctionNum = 0;
1713
1714 OutlineRepeatedNum = 0;
1715 // Clear once per module so candidates discovered before a rerun are retained,
1716 // even if too few sites survive for the suffix tree to rediscover them.
1717 UnprofitableCandidates.clear();
1718 UnprofitableCandidateHashTree.clear();
1719 // Each doOutline replaces the mapping; publishing below uses the last one.
1720 std::optional<InstructionMapper> Mapper;
1721 const bool OutlinedSomething = doOutline(M, Mapper, OutlinedFunctionNum);
1722
1723 for (unsigned I = 0; OutlinedSomething && I < Opts->machine_outliner_reruns;
1724 ++I) {
1725 OutlinedFunctionNum = 0;
1726 OutlineRepeatedNum++;
1727 if (!doOutline(M, Mapper, OutlinedFunctionNum)) {
1728 LLVM_DEBUG({
1729 dbgs() << "Did not outline on iteration " << I + 2 << " out of "
1730 << Opts->machine_outliner_reruns + 1 << "\n";
1731 });
1732 break;
1733 }
1734 }
1735
1736 // Recount sequences collected across all iterations in the final mapping,
1737 // which excludes sites consumed by local outlining. Remapping the module
1738 // would also count sites inside the functions outlined by that iteration.
1739 const bool PublishedUnprofitableCandidates =
1740 publishUnprofitableCandidates(*Mapper);
1741 if (!OutlinedSomething && !PublishedUnprofitableCandidates)
1742 return false;
1743
1744 if (OutlinerMode == CGDataMode::Write)
1745 emitOutlinedHashTree(M);
1746
1747 return true;
1748}
1749
1750bool MachineOutliner::doOutline(Module &M,
1751 std::optional<InstructionMapper> &Mapper,
1752 unsigned &OutlinedFunctionNum) {
1753 // If the user passed -enable-machine-outliner=always or
1754 // -enable-machine-outliner, the pass will run on all functions in the module.
1755 // Otherwise, if the target supports default outlining, it will run on all
1756 // functions deemed by the target to be worth outlining from by default. Tell
1757 // the user how the outliner is running.
1758 LLVM_DEBUG({
1759 dbgs() << "Machine Outliner: Running on ";
1760 switch (RunOutlinerMode) {
1761 case RunOutliner::AlwaysOutline:
1762 dbgs() << "all functions";
1763 break;
1764 case RunOutliner::OptimisticPGO:
1765 dbgs() << "optimistically cold functions";
1766 break;
1767 case RunOutliner::ConservativePGO:
1768 dbgs() << "conservatively cold functions";
1769 break;
1770 case RunOutliner::TargetDefault:
1771 dbgs() << "target-default functions";
1772 break;
1773 case RunOutliner::NeverOutline:
1774 llvm_unreachable("should not outline");
1775 }
1776 dbgs() << "\n";
1777 });
1778
1779 // If the user specifies that they want to outline from linkonceodrs, set
1780 // it here.
1781 OutlineFromLinkOnceODRs = Opts->enable_linkonceodr_outlining;
1782 Mapper.emplace(*MMI);
1783
1784 // Prepare instruction mappings for the suffix tree.
1785 populateMapper(*Mapper, M);
1786 std::vector<std::unique_ptr<OutlinedFunction>> FunctionList;
1787
1788 // Find all of the outlining candidates.
1789 if (OutlinerMode == CGDataMode::Read)
1790 findGlobalCandidates(*Mapper, FunctionList);
1791 else
1792 findCandidates(*Mapper, FunctionList);
1793
1794 // If we've requested size remarks, then collect the MI counts of every
1795 // function before outlining, and the MI counts after outlining.
1796 // FIXME: This shouldn't be in the outliner at all; it should ultimately be
1797 // the pass manager's responsibility.
1798 // This could pretty easily be placed in outline instead, but because we
1799 // really ultimately *don't* want this here, it's done like this for now
1800 // instead.
1801
1802 // Check if we want size remarks.
1803 bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
1804 StringMap<unsigned> FunctionToInstrCount;
1805 if (ShouldEmitSizeRemarks)
1806 initSizeRemarkInfo(M, FunctionToInstrCount);
1807
1808 // Outline each of the candidates and return true if something was outlined.
1809 bool OutlinedSomething =
1810 outline(M, FunctionList, *Mapper, OutlinedFunctionNum);
1811
1812 // If we outlined something, we definitely changed the MI count of the
1813 // module. If we've asked for size remarks, then output them.
1814 // FIXME: This should be in the pass manager.
1815 if (ShouldEmitSizeRemarks && OutlinedSomething)
1816 emitInstrCountChangedRemark(M, FunctionToInstrCount);
1817
1818 LLVM_DEBUG({
1819 if (!OutlinedSomething)
1820 dbgs() << "Stopped outlining at iteration " << OutlineRepeatedNum
1821 << " because no changes were found.\n";
1822 });
1823
1824 return OutlinedSomething;
1825}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file defines the DenseMap class.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
A set of register units.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
static bool allowPGOOutlining(RunOutliner RunOutlinerMode, const ProfileSummaryInfo *PSI, const BlockFrequencyInfo *BFI, MachineBasicBlock &MBB)
static SmallVector< std::vector< Candidate > > partitionCandidatesByInputSection(std::vector< Candidate > &Candidates)
static StringRef getCandidateInputSection(const Candidate &C)
static stable_hash hashInstruction(const MachineInstr &MI)
static SmallVector< MatchedEntry > getMatchedEntries(InstructionMapper &Mapper, const OutlinedHashTree &HashTree)
Contains all data structures shared between the outliner implemented in MachineOutliner....
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
This is the interface to build a ModuleSummaryIndex for a module.
static Expected< Function * > createOutlinedFunction(OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, const OpenMPIRBuilder::TargetKernelDefaultAttrs &DefaultAttrs, StringRef FuncName, SmallVectorImpl< Value * > &Inputs, OpenMPIRBuilder::TargetBodyGenCallbackTy &CBFunc, OpenMPIRBuilder::TargetGenArgAccessorsCallbackTy &ArgAccessorFuncCB, DebugLoc OutlinedFnLoc)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
Func MI getDebugLoc()))
This file defines the SmallSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Target-Independent Code Generator Pass Configuration Options pass.
Value * RHS
Value * LHS
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI std::optional< uint64_t > getBlockProfileCount(const BasicBlock *BB) const
Returns the estimated profile count of BB.
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
Definition DebugLoc.cpp:186
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
StringRef getSection() const
Get the custom section of this global if it has one.
bool hasSection() const
Check if this global has a custom object file section.
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
bool hasAddressTaken() const
Test whether this block is used as something other than the target of a terminator,...
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
unsigned getInstructionCount() const
Return the number of MachineInstrs in this MachineFunction.
unsigned addFrameInst(const MCCFIInstruction &Inst)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const std::vector< MCCFIInstruction > & getFrameInstructions() const
Returns a reference to a list of cfi instructions in the function's prologue.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool exposesReturnsTwice() const
exposesReturnsTwice - Returns true if the function calls setjmp or any other similar functions with a...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineBasicBlock & front() const
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
Representation of each machine instruction.
bool isDebugInstr() const
LLVM_ABI void dropMemRefs(MachineFunction &MF)
Clear this MachineInstr's memory reference descriptor list.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
bool isBundledWithSucc() const
Return true if this instruction is part of a bundle, and it is not the last instruction in the bundle...
LLVM_ABI void clearKillInfo()
Clears kill flags on all operands.
void setDebugLoc(DebugLoc DL)
Replace current source information with new such.
This class contains meta information specific to a module.
LLVM_ABI MachineFunction & getOrCreateMachineFunction(Function &F)
Returns the MachineFunction constructed for the IR function F.
LLVM_ABI MachineFunction * getMachineFunction(const Function &F) const
Returns the MachineFunction associated to IR function F if there is one, otherwise nullptr.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
Diagnostic information for missed-optimization remarks.
LLVM_ABI void freezeReservedRegs()
freezeReservedRegs - Called by the register allocator to freeze the set of reserved registers before ...
const TargetRegisterInfo * getTargetRegisterInfo() const
LLVM_ABI void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Definition Mangler.cpp:121
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:253
void clear()
Release all hash nodes except the root hash node.
LLVM_ABI std::optional< unsigned > find(const HashSequence &Sequence) const
const HashNode * getRoot() const
LLVM_ABI void insert(const HashSequencePair &SequencePair)
Inserts a Sequence into the this tree.
Analysis providing profile information.
LLVM_ABI uint64_t getOrCompColdCountThreshold() const
Returns ColdCountThreshold if set.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator end()
Definition StringMap.h:214
iterator find(StringRef Key)
Definition StringMap.h:227
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
virtual size_t clearLinkerOptimizationHints(const SmallPtrSetImpl< MachineInstr * > &MIs) const
Remove all Linker Optimization Hints (LOH) associated with instructions in MIs and.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
constexpr MCPhysReg SP
SmallVector< const MachineInstr * > InstrList
const OutlinedHashTree * getOutlinedHashTree(const cl::LibraryOptionsContext &LibraryOptions)
bool hasOutlinedHashTree(const cl::LibraryOptionsContext &LibraryOptions)
bool emitCGData(const cl::LibraryOptionsContext &LibraryOptions)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
@ Length
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
uint64_t stable_hash
An opaque object representing a stable hash code.
LLVM_ABI stable_hash stableHashValue(const MachineOperand &MO, bool SourceQualifyLocalGlobals=false)
bool hasNItemsOrMore(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;}, std::enable_if_t< !std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< std::remove_reference_t< decltype(Begin)> >::iterator_category >::value, void > *=nullptr)
Return true if the sequence [Begin, End) has N or more items.
Definition STLExtras.h:2659
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
UWTableKind
Definition CodeGen.h:362
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
MachineBasicBlock::instr_iterator getBundleEnd(MachineBasicBlock::instr_iterator I)
Returns an iterator pointing beyond the bundle containing I.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
LLVM_ABI ModulePass * createMachineOutlinerPass(RunOutliner RunOutlinerMode)
This pass performs outlining on machine instructions directly before printing assembly.
@ Other
Any other memory.
Definition ModRef.h:68
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
stable_hash stable_hash_combine(ArrayRef< stable_hash > Buffer)
LLVM_ABI GlobalVariable * embedBufferInModule(Module &M, MemoryBufferRef Buf, StringRef SectionName, Align Alignment=Align(1), bool SectionExclude=true)
Embed the memory buffer Buf into the module M as a global using the specified section name.
LLVM_ABI void addLiveIns(MachineBasicBlock &MBB, const LivePhysRegs &LiveRegs)
Adds registers contained in LiveRegs to the block live-in list of MBB.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
LLVM_ABI std::string getCodeGenDataSectionName(CGDataSectKind CGSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
#define MORE()
Definition regcomp.c:247
MatchedEntry()=delete
MatchedEntry(unsigned StartIdx, unsigned EndIdx, unsigned Count)
A HashNode is an entry in an OutlinedHashTree, holding a hash value and a collection of Successors (o...
std::optional< unsigned > Terminals
The number of terminals in the sequence ending at this node.
An individual sequence of instructions to be replaced with a call to an outlined function.
MachineFunction * getMF() const
The information necessary to create an outlined function for some class of candidate.