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