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