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