Bug Summary

File:src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
Warning:line 1396, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ClangExpressionParser.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model static -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../include -I /usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/obj -I /usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -I /usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/include -I /usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source -I /usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/clang/include -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -stack-protector 2 -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp

/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp

1//===-- ClangExpressionParser.cpp -----------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "clang/AST/ASTContext.h"
10#include "clang/AST/ASTDiagnostic.h"
11#include "clang/AST/ExternalASTSource.h"
12#include "clang/AST/PrettyPrinter.h"
13#include "clang/Basic/Builtins.h"
14#include "clang/Basic/DiagnosticIDs.h"
15#include "clang/Basic/SourceLocation.h"
16#include "clang/Basic/TargetInfo.h"
17#include "clang/Basic/Version.h"
18#include "clang/CodeGen/CodeGenAction.h"
19#include "clang/CodeGen/ModuleBuilder.h"
20#include "clang/Edit/Commit.h"
21#include "clang/Edit/EditedSource.h"
22#include "clang/Edit/EditsReceiver.h"
23#include "clang/Frontend/CompilerInstance.h"
24#include "clang/Frontend/CompilerInvocation.h"
25#include "clang/Frontend/FrontendActions.h"
26#include "clang/Frontend/FrontendDiagnostic.h"
27#include "clang/Frontend/FrontendPluginRegistry.h"
28#include "clang/Frontend/TextDiagnosticBuffer.h"
29#include "clang/Frontend/TextDiagnosticPrinter.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Parse/ParseAST.h"
32#include "clang/Rewrite/Core/Rewriter.h"
33#include "clang/Rewrite/Frontend/FrontendActions.h"
34#include "clang/Sema/CodeCompleteConsumer.h"
35#include "clang/Sema/Sema.h"
36#include "clang/Sema/SemaConsumer.h"
37
38#include "llvm/ADT/StringRef.h"
39#include "llvm/ExecutionEngine/ExecutionEngine.h"
40#include "llvm/Support/CrashRecoveryContext.h"
41#include "llvm/Support/Debug.h"
42#include "llvm/Support/FileSystem.h"
43#include "llvm/Support/TargetSelect.h"
44
45#include "llvm/IR/LLVMContext.h"
46#include "llvm/IR/Module.h"
47#include "llvm/Support/DynamicLibrary.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/Host.h"
50#include "llvm/Support/MemoryBuffer.h"
51#include "llvm/Support/Signals.h"
52
53#include "ClangDiagnostic.h"
54#include "ClangExpressionParser.h"
55#include "ClangUserExpression.h"
56
57#include "ASTUtils.h"
58#include "ClangASTSource.h"
59#include "ClangDiagnostic.h"
60#include "ClangExpressionDeclMap.h"
61#include "ClangExpressionHelper.h"
62#include "ClangExpressionParser.h"
63#include "ClangHost.h"
64#include "ClangModulesDeclVendor.h"
65#include "ClangPersistentVariables.h"
66#include "IRDynamicChecks.h"
67#include "IRForTarget.h"
68#include "ModuleDependencyCollector.h"
69
70#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
71#include "lldb/Core/Debugger.h"
72#include "lldb/Core/Disassembler.h"
73#include "lldb/Core/Module.h"
74#include "lldb/Core/StreamFile.h"
75#include "lldb/Expression/IRExecutionUnit.h"
76#include "lldb/Expression/IRInterpreter.h"
77#include "lldb/Host/File.h"
78#include "lldb/Host/HostInfo.h"
79#include "lldb/Symbol/SymbolVendor.h"
80#include "lldb/Target/ExecutionContext.h"
81#include "lldb/Target/Language.h"
82#include "lldb/Target/Process.h"
83#include "lldb/Target/Target.h"
84#include "lldb/Target/ThreadPlanCallFunction.h"
85#include "lldb/Utility/DataBufferHeap.h"
86#include "lldb/Utility/LLDBAssert.h"
87#include "lldb/Utility/Log.h"
88#include "lldb/Utility/ReproducerProvider.h"
89#include "lldb/Utility/Stream.h"
90#include "lldb/Utility/StreamString.h"
91#include "lldb/Utility/StringList.h"
92
93#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
94#include "Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.h"
95
96#include <cctype>
97#include <memory>
98
99using namespace clang;
100using namespace llvm;
101using namespace lldb_private;
102
103//===----------------------------------------------------------------------===//
104// Utility Methods for Clang
105//===----------------------------------------------------------------------===//
106
107class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks {
108 ClangModulesDeclVendor &m_decl_vendor;
109 ClangPersistentVariables &m_persistent_vars;
110 clang::SourceManager &m_source_mgr;
111 StreamString m_error_stream;
112 bool m_has_errors = false;
113
114public:
115 LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
116 ClangPersistentVariables &persistent_vars,
117 clang::SourceManager &source_mgr)
118 : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars),
119 m_source_mgr(source_mgr) {}
120
121 void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,
122 const clang::Module * /*null*/) override {
123 // Ignore modules that are imported in the wrapper code as these are not
124 // loaded by the user.
125 llvm::StringRef filename =
126 m_source_mgr.getPresumedLoc(import_location).getFilename();
127 if (filename == ClangExpressionSourceCode::g_prefix_file_name)
128 return;
129
130 SourceModule module;
131
132 for (const std::pair<IdentifierInfo *, SourceLocation> &component : path)
133 module.path.push_back(ConstString(component.first->getName()));
134
135 StreamString error_stream;
136
137 ClangModulesDeclVendor::ModuleVector exported_modules;
138 if (!m_decl_vendor.AddModule(module, &exported_modules, m_error_stream))
139 m_has_errors = true;
140
141 for (ClangModulesDeclVendor::ModuleID module : exported_modules)
142 m_persistent_vars.AddHandLoadedClangModule(module);
143 }
144
145 bool hasErrors() { return m_has_errors; }
146
147 llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
148};
149
150static void AddAllFixIts(ClangDiagnostic *diag, const clang::Diagnostic &Info) {
151 for (auto &fix_it : Info.getFixItHints()) {
152 if (fix_it.isNull())
153 continue;
154 diag->AddFixitHint(fix_it);
155 }
156}
157
158class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
159public:
160 ClangDiagnosticManagerAdapter(DiagnosticOptions &opts) {
161 DiagnosticOptions *options = new DiagnosticOptions(opts);
162 options->ShowPresumedLoc = true;
163 options->ShowLevel = false;
164 m_os = std::make_shared<llvm::raw_string_ostream>(m_output);
165 m_passthrough =
166 std::make_shared<clang::TextDiagnosticPrinter>(*m_os, options);
167 }
168
169 void ResetManager(DiagnosticManager *manager = nullptr) {
170 m_manager = manager;
171 }
172
173 /// Returns the last ClangDiagnostic message that the DiagnosticManager
174 /// received or a nullptr if the DiagnosticMangager hasn't seen any
175 /// Clang diagnostics yet.
176 ClangDiagnostic *MaybeGetLastClangDiag() const {
177 if (m_manager->Diagnostics().empty())
178 return nullptr;
179 lldb_private::Diagnostic *diag = m_manager->Diagnostics().back().get();
180 ClangDiagnostic *clang_diag = dyn_cast<ClangDiagnostic>(diag);
181 return clang_diag;
182 }
183
184 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
185 const clang::Diagnostic &Info) override {
186 if (!m_manager) {
187 // We have no DiagnosticManager before/after parsing but we still could
188 // receive diagnostics (e.g., by the ASTImporter failing to copy decls
189 // when we move the expression result ot the ScratchASTContext). Let's at
190 // least log these diagnostics until we find a way to properly render
191 // them and display them to the user.
192 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS(1u << 8)));
193 if (log) {
194 llvm::SmallVector<char, 32> diag_str;
195 Info.FormatDiagnostic(diag_str);
196 diag_str.push_back('\0');
197 const char *plain_diag = diag_str.data();
198 LLDB_LOG(log, "Received diagnostic outside parsing: {0}", plain_diag)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, __func__, "Received diagnostic outside parsing: {0}", plain_diag
); } while (0)
;
199 }
200 return;
201 }
202
203 // Update error/warning counters.
204 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
205
206 // Render diagnostic message to m_output.
207 m_output.clear();
208 m_passthrough->HandleDiagnostic(DiagLevel, Info);
209 m_os->flush();
210
211 lldb_private::DiagnosticSeverity severity;
212 bool make_new_diagnostic = true;
213
214 switch (DiagLevel) {
215 case DiagnosticsEngine::Level::Fatal:
216 case DiagnosticsEngine::Level::Error:
217 severity = eDiagnosticSeverityError;
218 break;
219 case DiagnosticsEngine::Level::Warning:
220 severity = eDiagnosticSeverityWarning;
221 break;
222 case DiagnosticsEngine::Level::Remark:
223 case DiagnosticsEngine::Level::Ignored:
224 severity = eDiagnosticSeverityRemark;
225 break;
226 case DiagnosticsEngine::Level::Note:
227 m_manager->AppendMessageToDiagnostic(m_output);
228 make_new_diagnostic = false;
229
230 // 'note:' diagnostics for errors and warnings can also contain Fix-Its.
231 // We add these Fix-Its to the last error diagnostic to make sure
232 // that we later have all Fix-Its related to an 'error' diagnostic when
233 // we apply them to the user expression.
234 auto *clang_diag = MaybeGetLastClangDiag();
235 // If we don't have a previous diagnostic there is nothing to do.
236 // If the previous diagnostic already has its own Fix-Its, assume that
237 // the 'note:' Fix-It is just an alternative way to solve the issue and
238 // ignore these Fix-Its.
239 if (!clang_diag || clang_diag->HasFixIts())
240 break;
241 // Ignore all Fix-Its that are not associated with an error.
242 if (clang_diag->GetSeverity() != eDiagnosticSeverityError)
243 break;
244 AddAllFixIts(clang_diag, Info);
245 break;
246 }
247 if (make_new_diagnostic) {
248 // ClangDiagnostic messages are expected to have no whitespace/newlines
249 // around them.
250 std::string stripped_output =
251 std::string(llvm::StringRef(m_output).trim());
252
253 auto new_diagnostic = std::make_unique<ClangDiagnostic>(
254 stripped_output, severity, Info.getID());
255
256 // Don't store away warning fixits, since the compiler doesn't have
257 // enough context in an expression for the warning to be useful.
258 // FIXME: Should we try to filter out FixIts that apply to our generated
259 // code, and not the user's expression?
260 if (severity == eDiagnosticSeverityError)
261 AddAllFixIts(new_diagnostic.get(), Info);
262
263 m_manager->AddDiagnostic(std::move(new_diagnostic));
264 }
265 }
266
267 void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP) override {
268 m_passthrough->BeginSourceFile(LO, PP);
269 }
270
271 void EndSourceFile() override { m_passthrough->EndSourceFile(); }
272
273private:
274 DiagnosticManager *m_manager = nullptr;
275 std::shared_ptr<clang::TextDiagnosticPrinter> m_passthrough;
276 /// Output stream of m_passthrough.
277 std::shared_ptr<llvm::raw_string_ostream> m_os;
278 /// Output string filled by m_os.
279 std::string m_output;
280};
281
282static void SetupModuleHeaderPaths(CompilerInstance *compiler,
283 std::vector<std::string> include_directories,
284 lldb::TargetSP target_sp) {
285 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS(1u << 8)));
286
287 HeaderSearchOptions &search_opts = compiler->getHeaderSearchOpts();
288
289 for (const std::string &dir : include_directories) {
290 search_opts.AddPath(dir, frontend::System, false, true);
291 LLDB_LOG(log, "Added user include dir: {0}", dir)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, __func__, "Added user include dir: {0}", dir); } while (0)
;
292 }
293
294 llvm::SmallString<128> module_cache;
295 const auto &props = ModuleList::GetGlobalModuleListProperties();
296 props.GetClangModulesCachePath().GetPath(module_cache);
297 search_opts.ModuleCachePath = std::string(module_cache.str());
298 LLDB_LOG(log, "Using module cache path: {0}", module_cache.c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, __func__, "Using module cache path: {0}", module_cache.c_str
()); } while (0)
;
299
300 search_opts.ResourceDir = GetClangResourceDir().GetPath();
301
302 search_opts.ImplicitModuleMaps = true;
303}
304
305/// Iff the given identifier is a C++ keyword, remove it from the
306/// identifier table (i.e., make the token a normal identifier).
307static void RemoveCppKeyword(IdentifierTable &idents, llvm::StringRef token) {
308 // FIXME: 'using' is used by LLDB for local variables, so we can't remove
309 // this keyword without breaking this functionality.
310 if (token == "using")
311 return;
312 // GCC's '__null' is used by LLDB to define NULL/Nil/nil.
313 if (token == "__null")
314 return;
315
316 LangOptions cpp_lang_opts;
317 cpp_lang_opts.CPlusPlus = true;
318 cpp_lang_opts.CPlusPlus11 = true;
319 cpp_lang_opts.CPlusPlus20 = true;
320
321 clang::IdentifierInfo &ii = idents.get(token);
322 // The identifier has to be a C++-exclusive keyword. if not, then there is
323 // nothing to do.
324 if (!ii.isCPlusPlusKeyword(cpp_lang_opts))
325 return;
326 // If the token is already an identifier, then there is nothing to do.
327 if (ii.getTokenID() == clang::tok::identifier)
328 return;
329 // Otherwise the token is a C++ keyword, so turn it back into a normal
330 // identifier.
331 ii.revertTokenIDToIdentifier();
332}
333
334/// Remove all C++ keywords from the given identifier table.
335static void RemoveAllCppKeywords(IdentifierTable &idents) {
336#define KEYWORD(NAME, FLAGS) RemoveCppKeyword(idents, llvm::StringRef(#NAME));
337#include "clang/Basic/TokenKinds.def"
338}
339
340/// Configures Clang diagnostics for the expression parser.
341static void SetupDefaultClangDiagnostics(CompilerInstance &compiler) {
342 // List of Clang warning groups that are not useful when parsing expressions.
343 const std::vector<const char *> groupsToIgnore = {
344 "unused-value",
345 "odr",
346 "unused-getter-return-value",
347 };
348 for (const char *group : groupsToIgnore) {
349 compiler.getDiagnostics().setSeverityForGroup(
350 clang::diag::Flavor::WarningOrError, group,
351 clang::diag::Severity::Ignored, SourceLocation());
352 }
353}
354
355//===----------------------------------------------------------------------===//
356// Implementation of ClangExpressionParser
357//===----------------------------------------------------------------------===//
358
359ClangExpressionParser::ClangExpressionParser(
360 ExecutionContextScope *exe_scope, Expression &expr,
361 bool generate_debug_info, std::vector<std::string> include_directories,
362 std::string filename)
363 : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
364 m_pp_callbacks(nullptr),
365 m_include_directories(std::move(include_directories)),
366 m_filename(std::move(filename)) {
367 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS(1u << 8)));
368
369 // We can't compile expressions without a target. So if the exe_scope is
370 // null or doesn't have a target, then we just need to get out of here. I'll
371 // lldbassert and not make any of the compiler objects since
372 // I can't return errors directly from the constructor. Further calls will
373 // check if the compiler was made and
374 // bag out if it wasn't.
375
376 if (!exe_scope) {
377 lldbassert(exe_scope &&lldb_private::lldb_assert(static_cast<bool>(exe_scope &&
"Can't make an expression parser with a null scope."), "exe_scope && \"Can't make an expression parser with a null scope.\""
, __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, 378)
378 "Can't make an expression parser with a null scope.")lldb_private::lldb_assert(static_cast<bool>(exe_scope &&
"Can't make an expression parser with a null scope."), "exe_scope && \"Can't make an expression parser with a null scope.\""
, __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, 378)
;
379 return;
380 }
381
382 lldb::TargetSP target_sp;
383 target_sp = exe_scope->CalculateTarget();
384 if (!target_sp) {
385 lldbassert(target_sp.get() &&lldb_private::lldb_assert(static_cast<bool>(target_sp.get
() && "Can't make an expression parser with a null target."
), "target_sp.get() && \"Can't make an expression parser with a null target.\""
, __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, 386)
386 "Can't make an expression parser with a null target.")lldb_private::lldb_assert(static_cast<bool>(target_sp.get
() && "Can't make an expression parser with a null target."
), "target_sp.get() && \"Can't make an expression parser with a null target.\""
, __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, 386)
;
387 return;
388 }
389
390 // 1. Create a new compiler instance.
391 m_compiler = std::make_unique<CompilerInstance>();
392
393 // When capturing a reproducer, hook up the file collector with clang to
394 // collector modules and headers.
395 if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
396 repro::FileProvider &fp = g->GetOrCreate<repro::FileProvider>();
397 m_compiler->setModuleDepCollector(
398 std::make_shared<ModuleDependencyCollectorAdaptor>(
399 fp.GetFileCollector()));
400 DependencyOutputOptions &opts = m_compiler->getDependencyOutputOpts();
401 opts.IncludeSystemHeaders = true;
402 opts.IncludeModuleFiles = true;
403 }
404
405 // Make sure clang uses the same VFS as LLDB.
406 m_compiler->createFileManager(FileSystem::Instance().GetVirtualFileSystem());
407
408 lldb::LanguageType frame_lang =
409 expr.Language(); // defaults to lldb::eLanguageTypeUnknown
410 bool overridden_target_opts = false;
411 lldb_private::LanguageRuntime *lang_rt = nullptr;
412
413 std::string abi;
414 ArchSpec target_arch;
415 target_arch = target_sp->GetArchitecture();
416
417 const auto target_machine = target_arch.GetMachine();
418
419 // If the expression is being evaluated in the context of an existing stack
420 // frame, we introspect to see if the language runtime is available.
421
422 lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame();
423 lldb::ProcessSP process_sp = exe_scope->CalculateProcess();
424
425 // Make sure the user hasn't provided a preferred execution language with
426 // `expression --language X -- ...`
427 if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
428 frame_lang = frame_sp->GetLanguage();
429
430 if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {
431 lang_rt = process_sp->GetLanguageRuntime(frame_lang);
432 LLDB_LOGF(log, "Frame has language of type %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Frame has language of type %s", Language
::GetNameForLanguageType(frame_lang)); } while (0)
433 Language::GetNameForLanguageType(frame_lang))do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Frame has language of type %s", Language
::GetNameForLanguageType(frame_lang)); } while (0)
;
434 }
435
436 // 2. Configure the compiler with a set of default options that are
437 // appropriate for most situations.
438 if (target_arch.IsValid()) {
439 std::string triple = target_arch.GetTriple().str();
440 m_compiler->getTargetOpts().Triple = triple;
441 LLDB_LOGF(log, "Using %s as the target triple",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Using %s as the target triple", m_compiler
->getTargetOpts().Triple.c_str()); } while (0)
442 m_compiler->getTargetOpts().Triple.c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Using %s as the target triple", m_compiler
->getTargetOpts().Triple.c_str()); } while (0)
;
443 } else {
444 // If we get here we don't have a valid target and just have to guess.
445 // Sometimes this will be ok to just use the host target triple (when we
446 // evaluate say "2+3", but other expressions like breakpoint conditions and
447 // other things that _are_ target specific really shouldn't just be using
448 // the host triple. In such a case the language runtime should expose an
449 // overridden options set (3), below.
450 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
451 LLDB_LOGF(log, "Using default target triple of %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Using default target triple of %s",
m_compiler->getTargetOpts().Triple.c_str()); } while (0)
452 m_compiler->getTargetOpts().Triple.c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Using default target triple of %s",
m_compiler->getTargetOpts().Triple.c_str()); } while (0)
;
453 }
454 // Now add some special fixes for known architectures: Any arm32 iOS
455 // environment, but not on arm64
456 if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
457 m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
458 m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) {
459 m_compiler->getTargetOpts().ABI = "apcs-gnu";
460 }
461 // Supported subsets of x86
462 if (target_machine == llvm::Triple::x86 ||
463 target_machine == llvm::Triple::x86_64) {
464 m_compiler->getTargetOpts().Features.push_back("+sse");
465 m_compiler->getTargetOpts().Features.push_back("+sse2");
466 }
467
468 // Set the target CPU to generate code for. This will be empty for any CPU
469 // that doesn't really need to make a special
470 // CPU string.
471 m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
472
473 // Set the target ABI
474 abi = GetClangTargetABI(target_arch);
475 if (!abi.empty())
476 m_compiler->getTargetOpts().ABI = abi;
477
478 // 3. Now allow the runtime to provide custom configuration options for the
479 // target. In this case, a specialized language runtime is available and we
480 // can query it for extra options. For 99% of use cases, this will not be
481 // needed and should be provided when basic platform detection is not enough.
482 // FIXME: Generalize this. Only RenderScriptRuntime currently supports this
483 // currently. Hardcoding this isn't ideal but it's better than LanguageRuntime
484 // having knowledge of clang::TargetOpts.
485 if (auto *renderscript_rt =
486 llvm::dyn_cast_or_null<RenderScriptRuntime>(lang_rt))
487 overridden_target_opts =
488 renderscript_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
489
490 if (overridden_target_opts)
491 if (log && log->GetVerbose()) {
492 LLDB_LOGV(do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, __func__, "Using overridden target options for the expression evaluation"
); } while (0)
493 log, "Using overridden target options for the expression evaluation")do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, __func__, "Using overridden target options for the expression evaluation"
); } while (0)
;
494
495 auto opts = m_compiler->getTargetOpts();
496 LLDB_LOGV(log, "Triple: '{0}'", opts.Triple)do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, __func__, "Triple: '{0}'", opts.Triple); } while (0)
;
497 LLDB_LOGV(log, "CPU: '{0}'", opts.CPU)do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, __func__, "CPU: '{0}'", opts.CPU); } while (0)
;
498 LLDB_LOGV(log, "FPMath: '{0}'", opts.FPMath)do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, __func__, "FPMath: '{0}'", opts.FPMath); } while (0)
;
499 LLDB_LOGV(log, "ABI: '{0}'", opts.ABI)do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, __func__, "ABI: '{0}'", opts.ABI); } while (0)
;
500 LLDB_LOGV(log, "LinkerVersion: '{0}'", opts.LinkerVersion)do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, __func__, "LinkerVersion: '{0}'", opts.LinkerVersion); } while
(0)
;
501 StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
502 StringList::LogDump(log, opts.Features, "Features");
503 }
504
505 // 4. Create and install the target on the compiler.
506 m_compiler->createDiagnostics();
507 // Limit the number of error diagnostics we emit.
508 // A value of 0 means no limit for both LLDB and Clang.
509 m_compiler->getDiagnostics().setErrorLimit(target_sp->GetExprErrorLimit());
510
511 auto target_info = TargetInfo::CreateTargetInfo(
512 m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
513 if (log) {
514 LLDB_LOGF(log, "Using SIMD alignment: %d",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Using SIMD alignment: %d", target_info
->getSimdDefaultAlign()); } while (0)
515 target_info->getSimdDefaultAlign())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Using SIMD alignment: %d", target_info
->getSimdDefaultAlign()); } while (0)
;
516 LLDB_LOGF(log, "Target datalayout string: '%s'",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Target datalayout string: '%s'", target_info
->getDataLayoutString()); } while (0)
517 target_info->getDataLayoutString())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Target datalayout string: '%s'", target_info
->getDataLayoutString()); } while (0)
;
518 LLDB_LOGF(log, "Target ABI: '%s'", target_info->getABI().str().c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Target ABI: '%s'", target_info->
getABI().str().c_str()); } while (0)
;
519 LLDB_LOGF(log, "Target vector alignment: %d",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Target vector alignment: %d", target_info
->getMaxVectorAlign()); } while (0)
520 target_info->getMaxVectorAlign())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Target vector alignment: %d", target_info
->getMaxVectorAlign()); } while (0)
;
521 }
522 m_compiler->setTarget(target_info);
523
524 assert(m_compiler->hasTarget())((void)0);
525
526 // 5. Set language options.
527 lldb::LanguageType language = expr.Language();
528 LangOptions &lang_opts = m_compiler->getLangOpts();
529
530 switch (language) {
531 case lldb::eLanguageTypeC:
532 case lldb::eLanguageTypeC89:
533 case lldb::eLanguageTypeC99:
534 case lldb::eLanguageTypeC11:
535 // FIXME: the following language option is a temporary workaround,
536 // to "ask for C, get C++."
537 // For now, the expression parser must use C++ anytime the language is a C
538 // family language, because the expression parser uses features of C++ to
539 // capture values.
540 lang_opts.CPlusPlus = true;
541 break;
542 case lldb::eLanguageTypeObjC:
543 lang_opts.ObjC = true;
544 // FIXME: the following language option is a temporary workaround,
545 // to "ask for ObjC, get ObjC++" (see comment above).
546 lang_opts.CPlusPlus = true;
547
548 // Clang now sets as default C++14 as the default standard (with
549 // GNU extensions), so we do the same here to avoid mismatches that
550 // cause compiler error when evaluating expressions (e.g. nullptr not found
551 // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
552 // two lines below) so we decide to be consistent with that, but this could
553 // be re-evaluated in the future.
554 lang_opts.CPlusPlus11 = true;
555 break;
556 case lldb::eLanguageTypeC_plus_plus:
557 case lldb::eLanguageTypeC_plus_plus_11:
558 case lldb::eLanguageTypeC_plus_plus_14:
559 lang_opts.CPlusPlus11 = true;
560 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
561 LLVM_FALLTHROUGH[[gnu::fallthrough]];
562 case lldb::eLanguageTypeC_plus_plus_03:
563 lang_opts.CPlusPlus = true;
564 if (process_sp)
565 lang_opts.ObjC =
566 process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr;
567 break;
568 case lldb::eLanguageTypeObjC_plus_plus:
569 case lldb::eLanguageTypeUnknown:
570 default:
571 lang_opts.ObjC = true;
572 lang_opts.CPlusPlus = true;
573 lang_opts.CPlusPlus11 = true;
574 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
575 break;
576 }
577
578 lang_opts.Bool = true;
579 lang_opts.WChar = true;
580 lang_opts.Blocks = true;
581 lang_opts.DebuggerSupport =
582 true; // Features specifically for debugger clients
583 if (expr.DesiredResultType() == Expression::eResultTypeId)
584 lang_opts.DebuggerCastResultToId = true;
585
586 lang_opts.CharIsSigned = ArchSpec(m_compiler->getTargetOpts().Triple.c_str())
587 .CharIsSignedByDefault();
588
589 // Spell checking is a nice feature, but it ends up completing a lot of types
590 // that we didn't strictly speaking need to complete. As a result, we spend a
591 // long time parsing and importing debug information.
592 lang_opts.SpellChecking = false;
593
594 auto *clang_expr = dyn_cast<ClangUserExpression>(&m_expr);
595 if (clang_expr && clang_expr->DidImportCxxModules()) {
596 LLDB_LOG(log, "Adding lang options for importing C++ modules")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, __func__, "Adding lang options for importing C++ modules");
} while (0)
;
597
598 lang_opts.Modules = true;
599 // We want to implicitly build modules.
600 lang_opts.ImplicitModules = true;
601 // To automatically import all submodules when we import 'std'.
602 lang_opts.ModulesLocalVisibility = false;
603
604 // We use the @import statements, so we need this:
605 // FIXME: We could use the modules-ts, but that currently doesn't work.
606 lang_opts.ObjC = true;
607
608 // Options we need to parse libc++ code successfully.
609 // FIXME: We should ask the driver for the appropriate default flags.
610 lang_opts.GNUMode = true;
611 lang_opts.GNUKeywords = true;
612 lang_opts.DoubleSquareBracketAttributes = true;
613 lang_opts.CPlusPlus11 = true;
614
615 // The Darwin libc expects this macro to be set.
616 lang_opts.GNUCVersion = 40201;
617
618 SetupModuleHeaderPaths(m_compiler.get(), m_include_directories,
619 target_sp);
620 }
621
622 if (process_sp && lang_opts.ObjC) {
623 if (auto *runtime = ObjCLanguageRuntime::Get(*process_sp)) {
624 if (runtime->GetRuntimeVersion() ==
625 ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
626 lang_opts.ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
627 else
628 lang_opts.ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
629 VersionTuple(10, 7));
630
631 if (runtime->HasNewLiteralsAndIndexing())
632 lang_opts.DebuggerObjCLiteral = true;
633 }
634 }
635
636 lang_opts.ThreadsafeStatics = false;
637 lang_opts.AccessControl = false; // Debuggers get universal access
638 lang_opts.DollarIdents = true; // $ indicates a persistent variable name
639 // We enable all builtin functions beside the builtins from libc/libm (e.g.
640 // 'fopen'). Those libc functions are already correctly handled by LLDB, and
641 // additionally enabling them as expandable builtins is breaking Clang.
642 lang_opts.NoBuiltin = true;
643
644 // Set CodeGen options
645 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
646 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
647 m_compiler->getCodeGenOpts().setFramePointer(
648 CodeGenOptions::FramePointerKind::All);
649 if (generate_debug_info)
650 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
651 else
652 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
653
654 // Disable some warnings.
655 SetupDefaultClangDiagnostics(*m_compiler);
656
657 // Inform the target of the language options
658 //
659 // FIXME: We shouldn't need to do this, the target should be immutable once
660 // created. This complexity should be lifted elsewhere.
661 m_compiler->getTarget().adjust(m_compiler->getDiagnostics(),
662 m_compiler->getLangOpts());
663
664 // 6. Set up the diagnostic buffer for reporting errors
665
666 auto diag_mgr = new ClangDiagnosticManagerAdapter(
667 m_compiler->getDiagnostics().getDiagnosticOptions());
668 m_compiler->getDiagnostics().setClient(diag_mgr);
669
670 // 7. Set up the source management objects inside the compiler
671 m_compiler->createFileManager();
672 if (!m_compiler->hasSourceManager())
673 m_compiler->createSourceManager(m_compiler->getFileManager());
674 m_compiler->createPreprocessor(TU_Complete);
675
676 switch (language) {
677 case lldb::eLanguageTypeC:
678 case lldb::eLanguageTypeC89:
679 case lldb::eLanguageTypeC99:
680 case lldb::eLanguageTypeC11:
681 case lldb::eLanguageTypeObjC:
682 // This is not a C++ expression but we enabled C++ as explained above.
683 // Remove all C++ keywords from the PP so that the user can still use
684 // variables that have C++ keywords as names (e.g. 'int template;').
685 RemoveAllCppKeywords(m_compiler->getPreprocessor().getIdentifierTable());
686 break;
687 default:
688 break;
689 }
690
691 if (auto *clang_persistent_vars = llvm::cast<ClangPersistentVariables>(
692 target_sp->GetPersistentExpressionStateForLanguage(
693 lldb::eLanguageTypeC))) {
694 if (std::shared_ptr<ClangModulesDeclVendor> decl_vendor =
695 clang_persistent_vars->GetClangModulesDeclVendor()) {
696 std::unique_ptr<PPCallbacks> pp_callbacks(
697 new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars,
698 m_compiler->getSourceManager()));
699 m_pp_callbacks =
700 static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
701 m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
702 }
703 }
704
705 // 8. Most of this we get from the CompilerInstance, but we also want to give
706 // the context an ExternalASTSource.
707
708 auto &PP = m_compiler->getPreprocessor();
709 auto &builtin_context = PP.getBuiltinInfo();
710 builtin_context.initializeBuiltins(PP.getIdentifierTable(),
711 m_compiler->getLangOpts());
712
713 m_compiler->createASTContext();
714 clang::ASTContext &ast_context = m_compiler->getASTContext();
715
716 m_ast_context = std::make_unique<TypeSystemClang>(
717 "Expression ASTContext for '" + m_filename + "'", ast_context);
718
719 std::string module_name("$__lldb_module");
720
721 m_llvm_context = std::make_unique<LLVMContext>();
722 m_code_generator.reset(CreateLLVMCodeGen(
723 m_compiler->getDiagnostics(), module_name,
724 m_compiler->getHeaderSearchOpts(), m_compiler->getPreprocessorOpts(),
725 m_compiler->getCodeGenOpts(), *m_llvm_context));
726}
727
728ClangExpressionParser::~ClangExpressionParser() = default;
729
730namespace {
731
732/// \class CodeComplete
733///
734/// A code completion consumer for the clang Sema that is responsible for
735/// creating the completion suggestions when a user requests completion
736/// of an incomplete `expr` invocation.
737class CodeComplete : public CodeCompleteConsumer {
738 CodeCompletionTUInfo m_info;
739
740 std::string m_expr;
741 unsigned m_position = 0;
742 /// The printing policy we use when printing declarations for our completion
743 /// descriptions.
744 clang::PrintingPolicy m_desc_policy;
745
746 struct CompletionWithPriority {
747 CompletionResult::Completion completion;
748 /// See CodeCompletionResult::Priority;
749 unsigned Priority;
750
751 /// Establishes a deterministic order in a list of CompletionWithPriority.
752 /// The order returned here is the order in which the completions are
753 /// displayed to the user.
754 bool operator<(const CompletionWithPriority &o) const {
755 // High priority results should come first.
756 if (Priority != o.Priority)
757 return Priority > o.Priority;
758
759 // Identical priority, so just make sure it's a deterministic order.
760 return completion.GetUniqueKey() < o.completion.GetUniqueKey();
761 }
762 };
763
764 /// The stored completions.
765 /// Warning: These are in a non-deterministic order until they are sorted
766 /// and returned back to the caller.
767 std::vector<CompletionWithPriority> m_completions;
768
769 /// Returns true if the given character can be used in an identifier.
770 /// This also returns true for numbers because for completion we usually
771 /// just iterate backwards over iterators.
772 ///
773 /// Note: lldb uses '$' in its internal identifiers, so we also allow this.
774 static bool IsIdChar(char c) {
775 return c == '_' || std::isalnum(c) || c == '$';
776 }
777
778 /// Returns true if the given character is used to separate arguments
779 /// in the command line of lldb.
780 static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; }
781
782 /// Drops all tokens in front of the expression that are unrelated for
783 /// the completion of the cmd line. 'unrelated' means here that the token
784 /// is not interested for the lldb completion API result.
785 StringRef dropUnrelatedFrontTokens(StringRef cmd) const {
786 if (cmd.empty())
787 return cmd;
788
789 // If we are at the start of a word, then all tokens are unrelated to
790 // the current completion logic.
791 if (IsTokenSeparator(cmd.back()))
792 return StringRef();
793
794 // Remove all previous tokens from the string as they are unrelated
795 // to completing the current token.
796 StringRef to_remove = cmd;
797 while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) {
798 to_remove = to_remove.drop_back();
799 }
800 cmd = cmd.drop_front(to_remove.size());
801
802 return cmd;
803 }
804
805 /// Removes the last identifier token from the given cmd line.
806 StringRef removeLastToken(StringRef cmd) const {
807 while (!cmd.empty() && IsIdChar(cmd.back())) {
808 cmd = cmd.drop_back();
809 }
810 return cmd;
811 }
812
813 /// Attempts to merge the given completion from the given position into the
814 /// existing command. Returns the completion string that can be returned to
815 /// the lldb completion API.
816 std::string mergeCompletion(StringRef existing, unsigned pos,
817 StringRef completion) const {
818 StringRef existing_command = existing.substr(0, pos);
819 // We rewrite the last token with the completion, so let's drop that
820 // token from the command.
821 existing_command = removeLastToken(existing_command);
822 // We also should remove all previous tokens from the command as they
823 // would otherwise be added to the completion that already has the
824 // completion.
825 existing_command = dropUnrelatedFrontTokens(existing_command);
826 return existing_command.str() + completion.str();
827 }
828
829public:
830 /// Constructs a CodeComplete consumer that can be attached to a Sema.
831 ///
832 /// \param[out] expr
833 /// The whole expression string that we are currently parsing. This
834 /// string needs to be equal to the input the user typed, and NOT the
835 /// final code that Clang is parsing.
836 /// \param[out] position
837 /// The character position of the user cursor in the `expr` parameter.
838 ///
839 CodeComplete(clang::LangOptions ops, std::string expr, unsigned position)
840 : CodeCompleteConsumer(CodeCompleteOptions()),
841 m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr),
842 m_position(position), m_desc_policy(ops) {
843
844 // Ensure that the printing policy is producing a description that is as
845 // short as possible.
846 m_desc_policy.SuppressScope = true;
847 m_desc_policy.SuppressTagKeyword = true;
848 m_desc_policy.FullyQualifiedName = false;
849 m_desc_policy.TerseOutput = true;
850 m_desc_policy.IncludeNewlines = false;
851 m_desc_policy.UseVoidForZeroParams = false;
852 m_desc_policy.Bool = true;
853 }
854
855 /// \name Code-completion filtering
856 /// Check if the result should be filtered out.
857 bool isResultFilteredOut(StringRef Filter,
858 CodeCompletionResult Result) override {
859 // This code is mostly copied from CodeCompleteConsumer.
860 switch (Result.Kind) {
861 case CodeCompletionResult::RK_Declaration:
862 return !(
863 Result.Declaration->getIdentifier() &&
864 Result.Declaration->getIdentifier()->getName().startswith(Filter));
865 case CodeCompletionResult::RK_Keyword:
866 return !StringRef(Result.Keyword).startswith(Filter);
867 case CodeCompletionResult::RK_Macro:
868 return !Result.Macro->getName().startswith(Filter);
869 case CodeCompletionResult::RK_Pattern:
870 return !StringRef(Result.Pattern->getAsString()).startswith(Filter);
871 }
872 // If we trigger this assert or the above switch yields a warning, then
873 // CodeCompletionResult has been enhanced with more kinds of completion
874 // results. Expand the switch above in this case.
875 assert(false && "Unknown completion result type?")((void)0);
876 // If we reach this, then we should just ignore whatever kind of unknown
877 // result we got back. We probably can't turn it into any kind of useful
878 // completion suggestion with the existing code.
879 return true;
880 }
881
882private:
883 /// Generate the completion strings for the given CodeCompletionResult.
884 /// Note that this function has to process results that could come in
885 /// non-deterministic order, so this function should have no side effects.
886 /// To make this easier to enforce, this function and all its parameters
887 /// should always be const-qualified.
888 /// \return Returns llvm::None if no completion should be provided for the
889 /// given CodeCompletionResult.
890 llvm::Optional<CompletionWithPriority>
891 getCompletionForResult(const CodeCompletionResult &R) const {
892 std::string ToInsert;
893 std::string Description;
894 // Handle the different completion kinds that come from the Sema.
895 switch (R.Kind) {
896 case CodeCompletionResult::RK_Declaration: {
897 const NamedDecl *D = R.Declaration;
898 ToInsert = R.Declaration->getNameAsString();
899 // If we have a function decl that has no arguments we want to
900 // complete the empty parantheses for the user. If the function has
901 // arguments, we at least complete the opening bracket.
902 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) {
903 if (F->getNumParams() == 0)
904 ToInsert += "()";
905 else
906 ToInsert += "(";
907 raw_string_ostream OS(Description);
908 F->print(OS, m_desc_policy, false);
909 OS.flush();
910 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
911 Description = V->getType().getAsString(m_desc_policy);
912 } else if (const FieldDecl *F = dyn_cast<FieldDecl>(D)) {
913 Description = F->getType().getAsString(m_desc_policy);
914 } else if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) {
915 // If we try to complete a namespace, then we can directly append
916 // the '::'.
917 if (!N->isAnonymousNamespace())
918 ToInsert += "::";
919 }
920 break;
921 }
922 case CodeCompletionResult::RK_Keyword:
923 ToInsert = R.Keyword;
924 break;
925 case CodeCompletionResult::RK_Macro:
926 ToInsert = R.Macro->getName().str();
927 break;
928 case CodeCompletionResult::RK_Pattern:
929 ToInsert = R.Pattern->getTypedText();
930 break;
931 }
932 // We also filter some internal lldb identifiers here. The user
933 // shouldn't see these.
934 if (llvm::StringRef(ToInsert).startswith("$__lldb_"))
935 return llvm::None;
936 if (ToInsert.empty())
937 return llvm::None;
938 // Merge the suggested Token into the existing command line to comply
939 // with the kind of result the lldb API expects.
940 std::string CompletionSuggestion =
941 mergeCompletion(m_expr, m_position, ToInsert);
942
943 CompletionResult::Completion completion(CompletionSuggestion, Description,
944 CompletionMode::Normal);
945 return {{completion, R.Priority}};
946 }
947
948public:
949 /// Adds the completions to the given CompletionRequest.
950 void GetCompletions(CompletionRequest &request) {
951 // Bring m_completions into a deterministic order and pass it on to the
952 // CompletionRequest.
953 llvm::sort(m_completions);
954
955 for (const CompletionWithPriority &C : m_completions)
956 request.AddCompletion(C.completion.GetCompletion(),
957 C.completion.GetDescription(),
958 C.completion.GetMode());
959 }
960
961 /// \name Code-completion callbacks
962 /// Process the finalized code-completion results.
963 void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context,
964 CodeCompletionResult *Results,
965 unsigned NumResults) override {
966
967 // The Sema put the incomplete token we try to complete in here during
968 // lexing, so we need to retrieve it here to know what we are completing.
969 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
970
971 // Iterate over all the results. Filter out results we don't want and
972 // process the rest.
973 for (unsigned I = 0; I != NumResults; ++I) {
974 // Filter the results with the information from the Sema.
975 if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
976 continue;
977
978 CodeCompletionResult &R = Results[I];
979 llvm::Optional<CompletionWithPriority> CompletionAndPriority =
980 getCompletionForResult(R);
981 if (!CompletionAndPriority)
982 continue;
983 m_completions.push_back(*CompletionAndPriority);
984 }
985 }
986
987 /// \param S the semantic-analyzer object for which code-completion is being
988 /// done.
989 ///
990 /// \param CurrentArg the index of the current argument.
991 ///
992 /// \param Candidates an array of overload candidates.
993 ///
994 /// \param NumCandidates the number of overload candidates
995 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
996 OverloadCandidate *Candidates,
997 unsigned NumCandidates,
998 SourceLocation OpenParLoc) override {
999 // At the moment we don't filter out any overloaded candidates.
1000 }
1001
1002 CodeCompletionAllocator &getAllocator() override {
1003 return m_info.getAllocator();
1004 }
1005
1006 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; }
1007};
1008} // namespace
1009
1010bool ClangExpressionParser::Complete(CompletionRequest &request, unsigned line,
1011 unsigned pos, unsigned typed_pos) {
1012 DiagnosticManager mgr;
1013 // We need the raw user expression here because that's what the CodeComplete
1014 // class uses to provide completion suggestions.
1015 // However, the `Text` method only gives us the transformed expression here.
1016 // To actually get the raw user input here, we have to cast our expression to
1017 // the LLVMUserExpression which exposes the right API. This should never fail
1018 // as we always have a ClangUserExpression whenever we call this.
1019 ClangUserExpression *llvm_expr = cast<ClangUserExpression>(&m_expr);
1020 CodeComplete CC(m_compiler->getLangOpts(), llvm_expr->GetUserText(),
1021 typed_pos);
1022 // We don't need a code generator for parsing.
1023 m_code_generator.reset();
1024 // Start parsing the expression with our custom code completion consumer.
1025 ParseInternal(mgr, &CC, line, pos);
1026 CC.GetCompletions(request);
1027 return true;
1028}
1029
1030unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) {
1031 return ParseInternal(diagnostic_manager);
1032}
1033
1034unsigned
1035ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager,
1036 CodeCompleteConsumer *completion_consumer,
1037 unsigned completion_line,
1038 unsigned completion_column) {
1039 ClangDiagnosticManagerAdapter *adapter =
1040 static_cast<ClangDiagnosticManagerAdapter *>(
1041 m_compiler->getDiagnostics().getClient());
1042
1043 adapter->ResetManager(&diagnostic_manager);
1044
1045 const char *expr_text = m_expr.Text();
1046
1047 clang::SourceManager &source_mgr = m_compiler->getSourceManager();
1048 bool created_main_file = false;
1049
1050 // Clang wants to do completion on a real file known by Clang's file manager,
1051 // so we have to create one to make this work.
1052 // TODO: We probably could also simulate to Clang's file manager that there
1053 // is a real file that contains our code.
1054 bool should_create_file = completion_consumer != nullptr;
1055
1056 // We also want a real file on disk if we generate full debug info.
1057 should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() ==
1058 codegenoptions::FullDebugInfo;
1059
1060 if (should_create_file) {
1061 int temp_fd = -1;
1062 llvm::SmallString<128> result_path;
1063 if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
1064 tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
1065 std::string temp_source_path = tmpdir_file_spec.GetPath();
1066 llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
1067 } else {
1068 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
1069 }
1070
1071 if (temp_fd != -1) {
1072 lldb_private::NativeFile file(temp_fd, File::eOpenOptionWrite, true);
1073 const size_t expr_text_len = strlen(expr_text);
1074 size_t bytes_written = expr_text_len;
1075 if (file.Write(expr_text, bytes_written).Success()) {
1076 if (bytes_written == expr_text_len) {
1077 file.Close();
1078 if (auto fileEntry = m_compiler->getFileManager().getOptionalFileRef(
1079 result_path)) {
1080 source_mgr.setMainFileID(source_mgr.createFileID(
1081 *fileEntry,
1082 SourceLocation(), SrcMgr::C_User));
1083 created_main_file = true;
1084 }
1085 }
1086 }
1087 }
1088 }
1089
1090 if (!created_main_file) {
1091 std::unique_ptr<MemoryBuffer> memory_buffer =
1092 MemoryBuffer::getMemBufferCopy(expr_text, m_filename);
1093 source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
1094 }
1095
1096 adapter->BeginSourceFile(m_compiler->getLangOpts(),
1097 &m_compiler->getPreprocessor());
1098
1099 ClangExpressionHelper *type_system_helper =
1100 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
1101
1102 // If we want to parse for code completion, we need to attach our code
1103 // completion consumer to the Sema and specify a completion position.
1104 // While parsing the Sema will call this consumer with the provided
1105 // completion suggestions.
1106 if (completion_consumer) {
1107 auto main_file = source_mgr.getFileEntryForID(source_mgr.getMainFileID());
1108 auto &PP = m_compiler->getPreprocessor();
1109 // Lines and columns start at 1 in Clang, but code completion positions are
1110 // indexed from 0, so we need to add 1 to the line and column here.
1111 ++completion_line;
1112 ++completion_column;
1113 PP.SetCodeCompletionPoint(main_file, completion_line, completion_column);
1114 }
1115
1116 ASTConsumer *ast_transformer =
1117 type_system_helper->ASTTransformer(m_code_generator.get());
1118
1119 std::unique_ptr<clang::ASTConsumer> Consumer;
1120 if (ast_transformer) {
1121 Consumer = std::make_unique<ASTConsumerForwarder>(ast_transformer);
1122 } else if (m_code_generator) {
1123 Consumer = std::make_unique<ASTConsumerForwarder>(m_code_generator.get());
1124 } else {
1125 Consumer = std::make_unique<ASTConsumer>();
1126 }
1127
1128 clang::ASTContext &ast_context = m_compiler->getASTContext();
1129
1130 m_compiler->setSema(new Sema(m_compiler->getPreprocessor(), ast_context,
1131 *Consumer, TU_Complete, completion_consumer));
1132 m_compiler->setASTConsumer(std::move(Consumer));
1133
1134 if (ast_context.getLangOpts().Modules) {
1135 m_compiler->createASTReader();
1136 m_ast_context->setSema(&m_compiler->getSema());
1137 }
1138
1139 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
1140 if (decl_map) {
1141 decl_map->InstallCodeGenerator(&m_compiler->getASTConsumer());
1142 decl_map->InstallDiagnosticManager(diagnostic_manager);
1143
1144 clang::ExternalASTSource *ast_source = decl_map->CreateProxy();
1145
1146 if (ast_context.getExternalSource()) {
1147 auto module_wrapper =
1148 new ExternalASTSourceWrapper(ast_context.getExternalSource());
1149
1150 auto ast_source_wrapper = new ExternalASTSourceWrapper(ast_source);
1151
1152 auto multiplexer =
1153 new SemaSourceWithPriorities(*module_wrapper, *ast_source_wrapper);
1154 IntrusiveRefCntPtr<ExternalASTSource> Source(multiplexer);
1155 ast_context.setExternalSource(Source);
1156 } else {
1157 ast_context.setExternalSource(ast_source);
1158 }
1159 decl_map->InstallASTContext(*m_ast_context);
1160 }
1161
1162 // Check that the ASTReader is properly attached to ASTContext and Sema.
1163 if (ast_context.getLangOpts().Modules) {
1164 assert(m_compiler->getASTContext().getExternalSource() &&((void)0)
1165 "ASTContext doesn't know about the ASTReader?")((void)0);
1166 assert(m_compiler->getSema().getExternalSource() &&((void)0)
1167 "Sema doesn't know about the ASTReader?")((void)0);
1168 }
1169
1170 {
1171 llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(
1172 &m_compiler->getSema());
1173 ParseAST(m_compiler->getSema(), false, false);
1174 }
1175
1176 // Make sure we have no pointer to the Sema we are about to destroy.
1177 if (ast_context.getLangOpts().Modules)
1178 m_ast_context->setSema(nullptr);
1179 // Destroy the Sema. This is necessary because we want to emulate the
1180 // original behavior of ParseAST (which also destroys the Sema after parsing).
1181 m_compiler->setSema(nullptr);
1182
1183 adapter->EndSourceFile();
1184
1185 unsigned num_errors = adapter->getNumErrors();
1186
1187 if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
1188 num_errors++;
1189 diagnostic_manager.PutString(eDiagnosticSeverityError,
1190 "while importing modules:");
1191 diagnostic_manager.AppendMessageToDiagnostic(
1192 m_pp_callbacks->getErrorString());
1193 }
1194
1195 if (!num_errors) {
1196 type_system_helper->CommitPersistentDecls();
1197 }
1198
1199 adapter->ResetManager();
1200
1201 return num_errors;
1202}
1203
1204std::string
1205ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) {
1206 std::string abi;
1207
1208 if (target_arch.IsMIPS()) {
1209 switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
1210 case ArchSpec::eMIPSABI_N64:
1211 abi = "n64";
1212 break;
1213 case ArchSpec::eMIPSABI_N32:
1214 abi = "n32";
1215 break;
1216 case ArchSpec::eMIPSABI_O32:
1217 abi = "o32";
1218 break;
1219 default:
1220 break;
1221 }
1222 }
1223 return abi;
1224}
1225
1226/// Applies the given Fix-It hint to the given commit.
1227static void ApplyFixIt(const FixItHint &fixit, clang::edit::Commit &commit) {
1228 // This is cobbed from clang::Rewrite::FixItRewriter.
1229 if (fixit.CodeToInsert.empty()) {
1230 if (fixit.InsertFromRange.isValid()) {
1231 commit.insertFromRange(fixit.RemoveRange.getBegin(),
1232 fixit.InsertFromRange, /*afterToken=*/false,
1233 fixit.BeforePreviousInsertions);
1234 return;
1235 }
1236 commit.remove(fixit.RemoveRange);
1237 return;
1238 }
1239 if (fixit.RemoveRange.isTokenRange() ||
1240 fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd()) {
1241 commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
1242 return;
1243 }
1244 commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
1245 /*afterToken=*/false, fixit.BeforePreviousInsertions);
1246}
1247
1248bool ClangExpressionParser::RewriteExpression(
1249 DiagnosticManager &diagnostic_manager) {
1250 clang::SourceManager &source_manager = m_compiler->getSourceManager();
1251 clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
1252 nullptr);
1253 clang::edit::Commit commit(editor);
1254 clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
1255
1256 class RewritesReceiver : public edit::EditsReceiver {
1257 Rewriter &rewrite;
1258
1259 public:
1260 RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
1261
1262 void insert(SourceLocation loc, StringRef text) override {
1263 rewrite.InsertText(loc, text);
1264 }
1265 void replace(CharSourceRange range, StringRef text) override {
1266 rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
1267 }
1268 };
1269
1270 RewritesReceiver rewrites_receiver(rewriter);
1271
1272 const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
1273 size_t num_diags = diagnostics.size();
1274 if (num_diags == 0)
1275 return false;
1276
1277 for (const auto &diag : diagnostic_manager.Diagnostics()) {
1278 const auto *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag.get());
1279 if (!diagnostic)
1280 continue;
1281 if (!diagnostic->HasFixIts())
1282 continue;
1283 for (const FixItHint &fixit : diagnostic->FixIts())
1284 ApplyFixIt(fixit, commit);
1285 }
1286
1287 // FIXME - do we want to try to propagate specific errors here?
1288 if (!commit.isCommitable())
1289 return false;
1290 else if (!editor.commit(commit))
1291 return false;
1292
1293 // Now play all the edits, and stash the result in the diagnostic manager.
1294 editor.applyRewrites(rewrites_receiver);
1295 RewriteBuffer &main_file_buffer =
1296 rewriter.getEditBuffer(source_manager.getMainFileID());
1297
1298 std::string fixed_expression;
1299 llvm::raw_string_ostream out_stream(fixed_expression);
1300
1301 main_file_buffer.write(out_stream);
1302 out_stream.flush();
1303 diagnostic_manager.SetFixedExpression(fixed_expression);
1304
1305 return true;
1306}
1307
1308static bool FindFunctionInModule(ConstString &mangled_name,
1309 llvm::Module *module, const char *orig_name) {
1310 for (const auto &func : module->getFunctionList()) {
1311 const StringRef &name = func.getName();
1312 if (name.find(orig_name) != StringRef::npos) {
1313 mangled_name.SetString(name);
1314 return true;
1315 }
1316 }
1317
1318 return false;
1319}
1320
1321lldb_private::Status ClangExpressionParser::PrepareForExecution(
1322 lldb::addr_t &func_addr, lldb::addr_t &func_end,
1323 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
1324 bool &can_interpret, ExecutionPolicy execution_policy) {
1325 func_addr = LLDB_INVALID_ADDRESS0xffffffffffffffffULL;
1326 func_end = LLDB_INVALID_ADDRESS0xffffffffffffffffULL;
1327 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS(1u << 8)));
1328
1329 lldb_private::Status err;
1330
1331 std::unique_ptr<llvm::Module> llvm_module_up(
1332 m_code_generator->ReleaseModule());
1333
1334 if (!llvm_module_up) {
1
Calling 'unique_ptr::operator bool'
4
Returning from 'unique_ptr::operator bool'
5
Taking false branch
1335 err.SetErrorToGenericError();
1336 err.SetErrorString("IR doesn't contain a module");
1337 return err;
1338 }
1339
1340 ConstString function_name;
1341
1342 if (execution_policy != eExecutionPolicyTopLevel) {
6
Assuming 'execution_policy' is equal to eExecutionPolicyTopLevel
7
Taking false branch
1343 // Find the actual name of the function (it's often mangled somehow)
1344
1345 if (!FindFunctionInModule(function_name, llvm_module_up.get(),
1346 m_expr.FunctionName())) {
1347 err.SetErrorToGenericError();
1348 err.SetErrorStringWithFormat("Couldn't find %s() in the module",
1349 m_expr.FunctionName());
1350 return err;
1351 } else {
1352 LLDB_LOGF(log, "Found function %s for %s", function_name.AsCString(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Found function %s for %s", function_name
.AsCString(), m_expr.FunctionName()); } while (0)
1353 m_expr.FunctionName())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Found function %s for %s", function_name
.AsCString(), m_expr.FunctionName()); } while (0)
;
1354 }
1355 }
1356
1357 SymbolContext sc;
1358
1359 if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
8
Taking false branch
1360 sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
1361 } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
9
Taking false branch
1362 sc.target_sp = target_sp;
1363 }
1364
1365 LLVMUserExpression::IRPasses custom_passes;
1366 {
1367 auto lang = m_expr.Language();
1368 LLDB_LOGF(log, "%s - Current expression language is %s\n", __FUNCTION__,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("%s - Current expression language is %s\n"
, __FUNCTION__, Language::GetNameForLanguageType(lang)); } while
(0)
10
Assuming 'log_private' is null
11
Taking false branch
12
Loop condition is false. Exiting loop
1369 Language::GetNameForLanguageType(lang))do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("%s - Current expression language is %s\n"
, __FUNCTION__, Language::GetNameForLanguageType(lang)); } while
(0)
;
1370 lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
1371 if (process_sp && lang != lldb::eLanguageTypeUnknown) {
1372 auto runtime = process_sp->GetLanguageRuntime(lang);
1373 if (runtime)
1374 runtime->GetIRPasses(custom_passes);
1375 }
1376 }
1377
1378 if (custom_passes.EarlyPasses) {
13
Taking false branch
1379 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("%s - Running Early IR Passes from LanguageRuntime on "
"expression module '%s'", __FUNCTION__, m_expr.FunctionName(
)); } while (0)
1380 "%s - Running Early IR Passes from LanguageRuntime on "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("%s - Running Early IR Passes from LanguageRuntime on "
"expression module '%s'", __FUNCTION__, m_expr.FunctionName(
)); } while (0)
1381 "expression module '%s'",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("%s - Running Early IR Passes from LanguageRuntime on "
"expression module '%s'", __FUNCTION__, m_expr.FunctionName(
)); } while (0)
1382 __FUNCTION__, m_expr.FunctionName())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("%s - Running Early IR Passes from LanguageRuntime on "
"expression module '%s'", __FUNCTION__, m_expr.FunctionName(
)); } while (0)
;
1383
1384 custom_passes.EarlyPasses->run(*llvm_module_up);
1385 }
1386
1387 execution_unit_sp = std::make_shared<IRExecutionUnit>(
1388 m_llvm_context, // handed off here
1389 llvm_module_up, // handed off here
1390 function_name, exe_ctx.GetTargetSP(), sc,
1391 m_compiler->getTargetOpts().Features);
1392
1393 ClangExpressionHelper *type_system_helper =
15
'type_system_helper' initialized to a null pointer value
1394 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
14
Assuming the object is not a 'ClangExpressionHelper'
1395 ClangExpressionDeclMap *decl_map =
1396 type_system_helper->DeclMap(); // result can be NULL
16
Called C++ object pointer is null
1397
1398 if (decl_map) {
1399 StreamString error_stream;
1400 IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),
1401 *execution_unit_sp, error_stream,
1402 function_name.AsCString());
1403
1404 if (!ir_for_target.runOnModule(*execution_unit_sp->GetModule())) {
1405 err.SetErrorString(error_stream.GetString());
1406 return err;
1407 }
1408
1409 Process *process = exe_ctx.GetProcessPtr();
1410
1411 if (execution_policy != eExecutionPolicyAlways &&
1412 execution_policy != eExecutionPolicyTopLevel) {
1413 lldb_private::Status interpret_error;
1414
1415 bool interpret_function_calls =
1416 !process ? false : process->CanInterpretFunctionCalls();
1417 can_interpret = IRInterpreter::CanInterpret(
1418 *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
1419 interpret_error, interpret_function_calls);
1420
1421 if (!can_interpret && execution_policy == eExecutionPolicyNever) {
1422 err.SetErrorStringWithFormat(
1423 "Can't evaluate the expression without a running target due to: %s",
1424 interpret_error.AsCString());
1425 return err;
1426 }
1427 }
1428
1429 if (!process && execution_policy == eExecutionPolicyAlways) {
1430 err.SetErrorString("Expression needed to run in the target, but the "
1431 "target can't be run");
1432 return err;
1433 }
1434
1435 if (!process && execution_policy == eExecutionPolicyTopLevel) {
1436 err.SetErrorString("Top-level code needs to be inserted into a runnable "
1437 "target, but the target can't be run");
1438 return err;
1439 }
1440
1441 if (execution_policy == eExecutionPolicyAlways ||
1442 (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
1443 if (m_expr.NeedsValidation() && process) {
1444 if (!process->GetDynamicCheckers()) {
1445 ClangDynamicCheckerFunctions *dynamic_checkers =
1446 new ClangDynamicCheckerFunctions();
1447
1448 DiagnosticManager install_diagnostics;
1449
1450 if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) {
1451 if (install_diagnostics.Diagnostics().size())
1452 err.SetErrorString(install_diagnostics.GetString().c_str());
1453 else
1454 err.SetErrorString("couldn't install checkers, unknown error");
1455
1456 return err;
1457 }
1458
1459 process->SetDynamicCheckers(dynamic_checkers);
1460
1461 LLDB_LOGF(log, "== [ClangExpressionParser::PrepareForExecution] "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("== [ClangExpressionParser::PrepareForExecution] "
"Finished installing dynamic checkers =="); } while (0)
1462 "Finished installing dynamic checkers ==")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("== [ClangExpressionParser::PrepareForExecution] "
"Finished installing dynamic checkers =="); } while (0)
;
1463 }
1464
1465 if (auto *checker_funcs = llvm::dyn_cast<ClangDynamicCheckerFunctions>(
1466 process->GetDynamicCheckers())) {
1467 IRDynamicChecks ir_dynamic_checks(*checker_funcs,
1468 function_name.AsCString());
1469
1470 llvm::Module *module = execution_unit_sp->GetModule();
1471 if (!module || !ir_dynamic_checks.runOnModule(*module)) {
1472 err.SetErrorToGenericError();
1473 err.SetErrorString("Couldn't add dynamic checks to the expression");
1474 return err;
1475 }
1476
1477 if (custom_passes.LatePasses) {
1478 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("%s - Running Late IR Passes from LanguageRuntime on "
"expression module '%s'", __FUNCTION__, m_expr.FunctionName(
)); } while (0)
1479 "%s - Running Late IR Passes from LanguageRuntime on "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("%s - Running Late IR Passes from LanguageRuntime on "
"expression module '%s'", __FUNCTION__, m_expr.FunctionName(
)); } while (0)
1480 "expression module '%s'",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("%s - Running Late IR Passes from LanguageRuntime on "
"expression module '%s'", __FUNCTION__, m_expr.FunctionName(
)); } while (0)
1481 __FUNCTION__, m_expr.FunctionName())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("%s - Running Late IR Passes from LanguageRuntime on "
"expression module '%s'", __FUNCTION__, m_expr.FunctionName(
)); } while (0)
;
1482
1483 custom_passes.LatePasses->run(*module);
1484 }
1485 }
1486 }
1487 }
1488
1489 if (execution_policy == eExecutionPolicyAlways ||
1490 execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
1491 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1492 }
1493 } else {
1494 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1495 }
1496
1497 return err;
1498}
1499
1500lldb_private::Status ClangExpressionParser::RunStaticInitializers(
1501 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) {
1502 lldb_private::Status err;
1503
1504 lldbassert(execution_unit_sp.get())lldb_private::lldb_assert(static_cast<bool>(execution_unit_sp
.get()), "execution_unit_sp.get()", __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, 1504)
;
1505 lldbassert(exe_ctx.HasThreadScope())lldb_private::lldb_assert(static_cast<bool>(exe_ctx.HasThreadScope
()), "exe_ctx.HasThreadScope()", __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginExpressionParser/../../../llvm/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp"
, 1505)
;
1506
1507 if (!execution_unit_sp.get()) {
1508 err.SetErrorString(
1509 "can't run static initializers for a NULL execution unit");
1510 return err;
1511 }
1512
1513 if (!exe_ctx.HasThreadScope()) {
1514 err.SetErrorString("can't run static initializers without a thread");
1515 return err;
1516 }
1517
1518 std::vector<lldb::addr_t> static_initializers;
1519
1520 execution_unit_sp->GetStaticInitializers(static_initializers);
1521
1522 for (lldb::addr_t static_initializer : static_initializers) {
1523 EvaluateExpressionOptions options;
1524
1525 lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(
1526 exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(),
1527 llvm::ArrayRef<lldb::addr_t>(), options));
1528
1529 DiagnosticManager execution_errors;
1530 lldb::ExpressionResults results =
1531 exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(
1532 exe_ctx, call_static_initializer, options, execution_errors);
1533
1534 if (results != lldb::eExpressionCompleted) {
1535 err.SetErrorStringWithFormat("couldn't run static initializer: %s",
1536 execution_errors.GetString().c_str());
1537 return err;
1538 }
1539 }
1540
1541 return err;
1542}

/usr/include/c++/v1/__memory/unique_ptr.h

1// -*- C++ -*-
2//===----------------------------------------------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef _LIBCPP___MEMORY_UNIQUE_PTR_H
11#define _LIBCPP___MEMORY_UNIQUE_PTR_H
12
13#include <__config>
14#include <__functional_base>
15#include <__functional/hash.h>
16#include <__functional/operations.h>
17#include <__memory/allocator_traits.h> // __pointer
18#include <__memory/compressed_pair.h>
19#include <__utility/forward.h>
20#include <cstddef>
21#include <type_traits>
22#include <utility>
23
24#if _LIBCPP_STD_VER14 <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
25# include <__memory/auto_ptr.h>
26#endif
27
28#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
29#pragma GCC system_header
30#endif
31
32_LIBCPP_PUSH_MACROSpush_macro("min") push_macro("max")
33#include <__undef_macros>
34
35_LIBCPP_BEGIN_NAMESPACE_STDnamespace std { inline namespace __1 {
36
37template <class _Tp>
38struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) default_delete {
39 static_assert(!is_function<_Tp>::value,
40 "default_delete cannot be instantiated for function types");
41#ifndef _LIBCPP_CXX03_LANG
42 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
constexpr default_delete() _NOEXCEPTnoexcept = default;
43#else
44 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
default_delete() {}
45#endif
46 template <class _Up>
47 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
48 default_delete(const default_delete<_Up>&,
49 typename enable_if<is_convertible<_Up*, _Tp*>::value>::type* =
50 0) _NOEXCEPTnoexcept {}
51
52 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
void operator()(_Tp* __ptr) const _NOEXCEPTnoexcept {
53 static_assert(sizeof(_Tp) > 0,
54 "default_delete can not delete incomplete type");
55 static_assert(!is_void<_Tp>::value,
56 "default_delete can not delete incomplete type");
57 delete __ptr;
58 }
59};
60
61template <class _Tp>
62struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) default_delete<_Tp[]> {
63private:
64 template <class _Up>
65 struct _EnableIfConvertible
66 : enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value> {};
67
68public:
69#ifndef _LIBCPP_CXX03_LANG
70 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
constexpr default_delete() _NOEXCEPTnoexcept = default;
71#else
72 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
default_delete() {}
73#endif
74
75 template <class _Up>
76 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
77 default_delete(const default_delete<_Up[]>&,
78 typename _EnableIfConvertible<_Up>::type* = 0) _NOEXCEPTnoexcept {}
79
80 template <class _Up>
81 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
82 typename _EnableIfConvertible<_Up>::type
83 operator()(_Up* __ptr) const _NOEXCEPTnoexcept {
84 static_assert(sizeof(_Tp) > 0,
85 "default_delete can not delete incomplete type");
86 static_assert(!is_void<_Tp>::value,
87 "default_delete can not delete void type");
88 delete[] __ptr;
89 }
90};
91
92template <class _Deleter>
93struct __unique_ptr_deleter_sfinae {
94 static_assert(!is_reference<_Deleter>::value, "incorrect specialization");
95 typedef const _Deleter& __lval_ref_type;
96 typedef _Deleter&& __good_rval_ref_type;
97 typedef true_type __enable_rval_overload;
98};
99
100template <class _Deleter>
101struct __unique_ptr_deleter_sfinae<_Deleter const&> {
102 typedef const _Deleter& __lval_ref_type;
103 typedef const _Deleter&& __bad_rval_ref_type;
104 typedef false_type __enable_rval_overload;
105};
106
107template <class _Deleter>
108struct __unique_ptr_deleter_sfinae<_Deleter&> {
109 typedef _Deleter& __lval_ref_type;
110 typedef _Deleter&& __bad_rval_ref_type;
111 typedef false_type __enable_rval_overload;
112};
113
114#if defined(_LIBCPP_ABI_ENABLE_UNIQUE_PTR_TRIVIAL_ABI)
115# define _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI __attribute__((trivial_abi))
116#else
117# define _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI
118#endif
119
120template <class _Tp, class _Dp = default_delete<_Tp> >
121class _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) unique_ptr {
122public:
123 typedef _Tp element_type;
124 typedef _Dp deleter_type;
125 typedef _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) typename __pointer<_Tp, deleter_type>::type pointer;
126
127 static_assert(!is_rvalue_reference<deleter_type>::value,
128 "the specified deleter type cannot be an rvalue reference");
129
130private:
131 __compressed_pair<pointer, deleter_type> __ptr_;
132
133 struct __nat { int __for_bool_; };
134
135 typedef _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) __unique_ptr_deleter_sfinae<_Dp> _DeleterSFINAE;
136
137 template <bool _Dummy>
138 using _LValRefType _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
139 typename __dependent_type<_DeleterSFINAE, _Dummy>::__lval_ref_type;
140
141 template <bool _Dummy>
142 using _GoodRValRefType _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
143 typename __dependent_type<_DeleterSFINAE, _Dummy>::__good_rval_ref_type;
144
145 template <bool _Dummy>
146 using _BadRValRefType _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
147 typename __dependent_type<_DeleterSFINAE, _Dummy>::__bad_rval_ref_type;
148
149 template <bool _Dummy, class _Deleter = typename __dependent_type<
150 __identity<deleter_type>, _Dummy>::type>
151 using _EnableIfDeleterDefaultConstructible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
152 typename enable_if<is_default_constructible<_Deleter>::value &&
153 !is_pointer<_Deleter>::value>::type;
154
155 template <class _ArgType>
156 using _EnableIfDeleterConstructible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
157 typename enable_if<is_constructible<deleter_type, _ArgType>::value>::type;
158
159 template <class _UPtr, class _Up>
160 using _EnableIfMoveConvertible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) = typename enable_if<
161 is_convertible<typename _UPtr::pointer, pointer>::value &&
162 !is_array<_Up>::value
163 >::type;
164
165 template <class _UDel>
166 using _EnableIfDeleterConvertible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) = typename enable_if<
167 (is_reference<_Dp>::value && is_same<_Dp, _UDel>::value) ||
168 (!is_reference<_Dp>::value && is_convertible<_UDel, _Dp>::value)
169 >::type;
170
171 template <class _UDel>
172 using _EnableIfDeleterAssignable = typename enable_if<
173 is_assignable<_Dp&, _UDel&&>::value
174 >::type;
175
176public:
177 template <bool _Dummy = true,
178 class = _EnableIfDeleterDefaultConstructible<_Dummy> >
179 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
180 _LIBCPP_CONSTEXPRconstexpr unique_ptr() _NOEXCEPTnoexcept : __ptr_(pointer(), __default_init_tag()) {}
181
182 template <bool _Dummy = true,
183 class = _EnableIfDeleterDefaultConstructible<_Dummy> >
184 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
185 _LIBCPP_CONSTEXPRconstexpr unique_ptr(nullptr_t) _NOEXCEPTnoexcept : __ptr_(pointer(), __default_init_tag()) {}
186
187 template <bool _Dummy = true,
188 class = _EnableIfDeleterDefaultConstructible<_Dummy> >
189 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
190 explicit unique_ptr(pointer __p) _NOEXCEPTnoexcept : __ptr_(__p, __default_init_tag()) {}
191
192 template <bool _Dummy = true,
193 class = _EnableIfDeleterConstructible<_LValRefType<_Dummy> > >
194 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
195 unique_ptr(pointer __p, _LValRefType<_Dummy> __d) _NOEXCEPTnoexcept
196 : __ptr_(__p, __d) {}
197
198 template <bool _Dummy = true,
199 class = _EnableIfDeleterConstructible<_GoodRValRefType<_Dummy> > >
200 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
201 unique_ptr(pointer __p, _GoodRValRefType<_Dummy> __d) _NOEXCEPTnoexcept
202 : __ptr_(__p, _VSTDstd::__1::move(__d)) {
203 static_assert(!is_reference<deleter_type>::value,
204 "rvalue deleter bound to reference");
205 }
206
207 template <bool _Dummy = true,
208 class = _EnableIfDeleterConstructible<_BadRValRefType<_Dummy> > >
209 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
210 unique_ptr(pointer __p, _BadRValRefType<_Dummy> __d) = delete;
211
212 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
213 unique_ptr(unique_ptr&& __u) _NOEXCEPTnoexcept
214 : __ptr_(__u.release(), _VSTDstd::__1::forward<deleter_type>(__u.get_deleter())) {
215 }
216
217 template <class _Up, class _Ep,
218 class = _EnableIfMoveConvertible<unique_ptr<_Up, _Ep>, _Up>,
219 class = _EnableIfDeleterConvertible<_Ep>
220 >
221 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
222 unique_ptr(unique_ptr<_Up, _Ep>&& __u) _NOEXCEPTnoexcept
223 : __ptr_(__u.release(), _VSTDstd::__1::forward<_Ep>(__u.get_deleter())) {}
224
225#if _LIBCPP_STD_VER14 <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
226 template <class _Up>
227 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
228 unique_ptr(auto_ptr<_Up>&& __p,
229 typename enable_if<is_convertible<_Up*, _Tp*>::value &&
230 is_same<_Dp, default_delete<_Tp> >::value,
231 __nat>::type = __nat()) _NOEXCEPTnoexcept
232 : __ptr_(__p.release(), __default_init_tag()) {}
233#endif
234
235 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
236 unique_ptr& operator=(unique_ptr&& __u) _NOEXCEPTnoexcept {
237 reset(__u.release());
238 __ptr_.second() = _VSTDstd::__1::forward<deleter_type>(__u.get_deleter());
239 return *this;
240 }
241
242 template <class _Up, class _Ep,
243 class = _EnableIfMoveConvertible<unique_ptr<_Up, _Ep>, _Up>,
244 class = _EnableIfDeleterAssignable<_Ep>
245 >
246 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
247 unique_ptr& operator=(unique_ptr<_Up, _Ep>&& __u) _NOEXCEPTnoexcept {
248 reset(__u.release());
249 __ptr_.second() = _VSTDstd::__1::forward<_Ep>(__u.get_deleter());
250 return *this;
251 }
252
253#if _LIBCPP_STD_VER14 <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
254 template <class _Up>
255 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
256 typename enable_if<is_convertible<_Up*, _Tp*>::value &&
257 is_same<_Dp, default_delete<_Tp> >::value,
258 unique_ptr&>::type
259 operator=(auto_ptr<_Up> __p) {
260 reset(__p.release());
261 return *this;
262 }
263#endif
264
265#ifdef _LIBCPP_CXX03_LANG
266 unique_ptr(unique_ptr const&) = delete;
267 unique_ptr& operator=(unique_ptr const&) = delete;
268#endif
269
270
271 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
272 ~unique_ptr() { reset(); }
273
274 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
275 unique_ptr& operator=(nullptr_t) _NOEXCEPTnoexcept {
276 reset();
277 return *this;
278 }
279
280 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
281 typename add_lvalue_reference<_Tp>::type
282 operator*() const {
283 return *__ptr_.first();
284 }
285 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
286 pointer operator->() const _NOEXCEPTnoexcept {
287 return __ptr_.first();
288 }
289 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
290 pointer get() const _NOEXCEPTnoexcept {
291 return __ptr_.first();
292 }
293 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
294 deleter_type& get_deleter() _NOEXCEPTnoexcept {
295 return __ptr_.second();
296 }
297 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
298 const deleter_type& get_deleter() const _NOEXCEPTnoexcept {
299 return __ptr_.second();
300 }
301 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
302 explicit operator bool() const _NOEXCEPTnoexcept {
303 return __ptr_.first() != nullptr;
2
Assuming the condition is true
3
Returning the value 1, which participates in a condition later
304 }
305
306 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
307 pointer release() _NOEXCEPTnoexcept {
308 pointer __t = __ptr_.first();
309 __ptr_.first() = pointer();
310 return __t;
311 }
312
313 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
314 void reset(pointer __p = pointer()) _NOEXCEPTnoexcept {
315 pointer __tmp = __ptr_.first();
316 __ptr_.first() = __p;
317 if (__tmp)
318 __ptr_.second()(__tmp);
319 }
320
321 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
322 void swap(unique_ptr& __u) _NOEXCEPTnoexcept {
323 __ptr_.swap(__u.__ptr_);
324 }
325};
326
327
328template <class _Tp, class _Dp>
329class _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) unique_ptr<_Tp[], _Dp> {
330public:
331 typedef _Tp element_type;
332 typedef _Dp deleter_type;
333 typedef typename __pointer<_Tp, deleter_type>::type pointer;
334
335private:
336 __compressed_pair<pointer, deleter_type> __ptr_;
337
338 template <class _From>
339 struct _CheckArrayPointerConversion : is_same<_From, pointer> {};
340
341 template <class _FromElem>
342 struct _CheckArrayPointerConversion<_FromElem*>
343 : integral_constant<bool,
344 is_same<_FromElem*, pointer>::value ||
345 (is_same<pointer, element_type*>::value &&
346 is_convertible<_FromElem(*)[], element_type(*)[]>::value)
347 >
348 {};
349
350 typedef __unique_ptr_deleter_sfinae<_Dp> _DeleterSFINAE;
351
352 template <bool _Dummy>
353 using _LValRefType _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
354 typename __dependent_type<_DeleterSFINAE, _Dummy>::__lval_ref_type;
355
356 template <bool _Dummy>
357 using _GoodRValRefType _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
358 typename __dependent_type<_DeleterSFINAE, _Dummy>::__good_rval_ref_type;
359
360 template <bool _Dummy>
361 using _BadRValRefType _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
362 typename __dependent_type<_DeleterSFINAE, _Dummy>::__bad_rval_ref_type;
363
364 template <bool _Dummy, class _Deleter = typename __dependent_type<
365 __identity<deleter_type>, _Dummy>::type>
366 using _EnableIfDeleterDefaultConstructible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
367 typename enable_if<is_default_constructible<_Deleter>::value &&
368 !is_pointer<_Deleter>::value>::type;
369
370 template <class _ArgType>
371 using _EnableIfDeleterConstructible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
372 typename enable_if<is_constructible<deleter_type, _ArgType>::value>::type;
373
374 template <class _Pp>
375 using _EnableIfPointerConvertible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) = typename enable_if<
376 _CheckArrayPointerConversion<_Pp>::value
377 >::type;
378
379 template <class _UPtr, class _Up,
380 class _ElemT = typename _UPtr::element_type>
381 using _EnableIfMoveConvertible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) = typename enable_if<
382 is_array<_Up>::value &&
383 is_same<pointer, element_type*>::value &&
384 is_same<typename _UPtr::pointer, _ElemT*>::value &&
385 is_convertible<_ElemT(*)[], element_type(*)[]>::value
386 >::type;
387
388 template <class _UDel>
389 using _EnableIfDeleterConvertible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) = typename enable_if<
390 (is_reference<_Dp>::value && is_same<_Dp, _UDel>::value) ||
391 (!is_reference<_Dp>::value && is_convertible<_UDel, _Dp>::value)
392 >::type;
393
394 template <class _UDel>
395 using _EnableIfDeleterAssignable _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) = typename enable_if<
396 is_assignable<_Dp&, _UDel&&>::value
397 >::type;
398
399public:
400 template <bool _Dummy = true,
401 class = _EnableIfDeleterDefaultConstructible<_Dummy> >
402 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
403 _LIBCPP_CONSTEXPRconstexpr unique_ptr() _NOEXCEPTnoexcept : __ptr_(pointer(), __default_init_tag()) {}
404
405 template <bool _Dummy = true,
406 class = _EnableIfDeleterDefaultConstructible<_Dummy> >
407 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
408 _LIBCPP_CONSTEXPRconstexpr unique_ptr(nullptr_t) _NOEXCEPTnoexcept : __ptr_(pointer(), __default_init_tag()) {}
409
410 template <class _Pp, bool _Dummy = true,
411 class = _EnableIfDeleterDefaultConstructible<_Dummy>,
412 class = _EnableIfPointerConvertible<_Pp> >
413 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
414 explicit unique_ptr(_Pp __p) _NOEXCEPTnoexcept
415 : __ptr_(__p, __default_init_tag()) {}
416
417 template <class _Pp, bool _Dummy = true,
418 class = _EnableIfDeleterConstructible<_LValRefType<_Dummy> >,
419 class = _EnableIfPointerConvertible<_Pp> >
420 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
421 unique_ptr(_Pp __p, _LValRefType<_Dummy> __d) _NOEXCEPTnoexcept
422 : __ptr_(__p, __d) {}
423
424 template <bool _Dummy = true,
425 class = _EnableIfDeleterConstructible<_LValRefType<_Dummy> > >
426 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
427 unique_ptr(nullptr_t, _LValRefType<_Dummy> __d) _NOEXCEPTnoexcept
428 : __ptr_(nullptr, __d) {}
429
430 template <class _Pp, bool _Dummy = true,
431 class = _EnableIfDeleterConstructible<_GoodRValRefType<_Dummy> >,
432 class = _EnableIfPointerConvertible<_Pp> >
433 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
434 unique_ptr(_Pp __p, _GoodRValRefType<_Dummy> __d) _NOEXCEPTnoexcept
435 : __ptr_(__p, _VSTDstd::__1::move(__d)) {
436 static_assert(!is_reference<deleter_type>::value,
437 "rvalue deleter bound to reference");
438 }
439
440 template <bool _Dummy = true,
441 class = _EnableIfDeleterConstructible<_GoodRValRefType<_Dummy> > >
442 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
443 unique_ptr(nullptr_t, _GoodRValRefType<_Dummy> __d) _NOEXCEPTnoexcept
444 : __ptr_(nullptr, _VSTDstd::__1::move(__d)) {
445 static_assert(!is_reference<deleter_type>::value,
446 "rvalue deleter bound to reference");
447 }
448
449 template <class _Pp, bool _Dummy = true,
450 class = _EnableIfDeleterConstructible<_BadRValRefType<_Dummy> >,
451 class = _EnableIfPointerConvertible<_Pp> >
452 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
453 unique_ptr(_Pp __p, _BadRValRefType<_Dummy> __d) = delete;
454
455 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
456 unique_ptr(unique_ptr&& __u) _NOEXCEPTnoexcept
457 : __ptr_(__u.release(), _VSTDstd::__1::forward<deleter_type>(__u.get_deleter())) {
458 }
459
460 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
461 unique_ptr& operator=(unique_ptr&& __u) _NOEXCEPTnoexcept {
462 reset(__u.release());
463 __ptr_.second() = _VSTDstd::__1::forward<deleter_type>(__u.get_deleter());
464 return *this;
465 }
466
467 template <class _Up, class _Ep,
468 class = _EnableIfMoveConvertible<unique_ptr<_Up, _Ep>, _Up>,
469 class = _EnableIfDeleterConvertible<_Ep>
470 >
471 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
472 unique_ptr(unique_ptr<_Up, _Ep>&& __u) _NOEXCEPTnoexcept
473 : __ptr_(__u.release(), _VSTDstd::__1::forward<_Ep>(__u.get_deleter())) {
474 }
475
476 template <class _Up, class _Ep,
477 class = _EnableIfMoveConvertible<unique_ptr<_Up, _Ep>, _Up>,
478 class = _EnableIfDeleterAssignable<_Ep>
479 >
480 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
481 unique_ptr&
482 operator=(unique_ptr<_Up, _Ep>&& __u) _NOEXCEPTnoexcept {
483 reset(__u.release());
484 __ptr_.second() = _VSTDstd::__1::forward<_Ep>(__u.get_deleter());
485 return *this;
486 }
487
488#ifdef _LIBCPP_CXX03_LANG
489 unique_ptr(unique_ptr const&) = delete;
490 unique_ptr& operator=(unique_ptr const&) = delete;
491#endif
492
493public:
494 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
495 ~unique_ptr() { reset(); }
496
497 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
498 unique_ptr& operator=(nullptr_t) _NOEXCEPTnoexcept {
499 reset();
500 return *this;
501 }
502
503 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
504 typename add_lvalue_reference<_Tp>::type
505 operator[](size_t __i) const {
506 return __ptr_.first()[__i];
507 }
508 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
509 pointer get() const _NOEXCEPTnoexcept {
510 return __ptr_.first();
511 }
512
513 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
514 deleter_type& get_deleter() _NOEXCEPTnoexcept {
515 return __ptr_.second();
516 }
517
518 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
519 const deleter_type& get_deleter() const _NOEXCEPTnoexcept {
520 return __ptr_.second();
521 }
522 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
523 explicit operator bool() const _NOEXCEPTnoexcept {
524 return __ptr_.first() != nullptr;
525 }
526
527 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
528 pointer release() _NOEXCEPTnoexcept {
529 pointer __t = __ptr_.first();
530 __ptr_.first() = pointer();
531 return __t;
532 }
533
534 template <class _Pp>
535 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
536 typename enable_if<
537 _CheckArrayPointerConversion<_Pp>::value
538 >::type
539 reset(_Pp __p) _NOEXCEPTnoexcept {
540 pointer __tmp = __ptr_.first();
541 __ptr_.first() = __p;
542 if (__tmp)
543 __ptr_.second()(__tmp);
544 }
545
546 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
547 void reset(nullptr_t = nullptr) _NOEXCEPTnoexcept {
548 pointer __tmp = __ptr_.first();
549 __ptr_.first() = nullptr;
550 if (__tmp)
551 __ptr_.second()(__tmp);
552 }
553
554 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
555 void swap(unique_ptr& __u) _NOEXCEPTnoexcept {
556 __ptr_.swap(__u.__ptr_);
557 }
558
559};
560
561template <class _Tp, class _Dp>
562inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
563typename enable_if<
564 __is_swappable<_Dp>::value,
565 void
566>::type
567swap(unique_ptr<_Tp, _Dp>& __x, unique_ptr<_Tp, _Dp>& __y) _NOEXCEPTnoexcept {__x.swap(__y);}
568
569template <class _T1, class _D1, class _T2, class _D2>
570inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
571bool
572operator==(const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return __x.get() == __y.get();}
573
574template <class _T1, class _D1, class _T2, class _D2>
575inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
576bool
577operator!=(const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return !(__x == __y);}
578
579template <class _T1, class _D1, class _T2, class _D2>
580inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
581bool
582operator< (const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y)
583{
584 typedef typename unique_ptr<_T1, _D1>::pointer _P1;
585 typedef typename unique_ptr<_T2, _D2>::pointer _P2;
586 typedef typename common_type<_P1, _P2>::type _Vp;
587 return less<_Vp>()(__x.get(), __y.get());
588}
589
590template <class _T1, class _D1, class _T2, class _D2>
591inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
592bool
593operator> (const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return __y < __x;}
594
595template <class _T1, class _D1, class _T2, class _D2>
596inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
597bool
598operator<=(const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return !(__y < __x);}
599
600template <class _T1, class _D1, class _T2, class _D2>
601inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
602bool
603operator>=(const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return !(__x < __y);}
604
605template <class _T1, class _D1>
606inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
607bool
608operator==(const unique_ptr<_T1, _D1>& __x, nullptr_t) _NOEXCEPTnoexcept
609{
610 return !__x;
611}
612
613template <class _T1, class _D1>
614inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
615bool
616operator==(nullptr_t, const unique_ptr<_T1, _D1>& __x) _NOEXCEPTnoexcept
617{
618 return !__x;
619}
620
621template <class _T1, class _D1>
622inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
623bool
624operator!=(const unique_ptr<_T1, _D1>& __x, nullptr_t) _NOEXCEPTnoexcept
625{
626 return static_cast<bool>(__x);
627}
628
629template <class _T1, class _D1>
630inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
631bool
632operator!=(nullptr_t, const unique_ptr<_T1, _D1>& __x) _NOEXCEPTnoexcept
633{
634 return static_cast<bool>(__x);
635}
636
637template <class _T1, class _D1>
638inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
639bool
640operator<(const unique_ptr<_T1, _D1>& __x, nullptr_t)
641{
642 typedef typename unique_ptr<_T1, _D1>::pointer _P1;
643 return less<_P1>()(__x.get(), nullptr);
644}
645
646template <class _T1, class _D1>
647inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
648bool
649operator<(nullptr_t, const unique_ptr<_T1, _D1>& __x)
650{
651 typedef typename unique_ptr<_T1, _D1>::pointer _P1;
652 return less<_P1>()(nullptr, __x.get());
653}
654
655template <class _T1, class _D1>
656inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
657bool
658operator>(const unique_ptr<_T1, _D1>& __x, nullptr_t)
659{
660 return nullptr < __x;
661}
662
663template <class _T1, class _D1>
664inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
665bool
666operator>(nullptr_t, const unique_ptr<_T1, _D1>& __x)
667{
668 return __x < nullptr;
669}
670
671template <class _T1, class _D1>
672inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
673bool
674operator<=(const unique_ptr<_T1, _D1>& __x, nullptr_t)
675{
676 return !(nullptr < __x);
677}
678
679template <class _T1, class _D1>
680inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
681bool
682operator<=(nullptr_t, const unique_ptr<_T1, _D1>& __x)
683{
684 return !(__x < nullptr);
685}
686
687template <class _T1, class _D1>
688inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
689bool
690operator>=(const unique_ptr<_T1, _D1>& __x, nullptr_t)
691{
692 return !(__x < nullptr);
693}
694
695template <class _T1, class _D1>
696inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
697bool
698operator>=(nullptr_t, const unique_ptr<_T1, _D1>& __x)
699{
700 return !(nullptr < __x);
701}
702
703#if _LIBCPP_STD_VER14 > 11
704
705template<class _Tp>
706struct __unique_if
707{
708 typedef unique_ptr<_Tp> __unique_single;
709};
710
711template<class _Tp>
712struct __unique_if<_Tp[]>
713{
714 typedef unique_ptr<_Tp[]> __unique_array_unknown_bound;
715};
716
717template<class _Tp, size_t _Np>
718struct __unique_if<_Tp[_Np]>
719{
720 typedef void __unique_array_known_bound;
721};
722
723template<class _Tp, class... _Args>
724inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
725typename __unique_if<_Tp>::__unique_single
726make_unique(_Args&&... __args)
727{
728 return unique_ptr<_Tp>(new _Tp(_VSTDstd::__1::forward<_Args>(__args)...));
729}
730
731template<class _Tp>
732inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
733typename __unique_if<_Tp>::__unique_array_unknown_bound
734make_unique(size_t __n)
735{
736 typedef typename remove_extent<_Tp>::type _Up;
737 return unique_ptr<_Tp>(new _Up[__n]());
738}
739
740template<class _Tp, class... _Args>
741 typename __unique_if<_Tp>::__unique_array_known_bound
742 make_unique(_Args&&...) = delete;
743
744#endif // _LIBCPP_STD_VER > 11
745
746template <class _Tp> struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) hash;
747
748template <class _Tp, class _Dp>
749#ifdef _LIBCPP_CXX03_LANG
750struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) hash<unique_ptr<_Tp, _Dp> >
751#else
752struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) hash<__enable_hash_helper<
753 unique_ptr<_Tp, _Dp>, typename unique_ptr<_Tp, _Dp>::pointer> >
754#endif
755{
756#if _LIBCPP_STD_VER14 <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
757 _LIBCPP_DEPRECATED_IN_CXX17 typedef unique_ptr<_Tp, _Dp> argument_type;
758 _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
759#endif
760
761 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
762 size_t operator()(const unique_ptr<_Tp, _Dp>& __ptr) const
763 {
764 typedef typename unique_ptr<_Tp, _Dp>::pointer pointer;
765 return hash<pointer>()(__ptr.get());
766 }
767};
768
769_LIBCPP_END_NAMESPACE_STD} }
770
771_LIBCPP_POP_MACROSpop_macro("min") pop_macro("max")
772
773#endif // _LIBCPP___MEMORY_UNIQUE_PTR_H