1 //===-------- X86PadShortFunction.cpp - pad short functions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the pass which will pad short functions to prevent
11 // a stall if a function returns before the return address is ready. This
12 // is needed for some Intel Atom processors.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include <algorithm>
17 
18 #include "X86.h"
19 #include "X86InstrInfo.h"
20 #include "X86Subtarget.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Target/TargetInstrInfo.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), STI(nullptr), TII(nullptr) {}
55 
56     bool runOnMachineFunction(MachineFunction &MF) override;
57 
58     MachineFunctionProperties getRequiredProperties() const override {
59       return MachineFunctionProperties().set(
60           MachineFunctionProperties::Property::AllVRegsAllocated);
61     }
62 
63     const char *getPassName() const override {
64       return "X86 Atom pad short functions";
65     }
66 
67   private:
68     void findReturns(MachineBasicBlock *MBB,
69                      unsigned int Cycles = 0);
70 
71     bool cyclesUntilReturn(MachineBasicBlock *MBB,
72                            unsigned int &Cycles);
73 
74     void addPadding(MachineBasicBlock *MBB,
75                     MachineBasicBlock::iterator &MBBI,
76                     unsigned int NOOPsToAdd);
77 
78     const unsigned int Threshold;
79 
80     // ReturnBBs - Maps basic blocks that return to the minimum number of
81     // cycles until the return, starting from the entry block.
82     DenseMap<MachineBasicBlock*, unsigned int> ReturnBBs;
83 
84     // VisitedBBs - Cache of previously visited BBs.
85     DenseMap<MachineBasicBlock*, VisitedBBInfo> VisitedBBs;
86 
87     const X86Subtarget *STI;
88     const TargetInstrInfo *TII;
89   };
90 
91   char PadShortFunc::ID = 0;
92 }
93 
94 FunctionPass *llvm::createX86PadShortFunctions() {
95   return new PadShortFunc();
96 }
97 
98 /// runOnMachineFunction - Loop over all of the basic blocks, inserting
99 /// NOOP instructions before early exits.
100 bool PadShortFunc::runOnMachineFunction(MachineFunction &MF) {
101   if (MF.getFunction()->optForSize()) {
102     return false;
103   }
104 
105   STI = &MF.getSubtarget<X86Subtarget>();
106   if (!STI->padShortFunctions())
107     return false;
108 
109   TII = STI->getInstrInfo();
110 
111   // Search through basic blocks and mark the ones that have early returns
112   ReturnBBs.clear();
113   VisitedBBs.clear();
114   findReturns(&MF.front());
115 
116   bool MadeChange = false;
117 
118   MachineBasicBlock *MBB;
119   unsigned int Cycles = 0;
120 
121   // Pad the identified basic blocks with NOOPs
122   for (DenseMap<MachineBasicBlock*, unsigned int>::iterator I = ReturnBBs.begin();
123        I != ReturnBBs.end(); ++I) {
124     MBB = I->first;
125     Cycles = I->second;
126 
127     if (Cycles < Threshold) {
128       // BB ends in a return. Skip over any DBG_VALUE instructions
129       // trailing the terminator.
130       assert(MBB->size() > 0 &&
131              "Basic block should contain at least a RET but is empty");
132       MachineBasicBlock::iterator ReturnLoc = --MBB->end();
133 
134       while (ReturnLoc->isDebugValue())
135         --ReturnLoc;
136       assert(ReturnLoc->isReturn() && !ReturnLoc->isCall() &&
137              "Basic block does not end with RET");
138 
139       addPadding(MBB, ReturnLoc, Threshold - Cycles);
140       NumBBsPadded++;
141       MadeChange = true;
142     }
143   }
144 
145   return MadeChange;
146 }
147 
148 /// findReturn - Starting at MBB, follow control flow and add all
149 /// basic blocks that contain a return to ReturnBBs.
150 void PadShortFunc::findReturns(MachineBasicBlock *MBB, unsigned int Cycles) {
151   // If this BB has a return, note how many cycles it takes to get there.
152   bool hasReturn = cyclesUntilReturn(MBB, Cycles);
153   if (Cycles >= Threshold)
154     return;
155 
156   if (hasReturn) {
157     ReturnBBs[MBB] = std::max(ReturnBBs[MBB], Cycles);
158     return;
159   }
160 
161   // Follow branches in BB and look for returns
162   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin();
163        I != MBB->succ_end(); ++I) {
164     if (*I == MBB)
165       continue;
166     findReturns(*I, Cycles);
167   }
168 }
169 
170 /// cyclesUntilReturn - return true if the MBB has a return instruction,
171 /// and return false otherwise.
172 /// Cycles will be incremented by the number of cycles taken to reach the
173 /// return or the end of the BB, whichever occurs first.
174 bool PadShortFunc::cyclesUntilReturn(MachineBasicBlock *MBB,
175                                      unsigned int &Cycles) {
176   // Return cached result if BB was previously visited
177   DenseMap<MachineBasicBlock*, VisitedBBInfo>::iterator it
178     = VisitedBBs.find(MBB);
179   if (it != VisitedBBs.end()) {
180     VisitedBBInfo BBInfo = it->second;
181     Cycles += BBInfo.Cycles;
182     return BBInfo.HasReturn;
183   }
184 
185   unsigned int CyclesToEnd = 0;
186 
187   for (MachineBasicBlock::iterator MBBI = MBB->begin();
188         MBBI != MBB->end(); ++MBBI) {
189     MachineInstr *MI = MBBI;
190     // Mark basic blocks with a return instruction. Calls to other
191     // functions do not count because the called function will be padded,
192     // if necessary.
193     if (MI->isReturn() && !MI->isCall()) {
194       VisitedBBs[MBB] = VisitedBBInfo(true, CyclesToEnd);
195       Cycles += CyclesToEnd;
196       return true;
197     }
198 
199     CyclesToEnd += TII->getInstrLatency(STI->getInstrItineraryData(), MI);
200   }
201 
202   VisitedBBs[MBB] = VisitedBBInfo(false, CyclesToEnd);
203   Cycles += CyclesToEnd;
204   return false;
205 }
206 
207 /// addPadding - Add the given number of NOOP instructions to the function
208 /// just prior to the return at MBBI
209 void PadShortFunc::addPadding(MachineBasicBlock *MBB,
210                               MachineBasicBlock::iterator &MBBI,
211                               unsigned int NOOPsToAdd) {
212   DebugLoc DL = MBBI->getDebugLoc();
213 
214   while (NOOPsToAdd-- > 0) {
215     BuildMI(*MBB, MBBI, DL, TII->get(X86::NOOP));
216     BuildMI(*MBB, MBBI, DL, TII->get(X86::NOOP));
217   }
218 }
219