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