LLVM  10.0.0
X86PadShortFunction.cpp
Go to the documentation of this file.
1 //===-------- X86PadShortFunction.cpp - pad short functions -----------===//
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 // This file defines the pass which will pad short functions to prevent
10 // a stall if a function returns before the return address is ready. This
11 // is needed for some Intel Atom processors.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 
16 #include "X86.h"
17 #include "X86InstrInfo.h"
18 #include "X86Subtarget.h"
19 #include "llvm/ADT/Statistic.h"
25 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/Support/Debug.h"
30 
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "x86-pad-short-functions"
34 
35 STATISTIC(NumBBsPadded, "Number of basic blocks padded");
36 
37 namespace {
38  struct VisitedBBInfo {
39  // HasReturn - Whether the BB contains a return instruction
40  bool HasReturn;
41 
42  // Cycles - Number of cycles until return if HasReturn is true, otherwise
43  // number of cycles until end of the BB
44  unsigned int Cycles;
45 
46  VisitedBBInfo() : HasReturn(false), Cycles(0) {}
47  VisitedBBInfo(bool HasReturn, unsigned int Cycles)
48  : HasReturn(HasReturn), Cycles(Cycles) {}
49  };
50 
51  struct PadShortFunc : public MachineFunctionPass {
52  static char ID;
53  PadShortFunc() : MachineFunctionPass(ID)
54  , Threshold(4) {}
55 
56  bool runOnMachineFunction(MachineFunction &MF) override;
57 
58  void getAnalysisUsage(AnalysisUsage &AU) const override {
62  }
63 
64  MachineFunctionProperties getRequiredProperties() const override {
67  }
68 
69  StringRef getPassName() const override {
70  return "X86 Atom pad short functions";
71  }
72 
73  private:
74  void findReturns(MachineBasicBlock *MBB,
75  unsigned int Cycles = 0);
76 
77  bool cyclesUntilReturn(MachineBasicBlock *MBB,
78  unsigned int &Cycles);
79 
80  void addPadding(MachineBasicBlock *MBB,
82  unsigned int NOOPsToAdd);
83 
84  const unsigned int Threshold;
85 
86  // ReturnBBs - Maps basic blocks that return to the minimum number of
87  // cycles until the return, starting from the entry block.
89 
90  // VisitedBBs - Cache of previously visited BBs.
92 
93  TargetSchedModel TSM;
94  };
95 
96  char PadShortFunc::ID = 0;
97 }
98 
100  return new PadShortFunc();
101 }
102 
103 /// runOnMachineFunction - Loop over all of the basic blocks, inserting
104 /// NOOP instructions before early exits.
105 bool PadShortFunc::runOnMachineFunction(MachineFunction &MF) {
106  if (skipFunction(MF.getFunction()))
107  return false;
108 
109  if (MF.getFunction().hasOptSize())
110  return false;
111 
113  return false;
114 
115  TSM.init(&MF.getSubtarget());
116 
117  auto *PSI =
118  &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
119  auto *MBFI = (PSI && PSI->hasProfileSummary()) ?
120  &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI() :
121  nullptr;
122 
123  // Search through basic blocks and mark the ones that have early returns
124  ReturnBBs.clear();
125  VisitedBBs.clear();
126  findReturns(&MF.front());
127 
128  bool MadeChange = false;
129 
130  // Pad the identified basic blocks with NOOPs
132  I != ReturnBBs.end(); ++I) {
133  MachineBasicBlock *MBB = I->first;
134  unsigned Cycles = I->second;
135 
136  // Function::hasOptSize is already checked above.
137  bool OptForSize = llvm::shouldOptimizeForSize(MBB, PSI, MBFI);
138  if (OptForSize)
139  continue;
140 
141  if (Cycles < Threshold) {
142  // BB ends in a return. Skip over any DBG_VALUE instructions
143  // trailing the terminator.
144  assert(MBB->size() > 0 &&
145  "Basic block should contain at least a RET but is empty");
146  MachineBasicBlock::iterator ReturnLoc = --MBB->end();
147 
148  while (ReturnLoc->isDebugInstr())
149  --ReturnLoc;
150  assert(ReturnLoc->isReturn() && !ReturnLoc->isCall() &&
151  "Basic block does not end with RET");
152 
153  addPadding(MBB, ReturnLoc, Threshold - Cycles);
154  NumBBsPadded++;
155  MadeChange = true;
156  }
157  }
158 
159  return MadeChange;
160 }
161 
162 /// findReturn - Starting at MBB, follow control flow and add all
163 /// basic blocks that contain a return to ReturnBBs.
164 void PadShortFunc::findReturns(MachineBasicBlock *MBB, unsigned int Cycles) {
165  // If this BB has a return, note how many cycles it takes to get there.
166  bool hasReturn = cyclesUntilReturn(MBB, Cycles);
167  if (Cycles >= Threshold)
168  return;
169 
170  if (hasReturn) {
171  ReturnBBs[MBB] = std::max(ReturnBBs[MBB], Cycles);
172  return;
173  }
174 
175  // Follow branches in BB and look for returns
177  I != MBB->succ_end(); ++I) {
178  if (*I == MBB)
179  continue;
180  findReturns(*I, Cycles);
181  }
182 }
183 
184 /// cyclesUntilReturn - return true if the MBB has a return instruction,
185 /// and return false otherwise.
186 /// Cycles will be incremented by the number of cycles taken to reach the
187 /// return or the end of the BB, whichever occurs first.
188 bool PadShortFunc::cyclesUntilReturn(MachineBasicBlock *MBB,
189  unsigned int &Cycles) {
190  // Return cached result if BB was previously visited
192  = VisitedBBs.find(MBB);
193  if (it != VisitedBBs.end()) {
194  VisitedBBInfo BBInfo = it->second;
195  Cycles += BBInfo.Cycles;
196  return BBInfo.HasReturn;
197  }
198 
199  unsigned int CyclesToEnd = 0;
200 
201  for (MachineInstr &MI : *MBB) {
202  // Mark basic blocks with a return instruction. Calls to other
203  // functions do not count because the called function will be padded,
204  // if necessary.
205  if (MI.isReturn() && !MI.isCall()) {
206  VisitedBBs[MBB] = VisitedBBInfo(true, CyclesToEnd);
207  Cycles += CyclesToEnd;
208  return true;
209  }
210 
211  CyclesToEnd += TSM.computeInstrLatency(&MI);
212  }
213 
214  VisitedBBs[MBB] = VisitedBBInfo(false, CyclesToEnd);
215  Cycles += CyclesToEnd;
216  return false;
217 }
218 
219 /// addPadding - Add the given number of NOOP instructions to the function
220 /// just prior to the return at MBBI
223  unsigned int NOOPsToAdd) {
224  DebugLoc DL = MBBI->getDebugLoc();
225  unsigned IssueWidth = TSM.getIssueWidth();
226 
227  for (unsigned i = 0, e = IssueWidth * NOOPsToAdd; i != e; ++i)
228  BuildMI(*MBB, MBBI, DL, TSM.getInstrInfo()->get(X86::NOOP));
229 }
This class represents lattice values for constants.
Definition: AllocatorList.h:23
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition: Function.h:633
STATISTIC(NumFunctions, "Total number of functions")
A debug info location.
Definition: DebugLoc.h:33
AnalysisUsage & addRequired()
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Provide an instruction scheduling machine model to CodeGen passes.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
bool padShortFunctions() const
Definition: X86Subtarget.h:676
FunctionPass * createX86PadShortFunctions()
Return a pass that pads short functions with NOOPs.
===- LazyMachineBlockFrequencyInfo.h - Lazy Block Frequency -*- C++ -*–===//
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1174
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
This is an alternative analysis pass to MachineBlockFrequencyInfo.
Represent the analysis usage information of a pass.
constexpr double e
Definition: MathExtras.h:57
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:282
const MachineBasicBlock & front() const
static bool hasReturn(const MachineBasicBlock &MBB)
Returns true if MBB contains an instruction that returns.
static void addPadding(BinaryStreamWriter &Writer)
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:390
const Function & getFunction() const
Return the LLVM function that this machine code represents.
bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile...
static cl::opt< unsigned > Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), cl::init(100), cl::Hidden)
MachineFunctionProperties & set(Property P)
Representation of each machine instruction.
Definition: MachineInstr.h:63
#define I(x, y, z)
Definition: MD5.cpp:58
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
std::vector< MachineBasicBlock * >::iterator succ_iterator
Properties which a MachineFunction may have at a given point in time.