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