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