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 : 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. This is a pointer union that is
58 /// either one symbol (the common case) or a list of symbols.
59 PointerUnion<MCSymbol *, std::vector<MCSymbol*>*> Symbols;
61 Function *Fn; // The containing function of the BasicBlock.
62 unsigned Index; // The index in BBCallbacks for the BasicBlock.
65 DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
67 /// BBCallbacks - Callbacks for the BasicBlock's that we have entries for. We
68 /// use this so we get notified if a block is deleted or RAUWd.
69 std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
71 /// DeletedAddrLabelsNeedingEmission - This is a per-function list of symbols
72 /// whose corresponding BasicBlock got deleted. These symbols need to be
73 /// emitted at some point in the file, so AsmPrinter emits them after the
75 DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >
76 DeletedAddrLabelsNeedingEmission;
79 MMIAddrLabelMap(MCContext &context) : Context(context) {}
81 assert(DeletedAddrLabelsNeedingEmission.empty() &&
82 "Some labels for deleted blocks never got emitted");
84 // Deallocate any of the 'list of symbols' case.
85 for (DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry>::iterator
86 I = AddrLabelSymbols.begin(), E = AddrLabelSymbols.end(); I != E; ++I)
87 if (I->second.Symbols.is<std::vector<MCSymbol*>*>())
88 delete I->second.Symbols.get<std::vector<MCSymbol*>*>();
91 MCSymbol *getAddrLabelSymbol(BasicBlock *BB);
92 std::vector<MCSymbol*> getAddrLabelSymbolToEmit(BasicBlock *BB);
94 void takeDeletedSymbolsForFunction(Function *F,
95 std::vector<MCSymbol*> &Result);
97 void UpdateForDeletedBlock(BasicBlock *BB);
98 void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
102 MCSymbol *MMIAddrLabelMap::getAddrLabelSymbol(BasicBlock *BB) {
103 assert(BB->hasAddressTaken() &&
104 "Shouldn't get label for block without address taken");
105 AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
107 // If we already had an entry for this block, just return it.
108 if (!Entry.Symbols.isNull()) {
109 assert(BB->getParent() == Entry.Fn && "Parent changed");
110 if (Entry.Symbols.is<MCSymbol*>())
111 return Entry.Symbols.get<MCSymbol*>();
112 return (*Entry.Symbols.get<std::vector<MCSymbol*>*>())[0];
115 // Otherwise, this is a new entry, create a new symbol for it and add an
116 // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
117 BBCallbacks.emplace_back(BB);
118 BBCallbacks.back().setMap(this);
119 Entry.Index = BBCallbacks.size()-1;
120 Entry.Fn = BB->getParent();
121 MCSymbol *Result = Context.createTempSymbol();
122 Entry.Symbols = Result;
126 std::vector<MCSymbol*>
127 MMIAddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) {
128 assert(BB->hasAddressTaken() &&
129 "Shouldn't get label for block without address taken");
130 AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
132 std::vector<MCSymbol*> Result;
134 // If we already had an entry for this block, just return it.
135 if (Entry.Symbols.isNull())
136 Result.push_back(getAddrLabelSymbol(BB));
137 else if (MCSymbol *Sym = Entry.Symbols.dyn_cast<MCSymbol*>())
138 Result.push_back(Sym);
140 Result = *Entry.Symbols.get<std::vector<MCSymbol*>*>();
145 /// takeDeletedSymbolsForFunction - If we have any deleted symbols for F, return
147 void MMIAddrLabelMap::
148 takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
149 DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >::iterator I =
150 DeletedAddrLabelsNeedingEmission.find(F);
152 // If there are no entries for the function, just return.
153 if (I == DeletedAddrLabelsNeedingEmission.end()) return;
155 // Otherwise, take the list.
156 std::swap(Result, I->second);
157 DeletedAddrLabelsNeedingEmission.erase(I);
161 void MMIAddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
162 // If the block got deleted, there is no need for the symbol. If the symbol
163 // was already emitted, we can just forget about it, otherwise we need to
164 // queue it up for later emission when the function is output.
165 AddrLabelSymEntry Entry = AddrLabelSymbols[BB];
166 AddrLabelSymbols.erase(BB);
167 assert(!Entry.Symbols.isNull() && "Didn't have a symbol, why a callback?");
168 BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
170 assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
171 "Block/parent mismatch");
173 // Handle both the single and the multiple symbols cases.
174 if (MCSymbol *Sym = Entry.Symbols.dyn_cast<MCSymbol*>()) {
175 if (Sym->isDefined())
178 // If the block is not yet defined, we need to emit it at the end of the
179 // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
180 // for the containing Function. Since the block is being deleted, its
181 // parent may already be removed, we have to get the function from 'Entry'.
182 DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
184 std::vector<MCSymbol*> *Syms = Entry.Symbols.get<std::vector<MCSymbol*>*>();
186 for (unsigned i = 0, e = Syms->size(); i != e; ++i) {
187 MCSymbol *Sym = (*Syms)[i];
188 if (Sym->isDefined()) continue; // Ignore already emitted labels.
190 // If the block is not yet defined, we need to emit it at the end of the
191 // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
192 // for the containing Function. Since the block is being deleted, its
193 // parent may already be removed, we have to get the function from
195 DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
198 // The entry is deleted, free the memory associated with the symbol list.
203 void MMIAddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
204 // Get the entry for the RAUW'd block and remove it from our map.
205 AddrLabelSymEntry OldEntry = AddrLabelSymbols[Old];
206 AddrLabelSymbols.erase(Old);
207 assert(!OldEntry.Symbols.isNull() && "Didn't have a symbol, why a callback?");
209 AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
211 // If New is not address taken, just move our symbol over to it.
212 if (NewEntry.Symbols.isNull()) {
213 BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
214 NewEntry = OldEntry; // Set New's entry.
218 BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
220 // Otherwise, we need to add the old symbol to the new block's set. If it is
221 // just a single entry, upgrade it to a symbol list.
222 if (MCSymbol *PrevSym = NewEntry.Symbols.dyn_cast<MCSymbol*>()) {
223 std::vector<MCSymbol*> *SymList = new std::vector<MCSymbol*>();
224 SymList->push_back(PrevSym);
225 NewEntry.Symbols = SymList;
228 std::vector<MCSymbol*> *SymList =
229 NewEntry.Symbols.get<std::vector<MCSymbol*>*>();
231 // If the old entry was a single symbol, add it.
232 if (MCSymbol *Sym = OldEntry.Symbols.dyn_cast<MCSymbol*>()) {
233 SymList->push_back(Sym);
237 // Otherwise, concatenate the list.
238 std::vector<MCSymbol*> *Syms =OldEntry.Symbols.get<std::vector<MCSymbol*>*>();
239 SymList->insert(SymList->end(), Syms->begin(), Syms->end());
244 void MMIAddrLabelMapCallbackPtr::deleted() {
245 Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
248 void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
249 Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
253 //===----------------------------------------------------------------------===//
255 MachineModuleInfo::MachineModuleInfo(const MCAsmInfo &MAI,
256 const MCRegisterInfo &MRI,
257 const MCObjectFileInfo *MOFI)
258 : ImmutablePass(ID), Context(&MAI, &MRI, MOFI, nullptr, false) {
259 initializeMachineModuleInfoPass(*PassRegistry::getPassRegistry());
262 MachineModuleInfo::MachineModuleInfo()
263 : ImmutablePass(ID), Context(nullptr, nullptr, nullptr) {
264 llvm_unreachable("This MachineModuleInfo constructor should never be called, "
265 "MMI should always be explicitly constructed by "
266 "LLVMTargetMachine");
269 MachineModuleInfo::~MachineModuleInfo() {
272 bool MachineModuleInfo::doInitialization(Module &M) {
274 ObjFileMMI = nullptr;
278 DbgInfoAvailable = UsesVAFloatArgument = UsesMorestackAddr = false;
279 // Always emit some info, by default "no personality" info.
280 Personalities.push_back(nullptr);
281 PersonalityTypeCache = EHPersonality::Unknown;
282 AddrLabelSymbols = nullptr;
288 bool MachineModuleInfo::doFinalization(Module &M) {
290 Personalities.clear();
292 delete AddrLabelSymbols;
293 AddrLabelSymbols = nullptr;
298 ObjFileMMI = nullptr;
303 /// EndFunction - Discard function meta information.
305 void MachineModuleInfo::EndFunction() {
306 // Clean up frame info.
307 FrameInstructions.clear();
309 // Clean up exception info.
311 PersonalityTypeCache = EHPersonality::Unknown;
318 VariableDbgInfos.clear();
321 //===- Address of Block Management ----------------------------------------===//
324 /// getAddrLabelSymbol - Return the symbol to be used for the specified basic
325 /// block when its address is taken. This cannot be its normal LBB label
326 /// because the block may be accessed outside its containing function.
327 MCSymbol *MachineModuleInfo::getAddrLabelSymbol(const BasicBlock *BB) {
328 // Lazily create AddrLabelSymbols.
329 if (!AddrLabelSymbols)
330 AddrLabelSymbols = new MMIAddrLabelMap(Context);
331 return AddrLabelSymbols->getAddrLabelSymbol(const_cast<BasicBlock*>(BB));
334 /// getAddrLabelSymbolToEmit - Return the symbol to be used for the specified
335 /// basic block when its address is taken. If other blocks were RAUW'd to
336 /// this one, we may have to emit them as well, return the whole set.
337 std::vector<MCSymbol*> MachineModuleInfo::
338 getAddrLabelSymbolToEmit(const BasicBlock *BB) {
339 // Lazily create AddrLabelSymbols.
340 if (!AddrLabelSymbols)
341 AddrLabelSymbols = new MMIAddrLabelMap(Context);
342 return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
346 /// takeDeletedSymbolsForFunction - If the specified function has had any
347 /// references to address-taken blocks generated, but the block got deleted,
348 /// return the symbol now so we can emit it. This prevents emitting a
349 /// reference to a symbol that has no definition.
350 void MachineModuleInfo::
351 takeDeletedSymbolsForFunction(const Function *F,
352 std::vector<MCSymbol*> &Result) {
353 // If no blocks have had their addresses taken, we're done.
354 if (!AddrLabelSymbols) return;
355 return AddrLabelSymbols->
356 takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
359 //===- EH -----------------------------------------------------------------===//
361 /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
362 /// specified MachineBasicBlock.
363 LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo
364 (MachineBasicBlock *LandingPad) {
365 unsigned N = LandingPads.size();
366 for (unsigned i = 0; i < N; ++i) {
367 LandingPadInfo &LP = LandingPads[i];
368 if (LP.LandingPadBlock == LandingPad)
372 LandingPads.push_back(LandingPadInfo(LandingPad));
373 return LandingPads[N];
376 /// addInvoke - Provide the begin and end labels of an invoke style call and
377 /// associate it with a try landing pad block.
378 void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad,
379 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
380 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
381 LP.BeginLabels.push_back(BeginLabel);
382 LP.EndLabels.push_back(EndLabel);
385 /// addLandingPad - Provide the label of a try LandingPad block.
387 MCSymbol *MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {
388 MCSymbol *LandingPadLabel = Context.createTempSymbol();
389 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
390 LP.LandingPadLabel = LandingPadLabel;
391 return LandingPadLabel;
394 /// addPersonality - Provide the personality function for the exception
396 void MachineModuleInfo::addPersonality(MachineBasicBlock *LandingPad,
397 const Function *Personality) {
398 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
399 LP.Personality = Personality;
401 for (unsigned i = 0; i < Personalities.size(); ++i)
402 if (Personalities[i] == Personality)
405 // If this is the first personality we're adding go
406 // ahead and add it at the beginning.
407 if (!Personalities[0])
408 Personalities[0] = Personality;
410 Personalities.push_back(Personality);
413 void MachineModuleInfo::addWinEHState(MachineBasicBlock *LandingPad,
415 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
416 LP.WinEHState = State;
419 /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
421 void MachineModuleInfo::
422 addCatchTypeInfo(MachineBasicBlock *LandingPad,
423 ArrayRef<const GlobalValue *> TyInfo) {
424 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
425 for (unsigned N = TyInfo.size(); N; --N)
426 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
429 /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
431 void MachineModuleInfo::
432 addFilterTypeInfo(MachineBasicBlock *LandingPad,
433 ArrayRef<const GlobalValue *> TyInfo) {
434 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
435 std::vector<unsigned> IdsInFilter(TyInfo.size());
436 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
437 IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
438 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
441 /// addCleanup - Add a cleanup action for a landing pad.
443 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {
444 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
445 LP.TypeIds.push_back(0);
448 void MachineModuleInfo::addSEHCatchHandler(MachineBasicBlock *LandingPad,
449 const Function *Filter,
450 const BlockAddress *RecoverBA) {
451 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
453 Handler.FilterOrFinally = Filter;
454 Handler.RecoverBA = RecoverBA;
455 LP.SEHHandlers.push_back(Handler);
458 void MachineModuleInfo::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
459 const Function *Cleanup) {
460 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
462 Handler.FilterOrFinally = Cleanup;
463 Handler.RecoverBA = nullptr;
464 LP.SEHHandlers.push_back(Handler);
467 /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
469 void MachineModuleInfo::TidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap) {
470 for (unsigned i = 0; i != LandingPads.size(); ) {
471 LandingPadInfo &LandingPad = LandingPads[i];
472 if (LandingPad.LandingPadLabel &&
473 !LandingPad.LandingPadLabel->isDefined() &&
474 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
475 LandingPad.LandingPadLabel = nullptr;
477 // Special case: we *should* emit LPs with null LP MBB. This indicates
479 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
480 LandingPads.erase(LandingPads.begin() + i);
484 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
485 MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
486 MCSymbol *EndLabel = LandingPad.EndLabels[j];
487 if ((BeginLabel->isDefined() ||
488 (LPMap && (*LPMap)[BeginLabel] != 0)) &&
489 (EndLabel->isDefined() ||
490 (LPMap && (*LPMap)[EndLabel] != 0))) continue;
492 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
493 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
497 // Remove landing pads with no try-ranges.
498 if (LandingPads[i].BeginLabels.empty()) {
499 LandingPads.erase(LandingPads.begin() + i);
503 // If there is no landing pad, ensure that the list of typeids is empty.
504 // If the only typeid is a cleanup, this is the same as having no typeids.
505 if (!LandingPad.LandingPadBlock ||
506 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
507 LandingPad.TypeIds.clear();
512 /// setCallSiteLandingPad - Map the landing pad's EH symbol to the call site
514 void MachineModuleInfo::setCallSiteLandingPad(MCSymbol *Sym,
515 ArrayRef<unsigned> Sites) {
516 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
519 /// getTypeIDFor - Return the type id for the specified typeinfo. This is
521 unsigned MachineModuleInfo::getTypeIDFor(const GlobalValue *TI) {
522 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
523 if (TypeInfos[i] == TI) return i + 1;
525 TypeInfos.push_back(TI);
526 return TypeInfos.size();
529 /// getFilterIDFor - Return the filter id for the specified typeinfos. This is
531 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {
532 // If the new filter coincides with the tail of an existing filter, then
533 // re-use the existing filter. Folding filters more than this requires
534 // re-ordering filters and/or their elements - probably not worth it.
535 for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
536 E = FilterEnds.end(); I != E; ++I) {
537 unsigned i = *I, j = TyIds.size();
540 if (FilterIds[--i] != TyIds[--j])
544 // The new filter coincides with range [i, end) of the existing filter.
550 // Add the new filter.
551 int FilterID = -(1 + FilterIds.size());
552 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
553 FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
554 FilterEnds.push_back(FilterIds.size());
555 FilterIds.push_back(0); // terminator
559 /// getPersonality - Return the personality function for the current function.
560 const Function *MachineModuleInfo::getPersonality() const {
561 for (const LandingPadInfo &LPI : LandingPads)
563 return LPI.Personality;
567 EHPersonality MachineModuleInfo::getPersonalityType() {
568 if (PersonalityTypeCache == EHPersonality::Unknown) {
569 if (const Function *F = getPersonality())
570 PersonalityTypeCache = classifyEHPersonality(F);
572 return PersonalityTypeCache;
575 /// getPersonalityIndex - Return unique index for current personality
576 /// function. NULL/first personality function should always get zero index.
577 unsigned MachineModuleInfo::getPersonalityIndex() const {
578 const Function* Personality = nullptr;
580 // Scan landing pads. If there is at least one non-NULL personality - use it.
581 for (unsigned i = 0, e = LandingPads.size(); i != e; ++i)
582 if (LandingPads[i].Personality) {
583 Personality = LandingPads[i].Personality;
587 for (unsigned i = 0, e = Personalities.size(); i < e; ++i) {
588 if (Personalities[i] == Personality)
592 // This will happen if the current personality function is
593 // in the zero index.
597 const Function *MachineModuleInfo::getWinEHParent(const Function *F) const {
598 StringRef WinEHParentName =
599 F->getFnAttribute("wineh-parent").getValueAsString();
600 if (WinEHParentName.empty() || WinEHParentName == F->getName())
602 return F->getParent()->getFunction(WinEHParentName);
605 WinEHFuncInfo &MachineModuleInfo::getWinEHFuncInfo(const Function *F) {
606 auto &Ptr = FuncInfoMap[getWinEHParent(F)];
608 Ptr.reset(new WinEHFuncInfo);