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