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