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/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" 26 using namespace llvm; 27 using namespace llvm::dwarf; 28 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; 33 34 // Out of line virtual method. 35 MachineModuleInfoImpl::~MachineModuleInfoImpl() {} 36 37 namespace llvm { 38 class MMIAddrLabelMapCallbackPtr : CallbackVH { 39 MMIAddrLabelMap *Map; 40 public: 41 MMIAddrLabelMapCallbackPtr() : Map(nullptr) {} 42 MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V), Map(nullptr) {} 43 44 void setPtr(BasicBlock *BB) { 45 ValueHandleBase::operator=(BB); 46 } 47 48 void setMap(MMIAddrLabelMap *map) { Map = map; } 49 50 void deleted() override; 51 void allUsesReplacedWith(Value *V2) override; 52 }; 53 54 class MMIAddrLabelMap { 55 MCContext &Context; 56 struct AddrLabelSymEntry { 57 /// Symbols - The symbols for the label. 58 TinyPtrVector<MCSymbol *> Symbols; 59 60 Function *Fn; // The containing function of the BasicBlock. 61 unsigned Index; // The index in BBCallbacks for the BasicBlock. 62 }; 63 64 DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols; 65 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; 69 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 73 /// function body. 74 DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> > 75 DeletedAddrLabelsNeedingEmission; 76 public: 77 78 MMIAddrLabelMap(MCContext &context) : Context(context) {} 79 ~MMIAddrLabelMap() { 80 assert(DeletedAddrLabelsNeedingEmission.empty() && 81 "Some labels for deleted blocks never got emitted"); 82 } 83 84 ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB); 85 86 void takeDeletedSymbolsForFunction(Function *F, 87 std::vector<MCSymbol*> &Result); 88 89 void UpdateForDeletedBlock(BasicBlock *BB); 90 void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New); 91 }; 92 } 93 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]; 98 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; 103 } 104 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; 113 } 114 115 /// takeDeletedSymbolsForFunction - If we have any deleted symbols for F, return 116 /// them. 117 void MMIAddrLabelMap:: 118 takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) { 119 DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >::iterator I = 120 DeletedAddrLabelsNeedingEmission.find(F); 121 122 // If there are no entries for the function, just return. 123 if (I == DeletedAddrLabelsNeedingEmission.end()) return; 124 125 // Otherwise, take the list. 126 std::swap(Result, I->second); 127 DeletedAddrLabelsNeedingEmission.erase(I); 128 } 129 130 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. 139 140 assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) && 141 "Block/parent mismatch"); 142 143 for (MCSymbol *Sym : Entry.Symbols) { 144 if (Sym->isDefined()) 145 return; 146 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); 152 } 153 } 154 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?"); 160 161 AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New]; 162 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. 167 return; 168 } 169 170 BBCallbacks[OldEntry.Index] = nullptr; // Update the callback. 171 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()); 175 } 176 177 178 void MMIAddrLabelMapCallbackPtr::deleted() { 179 Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr())); 180 } 181 182 void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) { 183 Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2)); 184 } 185 186 187 //===----------------------------------------------------------------------===// 188 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()); 194 } 195 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"); 201 } 202 203 MachineModuleInfo::~MachineModuleInfo() { 204 } 205 206 bool MachineModuleInfo::doInitialization(Module &M) { 207 208 ObjFileMMI = nullptr; 209 CurCallSite = 0; 210 CallsEHReturn = false; 211 CallsUnwindInit = false; 212 DbgInfoAvailable = UsesVAFloatArgument = UsesMorestackAddr = false; 213 // Always emit some info, by default "no personality" info. 214 Personalities.push_back(nullptr); 215 PersonalityTypeCache = EHPersonality::Unknown; 216 AddrLabelSymbols = nullptr; 217 TheModule = nullptr; 218 219 return false; 220 } 221 222 bool MachineModuleInfo::doFinalization(Module &M) { 223 224 Personalities.clear(); 225 226 delete AddrLabelSymbols; 227 AddrLabelSymbols = nullptr; 228 229 Context.reset(); 230 231 delete ObjFileMMI; 232 ObjFileMMI = nullptr; 233 234 return false; 235 } 236 237 /// EndFunction - Discard function meta information. 238 /// 239 void MachineModuleInfo::EndFunction() { 240 // Clean up frame info. 241 FrameInstructions.clear(); 242 243 // Clean up exception info. 244 LandingPads.clear(); 245 PersonalityTypeCache = EHPersonality::Unknown; 246 CallSiteMap.clear(); 247 TypeInfos.clear(); 248 FilterIds.clear(); 249 FilterEnds.clear(); 250 CallsEHReturn = false; 251 CallsUnwindInit = false; 252 VariableDbgInfos.clear(); 253 } 254 255 //===- Address of Block Management ----------------------------------------===// 256 257 /// getAddrLabelSymbolToEmit - Return the symbol to be used for the specified 258 /// basic block when its address is taken. If other blocks were RAUW'd to 259 /// this one, we may have to emit them as well, return the whole set. 260 ArrayRef<MCSymbol *> 261 MachineModuleInfo::getAddrLabelSymbolToEmit(const BasicBlock *BB) { 262 // Lazily create AddrLabelSymbols. 263 if (!AddrLabelSymbols) 264 AddrLabelSymbols = new MMIAddrLabelMap(Context); 265 return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB)); 266 } 267 268 269 /// takeDeletedSymbolsForFunction - If the specified function has had any 270 /// references to address-taken blocks generated, but the block got deleted, 271 /// return the symbol now so we can emit it. This prevents emitting a 272 /// reference to a symbol that has no definition. 273 void MachineModuleInfo:: 274 takeDeletedSymbolsForFunction(const Function *F, 275 std::vector<MCSymbol*> &Result) { 276 // If no blocks have had their addresses taken, we're done. 277 if (!AddrLabelSymbols) return; 278 return AddrLabelSymbols-> 279 takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result); 280 } 281 282 //===- EH -----------------------------------------------------------------===// 283 284 /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the 285 /// specified MachineBasicBlock. 286 LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo 287 (MachineBasicBlock *LandingPad) { 288 unsigned N = LandingPads.size(); 289 for (unsigned i = 0; i < N; ++i) { 290 LandingPadInfo &LP = LandingPads[i]; 291 if (LP.LandingPadBlock == LandingPad) 292 return LP; 293 } 294 295 LandingPads.push_back(LandingPadInfo(LandingPad)); 296 return LandingPads[N]; 297 } 298 299 /// addInvoke - Provide the begin and end labels of an invoke style call and 300 /// associate it with a try landing pad block. 301 void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad, 302 MCSymbol *BeginLabel, MCSymbol *EndLabel) { 303 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 304 LP.BeginLabels.push_back(BeginLabel); 305 LP.EndLabels.push_back(EndLabel); 306 } 307 308 /// addLandingPad - Provide the label of a try LandingPad block. 309 /// 310 MCSymbol *MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) { 311 MCSymbol *LandingPadLabel = Context.createTempSymbol(); 312 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 313 LP.LandingPadLabel = LandingPadLabel; 314 return LandingPadLabel; 315 } 316 317 /// addPersonality - Provide the personality function for the exception 318 /// information. 319 void MachineModuleInfo::addPersonality(MachineBasicBlock *LandingPad, 320 const Function *Personality) { 321 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 322 LP.Personality = Personality; 323 324 for (unsigned i = 0; i < Personalities.size(); ++i) 325 if (Personalities[i] == Personality) 326 return; 327 328 // If this is the first personality we're adding go 329 // ahead and add it at the beginning. 330 if (!Personalities[0]) 331 Personalities[0] = Personality; 332 else 333 Personalities.push_back(Personality); 334 } 335 336 void MachineModuleInfo::addWinEHState(MachineBasicBlock *LandingPad, 337 int State) { 338 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 339 LP.WinEHState = State; 340 } 341 342 /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad. 343 /// 344 void MachineModuleInfo:: 345 addCatchTypeInfo(MachineBasicBlock *LandingPad, 346 ArrayRef<const GlobalValue *> TyInfo) { 347 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 348 for (unsigned N = TyInfo.size(); N; --N) 349 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1])); 350 } 351 352 /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad. 353 /// 354 void MachineModuleInfo:: 355 addFilterTypeInfo(MachineBasicBlock *LandingPad, 356 ArrayRef<const GlobalValue *> TyInfo) { 357 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 358 std::vector<unsigned> IdsInFilter(TyInfo.size()); 359 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I) 360 IdsInFilter[I] = getTypeIDFor(TyInfo[I]); 361 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter)); 362 } 363 364 /// addCleanup - Add a cleanup action for a landing pad. 365 /// 366 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) { 367 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 368 LP.TypeIds.push_back(0); 369 } 370 371 void MachineModuleInfo::addSEHCatchHandler(MachineBasicBlock *LandingPad, 372 const Function *Filter, 373 const BlockAddress *RecoverBA) { 374 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 375 SEHHandler Handler; 376 Handler.FilterOrFinally = Filter; 377 Handler.RecoverBA = RecoverBA; 378 LP.SEHHandlers.push_back(Handler); 379 } 380 381 void MachineModuleInfo::addSEHCleanupHandler(MachineBasicBlock *LandingPad, 382 const Function *Cleanup) { 383 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 384 SEHHandler Handler; 385 Handler.FilterOrFinally = Cleanup; 386 Handler.RecoverBA = nullptr; 387 LP.SEHHandlers.push_back(Handler); 388 } 389 390 /// TidyLandingPads - Remap landing pad labels and remove any deleted landing 391 /// pads. 392 void MachineModuleInfo::TidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap) { 393 for (unsigned i = 0; i != LandingPads.size(); ) { 394 LandingPadInfo &LandingPad = LandingPads[i]; 395 if (LandingPad.LandingPadLabel && 396 !LandingPad.LandingPadLabel->isDefined() && 397 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0)) 398 LandingPad.LandingPadLabel = nullptr; 399 400 // Special case: we *should* emit LPs with null LP MBB. This indicates 401 // "nounwind" case. 402 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) { 403 LandingPads.erase(LandingPads.begin() + i); 404 continue; 405 } 406 407 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) { 408 MCSymbol *BeginLabel = LandingPad.BeginLabels[j]; 409 MCSymbol *EndLabel = LandingPad.EndLabels[j]; 410 if ((BeginLabel->isDefined() || 411 (LPMap && (*LPMap)[BeginLabel] != 0)) && 412 (EndLabel->isDefined() || 413 (LPMap && (*LPMap)[EndLabel] != 0))) continue; 414 415 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j); 416 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j); 417 --j, --e; 418 } 419 420 // Remove landing pads with no try-ranges. 421 if (LandingPads[i].BeginLabels.empty()) { 422 LandingPads.erase(LandingPads.begin() + i); 423 continue; 424 } 425 426 // If there is no landing pad, ensure that the list of typeids is empty. 427 // If the only typeid is a cleanup, this is the same as having no typeids. 428 if (!LandingPad.LandingPadBlock || 429 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0])) 430 LandingPad.TypeIds.clear(); 431 ++i; 432 } 433 } 434 435 /// setCallSiteLandingPad - Map the landing pad's EH symbol to the call site 436 /// indexes. 437 void MachineModuleInfo::setCallSiteLandingPad(MCSymbol *Sym, 438 ArrayRef<unsigned> Sites) { 439 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end()); 440 } 441 442 /// getTypeIDFor - Return the type id for the specified typeinfo. This is 443 /// function wide. 444 unsigned MachineModuleInfo::getTypeIDFor(const GlobalValue *TI) { 445 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i) 446 if (TypeInfos[i] == TI) return i + 1; 447 448 TypeInfos.push_back(TI); 449 return TypeInfos.size(); 450 } 451 452 /// getFilterIDFor - Return the filter id for the specified typeinfos. This is 453 /// function wide. 454 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) { 455 // If the new filter coincides with the tail of an existing filter, then 456 // re-use the existing filter. Folding filters more than this requires 457 // re-ordering filters and/or their elements - probably not worth it. 458 for (std::vector<unsigned>::iterator I = FilterEnds.begin(), 459 E = FilterEnds.end(); I != E; ++I) { 460 unsigned i = *I, j = TyIds.size(); 461 462 while (i && j) 463 if (FilterIds[--i] != TyIds[--j]) 464 goto try_next; 465 466 if (!j) 467 // The new filter coincides with range [i, end) of the existing filter. 468 return -(1 + i); 469 470 try_next:; 471 } 472 473 // Add the new filter. 474 int FilterID = -(1 + FilterIds.size()); 475 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1); 476 FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end()); 477 FilterEnds.push_back(FilterIds.size()); 478 FilterIds.push_back(0); // terminator 479 return FilterID; 480 } 481 482 /// getPersonality - Return the personality function for the current function. 483 const Function *MachineModuleInfo::getPersonality() const { 484 for (const LandingPadInfo &LPI : LandingPads) 485 if (LPI.Personality) 486 return LPI.Personality; 487 return nullptr; 488 } 489 490 EHPersonality MachineModuleInfo::getPersonalityType() { 491 if (PersonalityTypeCache == EHPersonality::Unknown) { 492 if (const Function *F = getPersonality()) 493 PersonalityTypeCache = classifyEHPersonality(F); 494 } 495 return PersonalityTypeCache; 496 } 497 498 /// getPersonalityIndex - Return unique index for current personality 499 /// function. NULL/first personality function should always get zero index. 500 unsigned MachineModuleInfo::getPersonalityIndex() const { 501 const Function* Personality = nullptr; 502 503 // Scan landing pads. If there is at least one non-NULL personality - use it. 504 for (unsigned i = 0, e = LandingPads.size(); i != e; ++i) 505 if (LandingPads[i].Personality) { 506 Personality = LandingPads[i].Personality; 507 break; 508 } 509 510 for (unsigned i = 0, e = Personalities.size(); i < e; ++i) { 511 if (Personalities[i] == Personality) 512 return i; 513 } 514 515 // This will happen if the current personality function is 516 // in the zero index. 517 return 0; 518 } 519 520 const Function *MachineModuleInfo::getWinEHParent(const Function *F) const { 521 StringRef WinEHParentName = 522 F->getFnAttribute("wineh-parent").getValueAsString(); 523 if (WinEHParentName.empty() || WinEHParentName == F->getName()) 524 return F; 525 return F->getParent()->getFunction(WinEHParentName); 526 } 527 528 WinEHFuncInfo &MachineModuleInfo::getWinEHFuncInfo(const Function *F) { 529 auto &Ptr = FuncInfoMap[getWinEHParent(F)]; 530 if (!Ptr) 531 Ptr.reset(new WinEHFuncInfo); 532 return *Ptr; 533 } 534