MachineModuleInfo.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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/ADT/PostOrderIterator.h"
  12. #include "llvm/ADT/TinyPtrVector.h"
  13. #include "llvm/Analysis/EHPersonalities.h"
  14. #include "llvm/Analysis/ValueTracking.h"
  15. #include "llvm/CodeGen/MachineFunction.h"
  16. #include "llvm/CodeGen/MachineFunctionInitializer.h"
  17. #include "llvm/CodeGen/MachineFunctionPass.h"
  18. #include "llvm/CodeGen/Passes.h"
  19. #include "llvm/IR/Constants.h"
  20. #include "llvm/IR/DerivedTypes.h"
  21. #include "llvm/IR/GlobalVariable.h"
  22. #include "llvm/IR/Instructions.h"
  23. #include "llvm/IR/Module.h"
  24. #include "llvm/MC/MCObjectFileInfo.h"
  25. #include "llvm/MC/MCSymbol.h"
  26. #include "llvm/Support/Dwarf.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Target/TargetLoweringObjectFile.h"
  29. #include "llvm/Target/TargetMachine.h"
  30. using namespace llvm;
  31. using namespace llvm::dwarf;
  32. // Handle the Pass registration stuff necessary to use DataLayout's.
  33. INITIALIZE_TM_PASS(MachineModuleInfo, "machinemoduleinfo",
  34. "Machine Module Information", false, false)
  35. char MachineModuleInfo::ID = 0;
  36. // Out of line virtual method.
  37. MachineModuleInfoImpl::~MachineModuleInfoImpl() {}
  38. namespace llvm {
  39. class MMIAddrLabelMapCallbackPtr final : CallbackVH {
  40. MMIAddrLabelMap *Map;
  41. public:
  42. MMIAddrLabelMapCallbackPtr() : Map(nullptr) {}
  43. MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V), Map(nullptr) {}
  44. void setPtr(BasicBlock *BB) {
  45. ValueHandleBase::operator=(BB);
  46. }
  47. void setMap(MMIAddrLabelMap *map) { Map = map; }
  48. void deleted() override;
  49. void allUsesReplacedWith(Value *V2) override;
  50. };
  51. class MMIAddrLabelMap {
  52. MCContext &Context;
  53. struct AddrLabelSymEntry {
  54. /// The symbols for the label.
  55. TinyPtrVector<MCSymbol *> Symbols;
  56. Function *Fn; // The containing function of the BasicBlock.
  57. unsigned Index; // The index in BBCallbacks for the BasicBlock.
  58. };
  59. DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
  60. /// Callbacks for the BasicBlock's that we have entries for. We use this so
  61. /// we get notified if a block is deleted or RAUWd.
  62. std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
  63. /// This is a per-function list of symbols whose corresponding BasicBlock got
  64. /// deleted. These symbols need to be emitted at some point in the file, so
  65. /// AsmPrinter emits them after the function body.
  66. DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >
  67. DeletedAddrLabelsNeedingEmission;
  68. public:
  69. MMIAddrLabelMap(MCContext &context) : Context(context) {}
  70. ~MMIAddrLabelMap() {
  71. assert(DeletedAddrLabelsNeedingEmission.empty() &&
  72. "Some labels for deleted blocks never got emitted");
  73. }
  74. ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
  75. void takeDeletedSymbolsForFunction(Function *F,
  76. std::vector<MCSymbol*> &Result);
  77. void UpdateForDeletedBlock(BasicBlock *BB);
  78. void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
  79. };
  80. }
  81. ArrayRef<MCSymbol *> MMIAddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) {
  82. assert(BB->hasAddressTaken() &&
  83. "Shouldn't get label for block without address taken");
  84. AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
  85. // If we already had an entry for this block, just return it.
  86. if (!Entry.Symbols.empty()) {
  87. assert(BB->getParent() == Entry.Fn && "Parent changed");
  88. return Entry.Symbols;
  89. }
  90. // Otherwise, this is a new entry, create a new symbol for it and add an
  91. // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
  92. BBCallbacks.emplace_back(BB);
  93. BBCallbacks.back().setMap(this);
  94. Entry.Index = BBCallbacks.size() - 1;
  95. Entry.Fn = BB->getParent();
  96. Entry.Symbols.push_back(Context.createTempSymbol());
  97. return Entry.Symbols;
  98. }
  99. /// If we have any deleted symbols for F, return them.
  100. void MMIAddrLabelMap::
  101. takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
  102. DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >::iterator I =
  103. DeletedAddrLabelsNeedingEmission.find(F);
  104. // If there are no entries for the function, just return.
  105. if (I == DeletedAddrLabelsNeedingEmission.end()) return;
  106. // Otherwise, take the list.
  107. std::swap(Result, I->second);
  108. DeletedAddrLabelsNeedingEmission.erase(I);
  109. }
  110. void MMIAddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
  111. // If the block got deleted, there is no need for the symbol. If the symbol
  112. // was already emitted, we can just forget about it, otherwise we need to
  113. // queue it up for later emission when the function is output.
  114. AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
  115. AddrLabelSymbols.erase(BB);
  116. assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
  117. BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
  118. assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
  119. "Block/parent mismatch");
  120. for (MCSymbol *Sym : Entry.Symbols) {
  121. if (Sym->isDefined())
  122. return;
  123. // If the block is not yet defined, we need to emit it at the end of the
  124. // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
  125. // for the containing Function. Since the block is being deleted, its
  126. // parent may already be removed, we have to get the function from 'Entry'.
  127. DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
  128. }
  129. }
  130. void MMIAddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
  131. // Get the entry for the RAUW'd block and remove it from our map.
  132. AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
  133. AddrLabelSymbols.erase(Old);
  134. assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
  135. AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
  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. BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
  143. // Otherwise, we need to add the old symbols to the new block's set.
  144. NewEntry.Symbols.insert(NewEntry.Symbols.end(), OldEntry.Symbols.begin(),
  145. OldEntry.Symbols.end());
  146. }
  147. void MMIAddrLabelMapCallbackPtr::deleted() {
  148. Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
  149. }
  150. void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
  151. Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
  152. }
  153. //===----------------------------------------------------------------------===//
  154. MachineModuleInfo::MachineModuleInfo(const TargetMachine *TM)
  155. : ImmutablePass(ID), TM(*TM),
  156. Context(TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
  157. TM->getObjFileLowering(), nullptr, false) {
  158. initializeMachineModuleInfoPass(*PassRegistry::getPassRegistry());
  159. }
  160. MachineModuleInfo::~MachineModuleInfo() {
  161. }
  162. bool MachineModuleInfo::doInitialization(Module &M) {
  163. ObjFileMMI = nullptr;
  164. CurCallSite = 0;
  165. CallsEHReturn = false;
  166. CallsUnwindInit = false;
  167. HasEHFunclets = false;
  168. DbgInfoAvailable = UsesVAFloatArgument = UsesMorestackAddr = false;
  169. PersonalityTypeCache = EHPersonality::Unknown;
  170. AddrLabelSymbols = nullptr;
  171. TheModule = &M;
  172. return false;
  173. }
  174. bool MachineModuleInfo::doFinalization(Module &M) {
  175. Personalities.clear();
  176. delete AddrLabelSymbols;
  177. AddrLabelSymbols = nullptr;
  178. Context.reset();
  179. delete ObjFileMMI;
  180. ObjFileMMI = nullptr;
  181. return false;
  182. }
  183. void MachineModuleInfo::EndFunction() {
  184. // Clean up exception info.
  185. LandingPads.clear();
  186. PersonalityTypeCache = EHPersonality::Unknown;
  187. CallSiteMap.clear();
  188. TypeInfos.clear();
  189. FilterIds.clear();
  190. FilterEnds.clear();
  191. CallsEHReturn = false;
  192. CallsUnwindInit = false;
  193. HasEHFunclets = false;
  194. }
  195. //===- Address of Block Management ----------------------------------------===//
  196. ArrayRef<MCSymbol *>
  197. MachineModuleInfo::getAddrLabelSymbolToEmit(const BasicBlock *BB) {
  198. // Lazily create AddrLabelSymbols.
  199. if (!AddrLabelSymbols)
  200. AddrLabelSymbols = new MMIAddrLabelMap(Context);
  201. return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
  202. }
  203. void MachineModuleInfo::
  204. takeDeletedSymbolsForFunction(const Function *F,
  205. std::vector<MCSymbol*> &Result) {
  206. // If no blocks have had their addresses taken, we're done.
  207. if (!AddrLabelSymbols) return;
  208. return AddrLabelSymbols->
  209. takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
  210. }
  211. //===- EH -----------------------------------------------------------------===//
  212. LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo
  213. (MachineBasicBlock *LandingPad) {
  214. unsigned N = LandingPads.size();
  215. for (unsigned i = 0; i < N; ++i) {
  216. LandingPadInfo &LP = LandingPads[i];
  217. if (LP.LandingPadBlock == LandingPad)
  218. return LP;
  219. }
  220. LandingPads.push_back(LandingPadInfo(LandingPad));
  221. return LandingPads[N];
  222. }
  223. void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad,
  224. MCSymbol *BeginLabel, MCSymbol *EndLabel) {
  225. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  226. LP.BeginLabels.push_back(BeginLabel);
  227. LP.EndLabels.push_back(EndLabel);
  228. }
  229. MCSymbol *MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {
  230. MCSymbol *LandingPadLabel = Context.createTempSymbol();
  231. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  232. LP.LandingPadLabel = LandingPadLabel;
  233. return LandingPadLabel;
  234. }
  235. void MachineModuleInfo::addPersonality(const Function *Personality) {
  236. for (unsigned i = 0; i < Personalities.size(); ++i)
  237. if (Personalities[i] == Personality)
  238. return;
  239. Personalities.push_back(Personality);
  240. }
  241. void MachineModuleInfo::
  242. addCatchTypeInfo(MachineBasicBlock *LandingPad,
  243. ArrayRef<const GlobalValue *> TyInfo) {
  244. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  245. for (unsigned N = TyInfo.size(); N; --N)
  246. LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
  247. }
  248. void MachineModuleInfo::
  249. addFilterTypeInfo(MachineBasicBlock *LandingPad,
  250. ArrayRef<const GlobalValue *> TyInfo) {
  251. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  252. std::vector<unsigned> IdsInFilter(TyInfo.size());
  253. for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
  254. IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
  255. LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
  256. }
  257. void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {
  258. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  259. LP.TypeIds.push_back(0);
  260. }
  261. void MachineModuleInfo::addSEHCatchHandler(MachineBasicBlock *LandingPad,
  262. const Function *Filter,
  263. const BlockAddress *RecoverBA) {
  264. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  265. SEHHandler Handler;
  266. Handler.FilterOrFinally = Filter;
  267. Handler.RecoverBA = RecoverBA;
  268. LP.SEHHandlers.push_back(Handler);
  269. }
  270. void MachineModuleInfo::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
  271. const Function *Cleanup) {
  272. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  273. SEHHandler Handler;
  274. Handler.FilterOrFinally = Cleanup;
  275. Handler.RecoverBA = nullptr;
  276. LP.SEHHandlers.push_back(Handler);
  277. }
  278. void MachineModuleInfo::TidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap) {
  279. for (unsigned i = 0; i != LandingPads.size(); ) {
  280. LandingPadInfo &LandingPad = LandingPads[i];
  281. if (LandingPad.LandingPadLabel &&
  282. !LandingPad.LandingPadLabel->isDefined() &&
  283. (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
  284. LandingPad.LandingPadLabel = nullptr;
  285. // Special case: we *should* emit LPs with null LP MBB. This indicates
  286. // "nounwind" case.
  287. if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
  288. LandingPads.erase(LandingPads.begin() + i);
  289. continue;
  290. }
  291. for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
  292. MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
  293. MCSymbol *EndLabel = LandingPad.EndLabels[j];
  294. if ((BeginLabel->isDefined() ||
  295. (LPMap && (*LPMap)[BeginLabel] != 0)) &&
  296. (EndLabel->isDefined() ||
  297. (LPMap && (*LPMap)[EndLabel] != 0))) continue;
  298. LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
  299. LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
  300. --j;
  301. --e;
  302. }
  303. // Remove landing pads with no try-ranges.
  304. if (LandingPads[i].BeginLabels.empty()) {
  305. LandingPads.erase(LandingPads.begin() + i);
  306. continue;
  307. }
  308. // If there is no landing pad, ensure that the list of typeids is empty.
  309. // If the only typeid is a cleanup, this is the same as having no typeids.
  310. if (!LandingPad.LandingPadBlock ||
  311. (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
  312. LandingPad.TypeIds.clear();
  313. ++i;
  314. }
  315. }
  316. void MachineModuleInfo::setCallSiteLandingPad(MCSymbol *Sym,
  317. ArrayRef<unsigned> Sites) {
  318. LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
  319. }
  320. unsigned MachineModuleInfo::getTypeIDFor(const GlobalValue *TI) {
  321. for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
  322. if (TypeInfos[i] == TI) return i + 1;
  323. TypeInfos.push_back(TI);
  324. return TypeInfos.size();
  325. }
  326. int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {
  327. // If the new filter coincides with the tail of an existing filter, then
  328. // re-use the existing filter. Folding filters more than this requires
  329. // re-ordering filters and/or their elements - probably not worth it.
  330. for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
  331. E = FilterEnds.end(); I != E; ++I) {
  332. unsigned i = *I, j = TyIds.size();
  333. while (i && j)
  334. if (FilterIds[--i] != TyIds[--j])
  335. goto try_next;
  336. if (!j)
  337. // The new filter coincides with range [i, end) of the existing filter.
  338. return -(1 + i);
  339. try_next:;
  340. }
  341. // Add the new filter.
  342. int FilterID = -(1 + FilterIds.size());
  343. FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
  344. FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
  345. FilterEnds.push_back(FilterIds.size());
  346. FilterIds.push_back(0); // terminator
  347. return FilterID;
  348. }
  349. MachineFunction &MachineModuleInfo::getMachineFunction(const Function &F) {
  350. // Shortcut for the common case where a sequence of MachineFunctionPasses
  351. // all query for the same Function.
  352. if (LastRequest == &F)
  353. return *LastResult;
  354. auto I = MachineFunctions.insert(
  355. std::make_pair(&F, std::unique_ptr<MachineFunction>()));
  356. MachineFunction *MF;
  357. if (I.second) {
  358. // No pre-existing machine function, create a new one.
  359. MF = new MachineFunction(&F, TM, NextFnNum++, *this);
  360. // Update the set entry.
  361. I.first->second.reset(MF);
  362. if (MFInitializer)
  363. if (MFInitializer->initializeMachineFunction(*MF))
  364. report_fatal_error("Unable to initialize machine function");
  365. } else {
  366. MF = I.first->second.get();
  367. }
  368. LastRequest = &F;
  369. LastResult = MF;
  370. return *MF;
  371. }
  372. void MachineModuleInfo::deleteMachineFunctionFor(Function &F) {
  373. MachineFunctions.erase(&F);
  374. LastRequest = nullptr;
  375. LastResult = nullptr;
  376. }
  377. namespace {
  378. /// This pass frees the MachineFunction object associated with a Function.
  379. class FreeMachineFunction : public FunctionPass {
  380. public:
  381. static char ID;
  382. FreeMachineFunction() : FunctionPass(ID) {}
  383. void getAnalysisUsage(AnalysisUsage &AU) const override {
  384. AU.addRequired<MachineModuleInfo>();
  385. AU.addPreserved<MachineModuleInfo>();
  386. }
  387. bool runOnFunction(Function &F) override {
  388. MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
  389. MMI.deleteMachineFunctionFor(F);
  390. return true;
  391. }
  392. };
  393. char FreeMachineFunction::ID;
  394. } // end anonymous namespace
  395. namespace llvm {
  396. FunctionPass *createFreeMachineFunctionPass() {
  397. return new FreeMachineFunction();
  398. }
  399. } // end namespace llvm
  400. //===- MMI building helpers -----------------------------------------------===//
  401. void llvm::computeUsesVAFloatArgument(const CallInst &I,
  402. MachineModuleInfo &MMI) {
  403. FunctionType *FT =
  404. cast<FunctionType>(I.getCalledValue()->getType()->getContainedType(0));
  405. if (FT->isVarArg() && !MMI.usesVAFloatArgument()) {
  406. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  407. Type *T = I.getArgOperand(i)->getType();
  408. for (auto i : post_order(T)) {
  409. if (i->isFloatingPointTy()) {
  410. MMI.setUsesVAFloatArgument(true);
  411. return;
  412. }
  413. }
  414. }
  415. }
  416. }
  417. void llvm::addLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
  418. MachineBasicBlock &MBB) {
  419. if (const auto *PF = dyn_cast<Function>(
  420. I.getParent()->getParent()->getPersonalityFn()->stripPointerCasts()))
  421. MMI.addPersonality(PF);
  422. if (I.isCleanup())
  423. MMI.addCleanup(&MBB);
  424. // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
  425. // but we need to do it this way because of how the DWARF EH emitter
  426. // processes the clauses.
  427. for (unsigned i = I.getNumClauses(); i != 0; --i) {
  428. Value *Val = I.getClause(i - 1);
  429. if (I.isCatch(i - 1)) {
  430. MMI.addCatchTypeInfo(&MBB,
  431. dyn_cast<GlobalValue>(Val->stripPointerCasts()));
  432. } else {
  433. // Add filters in a list.
  434. Constant *CVal = cast<Constant>(Val);
  435. SmallVector<const GlobalValue *, 4> FilterList;
  436. for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end();
  437. II != IE; ++II)
  438. FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
  439. MMI.addFilterTypeInfo(&MBB, FilterList);
  440. }
  441. }
  442. }