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