Debian Codegraph @

clang/docs/ClangRepl.rst

raw
1 ===========
2 Clang-Repl
3 ===========
4
5 **Clang-Repl** is an interactive C++ interpreter that allows for incremental
6 compilation. It supports interactive programming for C++ in a
7 read-evaluate-print-loop (REPL) style. It uses Clang as a library to compile the
8 high level programming language into LLVM IR. Then the LLVM IR is executed by
9 the LLVM just-in-time (JIT) infrastructure.
10
11 Clang-Repl is suitable for exploratory programming and in places where time
12 to insight is important. Clang-Repl is a project inspired by the work in
13 `Cling <https://github.com/root-project/cling>`_, a LLVM-based C/C++ interpreter
14 developed by the field of high energy physics and used by the scientific data
15 analysis framework `ROOT <https://root.cern/>`_. Clang-Repl allows to move parts
16 of Cling upstream, making them useful and available to a broader audience.
17
18
19 Clang-Repl Basic Data Flow
20 ==========================
21
22 .. image:: ClangRepl_design.png
23 :align: center
24 :alt: ClangRepl design
25
26 Clang-Repl data flow can be divided into roughly 8 phases:
27
28 1. Clang-Repl controls the input infrastructure by an interactive prompt or by
29 an interface allowing the incremental processing of input.
30
31 2. Then it sends the input to the underlying incremental facilities in Clang
32 infrastructure.
33
34 3. Clang compiles the input into an AST representation.
35
36 4. When required the AST can be further transformed in order to attach specific
37 behavior.
38
39 5. The AST representation is then lowered to LLVM IR.
40
41 6. The LLVM IR is the input format for LLVM’s JIT compilation infrastructure.
42 The tool will instruct the JIT to run specified functions, translating them
43 into machine code targeting the underlying device architecture (eg. Intel
44 x86 or NVPTX).
45
46 7. The LLVM JIT lowers the LLVM IR to machine code.
47
48 8. The machine code is then executed.
49
50 Build Instructions:
51 ===================
52
53
54 .. code-block:: console
55
56 $ cd llvm-project
57 $ mkdir build
58 $ cd build
59 $ cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DLLVM_ENABLE_PROJECTS=clang -G "Unix Makefiles" ../llvm
60
61 **Note here**, above RelWithDebInfo - Debug / Release
62
63 .. code-block:: console
64
65 cmake --build . --target clang clang-repl -j n
66 OR
67 cmake --build . --target clang clang-repl
68
69 **Clang-repl** is built under llvm-project/build/bin. Proceed into the directory **llvm-project/build/bin**
70
71 .. code-block:: console
72
73 ./clang-repl
74 clang-repl>
75
76
77 Clang-Repl Usage
78 ================
79
80 **Clang-Repl** is an interactive C++ interpreter that allows for incremental
81 compilation. It supports interactive programming for C++ in a
82 read-evaluate-print-loop (REPL) style. It uses Clang as a library to compile the
83 high level programming language into LLVM IR. Then the LLVM IR is executed by
84 the LLVM just-in-time (JIT) infrastructure.
85
86
87 Basic:
88 ======
89
90 .. code-block:: text
91
92 clang-repl> #include <iostream>
93 clang-repl> int f() { std::cout << "Hello Interpreted World!\n"; return 0; }
94 clang-repl> auto r = f();
95 // Prints Hello Interpreted World!
96
97 .. code-block:: text
98
99 clang-repl> #include<iostream>
100 clang-repl> using namespace std;
101 clang-repl> std::cout << "Welcome to CLANG-REPL" << std::endl;
102 Welcome to CLANG-REPL
103 // Prints Welcome to CLANG-REPL
104
105
106 Function Definitions and Calls:
107 ===============================
108
109 .. code-block:: text
110
111 clang-repl> #include <iostream>
112 clang-repl> int sum(int a, int b){ return a+b; };
113 clang-repl> int c = sum(9,10);
114 clang-repl> std::cout << c << std::endl;
115 19
116 clang-repl>
117
118 Iterative Structures:
119 =====================
120
121 .. code-block:: text
122
123 clang-repl> #include <iostream>
124 clang-repl> for (int i = 0;i < 3;i++){ std::cout << i << std::endl;}
125 0
126 1
127 2
128 clang-repl> while(i < 7){ i++; std::cout << i << std::endl;}
129 4
130 5
131 6
132 7
133
134 Classes and Structures:
135 =======================
136
137 .. code-block:: text
138
139 clang-repl> #include <iostream>
140 clang-repl> class Rectangle {int width, height; public: void set_values (int,int);\
141 clang-repl... int area() {return width*height;}};
142 clang-repl> void Rectangle::set_values (int x, int y) { width = x;height = y;}
143 clang-repl> int main () { Rectangle rect;rect.set_values (3,4);\
144 clang-repl... std::cout << "area: " << rect.area() << std::endl;\
145 clang-repl... return 0;}
146 clang-repl> main();
147 area: 12
148 clang-repl>
149 // Note: This '\' can be used for continuation of the statements in the next line
150
151 Lamdas:
152 =======
153
154 .. code-block:: text
155
156 clang-repl> #include <iostream>
157 clang-repl> using namespace std;
158 clang-repl> auto welcome = []() { std::cout << "Welcome to REPL" << std::endl;};
159 clang-repl> welcome();
160 Welcome to REPL
161
162 Comments:
163 =========
164
165 .. code-block:: text
166
167 clang-repl> // Comments in Clang-Repl
168 clang-repl> /* Comments in Clang-Repl */
169
170 Built in Commands:
171 ==================
172 clang-repl has some special commands that are of the form ``%<something>``. To list all these commands, use the ``%help`` command:
173
174 Help:
175 -----
176 The ``%help`` command lists all built in clang-repl commands.
177
178 .. code-block:: text
179
180 clang-repl> %help
181
182 Using Dynamic Libraries:
183 ------------------------
184 The ``%lib`` command links a dynamic library.
185
186 .. code-block:: text
187
188 clang-repl> %lib print.so
189 clang-repl> #include"print.hpp"
190 clang-repl> print(9);
191 9
192
193 **Generation of dynamic library**
194
195 .. code-block:: text
196
197 // print.cpp
198 #include <iostream>
199 #include "print.hpp"
200
201 void print(int a)
202 {
203 std::cout << a << std::endl;
204 }
205
206 // print.hpp
207 void print (int a);
208
209 // Commands
210 clang++-17 -c -o print.o print.cpp
211 clang-17 -shared print.o -o print.so
212
213 Undo:
214 -----
215 The ``%undo`` command undoes the previous input.
216
217 .. code-block:: text
218
219 clang-repl> int a = 1; a
220 (int) 1
221 clang-repl> %undo
222 clang-repl> a
223 In file included from <<< inputs >>>:1:
224 input_line_2:1:1: error: use of undeclared identifier 'a'
225 1 | a
226 * | ^
227 error: Parsing failed.
228
229 Quit:
230 -----
231 The ``%quit`` command terminates clang-repl.
232
233 .. code-block:: text
234
235 clang-repl> %quit
236
237
238
239 Just like Clang, Clang-Repl can be integrated in existing applications as a library
240 (using the clangInterpreter library). This turns your C++ compiler into a service that
241 can incrementally consume and execute code. The **Compiler as A Service** (**CaaS**)
242 concept helps support advanced use cases such as template instantiations on demand and
243 automatic language interoperability. It also helps static languages such as C/C++ become
244 apt for data science.
245
246 Execution Results Handling in Clang-Repl
247 ========================================
248
249 Execution Results Handling features discussed below help extend the Clang-Repl
250 functionality by creating an interface between the execution results of a
251 program and the compiled program.
252
253 1. **Capture Execution Results**: This feature helps capture the execution results
254 of a program and bring them back to the compiled program.
255
256 2. **Dump Captured Execution Results**: This feature helps create a temporary dump
257 for Value Printing/Automatic Printf, that is, to display the value and type of
258 the captured data.
259
260
261 1. Capture Execution Results
262 ============================
263
264 In many cases, it is useful to bring back the program execution result to the
265 compiled program. This result can be stored in an object of type **Value**.
266
267 How Execution Results are captured (Value Synthesis):
268 -----------------------------------------------------
269
270 The synthesizer chooses which expression to synthesize, and then it replaces
271 the original expression with the synthesized expression. Depending on the
272 expression type, it may choose to save an object (``LastValue``) of type 'value'
273 while allocating memory to it (``SetValueWithAlloc()``), or not (
274 ``SetValueNoAlloc()``).
275
276 .. graphviz::
277 :name: valuesynthesis
278 :caption: Value Synthesis
279 :alt: Shows how an object of type 'Value' is synthesized
280 :align: center
281
282 digraph "valuesynthesis" {
283 rankdir="LR";
284 graph [fontname="Verdana", fontsize="12"];
285 node [fontname="Verdana", fontsize="12"];
286 edge [fontname="Sans", fontsize="9"];
287
288 start [label=" Create an Object \n 'Last Value' \n of type 'Value' ", shape="note", fontcolor=white, fillcolor="#3333ff", style=filled];
289 assign [label=" Assign the result \n to the 'LastValue' \n (based on respective \n Memory Allocation \n scenario) ", shape="box"]
290 print [label=" Pretty Print \n the Value Object ", shape="Msquare", fillcolor="yellow", style=filled];
291 start -> assign;
292 assign -> print;
293
294 subgraph SynthesizeExpression {
295 synth [label=" SynthesizeExpr() ", shape="note", fontcolor=white, fillcolor="#3333ff", style=filled];
296 mem [label=" New Memory \n Allocation? ", shape="diamond"];
297 withaloc [label=" SetValueWithAlloc() ", shape="box"];
298 noaloc [label=" SetValueNoAlloc() ", shape="box"];
299 right [label=" 1. RValue Structure \n (a temporary value)", shape="box"];
300 left2 [label=" 2. LValue Structure \n (a variable with \n an address)", shape="box"];
301 left3 [label=" 3. Built-In Type \n (int, float, etc.)", shape="box"];
302 output [label=" move to 'Assign' step ", shape="box"];
303
304 synth -> mem;
305 mem -> withaloc [label="Yes"];
306 mem -> noaloc [label="No"];
307 withaloc -> right;
308 noaloc -> left2;
309 noaloc -> left3;
310 right -> output;
311 left2 -> output;
312 left3 -> output;
313 }
314 output -> assign
315 }
316
317 Where is the captured result stored?
318 ------------------------------------
319
320 ``LastValue`` holds the last result of the value printing. It is a class member
321 because it can be accessed even after subsequent inputs.
322
323 **Note:** If no value printing happens, then it is in an invalid state.
324
325 Improving Efficiency and User Experience
326 ----------------------------------------
327
328 The Value object is essentially used to create a mapping between an expression
329 'type' and the allocated 'memory'. Built-in types (bool, char, int,
330 float, double, etc.) are copyable. Their memory allocation size is known
331 and the Value object can introduce a small-buffer optimization.
332 In case of objects, the ``Value`` class provides reference-counted memory
333 management.
334
335 The implementation maps the type as written and the Clang Type to be able to use
336 the preprocessor to synthesize the relevant cast operations. For example,
337 ``X(char, Char_S)``, where ``char`` is the type from the language's type system
338 and ``Char_S`` is the Clang builtin type which represents it. This mapping helps
339 to import execution results from the interpreter in a compiled program and vice
340 versa. The ``Value.h`` header file can be included at runtime and this is why it
341 has a very low token count and was developed with strict constraints in mind.
342
343 This also enables the user to receive the computed 'type' back in their code
344 and then transform the type into something else (e.g., re-cast a double into
345 a float). Normally, the compiler can handle these conversions transparently,
346 but in interpreter mode, the compiler cannot see all the 'from' and 'to' types,
347 so it cannot implicitly do the conversions. So this logic enables providing
348 these conversions on request.
349
350 On-request conversions can help improve the user experience, by allowing
351 conversion to a desired 'to' type, when the 'from' type is unknown or unclear.
352
353 Significance of this Feature
354 ----------------------------
355
356 The 'Value' object enables wrapping a memory region that comes from the
357 JIT, and bringing it back to the compiled code (and vice versa).
358 This is a very useful functionality when:
359
360 - connecting an interpreter to the compiled code, or
361 - connecting an interpreter in another language.
362
363 For example, this feature helps transport values across boundaries. A notable
364 example is the cppyy project code makes use of this feature to enable running C++
365 within Python. It enables transporting values/information between C++
366 and Python.
367
368 Note: `cppyy <https://github.com/wlav/cppyy/>`_ is an automatic, run-time,
369 Python-to-C++ bindings generator, for calling C++ from Python and Python from C++.
370 It uses LLVM along with a C++ interpreter (e.g., Cling) to enable features like
371 run-time instantiation of C++ templates, cross-inheritance, callbacks,
372 auto-casting, transparent use of smart pointers, etc.
373
374 In a nutshell, this feature enables a new way of developing code, paving the
375 way for language interoperability and easier interactive programming.
376
377 Implementation Details
378 ======================
379
380 Interpreter as a REPL vs. as a Library
381 --------------------------------------
382
383 1 - If we're using the interpreter in interactive (REPL) mode, it will dump
384 the value (i.e., value printing).
385
386 .. code-block:: console
387
388 if (LastValue.isValid()) {
389 if (!V) {
390 LastValue.dump();
391 LastValue.clear();
392 } else
393 *V = std::move(LastValue);
394 }
395
396
397 2 - If we're using the interpreter as a library, then it will pass the value
398 to the user.
399
400 Incremental AST Consumer
401 ------------------------
402
403 The ``IncrementalASTConsumer`` class wraps the original code generator
404 ``ASTConsumer`` and it performs a hook, to traverse all the top-level decls, to
405 look for expressions to synthesize, based on the ``isSemiMissing()`` condition.
406
407 If this condition is found to be true, then ``Interp.SynthesizeExpr()`` will be
408 invoked.
409
410 **Note:** Following is a sample code snippet. Actual code may vary over time.
411
412 .. code-block:: console
413
414 for (Decl *D : DGR)
415 if (auto *TSD = llvm::dyn_cast<TopLevelStmtDecl>(D);
416 TSD && TSD->isSemiMissing())
417 TSD->setStmt(Interp.SynthesizeExpr(cast<Expr>(TSD->getStmt())));
418
419 return Consumer->HandleTopLevelDecl(DGR);
420
421 The synthesizer will then choose the relevant expression, based on its type.
422
423 Communication between Compiled Code and Interpreted Code
424 --------------------------------------------------------
425
426 In Clang-Repl there is **interpreted code**, and this feature adds a 'value'
427 runtime that can talk to the **compiled code**.
428
429 Following is an example where the compiled code interacts with the interpreter
430 code. The execution results of an expression are stored in the object 'V' of
431 type Value. This value is then printed, effectively helping the interpreter
432 use a value from the compiled code.
433
434 .. code-block:: console
435
436 int Global = 42;
437 void setGlobal(int val) { Global = val; }
438 int getGlobal() { return Global; }
439 Interp.ParseAndExecute(“void setGlobal(int val);”);
440 Interp.ParseAndExecute(“int getGlobal();”);
441 Value V;
442 Interp.ParseAndExecute(“getGlobal()”, &V);
443 std::cout << V.getAs<int>() << “\n”; // Prints 42
444
445
446 **Note:** Above is an example of interoperability between the compiled code and
447 the interpreted code. Interoperability between languages (e.g., C++ and Python)
448 works similarly.
449
450
451 2. Dump Captured Execution Results
452 ==================================
453
454 This feature helps create a temporary dump to display the value and type
455 (pretty print) of the desired data. This is a good way to interact with the
456 interpreter during interactive programming.
457
458 How value printing is simplified (Automatic Printf)
459 ---------------------------------------------------
460
461 The ``Automatic Printf`` feature makes it easy to display variable values during
462 program execution. Using the ``printf`` function repeatedly is not required.
463 This is achieved using an extension in the ``libclangInterpreter`` library.
464
465 To automatically print the value of an expression, simply write the expression
466 in the global scope **without a semicolon**.
467
468 .. graphviz::
469 :name: automaticprintf
470 :caption: Automatic PrintF
471 :alt: Shows how Automatic PrintF can be used
472 :align: center
473
474 digraph "AutomaticPrintF" {
475 size="6,4";
476 rankdir="LR";
477 graph [fontname="Verdana", fontsize="12"];
478 node [fontname="Verdana", fontsize="12"];
479 edge [fontname="Sans", fontsize="9"];
480
481 manual [label=" Manual PrintF ", shape="box"];
482 int1 [label=" int ( &) 42 ", shape="box"]
483 auto [label=" Automatic PrintF ", shape="box"];
484 int2 [label=" int ( &) 42 ", shape="box"]
485
486 auto -> int2 [label="int x = 42; \n x"];
487 manual -> int1 [label="int x = 42; \n printf(&quot;(int &) %d \\n&quot;, x);"];
488 }
489
490
491 Significance of this feature
492 ----------------------------
493
494 Inspired by a similar implementation in `Cling <https://github.com/root-project/cling>`_,
495 this feature added to upstream Clang repo has essentially extended the syntax of
496 C++, so that it can be more helpful for people that are writing code for data
497 science applications.
498
499 This is useful, for example, when you want to experiment with a set of values
500 against a set of functions, and you'd like to know the results right away.
501 This is similar to how Python works (hence its popularity in data science
502 research), but the superior performance of C++, along with this flexibility
503 makes it a more attractive option.
504
505 Implementation Details
506 ======================
507
508 Parsing mechanism:
509 ------------------
510
511 The Interpreter in Clang-Repl (``Interpreter.cpp``) includes the function
512 ``ParseAndExecute()`` that can accept a 'Value' parameter to capture the result.
513 But if the value parameter is made optional and it is omitted (i.e., that the
514 user does not want to utilize it elsewhere), then the last value can be
515 validated and pushed into the ``dump()`` function.
516
517 .. graphviz::
518 :name: parsing
519 :caption: Parsing Mechanism
520 :alt: Shows the Parsing Mechanism for Pretty Printing
521 :align: center
522
523
524 digraph "prettyprint" {
525 rankdir="LR";
526 graph [fontname="Verdana", fontsize="12"];
527 node [fontname="Verdana", fontsize="12"];
528 edge [fontname="Verdana", fontsize="9"];
529
530 parse [label=" ParseAndExecute() \n in Clang ", shape="box"];
531 capture [label=" Capture 'Value' parameter \n for processing? ", shape="diamond"];
532 use [label=" Use for processing ", shape="box"];
533 dump [label=" Validate and push \n to dump()", shape="box"];
534 callp [label=" call print() function ", shape="box"];
535 type [label=" Print the Type \n ReplPrintTypeImpl()", shape="box"];
536 data [label=" Print the Data \n ReplPrintDataImpl() ", shape="box"];
537 output [label=" Output Pretty Print \n to the user ", shape="box", fontcolor=white, fillcolor="#3333ff", style=filled];
538
539 parse -> capture [label="Optional 'Value' Parameter"];
540 capture -> use [label="Yes"];
541 use -> End;
542 capture -> dump [label="No"];
543 dump -> callp;
544 callp -> type;
545 callp -> data;
546 type -> output;
547 data -> output;
548 }
549
550 **Note:** Following is a sample code snippet. Actual code may vary over time.
551
552 .. code-block:: console
553
554 llvm::Error Interpreter::ParseAndExecute(llvm::StringRef Code, Value *V) {
555
556 auto PTU = Parse(Code);
557 if (!PTU)
558 return PTU.takeError();
559 if (PTU->TheModule)
560 if (llvm::Error Err = Execute(*PTU))
561 return Err;
562
563 if (LastValue.isValid()) {
564 if (!V) {
565 LastValue.dump();
566 LastValue.clear();
567 } else
568 *V = std::move(LastValue);
569 }
570 return llvm::Error::success();
571 }
572
573 The ``dump()`` function (in ``value.cpp``) calls the ``print()`` function.
574
575 Printing the Data and Type are handled in their respective functions:
576 ``ReplPrintDataImpl()`` and ``ReplPrintTypeImpl()``.
577
578 Annotation Token (annot_repl_input_end)
579 ---------------------------------------
580
581 This feature uses a new token (``annot_repl_input_end``) to consider printing the
582 value of an expression if it doesn't end with a semicolon. When parsing an
583 Expression Statement, if the last semicolon is missing, then the code will
584 pretend that there one and set a marker there for later utilization, and
585 continue parsing.
586
587 A semicolon is normally required in C++, but this feature expands the C++
588 syntax to handle cases where a missing semicolon is expected (i.e., when
589 handling an expression statement). It also makes sure that an error is not
590 generated for the missing semicolon in this specific case.
591
592 This is accomplished by identifying the end position of the user input
593 (expression statement). This helps store and return the expression statement
594 effectively, so that it can be printed (displayed to the user automatically).
595
596 **Note:** This logic is only available for C++ for now, since part of the
597 implementation itself requires C++ features. Future versions may support more
598 languages.
599
600 .. code-block:: console
601
602 Token *CurTok = nullptr;
603 // If the semicolon is missing at the end of REPL input, consider if
604 // we want to do value printing. Note this is only enabled in C++ mode
605 // since part of the implementation requires C++ language features.
606 // Note we shouldn't eat the token since the callback needs it.
607 if (Tok.is(tok::annot_repl_input_end) && Actions.getLangOpts().CPlusPlus)
608 CurTok = &Tok;
609 else
610 // Otherwise, eat the semicolon.
611 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
612
613 StmtResult R = handleExprStmt(Expr, StmtCtx);
614 if (CurTok && !R.isInvalid())
615 CurTok->setAnnotationValue(R.get());
616
617 return R;
618 }
619
620 AST Transformation
621 -------------------
622
623 When Sema encounters the ``annot_repl_input_end`` token, it knows to transform
624 the AST before the real CodeGen process. It will consume the token and set a
625 'semi missing' bit in the respective decl.
626
627 .. code-block:: console
628
629 if (Tok.is(tok::annot_repl_input_end) &&
630 Tok.getAnnotationValue() != nullptr) {
631 ConsumeAnnotationToken();
632 cast<TopLevelStmtDecl>(DeclsInGroup.back())->setSemiMissing();
633 }
634
635 In the AST Consumer, traverse all the Top Level Decls, to look for expressions
636 to synthesize. If the current Decl is the Top Level Statement
637 Decl(``TopLevelStmtDecl``) and has a semicolon missing, then ask the interpreter
638 to synthesize another expression (an internal function call) to replace this
639 original expression.
640
641
642 Detailed RFC and Discussion:
643 ----------------------------
644
645 For more technical details, community discussion and links to patches related
646 to these features,
647 Please visit: `RFC on LLVM Discourse <https://discourse.llvm.org/t/rfc-handle-execution-results-in-clang-repl/68493>`_.
648
649 Some logic presented in the RFC (e.g. ValueGetter()) may be outdated,
650 compared to the final developed solution.
651
652 Related Reading
653 ===============
654 `Cling Transitions to LLVM's Clang-Repl <https://root.cern/blog/cling-in-llvm/>`_
655
656 `Moving (parts of) the Cling REPL in Clang <https://lists.llvm.org/pipermail/llvm-dev/2020-July/143257.html>`_
657
658 `GPU Accelerated Automatic Differentiation With Clad <https://arxiv.org/pdf/2203.06139.pdf>`_