File: ORCv2.html

package info (click to toggle)
llvm-toolchain-13 1%3A13.0.1-6~deb10u4
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,418,792 kB
  • sloc: cpp: 5,290,827; ansic: 996,570; asm: 544,593; python: 188,212; objc: 72,027; lisp: 30,291; f90: 25,395; sh: 24,900; javascript: 9,780; pascal: 9,398; perl: 7,484; ml: 5,432; awk: 3,523; makefile: 2,892; xml: 953; cs: 573; fortran: 539
file content (897 lines) | stat: -rw-r--r-- 72,777 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897


<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>ORC Design and Implementation &#8212; LLVM 13 documentation</title>
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="_static/llvm-theme.css" type="text/css" />
    <script id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script src="_static/jquery.js"></script>
    <script src="_static/underscore.js"></script>
    <script src="_static/doctools.js"></script>
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="Opaque Pointers" href="OpaquePointers.html" />
    <link rel="prev" title="MCJIT Design and Implementation" href="MCJITDesignAndImplementation.html" />
<style type="text/css">
  table.right { float: right; margin-left: 20px; }
  table.right td { border: 1px solid #ccc; }
</style>

  </head><body>
<div class="logo">
  <a href="index.html">
    <img src="_static/logo.png"
         alt="LLVM Logo" width="250" height="88"/></a>
</div>

    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="OpaquePointers.html" title="Opaque Pointers"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="MCJITDesignAndImplementation.html" title="MCJIT Design and Implementation"
             accesskey="P">previous</a> |</li>
  <li><a href="https://llvm.org/">LLVM Home</a>&nbsp;|&nbsp;</li>
  <li><a href="index.html">Documentation</a>&raquo;</li>

          <li class="nav-item nav-item-1"><a href="UserGuides.html" accesskey="U">User Guides</a> &#187;</li>
        <li class="nav-item nav-item-this"><a href="">ORC Design and Implementation</a></li> 
      </ul>
    </div>

      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">

<h3>Documentation</h3>

<ul class="want-points">
    <li><a href="https://llvm.org/docs/GettingStartedTutorials.html">Getting Started/Tutorials</a></li>
    <li><a href="https://llvm.org/docs/UserGuides.html">User Guides</a></li>
    <li><a href="https://llvm.org/docs/Reference.html">Reference</a></li>
</ul>

<h3>Getting Involved</h3>

<ul class="want-points">
    <li><a href="https://llvm.org/docs/Contributing.html">Contributing to LLVM</a></li>
    <li><a href="https://llvm.org/docs/HowToSubmitABug.html">Submitting Bug Reports</a></li>
    <li><a href="https://llvm.org/docs/GettingInvolved.html#mailing-lists">Mailing Lists</a></li>
    <li><a href="https://llvm.org/docs/GettingInvolved.html#irc">IRC</a></li>
    <li><a href="https://llvm.org/docs/GettingInvolved.html#meetups-and-social-events">Meetups and Social Events</a></li>
</ul>

<h3>Additional Links</h3>

<ul class="want-points">
    <li><a href="https://llvm.org/docs/FAQ.html">FAQ</a></li>
    <li><a href="https://llvm.org/docs/Lexicon.html">Glossary</a></li>
    <li><a href="https://llvm.org/pubs">Publications</a></li>
    <li><a href="https://github.com/llvm/llvm-project//">Github Repository</a></li>
</ul>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="_sources/ORCv2.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3 id="searchlabel">Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" />
      <input type="submit" value="Go" />
    </form>
    </div>
</div>
<script>$('#searchbox').show(0);</script>
        </div>
      </div>

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="orc-design-and-implementation">
<h1>ORC Design and Implementation<a class="headerlink" href="#orc-design-and-implementation" title="Permalink to this headline">¶</a></h1>
<div class="contents local topic" id="contents">
<ul class="simple">
<li><p><a class="reference internal" href="#introduction" id="id8">Introduction</a></p></li>
<li><p><a class="reference internal" href="#use-cases" id="id9">Use-cases</a></p></li>
<li><p><a class="reference internal" href="#features" id="id10">Features</a></p></li>
<li><p><a class="reference internal" href="#lljit-and-lllazyjit" id="id11">LLJIT and LLLazyJIT</a></p></li>
<li><p><a class="reference internal" href="#design-overview" id="id12">Design Overview</a></p></li>
<li><p><a class="reference internal" href="#top-level-apis" id="id13">Top Level APIs</a></p></li>
<li><p><a class="reference internal" href="#absolute-symbols-aliases-and-reexports" id="id14">Absolute Symbols, Aliases, and Reexports</a></p>
<ul>
<li><p><a class="reference internal" href="#absolute-symbols" id="id15">Absolute Symbols</a></p></li>
<li><p><a class="reference internal" href="#aliases-and-reexports" id="id16">Aliases and Reexports</a></p></li>
</ul>
</li>
<li><p><a class="reference internal" href="#laziness" id="id17">Laziness</a></p></li>
<li><p><a class="reference internal" href="#supporting-custom-compilers" id="id18">Supporting Custom Compilers</a></p></li>
<li><p><a class="reference internal" href="#transitioning-from-orcv1-to-orcv2" id="id19">Transitioning from ORCv1 to ORCv2</a></p></li>
<li><p><a class="reference internal" href="#how-tos" id="id20">How-tos</a></p>
<ul>
<li><p><a class="reference internal" href="#how-to-manage-symbol-strings" id="id21">How to manage symbol strings</a></p></li>
<li><p><a class="reference internal" href="#how-to-create-jitdylibs-and-set-up-linkage-relationships" id="id22">How to create JITDylibs and set up linkage relationships</a></p></li>
<li><p><a class="reference internal" href="#how-to-use-threadsafemodule-and-threadsafecontext" id="id23">How to use ThreadSafeModule and ThreadSafeContext</a></p></li>
</ul>
</li>
<li><p><a class="reference internal" href="#how-to-add-process-and-library-symbols-to-the-jitdylibs" id="id24">How to Add Process and Library Symbols to the JITDylibs</a></p></li>
<li><p><a class="reference internal" href="#roadmap" id="id25">Roadmap</a></p>
<ul>
<li><p><a class="reference internal" href="#current-work" id="id26">Current Work</a></p></li>
<li><p><a class="reference internal" href="#near-future-work" id="id27">Near Future Work</a></p></li>
<li><p><a class="reference internal" href="#further-future-work" id="id28">Further Future Work</a></p></li>
</ul>
</li>
</ul>
</div>
<div class="section" id="introduction">
<h2><a class="toc-backref" href="#id8">Introduction</a><a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
<p>This document aims to provide a high-level overview of the design and
implementation of the ORC JIT APIs. Except where otherwise stated all discussion
refers to the modern ORCv2 APIs (available since LLVM 7). Clients wishing to
transition from OrcV1 should see Section <a class="reference internal" href="#transitioning-orcv1-to-orcv2"><span class="std std-ref">Transitioning from ORCv1 to ORCv2</span></a>.</p>
</div>
<div class="section" id="use-cases">
<h2><a class="toc-backref" href="#id9">Use-cases</a><a class="headerlink" href="#use-cases" title="Permalink to this headline">¶</a></h2>
<p>ORC provides a modular API for building JIT compilers. There are a number
of use cases for such an API. For example:</p>
<p>1. The LLVM tutorials use a simple ORC-based JIT class to execute expressions
compiled from a toy language: Kaleidoscope.</p>
<p>2. The LLVM debugger, LLDB, uses a cross-compiling JIT for expression
evaluation. In this use case, cross compilation allows expressions compiled
in the debugger process to be executed on the debug target process, which may
be on a different device/architecture.</p>
<p>3. In high-performance JITs (e.g. JVMs, Julia) that want to make use of LLVM’s
optimizations within an existing JIT infrastructure.</p>
<ol class="arabic simple" start="4">
<li><p>In interpreters and REPLs, e.g. Cling (C++) and the Swift interpreter.</p></li>
</ol>
<p>By adopting a modular, library-based design we aim to make ORC useful in as many
of these contexts as possible.</p>
</div>
<div class="section" id="features">
<h2><a class="toc-backref" href="#id10">Features</a><a class="headerlink" href="#features" title="Permalink to this headline">¶</a></h2>
<p>ORC provides the following features:</p>
<dl class="simple">
<dt><strong>JIT-linking</strong></dt><dd><p>ORC provides APIs to link relocatable object files (COFF, ELF, MachO) <a class="footnote-reference brackets" href="#id5" id="id1">1</a>
into a target process at runtime. The target process may be the same process
that contains the JIT session object and jit-linker, or may be another process
(even one running on a different machine or architecture) that communicates
with the JIT via RPC.</p>
</dd>
<dt><strong>LLVM IR compilation</strong></dt><dd><p>ORC provides off the shelf components (IRCompileLayer, SimpleCompiler,
ConcurrentIRCompiler) that make it easy to add LLVM IR to a JIT’d process.</p>
</dd>
<dt><strong>Eager and lazy compilation</strong></dt><dd><p>By default, ORC will compile symbols as soon as they are looked up in the JIT
session object (<code class="docutils literal notranslate"><span class="pre">ExecutionSession</span></code>). Compiling eagerly by default makes it
easy to use ORC as an in-memory compiler for an existing JIT (similar to how
MCJIT is commonly used). However ORC also provides built-in support for lazy
compilation via lazy-reexports (see <a class="reference internal" href="#laziness"><span class="std std-ref">Laziness</span></a>).</p>
</dd>
<dt><strong>Support for Custom Compilers and Program Representations</strong></dt><dd><p>Clients can supply custom compilers for each symbol that they define in their
JIT session. ORC will run the user-supplied compiler when the a definition of
a symbol is needed. ORC is actually fully language agnostic: LLVM IR is not
treated specially, and is supported via the same wrapper mechanism (the
<code class="docutils literal notranslate"><span class="pre">MaterializationUnit</span></code> class) that is used for custom compilers.</p>
</dd>
<dt><strong>Concurrent JIT’d code</strong> and <strong>Concurrent Compilation</strong></dt><dd><p>JIT’d code may be executed in multiple threads, may spawn new threads, and may
re-enter the ORC (e.g. to request lazy compilation) concurrently from multiple
threads. Compilers launched my ORC can run concurrently (provided the client
sets up an appropriate dispatcher). Built-in dependency tracking ensures that
ORC does not release pointers to JIT’d code or data until all dependencies
have also been JIT’d and they are safe to call or use.</p>
</dd>
<dt><strong>Removable Code</strong></dt><dd><p>Resources for JIT’d program representations</p>
</dd>
<dt><strong>Orthogonality</strong> and <strong>Composability</strong></dt><dd><p>Each of the features above can be used independently. It is possible to put
ORC components together to make a non-lazy, in-process, single threaded JIT
or a lazy, out-of-process, concurrent JIT, or anything in between.</p>
</dd>
</dl>
</div>
<div class="section" id="lljit-and-lllazyjit">
<h2><a class="toc-backref" href="#id11">LLJIT and LLLazyJIT</a><a class="headerlink" href="#lljit-and-lllazyjit" title="Permalink to this headline">¶</a></h2>
<p>ORC provides two basic JIT classes off-the-shelf. These are useful both as
examples of how to assemble ORC components to make a JIT, and as replacements
for earlier LLVM JIT APIs (e.g. MCJIT).</p>
<p>The LLJIT class uses an IRCompileLayer and RTDyldObjectLinkingLayer to support
compilation of LLVM IR and linking of relocatable object files. All operations
are performed eagerly on symbol lookup (i.e. a symbol’s definition is compiled
as soon as you attempt to look up its address). LLJIT is a suitable replacement
for MCJIT in most cases (note: some more advanced features, e.g.
JITEventListeners are not supported yet).</p>
<p>The LLLazyJIT extends LLJIT and adds a CompileOnDemandLayer to enable lazy
compilation of LLVM IR. When an LLVM IR module is added via the addLazyIRModule
method, function bodies in that module will not be compiled until they are first
called. LLLazyJIT aims to provide a replacement of LLVM’s original (pre-MCJIT)
JIT API.</p>
<p>LLJIT and LLLazyJIT instances can be created using their respective builder
classes: LLJITBuilder and LLazyJITBuilder. For example, assuming you have a
module <code class="docutils literal notranslate"><span class="pre">M</span></code> loaded on a ThreadSafeContext <code class="docutils literal notranslate"><span class="pre">Ctx</span></code>:</p>
<div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="c1">// Try to detect the host arch and construct an LLJIT instance.</span>
<span class="k">auto</span> <span class="n">JIT</span> <span class="o">=</span> <span class="n">LLJITBuilder</span><span class="p">().</span><span class="n">create</span><span class="p">();</span>

<span class="c1">// If we could not construct an instance, return an error.</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">JIT</span><span class="p">)</span>
  <span class="k">return</span> <span class="n">JIT</span><span class="p">.</span><span class="n">takeError</span><span class="p">();</span>

<span class="c1">// Add the module.</span>
<span class="k">if</span> <span class="p">(</span><span class="k">auto</span> <span class="n">Err</span> <span class="o">=</span> <span class="n">JIT</span><span class="o">-&gt;</span><span class="n">addIRModule</span><span class="p">(</span><span class="n">TheadSafeModule</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">M</span><span class="p">),</span> <span class="n">Ctx</span><span class="p">)))</span>
  <span class="k">return</span> <span class="n">Err</span><span class="p">;</span>

<span class="c1">// Look up the JIT&#39;d code entry point.</span>
<span class="k">auto</span> <span class="n">EntrySym</span> <span class="o">=</span> <span class="n">JIT</span><span class="o">-&gt;</span><span class="n">lookup</span><span class="p">(</span><span class="s">&quot;entry&quot;</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">EntrySym</span><span class="p">)</span>
  <span class="k">return</span> <span class="n">EntrySym</span><span class="p">.</span><span class="n">takeError</span><span class="p">();</span>

<span class="c1">// Cast the entry point address to a function pointer.</span>
<span class="k">auto</span> <span class="o">*</span><span class="n">Entry</span> <span class="o">=</span> <span class="p">(</span><span class="kt">void</span><span class="p">(</span><span class="o">*</span><span class="p">)())</span><span class="n">EntrySym</span><span class="p">.</span><span class="n">getAddress</span><span class="p">();</span>

<span class="c1">// Call into JIT&#39;d code.</span>
<span class="n">Entry</span><span class="p">();</span>
</pre></div>
</div>
<p>The builder classes provide a number of configuration options that can be
specified before the JIT instance is constructed. For example:</p>
<div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="c1">// Build an LLLazyJIT instance that uses four worker threads for compilation,</span>
<span class="c1">// and jumps to a specific error handler (rather than null) on lazy compile</span>
<span class="c1">// failures.</span>

<span class="kt">void</span> <span class="nf">handleLazyCompileFailure</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// JIT&#39;d code will jump here if lazy compilation fails, giving us an</span>
  <span class="c1">// opportunity to exit or throw an exception into JIT&#39;d code.</span>
  <span class="k">throw</span> <span class="n">JITFailed</span><span class="p">();</span>
<span class="p">}</span>

<span class="k">auto</span> <span class="n">JIT</span> <span class="o">=</span> <span class="n">LLLazyJITBuilder</span><span class="p">()</span>
             <span class="p">.</span><span class="n">setNumCompileThreads</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
             <span class="p">.</span><span class="n">setLazyCompileFailureAddr</span><span class="p">(</span>
                 <span class="n">toJITTargetAddress</span><span class="p">(</span><span class="o">&amp;</span><span class="n">handleLazyCompileFailure</span><span class="p">))</span>
             <span class="p">.</span><span class="n">create</span><span class="p">();</span>

<span class="c1">// ...</span>
</pre></div>
</div>
<p>For users wanting to get started with LLJIT a minimal example program can be
found at <code class="docutils literal notranslate"><span class="pre">llvm/examples/HowToUseLLJIT</span></code>.</p>
</div>
<div class="section" id="design-overview">
<h2><a class="toc-backref" href="#id12">Design Overview</a><a class="headerlink" href="#design-overview" title="Permalink to this headline">¶</a></h2>
<p>ORC’s JIT program model aims to emulate the linking and symbol resolution
rules used by the static and dynamic linkers. This allows ORC to JIT
arbitrary LLVM IR, including IR produced by an ordinary static compiler (e.g.
clang) that uses constructs like symbol linkage and visibility, and weak <a class="footnote-reference brackets" href="#id7" id="id2">3</a>
and common symbol definitions.</p>
<p>To see how this works, imagine a program <code class="docutils literal notranslate"><span class="pre">foo</span></code> which links against a pair
of dynamic libraries: <code class="docutils literal notranslate"><span class="pre">libA</span></code> and <code class="docutils literal notranslate"><span class="pre">libB</span></code>. On the command line, building this
program might look like:</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span>$ clang++ -shared -o libA.dylib a1.cpp a2.cpp
$ clang++ -shared -o libB.dylib b1.cpp b2.cpp
$ clang++ -o myapp myapp.cpp -L. -lA -lB
$ ./myapp
</pre></div>
</div>
<p>In ORC, this would translate into API calls on a hypothetical CXXCompilingLayer
(with error checking omitted for brevity) as:</p>
<div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="n">ExecutionSession</span> <span class="n">ES</span><span class="p">;</span>
<span class="n">RTDyldObjectLinkingLayer</span> <span class="nf">ObjLinkingLayer</span><span class="p">(</span>
    <span class="n">ES</span><span class="p">,</span> <span class="p">[]()</span> <span class="p">{</span> <span class="k">return</span> <span class="n">std</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">SectionMemoryManager</span><span class="o">&gt;</span><span class="p">();</span> <span class="p">});</span>
<span class="n">CXXCompileLayer</span> <span class="nf">CXXLayer</span><span class="p">(</span><span class="n">ES</span><span class="p">,</span> <span class="n">ObjLinkingLayer</span><span class="p">);</span>

<span class="c1">// Create JITDylib &quot;A&quot; and add code to it using the CXX layer.</span>
<span class="k">auto</span> <span class="o">&amp;</span><span class="n">LibA</span> <span class="o">=</span> <span class="n">ES</span><span class="p">.</span><span class="n">createJITDylib</span><span class="p">(</span><span class="s">&quot;A&quot;</span><span class="p">);</span>
<span class="n">CXXLayer</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">LibA</span><span class="p">,</span> <span class="n">MemoryBuffer</span><span class="o">::</span><span class="n">getFile</span><span class="p">(</span><span class="s">&quot;a1.cpp&quot;</span><span class="p">));</span>
<span class="n">CXXLayer</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">LibA</span><span class="p">,</span> <span class="n">MemoryBuffer</span><span class="o">::</span><span class="n">getFile</span><span class="p">(</span><span class="s">&quot;a2.cpp&quot;</span><span class="p">));</span>

<span class="c1">// Create JITDylib &quot;B&quot; and add code to it using the CXX layer.</span>
<span class="k">auto</span> <span class="o">&amp;</span><span class="n">LibB</span> <span class="o">=</span> <span class="n">ES</span><span class="p">.</span><span class="n">createJITDylib</span><span class="p">(</span><span class="s">&quot;B&quot;</span><span class="p">);</span>
<span class="n">CXXLayer</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">LibB</span><span class="p">,</span> <span class="n">MemoryBuffer</span><span class="o">::</span><span class="n">getFile</span><span class="p">(</span><span class="s">&quot;b1.cpp&quot;</span><span class="p">));</span>
<span class="n">CXXLayer</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">LibB</span><span class="p">,</span> <span class="n">MemoryBuffer</span><span class="o">::</span><span class="n">getFile</span><span class="p">(</span><span class="s">&quot;b2.cpp&quot;</span><span class="p">));</span>

<span class="c1">// Create and specify the search order for the main JITDylib. This is</span>
<span class="c1">// equivalent to a &quot;links against&quot; relationship in a command-line link.</span>
<span class="k">auto</span> <span class="o">&amp;</span><span class="n">MainJD</span> <span class="o">=</span> <span class="n">ES</span><span class="p">.</span><span class="n">createJITDylib</span><span class="p">(</span><span class="s">&quot;main&quot;</span><span class="p">);</span>
<span class="n">MainJD</span><span class="p">.</span><span class="n">addToLinkOrder</span><span class="p">(</span><span class="o">&amp;</span><span class="n">LibA</span><span class="p">);</span>
<span class="n">MainJD</span><span class="p">.</span><span class="n">addToLinkOrder</span><span class="p">(</span><span class="o">&amp;</span><span class="n">LibB</span><span class="p">);</span>
<span class="n">CXXLayer</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">MainJD</span><span class="p">,</span> <span class="n">MemoryBuffer</span><span class="o">::</span><span class="n">getFile</span><span class="p">(</span><span class="s">&quot;main.cpp&quot;</span><span class="p">));</span>

<span class="c1">// Look up the JIT&#39;d main, cast it to a function pointer, then call it.</span>
<span class="k">auto</span> <span class="n">MainSym</span> <span class="o">=</span> <span class="n">ExitOnErr</span><span class="p">(</span><span class="n">ES</span><span class="p">.</span><span class="n">lookup</span><span class="p">({</span><span class="o">&amp;</span><span class="n">MainJD</span><span class="p">},</span> <span class="s">&quot;main&quot;</span><span class="p">));</span>
<span class="k">auto</span> <span class="o">*</span><span class="n">Main</span> <span class="o">=</span> <span class="p">(</span><span class="kt">int</span><span class="p">(</span><span class="o">*</span><span class="p">)(</span><span class="kt">int</span><span class="p">,</span> <span class="kt">char</span><span class="o">*</span><span class="p">[]))</span><span class="n">MainSym</span><span class="p">.</span><span class="n">getAddress</span><span class="p">();</span>

<span class="kt">int</span> <span class="n">Result</span> <span class="o">=</span> <span class="n">Main</span><span class="p">(...);</span>
</pre></div>
</div>
<p>This example tells us nothing about <em>how</em> or <em>when</em> compilation will happen.
That will depend on the implementation of the hypothetical CXXCompilingLayer.
The same linker-based symbol resolution rules will apply regardless of that
implementation, however. For example, if a1.cpp and a2.cpp both define a
function “foo” then ORCv2 will generate a duplicate definition error. On the
other hand, if a1.cpp and b1.cpp both define “foo” there is no error (different
dynamic libraries may define the same symbol). If main.cpp refers to “foo”, it
should bind to the definition in LibA rather than the one in LibB, since
main.cpp is part of the “main” dylib, and the main dylib links against LibA
before LibB.</p>
<p>Many JIT clients will have no need for this strict adherence to the usual
ahead-of-time linking rules, and should be able to get by just fine by putting
all of their code in a single JITDylib. However, clients who want to JIT code
for languages/projects that traditionally rely on ahead-of-time linking (e.g.
C++) will find that this feature makes life much easier.</p>
<p>Symbol lookup in ORC serves two other important functions, beyond providing
addresses for symbols: (1) It triggers compilation of the symbol(s) searched for
(if they have not been compiled already), and (2) it provides the
synchronization mechanism for concurrent compilation. The pseudo-code for the
lookup process is:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>construct a query object from a query set and query handler
lock the session
lodge query against requested symbols, collect required materializers (if any)
unlock the session
dispatch materializers (if any)
</pre></div>
</div>
<p>In this context a materializer is something that provides a working definition
of a symbol upon request. Usually materializers are just wrappers for compilers,
but they may also wrap a jit-linker directly (if the program representation
backing the definitions is an object file), or may even be a class that writes
bits directly into memory (for example, if the definitions are
stubs). Materialization is the blanket term for any actions (compiling, linking,
splatting bits, registering with runtimes, etc.) that are required to generate a
symbol definition that is safe to call or access.</p>
<p>As each materializer completes its work it notifies the JITDylib, which in turn
notifies any query objects that are waiting on the newly materialized
definitions. Each query object maintains a count of the number of symbols that
it is still waiting on, and once this count reaches zero the query object calls
the query handler with a <em>SymbolMap</em> (a map of symbol names to addresses)
describing the result. If any symbol fails to materialize the query immediately
calls the query handler with an error.</p>
<p>The collected materialization units are sent to the ExecutionSession to be
dispatched, and the dispatch behavior can be set by the client. By default each
materializer is run on the calling thread. Clients are free to create new
threads to run materializers, or to send the work to a work queue for a thread
pool (this is what LLJIT/LLLazyJIT do).</p>
</div>
<div class="section" id="top-level-apis">
<h2><a class="toc-backref" href="#id13">Top Level APIs</a><a class="headerlink" href="#top-level-apis" title="Permalink to this headline">¶</a></h2>
<p>Many of ORC’s top-level APIs are visible in the example above:</p>
<ul class="simple">
<li><p><em>ExecutionSession</em> represents the JIT’d program and provides context for the
JIT: It contains the JITDylibs, error reporting mechanisms, and dispatches the
materializers.</p></li>
<li><p><em>JITDylibs</em> provide the symbol tables.</p></li>
<li><p><em>Layers</em> (ObjLinkingLayer and CXXLayer) are wrappers around compilers and
allow clients to add uncompiled program representations supported by those
compilers to JITDylibs.</p></li>
</ul>
<p>Several other important APIs are used explicitly. JIT clients need not be aware
of them, but Layer authors will use them:</p>
<ul class="simple">
<li><p><em>MaterializationUnit</em> - When XXXLayer::add is invoked it wraps the given
program representation (in this example, C++ source) in a MaterializationUnit,
which is then stored in the JITDylib. MaterializationUnits are responsible for
describing the definitions they provide, and for unwrapping the program
representation and passing it back to the layer when compilation is required
(this ownership shuffle makes writing thread-safe layers easier, since the
ownership of the program representation will be passed back on the stack,
rather than having to be fished out of a Layer member, which would require
synchronization).</p></li>
<li><p><em>MaterializationResponsibility</em> - When a MaterializationUnit hands a program
representation back to the layer it comes with an associated
MaterializationResponsibility object. This object tracks the definitions
that must be materialized and provides a way to notify the JITDylib once they
are either successfully materialized or a failure occurs.</p></li>
</ul>
</div>
<div class="section" id="absolute-symbols-aliases-and-reexports">
<h2><a class="toc-backref" href="#id14">Absolute Symbols, Aliases, and Reexports</a><a class="headerlink" href="#absolute-symbols-aliases-and-reexports" title="Permalink to this headline">¶</a></h2>
<p>ORC makes it easy to define symbols with absolute addresses, or symbols that
are simply aliases of other symbols:</p>
<div class="section" id="absolute-symbols">
<h3><a class="toc-backref" href="#id15">Absolute Symbols</a><a class="headerlink" href="#absolute-symbols" title="Permalink to this headline">¶</a></h3>
<p>Absolute symbols are symbols that map directly to addresses without requiring
further materialization, for example: “foo” = 0x1234. One use case for
absolute symbols is allowing resolution of process symbols. E.g.</p>
<p>With this mapping established code added to the JIT can refer to printf
symbolically rather than requiring the address of printf to be “baked in”.
This in turn allows cached versions of the JIT’d code (e.g. compiled objects)
to be re-used across JIT sessions as the JIT’d code no longer changes, only the
absolute symbol definition does.</p>
<p>For process and library symbols the DynamicLibrarySearchGenerator utility (See
<a class="reference internal" href="#processandlibrarysymbols"><span class="std std-ref">How to Add Process and Library Symbols to JITDylibs</span></a>) can be used to automatically build absolute
symbol mappings for you. However the absoluteSymbols function is still useful
for making non-global objects in your JIT visible to JIT’d code. For example,
imagine that your JIT standard library needs access to your JIT object to make
some calls. We could bake the address of your object into the library, but then
it would need to be recompiled for each session:</p>
<p>We can turn this into a symbolic reference in the JIT standard library:</p>
<p>And then make our JIT object visible to the JIT standard library with an
absolute symbol definition when the JIT is started:</p>
</div>
<div class="section" id="aliases-and-reexports">
<h3><a class="toc-backref" href="#id16">Aliases and Reexports</a><a class="headerlink" href="#aliases-and-reexports" title="Permalink to this headline">¶</a></h3>
<p>Aliases and reexports allow you to define new symbols that map to existing
symbols. This can be useful for changing linkage relationships between symbols
across sessions without having to recompile code. For example, imagine that
JIT’d code has access to a log function, <code class="docutils literal notranslate"><span class="pre">void</span> <span class="pre">log(const</span> <span class="pre">char*)</span></code> for which
there are two implementations in the JIT standard library: <code class="docutils literal notranslate"><span class="pre">log_fast</span></code> and
<code class="docutils literal notranslate"><span class="pre">log_detailed</span></code>. Your JIT can choose which one of these definitions will be
used when the <code class="docutils literal notranslate"><span class="pre">log</span></code> symbol is referenced by setting up an alias at JIT startup
time:</p>
<p>The <code class="docutils literal notranslate"><span class="pre">symbolAliases</span></code> function allows you to define aliases within a single
JITDylib. The <code class="docutils literal notranslate"><span class="pre">reexports</span></code> function provides the same functionality, but
operates across JITDylib boundaries. E.g.</p>
<p>The reexports utility can be handy for composing a single JITDylib interface by
re-exporting symbols from several other JITDylibs.</p>
</div>
</div>
<div class="section" id="laziness">
<span id="id3"></span><h2><a class="toc-backref" href="#id17">Laziness</a><a class="headerlink" href="#laziness" title="Permalink to this headline">¶</a></h2>
<p>Laziness in ORC is provided by a utility called “lazy reexports”. A lazy
reexport is similar to a regular reexport or alias: It provides a new name for
an existing symbol. Unlike regular reexports however, lookups of lazy reexports
do not trigger immediate materialization of the reexported symbol. Instead, they
only trigger materialization of a function stub. This function stub is
initialized to point at a <em>lazy call-through</em>, which provides reentry into the
JIT. If the stub is called at runtime then the lazy call-through will look up
the reexported symbol (triggering materialization for it if necessary), update
the stub (to call directly to the reexported symbol on subsequent calls), and
then return via the reexported symbol. By re-using the existing symbol lookup
mechanism, lazy reexports inherit the same concurrency guarantees: calls to lazy
reexports can be made from multiple threads concurrently, and the reexported
symbol can be any state of compilation (uncompiled, already in the process of
being compiled, or already compiled) and the call will succeed. This allows
laziness to be safely mixed with features like remote compilation, concurrent
compilation, concurrent JIT’d code, and speculative compilation.</p>
<p>There is one other key difference between regular reexports and lazy reexports
that some clients must be aware of: The address of a lazy reexport will be
<em>different</em> from the address of the reexported symbol (whereas a regular
reexport is guaranteed to have the same address as the reexported symbol).
Clients who care about pointer equality will generally want to use the address
of the reexport as the canonical address of the reexported symbol. This will
allow the address to be taken without forcing materialization of the reexport.</p>
<p>Usage example:</p>
<p>If JITDylib <code class="docutils literal notranslate"><span class="pre">JD</span></code> contains definitions for symbols <code class="docutils literal notranslate"><span class="pre">foo_body</span></code> and
<code class="docutils literal notranslate"><span class="pre">bar_body</span></code>, we can create lazy entry points <code class="docutils literal notranslate"><span class="pre">Foo</span></code> and <code class="docutils literal notranslate"><span class="pre">Bar</span></code> in JITDylib
<code class="docutils literal notranslate"><span class="pre">JD2</span></code> by calling:</p>
<div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="k">auto</span> <span class="n">ReexportFlags</span> <span class="o">=</span> <span class="n">JITSymbolFlags</span><span class="o">::</span><span class="n">Exported</span> <span class="o">|</span> <span class="n">JITSymbolFlags</span><span class="o">::</span><span class="n">Callable</span><span class="p">;</span>
<span class="n">JD2</span><span class="p">.</span><span class="n">define</span><span class="p">(</span>
  <span class="n">lazyReexports</span><span class="p">(</span><span class="n">CallThroughMgr</span><span class="p">,</span> <span class="n">StubsMgr</span><span class="p">,</span> <span class="n">JD</span><span class="p">,</span>
                <span class="n">SymbolAliasMap</span><span class="p">({</span>
                  <span class="p">{</span> <span class="n">Mangle</span><span class="p">(</span><span class="s">&quot;foo&quot;</span><span class="p">),</span> <span class="p">{</span> <span class="n">Mangle</span><span class="p">(</span><span class="s">&quot;foo_body&quot;</span><span class="p">),</span> <span class="n">ReexportedFlags</span> <span class="p">}</span> <span class="p">},</span>
                  <span class="p">{</span> <span class="n">Mangle</span><span class="p">(</span><span class="s">&quot;bar&quot;</span><span class="p">),</span> <span class="p">{</span> <span class="n">Mangle</span><span class="p">(</span><span class="s">&quot;bar_body&quot;</span><span class="p">),</span> <span class="n">ReexportedFlags</span> <span class="p">}</span> <span class="p">}</span>
                <span class="p">}));</span>
</pre></div>
</div>
<p>A full example of how to use lazyReexports with the LLJIT class can be found at
<code class="docutils literal notranslate"><span class="pre">llvm_project/llvm/examples/LLJITExamples/LLJITWithLazyReexports</span></code>.</p>
</div>
<div class="section" id="supporting-custom-compilers">
<h2><a class="toc-backref" href="#id18">Supporting Custom Compilers</a><a class="headerlink" href="#supporting-custom-compilers" title="Permalink to this headline">¶</a></h2>
<p>TBD.</p>
</div>
<div class="section" id="transitioning-from-orcv1-to-orcv2">
<span id="transitioning-orcv1-to-orcv2"></span><h2><a class="toc-backref" href="#id19">Transitioning from ORCv1 to ORCv2</a><a class="headerlink" href="#transitioning-from-orcv1-to-orcv2" title="Permalink to this headline">¶</a></h2>
<p>Since LLVM 7.0, new ORC development work has focused on adding support for
concurrent JIT compilation. The new APIs (including new layer interfaces and
implementations, and new utilities) that support concurrency are collectively
referred to as ORCv2, and the original, non-concurrent layers and utilities
are now referred to as ORCv1.</p>
<p>The majority of the ORCv1 layers and utilities were renamed with a ‘Legacy’
prefix in LLVM 8.0, and have deprecation warnings attached in LLVM 9.0. In LLVM
12.0 ORCv1 will be removed entirely.</p>
<p>Transitioning from ORCv1 to ORCv2 should be easy for most clients. Most of the
ORCv1 layers and utilities have ORCv2 counterparts <a class="footnote-reference brackets" href="#id6" id="id4">2</a> that can be directly
substituted. However there are some design differences between ORCv1 and ORCv2
to be aware of:</p>
<blockquote>
<div><ol class="arabic">
<li><p>ORCv2 fully adopts the JIT-as-linker model that began with MCJIT. Modules
(and other program representations, e.g. Object Files)  are no longer added
directly to JIT classes or layers. Instead, they are added to <code class="docutils literal notranslate"><span class="pre">JITDylib</span></code>
instances <em>by</em> layers. The <code class="docutils literal notranslate"><span class="pre">JITDylib</span></code> determines <em>where</em> the definitions
reside, the layers determine <em>how</em> the definitions will be compiled.
Linkage relationships between <code class="docutils literal notranslate"><span class="pre">JITDylibs</span></code> determine how inter-module
references are resolved, and symbol resolvers are no longer used. See the
section <a class="reference internal" href="#design-overview">Design Overview</a> for more details.</p>
<p>Unless multiple JITDylibs are needed to model linkage relationships, ORCv1
clients should place all code in a single JITDylib.
MCJIT clients should use LLJIT (see <a class="reference internal" href="#lljit-and-lllazyjit">LLJIT and LLLazyJIT</a>), and can place
code in LLJIT’s default created main JITDylib (See
<code class="docutils literal notranslate"><span class="pre">LLJIT::getMainJITDylib()</span></code>).</p>
</li>
<li><p>All JIT stacks now need an <code class="docutils literal notranslate"><span class="pre">ExecutionSession</span></code> instance. ExecutionSession
manages the string pool, error reporting, synchronization, and symbol
lookup.</p></li>
<li><p>ORCv2 uses uniqued strings (<code class="docutils literal notranslate"><span class="pre">SymbolStringPtr</span></code> instances) rather than
string values in order to reduce memory overhead and improve lookup
performance. See the subsection <a class="reference internal" href="#how-to-manage-symbol-strings">How to manage symbol strings</a>.</p></li>
<li><p>IR layers require ThreadSafeModule instances, rather than
std::unique_ptr&lt;Module&gt;s. ThreadSafeModule is a wrapper that ensures that
Modules that use the same LLVMContext are not accessed concurrently.
See <a class="reference internal" href="#how-to-use-threadsafemodule-and-threadsafecontext">How to use ThreadSafeModule and ThreadSafeContext</a>.</p></li>
<li><p>Symbol lookup is no longer handled by layers. Instead, there is a
<code class="docutils literal notranslate"><span class="pre">lookup</span></code> method on JITDylib that takes a list of JITDylibs to scan.</p>
<div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="n">ExecutionSession</span> <span class="n">ES</span><span class="p">;</span>
<span class="n">JITDylib</span> <span class="o">&amp;</span><span class="n">JD1</span> <span class="o">=</span> <span class="p">...;</span>
<span class="n">JITDylib</span> <span class="o">&amp;</span><span class="n">JD2</span> <span class="o">=</span> <span class="p">...;</span>

<span class="k">auto</span> <span class="n">Sym</span> <span class="o">=</span> <span class="n">ES</span><span class="p">.</span><span class="n">lookup</span><span class="p">({</span><span class="o">&amp;</span><span class="n">JD1</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">JD2</span><span class="p">},</span> <span class="n">ES</span><span class="p">.</span><span class="n">intern</span><span class="p">(</span><span class="s">&quot;_main&quot;</span><span class="p">));</span>
</pre></div>
</div>
</li>
<li><p>Module removal is not yet supported. There is no equivalent of the
layer concept removeModule/removeObject methods. Work on resource tracking
and removal in ORCv2 is ongoing.</p></li>
</ol>
</div></blockquote>
<p>For code examples and suggestions of how to use the ORCv2 APIs, please see
the section <a class="reference internal" href="#how-tos">How-tos</a>.</p>
</div>
<div class="section" id="how-tos">
<h2><a class="toc-backref" href="#id20">How-tos</a><a class="headerlink" href="#how-tos" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-to-manage-symbol-strings">
<h3><a class="toc-backref" href="#id21">How to manage symbol strings</a><a class="headerlink" href="#how-to-manage-symbol-strings" title="Permalink to this headline">¶</a></h3>
<p>Symbol strings in ORC are uniqued to improve lookup performance, reduce memory
overhead, and allow symbol names to function as efficient keys. To get the
unique <code class="docutils literal notranslate"><span class="pre">SymbolStringPtr</span></code> for a string value, call the
<code class="docutils literal notranslate"><span class="pre">ExecutionSession::intern</span></code> method:</p>
<blockquote>
<div><div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="n">ExecutionSession</span> <span class="n">ES</span><span class="p">;</span>
<span class="c1">/// ...</span>
<span class="k">auto</span> <span class="n">MainSymbolName</span> <span class="o">=</span> <span class="n">ES</span><span class="p">.</span><span class="n">intern</span><span class="p">(</span><span class="s">&quot;main&quot;</span><span class="p">);</span>
</pre></div>
</div>
</div></blockquote>
<p>If you wish to perform lookup using the C/IR name of a symbol you will also
need to apply the platform linker-mangling before interning the string. On
Linux this mangling is a no-op, but on other platforms it usually involves
adding a prefix to the string (e.g. ‘_’ on Darwin). The mangling scheme is
based on the DataLayout for the target. Given a DataLayout and an
ExecutionSession, you can create a MangleAndInterner function object that
will perform both jobs for you:</p>
<blockquote>
<div><div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="n">ExecutionSession</span> <span class="n">ES</span><span class="p">;</span>
<span class="k">const</span> <span class="n">DataLayout</span> <span class="o">&amp;</span><span class="n">DL</span> <span class="o">=</span> <span class="p">...;</span>
<span class="n">MangleAndInterner</span> <span class="nf">Mangle</span><span class="p">(</span><span class="n">ES</span><span class="p">,</span> <span class="n">DL</span><span class="p">);</span>

<span class="c1">// ...</span>

<span class="c1">// Portable IR-symbol-name lookup:</span>
<span class="k">auto</span> <span class="n">Sym</span> <span class="o">=</span> <span class="n">ES</span><span class="p">.</span><span class="n">lookup</span><span class="p">({</span><span class="o">&amp;</span><span class="n">MainJD</span><span class="p">},</span> <span class="n">Mangle</span><span class="p">(</span><span class="s">&quot;main&quot;</span><span class="p">));</span>
</pre></div>
</div>
</div></blockquote>
</div>
<div class="section" id="how-to-create-jitdylibs-and-set-up-linkage-relationships">
<h3><a class="toc-backref" href="#id22">How to create JITDylibs and set up linkage relationships</a><a class="headerlink" href="#how-to-create-jitdylibs-and-set-up-linkage-relationships" title="Permalink to this headline">¶</a></h3>
<p>In ORC, all symbol definitions reside in JITDylibs. JITDylibs are created by
calling the <code class="docutils literal notranslate"><span class="pre">ExecutionSession::createJITDylib</span></code> method with a unique name:</p>
<blockquote>
<div><div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="n">ExecutionSession</span> <span class="n">ES</span><span class="p">;</span>
<span class="k">auto</span> <span class="o">&amp;</span><span class="n">JD</span> <span class="o">=</span> <span class="n">ES</span><span class="p">.</span><span class="n">createJITDylib</span><span class="p">(</span><span class="s">&quot;libFoo.dylib&quot;</span><span class="p">);</span>
</pre></div>
</div>
</div></blockquote>
<p>The JITDylib is owned by the <code class="docutils literal notranslate"><span class="pre">ExecutionEngine</span></code> instance and will be freed
when it is destroyed.</p>
</div>
<div class="section" id="how-to-use-threadsafemodule-and-threadsafecontext">
<h3><a class="toc-backref" href="#id23">How to use ThreadSafeModule and ThreadSafeContext</a><a class="headerlink" href="#how-to-use-threadsafemodule-and-threadsafecontext" title="Permalink to this headline">¶</a></h3>
<p>ThreadSafeModule and ThreadSafeContext are wrappers around Modules and
LLVMContexts respectively. A ThreadSafeModule is a pair of a
std::unique_ptr&lt;Module&gt; and a (possibly shared) ThreadSafeContext value. A
ThreadSafeContext is a pair of a std::unique_ptr&lt;LLVMContext&gt; and a lock.
This design serves two purposes: providing a locking scheme and lifetime
management for LLVMContexts. The ThreadSafeContext may be locked to prevent
accidental concurrent access by two Modules that use the same LLVMContext.
The underlying LLVMContext is freed once all ThreadSafeContext values pointing
to it are destroyed, allowing the context memory to be reclaimed as soon as
the Modules referring to it are destroyed.</p>
<p>ThreadSafeContexts can be explicitly constructed from a
std::unique_ptr&lt;LLVMContext&gt;:</p>
<blockquote>
<div><div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="n">ThreadSafeContext</span> <span class="nf">TSCtx</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">LLVMContext</span><span class="o">&gt;</span><span class="p">());</span>
</pre></div>
</div>
</div></blockquote>
<p>ThreadSafeModules can be constructed from a pair of a std::unique_ptr&lt;Module&gt;
and a ThreadSafeContext value. ThreadSafeContext values may be shared between
multiple ThreadSafeModules:</p>
<blockquote>
<div><div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="n">ThreadSafeModule</span> <span class="nf">TSM1</span><span class="p">(</span>
  <span class="n">std</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">Module</span><span class="o">&gt;</span><span class="p">(</span><span class="s">&quot;M1&quot;</span><span class="p">,</span> <span class="o">*</span><span class="n">TSCtx</span><span class="p">.</span><span class="n">getContext</span><span class="p">()),</span> <span class="n">TSCtx</span><span class="p">);</span>

<span class="n">ThreadSafeModule</span> <span class="nf">TSM2</span><span class="p">(</span>
  <span class="n">std</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">Module</span><span class="o">&gt;</span><span class="p">(</span><span class="s">&quot;M2&quot;</span><span class="p">,</span> <span class="o">*</span><span class="n">TSCtx</span><span class="p">.</span><span class="n">getContext</span><span class="p">()),</span> <span class="n">TSCtx</span><span class="p">);</span>
</pre></div>
</div>
</div></blockquote>
<p>Before using a ThreadSafeContext, clients should ensure that either the context
is only accessible on the current thread, or that the context is locked. In the
example above (where the context is never locked) we rely on the fact that both
<code class="docutils literal notranslate"><span class="pre">TSM1</span></code> and <code class="docutils literal notranslate"><span class="pre">TSM2</span></code>, and TSCtx are all created on one thread. If a context is
going to be shared between threads then it must be locked before any accessing
or creating any Modules attached to it. E.g.</p>
<blockquote>
<div><div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="n">ThreadSafeContext</span> <span class="nf">TSCtx</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">LLVMContext</span><span class="o">&gt;</span><span class="p">());</span>

<span class="n">ThreadPool</span> <span class="nf">TP</span><span class="p">(</span><span class="n">NumThreads</span><span class="p">);</span>
<span class="n">JITStack</span> <span class="n">J</span><span class="p">;</span>

<span class="k">for</span> <span class="p">(</span><span class="k">auto</span> <span class="o">&amp;</span><span class="nl">ModulePath</span> <span class="p">:</span> <span class="n">ModulePaths</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">TP</span><span class="p">.</span><span class="n">async</span><span class="p">(</span>
    <span class="p">[</span><span class="o">&amp;</span><span class="p">]()</span> <span class="p">{</span>
      <span class="k">auto</span> <span class="n">Lock</span> <span class="o">=</span> <span class="n">TSCtx</span><span class="p">.</span><span class="n">getLock</span><span class="p">();</span>
      <span class="k">auto</span> <span class="n">M</span> <span class="o">=</span> <span class="n">loadModuleOnContext</span><span class="p">(</span><span class="n">ModulePath</span><span class="p">,</span> <span class="n">TSCtx</span><span class="p">.</span><span class="n">getContext</span><span class="p">());</span>
      <span class="n">J</span><span class="p">.</span><span class="n">addModule</span><span class="p">(</span><span class="n">ThreadSafeModule</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">M</span><span class="p">),</span> <span class="n">TSCtx</span><span class="p">));</span>
    <span class="p">});</span>
<span class="p">}</span>

<span class="n">TP</span><span class="p">.</span><span class="n">wait</span><span class="p">();</span>
</pre></div>
</div>
</div></blockquote>
<p>To make exclusive access to Modules easier to manage the ThreadSafeModule class
provides a convenience function, <code class="docutils literal notranslate"><span class="pre">withModuleDo</span></code>, that implicitly (1) locks the
associated context, (2) runs a given function object, (3) unlocks the context,
and (3) returns the result generated by the function object. E.g.</p>
<blockquote>
<div><div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="n">ThreadSafeModule</span> <span class="n">TSM</span> <span class="o">=</span> <span class="n">getModule</span><span class="p">(...);</span>

<span class="c1">// Dump the module:</span>
<span class="kt">size_t</span> <span class="n">NumFunctionsInModule</span> <span class="o">=</span>
  <span class="n">TSM</span><span class="p">.</span><span class="n">withModuleDo</span><span class="p">(</span>
    <span class="p">[](</span><span class="n">Module</span> <span class="o">&amp;</span><span class="n">M</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// &lt;- Context locked before entering lambda.</span>
      <span class="k">return</span> <span class="n">M</span><span class="p">.</span><span class="n">size</span><span class="p">();</span>
    <span class="p">}</span> <span class="c1">// &lt;- Context unlocked after leaving.</span>
  <span class="p">);</span>
</pre></div>
</div>
</div></blockquote>
<p>Clients wishing to maximize possibilities for concurrent compilation will want
to create every new ThreadSafeModule on a new ThreadSafeContext. For this
reason a convenience constructor for ThreadSafeModule is provided that implicitly
constructs a new ThreadSafeContext value from a std::unique_ptr&lt;LLVMContext&gt;:</p>
<blockquote>
<div><div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="c1">// Maximize concurrency opportunities by loading every module on a</span>
<span class="c1">// separate context.</span>
<span class="k">for</span> <span class="p">(</span><span class="k">const</span> <span class="k">auto</span> <span class="o">&amp;</span><span class="nl">IRPath</span> <span class="p">:</span> <span class="n">IRPaths</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">auto</span> <span class="n">Ctx</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">LLVMContext</span><span class="o">&gt;</span><span class="p">();</span>
  <span class="k">auto</span> <span class="n">M</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">LLVMContext</span><span class="o">&gt;</span><span class="p">(</span><span class="s">&quot;M&quot;</span><span class="p">,</span> <span class="o">*</span><span class="n">Ctx</span><span class="p">);</span>
  <span class="n">CompileLayer</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">MainJD</span><span class="p">,</span> <span class="n">ThreadSafeModule</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">M</span><span class="p">),</span> <span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">Ctx</span><span class="p">)));</span>
<span class="p">}</span>
</pre></div>
</div>
</div></blockquote>
<p>Clients who plan to run single-threaded may choose to save memory by loading
all modules on the same context:</p>
<blockquote>
<div><div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="c1">// Save memory by using one context for all Modules:</span>
<span class="n">ThreadSafeContext</span> <span class="nf">TSCtx</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">LLVMContext</span><span class="o">&gt;</span><span class="p">());</span>
<span class="k">for</span> <span class="p">(</span><span class="k">const</span> <span class="k">auto</span> <span class="o">&amp;</span><span class="nl">IRPath</span> <span class="p">:</span> <span class="n">IRPaths</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">ThreadSafeModule</span> <span class="nf">TSM</span><span class="p">(</span><span class="n">parsePath</span><span class="p">(</span><span class="n">IRPath</span><span class="p">,</span> <span class="o">*</span><span class="n">TSCtx</span><span class="p">.</span><span class="n">getContext</span><span class="p">()),</span> <span class="n">TSCtx</span><span class="p">);</span>
  <span class="n">CompileLayer</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">MainJD</span><span class="p">,</span> <span class="n">ThreadSafeModule</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">TSM</span><span class="p">));</span>
<span class="p">}</span>
</pre></div>
</div>
</div></blockquote>
</div>
</div>
<div class="section" id="how-to-add-process-and-library-symbols-to-the-jitdylibs">
<span id="processandlibrarysymbols"></span><h2><a class="toc-backref" href="#id24">How to Add Process and Library Symbols to the JITDylibs</a><a class="headerlink" href="#how-to-add-process-and-library-symbols-to-the-jitdylibs" title="Permalink to this headline">¶</a></h2>
<p>JIT’d code typically needs access to symbols in the host program or in
supporting libraries. References to process symbols can be “baked in” to code
as it is compiled by turning external references into pre-resolved integer
constants, however this ties the JIT’d code to the current process’s virtual
memory layout (meaning that it can not be cached between runs) and makes
debugging lower level program representations difficult (as all external
references are opaque integer values). A bettor solution is to maintain symbolic
external references and let the jit-linker bind them for you at runtime. To
allow the JIT linker to find these external definitions their addresses must
be added to a JITDylib that the JIT’d definitions link against.</p>
<p>Adding definitions for external symbols could be done using the absoluteSymbols
function:</p>
<blockquote>
<div><div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="k">const</span> <span class="n">DataLayout</span> <span class="o">&amp;</span><span class="n">DL</span> <span class="o">=</span> <span class="n">getDataLayout</span><span class="p">();</span>
<span class="n">MangleAndInterner</span> <span class="nf">Mangle</span><span class="p">(</span><span class="n">ES</span><span class="p">,</span> <span class="n">DL</span><span class="p">);</span>

<span class="k">auto</span> <span class="o">&amp;</span><span class="n">JD</span> <span class="o">=</span> <span class="n">ES</span><span class="p">.</span><span class="n">createJITDylib</span><span class="p">(</span><span class="s">&quot;main&quot;</span><span class="p">);</span>

<span class="n">JD</span><span class="p">.</span><span class="n">define</span><span class="p">(</span>
  <span class="n">absoluteSymbols</span><span class="p">({</span>
    <span class="p">{</span> <span class="n">Mangle</span><span class="p">(</span><span class="s">&quot;puts&quot;</span><span class="p">),</span> <span class="n">pointerToJITTargetAddress</span><span class="p">(</span><span class="o">&amp;</span><span class="n">puts</span><span class="p">)},</span>
    <span class="p">{</span> <span class="n">Mangle</span><span class="p">(</span><span class="s">&quot;gets&quot;</span><span class="p">),</span> <span class="n">pointerToJITTargetAddress</span><span class="p">(</span><span class="o">&amp;</span><span class="n">getS</span><span class="p">)}</span>
  <span class="p">}));</span>
</pre></div>
</div>
</div></blockquote>
<p>Manually adding absolute symbols for a large or changing interface is cumbersome
however, so ORC provides an alternative to generate new definitions on demand:
<em>definition generators</em>. If a definition generator is attached to a JITDylib,
then any unsuccessful lookup on that JITDylib will fall back to calling the
definition generator, and the definition generator may choose to generate a new
definition for the missing symbols. Of particular use here is the
<code class="docutils literal notranslate"><span class="pre">DynamicLibrarySearchGenerator</span></code> utility. This can be used to reflect the whole
exported symbol set of the process or a specific dynamic library, or a subset
of either of these determined by a predicate.</p>
<p>For example, to load the whole interface of a runtime library:</p>
<blockquote>
<div><div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="k">const</span> <span class="n">DataLayout</span> <span class="o">&amp;</span><span class="n">DL</span> <span class="o">=</span> <span class="n">getDataLayout</span><span class="p">();</span>
<span class="k">auto</span> <span class="o">&amp;</span><span class="n">JD</span> <span class="o">=</span> <span class="n">ES</span><span class="p">.</span><span class="n">createJITDylib</span><span class="p">(</span><span class="s">&quot;main&quot;</span><span class="p">);</span>

<span class="n">JD</span><span class="p">.</span><span class="n">addGenerator</span><span class="p">(</span><span class="n">DynamicLibrarySearchGenerator</span><span class="o">::</span><span class="n">Load</span><span class="p">(</span><span class="s">&quot;/path/to/lib&quot;</span>
                                                    <span class="n">DL</span><span class="p">.</span><span class="n">getGlobalPrefix</span><span class="p">()));</span>

<span class="c1">// IR added to JD can now link against all symbols exported by the library</span>
<span class="c1">// at &#39;/path/to/lib&#39;.</span>
<span class="n">CompileLayer</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">JD</span><span class="p">,</span> <span class="n">loadModule</span><span class="p">(...));</span>
</pre></div>
</div>
</div></blockquote>
<p>Or, to expose an allowed set of symbols from the main process:</p>
<blockquote>
<div><div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="k">const</span> <span class="n">DataLayout</span> <span class="o">&amp;</span><span class="n">DL</span> <span class="o">=</span> <span class="n">getDataLayout</span><span class="p">();</span>
<span class="n">MangleAndInterner</span> <span class="nf">Mangle</span><span class="p">(</span><span class="n">ES</span><span class="p">,</span> <span class="n">DL</span><span class="p">);</span>

<span class="k">auto</span> <span class="o">&amp;</span><span class="n">JD</span> <span class="o">=</span> <span class="n">ES</span><span class="p">.</span><span class="n">createJITDylib</span><span class="p">(</span><span class="s">&quot;main&quot;</span><span class="p">);</span>

<span class="n">DenseSet</span><span class="o">&lt;</span><span class="n">SymbolStringPtr</span><span class="o">&gt;</span> <span class="n">AllowList</span><span class="p">({</span>
    <span class="n">Mangle</span><span class="p">(</span><span class="s">&quot;puts&quot;</span><span class="p">),</span>
    <span class="n">Mangle</span><span class="p">(</span><span class="s">&quot;gets&quot;</span><span class="p">)</span>
  <span class="p">});</span>

<span class="c1">// Use GetForCurrentProcess with a predicate function that checks the</span>
<span class="c1">// allowed list.</span>
<span class="n">JD</span><span class="p">.</span><span class="n">addGenerator</span><span class="p">(</span>
  <span class="n">DynamicLibrarySearchGenerator</span><span class="o">::</span><span class="n">GetForCurrentProcess</span><span class="p">(</span>
    <span class="n">DL</span><span class="p">.</span><span class="n">getGlobalPrefix</span><span class="p">(),</span>
    <span class="p">[</span><span class="o">&amp;</span><span class="p">](</span><span class="k">const</span> <span class="n">SymbolStringPtr</span> <span class="o">&amp;</span><span class="n">S</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="n">AllowList</span><span class="p">.</span><span class="n">count</span><span class="p">(</span><span class="n">S</span><span class="p">);</span> <span class="p">}));</span>

<span class="c1">// IR added to JD can now link against any symbols exported by the process</span>
<span class="c1">// and contained in the list.</span>
<span class="n">CompileLayer</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">JD</span><span class="p">,</span> <span class="n">loadModule</span><span class="p">(...));</span>
</pre></div>
</div>
</div></blockquote>
</div>
<div class="section" id="roadmap">
<h2><a class="toc-backref" href="#id25">Roadmap</a><a class="headerlink" href="#roadmap" title="Permalink to this headline">¶</a></h2>
<p>ORC is still undergoing active development. Some current and future works are
listed below.</p>
<div class="section" id="current-work">
<h3><a class="toc-backref" href="#id26">Current Work</a><a class="headerlink" href="#current-work" title="Permalink to this headline">¶</a></h3>
<ol class="arabic">
<li><p><strong>TargetProcessControl: Improvements to in-tree support for out-of-process
execution</strong></p>
<p>The <code class="docutils literal notranslate"><span class="pre">TargetProcessControl</span></code> API provides various operations on the JIT
target process (the one which will execute the JIT’d code), including
memory allocation, memory writes, function execution, and process queries
(e.g. for the target triple). By targeting this API new components can be
developed which will work equally well for in-process and out-of-process
JITing.</p>
</li>
<li><p><strong>ORC RPC based TargetProcessControl implementation</strong></p>
<p>An ORC RPC based implementation of the <code class="docutils literal notranslate"><span class="pre">TargetProcessControl</span></code> API is
currently under development to enable easy out-of-process JITing via
file descriptors / sockets.</p>
</li>
<li><p><strong>Core State Machine Cleanup</strong></p>
<p>The core ORC state machine is currently implemented between JITDylib and
ExecutionSession. Methods are slowly being moved to <cite>ExecutionSession</cite>. This
will tidy up the code base, and also allow us to support asynchronous removal
of JITDylibs (in practice deleting an associated state object in
ExecutionSession and leaving the JITDylib instance in a defunct state until
all references to it have been released).</p>
</li>
</ol>
</div>
<div class="section" id="near-future-work">
<h3><a class="toc-backref" href="#id27">Near Future Work</a><a class="headerlink" href="#near-future-work" title="Permalink to this headline">¶</a></h3>
<ol class="arabic">
<li><p><strong>ORC JIT Runtime Libraries</strong></p>
<p>We need a runtime library for JIT’d code. This would include things like
TLS registration, reentry functions, registration code for language runtimes
(e.g. Objective C and Swift) and other JIT specific runtime code. This should
be built in a similar manner to compiler-rt (possibly even as part of it).</p>
</li>
<li><p><strong>Remote jit_dlopen / jit_dlclose</strong></p>
<p>To more fully mimic the environment that static programs operate in we would
like JIT’d code to be able to “dlopen” and “dlclose” JITDylibs, running all of
their initializers/deinitializers on the current thread. This would require
support from the runtime library described above.</p>
</li>
<li><p><strong>Debugging support</strong></p>
<p>ORC currently supports the GDBRegistrationListener API when using RuntimeDyld
as the underlying JIT linker. We will need a new solution for JITLink based
platforms.</p>
</li>
</ol>
</div>
<div class="section" id="further-future-work">
<h3><a class="toc-backref" href="#id28">Further Future Work</a><a class="headerlink" href="#further-future-work" title="Permalink to this headline">¶</a></h3>
<ol class="arabic">
<li><p><strong>Speculative Compilation</strong></p>
<p>ORC’s support for concurrent compilation allows us to easily enable
<em>speculative</em> JIT compilation: compilation of code that is not needed yet,
but which we have reason to believe will be needed in the future. This can be
used to hide compile latency and improve JIT throughput. A proof-of-concept
example of speculative compilation with ORC has already been developed (see
<code class="docutils literal notranslate"><span class="pre">llvm/examples/SpeculativeJIT</span></code>). Future work on this is likely to focus on
re-using and improving existing profiling support (currently used by PGO) to
feed speculation decisions, as well as built-in tools to simplify use of
speculative compilation.</p>
</li>
</ol>
<dl class="footnote brackets">
<dt class="label" id="id5"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
<dd><p>Formats/architectures vary in terms of supported features. MachO and
ELF tend to have better support than COFF. Patches very welcome!</p>
</dd>
<dt class="label" id="id6"><span class="brackets"><a class="fn-backref" href="#id4">2</a></span></dt>
<dd><p>The <code class="docutils literal notranslate"><span class="pre">LazyEmittingLayer</span></code>, <code class="docutils literal notranslate"><span class="pre">RemoteObjectClientLayer</span></code> and
<code class="docutils literal notranslate"><span class="pre">RemoteObjectServerLayer</span></code> do not have counterparts in the new
system. In the case of <code class="docutils literal notranslate"><span class="pre">LazyEmittingLayer</span></code> it was simply no longer
needed: in ORCv2, deferring compilation until symbols are looked up is
the default. The removal of <code class="docutils literal notranslate"><span class="pre">RemoteObjectClientLayer</span></code> and
<code class="docutils literal notranslate"><span class="pre">RemoteObjectServerLayer</span></code> means that JIT stacks can no longer be split
across processes, however this functionality appears not to have been
used.</p>
</dd>
<dt class="label" id="id7"><span class="brackets"><a class="fn-backref" href="#id2">3</a></span></dt>
<dd><p>Weak definitions are currently handled correctly within dylibs, but if
multiple dylibs provide a weak definition of a symbol then each will end
up with its own definition (similar to how weak definitions are handled
in Windows DLLs). This will be fixed in the future.</p>
</dd>
</dl>
</div>
</div>
</div>


            <div class="clearer"></div>
          </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="OpaquePointers.html" title="Opaque Pointers"
             >next</a> |</li>
        <li class="right" >
          <a href="MCJITDesignAndImplementation.html" title="MCJIT Design and Implementation"
             >previous</a> |</li>
  <li><a href="https://llvm.org/">LLVM Home</a>&nbsp;|&nbsp;</li>
  <li><a href="index.html">Documentation</a>&raquo;</li>

          <li class="nav-item nav-item-1"><a href="UserGuides.html" >User Guides</a> &#187;</li>
        <li class="nav-item nav-item-this"><a href="">ORC Design and Implementation</a></li> 
      </ul>
    </div>
    <div class="footer" role="contentinfo">
        &#169; Copyright 2003-2021, LLVM Project.
      Last updated on 2021-09-18.
      Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 3.5.4.
    </div>
  </body>
</html>