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