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