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 10 #include "llvm/CodeGen/MachineModuleInfo.h" 11 #include "llvm/ADT/PointerUnion.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/Module.h" 23 #include "llvm/MC/MCObjectFileInfo.h" 24 #include "llvm/MC/MCSymbol.h" 25 #include "llvm/Support/Dwarf.h" 26 #include "llvm/Support/ErrorHandling.h" 27 #include "llvm/Target/TargetLoweringObjectFile.h" 28 #include "llvm/Target/TargetMachine.h" 29 using namespace llvm; 30 using namespace llvm::dwarf; 31 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 37 // Out of line virtual method. 38 MachineModuleInfoImpl::~MachineModuleInfoImpl() {} 39 40 namespace llvm { 41 class MMIAddrLabelMapCallbackPtr final : CallbackVH { 42 MMIAddrLabelMap *Map; 43 public: 44 MMIAddrLabelMapCallbackPtr() : Map(nullptr) {} 45 MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V), Map(nullptr) {} 46 47 void setPtr(BasicBlock *BB) { 48 ValueHandleBase::operator=(BB); 49 } 50 51 void setMap(MMIAddrLabelMap *map) { Map = map; } 52 53 void deleted() override; 54 void allUsesReplacedWith(Value *V2) override; 55 }; 56 57 class MMIAddrLabelMap { 58 MCContext &Context; 59 struct AddrLabelSymEntry { 60 /// Symbols - The symbols for the label. 61 TinyPtrVector<MCSymbol *> Symbols; 62 63 Function *Fn; // The containing function of the BasicBlock. 64 unsigned Index; // The index in BBCallbacks for the BasicBlock. 65 }; 66 67 DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols; 68 69 /// BBCallbacks - Callbacks for the BasicBlock's that we have entries for. We 70 /// use this so we get notified if a block is deleted or RAUWd. 71 std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks; 72 73 /// DeletedAddrLabelsNeedingEmission - This is a per-function list of symbols 74 /// whose corresponding BasicBlock got deleted. These symbols need to be 75 /// emitted at some point in the file, so AsmPrinter emits them after the 76 /// function body. 77 DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> > 78 DeletedAddrLabelsNeedingEmission; 79 public: 80 81 MMIAddrLabelMap(MCContext &context) : Context(context) {} 82 ~MMIAddrLabelMap() { 83 assert(DeletedAddrLabelsNeedingEmission.empty() && 84 "Some labels for deleted blocks never got emitted"); 85 } 86 87 ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB); 88 89 void takeDeletedSymbolsForFunction(Function *F, 90 std::vector<MCSymbol*> &Result); 91 92 void UpdateForDeletedBlock(BasicBlock *BB); 93 void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New); 94 }; 95 } 96 97 ArrayRef<MCSymbol *> MMIAddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) { 98 assert(BB->hasAddressTaken() && 99 "Shouldn't get label for block without address taken"); 100 AddrLabelSymEntry &Entry = AddrLabelSymbols[BB]; 101 102 // If we already had an entry for this block, just return it. 103 if (!Entry.Symbols.empty()) { 104 assert(BB->getParent() == Entry.Fn && "Parent changed"); 105 return Entry.Symbols; 106 } 107 108 // Otherwise, this is a new entry, create a new symbol for it and add an 109 // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd. 110 BBCallbacks.emplace_back(BB); 111 BBCallbacks.back().setMap(this); 112 Entry.Index = BBCallbacks.size() - 1; 113 Entry.Fn = BB->getParent(); 114 Entry.Symbols.push_back(Context.createTempSymbol()); 115 return Entry.Symbols; 116 } 117 118 /// takeDeletedSymbolsForFunction - If we have any deleted symbols for F, return 119 /// them. 120 void MMIAddrLabelMap:: 121 takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) { 122 DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >::iterator I = 123 DeletedAddrLabelsNeedingEmission.find(F); 124 125 // If there are no entries for the function, just return. 126 if (I == DeletedAddrLabelsNeedingEmission.end()) return; 127 128 // Otherwise, take the list. 129 std::swap(Result, I->second); 130 DeletedAddrLabelsNeedingEmission.erase(I); 131 } 132 133 134 void MMIAddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) { 135 // If the block got deleted, there is no need for the symbol. If the symbol 136 // was already emitted, we can just forget about it, otherwise we need to 137 // queue it up for later emission when the function is output. 138 AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]); 139 AddrLabelSymbols.erase(BB); 140 assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?"); 141 BBCallbacks[Entry.Index] = nullptr; // Clear the callback. 142 143 assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) && 144 "Block/parent mismatch"); 145 146 for (MCSymbol *Sym : Entry.Symbols) { 147 if (Sym->isDefined()) 148 return; 149 150 // If the block is not yet defined, we need to emit it at the end of the 151 // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list 152 // for the containing Function. Since the block is being deleted, its 153 // parent may already be removed, we have to get the function from 'Entry'. 154 DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym); 155 } 156 } 157 158 void MMIAddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) { 159 // Get the entry for the RAUW'd block and remove it from our map. 160 AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]); 161 AddrLabelSymbols.erase(Old); 162 assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?"); 163 164 AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New]; 165 166 // If New is not address taken, just move our symbol over to it. 167 if (NewEntry.Symbols.empty()) { 168 BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback. 169 NewEntry = std::move(OldEntry); // Set New's entry. 170 return; 171 } 172 173 BBCallbacks[OldEntry.Index] = nullptr; // Update the callback. 174 175 // Otherwise, we need to add the old symbols to the new block's set. 176 NewEntry.Symbols.insert(NewEntry.Symbols.end(), OldEntry.Symbols.begin(), 177 OldEntry.Symbols.end()); 178 } 179 180 181 void MMIAddrLabelMapCallbackPtr::deleted() { 182 Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr())); 183 } 184 185 void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) { 186 Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2)); 187 } 188 189 190 //===----------------------------------------------------------------------===// 191 192 MachineModuleInfo::MachineModuleInfo(const TargetMachine *TM) 193 : ImmutablePass(ID), TM(*TM), 194 Context(TM->getMCAsmInfo(), TM->getMCRegisterInfo(), 195 TM->getObjFileLowering(), nullptr, false) { 196 initializeMachineModuleInfoPass(*PassRegistry::getPassRegistry()); 197 } 198 199 MachineModuleInfo::~MachineModuleInfo() { 200 } 201 202 bool MachineModuleInfo::doInitialization(Module &M) { 203 204 ObjFileMMI = nullptr; 205 CurCallSite = 0; 206 CallsEHReturn = false; 207 CallsUnwindInit = false; 208 HasEHFunclets = false; 209 DbgInfoAvailable = UsesVAFloatArgument = UsesMorestackAddr = false; 210 PersonalityTypeCache = EHPersonality::Unknown; 211 AddrLabelSymbols = nullptr; 212 TheModule = &M; 213 214 return false; 215 } 216 217 bool MachineModuleInfo::doFinalization(Module &M) { 218 219 Personalities.clear(); 220 221 delete AddrLabelSymbols; 222 AddrLabelSymbols = nullptr; 223 224 Context.reset(); 225 226 delete ObjFileMMI; 227 ObjFileMMI = nullptr; 228 229 return false; 230 } 231 232 /// EndFunction - Discard function meta information. 233 /// 234 void MachineModuleInfo::EndFunction() { 235 // Clean up frame info. 236 FrameInstructions.clear(); 237 238 // Clean up exception info. 239 LandingPads.clear(); 240 PersonalityTypeCache = EHPersonality::Unknown; 241 CallSiteMap.clear(); 242 TypeInfos.clear(); 243 FilterIds.clear(); 244 FilterEnds.clear(); 245 CallsEHReturn = false; 246 CallsUnwindInit = false; 247 HasEHFunclets = false; 248 VariableDbgInfos.clear(); 249 } 250 251 //===- Address of Block Management ----------------------------------------===// 252 253 /// getAddrLabelSymbolToEmit - Return the symbol to be used for the specified 254 /// basic block when its address is taken. If other blocks were RAUW'd to 255 /// this one, we may have to emit them as well, return the whole set. 256 ArrayRef<MCSymbol *> 257 MachineModuleInfo::getAddrLabelSymbolToEmit(const BasicBlock *BB) { 258 // Lazily create AddrLabelSymbols. 259 if (!AddrLabelSymbols) 260 AddrLabelSymbols = new MMIAddrLabelMap(Context); 261 return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB)); 262 } 263 264 265 /// takeDeletedSymbolsForFunction - If the specified function has had any 266 /// references to address-taken blocks generated, but the block got deleted, 267 /// return the symbol now so we can emit it. This prevents emitting a 268 /// reference to a symbol that has no definition. 269 void MachineModuleInfo:: 270 takeDeletedSymbolsForFunction(const Function *F, 271 std::vector<MCSymbol*> &Result) { 272 // If no blocks have had their addresses taken, we're done. 273 if (!AddrLabelSymbols) return; 274 return AddrLabelSymbols-> 275 takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result); 276 } 277 278 //===- EH -----------------------------------------------------------------===// 279 280 /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the 281 /// specified MachineBasicBlock. 282 LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo 283 (MachineBasicBlock *LandingPad) { 284 unsigned N = LandingPads.size(); 285 for (unsigned i = 0; i < N; ++i) { 286 LandingPadInfo &LP = LandingPads[i]; 287 if (LP.LandingPadBlock == LandingPad) 288 return LP; 289 } 290 291 LandingPads.push_back(LandingPadInfo(LandingPad)); 292 return LandingPads[N]; 293 } 294 295 /// addInvoke - Provide the begin and end labels of an invoke style call and 296 /// associate it with a try landing pad block. 297 void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad, 298 MCSymbol *BeginLabel, MCSymbol *EndLabel) { 299 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 300 LP.BeginLabels.push_back(BeginLabel); 301 LP.EndLabels.push_back(EndLabel); 302 } 303 304 /// addLandingPad - Provide the label of a try LandingPad block. 305 /// 306 MCSymbol *MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) { 307 MCSymbol *LandingPadLabel = Context.createTempSymbol(); 308 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 309 LP.LandingPadLabel = LandingPadLabel; 310 return LandingPadLabel; 311 } 312 313 void MachineModuleInfo::addPersonality(const Function *Personality) { 314 for (unsigned i = 0; i < Personalities.size(); ++i) 315 if (Personalities[i] == Personality) 316 return; 317 Personalities.push_back(Personality); 318 } 319 320 /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad. 321 /// 322 void MachineModuleInfo:: 323 addCatchTypeInfo(MachineBasicBlock *LandingPad, 324 ArrayRef<const GlobalValue *> TyInfo) { 325 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 326 for (unsigned N = TyInfo.size(); N; --N) 327 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1])); 328 } 329 330 /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad. 331 /// 332 void MachineModuleInfo:: 333 addFilterTypeInfo(MachineBasicBlock *LandingPad, 334 ArrayRef<const GlobalValue *> TyInfo) { 335 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 336 std::vector<unsigned> IdsInFilter(TyInfo.size()); 337 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I) 338 IdsInFilter[I] = getTypeIDFor(TyInfo[I]); 339 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter)); 340 } 341 342 /// addCleanup - Add a cleanup action for a landing pad. 343 /// 344 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) { 345 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 346 LP.TypeIds.push_back(0); 347 } 348 349 void MachineModuleInfo::addSEHCatchHandler(MachineBasicBlock *LandingPad, 350 const Function *Filter, 351 const BlockAddress *RecoverBA) { 352 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 353 SEHHandler Handler; 354 Handler.FilterOrFinally = Filter; 355 Handler.RecoverBA = RecoverBA; 356 LP.SEHHandlers.push_back(Handler); 357 } 358 359 void MachineModuleInfo::addSEHCleanupHandler(MachineBasicBlock *LandingPad, 360 const Function *Cleanup) { 361 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 362 SEHHandler Handler; 363 Handler.FilterOrFinally = Cleanup; 364 Handler.RecoverBA = nullptr; 365 LP.SEHHandlers.push_back(Handler); 366 } 367 368 /// TidyLandingPads - Remap landing pad labels and remove any deleted landing 369 /// pads. 370 void MachineModuleInfo::TidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap) { 371 for (unsigned i = 0; i != LandingPads.size(); ) { 372 LandingPadInfo &LandingPad = LandingPads[i]; 373 if (LandingPad.LandingPadLabel && 374 !LandingPad.LandingPadLabel->isDefined() && 375 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0)) 376 LandingPad.LandingPadLabel = nullptr; 377 378 // Special case: we *should* emit LPs with null LP MBB. This indicates 379 // "nounwind" case. 380 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) { 381 LandingPads.erase(LandingPads.begin() + i); 382 continue; 383 } 384 385 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) { 386 MCSymbol *BeginLabel = LandingPad.BeginLabels[j]; 387 MCSymbol *EndLabel = LandingPad.EndLabels[j]; 388 if ((BeginLabel->isDefined() || 389 (LPMap && (*LPMap)[BeginLabel] != 0)) && 390 (EndLabel->isDefined() || 391 (LPMap && (*LPMap)[EndLabel] != 0))) continue; 392 393 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j); 394 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j); 395 --j; 396 --e; 397 } 398 399 // Remove landing pads with no try-ranges. 400 if (LandingPads[i].BeginLabels.empty()) { 401 LandingPads.erase(LandingPads.begin() + i); 402 continue; 403 } 404 405 // If there is no landing pad, ensure that the list of typeids is empty. 406 // If the only typeid is a cleanup, this is the same as having no typeids. 407 if (!LandingPad.LandingPadBlock || 408 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0])) 409 LandingPad.TypeIds.clear(); 410 ++i; 411 } 412 } 413 414 /// setCallSiteLandingPad - Map the landing pad's EH symbol to the call site 415 /// indexes. 416 void MachineModuleInfo::setCallSiteLandingPad(MCSymbol *Sym, 417 ArrayRef<unsigned> Sites) { 418 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end()); 419 } 420 421 /// getTypeIDFor - Return the type id for the specified typeinfo. This is 422 /// function wide. 423 unsigned MachineModuleInfo::getTypeIDFor(const GlobalValue *TI) { 424 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i) 425 if (TypeInfos[i] == TI) return i + 1; 426 427 TypeInfos.push_back(TI); 428 return TypeInfos.size(); 429 } 430 431 /// getFilterIDFor - Return the filter id for the specified typeinfos. This is 432 /// function wide. 433 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) { 434 // If the new filter coincides with the tail of an existing filter, then 435 // re-use the existing filter. Folding filters more than this requires 436 // re-ordering filters and/or their elements - probably not worth it. 437 for (std::vector<unsigned>::iterator I = FilterEnds.begin(), 438 E = FilterEnds.end(); I != E; ++I) { 439 unsigned i = *I, j = TyIds.size(); 440 441 while (i && j) 442 if (FilterIds[--i] != TyIds[--j]) 443 goto try_next; 444 445 if (!j) 446 // The new filter coincides with range [i, end) of the existing filter. 447 return -(1 + i); 448 449 try_next:; 450 } 451 452 // Add the new filter. 453 int FilterID = -(1 + FilterIds.size()); 454 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1); 455 FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end()); 456 FilterEnds.push_back(FilterIds.size()); 457 FilterIds.push_back(0); // terminator 458 return FilterID; 459 } 460 461 MachineFunction &MachineModuleInfo::getMachineFunction(const Function &F) { 462 // Shortcut for the common case where a sequence of MachineFunctionPasses 463 // all query for the same Function. 464 if (LastRequest == &F) 465 return *LastResult; 466 467 auto I = MachineFunctions.insert( 468 std::make_pair(&F, std::unique_ptr<MachineFunction>())); 469 MachineFunction *MF; 470 if (I.second) { 471 // No pre-existing machine function, create a new one. 472 MF = new MachineFunction(&F, TM, NextFnNum++, *this); 473 // Update the set entry. 474 I.first->second.reset(MF); 475 476 if (MFInitializer) 477 if (MFInitializer->initializeMachineFunction(*MF)) 478 report_fatal_error("Unable to initialize machine function"); 479 } else { 480 MF = I.first->second.get(); 481 } 482 483 LastRequest = &F; 484 LastResult = MF; 485 return *MF; 486 } 487 488 void MachineModuleInfo::deleteMachineFunctionFor(Function &F) { 489 MachineFunctions.erase(&F); 490 LastRequest = nullptr; 491 LastResult = nullptr; 492 } 493 494 namespace { 495 /// This pass frees the MachineFunction object associated with a Function. 496 class FreeMachineFunction : public FunctionPass { 497 public: 498 static char ID; 499 FreeMachineFunction() : FunctionPass(ID) {} 500 501 void getAnalysisUsage(AnalysisUsage &AU) const override { 502 AU.addRequired<MachineModuleInfo>(); 503 AU.addPreserved<MachineModuleInfo>(); 504 } 505 506 bool runOnFunction(Function &F) override { 507 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>(); 508 MMI.deleteMachineFunctionFor(F); 509 return true; 510 } 511 }; 512 char FreeMachineFunction::ID; 513 } // end anonymous namespace 514 515 namespace llvm { 516 FunctionPass *createFreeMachineFunctionPass() { 517 return new FreeMachineFunction(); 518 } 519 } // end namespace llvm 520