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