MachineModuleInfo.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- C++ -*-===//
  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. #include "llvm/CodeGen/MachineModuleInfo.h"
  10. #include "llvm/ADT/PointerUnion.h"
  11. #include "llvm/Analysis/LibCallSemantics.h"
  12. #include "llvm/Analysis/ValueTracking.h"
  13. #include "llvm/CodeGen/MachineFunction.h"
  14. #include "llvm/CodeGen/MachineFunctionPass.h"
  15. #include "llvm/CodeGen/Passes.h"
  16. #include "llvm/CodeGen/WinEHFuncInfo.h"
  17. #include "llvm/IR/Constants.h"
  18. #include "llvm/IR/DerivedTypes.h"
  19. #include "llvm/IR/GlobalVariable.h"
  20. #include "llvm/IR/Module.h"
  21. #include "llvm/MC/MCObjectFileInfo.h"
  22. #include "llvm/MC/MCSymbol.h"
  23. #include "llvm/Support/Dwarf.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. using namespace llvm;
  26. using namespace llvm::dwarf;
  27. // Handle the Pass registration stuff necessary to use DataLayout's.
  28. INITIALIZE_PASS(MachineModuleInfo, "machinemoduleinfo",
  29. "Machine Module Information", false, false)
  30. char MachineModuleInfo::ID = 0;
  31. // Out of line virtual method.
  32. MachineModuleInfoImpl::~MachineModuleInfoImpl() {}
  33. namespace llvm {
  34. class MMIAddrLabelMapCallbackPtr final : CallbackVH {
  35. MMIAddrLabelMap *Map;
  36. public:
  37. MMIAddrLabelMapCallbackPtr() : Map(nullptr) {}
  38. MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V), Map(nullptr) {}
  39. void setPtr(BasicBlock *BB) {
  40. ValueHandleBase::operator=(BB);
  41. }
  42. void setMap(MMIAddrLabelMap *map) { Map = map; }
  43. void deleted() override;
  44. void allUsesReplacedWith(Value *V2) override;
  45. };
  46. class MMIAddrLabelMap {
  47. MCContext &Context;
  48. struct AddrLabelSymEntry {
  49. /// Symbols - The symbols for the label.
  50. TinyPtrVector<MCSymbol *> Symbols;
  51. Function *Fn; // The containing function of the BasicBlock.
  52. unsigned Index; // The index in BBCallbacks for the BasicBlock.
  53. };
  54. DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
  55. /// BBCallbacks - Callbacks for the BasicBlock's that we have entries for. We
  56. /// use this so we get notified if a block is deleted or RAUWd.
  57. std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
  58. /// DeletedAddrLabelsNeedingEmission - This is a per-function list of symbols
  59. /// whose corresponding BasicBlock got deleted. These symbols need to be
  60. /// emitted at some point in the file, so AsmPrinter emits them after the
  61. /// function body.
  62. DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >
  63. DeletedAddrLabelsNeedingEmission;
  64. public:
  65. MMIAddrLabelMap(MCContext &context) : Context(context) {}
  66. ~MMIAddrLabelMap() {
  67. assert(DeletedAddrLabelsNeedingEmission.empty() &&
  68. "Some labels for deleted blocks never got emitted");
  69. }
  70. ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
  71. void takeDeletedSymbolsForFunction(Function *F,
  72. std::vector<MCSymbol*> &Result);
  73. void UpdateForDeletedBlock(BasicBlock *BB);
  74. void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
  75. };
  76. }
  77. ArrayRef<MCSymbol *> MMIAddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) {
  78. assert(BB->hasAddressTaken() &&
  79. "Shouldn't get label for block without address taken");
  80. AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
  81. // If we already had an entry for this block, just return it.
  82. if (!Entry.Symbols.empty()) {
  83. assert(BB->getParent() == Entry.Fn && "Parent changed");
  84. return Entry.Symbols;
  85. }
  86. // Otherwise, this is a new entry, create a new symbol for it and add an
  87. // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
  88. BBCallbacks.emplace_back(BB);
  89. BBCallbacks.back().setMap(this);
  90. Entry.Index = BBCallbacks.size() - 1;
  91. Entry.Fn = BB->getParent();
  92. Entry.Symbols.push_back(Context.createTempSymbol());
  93. return Entry.Symbols;
  94. }
  95. /// takeDeletedSymbolsForFunction - If we have any deleted symbols for F, return
  96. /// them.
  97. void MMIAddrLabelMap::
  98. takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
  99. DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >::iterator I =
  100. DeletedAddrLabelsNeedingEmission.find(F);
  101. // If there are no entries for the function, just return.
  102. if (I == DeletedAddrLabelsNeedingEmission.end()) return;
  103. // Otherwise, take the list.
  104. std::swap(Result, I->second);
  105. DeletedAddrLabelsNeedingEmission.erase(I);
  106. }
  107. void MMIAddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
  108. // If the block got deleted, there is no need for the symbol. If the symbol
  109. // was already emitted, we can just forget about it, otherwise we need to
  110. // queue it up for later emission when the function is output.
  111. AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
  112. AddrLabelSymbols.erase(BB);
  113. assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
  114. BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
  115. assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
  116. "Block/parent mismatch");
  117. for (MCSymbol *Sym : Entry.Symbols) {
  118. if (Sym->isDefined())
  119. return;
  120. // If the block is not yet defined, we need to emit it at the end of the
  121. // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
  122. // for the containing Function. Since the block is being deleted, its
  123. // parent may already be removed, we have to get the function from 'Entry'.
  124. DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
  125. }
  126. }
  127. void MMIAddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
  128. // Get the entry for the RAUW'd block and remove it from our map.
  129. AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
  130. AddrLabelSymbols.erase(Old);
  131. assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
  132. AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
  133. // If New is not address taken, just move our symbol over to it.
  134. if (NewEntry.Symbols.empty()) {
  135. BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
  136. NewEntry = std::move(OldEntry); // Set New's entry.
  137. return;
  138. }
  139. BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
  140. // Otherwise, we need to add the old symbols to the new block's set.
  141. NewEntry.Symbols.insert(NewEntry.Symbols.end(), OldEntry.Symbols.begin(),
  142. OldEntry.Symbols.end());
  143. }
  144. void MMIAddrLabelMapCallbackPtr::deleted() {
  145. Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
  146. }
  147. void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
  148. Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
  149. }
  150. //===----------------------------------------------------------------------===//
  151. MachineModuleInfo::MachineModuleInfo(const MCAsmInfo &MAI,
  152. const MCRegisterInfo &MRI,
  153. const MCObjectFileInfo *MOFI)
  154. : ImmutablePass(ID), Context(&MAI, &MRI, MOFI, nullptr, false) {
  155. initializeMachineModuleInfoPass(*PassRegistry::getPassRegistry());
  156. }
  157. MachineModuleInfo::MachineModuleInfo()
  158. : ImmutablePass(ID), Context(nullptr, nullptr, nullptr) {
  159. llvm_unreachable("This MachineModuleInfo constructor should never be called, "
  160. "MMI should always be explicitly constructed by "
  161. "LLVMTargetMachine");
  162. }
  163. MachineModuleInfo::~MachineModuleInfo() {
  164. }
  165. bool MachineModuleInfo::doInitialization(Module &M) {
  166. ObjFileMMI = nullptr;
  167. CurCallSite = 0;
  168. CallsEHReturn = false;
  169. CallsUnwindInit = false;
  170. HasEHFunclets = false;
  171. DbgInfoAvailable = UsesVAFloatArgument = UsesMorestackAddr = false;
  172. PersonalityTypeCache = EHPersonality::Unknown;
  173. AddrLabelSymbols = nullptr;
  174. TheModule = nullptr;
  175. return false;
  176. }
  177. bool MachineModuleInfo::doFinalization(Module &M) {
  178. Personalities.clear();
  179. delete AddrLabelSymbols;
  180. AddrLabelSymbols = nullptr;
  181. Context.reset();
  182. delete ObjFileMMI;
  183. ObjFileMMI = nullptr;
  184. return false;
  185. }
  186. /// EndFunction - Discard function meta information.
  187. ///
  188. void MachineModuleInfo::EndFunction() {
  189. // Clean up frame info.
  190. FrameInstructions.clear();
  191. // Clean up exception info.
  192. LandingPads.clear();
  193. PersonalityTypeCache = EHPersonality::Unknown;
  194. CallSiteMap.clear();
  195. TypeInfos.clear();
  196. FilterIds.clear();
  197. FilterEnds.clear();
  198. CallsEHReturn = false;
  199. CallsUnwindInit = false;
  200. HasEHFunclets = false;
  201. VariableDbgInfos.clear();
  202. }
  203. //===- Address of Block Management ----------------------------------------===//
  204. /// getAddrLabelSymbolToEmit - Return the symbol to be used for the specified
  205. /// basic block when its address is taken. If other blocks were RAUW'd to
  206. /// this one, we may have to emit them as well, return the whole set.
  207. ArrayRef<MCSymbol *>
  208. MachineModuleInfo::getAddrLabelSymbolToEmit(const BasicBlock *BB) {
  209. // Lazily create AddrLabelSymbols.
  210. if (!AddrLabelSymbols)
  211. AddrLabelSymbols = new MMIAddrLabelMap(Context);
  212. return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
  213. }
  214. /// takeDeletedSymbolsForFunction - If the specified function has had any
  215. /// references to address-taken blocks generated, but the block got deleted,
  216. /// return the symbol now so we can emit it. This prevents emitting a
  217. /// reference to a symbol that has no definition.
  218. void MachineModuleInfo::
  219. takeDeletedSymbolsForFunction(const Function *F,
  220. std::vector<MCSymbol*> &Result) {
  221. // If no blocks have had their addresses taken, we're done.
  222. if (!AddrLabelSymbols) return;
  223. return AddrLabelSymbols->
  224. takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
  225. }
  226. //===- EH -----------------------------------------------------------------===//
  227. /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
  228. /// specified MachineBasicBlock.
  229. LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo
  230. (MachineBasicBlock *LandingPad) {
  231. unsigned N = LandingPads.size();
  232. for (unsigned i = 0; i < N; ++i) {
  233. LandingPadInfo &LP = LandingPads[i];
  234. if (LP.LandingPadBlock == LandingPad)
  235. return LP;
  236. }
  237. LandingPads.push_back(LandingPadInfo(LandingPad));
  238. return LandingPads[N];
  239. }
  240. /// addInvoke - Provide the begin and end labels of an invoke style call and
  241. /// associate it with a try landing pad block.
  242. void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad,
  243. MCSymbol *BeginLabel, MCSymbol *EndLabel) {
  244. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  245. LP.BeginLabels.push_back(BeginLabel);
  246. LP.EndLabels.push_back(EndLabel);
  247. }
  248. /// addLandingPad - Provide the label of a try LandingPad block.
  249. ///
  250. MCSymbol *MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {
  251. MCSymbol *LandingPadLabel = Context.createTempSymbol();
  252. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  253. LP.LandingPadLabel = LandingPadLabel;
  254. return LandingPadLabel;
  255. }
  256. void MachineModuleInfo::addPersonality(const Function *Personality) {
  257. for (unsigned i = 0; i < Personalities.size(); ++i)
  258. if (Personalities[i] == Personality)
  259. return;
  260. Personalities.push_back(Personality);
  261. }
  262. void MachineModuleInfo::addWinEHState(MachineBasicBlock *LandingPad,
  263. int State) {
  264. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  265. LP.WinEHState = State;
  266. }
  267. /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
  268. ///
  269. void MachineModuleInfo::
  270. addCatchTypeInfo(MachineBasicBlock *LandingPad,
  271. ArrayRef<const GlobalValue *> TyInfo) {
  272. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  273. for (unsigned N = TyInfo.size(); N; --N)
  274. LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
  275. }
  276. /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
  277. ///
  278. void MachineModuleInfo::
  279. addFilterTypeInfo(MachineBasicBlock *LandingPad,
  280. ArrayRef<const GlobalValue *> TyInfo) {
  281. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  282. std::vector<unsigned> IdsInFilter(TyInfo.size());
  283. for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
  284. IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
  285. LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
  286. }
  287. /// addCleanup - Add a cleanup action for a landing pad.
  288. ///
  289. void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {
  290. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  291. LP.TypeIds.push_back(0);
  292. }
  293. void MachineModuleInfo::addSEHCatchHandler(MachineBasicBlock *LandingPad,
  294. const Function *Filter,
  295. const BlockAddress *RecoverBA) {
  296. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  297. SEHHandler Handler;
  298. Handler.FilterOrFinally = Filter;
  299. Handler.RecoverBA = RecoverBA;
  300. LP.SEHHandlers.push_back(Handler);
  301. }
  302. void MachineModuleInfo::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
  303. const Function *Cleanup) {
  304. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  305. SEHHandler Handler;
  306. Handler.FilterOrFinally = Cleanup;
  307. Handler.RecoverBA = nullptr;
  308. LP.SEHHandlers.push_back(Handler);
  309. }
  310. /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
  311. /// pads.
  312. void MachineModuleInfo::TidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap) {
  313. for (unsigned i = 0; i != LandingPads.size(); ) {
  314. LandingPadInfo &LandingPad = LandingPads[i];
  315. if (LandingPad.LandingPadLabel &&
  316. !LandingPad.LandingPadLabel->isDefined() &&
  317. (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
  318. LandingPad.LandingPadLabel = nullptr;
  319. // Special case: we *should* emit LPs with null LP MBB. This indicates
  320. // "nounwind" case.
  321. if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
  322. LandingPads.erase(LandingPads.begin() + i);
  323. continue;
  324. }
  325. for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
  326. MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
  327. MCSymbol *EndLabel = LandingPad.EndLabels[j];
  328. if ((BeginLabel->isDefined() ||
  329. (LPMap && (*LPMap)[BeginLabel] != 0)) &&
  330. (EndLabel->isDefined() ||
  331. (LPMap && (*LPMap)[EndLabel] != 0))) continue;
  332. LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
  333. LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
  334. --j, --e;
  335. }
  336. // Remove landing pads with no try-ranges.
  337. if (LandingPads[i].BeginLabels.empty()) {
  338. LandingPads.erase(LandingPads.begin() + i);
  339. continue;
  340. }
  341. // If there is no landing pad, ensure that the list of typeids is empty.
  342. // If the only typeid is a cleanup, this is the same as having no typeids.
  343. if (!LandingPad.LandingPadBlock ||
  344. (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
  345. LandingPad.TypeIds.clear();
  346. ++i;
  347. }
  348. }
  349. /// setCallSiteLandingPad - Map the landing pad's EH symbol to the call site
  350. /// indexes.
  351. void MachineModuleInfo::setCallSiteLandingPad(MCSymbol *Sym,
  352. ArrayRef<unsigned> Sites) {
  353. LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
  354. }
  355. /// getTypeIDFor - Return the type id for the specified typeinfo. This is
  356. /// function wide.
  357. unsigned MachineModuleInfo::getTypeIDFor(const GlobalValue *TI) {
  358. for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
  359. if (TypeInfos[i] == TI) return i + 1;
  360. TypeInfos.push_back(TI);
  361. return TypeInfos.size();
  362. }
  363. /// getFilterIDFor - Return the filter id for the specified typeinfos. This is
  364. /// function wide.
  365. int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {
  366. // If the new filter coincides with the tail of an existing filter, then
  367. // re-use the existing filter. Folding filters more than this requires
  368. // re-ordering filters and/or their elements - probably not worth it.
  369. for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
  370. E = FilterEnds.end(); I != E; ++I) {
  371. unsigned i = *I, j = TyIds.size();
  372. while (i && j)
  373. if (FilterIds[--i] != TyIds[--j])
  374. goto try_next;
  375. if (!j)
  376. // The new filter coincides with range [i, end) of the existing filter.
  377. return -(1 + i);
  378. try_next:;
  379. }
  380. // Add the new filter.
  381. int FilterID = -(1 + FilterIds.size());
  382. FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
  383. FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
  384. FilterEnds.push_back(FilterIds.size());
  385. FilterIds.push_back(0); // terminator
  386. return FilterID;
  387. }
  388. const Function *MachineModuleInfo::getWinEHParent(const Function *F) const {
  389. StringRef WinEHParentName =
  390. F->getFnAttribute("wineh-parent").getValueAsString();
  391. if (WinEHParentName.empty() || WinEHParentName == F->getName())
  392. return F;
  393. return F->getParent()->getFunction(WinEHParentName);
  394. }
  395. WinEHFuncInfo &MachineModuleInfo::getWinEHFuncInfo(const Function *F) {
  396. auto &Ptr = FuncInfoMap[getWinEHParent(F)];
  397. if (!Ptr)
  398. Ptr.reset(new WinEHFuncInfo);
  399. return *Ptr;
  400. }