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