Bug Summary

File:tools/clang/lib/CodeGen/CodeGenModule.cpp
Location:line 2307, column 9
Description:Called C++ object pointer is null

Annotated Source Code

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