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