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