brintos

brintos / llvm-project-archived public Read only

0
0
Text · 83.5 KiB · 0ff4cc7 Raw
2214 lines · plain
1===============================2TableGen Programmer's Reference3===============================4 5.. sectnum::6 7.. contents::8   :local:9 10Introduction11============12 13The purpose of TableGen is to generate complex output files based on14information from source files that are significantly easier to code than the15output files would be, and also easier to maintain and modify over time. The16information is coded in a declarative style involving classes and records,17which are then processed by TableGen. The internalized records are passed on18to various *backends*, which extract information from a subset of the records19and generate one or more output files. These output files are typically20``.inc`` files for C++, but may be any type of file that the backend21developer needs.22 23This document describes the LLVM TableGen facility in detail. It is intended24for the programmer who is using TableGen to produce code for a project. If25you are looking for a simple overview, check out the :doc:`TableGen Overview26<./index>`.  The various ``*-tblgen`` commands used to invoke TableGen are27described in :doc:`tblgen Family - Description to C++28Code<../CommandGuide/tblgen>`.29 30An example of a backend is ``RegisterInfo``, which generates the register31file information for a particular target machine, for use by the LLVM32target-independent code generator. See :doc:`TableGen Backends <./BackEnds>`33for a description of the LLVM TableGen backends, and :doc:`TableGen34Backend Developer's Guide <./BackGuide>` for a guide to writing a new35backend.36 37Here are a few of the things backends can do.38 39* Generate the register file information for a particular target machine.40 41* Generate the instruction definitions for a target.42 43* Generate the patterns that the code generator uses to match instructions44  to intermediate representation (IR) nodes.45 46* Generate semantic attribute identifiers for Clang.47 48* Generate abstract syntax tree (AST) declaration node definitions for Clang.49 50* Generate AST statement node definitions for Clang.51 52 53Concepts54--------55 56TableGen source files contain two primary items: *abstract records* and57*concrete records*. In this and other TableGen documents, abstract records58are called *classes.* (These classes are different from C++ classes and do59not map onto them.) In addition, concrete records are usually just called60records, although sometimes the term *record* refers to both classes and61concrete records. The distinction should be clear in context.62 63Classes and concrete records have a unique *name*, either chosen by64the programmer or generated by TableGen. Associated with that name65is a list of *fields* with values and an optional list of *parent classes*66(sometimes called base or super classes). The fields are the primary data that67backends will process. Note that TableGen assigns no meaning to fields; the68meanings are entirely up to the backends and the programs that incorporate69the output of those backends.70 71.. note::72 73  The term "parent class" can refer to a class that is a parent of another74  class, and also to a class from which a concrete record inherits. This75  nonstandard use of the term arises because TableGen treats classes and76  concrete records similarly.77 78A backend processes some subset of the concrete records built by the79TableGen parser and emits the output files. These files are usually C++80``.inc`` files that are included by the programs that require the data in81those records. However, a backend can produce any type of output files. For82example, it could produce a data file containing messages tagged with83identifiers and substitution parameters. In a complex use case such as the84LLVM code generator, there can be many concrete records and some of them can85have an unexpectedly large number of fields, resulting in large output files.86 87In order to reduce the complexity of TableGen files, classes are used to88abstract out groups of record fields. For example, a few classes may89abstract the concept of a machine register file, while other classes may90abstract the instruction formats, and still others may abstract the91individual instructions. TableGen allows an arbitrary hierarchy of classes,92so that the abstract classes for two concepts can share a third superclass that93abstracts common "sub-concepts" from the two original concepts.94 95In order to make classes more useful, a concrete record (or another class)96can request a class as a parent class and pass *template arguments* to it.97These template arguments can be used in the fields of the parent class to98initialize them in a custom manner. That is, record or class ``A`` can99request parent class ``S`` with one set of template arguments, while record or class100``B`` can request ``S`` with a different set of arguments. Without template101arguments, many more classes would be required, one for each combination of102the template arguments.103 104Both classes and concrete records can include fields that are uninitialized.105The uninitialized "value" is represented by a question mark (``?``). Classes106often have uninitialized fields that are expected to be filled in when those107classes are inherited by concrete records. Even so, some fields of concrete108records may remain uninitialized.109 110TableGen provides *multiclasses* to collect a group of record definitions in111one place. A multiclass is a sort of macro that can be "invoked" to define112multiple concrete records all at once. A multiclass can inherit from other113multiclasses, which means that the multiclass inherits all the definitions114from its parent multiclasses.115 116`Appendix C: Sample Record`_ illustrates a complex record in the Intel X86117target and the simple way in which it is defined.118 119Source Files120============121 122TableGen source files are plain ASCII text files. The files can contain123statements, comments, and blank lines (see `Lexical Analysis`_). The standard file124extension for TableGen files is ``.td``.125 126TableGen files can grow quite large, so there is an include mechanism that127allows one file to include the content of another file (see `Include128Files`_). This allows large files to be broken up into smaller ones, and129also provides a simple library mechanism where multiple source files can130include the same library file.131 132TableGen supports a simple preprocessor that can be used to conditionalize133portions of ``.td`` files. See `Preprocessing Facilities`_ for more134information.135 136Lexical Analysis137================138 139The lexical and syntax notation used here is intended to imitate140`Python's`_ notation. In particular, for lexical definitions, the productions141operate at the character level and there is no implied whitespace between142elements. The syntax definitions operate at the token level, so there is143implied whitespace between tokens.144 145.. _`Python's`: http://docs.python.org/py3k/reference/introduction.html#notation146 147TableGen supports BCPL-style comments (``// ...``) and nestable C-style148comments (``/* ... */``).149TableGen also provides simple `Preprocessing Facilities`_.150 151Formfeed characters may be used freely in files to produce page breaks when152the file is printed for review.153 154The following are the basic punctuation tokens::155 156   - + [ ] { } ( ) < > : ; . ... = ? #157 158Literals159--------160 161Numeric literals take one of the following forms:162 163.. productionlist::164   TokInteger: `DecimalInteger` | `HexInteger` | `BinInteger`165   DecimalInteger: ["+" | "-"] ("0"..."9")+166   HexInteger: "0x" ("0"..."9" | "a"..."f" | "A"..."F")+167   BinInteger: "0b" ("0" | "1")+168 169Observe that the :token:`DecimalInteger` token includes the optional ``+``170or ``-`` sign, unlike most languages where the sign would be treated as a171unary operator.172 173TableGen has two kinds of string literals:174 175.. productionlist::176   TokString: '"' (non-'"' characters and escapes) '"'177   TokCode: "[{" (text not containing "}]") "}]"178 179A :token:`TokCode` is nothing more than a multi-line string literal180delimited by ``[{`` and ``}]``. It can break across lines and the181line breaks are retained in the string.182 183The current implementation accepts the following escape sequences::184 185   \\ \' \" \t \n186 187Identifiers188-----------189 190TableGen has name- and identifier-like tokens, which are case-sensitive.191 192.. productionlist::193   ualpha: "a"..."z" | "A"..."Z" | "_"194   TokIdentifier: ("0"..."9")* `ualpha` (`ualpha` | "0"..."9")*195   TokVarName: "$" `ualpha` (`ualpha` |  "0"..."9")*196 197Note that, unlike most languages, TableGen allows :token:`TokIdentifier` to198begin with an integer. In case of ambiguity, a token is interpreted as a199numeric literal rather than an identifier.200 201TableGen has the following reserved keywords, which cannot be used as202identifiers::203 204   assert     bit           bits          class         code205   dag        def           dump          else          false206   foreach    defm          defset        defvar        field207   if         in            include       int           let208   list       multiclass    string        then          true209 210.. warning::211  The ``field`` reserved word is deprecated, except when used with the212  CodeEmitterGen backend where it's used to distinguish normal record213  fields from encoding fields.214 215Bang operators216--------------217 218TableGen provides "bang operators" that have a wide variety of uses:219 220.. productionlist::221   BangOperator: one of222               : !add         !and         !cast         !con         !dag223               : !div         !empty       !eq           !exists      !filter224               : !find        !foldl       !foreach      !ge          !getdagarg225               : !getdagname  !getdagop    !getdagopname !gt          !head226               : !if          !initialized !instances    !interleave  !isa227               : !le          !listconcat  !listflatten  !listremove  !listsplat228               : !logtwo      !lt          !match        !mul         !ne229               : !not         !or          !range        !repr        !setdagarg230               : !setdagname  !setdagop    !setdagopname !shl         !size231               : !sra         !srl         !strconcat    !sub         !subst232               : !substr      !tail        !tolower      !toupper     !xor233 234The ``!cond`` operator has a slightly different235syntax compared to other bang operators, so it is defined separately:236 237.. productionlist::238   CondOperator: !cond239 240See `Appendix A: Bang Operators`_ for a description of each bang operator.241 242Include files243-------------244 245TableGen has an include mechanism. The content of the included file246lexically replaces the ``include`` directive and is then parsed as if it were247originally in the main file.248 249.. productionlist::250   IncludeDirective: "include" `TokString`251 252Portions of the main file and included files can be conditionalized using253preprocessor directives.254 255.. productionlist::256   PreprocessorDirective: "#define" | "#ifdef" | "#ifndef"257 258Types259=====260 261The TableGen language is statically typed, using a simple but complete type262system. Types are used to check for errors, to perform implicit conversions,263and to help interface designers constrain the allowed input. Every value is264required to have an associated type.265 266TableGen supports a mixture of low-level types (e.g., ``bit``) and267high-level types (e.g., ``dag``). This flexibility allows you to describe a268wide range of records conveniently and compactly.269 270.. productionlist::271   Type: "bit" | "int" | "string" | "dag" | "code"272       :| "bits" "<" `TokInteger` ">"273       :| "list" "<" `Type` ">"274       :| `ClassID`275   ClassID: `TokIdentifier`276 277``bit``278    A ``bit`` is a boolean value that can be 0 or 1.279 280``int``281    The ``int`` type represents a simple 64-bit integer value, such as 5 or282    -42.283 284``string``285    The ``string`` type represents an ordered sequence of characters of arbitrary286    length.287 288``code``289    The keyword ``code`` is an alias for ``string`` which may be used to290    indicate string values that are code.291 292``bits<``\ *n*\ ``>``293    The ``bits`` type is a fixed-sized integer of arbitrary length *n* that294    is treated as separate bits. These bits can be accessed individually.295    A field of this type is useful for representing an instruction operation296    code, register number, or address mode/register/displacement.  The bits of297    the field can be set individually or as subfields. For example, in an298    instruction address, the addressing mode, base register number, and299    displacement can be set separately.300 301``list<``\ *type*\ ``>``302    This type represents a list whose elements are of the *type* specified in303    angle brackets. The element type is arbitrary; it can even be another304    list type. List elements are indexed from 0.305 306``dag``307    This type represents a nestable directed acyclic graph (DAG) of nodes.308    Each node has an *operator* and zero or more *arguments* (or *operands*).309    An argument can be310    another ``dag`` object, allowing an arbitrary tree of nodes and edges.311    As an example, DAGs are used to represent code patterns for use by312    the code generator instruction selection algorithms. See `Directed313    acyclic graphs (DAGs)`_ for more details;314 315:token:`ClassID`316    Specifying a class name in a type context indicates317    that the type of the defined value must318    be a subclass of the specified class. This is useful in conjunction with319    the ``list`` type; for example, to constrain the elements of the list to a320    common base class (e.g., a ``list<Register>`` can only contain definitions321    derived from the ``Register`` class).322    The :token:`ClassID` must name a class that has been previously323    declared or defined.324 325 326Values and Expressions327======================328 329There are many contexts in TableGen statements where a value is required. A330common example is in the definition of a record, where each field is331specified by a name and an optional value. TableGen allows for a reasonable332number of different forms when building up value expressions. These forms333allow the TableGen file to be written in a syntax that is natural for the334application.335 336Note that all of the values have rules for converting them from one type to337another. For example, these rules allow you to assign a value like ``7``338to an entity of type ``bits<4>``.339 340.. productionlist::341   Value: `SimpleValue` `ValueSuffix`*342        :| `Value` "#" [`Value`]343   ValueSuffix: "{" `RangeList` "}"344              :| "[" `SliceElements` "]"345              :| "." `TokIdentifier`346   RangeList: `RangePiece` ("," `RangePiece`)*347   RangePiece: `TokInteger`348             :| `TokInteger` "..." `TokInteger`349             :| `TokInteger` "-" `TokInteger`350             :| `TokInteger` `TokInteger`351   SliceElements: (`SliceElement` ",")* `SliceElement` ","?352   SliceElement: `Value`353               :| `Value` "..." `Value`354               :| `Value` "-" `Value`355               :| `Value` `TokInteger`356 357.. warning::358  The peculiar last form of :token:`RangePiece` and :token:`SliceElement` is359  due to the fact that the "``-``" is included in the :token:`TokInteger`,360  hence ``1-5`` gets lexed as two consecutive tokens, with values ``1`` and361  ``-5``, instead of "1", "-", and "5".362  The use of hyphen as the range punctuation is deprecated.363 364Simple values365-------------366 367The :token:`SimpleValue` has a number of forms.368 369.. productionlist::370   SimpleValue: `SimpleValue1`371              :| `SimpleValue2`372              :| `SimpleValue3`373              :| `SimpleValue4`374              :| `SimpleValue5`375              :| `SimpleValue6`376              :| `SimpleValue7`377              :| `SimpleValue8`378              :| `SimpleValue9`379   SimpleValue1: `TokInteger` | `TokString`+ | `TokCode`380 381A value can be an integer literal, a string literal, or a code literal.382Multiple adjacent string literals are concatenated as in C/C++; the simple383value is the concatenation of the strings. Code literals become strings and384are then indistinguishable from them.385 386.. productionlist::387   SimpleValue2: "true" | "false"388 389The ``true`` and ``false`` literals are essentially syntactic sugar for the390integer values 1 and 0. They improve the readability of TableGen files when391boolean values are used in field initializations, bit sequences, ``if``392statements, etc. When parsed, these literals are converted to integers.393 394.. note::395 396  Although ``true`` and ``false`` are literal names for 1 and 0, we397  recommend as a stylistic rule that you use them for boolean398  values only.399 400.. productionlist::401   SimpleValue3: "?"402 403A question mark represents an uninitialized value.404 405.. productionlist::406   SimpleValue4: "{" [`ValueList`] "}"407   ValueList: `ValueListNE`408   ValueListNE: `Value` ("," `Value`)*409 410This value represents a sequence of bits, which can be used to initialize a411``bits<``\ *n*\ ``>`` field (note the braces). When doing so, the values412must represent a total of *n* bits.413 414.. productionlist::415   SimpleValue5: "[" `ValueList` "]" ["<" `Type` ">"]416 417This value is a list initializer (note the brackets). The values in brackets418are the elements of the list. The optional :token:`Type` can be used to419indicate a specific element type; otherwise the element type is inferred420from the given values. TableGen can usually infer the type, although421sometimes not when the value is the empty list (``[]``).422 423.. productionlist::424   SimpleValue6: "(" `DagArg` [`DagArgList`] ")"425   DagArgList: `DagArg` ("," `DagArg`)*426   DagArg: `Value` [":" `TokVarName`] | `TokVarName`427 428This represents a DAG initializer (note the parentheses).  The first429:token:`DagArg` is called the "operator" of the DAG and must be a record.430See `Directed acyclic graphs (DAGs)`_ for more details.431 432.. productionlist::433   SimpleValue7: `TokIdentifier`434 435The resulting value is the value of the entity named by the identifier. The436possible identifiers are described here, but the descriptions will make more437sense after reading the remainder of this guide.438 439.. The code for this is exceptionally abstruse. These examples are a440   best-effort attempt.441 442* A template argument of a ``class``, such as the use of ``Bar`` in::443 444     class Foo <int Bar> {445       int Baz = Bar;446     }447 448* The implicit template argument ``NAME`` in a ``class`` or ``multiclass``449  definition (see `NAME`_).450 451* A field local to a ``class``, such as the use of ``Bar`` in::452 453     class Foo {454       int Bar = 5;455       int Baz = Bar;456     }457 458* The name of a record definition, such as the use of ``Bar`` in the459  definition of ``Foo``::460 461     def Bar : SomeClass {462       int X = 5;463     }464 465     def Foo {466       SomeClass Baz = Bar;467     }468 469* A field local to a record definition, such as the use of ``Bar`` in::470 471     def Foo {472       int Bar = 5;473       int Baz = Bar;474     }475 476  Fields inherited from the record's parent classes can be accessed the same way.477 478* A template argument of a ``multiclass``, such as the use of ``Bar`` in::479 480     multiclass Foo <int Bar> {481       def : SomeClass<Bar>;482     }483 484* A variable defined with the ``defvar`` or ``defset`` statements.485 486* The iteration variable of a ``foreach``, such as the use of ``i`` in::487 488     foreach i = 0...5 in489       def Foo#i;490 491.. productionlist::492   SimpleValue8: `ClassID` "<" `ArgValueList` ">"493 494This form creates a new anonymous record definition (as would be created by an495unnamed ``def`` inheriting from the given class with the given template496arguments; see `def`_) and the value is that record. A field of the record can be497obtained using a suffix; see `Suffixed Values`_.498 499Invoking a class in this manner can provide a simple subroutine facility.500See `Using Classes as Subroutines`_ for more information.501 502.. productionlist::503   SimpleValue9: `BangOperator` ["<" `Type` ">"] "(" `ValueListNE` ")"504              :| `CondOperator` "(" `CondClause` ("," `CondClause`)* ")"505   CondClause: `Value` ":" `Value`506 507The bang operators provide functions that are not available with the other508simple values. Except in the case of ``!cond``, a bang operator takes a list509of arguments enclosed in parentheses and performs some function on those510arguments, producing a value for that bang operator. The ``!cond`` operator511takes a list of pairs of arguments separated by colons. See `Appendix A:512Bang Operators`_ for a description of each bang operator.513 514The `Type` is only accepted for certain bang operators, and must not be515``code``.516 517Suffixed values518---------------519 520The :token:`SimpleValue` values described above can be specified with521certain suffixes. The purpose of a suffix is to obtain a subvalue of the522primary value. Here are the possible suffixes for some primary *value*.523 524*value*\ ``{17}``525    The final value is bit 17 of the integer *value* (note the braces).526 527*value*\ ``{8...15}``528    The final value is bits 8--15 of the integer *value*. The order of the529    bits can be reversed by specifying ``{15...8}``.530 531*value*\ ``[i]``532    The final value is element `i` of the list *value* (note the brackets).533    In other words, the brackets act as a subscripting operator on the list.534    This is the case only when a single element is specified.535 536*value*\ ``[i,]``537    The final value is a list that contains a single element `i` of the list.538    In short, a list slice with a single element.539 540*value*\ ``[4...7,17,2...3,4]``541    The final value is a new list that is a slice of the list *value*.542    The new list contains elements 4, 5, 6, 7, 17, 2, 3, and 4.543    Elements may be included multiple times and in any order. This is the result544    only when more than one element is specified.545 546    *value*\ ``[i,m...n,j,ls]``547        Each element may be an expression (variables, bang operators).548        The type of `m` and `n` should be `int`.549        The type of `i`, `j`, and `ls` should be either `int` or `list<int>`.550 551*value*\ ``.``\ *field*552    The final value is the value of the specified *field* in the specified553    record *value*.554 555The paste operator556------------------557 558The paste operator (``#``) is the only infix operator available in TableGen559expressions. It allows you to concatenate strings or lists, but has a few560unusual features.561 562The paste operator can be used when specifying the record name in a563:token:`Def` or :token:`Defm` statement, in which case it must construct a564string. If an operand is an undefined name (:token:`TokIdentifier`) or the565name of a global :token:`Defvar` or :token:`Defset`, it is treated as a566verbatim string of characters. The value of a global name is not used.567 568The paste operator can be used in all other value expressions, in which case569it can construct a string or a list. Rather oddly, but consistent with the570previous case, if the *right-hand-side* operand is an undefined name or a571global name, it is treated as a verbatim string of characters. The572left-hand-side operand is treated normally.573 574Values can have a trailing paste operator, in which case the left-hand-side575operand is concatenated to an empty string.576 577`Appendix B: Paste Operator Examples`_ presents examples of the behavior of578the paste operator.579 580Statements581==========582 583The following statements may appear at the top level of TableGen source584files.585 586.. productionlist::587   TableGenFile: (`Statement` | `IncludeDirective`588            :| `PreprocessorDirective`)*589   Statement: `Assert` | `Class` | `Def` | `Defm` | `Defset` | `Deftype`590            :| `Defvar` | `Dump`  | `Foreach` | `If` | `Let` | `MultiClass`591 592The following sections describe each of these top-level statements.593 594 595``class`` --- define an abstract record class596---------------------------------------------597 598A ``class`` statement defines an abstract record class from which other599classes and records can inherit.600 601.. productionlist::602   Class: "class" `ClassID` [`TemplateArgList`] `RecordBody`603   TemplateArgList: "<" `TemplateArgDecl` ("," `TemplateArgDecl`)* ">"604   TemplateArgDecl: `Type` `TokIdentifier` ["=" `Value`]605 606A class can be parameterized by a list of "template arguments," whose values607can be used in the class's record body. These template arguments are608specified each time the class is inherited by another class or record.609 610If a template argument is not assigned a default value with ``=``, it is611uninitialized (has the "value" ``?``) and must be specified in the template612argument list when the class is inherited (required argument). If an613argument is assigned a default value, then it need not be specified in the614argument list (optional argument). In the declaration, all required template615arguments must precede any optional arguments. The template argument default616values are evaluated from left to right.617 618The :token:`RecordBody` is defined below. It can include a list of619parent classes from which the current class inherits, along with field620definitions and other statements. When a class ``C`` inherits from another621class ``D``, the fields of ``D`` are effectively merged into the fields of622``C``.623 624A given class can only be defined once. A ``class`` statement is625considered to define the class if *any* of the following are true (the626:token:`RecordBody` elements are described below).627 628* The :token:`TemplateArgList` is present, or629* The :token:`ParentClassList` in the :token:`RecordBody` is present, or630* The :token:`Body` in the :token:`RecordBody` is present and not empty.631 632You can declare an empty class by specifying an empty :token:`TemplateArgList`633and an empty :token:`RecordBody`. This can serve as a restricted form of634forward declaration. Note that records derived from a forward-declared635class will inherit no fields from it, because those records are built when636their declarations are parsed, and thus before the class is finally defined.637 638.. _NAME:639 640Every class has an implicit template argument named ``NAME`` (uppercase),641which is bound to the name of the :token:`Def` or :token:`Defm` inheriting642from the class. If the class is inherited by an anonymous record, the name643is unspecified but globally unique.644 645See `Examples: classes and records`_ for examples.646 647Record Bodies648`````````````649 650Record bodies appear in both class and record definitions. A record body can651include a parent class list, which specifies the classes from which the652current class or record inherits fields. Such classes are called the653parent classes of the class or record. The record body also654includes the main body of the definition, which contains the specification655of the fields of the class or record.656 657.. productionlist::658   RecordBody: `ParentClassList` `Body`659   ParentClassList: [":" `ParentClassListNE`]660   ParentClassListNE: `ClassRef` ("," `ClassRef`)*661   ClassRef: (`ClassID` | `MultiClassID`) ["<" [`ArgValueList`] ">"]662   ArgValueList: `PostionalArgValueList` [","] `NamedArgValueList`663   PostionalArgValueList: [`Value` {"," `Value`}*]664   NamedArgValueList: [`NameValue` "=" `Value` {"," `NameValue` "=" `Value`}*]665 666A :token:`ParentClassList` containing a :token:`MultiClassID` is valid only667in the class list of a ``defm`` statement. In that case, the ID must be the668name of a multiclass.669 670The argument values can be specified in two forms:671 672* Positional argument (``value``). The value is assigned to the argument in the673  corresponding position. For ``Foo<a0, a1>``, ``a0`` will be assigned to the first674  argument and ``a1`` will be assigned to the second argument.675* Named argument (``name=value``). The value is assigned to the argument with676  the specified name. For ``Foo<a=a0, b=a1>``, ``a0`` will be assigned to the677  argument with name ``a`` and ``a1`` will be assigned to the argument with678  name ``b``.679 680Required arguments can also be specified as a named argument.681 682Note that the argument can only be specified once regardless of the way (named683or positional) to specify and positional arguments should precede named684arguments.685 686.. productionlist::687   Body: ";" | "{" `BodyItem`* "}"688   BodyItem: `Type` `TokIdentifier` ["=" `Value`] ";"689           :| "let" `TokIdentifier` ["{" `RangeList` "}"] "=" `Value` ";"690           :| "defvar" `TokIdentifier` "=" `Value` ";"691           :| `Assert`692 693A field definition in the body specifies a field to be included in the class694or record. If no initial value is specified, then the field's value is695uninitialized. The type must be specified; TableGen will not infer it from696the value.697 698The ``let`` form is used to reset a field to a new value. This can be done699for fields defined directly in the body or fields inherited from parent700classes.  A :token:`RangeList` can be specified to reset certain bits in a701``bit<n>`` field.702 703The ``defvar`` form defines a variable whose value can be used in other704value expressions within the body. The variable is not a field: it does not705become a field of the class or record being defined. Variables are provided706to hold temporary values while processing the body. See `Defvar in a Record707Body`_ for more details.708 709When class ``C2`` inherits from class ``C1``, it acquires all the field710definitions of ``C1``. As those definitions are merged into class ``C2``, any711template arguments passed to ``C1`` by ``C2`` are substituted into the712definitions. In other words, the abstract record fields defined by ``C1`` are713expanded with the template arguments before being merged into ``C2``.714 715 716.. _def:717 718``def`` --- define a concrete record719------------------------------------720 721A ``def`` statement defines a new concrete record.722 723.. productionlist::724   Def: "def" [`NameValue`] `RecordBody`725   NameValue: `Value` (parsed in a special mode)726 727The name value is optional. If specified, it is parsed in a special mode728where undefined (unrecognized) identifiers are interpreted as literal729strings. In particular, global identifiers are considered unrecognized.730These include global variables defined by ``defvar`` and ``defset``. A731record name can be the null string.732 733If no name value is given, the record is *anonymous*. The final name of an734anonymous record is unspecified but globally unique.735 736Special handling occurs if a ``def`` appears inside a ``multiclass``737statement. See the ``multiclass`` section below for details.738 739A record can inherit from one or more classes by specifying the740:token:`ParentClassList` clause at the beginning of its record body. All of741the fields in the parent classes are added to the record. If two or more742parent classes provide the same field, the record ends up with the field value743of the last parent class.744 745As a special case, the name of a record can be passed as a template argument746to that record's parent classes. For example:747 748.. code-block:: text749 750  class A <dag d> {751    dag the_dag = d;752  }753 754  def rec1 : A<(ops rec1)>;755 756The DAG ``(ops rec1)`` is passed as a template argument to class ``A``. Notice757that the DAG includes ``rec1``, the record being defined.758 759The steps taken to create a new record are somewhat complex. See `How760records are built`_.761 762See `Examples: classes and records`_ for examples.763 764 765Examples: classes and records766-----------------------------767 768Here is a simple TableGen file with one class and two record definitions.769 770.. code-block:: text771 772  class C {773    bit V = true;774  }775 776  def X : C;777  def Y : C {778    let V = false;779    string Greeting = "Hello!";780  }781 782First, the abstract class ``C`` is defined. It has one field named ``V``783that is a bit initialized to true.784 785Next, two records are defined, derived from class ``C``; that is, with ``C``786as their parent class. Thus they both inherit the ``V`` field. Record ``Y``787also defines another string field, ``Greeting``, which is initialized to788``"Hello!"``. In addition, ``Y`` overrides the inherited ``V`` field,789setting it to false.790 791A class is useful for isolating the common features of multiple records in792one place. A class can initialize common fields to default values, but793records inheriting from that class can override the defaults.794 795TableGen supports the definition of parameterized classes as well as796nonparameterized ones. Parameterized classes specify a list of variable797declarations, which may optionally have defaults, that are bound when the798class is specified as a parent class of another class or record.799 800.. code-block:: text801 802  class FPFormat <bits<3> val> {803    bits<3> Value = val;804  }805 806  def NotFP      : FPFormat<0>;807  def ZeroArgFP  : FPFormat<1>;808  def OneArgFP   : FPFormat<2>;809  def OneArgFPRW : FPFormat<3>;810  def TwoArgFP   : FPFormat<4>;811  def CompareFP  : FPFormat<5>;812  def CondMovFP  : FPFormat<6>;813  def SpecialFP  : FPFormat<7>;814 815The purpose of the ``FPFormat`` class is to act as a sort of enumerated816type. It provides a single field, ``Value``, which holds a 3-bit number. Its817template argument, ``val``, is used to set the ``Value`` field.  Each of the818eight records is defined with ``FPFormat`` as its parent class. The819enumeration value is passed in angle brackets as the template argument. Each820record will inherit the ``Value`` field with the appropriate enumeration821value.822 823Here is a more complex example of classes with template arguments. First, we824define a class similar to the ``FPFormat`` class above. It takes a template825argument and uses it to initialize a field named ``Value``. Then we define826four records that inherit the ``Value`` field with its four different827integer values.828 829.. code-block:: text830 831  class ModRefVal <bits<2> val> {832    bits<2> Value = val;833  }834 835  def None   : ModRefVal<0>;836  def Mod    : ModRefVal<1>;837  def Ref    : ModRefVal<2>;838  def ModRef : ModRefVal<3>;839 840This is somewhat contrived, but let's say we would like to examine the two841bits of the ``Value`` field independently. We can define a class that842accepts a ``ModRefVal`` record as a template argument and splits up its843value into two fields, one bit each. Then we can define records that inherit from844``ModRefBits`` and so acquire two fields from it, one for each bit in the845``ModRefVal`` record passed as the template argument.846 847.. code-block:: text848 849  class ModRefBits <ModRefVal mrv> {850    // Break the value up into its bits, which can provide a nice851    // interface to the ModRefVal values.852    bit isMod = mrv.Value{0};853    bit isRef = mrv.Value{1};854  }855 856  // Example uses.857  def foo   : ModRefBits<Mod>;858  def bar   : ModRefBits<Ref>;859  def snork : ModRefBits<ModRef>;860 861This illustrates how one class can be defined to reorganize the862fields in another class, thus hiding the internal representation of that863other class.864 865Running ``llvm-tblgen`` on the example prints the following definitions:866 867.. code-block:: text868 869  def bar {      // Value870    bit isMod = 0;871    bit isRef = 1;872  }873  def foo {      // Value874    bit isMod = 1;875    bit isRef = 0;876  }877  def snork {      // Value878    bit isMod = 1;879    bit isRef = 1;880  }881 882``let`` --- override fields in classes or records883-------------------------------------------------884 885A ``let`` statement collects a set of field values (sometimes called886*bindings*) and applies them to all the classes and records defined by887statements within the scope of the ``let``.888 889.. productionlist::890   Let:  "let" `LetList` "in" "{" `Statement`* "}"891      :| "let" `LetList` "in" `Statement`892   LetList: `LetItem` ("," `LetItem`)*893   LetItem: `TokIdentifier` ["<" `RangeList` ">"] "=" `Value`894 895The ``let`` statement establishes a scope, which is a sequence of statements896in braces or a single statement with no braces. The bindings in the897:token:`LetList` apply to the statements in that scope.898 899The field names in the :token:`LetList` must name fields in classes inherited by900the classes and records defined in the statements. The field values are901applied to the classes and records *after* the records inherit all the fields from902their parent classes. So the ``let`` acts to override inherited field903values. A ``let`` cannot override the value of a template argument.904 905Top-level ``let`` statements are often useful when a few fields need to be906overridden in several records. Here are two examples. Note that ``let``907statements can be nested.908 909.. code-block:: text910 911  let isTerminator = true, isReturn = true, isBarrier = true, hasCtrlDep = true in912    def RET : I<0xC3, RawFrm, (outs), (ins), "ret", [(X86retflag 0)]>;913 914  let isCall = true in915    // All calls clobber the non-callee saved registers...916    let Defs = [EAX, ECX, EDX, FP0, FP1, FP2, FP3, FP4, FP5, FP6, ST0,917                MM0, MM1, MM2, MM3, MM4, MM5, MM6, MM7, XMM0, XMM1, XMM2,918                XMM3, XMM4, XMM5, XMM6, XMM7, EFLAGS] in {919      def CALLpcrel32 : Ii32<0xE8, RawFrm, (outs), (ins i32imm:$dst, variable_ops),920                             "call\t${dst:call}", []>;921      def CALL32r     : I<0xFF, MRM2r, (outs), (ins GR32:$dst, variable_ops),922                          "call\t{*}$dst", [(X86call GR32:$dst)]>;923      def CALL32m     : I<0xFF, MRM2m, (outs), (ins i32mem:$dst, variable_ops),924                          "call\t{*}$dst", []>;925    }926 927Note that a top-level ``let`` will not override fields defined in the classes or records928themselves.929 930 931``multiclass`` --- define multiple records932------------------------------------------933 934While classes with template arguments are a good way to factor out commonality935between multiple records, multiclasses allow a convenient method for936defining many records at once. For example, consider a 3-address937instruction architecture whose instructions come in two formats: ``reg = reg938op reg`` and ``reg = reg op imm`` (e.g., SPARC). We would like to specify in939one place that these two common formats exist, then in a separate place940specify what all the operations are. The ``multiclass`` and ``defm``941statements accomplish this goal. You can think of a multiclass as a macro or942template that expands into multiple records.943 944.. productionlist::945   MultiClass: "multiclass" `TokIdentifier` [`TemplateArgList`]946             : `ParentClassList`947             : "{" `MultiClassStatement`+ "}"948   MultiClassID: `TokIdentifier`949   MultiClassStatement: `Assert` | `Def` | `Defm` | `Defvar` | `Foreach` | `If` | `Let`950 951As with regular classes, the multiclass has a name and can accept template952arguments. A multiclass can inherit from other multiclasses, which causes953the other multiclasses to be expanded and contribute to the record954definitions in the inheriting multiclass. The body of the multiclass955contains a series of statements that define records, using :token:`Def` and956:token:`Defm`. In addition, :token:`Defvar`, :token:`Foreach`, and957:token:`Let` statements can be used to factor out even more common elements.958The :token:`If` and :token:`Assert` statements can also be used.959 960Also as with regular classes, the multiclass has the implicit template961argument ``NAME`` (see NAME_). When a named (non-anonymous) record is962defined in a multiclass and the record's name does not include a use of the963template argument ``NAME``, such a use is automatically *prepended*964to the name.  That is, the following are equivalent inside a multiclass::965 966    def Foo ...967    def NAME # Foo ...968 969The records defined in a multiclass are created when the multiclass is970"instantiated" or "invoked" by a ``defm`` statement outside the multiclass971definition. Each ``def`` statement in the multiclass produces a record. As972with top-level ``def`` statements, these definitions can inherit from973multiple parent classes.974 975See `Examples: multiclasses and defms`_ for examples.976 977 978``defm`` --- invoke multiclasses to define multiple records979-----------------------------------------------------------980 981Once multiclasses have been defined, you use the ``defm`` statement to982"invoke" them and process the multiple record definitions in those983multiclasses. Those record definitions are specified by ``def``984statements in the multiclasses, and indirectly by ``defm`` statements.985 986.. productionlist::987   Defm: "defm" [`NameValue`] `ParentClassList` ";"988 989The optional :token:`NameValue` is formed in the same way as the name of a990``def``. The :token:`ParentClassList` is a colon followed by a list of at991least one multiclass and any number of regular classes. The multiclasses992must precede the regular classes. Note that the ``defm`` does not have a993body.994 995This statement instantiates all the records defined in all the specified996multiclasses, either directly by ``def`` statements or indirectly by997``defm`` statements. These records also receive the fields defined in any998regular classes included in the parent class list. This is useful for adding999a common set of fields to all the records created by the ``defm``.1000 1001The name is parsed in the same special mode used by ``def``. If the name is1002not included, an unspecified but globally unique name is provided. That is,1003the following examples end up with different names::1004 1005    defm    : SomeMultiClass<...>;   // A globally unique name.1006    defm "" : SomeMultiClass<...>;   // An empty name.1007 1008The ``defm`` statement can be used in a multiclass body. When this occurs,1009the second variant is equivalent to::1010 1011  defm NAME : SomeMultiClass<...>;1012 1013More generally, when ``defm`` occurs in a multiclass and its name does not1014include a use of the implicit template argument ``NAME``, then ``NAME`` will1015be prepended automatically. That is, the following are equivalent inside a1016multiclass::1017 1018    defm Foo        : SomeMultiClass<...>;1019    defm NAME # Foo : SomeMultiClass<...>;1020 1021See `Examples: multiclasses and defms`_ for examples.1022 1023Examples: multiclasses and defms1024--------------------------------1025 1026Here is a simple example using ``multiclass`` and ``defm``.  Consider a10273-address instruction architecture whose instructions come in two formats:1028``reg = reg op reg`` and ``reg = reg op imm`` (immediate). The SPARC is an1029example of such an architecture.1030 1031.. code-block:: text1032 1033  def ops;1034  def GPR;1035  def Imm;1036  class inst <int opc, string asmstr, dag operandlist>;1037 1038  multiclass ri_inst <int opc, string asmstr> {1039    def _rr : inst<opc, !strconcat(asmstr, " $dst, $src1, $src2"),1040                     (ops GPR:$dst, GPR:$src1, GPR:$src2)>;1041    def _ri : inst<opc, !strconcat(asmstr, " $dst, $src1, $src2"),1042                     (ops GPR:$dst, GPR:$src1, Imm:$src2)>;1043  }1044 1045  // Define records for each instruction in the RR and RI formats.1046  defm ADD : ri_inst<0b111, "add">;1047  defm SUB : ri_inst<0b101, "sub">;1048  defm MUL : ri_inst<0b100, "mul">;1049 1050Each use of the ``ri_inst`` multiclass defines two records, one with the1051``_rr`` suffix and one with ``_ri``. Recall that the name of the ``defm``1052that uses a multiclass is prepended to the names of the records defined in1053that multiclass. So the resulting definitions are named::1054 1055  ADD_rr, ADD_ri1056  SUB_rr, SUB_ri1057  MUL_rr, MUL_ri1058 1059Without the ``multiclass`` feature, the instructions would have to be1060defined as follows.1061 1062.. code-block:: text1063 1064  def ops;1065  def GPR;1066  def Imm;1067  class inst <int opc, string asmstr, dag operandlist>;1068 1069  class rrinst <int opc, string asmstr>1070    : inst<opc, !strconcat(asmstr, " $dst, $src1, $src2"),1071             (ops GPR:$dst, GPR:$src1, GPR:$src2)>;1072 1073  class riinst <int opc, string asmstr>1074    : inst<opc, !strconcat(asmstr, " $dst, $src1, $src2"),1075             (ops GPR:$dst, GPR:$src1, Imm:$src2)>;1076 1077  // Define records for each instruction in the RR and RI formats.1078  def ADD_rr : rrinst<0b111, "add">;1079  def ADD_ri : riinst<0b111, "add">;1080  def SUB_rr : rrinst<0b101, "sub">;1081  def SUB_ri : riinst<0b101, "sub">;1082  def MUL_rr : rrinst<0b100, "mul">;1083  def MUL_ri : riinst<0b100, "mul">;1084 1085A ``defm`` can be used in a multiclass to "invoke" other multiclasses and1086create the records defined in those multiclasses in addition to the records1087defined in the current multiclass. In the following example, the ``basic_s``1088and ``basic_p`` multiclasses contain ``defm`` statements that refer to the1089``basic_r`` multiclass. The ``basic_r`` multiclass contains only ``def``1090statements.1091 1092.. code-block:: text1093 1094  class Instruction <bits<4> opc, string Name> {1095    bits<4> opcode = opc;1096    string name = Name;1097  }1098 1099  multiclass basic_r <bits<4> opc> {1100    def rr : Instruction<opc, "rr">;1101    def rm : Instruction<opc, "rm">;1102  }1103 1104  multiclass basic_s <bits<4> opc> {1105    defm SS : basic_r<opc>;1106    defm SD : basic_r<opc>;1107    def X : Instruction<opc, "x">;1108  }1109 1110  multiclass basic_p <bits<4> opc> {1111    defm PS : basic_r<opc>;1112    defm PD : basic_r<opc>;1113    def Y : Instruction<opc, "y">;1114  }1115 1116  defm ADD : basic_s<0xf>, basic_p<0xf>;1117 1118The final ``defm`` creates the following records, five from the ``basic_s``1119multiclass and five from the ``basic_p`` multiclass::1120 1121  ADDSSrr, ADDSSrm1122  ADDSDrr, ADDSDrm1123  ADDX1124  ADDPSrr, ADDPSrm1125  ADDPDrr, ADDPDrm1126  ADDY1127 1128A ``defm`` statement, both at top level and in a multiclass, can inherit1129from regular classes in addition to multiclasses. The rule is that the1130regular classes must be listed after the multiclasses, and there must be at least1131one multiclass.1132 1133.. code-block:: text1134 1135  class XD {1136    bits<4> Prefix = 11;1137  }1138  class XS {1139    bits<4> Prefix = 12;1140  }1141  class I <bits<4> op> {1142    bits<4> opcode = op;1143  }1144 1145  multiclass R {1146    def rr : I<4>;1147    def rm : I<2>;1148  }1149 1150  multiclass Y {1151    defm SS : R, XD;    // First multiclass R, then regular class XD.1152    defm SD : R, XS;1153  }1154 1155  defm Instr : Y;1156 1157This example will create four records, shown here in alphabetical order with1158their fields.1159 1160.. code-block:: text1161 1162  def InstrSDrm {1163    bits<4> opcode = { 0, 0, 1, 0 };1164    bits<4> Prefix = { 1, 1, 0, 0 };1165  }1166 1167  def InstrSDrr {1168    bits<4> opcode = { 0, 1, 0, 0 };1169    bits<4> Prefix = { 1, 1, 0, 0 };1170  }1171 1172  def InstrSSrm {1173    bits<4> opcode = { 0, 0, 1, 0 };1174    bits<4> Prefix = { 1, 0, 1, 1 };1175  }1176 1177  def InstrSSrr {1178    bits<4> opcode = { 0, 1, 0, 0 };1179    bits<4> Prefix = { 1, 0, 1, 1 };1180  }1181 1182It's also possible to use ``let`` statements inside multiclasses, providing1183another way to factor out commonality from the records, especially when1184using several levels of multiclass instantiations.1185 1186.. code-block:: text1187 1188  multiclass basic_r <bits<4> opc> {1189    let Predicates = [HasSSE2] in {1190      def rr : Instruction<opc, "rr">;1191      def rm : Instruction<opc, "rm">;1192    }1193    let Predicates = [HasSSE3] in1194      def rx : Instruction<opc, "rx">;1195  }1196 1197  multiclass basic_ss <bits<4> opc> {1198    let IsDouble = false in1199      defm SS : basic_r<opc>;1200 1201    let IsDouble = true in1202      defm SD : basic_r<opc>;1203  }1204 1205  defm ADD : basic_ss<0xf>;1206 1207 1208``defset`` --- create a definition set1209--------------------------------------1210 1211The ``defset`` statement is used to collect a set of records into a global1212list of records.1213 1214.. productionlist::1215   Defset: "defset" `Type` `TokIdentifier` "=" "{" `Statement`* "}"1216 1217All records defined inside the braces via ``def`` and ``defm`` are defined1218as usual, and they are also collected in a global list of the given name1219(:token:`TokIdentifier`).1220 1221The specified type must be ``list<``\ *class*\ ``>``, where *class* is some1222record class.  The ``defset`` statement establishes a scope for its1223statements. It is an error to define a record in the scope of the1224``defset`` that is not of type *class*.1225 1226The ``defset`` statement can be nested. The inner ``defset`` adds the1227records to its own set, and all those records are also added to the outer1228set.1229 1230Anonymous records created inside initialization expressions using the1231``ClassID<...>`` syntax are not collected in the set.1232 1233``deftype`` --- define a type1234--------------------------------1235 1236A ``deftype`` statement defines a type. The type can be used throughout the1237statements that follow the definition.1238 1239.. productionlist::1240   Deftype: "deftype" `TokIdentifier` "=" `Type` ";"1241 1242The identifier on the left of the ``=`` is defined to be a type name1243whose actual type is given by the type expression on the right of the ``=``.1244 1245Currently, only primitive types and type aliases are supported to be the source1246type and `deftype` statements can only appear at the top level.1247 1248``defvar`` --- define a variable1249--------------------------------1250 1251A ``defvar`` statement defines a global variable. Its value can be used1252throughout the statements that follow the definition.1253 1254.. productionlist::1255   Defvar: "defvar" `TokIdentifier` "=" `Value` ";"1256 1257The identifier on the left of the ``=`` is defined to be a global variable1258whose value is given by the value expression on the right of the ``=``. The1259type of the variable is automatically inferred.1260 1261Once a variable has been defined, it cannot be set to another value.1262 1263Variables defined in a top-level ``foreach`` go out of scope at the end of1264each loop iteration, so their value in one iteration is not available in1265the next iteration.  The following ``defvar`` will not work::1266 1267  defvar i = !add(i, 1);1268 1269Variables can also be defined with ``defvar`` in a record body. See1270`Defvar in a Record Body`_ for more details.1271 1272``foreach`` --- iterate over a sequence of statements1273-----------------------------------------------------1274 1275The ``foreach`` statement iterates over a series of statements, varying a1276variable over a sequence of values.1277 1278.. productionlist::1279   Foreach: "foreach" `ForeachIterator` "in" "{" `Statement`* "}"1280          :| "foreach" `ForeachIterator` "in" `Statement`1281   ForeachIterator: `TokIdentifier` "=" ("{" `RangeList` "}" | `RangePiece` | `Value`)1282 1283The body of the ``foreach`` is a series of statements in braces or a1284single statement with no braces. The statements are re-evaluated once for1285each value in the range list, range piece, or single value. On each1286iteration, the :token:`TokIdentifier` variable is set to the value and can1287be used in the statements.1288 1289The statement list establishes an inner scope. Variables local to a1290``foreach`` go out of scope at the end of each loop iteration, so their1291values do not carry over from one iteration to the next. Foreach loops may1292be nested.1293 1294.. Note that the productions involving RangeList and RangePiece have precedence1295   over the more generic value parsing based on the first token.1296 1297.. code-block:: text1298 1299  foreach i = [0, 1, 2, 3] in {1300    def R#i : Register<...>;1301    def F#i : Register<...>;1302  }1303 1304This loop defines records named ``R0``, ``R1``, ``R2``, and ``R3``, along1305with ``F0``, ``F1``, ``F2``, and ``F3``.1306 1307``dump`` --- print messages to stderr1308-------------------------------------1309 1310A ``dump`` statement prints the input string to standard error1311output. It is intended for debugging purposes.1312 1313* At top level, the message is printed immediately.1314 1315* Within a record/class/multiclass, `dump` gets evaluated at each1316  instantiation point of the containing record.1317 1318.. productionlist::1319   Dump: "dump" `Value` ";"1320 1321The :token:`Value` is an arbitrary string expression.1322For example, it can be used in combination with `!repr` to investigate1323the values passed to a multiclass:1324 1325.. code-block:: text1326 1327  multiclass MC<dag s> {1328    dump "s = " # !repr(s);1329  }1330 1331 1332``if`` --- select statements based on a test1333--------------------------------------------1334 1335The ``if`` statement allows one of two statement groups to be selected based1336on the value of an expression.1337 1338.. productionlist::1339   If: "if" `Value` "then" `IfBody`1340     :| "if" `Value` "then" `IfBody` "else" `IfBody`1341   IfBody: "{" `Statement`* "}" | `Statement`1342 1343The value expression is evaluated. If it evaluates to true (in the same1344sense used by the bang operators), then the statements following the1345``then`` reserved word are processed. Otherwise, if there is an ``else``1346reserved word, the statements following the ``else`` are processed. If the1347value is false and there is no ``else`` arm, no statements are processed.1348 1349Because the braces around the ``then`` statements are optional, this grammar rule1350has the usual ambiguity with "dangling else" clauses, and it is resolved in1351the usual way: in a case like ``if v1 then if v2 then {...} else {...}``, the1352``else`` associates with the inner ``if`` rather than the outer one.1353 1354The :token:`IfBody` of the then and else arms of the ``if`` establish an1355inner scope. Any ``defvar`` variables defined in the bodies go out of scope1356when the bodies are finished (see `Defvar in a Record Body`_ for more details).1357 1358The ``if`` statement can also be used in a record :token:`Body`.1359 1360 1361``assert`` --- check that a condition is true1362---------------------------------------------1363 1364The ``assert`` statement checks a boolean condition to be sure that it is true1365and prints an error message if it is not.1366 1367.. productionlist::1368   Assert: "assert" `Value` "," `Value` ";"1369 1370The first :token:`Value` is a boolean condition. If it is true, the1371statement does nothing. If the condition is false, it prints a nonfatal1372error message. The second :token:`Value` is a message, which can be an1373arbitrary string expression. It is included in the error message as a1374note. The exact behavior of the ``assert`` statement depends on its1375placement.1376 1377* At top level, the assertion is checked immediately.1378 1379* In a record definition, the statement is saved and all assertions are1380  checked after the record is completely built.1381 1382* In a class definition, the assertions are saved and inherited by all1383  the subclasses and records that inherit from the class. The assertions are1384  then checked when the records are completely built.1385 1386* In a multiclass definition, the assertions are saved with the other1387  components of the multiclass and then checked each time the multiclass1388  is instantiated with ``defm``.1389 1390Using assertions in TableGen files can simplify record checking in TableGen1391backends. Here is an example of an ``assert`` in two class definitions.1392 1393.. code-block:: text1394 1395  class PersonName<string name> {1396    assert !le(!size(name), 32), "person name is too long: " # name;1397    string Name = name;1398  }1399 1400  class Person<string name, int age> : PersonName<name> {1401    assert !and(!ge(age, 1), !le(age, 120)), "person age is invalid: " # age;1402    int Age = age;1403  }1404 1405  def Rec20 : Person<"Donald Knuth", 60> {1406    ...1407  }1408 1409 1410Additional Details1411==================1412 1413Directed acyclic graphs (DAGs)1414------------------------------1415 1416A directed acyclic graph can be represented directly in TableGen using the1417``dag`` datatype. A DAG node consists of an operator and zero or more1418arguments (or operands). Each argument can be of any desired type. By using1419another DAG node as an argument, an arbitrary graph of DAG nodes can be1420built.1421 1422The syntax of a ``dag`` instance is:1423 1424  ``(`` *operator* *argument1*\ ``,`` *argument2*\ ``,`` ... ``)``1425 1426The operator must be present and must be a record. There can be zero or more1427arguments, separated by commas. The operator and arguments can have three1428formats.1429 1430====================== =============================================1431Format                 Meaning1432====================== =============================================1433*value*                argument value1434*value*\ ``:``\ *name* argument value and associated name1435*name*                 argument name with unset (uninitialized) value1436====================== =============================================1437 1438The *value* can be any TableGen value. The *name*, if present, must be a1439:token:`TokVarName`, which starts with a dollar sign (``$``). The purpose of1440a name is to tag an operator or argument in a DAG with a particular meaning,1441or to associate an argument in one DAG with a like-named argument in another1442DAG.1443 1444The following bang operators are useful for working with DAGs:1445``!con``, ``!dag``, ``!empty``, ``!foreach``, ``!getdagarg``, ``!getdagname``,1446``!getdagop``, ``!getdagopname``, ``!setdagarg``, ``!setdagname``, ``!setdagop``,1447``!setdagopname``, ``!size``.1448 1449Defvar in a record body1450-----------------------1451 1452In addition to defining global variables, the ``defvar`` statement can1453be used inside the :token:`Body` of a class or record definition to define1454local variables. Template arguments of ``class`` or ``multiclass`` can be1455used in the value expression. The scope of the variable extends from the1456``defvar`` statement to the end of the body. It cannot be set to a different1457value within its scope. The ``defvar`` statement can also be used in the statement1458list of a ``foreach``, which establishes a scope.1459 1460A variable named ``V`` in an inner scope shadows (hides) any variables ``V``1461in outer scopes. In particular, there are several cases:1462 1463* ``V`` in a record body shadows a global ``V``.1464 1465* ``V`` in a record body shadows template argument ``V``.1466 1467* ``V`` in template arguments shadows a global ``V``.1468 1469* ``V`` in a ``foreach`` statement list shadows any ``V`` in surrounding record or1470  global scopes.1471 1472Variables defined in a ``foreach`` go out of scope at the end of1473each loop iteration, so their value in one iteration is not available in1474the next iteration.  The following ``defvar`` will not work::1475 1476  defvar i = !add(i, 1)1477 1478How records are built1479---------------------1480 1481The following steps are taken by TableGen when a record is built. Classes are simply1482abstract records and so go through the same steps.1483 14841. Build the record name (:token:`NameValue`) and create an empty record.1485 14862. Parse the parent classes in the :token:`ParentClassList` from left to1487   right, visiting each parent class's ancestor classes from top to bottom.1488 1489  a. Add the fields from the parent class to the record.1490  b. Substitute the template arguments into those fields.1491  c. Add the parent class to the record's list of inherited classes.1492 14933. Apply any top-level ``let`` bindings to the record. Recall that top-level1494   bindings only apply to inherited fields.1495 14964. Parse the body of the record.1497 1498  * Add any fields to the record.1499  * Modify the values of fields according to local ``let`` statements.1500  * Define any ``defvar`` variables.1501 15025. Make a pass over all the fields to resolve any inter-field references.1503 15046. Add the record to the final record list.1505 1506Because references between fields are resolved (step 5) after ``let`` bindings are1507applied (step 3), the ``let`` statement has unusual power. For example:1508 1509.. code-block:: text1510 1511  class C <int x> {1512    int Y = x;1513    int Yplus1 = !add(Y, 1);1514    int xplus1 = !add(x, 1);1515  }1516 1517  let Y = 10 in {1518    def rec1 : C<5> {1519    }1520  }1521 1522  def rec2 : C<5> {1523    let Y = 10;1524  }1525 1526In both cases, one where a top-level ``let`` is used to bind ``Y`` and one1527where a local ``let`` does the same thing, the results are:1528 1529.. code-block:: text1530 1531  def rec1 {      // C1532    int Y = 10;1533    int Yplus1 = 11;1534    int xplus1 = 6;1535  }1536  def rec2 {      // C1537    int Y = 10;1538    int Yplus1 = 11;1539    int xplus1 = 6;1540  }1541 1542``Yplus1`` is 11 because the ``let Y`` is performed before the ``!add(Y,15431)`` is resolved. Use this power wisely.1544 1545 1546Using Classes as Subroutines1547============================1548 1549As described in `Simple values`_, a class can be invoked in an expression1550and passed template arguments. This causes TableGen to create a new anonymous1551record inheriting from that class. As usual, the record receives all the1552fields defined in the class.1553 1554This feature can be employed as a simple subroutine facility. The class can1555use the template arguments to define various variables and fields, which end1556up in the anonymous record. Those fields can then be retrieved in the1557expression invoking the class as follows. Assume that the field ``ret``1558contains the final value of the subroutine.1559 1560.. code-block:: text1561 1562  int Result = ... CalcValue<arg>.ret ...;1563 1564The ``CalcValue`` class is invoked with the template argument ``arg``. It1565calculates a value for the ``ret`` field, which is then retrieved at the1566"point of call" in the initialization for the Result field. The anonymous1567record created in this example serves no other purpose than to carry the1568result value.1569 1570Here is a practical example. The class ``isValidSize`` determines whether a1571specified number of bytes represents a valid data size. The bit ``ret`` is1572set appropriately. The field ``ValidSize`` obtains its initial value by1573invoking ``isValidSize`` with the data size and retrieving the ``ret`` field1574from the resulting anonymous record.1575 1576.. code-block:: text1577 1578  class isValidSize<int size> {1579    bit ret = !cond(!eq(size,  1): 1,1580                    !eq(size,  2): 1,1581                    !eq(size,  4): 1,1582                    !eq(size,  8): 1,1583                    !eq(size, 16): 1,1584                    true: 0);1585  }1586 1587  def Data1 {1588    int Size = ...;1589    bit ValidSize = isValidSize<Size>.ret;1590  }1591 1592Preprocessing Facilities1593========================1594 1595The preprocessor embedded in TableGen is intended only for simple1596conditional compilation. It supports the following directives, which are1597specified somewhat informally.1598 1599.. productionlist::1600   LineBegin: beginning of line1601   LineEnd: newline | return | EOF1602   WhiteSpace: space | tab1603   CComment: "/*" ... "*/"1604   BCPLComment: "//" ... `LineEnd`1605   WhiteSpaceOrCComment: `WhiteSpace` | `CComment`1606   WhiteSpaceOrAnyComment: `WhiteSpace` | `CComment` | `BCPLComment`1607   MacroName: `ualpha` (`ualpha` | "0"..."9")*1608   PreDefine: `LineBegin` (`WhiteSpaceOrCComment`)*1609            : "#define" (`WhiteSpace`)+ `MacroName`1610            : (`WhiteSpaceOrAnyComment`)* `LineEnd`1611   PreIfdef: `LineBegin` (`WhiteSpaceOrCComment`)*1612           : ("#ifdef" | "#ifndef") (`WhiteSpace`)+ `MacroName`1613           : (`WhiteSpaceOrAnyComment`)* `LineEnd`1614   PreElse: `LineBegin` (`WhiteSpaceOrCComment`)*1615          : "#else" (`WhiteSpaceOrAnyComment`)* `LineEnd`1616   PreEndif: `LineBegin` (`WhiteSpaceOrCComment`)*1617           : "#endif" (`WhiteSpaceOrAnyComment`)* `LineEnd`1618 1619..1620   PreRegContentException: `PreIfdef` | `PreElse` | `PreEndif` | EOF1621   PreRegion: .* - `PreRegContentException`1622             :| `PreIfdef`1623             :  (`PreRegion`)*1624             :  [`PreElse`]1625             :  (`PreRegion`)*1626             :  `PreEndif`1627 1628A :token:`MacroName` can be defined anywhere in a TableGen file. The name has1629no value; it can only be tested to see whether it is defined.1630 1631A macro test region begins with an ``#ifdef`` or ``#ifndef`` directive. If1632the macro name is defined (``#ifdef``) or undefined (``#ifndef``), then the1633source code between the directive and the corresponding ``#else`` or1634``#endif`` is processed. If the test fails but there is an ``#else``1635clause, the source code between the ``#else`` and the ``#endif`` is1636processed. If the test fails and there is no ``#else`` clause, then no1637source code in the test region is processed.1638 1639Test regions may be nested, but they must be properly nested. A region1640started in a file must end in that file; that is, must have its1641``#endif`` in the same file.1642 1643A :token:`MacroName` may be defined externally using the ``-D`` option on the1644``*-tblgen`` command line::1645 1646  llvm-tblgen self-reference.td -Dmacro1 -Dmacro31647 1648Appendix A: Bang Operators1649==========================1650 1651Bang operators act as functions in value expressions. A bang operator takes1652one or more arguments, operates on them, and produces a result. If the1653operator produces a boolean result, the result value will be 1 for true or 01654for false. When an operator tests a boolean argument, it interprets 0 as false1655and non-0 as true.1656 1657.. warning::1658  The ``!getop`` and ``!setop`` bang operators are deprecated in favor of1659  ``!getdagop`` and ``!setdagop``.1660 1661``!add(``\ *a*\ ``,`` *b*\ ``, ...)``1662    This operator adds *a*, *b*, etc., and produces the sum.1663 1664``!and(``\ *a*\ ``,`` *b*\ ``, ...)``1665    This operator does a bitwise AND on *a*, *b*, etc., and produces the1666    result. A logical AND can be performed if all the arguments are either1667    0 or 1. This operator is short-circuit to 0 when the left-most operand1668    is 0.1669 1670``!cast<``\ *type*\ ``>(``\ *a*\ ``)``1671    This operator performs a cast on *a* and produces the result.1672    If *a* is not a string, then a straightforward cast is performed, say1673    between an ``int`` and a ``bit``, or between record types. This allows1674    casting a record to a class. If a record is cast to ``string``, the1675    record's name is produced.1676 1677    If *a* is a string, then it is treated as a record name and looked up in1678    the list of all defined records. The resulting record is expected to be of1679    the specified *type*.1680 1681    For example, if ``!cast<``\ *type*\ ``>(``\ *name*\ ``)``1682    appears in a multiclass definition, or in a1683    class instantiated inside a multiclass definition, and the *name* does not1684    reference any template arguments of the multiclass, then a record by1685    that name must have been instantiated earlier1686    in the source file. If *name* does reference1687    a template argument, then the lookup is delayed until ``defm`` statements1688    instantiating the multiclass (or later, if the defm occurs in another1689    multiclass and template arguments of the inner multiclass that are1690    referenced by *name* are substituted by values that themselves contain1691    references to template arguments of the outer multiclass).1692 1693    If the type of *a* does not match *type*, TableGen raises an error.1694 1695``!con(``\ *a*\ ``,`` *b*\ ``, ...)``1696    This operator concatenates the DAG nodes *a*, *b*, etc. Their operations1697    must equal.1698 1699    ``!con((op:$lhs a1:$name1, a2:$name2), (op:$rhs b1:$name3))``1700 1701    results in the DAG node ``(op:$lhs a1:$name1, a2:$name2, b1:$name3)``.1702    The name of the dag operator is derived from the LHS DAG node if it is1703    set, otherwise from the RHS DAG node.1704 1705``!cond(``\ *cond1* ``:`` *val1*\ ``,`` *cond2* ``:`` *val2*\ ``, ...,`` *condn* ``:`` *valn*\ ``)``1706    This operator tests *cond1* and returns *val1* if the result is true.1707    If false, the operator tests *cond2* and returns *val2* if the result is1708    true. And so forth. An error is reported if no conditions are true.1709 1710    This example produces the sign word for an integer::1711 1712    !cond(!lt(x, 0) : "negative", !eq(x, 0) : "zero", true : "positive")1713 1714``!dag(``\ *op*\ ``,`` *arguments*\ ``,`` *names*\ ``)``1715    This operator creates a DAG node with the given operator and1716    arguments. The *arguments* and *names* arguments must be lists1717    of equal length or uninitialized (``?``). The *names* argument1718    must be of type ``list<string>``.1719 1720    Due to limitations of the type system, *arguments* must be a list of items1721    of a common type. In practice, this means that they should either have the1722    same type or be records with a common parent class. Mixing ``dag`` and1723    non-``dag`` items is not possible. However, ``?`` can be used.1724 1725    Example: ``!dag(op, [a1, a2, ?], ["name1", "name2", "name3"])`` results in1726    ``(op a1-value:$name1, a2-value:$name2, ?:$name3)``.1727 1728``!div(``\ *a*\ ``,`` *b*\ ``)``1729    This operator performs signed division of *a* by *b*, and produces the quotient.1730    Division by 0 produces an error. Division of ``INT64_MIN`` by -1 produces an error.1731 1732``!empty(``\ *a*\ ``)``1733    This operator produces 1 if the string, list, or DAG *a* is empty; 0 otherwise.1734    A dag is empty if it has no arguments; the operator does not count.1735 1736``!eq(`` *a*\ `,` *b*\ ``)``1737    This operator produces 1 if *a* is equal to *b*; 0 otherwise.1738    The arguments must be ``bit``, ``bits``, ``int``, ``string``, or1739    record values. Use ``!cast<string>`` to compare other types of objects.1740 1741``!exists<``\ *type*\ ``>(``\ *name*\ ``)``1742    This operator produces 1 if a record of the given *type* whose name is *name*1743    exists; 0 otherwise. *name* should be of type *string*.1744 1745``!filter(``\ *var*\ ``,`` *list*\ ``,`` *predicate*\ ``)``1746 1747    This operator creates a new ``list`` by filtering the elements in1748    *list*. To perform the filtering, TableGen binds the variable *var* to each1749    element and then evaluates the *predicate* expression, which presumably1750    refers to *var*. The predicate must1751    produce a boolean value (``bit``, ``bits``, or ``int``). The value is1752    interpreted as with ``!if``:1753    if the value is 0, the element is not included in the new list. If the value1754    is anything else, the element is included.1755 1756``!find(``\ *string1*\ ``,`` *string2*\ [``,`` *start*]\ ``)``1757    This operator searches for *string2* in *string1* and produces its1758    position. The starting position of the search may be specified by *start*,1759    which can range between 0 and the length of *string1*; the default is 0.1760    If the string is not found, the result is -1.1761 1762``!foldl(``\ *init*\ ``,`` *list*\ ``,`` *acc*\ ``,`` *var*\ ``,`` *expr*\ ``)``1763    This operator performs a left-fold over the items in *list*. The1764    variable *acc* acts as the accumulator and is initialized to *init*.1765    The variable *var* is bound to each element in the *list*. The1766    expression is evaluated for each element and presumably uses *acc* and1767    *var* to calculate the accumulated value, which ``!foldl`` stores back in1768    *acc*. The type of *acc* is the same as *init*; the type of *var* is the1769    same as the elements of *list*; *expr* must have the same type as *init*.1770 1771    The following example computes the total of the ``Number`` field in the1772    list of records in ``RecList``::1773 1774      int x = !foldl(0, RecList, total, rec, !add(total, rec.Number));1775 1776    If your goal is to filter the list and produce a new list that includes only1777    some of the elements, see ``!filter``.1778 1779``!foreach(``\ *var*\ ``,`` *sequence*\ ``,`` *expr*\ ``)``1780    This operator creates a new ``list``/``dag`` in which each element is a1781    function of the corresponding element in the *sequence* ``list``/``dag``.1782    To perform the function, TableGen binds the variable *var* to an element1783    and then evaluates the expression. The expression presumably refers1784    to the variable *var* and calculates the result value.1785 1786    If you simply want to create a list of a certain length containing1787    the same value repeated multiple times, see ``!listsplat``.1788 1789``!ge(``\ *a*\ `,` *b*\ ``)``1790    This operator produces 1 if *a* is greater than or equal to *b*; 0 otherwise.1791    The arguments must be ``bit``, ``bits``, ``int``, or ``string`` values.1792 1793``!getdagarg<``\ *type*\ ``>(``\ *dag*\ ``,``\ *key*\ ``)``1794    This operator retrieves the argument from the given *dag* node by the1795    specified *key*, which is either an integer index or a string name. If that1796    argument is not convertible to the specified *type*, ``?`` is returned.1797 1798``!getdagname(``\ *dag*\ ``,``\ *index*\ ``)``1799    This operator retrieves the argument name from the given *dag* node by the1800    specified *index*. If that argument has no name associated, ``?`` is1801    returned.1802 1803``!getdagop(``\ *dag*\ ``)`` --or-- ``!getdagop<``\ *type*\ ``>(``\ *dag*\ ``)``1804    This operator produces the operator of the given *dag* node.1805    Example: ``!getdagop((foo 1, 2))`` results in ``foo``. Recall that1806    DAG operators are always records.1807 1808    The result of ``!getdagop`` can be used directly in a context where1809    any record class at all is acceptable (typically placing it into1810    another dag value). But in other contexts, it must be explicitly1811    cast to a particular class. The ``<``\ *type*\ ``>`` syntax is1812    provided to make this easy.1813 1814    For example, to assign the result to a value of type ``BaseClass``, you1815    could write either of these::1816 1817      BaseClass b = !getdagop<BaseClass>(someDag);1818      BaseClass b = !cast<BaseClass>(!getdagop(someDag));1819 1820    But to create a new DAG node that reuses the operator from another, no1821    cast is necessary::1822 1823      dag d = !dag(!getdagop(someDag), args, names);1824 1825``!getdagopname(``\ *dag*\ ``)``1826    This operator retrieves the name of the given *dag* operator. If the operator1827    has no name associated, ``?`` is returned.1828 1829``!gt(``\ *a*\ `,` *b*\ ``)``1830    This operator produces 1 if *a* is greater than *b*; 0 otherwise.1831    The arguments must be ``bit``, ``bits``, ``int``, or ``string`` values.1832 1833``!head(``\ *a*\ ``)``1834    This operator produces the zeroth element of the list *a*.1835    (See also ``!tail``.)1836 1837``!if(``\ *test*\ ``,`` *then*\ ``,`` *else*\ ``)``1838  This operator evaluates the *test*, which must produce a ``bit`` or1839  ``int``. If the result is not 0, the *then* expression is produced; otherwise1840  the *else* expression is produced.1841 1842``!initialized(``\ *a*\ ``)``1843  This operator produces 1 if *a* is not the uninitialized value (``?``) and 01844  otherwise.1845 1846``!instances<``\ *type*\ ``>([``\ *regex*\ ``])``1847    This operator produces a list of records whose type is *type*. If *regex*1848    is provided, only records whose name matches the regular expression *regex*1849    will be included. The format of *regex* is ERE (Extended POSIX Regular1850    Expressions).1851 1852    If ``!instances`` is in a class/multiclass/foreach, only these records of1853    *type* that have been instantiated will be considered.1854 1855``!interleave(``\ *list*\ ``,`` *delim*\ ``)``1856    This operator concatenates the items in the *list*, interleaving the1857    *delim* string between each pair, and produces the resulting string.1858    The list can be a list of string, int, bits, or bit. An empty list1859    results in an empty string. The delimiter can be the empty string.1860 1861``!isa<``\ *type*\ ``>(``\ *a*\ ``)``1862    This operator produces 1 if the type of *a* is a subtype of the given *type*; 01863    otherwise.1864 1865``!le(``\ *a*\ ``,`` *b*\ ``)``1866    This operator produces 1 if *a* is less than or equal to *b*; 0 otherwise.1867    The arguments must be ``bit``, ``bits``, ``int``, or ``string`` values.1868 1869``!listconcat(``\ *list1*\ ``,`` *list2*\ ``, ...)``1870    This operator concatenates the list arguments *list1*, *list2*, etc., and1871    produces the resulting list. The lists must have the same element type.1872 1873``!listflatten(``\ *list*\ ``)``1874    This operator flattens a list of lists *list* and produces a list with all1875    elements of the constituent lists concatenated. If *list* is of type1876    ``list<list<X>>`` the resulting list is of type ``list<X>``. If *list*'s1877    element type is not a list, the result is *list* itself.1878 1879``!listremove(``\ *list1*\ ``,`` *list2*\ ``)``1880    This operator returns a copy of *list1* removing all elements that also occur in1881    *list2*. The lists must have the same element type.1882 1883``!listsplat(``\ *value*\ ``,`` *count*\ ``)``1884    This operator produces a list of length *count* whose elements are all1885    equal to the *value*. For example, ``!listsplat(42, 3)`` results in1886    ``[42, 42, 42]``.1887 1888``!logtwo(``\ *a*\ ``)``1889    This operator produces the base 2 log of *a* and produces the integer1890    result. The log of 0 or a negative number produces an error. This1891    is a flooring operation.1892 1893``!lt(``\ *a*\ `,` *b*\ ``)``1894    This operator produces 1 if *a* is less than *b*; 0 otherwise.1895    The arguments must be ``bit``, ``bits``, ``int``, or ``string`` values.1896 1897``!match(``\ *str*\ `,` *regex*\ ``)``1898    This operator produces 1 if the *str* matches the regular expression1899    *regex*. The format of *regex* is ERE (Extended POSIX Regular Expressions).1900 1901``!mul(``\ *a*\ ``,`` *b*\ ``, ...)``1902    This operator multiplies *a*, *b*, etc., and produces the product.1903 1904``!ne(``\ *a*\ `,` *b*\ ``)``1905    This operator produces 1 if *a* is not equal to *b*; 0 otherwise.1906    The arguments must be ``bit``, ``bits``, ``int``, ``string``,1907    or record values. Use ``!cast<string>`` to compare other types of objects.1908 1909``!not(``\ *a*\ ``)``1910    This operator performs a logical NOT on *a*, which must be1911    an integer. The argument 0 results in 1 (true); any other1912    argument results in 0 (false).1913 1914``!or(``\ *a*\ ``,`` *b*\ ``, ...)``1915    This operator does a bitwise OR on *a*, *b*, etc., and produces the1916    result. A logical OR can be performed if all the arguments are either1917    0 or 1. This operator is short-circuit to -1 (all ones) when the left-most1918    operand is -1.1919 1920``!range([``\ *start*\ ``,]`` *end*\ ``[,``\ *step*\ ``])``1921    This operator produces half-open range sequence ``[start : end : step)`` as1922    ``list<int>``. *start* is ``0`` and *step* is ``1`` by default. *step* can1923    be negative and cannot be 0. If *start* ``<`` *end* and *step* is negative,1924    or *start* ``>`` *end* and *step* is positive, the result is an empty list1925    ``[]<int>``.1926 1927    For example:1928 1929    * ``!range(4)`` is equivalent to ``!range(0, 4, 1)`` and the result is1930      `[0, 1, 2, 3]`.1931    * ``!range(1, 4)`` is equivalent to ``!range(1, 4, 1)`` and the result is1932      `[1, 2, 3]`.1933    * The result of ``!range(0, 4, 2)`` is `[0, 2]`.1934    * The results of ``!range(0, 4, -1)`` and ``!range(4, 0, 1)`` are empty.1935 1936``!range(``\ *list*\ ``)``1937    Equivalent to ``!range(0, !size(list))``.1938 1939``!repr(``\ *value*\ ``)``1940    Represents *value* as a string. The string format for the value is not1941    guaranteed to be stable. Intended for debugging purposes only.1942 1943``!setdagarg(``\ *dag*\ ``,``\ *key*\ ``,``\ *arg*\ ``)``1944    This operator produces a DAG node with the same operator and arguments as1945    *dag*, but replacing the value of the argument specified by the *key* with1946    *arg*. That *key* could be either an integer index or a string name.1947 1948``!setdagname(``\ *dag*\ ``,``\ *key*\ ``,``\ *name*\ ``)``1949    This operator produces a DAG node with the same operator and arguments as1950    *dag*, but replacing the name of the argument specified by the *key* with1951    *name*. That *key* could be either an integer index or a string name.1952 1953``!setdagop(``\ *dag*\ ``,`` *op*\ ``)``1954    This operator produces a DAG node with the same arguments as *dag*, but with its1955    operator replaced with *op*.1956 1957    Example: ``!setdagop((foo 1, 2), bar)`` results in ``(bar 1, 2)``.1958 1959``!setdagopname(``\ *dag*\ ``,``\ *name*\ ``)``1960    This operator produces a DAG node with the same operator and arguments as1961    *dag*, but replacing the name of the operator with *name*.1962 1963``!shl(``\ *a*\ ``,`` *count*\ ``)``1964    This operator shifts *a* left logically by *count* bits and produces the resulting1965    value. The operation is performed on a 64-bit integer; the result1966    is undefined for shift counts outside 0...63.1967 1968``!size(``\ *a*\ ``)``1969    This operator produces the size of the string, list, or dag *a*.1970    The size of a DAG is the number of arguments; the operator does not count.1971 1972``!sra(``\ *a*\ ``,`` *count*\ ``)``1973    This operator shifts *a* right arithmetically by *count* bits and produces the resulting1974    value. The operation is performed on a 64-bit integer; the result1975    is undefined for shift counts outside 0...63.1976 1977``!srl(``\ *a*\ ``,`` *count*\ ``)``1978    This operator shifts *a* right logically by *count* bits and produces the resulting1979    value. The operation is performed on a 64-bit integer; the result1980    is undefined for shift counts outside 0...63.1981 1982``!strconcat(``\ *str1*\ ``,`` *str2*\ ``, ...)``1983    This operator concatenates the string arguments *str1*, *str2*, etc., and1984    produces the resulting string.1985 1986``!sub(``\ *a*\ ``,`` *b*\ ``)``1987    This operator subtracts *b* from *a* and produces the arithmetic difference.1988 1989``!subst(``\ *target*\ ``,`` *repl*\ ``,`` *value*\ ``)``1990    This operator replaces all occurrences of the *target* in the *value* with1991    the *repl* and produces the resulting value. The *value* can1992    be a string, in which case substring substitution is performed.1993 1994    The *value* can be a record name, in which case the operator produces the *repl*1995    record if the *target* record name equals the *value* record name; otherwise it1996    produces the *value*.1997 1998``!substr(``\ *string*\ ``,`` *start*\ [``,`` *length*]\ ``)``1999    This operator extracts a substring of the given *string*. The starting2000    position of the substring is specified by *start*, which can range2001    between 0 and the length of the string. The length of the substring2002    is specified by *length*; if not specified, the rest of the string is2003    extracted. The *start* and *length* arguments must be integers.2004 2005``!tail(``\ *a*\ ``)``2006    This operator produces a new list with all the elements2007    of the list *a* except for the zeroth one. (See also ``!head``.)2008 2009``!tolower(``\ *a*\ ``)``2010  This operator converts a string input *a* to lower case.2011 2012``!toupper(``\ *a*\ ``)``2013  This operator converts a string input *a* to upper case.2014 2015``!xor(``\ *a*\ ``,`` *b*\ ``, ...)``2016    This operator does a bitwise EXCLUSIVE OR on *a*, *b*, etc., and produces2017    the result. A logical XOR can be performed if all the arguments are either2018    0 or 1.2019 2020Appendix B: Paste Operator Examples2021===================================2022 2023Here is an example illustrating the use of the paste operator in record names.2024 2025.. code-block:: text2026 2027  defvar suffix = "_suffstring";2028  defvar some_ints = [0, 1, 2, 3];2029 2030  def name # suffix {2031  }2032 2033  foreach i = [1, 2] in {2034  def rec # i {2035  }2036  }2037 2038The first ``def`` does not use the value of the ``suffix`` variable. The2039second def does use the value of the ``i`` iterator variable, because it is not a2040global name. The following records are produced.2041 2042.. code-block:: text2043 2044  def namesuffix {2045  }2046  def rec1 {2047  }2048  def rec2 {2049  }2050 2051Here is a second example illustrating the paste operator in field value expressions.2052 2053.. code-block:: text2054 2055  def test {2056    string strings = suffix # suffix;2057    list<int> integers = some_ints # [4, 5, 6];2058  }2059 2060The ``strings`` field expression uses ``suffix`` on both sides of the paste2061operator. It is evaluated normally on the left hand side, but taken verbatim2062on the right hand side. The ``integers`` field expression uses the value of2063the ``some_ints`` variable and a literal list. The following record is2064produced.2065 2066.. code-block:: text2067 2068  def test {2069    string strings = "_suffstringsuffix";2070    list<int> ints = [0, 1, 2, 3, 4, 5, 6];2071  }2072 2073 2074Appendix C: Sample Record2075=========================2076 2077One target machine supported by LLVM is the Intel x86. The following output2078from TableGen shows the record that is created to represent the 32-bit2079register-to-register ADD instruction.2080 2081.. code-block:: text2082 2083  def ADD32rr {	// InstructionEncoding Instruction X86Inst I ITy Sched BinOpRR BinOpRR_RF2084    int Size = 0;2085    string DecoderNamespace = "";2086    list<Predicate> Predicates = [];2087    string DecoderMethod = "";2088    bit hasCompleteDecoder = 1;2089    string Namespace = "X86";2090    dag OutOperandList = (outs GR32:$dst);2091    dag InOperandList = (ins GR32:$src1, GR32:$src2);2092    string AsmString = "add{l}	{$src2, $src1|$src1, $src2}";2093    EncodingByHwMode EncodingInfos = ?;2094    list<dag> Pattern = [(set GR32:$dst, EFLAGS, (X86add_flag GR32:$src1, GR32:$src2))];2095    list<Register> Uses = [];2096    list<Register> Defs = [EFLAGS];2097    int CodeSize = 3;2098    int AddedComplexity = 0;2099    bit isPreISelOpcode = 0;2100    bit isReturn = 0;2101    bit isBranch = 0;2102    bit isEHScopeReturn = 0;2103    bit isIndirectBranch = 0;2104    bit isCompare = 0;2105    bit isMoveImm = 0;2106    bit isMoveReg = 0;2107    bit isBitcast = 0;2108    bit isSelect = 0;2109    bit isBarrier = 0;2110    bit isCall = 0;2111    bit isAdd = 0;2112    bit isTrap = 0;2113    bit canFoldAsLoad = 0;2114    bit mayLoad = ?;2115    bit mayStore = ?;2116    bit mayRaiseFPException = 0;2117    bit isConvertibleToThreeAddress = 1;2118    bit isCommutable = 1;2119    bit isTerminator = 0;2120    bit isReMaterializable = 0;2121    bit isPredicable = 0;2122    bit isUnpredicable = 0;2123    bit hasDelaySlot = 0;2124    bit usesCustomInserter = 0;2125    bit hasPostISelHook = 0;2126    bit hasCtrlDep = 0;2127    bit isNotDuplicable = 0;2128    bit isConvergent = 0;2129    bit isAuthenticated = 0;2130    bit isAsCheapAsAMove = 0;2131    bit hasExtraSrcRegAllocReq = 0;2132    bit hasExtraDefRegAllocReq = 0;2133    bit isRegSequence = 0;2134    bit isPseudo = 0;2135    bit isExtractSubreg = 0;2136    bit isInsertSubreg = 0;2137    bit variadicOpsAreDefs = 0;2138    bit hasSideEffects = ?;2139    bit isCodeGenOnly = 0;2140    bit isAsmParserOnly = 0;2141    bit hasNoSchedulingInfo = 0;2142    InstrItinClass Itinerary = NoItinerary;2143    list<SchedReadWrite> SchedRW = [WriteALU];2144    string Constraints = "$src1 = $dst";2145    string DisableEncoding = "";2146    string PostEncoderMethod = "";2147    bits<64> TSFlags = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0 };2148    string AsmMatchConverter = "";2149    string TwoOperandAliasConstraint = "";2150    string AsmVariantName = "";2151    bit UseNamedOperandTable = 0;2152    bit FastISelShouldIgnore = 0;2153    bits<8> Opcode = { 0, 0, 0, 0, 0, 0, 0, 1 };2154    Format Form = MRMDestReg;2155    bits<7> FormBits = { 0, 1, 0, 1, 0, 0, 0 };2156    ImmType ImmT = NoImm;2157    bit ForceDisassemble = 0;2158    OperandSize OpSize = OpSize32;2159    bits<2> OpSizeBits = { 1, 0 };2160    AddressSize AdSize = AdSizeX;2161    bits<2> AdSizeBits = { 0, 0 };2162    Prefix OpPrefix = NoPrfx;2163    bits<3> OpPrefixBits = { 0, 0, 0 };2164    Map OpMap = OB;2165    bits<3> OpMapBits = { 0, 0, 0 };2166    bit hasREX_WPrefix = 0;2167    FPFormat FPForm = NotFP;2168    bit hasLockPrefix = 0;2169    Domain ExeDomain = GenericDomain;2170    bit hasREPPrefix = 0;2171    Encoding OpEnc = EncNormal;2172    bits<2> OpEncBits = { 0, 0 };2173    bit HasVEX_W = 0;2174    bit IgnoresVEX_W = 0;2175    bit EVEX_W1_VEX_W0 = 0;2176    bit hasVEX_4V = 0;2177    bit hasVEX_L = 0;2178    bit ignoresVEX_L = 0;2179    bit hasEVEX_K = 0;2180    bit hasEVEX_Z = 0;2181    bit hasEVEX_L2 = 0;2182    bit hasEVEX_B = 0;2183    bits<3> CD8_Form = { 0, 0, 0 };2184    int CD8_EltSize = 0;2185    bit hasEVEX_RC = 0;2186    bit hasNoTrackPrefix = 0;2187    bits<7> VectSize = { 0, 0, 1, 0, 0, 0, 0 };2188    bits<7> CD8_Scale = { 0, 0, 0, 0, 0, 0, 0 };2189    string FoldGenRegForm = ?;2190    string EVEX2VEXOverride = ?;2191    bit isMemoryFoldable = 1;2192    bit notEVEX2VEXConvertible = 0;2193  }2194 2195On the first line of the record, you can see that the ``ADD32rr`` record2196inherited from eight classes. Although the inheritance hierarchy is complex,2197using parent classes is much simpler than specifying the 109 individual2198fields for each instruction.2199 2200Here is the code fragment used to define ``ADD32rr`` and multiple other2201``ADD`` instructions:2202 2203.. code-block:: text2204 2205  defm ADD : ArithBinOp_RF<0x00, 0x02, 0x04, "add", MRM0r, MRM0m,2206                           X86add_flag, add, 1, 1, 1>;2207 2208The ``defm`` statement tells TableGen that ``ArithBinOp_RF`` is a2209multiclass, which contains multiple concrete record definitions that inherit2210from ``BinOpRR_RF``. That class, in turn, inherits from ``BinOpRR``, which2211inherits from ``ITy`` and ``Sched``, and so forth. The fields are inherited2212from all the parent classes; for example, ``IsIndirectBranch`` is inherited2213from the ``Instruction`` class.2214