1 //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/CodeGen/MachineModuleInfo.h"
11 #include "llvm/ADT/PointerUnion.h"
12 #include "llvm/Analysis/LibCallSemantics.h"
13 #include "llvm/Analysis/ValueTracking.h"
14 #include "llvm/CodeGen/MachineFunction.h"
15 #include "llvm/CodeGen/MachineFunctionPass.h"
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/CodeGen/WinEHFuncInfo.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/GlobalVariable.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/MC/MCObjectFileInfo.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/Support/Dwarf.h"
25 #include "llvm/Support/ErrorHandling.h"
27 using namespace llvm::dwarf;
29 // Handle the Pass registration stuff necessary to use DataLayout's.
30 INITIALIZE_PASS(MachineModuleInfo, "machinemoduleinfo",
31 "Machine Module Information", false, false)
32 char MachineModuleInfo::ID = 0;
34 // Out of line virtual method.
35 MachineModuleInfoImpl::~MachineModuleInfoImpl() {}
38 class MMIAddrLabelMapCallbackPtr final : CallbackVH {
41 MMIAddrLabelMapCallbackPtr() : Map(nullptr) {}
42 MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V), Map(nullptr) {}
44 void setPtr(BasicBlock *BB) {
45 ValueHandleBase::operator=(BB);
48 void setMap(MMIAddrLabelMap *map) { Map = map; }
50 void deleted() override;
51 void allUsesReplacedWith(Value *V2) override;
54 class MMIAddrLabelMap {
56 struct AddrLabelSymEntry {
57 /// Symbols - The symbols for the label.
58 TinyPtrVector<MCSymbol *> Symbols;
60 Function *Fn; // The containing function of the BasicBlock.
61 unsigned Index; // The index in BBCallbacks for the BasicBlock.
64 DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
66 /// BBCallbacks - Callbacks for the BasicBlock's that we have entries for. We
67 /// use this so we get notified if a block is deleted or RAUWd.
68 std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
70 /// DeletedAddrLabelsNeedingEmission - This is a per-function list of symbols
71 /// whose corresponding BasicBlock got deleted. These symbols need to be
72 /// emitted at some point in the file, so AsmPrinter emits them after the
74 DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >
75 DeletedAddrLabelsNeedingEmission;
78 MMIAddrLabelMap(MCContext &context) : Context(context) {}
80 assert(DeletedAddrLabelsNeedingEmission.empty() &&
81 "Some labels for deleted blocks never got emitted");
84 ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
86 void takeDeletedSymbolsForFunction(Function *F,
87 std::vector<MCSymbol*> &Result);
89 void UpdateForDeletedBlock(BasicBlock *BB);
90 void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
94 ArrayRef<MCSymbol *> MMIAddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) {
95 assert(BB->hasAddressTaken() &&
96 "Shouldn't get label for block without address taken");
97 AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
99 // If we already had an entry for this block, just return it.
100 if (!Entry.Symbols.empty()) {
101 assert(BB->getParent() == Entry.Fn && "Parent changed");
102 return Entry.Symbols;
105 // Otherwise, this is a new entry, create a new symbol for it and add an
106 // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
107 BBCallbacks.emplace_back(BB);
108 BBCallbacks.back().setMap(this);
109 Entry.Index = BBCallbacks.size() - 1;
110 Entry.Fn = BB->getParent();
111 Entry.Symbols.push_back(Context.createTempSymbol());
112 return Entry.Symbols;
115 /// takeDeletedSymbolsForFunction - If we have any deleted symbols for F, return
117 void MMIAddrLabelMap::
118 takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
119 DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >::iterator I =
120 DeletedAddrLabelsNeedingEmission.find(F);
122 // If there are no entries for the function, just return.
123 if (I == DeletedAddrLabelsNeedingEmission.end()) return;
125 // Otherwise, take the list.
126 std::swap(Result, I->second);
127 DeletedAddrLabelsNeedingEmission.erase(I);
131 void MMIAddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
132 // If the block got deleted, there is no need for the symbol. If the symbol
133 // was already emitted, we can just forget about it, otherwise we need to
134 // queue it up for later emission when the function is output.
135 AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
136 AddrLabelSymbols.erase(BB);
137 assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
138 BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
140 assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
141 "Block/parent mismatch");
143 for (MCSymbol *Sym : Entry.Symbols) {
144 if (Sym->isDefined())
147 // If the block is not yet defined, we need to emit it at the end of the
148 // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
149 // for the containing Function. Since the block is being deleted, its
150 // parent may already be removed, we have to get the function from 'Entry'.
151 DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
155 void MMIAddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
156 // Get the entry for the RAUW'd block and remove it from our map.
157 AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
158 AddrLabelSymbols.erase(Old);
159 assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
161 AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
163 // If New is not address taken, just move our symbol over to it.
164 if (NewEntry.Symbols.empty()) {
165 BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
166 NewEntry = std::move(OldEntry); // Set New's entry.
170 BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
172 // Otherwise, we need to add the old symbols to the new block's set.
173 NewEntry.Symbols.insert(NewEntry.Symbols.end(), OldEntry.Symbols.begin(),
174 OldEntry.Symbols.end());
178 void MMIAddrLabelMapCallbackPtr::deleted() {
179 Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
182 void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
183 Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
187 //===----------------------------------------------------------------------===//
189 MachineModuleInfo::MachineModuleInfo(const MCAsmInfo &MAI,
190 const MCRegisterInfo &MRI,
191 const MCObjectFileInfo *MOFI)
192 : ImmutablePass(ID), Context(&MAI, &MRI, MOFI, nullptr, false) {
193 initializeMachineModuleInfoPass(*PassRegistry::getPassRegistry());
196 MachineModuleInfo::MachineModuleInfo()
197 : ImmutablePass(ID), Context(nullptr, nullptr, nullptr) {
198 llvm_unreachable("This MachineModuleInfo constructor should never be called, "
199 "MMI should always be explicitly constructed by "
200 "LLVMTargetMachine");
203 MachineModuleInfo::~MachineModuleInfo() {
206 bool MachineModuleInfo::doInitialization(Module &M) {
208 ObjFileMMI = nullptr;
210 CallsEHReturn = false;
211 CallsUnwindInit = false;
212 HasEHFunclets = false;
213 DbgInfoAvailable = UsesVAFloatArgument = UsesMorestackAddr = false;
214 // Always emit some info, by default "no personality" info.
215 Personalities.push_back(nullptr);
216 PersonalityTypeCache = EHPersonality::Unknown;
217 AddrLabelSymbols = nullptr;
223 bool MachineModuleInfo::doFinalization(Module &M) {
225 Personalities.clear();
227 delete AddrLabelSymbols;
228 AddrLabelSymbols = nullptr;
233 ObjFileMMI = nullptr;
238 /// EndFunction - Discard function meta information.
240 void MachineModuleInfo::EndFunction() {
241 // Clean up frame info.
242 FrameInstructions.clear();
244 // Clean up exception info.
246 PersonalityTypeCache = EHPersonality::Unknown;
251 CallsEHReturn = false;
252 CallsUnwindInit = false;
253 HasEHFunclets = false;
254 VariableDbgInfos.clear();
257 //===- Address of Block Management ----------------------------------------===//
259 /// getAddrLabelSymbolToEmit - Return the symbol to be used for the specified
260 /// basic block when its address is taken. If other blocks were RAUW'd to
261 /// this one, we may have to emit them as well, return the whole set.
263 MachineModuleInfo::getAddrLabelSymbolToEmit(const BasicBlock *BB) {
264 // Lazily create AddrLabelSymbols.
265 if (!AddrLabelSymbols)
266 AddrLabelSymbols = new MMIAddrLabelMap(Context);
267 return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
271 /// takeDeletedSymbolsForFunction - If the specified function has had any
272 /// references to address-taken blocks generated, but the block got deleted,
273 /// return the symbol now so we can emit it. This prevents emitting a
274 /// reference to a symbol that has no definition.
275 void MachineModuleInfo::
276 takeDeletedSymbolsForFunction(const Function *F,
277 std::vector<MCSymbol*> &Result) {
278 // If no blocks have had their addresses taken, we're done.
279 if (!AddrLabelSymbols) return;
280 return AddrLabelSymbols->
281 takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
284 //===- EH -----------------------------------------------------------------===//
286 /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
287 /// specified MachineBasicBlock.
288 LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo
289 (MachineBasicBlock *LandingPad) {
290 unsigned N = LandingPads.size();
291 for (unsigned i = 0; i < N; ++i) {
292 LandingPadInfo &LP = LandingPads[i];
293 if (LP.LandingPadBlock == LandingPad)
297 LandingPads.push_back(LandingPadInfo(LandingPad));
298 return LandingPads[N];
301 /// addInvoke - Provide the begin and end labels of an invoke style call and
302 /// associate it with a try landing pad block.
303 void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad,
304 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
305 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
306 LP.BeginLabels.push_back(BeginLabel);
307 LP.EndLabels.push_back(EndLabel);
310 /// addLandingPad - Provide the label of a try LandingPad block.
312 MCSymbol *MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {
313 MCSymbol *LandingPadLabel = Context.createTempSymbol();
314 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
315 LP.LandingPadLabel = LandingPadLabel;
316 return LandingPadLabel;
319 /// addPersonality - Provide the personality function for the exception
321 void MachineModuleInfo::addPersonality(MachineBasicBlock *LandingPad,
322 const Function *Personality) {
323 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
324 LP.Personality = Personality;
325 addPersonality(Personality);
328 void MachineModuleInfo::addPersonality(const Function *Personality) {
329 for (unsigned i = 0; i < Personalities.size(); ++i)
330 if (Personalities[i] == Personality)
333 // If this is the first personality we're adding go
334 // ahead and add it at the beginning.
335 if (!Personalities[0])
336 Personalities[0] = Personality;
338 Personalities.push_back(Personality);
341 void MachineModuleInfo::addWinEHState(MachineBasicBlock *LandingPad,
343 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
344 LP.WinEHState = State;
347 /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
349 void MachineModuleInfo::
350 addCatchTypeInfo(MachineBasicBlock *LandingPad,
351 ArrayRef<const GlobalValue *> TyInfo) {
352 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
353 for (unsigned N = TyInfo.size(); N; --N)
354 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
357 /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
359 void MachineModuleInfo::
360 addFilterTypeInfo(MachineBasicBlock *LandingPad,
361 ArrayRef<const GlobalValue *> TyInfo) {
362 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
363 std::vector<unsigned> IdsInFilter(TyInfo.size());
364 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
365 IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
366 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
369 /// addCleanup - Add a cleanup action for a landing pad.
371 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {
372 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
373 LP.TypeIds.push_back(0);
376 void MachineModuleInfo::addSEHCatchHandler(MachineBasicBlock *LandingPad,
377 const Function *Filter,
378 const BlockAddress *RecoverBA) {
379 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
381 Handler.FilterOrFinally = Filter;
382 Handler.RecoverBA = RecoverBA;
383 LP.SEHHandlers.push_back(Handler);
386 void MachineModuleInfo::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
387 const Function *Cleanup) {
388 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
390 Handler.FilterOrFinally = Cleanup;
391 Handler.RecoverBA = nullptr;
392 LP.SEHHandlers.push_back(Handler);
395 /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
397 void MachineModuleInfo::TidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap) {
398 for (unsigned i = 0; i != LandingPads.size(); ) {
399 LandingPadInfo &LandingPad = LandingPads[i];
400 if (LandingPad.LandingPadLabel &&
401 !LandingPad.LandingPadLabel->isDefined() &&
402 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
403 LandingPad.LandingPadLabel = nullptr;
405 // Special case: we *should* emit LPs with null LP MBB. This indicates
407 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
408 LandingPads.erase(LandingPads.begin() + i);
412 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
413 MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
414 MCSymbol *EndLabel = LandingPad.EndLabels[j];
415 if ((BeginLabel->isDefined() ||
416 (LPMap && (*LPMap)[BeginLabel] != 0)) &&
417 (EndLabel->isDefined() ||
418 (LPMap && (*LPMap)[EndLabel] != 0))) continue;
420 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
421 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
425 // Remove landing pads with no try-ranges.
426 if (LandingPads[i].BeginLabels.empty()) {
427 LandingPads.erase(LandingPads.begin() + i);
431 // If there is no landing pad, ensure that the list of typeids is empty.
432 // If the only typeid is a cleanup, this is the same as having no typeids.
433 if (!LandingPad.LandingPadBlock ||
434 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
435 LandingPad.TypeIds.clear();
440 /// setCallSiteLandingPad - Map the landing pad's EH symbol to the call site
442 void MachineModuleInfo::setCallSiteLandingPad(MCSymbol *Sym,
443 ArrayRef<unsigned> Sites) {
444 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
447 /// getTypeIDFor - Return the type id for the specified typeinfo. This is
449 unsigned MachineModuleInfo::getTypeIDFor(const GlobalValue *TI) {
450 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
451 if (TypeInfos[i] == TI) return i + 1;
453 TypeInfos.push_back(TI);
454 return TypeInfos.size();
457 /// getFilterIDFor - Return the filter id for the specified typeinfos. This is
459 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {
460 // If the new filter coincides with the tail of an existing filter, then
461 // re-use the existing filter. Folding filters more than this requires
462 // re-ordering filters and/or their elements - probably not worth it.
463 for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
464 E = FilterEnds.end(); I != E; ++I) {
465 unsigned i = *I, j = TyIds.size();
468 if (FilterIds[--i] != TyIds[--j])
472 // The new filter coincides with range [i, end) of the existing filter.
478 // Add the new filter.
479 int FilterID = -(1 + FilterIds.size());
480 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
481 FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
482 FilterEnds.push_back(FilterIds.size());
483 FilterIds.push_back(0); // terminator
487 /// getPersonality - Return the personality function for the current function.
488 const Function *MachineModuleInfo::getPersonality() const {
489 for (const LandingPadInfo &LPI : LandingPads)
491 return LPI.Personality;
495 EHPersonality MachineModuleInfo::getPersonalityType() {
496 if (PersonalityTypeCache == EHPersonality::Unknown) {
497 if (const Function *F = getPersonality())
498 PersonalityTypeCache = classifyEHPersonality(F);
500 return PersonalityTypeCache;
503 /// getPersonalityIndex - Return unique index for current personality
504 /// function. NULL/first personality function should always get zero index.
505 unsigned MachineModuleInfo::getPersonalityIndex() const {
506 const Function* Personality = nullptr;
508 // Scan landing pads. If there is at least one non-NULL personality - use it.
509 for (unsigned i = 0, e = LandingPads.size(); i != e; ++i)
510 if (LandingPads[i].Personality) {
511 Personality = LandingPads[i].Personality;
515 for (unsigned i = 0, e = Personalities.size(); i < e; ++i) {
516 if (Personalities[i] == Personality)
520 // This will happen if the current personality function is
521 // in the zero index.
525 const Function *MachineModuleInfo::getWinEHParent(const Function *F) const {
526 StringRef WinEHParentName =
527 F->getFnAttribute("wineh-parent").getValueAsString();
528 if (WinEHParentName.empty() || WinEHParentName == F->getName())
530 return F->getParent()->getFunction(WinEHParentName);
533 WinEHFuncInfo &MachineModuleInfo::getWinEHFuncInfo(const Function *F) {
534 auto &Ptr = FuncInfoMap[getWinEHParent(F)];
536 Ptr.reset(new WinEHFuncInfo);