1 //===-- ClangExpressionParser.cpp -------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // C Includes
11 // C++ Includes
12 // Other libraries and framework includes
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/ASTDiagnostic.h"
15 #include "clang/AST/ExternalASTSource.h"
16 #include "clang/Basic/DiagnosticIDs.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Basic/SourceLocation.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/Basic/Version.h"
21 #include "clang/CodeGen/CodeGenAction.h"
22 #include "clang/CodeGen/ModuleBuilder.h"
23 #include "clang/Edit/Commit.h"
24 #include "clang/Edit/EditsReceiver.h"
25 #include "clang/Edit/EditedSource.h"
26 #include "clang/Frontend/CompilerInstance.h"
27 #include "clang/Frontend/CompilerInvocation.h"
28 #include "clang/Frontend/FrontendActions.h"
29 #include "clang/Frontend/FrontendDiagnostic.h"
30 #include "clang/Frontend/FrontendPluginRegistry.h"
31 #include "clang/Frontend/TextDiagnosticBuffer.h"
32 #include "clang/Frontend/TextDiagnosticPrinter.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Parse/ParseAST.h"
35 #include "clang/Rewrite/Frontend/FrontendActions.h"
36 #include "clang/Rewrite/Core/Rewriter.h"
37 #include "clang/Sema/SemaConsumer.h"
38 #include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
39 
40 #include "llvm/ADT/StringRef.h"
41 #include "llvm/ExecutionEngine/ExecutionEngine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/TargetSelect.h"
45 
46 #pragma clang diagnostic push
47 #pragma clang diagnostic ignored "-Wglobal-constructors"
48 #include "llvm/ExecutionEngine/MCJIT.h"
49 #pragma clang diagnostic pop
50 
51 #include "llvm/IR/LLVMContext.h"
52 #include "llvm/IR/Module.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MemoryBuffer.h"
55 #include "llvm/Support/DynamicLibrary.h"
56 #include "llvm/Support/Host.h"
57 #include "llvm/Support/Signals.h"
58 
59 // Project includes
60 #include "ClangExpressionParser.h"
61 #include "ClangDiagnostic.h"
62 
63 #include "ClangASTSource.h"
64 #include "ClangExpressionHelper.h"
65 #include "ClangExpressionDeclMap.h"
66 #include "ClangModulesDeclVendor.h"
67 #include "ClangPersistentVariables.h"
68 #include "IRForTarget.h"
69 
70 #include "lldb/Core/ArchSpec.h"
71 #include "lldb/Core/DataBufferHeap.h"
72 #include "lldb/Core/Debugger.h"
73 #include "lldb/Core/Disassembler.h"
74 #include "lldb/Core/Log.h"
75 #include "lldb/Core/Module.h"
76 #include "lldb/Core/Stream.h"
77 #include "lldb/Core/StreamFile.h"
78 #include "lldb/Core/StreamString.h"
79 #include "lldb/Core/StringList.h"
80 #include "lldb/Expression/IRDynamicChecks.h"
81 #include "lldb/Expression/IRExecutionUnit.h"
82 #include "lldb/Expression/IRInterpreter.h"
83 #include "lldb/Host/File.h"
84 #include "lldb/Host/HostInfo.h"
85 #include "lldb/Symbol/ClangASTContext.h"
86 #include "lldb/Symbol/SymbolVendor.h"
87 #include "lldb/Target/ExecutionContext.h"
88 #include "lldb/Target/Language.h"
89 #include "lldb/Target/ObjCLanguageRuntime.h"
90 #include "lldb/Target/Process.h"
91 #include "lldb/Target/Target.h"
92 #include "lldb/Target/ThreadPlanCallFunction.h"
93 #include "lldb/Utility/LLDBAssert.h"
94 
95 using namespace clang;
96 using namespace llvm;
97 using namespace lldb_private;
98 
99 //===----------------------------------------------------------------------===//
100 // Utility Methods for Clang
101 //===----------------------------------------------------------------------===//
102 
103 
104 class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks
105 {
106     ClangModulesDeclVendor     &m_decl_vendor;
107     ClangPersistentVariables   &m_persistent_vars;
108     StreamString                m_error_stream;
109     bool                        m_has_errors = false;
110 
111 public:
112     LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
113                               ClangPersistentVariables &persistent_vars) :
114         m_decl_vendor(decl_vendor),
115         m_persistent_vars(persistent_vars)
116     {
117     }
118 
119     void
120     moduleImport(SourceLocation import_location,
121                  clang::ModuleIdPath path,
122                  const clang::Module * /*null*/) override
123     {
124         std::vector<ConstString> string_path;
125 
126         for (const std::pair<IdentifierInfo *, SourceLocation> &component : path)
127         {
128             string_path.push_back(ConstString(component.first->getName()));
129         }
130 
131         StreamString error_stream;
132 
133         ClangModulesDeclVendor::ModuleVector exported_modules;
134 
135         if (!m_decl_vendor.AddModule(string_path, &exported_modules, m_error_stream))
136         {
137             m_has_errors = true;
138         }
139 
140         for (ClangModulesDeclVendor::ModuleID module : exported_modules)
141         {
142             m_persistent_vars.AddHandLoadedClangModule(module);
143         }
144     }
145 
146     bool hasErrors()
147     {
148         return m_has_errors;
149     }
150 
151     const std::string &getErrorString()
152     {
153         return m_error_stream.GetString();
154     }
155 };
156 
157 class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer
158 {
159 public:
160     ClangDiagnosticManagerAdapter() : m_passthrough(new clang::TextDiagnosticBuffer) {}
161 
162     ClangDiagnosticManagerAdapter(const std::shared_ptr<clang::TextDiagnosticBuffer> &passthrough)
163         : m_passthrough(passthrough)
164     {
165     }
166 
167     void
168     ResetManager(DiagnosticManager *manager = nullptr)
169     {
170         m_manager = manager;
171     }
172 
173     void
174     HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &Info)
175     {
176         if (m_manager)
177         {
178             llvm::SmallVector<char, 32> diag_str;
179             Info.FormatDiagnostic(diag_str);
180             diag_str.push_back('\0');
181             const char *data = diag_str.data();
182 
183             DiagnosticSeverity severity;
184             bool make_new_diagnostic = true;
185 
186             switch (DiagLevel)
187             {
188                 case DiagnosticsEngine::Level::Fatal:
189                 case DiagnosticsEngine::Level::Error:
190                     severity = eDiagnosticSeverityError;
191                     break;
192                 case DiagnosticsEngine::Level::Warning:
193                     severity = eDiagnosticSeverityWarning;
194                     break;
195                 case DiagnosticsEngine::Level::Remark:
196                 case DiagnosticsEngine::Level::Ignored:
197                     severity = eDiagnosticSeverityRemark;
198                     break;
199                 case DiagnosticsEngine::Level::Note:
200                     m_manager->AppendMessageToDiagnostic(data);
201                     make_new_diagnostic = false;
202             }
203             if (make_new_diagnostic)
204             {
205                 ClangDiagnostic *new_diagnostic = new ClangDiagnostic(data, severity, Info.getID());
206                 m_manager->AddDiagnostic(new_diagnostic);
207 
208                 // Don't store away warning fixits, since the compiler doesn't have enough
209                 // context in an expression for the warning to be useful.
210                 // FIXME: Should we try to filter out FixIts that apply to our generated
211                 // code, and not the user's expression?
212                 if (severity == eDiagnosticSeverityError)
213                 {
214                     size_t num_fixit_hints = Info.getNumFixItHints();
215                     for (size_t i = 0; i < num_fixit_hints; i++)
216                     {
217                         const clang::FixItHint &fixit = Info.getFixItHint(i);
218                         if (!fixit.isNull())
219                             new_diagnostic->AddFixitHint(fixit);
220                     }
221                 }
222             }
223         }
224 
225         m_passthrough->HandleDiagnostic(DiagLevel, Info);
226     }
227 
228     void
229     FlushDiagnostics(DiagnosticsEngine &Diags)
230     {
231         m_passthrough->FlushDiagnostics(Diags);
232     }
233 
234     DiagnosticConsumer *
235     clone(DiagnosticsEngine &Diags) const
236     {
237         return new ClangDiagnosticManagerAdapter(m_passthrough);
238     }
239 
240     clang::TextDiagnosticBuffer *
241     GetPassthrough()
242     {
243         return m_passthrough.get();
244     }
245 
246 private:
247     DiagnosticManager *m_manager = nullptr;
248     std::shared_ptr<clang::TextDiagnosticBuffer> m_passthrough;
249 };
250 
251 //===----------------------------------------------------------------------===//
252 // Implementation of ClangExpressionParser
253 //===----------------------------------------------------------------------===//
254 
255 ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
256                                               Expression &expr,
257                                               bool generate_debug_info) :
258     ExpressionParser (exe_scope, expr, generate_debug_info),
259     m_compiler (),
260     m_code_generator (),
261     m_pp_callbacks(nullptr)
262 {
263     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
264 
265     // We can't compile expressions without a target.  So if the exe_scope is null or doesn't have a target,
266     // then we just need to get out of here.  I'll lldb_assert and not make any of the compiler objects since
267     // I can't return errors directly from the constructor.  Further calls will check if the compiler was made and
268     // bag out if it wasn't.
269 
270     if (!exe_scope)
271     {
272         lldb_assert(exe_scope, "Can't make an expression parser with a null scope.", __FUNCTION__, __FILE__, __LINE__);
273         return;
274     }
275 
276     lldb::TargetSP target_sp;
277     target_sp = exe_scope->CalculateTarget();
278     if (!target_sp)
279     {
280         lldb_assert(exe_scope, "Can't make an expression parser with a null target.", __FUNCTION__, __FILE__, __LINE__);
281         return;
282     }
283 
284     // 1. Create a new compiler instance.
285     m_compiler.reset(new CompilerInstance());
286     lldb::LanguageType frame_lang = expr.Language(); // defaults to lldb::eLanguageTypeUnknown
287     bool overridden_target_opts = false;
288     lldb_private::LanguageRuntime *lang_rt = nullptr;
289 
290     ArchSpec target_arch;
291     target_arch = target_sp->GetArchitecture();
292 
293     const auto target_machine = target_arch.GetMachine();
294 
295     // If the expression is being evaluated in the context of an existing
296     // stack frame, we introspect to see if the language runtime is available.
297 
298     lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame();
299     lldb::ProcessSP process_sp = exe_scope->CalculateProcess();
300 
301     // Make sure the user hasn't provided a preferred execution language
302     // with `expression --language X -- ...`
303     if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
304         frame_lang = frame_sp->GetLanguage();
305 
306     if (process_sp && frame_lang != lldb::eLanguageTypeUnknown)
307     {
308         lang_rt = process_sp->GetLanguageRuntime(frame_lang);
309         if (log)
310             log->Printf("Frame has language of type %s", Language::GetNameForLanguageType(frame_lang));
311     }
312 
313     // 2. Configure the compiler with a set of default options that are appropriate
314     // for most situations.
315     if (target_arch.IsValid())
316     {
317         std::string triple = target_arch.GetTriple().str();
318         m_compiler->getTargetOpts().Triple = triple;
319         if (log)
320             log->Printf("Using %s as the target triple", m_compiler->getTargetOpts().Triple.c_str());
321     }
322     else
323     {
324         // If we get here we don't have a valid target and just have to guess.
325         // Sometimes this will be ok to just use the host target triple (when we evaluate say "2+3", but other
326         // expressions like breakpoint conditions and other things that _are_ target specific really shouldn't just be
327         // using the host triple. In such a case the language runtime should expose an overridden options set (3),
328         // below.
329         m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
330         if (log)
331             log->Printf("Using default target triple of %s", m_compiler->getTargetOpts().Triple.c_str());
332     }
333     // Now add some special fixes for known architectures:
334     // Any arm32 iOS environment, but not on arm64
335     if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
336         m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
337         m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos)
338     {
339         m_compiler->getTargetOpts().ABI = "apcs-gnu";
340     }
341     // Supported subsets of x86
342     if (target_machine == llvm::Triple::x86 ||
343         target_machine == llvm::Triple::x86_64)
344     {
345         m_compiler->getTargetOpts().Features.push_back("+sse");
346         m_compiler->getTargetOpts().Features.push_back("+sse2");
347     }
348 
349     // Set the target CPU to generate code for.
350     // This will be empty for any CPU that doesn't really need to make a special CPU string.
351     m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
352 
353     // 3. Now allow the runtime to provide custom configuration options for the target.
354     // In this case, a specialized language runtime is available and we can query it for extra options.
355     // For 99% of use cases, this will not be needed and should be provided when basic platform detection is not enough.
356     if (lang_rt)
357         overridden_target_opts = lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
358 
359     if (overridden_target_opts)
360         if (log)
361         {
362             log->Debug("Using overridden target options for the expression evaluation");
363 
364             auto opts = m_compiler->getTargetOpts();
365             log->Debug("Triple: '%s'", opts.Triple.c_str());
366             log->Debug("CPU: '%s'", opts.CPU.c_str());
367             log->Debug("FPMath: '%s'", opts.FPMath.c_str());
368             log->Debug("ABI: '%s'", opts.ABI.c_str());
369             log->Debug("LinkerVersion: '%s'", opts.LinkerVersion.c_str());
370             StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
371             StringList::LogDump(log, opts.Features, "Features");
372             StringList::LogDump(log, opts.Reciprocals, "Reciprocals");
373         }
374 
375     // 4. Create and install the target on the compiler.
376     m_compiler->createDiagnostics();
377     auto target_info = TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
378     if (log)
379     {
380         log->Printf("Using SIMD alignment: %d", target_info->getSimdDefaultAlign());
381         log->Printf("Target datalayout string: '%s'", target_info->getDataLayout().getStringRepresentation().c_str());
382         log->Printf("Target ABI: '%s'", target_info->getABI().str().c_str());
383         log->Printf("Target vector alignment: %d", target_info->getMaxVectorAlign());
384     }
385     m_compiler->setTarget(target_info);
386 
387     assert (m_compiler->hasTarget());
388 
389     // 5. Set language options.
390     lldb::LanguageType language = expr.Language();
391 
392     switch (language)
393     {
394     case lldb::eLanguageTypeC:
395     case lldb::eLanguageTypeC89:
396     case lldb::eLanguageTypeC99:
397     case lldb::eLanguageTypeC11:
398         // FIXME: the following language option is a temporary workaround,
399         // to "ask for C, get C++."
400         // For now, the expression parser must use C++ anytime the
401         // language is a C family language, because the expression parser
402         // uses features of C++ to capture values.
403         m_compiler->getLangOpts().CPlusPlus = true;
404         break;
405     case lldb::eLanguageTypeObjC:
406         m_compiler->getLangOpts().ObjC1 = true;
407         m_compiler->getLangOpts().ObjC2 = true;
408         // FIXME: the following language option is a temporary workaround,
409         // to "ask for ObjC, get ObjC++" (see comment above).
410         m_compiler->getLangOpts().CPlusPlus = true;
411         break;
412     case lldb::eLanguageTypeC_plus_plus:
413     case lldb::eLanguageTypeC_plus_plus_11:
414     case lldb::eLanguageTypeC_plus_plus_14:
415         m_compiler->getLangOpts().CPlusPlus11 = true;
416         m_compiler->getHeaderSearchOpts().UseLibcxx = true;
417         LLVM_FALLTHROUGH;
418     case lldb::eLanguageTypeC_plus_plus_03:
419         m_compiler->getLangOpts().CPlusPlus = true;
420         // FIXME: the following language option is a temporary workaround,
421         // to "ask for C++, get ObjC++".  Apple hopes to remove this requirement
422         // on non-Apple platforms, but for now it is needed.
423         m_compiler->getLangOpts().ObjC1 = true;
424         break;
425     case lldb::eLanguageTypeObjC_plus_plus:
426     case lldb::eLanguageTypeUnknown:
427     default:
428         m_compiler->getLangOpts().ObjC1 = true;
429         m_compiler->getLangOpts().ObjC2 = true;
430         m_compiler->getLangOpts().CPlusPlus = true;
431         m_compiler->getLangOpts().CPlusPlus11 = true;
432         m_compiler->getHeaderSearchOpts().UseLibcxx = true;
433         break;
434     }
435 
436     m_compiler->getLangOpts().Bool = true;
437     m_compiler->getLangOpts().WChar = true;
438     m_compiler->getLangOpts().Blocks = true;
439     m_compiler->getLangOpts().DebuggerSupport = true; // Features specifically for debugger clients
440     if (expr.DesiredResultType() == Expression::eResultTypeId)
441         m_compiler->getLangOpts().DebuggerCastResultToId = true;
442 
443     m_compiler->getLangOpts().CharIsSigned =
444             ArchSpec(m_compiler->getTargetOpts().Triple.c_str()).CharIsSignedByDefault();
445 
446     // Spell checking is a nice feature, but it ends up completing a
447     // lot of types that we didn't strictly speaking need to complete.
448     // As a result, we spend a long time parsing and importing debug
449     // information.
450     m_compiler->getLangOpts().SpellChecking = false;
451 
452     if (process_sp && m_compiler->getLangOpts().ObjC1)
453     {
454         if (process_sp->GetObjCLanguageRuntime())
455         {
456             if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() == ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
457                 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
458             else
459                 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::FragileMacOSX, VersionTuple(10, 7));
460 
461             if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing())
462                 m_compiler->getLangOpts().DebuggerObjCLiteral = true;
463         }
464     }
465 
466     m_compiler->getLangOpts().ThreadsafeStatics = false;
467     m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
468     m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
469 
470     // Set CodeGen options
471     m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
472     m_compiler->getCodeGenOpts().InstrumentFunctions = false;
473     m_compiler->getCodeGenOpts().DisableFPElim = true;
474     m_compiler->getCodeGenOpts().OmitLeafFramePointer = false;
475     if (generate_debug_info)
476         m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
477     else
478         m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
479 
480     // Disable some warnings.
481     m_compiler->getDiagnostics().setSeverityForGroup(clang::diag::Flavor::WarningOrError,
482         "unused-value", clang::diag::Severity::Ignored, SourceLocation());
483     m_compiler->getDiagnostics().setSeverityForGroup(clang::diag::Flavor::WarningOrError,
484         "odr", clang::diag::Severity::Ignored, SourceLocation());
485 
486     // Inform the target of the language options
487     //
488     // FIXME: We shouldn't need to do this, the target should be immutable once
489     // created. This complexity should be lifted elsewhere.
490     m_compiler->getTarget().adjust(m_compiler->getLangOpts());
491 
492     // 6. Set up the diagnostic buffer for reporting errors
493 
494     m_compiler->getDiagnostics().setClient(new ClangDiagnosticManagerAdapter);
495 
496     // 7. Set up the source management objects inside the compiler
497 
498     clang::FileSystemOptions file_system_options;
499     m_file_manager.reset(new clang::FileManager(file_system_options));
500 
501     if (!m_compiler->hasSourceManager())
502         m_compiler->createSourceManager(*m_file_manager.get());
503 
504     m_compiler->createFileManager();
505     m_compiler->createPreprocessor(TU_Complete);
506 
507     if (ClangModulesDeclVendor *decl_vendor = target_sp->GetClangModulesDeclVendor())
508     {
509         ClangPersistentVariables *clang_persistent_vars = llvm::cast<ClangPersistentVariables>(target_sp->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC));
510         std::unique_ptr<PPCallbacks> pp_callbacks(new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars));
511         m_pp_callbacks = static_cast<LLDBPreprocessorCallbacks*>(pp_callbacks.get());
512         m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
513     }
514 
515     // 8. Most of this we get from the CompilerInstance, but we
516     // also want to give the context an ExternalASTSource.
517     m_selector_table.reset(new SelectorTable());
518     m_builtin_context.reset(new Builtin::Context());
519 
520     std::unique_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
521                                                                   m_compiler->getSourceManager(),
522                                                                   m_compiler->getPreprocessor().getIdentifierTable(),
523                                                                   *m_selector_table.get(),
524                                                                   *m_builtin_context.get()));
525 
526     ast_context->InitBuiltinTypes(m_compiler->getTarget());
527 
528     ClangExpressionHelper *type_system_helper = dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
529     ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
530 
531     if (decl_map)
532     {
533         llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source(decl_map->CreateProxy());
534         decl_map->InstallASTContext(ast_context.get());
535         ast_context->setExternalSource(ast_source);
536     }
537 
538     m_ast_context.reset(new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str()));
539     m_ast_context->setASTContext(ast_context.get());
540     m_compiler->setASTContext(ast_context.release());
541 
542     std::string module_name("$__lldb_module");
543 
544     m_llvm_context.reset(new LLVMContext());
545     m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
546                                              module_name,
547                                              m_compiler->getHeaderSearchOpts(),
548                                              m_compiler->getPreprocessorOpts(),
549                                              m_compiler->getCodeGenOpts(),
550                                              *m_llvm_context));
551 }
552 
553 ClangExpressionParser::~ClangExpressionParser()
554 {
555 }
556 
557 unsigned
558 ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager)
559 {
560     ClangDiagnosticManagerAdapter *adapter =
561         static_cast<ClangDiagnosticManagerAdapter *>(m_compiler->getDiagnostics().getClient());
562     clang::TextDiagnosticBuffer *diag_buf = adapter->GetPassthrough();
563     diag_buf->FlushDiagnostics(m_compiler->getDiagnostics());
564 
565     adapter->ResetManager(&diagnostic_manager);
566 
567     const char *expr_text = m_expr.Text();
568 
569     clang::SourceManager &source_mgr = m_compiler->getSourceManager();
570     bool created_main_file = false;
571     if (m_compiler->getCodeGenOpts().getDebugInfo() == codegenoptions::FullDebugInfo)
572     {
573         int temp_fd = -1;
574         llvm::SmallString<PATH_MAX> result_path;
575         FileSpec tmpdir_file_spec;
576         if (HostInfo::GetLLDBPath(lldb::ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
577         {
578             tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
579             std::string temp_source_path = tmpdir_file_spec.GetPath();
580             llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
581         }
582         else
583         {
584             llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
585         }
586 
587         if (temp_fd != -1)
588         {
589             lldb_private::File file(temp_fd, true);
590             const size_t expr_text_len = strlen(expr_text);
591             size_t bytes_written = expr_text_len;
592             if (file.Write(expr_text, bytes_written).Success())
593             {
594                 if (bytes_written == expr_text_len)
595                 {
596                     file.Close();
597                     source_mgr.setMainFileID(source_mgr.createFileID(m_file_manager->getFile(result_path),
598                                                                      SourceLocation(), SrcMgr::C_User));
599                     created_main_file = true;
600                 }
601             }
602         }
603     }
604 
605     if (!created_main_file)
606     {
607         std::unique_ptr<MemoryBuffer> memory_buffer = MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
608         source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
609     }
610 
611     diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
612 
613     ClangExpressionHelper *type_system_helper = dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
614 
615     ASTConsumer *ast_transformer = type_system_helper->ASTTransformer(m_code_generator.get());
616 
617     if (ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap())
618         decl_map->InstallCodeGenerator(m_code_generator.get());
619 
620     if (ast_transformer)
621     {
622         ast_transformer->Initialize(m_compiler->getASTContext());
623         ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
624     }
625     else
626     {
627         m_code_generator->Initialize(m_compiler->getASTContext());
628         ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
629     }
630 
631     diag_buf->EndSourceFile();
632 
633     unsigned num_errors = diag_buf->getNumErrors();
634 
635     if (m_pp_callbacks && m_pp_callbacks->hasErrors())
636     {
637         num_errors++;
638         diagnostic_manager.PutCString(eDiagnosticSeverityError, "while importing modules:");
639         diagnostic_manager.AppendMessageToDiagnostic(m_pp_callbacks->getErrorString().c_str());
640     }
641 
642     if (!num_errors)
643     {
644         if (type_system_helper->DeclMap() && !type_system_helper->DeclMap()->ResolveUnknownTypes())
645         {
646             diagnostic_manager.Printf(eDiagnosticSeverityError, "Couldn't infer the type of a variable");
647             num_errors++;
648         }
649     }
650 
651     if (!num_errors)
652     {
653         type_system_helper->CommitPersistentDecls();
654     }
655 
656     adapter->ResetManager();
657 
658     return num_errors;
659 }
660 
661 bool
662 ClangExpressionParser::RewriteExpression(DiagnosticManager &diagnostic_manager)
663 {
664     clang::SourceManager &source_manager = m_compiler->getSourceManager();
665     clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(), nullptr);
666     clang::edit::Commit commit(editor);
667     clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
668 
669     class RewritesReceiver : public edit::EditsReceiver {
670       Rewriter &rewrite;
671 
672     public:
673       RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) { }
674 
675       void insert(SourceLocation loc, StringRef text) override {
676         rewrite.InsertText(loc, text);
677       }
678       void replace(CharSourceRange range, StringRef text) override {
679         rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
680       }
681     };
682 
683     RewritesReceiver rewrites_receiver(rewriter);
684 
685     const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
686     size_t num_diags = diagnostics.size();
687     if (num_diags == 0)
688         return false;
689 
690     for (const Diagnostic *diag : diagnostic_manager.Diagnostics())
691     {
692         const ClangDiagnostic *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag);
693         if (diagnostic && diagnostic->HasFixIts())
694         {
695              for (const FixItHint &fixit : diagnostic->FixIts())
696              {
697                 // This is cobbed from clang::Rewrite::FixItRewriter.
698                 if (fixit.CodeToInsert.empty())
699                 {
700                   if (fixit.InsertFromRange.isValid())
701                   {
702                       commit.insertFromRange(fixit.RemoveRange.getBegin(),
703                                              fixit.InsertFromRange, /*afterToken=*/false,
704                                              fixit.BeforePreviousInsertions);
705                   }
706                   else
707                     commit.remove(fixit.RemoveRange);
708                 }
709                 else
710                 {
711                   if (fixit.RemoveRange.isTokenRange() ||
712                       fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd())
713                     commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
714                   else
715                     commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
716                                 /*afterToken=*/false, fixit.BeforePreviousInsertions);
717                 }
718             }
719         }
720     }
721 
722     // FIXME - do we want to try to propagate specific errors here?
723     if (!commit.isCommitable())
724         return false;
725     else if (!editor.commit(commit))
726         return false;
727 
728     // Now play all the edits, and stash the result in the diagnostic manager.
729     editor.applyRewrites(rewrites_receiver);
730     RewriteBuffer &main_file_buffer = rewriter.getEditBuffer(source_manager.getMainFileID());
731 
732     std::string fixed_expression;
733     llvm::raw_string_ostream out_stream(fixed_expression);
734 
735     main_file_buffer.write(out_stream);
736     out_stream.flush();
737     diagnostic_manager.SetFixedExpression(fixed_expression);
738 
739     return true;
740 }
741 
742 static bool FindFunctionInModule (ConstString &mangled_name,
743                                   llvm::Module *module,
744                                   const char *orig_name)
745 {
746     for (const auto &func : module->getFunctionList())
747     {
748         const StringRef &name = func.getName();
749         if (name.find(orig_name) != StringRef::npos)
750         {
751             mangled_name.SetString(name);
752             return true;
753         }
754     }
755 
756     return false;
757 }
758 
759 lldb_private::Error
760 ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_addr,
761                                             lldb::addr_t &func_end,
762                                             lldb::IRExecutionUnitSP &execution_unit_sp,
763                                             ExecutionContext &exe_ctx,
764                                             bool &can_interpret,
765                                             ExecutionPolicy execution_policy)
766 {
767 	func_addr = LLDB_INVALID_ADDRESS;
768 	func_end = LLDB_INVALID_ADDRESS;
769     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
770 
771     lldb_private::Error err;
772 
773     std::unique_ptr<llvm::Module> llvm_module_ap (m_code_generator->ReleaseModule());
774 
775     if (!llvm_module_ap.get())
776     {
777         err.SetErrorToGenericError();
778         err.SetErrorString("IR doesn't contain a module");
779         return err;
780     }
781 
782     ConstString function_name;
783 
784     if (execution_policy != eExecutionPolicyTopLevel)
785     {
786         // Find the actual name of the function (it's often mangled somehow)
787 
788         if (!FindFunctionInModule(function_name, llvm_module_ap.get(), m_expr.FunctionName()))
789         {
790             err.SetErrorToGenericError();
791             err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
792             return err;
793         }
794         else
795         {
796             if (log)
797                 log->Printf("Found function %s for %s", function_name.AsCString(), m_expr.FunctionName());
798         }
799     }
800 
801     SymbolContext sc;
802 
803     if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP())
804     {
805         sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
806     }
807     else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP())
808     {
809         sc.target_sp = target_sp;
810     }
811 
812     execution_unit_sp.reset(new IRExecutionUnit (m_llvm_context, // handed off here
813                                                  llvm_module_ap, // handed off here
814                                                  function_name,
815                                                  exe_ctx.GetTargetSP(),
816                                                  sc,
817                                                  m_compiler->getTargetOpts().Features));
818 
819     ClangExpressionHelper *type_system_helper = dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
820     ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap(); // result can be NULL
821 
822     if (decl_map)
823     {
824         Stream *error_stream = NULL;
825         Target *target = exe_ctx.GetTargetPtr();
826         if (target)
827             error_stream = target->GetDebugger().GetErrorFile().get();
828 
829         IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(), *execution_unit_sp, error_stream,
830                                   function_name.AsCString());
831 
832         bool ir_can_run = ir_for_target.runOnModule(*execution_unit_sp->GetModule());
833 
834         Process *process = exe_ctx.GetProcessPtr();
835 
836         if (execution_policy != eExecutionPolicyAlways && execution_policy != eExecutionPolicyTopLevel)
837         {
838             lldb_private::Error interpret_error;
839 
840             bool interpret_function_calls = !process ? false : process->CanInterpretFunctionCalls();
841             can_interpret =
842                 IRInterpreter::CanInterpret(*execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
843                                             interpret_error, interpret_function_calls);
844 
845             if (!can_interpret && execution_policy == eExecutionPolicyNever)
846             {
847                 err.SetErrorStringWithFormat("Can't run the expression locally: %s", interpret_error.AsCString());
848                 return err;
849             }
850         }
851 
852         if (!ir_can_run)
853         {
854             err.SetErrorString("The expression could not be prepared to run in the target");
855             return err;
856         }
857 
858         if (!process && execution_policy == eExecutionPolicyAlways)
859         {
860             err.SetErrorString("Expression needed to run in the target, but the target can't be run");
861             return err;
862         }
863 
864         if (!process && execution_policy == eExecutionPolicyTopLevel)
865         {
866             err.SetErrorString(
867                 "Top-level code needs to be inserted into a runnable target, but the target can't be run");
868             return err;
869         }
870 
871         if (execution_policy == eExecutionPolicyAlways ||
872             (execution_policy != eExecutionPolicyTopLevel && !can_interpret))
873         {
874             if (m_expr.NeedsValidation() && process)
875             {
876                 if (!process->GetDynamicCheckers())
877                 {
878                     DynamicCheckerFunctions *dynamic_checkers = new DynamicCheckerFunctions();
879 
880                     DiagnosticManager install_diagnostics;
881 
882                     if (!dynamic_checkers->Install(install_diagnostics, exe_ctx))
883                     {
884                         if (install_diagnostics.Diagnostics().size())
885                             err.SetErrorString("couldn't install checkers, unknown error");
886                         else
887                             err.SetErrorString(install_diagnostics.GetString().c_str());
888 
889                         return err;
890                     }
891 
892                     process->SetDynamicCheckers(dynamic_checkers);
893 
894                     if (log)
895                         log->Printf("== [ClangUserExpression::Evaluate] Finished installing dynamic checkers ==");
896                 }
897 
898                 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(), function_name.AsCString());
899 
900                 if (!ir_dynamic_checks.runOnModule(*execution_unit_sp->GetModule()))
901                 {
902                     err.SetErrorToGenericError();
903                     err.SetErrorString("Couldn't add dynamic checks to the expression");
904                     return err;
905                 }
906             }
907         }
908 
909         if (execution_policy == eExecutionPolicyAlways || execution_policy == eExecutionPolicyTopLevel ||
910             !can_interpret)
911         {
912             execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
913         }
914     }
915     else
916     {
917         execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
918     }
919 
920     return err;
921 }
922 
923 lldb_private::Error
924 ClangExpressionParser::RunStaticInitializers (lldb::IRExecutionUnitSP &execution_unit_sp,
925                                               ExecutionContext &exe_ctx)
926 {
927     lldb_private::Error err;
928 
929     lldbassert(execution_unit_sp.get());
930     lldbassert(exe_ctx.HasThreadScope());
931 
932     if (!execution_unit_sp.get())
933     {
934         err.SetErrorString ("can't run static initializers for a NULL execution unit");
935         return err;
936     }
937 
938     if (!exe_ctx.HasThreadScope())
939     {
940         err.SetErrorString ("can't run static initializers without a thread");
941         return err;
942     }
943 
944     std::vector<lldb::addr_t> static_initializers;
945 
946     execution_unit_sp->GetStaticInitializers(static_initializers);
947 
948     for (lldb::addr_t static_initializer : static_initializers)
949     {
950         EvaluateExpressionOptions options;
951 
952         lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(exe_ctx.GetThreadRef(),
953                                                                               Address(static_initializer),
954                                                                               CompilerType(),
955                                                                               llvm::ArrayRef<lldb::addr_t>(),
956                                                                               options));
957 
958         DiagnosticManager execution_errors;
959         lldb::ExpressionResults results = exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(exe_ctx, call_static_initializer, options, execution_errors);
960 
961         if (results != lldb::eExpressionCompleted)
962         {
963             err.SetErrorStringWithFormat ("couldn't run static initializer: %s", execution_errors.GetString().c_str());
964             return err;
965         }
966     }
967 
968     return err;
969 }
970