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/PostOrderIterator.h" 13 #include "llvm/ADT/TinyPtrVector.h" 14 #include "llvm/Analysis/EHPersonalities.h" 15 #include "llvm/Analysis/ValueTracking.h" 16 #include "llvm/CodeGen/MachineFunction.h" 17 #include "llvm/CodeGen/MachineFunctionInitializer.h" 18 #include "llvm/CodeGen/MachineFunctionPass.h" 19 #include "llvm/CodeGen/Passes.h" 20 #include "llvm/IR/Constants.h" 21 #include "llvm/IR/DerivedTypes.h" 22 #include "llvm/IR/GlobalVariable.h" 23 #include "llvm/IR/Instructions.h" 24 #include "llvm/IR/Module.h" 25 #include "llvm/MC/MCObjectFileInfo.h" 26 #include "llvm/MC/MCSymbol.h" 27 #include "llvm/Support/Dwarf.h" 28 #include "llvm/Support/ErrorHandling.h" 29 #include "llvm/Target/TargetLoweringObjectFile.h" 30 #include "llvm/Target/TargetMachine.h" 31 using namespace llvm; 32 using namespace llvm::dwarf; 33 34 // Handle the Pass registration stuff necessary to use DataLayout's. 35 INITIALIZE_TM_PASS(MachineModuleInfo, "machinemoduleinfo", 36 "Machine Module Information", false, false) 37 char MachineModuleInfo::ID = 0; 38 39 // Out of line virtual method. 40 MachineModuleInfoImpl::~MachineModuleInfoImpl() {} 41 42 namespace llvm { 43 class MMIAddrLabelMapCallbackPtr final : CallbackVH { 44 MMIAddrLabelMap *Map; 45 public: 46 MMIAddrLabelMapCallbackPtr() : Map(nullptr) {} 47 MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V), Map(nullptr) {} 48 49 void setPtr(BasicBlock *BB) { 50 ValueHandleBase::operator=(BB); 51 } 52 53 void setMap(MMIAddrLabelMap *map) { Map = map; } 54 55 void deleted() override; 56 void allUsesReplacedWith(Value *V2) override; 57 }; 58 59 class MMIAddrLabelMap { 60 MCContext &Context; 61 struct AddrLabelSymEntry { 62 /// The symbols for the label. 63 TinyPtrVector<MCSymbol *> Symbols; 64 65 Function *Fn; // The containing function of the BasicBlock. 66 unsigned Index; // The index in BBCallbacks for the BasicBlock. 67 }; 68 69 DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols; 70 71 /// Callbacks for the BasicBlock's that we have entries for. We use this so 72 /// we get notified if a block is deleted or RAUWd. 73 std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks; 74 75 /// This is a per-function list of symbols whose corresponding BasicBlock got 76 /// deleted. These symbols need to be emitted at some point in the file, so 77 /// AsmPrinter emits them after the function body. 78 DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> > 79 DeletedAddrLabelsNeedingEmission; 80 public: 81 82 MMIAddrLabelMap(MCContext &context) : Context(context) {} 83 ~MMIAddrLabelMap() { 84 assert(DeletedAddrLabelsNeedingEmission.empty() && 85 "Some labels for deleted blocks never got emitted"); 86 } 87 88 ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB); 89 90 void takeDeletedSymbolsForFunction(Function *F, 91 std::vector<MCSymbol*> &Result); 92 93 void UpdateForDeletedBlock(BasicBlock *BB); 94 void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New); 95 }; 96 } 97 98 ArrayRef<MCSymbol *> MMIAddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) { 99 assert(BB->hasAddressTaken() && 100 "Shouldn't get label for block without address taken"); 101 AddrLabelSymEntry &Entry = AddrLabelSymbols[BB]; 102 103 // If we already had an entry for this block, just return it. 104 if (!Entry.Symbols.empty()) { 105 assert(BB->getParent() == Entry.Fn && "Parent changed"); 106 return Entry.Symbols; 107 } 108 109 // Otherwise, this is a new entry, create a new symbol for it and add an 110 // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd. 111 BBCallbacks.emplace_back(BB); 112 BBCallbacks.back().setMap(this); 113 Entry.Index = BBCallbacks.size() - 1; 114 Entry.Fn = BB->getParent(); 115 Entry.Symbols.push_back(Context.createTempSymbol()); 116 return Entry.Symbols; 117 } 118 119 /// If we have any deleted symbols for F, return 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 void MachineModuleInfo::EndFunction() { 233 // Clean up exception info. 234 LandingPads.clear(); 235 PersonalityTypeCache = EHPersonality::Unknown; 236 CallSiteMap.clear(); 237 TypeInfos.clear(); 238 FilterIds.clear(); 239 FilterEnds.clear(); 240 CallsEHReturn = false; 241 CallsUnwindInit = false; 242 HasEHFunclets = false; 243 } 244 245 //===- Address of Block Management ----------------------------------------===// 246 247 ArrayRef<MCSymbol *> 248 MachineModuleInfo::getAddrLabelSymbolToEmit(const BasicBlock *BB) { 249 // Lazily create AddrLabelSymbols. 250 if (!AddrLabelSymbols) 251 AddrLabelSymbols = new MMIAddrLabelMap(Context); 252 return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB)); 253 } 254 255 void MachineModuleInfo:: 256 takeDeletedSymbolsForFunction(const Function *F, 257 std::vector<MCSymbol*> &Result) { 258 // If no blocks have had their addresses taken, we're done. 259 if (!AddrLabelSymbols) return; 260 return AddrLabelSymbols-> 261 takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result); 262 } 263 264 //===- EH -----------------------------------------------------------------===// 265 266 LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo 267 (MachineBasicBlock *LandingPad) { 268 unsigned N = LandingPads.size(); 269 for (unsigned i = 0; i < N; ++i) { 270 LandingPadInfo &LP = LandingPads[i]; 271 if (LP.LandingPadBlock == LandingPad) 272 return LP; 273 } 274 275 LandingPads.push_back(LandingPadInfo(LandingPad)); 276 return LandingPads[N]; 277 } 278 279 void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad, 280 MCSymbol *BeginLabel, MCSymbol *EndLabel) { 281 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 282 LP.BeginLabels.push_back(BeginLabel); 283 LP.EndLabels.push_back(EndLabel); 284 } 285 286 MCSymbol *MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) { 287 MCSymbol *LandingPadLabel = Context.createTempSymbol(); 288 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 289 LP.LandingPadLabel = LandingPadLabel; 290 return LandingPadLabel; 291 } 292 293 void MachineModuleInfo::addPersonality(const Function *Personality) { 294 for (unsigned i = 0; i < Personalities.size(); ++i) 295 if (Personalities[i] == Personality) 296 return; 297 Personalities.push_back(Personality); 298 } 299 300 void MachineModuleInfo:: 301 addCatchTypeInfo(MachineBasicBlock *LandingPad, 302 ArrayRef<const GlobalValue *> TyInfo) { 303 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 304 for (unsigned N = TyInfo.size(); N; --N) 305 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1])); 306 } 307 308 void MachineModuleInfo:: 309 addFilterTypeInfo(MachineBasicBlock *LandingPad, 310 ArrayRef<const GlobalValue *> TyInfo) { 311 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 312 std::vector<unsigned> IdsInFilter(TyInfo.size()); 313 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I) 314 IdsInFilter[I] = getTypeIDFor(TyInfo[I]); 315 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter)); 316 } 317 318 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) { 319 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 320 LP.TypeIds.push_back(0); 321 } 322 323 void MachineModuleInfo::addSEHCatchHandler(MachineBasicBlock *LandingPad, 324 const Function *Filter, 325 const BlockAddress *RecoverBA) { 326 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 327 SEHHandler Handler; 328 Handler.FilterOrFinally = Filter; 329 Handler.RecoverBA = RecoverBA; 330 LP.SEHHandlers.push_back(Handler); 331 } 332 333 void MachineModuleInfo::addSEHCleanupHandler(MachineBasicBlock *LandingPad, 334 const Function *Cleanup) { 335 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 336 SEHHandler Handler; 337 Handler.FilterOrFinally = Cleanup; 338 Handler.RecoverBA = nullptr; 339 LP.SEHHandlers.push_back(Handler); 340 } 341 342 void MachineModuleInfo::TidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap) { 343 for (unsigned i = 0; i != LandingPads.size(); ) { 344 LandingPadInfo &LandingPad = LandingPads[i]; 345 if (LandingPad.LandingPadLabel && 346 !LandingPad.LandingPadLabel->isDefined() && 347 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0)) 348 LandingPad.LandingPadLabel = nullptr; 349 350 // Special case: we *should* emit LPs with null LP MBB. This indicates 351 // "nounwind" case. 352 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) { 353 LandingPads.erase(LandingPads.begin() + i); 354 continue; 355 } 356 357 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) { 358 MCSymbol *BeginLabel = LandingPad.BeginLabels[j]; 359 MCSymbol *EndLabel = LandingPad.EndLabels[j]; 360 if ((BeginLabel->isDefined() || 361 (LPMap && (*LPMap)[BeginLabel] != 0)) && 362 (EndLabel->isDefined() || 363 (LPMap && (*LPMap)[EndLabel] != 0))) continue; 364 365 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j); 366 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j); 367 --j; 368 --e; 369 } 370 371 // Remove landing pads with no try-ranges. 372 if (LandingPads[i].BeginLabels.empty()) { 373 LandingPads.erase(LandingPads.begin() + i); 374 continue; 375 } 376 377 // If there is no landing pad, ensure that the list of typeids is empty. 378 // If the only typeid is a cleanup, this is the same as having no typeids. 379 if (!LandingPad.LandingPadBlock || 380 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0])) 381 LandingPad.TypeIds.clear(); 382 ++i; 383 } 384 } 385 386 void MachineModuleInfo::setCallSiteLandingPad(MCSymbol *Sym, 387 ArrayRef<unsigned> Sites) { 388 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end()); 389 } 390 391 unsigned MachineModuleInfo::getTypeIDFor(const GlobalValue *TI) { 392 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i) 393 if (TypeInfos[i] == TI) return i + 1; 394 395 TypeInfos.push_back(TI); 396 return TypeInfos.size(); 397 } 398 399 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) { 400 // If the new filter coincides with the tail of an existing filter, then 401 // re-use the existing filter. Folding filters more than this requires 402 // re-ordering filters and/or their elements - probably not worth it. 403 for (std::vector<unsigned>::iterator I = FilterEnds.begin(), 404 E = FilterEnds.end(); I != E; ++I) { 405 unsigned i = *I, j = TyIds.size(); 406 407 while (i && j) 408 if (FilterIds[--i] != TyIds[--j]) 409 goto try_next; 410 411 if (!j) 412 // The new filter coincides with range [i, end) of the existing filter. 413 return -(1 + i); 414 415 try_next:; 416 } 417 418 // Add the new filter. 419 int FilterID = -(1 + FilterIds.size()); 420 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1); 421 FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end()); 422 FilterEnds.push_back(FilterIds.size()); 423 FilterIds.push_back(0); // terminator 424 return FilterID; 425 } 426 427 MachineFunction &MachineModuleInfo::getMachineFunction(const Function &F) { 428 // Shortcut for the common case where a sequence of MachineFunctionPasses 429 // all query for the same Function. 430 if (LastRequest == &F) 431 return *LastResult; 432 433 auto I = MachineFunctions.insert( 434 std::make_pair(&F, std::unique_ptr<MachineFunction>())); 435 MachineFunction *MF; 436 if (I.second) { 437 // No pre-existing machine function, create a new one. 438 MF = new MachineFunction(&F, TM, NextFnNum++, *this); 439 // Update the set entry. 440 I.first->second.reset(MF); 441 442 if (MFInitializer) 443 if (MFInitializer->initializeMachineFunction(*MF)) 444 report_fatal_error("Unable to initialize machine function"); 445 } else { 446 MF = I.first->second.get(); 447 } 448 449 LastRequest = &F; 450 LastResult = MF; 451 return *MF; 452 } 453 454 void MachineModuleInfo::deleteMachineFunctionFor(Function &F) { 455 MachineFunctions.erase(&F); 456 LastRequest = nullptr; 457 LastResult = nullptr; 458 } 459 460 namespace { 461 /// This pass frees the MachineFunction object associated with a Function. 462 class FreeMachineFunction : public FunctionPass { 463 public: 464 static char ID; 465 FreeMachineFunction() : FunctionPass(ID) {} 466 467 void getAnalysisUsage(AnalysisUsage &AU) const override { 468 AU.addRequired<MachineModuleInfo>(); 469 AU.addPreserved<MachineModuleInfo>(); 470 } 471 472 bool runOnFunction(Function &F) override { 473 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>(); 474 MMI.deleteMachineFunctionFor(F); 475 return true; 476 } 477 }; 478 char FreeMachineFunction::ID; 479 } // end anonymous namespace 480 481 namespace llvm { 482 FunctionPass *createFreeMachineFunctionPass() { 483 return new FreeMachineFunction(); 484 } 485 } // end namespace llvm 486 487 //===- MMI building helpers -----------------------------------------------===// 488 489 void llvm::computeUsesVAFloatArgument(const CallInst &I, 490 MachineModuleInfo &MMI) { 491 FunctionType *FT = 492 cast<FunctionType>(I.getCalledValue()->getType()->getContainedType(0)); 493 if (FT->isVarArg() && !MMI.usesVAFloatArgument()) { 494 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 495 Type *T = I.getArgOperand(i)->getType(); 496 for (auto i : post_order(T)) { 497 if (i->isFloatingPointTy()) { 498 MMI.setUsesVAFloatArgument(true); 499 return; 500 } 501 } 502 } 503 } 504 } 505 506 void llvm::addLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI, 507 MachineBasicBlock &MBB) { 508 if (const auto *PF = dyn_cast<Function>( 509 I.getParent()->getParent()->getPersonalityFn()->stripPointerCasts())) 510 MMI.addPersonality(PF); 511 512 if (I.isCleanup()) 513 MMI.addCleanup(&MBB); 514 515 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct, 516 // but we need to do it this way because of how the DWARF EH emitter 517 // processes the clauses. 518 for (unsigned i = I.getNumClauses(); i != 0; --i) { 519 Value *Val = I.getClause(i - 1); 520 if (I.isCatch(i - 1)) { 521 MMI.addCatchTypeInfo(&MBB, 522 dyn_cast<GlobalValue>(Val->stripPointerCasts())); 523 } else { 524 // Add filters in a list. 525 Constant *CVal = cast<Constant>(Val); 526 SmallVector<const GlobalValue *, 4> FilterList; 527 for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end(); 528 II != IE; ++II) 529 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts())); 530 531 MMI.addFilterTypeInfo(&MBB, FilterList); 532 } 533 } 534 } 535