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