1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 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 // This coordinates the per-module state used while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenModule.h" 15 #include "CGBlocks.h" 16 #include "CGCUDARuntime.h" 17 #include "CGCXXABI.h" 18 #include "CGCall.h" 19 #include "CGDebugInfo.h" 20 #include "CGObjCRuntime.h" 21 #include "CGOpenCLRuntime.h" 22 #include "CGOpenMPRuntime.h" 23 #include "CodeGenFunction.h" 24 #include "CodeGenPGO.h" 25 #include "CodeGenTBAA.h" 26 #include "CoverageMappingGen.h" 27 #include "TargetInfo.h" 28 #include "clang/AST/ASTContext.h" 29 #include "clang/AST/CharUnits.h" 30 #include "clang/AST/DeclCXX.h" 31 #include "clang/AST/DeclObjC.h" 32 #include "clang/AST/DeclTemplate.h" 33 #include "clang/AST/Mangle.h" 34 #include "clang/AST/RecordLayout.h" 35 #include "clang/AST/RecursiveASTVisitor.h" 36 #include "clang/Basic/Builtins.h" 37 #include "clang/Basic/CharInfo.h" 38 #include "clang/Basic/Diagnostic.h" 39 #include "clang/Basic/Module.h" 40 #include "clang/Basic/SourceManager.h" 41 #include "clang/Basic/TargetInfo.h" 42 #include "clang/Basic/Version.h" 43 #include "clang/Frontend/CodeGenOptions.h" 44 #include "clang/Sema/SemaDiagnostic.h" 45 #include "llvm/ADT/APSInt.h" 46 #include "llvm/ADT/Triple.h" 47 #include "llvm/IR/CallSite.h" 48 #include "llvm/IR/CallingConv.h" 49 #include "llvm/IR/DataLayout.h" 50 #include "llvm/IR/Intrinsics.h" 51 #include "llvm/IR/LLVMContext.h" 52 #include "llvm/IR/Module.h" 53 #include "llvm/ProfileData/InstrProfReader.h" 54 #include "llvm/Support/ConvertUTF.h" 55 #include "llvm/Support/ErrorHandling.h" 56 57 using namespace clang; 58 using namespace CodeGen; 59 60 static const char AnnotationSection[] = "llvm.metadata"; 61 62 static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 63 switch (CGM.getTarget().getCXXABI().getKind()) { 64 case TargetCXXABI::GenericAArch64: 65 case TargetCXXABI::GenericARM: 66 case TargetCXXABI::iOS: 67 case TargetCXXABI::iOS64: 68 case TargetCXXABI::GenericMIPS: 69 case TargetCXXABI::GenericItanium: 70 case TargetCXXABI::WebAssembly: 71 return CreateItaniumCXXABI(CGM); 72 case TargetCXXABI::Microsoft: 73 return CreateMicrosoftCXXABI(CGM); 74 } 75 76 llvm_unreachable("invalid C++ ABI kind"); 77 } 78 79 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO, 80 const PreprocessorOptions &PPO, 81 const CodeGenOptions &CGO, llvm::Module &M, 82 DiagnosticsEngine &diags, 83 CoverageSourceInfo *CoverageInfo) 84 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO), 85 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 86 Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 87 VMContext(M.getContext()), TBAA(nullptr), TheTargetCodeGenInfo(nullptr), 88 Types(*this), VTables(*this), ObjCRuntime(nullptr), 89 OpenCLRuntime(nullptr), OpenMPRuntime(nullptr), CUDARuntime(nullptr), 90 DebugInfo(nullptr), ARCData(nullptr), 91 NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr), 92 CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr), 93 NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr), 94 NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr), 95 BlockObjectDispose(nullptr), BlockDescriptorType(nullptr), 96 GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr), 97 LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) { 98 99 // Initialize the type cache. 100 llvm::LLVMContext &LLVMContext = M.getContext(); 101 VoidTy = llvm::Type::getVoidTy(LLVMContext); 102 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 103 Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 104 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 105 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 106 FloatTy = llvm::Type::getFloatTy(LLVMContext); 107 DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 108 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 109 PointerAlignInBytes = 110 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 111 IntAlignInBytes = 112 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 113 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 114 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 115 Int8PtrTy = Int8Ty->getPointerTo(0); 116 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 117 118 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 119 BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC(); 120 121 if (LangOpts.ObjC1) 122 createObjCRuntime(); 123 if (LangOpts.OpenCL) 124 createOpenCLRuntime(); 125 if (LangOpts.OpenMP) 126 createOpenMPRuntime(); 127 if (LangOpts.CUDA) 128 createCUDARuntime(); 129 130 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 131 if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 132 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 133 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 134 getCXXABI().getMangleContext()); 135 136 // If debug info or coverage generation is enabled, create the CGDebugInfo 137 // object. 138 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo || 139 CodeGenOpts.EmitGcovArcs || 140 CodeGenOpts.EmitGcovNotes) 141 DebugInfo = new CGDebugInfo(*this); 142 143 Block.GlobalUniqueCount = 0; 144 145 if (C.getLangOpts().ObjCAutoRefCount) 146 ARCData = new ARCEntrypoints(); 147 RRData = new RREntrypoints(); 148 149 if (!CodeGenOpts.InstrProfileInput.empty()) { 150 auto ReaderOrErr = 151 llvm::IndexedInstrProfReader::create(CodeGenOpts.InstrProfileInput); 152 if (std::error_code EC = ReaderOrErr.getError()) { 153 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 154 "Could not read profile %0: %1"); 155 getDiags().Report(DiagID) << CodeGenOpts.InstrProfileInput 156 << EC.message(); 157 } else 158 PGOReader = std::move(ReaderOrErr.get()); 159 } 160 161 // If coverage mapping generation is enabled, create the 162 // CoverageMappingModuleGen object. 163 if (CodeGenOpts.CoverageMapping) 164 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 165 } 166 167 CodeGenModule::~CodeGenModule() { 168 delete ObjCRuntime; 169 delete OpenCLRuntime; 170 delete OpenMPRuntime; 171 delete CUDARuntime; 172 delete TheTargetCodeGenInfo; 173 delete TBAA; 174 delete DebugInfo; 175 delete ARCData; 176 delete RRData; 177 } 178 179 void CodeGenModule::createObjCRuntime() { 180 // This is just isGNUFamily(), but we want to force implementors of 181 // new ABIs to decide how best to do this. 182 switch (LangOpts.ObjCRuntime.getKind()) { 183 case ObjCRuntime::GNUstep: 184 case ObjCRuntime::GCC: 185 case ObjCRuntime::ObjFW: 186 ObjCRuntime = CreateGNUObjCRuntime(*this); 187 return; 188 189 case ObjCRuntime::FragileMacOSX: 190 case ObjCRuntime::MacOSX: 191 case ObjCRuntime::iOS: 192 ObjCRuntime = CreateMacObjCRuntime(*this); 193 return; 194 } 195 llvm_unreachable("bad runtime kind"); 196 } 197 198 void CodeGenModule::createOpenCLRuntime() { 199 OpenCLRuntime = new CGOpenCLRuntime(*this); 200 } 201 202 void CodeGenModule::createOpenMPRuntime() { 203 OpenMPRuntime = new CGOpenMPRuntime(*this); 204 } 205 206 void CodeGenModule::createCUDARuntime() { 207 CUDARuntime = CreateNVCUDARuntime(*this); 208 } 209 210 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 211 Replacements[Name] = C; 212 } 213 214 void CodeGenModule::applyReplacements() { 215 for (auto &I : Replacements) { 216 StringRef MangledName = I.first(); 217 llvm::Constant *Replacement = I.second; 218 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 219 if (!Entry) 220 continue; 221 auto *OldF = cast<llvm::Function>(Entry); 222 auto *NewF = dyn_cast<llvm::Function>(Replacement); 223 if (!NewF) { 224 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 225 NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 226 } else { 227 auto *CE = cast<llvm::ConstantExpr>(Replacement); 228 assert(CE->getOpcode() == llvm::Instruction::BitCast || 229 CE->getOpcode() == llvm::Instruction::GetElementPtr); 230 NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 231 } 232 } 233 234 // Replace old with new, but keep the old order. 235 OldF->replaceAllUsesWith(Replacement); 236 if (NewF) { 237 NewF->removeFromParent(); 238 OldF->getParent()->getFunctionList().insertAfter(OldF, NewF); 239 } 240 OldF->eraseFromParent(); 241 } 242 } 243 244 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 245 GlobalValReplacements.push_back(std::make_pair(GV, C)); 246 } 247 248 void CodeGenModule::applyGlobalValReplacements() { 249 for (auto &I : GlobalValReplacements) { 250 llvm::GlobalValue *GV = I.first; 251 llvm::Constant *C = I.second; 252 253 GV->replaceAllUsesWith(C); 254 GV->eraseFromParent(); 255 } 256 } 257 258 // This is only used in aliases that we created and we know they have a 259 // linear structure. 260 static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) { 261 llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited; 262 const llvm::Constant *C = &GA; 263 for (;;) { 264 C = C->stripPointerCasts(); 265 if (auto *GO = dyn_cast<llvm::GlobalObject>(C)) 266 return GO; 267 // stripPointerCasts will not walk over weak aliases. 268 auto *GA2 = dyn_cast<llvm::GlobalAlias>(C); 269 if (!GA2) 270 return nullptr; 271 if (!Visited.insert(GA2).second) 272 return nullptr; 273 C = GA2->getAliasee(); 274 } 275 } 276 277 void CodeGenModule::checkAliases() { 278 // Check if the constructed aliases are well formed. It is really unfortunate 279 // that we have to do this in CodeGen, but we only construct mangled names 280 // and aliases during codegen. 281 bool Error = false; 282 DiagnosticsEngine &Diags = getDiags(); 283 for (const GlobalDecl &GD : Aliases) { 284 const auto *D = cast<ValueDecl>(GD.getDecl()); 285 const AliasAttr *AA = D->getAttr<AliasAttr>(); 286 StringRef MangledName = getMangledName(GD); 287 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 288 auto *Alias = cast<llvm::GlobalAlias>(Entry); 289 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias); 290 if (!GV) { 291 Error = true; 292 Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 293 } else if (GV->isDeclaration()) { 294 Error = true; 295 Diags.Report(AA->getLocation(), diag::err_alias_to_undefined); 296 } 297 298 llvm::Constant *Aliasee = Alias->getAliasee(); 299 llvm::GlobalValue *AliaseeGV; 300 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 301 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 302 else 303 AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 304 305 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 306 StringRef AliasSection = SA->getName(); 307 if (AliasSection != AliaseeGV->getSection()) 308 Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 309 << AliasSection; 310 } 311 312 // We have to handle alias to weak aliases in here. LLVM itself disallows 313 // this since the object semantics would not match the IL one. For 314 // compatibility with gcc we implement it by just pointing the alias 315 // to its aliasee's aliasee. We also warn, since the user is probably 316 // expecting the link to be weak. 317 if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { 318 if (GA->mayBeOverridden()) { 319 Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias) 320 << GV->getName() << GA->getName(); 321 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 322 GA->getAliasee(), Alias->getType()); 323 Alias->setAliasee(Aliasee); 324 } 325 } 326 } 327 if (!Error) 328 return; 329 330 for (const GlobalDecl &GD : Aliases) { 331 StringRef MangledName = getMangledName(GD); 332 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 333 auto *Alias = cast<llvm::GlobalAlias>(Entry); 334 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 335 Alias->eraseFromParent(); 336 } 337 } 338 339 void CodeGenModule::clear() { 340 DeferredDeclsToEmit.clear(); 341 if (OpenMPRuntime) 342 OpenMPRuntime->clear(); 343 } 344 345 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 346 StringRef MainFile) { 347 if (!hasDiagnostics()) 348 return; 349 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 350 if (MainFile.empty()) 351 MainFile = "<stdin>"; 352 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 353 } else 354 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing 355 << Mismatched; 356 } 357 358 void CodeGenModule::Release() { 359 EmitDeferred(); 360 applyGlobalValReplacements(); 361 applyReplacements(); 362 checkAliases(); 363 EmitCXXGlobalInitFunc(); 364 EmitCXXGlobalDtorFunc(); 365 EmitCXXThreadLocalInitFunc(); 366 if (ObjCRuntime) 367 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 368 AddGlobalCtor(ObjCInitFunction); 369 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice && 370 CUDARuntime) { 371 if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction()) 372 AddGlobalCtor(CudaCtorFunction); 373 if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction()) 374 AddGlobalDtor(CudaDtorFunction); 375 } 376 if (PGOReader && PGOStats.hasDiagnostics()) 377 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 378 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 379 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 380 EmitGlobalAnnotations(); 381 EmitStaticExternCAliases(); 382 EmitDeferredUnusedCoverageMappings(); 383 if (CoverageMapping) 384 CoverageMapping->emit(); 385 emitLLVMUsed(); 386 387 if (CodeGenOpts.Autolink && 388 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 389 EmitModuleLinkOptions(); 390 } 391 if (CodeGenOpts.DwarfVersion) { 392 // We actually want the latest version when there are conflicts. 393 // We can change from Warning to Latest if such mode is supported. 394 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 395 CodeGenOpts.DwarfVersion); 396 } 397 if (CodeGenOpts.EmitCodeView) { 398 // Indicate that we want CodeView in the metadata. 399 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 400 } 401 if (DebugInfo) 402 // We support a single version in the linked module. The LLVM 403 // parser will drop debug info with a different version number 404 // (and warn about it, too). 405 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 406 llvm::DEBUG_METADATA_VERSION); 407 408 // We need to record the widths of enums and wchar_t, so that we can generate 409 // the correct build attributes in the ARM backend. 410 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 411 if ( Arch == llvm::Triple::arm 412 || Arch == llvm::Triple::armeb 413 || Arch == llvm::Triple::thumb 414 || Arch == llvm::Triple::thumbeb) { 415 // Width of wchar_t in bytes 416 uint64_t WCharWidth = 417 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 418 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 419 420 // The minimum width of an enum in bytes 421 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 422 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 423 } 424 425 if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 426 llvm::PICLevel::Level PL = llvm::PICLevel::Default; 427 switch (PLevel) { 428 case 0: break; 429 case 1: PL = llvm::PICLevel::Small; break; 430 case 2: PL = llvm::PICLevel::Large; break; 431 default: llvm_unreachable("Invalid PIC Level"); 432 } 433 434 getModule().setPICLevel(PL); 435 } 436 437 SimplifyPersonality(); 438 439 if (getCodeGenOpts().EmitDeclMetadata) 440 EmitDeclMetadata(); 441 442 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 443 EmitCoverageFile(); 444 445 if (DebugInfo) 446 DebugInfo->finalize(); 447 448 EmitVersionIdentMetadata(); 449 450 EmitTargetMetadata(); 451 452 RewriteAlwaysInlineFunctions(); 453 } 454 455 void CodeGenModule::AddAlwaysInlineFunction(llvm::Function *Fn) { 456 AlwaysInlineFunctions.push_back(Fn); 457 } 458 459 /// Find all uses of GV that are not direct calls or invokes. 460 static void FindNonDirectCallUses(llvm::GlobalValue *GV, 461 llvm::SmallVectorImpl<llvm::Use *> *Uses) { 462 llvm::GlobalValue::use_iterator UI = GV->use_begin(), E = GV->use_end(); 463 for (; UI != E;) { 464 llvm::Use &U = *UI; 465 ++UI; 466 467 llvm::CallSite CS(U.getUser()); 468 bool isDirectCall = (CS.isCall() || CS.isInvoke()) && CS.isCallee(&U); 469 if (!isDirectCall) 470 Uses->push_back(&U); 471 } 472 } 473 474 /// Replace a list of uses. 475 static void ReplaceUsesWith(const llvm::SmallVectorImpl<llvm::Use *> &Uses, 476 llvm::GlobalValue *V, 477 llvm::GlobalValue *Replacement) { 478 for (llvm::Use *U : Uses) { 479 auto *C = dyn_cast<llvm::Constant>(U->getUser()); 480 if (C && !isa<llvm::GlobalValue>(C)) 481 C->handleOperandChange(V, Replacement, U); 482 else 483 U->set(Replacement); 484 } 485 } 486 487 void CodeGenModule::RewriteAlwaysInlineFunction(llvm::Function *Fn) { 488 std::string Name = Fn->getName(); 489 std::string InlineName = Name + ".alwaysinline"; 490 Fn->setName(InlineName); 491 492 llvm::SmallVector<llvm::Use *, 8> NonDirectCallUses; 493 Fn->removeDeadConstantUsers(); 494 FindNonDirectCallUses(Fn, &NonDirectCallUses); 495 // Do not create the wrapper if there are no non-direct call uses, and we are 496 // not required to emit an external definition. 497 if (NonDirectCallUses.empty() && Fn->isDiscardableIfUnused()) 498 return; 499 500 llvm::FunctionType *FT = Fn->getFunctionType(); 501 llvm::LLVMContext &Ctx = getModule().getContext(); 502 llvm::Function *StubFn = 503 llvm::Function::Create(FT, Fn->getLinkage(), Name, &getModule()); 504 assert(StubFn->getName() == Name && "name was uniqued!"); 505 506 // Insert the stub immediately after the original function. Helps with the 507 // fragile tests, among other things. 508 StubFn->removeFromParent(); 509 TheModule.getFunctionList().insertAfter(Fn, StubFn); 510 511 StubFn->copyAttributesFrom(Fn); 512 StubFn->setPersonalityFn(nullptr); 513 514 // AvailableExternally functions are replaced with a declaration. 515 // Everyone else gets a wrapper that musttail-calls the original function. 516 if (Fn->hasAvailableExternallyLinkage()) { 517 StubFn->setLinkage(llvm::GlobalValue::ExternalLinkage); 518 } else { 519 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", StubFn); 520 std::vector<llvm::Value *> Args; 521 for (llvm::Function::arg_iterator ai = StubFn->arg_begin(); 522 ai != StubFn->arg_end(); ++ai) 523 Args.push_back(&*ai); 524 llvm::CallInst *CI = llvm::CallInst::Create(Fn, Args, "", BB); 525 CI->setCallingConv(Fn->getCallingConv()); 526 CI->setTailCallKind(llvm::CallInst::TCK_MustTail); 527 CI->setAttributes(Fn->getAttributes()); 528 if (FT->getReturnType()->isVoidTy()) 529 llvm::ReturnInst::Create(Ctx, BB); 530 else 531 llvm::ReturnInst::Create(Ctx, CI, BB); 532 } 533 534 if (Fn->hasComdat()) 535 StubFn->setComdat(Fn->getComdat()); 536 537 ReplaceUsesWith(NonDirectCallUses, Fn, StubFn); 538 } 539 540 void CodeGenModule::RewriteAlwaysInlineFunctions() { 541 for (llvm::Function *Fn : AlwaysInlineFunctions) { 542 RewriteAlwaysInlineFunction(Fn); 543 Fn->setLinkage(llvm::GlobalValue::InternalLinkage); 544 Fn->addFnAttr(llvm::Attribute::AlwaysInline); 545 Fn->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 546 Fn->setVisibility(llvm::GlobalValue::DefaultVisibility); 547 } 548 } 549 550 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 551 // Make sure that this type is translated. 552 Types.UpdateCompletedType(TD); 553 } 554 555 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 556 if (!TBAA) 557 return nullptr; 558 return TBAA->getTBAAInfo(QTy); 559 } 560 561 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 562 if (!TBAA) 563 return nullptr; 564 return TBAA->getTBAAInfoForVTablePtr(); 565 } 566 567 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 568 if (!TBAA) 569 return nullptr; 570 return TBAA->getTBAAStructInfo(QTy); 571 } 572 573 llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) { 574 if (!TBAA) 575 return nullptr; 576 return TBAA->getTBAAStructTypeInfo(QTy); 577 } 578 579 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 580 llvm::MDNode *AccessN, 581 uint64_t O) { 582 if (!TBAA) 583 return nullptr; 584 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 585 } 586 587 /// Decorate the instruction with a TBAA tag. For both scalar TBAA 588 /// and struct-path aware TBAA, the tag has the same format: 589 /// base type, access type and offset. 590 /// When ConvertTypeToTag is true, we create a tag based on the scalar type. 591 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst, 592 llvm::MDNode *TBAAInfo, 593 bool ConvertTypeToTag) { 594 if (ConvertTypeToTag && TBAA) 595 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 596 TBAA->getTBAAScalarTagInfo(TBAAInfo)); 597 else 598 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 599 } 600 601 void CodeGenModule::Error(SourceLocation loc, StringRef message) { 602 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 603 getDiags().Report(Context.getFullLoc(loc), diagID) << message; 604 } 605 606 /// ErrorUnsupported - Print out an error that codegen doesn't support the 607 /// specified stmt yet. 608 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 609 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 610 "cannot compile this %0 yet"); 611 std::string Msg = Type; 612 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 613 << Msg << S->getSourceRange(); 614 } 615 616 /// ErrorUnsupported - Print out an error that codegen doesn't support the 617 /// specified decl yet. 618 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 619 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 620 "cannot compile this %0 yet"); 621 std::string Msg = Type; 622 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 623 } 624 625 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 626 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 627 } 628 629 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 630 const NamedDecl *D) const { 631 // Internal definitions always have default visibility. 632 if (GV->hasLocalLinkage()) { 633 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 634 return; 635 } 636 637 // Set visibility for definitions. 638 LinkageInfo LV = D->getLinkageAndVisibility(); 639 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 640 GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 641 } 642 643 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 644 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 645 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 646 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 647 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 648 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 649 } 650 651 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 652 CodeGenOptions::TLSModel M) { 653 switch (M) { 654 case CodeGenOptions::GeneralDynamicTLSModel: 655 return llvm::GlobalVariable::GeneralDynamicTLSModel; 656 case CodeGenOptions::LocalDynamicTLSModel: 657 return llvm::GlobalVariable::LocalDynamicTLSModel; 658 case CodeGenOptions::InitialExecTLSModel: 659 return llvm::GlobalVariable::InitialExecTLSModel; 660 case CodeGenOptions::LocalExecTLSModel: 661 return llvm::GlobalVariable::LocalExecTLSModel; 662 } 663 llvm_unreachable("Invalid TLS model!"); 664 } 665 666 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 667 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 668 669 llvm::GlobalValue::ThreadLocalMode TLM; 670 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 671 672 // Override the TLS model if it is explicitly specified. 673 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 674 TLM = GetLLVMTLSModel(Attr->getModel()); 675 } 676 677 GV->setThreadLocalMode(TLM); 678 } 679 680 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 681 StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()]; 682 if (!FoundStr.empty()) 683 return FoundStr; 684 685 const auto *ND = cast<NamedDecl>(GD.getDecl()); 686 SmallString<256> Buffer; 687 StringRef Str; 688 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 689 llvm::raw_svector_ostream Out(Buffer); 690 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 691 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 692 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 693 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 694 else 695 getCXXABI().getMangleContext().mangleName(ND, Out); 696 Str = Out.str(); 697 } else { 698 IdentifierInfo *II = ND->getIdentifier(); 699 assert(II && "Attempt to mangle unnamed decl."); 700 Str = II->getName(); 701 } 702 703 // Keep the first result in the case of a mangling collision. 704 auto Result = Manglings.insert(std::make_pair(Str, GD)); 705 return FoundStr = Result.first->first(); 706 } 707 708 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 709 const BlockDecl *BD) { 710 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 711 const Decl *D = GD.getDecl(); 712 713 SmallString<256> Buffer; 714 llvm::raw_svector_ostream Out(Buffer); 715 if (!D) 716 MangleCtx.mangleGlobalBlock(BD, 717 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 718 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 719 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 720 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 721 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 722 else 723 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 724 725 auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 726 return Result.first->first(); 727 } 728 729 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 730 return getModule().getNamedValue(Name); 731 } 732 733 /// AddGlobalCtor - Add a function to the list that will be called before 734 /// main() runs. 735 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 736 llvm::Constant *AssociatedData) { 737 // FIXME: Type coercion of void()* types. 738 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 739 } 740 741 /// AddGlobalDtor - Add a function to the list that will be called 742 /// when the module is unloaded. 743 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { 744 // FIXME: Type coercion of void()* types. 745 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 746 } 747 748 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 749 // Ctor function type is void()*. 750 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 751 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 752 753 // Get the type of a ctor entry, { i32, void ()*, i8* }. 754 llvm::StructType *CtorStructTy = llvm::StructType::get( 755 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr); 756 757 // Construct the constructor and destructor arrays. 758 SmallVector<llvm::Constant *, 8> Ctors; 759 for (const auto &I : Fns) { 760 llvm::Constant *S[] = { 761 llvm::ConstantInt::get(Int32Ty, I.Priority, false), 762 llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy), 763 (I.AssociatedData 764 ? llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy) 765 : llvm::Constant::getNullValue(VoidPtrTy))}; 766 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 767 } 768 769 if (!Ctors.empty()) { 770 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 771 new llvm::GlobalVariable(TheModule, AT, false, 772 llvm::GlobalValue::AppendingLinkage, 773 llvm::ConstantArray::get(AT, Ctors), 774 GlobalName); 775 } 776 } 777 778 llvm::GlobalValue::LinkageTypes 779 CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 780 const auto *D = cast<FunctionDecl>(GD.getDecl()); 781 782 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 783 784 if (isa<CXXDestructorDecl>(D) && 785 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 786 GD.getDtorType())) { 787 // Destructor variants in the Microsoft C++ ABI are always internal or 788 // linkonce_odr thunks emitted on an as-needed basis. 789 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage 790 : llvm::GlobalValue::LinkOnceODRLinkage; 791 } 792 793 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false); 794 } 795 796 void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) { 797 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 798 799 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) { 800 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) { 801 // Don't dllexport/import destructor thunks. 802 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 803 return; 804 } 805 } 806 807 if (FD->hasAttr<DLLImportAttr>()) 808 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 809 else if (FD->hasAttr<DLLExportAttr>()) 810 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 811 else 812 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 813 } 814 815 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, 816 llvm::Function *F) { 817 setNonAliasAttributes(D, F); 818 } 819 820 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 821 const CGFunctionInfo &Info, 822 llvm::Function *F) { 823 unsigned CallingConv; 824 AttributeListType AttributeList; 825 ConstructAttributeList(Info, D, AttributeList, CallingConv, false); 826 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList)); 827 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 828 } 829 830 /// Determines whether the language options require us to model 831 /// unwind exceptions. We treat -fexceptions as mandating this 832 /// except under the fragile ObjC ABI with only ObjC exceptions 833 /// enabled. This means, for example, that C with -fexceptions 834 /// enables this. 835 static bool hasUnwindExceptions(const LangOptions &LangOpts) { 836 // If exceptions are completely disabled, obviously this is false. 837 if (!LangOpts.Exceptions) return false; 838 839 // If C++ exceptions are enabled, this is true. 840 if (LangOpts.CXXExceptions) return true; 841 842 // If ObjC exceptions are enabled, this depends on the ABI. 843 if (LangOpts.ObjCExceptions) { 844 return LangOpts.ObjCRuntime.hasUnwindExceptions(); 845 } 846 847 return true; 848 } 849 850 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 851 llvm::Function *F) { 852 llvm::AttrBuilder B; 853 854 if (CodeGenOpts.UnwindTables) 855 B.addAttribute(llvm::Attribute::UWTable); 856 857 if (!hasUnwindExceptions(LangOpts)) 858 B.addAttribute(llvm::Attribute::NoUnwind); 859 860 if (D->hasAttr<NakedAttr>()) { 861 // Naked implies noinline: we should not be inlining such functions. 862 B.addAttribute(llvm::Attribute::Naked); 863 B.addAttribute(llvm::Attribute::NoInline); 864 } else if (D->hasAttr<NoDuplicateAttr>()) { 865 B.addAttribute(llvm::Attribute::NoDuplicate); 866 } else if (D->hasAttr<NoInlineAttr>()) { 867 B.addAttribute(llvm::Attribute::NoInline); 868 } else if (D->hasAttr<AlwaysInlineAttr>() && 869 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex, 870 llvm::Attribute::NoInline)) { 871 // (noinline wins over always_inline, and we can't specify both in IR) 872 AddAlwaysInlineFunction(F); 873 } 874 875 if (D->hasAttr<ColdAttr>()) { 876 if (!D->hasAttr<OptimizeNoneAttr>()) 877 B.addAttribute(llvm::Attribute::OptimizeForSize); 878 B.addAttribute(llvm::Attribute::Cold); 879 } 880 881 if (D->hasAttr<MinSizeAttr>()) 882 B.addAttribute(llvm::Attribute::MinSize); 883 884 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 885 B.addAttribute(llvm::Attribute::StackProtect); 886 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 887 B.addAttribute(llvm::Attribute::StackProtectStrong); 888 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 889 B.addAttribute(llvm::Attribute::StackProtectReq); 890 891 F->addAttributes(llvm::AttributeSet::FunctionIndex, 892 llvm::AttributeSet::get( 893 F->getContext(), llvm::AttributeSet::FunctionIndex, B)); 894 895 if (D->hasAttr<OptimizeNoneAttr>()) { 896 // OptimizeNone implies noinline; we should not be inlining such functions. 897 F->addFnAttr(llvm::Attribute::OptimizeNone); 898 F->addFnAttr(llvm::Attribute::NoInline); 899 900 // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline. 901 assert(!F->hasFnAttribute(llvm::Attribute::OptimizeForSize) && 902 "OptimizeNone and OptimizeForSize on same function!"); 903 assert(!F->hasFnAttribute(llvm::Attribute::MinSize) && 904 "OptimizeNone and MinSize on same function!"); 905 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 906 "OptimizeNone and AlwaysInline on same function!"); 907 908 // Attribute 'inlinehint' has no effect on 'optnone' functions. 909 // Explicitly remove it from the set of function attributes. 910 F->removeFnAttr(llvm::Attribute::InlineHint); 911 } 912 913 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 914 F->setUnnamedAddr(true); 915 else if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) 916 if (MD->isVirtual()) 917 F->setUnnamedAddr(true); 918 919 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 920 if (alignment) 921 F->setAlignment(alignment); 922 923 // Some C++ ABIs require 2-byte alignment for member functions, in order to 924 // reserve a bit for differentiating between virtual and non-virtual member 925 // functions. If the current target's C++ ABI requires this and this is a 926 // member function, set its alignment accordingly. 927 if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 928 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 929 F->setAlignment(2); 930 } 931 } 932 933 void CodeGenModule::SetCommonAttributes(const Decl *D, 934 llvm::GlobalValue *GV) { 935 if (const auto *ND = dyn_cast<NamedDecl>(D)) 936 setGlobalVisibility(GV, ND); 937 else 938 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 939 940 if (D->hasAttr<UsedAttr>()) 941 addUsedGlobal(GV); 942 } 943 944 void CodeGenModule::setAliasAttributes(const Decl *D, 945 llvm::GlobalValue *GV) { 946 SetCommonAttributes(D, GV); 947 948 // Process the dllexport attribute based on whether the original definition 949 // (not necessarily the aliasee) was exported. 950 if (D->hasAttr<DLLExportAttr>()) 951 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 952 } 953 954 void CodeGenModule::setNonAliasAttributes(const Decl *D, 955 llvm::GlobalObject *GO) { 956 SetCommonAttributes(D, GO); 957 958 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 959 GO->setSection(SA->getName()); 960 961 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 962 } 963 964 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 965 llvm::Function *F, 966 const CGFunctionInfo &FI) { 967 SetLLVMFunctionAttributes(D, FI, F); 968 SetLLVMFunctionAttributesForDefinition(D, F); 969 970 F->setLinkage(llvm::Function::InternalLinkage); 971 972 setNonAliasAttributes(D, F); 973 } 974 975 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, 976 const NamedDecl *ND) { 977 // Set linkage and visibility in case we never see a definition. 978 LinkageInfo LV = ND->getLinkageAndVisibility(); 979 if (LV.getLinkage() != ExternalLinkage) { 980 // Don't set internal linkage on declarations. 981 } else { 982 if (ND->hasAttr<DLLImportAttr>()) { 983 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 984 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 985 } else if (ND->hasAttr<DLLExportAttr>()) { 986 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 987 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 988 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 989 // "extern_weak" is overloaded in LLVM; we probably should have 990 // separate linkage types for this. 991 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 992 } 993 994 // Set visibility on a declaration only if it's explicit. 995 if (LV.isVisibilityExplicit()) 996 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility())); 997 } 998 } 999 1000 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 1001 bool IsIncompleteFunction, 1002 bool IsThunk) { 1003 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 1004 // If this is an intrinsic function, set the function's attributes 1005 // to the intrinsic's attributes. 1006 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 1007 return; 1008 } 1009 1010 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1011 1012 if (!IsIncompleteFunction) 1013 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 1014 1015 // Add the Returned attribute for "this", except for iOS 5 and earlier 1016 // where substantial code, including the libstdc++ dylib, was compiled with 1017 // GCC and does not actually return "this". 1018 if (!IsThunk && getCXXABI().HasThisReturn(GD) && 1019 !(getTarget().getTriple().isiOS() && 1020 getTarget().getTriple().isOSVersionLT(6))) { 1021 assert(!F->arg_empty() && 1022 F->arg_begin()->getType() 1023 ->canLosslesslyBitCastTo(F->getReturnType()) && 1024 "unexpected this return"); 1025 F->addAttribute(1, llvm::Attribute::Returned); 1026 } 1027 1028 // Only a few attributes are set on declarations; these may later be 1029 // overridden by a definition. 1030 1031 setLinkageAndVisibilityForGV(F, FD); 1032 1033 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 1034 F->setSection(SA->getName()); 1035 1036 // A replaceable global allocation function does not act like a builtin by 1037 // default, only if it is invoked by a new-expression or delete-expression. 1038 if (FD->isReplaceableGlobalAllocationFunction()) 1039 F->addAttribute(llvm::AttributeSet::FunctionIndex, 1040 llvm::Attribute::NoBuiltin); 1041 1042 // If we are checking indirect calls and this is not a non-static member 1043 // function, emit a bit set entry for the function type. 1044 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall) && 1045 !(isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())) { 1046 llvm::NamedMDNode *BitsetsMD = 1047 getModule().getOrInsertNamedMetadata("llvm.bitsets"); 1048 1049 llvm::Metadata *BitsetOps[] = { 1050 CreateMetadataIdentifierForType(FD->getType()), 1051 llvm::ConstantAsMetadata::get(F), 1052 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int64Ty, 0))}; 1053 BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps)); 1054 } 1055 } 1056 1057 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 1058 assert(!GV->isDeclaration() && 1059 "Only globals with definition can force usage."); 1060 LLVMUsed.emplace_back(GV); 1061 } 1062 1063 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 1064 assert(!GV->isDeclaration() && 1065 "Only globals with definition can force usage."); 1066 LLVMCompilerUsed.emplace_back(GV); 1067 } 1068 1069 static void emitUsed(CodeGenModule &CGM, StringRef Name, 1070 std::vector<llvm::WeakVH> &List) { 1071 // Don't create llvm.used if there is no need. 1072 if (List.empty()) 1073 return; 1074 1075 // Convert List to what ConstantArray needs. 1076 SmallVector<llvm::Constant*, 8> UsedArray; 1077 UsedArray.resize(List.size()); 1078 for (unsigned i = 0, e = List.size(); i != e; ++i) { 1079 UsedArray[i] = 1080 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 1081 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 1082 } 1083 1084 if (UsedArray.empty()) 1085 return; 1086 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 1087 1088 auto *GV = new llvm::GlobalVariable( 1089 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 1090 llvm::ConstantArray::get(ATy, UsedArray), Name); 1091 1092 GV->setSection("llvm.metadata"); 1093 } 1094 1095 void CodeGenModule::emitLLVMUsed() { 1096 emitUsed(*this, "llvm.used", LLVMUsed); 1097 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 1098 } 1099 1100 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 1101 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 1102 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1103 } 1104 1105 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 1106 llvm::SmallString<32> Opt; 1107 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 1108 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1109 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1110 } 1111 1112 void CodeGenModule::AddDependentLib(StringRef Lib) { 1113 llvm::SmallString<24> Opt; 1114 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 1115 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1116 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1117 } 1118 1119 /// \brief Add link options implied by the given module, including modules 1120 /// it depends on, using a postorder walk. 1121 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 1122 SmallVectorImpl<llvm::Metadata *> &Metadata, 1123 llvm::SmallPtrSet<Module *, 16> &Visited) { 1124 // Import this module's parent. 1125 if (Mod->Parent && Visited.insert(Mod->Parent).second) { 1126 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 1127 } 1128 1129 // Import this module's dependencies. 1130 for (unsigned I = Mod->Imports.size(); I > 0; --I) { 1131 if (Visited.insert(Mod->Imports[I - 1]).second) 1132 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 1133 } 1134 1135 // Add linker options to link against the libraries/frameworks 1136 // described by this module. 1137 llvm::LLVMContext &Context = CGM.getLLVMContext(); 1138 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 1139 // Link against a framework. Frameworks are currently Darwin only, so we 1140 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 1141 if (Mod->LinkLibraries[I-1].IsFramework) { 1142 llvm::Metadata *Args[2] = { 1143 llvm::MDString::get(Context, "-framework"), 1144 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 1145 1146 Metadata.push_back(llvm::MDNode::get(Context, Args)); 1147 continue; 1148 } 1149 1150 // Link against a library. 1151 llvm::SmallString<24> Opt; 1152 CGM.getTargetCodeGenInfo().getDependentLibraryOption( 1153 Mod->LinkLibraries[I-1].Library, Opt); 1154 auto *OptString = llvm::MDString::get(Context, Opt); 1155 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 1156 } 1157 } 1158 1159 void CodeGenModule::EmitModuleLinkOptions() { 1160 // Collect the set of all of the modules we want to visit to emit link 1161 // options, which is essentially the imported modules and all of their 1162 // non-explicit child modules. 1163 llvm::SetVector<clang::Module *> LinkModules; 1164 llvm::SmallPtrSet<clang::Module *, 16> Visited; 1165 SmallVector<clang::Module *, 16> Stack; 1166 1167 // Seed the stack with imported modules. 1168 for (Module *M : ImportedModules) 1169 if (Visited.insert(M).second) 1170 Stack.push_back(M); 1171 1172 // Find all of the modules to import, making a little effort to prune 1173 // non-leaf modules. 1174 while (!Stack.empty()) { 1175 clang::Module *Mod = Stack.pop_back_val(); 1176 1177 bool AnyChildren = false; 1178 1179 // Visit the submodules of this module. 1180 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 1181 SubEnd = Mod->submodule_end(); 1182 Sub != SubEnd; ++Sub) { 1183 // Skip explicit children; they need to be explicitly imported to be 1184 // linked against. 1185 if ((*Sub)->IsExplicit) 1186 continue; 1187 1188 if (Visited.insert(*Sub).second) { 1189 Stack.push_back(*Sub); 1190 AnyChildren = true; 1191 } 1192 } 1193 1194 // We didn't find any children, so add this module to the list of 1195 // modules to link against. 1196 if (!AnyChildren) { 1197 LinkModules.insert(Mod); 1198 } 1199 } 1200 1201 // Add link options for all of the imported modules in reverse topological 1202 // order. We don't do anything to try to order import link flags with respect 1203 // to linker options inserted by things like #pragma comment(). 1204 SmallVector<llvm::Metadata *, 16> MetadataArgs; 1205 Visited.clear(); 1206 for (Module *M : LinkModules) 1207 if (Visited.insert(M).second) 1208 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 1209 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1210 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1211 1212 // Add the linker options metadata flag. 1213 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 1214 llvm::MDNode::get(getLLVMContext(), 1215 LinkerOptionsMetadata)); 1216 } 1217 1218 void CodeGenModule::EmitDeferred() { 1219 // Emit code for any potentially referenced deferred decls. Since a 1220 // previously unused static decl may become used during the generation of code 1221 // for a static function, iterate until no changes are made. 1222 1223 if (!DeferredVTables.empty()) { 1224 EmitDeferredVTables(); 1225 1226 // Emitting a v-table doesn't directly cause more v-tables to 1227 // become deferred, although it can cause functions to be 1228 // emitted that then need those v-tables. 1229 assert(DeferredVTables.empty()); 1230 } 1231 1232 // Stop if we're out of both deferred v-tables and deferred declarations. 1233 if (DeferredDeclsToEmit.empty()) 1234 return; 1235 1236 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 1237 // work, it will not interfere with this. 1238 std::vector<DeferredGlobal> CurDeclsToEmit; 1239 CurDeclsToEmit.swap(DeferredDeclsToEmit); 1240 1241 for (DeferredGlobal &G : CurDeclsToEmit) { 1242 GlobalDecl D = G.GD; 1243 llvm::GlobalValue *GV = G.GV; 1244 G.GV = nullptr; 1245 1246 // We should call GetAddrOfGlobal with IsForDefinition set to true in order 1247 // to get GlobalValue with exactly the type we need, not something that 1248 // might had been created for another decl with the same mangled name but 1249 // different type. 1250 // FIXME: Support for variables is not implemented yet. 1251 if (isa<FunctionDecl>(D.getDecl())) 1252 GV = cast<llvm::GlobalValue>(GetAddrOfGlobal(D, /*IsForDefinition=*/true)); 1253 else 1254 if (!GV) 1255 GV = GetGlobalValue(getMangledName(D)); 1256 1257 // Check to see if we've already emitted this. This is necessary 1258 // for a couple of reasons: first, decls can end up in the 1259 // deferred-decls queue multiple times, and second, decls can end 1260 // up with definitions in unusual ways (e.g. by an extern inline 1261 // function acquiring a strong function redefinition). Just 1262 // ignore these cases. 1263 if (GV && !GV->isDeclaration()) 1264 continue; 1265 1266 // Otherwise, emit the definition and move on to the next one. 1267 EmitGlobalDefinition(D, GV); 1268 1269 // If we found out that we need to emit more decls, do that recursively. 1270 // This has the advantage that the decls are emitted in a DFS and related 1271 // ones are close together, which is convenient for testing. 1272 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 1273 EmitDeferred(); 1274 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 1275 } 1276 } 1277 } 1278 1279 void CodeGenModule::EmitGlobalAnnotations() { 1280 if (Annotations.empty()) 1281 return; 1282 1283 // Create a new global variable for the ConstantStruct in the Module. 1284 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 1285 Annotations[0]->getType(), Annotations.size()), Annotations); 1286 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 1287 llvm::GlobalValue::AppendingLinkage, 1288 Array, "llvm.global.annotations"); 1289 gv->setSection(AnnotationSection); 1290 } 1291 1292 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1293 llvm::Constant *&AStr = AnnotationStrings[Str]; 1294 if (AStr) 1295 return AStr; 1296 1297 // Not found yet, create a new global. 1298 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 1299 auto *gv = 1300 new llvm::GlobalVariable(getModule(), s->getType(), true, 1301 llvm::GlobalValue::PrivateLinkage, s, ".str"); 1302 gv->setSection(AnnotationSection); 1303 gv->setUnnamedAddr(true); 1304 AStr = gv; 1305 return gv; 1306 } 1307 1308 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 1309 SourceManager &SM = getContext().getSourceManager(); 1310 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 1311 if (PLoc.isValid()) 1312 return EmitAnnotationString(PLoc.getFilename()); 1313 return EmitAnnotationString(SM.getBufferName(Loc)); 1314 } 1315 1316 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 1317 SourceManager &SM = getContext().getSourceManager(); 1318 PresumedLoc PLoc = SM.getPresumedLoc(L); 1319 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 1320 SM.getExpansionLineNumber(L); 1321 return llvm::ConstantInt::get(Int32Ty, LineNo); 1322 } 1323 1324 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1325 const AnnotateAttr *AA, 1326 SourceLocation L) { 1327 // Get the globals for file name, annotation, and the line number. 1328 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 1329 *UnitGV = EmitAnnotationUnit(L), 1330 *LineNoCst = EmitAnnotationLineNo(L); 1331 1332 // Create the ConstantStruct for the global annotation. 1333 llvm::Constant *Fields[4] = { 1334 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 1335 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 1336 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 1337 LineNoCst 1338 }; 1339 return llvm::ConstantStruct::getAnon(Fields); 1340 } 1341 1342 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 1343 llvm::GlobalValue *GV) { 1344 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1345 // Get the struct elements for these annotations. 1346 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 1347 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 1348 } 1349 1350 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn, 1351 SourceLocation Loc) const { 1352 const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 1353 // Blacklist by function name. 1354 if (SanitizerBL.isBlacklistedFunction(Fn->getName())) 1355 return true; 1356 // Blacklist by location. 1357 if (!Loc.isInvalid()) 1358 return SanitizerBL.isBlacklistedLocation(Loc); 1359 // If location is unknown, this may be a compiler-generated function. Assume 1360 // it's located in the main file. 1361 auto &SM = Context.getSourceManager(); 1362 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 1363 return SanitizerBL.isBlacklistedFile(MainFile->getName()); 1364 } 1365 return false; 1366 } 1367 1368 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 1369 SourceLocation Loc, QualType Ty, 1370 StringRef Category) const { 1371 // For now globals can be blacklisted only in ASan and KASan. 1372 if (!LangOpts.Sanitize.hasOneOf( 1373 SanitizerKind::Address | SanitizerKind::KernelAddress)) 1374 return false; 1375 const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 1376 if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category)) 1377 return true; 1378 if (SanitizerBL.isBlacklistedLocation(Loc, Category)) 1379 return true; 1380 // Check global type. 1381 if (!Ty.isNull()) { 1382 // Drill down the array types: if global variable of a fixed type is 1383 // blacklisted, we also don't instrument arrays of them. 1384 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 1385 Ty = AT->getElementType(); 1386 Ty = Ty.getCanonicalType().getUnqualifiedType(); 1387 // We allow to blacklist only record types (classes, structs etc.) 1388 if (Ty->isRecordType()) { 1389 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 1390 if (SanitizerBL.isBlacklistedType(TypeStr, Category)) 1391 return true; 1392 } 1393 } 1394 return false; 1395 } 1396 1397 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 1398 // Never defer when EmitAllDecls is specified. 1399 if (LangOpts.EmitAllDecls) 1400 return true; 1401 1402 return getContext().DeclMustBeEmitted(Global); 1403 } 1404 1405 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 1406 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) 1407 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1408 // Implicit template instantiations may change linkage if they are later 1409 // explicitly instantiated, so they should not be emitted eagerly. 1410 return false; 1411 // If OpenMP is enabled and threadprivates must be generated like TLS, delay 1412 // codegen for global variables, because they may be marked as threadprivate. 1413 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 1414 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global)) 1415 return false; 1416 1417 return true; 1418 } 1419 1420 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( 1421 const CXXUuidofExpr* E) { 1422 // Sema has verified that IIDSource has a __declspec(uuid()), and that its 1423 // well-formed. 1424 StringRef Uuid = E->getUuidAsStringRef(Context); 1425 std::string Name = "_GUID_" + Uuid.lower(); 1426 std::replace(Name.begin(), Name.end(), '-', '_'); 1427 1428 // Contains a 32-bit field. 1429 CharUnits Alignment = CharUnits::fromQuantity(4); 1430 1431 // Look for an existing global. 1432 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 1433 return ConstantAddress(GV, Alignment); 1434 1435 llvm::Constant *Init = EmitUuidofInitializer(Uuid); 1436 assert(Init && "failed to initialize as constant"); 1437 1438 auto *GV = new llvm::GlobalVariable( 1439 getModule(), Init->getType(), 1440 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 1441 if (supportsCOMDAT()) 1442 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 1443 return ConstantAddress(GV, Alignment); 1444 } 1445 1446 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1447 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1448 assert(AA && "No alias?"); 1449 1450 CharUnits Alignment = getContext().getDeclAlign(VD); 1451 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1452 1453 // See if there is already something with the target's name in the module. 1454 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 1455 if (Entry) { 1456 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 1457 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 1458 return ConstantAddress(Ptr, Alignment); 1459 } 1460 1461 llvm::Constant *Aliasee; 1462 if (isa<llvm::FunctionType>(DeclTy)) 1463 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 1464 GlobalDecl(cast<FunctionDecl>(VD)), 1465 /*ForVTable=*/false); 1466 else 1467 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1468 llvm::PointerType::getUnqual(DeclTy), 1469 nullptr); 1470 1471 auto *F = cast<llvm::GlobalValue>(Aliasee); 1472 F->setLinkage(llvm::Function::ExternalWeakLinkage); 1473 WeakRefReferences.insert(F); 1474 1475 return ConstantAddress(Aliasee, Alignment); 1476 } 1477 1478 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 1479 const auto *Global = cast<ValueDecl>(GD.getDecl()); 1480 1481 // Weak references don't produce any output by themselves. 1482 if (Global->hasAttr<WeakRefAttr>()) 1483 return; 1484 1485 // If this is an alias definition (which otherwise looks like a declaration) 1486 // emit it now. 1487 if (Global->hasAttr<AliasAttr>()) 1488 return EmitAliasDefinition(GD); 1489 1490 // If this is CUDA, be selective about which declarations we emit. 1491 if (LangOpts.CUDA) { 1492 if (LangOpts.CUDAIsDevice) { 1493 if (!Global->hasAttr<CUDADeviceAttr>() && 1494 !Global->hasAttr<CUDAGlobalAttr>() && 1495 !Global->hasAttr<CUDAConstantAttr>() && 1496 !Global->hasAttr<CUDASharedAttr>()) 1497 return; 1498 } else { 1499 if (!Global->hasAttr<CUDAHostAttr>() && ( 1500 Global->hasAttr<CUDADeviceAttr>() || 1501 Global->hasAttr<CUDAConstantAttr>() || 1502 Global->hasAttr<CUDASharedAttr>())) 1503 return; 1504 } 1505 } 1506 1507 // Ignore declarations, they will be emitted on their first use. 1508 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1509 // Forward declarations are emitted lazily on first use. 1510 if (!FD->doesThisDeclarationHaveABody()) { 1511 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1512 return; 1513 1514 StringRef MangledName = getMangledName(GD); 1515 1516 // Compute the function info and LLVM type. 1517 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 1518 llvm::Type *Ty = getTypes().GetFunctionType(FI); 1519 1520 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 1521 /*DontDefer=*/false); 1522 return; 1523 } 1524 } else { 1525 const auto *VD = cast<VarDecl>(Global); 1526 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1527 1528 if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 1529 !Context.isMSStaticDataMemberInlineDefinition(VD)) 1530 return; 1531 } 1532 1533 // Defer code generation to first use when possible, e.g. if this is an inline 1534 // function. If the global must always be emitted, do it eagerly if possible 1535 // to benefit from cache locality. 1536 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 1537 // Emit the definition if it can't be deferred. 1538 EmitGlobalDefinition(GD); 1539 return; 1540 } 1541 1542 // If we're deferring emission of a C++ variable with an 1543 // initializer, remember the order in which it appeared in the file. 1544 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1545 cast<VarDecl>(Global)->hasInit()) { 1546 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 1547 CXXGlobalInits.push_back(nullptr); 1548 } 1549 1550 StringRef MangledName = getMangledName(GD); 1551 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) { 1552 // The value has already been used and should therefore be emitted. 1553 addDeferredDeclToEmit(GV, GD); 1554 } else if (MustBeEmitted(Global)) { 1555 // The value must be emitted, but cannot be emitted eagerly. 1556 assert(!MayBeEmittedEagerly(Global)); 1557 addDeferredDeclToEmit(/*GV=*/nullptr, GD); 1558 } else { 1559 // Otherwise, remember that we saw a deferred decl with this name. The 1560 // first use of the mangled name will cause it to move into 1561 // DeferredDeclsToEmit. 1562 DeferredDecls[MangledName] = GD; 1563 } 1564 } 1565 1566 namespace { 1567 struct FunctionIsDirectlyRecursive : 1568 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1569 const StringRef Name; 1570 const Builtin::Context &BI; 1571 bool Result; 1572 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1573 Name(N), BI(C), Result(false) { 1574 } 1575 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1576 1577 bool TraverseCallExpr(CallExpr *E) { 1578 const FunctionDecl *FD = E->getDirectCallee(); 1579 if (!FD) 1580 return true; 1581 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1582 if (Attr && Name == Attr->getLabel()) { 1583 Result = true; 1584 return false; 1585 } 1586 unsigned BuiltinID = FD->getBuiltinID(); 1587 if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 1588 return true; 1589 StringRef BuiltinName = BI.getName(BuiltinID); 1590 if (BuiltinName.startswith("__builtin_") && 1591 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1592 Result = true; 1593 return false; 1594 } 1595 return true; 1596 } 1597 }; 1598 1599 struct DLLImportFunctionVisitor 1600 : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 1601 bool SafeToInline = true; 1602 1603 bool VisitVarDecl(VarDecl *VD) { 1604 // A thread-local variable cannot be imported. 1605 SafeToInline = !VD->getTLSKind(); 1606 return SafeToInline; 1607 } 1608 1609 // Make sure we're not referencing non-imported vars or functions. 1610 bool VisitDeclRefExpr(DeclRefExpr *E) { 1611 ValueDecl *VD = E->getDecl(); 1612 if (isa<FunctionDecl>(VD)) 1613 SafeToInline = VD->hasAttr<DLLImportAttr>(); 1614 else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 1615 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 1616 return SafeToInline; 1617 } 1618 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 1619 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 1620 return SafeToInline; 1621 } 1622 bool VisitCXXNewExpr(CXXNewExpr *E) { 1623 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 1624 return SafeToInline; 1625 } 1626 }; 1627 } 1628 1629 // isTriviallyRecursive - Check if this function calls another 1630 // decl that, because of the asm attribute or the other decl being a builtin, 1631 // ends up pointing to itself. 1632 bool 1633 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1634 StringRef Name; 1635 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1636 // asm labels are a special kind of mangling we have to support. 1637 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1638 if (!Attr) 1639 return false; 1640 Name = Attr->getLabel(); 1641 } else { 1642 Name = FD->getName(); 1643 } 1644 1645 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1646 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1647 return Walker.Result; 1648 } 1649 1650 bool 1651 CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1652 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1653 return true; 1654 const auto *F = cast<FunctionDecl>(GD.getDecl()); 1655 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1656 return false; 1657 1658 if (F->hasAttr<DLLImportAttr>()) { 1659 // Check whether it would be safe to inline this dllimport function. 1660 DLLImportFunctionVisitor Visitor; 1661 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 1662 if (!Visitor.SafeToInline) 1663 return false; 1664 } 1665 1666 // PR9614. Avoid cases where the source code is lying to us. An available 1667 // externally function should have an equivalent function somewhere else, 1668 // but a function that calls itself is clearly not equivalent to the real 1669 // implementation. 1670 // This happens in glibc's btowc and in some configure checks. 1671 return !isTriviallyRecursive(F); 1672 } 1673 1674 /// If the type for the method's class was generated by 1675 /// CGDebugInfo::createContextChain(), the cache contains only a 1676 /// limited DIType without any declarations. Since EmitFunctionStart() 1677 /// needs to find the canonical declaration for each method, we need 1678 /// to construct the complete type prior to emitting the method. 1679 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) { 1680 if (!D->isInstance()) 1681 return; 1682 1683 if (CGDebugInfo *DI = getModuleDebugInfo()) 1684 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 1685 const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext())); 1686 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation()); 1687 } 1688 } 1689 1690 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 1691 const auto *D = cast<ValueDecl>(GD.getDecl()); 1692 1693 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1694 Context.getSourceManager(), 1695 "Generating code for declaration"); 1696 1697 if (isa<FunctionDecl>(D)) { 1698 // At -O0, don't generate IR for functions with available_externally 1699 // linkage. 1700 if (!shouldEmitFunction(GD)) 1701 return; 1702 1703 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 1704 CompleteDIClassType(Method); 1705 // Make sure to emit the definition(s) before we emit the thunks. 1706 // This is necessary for the generation of certain thunks. 1707 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 1708 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 1709 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 1710 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 1711 else 1712 EmitGlobalFunctionDefinition(GD, GV); 1713 1714 if (Method->isVirtual()) 1715 getVTables().EmitThunks(GD); 1716 1717 return; 1718 } 1719 1720 return EmitGlobalFunctionDefinition(GD, GV); 1721 } 1722 1723 if (const auto *VD = dyn_cast<VarDecl>(D)) 1724 return EmitGlobalVarDefinition(VD); 1725 1726 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1727 } 1728 1729 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1730 llvm::Function *NewFn); 1731 1732 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1733 /// module, create and return an llvm Function with the specified type. If there 1734 /// is something in the module with the specified name, return it potentially 1735 /// bitcasted to the right type. 1736 /// 1737 /// If D is non-null, it specifies a decl that correspond to this. This is used 1738 /// to set the attributes on the function when it is first created. 1739 llvm::Constant * 1740 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 1741 llvm::Type *Ty, 1742 GlobalDecl GD, bool ForVTable, 1743 bool DontDefer, bool IsThunk, 1744 llvm::AttributeSet ExtraAttrs, 1745 bool IsForDefinition) { 1746 const Decl *D = GD.getDecl(); 1747 1748 // Lookup the entry, lazily creating it if necessary. 1749 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1750 if (Entry) { 1751 if (WeakRefReferences.erase(Entry)) { 1752 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 1753 if (FD && !FD->hasAttr<WeakAttr>()) 1754 Entry->setLinkage(llvm::Function::ExternalLinkage); 1755 } 1756 1757 // Handle dropped DLL attributes. 1758 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 1759 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 1760 1761 // If there are two attempts to define the same mangled name, issue an 1762 // error. 1763 if (IsForDefinition && !Entry->isDeclaration()) { 1764 GlobalDecl OtherGD; 1765 // Check that GD is not yet in ExplicitDefinitions is required to make 1766 // sure that we issue an error only once. 1767 if (lookupRepresentativeDecl(MangledName, OtherGD) && 1768 (GD.getCanonicalDecl().getDecl() != 1769 OtherGD.getCanonicalDecl().getDecl()) && 1770 DiagnosedConflictingDefinitions.insert(GD).second) { 1771 getDiags().Report(D->getLocation(), 1772 diag::err_duplicate_mangled_name); 1773 getDiags().Report(OtherGD.getDecl()->getLocation(), 1774 diag::note_previous_definition); 1775 } 1776 } 1777 1778 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 1779 (Entry->getType()->getElementType() == Ty)) { 1780 return Entry; 1781 } 1782 1783 // Make sure the result is of the correct type. 1784 // (If function is requested for a definition, we always need to create a new 1785 // function, not just return a bitcast.) 1786 if (!IsForDefinition) 1787 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1788 } 1789 1790 // This function doesn't have a complete type (for example, the return 1791 // type is an incomplete struct). Use a fake type instead, and make 1792 // sure not to try to set attributes. 1793 bool IsIncompleteFunction = false; 1794 1795 llvm::FunctionType *FTy; 1796 if (isa<llvm::FunctionType>(Ty)) { 1797 FTy = cast<llvm::FunctionType>(Ty); 1798 } else { 1799 FTy = llvm::FunctionType::get(VoidTy, false); 1800 IsIncompleteFunction = true; 1801 } 1802 1803 llvm::Function *F = 1804 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 1805 Entry ? StringRef() : MangledName, &getModule()); 1806 1807 // If we already created a function with the same mangled name (but different 1808 // type) before, take its name and add it to the list of functions to be 1809 // replaced with F at the end of CodeGen. 1810 // 1811 // This happens if there is a prototype for a function (e.g. "int f()") and 1812 // then a definition of a different type (e.g. "int f(int x)"). 1813 if (Entry) { 1814 F->takeName(Entry); 1815 1816 // This might be an implementation of a function without a prototype, in 1817 // which case, try to do special replacement of calls which match the new 1818 // prototype. The really key thing here is that we also potentially drop 1819 // arguments from the call site so as to make a direct call, which makes the 1820 // inliner happier and suppresses a number of optimizer warnings (!) about 1821 // dropping arguments. 1822 if (!Entry->use_empty()) { 1823 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 1824 Entry->removeDeadConstantUsers(); 1825 } 1826 1827 llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 1828 F, Entry->getType()->getElementType()->getPointerTo()); 1829 addGlobalValReplacement(Entry, BC); 1830 } 1831 1832 assert(F->getName() == MangledName && "name was uniqued!"); 1833 if (D) 1834 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 1835 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) { 1836 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex); 1837 F->addAttributes(llvm::AttributeSet::FunctionIndex, 1838 llvm::AttributeSet::get(VMContext, 1839 llvm::AttributeSet::FunctionIndex, 1840 B)); 1841 } 1842 1843 if (!DontDefer) { 1844 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 1845 // each other bottoming out with the base dtor. Therefore we emit non-base 1846 // dtors on usage, even if there is no dtor definition in the TU. 1847 if (D && isa<CXXDestructorDecl>(D) && 1848 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 1849 GD.getDtorType())) 1850 addDeferredDeclToEmit(F, GD); 1851 1852 // This is the first use or definition of a mangled name. If there is a 1853 // deferred decl with this name, remember that we need to emit it at the end 1854 // of the file. 1855 auto DDI = DeferredDecls.find(MangledName); 1856 if (DDI != DeferredDecls.end()) { 1857 // Move the potentially referenced deferred decl to the 1858 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 1859 // don't need it anymore). 1860 addDeferredDeclToEmit(F, DDI->second); 1861 DeferredDecls.erase(DDI); 1862 1863 // Otherwise, there are cases we have to worry about where we're 1864 // using a declaration for which we must emit a definition but where 1865 // we might not find a top-level definition: 1866 // - member functions defined inline in their classes 1867 // - friend functions defined inline in some class 1868 // - special member functions with implicit definitions 1869 // If we ever change our AST traversal to walk into class methods, 1870 // this will be unnecessary. 1871 // 1872 // We also don't emit a definition for a function if it's going to be an 1873 // entry in a vtable, unless it's already marked as used. 1874 } else if (getLangOpts().CPlusPlus && D) { 1875 // Look for a declaration that's lexically in a record. 1876 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 1877 FD = FD->getPreviousDecl()) { 1878 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 1879 if (FD->doesThisDeclarationHaveABody()) { 1880 addDeferredDeclToEmit(F, GD.getWithDecl(FD)); 1881 break; 1882 } 1883 } 1884 } 1885 } 1886 } 1887 1888 // Make sure the result is of the requested type. 1889 if (!IsIncompleteFunction) { 1890 assert(F->getType()->getElementType() == Ty); 1891 return F; 1892 } 1893 1894 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1895 return llvm::ConstantExpr::getBitCast(F, PTy); 1896 } 1897 1898 /// GetAddrOfFunction - Return the address of the given function. If Ty is 1899 /// non-null, then this function will use the specified type if it has to 1900 /// create it (this occurs when we see a definition of the function). 1901 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 1902 llvm::Type *Ty, 1903 bool ForVTable, 1904 bool DontDefer, 1905 bool IsForDefinition) { 1906 // If there was no specific requested type, just convert it now. 1907 if (!Ty) 1908 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 1909 1910 StringRef MangledName = getMangledName(GD); 1911 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 1912 /*IsThunk=*/false, llvm::AttributeSet(), 1913 IsForDefinition); 1914 } 1915 1916 /// CreateRuntimeFunction - Create a new runtime function with the specified 1917 /// type and name. 1918 llvm::Constant * 1919 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 1920 StringRef Name, 1921 llvm::AttributeSet ExtraAttrs) { 1922 llvm::Constant *C = 1923 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 1924 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 1925 if (auto *F = dyn_cast<llvm::Function>(C)) 1926 if (F->empty()) 1927 F->setCallingConv(getRuntimeCC()); 1928 return C; 1929 } 1930 1931 /// CreateBuiltinFunction - Create a new builtin function with the specified 1932 /// type and name. 1933 llvm::Constant * 1934 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, 1935 StringRef Name, 1936 llvm::AttributeSet ExtraAttrs) { 1937 llvm::Constant *C = 1938 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 1939 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 1940 if (auto *F = dyn_cast<llvm::Function>(C)) 1941 if (F->empty()) 1942 F->setCallingConv(getBuiltinCC()); 1943 return C; 1944 } 1945 1946 /// isTypeConstant - Determine whether an object of this type can be emitted 1947 /// as a constant. 1948 /// 1949 /// If ExcludeCtor is true, the duration when the object's constructor runs 1950 /// will not be considered. The caller will need to verify that the object is 1951 /// not written to during its construction. 1952 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 1953 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 1954 return false; 1955 1956 if (Context.getLangOpts().CPlusPlus) { 1957 if (const CXXRecordDecl *Record 1958 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 1959 return ExcludeCtor && !Record->hasMutableFields() && 1960 Record->hasTrivialDestructor(); 1961 } 1962 1963 return true; 1964 } 1965 1966 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1967 /// create and return an llvm GlobalVariable with the specified type. If there 1968 /// is something in the module with the specified name, return it potentially 1969 /// bitcasted to the right type. 1970 /// 1971 /// If D is non-null, it specifies a decl that correspond to this. This is used 1972 /// to set the attributes on the global when it is first created. 1973 llvm::Constant * 1974 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 1975 llvm::PointerType *Ty, 1976 const VarDecl *D) { 1977 // Lookup the entry, lazily creating it if necessary. 1978 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1979 if (Entry) { 1980 if (WeakRefReferences.erase(Entry)) { 1981 if (D && !D->hasAttr<WeakAttr>()) 1982 Entry->setLinkage(llvm::Function::ExternalLinkage); 1983 } 1984 1985 // Handle dropped DLL attributes. 1986 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 1987 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 1988 1989 if (Entry->getType() == Ty) 1990 return Entry; 1991 1992 // Make sure the result is of the correct type. 1993 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 1994 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 1995 1996 return llvm::ConstantExpr::getBitCast(Entry, Ty); 1997 } 1998 1999 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 2000 auto *GV = new llvm::GlobalVariable( 2001 getModule(), Ty->getElementType(), false, 2002 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 2003 llvm::GlobalVariable::NotThreadLocal, AddrSpace); 2004 2005 // This is the first use or definition of a mangled name. If there is a 2006 // deferred decl with this name, remember that we need to emit it at the end 2007 // of the file. 2008 auto DDI = DeferredDecls.find(MangledName); 2009 if (DDI != DeferredDecls.end()) { 2010 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 2011 // list, and remove it from DeferredDecls (since we don't need it anymore). 2012 addDeferredDeclToEmit(GV, DDI->second); 2013 DeferredDecls.erase(DDI); 2014 } 2015 2016 // Handle things which are present even on external declarations. 2017 if (D) { 2018 // FIXME: This code is overly simple and should be merged with other global 2019 // handling. 2020 GV->setConstant(isTypeConstant(D->getType(), false)); 2021 2022 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2023 2024 setLinkageAndVisibilityForGV(GV, D); 2025 2026 if (D->getTLSKind()) { 2027 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 2028 CXXThreadLocals.push_back(std::make_pair(D, GV)); 2029 setTLSMode(GV, *D); 2030 } 2031 2032 // If required by the ABI, treat declarations of static data members with 2033 // inline initializers as definitions. 2034 if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 2035 EmitGlobalVarDefinition(D); 2036 } 2037 2038 // Handle XCore specific ABI requirements. 2039 if (getTarget().getTriple().getArch() == llvm::Triple::xcore && 2040 D->getLanguageLinkage() == CLanguageLinkage && 2041 D->getType().isConstant(Context) && 2042 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 2043 GV->setSection(".cp.rodata"); 2044 } 2045 2046 if (AddrSpace != Ty->getAddressSpace()) 2047 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 2048 2049 return GV; 2050 } 2051 2052 llvm::Constant * 2053 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, 2054 bool IsForDefinition) { 2055 if (isa<CXXConstructorDecl>(GD.getDecl())) 2056 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()), 2057 getFromCtorType(GD.getCtorType()), 2058 /*FnInfo=*/nullptr, /*FnType=*/nullptr, 2059 /*DontDefer=*/false, IsForDefinition); 2060 else if (isa<CXXDestructorDecl>(GD.getDecl())) 2061 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()), 2062 getFromDtorType(GD.getDtorType()), 2063 /*FnInfo=*/nullptr, /*FnType=*/nullptr, 2064 /*DontDefer=*/false, IsForDefinition); 2065 else if (isa<CXXMethodDecl>(GD.getDecl())) { 2066 auto FInfo = &getTypes().arrangeCXXMethodDeclaration( 2067 cast<CXXMethodDecl>(GD.getDecl())); 2068 auto Ty = getTypes().GetFunctionType(*FInfo); 2069 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 2070 IsForDefinition); 2071 } else if (isa<FunctionDecl>(GD.getDecl())) { 2072 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2073 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2074 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 2075 IsForDefinition); 2076 } else 2077 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl())); 2078 } 2079 2080 llvm::GlobalVariable * 2081 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 2082 llvm::Type *Ty, 2083 llvm::GlobalValue::LinkageTypes Linkage) { 2084 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 2085 llvm::GlobalVariable *OldGV = nullptr; 2086 2087 if (GV) { 2088 // Check if the variable has the right type. 2089 if (GV->getType()->getElementType() == Ty) 2090 return GV; 2091 2092 // Because C++ name mangling, the only way we can end up with an already 2093 // existing global with the same name is if it has been declared extern "C". 2094 assert(GV->isDeclaration() && "Declaration has wrong type!"); 2095 OldGV = GV; 2096 } 2097 2098 // Create a new variable. 2099 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 2100 Linkage, nullptr, Name); 2101 2102 if (OldGV) { 2103 // Replace occurrences of the old variable if needed. 2104 GV->takeName(OldGV); 2105 2106 if (!OldGV->use_empty()) { 2107 llvm::Constant *NewPtrForOldDecl = 2108 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 2109 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 2110 } 2111 2112 OldGV->eraseFromParent(); 2113 } 2114 2115 if (supportsCOMDAT() && GV->isWeakForLinker() && 2116 !GV->hasAvailableExternallyLinkage()) 2117 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2118 2119 return GV; 2120 } 2121 2122 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 2123 /// given global variable. If Ty is non-null and if the global doesn't exist, 2124 /// then it will be created with the specified type instead of whatever the 2125 /// normal requested type would be. 2126 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 2127 llvm::Type *Ty) { 2128 assert(D->hasGlobalStorage() && "Not a global variable"); 2129 QualType ASTTy = D->getType(); 2130 if (!Ty) 2131 Ty = getTypes().ConvertTypeForMem(ASTTy); 2132 2133 llvm::PointerType *PTy = 2134 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 2135 2136 StringRef MangledName = getMangledName(D); 2137 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 2138 } 2139 2140 /// CreateRuntimeVariable - Create a new runtime global variable with the 2141 /// specified type and name. 2142 llvm::Constant * 2143 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 2144 StringRef Name) { 2145 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); 2146 } 2147 2148 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 2149 assert(!D->getInit() && "Cannot emit definite definitions here!"); 2150 2151 if (!MustBeEmitted(D)) { 2152 // If we have not seen a reference to this variable yet, place it 2153 // into the deferred declarations table to be emitted if needed 2154 // later. 2155 StringRef MangledName = getMangledName(D); 2156 if (!GetGlobalValue(MangledName)) { 2157 DeferredDecls[MangledName] = D; 2158 return; 2159 } 2160 } 2161 2162 // The tentative definition is the only definition. 2163 EmitGlobalVarDefinition(D); 2164 } 2165 2166 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 2167 return Context.toCharUnitsFromBits( 2168 getDataLayout().getTypeStoreSizeInBits(Ty)); 2169 } 2170 2171 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 2172 unsigned AddrSpace) { 2173 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 2174 if (D->hasAttr<CUDAConstantAttr>()) 2175 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 2176 else if (D->hasAttr<CUDASharedAttr>()) 2177 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 2178 else 2179 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 2180 } 2181 2182 return AddrSpace; 2183 } 2184 2185 template<typename SomeDecl> 2186 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 2187 llvm::GlobalValue *GV) { 2188 if (!getLangOpts().CPlusPlus) 2189 return; 2190 2191 // Must have 'used' attribute, or else inline assembly can't rely on 2192 // the name existing. 2193 if (!D->template hasAttr<UsedAttr>()) 2194 return; 2195 2196 // Must have internal linkage and an ordinary name. 2197 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 2198 return; 2199 2200 // Must be in an extern "C" context. Entities declared directly within 2201 // a record are not extern "C" even if the record is in such a context. 2202 const SomeDecl *First = D->getFirstDecl(); 2203 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 2204 return; 2205 2206 // OK, this is an internal linkage entity inside an extern "C" linkage 2207 // specification. Make a note of that so we can give it the "expected" 2208 // mangled name if nothing else is using that name. 2209 std::pair<StaticExternCMap::iterator, bool> R = 2210 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 2211 2212 // If we have multiple internal linkage entities with the same name 2213 // in extern "C" regions, none of them gets that name. 2214 if (!R.second) 2215 R.first->second = nullptr; 2216 } 2217 2218 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 2219 if (!CGM.supportsCOMDAT()) 2220 return false; 2221 2222 if (D.hasAttr<SelectAnyAttr>()) 2223 return true; 2224 2225 GVALinkage Linkage; 2226 if (auto *VD = dyn_cast<VarDecl>(&D)) 2227 Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 2228 else 2229 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 2230 2231 switch (Linkage) { 2232 case GVA_Internal: 2233 case GVA_AvailableExternally: 2234 case GVA_StrongExternal: 2235 return false; 2236 case GVA_DiscardableODR: 2237 case GVA_StrongODR: 2238 return true; 2239 } 2240 llvm_unreachable("No such linkage"); 2241 } 2242 2243 void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 2244 llvm::GlobalObject &GO) { 2245 if (!shouldBeInCOMDAT(*this, D)) 2246 return; 2247 GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 2248 } 2249 2250 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 2251 llvm::Constant *Init = nullptr; 2252 QualType ASTTy = D->getType(); 2253 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2254 bool NeedsGlobalCtor = false; 2255 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 2256 2257 const VarDecl *InitDecl; 2258 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 2259 2260 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization as part 2261 // of their declaration." 2262 if (getLangOpts().CPlusPlus && getLangOpts().CUDAIsDevice 2263 && D->hasAttr<CUDASharedAttr>()) { 2264 if (InitExpr) { 2265 const auto *C = dyn_cast<CXXConstructExpr>(InitExpr); 2266 if (C == nullptr || !C->getConstructor()->hasTrivialBody()) 2267 Error(D->getLocation(), 2268 "__shared__ variable cannot have an initialization."); 2269 } 2270 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 2271 } else if (!InitExpr) { 2272 // This is a tentative definition; tentative definitions are 2273 // implicitly initialized with { 0 }. 2274 // 2275 // Note that tentative definitions are only emitted at the end of 2276 // a translation unit, so they should never have incomplete 2277 // type. In addition, EmitTentativeDefinition makes sure that we 2278 // never attempt to emit a tentative definition if a real one 2279 // exists. A use may still exists, however, so we still may need 2280 // to do a RAUW. 2281 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 2282 Init = EmitNullConstant(D->getType()); 2283 } else { 2284 initializedGlobalDecl = GlobalDecl(D); 2285 Init = EmitConstantInit(*InitDecl); 2286 2287 if (!Init) { 2288 QualType T = InitExpr->getType(); 2289 if (D->getType()->isReferenceType()) 2290 T = D->getType(); 2291 2292 if (getLangOpts().CPlusPlus) { 2293 Init = EmitNullConstant(T); 2294 NeedsGlobalCtor = true; 2295 } else { 2296 ErrorUnsupported(D, "static initializer"); 2297 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 2298 } 2299 } else { 2300 // We don't need an initializer, so remove the entry for the delayed 2301 // initializer position (just in case this entry was delayed) if we 2302 // also don't need to register a destructor. 2303 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 2304 DelayedCXXInitPosition.erase(D); 2305 } 2306 } 2307 2308 llvm::Type* InitType = Init->getType(); 2309 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 2310 2311 // Strip off a bitcast if we got one back. 2312 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2313 assert(CE->getOpcode() == llvm::Instruction::BitCast || 2314 CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 2315 // All zero index gep. 2316 CE->getOpcode() == llvm::Instruction::GetElementPtr); 2317 Entry = CE->getOperand(0); 2318 } 2319 2320 // Entry is now either a Function or GlobalVariable. 2321 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 2322 2323 // We have a definition after a declaration with the wrong type. 2324 // We must make a new GlobalVariable* and update everything that used OldGV 2325 // (a declaration or tentative definition) with the new GlobalVariable* 2326 // (which will be a definition). 2327 // 2328 // This happens if there is a prototype for a global (e.g. 2329 // "extern int x[];") and then a definition of a different type (e.g. 2330 // "int x[10];"). This also happens when an initializer has a different type 2331 // from the type of the global (this happens with unions). 2332 if (!GV || 2333 GV->getType()->getElementType() != InitType || 2334 GV->getType()->getAddressSpace() != 2335 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 2336 2337 // Move the old entry aside so that we'll create a new one. 2338 Entry->setName(StringRef()); 2339 2340 // Make a new global with the correct type, this is now guaranteed to work. 2341 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 2342 2343 // Replace all uses of the old global with the new global 2344 llvm::Constant *NewPtrForOldDecl = 2345 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2346 Entry->replaceAllUsesWith(NewPtrForOldDecl); 2347 2348 // Erase the old global, since it is no longer used. 2349 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 2350 } 2351 2352 MaybeHandleStaticInExternC(D, GV); 2353 2354 if (D->hasAttr<AnnotateAttr>()) 2355 AddGlobalAnnotations(D, GV); 2356 2357 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 2358 // the device. [...]" 2359 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 2360 // __device__, declares a variable that: [...] 2361 // Is accessible from all the threads within the grid and from the host 2362 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 2363 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 2364 if (GV && LangOpts.CUDA && LangOpts.CUDAIsDevice && 2365 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>())) { 2366 GV->setExternallyInitialized(true); 2367 } 2368 GV->setInitializer(Init); 2369 2370 // If it is safe to mark the global 'constant', do so now. 2371 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 2372 isTypeConstant(D->getType(), true)); 2373 2374 // If it is in a read-only section, mark it 'constant'. 2375 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 2376 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 2377 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 2378 GV->setConstant(true); 2379 } 2380 2381 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2382 2383 // Set the llvm linkage type as appropriate. 2384 llvm::GlobalValue::LinkageTypes Linkage = 2385 getLLVMLinkageVarDefinition(D, GV->isConstant()); 2386 2387 // On Darwin, the backing variable for a C++11 thread_local variable always 2388 // has internal linkage; all accesses should just be calls to the 2389 // Itanium-specified entry point, which has the normal linkage of the 2390 // variable. 2391 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic && 2392 Context.getTargetInfo().getTriple().isMacOSX()) 2393 Linkage = llvm::GlobalValue::InternalLinkage; 2394 2395 GV->setLinkage(Linkage); 2396 if (D->hasAttr<DLLImportAttr>()) 2397 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 2398 else if (D->hasAttr<DLLExportAttr>()) 2399 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 2400 else 2401 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 2402 2403 if (Linkage == llvm::GlobalVariable::CommonLinkage) 2404 // common vars aren't constant even if declared const. 2405 GV->setConstant(false); 2406 2407 setNonAliasAttributes(D, GV); 2408 2409 if (D->getTLSKind() && !GV->isThreadLocal()) { 2410 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 2411 CXXThreadLocals.push_back(std::make_pair(D, GV)); 2412 setTLSMode(GV, *D); 2413 } 2414 2415 maybeSetTrivialComdat(*D, *GV); 2416 2417 // Emit the initializer function if necessary. 2418 if (NeedsGlobalCtor || NeedsGlobalDtor) 2419 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 2420 2421 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 2422 2423 // Emit global variable debug information. 2424 if (CGDebugInfo *DI = getModuleDebugInfo()) 2425 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 2426 DI->EmitGlobalVariable(GV, D); 2427 } 2428 2429 static bool isVarDeclStrongDefinition(const ASTContext &Context, 2430 CodeGenModule &CGM, const VarDecl *D, 2431 bool NoCommon) { 2432 // Don't give variables common linkage if -fno-common was specified unless it 2433 // was overridden by a NoCommon attribute. 2434 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 2435 return true; 2436 2437 // C11 6.9.2/2: 2438 // A declaration of an identifier for an object that has file scope without 2439 // an initializer, and without a storage-class specifier or with the 2440 // storage-class specifier static, constitutes a tentative definition. 2441 if (D->getInit() || D->hasExternalStorage()) 2442 return true; 2443 2444 // A variable cannot be both common and exist in a section. 2445 if (D->hasAttr<SectionAttr>()) 2446 return true; 2447 2448 // Thread local vars aren't considered common linkage. 2449 if (D->getTLSKind()) 2450 return true; 2451 2452 // Tentative definitions marked with WeakImportAttr are true definitions. 2453 if (D->hasAttr<WeakImportAttr>()) 2454 return true; 2455 2456 // A variable cannot be both common and exist in a comdat. 2457 if (shouldBeInCOMDAT(CGM, *D)) 2458 return true; 2459 2460 // Declarations with a required alignment do not have common linakge in MSVC 2461 // mode. 2462 if (Context.getLangOpts().MSVCCompat) { 2463 if (D->hasAttr<AlignedAttr>()) 2464 return true; 2465 QualType VarType = D->getType(); 2466 if (Context.isAlignmentRequired(VarType)) 2467 return true; 2468 2469 if (const auto *RT = VarType->getAs<RecordType>()) { 2470 const RecordDecl *RD = RT->getDecl(); 2471 for (const FieldDecl *FD : RD->fields()) { 2472 if (FD->isBitField()) 2473 continue; 2474 if (FD->hasAttr<AlignedAttr>()) 2475 return true; 2476 if (Context.isAlignmentRequired(FD->getType())) 2477 return true; 2478 } 2479 } 2480 } 2481 2482 return false; 2483 } 2484 2485 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 2486 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 2487 if (Linkage == GVA_Internal) 2488 return llvm::Function::InternalLinkage; 2489 2490 if (D->hasAttr<WeakAttr>()) { 2491 if (IsConstantVariable) 2492 return llvm::GlobalVariable::WeakODRLinkage; 2493 else 2494 return llvm::GlobalVariable::WeakAnyLinkage; 2495 } 2496 2497 // We are guaranteed to have a strong definition somewhere else, 2498 // so we can use available_externally linkage. 2499 if (Linkage == GVA_AvailableExternally) 2500 return llvm::Function::AvailableExternallyLinkage; 2501 2502 // Note that Apple's kernel linker doesn't support symbol 2503 // coalescing, so we need to avoid linkonce and weak linkages there. 2504 // Normally, this means we just map to internal, but for explicit 2505 // instantiations we'll map to external. 2506 2507 // In C++, the compiler has to emit a definition in every translation unit 2508 // that references the function. We should use linkonce_odr because 2509 // a) if all references in this translation unit are optimized away, we 2510 // don't need to codegen it. b) if the function persists, it needs to be 2511 // merged with other definitions. c) C++ has the ODR, so we know the 2512 // definition is dependable. 2513 if (Linkage == GVA_DiscardableODR) 2514 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 2515 : llvm::Function::InternalLinkage; 2516 2517 // An explicit instantiation of a template has weak linkage, since 2518 // explicit instantiations can occur in multiple translation units 2519 // and must all be equivalent. However, we are not allowed to 2520 // throw away these explicit instantiations. 2521 if (Linkage == GVA_StrongODR) 2522 return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage 2523 : llvm::Function::ExternalLinkage; 2524 2525 // C++ doesn't have tentative definitions and thus cannot have common 2526 // linkage. 2527 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 2528 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 2529 CodeGenOpts.NoCommon)) 2530 return llvm::GlobalVariable::CommonLinkage; 2531 2532 // selectany symbols are externally visible, so use weak instead of 2533 // linkonce. MSVC optimizes away references to const selectany globals, so 2534 // all definitions should be the same and ODR linkage should be used. 2535 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 2536 if (D->hasAttr<SelectAnyAttr>()) 2537 return llvm::GlobalVariable::WeakODRLinkage; 2538 2539 // Otherwise, we have strong external linkage. 2540 assert(Linkage == GVA_StrongExternal); 2541 return llvm::GlobalVariable::ExternalLinkage; 2542 } 2543 2544 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 2545 const VarDecl *VD, bool IsConstant) { 2546 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 2547 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 2548 } 2549 2550 /// Replace the uses of a function that was declared with a non-proto type. 2551 /// We want to silently drop extra arguments from call sites 2552 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 2553 llvm::Function *newFn) { 2554 // Fast path. 2555 if (old->use_empty()) return; 2556 2557 llvm::Type *newRetTy = newFn->getReturnType(); 2558 SmallVector<llvm::Value*, 4> newArgs; 2559 2560 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 2561 ui != ue; ) { 2562 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 2563 llvm::User *user = use->getUser(); 2564 2565 // Recognize and replace uses of bitcasts. Most calls to 2566 // unprototyped functions will use bitcasts. 2567 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 2568 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 2569 replaceUsesOfNonProtoConstant(bitcast, newFn); 2570 continue; 2571 } 2572 2573 // Recognize calls to the function. 2574 llvm::CallSite callSite(user); 2575 if (!callSite) continue; 2576 if (!callSite.isCallee(&*use)) continue; 2577 2578 // If the return types don't match exactly, then we can't 2579 // transform this call unless it's dead. 2580 if (callSite->getType() != newRetTy && !callSite->use_empty()) 2581 continue; 2582 2583 // Get the call site's attribute list. 2584 SmallVector<llvm::AttributeSet, 8> newAttrs; 2585 llvm::AttributeSet oldAttrs = callSite.getAttributes(); 2586 2587 // Collect any return attributes from the call. 2588 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex)) 2589 newAttrs.push_back( 2590 llvm::AttributeSet::get(newFn->getContext(), 2591 oldAttrs.getRetAttributes())); 2592 2593 // If the function was passed too few arguments, don't transform. 2594 unsigned newNumArgs = newFn->arg_size(); 2595 if (callSite.arg_size() < newNumArgs) continue; 2596 2597 // If extra arguments were passed, we silently drop them. 2598 // If any of the types mismatch, we don't transform. 2599 unsigned argNo = 0; 2600 bool dontTransform = false; 2601 for (llvm::Function::arg_iterator ai = newFn->arg_begin(), 2602 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) { 2603 if (callSite.getArgument(argNo)->getType() != ai->getType()) { 2604 dontTransform = true; 2605 break; 2606 } 2607 2608 // Add any parameter attributes. 2609 if (oldAttrs.hasAttributes(argNo + 1)) 2610 newAttrs. 2611 push_back(llvm:: 2612 AttributeSet::get(newFn->getContext(), 2613 oldAttrs.getParamAttributes(argNo + 1))); 2614 } 2615 if (dontTransform) 2616 continue; 2617 2618 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) 2619 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(), 2620 oldAttrs.getFnAttributes())); 2621 2622 // Okay, we can transform this. Create the new call instruction and copy 2623 // over the required information. 2624 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 2625 2626 llvm::CallSite newCall; 2627 if (callSite.isCall()) { 2628 newCall = llvm::CallInst::Create(newFn, newArgs, "", 2629 callSite.getInstruction()); 2630 } else { 2631 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); 2632 newCall = llvm::InvokeInst::Create(newFn, 2633 oldInvoke->getNormalDest(), 2634 oldInvoke->getUnwindDest(), 2635 newArgs, "", 2636 callSite.getInstruction()); 2637 } 2638 newArgs.clear(); // for the next iteration 2639 2640 if (!newCall->getType()->isVoidTy()) 2641 newCall->takeName(callSite.getInstruction()); 2642 newCall.setAttributes( 2643 llvm::AttributeSet::get(newFn->getContext(), newAttrs)); 2644 newCall.setCallingConv(callSite.getCallingConv()); 2645 2646 // Finally, remove the old call, replacing any uses with the new one. 2647 if (!callSite->use_empty()) 2648 callSite->replaceAllUsesWith(newCall.getInstruction()); 2649 2650 // Copy debug location attached to CI. 2651 if (callSite->getDebugLoc()) 2652 newCall->setDebugLoc(callSite->getDebugLoc()); 2653 callSite->eraseFromParent(); 2654 } 2655 } 2656 2657 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2658 /// implement a function with no prototype, e.g. "int foo() {}". If there are 2659 /// existing call uses of the old function in the module, this adjusts them to 2660 /// call the new function directly. 2661 /// 2662 /// This is not just a cleanup: the always_inline pass requires direct calls to 2663 /// functions to be able to inline them. If there is a bitcast in the way, it 2664 /// won't inline them. Instcombine normally deletes these calls, but it isn't 2665 /// run at -O0. 2666 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2667 llvm::Function *NewFn) { 2668 // If we're redefining a global as a function, don't transform it. 2669 if (!isa<llvm::Function>(Old)) return; 2670 2671 replaceUsesOfNonProtoConstant(Old, NewFn); 2672 } 2673 2674 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 2675 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 2676 // If we have a definition, this might be a deferred decl. If the 2677 // instantiation is explicit, make sure we emit it at the end. 2678 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 2679 GetAddrOfGlobalVar(VD); 2680 2681 EmitTopLevelDecl(VD); 2682 } 2683 2684 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 2685 llvm::GlobalValue *GV) { 2686 const auto *D = cast<FunctionDecl>(GD.getDecl()); 2687 2688 // Compute the function info and LLVM type. 2689 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2690 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2691 2692 // Get or create the prototype for the function. 2693 if (!GV || (GV->getType()->getElementType() != Ty)) 2694 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 2695 /*DontDefer=*/true, 2696 /*IsForDefinition=*/true)); 2697 2698 // Already emitted. 2699 if (!GV->isDeclaration()) 2700 return; 2701 2702 // We need to set linkage and visibility on the function before 2703 // generating code for it because various parts of IR generation 2704 // want to propagate this information down (e.g. to local static 2705 // declarations). 2706 auto *Fn = cast<llvm::Function>(GV); 2707 setFunctionLinkage(GD, Fn); 2708 setFunctionDLLStorageClass(GD, Fn); 2709 2710 // FIXME: this is redundant with part of setFunctionDefinitionAttributes 2711 setGlobalVisibility(Fn, D); 2712 2713 MaybeHandleStaticInExternC(D, Fn); 2714 2715 maybeSetTrivialComdat(*D, *Fn); 2716 2717 CodeGenFunction(*this).GenerateCode(D, Fn, FI); 2718 2719 setFunctionDefinitionAttributes(D, Fn); 2720 SetLLVMFunctionAttributesForDefinition(D, Fn); 2721 2722 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 2723 AddGlobalCtor(Fn, CA->getPriority()); 2724 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 2725 AddGlobalDtor(Fn, DA->getPriority()); 2726 if (D->hasAttr<AnnotateAttr>()) 2727 AddGlobalAnnotations(D, Fn); 2728 } 2729 2730 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 2731 const auto *D = cast<ValueDecl>(GD.getDecl()); 2732 const AliasAttr *AA = D->getAttr<AliasAttr>(); 2733 assert(AA && "Not an alias?"); 2734 2735 StringRef MangledName = getMangledName(GD); 2736 2737 if (AA->getAliasee() == MangledName) { 2738 Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 2739 return; 2740 } 2741 2742 // If there is a definition in the module, then it wins over the alias. 2743 // This is dubious, but allow it to be safe. Just ignore the alias. 2744 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2745 if (Entry && !Entry->isDeclaration()) 2746 return; 2747 2748 Aliases.push_back(GD); 2749 2750 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2751 2752 // Create a reference to the named value. This ensures that it is emitted 2753 // if a deferred decl. 2754 llvm::Constant *Aliasee; 2755 if (isa<llvm::FunctionType>(DeclTy)) 2756 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 2757 /*ForVTable=*/false); 2758 else 2759 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 2760 llvm::PointerType::getUnqual(DeclTy), 2761 /*D=*/nullptr); 2762 2763 // Create the new alias itself, but don't set a name yet. 2764 auto *GA = llvm::GlobalAlias::create( 2765 cast<llvm::PointerType>(Aliasee->getType()), 2766 llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); 2767 2768 if (Entry) { 2769 if (GA->getAliasee() == Entry) { 2770 Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 2771 return; 2772 } 2773 2774 assert(Entry->isDeclaration()); 2775 2776 // If there is a declaration in the module, then we had an extern followed 2777 // by the alias, as in: 2778 // extern int test6(); 2779 // ... 2780 // int test6() __attribute__((alias("test7"))); 2781 // 2782 // Remove it and replace uses of it with the alias. 2783 GA->takeName(Entry); 2784 2785 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2786 Entry->getType())); 2787 Entry->eraseFromParent(); 2788 } else { 2789 GA->setName(MangledName); 2790 } 2791 2792 // Set attributes which are particular to an alias; this is a 2793 // specialization of the attributes which may be set on a global 2794 // variable/function. 2795 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 2796 D->isWeakImported()) { 2797 GA->setLinkage(llvm::Function::WeakAnyLinkage); 2798 } 2799 2800 if (const auto *VD = dyn_cast<VarDecl>(D)) 2801 if (VD->getTLSKind()) 2802 setTLSMode(GA, *VD); 2803 2804 setAliasAttributes(D, GA); 2805 } 2806 2807 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 2808 ArrayRef<llvm::Type*> Tys) { 2809 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 2810 Tys); 2811 } 2812 2813 static llvm::StringMapEntry<llvm::GlobalVariable *> & 2814 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 2815 const StringLiteral *Literal, bool TargetIsLSB, 2816 bool &IsUTF16, unsigned &StringLength) { 2817 StringRef String = Literal->getString(); 2818 unsigned NumBytes = String.size(); 2819 2820 // Check for simple case. 2821 if (!Literal->containsNonAsciiOrNull()) { 2822 StringLength = NumBytes; 2823 return *Map.insert(std::make_pair(String, nullptr)).first; 2824 } 2825 2826 // Otherwise, convert the UTF8 literals into a string of shorts. 2827 IsUTF16 = true; 2828 2829 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 2830 const UTF8 *FromPtr = (const UTF8 *)String.data(); 2831 UTF16 *ToPtr = &ToBuf[0]; 2832 2833 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2834 &ToPtr, ToPtr + NumBytes, 2835 strictConversion); 2836 2837 // ConvertUTF8toUTF16 returns the length in ToPtr. 2838 StringLength = ToPtr - &ToBuf[0]; 2839 2840 // Add an explicit null. 2841 *ToPtr = 0; 2842 return *Map.insert(std::make_pair( 2843 StringRef(reinterpret_cast<const char *>(ToBuf.data()), 2844 (StringLength + 1) * 2), 2845 nullptr)).first; 2846 } 2847 2848 static llvm::StringMapEntry<llvm::GlobalVariable *> & 2849 GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 2850 const StringLiteral *Literal, unsigned &StringLength) { 2851 StringRef String = Literal->getString(); 2852 StringLength = String.size(); 2853 return *Map.insert(std::make_pair(String, nullptr)).first; 2854 } 2855 2856 ConstantAddress 2857 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 2858 unsigned StringLength = 0; 2859 bool isUTF16 = false; 2860 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2861 GetConstantCFStringEntry(CFConstantStringMap, Literal, 2862 getDataLayout().isLittleEndian(), isUTF16, 2863 StringLength); 2864 2865 if (auto *C = Entry.second) 2866 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 2867 2868 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2869 llvm::Constant *Zeros[] = { Zero, Zero }; 2870 llvm::Value *V; 2871 2872 // If we don't already have it, get __CFConstantStringClassReference. 2873 if (!CFConstantStringClassRef) { 2874 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2875 Ty = llvm::ArrayType::get(Ty, 0); 2876 llvm::Constant *GV = CreateRuntimeVariable(Ty, 2877 "__CFConstantStringClassReference"); 2878 // Decay array -> ptr 2879 V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros); 2880 CFConstantStringClassRef = V; 2881 } 2882 else 2883 V = CFConstantStringClassRef; 2884 2885 QualType CFTy = getContext().getCFConstantStringType(); 2886 2887 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 2888 2889 llvm::Constant *Fields[4]; 2890 2891 // Class pointer. 2892 Fields[0] = cast<llvm::ConstantExpr>(V); 2893 2894 // Flags. 2895 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2896 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 2897 llvm::ConstantInt::get(Ty, 0x07C8); 2898 2899 // String pointer. 2900 llvm::Constant *C = nullptr; 2901 if (isUTF16) { 2902 ArrayRef<uint16_t> Arr = llvm::makeArrayRef<uint16_t>( 2903 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 2904 Entry.first().size() / 2); 2905 C = llvm::ConstantDataArray::get(VMContext, Arr); 2906 } else { 2907 C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 2908 } 2909 2910 // Note: -fwritable-strings doesn't make the backing store strings of 2911 // CFStrings writable. (See <rdar://problem/10657500>) 2912 auto *GV = 2913 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 2914 llvm::GlobalValue::PrivateLinkage, C, ".str"); 2915 GV->setUnnamedAddr(true); 2916 // Don't enforce the target's minimum global alignment, since the only use 2917 // of the string is via this class initializer. 2918 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without 2919 // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing 2920 // that changes the section it ends in, which surprises ld64. 2921 if (isUTF16) { 2922 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 2923 GV->setAlignment(Align.getQuantity()); 2924 GV->setSection("__TEXT,__ustring"); 2925 } else { 2926 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2927 GV->setAlignment(Align.getQuantity()); 2928 GV->setSection("__TEXT,__cstring,cstring_literals"); 2929 } 2930 2931 // String. 2932 Fields[2] = 2933 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 2934 2935 if (isUTF16) 2936 // Cast the UTF16 string to the correct type. 2937 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 2938 2939 // String length. 2940 Ty = getTypes().ConvertType(getContext().LongTy); 2941 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 2942 2943 CharUnits Alignment = getPointerAlign(); 2944 2945 // The struct. 2946 C = llvm::ConstantStruct::get(STy, Fields); 2947 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2948 llvm::GlobalVariable::PrivateLinkage, C, 2949 "_unnamed_cfstring_"); 2950 GV->setSection("__DATA,__cfstring"); 2951 GV->setAlignment(Alignment.getQuantity()); 2952 Entry.second = GV; 2953 2954 return ConstantAddress(GV, Alignment); 2955 } 2956 2957 ConstantAddress 2958 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 2959 unsigned StringLength = 0; 2960 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2961 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 2962 2963 if (auto *C = Entry.second) 2964 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 2965 2966 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2967 llvm::Constant *Zeros[] = { Zero, Zero }; 2968 llvm::Value *V; 2969 // If we don't already have it, get _NSConstantStringClassReference. 2970 if (!ConstantStringClassRef) { 2971 std::string StringClass(getLangOpts().ObjCConstantStringClass); 2972 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2973 llvm::Constant *GV; 2974 if (LangOpts.ObjCRuntime.isNonFragile()) { 2975 std::string str = 2976 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 2977 : "OBJC_CLASS_$_" + StringClass; 2978 GV = getObjCRuntime().GetClassGlobal(str); 2979 // Make sure the result is of the correct type. 2980 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2981 V = llvm::ConstantExpr::getBitCast(GV, PTy); 2982 ConstantStringClassRef = V; 2983 } else { 2984 std::string str = 2985 StringClass.empty() ? "_NSConstantStringClassReference" 2986 : "_" + StringClass + "ClassReference"; 2987 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 2988 GV = CreateRuntimeVariable(PTy, str); 2989 // Decay array -> ptr 2990 V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros); 2991 ConstantStringClassRef = V; 2992 } 2993 } else 2994 V = ConstantStringClassRef; 2995 2996 if (!NSConstantStringType) { 2997 // Construct the type for a constant NSString. 2998 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString"); 2999 D->startDefinition(); 3000 3001 QualType FieldTypes[3]; 3002 3003 // const int *isa; 3004 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 3005 // const char *str; 3006 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 3007 // unsigned int length; 3008 FieldTypes[2] = Context.UnsignedIntTy; 3009 3010 // Create fields 3011 for (unsigned i = 0; i < 3; ++i) { 3012 FieldDecl *Field = FieldDecl::Create(Context, D, 3013 SourceLocation(), 3014 SourceLocation(), nullptr, 3015 FieldTypes[i], /*TInfo=*/nullptr, 3016 /*BitWidth=*/nullptr, 3017 /*Mutable=*/false, 3018 ICIS_NoInit); 3019 Field->setAccess(AS_public); 3020 D->addDecl(Field); 3021 } 3022 3023 D->completeDefinition(); 3024 QualType NSTy = Context.getTagDeclType(D); 3025 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 3026 } 3027 3028 llvm::Constant *Fields[3]; 3029 3030 // Class pointer. 3031 Fields[0] = cast<llvm::ConstantExpr>(V); 3032 3033 // String pointer. 3034 llvm::Constant *C = 3035 llvm::ConstantDataArray::getString(VMContext, Entry.first()); 3036 3037 llvm::GlobalValue::LinkageTypes Linkage; 3038 bool isConstant; 3039 Linkage = llvm::GlobalValue::PrivateLinkage; 3040 isConstant = !LangOpts.WritableStrings; 3041 3042 auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant, 3043 Linkage, C, ".str"); 3044 GV->setUnnamedAddr(true); 3045 // Don't enforce the target's minimum global alignment, since the only use 3046 // of the string is via this class initializer. 3047 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 3048 GV->setAlignment(Align.getQuantity()); 3049 Fields[1] = 3050 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 3051 3052 // String length. 3053 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 3054 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 3055 3056 // The struct. 3057 CharUnits Alignment = getPointerAlign(); 3058 C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 3059 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 3060 llvm::GlobalVariable::PrivateLinkage, C, 3061 "_unnamed_nsstring_"); 3062 GV->setAlignment(Alignment.getQuantity()); 3063 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip"; 3064 const char *NSStringNonFragileABISection = 3065 "__DATA,__objc_stringobj,regular,no_dead_strip"; 3066 // FIXME. Fix section. 3067 GV->setSection(LangOpts.ObjCRuntime.isNonFragile() 3068 ? NSStringNonFragileABISection 3069 : NSStringSection); 3070 Entry.second = GV; 3071 3072 return ConstantAddress(GV, Alignment); 3073 } 3074 3075 QualType CodeGenModule::getObjCFastEnumerationStateType() { 3076 if (ObjCFastEnumerationStateType.isNull()) { 3077 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 3078 D->startDefinition(); 3079 3080 QualType FieldTypes[] = { 3081 Context.UnsignedLongTy, 3082 Context.getPointerType(Context.getObjCIdType()), 3083 Context.getPointerType(Context.UnsignedLongTy), 3084 Context.getConstantArrayType(Context.UnsignedLongTy, 3085 llvm::APInt(32, 5), ArrayType::Normal, 0) 3086 }; 3087 3088 for (size_t i = 0; i < 4; ++i) { 3089 FieldDecl *Field = FieldDecl::Create(Context, 3090 D, 3091 SourceLocation(), 3092 SourceLocation(), nullptr, 3093 FieldTypes[i], /*TInfo=*/nullptr, 3094 /*BitWidth=*/nullptr, 3095 /*Mutable=*/false, 3096 ICIS_NoInit); 3097 Field->setAccess(AS_public); 3098 D->addDecl(Field); 3099 } 3100 3101 D->completeDefinition(); 3102 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 3103 } 3104 3105 return ObjCFastEnumerationStateType; 3106 } 3107 3108 llvm::Constant * 3109 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 3110 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 3111 3112 // Don't emit it as the address of the string, emit the string data itself 3113 // as an inline array. 3114 if (E->getCharByteWidth() == 1) { 3115 SmallString<64> Str(E->getString()); 3116 3117 // Resize the string to the right size, which is indicated by its type. 3118 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 3119 Str.resize(CAT->getSize().getZExtValue()); 3120 return llvm::ConstantDataArray::getString(VMContext, Str, false); 3121 } 3122 3123 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 3124 llvm::Type *ElemTy = AType->getElementType(); 3125 unsigned NumElements = AType->getNumElements(); 3126 3127 // Wide strings have either 2-byte or 4-byte elements. 3128 if (ElemTy->getPrimitiveSizeInBits() == 16) { 3129 SmallVector<uint16_t, 32> Elements; 3130 Elements.reserve(NumElements); 3131 3132 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3133 Elements.push_back(E->getCodeUnit(i)); 3134 Elements.resize(NumElements); 3135 return llvm::ConstantDataArray::get(VMContext, Elements); 3136 } 3137 3138 assert(ElemTy->getPrimitiveSizeInBits() == 32); 3139 SmallVector<uint32_t, 32> Elements; 3140 Elements.reserve(NumElements); 3141 3142 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3143 Elements.push_back(E->getCodeUnit(i)); 3144 Elements.resize(NumElements); 3145 return llvm::ConstantDataArray::get(VMContext, Elements); 3146 } 3147 3148 static llvm::GlobalVariable * 3149 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 3150 CodeGenModule &CGM, StringRef GlobalName, 3151 CharUnits Alignment) { 3152 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 3153 unsigned AddrSpace = 0; 3154 if (CGM.getLangOpts().OpenCL) 3155 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 3156 3157 llvm::Module &M = CGM.getModule(); 3158 // Create a global variable for this string 3159 auto *GV = new llvm::GlobalVariable( 3160 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 3161 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 3162 GV->setAlignment(Alignment.getQuantity()); 3163 GV->setUnnamedAddr(true); 3164 if (GV->isWeakForLinker()) { 3165 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 3166 GV->setComdat(M.getOrInsertComdat(GV->getName())); 3167 } 3168 3169 return GV; 3170 } 3171 3172 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 3173 /// constant array for the given string literal. 3174 ConstantAddress 3175 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 3176 StringRef Name) { 3177 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 3178 3179 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 3180 llvm::GlobalVariable **Entry = nullptr; 3181 if (!LangOpts.WritableStrings) { 3182 Entry = &ConstantStringMap[C]; 3183 if (auto GV = *Entry) { 3184 if (Alignment.getQuantity() > GV->getAlignment()) 3185 GV->setAlignment(Alignment.getQuantity()); 3186 return ConstantAddress(GV, Alignment); 3187 } 3188 } 3189 3190 SmallString<256> MangledNameBuffer; 3191 StringRef GlobalVariableName; 3192 llvm::GlobalValue::LinkageTypes LT; 3193 3194 // Mangle the string literal if the ABI allows for it. However, we cannot 3195 // do this if we are compiling with ASan or -fwritable-strings because they 3196 // rely on strings having normal linkage. 3197 if (!LangOpts.WritableStrings && 3198 !LangOpts.Sanitize.has(SanitizerKind::Address) && 3199 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 3200 llvm::raw_svector_ostream Out(MangledNameBuffer); 3201 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 3202 3203 LT = llvm::GlobalValue::LinkOnceODRLinkage; 3204 GlobalVariableName = MangledNameBuffer; 3205 } else { 3206 LT = llvm::GlobalValue::PrivateLinkage; 3207 GlobalVariableName = Name; 3208 } 3209 3210 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 3211 if (Entry) 3212 *Entry = GV; 3213 3214 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 3215 QualType()); 3216 return ConstantAddress(GV, Alignment); 3217 } 3218 3219 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 3220 /// array for the given ObjCEncodeExpr node. 3221 ConstantAddress 3222 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 3223 std::string Str; 3224 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 3225 3226 return GetAddrOfConstantCString(Str); 3227 } 3228 3229 /// GetAddrOfConstantCString - Returns a pointer to a character array containing 3230 /// the literal and a terminating '\0' character. 3231 /// The result has pointer to array type. 3232 ConstantAddress CodeGenModule::GetAddrOfConstantCString( 3233 const std::string &Str, const char *GlobalName) { 3234 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 3235 CharUnits Alignment = 3236 getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 3237 3238 llvm::Constant *C = 3239 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 3240 3241 // Don't share any string literals if strings aren't constant. 3242 llvm::GlobalVariable **Entry = nullptr; 3243 if (!LangOpts.WritableStrings) { 3244 Entry = &ConstantStringMap[C]; 3245 if (auto GV = *Entry) { 3246 if (Alignment.getQuantity() > GV->getAlignment()) 3247 GV->setAlignment(Alignment.getQuantity()); 3248 return ConstantAddress(GV, Alignment); 3249 } 3250 } 3251 3252 // Get the default prefix if a name wasn't specified. 3253 if (!GlobalName) 3254 GlobalName = ".str"; 3255 // Create a global variable for this. 3256 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 3257 GlobalName, Alignment); 3258 if (Entry) 3259 *Entry = GV; 3260 return ConstantAddress(GV, Alignment); 3261 } 3262 3263 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 3264 const MaterializeTemporaryExpr *E, const Expr *Init) { 3265 assert((E->getStorageDuration() == SD_Static || 3266 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 3267 const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 3268 3269 // If we're not materializing a subobject of the temporary, keep the 3270 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 3271 QualType MaterializedType = Init->getType(); 3272 if (Init == E->GetTemporaryExpr()) 3273 MaterializedType = E->getType(); 3274 3275 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 3276 3277 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) 3278 return ConstantAddress(Slot, Align); 3279 3280 // FIXME: If an externally-visible declaration extends multiple temporaries, 3281 // we need to give each temporary the same name in every translation unit (and 3282 // we also need to make the temporaries externally-visible). 3283 SmallString<256> Name; 3284 llvm::raw_svector_ostream Out(Name); 3285 getCXXABI().getMangleContext().mangleReferenceTemporary( 3286 VD, E->getManglingNumber(), Out); 3287 3288 APValue *Value = nullptr; 3289 if (E->getStorageDuration() == SD_Static) { 3290 // We might have a cached constant initializer for this temporary. Note 3291 // that this might have a different value from the value computed by 3292 // evaluating the initializer if the surrounding constant expression 3293 // modifies the temporary. 3294 Value = getContext().getMaterializedTemporaryValue(E, false); 3295 if (Value && Value->isUninit()) 3296 Value = nullptr; 3297 } 3298 3299 // Try evaluating it now, it might have a constant initializer. 3300 Expr::EvalResult EvalResult; 3301 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 3302 !EvalResult.hasSideEffects()) 3303 Value = &EvalResult.Val; 3304 3305 llvm::Constant *InitialValue = nullptr; 3306 bool Constant = false; 3307 llvm::Type *Type; 3308 if (Value) { 3309 // The temporary has a constant initializer, use it. 3310 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr); 3311 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 3312 Type = InitialValue->getType(); 3313 } else { 3314 // No initializer, the initialization will be provided when we 3315 // initialize the declaration which performed lifetime extension. 3316 Type = getTypes().ConvertTypeForMem(MaterializedType); 3317 } 3318 3319 // Create a global variable for this lifetime-extended temporary. 3320 llvm::GlobalValue::LinkageTypes Linkage = 3321 getLLVMLinkageVarDefinition(VD, Constant); 3322 if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 3323 const VarDecl *InitVD; 3324 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 3325 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 3326 // Temporaries defined inside a class get linkonce_odr linkage because the 3327 // class can be defined in multipe translation units. 3328 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 3329 } else { 3330 // There is no need for this temporary to have external linkage if the 3331 // VarDecl has external linkage. 3332 Linkage = llvm::GlobalVariable::InternalLinkage; 3333 } 3334 } 3335 unsigned AddrSpace = GetGlobalVarAddressSpace( 3336 VD, getContext().getTargetAddressSpace(MaterializedType)); 3337 auto *GV = new llvm::GlobalVariable( 3338 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 3339 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, 3340 AddrSpace); 3341 setGlobalVisibility(GV, VD); 3342 GV->setAlignment(Align.getQuantity()); 3343 if (supportsCOMDAT() && GV->isWeakForLinker()) 3344 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3345 if (VD->getTLSKind()) 3346 setTLSMode(GV, *VD); 3347 MaterializedGlobalTemporaryMap[E] = GV; 3348 return ConstantAddress(GV, Align); 3349 } 3350 3351 /// EmitObjCPropertyImplementations - Emit information for synthesized 3352 /// properties for an implementation. 3353 void CodeGenModule::EmitObjCPropertyImplementations(const 3354 ObjCImplementationDecl *D) { 3355 for (const auto *PID : D->property_impls()) { 3356 // Dynamic is just for type-checking. 3357 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 3358 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 3359 3360 // Determine which methods need to be implemented, some may have 3361 // been overridden. Note that ::isPropertyAccessor is not the method 3362 // we want, that just indicates if the decl came from a 3363 // property. What we want to know is if the method is defined in 3364 // this implementation. 3365 if (!D->getInstanceMethod(PD->getGetterName())) 3366 CodeGenFunction(*this).GenerateObjCGetter( 3367 const_cast<ObjCImplementationDecl *>(D), PID); 3368 if (!PD->isReadOnly() && 3369 !D->getInstanceMethod(PD->getSetterName())) 3370 CodeGenFunction(*this).GenerateObjCSetter( 3371 const_cast<ObjCImplementationDecl *>(D), PID); 3372 } 3373 } 3374 } 3375 3376 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 3377 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 3378 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 3379 ivar; ivar = ivar->getNextIvar()) 3380 if (ivar->getType().isDestructedType()) 3381 return true; 3382 3383 return false; 3384 } 3385 3386 static bool AllTrivialInitializers(CodeGenModule &CGM, 3387 ObjCImplementationDecl *D) { 3388 CodeGenFunction CGF(CGM); 3389 for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 3390 E = D->init_end(); B != E; ++B) { 3391 CXXCtorInitializer *CtorInitExp = *B; 3392 Expr *Init = CtorInitExp->getInit(); 3393 if (!CGF.isTrivialInitializer(Init)) 3394 return false; 3395 } 3396 return true; 3397 } 3398 3399 /// EmitObjCIvarInitializations - Emit information for ivar initialization 3400 /// for an implementation. 3401 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 3402 // We might need a .cxx_destruct even if we don't have any ivar initializers. 3403 if (needsDestructMethod(D)) { 3404 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 3405 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 3406 ObjCMethodDecl *DTORMethod = 3407 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 3408 cxxSelector, getContext().VoidTy, nullptr, D, 3409 /*isInstance=*/true, /*isVariadic=*/false, 3410 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 3411 /*isDefined=*/false, ObjCMethodDecl::Required); 3412 D->addInstanceMethod(DTORMethod); 3413 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 3414 D->setHasDestructors(true); 3415 } 3416 3417 // If the implementation doesn't have any ivar initializers, we don't need 3418 // a .cxx_construct. 3419 if (D->getNumIvarInitializers() == 0 || 3420 AllTrivialInitializers(*this, D)) 3421 return; 3422 3423 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 3424 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 3425 // The constructor returns 'self'. 3426 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 3427 D->getLocation(), 3428 D->getLocation(), 3429 cxxSelector, 3430 getContext().getObjCIdType(), 3431 nullptr, D, /*isInstance=*/true, 3432 /*isVariadic=*/false, 3433 /*isPropertyAccessor=*/true, 3434 /*isImplicitlyDeclared=*/true, 3435 /*isDefined=*/false, 3436 ObjCMethodDecl::Required); 3437 D->addInstanceMethod(CTORMethod); 3438 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 3439 D->setHasNonZeroConstructors(true); 3440 } 3441 3442 /// EmitNamespace - Emit all declarations in a namespace. 3443 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 3444 for (auto *I : ND->decls()) { 3445 if (const auto *VD = dyn_cast<VarDecl>(I)) 3446 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 3447 VD->getTemplateSpecializationKind() != TSK_Undeclared) 3448 continue; 3449 EmitTopLevelDecl(I); 3450 } 3451 } 3452 3453 // EmitLinkageSpec - Emit all declarations in a linkage spec. 3454 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 3455 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 3456 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 3457 ErrorUnsupported(LSD, "linkage spec"); 3458 return; 3459 } 3460 3461 for (auto *I : LSD->decls()) { 3462 // Meta-data for ObjC class includes references to implemented methods. 3463 // Generate class's method definitions first. 3464 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 3465 for (auto *M : OID->methods()) 3466 EmitTopLevelDecl(M); 3467 } 3468 EmitTopLevelDecl(I); 3469 } 3470 } 3471 3472 /// EmitTopLevelDecl - Emit code for a single top level declaration. 3473 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 3474 // Ignore dependent declarations. 3475 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 3476 return; 3477 3478 switch (D->getKind()) { 3479 case Decl::CXXConversion: 3480 case Decl::CXXMethod: 3481 case Decl::Function: 3482 // Skip function templates 3483 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 3484 cast<FunctionDecl>(D)->isLateTemplateParsed()) 3485 return; 3486 3487 EmitGlobal(cast<FunctionDecl>(D)); 3488 // Always provide some coverage mapping 3489 // even for the functions that aren't emitted. 3490 AddDeferredUnusedCoverageMapping(D); 3491 break; 3492 3493 case Decl::Var: 3494 // Skip variable templates 3495 if (cast<VarDecl>(D)->getDescribedVarTemplate()) 3496 return; 3497 case Decl::VarTemplateSpecialization: 3498 EmitGlobal(cast<VarDecl>(D)); 3499 break; 3500 3501 // Indirect fields from global anonymous structs and unions can be 3502 // ignored; only the actual variable requires IR gen support. 3503 case Decl::IndirectField: 3504 break; 3505 3506 // C++ Decls 3507 case Decl::Namespace: 3508 EmitNamespace(cast<NamespaceDecl>(D)); 3509 break; 3510 // No code generation needed. 3511 case Decl::UsingShadow: 3512 case Decl::ClassTemplate: 3513 case Decl::VarTemplate: 3514 case Decl::VarTemplatePartialSpecialization: 3515 case Decl::FunctionTemplate: 3516 case Decl::TypeAliasTemplate: 3517 case Decl::Block: 3518 case Decl::Empty: 3519 break; 3520 case Decl::Using: // using X; [C++] 3521 if (CGDebugInfo *DI = getModuleDebugInfo()) 3522 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 3523 return; 3524 case Decl::NamespaceAlias: 3525 if (CGDebugInfo *DI = getModuleDebugInfo()) 3526 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 3527 return; 3528 case Decl::UsingDirective: // using namespace X; [C++] 3529 if (CGDebugInfo *DI = getModuleDebugInfo()) 3530 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 3531 return; 3532 case Decl::CXXConstructor: 3533 // Skip function templates 3534 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 3535 cast<FunctionDecl>(D)->isLateTemplateParsed()) 3536 return; 3537 3538 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 3539 break; 3540 case Decl::CXXDestructor: 3541 if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 3542 return; 3543 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 3544 break; 3545 3546 case Decl::StaticAssert: 3547 // Nothing to do. 3548 break; 3549 3550 // Objective-C Decls 3551 3552 // Forward declarations, no (immediate) code generation. 3553 case Decl::ObjCInterface: 3554 case Decl::ObjCCategory: 3555 break; 3556 3557 case Decl::ObjCProtocol: { 3558 auto *Proto = cast<ObjCProtocolDecl>(D); 3559 if (Proto->isThisDeclarationADefinition()) 3560 ObjCRuntime->GenerateProtocol(Proto); 3561 break; 3562 } 3563 3564 case Decl::ObjCCategoryImpl: 3565 // Categories have properties but don't support synthesize so we 3566 // can ignore them here. 3567 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 3568 break; 3569 3570 case Decl::ObjCImplementation: { 3571 auto *OMD = cast<ObjCImplementationDecl>(D); 3572 EmitObjCPropertyImplementations(OMD); 3573 EmitObjCIvarInitializations(OMD); 3574 ObjCRuntime->GenerateClass(OMD); 3575 // Emit global variable debug information. 3576 if (CGDebugInfo *DI = getModuleDebugInfo()) 3577 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 3578 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 3579 OMD->getClassInterface()), OMD->getLocation()); 3580 break; 3581 } 3582 case Decl::ObjCMethod: { 3583 auto *OMD = cast<ObjCMethodDecl>(D); 3584 // If this is not a prototype, emit the body. 3585 if (OMD->getBody()) 3586 CodeGenFunction(*this).GenerateObjCMethod(OMD); 3587 break; 3588 } 3589 case Decl::ObjCCompatibleAlias: 3590 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 3591 break; 3592 3593 case Decl::LinkageSpec: 3594 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 3595 break; 3596 3597 case Decl::FileScopeAsm: { 3598 // File-scope asm is ignored during device-side CUDA compilation. 3599 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 3600 break; 3601 auto *AD = cast<FileScopeAsmDecl>(D); 3602 getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 3603 break; 3604 } 3605 3606 case Decl::Import: { 3607 auto *Import = cast<ImportDecl>(D); 3608 3609 // Ignore import declarations that come from imported modules. 3610 if (Import->getImportedOwningModule()) 3611 break; 3612 if (CGDebugInfo *DI = getModuleDebugInfo()) 3613 DI->EmitImportDecl(*Import); 3614 3615 ImportedModules.insert(Import->getImportedModule()); 3616 break; 3617 } 3618 3619 case Decl::OMPThreadPrivate: 3620 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 3621 break; 3622 3623 case Decl::ClassTemplateSpecialization: { 3624 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 3625 if (DebugInfo && 3626 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition && 3627 Spec->hasDefinition()) 3628 DebugInfo->completeTemplateDefinition(*Spec); 3629 break; 3630 } 3631 3632 default: 3633 // Make sure we handled everything we should, every other kind is a 3634 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 3635 // function. Need to recode Decl::Kind to do that easily. 3636 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 3637 break; 3638 } 3639 } 3640 3641 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 3642 // Do we need to generate coverage mapping? 3643 if (!CodeGenOpts.CoverageMapping) 3644 return; 3645 switch (D->getKind()) { 3646 case Decl::CXXConversion: 3647 case Decl::CXXMethod: 3648 case Decl::Function: 3649 case Decl::ObjCMethod: 3650 case Decl::CXXConstructor: 3651 case Decl::CXXDestructor: { 3652 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 3653 return; 3654 auto I = DeferredEmptyCoverageMappingDecls.find(D); 3655 if (I == DeferredEmptyCoverageMappingDecls.end()) 3656 DeferredEmptyCoverageMappingDecls[D] = true; 3657 break; 3658 } 3659 default: 3660 break; 3661 }; 3662 } 3663 3664 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 3665 // Do we need to generate coverage mapping? 3666 if (!CodeGenOpts.CoverageMapping) 3667 return; 3668 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 3669 if (Fn->isTemplateInstantiation()) 3670 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 3671 } 3672 auto I = DeferredEmptyCoverageMappingDecls.find(D); 3673 if (I == DeferredEmptyCoverageMappingDecls.end()) 3674 DeferredEmptyCoverageMappingDecls[D] = false; 3675 else 3676 I->second = false; 3677 } 3678 3679 void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 3680 std::vector<const Decl *> DeferredDecls; 3681 for (const auto &I : DeferredEmptyCoverageMappingDecls) { 3682 if (!I.second) 3683 continue; 3684 DeferredDecls.push_back(I.first); 3685 } 3686 // Sort the declarations by their location to make sure that the tests get a 3687 // predictable order for the coverage mapping for the unused declarations. 3688 if (CodeGenOpts.DumpCoverageMapping) 3689 std::sort(DeferredDecls.begin(), DeferredDecls.end(), 3690 [] (const Decl *LHS, const Decl *RHS) { 3691 return LHS->getLocStart() < RHS->getLocStart(); 3692 }); 3693 for (const auto *D : DeferredDecls) { 3694 switch (D->getKind()) { 3695 case Decl::CXXConversion: 3696 case Decl::CXXMethod: 3697 case Decl::Function: 3698 case Decl::ObjCMethod: { 3699 CodeGenPGO PGO(*this); 3700 GlobalDecl GD(cast<FunctionDecl>(D)); 3701 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 3702 getFunctionLinkage(GD)); 3703 break; 3704 } 3705 case Decl::CXXConstructor: { 3706 CodeGenPGO PGO(*this); 3707 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 3708 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 3709 getFunctionLinkage(GD)); 3710 break; 3711 } 3712 case Decl::CXXDestructor: { 3713 CodeGenPGO PGO(*this); 3714 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 3715 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 3716 getFunctionLinkage(GD)); 3717 break; 3718 } 3719 default: 3720 break; 3721 }; 3722 } 3723 } 3724 3725 /// Turns the given pointer into a constant. 3726 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 3727 const void *Ptr) { 3728 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 3729 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 3730 return llvm::ConstantInt::get(i64, PtrInt); 3731 } 3732 3733 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 3734 llvm::NamedMDNode *&GlobalMetadata, 3735 GlobalDecl D, 3736 llvm::GlobalValue *Addr) { 3737 if (!GlobalMetadata) 3738 GlobalMetadata = 3739 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 3740 3741 // TODO: should we report variant information for ctors/dtors? 3742 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 3743 llvm::ConstantAsMetadata::get(GetPointerConstant( 3744 CGM.getLLVMContext(), D.getDecl()))}; 3745 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 3746 } 3747 3748 /// For each function which is declared within an extern "C" region and marked 3749 /// as 'used', but has internal linkage, create an alias from the unmangled 3750 /// name to the mangled name if possible. People expect to be able to refer 3751 /// to such functions with an unmangled name from inline assembly within the 3752 /// same translation unit. 3753 void CodeGenModule::EmitStaticExternCAliases() { 3754 for (auto &I : StaticExternCValues) { 3755 IdentifierInfo *Name = I.first; 3756 llvm::GlobalValue *Val = I.second; 3757 if (Val && !getModule().getNamedValue(Name->getName())) 3758 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 3759 } 3760 } 3761 3762 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 3763 GlobalDecl &Result) const { 3764 auto Res = Manglings.find(MangledName); 3765 if (Res == Manglings.end()) 3766 return false; 3767 Result = Res->getValue(); 3768 return true; 3769 } 3770 3771 /// Emits metadata nodes associating all the global values in the 3772 /// current module with the Decls they came from. This is useful for 3773 /// projects using IR gen as a subroutine. 3774 /// 3775 /// Since there's currently no way to associate an MDNode directly 3776 /// with an llvm::GlobalValue, we create a global named metadata 3777 /// with the name 'clang.global.decl.ptrs'. 3778 void CodeGenModule::EmitDeclMetadata() { 3779 llvm::NamedMDNode *GlobalMetadata = nullptr; 3780 3781 // StaticLocalDeclMap 3782 for (auto &I : MangledDeclNames) { 3783 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 3784 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 3785 } 3786 } 3787 3788 /// Emits metadata nodes for all the local variables in the current 3789 /// function. 3790 void CodeGenFunction::EmitDeclMetadata() { 3791 if (LocalDeclMap.empty()) return; 3792 3793 llvm::LLVMContext &Context = getLLVMContext(); 3794 3795 // Find the unique metadata ID for this name. 3796 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 3797 3798 llvm::NamedMDNode *GlobalMetadata = nullptr; 3799 3800 for (auto &I : LocalDeclMap) { 3801 const Decl *D = I.first; 3802 llvm::Value *Addr = I.second.getPointer(); 3803 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 3804 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 3805 Alloca->setMetadata( 3806 DeclPtrKind, llvm::MDNode::get( 3807 Context, llvm::ValueAsMetadata::getConstant(DAddr))); 3808 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 3809 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 3810 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 3811 } 3812 } 3813 } 3814 3815 void CodeGenModule::EmitVersionIdentMetadata() { 3816 llvm::NamedMDNode *IdentMetadata = 3817 TheModule.getOrInsertNamedMetadata("llvm.ident"); 3818 std::string Version = getClangFullVersion(); 3819 llvm::LLVMContext &Ctx = TheModule.getContext(); 3820 3821 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 3822 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 3823 } 3824 3825 void CodeGenModule::EmitTargetMetadata() { 3826 // Warning, new MangledDeclNames may be appended within this loop. 3827 // We rely on MapVector insertions adding new elements to the end 3828 // of the container. 3829 // FIXME: Move this loop into the one target that needs it, and only 3830 // loop over those declarations for which we couldn't emit the target 3831 // metadata when we emitted the declaration. 3832 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 3833 auto Val = *(MangledDeclNames.begin() + I); 3834 const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 3835 llvm::GlobalValue *GV = GetGlobalValue(Val.second); 3836 getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 3837 } 3838 } 3839 3840 void CodeGenModule::EmitCoverageFile() { 3841 if (!getCodeGenOpts().CoverageFile.empty()) { 3842 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 3843 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 3844 llvm::LLVMContext &Ctx = TheModule.getContext(); 3845 llvm::MDString *CoverageFile = 3846 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 3847 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 3848 llvm::MDNode *CU = CUNode->getOperand(i); 3849 llvm::Metadata *Elts[] = {CoverageFile, CU}; 3850 GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 3851 } 3852 } 3853 } 3854 } 3855 3856 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 3857 // Sema has checked that all uuid strings are of the form 3858 // "12345678-1234-1234-1234-1234567890ab". 3859 assert(Uuid.size() == 36); 3860 for (unsigned i = 0; i < 36; ++i) { 3861 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 3862 else assert(isHexDigit(Uuid[i])); 3863 } 3864 3865 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 3866 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 3867 3868 llvm::Constant *Field3[8]; 3869 for (unsigned Idx = 0; Idx < 8; ++Idx) 3870 Field3[Idx] = llvm::ConstantInt::get( 3871 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 3872 3873 llvm::Constant *Fields[4] = { 3874 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 3875 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 3876 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 3877 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 3878 }; 3879 3880 return llvm::ConstantStruct::getAnon(Fields); 3881 } 3882 3883 llvm::Constant * 3884 CodeGenModule::getAddrOfCXXCatchHandlerType(QualType Ty, 3885 QualType CatchHandlerType) { 3886 return getCXXABI().getAddrOfCXXCatchHandlerType(Ty, CatchHandlerType); 3887 } 3888 3889 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 3890 bool ForEH) { 3891 // Return a bogus pointer if RTTI is disabled, unless it's for EH. 3892 // FIXME: should we even be calling this method if RTTI is disabled 3893 // and it's not for EH? 3894 if (!ForEH && !getLangOpts().RTTI) 3895 return llvm::Constant::getNullValue(Int8PtrTy); 3896 3897 if (ForEH && Ty->isObjCObjectPointerType() && 3898 LangOpts.ObjCRuntime.isGNUFamily()) 3899 return ObjCRuntime->GetEHType(Ty); 3900 3901 return getCXXABI().getAddrOfRTTIDescriptor(Ty); 3902 } 3903 3904 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 3905 for (auto RefExpr : D->varlists()) { 3906 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 3907 bool PerformInit = 3908 VD->getAnyInitializer() && 3909 !VD->getAnyInitializer()->isConstantInitializer(getContext(), 3910 /*ForRef=*/false); 3911 3912 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 3913 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 3914 VD, Addr, RefExpr->getLocStart(), PerformInit)) 3915 CXXGlobalInits.push_back(InitFunction); 3916 } 3917 } 3918 3919 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 3920 llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()]; 3921 if (InternalId) 3922 return InternalId; 3923 3924 if (isExternallyVisible(T->getLinkage())) { 3925 std::string OutName; 3926 llvm::raw_string_ostream Out(OutName); 3927 getCXXABI().getMangleContext().mangleTypeName(T, Out); 3928 3929 InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 3930 } else { 3931 InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 3932 llvm::ArrayRef<llvm::Metadata *>()); 3933 } 3934 3935 return InternalId; 3936 } 3937 3938 llvm::MDTuple *CodeGenModule::CreateVTableBitSetEntry( 3939 llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD) { 3940 llvm::Metadata *BitsetOps[] = { 3941 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)), 3942 llvm::ConstantAsMetadata::get(VTable), 3943 llvm::ConstantAsMetadata::get( 3944 llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))}; 3945 return llvm::MDTuple::get(getLLVMContext(), BitsetOps); 3946 } 3947