blob: 0161cfb611ca0b44fa022e29637a0eefcb231957 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080015#include "CGBlocks.h"
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000016#include "CGCUDARuntime.h"
John McCall4c40d982010-08-31 07:33:07 +000017#include "CGCXXABI.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "CGCall.h"
19#include "CGDebugInfo.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000020#include "CGObjCRuntime.h"
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000021#include "CGOpenCLRuntime.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070022#include "CGOpenMPRuntime.h"
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070023#include "CGOpenMPRuntimeNVPTX.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "CodeGenFunction.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070025#include "CodeGenPGO.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "CodeGenTBAA.h"
Stephen Hines0e2c34f2015-03-23 12:09:02 -070027#include "CoverageMappingGen.h"
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000028#include "TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include "clang/AST/ASTContext.h"
Ken Dyck687cc4a2010-01-26 13:48:07 +000030#include "clang/AST/CharUnits.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000031#include "clang/AST/DeclCXX.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/AST/DeclObjC.h"
Douglas Gregoraf896892010-06-21 18:41:26 +000033#include "clang/AST/DeclTemplate.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000034#include "clang/AST/Mangle.h"
Anders Carlsson1a5e0d72009-11-30 23:41:22 +000035#include "clang/AST/RecordLayout.h"
Rafael Espindolaa411d2f2011-10-26 20:41:06 +000036#include "clang/AST/RecursiveASTVisitor.h"
Rafael Espindolabcf6b982011-12-19 14:41:01 +000037#include "clang/Basic/Builtins.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000038#include "clang/Basic/CharInfo.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000039#include "clang/Basic/Diagnostic.h"
Douglas Gregorb6cbe512013-01-14 17:21:00 +000040#include "clang/Basic/Module.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000041#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000042#include "clang/Basic/TargetInfo.h"
Rafael Espindola9686f122013-10-16 19:28:50 +000043#include "clang/Basic/Version.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000044#include "clang/Frontend/CodeGenOptions.h"
Rafael Espindolad2054982013-10-22 19:26:13 +000045#include "clang/Sema/SemaDiagnostic.h"
Sebastian Redl19b1a6e2012-02-25 20:51:20 +000046#include "llvm/ADT/APSInt.h"
John McCall6374c332010-03-06 00:35:14 +000047#include "llvm/ADT/Triple.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070048#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000049#include "llvm/IR/CallingConv.h"
50#include "llvm/IR/DataLayout.h"
51#include "llvm/IR/Intrinsics.h"
52#include "llvm/IR/LLVMContext.h"
53#include "llvm/IR/Module.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070054#include "llvm/ProfileData/InstrProfReader.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000055#include "llvm/Support/ConvertUTF.h"
Chris Lattner78f7ece2009-11-07 09:22:46 +000056#include "llvm/Support/ErrorHandling.h"
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080057#include "llvm/Support/MD5.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000058
Reid Spencer5f016e22007-07-11 17:01:13 +000059using namespace clang;
60using namespace CodeGen;
61
Julien Lerouge77f68bb2011-09-09 22:41:49 +000062static const char AnnotationSection[] = "llvm.metadata";
63
Stephen Hines651f13c2014-04-23 16:59:28 -070064static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
John McCall64aa4b32013-04-16 22:48:15 +000065 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +000066 case TargetCXXABI::GenericAArch64:
John McCall96fcde02013-01-25 23:36:14 +000067 case TargetCXXABI::GenericARM:
68 case TargetCXXABI::iOS:
Stephen Hines651f13c2014-04-23 16:59:28 -070069 case TargetCXXABI::iOS64:
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080070 case TargetCXXABI::WatchOS:
Stephen Hines0e2c34f2015-03-23 12:09:02 -070071 case TargetCXXABI::GenericMIPS:
John McCall96fcde02013-01-25 23:36:14 +000072 case TargetCXXABI::GenericItanium:
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080073 case TargetCXXABI::WebAssembly:
Stephen Hines651f13c2014-04-23 16:59:28 -070074 return CreateItaniumCXXABI(CGM);
John McCall96fcde02013-01-25 23:36:14 +000075 case TargetCXXABI::Microsoft:
Stephen Hines651f13c2014-04-23 16:59:28 -070076 return CreateMicrosoftCXXABI(CGM);
John McCallf16aa102010-08-22 21:01:12 +000077 }
78
79 llvm_unreachable("invalid C++ ABI kind");
John McCallf16aa102010-08-22 21:01:12 +000080}
81
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080082CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
83 const PreprocessorOptions &PPO,
84 const CodeGenOptions &CGO, llvm::Module &M,
Stephen Hines176edba2014-12-01 14:53:08 -080085 DiagnosticsEngine &diags,
86 CoverageSourceInfo *CoverageInfo)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080087 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
88 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
89 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070090 VMContext(M.getContext()), Types(*this), VTables(*this),
91 SanitizerMD(new SanitizerMetadata(*this)) {
Will Dietz4f45bc02013-01-18 11:30:38 +000092
Chris Lattner8b418682012-02-07 00:39:47 +000093 // Initialize the type cache.
94 llvm::LLVMContext &LLVMContext = M.getContext();
95 VoidTy = llvm::Type::getVoidTy(LLVMContext);
96 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
97 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
98 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
99 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
100 FloatTy = llvm::Type::getFloatTy(LLVMContext);
101 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
102 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
103 PointerAlignInBytes =
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800104 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
105 IntAlignInBytes =
106 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
Chris Lattner8b418682012-02-07 00:39:47 +0000107 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
108 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
109 Int8PtrTy = Int8Ty->getPointerTo(0);
110 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
111
John McCallbd7370a2013-02-28 19:01:20 +0000112 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700113 BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
John McCallbd7370a2013-02-28 19:01:20 +0000114
David Blaikie4e4d0842012-03-11 07:00:24 +0000115 if (LangOpts.ObjC1)
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000116 createObjCRuntime();
David Blaikie4e4d0842012-03-11 07:00:24 +0000117 if (LangOpts.OpenCL)
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000118 createOpenCLRuntime();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700119 if (LangOpts.OpenMP)
120 createOpenMPRuntime();
David Blaikie4e4d0842012-03-11 07:00:24 +0000121 if (LangOpts.CUDA)
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000122 createCUDARuntime();
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000123
Kostya Serebryanyc9fe6052012-04-24 06:57:01 +0000124 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Stephen Hines176edba2014-12-01 14:53:08 -0800125 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
Kostya Serebryanyc9fe6052012-04-24 06:57:01 +0000126 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700127 TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
128 getCXXABI().getMangleContext()));
Dan Gohman3d5aff52010-10-14 23:06:10 +0000129
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000130 // If debug info or coverage generation is enabled, create the CGDebugInfo
131 // object.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700132 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
133 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
134 DebugInfo.reset(new CGDebugInfo(*this));
John McCalld16c2cf2011-02-08 08:22:06 +0000135
136 Block.GlobalUniqueCount = 0;
John McCall5936e332011-02-15 09:22:45 +0000137
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800138 if (C.getLangOpts().ObjC1)
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700139 ObjCData.reset(new ObjCEntrypoints());
Stephen Hines651f13c2014-04-23 16:59:28 -0700140
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700141 if (CodeGenOpts.hasProfileClangUse()) {
142 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
143 CodeGenOpts.ProfileInstrumentUsePath);
144 if (auto E = ReaderOrErr.takeError()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700145 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800146 "Could not read profile %0: %1");
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700147 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
148 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
149 << EI.message();
150 });
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700151 } else
152 PGOReader = std::move(ReaderOrErr.get());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700153 }
Stephen Hines176edba2014-12-01 14:53:08 -0800154
155 // If coverage mapping generation is enabled, create the
156 // CoverageMappingModuleGen object.
157 if (CodeGenOpts.CoverageMapping)
158 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
Chris Lattner2b94fe32008-03-01 08:45:05 +0000159}
160
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700161CodeGenModule::~CodeGenModule() {}
Ted Kremenek815c78f2008-08-05 18:50:11 +0000162
David Chisnall0d13f6f2010-01-23 02:40:42 +0000163void CodeGenModule::createObjCRuntime() {
John McCall260611a2012-06-20 06:18:46 +0000164 // This is just isGNUFamily(), but we want to force implementors of
165 // new ABIs to decide how best to do this.
166 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnall11d3f4c2012-07-03 20:49:52 +0000167 case ObjCRuntime::GNUstep:
168 case ObjCRuntime::GCC:
John McCallf7226fb2012-07-12 02:07:58 +0000169 case ObjCRuntime::ObjFW:
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700170 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
John McCall260611a2012-06-20 06:18:46 +0000171 return;
172
173 case ObjCRuntime::FragileMacOSX:
174 case ObjCRuntime::MacOSX:
175 case ObjCRuntime::iOS:
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800176 case ObjCRuntime::WatchOS:
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700177 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
John McCall260611a2012-06-20 06:18:46 +0000178 return;
179 }
180 llvm_unreachable("bad runtime kind");
David Chisnall0d13f6f2010-01-23 02:40:42 +0000181}
182
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000183void CodeGenModule::createOpenCLRuntime() {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700184 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000185}
186
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700187void CodeGenModule::createOpenMPRuntime() {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700188 // Select a specialized code generation class based on the target, if any.
189 // If it does not exist use the default implementation.
190 switch (getTarget().getTriple().getArch()) {
191
192 case llvm::Triple::nvptx:
193 case llvm::Triple::nvptx64:
194 assert(getLangOpts().OpenMPIsDevice &&
195 "OpenMP NVPTX is only prepared to deal with device code.");
196 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
197 break;
198 default:
199 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
200 break;
201 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700202}
203
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000204void CodeGenModule::createCUDARuntime() {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700205 CUDARuntime.reset(CreateNVCUDARuntime(*this));
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000206}
207
Stephen Hines176edba2014-12-01 14:53:08 -0800208void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
209 Replacements[Name] = C;
210}
211
Rafael Espindola61a0a752013-11-05 21:37:29 +0000212void CodeGenModule::applyReplacements() {
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700213 for (auto &I : Replacements) {
214 StringRef MangledName = I.first();
215 llvm::Constant *Replacement = I.second;
Rafael Espindola61a0a752013-11-05 21:37:29 +0000216 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
217 if (!Entry)
218 continue;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700219 auto *OldF = cast<llvm::Function>(Entry);
220 auto *NewF = dyn_cast<llvm::Function>(Replacement);
Rafael Espindola081c2152013-11-12 04:53:19 +0000221 if (!NewF) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700222 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
223 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
Stephen Hines651f13c2014-04-23 16:59:28 -0700224 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700225 auto *CE = cast<llvm::ConstantExpr>(Replacement);
Stephen Hines651f13c2014-04-23 16:59:28 -0700226 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
227 CE->getOpcode() == llvm::Instruction::GetElementPtr);
228 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
229 }
Rafael Espindola081c2152013-11-12 04:53:19 +0000230 }
231
232 // Replace old with new, but keep the old order.
233 OldF->replaceAllUsesWith(Replacement);
234 if (NewF) {
235 NewF->removeFromParent();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800236 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
237 NewF);
Rafael Espindola081c2152013-11-12 04:53:19 +0000238 }
239 OldF->eraseFromParent();
Rafael Espindola61a0a752013-11-05 21:37:29 +0000240 }
241}
242
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800243void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
244 GlobalValReplacements.push_back(std::make_pair(GV, C));
245}
246
247void CodeGenModule::applyGlobalValReplacements() {
248 for (auto &I : GlobalValReplacements) {
249 llvm::GlobalValue *GV = I.first;
250 llvm::Constant *C = I.second;
251
252 GV->replaceAllUsesWith(C);
253 GV->eraseFromParent();
254 }
255}
256
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700257// This is only used in aliases that we created and we know they have a
258// linear structure.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700259static const llvm::GlobalObject *getAliasedGlobal(
260 const llvm::GlobalIndirectSymbol &GIS) {
261 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
262 const llvm::Constant *C = &GIS;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700263 for (;;) {
264 C = C->stripPointerCasts();
265 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
266 return GO;
267 // stripPointerCasts will not walk over weak aliases.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700268 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
269 if (!GIS2)
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700270 return nullptr;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700271 if (!Visited.insert(GIS2).second)
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700272 return nullptr;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700273 C = GIS2->getIndirectSymbol();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700274 }
275}
276
Rafael Espindolad2054982013-10-22 19:26:13 +0000277void CodeGenModule::checkAliases() {
Stephen Hines651f13c2014-04-23 16:59:28 -0700278 // Check if the constructed aliases are well formed. It is really unfortunate
279 // that we have to do this in CodeGen, but we only construct mangled names
280 // and aliases during codegen.
Rafael Espindolad2054982013-10-22 19:26:13 +0000281 bool Error = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700282 DiagnosticsEngine &Diags = getDiags();
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700283 for (const GlobalDecl &GD : Aliases) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700284 const auto *D = cast<ValueDecl>(GD.getDecl());
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700285 SourceLocation Location;
286 bool IsIFunc = D->hasAttr<IFuncAttr>();
287 if (const Attr *A = D->getDefiningAttr())
288 Location = A->getLocation();
289 else
290 llvm_unreachable("Not an alias or ifunc?");
Rafael Espindolad2054982013-10-22 19:26:13 +0000291 StringRef MangledName = getMangledName(GD);
292 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700293 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700294 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
295 if (!GV) {
296 Error = true;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700297 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700298 } else if (GV->isDeclaration()) {
Rafael Espindolad2054982013-10-22 19:26:13 +0000299 Error = true;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700300 Diags.Report(Location, diag::err_alias_to_undefined)
301 << IsIFunc << IsIFunc;
302 } else if (IsIFunc) {
303 // Check resolver function type.
304 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
305 GV->getType()->getPointerElementType());
306 assert(FTy);
307 if (!FTy->getReturnType()->isPointerTy())
308 Diags.Report(Location, diag::err_ifunc_resolver_return);
309 if (FTy->getNumParams())
310 Diags.Report(Location, diag::err_ifunc_resolver_params);
Stephen Hines651f13c2014-04-23 16:59:28 -0700311 }
312
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700313 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700314 llvm::GlobalValue *AliaseeGV;
315 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
316 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
317 else
318 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
319
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700320 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
321 StringRef AliasSection = SA->getName();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700322 if (AliasSection != AliaseeGV->getSection())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700323 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700324 << AliasSection << IsIFunc << IsIFunc;
Rafael Espindolad2054982013-10-22 19:26:13 +0000325 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700326
327 // We have to handle alias to weak aliases in here. LLVM itself disallows
328 // this since the object semantics would not match the IL one. For
329 // compatibility with gcc we implement it by just pointing the alias
330 // to its aliasee's aliasee. We also warn, since the user is probably
331 // expecting the link to be weak.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700332 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
333 if (GA->isInterposable()) {
334 Diags.Report(Location, diag::warn_alias_to_weak_alias)
335 << GV->getName() << GA->getName() << IsIFunc;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700336 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700337 GA->getIndirectSymbol(), Alias->getType());
338 Alias->setIndirectSymbol(Aliasee);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700339 }
340 }
Rafael Espindolad2054982013-10-22 19:26:13 +0000341 }
342 if (!Error)
343 return;
344
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700345 for (const GlobalDecl &GD : Aliases) {
Rafael Espindolad2054982013-10-22 19:26:13 +0000346 StringRef MangledName = getMangledName(GD);
347 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700348 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
Rafael Espindolad2054982013-10-22 19:26:13 +0000349 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
350 Alias->eraseFromParent();
351 }
352}
353
Stephen Hines651f13c2014-04-23 16:59:28 -0700354void CodeGenModule::clear() {
355 DeferredDeclsToEmit.clear();
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700356 if (OpenMPRuntime)
357 OpenMPRuntime->clear();
Stephen Hines651f13c2014-04-23 16:59:28 -0700358}
359
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700360void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
361 StringRef MainFile) {
362 if (!hasDiagnostics())
363 return;
364 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
365 if (MainFile.empty())
366 MainFile = "<stdin>";
367 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
368 } else
369 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
370 << Mismatched;
371}
372
Ted Kremenek815c78f2008-08-05 18:50:11 +0000373void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +0000374 EmitDeferred();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800375 applyGlobalValReplacements();
Rafael Espindola61a0a752013-11-05 21:37:29 +0000376 applyReplacements();
Rafael Espindolad2054982013-10-22 19:26:13 +0000377 checkAliases();
Eli Friedman6c6bda32010-01-08 00:50:11 +0000378 EmitCXXGlobalInitFunc();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000379 EmitCXXGlobalDtorFunc();
Richard Smithb80a16e2013-04-19 16:42:07 +0000380 EmitCXXThreadLocalInitFunc();
Peter Collingbournee9265232011-07-27 20:29:46 +0000381 if (ObjCRuntime)
382 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000383 AddGlobalCtor(ObjCInitFunction);
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700384 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
385 CUDARuntime) {
386 if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
387 AddGlobalCtor(CudaCtorFunction);
388 if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
389 AddGlobalDtor(CudaDtorFunction);
390 }
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700391 if (OpenMPRuntime)
392 if (llvm::Function *OpenMPRegistrationFunction =
393 OpenMPRuntime->emitRegistrationFunction())
394 AddGlobalCtor(OpenMPRegistrationFunction, 0);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800395 if (PGOReader) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700396 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800397 if (PGOStats.hasDiagnostics())
398 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
399 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000400 EmitCtorList(GlobalCtors, "llvm.global_ctors");
401 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000402 EmitGlobalAnnotations();
Richard Smith00249372013-04-06 05:00:46 +0000403 EmitStaticExternCAliases();
Stephen Hines176edba2014-12-01 14:53:08 -0800404 EmitDeferredUnusedCoverageMappings();
405 if (CoverageMapping)
406 CoverageMapping->emit();
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700407 if (CodeGenOpts.SanitizeCfiCrossDso)
408 CodeGenFunction(*this).EmitCfiCheckFail();
Stephen Hines651f13c2014-04-23 16:59:28 -0700409 emitLLVMUsed();
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700410 if (SanStats)
411 SanStats->finish();
Douglas Gregorf43b7212013-01-16 01:23:41 +0000412
Reid Kleckner3190ca92013-05-08 13:44:39 +0000413 if (CodeGenOpts.Autolink &&
414 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorf43b7212013-01-16 01:23:41 +0000415 EmitModuleLinkOptions();
416 }
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800417 if (CodeGenOpts.DwarfVersion) {
Manman Renfc0f91c2013-06-19 01:46:49 +0000418 // We actually want the latest version when there are conflicts.
419 // We can change from Warning to Latest if such mode is supported.
420 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
421 CodeGenOpts.DwarfVersion);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800422 }
423 if (CodeGenOpts.EmitCodeView) {
424 // Indicate that we want CodeView in the metadata.
425 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
426 }
427 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
428 // We don't support LTO with 2 with different StrictVTablePointers
429 // FIXME: we could support it by stripping all the information introduced
430 // by StrictVTablePointers.
431
432 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
433
434 llvm::Metadata *Ops[2] = {
435 llvm::MDString::get(VMContext, "StrictVTablePointers"),
436 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
437 llvm::Type::getInt32Ty(VMContext), 1))};
438
439 getModule().addModuleFlag(llvm::Module::Require,
440 "StrictVTablePointersRequirement",
441 llvm::MDNode::get(VMContext, Ops));
442 }
Manman Ren1f856a02013-12-09 20:27:01 +0000443 if (DebugInfo)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700444 // We support a single version in the linked module. The LLVM
445 // parser will drop debug info with a different version number
446 // (and warn about it, too).
447 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
Manman Ren82e23c22013-12-09 21:04:35 +0000448 llvm::DEBUG_METADATA_VERSION);
Douglas Gregor5d75ea72013-01-14 18:28:43 +0000449
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700450 // We need to record the widths of enums and wchar_t, so that we can generate
451 // the correct build attributes in the ARM backend.
452 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
453 if ( Arch == llvm::Triple::arm
454 || Arch == llvm::Triple::armeb
455 || Arch == llvm::Triple::thumb
456 || Arch == llvm::Triple::thumbeb) {
457 // Width of wchar_t in bytes
458 uint64_t WCharWidth =
459 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
460 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
461
462 // The minimum width of an enum in bytes
463 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
464 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
465 }
466
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800467 if (CodeGenOpts.SanitizeCfiCrossDso) {
468 // Indicate that we want cross-DSO control flow integrity checks.
469 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
470 }
471
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700472 if (LangOpts.CUDAIsDevice && getTarget().getTriple().isNVPTX()) {
473 // Indicate whether __nvvm_reflect should be configured to flush denormal
474 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
475 // property.)
476 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
477 LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
478 }
Stephen Hines176edba2014-12-01 14:53:08 -0800479
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700480 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
481 assert(PLevel < 3 && "Invalid PIC Level");
482 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
483 if (Context.getLangOpts().PIE)
484 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
Stephen Hines176edba2014-12-01 14:53:08 -0800485 }
486
John McCallb2593832010-09-16 06:16:50 +0000487 SimplifyPersonality();
488
John McCall744016d2010-07-06 23:57:41 +0000489 if (getCodeGenOpts().EmitDeclMetadata)
490 EmitDeclMetadata();
Nick Lewycky5ea4f442011-05-04 20:46:58 +0000491
492 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky3dc05412011-05-05 00:08:20 +0000493 EmitCoverageFile();
Devang Patelf391dbe2011-08-16 20:58:22 +0000494
495 if (DebugInfo)
496 DebugInfo->finalize();
Rafael Espindola9686f122013-10-16 19:28:50 +0000497
498 EmitVersionIdentMetadata();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700499
500 EmitTargetMetadata();
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000501}
502
Devang Patele80d5672011-03-23 16:29:39 +0000503void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
504 // Make sure that this type is translated.
505 Types.UpdateCompletedType(TD);
Devang Patele80d5672011-03-23 16:29:39 +0000506}
507
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700508void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
509 // Make sure that this type is translated.
510 Types.RefreshTypeCacheForClass(RD);
511}
512
Dan Gohman3d5aff52010-10-14 23:06:10 +0000513llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
514 if (!TBAA)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700515 return nullptr;
Dan Gohman3d5aff52010-10-14 23:06:10 +0000516 return TBAA->getTBAAInfo(QTy);
517}
518
Kostya Serebryany8cb4a072012-03-26 17:03:51 +0000519llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
520 if (!TBAA)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700521 return nullptr;
Kostya Serebryany8cb4a072012-03-26 17:03:51 +0000522 return TBAA->getTBAAInfoForVTablePtr();
523}
524
Dan Gohmanb22c7dc2012-09-28 21:58:29 +0000525llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
526 if (!TBAA)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700527 return nullptr;
Dan Gohmanb22c7dc2012-09-28 21:58:29 +0000528 return TBAA->getTBAAStructInfo(QTy);
529}
530
Manman Renb37a73d2013-04-04 21:53:22 +0000531llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
532 llvm::MDNode *AccessN,
533 uint64_t O) {
534 if (!TBAA)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700535 return nullptr;
Manman Renb37a73d2013-04-04 21:53:22 +0000536 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
537}
538
Manman Renfeba9f22013-10-08 00:08:49 +0000539/// Decorate the instruction with a TBAA tag. For both scalar TBAA
540/// and struct-path aware TBAA, the tag has the same format:
541/// base type, access type and offset.
Manman Renca835182013-04-11 23:02:56 +0000542/// When ConvertTypeToTag is true, we create a tag based on the scalar type.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800543void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
544 llvm::MDNode *TBAAInfo,
545 bool ConvertTypeToTag) {
Manman Renfeba9f22013-10-08 00:08:49 +0000546 if (ConvertTypeToTag && TBAA)
Manman Renca835182013-04-11 23:02:56 +0000547 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
548 TBAA->getTBAAScalarTagInfo(TBAAInfo));
549 else
550 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
Dan Gohman3d5aff52010-10-14 23:06:10 +0000551}
552
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800553void CodeGenModule::DecorateInstructionWithInvariantGroup(
554 llvm::Instruction *I, const CXXRecordDecl *RD) {
555 llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
556 auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD);
557 // Check if we have to wrap MDString in MDNode.
558 if (!MetaDataNode)
559 MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD);
560 I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode);
561}
562
Stephen Hines651f13c2014-04-23 16:59:28 -0700563void CodeGenModule::Error(SourceLocation loc, StringRef message) {
564 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
565 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall32096692011-03-18 02:56:14 +0000566}
567
Daniel Dunbar488e9932008-08-16 00:56:44 +0000568/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000569/// specified stmt yet.
David Blaikie0a1c8622013-08-19 21:02:26 +0000570void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikied6471f72011-09-25 23:23:43 +0000571 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000572 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000573 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000574 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
575 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000576}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000577
Daniel Dunbar488e9932008-08-16 00:56:44 +0000578/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000579/// specified decl yet.
David Blaikie0a1c8622013-08-19 21:02:26 +0000580void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikied6471f72011-09-25 23:23:43 +0000581 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000582 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000583 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000584 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000585}
586
John McCallbc8d40d2011-06-24 21:55:10 +0000587llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
588 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
589}
590
Mike Stump1eb44332009-09-09 15:08:12 +0000591void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000592 const NamedDecl *D) const {
Daniel Dunbar04d40782009-04-14 06:00:08 +0000593 // Internal definitions always have default visibility.
Chris Lattnerdf102fc2009-04-14 05:27:13 +0000594 if (GV->hasLocalLinkage()) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000595 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000596 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000597 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000598
John McCallaf146032010-10-30 11:50:40 +0000599 // Set visibility for definitions.
Rafael Espindola2beda122013-02-27 02:15:29 +0000600 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000601 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
602 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman4f8d1232008-05-22 00:50:06 +0000603}
604
Hans Wennborgde981f32012-06-28 08:01:44 +0000605static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
606 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
607 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
608 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
609 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
610 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
611}
612
613static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
614 CodeGenOptions::TLSModel M) {
615 switch (M) {
616 case CodeGenOptions::GeneralDynamicTLSModel:
617 return llvm::GlobalVariable::GeneralDynamicTLSModel;
618 case CodeGenOptions::LocalDynamicTLSModel:
619 return llvm::GlobalVariable::LocalDynamicTLSModel;
620 case CodeGenOptions::InitialExecTLSModel:
621 return llvm::GlobalVariable::InitialExecTLSModel;
622 case CodeGenOptions::LocalExecTLSModel:
623 return llvm::GlobalVariable::LocalExecTLSModel;
624 }
625 llvm_unreachable("Invalid TLS model!");
626}
627
Stephen Hines176edba2014-12-01 14:53:08 -0800628void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
Richard Smith38afbc72013-04-13 02:43:54 +0000629 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgde981f32012-06-28 08:01:44 +0000630
Stephen Hines176edba2014-12-01 14:53:08 -0800631 llvm::GlobalValue::ThreadLocalMode TLM;
Douglas Gregor4cdad312012-10-23 20:05:01 +0000632 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgde981f32012-06-28 08:01:44 +0000633
634 // Override the TLS model if it is explicitly specified.
Stephen Hines651f13c2014-04-23 16:59:28 -0700635 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgde981f32012-06-28 08:01:44 +0000636 TLM = GetLLVMTLSModel(Attr->getModel());
637 }
638
639 GV->setThreadLocalMode(TLM);
640}
641
Chris Lattner5f9e2722011-07-23 10:55:15 +0000642StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700643 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
644
645 // Some ABIs don't have constructor variants. Make sure that base and
646 // complete constructors get mangled the same.
647 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
648 if (!getTarget().getCXXABI().hasConstructorVariants()) {
649 CXXCtorType OrigCtorType = GD.getCtorType();
650 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
651 if (OrigCtorType == Ctor_Base)
652 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
653 }
654 }
655
656 StringRef &FoundStr = MangledDeclNames[CanonicalGD];
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700657 if (!FoundStr.empty())
658 return FoundStr;
659
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700660 const auto *ND = cast<NamedDecl>(GD.getDecl());
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700661 SmallString<256> Buffer;
662 StringRef Str;
663 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
664 llvm::raw_svector_ostream Out(Buffer);
665 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
666 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
667 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
668 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
669 else
670 getCXXABI().getMangleContext().mangleName(ND, Out);
671 Str = Out.str();
672 } else {
Anders Carlsson793a9902010-06-22 16:05:32 +0000673 IdentifierInfo *II = ND->getIdentifier();
674 assert(II && "Attempt to mangle unnamed decl.");
Anders Carlsson793a9902010-06-22 16:05:32 +0000675 Str = II->getName();
Anders Carlsson793a9902010-06-22 16:05:32 +0000676 }
Anders Carlsson793a9902010-06-22 16:05:32 +0000677
Stephen Hines176edba2014-12-01 14:53:08 -0800678 // Keep the first result in the case of a mangling collision.
679 auto Result = Manglings.insert(std::make_pair(Str, GD));
680 return FoundStr = Result.first->first();
Anders Carlsson793a9902010-06-22 16:05:32 +0000681}
682
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700683StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
684 const BlockDecl *BD) {
Peter Collingbourne14110472011-01-13 18:57:25 +0000685 MangleContext &MangleCtx = getCXXABI().getMangleContext();
686 const Decl *D = GD.getDecl();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700687
688 SmallString<256> Buffer;
689 llvm::raw_svector_ostream Out(Buffer);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700690 if (!D)
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000691 MangleCtx.mangleGlobalBlock(BD,
692 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700693 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000694 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700695 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000696 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000697 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000698 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700699
Stephen Hines176edba2014-12-01 14:53:08 -0800700 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
701 return Result.first->first();
Anders Carlsson9a8822b2010-06-09 02:36:32 +0000702}
703
Chris Lattner5f9e2722011-07-23 10:55:15 +0000704llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCallf746aa62010-03-19 23:29:14 +0000705 return getModule().getNamedValue(Name);
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000706}
707
Chris Lattner6d397602008-03-14 17:18:18 +0000708/// AddGlobalCtor - Add a function to the list that will be called before
709/// main() runs.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700710void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
711 llvm::Constant *AssociatedData) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000712 // FIXME: Type coercion of void()* types.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700713 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
Chris Lattner6d397602008-03-14 17:18:18 +0000714}
715
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000716/// AddGlobalDtor - Add a function to the list that will be called
717/// when the module is unloaded.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700718void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000719 // FIXME: Type coercion of void()* types.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700720 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000721}
722
723void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
724 // Ctor function type is void()*.
John McCall0774cb82011-05-15 01:53:33 +0000725 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000726 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000727
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700728 // Get the type of a ctor entry, { i32, void ()*, i8* }.
729 llvm::StructType *CtorStructTy = llvm::StructType::get(
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700730 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
Chris Lattner6d397602008-03-14 17:18:18 +0000731
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000732 // Construct the constructor and destructor arrays.
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700733 SmallVector<llvm::Constant *, 8> Ctors;
734 for (const auto &I : Fns) {
Chris Lattner0b239712012-02-06 22:16:34 +0000735 llvm::Constant *S[] = {
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700736 llvm::ConstantInt::get(Int32Ty, I.Priority, false),
737 llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy),
738 (I.AssociatedData
739 ? llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)
740 : llvm::Constant::getNullValue(VoidPtrTy))};
Owen Anderson08e25242009-07-27 22:29:56 +0000741 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000742 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000743
744 if (!Ctors.empty()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000745 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Anderson1c431b32009-07-08 19:05:04 +0000746 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000747 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000748 llvm::ConstantArray::get(AT, Ctors),
Owen Anderson1c431b32009-07-08 19:05:04 +0000749 GlobalName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000750 }
Chris Lattner6d397602008-03-14 17:18:18 +0000751}
752
John McCalld46f9852010-02-19 01:32:20 +0000753llvm::GlobalValue::LinkageTypes
Peter Collingbourne144a31f2013-06-05 17:49:37 +0000754CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700755 const auto *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknera4130ba2013-07-22 13:51:44 +0000756
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000757 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000758
Stephen Hines651f13c2014-04-23 16:59:28 -0700759 if (isa<CXXDestructorDecl>(D) &&
760 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700761 GD.getDtorType())) {
762 // Destructor variants in the Microsoft C++ ABI are always internal or
763 // linkonce_odr thunks emitted on an as-needed basis.
764 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
765 : llvm::GlobalValue::LinkOnceODRLinkage;
766 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700767
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700768 if (isa<CXXConstructorDecl>(D) &&
769 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
770 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
771 // Our approach to inheriting constructors is fundamentally different from
772 // that used by the MS ABI, so keep our inheriting constructor thunks
773 // internal rather than trying to pick an unambiguous mangling for them.
774 return llvm::GlobalValue::InternalLinkage;
775 }
776
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700777 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
John McCalld46f9852010-02-19 01:32:20 +0000778}
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000779
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700780void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
781 const auto *FD = cast<FunctionDecl>(GD.getDecl());
782
783 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
784 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
785 // Don't dllexport/import destructor thunks.
786 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
787 return;
788 }
789 }
790
791 if (FD->hasAttr<DLLImportAttr>())
792 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
793 else if (FD->hasAttr<DLLExportAttr>())
794 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
795 else
796 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
797}
798
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700799llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800800 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
801 if (!MDS) return nullptr;
802
803 llvm::MD5 md5;
804 llvm::MD5::MD5Result result;
805 md5.update(MDS->getString());
806 md5.final(result);
807 uint64_t id = 0;
808 for (int i = 0; i < 8; ++i)
809 id |= static_cast<uint64_t>(result[i]) << (i * 8);
810 return llvm::ConstantInt::get(Int64Ty, id);
811}
812
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700813void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
814 llvm::Function *F) {
815 setNonAliasAttributes(D, F);
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000816}
817
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000818void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump1eb44332009-09-09 15:08:12 +0000819 const CGFunctionInfo &Info,
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000820 llvm::Function *F) {
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000821 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +0000822 AttributeListType AttributeList;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700823 ConstructAttributeList(F->getName(), Info, D, AttributeList, CallingConv,
824 false);
Bill Wendling785b7782012-12-07 23:17:26 +0000825 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000826 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000827}
828
John McCalld1e40d52011-10-02 01:16:38 +0000829/// Determines whether the language options require us to model
830/// unwind exceptions. We treat -fexceptions as mandating this
831/// except under the fragile ObjC ABI with only ObjC exceptions
832/// enabled. This means, for example, that C with -fexceptions
833/// enables this.
David Blaikie4e4d0842012-03-11 07:00:24 +0000834static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCalld1e40d52011-10-02 01:16:38 +0000835 // If exceptions are completely disabled, obviously this is false.
David Blaikie4e4d0842012-03-11 07:00:24 +0000836 if (!LangOpts.Exceptions) return false;
John McCalld1e40d52011-10-02 01:16:38 +0000837
838 // If C++ exceptions are enabled, this is true.
David Blaikie4e4d0842012-03-11 07:00:24 +0000839 if (LangOpts.CXXExceptions) return true;
John McCalld1e40d52011-10-02 01:16:38 +0000840
841 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikie4e4d0842012-03-11 07:00:24 +0000842 if (LangOpts.ObjCExceptions) {
David Chisnall11d3f4c2012-07-03 20:49:52 +0000843 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCalld1e40d52011-10-02 01:16:38 +0000844 }
845
846 return true;
847}
848
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000849void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
850 llvm::Function *F) {
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000851 llvm::AttrBuilder B;
852
Rafael Espindolaabca5a12011-05-25 03:44:55 +0000853 if (CodeGenOpts.UnwindTables)
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000854 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolaabca5a12011-05-25 03:44:55 +0000855
David Blaikie4e4d0842012-03-11 07:00:24 +0000856 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000857 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000858
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800859 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
860 B.addAttribute(llvm::Attribute::StackProtect);
861 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
862 B.addAttribute(llvm::Attribute::StackProtectStrong);
863 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
864 B.addAttribute(llvm::Attribute::StackProtectReq);
865
866 if (!D) {
867 F->addAttributes(llvm::AttributeSet::FunctionIndex,
868 llvm::AttributeSet::get(
869 F->getContext(),
870 llvm::AttributeSet::FunctionIndex, B));
871 return;
872 }
873
Eli Friedman2873aee2011-08-22 23:55:33 +0000874 if (D->hasAttr<NakedAttr>()) {
875 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000876 B.addAttribute(llvm::Attribute::Naked);
877 B.addAttribute(llvm::Attribute::NoInline);
Stephen Hines651f13c2014-04-23 16:59:28 -0700878 } else if (D->hasAttr<NoDuplicateAttr>()) {
879 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000880 } else if (D->hasAttr<NoInlineAttr>()) {
881 B.addAttribute(llvm::Attribute::NoInline);
Stephen Hines651f13c2014-04-23 16:59:28 -0700882 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000883 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
884 llvm::Attribute::NoInline)) {
885 // (noinline wins over always_inline, and we can't specify both in IR)
886 B.addAttribute(llvm::Attribute::AlwaysInline);
Eli Friedman2873aee2011-08-22 23:55:33 +0000887 }
Daniel Dunbardd0cb222010-09-29 18:20:25 +0000888
Diego Novillod27e5cb2013-05-24 20:18:15 +0000889 if (D->hasAttr<ColdAttr>()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700890 if (!D->hasAttr<OptimizeNoneAttr>())
891 B.addAttribute(llvm::Attribute::OptimizeForSize);
Diego Novillod27e5cb2013-05-24 20:18:15 +0000892 B.addAttribute(llvm::Attribute::Cold);
893 }
Benjamin Krameree409a92012-05-12 21:10:52 +0000894
Quentin Colombetaee56fa2012-11-01 23:55:47 +0000895 if (D->hasAttr<MinSizeAttr>())
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000896 B.addAttribute(llvm::Attribute::MinSize);
Richard Smithef4d5ce2012-09-28 22:46:07 +0000897
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000898 F->addAttributes(llvm::AttributeSet::FunctionIndex,
899 llvm::AttributeSet::get(
900 F->getContext(), llvm::AttributeSet::FunctionIndex, B));
901
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700902 if (D->hasAttr<OptimizeNoneAttr>()) {
903 // OptimizeNone implies noinline; we should not be inlining such functions.
904 F->addFnAttr(llvm::Attribute::OptimizeNone);
905 F->addFnAttr(llvm::Attribute::NoInline);
906
907 // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800908 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
909 F->removeFnAttr(llvm::Attribute::MinSize);
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700910 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
911 "OptimizeNone and AlwaysInline on same function!");
912
913 // Attribute 'inlinehint' has no effect on 'optnone' functions.
914 // Explicitly remove it from the set of function attributes.
915 F->removeFnAttr(llvm::Attribute::InlineHint);
916 }
917
Sean Huntcf807c42010-08-18 23:23:40 +0000918 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
919 if (alignment)
920 F->setAlignment(alignment);
921
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800922 // Some C++ ABIs require 2-byte alignment for member functions, in order to
923 // reserve a bit for differentiating between virtual and non-virtual member
924 // functions. If the current target's C++ ABI requires this and this is a
925 // member function, set its alignment accordingly.
926 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
927 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
928 F->setAlignment(2);
929 }
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000930}
931
Mike Stump1eb44332009-09-09 15:08:12 +0000932void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000933 llvm::GlobalValue *GV) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800934 if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
Anders Carlsson934176f2011-01-29 19:41:00 +0000935 setGlobalVisibility(GV, ND);
John McCall1fb0caa2010-10-22 21:05:15 +0000936 else
937 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000938
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800939 if (D && D->hasAttr<UsedAttr>())
Stephen Hines651f13c2014-04-23 16:59:28 -0700940 addUsedGlobal(GV);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700941}
942
Stephen Hines176edba2014-12-01 14:53:08 -0800943void CodeGenModule::setAliasAttributes(const Decl *D,
944 llvm::GlobalValue *GV) {
945 SetCommonAttributes(D, GV);
946
947 // Process the dllexport attribute based on whether the original definition
948 // (not necessarily the aliasee) was exported.
949 if (D->hasAttr<DLLExportAttr>())
950 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
951}
952
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700953void CodeGenModule::setNonAliasAttributes(const Decl *D,
954 llvm::GlobalObject *GO) {
955 SetCommonAttributes(D, GO);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000956
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800957 if (D)
958 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
959 GO->setSection(SA->getName());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000960
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700961 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000962}
963
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000964void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
965 llvm::Function *F,
966 const CGFunctionInfo &FI) {
967 SetLLVMFunctionAttributes(D, FI, F);
968 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000969
970 F->setLinkage(llvm::Function::InternalLinkage);
971
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700972 setNonAliasAttributes(D, F);
973}
974
975static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
976 const NamedDecl *ND) {
977 // Set linkage and visibility in case we never see a definition.
978 LinkageInfo LV = ND->getLinkageAndVisibility();
979 if (LV.getLinkage() != ExternalLinkage) {
980 // Don't set internal linkage on declarations.
981 } else {
982 if (ND->hasAttr<DLLImportAttr>()) {
983 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
984 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
985 } else if (ND->hasAttr<DLLExportAttr>()) {
986 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
987 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
988 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
989 // "extern_weak" is overloaded in LLVM; we probably should have
990 // separate linkage types for this.
991 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
992 }
993
994 // Set visibility on a declaration only if it's explicit.
995 if (LV.isVisibilityExplicit())
996 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
997 }
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000998}
999
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001000void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
1001 llvm::Function *F) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001002 // Only if we are checking indirect calls.
1003 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1004 return;
1005
1006 // Non-static class methods are handled via vtable pointer checks elsewhere.
1007 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1008 return;
1009
1010 // Additionally, if building with cross-DSO support...
1011 if (CodeGenOpts.SanitizeCfiCrossDso) {
1012 // Don't emit entries for function declarations. In cross-DSO mode these are
1013 // handled with better precision at run time.
1014 if (!FD->hasBody())
1015 return;
1016 // Skip available_externally functions. They won't be codegen'ed in the
1017 // current module anyway.
1018 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1019 return;
1020 }
1021
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001022 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001023 F->addTypeMetadata(0, MD);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001024
1025 // Emit a hash-based bit set entry for cross-DSO calls.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001026 if (CodeGenOpts.SanitizeCfiCrossDso)
1027 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1028 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001029}
1030
Stephen Hines176edba2014-12-01 14:53:08 -08001031void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1032 bool IsIncompleteFunction,
1033 bool IsThunk) {
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001034 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
Peter Collingbourne0ac2cf42011-04-06 12:29:04 +00001035 // If this is an intrinsic function, set the function's attributes
1036 // to the intrinsic's attributes.
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001037 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
Peter Collingbourne0ac2cf42011-04-06 12:29:04 +00001038 return;
1039 }
1040
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001041 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +00001042
Eli Friedmanc6c14d12009-05-26 01:22:57 +00001043 if (!IsIncompleteFunction)
John McCallde5d3c72012-02-17 03:33:10 +00001044 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Stephen Hines651f13c2014-04-23 16:59:28 -07001046 // Add the Returned attribute for "this", except for iOS 5 and earlier
1047 // where substantial code, including the libstdc++ dylib, was compiled with
1048 // GCC and does not actually return "this".
Stephen Hines176edba2014-12-01 14:53:08 -08001049 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
Stephen Hines651f13c2014-04-23 16:59:28 -07001050 !(getTarget().getTriple().isiOS() &&
1051 getTarget().getTriple().isOSVersionLT(6))) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +00001052 assert(!F->arg_empty() &&
1053 F->arg_begin()->getType()
1054 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1055 "unexpected this return");
1056 F->addAttribute(1, llvm::Attribute::Returned);
1057 }
1058
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001059 // Only a few attributes are set on declarations; these may later be
1060 // overridden by a definition.
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001062 setLinkageAndVisibilityForGV(F, FD);
John McCallaf146032010-10-30 11:50:40 +00001063
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001064 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001065 F->setSection(SA->getName());
Richard Smithddcff1b2013-07-21 23:12:18 +00001066
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001067 if (FD->isReplaceableGlobalAllocationFunction()) {
1068 // A replaceable global allocation function does not act like a builtin by
1069 // default, only if it is invoked by a new-expression or delete-expression.
Richard Smithddcff1b2013-07-21 23:12:18 +00001070 F->addAttribute(llvm::AttributeSet::FunctionIndex,
1071 llvm::Attribute::NoBuiltin);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001072
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001073 // A sane operator new returns a non-aliasing pointer.
1074 // FIXME: Also add NonNull attribute to the return value
1075 // for the non-nothrow forms?
1076 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1077 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1078 (Kind == OO_New || Kind == OO_Array_New))
1079 F->addAttribute(llvm::AttributeSet::ReturnIndex,
1080 llvm::Attribute::NoAlias);
1081 }
1082
1083 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1084 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1085 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1086 if (MD->isVirtual())
1087 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1088
1089 CreateFunctionTypeMetadata(FD, F);
Daniel Dunbar219df662008-09-08 23:44:31 +00001090}
1091
Stephen Hines651f13c2014-04-23 16:59:28 -07001092void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump1eb44332009-09-09 15:08:12 +00001093 assert(!GV->isDeclaration() &&
Daniel Dunbar02698712009-02-13 20:29:50 +00001094 "Only globals with definition can force usage.");
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001095 LLVMUsed.emplace_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +00001096}
1097
Stephen Hines651f13c2014-04-23 16:59:28 -07001098void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1099 assert(!GV->isDeclaration() &&
1100 "Only globals with definition can force usage.");
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001101 LLVMCompilerUsed.emplace_back(GV);
Stephen Hines651f13c2014-04-23 16:59:28 -07001102}
1103
1104static void emitUsed(CodeGenModule &CGM, StringRef Name,
1105 std::vector<llvm::WeakVH> &List) {
Daniel Dunbar02698712009-02-13 20:29:50 +00001106 // Don't create llvm.used if there is no need.
Stephen Hines651f13c2014-04-23 16:59:28 -07001107 if (List.empty())
Daniel Dunbar02698712009-02-13 20:29:50 +00001108 return;
1109
Stephen Hines651f13c2014-04-23 16:59:28 -07001110 // Convert List to what ConstantArray needs.
Chris Lattner0b239712012-02-06 22:16:34 +00001111 SmallVector<llvm::Constant*, 8> UsedArray;
Stephen Hines651f13c2014-04-23 16:59:28 -07001112 UsedArray.resize(List.size());
1113 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001114 UsedArray[i] =
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001115 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1116 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
Chris Lattner35f38a22009-03-31 22:37:52 +00001117 }
Mike Stump1eb44332009-09-09 15:08:12 +00001118
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00001119 if (UsedArray.empty())
1120 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07001121 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001123 auto *GV = new llvm::GlobalVariable(
1124 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1125 llvm::ConstantArray::get(ATy, UsedArray), Name);
Daniel Dunbar02698712009-02-13 20:29:50 +00001126
1127 GV->setSection("llvm.metadata");
1128}
1129
Stephen Hines651f13c2014-04-23 16:59:28 -07001130void CodeGenModule::emitLLVMUsed() {
1131 emitUsed(*this, "llvm.used", LLVMUsed);
1132 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1133}
1134
Reid Kleckner3190ca92013-05-08 13:44:39 +00001135void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001136 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
Reid Kleckner3190ca92013-05-08 13:44:39 +00001137 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1138}
1139
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001140void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1141 llvm::SmallString<32> Opt;
1142 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001143 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001144 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1145}
1146
Reid Kleckner3190ca92013-05-08 13:44:39 +00001147void CodeGenModule::AddDependentLib(StringRef Lib) {
1148 llvm::SmallString<24> Opt;
1149 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001150 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Reid Kleckner3190ca92013-05-08 13:44:39 +00001151 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1152}
1153
Douglas Gregor858afb32013-01-14 20:53:57 +00001154/// \brief Add link options implied by the given module, including modules
1155/// it depends on, using a postorder walk.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001156static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1157 SmallVectorImpl<llvm::Metadata *> &Metadata,
Douglas Gregor858afb32013-01-14 20:53:57 +00001158 llvm::SmallPtrSet<Module *, 16> &Visited) {
1159 // Import this module's parent.
Stephen Hines176edba2014-12-01 14:53:08 -08001160 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
Reid Kleckner3190ca92013-05-08 13:44:39 +00001161 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregor858afb32013-01-14 20:53:57 +00001162 }
1163
1164 // Import this module's dependencies.
1165 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
Stephen Hines176edba2014-12-01 14:53:08 -08001166 if (Visited.insert(Mod->Imports[I - 1]).second)
Reid Kleckner3190ca92013-05-08 13:44:39 +00001167 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregor858afb32013-01-14 20:53:57 +00001168 }
1169
1170 // Add linker options to link against the libraries/frameworks
1171 // described by this module.
Reid Kleckner3190ca92013-05-08 13:44:39 +00001172 llvm::LLVMContext &Context = CGM.getLLVMContext();
Douglas Gregor858afb32013-01-14 20:53:57 +00001173 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Kleckner3190ca92013-05-08 13:44:39 +00001174 // Link against a framework. Frameworks are currently Darwin only, so we
1175 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregor858afb32013-01-14 20:53:57 +00001176 if (Mod->LinkLibraries[I-1].IsFramework) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001177 llvm::Metadata *Args[2] = {
1178 llvm::MDString::get(Context, "-framework"),
1179 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
Douglas Gregor858afb32013-01-14 20:53:57 +00001180
1181 Metadata.push_back(llvm::MDNode::get(Context, Args));
1182 continue;
1183 }
1184
1185 // Link against a library.
Reid Kleckner3190ca92013-05-08 13:44:39 +00001186 llvm::SmallString<24> Opt;
1187 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1188 Mod->LinkLibraries[I-1].Library, Opt);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001189 auto *OptString = llvm::MDString::get(Context, Opt);
Douglas Gregor858afb32013-01-14 20:53:57 +00001190 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1191 }
1192}
1193
1194void CodeGenModule::EmitModuleLinkOptions() {
1195 // Collect the set of all of the modules we want to visit to emit link
1196 // options, which is essentially the imported modules and all of their
1197 // non-explicit child modules.
1198 llvm::SetVector<clang::Module *> LinkModules;
1199 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1200 SmallVector<clang::Module *, 16> Stack;
1201
1202 // Seed the stack with imported modules.
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001203 for (Module *M : ImportedModules)
1204 if (Visited.insert(M).second)
1205 Stack.push_back(M);
Douglas Gregor858afb32013-01-14 20:53:57 +00001206
1207 // Find all of the modules to import, making a little effort to prune
1208 // non-leaf modules.
1209 while (!Stack.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00001210 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregor858afb32013-01-14 20:53:57 +00001211
1212 bool AnyChildren = false;
1213
1214 // Visit the submodules of this module.
1215 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1216 SubEnd = Mod->submodule_end();
1217 Sub != SubEnd; ++Sub) {
1218 // Skip explicit children; they need to be explicitly imported to be
1219 // linked against.
1220 if ((*Sub)->IsExplicit)
1221 continue;
1222
Stephen Hines176edba2014-12-01 14:53:08 -08001223 if (Visited.insert(*Sub).second) {
Douglas Gregor858afb32013-01-14 20:53:57 +00001224 Stack.push_back(*Sub);
1225 AnyChildren = true;
1226 }
1227 }
1228
1229 // We didn't find any children, so add this module to the list of
1230 // modules to link against.
1231 if (!AnyChildren) {
1232 LinkModules.insert(Mod);
1233 }
1234 }
1235
1236 // Add link options for all of the imported modules in reverse topological
Reid Kleckner3190ca92013-05-08 13:44:39 +00001237 // order. We don't do anything to try to order import link flags with respect
1238 // to linker options inserted by things like #pragma comment().
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001239 SmallVector<llvm::Metadata *, 16> MetadataArgs;
Douglas Gregor858afb32013-01-14 20:53:57 +00001240 Visited.clear();
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001241 for (Module *M : LinkModules)
1242 if (Visited.insert(M).second)
1243 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
Daniel Dunbarf9d03c12013-01-17 01:35:06 +00001244 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Kleckner3190ca92013-05-08 13:44:39 +00001245 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregor858afb32013-01-14 20:53:57 +00001246
Daniel Dunbarf9d03c12013-01-17 01:35:06 +00001247 // Add the linker options metadata flag.
1248 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
Reid Kleckner3190ca92013-05-08 13:44:39 +00001249 llvm::MDNode::get(getLLVMContext(),
1250 LinkerOptionsMetadata));
Douglas Gregor858afb32013-01-14 20:53:57 +00001251}
1252
Daniel Dunbar02698712009-02-13 20:29:50 +00001253void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +00001254 // Emit code for any potentially referenced deferred decls. Since a
1255 // previously unused static decl may become used during the generation of code
Nick Lewyckydce67a72011-07-18 05:26:13 +00001256 // for a static function, iterate until no changes are made.
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00001257
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001258 if (!DeferredVTables.empty()) {
1259 EmitDeferredVTables();
John McCalld5617ee2013-01-25 22:31:03 +00001260
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001261 // Emitting a vtable doesn't directly cause more vtables to
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001262 // become deferred, although it can cause functions to be
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001263 // emitted that then need those vtables.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001264 assert(DeferredVTables.empty());
1265 }
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00001266
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001267 // Stop if we're out of both deferred vtables and deferred declarations.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001268 if (DeferredDeclsToEmit.empty())
1269 return;
John McCalld5617ee2013-01-25 22:31:03 +00001270
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001271 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1272 // work, it will not interfere with this.
1273 std::vector<DeferredGlobal> CurDeclsToEmit;
1274 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1275
1276 for (DeferredGlobal &G : CurDeclsToEmit) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001277 GlobalDecl D = G.GD;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001278 G.GV = nullptr;
Chris Lattner67b00522009-03-21 09:44:56 +00001279
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001280 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1281 // to get GlobalValue with exactly the type we need, not something that
1282 // might had been created for another decl with the same mangled name but
1283 // different type.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001284 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1285 GetAddrOfGlobal(D, /*IsForDefinition=*/true));
1286
1287 // In case of different address spaces, we may still get a cast, even with
1288 // IsForDefinition equal to true. Query mangled names table to get
1289 // GlobalValue.
1290 if (!GV)
1291 GV = GetGlobalValue(getMangledName(D));
1292
1293 // Make sure GetGlobalValue returned non-null.
1294 assert(GV);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001295
John McCallc76702c2010-05-27 01:45:30 +00001296 // Check to see if we've already emitted this. This is necessary
1297 // for a couple of reasons: first, decls can end up in the
1298 // deferred-decls queue multiple times, and second, decls can end
1299 // up with definitions in unusual ways (e.g. by an extern inline
1300 // function acquiring a strong function redefinition). Just
1301 // ignore these cases.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001302 if (!GV->isDeclaration())
John McCallc76702c2010-05-27 01:45:30 +00001303 continue;
1304
Chris Lattner67b00522009-03-21 09:44:56 +00001305 // Otherwise, emit the definition and move on to the next one.
Stephen Hines651f13c2014-04-23 16:59:28 -07001306 EmitGlobalDefinition(D, GV);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001307
1308 // If we found out that we need to emit more decls, do that recursively.
1309 // This has the advantage that the decls are emitted in a DFS and related
1310 // ones are close together, which is convenient for testing.
1311 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1312 EmitDeferred();
1313 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1314 }
Chris Lattner67b00522009-03-21 09:44:56 +00001315 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001316}
1317
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001318void CodeGenModule::EmitGlobalAnnotations() {
1319 if (Annotations.empty())
1320 return;
1321
1322 // Create a new global variable for the ConstantStruct in the Module.
1323 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1324 Annotations[0]->getType(), Annotations.size()), Annotations);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001325 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1326 llvm::GlobalValue::AppendingLinkage,
1327 Array, "llvm.global.annotations");
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001328 gv->setSection(AnnotationSection);
1329}
1330
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001331llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramer471b52a2013-11-10 16:55:11 +00001332 llvm::Constant *&AStr = AnnotationStrings[Str];
1333 if (AStr)
1334 return AStr;
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001335
1336 // Not found yet, create a new global.
Chris Lattner94010692012-02-05 02:30:40 +00001337 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001338 auto *gv =
1339 new llvm::GlobalVariable(getModule(), s->getType(), true,
1340 llvm::GlobalValue::PrivateLinkage, s, ".str");
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001341 gv->setSection(AnnotationSection);
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001342 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Benjamin Kramer471b52a2013-11-10 16:55:11 +00001343 AStr = gv;
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001344 return gv;
1345}
1346
1347llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1348 SourceManager &SM = getContext().getSourceManager();
1349 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1350 if (PLoc.isValid())
1351 return EmitAnnotationString(PLoc.getFilename());
1352 return EmitAnnotationString(SM.getBufferName(Loc));
1353}
1354
1355llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1356 SourceManager &SM = getContext().getSourceManager();
1357 PresumedLoc PLoc = SM.getPresumedLoc(L);
1358 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1359 SM.getExpansionLineNumber(L);
1360 return llvm::ConstantInt::get(Int32Ty, LineNo);
1361}
1362
Mike Stump1eb44332009-09-09 15:08:12 +00001363llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001364 const AnnotateAttr *AA,
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001365 SourceLocation L) {
1366 // Get the globals for file name, annotation, and the line number.
1367 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1368 *UnitGV = EmitAnnotationUnit(L),
1369 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001370
Daniel Dunbar57d5cee2009-04-14 22:41:13 +00001371 // Create the ConstantStruct for the global annotation.
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001372 llvm::Constant *Fields[4] = {
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001373 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1374 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1375 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1376 LineNoCst
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001377 };
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001378 return llvm::ConstantStruct::getAnon(Fields);
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001379}
1380
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001381void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1382 llvm::GlobalValue *GV) {
1383 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1384 // Get the struct elements for these annotations.
Stephen Hines651f13c2014-04-23 16:59:28 -07001385 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1386 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001387}
1388
Stephen Hines176edba2014-12-01 14:53:08 -08001389bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1390 SourceLocation Loc) const {
1391 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1392 // Blacklist by function name.
1393 if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1394 return true;
1395 // Blacklist by location.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001396 if (Loc.isValid())
Stephen Hines176edba2014-12-01 14:53:08 -08001397 return SanitizerBL.isBlacklistedLocation(Loc);
1398 // If location is unknown, this may be a compiler-generated function. Assume
1399 // it's located in the main file.
1400 auto &SM = Context.getSourceManager();
1401 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1402 return SanitizerBL.isBlacklistedFile(MainFile->getName());
1403 }
1404 return false;
1405}
1406
1407bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1408 SourceLocation Loc, QualType Ty,
1409 StringRef Category) const {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001410 // For now globals can be blacklisted only in ASan and KASan.
1411 if (!LangOpts.Sanitize.hasOneOf(
1412 SanitizerKind::Address | SanitizerKind::KernelAddress))
Stephen Hines176edba2014-12-01 14:53:08 -08001413 return false;
1414 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1415 if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1416 return true;
1417 if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1418 return true;
1419 // Check global type.
1420 if (!Ty.isNull()) {
1421 // Drill down the array types: if global variable of a fixed type is
1422 // blacklisted, we also don't instrument arrays of them.
1423 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1424 Ty = AT->getElementType();
1425 Ty = Ty.getCanonicalType().getUnqualifiedType();
1426 // We allow to blacklist only record types (classes, structs etc.)
1427 if (Ty->isRecordType()) {
1428 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1429 if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1430 return true;
1431 }
1432 }
1433 return false;
1434}
1435
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001436bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00001437 // Never defer when EmitAllDecls is specified.
David Blaikie4e4d0842012-03-11 07:00:24 +00001438 if (LangOpts.EmitAllDecls)
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001439 return true;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001440
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001441 return getContext().DeclMustBeEmitted(Global);
1442}
1443
1444bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1445 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1446 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1447 // Implicit template instantiations may change linkage if they are later
1448 // explicitly instantiated, so they should not be emitted eagerly.
1449 return false;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001450 if (const auto *VD = dyn_cast<VarDecl>(Global))
1451 if (Context.getInlineVariableDefinitionKind(VD) ==
1452 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1453 // A definition of an inline constexpr static data member may change
1454 // linkage later if it's redeclared outside the class.
1455 return false;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001456 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1457 // codegen for global variables, because they may be marked as threadprivate.
1458 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1459 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1460 return false;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001461
1462 return true;
Daniel Dunbar73241df2009-02-13 21:18:01 +00001463}
1464
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001465ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
Nico Weberc5f80462012-10-11 10:13:44 +00001466 const CXXUuidofExpr* E) {
1467 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1468 // well-formed.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001469 StringRef Uuid = E->getUuidStr();
David Majnemerc8fe0112013-08-09 08:35:59 +00001470 std::string Name = "_GUID_" + Uuid.lower();
1471 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Weberc5f80462012-10-11 10:13:44 +00001472
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001473 // The UUID descriptor should be pointer aligned.
1474 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001475
Nico Weberc5f80462012-10-11 10:13:44 +00001476 // Look for an existing global.
1477 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001478 return ConstantAddress(GV, Alignment);
Nico Weberc5f80462012-10-11 10:13:44 +00001479
Stephen Hines176edba2014-12-01 14:53:08 -08001480 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
Nico Weberc5f80462012-10-11 10:13:44 +00001481 assert(Init && "failed to initialize as constant");
1482
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001483 auto *GV = new llvm::GlobalVariable(
David Majnemer8effeda2013-08-15 19:59:14 +00001484 getModule(), Init->getType(),
Reid Klecknerdc1ac5e2013-09-03 21:49:32 +00001485 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001486 if (supportsCOMDAT())
1487 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001488 return ConstantAddress(GV, Alignment);
Nico Weberc5f80462012-10-11 10:13:44 +00001489}
1490
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001491ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
Rafael Espindola6a836702010-03-04 18:17:24 +00001492 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1493 assert(AA && "No alias?");
1494
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001495 CharUnits Alignment = getContext().getDeclAlign(VD);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001496 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola6a836702010-03-04 18:17:24 +00001497
Rafael Espindola6a836702010-03-04 18:17:24 +00001498 // See if there is already something with the target's name in the module.
John McCallf746aa62010-03-19 23:29:14 +00001499 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenberger4695f912012-10-16 17:45:27 +00001500 if (Entry) {
1501 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001502 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1503 return ConstantAddress(Ptr, Alignment);
Joerg Sonnenberger4695f912012-10-16 17:45:27 +00001504 }
Rafael Espindola6a836702010-03-04 18:17:24 +00001505
1506 llvm::Constant *Aliasee;
1507 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergc857ce82012-10-05 23:12:53 +00001508 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1509 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001510 /*ForVTable=*/false);
Rafael Espindola6a836702010-03-04 18:17:24 +00001511 else
John McCallf746aa62010-03-19 23:29:14 +00001512 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001513 llvm::PointerType::getUnqual(DeclTy),
1514 nullptr);
Joerg Sonnenberger4695f912012-10-16 17:45:27 +00001515
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001516 auto *F = cast<llvm::GlobalValue>(Aliasee);
Joerg Sonnenberger4695f912012-10-16 17:45:27 +00001517 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1518 WeakRefReferences.insert(F);
Rafael Espindola6a836702010-03-04 18:17:24 +00001519
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001520 return ConstantAddress(Aliasee, Alignment);
Rafael Espindola6a836702010-03-04 18:17:24 +00001521}
1522
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001523void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001524 const auto *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Rafael Espindola6a836702010-03-04 18:17:24 +00001526 // Weak references don't produce any output by themselves.
1527 if (Global->hasAttr<WeakRefAttr>())
1528 return;
1529
Chris Lattnerbd532712009-03-22 21:47:11 +00001530 // If this is an alias definition (which otherwise looks like a declaration)
1531 // emit it now.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001532 if (Global->hasAttr<AliasAttr>())
Rafael Espindola87017a72013-10-22 14:23:09 +00001533 return EmitAliasDefinition(GD);
Daniel Dunbar219df662008-09-08 23:44:31 +00001534
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001535 // IFunc like an alias whose value is resolved at runtime by calling resolver.
1536 if (Global->hasAttr<IFuncAttr>())
1537 return emitIFuncDefinition(GD);
1538
Peter Collingbourned51e43a2011-10-06 18:29:46 +00001539 // If this is CUDA, be selective about which declarations we emit.
David Blaikie4e4d0842012-03-11 07:00:24 +00001540 if (LangOpts.CUDA) {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001541 if (LangOpts.CUDAIsDevice) {
Peter Collingbourned51e43a2011-10-06 18:29:46 +00001542 if (!Global->hasAttr<CUDADeviceAttr>() &&
1543 !Global->hasAttr<CUDAGlobalAttr>() &&
1544 !Global->hasAttr<CUDAConstantAttr>() &&
1545 !Global->hasAttr<CUDASharedAttr>())
1546 return;
1547 } else {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001548 // We need to emit host-side 'shadows' for all global
1549 // device-side variables because the CUDA runtime needs their
1550 // size and host-side address in order to provide access to
1551 // their device-side incarnations.
1552
1553 // So device-only functions are the only things we skip.
1554 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1555 Global->hasAttr<CUDADeviceAttr>())
Peter Collingbourned51e43a2011-10-06 18:29:46 +00001556 return;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001557
1558 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1559 "Expected Variable or Function");
1560 }
1561 }
1562
1563 if (LangOpts.OpenMP) {
1564 // If this is OpenMP device, check if it is legal to emit this global
1565 // normally.
1566 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1567 return;
1568 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1569 if (MustBeEmitted(Global))
1570 EmitOMPDeclareReduction(DRD);
1571 return;
Peter Collingbourned51e43a2011-10-06 18:29:46 +00001572 }
1573 }
1574
Chris Lattner67b00522009-03-21 09:44:56 +00001575 // Ignore declarations, they will be emitted on their first use.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001576 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +00001577 // Forward declarations are emitted lazily on first use.
Nick Lewyckydce67a72011-07-18 05:26:13 +00001578 if (!FD->doesThisDeclarationHaveABody()) {
1579 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1580 return;
1581
Chris Lattner5f9e2722011-07-23 10:55:15 +00001582 StringRef MangledName = getMangledName(GD);
Stephen Hines651f13c2014-04-23 16:59:28 -07001583
1584 // Compute the function info and LLVM type.
1585 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1586 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1587
1588 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1589 /*DontDefer=*/false);
Daniel Dunbar73241df2009-02-13 21:18:01 +00001590 return;
Nick Lewyckydce67a72011-07-18 05:26:13 +00001591 }
Daniel Dunbar02698712009-02-13 20:29:50 +00001592 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001593 const auto *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001594 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001595 // We need to emit device-side global CUDA variables even if a
1596 // variable does not have a definition -- we still need to define
1597 // host-side shadow for it.
1598 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1599 !VD->hasDefinition() &&
1600 (VD->hasAttr<CUDAConstantAttr>() ||
1601 VD->hasAttr<CUDADeviceAttr>());
1602 if (!MustEmitForCuda &&
1603 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1604 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1605 // If this declaration may have caused an inline variable definition to
1606 // change linkage, make sure that it's emitted.
1607 if (Context.getInlineVariableDefinitionKind(VD) ==
1608 ASTContext::InlineVariableDefinitionKind::Strong)
1609 GetAddrOfGlobalVar(VD);
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00001610 return;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001611 }
Nate Begeman4c13b7a2008-04-20 06:29:50 +00001612 }
1613
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001614 // Defer code generation to first use when possible, e.g. if this is an inline
1615 // function. If the global must always be emitted, do it eagerly if possible
1616 // to benefit from cache locality.
1617 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
Chris Lattner4357a822010-04-13 17:39:09 +00001618 // Emit the definition if it can't be deferred.
1619 EmitGlobalDefinition(GD);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001620 return;
1621 }
John McCallbf40cb52010-07-15 23:40:35 +00001622
1623 // If we're deferring emission of a C++ variable with an
1624 // initializer, remember the order in which it appeared in the file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001625 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCallbf40cb52010-07-15 23:40:35 +00001626 cast<VarDecl>(Global)->hasInit()) {
1627 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001628 CXXGlobalInits.push_back(nullptr);
John McCallbf40cb52010-07-15 23:40:35 +00001629 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001630
Chris Lattner5f9e2722011-07-23 10:55:15 +00001631 StringRef MangledName = getMangledName(GD);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001632 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
1633 // The value has already been used and should therefore be emitted.
Stephen Hines651f13c2014-04-23 16:59:28 -07001634 addDeferredDeclToEmit(GV, GD);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001635 } else if (MustBeEmitted(Global)) {
1636 // The value must be emitted, but cannot be emitted eagerly.
1637 assert(!MayBeEmittedEagerly(Global));
1638 addDeferredDeclToEmit(/*GV=*/nullptr, GD);
1639 } else {
Chris Lattner4357a822010-04-13 17:39:09 +00001640 // Otherwise, remember that we saw a deferred decl with this name. The
1641 // first use of the mangled name will cause it to move into
1642 // DeferredDeclsToEmit.
1643 DeferredDecls[MangledName] = GD;
1644 }
Nate Begeman4c13b7a2008-04-20 06:29:50 +00001645}
1646
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001647namespace {
1648 struct FunctionIsDirectlyRecursive :
1649 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1650 const StringRef Name;
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001651 const Builtin::Context &BI;
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001652 bool Result;
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001653 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1654 Name(N), BI(C), Result(false) {
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001655 }
1656 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1657
1658 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001659 const FunctionDecl *FD = E->getDirectCallee();
1660 if (!FD)
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001661 return true;
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001662 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1663 if (Attr && Name == Attr->getLabel()) {
1664 Result = true;
1665 return false;
1666 }
1667 unsigned BuiltinID = FD->getBuiltinID();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001668 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001669 return true;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001670 StringRef BuiltinName = BI.getName(BuiltinID);
Nick Lewyckyf6b56372012-01-18 03:41:19 +00001671 if (BuiltinName.startswith("__builtin_") &&
1672 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001673 Result = true;
1674 return false;
1675 }
1676 return true;
1677 }
1678 };
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001679
1680 struct DLLImportFunctionVisitor
1681 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
1682 bool SafeToInline = true;
1683
1684 bool VisitVarDecl(VarDecl *VD) {
1685 // A thread-local variable cannot be imported.
1686 SafeToInline = !VD->getTLSKind();
1687 return SafeToInline;
1688 }
1689
1690 // Make sure we're not referencing non-imported vars or functions.
1691 bool VisitDeclRefExpr(DeclRefExpr *E) {
1692 ValueDecl *VD = E->getDecl();
1693 if (isa<FunctionDecl>(VD))
1694 SafeToInline = VD->hasAttr<DLLImportAttr>();
1695 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
1696 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1697 return SafeToInline;
1698 }
1699 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1700 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
1701 return SafeToInline;
1702 }
1703 bool VisitCXXNewExpr(CXXNewExpr *E) {
1704 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
1705 return SafeToInline;
1706 }
1707 };
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001708}
1709
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001710// isTriviallyRecursive - Check if this function calls another
1711// decl that, because of the asm attribute or the other decl being a builtin,
1712// ends up pointing to itself.
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001713bool
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001714CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1715 StringRef Name;
1716 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky22afacc2012-01-18 01:50:13 +00001717 // asm labels are a special kind of mangling we have to support.
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001718 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1719 if (!Attr)
1720 return false;
1721 Name = Attr->getLabel();
1722 } else {
1723 Name = FD->getName();
1724 }
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001725
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001726 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1727 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001728 return Walker.Result;
1729}
1730
1731bool
Peter Collingbourne144a31f2013-06-05 17:49:37 +00001732CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1733 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001734 return true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001735 const auto *F = cast<FunctionDecl>(GD.getDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -07001736 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001737 return false;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001738
1739 if (F->hasAttr<DLLImportAttr>()) {
1740 // Check whether it would be safe to inline this dllimport function.
1741 DLLImportFunctionVisitor Visitor;
1742 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1743 if (!Visitor.SafeToInline)
1744 return false;
1745 }
1746
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001747 // PR9614. Avoid cases where the source code is lying to us. An available
1748 // externally function should have an equivalent function somewhere else,
1749 // but a function that calls itself is clearly not equivalent to the real
1750 // implementation.
1751 // This happens in glibc's btowc and in some configure checks.
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001752 return !isTriviallyRecursive(F);
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001753}
1754
Adrian Prantl0a050f72013-05-09 23:16:27 +00001755/// If the type for the method's class was generated by
1756/// CGDebugInfo::createContextChain(), the cache contains only a
1757/// limited DIType without any declarations. Since EmitFunctionStart()
1758/// needs to find the canonical declaration for each method, we need
1759/// to construct the complete type prior to emitting the method.
1760void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1761 if (!D->isInstance())
1762 return;
1763
1764 if (CGDebugInfo *DI = getModuleDebugInfo())
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001765 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001766 const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
Adrian Prantl0a050f72013-05-09 23:16:27 +00001767 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1768 }
1769}
1770
Stephen Hines651f13c2014-04-23 16:59:28 -07001771void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001772 const auto *D = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Dan Gohmancb421fa2010-04-19 16:39:44 +00001774 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson8e2efcc2009-10-27 14:32:27 +00001775 Context.getSourceManager(),
1776 "Generating code for declaration");
1777
Peter Collingbourne144a31f2013-06-05 17:49:37 +00001778 if (isa<FunctionDecl>(D)) {
Douglas Gregor44eac332010-07-13 06:02:28 +00001779 // At -O0, don't generate IR for functions with available_externally
1780 // linkage.
Peter Collingbourne144a31f2013-06-05 17:49:37 +00001781 if (!shouldEmitFunction(GD))
Douglas Gregor44eac332010-07-13 06:02:28 +00001782 return;
Anders Carlsson7270ee42010-03-23 04:31:31 +00001783
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001784 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
Adrian Prantl0a050f72013-05-09 23:16:27 +00001785 CompleteDIClassType(Method);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001786 // Make sure to emit the definition(s) before we emit the thunks.
1787 // This is necessary for the generation of certain thunks.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001788 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
Stephen Hines176edba2014-12-01 14:53:08 -08001789 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001790 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
Stephen Hines176edba2014-12-01 14:53:08 -08001791 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001792 else
Stephen Hines651f13c2014-04-23 16:59:28 -07001793 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001794
Douglas Gregor44eac332010-07-13 06:02:28 +00001795 if (Method->isVirtual())
1796 getVTables().EmitThunks(GD);
1797
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001798 return;
Douglas Gregor44eac332010-07-13 06:02:28 +00001799 }
Chris Lattnerb5e81562010-04-13 17:57:11 +00001800
Stephen Hines651f13c2014-04-23 16:59:28 -07001801 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregor44eac332010-07-13 06:02:28 +00001802 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001803
1804 if (const auto *VD = dyn_cast<VarDecl>(D))
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001805 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
Chris Lattner4357a822010-04-13 17:39:09 +00001806
David Blaikieb219cfc2011-09-23 05:06:16 +00001807 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001808}
1809
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001810static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1811 llvm::Function *NewFn);
1812
Chris Lattner74391b42009-03-22 21:03:39 +00001813/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1814/// module, create and return an llvm Function with the specified type. If there
1815/// is something in the module with the specified name, return it potentially
1816/// bitcasted to the right type.
1817///
1818/// If D is non-null, it specifies a decl that correspond to this. This is used
1819/// to set the attributes on the function when it is first created.
John McCallf746aa62010-03-19 23:29:14 +00001820llvm::Constant *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001821CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001822 llvm::Type *Ty,
Reid Kleckner73701ea2013-07-22 13:07:10 +00001823 GlobalDecl GD, bool ForVTable,
Stephen Hines176edba2014-12-01 14:53:08 -08001824 bool DontDefer, bool IsThunk,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001825 llvm::AttributeSet ExtraAttrs,
1826 bool IsForDefinition) {
Reid Kleckner73701ea2013-07-22 13:07:10 +00001827 const Decl *D = GD.getDecl();
1828
Chris Lattner0558e792009-03-21 09:25:43 +00001829 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +00001830 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner0558e792009-03-21 09:25:43 +00001831 if (Entry) {
Benjamin Kramerd48bcb22012-08-22 15:37:55 +00001832 if (WeakRefReferences.erase(Entry)) {
Reid Kleckner73701ea2013-07-22 13:07:10 +00001833 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola6a836702010-03-04 18:17:24 +00001834 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +00001835 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +00001836 }
1837
Stephen Hines176edba2014-12-01 14:53:08 -08001838 // Handle dropped DLL attributes.
1839 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1840 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1841
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001842 // If there are two attempts to define the same mangled name, issue an
1843 // error.
1844 if (IsForDefinition && !Entry->isDeclaration()) {
1845 GlobalDecl OtherGD;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001846 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
1847 // to make sure that we issue an error only once.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001848 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
1849 (GD.getCanonicalDecl().getDecl() !=
1850 OtherGD.getCanonicalDecl().getDecl()) &&
1851 DiagnosedConflictingDefinitions.insert(GD).second) {
1852 getDiags().Report(D->getLocation(),
1853 diag::err_duplicate_mangled_name);
1854 getDiags().Report(OtherGD.getDecl()->getLocation(),
1855 diag::note_previous_definition);
1856 }
1857 }
1858
1859 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
1860 (Entry->getType()->getElementType() == Ty)) {
Chris Lattner0558e792009-03-21 09:25:43 +00001861 return Entry;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001862 }
Mike Stump1eb44332009-09-09 15:08:12 +00001863
Chris Lattner0558e792009-03-21 09:25:43 +00001864 // Make sure the result is of the correct type.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001865 // (If function is requested for a definition, we always need to create a new
1866 // function, not just return a bitcast.)
1867 if (!IsForDefinition)
1868 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattner0558e792009-03-21 09:25:43 +00001869 }
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Eli Friedman654ad402009-11-09 05:07:37 +00001871 // This function doesn't have a complete type (for example, the return
1872 // type is an incomplete struct). Use a fake type instead, and make
1873 // sure not to try to set attributes.
1874 bool IsIncompleteFunction = false;
John McCall784f2112010-04-28 00:00:30 +00001875
Chris Lattner2acc6e32011-07-18 04:24:23 +00001876 llvm::FunctionType *FTy;
John McCall784f2112010-04-28 00:00:30 +00001877 if (isa<llvm::FunctionType>(Ty)) {
1878 FTy = cast<llvm::FunctionType>(Ty);
1879 } else {
John McCall0774cb82011-05-15 01:53:33 +00001880 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedman654ad402009-11-09 05:07:37 +00001881 IsIncompleteFunction = true;
1882 }
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001883
1884 llvm::Function *F =
1885 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
1886 Entry ? StringRef() : MangledName, &getModule());
1887
1888 // If we already created a function with the same mangled name (but different
1889 // type) before, take its name and add it to the list of functions to be
1890 // replaced with F at the end of CodeGen.
1891 //
1892 // This happens if there is a prototype for a function (e.g. "int f()") and
1893 // then a definition of a different type (e.g. "int f(int x)").
1894 if (Entry) {
1895 F->takeName(Entry);
1896
1897 // This might be an implementation of a function without a prototype, in
1898 // which case, try to do special replacement of calls which match the new
1899 // prototype. The really key thing here is that we also potentially drop
1900 // arguments from the call site so as to make a direct call, which makes the
1901 // inliner happier and suppresses a number of optimizer warnings (!) about
1902 // dropping arguments.
1903 if (!Entry->use_empty()) {
1904 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
1905 Entry->removeDeadConstantUsers();
1906 }
1907
1908 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
1909 F, Entry->getType()->getElementType()->getPointerTo());
1910 addGlobalValReplacement(Entry, BC);
1911 }
1912
John McCallf746aa62010-03-19 23:29:14 +00001913 assert(F->getName() == MangledName && "name was uniqued!");
Reid Kleckner73701ea2013-07-22 13:07:10 +00001914 if (D)
Stephen Hines176edba2014-12-01 14:53:08 -08001915 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001916 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1917 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
Bill Wendling909b6de2013-01-23 00:21:06 +00001918 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1919 llvm::AttributeSet::get(VMContext,
1920 llvm::AttributeSet::FunctionIndex,
1921 B));
1922 }
Eli Friedman654ad402009-11-09 05:07:37 +00001923
Stephen Hines651f13c2014-04-23 16:59:28 -07001924 if (!DontDefer) {
1925 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1926 // each other bottoming out with the base dtor. Therefore we emit non-base
1927 // dtors on usage, even if there is no dtor definition in the TU.
1928 if (D && isa<CXXDestructorDecl>(D) &&
1929 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1930 GD.getDtorType()))
1931 addDeferredDeclToEmit(F, GD);
John McCallbfdcdc82010-12-15 04:00:32 +00001932
Stephen Hines651f13c2014-04-23 16:59:28 -07001933 // This is the first use or definition of a mangled name. If there is a
1934 // deferred decl with this name, remember that we need to emit it at the end
1935 // of the file.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001936 auto DDI = DeferredDecls.find(MangledName);
Stephen Hines651f13c2014-04-23 16:59:28 -07001937 if (DDI != DeferredDecls.end()) {
1938 // Move the potentially referenced deferred decl to the
1939 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1940 // don't need it anymore).
1941 addDeferredDeclToEmit(F, DDI->second);
1942 DeferredDecls.erase(DDI);
Stephen Hines651f13c2014-04-23 16:59:28 -07001943
1944 // Otherwise, there are cases we have to worry about where we're
1945 // using a declaration for which we must emit a definition but where
1946 // we might not find a top-level definition:
1947 // - member functions defined inline in their classes
1948 // - friend functions defined inline in some class
1949 // - special member functions with implicit definitions
1950 // If we ever change our AST traversal to walk into class methods,
1951 // this will be unnecessary.
1952 //
1953 // We also don't emit a definition for a function if it's going to be an
Stephen Hines176edba2014-12-01 14:53:08 -08001954 // entry in a vtable, unless it's already marked as used.
Stephen Hines651f13c2014-04-23 16:59:28 -07001955 } else if (getLangOpts().CPlusPlus && D) {
1956 // Look for a declaration that's lexically in a record.
Stephen Hines176edba2014-12-01 14:53:08 -08001957 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
1958 FD = FD->getPreviousDecl()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001959 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Stephen Hines176edba2014-12-01 14:53:08 -08001960 if (FD->doesThisDeclarationHaveABody()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001961 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1962 break;
1963 }
John McCallbfdcdc82010-12-15 04:00:32 +00001964 }
Stephen Hines176edba2014-12-01 14:53:08 -08001965 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001966 }
Chris Lattner67b00522009-03-21 09:44:56 +00001967 }
Mike Stump1eb44332009-09-09 15:08:12 +00001968
John McCall784f2112010-04-28 00:00:30 +00001969 // Make sure the result is of the requested type.
1970 if (!IsIncompleteFunction) {
1971 assert(F->getType()->getElementType() == Ty);
1972 return F;
1973 }
1974
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001975 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCall784f2112010-04-28 00:00:30 +00001976 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +00001977}
1978
Chris Lattner74391b42009-03-22 21:03:39 +00001979/// GetAddrOfFunction - Return the address of the given function. If Ty is
1980/// non-null, then this function will use the specified type if it has to
1981/// create it (this occurs when we see a definition of the function).
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001982llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001983 llvm::Type *Ty,
Stephen Hines651f13c2014-04-23 16:59:28 -07001984 bool ForVTable,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001985 bool DontDefer,
1986 bool IsForDefinition) {
Chris Lattner74391b42009-03-22 21:03:39 +00001987 // If there was no specific requested type, just convert it now.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001988 if (!Ty) {
1989 const auto *FD = cast<FunctionDecl>(GD.getDecl());
1990 auto CanonTy = Context.getCanonicalType(FD->getType());
1991 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
1992 }
1993
Chris Lattner5f9e2722011-07-23 10:55:15 +00001994 StringRef MangledName = getMangledName(GD);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001995 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
1996 /*IsThunk=*/false, llvm::AttributeSet(),
1997 IsForDefinition);
Chris Lattner74391b42009-03-22 21:03:39 +00001998}
Eli Friedman77ba7082008-05-30 19:50:47 +00001999
Chris Lattner74391b42009-03-22 21:03:39 +00002000/// CreateRuntimeFunction - Create a new runtime function with the specified
2001/// type and name.
2002llvm::Constant *
Chris Lattner2acc6e32011-07-18 04:24:23 +00002003CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002004 StringRef Name,
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00002005 llvm::AttributeSet ExtraAttrs) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002006 llvm::Constant *C =
2007 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
Stephen Hines176edba2014-12-01 14:53:08 -08002008 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002009 if (auto *F = dyn_cast<llvm::Function>(C))
John McCallbd7370a2013-02-28 19:01:20 +00002010 if (F->empty())
2011 F->setCallingConv(getRuntimeCC());
2012 return C;
Chris Lattner74391b42009-03-22 21:03:39 +00002013}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002014
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002015/// CreateBuiltinFunction - Create a new builtin function with the specified
2016/// type and name.
2017llvm::Constant *
2018CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
2019 StringRef Name,
2020 llvm::AttributeSet ExtraAttrs) {
2021 llvm::Constant *C =
2022 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2023 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2024 if (auto *F = dyn_cast<llvm::Function>(C))
2025 if (F->empty())
2026 F->setCallingConv(getBuiltinCC());
2027 return C;
2028}
2029
Richard Smitha9b21d22012-02-17 06:48:11 +00002030/// isTypeConstant - Determine whether an object of this type can be emitted
2031/// as a constant.
2032///
2033/// If ExcludeCtor is true, the duration when the object's constructor runs
2034/// will not be considered. The caller will need to verify that the object is
2035/// not written to during its construction.
2036bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2037 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedman20e098b2009-12-11 21:23:03 +00002038 return false;
Richard Smitha9b21d22012-02-17 06:48:11 +00002039
David Blaikie4e4d0842012-03-11 07:00:24 +00002040 if (Context.getLangOpts().CPlusPlus) {
Richard Smitha9b21d22012-02-17 06:48:11 +00002041 if (const CXXRecordDecl *Record
2042 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2043 return ExcludeCtor && !Record->hasMutableFields() &&
2044 Record->hasTrivialDestructor();
Eli Friedman20e098b2009-12-11 21:23:03 +00002045 }
Richard Smitha9b21d22012-02-17 06:48:11 +00002046
Eli Friedman20e098b2009-12-11 21:23:03 +00002047 return true;
2048}
2049
Chris Lattner74391b42009-03-22 21:03:39 +00002050/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2051/// create and return an llvm GlobalVariable with the specified type. If there
2052/// is something in the module with the specified name, return it potentially
2053/// bitcasted to the right type.
2054///
2055/// If D is non-null, it specifies a decl that correspond to this. This is used
2056/// to set the attributes on the global when it is first created.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002057///
2058/// If IsForDefinition is true, it is guranteed that an actual global with
2059/// type Ty will be returned, not conversion of a variable with the same
2060/// mangled name but some other type.
John McCallf746aa62010-03-19 23:29:14 +00002061llvm::Constant *
Chris Lattner5f9e2722011-07-23 10:55:15 +00002062CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2acc6e32011-07-18 04:24:23 +00002063 llvm::PointerType *Ty,
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002064 const VarDecl *D,
2065 bool IsForDefinition) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +00002066 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +00002067 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +00002068 if (Entry) {
Benjamin Kramerd48bcb22012-08-22 15:37:55 +00002069 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola6a836702010-03-04 18:17:24 +00002070 if (D && !D->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +00002071 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +00002072 }
2073
Stephen Hines176edba2014-12-01 14:53:08 -08002074 // Handle dropped DLL attributes.
2075 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2076 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2077
Chris Lattner74391b42009-03-22 21:03:39 +00002078 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +00002079 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002081 // If there are two attempts to define the same mangled name, issue an
2082 // error.
2083 if (IsForDefinition && !Entry->isDeclaration()) {
2084 GlobalDecl OtherGD;
2085 const VarDecl *OtherD;
2086
2087 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2088 // to make sure that we issue an error only once.
2089 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2090 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2091 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2092 OtherD->hasInit() &&
2093 DiagnosedConflictingDefinitions.insert(D).second) {
2094 getDiags().Report(D->getLocation(),
2095 diag::err_duplicate_mangled_name);
2096 getDiags().Report(OtherGD.getDecl()->getLocation(),
2097 diag::note_previous_definition);
2098 }
2099 }
2100
Chris Lattner99b53612009-03-21 08:03:33 +00002101 // Make sure the result is of the correct type.
Matt Arsenault54307da2013-11-15 02:19:52 +00002102 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2103 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2104
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002105 // (If global is requested for a definition, we always need to create a new
2106 // global, not just return a bitcast.)
2107 if (!IsForDefinition)
2108 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +00002109 }
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Stephen Hines651f13c2014-04-23 16:59:28 -07002111 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002112 auto *GV = new llvm::GlobalVariable(
2113 getModule(), Ty->getElementType(), false,
2114 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2115 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
Stephen Hines651f13c2014-04-23 16:59:28 -07002116
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002117 // If we already created a global with the same mangled name (but different
2118 // type) before, take its name and remove it from its parent.
2119 if (Entry) {
2120 GV->takeName(Entry);
2121
2122 if (!Entry->use_empty()) {
2123 llvm::Constant *NewPtrForOldDecl =
2124 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2125 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2126 }
2127
2128 Entry->eraseFromParent();
2129 }
2130
Chris Lattner67b00522009-03-21 09:44:56 +00002131 // This is the first use or definition of a mangled name. If there is a
2132 // deferred decl with this name, remember that we need to emit it at the end
2133 // of the file.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002134 auto DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +00002135 if (DDI != DeferredDecls.end()) {
2136 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2137 // list, and remove it from DeferredDecls (since we don't need it anymore).
Stephen Hines651f13c2014-04-23 16:59:28 -07002138 addDeferredDeclToEmit(GV, DDI->second);
Chris Lattner67b00522009-03-21 09:44:56 +00002139 DeferredDecls.erase(DDI);
2140 }
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Chris Lattner99b53612009-03-21 08:03:33 +00002142 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +00002143 if (D) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00002144 // FIXME: This code is overly simple and should be merged with other global
2145 // handling.
Richard Smitha9b21d22012-02-17 06:48:11 +00002146 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner99b53612009-03-21 08:03:33 +00002147
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07002148 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2149
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002150 setLinkageAndVisibilityForGV(GV, D);
Eli Friedman56ebe502009-04-19 21:05:03 +00002151
Richard Smithb80a16e2013-04-19 16:42:07 +00002152 if (D->getTLSKind()) {
Richard Smithdb4f61f2013-04-22 08:06:17 +00002153 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002154 CXXThreadLocals.push_back(D);
Hans Wennborgde981f32012-06-28 08:01:44 +00002155 setTLSMode(GV, *D);
Richard Smithb80a16e2013-04-19 16:42:07 +00002156 }
Bill Wendling0cbb3ed2013-11-21 05:19:27 +00002157
2158 // If required by the ABI, treat declarations of static data members with
2159 // inline initializers as definitions.
Stephen Hines176edba2014-12-01 14:53:08 -08002160 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
Bill Wendling0cbb3ed2013-11-21 05:19:27 +00002161 EmitGlobalVarDefinition(D);
Stephen Hines176edba2014-12-01 14:53:08 -08002162 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002163
2164 // Handle XCore specific ABI requirements.
2165 if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
2166 D->getLanguageLinkage() == CLanguageLinkage &&
2167 D->getType().isConstant(Context) &&
2168 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2169 GV->setSection(".cp.rodata");
Chris Lattner74391b42009-03-22 21:03:39 +00002170 }
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00002172 if (AddrSpace != Ty->getAddressSpace())
Matt Arsenault54307da2013-11-15 02:19:52 +00002173 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2174
2175 return GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002176}
2177
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002178llvm::Constant *
2179CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
2180 bool IsForDefinition) {
2181 if (isa<CXXConstructorDecl>(GD.getDecl()))
2182 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()),
2183 getFromCtorType(GD.getCtorType()),
2184 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2185 /*DontDefer=*/false, IsForDefinition);
2186 else if (isa<CXXDestructorDecl>(GD.getDecl()))
2187 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()),
2188 getFromDtorType(GD.getDtorType()),
2189 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2190 /*DontDefer=*/false, IsForDefinition);
2191 else if (isa<CXXMethodDecl>(GD.getDecl())) {
2192 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
2193 cast<CXXMethodDecl>(GD.getDecl()));
2194 auto Ty = getTypes().GetFunctionType(*FInfo);
2195 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2196 IsForDefinition);
2197 } else if (isa<FunctionDecl>(GD.getDecl())) {
2198 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2199 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2200 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2201 IsForDefinition);
2202 } else
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002203 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()), /*Ty=*/nullptr,
2204 IsForDefinition);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002205}
Chris Lattner74391b42009-03-22 21:03:39 +00002206
Anders Carlsson3bd62022011-01-29 18:20:20 +00002207llvm::GlobalVariable *
Chris Lattner5f9e2722011-07-23 10:55:15 +00002208CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2acc6e32011-07-18 04:24:23 +00002209 llvm::Type *Ty,
Anders Carlsson3bd62022011-01-29 18:20:20 +00002210 llvm::GlobalValue::LinkageTypes Linkage) {
2211 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002212 llvm::GlobalVariable *OldGV = nullptr;
Anders Carlsson3bd62022011-01-29 18:20:20 +00002213
Anders Carlsson3bd62022011-01-29 18:20:20 +00002214 if (GV) {
2215 // Check if the variable has the right type.
2216 if (GV->getType()->getElementType() == Ty)
2217 return GV;
2218
2219 // Because C++ name mangling, the only way we can end up with an already
2220 // existing global with the same name is if it has been declared extern "C".
Nico Weberc5f80462012-10-11 10:13:44 +00002221 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlsson3bd62022011-01-29 18:20:20 +00002222 OldGV = GV;
2223 }
2224
2225 // Create a new variable.
2226 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002227 Linkage, nullptr, Name);
2228
Anders Carlsson3bd62022011-01-29 18:20:20 +00002229 if (OldGV) {
2230 // Replace occurrences of the old variable if needed.
2231 GV->takeName(OldGV);
2232
2233 if (!OldGV->use_empty()) {
2234 llvm::Constant *NewPtrForOldDecl =
2235 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2236 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2237 }
2238
2239 OldGV->eraseFromParent();
2240 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002241
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07002242 if (supportsCOMDAT() && GV->isWeakForLinker() &&
2243 !GV->hasAvailableExternallyLinkage())
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002244 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2245
Anders Carlsson3bd62022011-01-29 18:20:20 +00002246 return GV;
2247}
2248
Chris Lattner74391b42009-03-22 21:03:39 +00002249/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2250/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher0ff258b2012-04-16 23:55:04 +00002251/// then it will be created with the specified type instead of whatever the
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002252/// normal requested type would be. If IsForDefinition is true, it is guranteed
2253/// that an actual global with type Ty will be returned, not conversion of a
2254/// variable with the same mangled name but some other type.
Chris Lattner74391b42009-03-22 21:03:39 +00002255llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002256 llvm::Type *Ty,
2257 bool IsForDefinition) {
Chris Lattner74391b42009-03-22 21:03:39 +00002258 assert(D->hasGlobalStorage() && "Not a global variable");
2259 QualType ASTTy = D->getType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002260 if (!Ty)
Chris Lattner74391b42009-03-22 21:03:39 +00002261 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002262
Chris Lattner2acc6e32011-07-18 04:24:23 +00002263 llvm::PointerType *PTy =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00002264 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCallf746aa62010-03-19 23:29:14 +00002265
Chris Lattner5f9e2722011-07-23 10:55:15 +00002266 StringRef MangledName = getMangledName(D);
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002267 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
Chris Lattner74391b42009-03-22 21:03:39 +00002268}
2269
2270/// CreateRuntimeVariable - Create a new runtime global variable with the
2271/// specified type and name.
2272llvm::Constant *
Chris Lattner2acc6e32011-07-18 04:24:23 +00002273CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002274 StringRef Name) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002275 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
Chris Lattner74391b42009-03-22 21:03:39 +00002276}
2277
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00002278void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2279 assert(!D->getInit() && "Cannot emit definite definitions here!");
2280
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002281 StringRef MangledName = getMangledName(D);
2282 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2283
2284 // We already have a definition, not declaration, with the same mangled name.
2285 // Emitting of declaration is not required (and actually overwrites emitted
2286 // definition).
2287 if (GV && !GV->isDeclaration())
2288 return;
2289
2290 // If we have not seen a reference to this variable yet, place it into the
2291 // deferred declarations table to be emitted if needed later.
2292 if (!MustBeEmitted(D) && !GV) {
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002293 DeferredDecls[MangledName] = D;
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00002294 return;
Douglas Gregor7520bd12009-04-21 19:28:58 +00002295 }
2296
2297 // The tentative definition is the only definition.
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00002298 EmitGlobalVarDefinition(D);
2299}
2300
Chris Lattner2acc6e32011-07-18 04:24:23 +00002301CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002302 return Context.toCharUnitsFromBits(
2303 getDataLayout().getTypeStoreSizeInBits(Ty));
Ken Dyck687cc4a2010-01-26 13:48:07 +00002304}
2305
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00002306unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
2307 unsigned AddrSpace) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002308 if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00002309 if (D->hasAttr<CUDAConstantAttr>())
2310 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
2311 else if (D->hasAttr<CUDASharedAttr>())
2312 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
2313 else
2314 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
2315 }
2316
2317 return AddrSpace;
2318}
2319
Richard Smith00249372013-04-06 05:00:46 +00002320template<typename SomeDecl>
2321void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2322 llvm::GlobalValue *GV) {
2323 if (!getLangOpts().CPlusPlus)
2324 return;
2325
2326 // Must have 'used' attribute, or else inline assembly can't rely on
2327 // the name existing.
2328 if (!D->template hasAttr<UsedAttr>())
2329 return;
2330
2331 // Must have internal linkage and an ordinary name.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00002332 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smith00249372013-04-06 05:00:46 +00002333 return;
2334
2335 // Must be in an extern "C" context. Entities declared directly within
2336 // a record are not extern "C" even if the record is in such a context.
Rafael Espindolabc650912013-10-17 15:37:26 +00002337 const SomeDecl *First = D->getFirstDecl();
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002338 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smith00249372013-04-06 05:00:46 +00002339 return;
2340
2341 // OK, this is an internal linkage entity inside an extern "C" linkage
2342 // specification. Make a note of that so we can give it the "expected"
2343 // mangled name if nothing else is using that name.
Richard Smith67972042013-04-06 07:07:44 +00002344 std::pair<StaticExternCMap::iterator, bool> R =
2345 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smith00249372013-04-06 05:00:46 +00002346
2347 // If we have multiple internal linkage entities with the same name
2348 // in extern "C" regions, none of them gets that name.
Richard Smith67972042013-04-06 07:07:44 +00002349 if (!R.second)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002350 R.first->second = nullptr;
Richard Smith00249372013-04-06 05:00:46 +00002351}
2352
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002353static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2354 if (!CGM.supportsCOMDAT())
2355 return false;
2356
2357 if (D.hasAttr<SelectAnyAttr>())
2358 return true;
2359
2360 GVALinkage Linkage;
2361 if (auto *VD = dyn_cast<VarDecl>(&D))
2362 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2363 else
2364 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2365
2366 switch (Linkage) {
2367 case GVA_Internal:
2368 case GVA_AvailableExternally:
2369 case GVA_StrongExternal:
2370 return false;
2371 case GVA_DiscardableODR:
2372 case GVA_StrongODR:
2373 return true;
2374 }
2375 llvm_unreachable("No such linkage");
2376}
2377
2378void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2379 llvm::GlobalObject &GO) {
2380 if (!shouldBeInCOMDAT(*this, D))
2381 return;
2382 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2383}
2384
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002385/// Pass IsTentative as true if you want to create a tentative definition.
2386void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2387 bool IsTentative) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002388 llvm::Constant *Init = nullptr;
Eli Friedman77ba7082008-05-30 19:50:47 +00002389 QualType ASTTy = D->getType();
Richard Smith7ca48502012-02-13 22:16:19 +00002390 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2391 bool NeedsGlobalCtor = false;
2392 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump1eb44332009-09-09 15:08:12 +00002393
Richard Smith2d6a5672012-01-14 04:30:29 +00002394 const VarDecl *InitDecl;
2395 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00002396
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002397 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2398 // as part of their declaration." Sema has already checked for
2399 // error cases, so we just need to set Init to UndefValue.
2400 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2401 D->hasAttr<CUDASharedAttr>())
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002402 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002403 else if (!InitExpr) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +00002404 // This is a tentative definition; tentative definitions are
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00002405 // implicitly initialized with { 0 }.
2406 //
2407 // Note that tentative definitions are only emitted at the end of
2408 // a translation unit, so they should never have incomplete
2409 // type. In addition, EmitTentativeDefinition makes sure that we
2410 // never attempt to emit a tentative definition if a real one
2411 // exists. A use may still exists, however, so we still may need
2412 // to do a RAUW.
2413 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonb0d0ea02009-08-02 21:18:22 +00002414 Init = EmitNullConstant(D->getType());
Eli Friedman77ba7082008-05-30 19:50:47 +00002415 } else {
Richard Smith7c3e6152013-06-12 22:31:48 +00002416 initializedGlobalDecl = GlobalDecl(D);
2417 Init = EmitConstantInit(*InitDecl);
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00002418
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00002419 if (!Init) {
Anders Carlsson3bb92692010-01-26 17:43:42 +00002420 QualType T = InitExpr->getType();
Douglas Gregorc446d182010-05-05 20:15:55 +00002421 if (D->getType()->isReferenceType())
2422 T = D->getType();
Richard Smith2d6a5672012-01-14 04:30:29 +00002423
David Blaikie4e4d0842012-03-11 07:00:24 +00002424 if (getLangOpts().CPlusPlus) {
Anders Carlsson89ed31d2009-08-08 23:24:23 +00002425 Init = EmitNullConstant(T);
Richard Smith7ca48502012-02-13 22:16:19 +00002426 NeedsGlobalCtor = true;
Anders Carlsson89ed31d2009-08-08 23:24:23 +00002427 } else {
2428 ErrorUnsupported(D, "static initializer");
2429 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2430 }
John McCallbf40cb52010-07-15 23:40:35 +00002431 } else {
2432 // We don't need an initializer, so remove the entry for the delayed
Richard Smith7ca48502012-02-13 22:16:19 +00002433 // initializer position (just in case this entry was delayed) if we
2434 // also don't need to register a destructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00002435 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCallbf40cb52010-07-15 23:40:35 +00002436 DelayedCXXInitPosition.erase(D);
Eli Friedman6e656f42009-02-20 01:18:21 +00002437 }
Eli Friedman77ba7082008-05-30 19:50:47 +00002438 }
Eli Friedman77ba7082008-05-30 19:50:47 +00002439
Chris Lattner2acc6e32011-07-18 04:24:23 +00002440 llvm::Type* InitType = Init->getType();
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002441 llvm::Constant *Entry =
2442 GetAddrOfGlobalVar(D, InitType, /*IsForDefinition=*/!IsTentative);
Mike Stump1eb44332009-09-09 15:08:12 +00002443
Chris Lattner570585c2009-03-21 09:16:30 +00002444 // Strip off a bitcast if we got one back.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002445 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattner9d4a15f2009-07-16 16:48:25 +00002446 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault54307da2013-11-15 02:19:52 +00002447 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2448 // All zero index gep.
Chris Lattner9d4a15f2009-07-16 16:48:25 +00002449 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner570585c2009-03-21 09:16:30 +00002450 Entry = CE->getOperand(0);
2451 }
Mike Stump1eb44332009-09-09 15:08:12 +00002452
Chris Lattner570585c2009-03-21 09:16:30 +00002453 // Entry is now either a Function or GlobalVariable.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002454 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00002455
Chris Lattner570585c2009-03-21 09:16:30 +00002456 // We have a definition after a declaration with the wrong type.
2457 // We must make a new GlobalVariable* and update everything that used OldGV
2458 // (a declaration or tentative definition) with the new GlobalVariable*
2459 // (which will be a definition).
2460 //
2461 // This happens if there is a prototype for a global (e.g.
2462 // "extern int x[];") and then a definition of a different type (e.g.
2463 // "int x[10];"). This also happens when an initializer has a different type
2464 // from the type of the global (this happens with unions).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002465 if (!GV ||
Chris Lattner570585c2009-03-21 09:16:30 +00002466 GV->getType()->getElementType() != InitType ||
Peter Collingbourne207f4d82011-03-18 22:38:29 +00002467 GV->getType()->getAddressSpace() !=
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00002468 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
Mike Stump1eb44332009-09-09 15:08:12 +00002469
John McCallf746aa62010-03-19 23:29:14 +00002470 // Move the old entry aside so that we'll create a new one.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002471 Entry->setName(StringRef());
Daniel Dunbar232350d2009-02-19 05:36:41 +00002472
Chris Lattner570585c2009-03-21 09:16:30 +00002473 // Make a new global with the correct type, this is now guaranteed to work.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002474 GV = cast<llvm::GlobalVariable>(
2475 GetAddrOfGlobalVar(D, InitType, /*IsForDefinition=*/!IsTentative));
Chris Lattner0558e792009-03-21 09:25:43 +00002476
Eli Friedman77ba7082008-05-30 19:50:47 +00002477 // Replace all uses of the old global with the new global
Mike Stump1eb44332009-09-09 15:08:12 +00002478 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00002479 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner570585c2009-03-21 09:16:30 +00002480 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +00002481
2482 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +00002483 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +00002484 }
Devang Patel8e53e722007-10-26 16:31:40 +00002485
Richard Smith00249372013-04-06 05:00:46 +00002486 MaybeHandleStaticInExternC(D, GV);
2487
Julien Lerouge77f68bb2011-09-09 22:41:49 +00002488 if (D->hasAttr<AnnotateAttr>())
2489 AddGlobalAnnotations(D, GV);
Nate Begeman8bd4afe2008-04-19 04:17:09 +00002490
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002491 // Set the llvm linkage type as appropriate.
2492 llvm::GlobalValue::LinkageTypes Linkage =
2493 getLLVMLinkageVarDefinition(D, GV->isConstant());
2494
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002495 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2496 // the device. [...]"
2497 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2498 // __device__, declares a variable that: [...]
2499 // Is accessible from all the threads within the grid and from the host
2500 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2501 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002502 if (GV && LangOpts.CUDA) {
2503 if (LangOpts.CUDAIsDevice) {
2504 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
2505 GV->setExternallyInitialized(true);
2506 } else {
2507 // Host-side shadows of external declarations of device-side
2508 // global variables become internal definitions. These have to
2509 // be internal in order to prevent name conflicts with global
2510 // host variables with the same name in a different TUs.
2511 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2512 Linkage = llvm::GlobalValue::InternalLinkage;
2513
2514 // Shadow variables and their properties must be registered
2515 // with CUDA runtime.
2516 unsigned Flags = 0;
2517 if (!D->hasDefinition())
2518 Flags |= CGCUDARuntime::ExternDeviceVar;
2519 if (D->hasAttr<CUDAConstantAttr>())
2520 Flags |= CGCUDARuntime::ConstantDeviceVar;
2521 getCUDARuntime().registerDeviceVar(*GV, Flags);
2522 } else if (D->hasAttr<CUDASharedAttr>())
2523 // __shared__ variables are odd. Shadows do get created, but
2524 // they are not registered with the CUDA runtime, so they
2525 // can't really be used to access their device-side
2526 // counterparts. It's not clear yet whether it's nvcc's bug or
2527 // a feature, but we've got to do the same for compatibility.
2528 Linkage = llvm::GlobalValue::InternalLinkage;
2529 }
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002530 }
Chris Lattner88a69ad2007-07-13 05:13:43 +00002531 GV->setInitializer(Init);
Chris Lattnere78b86f2009-08-05 05:20:29 +00002532
2533 // If it is safe to mark the global 'constant', do so now.
Richard Smitha9b21d22012-02-17 06:48:11 +00002534 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2535 isTypeConstant(D->getType(), true));
Mike Stump1eb44332009-09-09 15:08:12 +00002536
Stephen Hines176edba2014-12-01 14:53:08 -08002537 // If it is in a read-only section, mark it 'constant'.
2538 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2539 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2540 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2541 GV->setConstant(true);
2542 }
2543
Ken Dyck8b752f12010-01-27 17:10:57 +00002544 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smitha9b21d22012-02-17 06:48:11 +00002545
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002546
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002547 // On Darwin, if the normal linkage of a C++ thread_local variable is
2548 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
2549 // copies within a linkage unit; otherwise, the backing variable has
2550 // internal linkage and all accesses should just be calls to the
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002551 // Itanium-specified entry point, which has the normal linkage of the
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002552 // variable. This is to preserve the ability to change the implementation
2553 // behind the scenes.
Stephen Hines176edba2014-12-01 14:53:08 -08002554 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002555 Context.getTargetInfo().getTriple().isOSDarwin() &&
2556 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2557 !llvm::GlobalVariable::isWeakLinkage(Linkage))
Stephen Hines176edba2014-12-01 14:53:08 -08002558 Linkage = llvm::GlobalValue::InternalLinkage;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002559
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002560 GV->setLinkage(Linkage);
Stephen Hines651f13c2014-04-23 16:59:28 -07002561 if (D->hasAttr<DLLImportAttr>())
2562 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2563 else if (D->hasAttr<DLLExportAttr>())
2564 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Stephen Hines176edba2014-12-01 14:53:08 -08002565 else
2566 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Bill Wendling0cbb3ed2013-11-21 05:19:27 +00002567
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002568 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnere78b86f2009-08-05 05:20:29 +00002569 // common vars aren't constant even if declared const.
2570 GV->setConstant(false);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +00002571
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002572 setNonAliasAttributes(D, GV);
Daniel Dunbar04d40782009-04-14 06:00:08 +00002573
Stephen Hines176edba2014-12-01 14:53:08 -08002574 if (D->getTLSKind() && !GV->isThreadLocal()) {
2575 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002576 CXXThreadLocals.push_back(D);
Stephen Hines176edba2014-12-01 14:53:08 -08002577 setTLSMode(GV, *D);
2578 }
2579
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002580 maybeSetTrivialComdat(*D, *GV);
2581
John McCall3030eb82010-11-06 09:44:32 +00002582 // Emit the initializer function if necessary.
Richard Smith7ca48502012-02-13 22:16:19 +00002583 if (NeedsGlobalCtor || NeedsGlobalDtor)
2584 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCall3030eb82010-11-06 09:44:32 +00002585
Stephen Hines176edba2014-12-01 14:53:08 -08002586 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
Kostya Serebryany05c5ebc2012-08-21 06:53:28 +00002587
Sanjiv Gupta686226b2008-06-05 08:59:10 +00002588 // Emit global variable debug information.
Eric Christopher73fb3502011-10-13 21:45:18 +00002589 if (CGDebugInfo *DI = getModuleDebugInfo())
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002590 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00002591 DI->EmitGlobalVariable(GV, D);
Chris Lattner88a69ad2007-07-13 05:13:43 +00002592}
Reid Spencer5f016e22007-07-11 17:01:13 +00002593
Stephen Hines176edba2014-12-01 14:53:08 -08002594static bool isVarDeclStrongDefinition(const ASTContext &Context,
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07002595 CodeGenModule &CGM, const VarDecl *D,
2596 bool NoCommon) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002597 // Don't give variables common linkage if -fno-common was specified unless it
2598 // was overridden by a NoCommon attribute.
2599 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2600 return true;
2601
2602 // C11 6.9.2/2:
2603 // A declaration of an identifier for an object that has file scope without
2604 // an initializer, and without a storage-class specifier or with the
2605 // storage-class specifier static, constitutes a tentative definition.
2606 if (D->getInit() || D->hasExternalStorage())
2607 return true;
2608
2609 // A variable cannot be both common and exist in a section.
2610 if (D->hasAttr<SectionAttr>())
2611 return true;
2612
2613 // Thread local vars aren't considered common linkage.
2614 if (D->getTLSKind())
2615 return true;
2616
2617 // Tentative definitions marked with WeakImportAttr are true definitions.
2618 if (D->hasAttr<WeakImportAttr>())
2619 return true;
2620
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07002621 // A variable cannot be both common and exist in a comdat.
2622 if (shouldBeInCOMDAT(CGM, *D))
2623 return true;
2624
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002625 // Declarations with a required alignment do not have common linkage in MSVC
Stephen Hines176edba2014-12-01 14:53:08 -08002626 // mode.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002627 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002628 if (D->hasAttr<AlignedAttr>())
2629 return true;
2630 QualType VarType = D->getType();
2631 if (Context.isAlignmentRequired(VarType))
2632 return true;
2633
2634 if (const auto *RT = VarType->getAs<RecordType>()) {
2635 const RecordDecl *RD = RT->getDecl();
2636 for (const FieldDecl *FD : RD->fields()) {
2637 if (FD->isBitField())
2638 continue;
2639 if (FD->hasAttr<AlignedAttr>())
2640 return true;
2641 if (Context.isAlignmentRequired(FD->getType()))
2642 return true;
2643 }
2644 }
2645 }
Stephen Hines176edba2014-12-01 14:53:08 -08002646
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002647 return false;
2648}
2649
2650llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2651 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002652 if (Linkage == GVA_Internal)
2653 return llvm::Function::InternalLinkage;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002654
2655 if (D->hasAttr<WeakAttr>()) {
2656 if (IsConstantVariable)
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002657 return llvm::GlobalVariable::WeakODRLinkage;
2658 else
2659 return llvm::GlobalVariable::WeakAnyLinkage;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002660 }
2661
2662 // We are guaranteed to have a strong definition somewhere else,
2663 // so we can use available_externally linkage.
2664 if (Linkage == GVA_AvailableExternally)
2665 return llvm::Function::AvailableExternallyLinkage;
2666
2667 // Note that Apple's kernel linker doesn't support symbol
2668 // coalescing, so we need to avoid linkonce and weak linkages there.
2669 // Normally, this means we just map to internal, but for explicit
2670 // instantiations we'll map to external.
2671
2672 // In C++, the compiler has to emit a definition in every translation unit
2673 // that references the function. We should use linkonce_odr because
2674 // a) if all references in this translation unit are optimized away, we
2675 // don't need to codegen it. b) if the function persists, it needs to be
2676 // merged with other definitions. c) C++ has the ODR, so we know the
2677 // definition is dependable.
2678 if (Linkage == GVA_DiscardableODR)
2679 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2680 : llvm::Function::InternalLinkage;
2681
2682 // An explicit instantiation of a template has weak linkage, since
2683 // explicit instantiations can occur in multiple translation units
2684 // and must all be equivalent. However, we are not allowed to
2685 // throw away these explicit instantiations.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002686 //
2687 // We don't currently support CUDA device code spread out across multiple TUs,
2688 // so say that CUDA templates are either external (for kernels) or internal.
2689 // This lets llvm perform aggressive inter-procedural optimizations.
2690 if (Linkage == GVA_StrongODR) {
2691 if (Context.getLangOpts().AppleKext)
2692 return llvm::Function::ExternalLinkage;
2693 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2694 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2695 : llvm::Function::InternalLinkage;
2696 return llvm::Function::WeakODRLinkage;
2697 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002698
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002699 // C++ doesn't have tentative definitions and thus cannot have common
2700 // linkage.
2701 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07002702 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
Stephen Hines176edba2014-12-01 14:53:08 -08002703 CodeGenOpts.NoCommon))
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002704 return llvm::GlobalVariable::CommonLinkage;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002705
2706 // selectany symbols are externally visible, so use weak instead of
2707 // linkonce. MSVC optimizes away references to const selectany globals, so
2708 // all definitions should be the same and ODR linkage should be used.
2709 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2710 if (D->hasAttr<SelectAnyAttr>())
2711 return llvm::GlobalVariable::WeakODRLinkage;
2712
2713 // Otherwise, we have strong external linkage.
2714 assert(Linkage == GVA_StrongExternal);
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002715 return llvm::GlobalVariable::ExternalLinkage;
2716}
2717
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002718llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2719 const VarDecl *VD, bool IsConstant) {
2720 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2721 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2722}
2723
John McCalla923c972012-12-12 22:21:47 +00002724/// Replace the uses of a function that was declared with a non-proto type.
2725/// We want to silently drop extra arguments from call sites
2726static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2727 llvm::Function *newFn) {
2728 // Fast path.
2729 if (old->use_empty()) return;
2730
2731 llvm::Type *newRetTy = newFn->getReturnType();
2732 SmallVector<llvm::Value*, 4> newArgs;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002733 SmallVector<llvm::OperandBundleDef, 1> newBundles;
John McCalla923c972012-12-12 22:21:47 +00002734
2735 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2736 ui != ue; ) {
2737 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Stephen Hines651f13c2014-04-23 16:59:28 -07002738 llvm::User *user = use->getUser();
John McCalla923c972012-12-12 22:21:47 +00002739
2740 // Recognize and replace uses of bitcasts. Most calls to
2741 // unprototyped functions will use bitcasts.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002742 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
John McCalla923c972012-12-12 22:21:47 +00002743 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2744 replaceUsesOfNonProtoConstant(bitcast, newFn);
2745 continue;
2746 }
2747
2748 // Recognize calls to the function.
2749 llvm::CallSite callSite(user);
2750 if (!callSite) continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07002751 if (!callSite.isCallee(&*use)) continue;
John McCalla923c972012-12-12 22:21:47 +00002752
2753 // If the return types don't match exactly, then we can't
2754 // transform this call unless it's dead.
2755 if (callSite->getType() != newRetTy && !callSite->use_empty())
2756 continue;
2757
2758 // Get the call site's attribute list.
Bill Wendlingb263bdf2013-01-27 02:46:53 +00002759 SmallVector<llvm::AttributeSet, 8> newAttrs;
John McCalla923c972012-12-12 22:21:47 +00002760 llvm::AttributeSet oldAttrs = callSite.getAttributes();
2761
2762 // Collect any return attributes from the call.
Bill Wendlinga37ce612013-01-21 21:57:40 +00002763 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
Bill Wendlinged01f842013-01-21 22:45:00 +00002764 newAttrs.push_back(
Bill Wendlingb263bdf2013-01-27 02:46:53 +00002765 llvm::AttributeSet::get(newFn->getContext(),
2766 oldAttrs.getRetAttributes()));
John McCalla923c972012-12-12 22:21:47 +00002767
2768 // If the function was passed too few arguments, don't transform.
2769 unsigned newNumArgs = newFn->arg_size();
2770 if (callSite.arg_size() < newNumArgs) continue;
2771
2772 // If extra arguments were passed, we silently drop them.
2773 // If any of the types mismatch, we don't transform.
2774 unsigned argNo = 0;
2775 bool dontTransform = false;
2776 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2777 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2778 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2779 dontTransform = true;
2780 break;
2781 }
2782
2783 // Add any parameter attributes.
Bill Wendling89530e42013-01-23 06:15:10 +00002784 if (oldAttrs.hasAttributes(argNo + 1))
2785 newAttrs.
Bill Wendlingb263bdf2013-01-27 02:46:53 +00002786 push_back(llvm::
2787 AttributeSet::get(newFn->getContext(),
2788 oldAttrs.getParamAttributes(argNo + 1)));
John McCalla923c972012-12-12 22:21:47 +00002789 }
2790 if (dontTransform)
2791 continue;
2792
Bill Wendlinge67e4c92013-01-18 21:26:07 +00002793 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
Bill Wendlingb263bdf2013-01-27 02:46:53 +00002794 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2795 oldAttrs.getFnAttributes()));
John McCalla923c972012-12-12 22:21:47 +00002796
2797 // Okay, we can transform this. Create the new call instruction and copy
2798 // over the required information.
2799 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2800
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002801 // Copy over any operand bundles.
2802 callSite.getOperandBundlesAsDefs(newBundles);
2803
John McCalla923c972012-12-12 22:21:47 +00002804 llvm::CallSite newCall;
2805 if (callSite.isCall()) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002806 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
John McCalla923c972012-12-12 22:21:47 +00002807 callSite.getInstruction());
2808 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002809 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
John McCalla923c972012-12-12 22:21:47 +00002810 newCall = llvm::InvokeInst::Create(newFn,
2811 oldInvoke->getNormalDest(),
2812 oldInvoke->getUnwindDest(),
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002813 newArgs, newBundles, "",
John McCalla923c972012-12-12 22:21:47 +00002814 callSite.getInstruction());
2815 }
2816 newArgs.clear(); // for the next iteration
2817
2818 if (!newCall->getType()->isVoidTy())
2819 newCall->takeName(callSite.getInstruction());
2820 newCall.setAttributes(
2821 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2822 newCall.setCallingConv(callSite.getCallingConv());
2823
2824 // Finally, remove the old call, replacing any uses with the new one.
2825 if (!callSite->use_empty())
2826 callSite->replaceAllUsesWith(newCall.getInstruction());
2827
2828 // Copy debug location attached to CI.
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07002829 if (callSite->getDebugLoc())
John McCalla923c972012-12-12 22:21:47 +00002830 newCall->setDebugLoc(callSite->getDebugLoc());
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002831
John McCalla923c972012-12-12 22:21:47 +00002832 callSite->eraseFromParent();
2833 }
2834}
2835
Chris Lattnerbdb01322009-05-05 06:16:31 +00002836/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2837/// implement a function with no prototype, e.g. "int foo() {}". If there are
2838/// existing call uses of the old function in the module, this adjusts them to
2839/// call the new function directly.
2840///
2841/// This is not just a cleanup: the always_inline pass requires direct calls to
2842/// functions to be able to inline them. If there is a bitcast in the way, it
2843/// won't inline them. Instcombine normally deletes these calls, but it isn't
2844/// run at -O0.
2845static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2846 llvm::Function *NewFn) {
2847 // If we're redefining a global as a function, don't transform it.
John McCalla923c972012-12-12 22:21:47 +00002848 if (!isa<llvm::Function>(Old)) return;
Mike Stump1eb44332009-09-09 15:08:12 +00002849
John McCalla923c972012-12-12 22:21:47 +00002850 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattnerbdb01322009-05-05 06:16:31 +00002851}
2852
Rafael Espindola02503932012-03-08 15:51:03 +00002853void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002854 auto DK = VD->isThisDeclarationADefinition();
2855 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
2856 return;
2857
Rafael Espindola02503932012-03-08 15:51:03 +00002858 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2859 // If we have a definition, this might be a deferred decl. If the
2860 // instantiation is explicit, make sure we emit it at the end.
2861 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2862 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00002863
2864 EmitTopLevelDecl(VD);
Rafael Espindola234fe652012-03-05 10:54:55 +00002865}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002866
Stephen Hines651f13c2014-04-23 16:59:28 -07002867void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2868 llvm::GlobalValue *GV) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002869 const auto *D = cast<FunctionDecl>(GD.getDecl());
John McCalld26bc762011-03-09 04:27:21 +00002870
John McCall1f6f9612011-03-09 08:12:35 +00002871 // Compute the function info and LLVM type.
John McCallde5d3c72012-02-17 03:33:10 +00002872 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2873 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalld26bc762011-03-09 04:27:21 +00002874
Chris Lattner9fa959d2009-05-12 20:58:15 +00002875 // Get or create the prototype for the function.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002876 if (!GV || (GV->getType()->getElementType() != Ty))
2877 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
2878 /*DontDefer=*/true,
2879 /*IsForDefinition=*/true));
Mike Stump1eb44332009-09-09 15:08:12 +00002880
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002881 // Already emitted.
2882 if (!GV->isDeclaration())
Bill Wendlinga36ef5b2013-11-25 07:42:52 +00002883 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002884
John McCall112c9672010-11-02 21:04:24 +00002885 // We need to set linkage and visibility on the function before
2886 // generating code for it because various parts of IR generation
2887 // want to propagate this information down (e.g. to local static
2888 // declarations).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002889 auto *Fn = cast<llvm::Function>(GV);
Peter Collingbourne144a31f2013-06-05 17:49:37 +00002890 setFunctionLinkage(GD, Fn);
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07002891 setFunctionDLLStorageClass(GD, Fn);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002892
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002893 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
Anders Carlsson0ffeaad2011-01-29 19:39:23 +00002894 setGlobalVisibility(Fn, D);
John McCall112c9672010-11-02 21:04:24 +00002895
Richard Smith00249372013-04-06 05:00:46 +00002896 MaybeHandleStaticInExternC(D, Fn);
2897
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002898 maybeSetTrivialComdat(*D, *Fn);
2899
John McCalld26bc762011-03-09 04:27:21 +00002900 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +00002901
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002902 setFunctionDefinitionAttributes(D, Fn);
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002903 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump1eb44332009-09-09 15:08:12 +00002904
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002905 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00002906 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002907 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00002908 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge77f68bb2011-09-09 22:41:49 +00002909 if (D->hasAttr<AnnotateAttr>())
2910 AddGlobalAnnotations(D, Fn);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002911}
Stephen Hines651f13c2014-04-23 16:59:28 -07002912
John McCallf746aa62010-03-19 23:29:14 +00002913void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002914 const auto *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002915 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattnerbd532712009-03-22 21:47:11 +00002916 assert(AA && "Not an alias?");
2917
Chris Lattner5f9e2722011-07-23 10:55:15 +00002918 StringRef MangledName = getMangledName(GD);
Mike Stump1eb44332009-09-09 15:08:12 +00002919
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002920 if (AA->getAliasee() == MangledName) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002921 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002922 return;
2923 }
2924
John McCallf746aa62010-03-19 23:29:14 +00002925 // If there is a definition in the module, then it wins over the alias.
2926 // This is dubious, but allow it to be safe. Just ignore the alias.
2927 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2928 if (Entry && !Entry->isDeclaration())
2929 return;
2930
Rafael Espindolad2054982013-10-22 19:26:13 +00002931 Aliases.push_back(GD);
2932
Chris Lattner2acc6e32011-07-18 04:24:23 +00002933 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattnerbd532712009-03-22 21:47:11 +00002934
2935 // Create a reference to the named value. This ensures that it is emitted
2936 // if a deferred decl.
2937 llvm::Constant *Aliasee;
2938 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergc857ce82012-10-05 23:12:53 +00002939 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson1faa89f2011-02-05 04:35:53 +00002940 /*ForVTable=*/false);
Chris Lattnerbd532712009-03-22 21:47:11 +00002941 else
John McCallf746aa62010-03-19 23:29:14 +00002942 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002943 llvm::PointerType::getUnqual(DeclTy),
Stephen Hines176edba2014-12-01 14:53:08 -08002944 /*D=*/nullptr);
Chris Lattnerbd532712009-03-22 21:47:11 +00002945
2946 // Create the new alias itself, but don't set a name yet.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002947 auto *GA = llvm::GlobalAlias::create(
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002948 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
Mike Stump1eb44332009-09-09 15:08:12 +00002949
Chris Lattnerbd532712009-03-22 21:47:11 +00002950 if (Entry) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002951 if (GA->getAliasee() == Entry) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002952 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002953 return;
2954 }
2955
John McCallf746aa62010-03-19 23:29:14 +00002956 assert(Entry->isDeclaration());
2957
Chris Lattnerbd532712009-03-22 21:47:11 +00002958 // If there is a declaration in the module, then we had an extern followed
2959 // by the alias, as in:
2960 // extern int test6();
2961 // ...
2962 // int test6() __attribute__((alias("test7")));
2963 //
2964 // Remove it and replace uses of it with the alias.
John McCallf746aa62010-03-19 23:29:14 +00002965 GA->takeName(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00002966
Owen Anderson3c4972d2009-07-29 18:54:39 +00002967 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattnerbd532712009-03-22 21:47:11 +00002968 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +00002969 Entry->eraseFromParent();
John McCallf746aa62010-03-19 23:29:14 +00002970 } else {
Anders Carlsson9a20d552010-06-22 16:16:50 +00002971 GA->setName(MangledName);
Chris Lattnerbd532712009-03-22 21:47:11 +00002972 }
Mike Stump1eb44332009-09-09 15:08:12 +00002973
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002974 // Set attributes which are particular to an alias; this is a
2975 // specialization of the attributes which may be set on a global
2976 // variable/function.
Stephen Hines176edba2014-12-01 14:53:08 -08002977 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
2978 D->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002979 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2980 }
2981
Stephen Hines176edba2014-12-01 14:53:08 -08002982 if (const auto *VD = dyn_cast<VarDecl>(D))
2983 if (VD->getTLSKind())
2984 setTLSMode(GA, *VD);
2985
2986 setAliasAttributes(D, GA);
Chris Lattnerbd532712009-03-22 21:47:11 +00002987}
2988
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002989void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
2990 const auto *D = cast<ValueDecl>(GD.getDecl());
2991 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
2992 assert(IFA && "Not an ifunc?");
2993
2994 StringRef MangledName = getMangledName(GD);
2995
2996 if (IFA->getResolver() == MangledName) {
2997 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
2998 return;
2999 }
3000
3001 // Report an error if some definition overrides ifunc.
3002 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3003 if (Entry && !Entry->isDeclaration()) {
3004 GlobalDecl OtherGD;
3005 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3006 DiagnosedConflictingDefinitions.insert(GD).second) {
3007 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3008 Diags.Report(OtherGD.getDecl()->getLocation(),
3009 diag::note_previous_definition);
3010 }
3011 return;
3012 }
3013
3014 Aliases.push_back(GD);
3015
3016 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3017 llvm::Constant *Resolver =
3018 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3019 /*ForVTable=*/false);
3020 llvm::GlobalIFunc *GIF =
3021 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3022 "", Resolver, &getModule());
3023 if (Entry) {
3024 if (GIF->getResolver() == Entry) {
3025 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3026 return;
3027 }
3028 assert(Entry->isDeclaration());
3029
3030 // If there is a declaration in the module, then we had an extern followed
3031 // by the ifunc, as in:
3032 // extern int test();
3033 // ...
3034 // int test() __attribute__((ifunc("resolver")));
3035 //
3036 // Remove it and replace uses of it with the ifunc.
3037 GIF->takeName(Entry);
3038
3039 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3040 Entry->getType()));
3041 Entry->eraseFromParent();
3042 } else
3043 GIF->setName(MangledName);
3044
3045 SetCommonAttributes(D, GIF);
3046}
3047
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00003048llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00003049 ArrayRef<llvm::Type*> Tys) {
Jay Foaddf983a82011-07-12 14:06:48 +00003050 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00003051 Tys);
Chris Lattner7acda7c2007-12-18 00:25:38 +00003052}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00003053
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07003054static llvm::StringMapEntry<llvm::GlobalVariable *> &
3055GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3056 const StringLiteral *Literal, bool TargetIsLSB,
3057 bool &IsUTF16, unsigned &StringLength) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003058 StringRef String = Literal->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003059 unsigned NumBytes = String.size();
Daniel Dunbar1d552912009-07-23 22:52:48 +00003060
Daniel Dunbarf015b032009-09-22 10:03:52 +00003061 // Check for simple case.
3062 if (!Literal->containsNonAsciiOrNull()) {
3063 StringLength = NumBytes;
Stephen Hines176edba2014-12-01 14:53:08 -08003064 return *Map.insert(std::make_pair(String, nullptr)).first;
Daniel Dunbarf015b032009-09-22 10:03:52 +00003065 }
3066
Bill Wendling84392d02012-03-30 00:26:17 +00003067 // Otherwise, convert the UTF8 literals into a string of shorts.
3068 IsUTF16 = true;
3069
3070 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
Roman Divacky31ba6132012-09-06 15:59:27 +00003071 const UTF8 *FromPtr = (const UTF8 *)String.data();
Daniel Dunbar1d552912009-07-23 22:52:48 +00003072 UTF16 *ToPtr = &ToBuf[0];
Mike Stump1eb44332009-09-09 15:08:12 +00003073
Fariborz Jahaniane7ddfb92010-09-07 19:57:04 +00003074 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
3075 &ToPtr, ToPtr + NumBytes,
3076 strictConversion);
Mike Stump1eb44332009-09-09 15:08:12 +00003077
Daniel Dunbar70ee9752009-07-23 23:41:22 +00003078 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar1d552912009-07-23 22:52:48 +00003079 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar70ee9752009-07-23 23:41:22 +00003080
Bill Wendling84392d02012-03-30 00:26:17 +00003081 // Add an explicit null.
3082 *ToPtr = 0;
Stephen Hines176edba2014-12-01 14:53:08 -08003083 return *Map.insert(std::make_pair(
3084 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3085 (StringLength + 1) * 2),
3086 nullptr)).first;
Daniel Dunbar1d552912009-07-23 22:52:48 +00003087}
3088
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07003089static llvm::StringMapEntry<llvm::GlobalVariable *> &
3090GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3091 const StringLiteral *Literal, unsigned &StringLength) {
Bill Wendling8322c232012-03-29 22:12:09 +00003092 StringRef String = Literal->getString();
3093 StringLength = String.size();
Stephen Hines176edba2014-12-01 14:53:08 -08003094 return *Map.insert(std::make_pair(String, nullptr)).first;
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00003095}
3096
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003097ConstantAddress
Daniel Dunbar1d552912009-07-23 22:52:48 +00003098CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3099 unsigned StringLength = 0;
3100 bool isUTF16 = false;
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07003101 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3102 GetConstantCFStringEntry(CFConstantStringMap, Literal,
3103 getDataLayout().isLittleEndian(), isUTF16,
3104 StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Stephen Hines176edba2014-12-01 14:53:08 -08003106 if (auto *C = Entry.second)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003107 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
Mike Stump1eb44332009-09-09 15:08:12 +00003108
Chris Lattner8b418682012-02-07 00:39:47 +00003109 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00003110 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahanian428edb72013-04-16 15:25:39 +00003111 llvm::Value *V;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07003112
Chris Lattner9d4a15f2009-07-16 16:48:25 +00003113 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonc9e20912007-08-21 00:21:21 +00003114 if (!CFConstantStringClassRef) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00003115 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +00003116 Ty = llvm::ArrayType::get(Ty, 0);
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07003117 llvm::Constant *GV =
3118 CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3119
3120 if (getTarget().getTriple().isOSBinFormatCOFF()) {
3121 IdentifierInfo &II = getContext().Idents.get(GV->getName());
3122 TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3123 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3124 llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3125
3126 const VarDecl *VD = nullptr;
3127 for (const auto &Result : DC->lookup(&II))
3128 if ((VD = dyn_cast<VarDecl>(Result)))
3129 break;
3130
3131 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3132 CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3133 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3134 } else {
3135 CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3136 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3137 }
3138 }
3139
Daniel Dunbar3e9df992008-08-23 18:37:06 +00003140 // Decay array -> ptr
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07003141 V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
Fariborz Jahanian428edb72013-04-16 15:25:39 +00003142 CFConstantStringClassRef = V;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07003143 } else {
Fariborz Jahanian428edb72013-04-16 15:25:39 +00003144 V = CFConstantStringClassRef;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07003145 }
Mike Stump1eb44332009-09-09 15:08:12 +00003146
Anders Carlssone3daa762008-11-15 18:54:24 +00003147 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00003148
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003149 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
Anders Carlssone3daa762008-11-15 18:54:24 +00003150
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00003151 llvm::Constant *Fields[4];
Douglas Gregor44b43212008-12-11 16:49:14 +00003152
Anders Carlssonc9e20912007-08-21 00:21:21 +00003153 // Class pointer.
Fariborz Jahanian428edb72013-04-16 15:25:39 +00003154 Fields[0] = cast<llvm::ConstantExpr>(V);
Mike Stump1eb44332009-09-09 15:08:12 +00003155
Anders Carlssonc9e20912007-08-21 00:21:21 +00003156 // Flags.
Chris Lattner2acc6e32011-07-18 04:24:23 +00003157 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07003158 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0)
3159 : llvm::ConstantInt::get(Ty, 0x07C8);
Anders Carlsson5add6832009-08-16 05:55:31 +00003160
Anders Carlssonc9e20912007-08-21 00:21:21 +00003161 // String pointer.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003162 llvm::Constant *C = nullptr;
Bill Wendling84392d02012-03-30 00:26:17 +00003163 if (isUTF16) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003164 auto Arr = llvm::makeArrayRef(
Stephen Hines176edba2014-12-01 14:53:08 -08003165 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3166 Entry.first().size() / 2);
Bill Wendling84392d02012-03-30 00:26:17 +00003167 C = llvm::ConstantDataArray::get(VMContext, Arr);
3168 } else {
Stephen Hines176edba2014-12-01 14:53:08 -08003169 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
Bill Wendling84392d02012-03-30 00:26:17 +00003170 }
Daniel Dunbara9668e02009-04-03 00:57:44 +00003171
Bill Wendling1bf7a3f2012-01-10 08:46:39 +00003172 // Note: -fwritable-strings doesn't make the backing store strings of
3173 // CFStrings writable. (See <rdar://problem/10657500>)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003174 auto *GV =
Stephen Hines651f13c2014-04-23 16:59:28 -07003175 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3176 llvm::GlobalValue::PrivateLinkage, C, ".str");
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07003177 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Ulrich Weigand6b203512013-05-06 16:23:57 +00003178 // Don't enforce the target's minimum global alignment, since the only use
3179 // of the string is via this class initializer.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07003180 CharUnits Align = isUTF16
3181 ? getContext().getTypeAlignInChars(getContext().ShortTy)
3182 : getContext().getTypeAlignInChars(getContext().CharTy);
3183 GV->setAlignment(Align.getQuantity());
3184
3185 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3186 // Without it LLVM can merge the string with a non unnamed_addr one during
3187 // LTO. Doing that changes the section it ends in, which surprises ld64.
3188 if (getTarget().getTriple().isOSBinFormatMachO())
3189 GV->setSection(isUTF16 ? "__TEXT,__ustring"
3190 : "__TEXT,__cstring,cstring_literals");
Bill Wendling84392d02012-03-30 00:26:17 +00003191
3192 // String.
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07003193 Fields[2] =
3194 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
Anders Carlsson5add6832009-08-16 05:55:31 +00003195
Bill Wendling84392d02012-03-30 00:26:17 +00003196 if (isUTF16)
3197 // Cast the UTF16 string to the correct type.
3198 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
3199
Anders Carlssonc9e20912007-08-21 00:21:21 +00003200 // String length.
3201 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson5add6832009-08-16 05:55:31 +00003202 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00003203
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003204 CharUnits Alignment = getPointerAlign();
3205
Anders Carlssonc9e20912007-08-21 00:21:21 +00003206 // The struct.
Owen Anderson08e25242009-07-27 22:29:56 +00003207 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump1eb44332009-09-09 15:08:12 +00003208 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
3209 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner95b851e2009-07-16 05:03:48 +00003210 "_unnamed_cfstring_");
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003211 GV->setAlignment(Alignment.getQuantity());
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07003212 switch (getTarget().getTriple().getObjectFormat()) {
3213 case llvm::Triple::UnknownObjectFormat:
3214 llvm_unreachable("unknown file format");
3215 case llvm::Triple::COFF:
3216 case llvm::Triple::ELF:
3217 GV->setSection("cfstring");
3218 break;
3219 case llvm::Triple::MachO:
3220 GV->setSection("__DATA,__cfstring");
3221 break;
3222 }
Stephen Hines176edba2014-12-01 14:53:08 -08003223 Entry.second = GV;
Mike Stump1eb44332009-09-09 15:08:12 +00003224
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003225 return ConstantAddress(GV, Alignment);
Anders Carlssonc9e20912007-08-21 00:21:21 +00003226}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00003227
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003228ConstantAddress
Fariborz Jahanian4c733072010-10-19 17:19:29 +00003229CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003230 unsigned StringLength = 0;
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07003231 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3232 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
Stephen Hines176edba2014-12-01 14:53:08 -08003233
3234 if (auto *C = Entry.second)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003235 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003236
Chris Lattner812234b2012-02-06 22:47:00 +00003237 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003238 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahanian428edb72013-04-16 15:25:39 +00003239 llvm::Value *V;
Fariborz Jahanianec951e02010-04-23 22:33:39 +00003240 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00003241 if (!ConstantStringClassRef) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003242 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Chris Lattner2acc6e32011-07-18 04:24:23 +00003243 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00003244 llvm::Constant *GV;
John McCall260611a2012-06-20 06:18:46 +00003245 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00003246 std::string str =
3247 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
3248 : "OBJC_CLASS_$_" + StringClass;
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00003249 GV = getObjCRuntime().GetClassGlobal(str);
3250 // Make sure the result is of the correct type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00003251 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Fariborz Jahanian428edb72013-04-16 15:25:39 +00003252 V = llvm::ConstantExpr::getBitCast(GV, PTy);
3253 ConstantStringClassRef = V;
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00003254 } else {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00003255 std::string str =
3256 StringClass.empty() ? "_NSConstantStringClassReference"
3257 : "_" + StringClass + "ClassReference";
Chris Lattner2acc6e32011-07-18 04:24:23 +00003258 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00003259 GV = CreateRuntimeVariable(PTy, str);
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00003260 // Decay array -> ptr
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07003261 V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros);
Fariborz Jahanian428edb72013-04-16 15:25:39 +00003262 ConstantStringClassRef = V;
Fariborz Jahanian4c733072010-10-19 17:19:29 +00003263 }
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07003264 } else
Fariborz Jahanian428edb72013-04-16 15:25:39 +00003265 V = ConstantStringClassRef;
Douglas Gregor45c4ea72011-08-09 15:54:21 +00003266
3267 if (!NSConstantStringType) {
3268 // Construct the type for a constant NSString.
Stephen Hines651f13c2014-04-23 16:59:28 -07003269 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
Douglas Gregor45c4ea72011-08-09 15:54:21 +00003270 D->startDefinition();
3271
3272 QualType FieldTypes[3];
3273
3274 // const int *isa;
3275 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
3276 // const char *str;
3277 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
3278 // unsigned int length;
3279 FieldTypes[2] = Context.UnsignedIntTy;
3280
3281 // Create fields
3282 for (unsigned i = 0; i < 3; ++i) {
3283 FieldDecl *Field = FieldDecl::Create(Context, D,
3284 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003285 SourceLocation(), nullptr,
3286 FieldTypes[i], /*TInfo=*/nullptr,
3287 /*BitWidth=*/nullptr,
Douglas Gregor45c4ea72011-08-09 15:54:21 +00003288 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003289 ICIS_NoInit);
Douglas Gregor45c4ea72011-08-09 15:54:21 +00003290 Field->setAccess(AS_public);
3291 D->addDecl(Field);
3292 }
3293
3294 D->completeDefinition();
3295 QualType NSTy = Context.getTagDeclType(D);
3296 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
3297 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003298
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00003299 llvm::Constant *Fields[3];
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003300
3301 // Class pointer.
Fariborz Jahanian428edb72013-04-16 15:25:39 +00003302 Fields[0] = cast<llvm::ConstantExpr>(V);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003303
3304 // String pointer.
Chris Lattner94010692012-02-05 02:30:40 +00003305 llvm::Constant *C =
Stephen Hines176edba2014-12-01 14:53:08 -08003306 llvm::ConstantDataArray::getString(VMContext, Entry.first());
3307
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003308 llvm::GlobalValue::LinkageTypes Linkage;
3309 bool isConstant;
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00003310 Linkage = llvm::GlobalValue::PrivateLinkage;
David Blaikie4e4d0842012-03-11 07:00:24 +00003311 isConstant = !LangOpts.WritableStrings;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003312
3313 auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
3314 Linkage, C, ".str");
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07003315 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Ulrich Weigand6b203512013-05-06 16:23:57 +00003316 // Don't enforce the target's minimum global alignment, since the only use
3317 // of the string is via this class initializer.
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00003318 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
3319 GV->setAlignment(Align.getQuantity());
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07003320 Fields[1] =
3321 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3322
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003323 // String length.
Chris Lattner2acc6e32011-07-18 04:24:23 +00003324 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003325 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
3326
3327 // The struct.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003328 CharUnits Alignment = getPointerAlign();
Douglas Gregor45c4ea72011-08-09 15:54:21 +00003329 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003330 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
3331 llvm::GlobalVariable::PrivateLinkage, C,
3332 "_unnamed_nsstring_");
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003333 GV->setAlignment(Alignment.getQuantity());
Stephen Hines651f13c2014-04-23 16:59:28 -07003334 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
3335 const char *NSStringNonFragileABISection =
3336 "__DATA,__objc_stringobj,regular,no_dead_strip";
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003337 // FIXME. Fix section.
Stephen Hines651f13c2014-04-23 16:59:28 -07003338 GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
3339 ? NSStringNonFragileABISection
3340 : NSStringSection);
Stephen Hines176edba2014-12-01 14:53:08 -08003341 Entry.second = GV;
3342
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003343 return ConstantAddress(GV, Alignment);
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00003344}
3345
Douglas Gregor0815b572011-08-09 17:23:49 +00003346QualType CodeGenModule::getObjCFastEnumerationStateType() {
3347 if (ObjCFastEnumerationStateType.isNull()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003348 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor0815b572011-08-09 17:23:49 +00003349 D->startDefinition();
3350
3351 QualType FieldTypes[] = {
3352 Context.UnsignedLongTy,
3353 Context.getPointerType(Context.getObjCIdType()),
3354 Context.getPointerType(Context.UnsignedLongTy),
3355 Context.getConstantArrayType(Context.UnsignedLongTy,
3356 llvm::APInt(32, 5), ArrayType::Normal, 0)
3357 };
3358
3359 for (size_t i = 0; i < 4; ++i) {
3360 FieldDecl *Field = FieldDecl::Create(Context,
3361 D,
3362 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003363 SourceLocation(), nullptr,
3364 FieldTypes[i], /*TInfo=*/nullptr,
3365 /*BitWidth=*/nullptr,
Douglas Gregor0815b572011-08-09 17:23:49 +00003366 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003367 ICIS_NoInit);
Douglas Gregor0815b572011-08-09 17:23:49 +00003368 Field->setAccess(AS_public);
3369 D->addDecl(Field);
3370 }
3371
3372 D->completeDefinition();
3373 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3374 }
3375
3376 return ObjCFastEnumerationStateType;
3377}
3378
Eli Friedman64f45a22011-11-01 02:23:42 +00003379llvm::Constant *
3380CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3381 assert(!E->getType()->isPointerType() && "Strings are always arrays");
3382
3383 // Don't emit it as the address of the string, emit the string data itself
3384 // as an inline array.
Chris Lattner812234b2012-02-06 22:47:00 +00003385 if (E->getCharByteWidth() == 1) {
3386 SmallString<64> Str(E->getString());
3387
3388 // Resize the string to the right size, which is indicated by its type.
3389 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3390 Str.resize(CAT->getSize().getZExtValue());
3391 return llvm::ConstantDataArray::getString(VMContext, Str, false);
3392 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003393
3394 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
Chris Lattner94010692012-02-05 02:30:40 +00003395 llvm::Type *ElemTy = AType->getElementType();
3396 unsigned NumElements = AType->getNumElements();
Chris Lattnerd79ed432012-02-06 22:52:04 +00003397
3398 // Wide strings have either 2-byte or 4-byte elements.
3399 if (ElemTy->getPrimitiveSizeInBits() == 16) {
3400 SmallVector<uint16_t, 32> Elements;
3401 Elements.reserve(NumElements);
3402
3403 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3404 Elements.push_back(E->getCodeUnit(i));
3405 Elements.resize(NumElements);
3406 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner94010692012-02-05 02:30:40 +00003407 }
3408
Chris Lattnerd79ed432012-02-06 22:52:04 +00003409 assert(ElemTy->getPrimitiveSizeInBits() == 32);
3410 SmallVector<uint32_t, 32> Elements;
3411 Elements.reserve(NumElements);
3412
3413 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3414 Elements.push_back(E->getCodeUnit(i));
3415 Elements.resize(NumElements);
3416 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedman64f45a22011-11-01 02:23:42 +00003417}
3418
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003419static llvm::GlobalVariable *
3420GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3421 CodeGenModule &CGM, StringRef GlobalName,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003422 CharUnits Alignment) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003423 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3424 unsigned AddrSpace = 0;
3425 if (CGM.getLangOpts().OpenCL)
3426 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3427
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003428 llvm::Module &M = CGM.getModule();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003429 // Create a global variable for this string
3430 auto *GV = new llvm::GlobalVariable(
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003431 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3432 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003433 GV->setAlignment(Alignment.getQuantity());
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07003434 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003435 if (GV->isWeakForLinker()) {
3436 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3437 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3438 }
3439
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003440 return GV;
3441}
3442
Daniel Dunbar61432932008-08-13 23:20:05 +00003443/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3444/// constant array for the given string literal.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003445ConstantAddress
Stephen Hines176edba2014-12-01 14:53:08 -08003446CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3447 StringRef Name) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003448 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
Stephen Hines651f13c2014-04-23 16:59:28 -07003449
Stephen Hines176edba2014-12-01 14:53:08 -08003450 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3451 llvm::GlobalVariable **Entry = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07003452 if (!LangOpts.WritableStrings) {
Stephen Hines176edba2014-12-01 14:53:08 -08003453 Entry = &ConstantStringMap[C];
3454 if (auto GV = *Entry) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003455 if (Alignment.getQuantity() > GV->getAlignment())
3456 GV->setAlignment(Alignment.getQuantity());
3457 return ConstantAddress(GV, Alignment);
Stephen Hines651f13c2014-04-23 16:59:28 -07003458 }
Eli Friedman7eb79c12009-11-16 05:55:46 +00003459 }
Eli Friedman64f45a22011-11-01 02:23:42 +00003460
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003461 SmallString<256> MangledNameBuffer;
3462 StringRef GlobalVariableName;
3463 llvm::GlobalValue::LinkageTypes LT;
Seth Cantrell7d6a7c02012-01-18 12:11:32 +00003464
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003465 // Mangle the string literal if the ABI allows for it. However, we cannot
3466 // do this if we are compiling with ASan or -fwritable-strings because they
3467 // rely on strings having normal linkage.
Stephen Hines176edba2014-12-01 14:53:08 -08003468 if (!LangOpts.WritableStrings &&
3469 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003470 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3471 llvm::raw_svector_ostream Out(MangledNameBuffer);
3472 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
Stephen Hines651f13c2014-04-23 16:59:28 -07003473
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003474 LT = llvm::GlobalValue::LinkOnceODRLinkage;
3475 GlobalVariableName = MangledNameBuffer;
3476 } else {
3477 LT = llvm::GlobalValue::PrivateLinkage;
Stephen Hines176edba2014-12-01 14:53:08 -08003478 GlobalVariableName = Name;
Stephen Hines651f13c2014-04-23 16:59:28 -07003479 }
3480
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003481 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3482 if (Entry)
Stephen Hines176edba2014-12-01 14:53:08 -08003483 *Entry = GV;
Stephen Hines651f13c2014-04-23 16:59:28 -07003484
Stephen Hines176edba2014-12-01 14:53:08 -08003485 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3486 QualType());
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003487 return ConstantAddress(GV, Alignment);
Daniel Dunbar61432932008-08-13 23:20:05 +00003488}
3489
Chris Lattnereaf2bb82009-02-24 22:18:39 +00003490/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3491/// array for the given ObjCEncodeExpr node.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003492ConstantAddress
Chris Lattnereaf2bb82009-02-24 22:18:39 +00003493CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3494 std::string Str;
3495 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00003496
3497 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00003498}
3499
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003500/// GetAddrOfConstantCString - Returns a pointer to a character array containing
3501/// the literal and a terminating '\0' character.
3502/// The result has pointer to array type.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003503ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3504 const std::string &Str, const char *GlobalName) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003505 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003506 CharUnits Alignment =
3507 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003508
Stephen Hines176edba2014-12-01 14:53:08 -08003509 llvm::Constant *C =
3510 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3511
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003512 // Don't share any string literals if strings aren't constant.
Stephen Hines176edba2014-12-01 14:53:08 -08003513 llvm::GlobalVariable **Entry = nullptr;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003514 if (!LangOpts.WritableStrings) {
Stephen Hines176edba2014-12-01 14:53:08 -08003515 Entry = &ConstantStringMap[C];
3516 if (auto GV = *Entry) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003517 if (Alignment.getQuantity() > GV->getAlignment())
3518 GV->setAlignment(Alignment.getQuantity());
3519 return ConstantAddress(GV, Alignment);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003520 }
3521 }
3522
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003523 // Get the default prefix if a name wasn't specified.
3524 if (!GlobalName)
3525 GlobalName = ".str";
3526 // Create a global variable for this.
3527 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3528 GlobalName, Alignment);
3529 if (Entry)
Stephen Hines176edba2014-12-01 14:53:08 -08003530 *Entry = GV;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003531 return ConstantAddress(GV, Alignment);
Daniel Dunbar61432932008-08-13 23:20:05 +00003532}
Daniel Dunbar41071de2008-08-15 23:26:23 +00003533
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003534ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smith3282b842013-06-14 03:07:01 +00003535 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smith211c8dd2013-06-05 00:46:14 +00003536 assert((E->getStorageDuration() == SD_Static ||
3537 E->getStorageDuration() == SD_Thread) && "not a global temporary");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003538 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
Richard Smith211c8dd2013-06-05 00:46:14 +00003539
3540 // If we're not materializing a subobject of the temporary, keep the
3541 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smith3282b842013-06-14 03:07:01 +00003542 QualType MaterializedType = Init->getType();
3543 if (Init == E->GetTemporaryExpr())
3544 MaterializedType = E->getType();
Richard Smith211c8dd2013-06-05 00:46:14 +00003545
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003546 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3547
3548 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3549 return ConstantAddress(Slot, Align);
Richard Smith211c8dd2013-06-05 00:46:14 +00003550
3551 // FIXME: If an externally-visible declaration extends multiple temporaries,
3552 // we need to give each temporary the same name in every translation unit (and
3553 // we also need to make the temporaries externally-visible).
3554 SmallString<256> Name;
3555 llvm::raw_svector_ostream Out(Name);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003556 getCXXABI().getMangleContext().mangleReferenceTemporary(
3557 VD, E->getManglingNumber(), Out);
Richard Smith211c8dd2013-06-05 00:46:14 +00003558
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003559 APValue *Value = nullptr;
Richard Smith211c8dd2013-06-05 00:46:14 +00003560 if (E->getStorageDuration() == SD_Static) {
Richard Smith3282b842013-06-14 03:07:01 +00003561 // We might have a cached constant initializer for this temporary. Note
3562 // that this might have a different value from the value computed by
3563 // evaluating the initializer if the surrounding constant expression
3564 // modifies the temporary.
Richard Smith211c8dd2013-06-05 00:46:14 +00003565 Value = getContext().getMaterializedTemporaryValue(E, false);
3566 if (Value && Value->isUninit())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003567 Value = nullptr;
Richard Smith211c8dd2013-06-05 00:46:14 +00003568 }
3569
Richard Smith3282b842013-06-14 03:07:01 +00003570 // Try evaluating it now, it might have a constant initializer.
3571 Expr::EvalResult EvalResult;
3572 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3573 !EvalResult.hasSideEffects())
3574 Value = &EvalResult.Val;
3575
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003576 llvm::Constant *InitialValue = nullptr;
Richard Smith3282b842013-06-14 03:07:01 +00003577 bool Constant = false;
3578 llvm::Type *Type;
Richard Smith211c8dd2013-06-05 00:46:14 +00003579 if (Value) {
3580 // The temporary has a constant initializer, use it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003581 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
Richard Smith3282b842013-06-14 03:07:01 +00003582 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3583 Type = InitialValue->getType();
Richard Smith211c8dd2013-06-05 00:46:14 +00003584 } else {
Richard Smith3282b842013-06-14 03:07:01 +00003585 // No initializer, the initialization will be provided when we
Richard Smith211c8dd2013-06-05 00:46:14 +00003586 // initialize the declaration which performed lifetime extension.
Richard Smith3282b842013-06-14 03:07:01 +00003587 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smith211c8dd2013-06-05 00:46:14 +00003588 }
3589
3590 // Create a global variable for this lifetime-extended temporary.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003591 llvm::GlobalValue::LinkageTypes Linkage =
3592 getLLVMLinkageVarDefinition(VD, Constant);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003593 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3594 const VarDecl *InitVD;
3595 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3596 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3597 // Temporaries defined inside a class get linkonce_odr linkage because the
3598 // class can be defined in multipe translation units.
3599 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3600 } else {
3601 // There is no need for this temporary to have external linkage if the
3602 // VarDecl has external linkage.
3603 Linkage = llvm::GlobalVariable::InternalLinkage;
3604 }
3605 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003606 unsigned AddrSpace = GetGlobalVarAddressSpace(
3607 VD, getContext().getTargetAddressSpace(MaterializedType));
3608 auto *GV = new llvm::GlobalVariable(
3609 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3610 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3611 AddrSpace);
3612 setGlobalVisibility(GV, VD);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003613 GV->setAlignment(Align.getQuantity());
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003614 if (supportsCOMDAT() && GV->isWeakForLinker())
3615 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Richard Smith211c8dd2013-06-05 00:46:14 +00003616 if (VD->getTLSKind())
3617 setTLSMode(GV, *VD);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003618 MaterializedGlobalTemporaryMap[E] = GV;
3619 return ConstantAddress(GV, Align);
Richard Smith211c8dd2013-06-05 00:46:14 +00003620}
3621
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003622/// EmitObjCPropertyImplementations - Emit information for synthesized
3623/// properties for an implementation.
Mike Stump1eb44332009-09-09 15:08:12 +00003624void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003625 ObjCImplementationDecl *D) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003626 for (const auto *PID : D->property_impls()) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003627 // Dynamic is just for type-checking.
3628 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3629 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3630
3631 // Determine which methods need to be implemented, some may have
Jordan Rose1e4691b2012-10-10 16:42:25 +00003632 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003633 // we want, that just indicates if the decl came from a
3634 // property. What we want to know is if the method is defined in
3635 // this implementation.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003636 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00003637 CodeGenFunction(*this).GenerateObjCGetter(
3638 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003639 if (!PD->isReadOnly() &&
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003640 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00003641 CodeGenFunction(*this).GenerateObjCSetter(
3642 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003643 }
3644 }
3645}
3646
John McCalle81ac692011-03-22 07:05:39 +00003647static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00003648 const ObjCInterfaceDecl *iface = impl->getClassInterface();
3649 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00003650 ivar; ivar = ivar->getNextIvar())
3651 if (ivar->getType().isDestructedType())
3652 return true;
3653
3654 return false;
3655}
3656
Stephen Hines176edba2014-12-01 14:53:08 -08003657static bool AllTrivialInitializers(CodeGenModule &CGM,
3658 ObjCImplementationDecl *D) {
3659 CodeGenFunction CGF(CGM);
3660 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3661 E = D->init_end(); B != E; ++B) {
3662 CXXCtorInitializer *CtorInitExp = *B;
3663 Expr *Init = CtorInitExp->getInit();
3664 if (!CGF.isTrivialInitializer(Init))
3665 return false;
3666 }
3667 return true;
3668}
3669
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003670/// EmitObjCIvarInitializations - Emit information for ivar initialization
3671/// for an implementation.
3672void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCalle81ac692011-03-22 07:05:39 +00003673 // We might need a .cxx_destruct even if we don't have any ivar initializers.
3674 if (needsDestructMethod(D)) {
3675 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3676 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3677 ObjCMethodDecl *DTORMethod =
3678 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003679 cxxSelector, getContext().VoidTy, nullptr, D,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00003680 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rose1e4691b2012-10-10 16:42:25 +00003681 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00003682 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCalle81ac692011-03-22 07:05:39 +00003683 D->addInstanceMethod(DTORMethod);
3684 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCallb03527a2012-10-17 04:53:31 +00003685 D->setHasDestructors(true);
John McCalle81ac692011-03-22 07:05:39 +00003686 }
3687
3688 // If the implementation doesn't have any ivar initializers, we don't need
3689 // a .cxx_construct.
Stephen Hines176edba2014-12-01 14:53:08 -08003690 if (D->getNumIvarInitializers() == 0 ||
3691 AllTrivialInitializers(*this, D))
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003692 return;
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003693
John McCalle81ac692011-03-22 07:05:39 +00003694 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3695 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003696 // The constructor returns 'self'.
3697 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3698 D->getLocation(),
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00003699 D->getLocation(),
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00003700 cxxSelector,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003701 getContext().getObjCIdType(),
3702 nullptr, D, /*isInstance=*/true,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00003703 /*isVariadic=*/false,
Jordan Rose1e4691b2012-10-10 16:42:25 +00003704 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00003705 /*isImplicitlyDeclared=*/true,
3706 /*isDefined=*/false,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003707 ObjCMethodDecl::Required);
3708 D->addInstanceMethod(CTORMethod);
3709 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCallb03527a2012-10-17 04:53:31 +00003710 D->setHasNonZeroConstructors(true);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003711}
3712
Anders Carlsson91e20dd2009-04-02 05:55:18 +00003713/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00003714void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003715 for (auto *I : ND->decls()) {
3716 if (const auto *VD = dyn_cast<VarDecl>(I))
David Blaikie0d520f72013-09-04 21:07:37 +00003717 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
3718 VD->getTemplateSpecializationKind() != TSK_Undeclared)
3719 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07003720 EmitTopLevelDecl(I);
David Blaikie0d520f72013-09-04 21:07:37 +00003721 }
Anders Carlsson984e0682009-04-01 00:58:25 +00003722}
3723
Anders Carlsson91e20dd2009-04-02 05:55:18 +00003724// EmitLinkageSpec - Emit all declarations in a linkage spec.
3725void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmanf976be82009-08-01 20:48:04 +00003726 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3727 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlsson91e20dd2009-04-02 05:55:18 +00003728 ErrorUnsupported(LSD, "linkage spec");
3729 return;
3730 }
3731
Stephen Hines651f13c2014-04-23 16:59:28 -07003732 for (auto *I : LSD->decls()) {
Fariborz Jahanian107dae42012-10-26 22:20:25 +00003733 // Meta-data for ObjC class includes references to implemented methods.
3734 // Generate class's method definitions first.
Stephen Hines651f13c2014-04-23 16:59:28 -07003735 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3736 for (auto *M : OID->methods())
3737 EmitTopLevelDecl(M);
Fariborz Jahanianc1868e52012-10-26 20:22:11 +00003738 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003739 EmitTopLevelDecl(I);
Fariborz Jahanianc1868e52012-10-26 20:22:11 +00003740 }
Anders Carlsson91e20dd2009-04-02 05:55:18 +00003741}
3742
Daniel Dunbar41071de2008-08-15 23:26:23 +00003743/// EmitTopLevelDecl - Emit code for a single top level declaration.
3744void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor16e8be22009-06-29 17:30:29 +00003745 // Ignore dependent declarations.
3746 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3747 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003748
Daniel Dunbar41071de2008-08-15 23:26:23 +00003749 switch (D->getKind()) {
Anders Carlsson293361a2009-08-25 13:14:46 +00003750 case Decl::CXXConversion:
Anders Carlsson2b77ba82009-04-04 20:47:02 +00003751 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00003752 case Decl::Function:
Douglas Gregor16e8be22009-06-29 17:30:29 +00003753 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00003754 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3755 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor16e8be22009-06-29 17:30:29 +00003756 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003757
Anders Carlsson555b4bb2009-09-10 23:43:36 +00003758 EmitGlobal(cast<FunctionDecl>(D));
Stephen Hines176edba2014-12-01 14:53:08 -08003759 // Always provide some coverage mapping
3760 // even for the functions that aren't emitted.
3761 AddDeferredUnusedCoverageMapping(D);
Anders Carlsson555b4bb2009-09-10 23:43:36 +00003762 break;
Larisse Voufoef4579c2013-08-06 01:03:05 +00003763
Daniel Dunbar41071de2008-08-15 23:26:23 +00003764 case Decl::Var:
Larisse Voufoef4579c2013-08-06 01:03:05 +00003765 // Skip variable templates
3766 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3767 return;
3768 case Decl::VarTemplateSpecialization:
Anders Carlsson555b4bb2009-09-10 23:43:36 +00003769 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00003770 break;
3771
John McCall26fbc722011-04-12 01:01:22 +00003772 // Indirect fields from global anonymous structs and unions can be
3773 // ignored; only the actual variable requires IR gen support.
3774 case Decl::IndirectField:
3775 break;
3776
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00003777 // C++ Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00003778 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00003779 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00003780 break;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07003781 case Decl::CXXRecord:
3782 // Emit any static data members, they may be definitions.
3783 for (auto *I : cast<CXXRecordDecl>(D)->decls())
3784 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3785 EmitTopLevelDecl(I);
3786 break;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003787 // No code generation needed.
John McCall9d0c6612009-11-17 09:33:40 +00003788 case Decl::UsingShadow:
Douglas Gregor127102b2009-06-29 20:59:39 +00003789 case Decl::ClassTemplate:
Larisse Voufoef4579c2013-08-06 01:03:05 +00003790 case Decl::VarTemplate:
3791 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor127102b2009-06-29 20:59:39 +00003792 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +00003793 case Decl::TypeAliasTemplate:
Douglas Gregor6a576ab2011-06-05 05:04:23 +00003794 case Decl::Block:
Michael Han684aa732013-02-22 17:15:32 +00003795 case Decl::Empty:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003796 break;
Stephen Hines651f13c2014-04-23 16:59:28 -07003797 case Decl::Using: // using X; [C++]
3798 if (CGDebugInfo *DI = getModuleDebugInfo())
3799 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3800 return;
David Blaikiefc46ebc2013-05-20 22:50:41 +00003801 case Decl::NamespaceAlias:
3802 if (CGDebugInfo *DI = getModuleDebugInfo())
3803 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3804 return;
David Blaikie1601a4a2013-04-26 05:41:06 +00003805 case Decl::UsingDirective: // using namespace X; [C++]
3806 if (CGDebugInfo *DI = getModuleDebugInfo())
3807 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3808 return;
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00003809 case Decl::CXXConstructor:
Anders Carlsson1fe598c2009-11-24 05:16:24 +00003810 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00003811 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3812 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson1fe598c2009-11-24 05:16:24 +00003813 return;
3814
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +00003815 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00003816 break;
Anders Carlsson27ae5362009-04-17 01:58:57 +00003817 case Decl::CXXDestructor:
Francois Pichet8387e2a2011-04-22 22:18:13 +00003818 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3819 return;
Reid Klecknera4130ba2013-07-22 13:51:44 +00003820 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlsson27ae5362009-04-17 01:58:57 +00003821 break;
Anders Carlsson36674d22009-06-11 21:22:55 +00003822
3823 case Decl::StaticAssert:
3824 // Nothing to do.
3825 break;
3826
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00003827 // Objective-C Decls
Mike Stump1eb44332009-09-09 15:08:12 +00003828
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00003829 // Forward declarations, no (immediate) code generation.
Chris Lattner285d0db2009-04-01 02:36:43 +00003830 case Decl::ObjCInterface:
Eric Christopherffb0c3a2012-07-19 22:22:55 +00003831 case Decl::ObjCCategory:
Chris Lattner285d0db2009-04-01 02:36:43 +00003832 break;
3833
Douglas Gregorbd9482d2012-01-01 21:23:57 +00003834 case Decl::ObjCProtocol: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003835 auto *Proto = cast<ObjCProtocolDecl>(D);
Douglas Gregorbd9482d2012-01-01 21:23:57 +00003836 if (Proto->isThisDeclarationADefinition())
3837 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbar41071de2008-08-15 23:26:23 +00003838 break;
Douglas Gregorbd9482d2012-01-01 21:23:57 +00003839 }
3840
Daniel Dunbar41071de2008-08-15 23:26:23 +00003841 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003842 // Categories have properties but don't support synthesize so we
3843 // can ignore them here.
Peter Collingbournee9265232011-07-27 20:29:46 +00003844 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00003845 break;
3846
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003847 case Decl::ObjCImplementation: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003848 auto *OMD = cast<ObjCImplementationDecl>(D);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003849 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003850 EmitObjCIvarInitializations(OMD);
Peter Collingbournee9265232011-07-27 20:29:46 +00003851 ObjCRuntime->GenerateClass(OMD);
Eric Christopherbe6c6862012-04-11 05:56:05 +00003852 // Emit global variable debug information.
3853 if (CGDebugInfo *DI = getModuleDebugInfo())
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07003854 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov96a66392012-12-03 18:28:12 +00003855 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3856 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbar41071de2008-08-15 23:26:23 +00003857 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003858 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00003859 case Decl::ObjCMethod: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003860 auto *OMD = cast<ObjCMethodDecl>(D);
Daniel Dunbar41071de2008-08-15 23:26:23 +00003861 // If this is not a prototype, emit the body.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003862 if (OMD->getBody())
Daniel Dunbar41071de2008-08-15 23:26:23 +00003863 CodeGenFunction(*this).GenerateObjCMethod(OMD);
3864 break;
3865 }
Mike Stump1eb44332009-09-09 15:08:12 +00003866 case Decl::ObjCCompatibleAlias:
David Chisnall29254f42012-01-31 18:59:20 +00003867 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00003868 break;
3869
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07003870 case Decl::PragmaComment: {
3871 const auto *PCD = cast<PragmaCommentDecl>(D);
3872 switch (PCD->getCommentKind()) {
3873 case PCK_Unknown:
3874 llvm_unreachable("unexpected pragma comment kind");
3875 case PCK_Linker:
3876 AppendLinkerOptions(PCD->getArg());
3877 break;
3878 case PCK_Lib:
3879 AddDependentLib(PCD->getArg());
3880 break;
3881 case PCK_Compiler:
3882 case PCK_ExeStr:
3883 case PCK_User:
3884 break; // We ignore all of these.
3885 }
3886 break;
3887 }
3888
3889 case Decl::PragmaDetectMismatch: {
3890 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3891 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
3892 break;
3893 }
3894
Anders Carlsson91e20dd2009-04-02 05:55:18 +00003895 case Decl::LinkageSpec:
3896 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00003897 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00003898
3899 case Decl::FileScopeAsm: {
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07003900 // File-scope asm is ignored during device-side CUDA compilation.
3901 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3902 break;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07003903 // File-scope asm is ignored during device-side OpenMP compilation.
3904 if (LangOpts.OpenMPIsDevice)
3905 break;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003906 auto *AD = cast<FileScopeAsmDecl>(D);
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003907 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
Daniel Dunbar41071de2008-08-15 23:26:23 +00003908 break;
3909 }
Mike Stump1eb44332009-09-09 15:08:12 +00003910
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003911 case Decl::Import: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003912 auto *Import = cast<ImportDecl>(D);
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003913
3914 // Ignore import declarations that come from imported modules.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003915 if (Import->getImportedOwningModule())
3916 break;
3917 if (CGDebugInfo *DI = getModuleDebugInfo())
3918 DI->EmitImportDecl(*Import);
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003919
Douglas Gregor858afb32013-01-14 20:53:57 +00003920 ImportedModules.insert(Import->getImportedModule());
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003921 break;
Stephen Hines651f13c2014-04-23 16:59:28 -07003922 }
3923
Stephen Hines176edba2014-12-01 14:53:08 -08003924 case Decl::OMPThreadPrivate:
3925 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
3926 break;
3927
Stephen Hines651f13c2014-04-23 16:59:28 -07003928 case Decl::ClassTemplateSpecialization: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003929 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
Stephen Hines651f13c2014-04-23 16:59:28 -07003930 if (DebugInfo &&
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003931 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
3932 Spec->hasDefinition())
Stephen Hines651f13c2014-04-23 16:59:28 -07003933 DebugInfo->completeTemplateDefinition(*Spec);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003934 break;
Stephen Hines651f13c2014-04-23 16:59:28 -07003935 }
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003936
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07003937 case Decl::OMPDeclareReduction:
3938 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
3939 break;
3940
Mike Stump1eb44332009-09-09 15:08:12 +00003941 default:
Mike Stumpf5408fe2009-05-16 07:57:57 +00003942 // Make sure we handled everything we should, every other kind is a
3943 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
3944 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbar41071de2008-08-15 23:26:23 +00003945 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003946 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00003947 }
3948}
John McCall744016d2010-07-06 23:57:41 +00003949
Stephen Hines176edba2014-12-01 14:53:08 -08003950void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
3951 // Do we need to generate coverage mapping?
3952 if (!CodeGenOpts.CoverageMapping)
3953 return;
3954 switch (D->getKind()) {
3955 case Decl::CXXConversion:
3956 case Decl::CXXMethod:
3957 case Decl::Function:
3958 case Decl::ObjCMethod:
3959 case Decl::CXXConstructor:
3960 case Decl::CXXDestructor: {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08003961 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
Stephen Hines176edba2014-12-01 14:53:08 -08003962 return;
3963 auto I = DeferredEmptyCoverageMappingDecls.find(D);
3964 if (I == DeferredEmptyCoverageMappingDecls.end())
3965 DeferredEmptyCoverageMappingDecls[D] = true;
3966 break;
3967 }
3968 default:
3969 break;
3970 };
3971}
3972
3973void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
3974 // Do we need to generate coverage mapping?
3975 if (!CodeGenOpts.CoverageMapping)
3976 return;
3977 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
3978 if (Fn->isTemplateInstantiation())
3979 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
3980 }
3981 auto I = DeferredEmptyCoverageMappingDecls.find(D);
3982 if (I == DeferredEmptyCoverageMappingDecls.end())
3983 DeferredEmptyCoverageMappingDecls[D] = false;
3984 else
3985 I->second = false;
3986}
3987
3988void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
3989 std::vector<const Decl *> DeferredDecls;
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07003990 for (const auto &I : DeferredEmptyCoverageMappingDecls) {
Stephen Hines176edba2014-12-01 14:53:08 -08003991 if (!I.second)
3992 continue;
3993 DeferredDecls.push_back(I.first);
3994 }
3995 // Sort the declarations by their location to make sure that the tests get a
3996 // predictable order for the coverage mapping for the unused declarations.
3997 if (CodeGenOpts.DumpCoverageMapping)
3998 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
3999 [] (const Decl *LHS, const Decl *RHS) {
4000 return LHS->getLocStart() < RHS->getLocStart();
4001 });
4002 for (const auto *D : DeferredDecls) {
4003 switch (D->getKind()) {
4004 case Decl::CXXConversion:
4005 case Decl::CXXMethod:
4006 case Decl::Function:
4007 case Decl::ObjCMethod: {
4008 CodeGenPGO PGO(*this);
4009 GlobalDecl GD(cast<FunctionDecl>(D));
4010 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4011 getFunctionLinkage(GD));
4012 break;
4013 }
4014 case Decl::CXXConstructor: {
4015 CodeGenPGO PGO(*this);
4016 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4017 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4018 getFunctionLinkage(GD));
4019 break;
4020 }
4021 case Decl::CXXDestructor: {
4022 CodeGenPGO PGO(*this);
4023 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4024 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4025 getFunctionLinkage(GD));
4026 break;
4027 }
4028 default:
4029 break;
4030 };
4031 }
4032}
4033
John McCall744016d2010-07-06 23:57:41 +00004034/// Turns the given pointer into a constant.
4035static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4036 const void *Ptr) {
4037 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2acc6e32011-07-18 04:24:23 +00004038 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall744016d2010-07-06 23:57:41 +00004039 return llvm::ConstantInt::get(i64, PtrInt);
4040}
4041
4042static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4043 llvm::NamedMDNode *&GlobalMetadata,
4044 GlobalDecl D,
4045 llvm::GlobalValue *Addr) {
4046 if (!GlobalMetadata)
4047 GlobalMetadata =
4048 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4049
4050 // TODO: should we report variant information for ctors/dtors?
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004051 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4052 llvm::ConstantAsMetadata::get(GetPointerConstant(
4053 CGM.getLLVMContext(), D.getDecl()))};
Jay Foad6f141652011-04-21 19:59:12 +00004054 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall744016d2010-07-06 23:57:41 +00004055}
4056
Richard Smith00249372013-04-06 05:00:46 +00004057/// For each function which is declared within an extern "C" region and marked
4058/// as 'used', but has internal linkage, create an alias from the unmangled
4059/// name to the mangled name if possible. People expect to be able to refer
4060/// to such functions with an unmangled name from inline assembly within the
4061/// same translation unit.
4062void CodeGenModule::EmitStaticExternCAliases() {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07004063 // Don't do anything if we're generating CUDA device code -- the NVPTX
4064 // assembly target doesn't support aliases.
4065 if (Context.getTargetInfo().getTriple().isNVPTX())
4066 return;
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07004067 for (auto &I : StaticExternCValues) {
4068 IdentifierInfo *Name = I.first;
4069 llvm::GlobalValue *Val = I.second;
Richard Smith67972042013-04-06 07:07:44 +00004070 if (Val && !getModule().getNamedValue(Name->getName()))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004071 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
Richard Smith67972042013-04-06 07:07:44 +00004072 }
Richard Smith00249372013-04-06 05:00:46 +00004073}
4074
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004075bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4076 GlobalDecl &Result) const {
4077 auto Res = Manglings.find(MangledName);
4078 if (Res == Manglings.end())
4079 return false;
4080 Result = Res->getValue();
4081 return true;
4082}
4083
John McCall744016d2010-07-06 23:57:41 +00004084/// Emits metadata nodes associating all the global values in the
4085/// current module with the Decls they came from. This is useful for
4086/// projects using IR gen as a subroutine.
4087///
4088/// Since there's currently no way to associate an MDNode directly
4089/// with an llvm::GlobalValue, we create a global named metadata
4090/// with the name 'clang.global.decl.ptrs'.
4091void CodeGenModule::EmitDeclMetadata() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004092 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall744016d2010-07-06 23:57:41 +00004093
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004094 for (auto &I : MangledDeclNames) {
4095 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08004096 // Some mangled names don't necessarily have an associated GlobalValue
4097 // in this module, e.g. if we mangled it for DebugInfo.
4098 if (Addr)
4099 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
John McCall744016d2010-07-06 23:57:41 +00004100 }
4101}
4102
4103/// Emits metadata nodes for all the local variables in the current
4104/// function.
4105void CodeGenFunction::EmitDeclMetadata() {
4106 if (LocalDeclMap.empty()) return;
4107
4108 llvm::LLVMContext &Context = getLLVMContext();
4109
4110 // Find the unique metadata ID for this name.
4111 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4112
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004113 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall744016d2010-07-06 23:57:41 +00004114
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004115 for (auto &I : LocalDeclMap) {
4116 const Decl *D = I.first;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08004117 llvm::Value *Addr = I.second.getPointer();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004118 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
John McCall744016d2010-07-06 23:57:41 +00004119 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004120 Alloca->setMetadata(
4121 DeclPtrKind, llvm::MDNode::get(
4122 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004123 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
John McCall744016d2010-07-06 23:57:41 +00004124 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4125 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4126 }
4127 }
4128}
Daniel Dunbar673431a2010-07-16 00:00:15 +00004129
Rafael Espindola9686f122013-10-16 19:28:50 +00004130void CodeGenModule::EmitVersionIdentMetadata() {
4131 llvm::NamedMDNode *IdentMetadata =
4132 TheModule.getOrInsertNamedMetadata("llvm.ident");
4133 std::string Version = getClangFullVersion();
4134 llvm::LLVMContext &Ctx = TheModule.getContext();
4135
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004136 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
Rafael Espindola9686f122013-10-16 19:28:50 +00004137 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4138}
4139
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004140void CodeGenModule::EmitTargetMetadata() {
Stephen Hines176edba2014-12-01 14:53:08 -08004141 // Warning, new MangledDeclNames may be appended within this loop.
4142 // We rely on MapVector insertions adding new elements to the end
4143 // of the container.
4144 // FIXME: Move this loop into the one target that needs it, and only
4145 // loop over those declarations for which we couldn't emit the target
4146 // metadata when we emitted the declaration.
4147 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4148 auto Val = *(MangledDeclNames.begin() + I);
4149 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4150 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004151 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4152 }
4153}
4154
Nick Lewycky3dc05412011-05-05 00:08:20 +00004155void CodeGenModule::EmitCoverageFile() {
4156 if (!getCodeGenOpts().CoverageFile.empty()) {
Nick Lewycky5ea4f442011-05-04 20:46:58 +00004157 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
4158 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4159 llvm::LLVMContext &Ctx = TheModule.getContext();
Nick Lewycky3dc05412011-05-05 00:08:20 +00004160 llvm::MDString *CoverageFile =
4161 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
Nick Lewycky5ea4f442011-05-04 20:46:58 +00004162 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4163 llvm::MDNode *CU = CUNode->getOperand(i);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004164 llvm::Metadata *Elts[] = {CoverageFile, CU};
4165 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
Nick Lewycky5ea4f442011-05-04 20:46:58 +00004166 }
4167 }
4168 }
4169}
Nico Weberc5f80462012-10-11 10:13:44 +00004170
Stephen Hines176edba2014-12-01 14:53:08 -08004171llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
Nico Weberc5f80462012-10-11 10:13:44 +00004172 // Sema has checked that all uuid strings are of the form
4173 // "12345678-1234-1234-1234-1234567890ab".
4174 assert(Uuid.size() == 36);
David Majnemer8effeda2013-08-15 19:59:14 +00004175 for (unsigned i = 0; i < 36; ++i) {
4176 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4177 else assert(isHexDigit(Uuid[i]));
Nico Weberc5f80462012-10-11 10:13:44 +00004178 }
Nico Weberc5f80462012-10-11 10:13:44 +00004179
Stephen Hines176edba2014-12-01 14:53:08 -08004180 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
David Majnemer8effeda2013-08-15 19:59:14 +00004181 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Weberc5f80462012-10-11 10:13:44 +00004182
David Majnemer8effeda2013-08-15 19:59:14 +00004183 llvm::Constant *Field3[8];
4184 for (unsigned Idx = 0; Idx < 8; ++Idx)
4185 Field3[Idx] = llvm::ConstantInt::get(
4186 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4187
4188 llvm::Constant *Fields[4] = {
4189 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
4190 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
4191 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4192 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4193 };
4194
4195 return llvm::ConstantStruct::getAnon(Fields);
Nico Weberc5f80462012-10-11 10:13:44 +00004196}
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004197
4198llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4199 bool ForEH) {
4200 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4201 // FIXME: should we even be calling this method if RTTI is disabled
4202 // and it's not for EH?
4203 if (!ForEH && !getLangOpts().RTTI)
4204 return llvm::Constant::getNullValue(Int8PtrTy);
4205
4206 if (ForEH && Ty->isObjCObjectPointerType() &&
4207 LangOpts.ObjCRuntime.isGNUFamily())
4208 return ObjCRuntime->GetEHType(Ty);
4209
4210 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
4211}
4212
Stephen Hines176edba2014-12-01 14:53:08 -08004213void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4214 for (auto RefExpr : D->varlists()) {
4215 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4216 bool PerformInit =
4217 VD->getAnyInitializer() &&
4218 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4219 /*ForRef=*/false);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08004220
4221 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004222 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08004223 VD, Addr, RefExpr->getLocStart(), PerformInit))
Stephen Hines176edba2014-12-01 14:53:08 -08004224 CXXGlobalInits.push_back(InitFunction);
4225 }
4226}
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08004227
4228llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4229 llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4230 if (InternalId)
4231 return InternalId;
4232
4233 if (isExternallyVisible(T->getLinkage())) {
4234 std::string OutName;
4235 llvm::raw_string_ostream Out(OutName);
4236 getCXXABI().getMangleContext().mangleTypeName(T, Out);
4237
4238 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4239 } else {
4240 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4241 llvm::ArrayRef<llvm::Metadata *>());
4242 }
4243
4244 return InternalId;
4245}
4246
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07004247/// Returns whether this module needs the "all-vtables" type identifier.
4248bool CodeGenModule::NeedAllVtablesTypeId() const {
4249 // Returns true if at least one of vtable-based CFI checkers is enabled and
4250 // is not in the trapping mode.
4251 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4252 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4253 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4254 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4255 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4256 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4257 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4258 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4259}
4260
4261void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
4262 CharUnits Offset,
4263 const CXXRecordDecl *RD) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08004264 llvm::Metadata *MD =
4265 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07004266 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08004267
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07004268 if (CodeGenOpts.SanitizeCfiCrossDso)
4269 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4270 VTable->addTypeMetadata(Offset.getQuantity(),
4271 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4272
4273 if (NeedAllVtablesTypeId()) {
4274 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4275 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08004276 }
4277}
4278
4279// Fills in the supplied string map with the set of target features for the
4280// passed in function.
4281void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4282 const FunctionDecl *FD) {
4283 StringRef TargetCPU = Target.getTargetOpts().CPU;
4284 if (const auto *TD = FD->getAttr<TargetAttr>()) {
4285 // If we have a TargetAttr build up the feature map based on that.
4286 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4287
4288 // Make a copy of the features as passed on the command line into the
4289 // beginning of the additional features from the function to override.
4290 ParsedAttr.first.insert(ParsedAttr.first.begin(),
4291 Target.getTargetOpts().FeaturesAsWritten.begin(),
4292 Target.getTargetOpts().FeaturesAsWritten.end());
4293
4294 if (ParsedAttr.second != "")
4295 TargetCPU = ParsedAttr.second;
4296
4297 // Now populate the feature map, first with the TargetCPU which is either
4298 // the default or a new one from the target attribute string. Then we'll use
4299 // the passed in features (FeaturesAsWritten) along with the new ones from
4300 // the attribute.
4301 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
4302 } else {
4303 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4304 Target.getTargetOpts().Features);
4305 }
4306}
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07004307
4308llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4309 if (!SanStats)
4310 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4311
4312 return *SanStats;
4313}