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