xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/MachineModuleInfo.cpp (revision c8c62548bffb83f3d25e062929c45d66fea755f1)
1  //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- 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  #include "llvm/CodeGen/MachineModuleInfo.h"
10  #include "llvm/ADT/ArrayRef.h"
11  #include "llvm/ADT/DenseMap.h"
12  #include "llvm/ADT/PostOrderIterator.h"
13  #include "llvm/ADT/StringRef.h"
14  #include "llvm/ADT/TinyPtrVector.h"
15  #include "llvm/CodeGen/MachineFunction.h"
16  #include "llvm/CodeGen/Passes.h"
17  #include "llvm/IR/BasicBlock.h"
18  #include "llvm/IR/DerivedTypes.h"
19  #include "llvm/IR/Instructions.h"
20  #include "llvm/IR/Module.h"
21  #include "llvm/IR/Value.h"
22  #include "llvm/IR/ValueHandle.h"
23  #include "llvm/InitializePasses.h"
24  #include "llvm/MC/MCContext.h"
25  #include "llvm/MC/MCSymbol.h"
26  #include "llvm/MC/MCSymbolXCOFF.h"
27  #include "llvm/Pass.h"
28  #include "llvm/Support/Casting.h"
29  #include "llvm/Support/ErrorHandling.h"
30  #include "llvm/Target/TargetLoweringObjectFile.h"
31  #include "llvm/Target/TargetMachine.h"
32  #include <algorithm>
33  #include <cassert>
34  #include <memory>
35  #include <utility>
36  #include <vector>
37  
38  using namespace llvm;
39  using namespace llvm::dwarf;
40  
41  // Out of line virtual method.
42  MachineModuleInfoImpl::~MachineModuleInfoImpl() = default;
43  
44  namespace llvm {
45  
46  class MMIAddrLabelMapCallbackPtr final : CallbackVH {
47    MMIAddrLabelMap *Map = nullptr;
48  
49  public:
50    MMIAddrLabelMapCallbackPtr() = default;
51    MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V) {}
52  
53    void setPtr(BasicBlock *BB) {
54      ValueHandleBase::operator=(BB);
55    }
56  
57    void setMap(MMIAddrLabelMap *map) { Map = map; }
58  
59    void deleted() override;
60    void allUsesReplacedWith(Value *V2) override;
61  };
62  
63  class MMIAddrLabelMap {
64    MCContext &Context;
65    struct AddrLabelSymEntry {
66      /// The symbols for the label.
67      TinyPtrVector<MCSymbol *> Symbols;
68  
69      Function *Fn;   // The containing function of the BasicBlock.
70      unsigned Index; // The index in BBCallbacks for the BasicBlock.
71    };
72  
73    DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
74  
75    /// Callbacks for the BasicBlock's that we have entries for.  We use this so
76    /// we get notified if a block is deleted or RAUWd.
77    std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
78  
79  public:
80    MMIAddrLabelMap(MCContext &context) : Context(context) {}
81  
82    ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
83  
84    void UpdateForDeletedBlock(BasicBlock *BB);
85    void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
86  };
87  
88  } // end namespace llvm
89  
90  ArrayRef<MCSymbol *> MMIAddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) {
91    assert(BB->hasAddressTaken() &&
92           "Shouldn't get label for block without address taken");
93    AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
94  
95    // If we already had an entry for this block, just return it.
96    if (!Entry.Symbols.empty()) {
97      assert(BB->getParent() == Entry.Fn && "Parent changed");
98      return Entry.Symbols;
99    }
100  
101    // Otherwise, this is a new entry, create a new symbol for it and add an
102    // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
103    BBCallbacks.emplace_back(BB);
104    BBCallbacks.back().setMap(this);
105    Entry.Index = BBCallbacks.size() - 1;
106    Entry.Fn = BB->getParent();
107    MCSymbol *Sym = Context.createTempSymbol(!BB->hasAddressTaken());
108    Entry.Symbols.push_back(Sym);
109    return Entry.Symbols;
110  }
111  
112  void MMIAddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
113    // If the block got deleted, there is no need for the symbol.  If the symbol
114    // was already emitted, we can just forget about it, otherwise we need to
115    // queue it up for later emission when the function is output.
116    AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
117    AddrLabelSymbols.erase(BB);
118    assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
119    BBCallbacks[Entry.Index] = nullptr;  // Clear the callback.
120  
121    assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
122           "Block/parent mismatch");
123  
124    assert(llvm::all_of(Entry.Symbols, [](MCSymbol *Sym) {
125      return Sym->isDefined(); }));
126  }
127  
128  void MMIAddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
129    // Get the entry for the RAUW'd block and remove it from our map.
130    AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
131    AddrLabelSymbols.erase(Old);
132    assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
133  
134    AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
135  
136    // If New is not address taken, just move our symbol over to it.
137    if (NewEntry.Symbols.empty()) {
138      BBCallbacks[OldEntry.Index].setPtr(New);    // Update the callback.
139      NewEntry = std::move(OldEntry);             // Set New's entry.
140      return;
141    }
142  
143    BBCallbacks[OldEntry.Index] = nullptr;    // Update the callback.
144  
145    // Otherwise, we need to add the old symbols to the new block's set.
146    NewEntry.Symbols.insert(NewEntry.Symbols.end(), OldEntry.Symbols.begin(),
147                            OldEntry.Symbols.end());
148  }
149  
150  void MMIAddrLabelMapCallbackPtr::deleted() {
151    Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
152  }
153  
154  void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
155    Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
156  }
157  
158  void MachineModuleInfo::initialize() {
159    ObjFileMMI = nullptr;
160    CurCallSite = 0;
161    UsesMSVCFloatingPoint = UsesMorestackAddr = false;
162    HasSplitStack = HasNosplitStack = false;
163    AddrLabelSymbols = nullptr;
164  }
165  
166  void MachineModuleInfo::finalize() {
167    Personalities.clear();
168  
169    delete AddrLabelSymbols;
170    AddrLabelSymbols = nullptr;
171  
172    Context.reset();
173  
174    delete ObjFileMMI;
175    ObjFileMMI = nullptr;
176  }
177  
178  MachineModuleInfo::MachineModuleInfo(MachineModuleInfo &&MMI)
179      : TM(std::move(MMI.TM)),
180        Context(MMI.TM.getMCAsmInfo(), MMI.TM.getMCRegisterInfo(),
181                MMI.TM.getObjFileLowering(), nullptr, nullptr, false) {
182    ObjFileMMI = MMI.ObjFileMMI;
183    CurCallSite = MMI.CurCallSite;
184    UsesMSVCFloatingPoint = MMI.UsesMSVCFloatingPoint;
185    UsesMorestackAddr = MMI.UsesMorestackAddr;
186    HasSplitStack = MMI.HasSplitStack;
187    HasNosplitStack = MMI.HasNosplitStack;
188    AddrLabelSymbols = MMI.AddrLabelSymbols;
189    TheModule = MMI.TheModule;
190  }
191  
192  MachineModuleInfo::MachineModuleInfo(const LLVMTargetMachine *TM)
193      : TM(*TM), Context(TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
194                         TM->getObjFileLowering(), nullptr, nullptr, false) {
195    initialize();
196  }
197  
198  MachineModuleInfo::~MachineModuleInfo() { finalize(); }
199  
200  //===- Address of Block Management ----------------------------------------===//
201  
202  ArrayRef<MCSymbol *>
203  MachineModuleInfo::getAddrLabelSymbolToEmit(const BasicBlock *BB) {
204    // Lazily create AddrLabelSymbols.
205    if (!AddrLabelSymbols)
206      AddrLabelSymbols = new MMIAddrLabelMap(Context);
207   return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
208  }
209  
210  /// \name Exception Handling
211  /// \{
212  
213  void MachineModuleInfo::addPersonality(const Function *Personality) {
214    for (unsigned i = 0; i < Personalities.size(); ++i)
215      if (Personalities[i] == Personality)
216        return;
217    Personalities.push_back(Personality);
218  }
219  
220  /// \}
221  
222  MachineFunction *
223  MachineModuleInfo::getMachineFunction(const Function &F) const {
224    auto I = MachineFunctions.find(&F);
225    return I != MachineFunctions.end() ? I->second.get() : nullptr;
226  }
227  
228  MachineFunction &MachineModuleInfo::getOrCreateMachineFunction(Function &F) {
229    // Shortcut for the common case where a sequence of MachineFunctionPasses
230    // all query for the same Function.
231    if (LastRequest == &F)
232      return *LastResult;
233  
234    auto I = MachineFunctions.insert(
235        std::make_pair(&F, std::unique_ptr<MachineFunction>()));
236    MachineFunction *MF;
237    if (I.second) {
238      // No pre-existing machine function, create a new one.
239      const TargetSubtargetInfo &STI = *TM.getSubtargetImpl(F);
240      MF = new MachineFunction(F, TM, STI, NextFnNum++, *this);
241      // Update the set entry.
242      I.first->second.reset(MF);
243    } else {
244      MF = I.first->second.get();
245    }
246  
247    LastRequest = &F;
248    LastResult = MF;
249    return *MF;
250  }
251  
252  void MachineModuleInfo::deleteMachineFunctionFor(Function &F) {
253    MachineFunctions.erase(&F);
254    LastRequest = nullptr;
255    LastResult = nullptr;
256  }
257  
258  namespace {
259  
260  /// This pass frees the MachineFunction object associated with a Function.
261  class FreeMachineFunction : public FunctionPass {
262  public:
263    static char ID;
264  
265    FreeMachineFunction() : FunctionPass(ID) {}
266  
267    void getAnalysisUsage(AnalysisUsage &AU) const override {
268      AU.addRequired<MachineModuleInfoWrapperPass>();
269      AU.addPreserved<MachineModuleInfoWrapperPass>();
270    }
271  
272    bool runOnFunction(Function &F) override {
273      MachineModuleInfo &MMI =
274          getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
275      MMI.deleteMachineFunctionFor(F);
276      return true;
277    }
278  
279    StringRef getPassName() const override {
280      return "Free MachineFunction";
281    }
282  };
283  
284  } // end anonymous namespace
285  
286  char FreeMachineFunction::ID;
287  
288  FunctionPass *llvm::createFreeMachineFunctionPass() {
289    return new FreeMachineFunction();
290  }
291  
292  MachineModuleInfoWrapperPass::MachineModuleInfoWrapperPass(
293      const LLVMTargetMachine *TM)
294      : ImmutablePass(ID), MMI(TM) {
295    initializeMachineModuleInfoWrapperPassPass(*PassRegistry::getPassRegistry());
296  }
297  
298  // Handle the Pass registration stuff necessary to use DataLayout's.
299  INITIALIZE_PASS(MachineModuleInfoWrapperPass, "machinemoduleinfo",
300                  "Machine Module Information", false, false)
301  char MachineModuleInfoWrapperPass::ID = 0;
302  
303  bool MachineModuleInfoWrapperPass::doInitialization(Module &M) {
304    MMI.initialize();
305    MMI.TheModule = &M;
306    MMI.DbgInfoAvailable = !M.debug_compile_units().empty();
307    return false;
308  }
309  
310  bool MachineModuleInfoWrapperPass::doFinalization(Module &M) {
311    MMI.finalize();
312    return false;
313  }
314  
315  AnalysisKey MachineModuleAnalysis::Key;
316  
317  MachineModuleInfo MachineModuleAnalysis::run(Module &M,
318                                               ModuleAnalysisManager &) {
319    MachineModuleInfo MMI(TM);
320    MMI.TheModule = &M;
321    MMI.DbgInfoAvailable = !M.debug_compile_units().empty();
322    return MMI;
323  }
324