1========================
2LLVM Programmer's Manual
3========================
4
5.. contents::
6   :local:
7
8.. warning::
9   This is always a work in progress.
10
11.. _introduction:
12
13Introduction
14============
15
16This document is meant to highlight some of the important classes and interfaces
17available in the LLVM source-base.  This manual is not intended to explain what
18LLVM is, how it works, and what LLVM code looks like.  It assumes that you know
19the basics of LLVM and are interested in writing transformations or otherwise
20analyzing or manipulating the code.
21
22This document should get you oriented so that you can find your way in the
23continuously growing source code that makes up the LLVM infrastructure.  Note
24that this manual is not intended to serve as a replacement for reading the
25source code, so if you think there should be a method in one of these classes to
26do something, but it's not listed, check the source.  Links to the `doxygen
27<https://llvm.org/doxygen/>`__ sources are provided to make this as easy as
28possible.
29
30The first section of this document describes general information that is useful
31to know when working in the LLVM infrastructure, and the second describes the
32Core LLVM classes.  In the future this manual will be extended with information
33describing how to use extension libraries, such as dominator information, CFG
34traversal routines, and useful utilities like the ``InstVisitor`` (`doxygen
35<https://llvm.org/doxygen/InstVisitor_8h_source.html>`__) template.
36
37.. _general:
38
39General Information
40===================
41
42This section contains general information that is useful if you are working in
43the LLVM source-base, but that isn't specific to any particular API.
44
45.. _stl:
46
47The C++ Standard Template Library
48---------------------------------
49
50LLVM makes heavy use of the C++ Standard Template Library (STL), perhaps much
51more than you are used to, or have seen before.  Because of this, you might want
52to do a little background reading in the techniques used and capabilities of the
53library.  There are many good pages that discuss the STL, and several books on
54the subject that you can get, so it will not be discussed in this document.
55
56Here are some useful links:
57
58#. `cppreference.com
59   <http://en.cppreference.com/w/>`_ - an excellent
60   reference for the STL and other parts of the standard C++ library.
61
62#. `C++ In a Nutshell <http://www.tempest-sw.com/cpp/>`_ - This is an O'Reilly
63   book in the making.  It has a decent Standard Library Reference that rivals
64   Dinkumware's, and is unfortunately no longer free since the book has been
65   published.
66
67#. `C++ Frequently Asked Questions <http://www.parashift.com/c++-faq-lite/>`_.
68
69#. `SGI's STL Programmer's Guide <http://www.sgi.com/tech/stl/>`_ - Contains a
70   useful `Introduction to the STL
71   <http://www.sgi.com/tech/stl/stl_introduction.html>`_.
72
73#. `Bjarne Stroustrup's C++ Page
74   <http://www.stroustrup.com/C++.html>`_.
75
76#. `Bruce Eckel's Thinking in C++, 2nd ed. Volume 2 Revision 4.0
77   (even better, get the book)
78   <http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html>`_.
79
80You are also encouraged to take a look at the :doc:`LLVM Coding Standards
81<CodingStandards>` guide which focuses on how to write maintainable code more
82than where to put your curly braces.
83
84.. _resources:
85
86Other useful references
87-----------------------
88
89#. `Using static and shared libraries across platforms
90   <http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html>`_
91
92.. _apis:
93
94Important and useful LLVM APIs
95==============================
96
97Here we highlight some LLVM APIs that are generally useful and good to know
98about when writing transformations.
99
100.. _isa:
101
102The ``isa<>``, ``cast<>`` and ``dyn_cast<>`` templates
103------------------------------------------------------
104
105The LLVM source-base makes extensive use of a custom form of RTTI.  These
106templates have many similarities to the C++ ``dynamic_cast<>`` operator, but
107they don't have some drawbacks (primarily stemming from the fact that
108``dynamic_cast<>`` only works on classes that have a v-table).  Because they are
109used so often, you must know what they do and how they work.  All of these
110templates are defined in the ``llvm/Support/Casting.h`` (`doxygen
111<https://llvm.org/doxygen/Casting_8h_source.html>`__) file (note that you very
112rarely have to include this file directly).
113
114``isa<>``:
115  The ``isa<>`` operator works exactly like the Java "``instanceof``" operator.
116  It returns true or false depending on whether a reference or pointer points to
117  an instance of the specified class.  This can be very useful for constraint
118  checking of various sorts (example below).
119
120``cast<>``:
121  The ``cast<>`` operator is a "checked cast" operation.  It converts a pointer
122  or reference from a base class to a derived class, causing an assertion
123  failure if it is not really an instance of the right type.  This should be
124  used in cases where you have some information that makes you believe that
125  something is of the right type.  An example of the ``isa<>`` and ``cast<>``
126  template is:
127
128  .. code-block:: c++
129
130    static bool isLoopInvariant(const Value *V, const Loop *L) {
131      if (isa<Constant>(V) || isa<Argument>(V) || isa<GlobalValue>(V))
132        return true;
133
134      // Otherwise, it must be an instruction...
135      return !L->contains(cast<Instruction>(V)->getParent());
136    }
137
138  Note that you should **not** use an ``isa<>`` test followed by a ``cast<>``,
139  for that use the ``dyn_cast<>`` operator.
140
141``dyn_cast<>``:
142  The ``dyn_cast<>`` operator is a "checking cast" operation.  It checks to see
143  if the operand is of the specified type, and if so, returns a pointer to it
144  (this operator does not work with references).  If the operand is not of the
145  correct type, a null pointer is returned.  Thus, this works very much like
146  the ``dynamic_cast<>`` operator in C++, and should be used in the same
147  circumstances.  Typically, the ``dyn_cast<>`` operator is used in an ``if``
148  statement or some other flow control statement like this:
149
150  .. code-block:: c++
151
152    if (auto *AI = dyn_cast<AllocationInst>(Val)) {
153      // ...
154    }
155
156  This form of the ``if`` statement effectively combines together a call to
157  ``isa<>`` and a call to ``cast<>`` into one statement, which is very
158  convenient.
159
160  Note that the ``dyn_cast<>`` operator, like C++'s ``dynamic_cast<>`` or Java's
161  ``instanceof`` operator, can be abused.  In particular, you should not use big
162  chained ``if/then/else`` blocks to check for lots of different variants of
163  classes.  If you find yourself wanting to do this, it is much cleaner and more
164  efficient to use the ``InstVisitor`` class to dispatch over the instruction
165  type directly.
166
167``isa_and_nonnull<>``:
168  The ``isa_and_nonnull<>`` operator works just like the ``isa<>`` operator,
169  except that it allows for a null pointer as an argument (which it then
170  returns false).  This can sometimes be useful, allowing you to combine several
171  null checks into one.
172
173``cast_or_null<>``:
174  The ``cast_or_null<>`` operator works just like the ``cast<>`` operator,
175  except that it allows for a null pointer as an argument (which it then
176  propagates).  This can sometimes be useful, allowing you to combine several
177  null checks into one.
178
179``dyn_cast_or_null<>``:
180  The ``dyn_cast_or_null<>`` operator works just like the ``dyn_cast<>``
181  operator, except that it allows for a null pointer as an argument (which it
182  then propagates).  This can sometimes be useful, allowing you to combine
183  several null checks into one.
184
185These five templates can be used with any classes, whether they have a v-table
186or not.  If you want to add support for these templates, see the document
187:doc:`How to set up LLVM-style RTTI for your class hierarchy
188<HowToSetUpLLVMStyleRTTI>`
189
190.. _string_apis:
191
192Passing strings (the ``StringRef`` and ``Twine`` classes)
193---------------------------------------------------------
194
195Although LLVM generally does not do much string manipulation, we do have several
196important APIs which take strings.  Two important examples are the Value class
197-- which has names for instructions, functions, etc. -- and the ``StringMap``
198class which is used extensively in LLVM and Clang.
199
200These are generic classes, and they need to be able to accept strings which may
201have embedded null characters.  Therefore, they cannot simply take a ``const
202char *``, and taking a ``const std::string&`` requires clients to perform a heap
203allocation which is usually unnecessary.  Instead, many LLVM APIs use a
204``StringRef`` or a ``const Twine&`` for passing strings efficiently.
205
206.. _StringRef:
207
208The ``StringRef`` class
209^^^^^^^^^^^^^^^^^^^^^^^^^^^^
210
211The ``StringRef`` data type represents a reference to a constant string (a
212character array and a length) and supports the common operations available on
213``std::string``, but does not require heap allocation.
214
215It can be implicitly constructed using a C style null-terminated string, an
216``std::string``, or explicitly with a character pointer and length.  For
217example, the ``StringRef`` find function is declared as:
218
219.. code-block:: c++
220
221  iterator find(StringRef Key);
222
223and clients can call it using any one of:
224
225.. code-block:: c++
226
227  Map.find("foo");                 // Lookup "foo"
228  Map.find(std::string("bar"));    // Lookup "bar"
229  Map.find(StringRef("\0baz", 4)); // Lookup "\0baz"
230
231Similarly, APIs which need to return a string may return a ``StringRef``
232instance, which can be used directly or converted to an ``std::string`` using
233the ``str`` member function.  See ``llvm/ADT/StringRef.h`` (`doxygen
234<https://llvm.org/doxygen/StringRef_8h_source.html>`__) for more
235information.
236
237You should rarely use the ``StringRef`` class directly, because it contains
238pointers to external memory it is not generally safe to store an instance of the
239class (unless you know that the external storage will not be freed).
240``StringRef`` is small and pervasive enough in LLVM that it should always be
241passed by value.
242
243The ``Twine`` class
244^^^^^^^^^^^^^^^^^^^
245
246The ``Twine`` (`doxygen <https://llvm.org/doxygen/classllvm_1_1Twine.html>`__)
247class is an efficient way for APIs to accept concatenated strings.  For example,
248a common LLVM paradigm is to name one instruction based on the name of another
249instruction with a suffix, for example:
250
251.. code-block:: c++
252
253    New = CmpInst::Create(..., SO->getName() + ".cmp");
254
255The ``Twine`` class is effectively a lightweight `rope
256<http://en.wikipedia.org/wiki/Rope_(computer_science)>`_ which points to
257temporary (stack allocated) objects.  Twines can be implicitly constructed as
258the result of the plus operator applied to strings (i.e., a C strings, an
259``std::string``, or a ``StringRef``).  The twine delays the actual concatenation
260of strings until it is actually required, at which point it can be efficiently
261rendered directly into a character array.  This avoids unnecessary heap
262allocation involved in constructing the temporary results of string
263concatenation.  See ``llvm/ADT/Twine.h`` (`doxygen
264<https://llvm.org/doxygen/Twine_8h_source.html>`__) and :ref:`here <dss_twine>`
265for more information.
266
267As with a ``StringRef``, ``Twine`` objects point to external memory and should
268almost never be stored or mentioned directly.  They are intended solely for use
269when defining a function which should be able to efficiently accept concatenated
270strings.
271
272.. _formatting_strings:
273
274Formatting strings (the ``formatv`` function)
275---------------------------------------------
276While LLVM doesn't necessarily do a lot of string manipulation and parsing, it
277does do a lot of string formatting.  From diagnostic messages, to llvm tool
278outputs such as ``llvm-readobj`` to printing verbose disassembly listings and
279LLDB runtime logging, the need for string formatting is pervasive.
280
281The ``formatv`` is similar in spirit to ``printf``, but uses a different syntax
282which borrows heavily from Python and C#.  Unlike ``printf`` it deduces the type
283to be formatted at compile time, so it does not need a format specifier such as
284``%d``.  This reduces the mental overhead of trying to construct portable format
285strings, especially for platform-specific types like ``size_t`` or pointer types.
286Unlike both ``printf`` and Python, it additionally fails to compile if LLVM does
287not know how to format the type.  These two properties ensure that the function
288is both safer and simpler to use than traditional formatting methods such as
289the ``printf`` family of functions.
290
291Simple formatting
292^^^^^^^^^^^^^^^^^
293
294A call to ``formatv`` involves a single **format string** consisting of 0 or more
295**replacement sequences**, followed by a variable length list of **replacement values**.
296A replacement sequence is a string of the form ``{N[[,align]:style]}``.
297
298``N`` refers to the 0-based index of the argument from the list of replacement
299values.  Note that this means it is possible to reference the same parameter
300multiple times, possibly with different style and/or alignment options, in any order.
301
302``align`` is an optional string specifying the width of the field to format
303the value into, and the alignment of the value within the field.  It is specified as
304an optional **alignment style** followed by a positive integral **field width**.  The
305alignment style can be one of the characters ``-`` (left align), ``=`` (center align),
306or ``+`` (right align).  The default is right aligned.
307
308``style`` is an optional string consisting of a type specific that controls the
309formatting of the value.  For example, to format a floating point value as a percentage,
310you can use the style option ``P``.
311
312Custom formatting
313^^^^^^^^^^^^^^^^^
314
315There are two ways to customize the formatting behavior for a type.
316
3171. Provide a template specialization of ``llvm::format_provider<T>`` for your
318   type ``T`` with the appropriate static format method.
319
320  .. code-block:: c++
321
322    namespace llvm {
323      template<>
324      struct format_provider<MyFooBar> {
325        static void format(const MyFooBar &V, raw_ostream &Stream, StringRef Style) {
326          // Do whatever is necessary to format `V` into `Stream`
327        }
328      };
329      void foo() {
330        MyFooBar X;
331        std::string S = formatv("{0}", X);
332      }
333    }
334
335  This is a useful extensibility mechanism for adding support for formatting your own
336  custom types with your own custom Style options.  But it does not help when you want
337  to extend the mechanism for formatting a type that the library already knows how to
338  format.  For that, we need something else.
339
3402. Provide a **format adapter** inheriting from ``llvm::FormatAdapter<T>``.
341
342  .. code-block:: c++
343
344    namespace anything {
345      struct format_int_custom : public llvm::FormatAdapter<int> {
346        explicit format_int_custom(int N) : llvm::FormatAdapter<int>(N) {}
347        void format(llvm::raw_ostream &Stream, StringRef Style) override {
348          // Do whatever is necessary to format ``this->Item`` into ``Stream``
349        }
350      };
351    }
352    namespace llvm {
353      void foo() {
354        std::string S = formatv("{0}", anything::format_int_custom(42));
355      }
356    }
357
358  If the type is detected to be derived from ``FormatAdapter<T>``, ``formatv``
359  will call the
360  ``format`` method on the argument passing in the specified style.  This allows
361  one to provide custom formatting of any type, including one which already has
362  a builtin format provider.
363
364``formatv`` Examples
365^^^^^^^^^^^^^^^^^^^^
366Below is intended to provide an incomplete set of examples demonstrating
367the usage of ``formatv``.  More information can be found by reading the
368doxygen documentation or by looking at the unit test suite.
369
370
371.. code-block:: c++
372
373  std::string S;
374  // Simple formatting of basic types and implicit string conversion.
375  S = formatv("{0} ({1:P})", 7, 0.35);  // S == "7 (35.00%)"
376
377  // Out-of-order referencing and multi-referencing
378  outs() << formatv("{0} {2} {1} {0}", 1, "test", 3); // prints "1 3 test 1"
379
380  // Left, right, and center alignment
381  S = formatv("{0,7}",  'a');  // S == "      a";
382  S = formatv("{0,-7}", 'a');  // S == "a      ";
383  S = formatv("{0,=7}", 'a');  // S == "   a   ";
384  S = formatv("{0,+7}", 'a');  // S == "      a";
385
386  // Custom styles
387  S = formatv("{0:N} - {0:x} - {1:E}", 12345, 123908342); // S == "12,345 - 0x3039 - 1.24E8"
388
389  // Adapters
390  S = formatv("{0}", fmt_align(42, AlignStyle::Center, 7));  // S == "  42   "
391  S = formatv("{0}", fmt_repeat("hi", 3)); // S == "hihihi"
392  S = formatv("{0}", fmt_pad("hi", 2, 6)); // S == "  hi      "
393
394  // Ranges
395  std::vector<int> V = {8, 9, 10};
396  S = formatv("{0}", make_range(V.begin(), V.end())); // S == "8, 9, 10"
397  S = formatv("{0:$[+]}", make_range(V.begin(), V.end())); // S == "8+9+10"
398  S = formatv("{0:$[ + ]@[x]}", make_range(V.begin(), V.end())); // S == "0x8 + 0x9 + 0xA"
399
400.. _error_apis:
401
402Error handling
403--------------
404
405Proper error handling helps us identify bugs in our code, and helps end-users
406understand errors in their tool usage. Errors fall into two broad categories:
407*programmatic* and *recoverable*, with different strategies for handling and
408reporting.
409
410Programmatic Errors
411^^^^^^^^^^^^^^^^^^^
412
413Programmatic errors are violations of program invariants or API contracts, and
414represent bugs within the program itself. Our aim is to document invariants, and
415to abort quickly at the point of failure (providing some basic diagnostic) when
416invariants are broken at runtime.
417
418The fundamental tools for handling programmatic errors are assertions and the
419llvm_unreachable function. Assertions are used to express invariant conditions,
420and should include a message describing the invariant:
421
422.. code-block:: c++
423
424  assert(isPhysReg(R) && "All virt regs should have been allocated already.");
425
426The llvm_unreachable function can be used to document areas of control flow
427that should never be entered if the program invariants hold:
428
429.. code-block:: c++
430
431  enum { Foo, Bar, Baz } X = foo();
432
433  switch (X) {
434    case Foo: /* Handle Foo */; break;
435    case Bar: /* Handle Bar */; break;
436    default:
437      llvm_unreachable("X should be Foo or Bar here");
438  }
439
440Recoverable Errors
441^^^^^^^^^^^^^^^^^^
442
443Recoverable errors represent an error in the program's environment, for example
444a resource failure (a missing file, a dropped network connection, etc.), or
445malformed input. These errors should be detected and communicated to a level of
446the program where they can be handled appropriately. Handling the error may be
447as simple as reporting the issue to the user, or it may involve attempts at
448recovery.
449
450.. note::
451
452   While it would be ideal to use this error handling scheme throughout
453   LLVM, there are places where this hasn't been practical to apply. In
454   situations where you absolutely must emit a non-programmatic error and
455   the ``Error`` model isn't workable you can call ``report_fatal_error``,
456   which will call installed error handlers, print a message, and abort the
457   program. The use of `report_fatal_error` in this case is discouraged.
458
459Recoverable errors are modeled using LLVM's ``Error`` scheme. This scheme
460represents errors using function return values, similar to classic C integer
461error codes, or C++'s ``std::error_code``. However, the ``Error`` class is
462actually a lightweight wrapper for user-defined error types, allowing arbitrary
463information to be attached to describe the error. This is similar to the way C++
464exceptions allow throwing of user-defined types.
465
466Success values are created by calling ``Error::success()``, E.g.:
467
468.. code-block:: c++
469
470  Error foo() {
471    // Do something.
472    // Return success.
473    return Error::success();
474  }
475
476Success values are very cheap to construct and return - they have minimal
477impact on program performance.
478
479Failure values are constructed using ``make_error<T>``, where ``T`` is any class
480that inherits from the ErrorInfo utility, E.g.:
481
482.. code-block:: c++
483
484  class BadFileFormat : public ErrorInfo<BadFileFormat> {
485  public:
486    static char ID;
487    std::string Path;
488
489    BadFileFormat(StringRef Path) : Path(Path.str()) {}
490
491    void log(raw_ostream &OS) const override {
492      OS << Path << " is malformed";
493    }
494
495    std::error_code convertToErrorCode() const override {
496      return make_error_code(object_error::parse_failed);
497    }
498  };
499
500  char BadFileFormat::ID; // This should be declared in the C++ file.
501
502  Error printFormattedFile(StringRef Path) {
503    if (<check for valid format>)
504      return make_error<BadFileFormat>(Path);
505    // print file contents.
506    return Error::success();
507  }
508
509Error values can be implicitly converted to bool: true for error, false for
510success, enabling the following idiom:
511
512.. code-block:: c++
513
514  Error mayFail();
515
516  Error foo() {
517    if (auto Err = mayFail())
518      return Err;
519    // Success! We can proceed.
520    ...
521
522For functions that can fail but need to return a value the ``Expected<T>``
523utility can be used. Values of this type can be constructed with either a
524``T``, or an ``Error``. Expected<T> values are also implicitly convertible to
525boolean, but with the opposite convention to ``Error``: true for success, false
526for error. If success, the ``T`` value can be accessed via the dereference
527operator. If failure, the ``Error`` value can be extracted using the
528``takeError()`` method. Idiomatic usage looks like:
529
530.. code-block:: c++
531
532  Expected<FormattedFile> openFormattedFile(StringRef Path) {
533    // If badly formatted, return an error.
534    if (auto Err = checkFormat(Path))
535      return std::move(Err);
536    // Otherwise return a FormattedFile instance.
537    return FormattedFile(Path);
538  }
539
540  Error processFormattedFile(StringRef Path) {
541    // Try to open a formatted file
542    if (auto FileOrErr = openFormattedFile(Path)) {
543      // On success, grab a reference to the file and continue.
544      auto &File = *FileOrErr;
545      ...
546    } else
547      // On error, extract the Error value and return it.
548      return FileOrErr.takeError();
549  }
550
551If an ``Expected<T>`` value is in success mode then the ``takeError()`` method
552will return a success value. Using this fact, the above function can be
553rewritten as:
554
555.. code-block:: c++
556
557  Error processFormattedFile(StringRef Path) {
558    // Try to open a formatted file
559    auto FileOrErr = openFormattedFile(Path);
560    if (auto Err = FileOrErr.takeError())
561      // On error, extract the Error value and return it.
562      return Err;
563    // On success, grab a reference to the file and continue.
564    auto &File = *FileOrErr;
565    ...
566  }
567
568This second form is often more readable for functions that involve multiple
569``Expected<T>`` values as it limits the indentation required.
570
571All ``Error`` instances, whether success or failure, must be either checked or
572moved from (via ``std::move`` or a return) before they are destructed.
573Accidentally discarding an unchecked error will cause a program abort at the
574point where the unchecked value's destructor is run, making it easy to identify
575and fix violations of this rule.
576
577Success values are considered checked once they have been tested (by invoking
578the boolean conversion operator):
579
580.. code-block:: c++
581
582  if (auto Err = mayFail(...))
583    return Err; // Failure value - move error to caller.
584
585  // Safe to continue: Err was checked.
586
587In contrast, the following code will always cause an abort, even if ``mayFail``
588returns a success value:
589
590.. code-block:: c++
591
592    mayFail();
593    // Program will always abort here, even if mayFail() returns Success, since
594    // the value is not checked.
595
596Failure values are considered checked once a handler for the error type has
597been activated:
598
599.. code-block:: c++
600
601  handleErrors(
602    processFormattedFile(...),
603    [](const BadFileFormat &BFF) {
604      report("Unable to process " + BFF.Path + ": bad format");
605    },
606    [](const FileNotFound &FNF) {
607      report("File not found " + FNF.Path);
608    });
609
610The ``handleErrors`` function takes an error as its first argument, followed by
611a variadic list of "handlers", each of which must be a callable type (a
612function, lambda, or class with a call operator) with one argument. The
613``handleErrors`` function will visit each handler in the sequence and check its
614argument type against the dynamic type of the error, running the first handler
615that matches. This is the same decision process that is used decide which catch
616clause to run for a C++ exception.
617
618Since the list of handlers passed to ``handleErrors`` may not cover every error
619type that can occur, the ``handleErrors`` function also returns an Error value
620that must be checked or propagated. If the error value that is passed to
621``handleErrors`` does not match any of the handlers it will be returned from
622handleErrors. Idiomatic use of ``handleErrors`` thus looks like:
623
624.. code-block:: c++
625
626  if (auto Err =
627        handleErrors(
628          processFormattedFile(...),
629          [](const BadFileFormat &BFF) {
630            report("Unable to process " + BFF.Path + ": bad format");
631          },
632          [](const FileNotFound &FNF) {
633            report("File not found " + FNF.Path);
634          }))
635    return Err;
636
637In cases where you truly know that the handler list is exhaustive the
638``handleAllErrors`` function can be used instead. This is identical to
639``handleErrors`` except that it will terminate the program if an unhandled
640error is passed in, and can therefore return void. The ``handleAllErrors``
641function should generally be avoided: the introduction of a new error type
642elsewhere in the program can easily turn a formerly exhaustive list of errors
643into a non-exhaustive list, risking unexpected program termination. Where
644possible, use handleErrors and propagate unknown errors up the stack instead.
645
646For tool code, where errors can be handled by printing an error message then
647exiting with an error code, the :ref:`ExitOnError <err_exitonerr>` utility
648may be a better choice than handleErrors, as it simplifies control flow when
649calling fallible functions.
650
651In situations where it is known that a particular call to a fallible function
652will always succeed (for example, a call to a function that can only fail on a
653subset of inputs with an input that is known to be safe) the
654:ref:`cantFail <err_cantfail>` functions can be used to remove the error type,
655simplifying control flow.
656
657StringError
658"""""""""""
659
660Many kinds of errors have no recovery strategy, the only action that can be
661taken is to report them to the user so that the user can attempt to fix the
662environment. In this case representing the error as a string makes perfect
663sense. LLVM provides the ``StringError`` class for this purpose. It takes two
664arguments: A string error message, and an equivalent ``std::error_code`` for
665interoperability. It also provides a ``createStringError`` function to simplify
666common usage of this class:
667
668.. code-block:: c++
669
670  // These two lines of code are equivalent:
671  make_error<StringError>("Bad executable", errc::executable_format_error);
672  createStringError(errc::executable_format_error, "Bad executable");
673
674If you're certain that the error you're building will never need to be converted
675to a ``std::error_code`` you can use the ``inconvertibleErrorCode()`` function:
676
677.. code-block:: c++
678
679  createStringError(inconvertibleErrorCode(), "Bad executable");
680
681This should be done only after careful consideration. If any attempt is made to
682convert this error to a ``std::error_code`` it will trigger immediate program
683termination. Unless you are certain that your errors will not need
684interoperability you should look for an existing ``std::error_code`` that you
685can convert to, and even (as painful as it is) consider introducing a new one as
686a stopgap measure.
687
688``createStringError`` can take ``printf`` style format specifiers to provide a
689formatted message:
690
691.. code-block:: c++
692
693  createStringError(errc::executable_format_error,
694                    "Bad executable: %s", FileName);
695
696Interoperability with std::error_code and ErrorOr
697"""""""""""""""""""""""""""""""""""""""""""""""""
698
699Many existing LLVM APIs use ``std::error_code`` and its partner ``ErrorOr<T>``
700(which plays the same role as ``Expected<T>``, but wraps a ``std::error_code``
701rather than an ``Error``). The infectious nature of error types means that an
702attempt to change one of these functions to return ``Error`` or ``Expected<T>``
703instead often results in an avalanche of changes to callers, callers of callers,
704and so on. (The first such attempt, returning an ``Error`` from
705MachOObjectFile's constructor, was abandoned after the diff reached 3000 lines,
706impacted half a dozen libraries, and was still growing).
707
708To solve this problem, the ``Error``/``std::error_code`` interoperability requirement was
709introduced. Two pairs of functions allow any ``Error`` value to be converted to a
710``std::error_code``, any ``Expected<T>`` to be converted to an ``ErrorOr<T>``, and vice
711versa:
712
713.. code-block:: c++
714
715  std::error_code errorToErrorCode(Error Err);
716  Error errorCodeToError(std::error_code EC);
717
718  template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> TOrErr);
719  template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> TOrEC);
720
721
722Using these APIs it is easy to make surgical patches that update individual
723functions from ``std::error_code`` to ``Error``, and from ``ErrorOr<T>`` to
724``Expected<T>``.
725
726Returning Errors from error handlers
727""""""""""""""""""""""""""""""""""""
728
729Error recovery attempts may themselves fail. For that reason, ``handleErrors``
730actually recognises three different forms of handler signature:
731
732.. code-block:: c++
733
734  // Error must be handled, no new errors produced:
735  void(UserDefinedError &E);
736
737  // Error must be handled, new errors can be produced:
738  Error(UserDefinedError &E);
739
740  // Original error can be inspected, then re-wrapped and returned (or a new
741  // error can be produced):
742  Error(std::unique_ptr<UserDefinedError> E);
743
744Any error returned from a handler will be returned from the ``handleErrors``
745function so that it can be handled itself, or propagated up the stack.
746
747.. _err_exitonerr:
748
749Using ExitOnError to simplify tool code
750"""""""""""""""""""""""""""""""""""""""
751
752Library code should never call ``exit`` for a recoverable error, however in tool
753code (especially command line tools) this can be a reasonable approach. Calling
754``exit`` upon encountering an error dramatically simplifies control flow as the
755error no longer needs to be propagated up the stack. This allows code to be
756written in straight-line style, as long as each fallible call is wrapped in a
757check and call to exit. The ``ExitOnError`` class supports this pattern by
758providing call operators that inspect ``Error`` values, stripping the error away
759in the success case and logging to ``stderr`` then exiting in the failure case.
760
761To use this class, declare a global ``ExitOnError`` variable in your program:
762
763.. code-block:: c++
764
765  ExitOnError ExitOnErr;
766
767Calls to fallible functions can then be wrapped with a call to ``ExitOnErr``,
768turning them into non-failing calls:
769
770.. code-block:: c++
771
772  Error mayFail();
773  Expected<int> mayFail2();
774
775  void foo() {
776    ExitOnErr(mayFail());
777    int X = ExitOnErr(mayFail2());
778  }
779
780On failure, the error's log message will be written to ``stderr``, optionally
781preceded by a string "banner" that can be set by calling the setBanner method. A
782mapping can also be supplied from ``Error`` values to exit codes using the
783``setExitCodeMapper`` method:
784
785.. code-block:: c++
786
787  int main(int argc, char *argv[]) {
788    ExitOnErr.setBanner(std::string(argv[0]) + " error:");
789    ExitOnErr.setExitCodeMapper(
790      [](const Error &Err) {
791        if (Err.isA<BadFileFormat>())
792          return 2;
793        return 1;
794      });
795
796Use ``ExitOnError`` in your tool code where possible as it can greatly improve
797readability.
798
799.. _err_cantfail:
800
801Using cantFail to simplify safe callsites
802"""""""""""""""""""""""""""""""""""""""""
803
804Some functions may only fail for a subset of their inputs, so calls using known
805safe inputs can be assumed to succeed.
806
807The cantFail functions encapsulate this by wrapping an assertion that their
808argument is a success value and, in the case of Expected<T>, unwrapping the
809T value:
810
811.. code-block:: c++
812
813  Error onlyFailsForSomeXValues(int X);
814  Expected<int> onlyFailsForSomeXValues2(int X);
815
816  void foo() {
817    cantFail(onlyFailsForSomeXValues(KnownSafeValue));
818    int Y = cantFail(onlyFailsForSomeXValues2(KnownSafeValue));
819    ...
820  }
821
822Like the ExitOnError utility, cantFail simplifies control flow. Their treatment
823of error cases is very different however: Where ExitOnError is guaranteed to
824terminate the program on an error input, cantFail simply asserts that the result
825is success. In debug builds this will result in an assertion failure if an error
826is encountered. In release builds the behavior of cantFail for failure values is
827undefined. As such, care must be taken in the use of cantFail: clients must be
828certain that a cantFail wrapped call really can not fail with the given
829arguments.
830
831Use of the cantFail functions should be rare in library code, but they are
832likely to be of more use in tool and unit-test code where inputs and/or
833mocked-up classes or functions may be known to be safe.
834
835Fallible constructors
836"""""""""""""""""""""
837
838Some classes require resource acquisition or other complex initialization that
839can fail during construction. Unfortunately constructors can't return errors,
840and having clients test objects after they're constructed to ensure that they're
841valid is error prone as it's all too easy to forget the test. To work around
842this, use the named constructor idiom and return an ``Expected<T>``:
843
844.. code-block:: c++
845
846  class Foo {
847  public:
848
849    static Expected<Foo> Create(Resource R1, Resource R2) {
850      Error Err = Error::success();
851      Foo F(R1, R2, Err);
852      if (Err)
853        return std::move(Err);
854      return std::move(F);
855    }
856
857  private:
858
859    Foo(Resource R1, Resource R2, Error &Err) {
860      ErrorAsOutParameter EAO(&Err);
861      if (auto Err2 = R1.acquire()) {
862        Err = std::move(Err2);
863        return;
864      }
865      Err = R2.acquire();
866    }
867  };
868
869
870Here, the named constructor passes an ``Error`` by reference into the actual
871constructor, which the constructor can then use to return errors. The
872``ErrorAsOutParameter`` utility sets the ``Error`` value's checked flag on entry
873to the constructor so that the error can be assigned to, then resets it on exit
874to force the client (the named constructor) to check the error.
875
876By using this idiom, clients attempting to construct a Foo receive either a
877well-formed Foo or an Error, never an object in an invalid state.
878
879Propagating and consuming errors based on types
880"""""""""""""""""""""""""""""""""""""""""""""""
881
882In some contexts, certain types of error are known to be benign. For example,
883when walking an archive, some clients may be happy to skip over badly formatted
884object files rather than terminating the walk immediately. Skipping badly
885formatted objects could be achieved using an elaborate handler method, but the
886Error.h header provides two utilities that make this idiom much cleaner: the
887type inspection method, ``isA``, and the ``consumeError`` function:
888
889.. code-block:: c++
890
891  Error walkArchive(Archive A) {
892    for (unsigned I = 0; I != A.numMembers(); ++I) {
893      auto ChildOrErr = A.getMember(I);
894      if (auto Err = ChildOrErr.takeError()) {
895        if (Err.isA<BadFileFormat>())
896          consumeError(std::move(Err))
897        else
898          return Err;
899      }
900      auto &Child = *ChildOrErr;
901      // Use Child
902      ...
903    }
904    return Error::success();
905  }
906
907Concatenating Errors with joinErrors
908""""""""""""""""""""""""""""""""""""
909
910In the archive walking example above ``BadFileFormat`` errors are simply
911consumed and ignored. If the client had wanted report these errors after
912completing the walk over the archive they could use the ``joinErrors`` utility:
913
914.. code-block:: c++
915
916  Error walkArchive(Archive A) {
917    Error DeferredErrs = Error::success();
918    for (unsigned I = 0; I != A.numMembers(); ++I) {
919      auto ChildOrErr = A.getMember(I);
920      if (auto Err = ChildOrErr.takeError())
921        if (Err.isA<BadFileFormat>())
922          DeferredErrs = joinErrors(std::move(DeferredErrs), std::move(Err));
923        else
924          return Err;
925      auto &Child = *ChildOrErr;
926      // Use Child
927      ...
928    }
929    return DeferredErrs;
930  }
931
932The ``joinErrors`` routine builds a special error type called ``ErrorList``,
933which holds a list of user defined errors. The ``handleErrors`` routine
934recognizes this type and will attempt to handle each of the contained errors in
935order. If all contained errors can be handled, ``handleErrors`` will return
936``Error::success()``, otherwise ``handleErrors`` will concatenate the remaining
937errors and return the resulting ``ErrorList``.
938
939Building fallible iterators and iterator ranges
940"""""""""""""""""""""""""""""""""""""""""""""""
941
942The archive walking examples above retrieve archive members by index, however
943this requires considerable boiler-plate for iteration and error checking. We can
944clean this up by using the "fallible iterator" pattern, which supports the
945following natural iteration idiom for fallible containers like Archive:
946
947.. code-block:: c++
948
949  Error Err = Error::success();
950  for (auto &Child : Ar->children(Err)) {
951    // Use Child - only enter the loop when it's valid
952
953    // Allow early exit from the loop body, since we know that Err is success
954    // when we're inside the loop.
955    if (BailOutOn(Child))
956      return;
957
958    ...
959  }
960  // Check Err after the loop to ensure it didn't break due to an error.
961  if (Err)
962    return Err;
963
964To enable this idiom, iterators over fallible containers are written in a
965natural style, with their ``++`` and ``--`` operators replaced with fallible
966``Error inc()`` and ``Error dec()`` functions. E.g.:
967
968.. code-block:: c++
969
970  class FallibleChildIterator {
971  public:
972    FallibleChildIterator(Archive &A, unsigned ChildIdx);
973    Archive::Child &operator*();
974    friend bool operator==(const ArchiveIterator &LHS,
975                           const ArchiveIterator &RHS);
976
977    // operator++/operator-- replaced with fallible increment / decrement:
978    Error inc() {
979      if (!A.childValid(ChildIdx + 1))
980        return make_error<BadArchiveMember>(...);
981      ++ChildIdx;
982      return Error::success();
983    }
984
985    Error dec() { ... }
986  };
987
988Instances of this kind of fallible iterator interface are then wrapped with the
989fallible_iterator utility which provides ``operator++`` and ``operator--``,
990returning any errors via a reference passed in to the wrapper at construction
991time. The fallible_iterator wrapper takes care of (a) jumping to the end of the
992range on error, and (b) marking the error as checked whenever an iterator is
993compared to ``end`` and found to be inequal (in particular: this marks the
994error as checked throughout the body of a range-based for loop), enabling early
995exit from the loop without redundant error checking.
996
997Instances of the fallible iterator interface (e.g. FallibleChildIterator above)
998are wrapped using the ``make_fallible_itr`` and ``make_fallible_end``
999functions. E.g.:
1000
1001.. code-block:: c++
1002
1003  class Archive {
1004  public:
1005    using child_iterator = fallible_iterator<FallibleChildIterator>;
1006
1007    child_iterator child_begin(Error &Err) {
1008      return make_fallible_itr(FallibleChildIterator(*this, 0), Err);
1009    }
1010
1011    child_iterator child_end() {
1012      return make_fallible_end(FallibleChildIterator(*this, size()));
1013    }
1014
1015    iterator_range<child_iterator> children(Error &Err) {
1016      return make_range(child_begin(Err), child_end());
1017    }
1018  };
1019
1020Using the fallible_iterator utility allows for both natural construction of
1021fallible iterators (using failing ``inc`` and ``dec`` operations) and
1022relatively natural use of c++ iterator/loop idioms.
1023
1024.. _function_apis:
1025
1026More information on Error and its related utilities can be found in the
1027Error.h header file.
1028
1029Passing functions and other callable objects
1030--------------------------------------------
1031
1032Sometimes you may want a function to be passed a callback object. In order to
1033support lambda expressions and other function objects, you should not use the
1034traditional C approach of taking a function pointer and an opaque cookie:
1035
1036.. code-block:: c++
1037
1038    void takeCallback(bool (*Callback)(Function *, void *), void *Cookie);
1039
1040Instead, use one of the following approaches:
1041
1042Function template
1043^^^^^^^^^^^^^^^^^
1044
1045If you don't mind putting the definition of your function into a header file,
1046make it a function template that is templated on the callable type.
1047
1048.. code-block:: c++
1049
1050    template<typename Callable>
1051    void takeCallback(Callable Callback) {
1052      Callback(1, 2, 3);
1053    }
1054
1055The ``function_ref`` class template
1056^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1057
1058The ``function_ref``
1059(`doxygen <https://llvm.org/doxygen/classllvm_1_1function__ref_3_01Ret_07Params_8_8_8_08_4.html>`__) class
1060template represents a reference to a callable object, templated over the type
1061of the callable. This is a good choice for passing a callback to a function,
1062if you don't need to hold onto the callback after the function returns. In this
1063way, ``function_ref`` is to ``std::function`` as ``StringRef`` is to
1064``std::string``.
1065
1066``function_ref<Ret(Param1, Param2, ...)>`` can be implicitly constructed from
1067any callable object that can be called with arguments of type ``Param1``,
1068``Param2``, ..., and returns a value that can be converted to type ``Ret``.
1069For example:
1070
1071.. code-block:: c++
1072
1073    void visitBasicBlocks(Function *F, function_ref<bool (BasicBlock*)> Callback) {
1074      for (BasicBlock &BB : *F)
1075        if (Callback(&BB))
1076          return;
1077    }
1078
1079can be called using:
1080
1081.. code-block:: c++
1082
1083    visitBasicBlocks(F, [&](BasicBlock *BB) {
1084      if (process(BB))
1085        return isEmpty(BB);
1086      return false;
1087    });
1088
1089Note that a ``function_ref`` object contains pointers to external memory, so it
1090is not generally safe to store an instance of the class (unless you know that
1091the external storage will not be freed). If you need this ability, consider
1092using ``std::function``. ``function_ref`` is small enough that it should always
1093be passed by value.
1094
1095.. _DEBUG:
1096
1097The ``LLVM_DEBUG()`` macro and ``-debug`` option
1098------------------------------------------------
1099
1100Often when working on your pass you will put a bunch of debugging printouts and
1101other code into your pass.  After you get it working, you want to remove it, but
1102you may need it again in the future (to work out new bugs that you run across).
1103
1104Naturally, because of this, you don't want to delete the debug printouts, but
1105you don't want them to always be noisy.  A standard compromise is to comment
1106them out, allowing you to enable them if you need them in the future.
1107
1108The ``llvm/Support/Debug.h`` (`doxygen
1109<https://llvm.org/doxygen/Debug_8h_source.html>`__) file provides a macro named
1110``LLVM_DEBUG()`` that is a much nicer solution to this problem.  Basically, you can
1111put arbitrary code into the argument of the ``LLVM_DEBUG`` macro, and it is only
1112executed if '``opt``' (or any other tool) is run with the '``-debug``' command
1113line argument:
1114
1115.. code-block:: c++
1116
1117  LLVM_DEBUG(dbgs() << "I am here!\n");
1118
1119Then you can run your pass like this:
1120
1121.. code-block:: none
1122
1123  $ opt < a.bc > /dev/null -mypass
1124  <no output>
1125  $ opt < a.bc > /dev/null -mypass -debug
1126  I am here!
1127
1128Using the ``LLVM_DEBUG()`` macro instead of a home-brewed solution allows you to not
1129have to create "yet another" command line option for the debug output for your
1130pass.  Note that ``LLVM_DEBUG()`` macros are disabled for non-asserts builds, so they
1131do not cause a performance impact at all (for the same reason, they should also
1132not contain side-effects!).
1133
1134One additional nice thing about the ``LLVM_DEBUG()`` macro is that you can enable or
1135disable it directly in gdb.  Just use "``set DebugFlag=0``" or "``set
1136DebugFlag=1``" from the gdb if the program is running.  If the program hasn't
1137been started yet, you can always just run it with ``-debug``.
1138
1139.. _DEBUG_TYPE:
1140
1141Fine grained debug info with ``DEBUG_TYPE`` and the ``-debug-only`` option
1142^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1143
1144Sometimes you may find yourself in a situation where enabling ``-debug`` just
1145turns on **too much** information (such as when working on the code generator).
1146If you want to enable debug information with more fine-grained control, you
1147should define the ``DEBUG_TYPE`` macro and use the ``-debug-only`` option as
1148follows:
1149
1150.. code-block:: c++
1151
1152  #define DEBUG_TYPE "foo"
1153  LLVM_DEBUG(dbgs() << "'foo' debug type\n");
1154  #undef  DEBUG_TYPE
1155  #define DEBUG_TYPE "bar"
1156  LLVM_DEBUG(dbgs() << "'bar' debug type\n");
1157  #undef  DEBUG_TYPE
1158
1159Then you can run your pass like this:
1160
1161.. code-block:: none
1162
1163  $ opt < a.bc > /dev/null -mypass
1164  <no output>
1165  $ opt < a.bc > /dev/null -mypass -debug
1166  'foo' debug type
1167  'bar' debug type
1168  $ opt < a.bc > /dev/null -mypass -debug-only=foo
1169  'foo' debug type
1170  $ opt < a.bc > /dev/null -mypass -debug-only=bar
1171  'bar' debug type
1172  $ opt < a.bc > /dev/null -mypass -debug-only=foo,bar
1173  'foo' debug type
1174  'bar' debug type
1175
1176Of course, in practice, you should only set ``DEBUG_TYPE`` at the top of a file,
1177to specify the debug type for the entire module. Be careful that you only do
1178this after including Debug.h and not around any #include of headers. Also, you
1179should use names more meaningful than "foo" and "bar", because there is no
1180system in place to ensure that names do not conflict. If two different modules
1181use the same string, they will all be turned on when the name is specified.
1182This allows, for example, all debug information for instruction scheduling to be
1183enabled with ``-debug-only=InstrSched``, even if the source lives in multiple
1184files. The name must not include a comma (,) as that is used to separate the
1185arguments of the ``-debug-only`` option.
1186
1187For performance reasons, -debug-only is not available in optimized build
1188(``--enable-optimized``) of LLVM.
1189
1190The ``DEBUG_WITH_TYPE`` macro is also available for situations where you would
1191like to set ``DEBUG_TYPE``, but only for one specific ``DEBUG`` statement.  It
1192takes an additional first parameter, which is the type to use.  For example, the
1193preceding example could be written as:
1194
1195.. code-block:: c++
1196
1197  DEBUG_WITH_TYPE("foo", dbgs() << "'foo' debug type\n");
1198  DEBUG_WITH_TYPE("bar", dbgs() << "'bar' debug type\n");
1199
1200.. _Statistic:
1201
1202The ``Statistic`` class & ``-stats`` option
1203-------------------------------------------
1204
1205The ``llvm/ADT/Statistic.h`` (`doxygen
1206<https://llvm.org/doxygen/Statistic_8h_source.html>`__) file provides a class
1207named ``Statistic`` that is used as a unified way to keep track of what the LLVM
1208compiler is doing and how effective various optimizations are.  It is useful to
1209see what optimizations are contributing to making a particular program run
1210faster.
1211
1212Often you may run your pass on some big program, and you're interested to see
1213how many times it makes a certain transformation.  Although you can do this with
1214hand inspection, or some ad-hoc method, this is a real pain and not very useful
1215for big programs.  Using the ``Statistic`` class makes it very easy to keep
1216track of this information, and the calculated information is presented in a
1217uniform manner with the rest of the passes being executed.
1218
1219There are many examples of ``Statistic`` uses, but the basics of using it are as
1220follows:
1221
1222Define your statistic like this:
1223
1224.. code-block:: c++
1225
1226  #define DEBUG_TYPE "mypassname"   // This goes before any #includes.
1227  STATISTIC(NumXForms, "The # of times I did stuff");
1228
1229The ``STATISTIC`` macro defines a static variable, whose name is specified by
1230the first argument.  The pass name is taken from the ``DEBUG_TYPE`` macro, and
1231the description is taken from the second argument.  The variable defined
1232("NumXForms" in this case) acts like an unsigned integer.
1233
1234Whenever you make a transformation, bump the counter:
1235
1236.. code-block:: c++
1237
1238  ++NumXForms;   // I did stuff!
1239
1240That's all you have to do.  To get '``opt``' to print out the statistics
1241gathered, use the '``-stats``' option:
1242
1243.. code-block:: none
1244
1245  $ opt -stats -mypassname < program.bc > /dev/null
1246  ... statistics output ...
1247
1248Note that in order to use the '``-stats``' option, LLVM must be
1249compiled with assertions enabled.
1250
1251When running ``opt`` on a C file from the SPEC benchmark suite, it gives a
1252report that looks like this:
1253
1254.. code-block:: none
1255
1256   7646 bitcodewriter   - Number of normal instructions
1257    725 bitcodewriter   - Number of oversized instructions
1258 129996 bitcodewriter   - Number of bitcode bytes written
1259   2817 raise           - Number of insts DCEd or constprop'd
1260   3213 raise           - Number of cast-of-self removed
1261   5046 raise           - Number of expression trees converted
1262     75 raise           - Number of other getelementptr's formed
1263    138 raise           - Number of load/store peepholes
1264     42 deadtypeelim    - Number of unused typenames removed from symtab
1265    392 funcresolve     - Number of varargs functions resolved
1266     27 globaldce       - Number of global variables removed
1267      2 adce            - Number of basic blocks removed
1268    134 cee             - Number of branches revectored
1269     49 cee             - Number of setcc instruction eliminated
1270    532 gcse            - Number of loads removed
1271   2919 gcse            - Number of instructions removed
1272     86 indvars         - Number of canonical indvars added
1273     87 indvars         - Number of aux indvars removed
1274     25 instcombine     - Number of dead inst eliminate
1275    434 instcombine     - Number of insts combined
1276    248 licm            - Number of load insts hoisted
1277   1298 licm            - Number of insts hoisted to a loop pre-header
1278      3 licm            - Number of insts hoisted to multiple loop preds (bad, no loop pre-header)
1279     75 mem2reg         - Number of alloca's promoted
1280   1444 cfgsimplify     - Number of blocks simplified
1281
1282Obviously, with so many optimizations, having a unified framework for this stuff
1283is very nice.  Making your pass fit well into the framework makes it more
1284maintainable and useful.
1285
1286.. _DebugCounters:
1287
1288Adding debug counters to aid in debugging your code
1289---------------------------------------------------
1290
1291Sometimes, when writing new passes, or trying to track down bugs, it
1292is useful to be able to control whether certain things in your pass
1293happen or not.  For example, there are times the minimization tooling
1294can only easily give you large testcases.  You would like to narrow
1295your bug down to a specific transformation happening or not happening,
1296automatically, using bisection.  This is where debug counters help.
1297They provide a framework for making parts of your code only execute a
1298certain number of times.
1299
1300The ``llvm/Support/DebugCounter.h`` (`doxygen
1301<https://llvm.org/doxygen/DebugCounter_8h_source.html>`__) file
1302provides a class named ``DebugCounter`` that can be used to create
1303command line counter options that control execution of parts of your code.
1304
1305Define your DebugCounter like this:
1306
1307.. code-block:: c++
1308
1309  DEBUG_COUNTER(DeleteAnInstruction, "passname-delete-instruction",
1310		"Controls which instructions get delete");
1311
1312The ``DEBUG_COUNTER`` macro defines a static variable, whose name
1313is specified by the first argument.  The name of the counter
1314(which is used on the command line) is specified by the second
1315argument, and the description used in the help is specified by the
1316third argument.
1317
1318Whatever code you want that control, use ``DebugCounter::shouldExecute`` to control it.
1319
1320.. code-block:: c++
1321
1322  if (DebugCounter::shouldExecute(DeleteAnInstruction))
1323    I->eraseFromParent();
1324
1325That's all you have to do.  Now, using opt, you can control when this code triggers using
1326the '``--debug-counter``' option.  There are two counters provided, ``skip`` and ``count``.
1327``skip`` is the number of times to skip execution of the codepath.  ``count`` is the number
1328of times, once we are done skipping, to execute the codepath.
1329
1330.. code-block:: none
1331
1332  $ opt --debug-counter=passname-delete-instruction-skip=1,passname-delete-instruction-count=2 -passname
1333
1334This will skip the above code the first time we hit it, then execute it twice, then skip the rest of the executions.
1335
1336So if executed on the following code:
1337
1338.. code-block:: llvm
1339
1340  %1 = add i32 %a, %b
1341  %2 = add i32 %a, %b
1342  %3 = add i32 %a, %b
1343  %4 = add i32 %a, %b
1344
1345It would delete number ``%2`` and ``%3``.
1346
1347A utility is provided in `utils/bisect-skip-count` to binary search
1348skip and count arguments. It can be used to automatically minimize the
1349skip and count for a debug-counter variable.
1350
1351.. _ViewGraph:
1352
1353Viewing graphs while debugging code
1354-----------------------------------
1355
1356Several of the important data structures in LLVM are graphs: for example CFGs
1357made out of LLVM :ref:`BasicBlocks <BasicBlock>`, CFGs made out of LLVM
1358:ref:`MachineBasicBlocks <MachineBasicBlock>`, and :ref:`Instruction Selection
1359DAGs <SelectionDAG>`.  In many cases, while debugging various parts of the
1360compiler, it is nice to instantly visualize these graphs.
1361
1362LLVM provides several callbacks that are available in a debug build to do
1363exactly that.  If you call the ``Function::viewCFG()`` method, for example, the
1364current LLVM tool will pop up a window containing the CFG for the function where
1365each basic block is a node in the graph, and each node contains the instructions
1366in the block.  Similarly, there also exists ``Function::viewCFGOnly()`` (does
1367not include the instructions), the ``MachineFunction::viewCFG()`` and
1368``MachineFunction::viewCFGOnly()``, and the ``SelectionDAG::viewGraph()``
1369methods.  Within GDB, for example, you can usually use something like ``call
1370DAG.viewGraph()`` to pop up a window.  Alternatively, you can sprinkle calls to
1371these functions in your code in places you want to debug.
1372
1373Getting this to work requires a small amount of setup.  On Unix systems
1374with X11, install the `graphviz <http://www.graphviz.org>`_ toolkit, and make
1375sure 'dot' and 'gv' are in your path.  If you are running on macOS, download
1376and install the macOS `Graphviz program
1377<http://www.pixelglow.com/graphviz/>`_ and add
1378``/Applications/Graphviz.app/Contents/MacOS/`` (or wherever you install it) to
1379your path. The programs need not be present when configuring, building or
1380running LLVM and can simply be installed when needed during an active debug
1381session.
1382
1383``SelectionDAG`` has been extended to make it easier to locate *interesting*
1384nodes in large complex graphs.  From gdb, if you ``call DAG.setGraphColor(node,
1385"color")``, then the next ``call DAG.viewGraph()`` would highlight the node in
1386the specified color (choices of colors can be found at `colors
1387<http://www.graphviz.org/doc/info/colors.html>`_.) More complex node attributes
1388can be provided with ``call DAG.setGraphAttrs(node, "attributes")`` (choices can
1389be found at `Graph attributes <http://www.graphviz.org/doc/info/attrs.html>`_.)
1390If you want to restart and clear all the current graph attributes, then you can
1391``call DAG.clearGraphAttrs()``.
1392
1393Note that graph visualization features are compiled out of Release builds to
1394reduce file size.  This means that you need a Debug+Asserts or Release+Asserts
1395build to use these features.
1396
1397.. _datastructure:
1398
1399Picking the Right Data Structure for a Task
1400===========================================
1401
1402LLVM has a plethora of data structures in the ``llvm/ADT/`` directory, and we
1403commonly use STL data structures.  This section describes the trade-offs you
1404should consider when you pick one.
1405
1406The first step is a choose your own adventure: do you want a sequential
1407container, a set-like container, or a map-like container?  The most important
1408thing when choosing a container is the algorithmic properties of how you plan to
1409access the container.  Based on that, you should use:
1410
1411
1412* a :ref:`map-like <ds_map>` container if you need efficient look-up of a
1413  value based on another value.  Map-like containers also support efficient
1414  queries for containment (whether a key is in the map).  Map-like containers
1415  generally do not support efficient reverse mapping (values to keys).  If you
1416  need that, use two maps.  Some map-like containers also support efficient
1417  iteration through the keys in sorted order.  Map-like containers are the most
1418  expensive sort, only use them if you need one of these capabilities.
1419
1420* a :ref:`set-like <ds_set>` container if you need to put a bunch of stuff into
1421  a container that automatically eliminates duplicates.  Some set-like
1422  containers support efficient iteration through the elements in sorted order.
1423  Set-like containers are more expensive than sequential containers.
1424
1425* a :ref:`sequential <ds_sequential>` container provides the most efficient way
1426  to add elements and keeps track of the order they are added to the collection.
1427  They permit duplicates and support efficient iteration, but do not support
1428  efficient look-up based on a key.
1429
1430* a :ref:`string <ds_string>` container is a specialized sequential container or
1431  reference structure that is used for character or byte arrays.
1432
1433* a :ref:`bit <ds_bit>` container provides an efficient way to store and
1434  perform set operations on sets of numeric id's, while automatically
1435  eliminating duplicates.  Bit containers require a maximum of 1 bit for each
1436  identifier you want to store.
1437
1438Once the proper category of container is determined, you can fine tune the
1439memory use, constant factors, and cache behaviors of access by intelligently
1440picking a member of the category.  Note that constant factors and cache behavior
1441can be a big deal.  If you have a vector that usually only contains a few
1442elements (but could contain many), for example, it's much better to use
1443:ref:`SmallVector <dss_smallvector>` than :ref:`vector <dss_vector>`.  Doing so
1444avoids (relatively) expensive malloc/free calls, which dwarf the cost of adding
1445the elements to the container.
1446
1447.. _ds_sequential:
1448
1449Sequential Containers (std::vector, std::list, etc)
1450---------------------------------------------------
1451
1452There are a variety of sequential containers available for you, based on your
1453needs.  Pick the first in this section that will do what you want.
1454
1455.. _dss_arrayref:
1456
1457llvm/ADT/ArrayRef.h
1458^^^^^^^^^^^^^^^^^^^
1459
1460The ``llvm::ArrayRef`` class is the preferred class to use in an interface that
1461accepts a sequential list of elements in memory and just reads from them.  By
1462taking an ``ArrayRef``, the API can be passed a fixed size array, an
1463``std::vector``, an ``llvm::SmallVector`` and anything else that is contiguous
1464in memory.
1465
1466.. _dss_fixedarrays:
1467
1468Fixed Size Arrays
1469^^^^^^^^^^^^^^^^^
1470
1471Fixed size arrays are very simple and very fast.  They are good if you know
1472exactly how many elements you have, or you have a (low) upper bound on how many
1473you have.
1474
1475.. _dss_heaparrays:
1476
1477Heap Allocated Arrays
1478^^^^^^^^^^^^^^^^^^^^^
1479
1480Heap allocated arrays (``new[]`` + ``delete[]``) are also simple.  They are good
1481if the number of elements is variable, if you know how many elements you will
1482need before the array is allocated, and if the array is usually large (if not,
1483consider a :ref:`SmallVector <dss_smallvector>`).  The cost of a heap allocated
1484array is the cost of the new/delete (aka malloc/free).  Also note that if you
1485are allocating an array of a type with a constructor, the constructor and
1486destructors will be run for every element in the array (re-sizable vectors only
1487construct those elements actually used).
1488
1489.. _dss_tinyptrvector:
1490
1491llvm/ADT/TinyPtrVector.h
1492^^^^^^^^^^^^^^^^^^^^^^^^
1493
1494``TinyPtrVector<Type>`` is a highly specialized collection class that is
1495optimized to avoid allocation in the case when a vector has zero or one
1496elements.  It has two major restrictions: 1) it can only hold values of pointer
1497type, and 2) it cannot hold a null pointer.
1498
1499Since this container is highly specialized, it is rarely used.
1500
1501.. _dss_smallvector:
1502
1503llvm/ADT/SmallVector.h
1504^^^^^^^^^^^^^^^^^^^^^^
1505
1506``SmallVector<Type, N>`` is a simple class that looks and smells just like
1507``vector<Type>``: it supports efficient iteration, lays out elements in memory
1508order (so you can do pointer arithmetic between elements), supports efficient
1509push_back/pop_back operations, supports efficient random access to its elements,
1510etc.
1511
1512The main advantage of SmallVector is that it allocates space for some number of
1513elements (N) **in the object itself**.  Because of this, if the SmallVector is
1514dynamically smaller than N, no malloc is performed.  This can be a big win in
1515cases where the malloc/free call is far more expensive than the code that
1516fiddles around with the elements.
1517
1518This is good for vectors that are "usually small" (e.g. the number of
1519predecessors/successors of a block is usually less than 8).  On the other hand,
1520this makes the size of the SmallVector itself large, so you don't want to
1521allocate lots of them (doing so will waste a lot of space).  As such,
1522SmallVectors are most useful when on the stack.
1523
1524SmallVector also provides a nice portable and efficient replacement for
1525``alloca``.
1526
1527SmallVector has grown a few other minor advantages over std::vector, causing
1528``SmallVector<Type, 0>`` to be preferred over ``std::vector<Type>``.
1529
1530#. std::vector is exception-safe, and some implementations have pessimizations
1531   that copy elements when SmallVector would move them.
1532
1533#. SmallVector understands ``llvm::is_trivially_copyable<Type>`` and uses realloc aggressively.
1534
1535#. Many LLVM APIs take a SmallVectorImpl as an out parameter (see the note
1536   below).
1537
1538#. SmallVector with N equal to 0 is smaller than std::vector on 64-bit
1539   platforms, since it uses ``unsigned`` (instead of ``void*``) for its size
1540   and capacity.
1541
1542.. note::
1543
1544   Prefer to use ``SmallVectorImpl<T>`` as a parameter type.
1545
1546   In APIs that don't care about the "small size" (most?), prefer to use
1547   the ``SmallVectorImpl<T>`` class, which is basically just the "vector
1548   header" (and methods) without the elements allocated after it. Note that
1549   ``SmallVector<T, N>`` inherits from ``SmallVectorImpl<T>`` so the
1550   conversion is implicit and costs nothing. E.g.
1551
1552   .. code-block:: c++
1553
1554      // BAD: Clients cannot pass e.g. SmallVector<Foo, 4>.
1555      hardcodedSmallSize(SmallVector<Foo, 2> &Out);
1556      // GOOD: Clients can pass any SmallVector<Foo, N>.
1557      allowsAnySmallSize(SmallVectorImpl<Foo> &Out);
1558
1559      void someFunc() {
1560        SmallVector<Foo, 8> Vec;
1561        hardcodedSmallSize(Vec); // Error.
1562        allowsAnySmallSize(Vec); // Works.
1563      }
1564
1565   Even though it has "``Impl``" in the name, this is so widely used that
1566   it really isn't "private to the implementation" anymore. A name like
1567   ``SmallVectorHeader`` would be more appropriate.
1568
1569.. _dss_vector:
1570
1571<vector>
1572^^^^^^^^
1573
1574``std::vector<T>`` is well loved and respected.  However, ``SmallVector<T, 0>``
1575is often a better option due to the advantages listed above.  std::vector is
1576still useful when you need to store more than ``UINT32_MAX`` elements or when
1577interfacing with code that expects vectors :).
1578
1579One worthwhile note about std::vector: avoid code like this:
1580
1581.. code-block:: c++
1582
1583  for ( ... ) {
1584     std::vector<foo> V;
1585     // make use of V.
1586  }
1587
1588Instead, write this as:
1589
1590.. code-block:: c++
1591
1592  std::vector<foo> V;
1593  for ( ... ) {
1594     // make use of V.
1595     V.clear();
1596  }
1597
1598Doing so will save (at least) one heap allocation and free per iteration of the
1599loop.
1600
1601.. _dss_deque:
1602
1603<deque>
1604^^^^^^^
1605
1606``std::deque`` is, in some senses, a generalized version of ``std::vector``.
1607Like ``std::vector``, it provides constant time random access and other similar
1608properties, but it also provides efficient access to the front of the list.  It
1609does not guarantee continuity of elements within memory.
1610
1611In exchange for this extra flexibility, ``std::deque`` has significantly higher
1612constant factor costs than ``std::vector``.  If possible, use ``std::vector`` or
1613something cheaper.
1614
1615.. _dss_list:
1616
1617<list>
1618^^^^^^
1619
1620``std::list`` is an extremely inefficient class that is rarely useful.  It
1621performs a heap allocation for every element inserted into it, thus having an
1622extremely high constant factor, particularly for small data types.
1623``std::list`` also only supports bidirectional iteration, not random access
1624iteration.
1625
1626In exchange for this high cost, std::list supports efficient access to both ends
1627of the list (like ``std::deque``, but unlike ``std::vector`` or
1628``SmallVector``).  In addition, the iterator invalidation characteristics of
1629std::list are stronger than that of a vector class: inserting or removing an
1630element into the list does not invalidate iterator or pointers to other elements
1631in the list.
1632
1633.. _dss_ilist:
1634
1635llvm/ADT/ilist.h
1636^^^^^^^^^^^^^^^^
1637
1638``ilist<T>`` implements an 'intrusive' doubly-linked list.  It is intrusive,
1639because it requires the element to store and provide access to the prev/next
1640pointers for the list.
1641
1642``ilist`` has the same drawbacks as ``std::list``, and additionally requires an
1643``ilist_traits`` implementation for the element type, but it provides some novel
1644characteristics.  In particular, it can efficiently store polymorphic objects,
1645the traits class is informed when an element is inserted or removed from the
1646list, and ``ilist``\ s are guaranteed to support a constant-time splice
1647operation.
1648
1649These properties are exactly what we want for things like ``Instruction``\ s and
1650basic blocks, which is why these are implemented with ``ilist``\ s.
1651
1652Related classes of interest are explained in the following subsections:
1653
1654* :ref:`ilist_traits <dss_ilist_traits>`
1655
1656* :ref:`iplist <dss_iplist>`
1657
1658* :ref:`llvm/ADT/ilist_node.h <dss_ilist_node>`
1659
1660* :ref:`Sentinels <dss_ilist_sentinel>`
1661
1662.. _dss_packedvector:
1663
1664llvm/ADT/PackedVector.h
1665^^^^^^^^^^^^^^^^^^^^^^^
1666
1667Useful for storing a vector of values using only a few number of bits for each
1668value.  Apart from the standard operations of a vector-like container, it can
1669also perform an 'or' set operation.
1670
1671For example:
1672
1673.. code-block:: c++
1674
1675  enum State {
1676      None = 0x0,
1677      FirstCondition = 0x1,
1678      SecondCondition = 0x2,
1679      Both = 0x3
1680  };
1681
1682  State get() {
1683      PackedVector<State, 2> Vec1;
1684      Vec1.push_back(FirstCondition);
1685
1686      PackedVector<State, 2> Vec2;
1687      Vec2.push_back(SecondCondition);
1688
1689      Vec1 |= Vec2;
1690      return Vec1[0]; // returns 'Both'.
1691  }
1692
1693.. _dss_ilist_traits:
1694
1695ilist_traits
1696^^^^^^^^^^^^
1697
1698``ilist_traits<T>`` is ``ilist<T>``'s customization mechanism. ``iplist<T>``
1699(and consequently ``ilist<T>``) publicly derive from this traits class.
1700
1701.. _dss_iplist:
1702
1703iplist
1704^^^^^^
1705
1706``iplist<T>`` is ``ilist<T>``'s base and as such supports a slightly narrower
1707interface.  Notably, inserters from ``T&`` are absent.
1708
1709``ilist_traits<T>`` is a public base of this class and can be used for a wide
1710variety of customizations.
1711
1712.. _dss_ilist_node:
1713
1714llvm/ADT/ilist_node.h
1715^^^^^^^^^^^^^^^^^^^^^
1716
1717``ilist_node<T>`` implements the forward and backward links that are expected
1718by the ``ilist<T>`` (and analogous containers) in the default manner.
1719
1720``ilist_node<T>``\ s are meant to be embedded in the node type ``T``, usually
1721``T`` publicly derives from ``ilist_node<T>``.
1722
1723.. _dss_ilist_sentinel:
1724
1725Sentinels
1726^^^^^^^^^
1727
1728``ilist``\ s have another specialty that must be considered.  To be a good
1729citizen in the C++ ecosystem, it needs to support the standard container
1730operations, such as ``begin`` and ``end`` iterators, etc.  Also, the
1731``operator--`` must work correctly on the ``end`` iterator in the case of
1732non-empty ``ilist``\ s.
1733
1734The only sensible solution to this problem is to allocate a so-called *sentinel*
1735along with the intrusive list, which serves as the ``end`` iterator, providing
1736the back-link to the last element.  However conforming to the C++ convention it
1737is illegal to ``operator++`` beyond the sentinel and it also must not be
1738dereferenced.
1739
1740These constraints allow for some implementation freedom to the ``ilist`` how to
1741allocate and store the sentinel.  The corresponding policy is dictated by
1742``ilist_traits<T>``.  By default a ``T`` gets heap-allocated whenever the need
1743for a sentinel arises.
1744
1745While the default policy is sufficient in most cases, it may break down when
1746``T`` does not provide a default constructor.  Also, in the case of many
1747instances of ``ilist``\ s, the memory overhead of the associated sentinels is
1748wasted.  To alleviate the situation with numerous and voluminous
1749``T``-sentinels, sometimes a trick is employed, leading to *ghostly sentinels*.
1750
1751Ghostly sentinels are obtained by specially-crafted ``ilist_traits<T>`` which
1752superpose the sentinel with the ``ilist`` instance in memory.  Pointer
1753arithmetic is used to obtain the sentinel, which is relative to the ``ilist``'s
1754``this`` pointer.  The ``ilist`` is augmented by an extra pointer, which serves
1755as the back-link of the sentinel.  This is the only field in the ghostly
1756sentinel which can be legally accessed.
1757
1758.. _dss_other:
1759
1760Other Sequential Container options
1761^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1762
1763Other STL containers are available, such as ``std::string``.
1764
1765There are also various STL adapter classes such as ``std::queue``,
1766``std::priority_queue``, ``std::stack``, etc.  These provide simplified access
1767to an underlying container but don't affect the cost of the container itself.
1768
1769.. _ds_string:
1770
1771String-like containers
1772----------------------
1773
1774There are a variety of ways to pass around and use strings in C and C++, and
1775LLVM adds a few new options to choose from.  Pick the first option on this list
1776that will do what you need, they are ordered according to their relative cost.
1777
1778Note that it is generally preferred to *not* pass strings around as ``const
1779char*``'s.  These have a number of problems, including the fact that they
1780cannot represent embedded nul ("\0") characters, and do not have a length
1781available efficiently.  The general replacement for '``const char*``' is
1782StringRef.
1783
1784For more information on choosing string containers for APIs, please see
1785:ref:`Passing Strings <string_apis>`.
1786
1787.. _dss_stringref:
1788
1789llvm/ADT/StringRef.h
1790^^^^^^^^^^^^^^^^^^^^
1791
1792The StringRef class is a simple value class that contains a pointer to a
1793character and a length, and is quite related to the :ref:`ArrayRef
1794<dss_arrayref>` class (but specialized for arrays of characters).  Because
1795StringRef carries a length with it, it safely handles strings with embedded nul
1796characters in it, getting the length does not require a strlen call, and it even
1797has very convenient APIs for slicing and dicing the character range that it
1798represents.
1799
1800StringRef is ideal for passing simple strings around that are known to be live,
1801either because they are C string literals, std::string, a C array, or a
1802SmallVector.  Each of these cases has an efficient implicit conversion to
1803StringRef, which doesn't result in a dynamic strlen being executed.
1804
1805StringRef has a few major limitations which make more powerful string containers
1806useful:
1807
1808#. You cannot directly convert a StringRef to a 'const char*' because there is
1809   no way to add a trailing nul (unlike the .c_str() method on various stronger
1810   classes).
1811
1812#. StringRef doesn't own or keep alive the underlying string bytes.
1813   As such it can easily lead to dangling pointers, and is not suitable for
1814   embedding in datastructures in most cases (instead, use an std::string or
1815   something like that).
1816
1817#. For the same reason, StringRef cannot be used as the return value of a
1818   method if the method "computes" the result string.  Instead, use std::string.
1819
1820#. StringRef's do not allow you to mutate the pointed-to string bytes and it
1821   doesn't allow you to insert or remove bytes from the range.  For editing
1822   operations like this, it interoperates with the :ref:`Twine <dss_twine>`
1823   class.
1824
1825Because of its strengths and limitations, it is very common for a function to
1826take a StringRef and for a method on an object to return a StringRef that points
1827into some string that it owns.
1828
1829.. _dss_twine:
1830
1831llvm/ADT/Twine.h
1832^^^^^^^^^^^^^^^^
1833
1834The Twine class is used as an intermediary datatype for APIs that want to take a
1835string that can be constructed inline with a series of concatenations.  Twine
1836works by forming recursive instances of the Twine datatype (a simple value
1837object) on the stack as temporary objects, linking them together into a tree
1838which is then linearized when the Twine is consumed.  Twine is only safe to use
1839as the argument to a function, and should always be a const reference, e.g.:
1840
1841.. code-block:: c++
1842
1843  void foo(const Twine &T);
1844  ...
1845  StringRef X = ...
1846  unsigned i = ...
1847  foo(X + "." + Twine(i));
1848
1849This example forms a string like "blarg.42" by concatenating the values
1850together, and does not form intermediate strings containing "blarg" or "blarg.".
1851
1852Because Twine is constructed with temporary objects on the stack, and because
1853these instances are destroyed at the end of the current statement, it is an
1854inherently dangerous API.  For example, this simple variant contains undefined
1855behavior and will probably crash:
1856
1857.. code-block:: c++
1858
1859  void foo(const Twine &T);
1860  ...
1861  StringRef X = ...
1862  unsigned i = ...
1863  const Twine &Tmp = X + "." + Twine(i);
1864  foo(Tmp);
1865
1866... because the temporaries are destroyed before the call.  That said, Twine's
1867are much more efficient than intermediate std::string temporaries, and they work
1868really well with StringRef.  Just be aware of their limitations.
1869
1870.. _dss_smallstring:
1871
1872llvm/ADT/SmallString.h
1873^^^^^^^^^^^^^^^^^^^^^^
1874
1875SmallString is a subclass of :ref:`SmallVector <dss_smallvector>` that adds some
1876convenience APIs like += that takes StringRef's.  SmallString avoids allocating
1877memory in the case when the preallocated space is enough to hold its data, and
1878it calls back to general heap allocation when required.  Since it owns its data,
1879it is very safe to use and supports full mutation of the string.
1880
1881Like SmallVector's, the big downside to SmallString is their sizeof.  While they
1882are optimized for small strings, they themselves are not particularly small.
1883This means that they work great for temporary scratch buffers on the stack, but
1884should not generally be put into the heap: it is very rare to see a SmallString
1885as the member of a frequently-allocated heap data structure or returned
1886by-value.
1887
1888.. _dss_stdstring:
1889
1890std::string
1891^^^^^^^^^^^
1892
1893The standard C++ std::string class is a very general class that (like
1894SmallString) owns its underlying data.  sizeof(std::string) is very reasonable
1895so it can be embedded into heap data structures and returned by-value.  On the
1896other hand, std::string is highly inefficient for inline editing (e.g.
1897concatenating a bunch of stuff together) and because it is provided by the
1898standard library, its performance characteristics depend a lot of the host
1899standard library (e.g. libc++ and MSVC provide a highly optimized string class,
1900GCC contains a really slow implementation).
1901
1902The major disadvantage of std::string is that almost every operation that makes
1903them larger can allocate memory, which is slow.  As such, it is better to use
1904SmallVector or Twine as a scratch buffer, but then use std::string to persist
1905the result.
1906
1907.. _ds_set:
1908
1909Set-Like Containers (std::set, SmallSet, SetVector, etc)
1910--------------------------------------------------------
1911
1912Set-like containers are useful when you need to canonicalize multiple values
1913into a single representation.  There are several different choices for how to do
1914this, providing various trade-offs.
1915
1916.. _dss_sortedvectorset:
1917
1918A sorted 'vector'
1919^^^^^^^^^^^^^^^^^
1920
1921If you intend to insert a lot of elements, then do a lot of queries, a great
1922approach is to use an std::vector (or other sequential container) with
1923std::sort+std::unique to remove duplicates.  This approach works really well if
1924your usage pattern has these two distinct phases (insert then query), and can be
1925coupled with a good choice of :ref:`sequential container <ds_sequential>`.
1926
1927This combination provides the several nice properties: the result data is
1928contiguous in memory (good for cache locality), has few allocations, is easy to
1929address (iterators in the final vector are just indices or pointers), and can be
1930efficiently queried with a standard binary search (e.g.
1931``std::lower_bound``; if you want the whole range of elements comparing
1932equal, use ``std::equal_range``).
1933
1934.. _dss_smallset:
1935
1936llvm/ADT/SmallSet.h
1937^^^^^^^^^^^^^^^^^^^
1938
1939If you have a set-like data structure that is usually small and whose elements
1940are reasonably small, a ``SmallSet<Type, N>`` is a good choice.  This set has
1941space for N elements in place (thus, if the set is dynamically smaller than N,
1942no malloc traffic is required) and accesses them with a simple linear search.
1943When the set grows beyond N elements, it allocates a more expensive
1944representation that guarantees efficient access (for most types, it falls back
1945to :ref:`std::set <dss_set>`, but for pointers it uses something far better,
1946:ref:`SmallPtrSet <dss_smallptrset>`.
1947
1948The magic of this class is that it handles small sets extremely efficiently, but
1949gracefully handles extremely large sets without loss of efficiency.
1950
1951.. _dss_smallptrset:
1952
1953llvm/ADT/SmallPtrSet.h
1954^^^^^^^^^^^^^^^^^^^^^^
1955
1956``SmallPtrSet`` has all the advantages of ``SmallSet`` (and a ``SmallSet`` of
1957pointers is transparently implemented with a ``SmallPtrSet``). If more than N
1958insertions are performed, a single quadratically probed hash table is allocated
1959and grows as needed, providing extremely efficient access (constant time
1960insertion/deleting/queries with low constant factors) and is very stingy with
1961malloc traffic.
1962
1963Note that, unlike :ref:`std::set <dss_set>`, the iterators of ``SmallPtrSet``
1964are invalidated whenever an insertion occurs.  Also, the values visited by the
1965iterators are not visited in sorted order.
1966
1967.. _dss_stringset:
1968
1969llvm/ADT/StringSet.h
1970^^^^^^^^^^^^^^^^^^^^
1971
1972``StringSet`` is a thin wrapper around :ref:`StringMap\<char\> <dss_stringmap>`,
1973and it allows efficient storage and retrieval of unique strings.
1974
1975Functionally analogous to ``SmallSet<StringRef>``, ``StringSet`` also supports
1976iteration. (The iterator dereferences to a ``StringMapEntry<char>``, so you
1977need to call ``i->getKey()`` to access the item of the StringSet.)  On the
1978other hand, ``StringSet`` doesn't support range-insertion and
1979copy-construction, which :ref:`SmallSet <dss_smallset>` and :ref:`SmallPtrSet
1980<dss_smallptrset>` do support.
1981
1982.. _dss_denseset:
1983
1984llvm/ADT/DenseSet.h
1985^^^^^^^^^^^^^^^^^^^
1986
1987DenseSet is a simple quadratically probed hash table.  It excels at supporting
1988small values: it uses a single allocation to hold all of the pairs that are
1989currently inserted in the set.  DenseSet is a great way to unique small values
1990that are not simple pointers (use :ref:`SmallPtrSet <dss_smallptrset>` for
1991pointers).  Note that DenseSet has the same requirements for the value type that
1992:ref:`DenseMap <dss_densemap>` has.
1993
1994.. _dss_sparseset:
1995
1996llvm/ADT/SparseSet.h
1997^^^^^^^^^^^^^^^^^^^^
1998
1999SparseSet holds a small number of objects identified by unsigned keys of
2000moderate size.  It uses a lot of memory, but provides operations that are almost
2001as fast as a vector.  Typical keys are physical registers, virtual registers, or
2002numbered basic blocks.
2003
2004SparseSet is useful for algorithms that need very fast clear/find/insert/erase
2005and fast iteration over small sets.  It is not intended for building composite
2006data structures.
2007
2008.. _dss_sparsemultiset:
2009
2010llvm/ADT/SparseMultiSet.h
2011^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2012
2013SparseMultiSet adds multiset behavior to SparseSet, while retaining SparseSet's
2014desirable attributes. Like SparseSet, it typically uses a lot of memory, but
2015provides operations that are almost as fast as a vector.  Typical keys are
2016physical registers, virtual registers, or numbered basic blocks.
2017
2018SparseMultiSet is useful for algorithms that need very fast
2019clear/find/insert/erase of the entire collection, and iteration over sets of
2020elements sharing a key. It is often a more efficient choice than using composite
2021data structures (e.g. vector-of-vectors, map-of-vectors). It is not intended for
2022building composite data structures.
2023
2024.. _dss_FoldingSet:
2025
2026llvm/ADT/FoldingSet.h
2027^^^^^^^^^^^^^^^^^^^^^
2028
2029FoldingSet is an aggregate class that is really good at uniquing
2030expensive-to-create or polymorphic objects.  It is a combination of a chained
2031hash table with intrusive links (uniqued objects are required to inherit from
2032FoldingSetNode) that uses :ref:`SmallVector <dss_smallvector>` as part of its ID
2033process.
2034
2035Consider a case where you want to implement a "getOrCreateFoo" method for a
2036complex object (for example, a node in the code generator).  The client has a
2037description of **what** it wants to generate (it knows the opcode and all the
2038operands), but we don't want to 'new' a node, then try inserting it into a set
2039only to find out it already exists, at which point we would have to delete it
2040and return the node that already exists.
2041
2042To support this style of client, FoldingSet perform a query with a
2043FoldingSetNodeID (which wraps SmallVector) that can be used to describe the
2044element that we want to query for.  The query either returns the element
2045matching the ID or it returns an opaque ID that indicates where insertion should
2046take place.  Construction of the ID usually does not require heap traffic.
2047
2048Because FoldingSet uses intrusive links, it can support polymorphic objects in
2049the set (for example, you can have SDNode instances mixed with LoadSDNodes).
2050Because the elements are individually allocated, pointers to the elements are
2051stable: inserting or removing elements does not invalidate any pointers to other
2052elements.
2053
2054.. _dss_set:
2055
2056<set>
2057^^^^^
2058
2059``std::set`` is a reasonable all-around set class, which is decent at many
2060things but great at nothing.  std::set allocates memory for each element
2061inserted (thus it is very malloc intensive) and typically stores three pointers
2062per element in the set (thus adding a large amount of per-element space
2063overhead).  It offers guaranteed log(n) performance, which is not particularly
2064fast from a complexity standpoint (particularly if the elements of the set are
2065expensive to compare, like strings), and has extremely high constant factors for
2066lookup, insertion and removal.
2067
2068The advantages of std::set are that its iterators are stable (deleting or
2069inserting an element from the set does not affect iterators or pointers to other
2070elements) and that iteration over the set is guaranteed to be in sorted order.
2071If the elements in the set are large, then the relative overhead of the pointers
2072and malloc traffic is not a big deal, but if the elements of the set are small,
2073std::set is almost never a good choice.
2074
2075.. _dss_setvector:
2076
2077llvm/ADT/SetVector.h
2078^^^^^^^^^^^^^^^^^^^^
2079
2080LLVM's ``SetVector<Type>`` is an adapter class that combines your choice of a
2081set-like container along with a :ref:`Sequential Container <ds_sequential>` The
2082important property that this provides is efficient insertion with uniquing
2083(duplicate elements are ignored) with iteration support.  It implements this by
2084inserting elements into both a set-like container and the sequential container,
2085using the set-like container for uniquing and the sequential container for
2086iteration.
2087
2088The difference between SetVector and other sets is that the order of iteration
2089is guaranteed to match the order of insertion into the SetVector.  This property
2090is really important for things like sets of pointers.  Because pointer values
2091are non-deterministic (e.g. vary across runs of the program on different
2092machines), iterating over the pointers in the set will not be in a well-defined
2093order.
2094
2095The drawback of SetVector is that it requires twice as much space as a normal
2096set and has the sum of constant factors from the set-like container and the
2097sequential container that it uses.  Use it **only** if you need to iterate over
2098the elements in a deterministic order.  SetVector is also expensive to delete
2099elements out of (linear time), unless you use its "pop_back" method, which is
2100faster.
2101
2102``SetVector`` is an adapter class that defaults to using ``std::vector`` and a
2103size 16 ``SmallSet`` for the underlying containers, so it is quite expensive.
2104However, ``"llvm/ADT/SetVector.h"`` also provides a ``SmallSetVector`` class,
2105which defaults to using a ``SmallVector`` and ``SmallSet`` of a specified size.
2106If you use this, and if your sets are dynamically smaller than ``N``, you will
2107save a lot of heap traffic.
2108
2109.. _dss_uniquevector:
2110
2111llvm/ADT/UniqueVector.h
2112^^^^^^^^^^^^^^^^^^^^^^^
2113
2114UniqueVector is similar to :ref:`SetVector <dss_setvector>` but it retains a
2115unique ID for each element inserted into the set.  It internally contains a map
2116and a vector, and it assigns a unique ID for each value inserted into the set.
2117
2118UniqueVector is very expensive: its cost is the sum of the cost of maintaining
2119both the map and vector, it has high complexity, high constant factors, and
2120produces a lot of malloc traffic.  It should be avoided.
2121
2122.. _dss_immutableset:
2123
2124llvm/ADT/ImmutableSet.h
2125^^^^^^^^^^^^^^^^^^^^^^^
2126
2127ImmutableSet is an immutable (functional) set implementation based on an AVL
2128tree.  Adding or removing elements is done through a Factory object and results
2129in the creation of a new ImmutableSet object.  If an ImmutableSet already exists
2130with the given contents, then the existing one is returned; equality is compared
2131with a FoldingSetNodeID.  The time and space complexity of add or remove
2132operations is logarithmic in the size of the original set.
2133
2134There is no method for returning an element of the set, you can only check for
2135membership.
2136
2137.. _dss_otherset:
2138
2139Other Set-Like Container Options
2140^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2141
2142The STL provides several other options, such as std::multiset and the various
2143"hash_set" like containers (whether from C++ TR1 or from the SGI library).  We
2144never use hash_set and unordered_set because they are generally very expensive
2145(each insertion requires a malloc) and very non-portable.
2146
2147std::multiset is useful if you're not interested in elimination of duplicates,
2148but has all the drawbacks of :ref:`std::set <dss_set>`.  A sorted vector
2149(where you don't delete duplicate entries) or some other approach is almost
2150always better.
2151
2152.. _ds_map:
2153
2154Map-Like Containers (std::map, DenseMap, etc)
2155---------------------------------------------
2156
2157Map-like containers are useful when you want to associate data to a key.  As
2158usual, there are a lot of different ways to do this. :)
2159
2160.. _dss_sortedvectormap:
2161
2162A sorted 'vector'
2163^^^^^^^^^^^^^^^^^
2164
2165If your usage pattern follows a strict insert-then-query approach, you can
2166trivially use the same approach as :ref:`sorted vectors for set-like containers
2167<dss_sortedvectorset>`.  The only difference is that your query function (which
2168uses std::lower_bound to get efficient log(n) lookup) should only compare the
2169key, not both the key and value.  This yields the same advantages as sorted
2170vectors for sets.
2171
2172.. _dss_stringmap:
2173
2174llvm/ADT/StringMap.h
2175^^^^^^^^^^^^^^^^^^^^
2176
2177Strings are commonly used as keys in maps, and they are difficult to support
2178efficiently: they are variable length, inefficient to hash and compare when
2179long, expensive to copy, etc.  StringMap is a specialized container designed to
2180cope with these issues.  It supports mapping an arbitrary range of bytes to an
2181arbitrary other object.
2182
2183The StringMap implementation uses a quadratically-probed hash table, where the
2184buckets store a pointer to the heap allocated entries (and some other stuff).
2185The entries in the map must be heap allocated because the strings are variable
2186length.  The string data (key) and the element object (value) are stored in the
2187same allocation with the string data immediately after the element object.
2188This container guarantees the "``(char*)(&Value+1)``" points to the key string
2189for a value.
2190
2191The StringMap is very fast for several reasons: quadratic probing is very cache
2192efficient for lookups, the hash value of strings in buckets is not recomputed
2193when looking up an element, StringMap rarely has to touch the memory for
2194unrelated objects when looking up a value (even when hash collisions happen),
2195hash table growth does not recompute the hash values for strings already in the
2196table, and each pair in the map is store in a single allocation (the string data
2197is stored in the same allocation as the Value of a pair).
2198
2199StringMap also provides query methods that take byte ranges, so it only ever
2200copies a string if a value is inserted into the table.
2201
2202StringMap iteration order, however, is not guaranteed to be deterministic, so
2203any uses which require that should instead use a std::map.
2204
2205.. _dss_indexmap:
2206
2207llvm/ADT/IndexedMap.h
2208^^^^^^^^^^^^^^^^^^^^^
2209
2210IndexedMap is a specialized container for mapping small dense integers (or
2211values that can be mapped to small dense integers) to some other type.  It is
2212internally implemented as a vector with a mapping function that maps the keys
2213to the dense integer range.
2214
2215This is useful for cases like virtual registers in the LLVM code generator: they
2216have a dense mapping that is offset by a compile-time constant (the first
2217virtual register ID).
2218
2219.. _dss_densemap:
2220
2221llvm/ADT/DenseMap.h
2222^^^^^^^^^^^^^^^^^^^
2223
2224DenseMap is a simple quadratically probed hash table.  It excels at supporting
2225small keys and values: it uses a single allocation to hold all of the pairs
2226that are currently inserted in the map.  DenseMap is a great way to map
2227pointers to pointers, or map other small types to each other.
2228
2229There are several aspects of DenseMap that you should be aware of, however.
2230The iterators in a DenseMap are invalidated whenever an insertion occurs,
2231unlike map.  Also, because DenseMap allocates space for a large number of
2232key/value pairs (it starts with 64 by default), it will waste a lot of space if
2233your keys or values are large.  Finally, you must implement a partial
2234specialization of DenseMapInfo for the key that you want, if it isn't already
2235supported.  This is required to tell DenseMap about two special marker values
2236(which can never be inserted into the map) that it needs internally.
2237
2238DenseMap's find_as() method supports lookup operations using an alternate key
2239type.  This is useful in cases where the normal key type is expensive to
2240construct, but cheap to compare against.  The DenseMapInfo is responsible for
2241defining the appropriate comparison and hashing methods for each alternate key
2242type used.
2243
2244.. _dss_valuemap:
2245
2246llvm/IR/ValueMap.h
2247^^^^^^^^^^^^^^^^^^^
2248
2249ValueMap is a wrapper around a :ref:`DenseMap <dss_densemap>` mapping
2250``Value*``\ s (or subclasses) to another type.  When a Value is deleted or
2251RAUW'ed, ValueMap will update itself so the new version of the key is mapped to
2252the same value, just as if the key were a WeakVH.  You can configure exactly how
2253this happens, and what else happens on these two events, by passing a ``Config``
2254parameter to the ValueMap template.
2255
2256.. _dss_intervalmap:
2257
2258llvm/ADT/IntervalMap.h
2259^^^^^^^^^^^^^^^^^^^^^^
2260
2261IntervalMap is a compact map for small keys and values.  It maps key intervals
2262instead of single keys, and it will automatically coalesce adjacent intervals.
2263When the map only contains a few intervals, they are stored in the map object
2264itself to avoid allocations.
2265
2266The IntervalMap iterators are quite big, so they should not be passed around as
2267STL iterators.  The heavyweight iterators allow a smaller data structure.
2268
2269.. _dss_map:
2270
2271<map>
2272^^^^^
2273
2274std::map has similar characteristics to :ref:`std::set <dss_set>`: it uses a
2275single allocation per pair inserted into the map, it offers log(n) lookup with
2276an extremely large constant factor, imposes a space penalty of 3 pointers per
2277pair in the map, etc.
2278
2279std::map is most useful when your keys or values are very large, if you need to
2280iterate over the collection in sorted order, or if you need stable iterators
2281into the map (i.e. they don't get invalidated if an insertion or deletion of
2282another element takes place).
2283
2284.. _dss_mapvector:
2285
2286llvm/ADT/MapVector.h
2287^^^^^^^^^^^^^^^^^^^^
2288
2289``MapVector<KeyT,ValueT>`` provides a subset of the DenseMap interface.  The
2290main difference is that the iteration order is guaranteed to be the insertion
2291order, making it an easy (but somewhat expensive) solution for non-deterministic
2292iteration over maps of pointers.
2293
2294It is implemented by mapping from key to an index in a vector of key,value
2295pairs.  This provides fast lookup and iteration, but has two main drawbacks:
2296the key is stored twice and removing elements takes linear time.  If it is
2297necessary to remove elements, it's best to remove them in bulk using
2298``remove_if()``.
2299
2300.. _dss_inteqclasses:
2301
2302llvm/ADT/IntEqClasses.h
2303^^^^^^^^^^^^^^^^^^^^^^^
2304
2305IntEqClasses provides a compact representation of equivalence classes of small
2306integers.  Initially, each integer in the range 0..n-1 has its own equivalence
2307class.  Classes can be joined by passing two class representatives to the
2308join(a, b) method.  Two integers are in the same class when findLeader() returns
2309the same representative.
2310
2311Once all equivalence classes are formed, the map can be compressed so each
2312integer 0..n-1 maps to an equivalence class number in the range 0..m-1, where m
2313is the total number of equivalence classes.  The map must be uncompressed before
2314it can be edited again.
2315
2316.. _dss_immutablemap:
2317
2318llvm/ADT/ImmutableMap.h
2319^^^^^^^^^^^^^^^^^^^^^^^
2320
2321ImmutableMap is an immutable (functional) map implementation based on an AVL
2322tree.  Adding or removing elements is done through a Factory object and results
2323in the creation of a new ImmutableMap object.  If an ImmutableMap already exists
2324with the given key set, then the existing one is returned; equality is compared
2325with a FoldingSetNodeID.  The time and space complexity of add or remove
2326operations is logarithmic in the size of the original map.
2327
2328.. _dss_othermap:
2329
2330Other Map-Like Container Options
2331^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2332
2333The STL provides several other options, such as std::multimap and the various
2334"hash_map" like containers (whether from C++ TR1 or from the SGI library).  We
2335never use hash_set and unordered_set because they are generally very expensive
2336(each insertion requires a malloc) and very non-portable.
2337
2338std::multimap is useful if you want to map a key to multiple values, but has all
2339the drawbacks of std::map.  A sorted vector or some other approach is almost
2340always better.
2341
2342.. _ds_bit:
2343
2344Bit storage containers (BitVector, SparseBitVector, CoalescingBitVector)
2345------------------------------------------------------------------------
2346
2347There are three bit storage containers, and choosing when to use each is
2348relatively straightforward.
2349
2350One additional option is ``std::vector<bool>``: we discourage its use for two
2351reasons 1) the implementation in many common compilers (e.g.  commonly
2352available versions of GCC) is extremely inefficient and 2) the C++ standards
2353committee is likely to deprecate this container and/or change it significantly
2354somehow.  In any case, please don't use it.
2355
2356.. _dss_bitvector:
2357
2358BitVector
2359^^^^^^^^^
2360
2361The BitVector container provides a dynamic size set of bits for manipulation.
2362It supports individual bit setting/testing, as well as set operations.  The set
2363operations take time O(size of bitvector), but operations are performed one word
2364at a time, instead of one bit at a time.  This makes the BitVector very fast for
2365set operations compared to other containers.  Use the BitVector when you expect
2366the number of set bits to be high (i.e. a dense set).
2367
2368.. _dss_smallbitvector:
2369
2370SmallBitVector
2371^^^^^^^^^^^^^^
2372
2373The SmallBitVector container provides the same interface as BitVector, but it is
2374optimized for the case where only a small number of bits, less than 25 or so,
2375are needed.  It also transparently supports larger bit counts, but slightly less
2376efficiently than a plain BitVector, so SmallBitVector should only be used when
2377larger counts are rare.
2378
2379At this time, SmallBitVector does not support set operations (and, or, xor), and
2380its operator[] does not provide an assignable lvalue.
2381
2382.. _dss_sparsebitvector:
2383
2384SparseBitVector
2385^^^^^^^^^^^^^^^
2386
2387The SparseBitVector container is much like BitVector, with one major difference:
2388Only the bits that are set, are stored.  This makes the SparseBitVector much
2389more space efficient than BitVector when the set is sparse, as well as making
2390set operations O(number of set bits) instead of O(size of universe).  The
2391downside to the SparseBitVector is that setting and testing of random bits is
2392O(N), and on large SparseBitVectors, this can be slower than BitVector.  In our
2393implementation, setting or testing bits in sorted order (either forwards or
2394reverse) is O(1) worst case.  Testing and setting bits within 128 bits (depends
2395on size) of the current bit is also O(1).  As a general statement,
2396testing/setting bits in a SparseBitVector is O(distance away from last set bit).
2397
2398.. _dss_coalescingbitvector:
2399
2400CoalescingBitVector
2401^^^^^^^^^^^^^^^^^^^
2402
2403The CoalescingBitVector container is similar in principle to a SparseBitVector,
2404but is optimized to represent large contiguous ranges of set bits compactly. It
2405does this by coalescing contiguous ranges of set bits into intervals. Searching
2406for a bit in a CoalescingBitVector is O(log(gaps between contiguous ranges)).
2407
2408CoalescingBitVector is a better choice than BitVector when gaps between ranges
2409of set bits are large. It's a better choice than SparseBitVector when find()
2410operations must have fast, predictable performance. However, it's not a good
2411choice for representing sets which have lots of very short ranges. E.g. the set
2412`{2*x : x \in [0, n)}` would be a pathological input.
2413
2414.. _debugging:
2415
2416Debugging
2417=========
2418
2419A handful of `GDB pretty printers
2420<https://sourceware.org/gdb/onlinedocs/gdb/Pretty-Printing.html>`__ are
2421provided for some of the core LLVM libraries. To use them, execute the
2422following (or add it to your ``~/.gdbinit``)::
2423
2424  source /path/to/llvm/src/utils/gdb-scripts/prettyprinters.py
2425
2426It also might be handy to enable the `print pretty
2427<http://ftp.gnu.org/old-gnu/Manuals/gdb/html_node/gdb_57.html>`__ option to
2428avoid data structures being printed as a big block of text.
2429
2430.. _common:
2431
2432Helpful Hints for Common Operations
2433===================================
2434
2435This section describes how to perform some very simple transformations of LLVM
2436code.  This is meant to give examples of common idioms used, showing the
2437practical side of LLVM transformations.
2438
2439Because this is a "how-to" section, you should also read about the main classes
2440that you will be working with.  The :ref:`Core LLVM Class Hierarchy Reference
2441<coreclasses>` contains details and descriptions of the main classes that you
2442should know about.
2443
2444.. _inspection:
2445
2446Basic Inspection and Traversal Routines
2447---------------------------------------
2448
2449The LLVM compiler infrastructure have many different data structures that may be
2450traversed.  Following the example of the C++ standard template library, the
2451techniques used to traverse these various data structures are all basically the
2452same.  For a enumerable sequence of values, the ``XXXbegin()`` function (or
2453method) returns an iterator to the start of the sequence, the ``XXXend()``
2454function returns an iterator pointing to one past the last valid element of the
2455sequence, and there is some ``XXXiterator`` data type that is common between the
2456two operations.
2457
2458Because the pattern for iteration is common across many different aspects of the
2459program representation, the standard template library algorithms may be used on
2460them, and it is easier to remember how to iterate.  First we show a few common
2461examples of the data structures that need to be traversed.  Other data
2462structures are traversed in very similar ways.
2463
2464.. _iterate_function:
2465
2466Iterating over the ``BasicBlock`` in a ``Function``
2467^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2468
2469It's quite common to have a ``Function`` instance that you'd like to transform
2470in some way; in particular, you'd like to manipulate its ``BasicBlock``\ s.  To
2471facilitate this, you'll need to iterate over all of the ``BasicBlock``\ s that
2472constitute the ``Function``.  The following is an example that prints the name
2473of a ``BasicBlock`` and the number of ``Instruction``\ s it contains:
2474
2475.. code-block:: c++
2476
2477  Function &Func = ...
2478  for (BasicBlock &BB : Func)
2479    // Print out the name of the basic block if it has one, and then the
2480    // number of instructions that it contains
2481    errs() << "Basic block (name=" << BB.getName() << ") has "
2482               << BB.size() << " instructions.\n";
2483
2484.. _iterate_basicblock:
2485
2486Iterating over the ``Instruction`` in a ``BasicBlock``
2487^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2488
2489Just like when dealing with ``BasicBlock``\ s in ``Function``\ s, it's easy to
2490iterate over the individual instructions that make up ``BasicBlock``\ s.  Here's
2491a code snippet that prints out each instruction in a ``BasicBlock``:
2492
2493.. code-block:: c++
2494
2495  BasicBlock& BB = ...
2496  for (Instruction &I : BB)
2497     // The next statement works since operator<<(ostream&,...)
2498     // is overloaded for Instruction&
2499     errs() << I << "\n";
2500
2501
2502However, this isn't really the best way to print out the contents of a
2503``BasicBlock``!  Since the ostream operators are overloaded for virtually
2504anything you'll care about, you could have just invoked the print routine on the
2505basic block itself: ``errs() << BB << "\n";``.
2506
2507.. _iterate_insiter:
2508
2509Iterating over the ``Instruction`` in a ``Function``
2510^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2511
2512If you're finding that you commonly iterate over a ``Function``'s
2513``BasicBlock``\ s and then that ``BasicBlock``'s ``Instruction``\ s,
2514``InstIterator`` should be used instead.  You'll need to include
2515``llvm/IR/InstIterator.h`` (`doxygen
2516<https://llvm.org/doxygen/InstIterator_8h.html>`__) and then instantiate
2517``InstIterator``\ s explicitly in your code.  Here's a small example that shows
2518how to dump all instructions in a function to the standard error stream:
2519
2520.. code-block:: c++
2521
2522  #include "llvm/IR/InstIterator.h"
2523
2524  // F is a pointer to a Function instance
2525  for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2526    errs() << *I << "\n";
2527
2528Easy, isn't it?  You can also use ``InstIterator``\ s to fill a work list with
2529its initial contents.  For example, if you wanted to initialize a work list to
2530contain all instructions in a ``Function`` F, all you would need to do is
2531something like:
2532
2533.. code-block:: c++
2534
2535  std::set<Instruction*> worklist;
2536  // or better yet, SmallPtrSet<Instruction*, 64> worklist;
2537
2538  for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2539    worklist.insert(&*I);
2540
2541The STL set ``worklist`` would now contain all instructions in the ``Function``
2542pointed to by F.
2543
2544.. _iterate_convert:
2545
2546Turning an iterator into a class pointer (and vice-versa)
2547^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2548
2549Sometimes, it'll be useful to grab a reference (or pointer) to a class instance
2550when all you've got at hand is an iterator.  Well, extracting a reference or a
2551pointer from an iterator is very straight-forward.  Assuming that ``i`` is a
2552``BasicBlock::iterator`` and ``j`` is a ``BasicBlock::const_iterator``:
2553
2554.. code-block:: c++
2555
2556  Instruction& inst = *i;   // Grab reference to instruction reference
2557  Instruction* pinst = &*i; // Grab pointer to instruction reference
2558  const Instruction& inst = *j;
2559
2560However, the iterators you'll be working with in the LLVM framework are special:
2561they will automatically convert to a ptr-to-instance type whenever they need to.
2562Instead of dereferencing the iterator and then taking the address of the result,
2563you can simply assign the iterator to the proper pointer type and you get the
2564dereference and address-of operation as a result of the assignment (behind the
2565scenes, this is a result of overloading casting mechanisms).  Thus the second
2566line of the last example,
2567
2568.. code-block:: c++
2569
2570  Instruction *pinst = &*i;
2571
2572is semantically equivalent to
2573
2574.. code-block:: c++
2575
2576  Instruction *pinst = i;
2577
2578It's also possible to turn a class pointer into the corresponding iterator, and
2579this is a constant time operation (very efficient).  The following code snippet
2580illustrates use of the conversion constructors provided by LLVM iterators.  By
2581using these, you can explicitly grab the iterator of something without actually
2582obtaining it via iteration over some structure:
2583
2584.. code-block:: c++
2585
2586  void printNextInstruction(Instruction* inst) {
2587    BasicBlock::iterator it(inst);
2588    ++it; // After this line, it refers to the instruction after *inst
2589    if (it != inst->getParent()->end()) errs() << *it << "\n";
2590  }
2591
2592Unfortunately, these implicit conversions come at a cost; they prevent these
2593iterators from conforming to standard iterator conventions, and thus from being
2594usable with standard algorithms and containers.  For example, they prevent the
2595following code, where ``B`` is a ``BasicBlock``, from compiling:
2596
2597.. code-block:: c++
2598
2599  llvm::SmallVector<llvm::Instruction *, 16>(B->begin(), B->end());
2600
2601Because of this, these implicit conversions may be removed some day, and
2602``operator*`` changed to return a pointer instead of a reference.
2603
2604.. _iterate_complex:
2605
2606Finding call sites: a slightly more complex example
2607^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2608
2609Say that you're writing a FunctionPass and would like to count all the locations
2610in the entire module (that is, across every ``Function``) where a certain
2611function (i.e., some ``Function *``) is already in scope.  As you'll learn
2612later, you may want to use an ``InstVisitor`` to accomplish this in a much more
2613straight-forward manner, but this example will allow us to explore how you'd do
2614it if you didn't have ``InstVisitor`` around.  In pseudo-code, this is what we
2615want to do:
2616
2617.. code-block:: none
2618
2619  initialize callCounter to zero
2620  for each Function f in the Module
2621    for each BasicBlock b in f
2622      for each Instruction i in b
2623        if (i is a CallInst and calls the given function)
2624          increment callCounter
2625
2626And the actual code is (remember, because we're writing a ``FunctionPass``, our
2627``FunctionPass``-derived class simply has to override the ``runOnFunction``
2628method):
2629
2630.. code-block:: c++
2631
2632  Function* targetFunc = ...;
2633
2634  class OurFunctionPass : public FunctionPass {
2635    public:
2636      OurFunctionPass(): callCounter(0) { }
2637
2638      virtual runOnFunction(Function& F) {
2639        for (BasicBlock &B : F) {
2640          for (Instruction &I: B) {
2641            if (auto *CallInst = dyn_cast<CallInst>(&I)) {
2642              // We know we've encountered a call instruction, so we
2643              // need to determine if it's a call to the
2644              // function pointed to by m_func or not.
2645              if (CallInst->getCalledFunction() == targetFunc)
2646                ++callCounter;
2647            }
2648          }
2649        }
2650      }
2651
2652    private:
2653      unsigned callCounter;
2654  };
2655
2656.. _calls_and_invokes:
2657
2658Treating calls and invokes the same way
2659^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2660
2661You may have noticed that the previous example was a bit oversimplified in that
2662it did not deal with call sites generated by 'invoke' instructions.  In this,
2663and in other situations, you may find that you want to treat ``CallInst``\ s and
2664``InvokeInst``\ s the same way, even though their most-specific common base
2665class is ``Instruction``, which includes lots of less closely-related things.
2666For these cases, LLVM provides a handy wrapper class called ``CallSite``
2667(`doxygen <https://llvm.org/doxygen/classllvm_1_1CallSite.html>`__) It is
2668essentially a wrapper around an ``Instruction`` pointer, with some methods that
2669provide functionality common to ``CallInst``\ s and ``InvokeInst``\ s.
2670
2671This class has "value semantics": it should be passed by value, not by reference
2672and it should not be dynamically allocated or deallocated using ``operator new``
2673or ``operator delete``.  It is efficiently copyable, assignable and
2674constructable, with costs equivalents to that of a bare pointer.  If you look at
2675its definition, it has only a single pointer member.
2676
2677.. _iterate_chains:
2678
2679Iterating over def-use & use-def chains
2680^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2681
2682Frequently, we might have an instance of the ``Value`` class (`doxygen
2683<https://llvm.org/doxygen/classllvm_1_1Value.html>`__) and we want to determine
2684which ``User``\ s use the ``Value``.  The list of all ``User``\ s of a particular
2685``Value`` is called a *def-use* chain.  For example, let's say we have a
2686``Function*`` named ``F`` to a particular function ``foo``.  Finding all of the
2687instructions that *use* ``foo`` is as simple as iterating over the *def-use*
2688chain of ``F``:
2689
2690.. code-block:: c++
2691
2692  Function *F = ...;
2693
2694  for (User *U : F->users()) {
2695    if (Instruction *Inst = dyn_cast<Instruction>(U)) {
2696      errs() << "F is used in instruction:\n";
2697      errs() << *Inst << "\n";
2698    }
2699
2700Alternatively, it's common to have an instance of the ``User`` Class (`doxygen
2701<https://llvm.org/doxygen/classllvm_1_1User.html>`__) and need to know what
2702``Value``\ s are used by it.  The list of all ``Value``\ s used by a ``User`` is
2703known as a *use-def* chain.  Instances of class ``Instruction`` are common
2704``User`` s, so we might want to iterate over all of the values that a particular
2705instruction uses (that is, the operands of the particular ``Instruction``):
2706
2707.. code-block:: c++
2708
2709  Instruction *pi = ...;
2710
2711  for (Use &U : pi->operands()) {
2712    Value *v = U.get();
2713    // ...
2714  }
2715
2716Declaring objects as ``const`` is an important tool of enforcing mutation free
2717algorithms (such as analyses, etc.).  For this purpose above iterators come in
2718constant flavors as ``Value::const_use_iterator`` and
2719``Value::const_op_iterator``.  They automatically arise when calling
2720``use/op_begin()`` on ``const Value*``\ s or ``const User*``\ s respectively.
2721Upon dereferencing, they return ``const Use*``\ s.  Otherwise the above patterns
2722remain unchanged.
2723
2724.. _iterate_preds:
2725
2726Iterating over predecessors & successors of blocks
2727^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2728
2729Iterating over the predecessors and successors of a block is quite easy with the
2730routines defined in ``"llvm/IR/CFG.h"``.  Just use code like this to
2731iterate over all predecessors of BB:
2732
2733.. code-block:: c++
2734
2735  #include "llvm/IR/CFG.h"
2736  BasicBlock *BB = ...;
2737
2738  for (BasicBlock *Pred : predecessors(BB)) {
2739    // ...
2740  }
2741
2742Similarly, to iterate over successors use ``successors``.
2743
2744.. _simplechanges:
2745
2746Making simple changes
2747---------------------
2748
2749There are some primitive transformation operations present in the LLVM
2750infrastructure that are worth knowing about.  When performing transformations,
2751it's fairly common to manipulate the contents of basic blocks.  This section
2752describes some of the common methods for doing so and gives example code.
2753
2754.. _schanges_creating:
2755
2756Creating and inserting new ``Instruction``\ s
2757^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2758
2759*Instantiating Instructions*
2760
2761Creation of ``Instruction``\ s is straight-forward: simply call the constructor
2762for the kind of instruction to instantiate and provide the necessary parameters.
2763For example, an ``AllocaInst`` only *requires* a (const-ptr-to) ``Type``.  Thus:
2764
2765.. code-block:: c++
2766
2767  auto *ai = new AllocaInst(Type::Int32Ty);
2768
2769will create an ``AllocaInst`` instance that represents the allocation of one
2770integer in the current stack frame, at run time.  Each ``Instruction`` subclass
2771is likely to have varying default parameters which change the semantics of the
2772instruction, so refer to the `doxygen documentation for the subclass of
2773Instruction <https://llvm.org/doxygen/classllvm_1_1Instruction.html>`_ that
2774you're interested in instantiating.
2775
2776*Naming values*
2777
2778It is very useful to name the values of instructions when you're able to, as
2779this facilitates the debugging of your transformations.  If you end up looking
2780at generated LLVM machine code, you definitely want to have logical names
2781associated with the results of instructions!  By supplying a value for the
2782``Name`` (default) parameter of the ``Instruction`` constructor, you associate a
2783logical name with the result of the instruction's execution at run time.  For
2784example, say that I'm writing a transformation that dynamically allocates space
2785for an integer on the stack, and that integer is going to be used as some kind
2786of index by some other code.  To accomplish this, I place an ``AllocaInst`` at
2787the first point in the first ``BasicBlock`` of some ``Function``, and I'm
2788intending to use it within the same ``Function``.  I might do:
2789
2790.. code-block:: c++
2791
2792  auto *pa = new AllocaInst(Type::Int32Ty, 0, "indexLoc");
2793
2794where ``indexLoc`` is now the logical name of the instruction's execution value,
2795which is a pointer to an integer on the run time stack.
2796
2797*Inserting instructions*
2798
2799There are essentially three ways to insert an ``Instruction`` into an existing
2800sequence of instructions that form a ``BasicBlock``:
2801
2802* Insertion into an explicit instruction list
2803
2804  Given a ``BasicBlock* pb``, an ``Instruction* pi`` within that ``BasicBlock``,
2805  and a newly-created instruction we wish to insert before ``*pi``, we do the
2806  following:
2807
2808  .. code-block:: c++
2809
2810      BasicBlock *pb = ...;
2811      Instruction *pi = ...;
2812      auto *newInst = new Instruction(...);
2813
2814      pb->getInstList().insert(pi, newInst); // Inserts newInst before pi in pb
2815
2816  Appending to the end of a ``BasicBlock`` is so common that the ``Instruction``
2817  class and ``Instruction``-derived classes provide constructors which take a
2818  pointer to a ``BasicBlock`` to be appended to.  For example code that looked
2819  like:
2820
2821  .. code-block:: c++
2822
2823    BasicBlock *pb = ...;
2824    auto *newInst = new Instruction(...);
2825
2826    pb->getInstList().push_back(newInst); // Appends newInst to pb
2827
2828  becomes:
2829
2830  .. code-block:: c++
2831
2832    BasicBlock *pb = ...;
2833    auto *newInst = new Instruction(..., pb);
2834
2835  which is much cleaner, especially if you are creating long instruction
2836  streams.
2837
2838* Insertion into an implicit instruction list
2839
2840  ``Instruction`` instances that are already in ``BasicBlock``\ s are implicitly
2841  associated with an existing instruction list: the instruction list of the
2842  enclosing basic block.  Thus, we could have accomplished the same thing as the
2843  above code without being given a ``BasicBlock`` by doing:
2844
2845  .. code-block:: c++
2846
2847    Instruction *pi = ...;
2848    auto *newInst = new Instruction(...);
2849
2850    pi->getParent()->getInstList().insert(pi, newInst);
2851
2852  In fact, this sequence of steps occurs so frequently that the ``Instruction``
2853  class and ``Instruction``-derived classes provide constructors which take (as
2854  a default parameter) a pointer to an ``Instruction`` which the newly-created
2855  ``Instruction`` should precede.  That is, ``Instruction`` constructors are
2856  capable of inserting the newly-created instance into the ``BasicBlock`` of a
2857  provided instruction, immediately before that instruction.  Using an
2858  ``Instruction`` constructor with a ``insertBefore`` (default) parameter, the
2859  above code becomes:
2860
2861  .. code-block:: c++
2862
2863    Instruction* pi = ...;
2864    auto *newInst = new Instruction(..., pi);
2865
2866  which is much cleaner, especially if you're creating a lot of instructions and
2867  adding them to ``BasicBlock``\ s.
2868
2869* Insertion using an instance of ``IRBuilder``
2870
2871  Inserting several ``Instruction``\ s can be quite laborious using the previous
2872  methods. The ``IRBuilder`` is a convenience class that can be used to add
2873  several instructions to the end of a ``BasicBlock`` or before a particular
2874  ``Instruction``. It also supports constant folding and renaming named
2875  registers (see ``IRBuilder``'s template arguments).
2876
2877  The example below demonstrates a very simple use of the ``IRBuilder`` where
2878  three instructions are inserted before the instruction ``pi``. The first two
2879  instructions are Call instructions and third instruction multiplies the return
2880  value of the two calls.
2881
2882  .. code-block:: c++
2883
2884    Instruction *pi = ...;
2885    IRBuilder<> Builder(pi);
2886    CallInst* callOne = Builder.CreateCall(...);
2887    CallInst* callTwo = Builder.CreateCall(...);
2888    Value* result = Builder.CreateMul(callOne, callTwo);
2889
2890  The example below is similar to the above example except that the created
2891  ``IRBuilder`` inserts instructions at the end of the ``BasicBlock`` ``pb``.
2892
2893  .. code-block:: c++
2894
2895    BasicBlock *pb = ...;
2896    IRBuilder<> Builder(pb);
2897    CallInst* callOne = Builder.CreateCall(...);
2898    CallInst* callTwo = Builder.CreateCall(...);
2899    Value* result = Builder.CreateMul(callOne, callTwo);
2900
2901  See :doc:`tutorial/LangImpl03` for a practical use of the ``IRBuilder``.
2902
2903
2904.. _schanges_deleting:
2905
2906Deleting Instructions
2907^^^^^^^^^^^^^^^^^^^^^
2908
2909Deleting an instruction from an existing sequence of instructions that form a
2910BasicBlock_ is very straight-forward: just call the instruction's
2911``eraseFromParent()`` method.  For example:
2912
2913.. code-block:: c++
2914
2915  Instruction *I = .. ;
2916  I->eraseFromParent();
2917
2918This unlinks the instruction from its containing basic block and deletes it.  If
2919you'd just like to unlink the instruction from its containing basic block but
2920not delete it, you can use the ``removeFromParent()`` method.
2921
2922.. _schanges_replacing:
2923
2924Replacing an Instruction with another Value
2925^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2926
2927Replacing individual instructions
2928"""""""""""""""""""""""""""""""""
2929
2930Including "`llvm/Transforms/Utils/BasicBlockUtils.h
2931<https://llvm.org/doxygen/BasicBlockUtils_8h_source.html>`_" permits use of two
2932very useful replace functions: ``ReplaceInstWithValue`` and
2933``ReplaceInstWithInst``.
2934
2935.. _schanges_deleting_sub:
2936
2937Deleting Instructions
2938"""""""""""""""""""""
2939
2940* ``ReplaceInstWithValue``
2941
2942  This function replaces all uses of a given instruction with a value, and then
2943  removes the original instruction.  The following example illustrates the
2944  replacement of the result of a particular ``AllocaInst`` that allocates memory
2945  for a single integer with a null pointer to an integer.
2946
2947  .. code-block:: c++
2948
2949    AllocaInst* instToReplace = ...;
2950    BasicBlock::iterator ii(instToReplace);
2951
2952    ReplaceInstWithValue(instToReplace->getParent()->getInstList(), ii,
2953                         Constant::getNullValue(PointerType::getUnqual(Type::Int32Ty)));
2954
2955* ``ReplaceInstWithInst``
2956
2957  This function replaces a particular instruction with another instruction,
2958  inserting the new instruction into the basic block at the location where the
2959  old instruction was, and replacing any uses of the old instruction with the
2960  new instruction.  The following example illustrates the replacement of one
2961  ``AllocaInst`` with another.
2962
2963  .. code-block:: c++
2964
2965    AllocaInst* instToReplace = ...;
2966    BasicBlock::iterator ii(instToReplace);
2967
2968    ReplaceInstWithInst(instToReplace->getParent()->getInstList(), ii,
2969                        new AllocaInst(Type::Int32Ty, 0, "ptrToReplacedInt"));
2970
2971
2972Replacing multiple uses of Users and Values
2973"""""""""""""""""""""""""""""""""""""""""""
2974
2975You can use ``Value::replaceAllUsesWith`` and ``User::replaceUsesOfWith`` to
2976change more than one use at a time.  See the doxygen documentation for the
2977`Value Class <https://llvm.org/doxygen/classllvm_1_1Value.html>`_ and `User Class
2978<https://llvm.org/doxygen/classllvm_1_1User.html>`_, respectively, for more
2979information.
2980
2981.. _schanges_deletingGV:
2982
2983Deleting GlobalVariables
2984^^^^^^^^^^^^^^^^^^^^^^^^
2985
2986Deleting a global variable from a module is just as easy as deleting an
2987Instruction.  First, you must have a pointer to the global variable that you
2988wish to delete.  You use this pointer to erase it from its parent, the module.
2989For example:
2990
2991.. code-block:: c++
2992
2993  GlobalVariable *GV = .. ;
2994
2995  GV->eraseFromParent();
2996
2997
2998.. _threading:
2999
3000Threads and LLVM
3001================
3002
3003This section describes the interaction of the LLVM APIs with multithreading,
3004both on the part of client applications, and in the JIT, in the hosted
3005application.
3006
3007Note that LLVM's support for multithreading is still relatively young.  Up
3008through version 2.5, the execution of threaded hosted applications was
3009supported, but not threaded client access to the APIs.  While this use case is
3010now supported, clients *must* adhere to the guidelines specified below to ensure
3011proper operation in multithreaded mode.
3012
3013Note that, on Unix-like platforms, LLVM requires the presence of GCC's atomic
3014intrinsics in order to support threaded operation.  If you need a
3015multithreading-capable LLVM on a platform without a suitably modern system
3016compiler, consider compiling LLVM and LLVM-GCC in single-threaded mode, and
3017using the resultant compiler to build a copy of LLVM with multithreading
3018support.
3019
3020.. _shutdown:
3021
3022Ending Execution with ``llvm_shutdown()``
3023-----------------------------------------
3024
3025When you are done using the LLVM APIs, you should call ``llvm_shutdown()`` to
3026deallocate memory used for internal structures.
3027
3028.. _managedstatic:
3029
3030Lazy Initialization with ``ManagedStatic``
3031------------------------------------------
3032
3033``ManagedStatic`` is a utility class in LLVM used to implement static
3034initialization of static resources, such as the global type tables.  In a
3035single-threaded environment, it implements a simple lazy initialization scheme.
3036When LLVM is compiled with support for multi-threading, however, it uses
3037double-checked locking to implement thread-safe lazy initialization.
3038
3039.. _llvmcontext:
3040
3041Achieving Isolation with ``LLVMContext``
3042----------------------------------------
3043
3044``LLVMContext`` is an opaque class in the LLVM API which clients can use to
3045operate multiple, isolated instances of LLVM concurrently within the same
3046address space.  For instance, in a hypothetical compile-server, the compilation
3047of an individual translation unit is conceptually independent from all the
3048others, and it would be desirable to be able to compile incoming translation
3049units concurrently on independent server threads.  Fortunately, ``LLVMContext``
3050exists to enable just this kind of scenario!
3051
3052Conceptually, ``LLVMContext`` provides isolation.  Every LLVM entity
3053(``Module``\ s, ``Value``\ s, ``Type``\ s, ``Constant``\ s, etc.) in LLVM's
3054in-memory IR belongs to an ``LLVMContext``.  Entities in different contexts
3055*cannot* interact with each other: ``Module``\ s in different contexts cannot be
3056linked together, ``Function``\ s cannot be added to ``Module``\ s in different
3057contexts, etc.  What this means is that is safe to compile on multiple
3058threads simultaneously, as long as no two threads operate on entities within the
3059same context.
3060
3061In practice, very few places in the API require the explicit specification of a
3062``LLVMContext``, other than the ``Type`` creation/lookup APIs.  Because every
3063``Type`` carries a reference to its owning context, most other entities can
3064determine what context they belong to by looking at their own ``Type``.  If you
3065are adding new entities to LLVM IR, please try to maintain this interface
3066design.
3067
3068.. _jitthreading:
3069
3070Threads and the JIT
3071-------------------
3072
3073LLVM's "eager" JIT compiler is safe to use in threaded programs.  Multiple
3074threads can call ``ExecutionEngine::getPointerToFunction()`` or
3075``ExecutionEngine::runFunction()`` concurrently, and multiple threads can run
3076code output by the JIT concurrently.  The user must still ensure that only one
3077thread accesses IR in a given ``LLVMContext`` while another thread might be
3078modifying it.  One way to do that is to always hold the JIT lock while accessing
3079IR outside the JIT (the JIT *modifies* the IR by adding ``CallbackVH``\ s).
3080Another way is to only call ``getPointerToFunction()`` from the
3081``LLVMContext``'s thread.
3082
3083When the JIT is configured to compile lazily (using
3084``ExecutionEngine::DisableLazyCompilation(false)``), there is currently a `race
3085condition <https://bugs.llvm.org/show_bug.cgi?id=5184>`_ in updating call sites
3086after a function is lazily-jitted.  It's still possible to use the lazy JIT in a
3087threaded program if you ensure that only one thread at a time can call any
3088particular lazy stub and that the JIT lock guards any IR access, but we suggest
3089using only the eager JIT in threaded programs.
3090
3091.. _advanced:
3092
3093Advanced Topics
3094===============
3095
3096This section describes some of the advanced or obscure API's that most clients
3097do not need to be aware of.  These API's tend manage the inner workings of the
3098LLVM system, and only need to be accessed in unusual circumstances.
3099
3100.. _SymbolTable:
3101
3102The ``ValueSymbolTable`` class
3103------------------------------
3104
3105The ``ValueSymbolTable`` (`doxygen
3106<https://llvm.org/doxygen/classllvm_1_1ValueSymbolTable.html>`__) class provides
3107a symbol table that the :ref:`Function <c_Function>` and Module_ classes use for
3108naming value definitions.  The symbol table can provide a name for any Value_.
3109
3110Note that the ``SymbolTable`` class should not be directly accessed by most
3111clients.  It should only be used when iteration over the symbol table names
3112themselves are required, which is very special purpose.  Note that not all LLVM
3113Value_\ s have names, and those without names (i.e. they have an empty name) do
3114not exist in the symbol table.
3115
3116Symbol tables support iteration over the values in the symbol table with
3117``begin/end/iterator`` and supports querying to see if a specific name is in the
3118symbol table (with ``lookup``).  The ``ValueSymbolTable`` class exposes no
3119public mutator methods, instead, simply call ``setName`` on a value, which will
3120autoinsert it into the appropriate symbol table.
3121
3122.. _UserLayout:
3123
3124The ``User`` and owned ``Use`` classes' memory layout
3125-----------------------------------------------------
3126
3127The ``User`` (`doxygen <https://llvm.org/doxygen/classllvm_1_1User.html>`__)
3128class provides a basis for expressing the ownership of ``User`` towards other
3129`Value instance <https://llvm.org/doxygen/classllvm_1_1Value.html>`_\ s.  The
3130``Use`` (`doxygen <https://llvm.org/doxygen/classllvm_1_1Use.html>`__) helper
3131class is employed to do the bookkeeping and to facilitate *O(1)* addition and
3132removal.
3133
3134.. _Use2User:
3135
3136Interaction and relationship between ``User`` and ``Use`` objects
3137^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3138
3139A subclass of ``User`` can choose between incorporating its ``Use`` objects or
3140refer to them out-of-line by means of a pointer.  A mixed variant (some ``Use``
3141s inline others hung off) is impractical and breaks the invariant that the
3142``Use`` objects belonging to the same ``User`` form a contiguous array.
3143
3144We have 2 different layouts in the ``User`` (sub)classes:
3145
3146* Layout a)
3147
3148  The ``Use`` object(s) are inside (resp. at fixed offset) of the ``User``
3149  object and there are a fixed number of them.
3150
3151* Layout b)
3152
3153  The ``Use`` object(s) are referenced by a pointer to an array from the
3154  ``User`` object and there may be a variable number of them.
3155
3156As of v2.4 each layout still possesses a direct pointer to the start of the
3157array of ``Use``\ s.  Though not mandatory for layout a), we stick to this
3158redundancy for the sake of simplicity.  The ``User`` object also stores the
3159number of ``Use`` objects it has. (Theoretically this information can also be
3160calculated given the scheme presented below.)
3161
3162Special forms of allocation operators (``operator new``) enforce the following
3163memory layouts:
3164
3165* Layout a) is modelled by prepending the ``User`` object by the ``Use[]``
3166  array.
3167
3168  .. code-block:: none
3169
3170    ...---.---.---.---.-------...
3171      | P | P | P | P | User
3172    '''---'---'---'---'-------'''
3173
3174* Layout b) is modelled by pointing at the ``Use[]`` array.
3175
3176  .. code-block:: none
3177
3178    .-------...
3179    | User
3180    '-------'''
3181        |
3182        v
3183        .---.---.---.---...
3184        | P | P | P | P |
3185        '---'---'---'---'''
3186
3187*(In the above figures* '``P``' *stands for the* ``Use**`` *that is stored in
3188each* ``Use`` *object in the member* ``Use::Prev`` *)*
3189
3190.. _Waymarking:
3191
3192The waymarking algorithm
3193^^^^^^^^^^^^^^^^^^^^^^^^
3194
3195Since the ``Use`` objects are deprived of the direct (back)pointer to their
3196``User`` objects, there must be a fast and exact method to recover it.  This is
3197accomplished by the following scheme:
3198
3199A bit-encoding in the 2 LSBits (least significant bits) of the ``Use::Prev``
3200allows to find the start of the ``User`` object:
3201
3202* ``00`` --- binary digit 0
3203
3204* ``01`` --- binary digit 1
3205
3206* ``10`` --- stop and calculate (``s``)
3207
3208* ``11`` --- full stop (``S``)
3209
3210Given a ``Use*``, all we have to do is to walk till we get a stop and we either
3211have a ``User`` immediately behind or we have to walk to the next stop picking
3212up digits and calculating the offset:
3213
3214.. code-block:: none
3215
3216  .---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.----------------
3217  | 1 | s | 1 | 0 | 1 | 0 | s | 1 | 1 | 0 | s | 1 | 1 | s | 1 | S | User (or User*)
3218  '---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'----------------
3219      |+15                |+10            |+6         |+3     |+1
3220      |                   |               |           |       | __>
3221      |                   |               |           | __________>
3222      |                   |               | ______________________>
3223      |                   | ______________________________________>
3224      | __________________________________________________________>
3225
3226Only the significant number of bits need to be stored between the stops, so that
3227the *worst case is 20 memory accesses* when there are 1000 ``Use`` objects
3228associated with a ``User``.
3229
3230.. _ReferenceImpl:
3231
3232Reference implementation
3233^^^^^^^^^^^^^^^^^^^^^^^^
3234
3235The following literate Haskell fragment demonstrates the concept:
3236
3237.. code-block:: haskell
3238
3239  > import Test.QuickCheck
3240  >
3241  > digits :: Int -> [Char] -> [Char]
3242  > digits 0 acc = '0' : acc
3243  > digits 1 acc = '1' : acc
3244  > digits n acc = digits (n `div` 2) $ digits (n `mod` 2) acc
3245  >
3246  > dist :: Int -> [Char] -> [Char]
3247  > dist 0 [] = ['S']
3248  > dist 0 acc = acc
3249  > dist 1 acc = let r = dist 0 acc in 's' : digits (length r) r
3250  > dist n acc = dist (n - 1) $ dist 1 acc
3251  >
3252  > takeLast n ss = reverse $ take n $ reverse ss
3253  >
3254  > test = takeLast 40 $ dist 20 []
3255  >
3256
3257Printing <test> gives: ``"1s100000s11010s10100s1111s1010s110s11s1S"``
3258
3259The reverse algorithm computes the length of the string just by examining a
3260certain prefix:
3261
3262.. code-block:: haskell
3263
3264  > pref :: [Char] -> Int
3265  > pref "S" = 1
3266  > pref ('s':'1':rest) = decode 2 1 rest
3267  > pref (_:rest) = 1 + pref rest
3268  >
3269  > decode walk acc ('0':rest) = decode (walk + 1) (acc * 2) rest
3270  > decode walk acc ('1':rest) = decode (walk + 1) (acc * 2 + 1) rest
3271  > decode walk acc _ = walk + acc
3272  >
3273
3274Now, as expected, printing <pref test> gives ``40``.
3275
3276We can *quickCheck* this with following property:
3277
3278.. code-block:: haskell
3279
3280  > testcase = dist 2000 []
3281  > testcaseLength = length testcase
3282  >
3283  > identityProp n = n > 0 && n <= testcaseLength ==> length arr == pref arr
3284  >     where arr = takeLast n testcase
3285  >
3286
3287As expected <quickCheck identityProp> gives:
3288
3289::
3290
3291  *Main> quickCheck identityProp
3292  OK, passed 100 tests.
3293
3294Let's be a bit more exhaustive:
3295
3296.. code-block:: haskell
3297
3298  >
3299  > deepCheck p = check (defaultConfig { configMaxTest = 500 }) p
3300  >
3301
3302And here is the result of <deepCheck identityProp>:
3303
3304::
3305
3306  *Main> deepCheck identityProp
3307  OK, passed 500 tests.
3308
3309.. _Tagging:
3310
3311Tagging considerations
3312^^^^^^^^^^^^^^^^^^^^^^
3313
3314To maintain the invariant that the 2 LSBits of each ``Use**`` in ``Use`` never
3315change after being set up, setters of ``Use::Prev`` must re-tag the new
3316``Use**`` on every modification.  Accordingly getters must strip the tag bits.
3317
3318For layout b) instead of the ``User`` we find a pointer (``User*`` with LSBit
3319set).  Following this pointer brings us to the ``User``.  A portable trick
3320ensures that the first bytes of ``User`` (if interpreted as a pointer) never has
3321the LSBit set. (Portability is relying on the fact that all known compilers
3322place the ``vptr`` in the first word of the instances.)
3323
3324.. _polymorphism:
3325
3326Designing Type Hierarchies and Polymorphic Interfaces
3327-----------------------------------------------------
3328
3329There are two different design patterns that tend to result in the use of
3330virtual dispatch for methods in a type hierarchy in C++ programs. The first is
3331a genuine type hierarchy where different types in the hierarchy model
3332a specific subset of the functionality and semantics, and these types nest
3333strictly within each other. Good examples of this can be seen in the ``Value``
3334or ``Type`` type hierarchies.
3335
3336A second is the desire to dispatch dynamically across a collection of
3337polymorphic interface implementations. This latter use case can be modeled with
3338virtual dispatch and inheritance by defining an abstract interface base class
3339which all implementations derive from and override. However, this
3340implementation strategy forces an **"is-a"** relationship to exist that is not
3341actually meaningful. There is often not some nested hierarchy of useful
3342generalizations which code might interact with and move up and down. Instead,
3343there is a singular interface which is dispatched across a range of
3344implementations.
3345
3346The preferred implementation strategy for the second use case is that of
3347generic programming (sometimes called "compile-time duck typing" or "static
3348polymorphism"). For example, a template over some type parameter ``T`` can be
3349instantiated across any particular implementation that conforms to the
3350interface or *concept*. A good example here is the highly generic properties of
3351any type which models a node in a directed graph. LLVM models these primarily
3352through templates and generic programming. Such templates include the
3353``LoopInfoBase`` and ``DominatorTreeBase``. When this type of polymorphism
3354truly needs **dynamic** dispatch you can generalize it using a technique
3355called *concept-based polymorphism*. This pattern emulates the interfaces and
3356behaviors of templates using a very limited form of virtual dispatch for type
3357erasure inside its implementation. You can find examples of this technique in
3358the ``PassManager.h`` system, and there is a more detailed introduction to it
3359by Sean Parent in several of his talks and papers:
3360
3361#. `Inheritance Is The Base Class of Evil
3362   <http://channel9.msdn.com/Events/GoingNative/2013/Inheritance-Is-The-Base-Class-of-Evil>`_
3363   - The GoingNative 2013 talk describing this technique, and probably the best
3364   place to start.
3365#. `Value Semantics and Concepts-based Polymorphism
3366   <http://www.youtube.com/watch?v=_BpMYeUFXv8>`_ - The C++Now! 2012 talk
3367   describing this technique in more detail.
3368#. `Sean Parent's Papers and Presentations
3369   <http://github.com/sean-parent/sean-parent.github.com/wiki/Papers-and-Presentations>`_
3370   - A GitHub project full of links to slides, video, and sometimes code.
3371
3372When deciding between creating a type hierarchy (with either tagged or virtual
3373dispatch) and using templates or concepts-based polymorphism, consider whether
3374there is some refinement of an abstract base class which is a semantically
3375meaningful type on an interface boundary. If anything more refined than the
3376root abstract interface is meaningless to talk about as a partial extension of
3377the semantic model, then your use case likely fits better with polymorphism and
3378you should avoid using virtual dispatch. However, there may be some exigent
3379circumstances that require one technique or the other to be used.
3380
3381If you do need to introduce a type hierarchy, we prefer to use explicitly
3382closed type hierarchies with manual tagged dispatch and/or RTTI rather than the
3383open inheritance model and virtual dispatch that is more common in C++ code.
3384This is because LLVM rarely encourages library consumers to extend its core
3385types, and leverages the closed and tag-dispatched nature of its hierarchies to
3386generate significantly more efficient code. We have also found that a large
3387amount of our usage of type hierarchies fits better with tag-based pattern
3388matching rather than dynamic dispatch across a common interface. Within LLVM we
3389have built custom helpers to facilitate this design. See this document's
3390section on :ref:`isa and dyn_cast <isa>` and our :doc:`detailed document
3391<HowToSetUpLLVMStyleRTTI>` which describes how you can implement this
3392pattern for use with the LLVM helpers.
3393
3394.. _abi_breaking_checks:
3395
3396ABI Breaking Checks
3397-------------------
3398
3399Checks and asserts that alter the LLVM C++ ABI are predicated on the
3400preprocessor symbol `LLVM_ENABLE_ABI_BREAKING_CHECKS` -- LLVM
3401libraries built with `LLVM_ENABLE_ABI_BREAKING_CHECKS` are not ABI
3402compatible LLVM libraries built without it defined.  By default,
3403turning on assertions also turns on `LLVM_ENABLE_ABI_BREAKING_CHECKS`
3404so a default +Asserts build is not ABI compatible with a
3405default -Asserts build.  Clients that want ABI compatibility
3406between +Asserts and -Asserts builds should use the CMake build system
3407to set `LLVM_ENABLE_ABI_BREAKING_CHECKS` independently
3408of `LLVM_ENABLE_ASSERTIONS`.
3409
3410.. _coreclasses:
3411
3412The Core LLVM Class Hierarchy Reference
3413=======================================
3414
3415``#include "llvm/IR/Type.h"``
3416
3417header source: `Type.h <https://llvm.org/doxygen/Type_8h_source.html>`_
3418
3419doxygen info: `Type Classes <https://llvm.org/doxygen/classllvm_1_1Type.html>`_
3420
3421The Core LLVM classes are the primary means of representing the program being
3422inspected or transformed.  The core LLVM classes are defined in header files in
3423the ``include/llvm/IR`` directory, and implemented in the ``lib/IR``
3424directory. It's worth noting that, for historical reasons, this library is
3425called ``libLLVMCore.so``, not ``libLLVMIR.so`` as you might expect.
3426
3427.. _Type:
3428
3429The Type class and Derived Types
3430--------------------------------
3431
3432``Type`` is a superclass of all type classes.  Every ``Value`` has a ``Type``.
3433``Type`` cannot be instantiated directly but only through its subclasses.
3434Certain primitive types (``VoidType``, ``LabelType``, ``FloatType`` and
3435``DoubleType``) have hidden subclasses.  They are hidden because they offer no
3436useful functionality beyond what the ``Type`` class offers except to distinguish
3437themselves from other subclasses of ``Type``.
3438
3439All other types are subclasses of ``DerivedType``.  Types can be named, but this
3440is not a requirement.  There exists exactly one instance of a given shape at any
3441one time.  This allows type equality to be performed with address equality of
3442the Type Instance.  That is, given two ``Type*`` values, the types are identical
3443if the pointers are identical.
3444
3445.. _m_Type:
3446
3447Important Public Methods
3448^^^^^^^^^^^^^^^^^^^^^^^^
3449
3450* ``bool isIntegerTy() const``: Returns true for any integer type.
3451
3452* ``bool isFloatingPointTy()``: Return true if this is one of the five
3453  floating point types.
3454
3455* ``bool isSized()``: Return true if the type has known size.  Things
3456  that don't have a size are abstract types, labels and void.
3457
3458.. _derivedtypes:
3459
3460Important Derived Types
3461^^^^^^^^^^^^^^^^^^^^^^^
3462
3463``IntegerType``
3464  Subclass of DerivedType that represents integer types of any bit width.  Any
3465  bit width between ``IntegerType::MIN_INT_BITS`` (1) and
3466  ``IntegerType::MAX_INT_BITS`` (~8 million) can be represented.
3467
3468  * ``static const IntegerType* get(unsigned NumBits)``: get an integer
3469    type of a specific bit width.
3470
3471  * ``unsigned getBitWidth() const``: Get the bit width of an integer type.
3472
3473``SequentialType``
3474  This is subclassed by ArrayType and VectorType.
3475
3476  * ``const Type * getElementType() const``: Returns the type of each
3477    of the elements in the sequential type.
3478
3479  * ``uint64_t getNumElements() const``: Returns the number of elements
3480    in the sequential type.
3481
3482``ArrayType``
3483  This is a subclass of SequentialType and defines the interface for array
3484  types.
3485
3486``PointerType``
3487  Subclass of Type for pointer types.
3488
3489``VectorType``
3490  Subclass of SequentialType for vector types.  A vector type is similar to an
3491  ArrayType but is distinguished because it is a first class type whereas
3492  ArrayType is not.  Vector types are used for vector operations and are usually
3493  small vectors of an integer or floating point type.
3494
3495``StructType``
3496  Subclass of DerivedTypes for struct types.
3497
3498.. _FunctionType:
3499
3500``FunctionType``
3501  Subclass of DerivedTypes for function types.
3502
3503  * ``bool isVarArg() const``: Returns true if it's a vararg function.
3504
3505  * ``const Type * getReturnType() const``: Returns the return type of the
3506    function.
3507
3508  * ``const Type * getParamType (unsigned i)``: Returns the type of the ith
3509    parameter.
3510
3511  * ``const unsigned getNumParams() const``: Returns the number of formal
3512    parameters.
3513
3514.. _Module:
3515
3516The ``Module`` class
3517--------------------
3518
3519``#include "llvm/IR/Module.h"``
3520
3521header source: `Module.h <https://llvm.org/doxygen/Module_8h_source.html>`_
3522
3523doxygen info: `Module Class <https://llvm.org/doxygen/classllvm_1_1Module.html>`_
3524
3525The ``Module`` class represents the top level structure present in LLVM
3526programs.  An LLVM module is effectively either a translation unit of the
3527original program or a combination of several translation units merged by the
3528linker.  The ``Module`` class keeps track of a list of :ref:`Function
3529<c_Function>`\ s, a list of GlobalVariable_\ s, and a SymbolTable_.
3530Additionally, it contains a few helpful member functions that try to make common
3531operations easy.
3532
3533.. _m_Module:
3534
3535Important Public Members of the ``Module`` class
3536^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3537
3538* ``Module::Module(std::string name = "")``
3539
3540  Constructing a Module_ is easy.  You can optionally provide a name for it
3541  (probably based on the name of the translation unit).
3542
3543* | ``Module::iterator`` - Typedef for function list iterator
3544  | ``Module::const_iterator`` - Typedef for const_iterator.
3545  | ``begin()``, ``end()``, ``size()``, ``empty()``
3546
3547  These are forwarding methods that make it easy to access the contents of a
3548  ``Module`` object's :ref:`Function <c_Function>` list.
3549
3550* ``Module::FunctionListType &getFunctionList()``
3551
3552  Returns the list of :ref:`Function <c_Function>`\ s.  This is necessary to use
3553  when you need to update the list or perform a complex action that doesn't have
3554  a forwarding method.
3555
3556----------------
3557
3558* | ``Module::global_iterator`` - Typedef for global variable list iterator
3559  | ``Module::const_global_iterator`` - Typedef for const_iterator.
3560  | ``global_begin()``, ``global_end()``, ``global_size()``, ``global_empty()``
3561
3562  These are forwarding methods that make it easy to access the contents of a
3563  ``Module`` object's GlobalVariable_ list.
3564
3565* ``Module::GlobalListType &getGlobalList()``
3566
3567  Returns the list of GlobalVariable_\ s.  This is necessary to use when you
3568  need to update the list or perform a complex action that doesn't have a
3569  forwarding method.
3570
3571----------------
3572
3573* ``SymbolTable *getSymbolTable()``
3574
3575  Return a reference to the SymbolTable_ for this ``Module``.
3576
3577----------------
3578
3579* ``Function *getFunction(StringRef Name) const``
3580
3581  Look up the specified function in the ``Module`` SymbolTable_.  If it does not
3582  exist, return ``null``.
3583
3584* ``FunctionCallee getOrInsertFunction(const std::string &Name,
3585  const FunctionType *T)``
3586
3587  Look up the specified function in the ``Module`` SymbolTable_.  If
3588  it does not exist, add an external declaration for the function and
3589  return it. Note that the function signature already present may not
3590  match the requested signature. Thus, in order to enable the common
3591  usage of passing the result directly to EmitCall, the return type is
3592  a struct of ``{FunctionType *T, Constant *FunctionPtr}``, rather
3593  than simply the ``Function*`` with potentially an unexpected
3594  signature.
3595
3596* ``std::string getTypeName(const Type *Ty)``
3597
3598  If there is at least one entry in the SymbolTable_ for the specified Type_,
3599  return it.  Otherwise return the empty string.
3600
3601* ``bool addTypeName(const std::string &Name, const Type *Ty)``
3602
3603  Insert an entry in the SymbolTable_ mapping ``Name`` to ``Ty``.  If there is
3604  already an entry for this name, true is returned and the SymbolTable_ is not
3605  modified.
3606
3607.. _Value:
3608
3609The ``Value`` class
3610-------------------
3611
3612``#include "llvm/IR/Value.h"``
3613
3614header source: `Value.h <https://llvm.org/doxygen/Value_8h_source.html>`_
3615
3616doxygen info: `Value Class <https://llvm.org/doxygen/classllvm_1_1Value.html>`_
3617
3618The ``Value`` class is the most important class in the LLVM Source base.  It
3619represents a typed value that may be used (among other things) as an operand to
3620an instruction.  There are many different types of ``Value``\ s, such as
3621Constant_\ s, Argument_\ s.  Even Instruction_\ s and :ref:`Function
3622<c_Function>`\ s are ``Value``\ s.
3623
3624A particular ``Value`` may be used many times in the LLVM representation for a
3625program.  For example, an incoming argument to a function (represented with an
3626instance of the Argument_ class) is "used" by every instruction in the function
3627that references the argument.  To keep track of this relationship, the ``Value``
3628class keeps a list of all of the ``User``\ s that is using it (the User_ class
3629is a base class for all nodes in the LLVM graph that can refer to ``Value``\ s).
3630This use list is how LLVM represents def-use information in the program, and is
3631accessible through the ``use_*`` methods, shown below.
3632
3633Because LLVM is a typed representation, every LLVM ``Value`` is typed, and this
3634Type_ is available through the ``getType()`` method.  In addition, all LLVM
3635values can be named.  The "name" of the ``Value`` is a symbolic string printed
3636in the LLVM code:
3637
3638.. code-block:: llvm
3639
3640  %foo = add i32 1, 2
3641
3642.. _nameWarning:
3643
3644The name of this instruction is "foo". **NOTE** that the name of any value may
3645be missing (an empty string), so names should **ONLY** be used for debugging
3646(making the source code easier to read, debugging printouts), they should not be
3647used to keep track of values or map between them.  For this purpose, use a
3648``std::map`` of pointers to the ``Value`` itself instead.
3649
3650One important aspect of LLVM is that there is no distinction between an SSA
3651variable and the operation that produces it.  Because of this, any reference to
3652the value produced by an instruction (or the value available as an incoming
3653argument, for example) is represented as a direct pointer to the instance of the
3654class that represents this value.  Although this may take some getting used to,
3655it simplifies the representation and makes it easier to manipulate.
3656
3657.. _m_Value:
3658
3659Important Public Members of the ``Value`` class
3660^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3661
3662* | ``Value::use_iterator`` - Typedef for iterator over the use-list
3663  | ``Value::const_use_iterator`` - Typedef for const_iterator over the
3664    use-list
3665  | ``unsigned use_size()`` - Returns the number of users of the value.
3666  | ``bool use_empty()`` - Returns true if there are no users.
3667  | ``use_iterator use_begin()`` - Get an iterator to the start of the
3668    use-list.
3669  | ``use_iterator use_end()`` - Get an iterator to the end of the use-list.
3670  | ``User *use_back()`` - Returns the last element in the list.
3671
3672  These methods are the interface to access the def-use information in LLVM.
3673  As with all other iterators in LLVM, the naming conventions follow the
3674  conventions defined by the STL_.
3675
3676* ``Type *getType() const``
3677  This method returns the Type of the Value.
3678
3679* | ``bool hasName() const``
3680  | ``std::string getName() const``
3681  | ``void setName(const std::string &Name)``
3682
3683  This family of methods is used to access and assign a name to a ``Value``, be
3684  aware of the :ref:`precaution above <nameWarning>`.
3685
3686* ``void replaceAllUsesWith(Value *V)``
3687
3688  This method traverses the use list of a ``Value`` changing all User_\ s of the
3689  current value to refer to "``V``" instead.  For example, if you detect that an
3690  instruction always produces a constant value (for example through constant
3691  folding), you can replace all uses of the instruction with the constant like
3692  this:
3693
3694  .. code-block:: c++
3695
3696    Inst->replaceAllUsesWith(ConstVal);
3697
3698.. _User:
3699
3700The ``User`` class
3701------------------
3702
3703``#include "llvm/IR/User.h"``
3704
3705header source: `User.h <https://llvm.org/doxygen/User_8h_source.html>`_
3706
3707doxygen info: `User Class <https://llvm.org/doxygen/classllvm_1_1User.html>`_
3708
3709Superclass: Value_
3710
3711The ``User`` class is the common base class of all LLVM nodes that may refer to
3712``Value``\ s.  It exposes a list of "Operands" that are all of the ``Value``\ s
3713that the User is referring to.  The ``User`` class itself is a subclass of
3714``Value``.
3715
3716The operands of a ``User`` point directly to the LLVM ``Value`` that it refers
3717to.  Because LLVM uses Static Single Assignment (SSA) form, there can only be
3718one definition referred to, allowing this direct connection.  This connection
3719provides the use-def information in LLVM.
3720
3721.. _m_User:
3722
3723Important Public Members of the ``User`` class
3724^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3725
3726The ``User`` class exposes the operand list in two ways: through an index access
3727interface and through an iterator based interface.
3728
3729* | ``Value *getOperand(unsigned i)``
3730  | ``unsigned getNumOperands()``
3731
3732  These two methods expose the operands of the ``User`` in a convenient form for
3733  direct access.
3734
3735* | ``User::op_iterator`` - Typedef for iterator over the operand list
3736  | ``op_iterator op_begin()`` - Get an iterator to the start of the operand
3737    list.
3738  | ``op_iterator op_end()`` - Get an iterator to the end of the operand list.
3739
3740  Together, these methods make up the iterator based interface to the operands
3741  of a ``User``.
3742
3743
3744.. _Instruction:
3745
3746The ``Instruction`` class
3747-------------------------
3748
3749``#include "llvm/IR/Instruction.h"``
3750
3751header source: `Instruction.h
3752<https://llvm.org/doxygen/Instruction_8h_source.html>`_
3753
3754doxygen info: `Instruction Class
3755<https://llvm.org/doxygen/classllvm_1_1Instruction.html>`_
3756
3757Superclasses: User_, Value_
3758
3759The ``Instruction`` class is the common base class for all LLVM instructions.
3760It provides only a few methods, but is a very commonly used class.  The primary
3761data tracked by the ``Instruction`` class itself is the opcode (instruction
3762type) and the parent BasicBlock_ the ``Instruction`` is embedded into.  To
3763represent a specific type of instruction, one of many subclasses of
3764``Instruction`` are used.
3765
3766Because the ``Instruction`` class subclasses the User_ class, its operands can
3767be accessed in the same way as for other ``User``\ s (with the
3768``getOperand()``/``getNumOperands()`` and ``op_begin()``/``op_end()`` methods).
3769An important file for the ``Instruction`` class is the ``llvm/Instruction.def``
3770file.  This file contains some meta-data about the various different types of
3771instructions in LLVM.  It describes the enum values that are used as opcodes
3772(for example ``Instruction::Add`` and ``Instruction::ICmp``), as well as the
3773concrete sub-classes of ``Instruction`` that implement the instruction (for
3774example BinaryOperator_ and CmpInst_).  Unfortunately, the use of macros in this
3775file confuses doxygen, so these enum values don't show up correctly in the
3776`doxygen output <https://llvm.org/doxygen/classllvm_1_1Instruction.html>`_.
3777
3778.. _s_Instruction:
3779
3780Important Subclasses of the ``Instruction`` class
3781^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3782
3783.. _BinaryOperator:
3784
3785* ``BinaryOperator``
3786
3787  This subclasses represents all two operand instructions whose operands must be
3788  the same type, except for the comparison instructions.
3789
3790.. _CastInst:
3791
3792* ``CastInst``
3793  This subclass is the parent of the 12 casting instructions.  It provides
3794  common operations on cast instructions.
3795
3796.. _CmpInst:
3797
3798* ``CmpInst``
3799
3800  This subclass represents the two comparison instructions,
3801  `ICmpInst <LangRef.html#i_icmp>`_ (integer opreands), and
3802  `FCmpInst <LangRef.html#i_fcmp>`_ (floating point operands).
3803
3804.. _m_Instruction:
3805
3806Important Public Members of the ``Instruction`` class
3807^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3808
3809* ``BasicBlock *getParent()``
3810
3811  Returns the BasicBlock_ that this
3812  ``Instruction`` is embedded into.
3813
3814* ``bool mayWriteToMemory()``
3815
3816  Returns true if the instruction writes to memory, i.e. it is a ``call``,
3817  ``free``, ``invoke``, or ``store``.
3818
3819* ``unsigned getOpcode()``
3820
3821  Returns the opcode for the ``Instruction``.
3822
3823* ``Instruction *clone() const``
3824
3825  Returns another instance of the specified instruction, identical in all ways
3826  to the original except that the instruction has no parent (i.e. it's not
3827  embedded into a BasicBlock_), and it has no name.
3828
3829.. _Constant:
3830
3831The ``Constant`` class and subclasses
3832-------------------------------------
3833
3834Constant represents a base class for different types of constants.  It is
3835subclassed by ConstantInt, ConstantArray, etc. for representing the various
3836types of Constants.  GlobalValue_ is also a subclass, which represents the
3837address of a global variable or function.
3838
3839.. _s_Constant:
3840
3841Important Subclasses of Constant
3842^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3843
3844* ConstantInt : This subclass of Constant represents an integer constant of
3845  any width.
3846
3847  * ``const APInt& getValue() const``: Returns the underlying
3848    value of this constant, an APInt value.
3849
3850  * ``int64_t getSExtValue() const``: Converts the underlying APInt value to an
3851    int64_t via sign extension.  If the value (not the bit width) of the APInt
3852    is too large to fit in an int64_t, an assertion will result.  For this
3853    reason, use of this method is discouraged.
3854
3855  * ``uint64_t getZExtValue() const``: Converts the underlying APInt value
3856    to a uint64_t via zero extension.  IF the value (not the bit width) of the
3857    APInt is too large to fit in a uint64_t, an assertion will result.  For this
3858    reason, use of this method is discouraged.
3859
3860  * ``static ConstantInt* get(const APInt& Val)``: Returns the ConstantInt
3861    object that represents the value provided by ``Val``.  The type is implied
3862    as the IntegerType that corresponds to the bit width of ``Val``.
3863
3864  * ``static ConstantInt* get(const Type *Ty, uint64_t Val)``: Returns the
3865    ConstantInt object that represents the value provided by ``Val`` for integer
3866    type ``Ty``.
3867
3868* ConstantFP : This class represents a floating point constant.
3869
3870  * ``double getValue() const``: Returns the underlying value of this constant.
3871
3872* ConstantArray : This represents a constant array.
3873
3874  * ``const std::vector<Use> &getValues() const``: Returns a vector of
3875    component constants that makeup this array.
3876
3877* ConstantStruct : This represents a constant struct.
3878
3879  * ``const std::vector<Use> &getValues() const``: Returns a vector of
3880    component constants that makeup this array.
3881
3882* GlobalValue : This represents either a global variable or a function.  In
3883  either case, the value is a constant fixed address (after linking).
3884
3885.. _GlobalValue:
3886
3887The ``GlobalValue`` class
3888-------------------------
3889
3890``#include "llvm/IR/GlobalValue.h"``
3891
3892header source: `GlobalValue.h
3893<https://llvm.org/doxygen/GlobalValue_8h_source.html>`_
3894
3895doxygen info: `GlobalValue Class
3896<https://llvm.org/doxygen/classllvm_1_1GlobalValue.html>`_
3897
3898Superclasses: Constant_, User_, Value_
3899
3900Global values ( GlobalVariable_\ s or :ref:`Function <c_Function>`\ s) are the
3901only LLVM values that are visible in the bodies of all :ref:`Function
3902<c_Function>`\ s.  Because they are visible at global scope, they are also
3903subject to linking with other globals defined in different translation units.
3904To control the linking process, ``GlobalValue``\ s know their linkage rules.
3905Specifically, ``GlobalValue``\ s know whether they have internal or external
3906linkage, as defined by the ``LinkageTypes`` enumeration.
3907
3908If a ``GlobalValue`` has internal linkage (equivalent to being ``static`` in C),
3909it is not visible to code outside the current translation unit, and does not
3910participate in linking.  If it has external linkage, it is visible to external
3911code, and does participate in linking.  In addition to linkage information,
3912``GlobalValue``\ s keep track of which Module_ they are currently part of.
3913
3914Because ``GlobalValue``\ s are memory objects, they are always referred to by
3915their **address**.  As such, the Type_ of a global is always a pointer to its
3916contents.  It is important to remember this when using the ``GetElementPtrInst``
3917instruction because this pointer must be dereferenced first.  For example, if
3918you have a ``GlobalVariable`` (a subclass of ``GlobalValue)`` that is an array
3919of 24 ints, type ``[24 x i32]``, then the ``GlobalVariable`` is a pointer to
3920that array.  Although the address of the first element of this array and the
3921value of the ``GlobalVariable`` are the same, they have different types.  The
3922``GlobalVariable``'s type is ``[24 x i32]``.  The first element's type is
3923``i32.`` Because of this, accessing a global value requires you to dereference
3924the pointer with ``GetElementPtrInst`` first, then its elements can be accessed.
3925This is explained in the `LLVM Language Reference Manual
3926<LangRef.html#globalvars>`_.
3927
3928.. _m_GlobalValue:
3929
3930Important Public Members of the ``GlobalValue`` class
3931^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3932
3933* | ``bool hasInternalLinkage() const``
3934  | ``bool hasExternalLinkage() const``
3935  | ``void setInternalLinkage(bool HasInternalLinkage)``
3936
3937  These methods manipulate the linkage characteristics of the ``GlobalValue``.
3938
3939* ``Module *getParent()``
3940
3941  This returns the Module_ that the
3942  GlobalValue is currently embedded into.
3943
3944.. _c_Function:
3945
3946The ``Function`` class
3947----------------------
3948
3949``#include "llvm/IR/Function.h"``
3950
3951header source: `Function.h <https://llvm.org/doxygen/Function_8h_source.html>`_
3952
3953doxygen info: `Function Class
3954<https://llvm.org/doxygen/classllvm_1_1Function.html>`_
3955
3956Superclasses: GlobalValue_, Constant_, User_, Value_
3957
3958The ``Function`` class represents a single procedure in LLVM.  It is actually
3959one of the more complex classes in the LLVM hierarchy because it must keep track
3960of a large amount of data.  The ``Function`` class keeps track of a list of
3961BasicBlock_\ s, a list of formal Argument_\ s, and a SymbolTable_.
3962
3963The list of BasicBlock_\ s is the most commonly used part of ``Function``
3964objects.  The list imposes an implicit ordering of the blocks in the function,
3965which indicate how the code will be laid out by the backend.  Additionally, the
3966first BasicBlock_ is the implicit entry node for the ``Function``.  It is not
3967legal in LLVM to explicitly branch to this initial block.  There are no implicit
3968exit nodes, and in fact there may be multiple exit nodes from a single
3969``Function``.  If the BasicBlock_ list is empty, this indicates that the
3970``Function`` is actually a function declaration: the actual body of the function
3971hasn't been linked in yet.
3972
3973In addition to a list of BasicBlock_\ s, the ``Function`` class also keeps track
3974of the list of formal Argument_\ s that the function receives.  This container
3975manages the lifetime of the Argument_ nodes, just like the BasicBlock_ list does
3976for the BasicBlock_\ s.
3977
3978The SymbolTable_ is a very rarely used LLVM feature that is only used when you
3979have to look up a value by name.  Aside from that, the SymbolTable_ is used
3980internally to make sure that there are not conflicts between the names of
3981Instruction_\ s, BasicBlock_\ s, or Argument_\ s in the function body.
3982
3983Note that ``Function`` is a GlobalValue_ and therefore also a Constant_.  The
3984value of the function is its address (after linking) which is guaranteed to be
3985constant.
3986
3987.. _m_Function:
3988
3989Important Public Members of the ``Function``
3990^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3991
3992* ``Function(const FunctionType *Ty, LinkageTypes Linkage,
3993  const std::string &N = "", Module* Parent = 0)``
3994
3995  Constructor used when you need to create new ``Function``\ s to add the
3996  program.  The constructor must specify the type of the function to create and
3997  what type of linkage the function should have.  The FunctionType_ argument
3998  specifies the formal arguments and return value for the function.  The same
3999  FunctionType_ value can be used to create multiple functions.  The ``Parent``
4000  argument specifies the Module in which the function is defined.  If this
4001  argument is provided, the function will automatically be inserted into that
4002  module's list of functions.
4003
4004* ``bool isDeclaration()``
4005
4006  Return whether or not the ``Function`` has a body defined.  If the function is
4007  "external", it does not have a body, and thus must be resolved by linking with
4008  a function defined in a different translation unit.
4009
4010* | ``Function::iterator`` - Typedef for basic block list iterator
4011  | ``Function::const_iterator`` - Typedef for const_iterator.
4012  | ``begin()``, ``end()``, ``size()``, ``empty()``
4013
4014  These are forwarding methods that make it easy to access the contents of a
4015  ``Function`` object's BasicBlock_ list.
4016
4017* ``Function::BasicBlockListType &getBasicBlockList()``
4018
4019  Returns the list of BasicBlock_\ s.  This is necessary to use when you need to
4020  update the list or perform a complex action that doesn't have a forwarding
4021  method.
4022
4023* | ``Function::arg_iterator`` - Typedef for the argument list iterator
4024  | ``Function::const_arg_iterator`` - Typedef for const_iterator.
4025  | ``arg_begin()``, ``arg_end()``, ``arg_size()``, ``arg_empty()``
4026
4027  These are forwarding methods that make it easy to access the contents of a
4028  ``Function`` object's Argument_ list.
4029
4030* ``Function::ArgumentListType &getArgumentList()``
4031
4032  Returns the list of Argument_.  This is necessary to use when you need to
4033  update the list or perform a complex action that doesn't have a forwarding
4034  method.
4035
4036* ``BasicBlock &getEntryBlock()``
4037
4038  Returns the entry ``BasicBlock`` for the function.  Because the entry block
4039  for the function is always the first block, this returns the first block of
4040  the ``Function``.
4041
4042* | ``Type *getReturnType()``
4043  | ``FunctionType *getFunctionType()``
4044
4045  This traverses the Type_ of the ``Function`` and returns the return type of
4046  the function, or the FunctionType_ of the actual function.
4047
4048* ``SymbolTable *getSymbolTable()``
4049
4050  Return a pointer to the SymbolTable_ for this ``Function``.
4051
4052.. _GlobalVariable:
4053
4054The ``GlobalVariable`` class
4055----------------------------
4056
4057``#include "llvm/IR/GlobalVariable.h"``
4058
4059header source: `GlobalVariable.h
4060<https://llvm.org/doxygen/GlobalVariable_8h_source.html>`_
4061
4062doxygen info: `GlobalVariable Class
4063<https://llvm.org/doxygen/classllvm_1_1GlobalVariable.html>`_
4064
4065Superclasses: GlobalValue_, Constant_, User_, Value_
4066
4067Global variables are represented with the (surprise surprise) ``GlobalVariable``
4068class.  Like functions, ``GlobalVariable``\ s are also subclasses of
4069GlobalValue_, and as such are always referenced by their address (global values
4070must live in memory, so their "name" refers to their constant address).  See
4071GlobalValue_ for more on this.  Global variables may have an initial value
4072(which must be a Constant_), and if they have an initializer, they may be marked
4073as "constant" themselves (indicating that their contents never change at
4074runtime).
4075
4076.. _m_GlobalVariable:
4077
4078Important Public Members of the ``GlobalVariable`` class
4079^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4080
4081* ``GlobalVariable(const Type *Ty, bool isConstant, LinkageTypes &Linkage,
4082  Constant *Initializer = 0, const std::string &Name = "", Module* Parent = 0)``
4083
4084  Create a new global variable of the specified type.  If ``isConstant`` is true
4085  then the global variable will be marked as unchanging for the program.  The
4086  Linkage parameter specifies the type of linkage (internal, external, weak,
4087  linkonce, appending) for the variable.  If the linkage is InternalLinkage,
4088  WeakAnyLinkage, WeakODRLinkage, LinkOnceAnyLinkage or LinkOnceODRLinkage, then
4089  the resultant global variable will have internal linkage.  AppendingLinkage
4090  concatenates together all instances (in different translation units) of the
4091  variable into a single variable but is only applicable to arrays.  See the
4092  `LLVM Language Reference <LangRef.html#modulestructure>`_ for further details
4093  on linkage types.  Optionally an initializer, a name, and the module to put
4094  the variable into may be specified for the global variable as well.
4095
4096* ``bool isConstant() const``
4097
4098  Returns true if this is a global variable that is known not to be modified at
4099  runtime.
4100
4101* ``bool hasInitializer()``
4102
4103  Returns true if this ``GlobalVariable`` has an intializer.
4104
4105* ``Constant *getInitializer()``
4106
4107  Returns the initial value for a ``GlobalVariable``.  It is not legal to call
4108  this method if there is no initializer.
4109
4110.. _BasicBlock:
4111
4112The ``BasicBlock`` class
4113------------------------
4114
4115``#include "llvm/IR/BasicBlock.h"``
4116
4117header source: `BasicBlock.h
4118<https://llvm.org/doxygen/BasicBlock_8h_source.html>`_
4119
4120doxygen info: `BasicBlock Class
4121<https://llvm.org/doxygen/classllvm_1_1BasicBlock.html>`_
4122
4123Superclass: Value_
4124
4125This class represents a single entry single exit section of the code, commonly
4126known as a basic block by the compiler community.  The ``BasicBlock`` class
4127maintains a list of Instruction_\ s, which form the body of the block.  Matching
4128the language definition, the last element of this list of instructions is always
4129a terminator instruction.
4130
4131In addition to tracking the list of instructions that make up the block, the
4132``BasicBlock`` class also keeps track of the :ref:`Function <c_Function>` that
4133it is embedded into.
4134
4135Note that ``BasicBlock``\ s themselves are Value_\ s, because they are
4136referenced by instructions like branches and can go in the switch tables.
4137``BasicBlock``\ s have type ``label``.
4138
4139.. _m_BasicBlock:
4140
4141Important Public Members of the ``BasicBlock`` class
4142^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4143
4144* ``BasicBlock(const std::string &Name = "", Function *Parent = 0)``
4145
4146  The ``BasicBlock`` constructor is used to create new basic blocks for
4147  insertion into a function.  The constructor optionally takes a name for the
4148  new block, and a :ref:`Function <c_Function>` to insert it into.  If the
4149  ``Parent`` parameter is specified, the new ``BasicBlock`` is automatically
4150  inserted at the end of the specified :ref:`Function <c_Function>`, if not
4151  specified, the BasicBlock must be manually inserted into the :ref:`Function
4152  <c_Function>`.
4153
4154* | ``BasicBlock::iterator`` - Typedef for instruction list iterator
4155  | ``BasicBlock::const_iterator`` - Typedef for const_iterator.
4156  | ``begin()``, ``end()``, ``front()``, ``back()``,
4157    ``size()``, ``empty()``
4158    STL-style functions for accessing the instruction list.
4159
4160  These methods and typedefs are forwarding functions that have the same
4161  semantics as the standard library methods of the same names.  These methods
4162  expose the underlying instruction list of a basic block in a way that is easy
4163  to manipulate.  To get the full complement of container operations (including
4164  operations to update the list), you must use the ``getInstList()`` method.
4165
4166* ``BasicBlock::InstListType &getInstList()``
4167
4168  This method is used to get access to the underlying container that actually
4169  holds the Instructions.  This method must be used when there isn't a
4170  forwarding function in the ``BasicBlock`` class for the operation that you
4171  would like to perform.  Because there are no forwarding functions for
4172  "updating" operations, you need to use this if you want to update the contents
4173  of a ``BasicBlock``.
4174
4175* ``Function *getParent()``
4176
4177  Returns a pointer to :ref:`Function <c_Function>` the block is embedded into,
4178  or a null pointer if it is homeless.
4179
4180* ``Instruction *getTerminator()``
4181
4182  Returns a pointer to the terminator instruction that appears at the end of the
4183  ``BasicBlock``.  If there is no terminator instruction, or if the last
4184  instruction in the block is not a terminator, then a null pointer is returned.
4185
4186.. _Argument:
4187
4188The ``Argument`` class
4189----------------------
4190
4191This subclass of Value defines the interface for incoming formal arguments to a
4192function.  A Function maintains a list of its formal arguments.  An argument has
4193a pointer to the parent Function.
4194
4195
4196