MachineModuleInfo.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. #include "llvm/CodeGen/MachineModuleInfo.h"
  9. #include "llvm/ADT/ArrayRef.h"
  10. #include "llvm/ADT/DenseMap.h"
  11. #include "llvm/ADT/PostOrderIterator.h"
  12. #include "llvm/ADT/StringRef.h"
  13. #include "llvm/ADT/TinyPtrVector.h"
  14. #include "llvm/CodeGen/MachineFunction.h"
  15. #include "llvm/CodeGen/Passes.h"
  16. #include "llvm/IR/BasicBlock.h"
  17. #include "llvm/IR/DerivedTypes.h"
  18. #include "llvm/IR/DiagnosticInfo.h"
  19. #include "llvm/IR/Instructions.h"
  20. #include "llvm/IR/LLVMContext.h"
  21. #include "llvm/IR/Module.h"
  22. #include "llvm/IR/Value.h"
  23. #include "llvm/IR/ValueHandle.h"
  24. #include "llvm/InitializePasses.h"
  25. #include "llvm/MC/MCContext.h"
  26. #include "llvm/MC/MCSymbol.h"
  27. #include "llvm/MC/MCSymbolXCOFF.h"
  28. #include "llvm/Pass.h"
  29. #include "llvm/Support/Casting.h"
  30. #include "llvm/Support/ErrorHandling.h"
  31. #include "llvm/Target/TargetLoweringObjectFile.h"
  32. #include "llvm/Target/TargetMachine.h"
  33. #include <algorithm>
  34. #include <cassert>
  35. #include <memory>
  36. #include <utility>
  37. #include <vector>
  38. using namespace llvm;
  39. using namespace llvm::dwarf;
  40. // Out of line virtual method.
  41. MachineModuleInfoImpl::~MachineModuleInfoImpl() = default;
  42. namespace llvm {
  43. class MMIAddrLabelMapCallbackPtr final : CallbackVH {
  44. MMIAddrLabelMap *Map = nullptr;
  45. public:
  46. MMIAddrLabelMapCallbackPtr() = default;
  47. MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V) {}
  48. void setPtr(BasicBlock *BB) {
  49. ValueHandleBase::operator=(BB);
  50. }
  51. void setMap(MMIAddrLabelMap *map) { Map = map; }
  52. void deleted() override;
  53. void allUsesReplacedWith(Value *V2) override;
  54. };
  55. class MMIAddrLabelMap {
  56. MCContext &Context;
  57. struct AddrLabelSymEntry {
  58. /// The symbols for the label.
  59. TinyPtrVector<MCSymbol *> Symbols;
  60. Function *Fn; // The containing function of the BasicBlock.
  61. unsigned Index; // The index in BBCallbacks for the BasicBlock.
  62. };
  63. DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
  64. /// Callbacks for the BasicBlock's that we have entries for. We use this so
  65. /// we get notified if a block is deleted or RAUWd.
  66. std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
  67. /// This is a per-function list of symbols whose corresponding BasicBlock got
  68. /// deleted. These symbols need to be emitted at some point in the file, so
  69. /// AsmPrinter emits them after the function body.
  70. DenseMap<AssertingVH<Function>, std::vector<MCSymbol*>>
  71. DeletedAddrLabelsNeedingEmission;
  72. public:
  73. MMIAddrLabelMap(MCContext &context) : Context(context) {}
  74. ~MMIAddrLabelMap() {
  75. assert(DeletedAddrLabelsNeedingEmission.empty() &&
  76. "Some labels for deleted blocks never got emitted");
  77. }
  78. ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
  79. void takeDeletedSymbolsForFunction(Function *F,
  80. std::vector<MCSymbol*> &Result);
  81. void UpdateForDeletedBlock(BasicBlock *BB);
  82. void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
  83. };
  84. } // end namespace llvm
  85. ArrayRef<MCSymbol *> MMIAddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) {
  86. assert(BB->hasAddressTaken() &&
  87. "Shouldn't get label for block without address taken");
  88. AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
  89. // If we already had an entry for this block, just return it.
  90. if (!Entry.Symbols.empty()) {
  91. assert(BB->getParent() == Entry.Fn && "Parent changed");
  92. return Entry.Symbols;
  93. }
  94. // Otherwise, this is a new entry, create a new symbol for it and add an
  95. // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
  96. BBCallbacks.emplace_back(BB);
  97. BBCallbacks.back().setMap(this);
  98. Entry.Index = BBCallbacks.size() - 1;
  99. Entry.Fn = BB->getParent();
  100. MCSymbol *Sym = BB->hasAddressTaken() ? Context.createNamedTempSymbol()
  101. : Context.createTempSymbol();
  102. Entry.Symbols.push_back(Sym);
  103. return Entry.Symbols;
  104. }
  105. /// If we have any deleted symbols for F, return them.
  106. void MMIAddrLabelMap::
  107. takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
  108. DenseMap<AssertingVH<Function>, std::vector<MCSymbol*>>::iterator I =
  109. DeletedAddrLabelsNeedingEmission.find(F);
  110. // If there are no entries for the function, just return.
  111. if (I == DeletedAddrLabelsNeedingEmission.end()) return;
  112. // Otherwise, take the list.
  113. std::swap(Result, I->second);
  114. DeletedAddrLabelsNeedingEmission.erase(I);
  115. }
  116. void MMIAddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
  117. // If the block got deleted, there is no need for the symbol. If the symbol
  118. // was already emitted, we can just forget about it, otherwise we need to
  119. // queue it up for later emission when the function is output.
  120. AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
  121. AddrLabelSymbols.erase(BB);
  122. assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
  123. BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
  124. assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
  125. "Block/parent mismatch");
  126. for (MCSymbol *Sym : Entry.Symbols) {
  127. if (Sym->isDefined())
  128. return;
  129. // If the block is not yet defined, we need to emit it at the end of the
  130. // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
  131. // for the containing Function. Since the block is being deleted, its
  132. // parent may already be removed, we have to get the function from 'Entry'.
  133. DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
  134. }
  135. }
  136. void MMIAddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
  137. // Get the entry for the RAUW'd block and remove it from our map.
  138. AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
  139. AddrLabelSymbols.erase(Old);
  140. assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
  141. AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
  142. // If New is not address taken, just move our symbol over to it.
  143. if (NewEntry.Symbols.empty()) {
  144. BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
  145. NewEntry = std::move(OldEntry); // Set New's entry.
  146. return;
  147. }
  148. BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
  149. // Otherwise, we need to add the old symbols to the new block's set.
  150. llvm::append_range(NewEntry.Symbols, OldEntry.Symbols);
  151. }
  152. void MMIAddrLabelMapCallbackPtr::deleted() {
  153. Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
  154. }
  155. void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
  156. Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
  157. }
  158. void MachineModuleInfo::initialize() {
  159. ObjFileMMI = nullptr;
  160. CurCallSite = 0;
  161. NextFnNum = 0;
  162. UsesMSVCFloatingPoint = UsesMorestackAddr = false;
  163. HasSplitStack = HasNosplitStack = false;
  164. AddrLabelSymbols = nullptr;
  165. }
  166. void MachineModuleInfo::finalize() {
  167. Personalities.clear();
  168. delete AddrLabelSymbols;
  169. AddrLabelSymbols = nullptr;
  170. Context.reset();
  171. // We don't clear the ExternalContext.
  172. delete ObjFileMMI;
  173. ObjFileMMI = nullptr;
  174. }
  175. MachineModuleInfo::MachineModuleInfo(MachineModuleInfo &&MMI)
  176. : TM(std::move(MMI.TM)),
  177. Context(MMI.TM.getTargetTriple(), MMI.TM.getMCAsmInfo(),
  178. MMI.TM.getMCRegisterInfo(), MMI.TM.getMCSubtargetInfo(), nullptr,
  179. nullptr, false),
  180. MachineFunctions(std::move(MMI.MachineFunctions)) {
  181. Context.setObjectFileInfo(MMI.TM.getObjFileLowering());
  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. ExternalContext = MMI.ExternalContext;
  190. TheModule = MMI.TheModule;
  191. }
  192. MachineModuleInfo::MachineModuleInfo(const LLVMTargetMachine *TM)
  193. : TM(*TM), Context(TM->getTargetTriple(), TM->getMCAsmInfo(),
  194. TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(),
  195. nullptr, nullptr, false) {
  196. Context.setObjectFileInfo(TM->getObjFileLowering());
  197. initialize();
  198. }
  199. MachineModuleInfo::MachineModuleInfo(const LLVMTargetMachine *TM,
  200. MCContext *ExtContext)
  201. : TM(*TM), Context(TM->getTargetTriple(), TM->getMCAsmInfo(),
  202. TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(),
  203. nullptr, nullptr, false),
  204. ExternalContext(ExtContext) {
  205. Context.setObjectFileInfo(TM->getObjFileLowering());
  206. initialize();
  207. }
  208. MachineModuleInfo::~MachineModuleInfo() { finalize(); }
  209. //===- Address of Block Management ----------------------------------------===//
  210. ArrayRef<MCSymbol *>
  211. MachineModuleInfo::getAddrLabelSymbolToEmit(const BasicBlock *BB) {
  212. // Lazily create AddrLabelSymbols.
  213. if (!AddrLabelSymbols)
  214. AddrLabelSymbols = new MMIAddrLabelMap(getContext());
  215. return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
  216. }
  217. void MachineModuleInfo::
  218. takeDeletedSymbolsForFunction(const Function *F,
  219. std::vector<MCSymbol*> &Result) {
  220. // If no blocks have had their addresses taken, we're done.
  221. if (!AddrLabelSymbols) return;
  222. return AddrLabelSymbols->
  223. takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
  224. }
  225. /// \name Exception Handling
  226. /// \{
  227. void MachineModuleInfo::addPersonality(const Function *Personality) {
  228. if (!llvm::is_contained(Personalities, Personality))
  229. Personalities.push_back(Personality);
  230. }
  231. /// \}
  232. MachineFunction *
  233. MachineModuleInfo::getMachineFunction(const Function &F) const {
  234. auto I = MachineFunctions.find(&F);
  235. return I != MachineFunctions.end() ? I->second.get() : nullptr;
  236. }
  237. MachineFunction &MachineModuleInfo::getOrCreateMachineFunction(Function &F) {
  238. // Shortcut for the common case where a sequence of MachineFunctionPasses
  239. // all query for the same Function.
  240. if (LastRequest == &F)
  241. return *LastResult;
  242. auto I = MachineFunctions.insert(
  243. std::make_pair(&F, std::unique_ptr<MachineFunction>()));
  244. MachineFunction *MF;
  245. if (I.second) {
  246. // No pre-existing machine function, create a new one.
  247. const TargetSubtargetInfo &STI = *TM.getSubtargetImpl(F);
  248. MF = new MachineFunction(F, TM, STI, NextFnNum++, *this);
  249. // Update the set entry.
  250. I.first->second.reset(MF);
  251. } else {
  252. MF = I.first->second.get();
  253. }
  254. LastRequest = &F;
  255. LastResult = MF;
  256. return *MF;
  257. }
  258. void MachineModuleInfo::deleteMachineFunctionFor(Function &F) {
  259. MachineFunctions.erase(&F);
  260. LastRequest = nullptr;
  261. LastResult = nullptr;
  262. }
  263. namespace {
  264. /// This pass frees the MachineFunction object associated with a Function.
  265. class FreeMachineFunction : public FunctionPass {
  266. public:
  267. static char ID;
  268. FreeMachineFunction() : FunctionPass(ID) {}
  269. void getAnalysisUsage(AnalysisUsage &AU) const override {
  270. AU.addRequired<MachineModuleInfoWrapperPass>();
  271. AU.addPreserved<MachineModuleInfoWrapperPass>();
  272. }
  273. bool runOnFunction(Function &F) override {
  274. MachineModuleInfo &MMI =
  275. getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
  276. MMI.deleteMachineFunctionFor(F);
  277. return true;
  278. }
  279. StringRef getPassName() const override {
  280. return "Free MachineFunction";
  281. }
  282. };
  283. } // end anonymous namespace
  284. char FreeMachineFunction::ID;
  285. FunctionPass *llvm::createFreeMachineFunctionPass() {
  286. return new FreeMachineFunction();
  287. }
  288. MachineModuleInfoWrapperPass::MachineModuleInfoWrapperPass(
  289. const LLVMTargetMachine *TM)
  290. : ImmutablePass(ID), MMI(TM) {
  291. initializeMachineModuleInfoWrapperPassPass(*PassRegistry::getPassRegistry());
  292. }
  293. MachineModuleInfoWrapperPass::MachineModuleInfoWrapperPass(
  294. const LLVMTargetMachine *TM, MCContext *ExtContext)
  295. : ImmutablePass(ID), MMI(TM, ExtContext) {
  296. initializeMachineModuleInfoWrapperPassPass(*PassRegistry::getPassRegistry());
  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. static unsigned getLocCookie(const SMDiagnostic &SMD, const SourceMgr &SrcMgr,
  303. std::vector<const MDNode *> &LocInfos) {
  304. // Look up a LocInfo for the buffer this diagnostic is coming from.
  305. unsigned BufNum = SrcMgr.FindBufferContainingLoc(SMD.getLoc());
  306. const MDNode *LocInfo = nullptr;
  307. if (BufNum > 0 && BufNum <= LocInfos.size())
  308. LocInfo = LocInfos[BufNum - 1];
  309. // If the inline asm had metadata associated with it, pull out a location
  310. // cookie corresponding to which line the error occurred on.
  311. unsigned LocCookie = 0;
  312. if (LocInfo) {
  313. unsigned ErrorLine = SMD.getLineNo() - 1;
  314. if (ErrorLine >= LocInfo->getNumOperands())
  315. ErrorLine = 0;
  316. if (LocInfo->getNumOperands() != 0)
  317. if (const ConstantInt *CI =
  318. mdconst::dyn_extract<ConstantInt>(LocInfo->getOperand(ErrorLine)))
  319. LocCookie = CI->getZExtValue();
  320. }
  321. return LocCookie;
  322. }
  323. bool MachineModuleInfoWrapperPass::doInitialization(Module &M) {
  324. MMI.initialize();
  325. MMI.TheModule = &M;
  326. // FIXME: Do this for new pass manager.
  327. LLVMContext &Ctx = M.getContext();
  328. MMI.getContext().setDiagnosticHandler(
  329. [&Ctx, &M](const SMDiagnostic &SMD, bool IsInlineAsm,
  330. const SourceMgr &SrcMgr,
  331. std::vector<const MDNode *> &LocInfos) {
  332. unsigned LocCookie = 0;
  333. if (IsInlineAsm)
  334. LocCookie = getLocCookie(SMD, SrcMgr, LocInfos);
  335. Ctx.diagnose(
  336. DiagnosticInfoSrcMgr(SMD, M.getName(), IsInlineAsm, LocCookie));
  337. });
  338. MMI.DbgInfoAvailable = !M.debug_compile_units().empty();
  339. return false;
  340. }
  341. bool MachineModuleInfoWrapperPass::doFinalization(Module &M) {
  342. MMI.finalize();
  343. return false;
  344. }
  345. AnalysisKey MachineModuleAnalysis::Key;
  346. MachineModuleInfo MachineModuleAnalysis::run(Module &M,
  347. ModuleAnalysisManager &) {
  348. MachineModuleInfo MMI(TM);
  349. MMI.TheModule = &M;
  350. MMI.DbgInfoAvailable = !M.debug_compile_units().empty();
  351. return MMI;
  352. }