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