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