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