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