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