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