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