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