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 NextFnNum = 0; 200 UsesMSVCFloatingPoint = UsesMorestackAddr = false; 201 HasSplitStack = HasNosplitStack = false; 202 AddrLabelSymbols = nullptr; 203 } 204 205 void MachineModuleInfo::finalize() { 206 Personalities.clear(); 207 208 delete AddrLabelSymbols; 209 AddrLabelSymbols = nullptr; 210 211 Context.reset(); 212 // We don't clear the ExternalContext. 213 214 delete ObjFileMMI; 215 ObjFileMMI = nullptr; 216 } 217 218 MachineModuleInfo::MachineModuleInfo(MachineModuleInfo &&MMI) 219 : TM(std::move(MMI.TM)), 220 Context(MMI.TM.getMCAsmInfo(), MMI.TM.getMCRegisterInfo(), 221 MMI.TM.getObjFileLowering(), nullptr, nullptr, false), 222 MachineFunctions(std::move(MMI.MachineFunctions)) { 223 ObjFileMMI = MMI.ObjFileMMI; 224 CurCallSite = MMI.CurCallSite; 225 UsesMSVCFloatingPoint = MMI.UsesMSVCFloatingPoint; 226 UsesMorestackAddr = MMI.UsesMorestackAddr; 227 HasSplitStack = MMI.HasSplitStack; 228 HasNosplitStack = MMI.HasNosplitStack; 229 AddrLabelSymbols = MMI.AddrLabelSymbols; 230 ExternalContext = MMI.ExternalContext; 231 TheModule = MMI.TheModule; 232 } 233 234 MachineModuleInfo::MachineModuleInfo(const LLVMTargetMachine *TM) 235 : TM(*TM), Context(TM->getMCAsmInfo(), TM->getMCRegisterInfo(), 236 TM->getObjFileLowering(), nullptr, nullptr, false) { 237 initialize(); 238 } 239 240 MachineModuleInfo::MachineModuleInfo(const LLVMTargetMachine *TM, 241 MCContext *ExtContext) 242 : TM(*TM), Context(TM->getMCAsmInfo(), TM->getMCRegisterInfo(), 243 TM->getObjFileLowering(), nullptr, nullptr, false), 244 ExternalContext(ExtContext) { 245 initialize(); 246 } 247 248 MachineModuleInfo::~MachineModuleInfo() { finalize(); } 249 250 //===- Address of Block Management ----------------------------------------===// 251 252 ArrayRef<MCSymbol *> 253 MachineModuleInfo::getAddrLabelSymbolToEmit(const BasicBlock *BB) { 254 // Lazily create AddrLabelSymbols. 255 if (!AddrLabelSymbols) 256 AddrLabelSymbols = new MMIAddrLabelMap(getContext()); 257 return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB)); 258 } 259 260 void MachineModuleInfo:: 261 takeDeletedSymbolsForFunction(const Function *F, 262 std::vector<MCSymbol*> &Result) { 263 // If no blocks have had their addresses taken, we're done. 264 if (!AddrLabelSymbols) return; 265 return AddrLabelSymbols-> 266 takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result); 267 } 268 269 /// \name Exception Handling 270 /// \{ 271 272 void MachineModuleInfo::addPersonality(const Function *Personality) { 273 if (!llvm::is_contained(Personalities, Personality)) 274 Personalities.push_back(Personality); 275 } 276 277 /// \} 278 279 MachineFunction * 280 MachineModuleInfo::getMachineFunction(const Function &F) const { 281 auto I = MachineFunctions.find(&F); 282 return I != MachineFunctions.end() ? I->second.get() : nullptr; 283 } 284 285 MachineFunction &MachineModuleInfo::getOrCreateMachineFunction(Function &F) { 286 // Shortcut for the common case where a sequence of MachineFunctionPasses 287 // all query for the same Function. 288 if (LastRequest == &F) 289 return *LastResult; 290 291 auto I = MachineFunctions.insert( 292 std::make_pair(&F, std::unique_ptr<MachineFunction>())); 293 MachineFunction *MF; 294 if (I.second) { 295 // No pre-existing machine function, create a new one. 296 const TargetSubtargetInfo &STI = *TM.getSubtargetImpl(F); 297 MF = new MachineFunction(F, TM, STI, NextFnNum++, *this); 298 // Update the set entry. 299 I.first->second.reset(MF); 300 } else { 301 MF = I.first->second.get(); 302 } 303 304 LastRequest = &F; 305 LastResult = MF; 306 return *MF; 307 } 308 309 void MachineModuleInfo::deleteMachineFunctionFor(Function &F) { 310 MachineFunctions.erase(&F); 311 LastRequest = nullptr; 312 LastResult = nullptr; 313 } 314 315 namespace { 316 317 /// This pass frees the MachineFunction object associated with a Function. 318 class FreeMachineFunction : public FunctionPass { 319 public: 320 static char ID; 321 322 FreeMachineFunction() : FunctionPass(ID) {} 323 324 void getAnalysisUsage(AnalysisUsage &AU) const override { 325 AU.addRequired<MachineModuleInfoWrapperPass>(); 326 AU.addPreserved<MachineModuleInfoWrapperPass>(); 327 } 328 329 bool runOnFunction(Function &F) override { 330 MachineModuleInfo &MMI = 331 getAnalysis<MachineModuleInfoWrapperPass>().getMMI(); 332 MMI.deleteMachineFunctionFor(F); 333 return true; 334 } 335 336 StringRef getPassName() const override { 337 return "Free MachineFunction"; 338 } 339 }; 340 341 } // end anonymous namespace 342 343 char FreeMachineFunction::ID; 344 345 FunctionPass *llvm::createFreeMachineFunctionPass() { 346 return new FreeMachineFunction(); 347 } 348 349 MachineModuleInfoWrapperPass::MachineModuleInfoWrapperPass( 350 const LLVMTargetMachine *TM) 351 : ImmutablePass(ID), MMI(TM) { 352 initializeMachineModuleInfoWrapperPassPass(*PassRegistry::getPassRegistry()); 353 } 354 355 MachineModuleInfoWrapperPass::MachineModuleInfoWrapperPass( 356 const LLVMTargetMachine *TM, MCContext *ExtContext) 357 : ImmutablePass(ID), MMI(TM, ExtContext) { 358 initializeMachineModuleInfoWrapperPassPass(*PassRegistry::getPassRegistry()); 359 } 360 361 // Handle the Pass registration stuff necessary to use DataLayout's. 362 INITIALIZE_PASS(MachineModuleInfoWrapperPass, "machinemoduleinfo", 363 "Machine Module Information", false, false) 364 char MachineModuleInfoWrapperPass::ID = 0; 365 366 static unsigned getLocCookie(const SMDiagnostic &SMD, const SourceMgr &SrcMgr, 367 std::vector<const MDNode *> &LocInfos) { 368 // Look up a LocInfo for the buffer this diagnostic is coming from. 369 unsigned BufNum = SrcMgr.FindBufferContainingLoc(SMD.getLoc()); 370 const MDNode *LocInfo = nullptr; 371 if (BufNum > 0 && BufNum <= LocInfos.size()) 372 LocInfo = LocInfos[BufNum - 1]; 373 374 // If the inline asm had metadata associated with it, pull out a location 375 // cookie corresponding to which line the error occurred on. 376 unsigned LocCookie = 0; 377 if (LocInfo) { 378 unsigned ErrorLine = SMD.getLineNo() - 1; 379 if (ErrorLine >= LocInfo->getNumOperands()) 380 ErrorLine = 0; 381 382 if (LocInfo->getNumOperands() != 0) 383 if (const ConstantInt *CI = 384 mdconst::dyn_extract<ConstantInt>(LocInfo->getOperand(ErrorLine))) 385 LocCookie = CI->getZExtValue(); 386 } 387 388 return LocCookie; 389 } 390 391 bool MachineModuleInfoWrapperPass::doInitialization(Module &M) { 392 MMI.initialize(); 393 MMI.TheModule = &M; 394 // FIXME: Do this for new pass manager. 395 LLVMContext &Ctx = M.getContext(); 396 MMI.getContext().setDiagnosticHandler( 397 [&Ctx](const SMDiagnostic &SMD, bool IsInlineAsm, const SourceMgr &SrcMgr, 398 std::vector<const MDNode *> &LocInfos) { 399 unsigned LocCookie = 0; 400 if (IsInlineAsm) 401 LocCookie = getLocCookie(SMD, SrcMgr, LocInfos); 402 Ctx.diagnose(DiagnosticInfoSrcMgr(SMD, IsInlineAsm, LocCookie)); 403 }); 404 MMI.DbgInfoAvailable = !M.debug_compile_units().empty(); 405 return false; 406 } 407 408 bool MachineModuleInfoWrapperPass::doFinalization(Module &M) { 409 MMI.finalize(); 410 return false; 411 } 412 413 AnalysisKey MachineModuleAnalysis::Key; 414 415 MachineModuleInfo MachineModuleAnalysis::run(Module &M, 416 ModuleAnalysisManager &) { 417 MachineModuleInfo MMI(TM); 418 MMI.TheModule = &M; 419 MMI.DbgInfoAvailable = !M.debug_compile_units().empty(); 420 return MMI; 421 } 422