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