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