1=============================== 2TableGen Programmer's Reference 3=============================== 4 5.. sectnum:: 6 7.. contents:: 8 :local: 9 10Introduction 11============ 12 13The purpose of TableGen is to generate complex output files based on 14information from source files that are significantly easier to code than the 15output files would be, and also easier to maintain and modify over time. The 16information is coded in a declarative style involving classes and records, 17which are then processed by TableGen. The internalized records are passed on 18to various backends, which extract information from a subset of the records 19and generate one or more output files. These output files are typically 20``.inc`` files for C++, but may be any type of file that the backend 21developer needs. 22 23This document describes the LLVM TableGen facility in detail. It is intended 24for the programmer who is using TableGen to produce tables for a project. If 25you are looking for a simple overview, check out :doc:`TableGen Overview <./index>`. 26 27An example of a backend is ``RegisterInfo``, which generates the register 28file information for a particular target machine, for use by the LLVM 29target-independent code generator. See :doc:`TableGen Backends <./BackEnds>` 30for a description of the LLVM TableGen backends, and :doc:`TableGen 31Backend Developer's Guide <./BackGuide>` for a guide to writing a new 32backend. 33 34Here are a few of the things backends can do. 35 36* Generate the register file information for a particular target machine. 37 38* Generate the instruction definitions for a target. 39 40* Generate the patterns that the code generator uses to match instructions 41 to intermediate representation (IR) nodes. 42 43* Generate semantic attribute identifiers for Clang. 44 45* Generate abstract syntax tree (AST) declaration node definitions for Clang. 46 47* Generate AST statement node definitions for Clang. 48 49 50Concepts 51-------- 52 53TableGen source files contain two primary items: *abstract records* and 54*concrete records*. In this and other TableGen documents, abstract records 55are called *classes.* (These classes are different from C++ classes and do 56not map onto them.) In addition, concrete records are usually just called 57records, although sometimes the term *record* refers to both classes and 58concrete records. The distinction should be clear in context. 59 60Classes and concrete records have a unique *name*, either chosen by 61the programmer or generated by TableGen. Associated with that name 62is a list of *fields* with values and an optional list of *superclasses* 63(sometimes called base or parent classes). The fields are the primary data that 64backends will process. Note that TableGen assigns no meanings to fields; the 65meanings are entirely up to the backends and the programs that incorporate 66the output of those backends. 67 68A backend processes some subset of the concrete records built by the 69TableGen parser and emits the output files. These files are usually C++ 70``.inc`` files that are included by the programs that require the data in 71those records. However, a backend can produce any type of output files. For 72example, it could produce a data file containing messages tagged with 73identifiers and substitution parameters. In a complex use case such as the 74LLVM code generator, there can be many concrete records and some of them can 75have an unexpectedly large number of fields, resulting in large output files. 76 77In order to reduce the complexity of TableGen files, classes are used to 78abstract out groups of record fields. For example, a few classes may 79abstract the concept of a machine register file, while other classes may 80abstract the instruction formats, and still others may abstract the 81individual instructions. TableGen allows an arbitrary hierarchy of classes, 82so that the abstract classes for two concepts can share a third superclass that 83abstracts common "sub-concepts" from the two original concepts. 84 85In order to make classes more useful, a concrete record (or another class) 86can request a class as a superclass and pass *template arguments* to it. 87These template arguments can be used in the fields of the superclass to 88initialize them in a custom manner. That is, record or class ``A`` can 89request superclass ``S`` with one set of template arguments, while record or class 90``B`` can request ``S`` with a different set of arguments. Without template 91arguments, many more classes would be required, one for each combination of 92the template arguments. 93 94Both classes and concrete records can include fields that are uninitialized. 95The uninitialized "value" is represented by a question mark (``?``). Classes 96often have uninitialized fields that are expected to be filled in when those 97classes are inherited by concrete records. Even so, some fields of concrete 98records may remain uninitialized. 99 100TableGen provides *multiclasses* to collect a group of record definitions in 101one place. A multiclass is a sort of macro that can be "invoked" to define 102multiple concrete records all at once. A multiclass can inherit from other 103multiclasses, which means that the multiclass inherits all the definitions 104from its parent multiclasses. 105 106`Appendix B: Sample Record`_ illustrates a complex record in the Intel X86 107target and the simple way in which it is defined. 108 109Source Files 110============ 111 112TableGen source files are plain ASCII text files. The files can contain 113statements, comments, and blank lines (see `Lexical Analysis`_). The standard file 114extension for TableGen files is ``.td``. 115 116TableGen files can grow quite large, so there is an include mechanism that 117allows one file to include the content of another file (see `Include 118Files`_). This allows large files to be broken up into smaller ones, and 119also provides a simple library mechanism where multiple source files can 120include the same library file. 121 122TableGen supports a simple preprocessor that can be used to conditionalize 123portions of ``.td`` files. See `Preprocessing Facilities`_ for more 124information. 125 126Lexical Analysis 127================ 128 129The lexical and syntax notation used here is intended to imitate 130`Python's`_ notation. In particular, for lexical definitions, the productions 131operate at the character level and there is no implied whitespace between 132elements. The syntax definitions operate at the token level, so there is 133implied whitespace between tokens. 134 135.. _`Python's`: http://docs.python.org/py3k/reference/introduction.html#notation 136 137TableGen supports BCPL-style comments (``// ...``) and nestable C-style 138comments (``/* ... */``). 139TableGen also provides simple `Preprocessing Facilities`_. 140 141Formfeed characters may be used freely in files to produce page breaks when 142the file is printed for review. 143 144The following are the basic punctuation tokens:: 145 146 - + [ ] { } ( ) < > : ; . ... = ? # 147 148Literals 149-------- 150 151Numeric literals take one of the following forms: 152 153.. productionlist:: 154 TokInteger: `DecimalInteger` | `HexInteger` | `BinInteger` 155 DecimalInteger: ["+" | "-"] ("0"..."9")+ 156 HexInteger: "0x" ("0"..."9" | "a"..."f" | "A"..."F")+ 157 BinInteger: "0b" ("0" | "1")+ 158 159Observe that the :token:`DecimalInteger` token includes the optional ``+`` 160or ``-`` sign, unlike most languages where the sign would be treated as a 161unary operator. 162 163TableGen has two kinds of string literals: 164 165.. productionlist:: 166 TokString: '"' (non-'"' characters and escapes) '"' 167 TokCodeFragment: "[{" (shortest text not containing "}]") "}]" 168 169A :token:`TokCodeFragment` is nothing more than a multi-line string literal 170delimited by ``[{`` and ``}]``. It can break across lines. 171 172The current implementation accepts the following escape sequences:: 173 174 \\ \' \" \t \n 175 176Identifiers 177----------- 178 179TableGen has name- and identifier-like tokens, which are case-sensitive. 180 181.. productionlist:: 182 ualpha: "a"..."z" | "A"..."Z" | "_" 183 TokIdentifier: ("0"..."9")* `ualpha` (`ualpha` | "0"..."9")* 184 TokVarName: "$" `ualpha` (`ualpha` | "0"..."9")* 185 186Note that, unlike most languages, TableGen allows :token:`TokIdentifier` to 187begin with an integer. In case of ambiguity, a token is interpreted as a 188numeric literal rather than an identifier. 189 190TableGen has the following reserved words, which cannot be used as 191identifiers:: 192 193 bit bits class code dag 194 def else foreach defm defset 195 defvar field if in include 196 int let list multiclass string 197 then 198 199.. warning:: 200 The ``field`` reserved word is deprecated. 201 202Bang operators 203-------------- 204 205TableGen provides "bang operators" that have a wide variety of uses: 206 207.. productionlist:: 208 BangOperator: one of 209 : !add !and !cast !con !dag 210 : !empty !eq !foldl !foreach !ge 211 : !getop !gt !head !if !isa 212 : !le !listconcat !listsplat !lt !mul 213 : !ne !not !or !setop !shl 214 : !size !sra !srl !strconcat !subst 215 : !tail !xor 216 217The ``!cond`` operator has a slightly different 218syntax compared to other bang operators, so it is defined separately: 219 220.. productionlist:: 221 CondOperator: !cond 222 223See `Appendix A: Bang Operators`_ for a description of each bang operator. 224 225Include files 226------------- 227 228TableGen has an include mechanism. The content of the included file 229lexically replaces the ``include`` directive and is then parsed as if it was 230originally in the main file. 231 232.. productionlist:: 233 IncludeDirective: "include" `TokString` 234 235Portions of the main file and included files can be conditionalized using 236preprocessor directives. 237 238.. productionlist:: 239 PreprocessorDirective: "#define" | "#ifdef" | "#ifndef" 240 241Types 242===== 243 244The TableGen language is statically typed, using a simple but complete type 245system. Types are used to check for errors, to perform implicit conversions, 246and to help interface designers constrain the allowed input. Every value is 247required to have an associated type. 248 249TableGen supports a mixture of low-level types (e.g., ``bit``) and 250high-level types (e.g., ``dag``). This flexibility allows you to describe a 251wide range of records conveniently and compactly. 252 253.. productionlist:: 254 Type: "bit" | "int" | "string" | "code" | "dag" 255 :| "bits" "<" `TokInteger` ">" 256 :| "list" "<" `Type` ">" 257 :| `ClassID` 258 ClassID: `TokIdentifier` 259 260``bit`` 261 A ``bit`` is a boolean value that can be 0 or 1. 262 263``int`` 264 The ``int`` type represents a simple 64-bit integer value, such as 5 or 265 -42. 266 267``string`` 268 The ``string`` type represents an ordered sequence of characters of arbitrary 269 length. 270 271``code`` 272 The ``code`` type represents a code fragment. The values are the same as 273 those for the ``string`` type; the ``code`` type is provided just to indicate 274 the programmer's intention. 275 276``bits<``\ *n*\ ``>`` 277 The ``bits`` type is a fixed-sized integer of arbitrary length *n* that 278 is treated as separate bits. These bits can be accessed individually. 279 A field of this type is useful for representing an instruction operation 280 code, register number, or address mode/register/displacement. The bits of 281 the field can be set individually or as subfields. For example, in an 282 instruction address, the addressing mode, base register number, and 283 displacement can be set separately. 284 285``list<``\ *type*\ ``>`` 286 This type represents a list whose elements are of the *type* specified in 287 angle brackets. The element type is arbitrary; it can even be another 288 list type. List elements are indexed from 0. 289 290``dag`` 291 This type represents a nestable directed acyclic graph (DAG) of nodes. 292 Each node has an *operator* and zero or more *arguments* (or *operands*). 293 An argument can be 294 another ``dag`` object, allowing an arbitrary tree of nodes and edges. 295 As an example, DAGs are used to represent code patterns for use by 296 the code generator instruction selection algorithms. See `Directed 297 acyclic graphs (DAGs)`_ for more details; 298 299:token:`ClassID` 300 Specifying a class name in a type context indicates 301 that the type of the defined value must 302 be a subclass of the specified class. This is useful in conjunction with 303 the ``list`` type; for example, to constrain the elements of the list to a 304 common base class (e.g., a ``list<Register>`` can only contain definitions 305 derived from the ``Register`` class). 306 The :token:`ClassID` must name a class that has been previously 307 declared or defined. 308 309 310Values and Expressions 311====================== 312 313There are many contexts in TableGen statements where a value is required. A 314common example is in the definition of a record, where each field is 315specified by a name and an optional value. TableGen allows for a reasonable 316number of different forms when building up values. These forms allow the 317TableGen file to be written in a syntax that is natural for the application. 318 319Note that all of the values have rules for converting them from one type to 320another. For example, these rules allow you to assign a value like ``7`` 321to an entity of type ``bits<4>``. 322 323.. productionlist:: 324 Value: `SimpleValue` `ValueSuffix`* 325 ValueSuffix: "{" `RangeList` "}" 326 :| "[" `RangeList` "]" 327 :| "." `TokIdentifier` 328 RangeList: `RangePiece` ("," `RangePiece`)* 329 RangePiece: `TokInteger` 330 :| `TokInteger` "..." `TokInteger` 331 :| `TokInteger` "-" `TokInteger` 332 :| `TokInteger` `TokInteger` 333 334.. warning:: 335 The peculiar last form of :token:`RangePiece` is due to the fact that the 336 "``-``" is included in the :token:`TokInteger`, hence ``1-5`` gets lexed as 337 two consecutive tokens, with values ``1`` and ``-5``, instead of "1", "-", 338 and "5". The use of hyphen as the range punctuation is deprecated. 339 340Simple values 341------------- 342 343The :token:`SimpleValue` has a number of forms. 344 345.. productionlist:: 346 SimpleValue: `TokInteger` | `TokString`+ | `TokCodeFragment` 347 348A value can be an integer literal, a string literal, or a code fragment 349literal. Multiple adjacent string literals are concatenated as in C/C++; the 350simple value is the concatenation of the strings. Code fragments become 351strings and then are indistinguishable from them. 352 353.. productionlist:: 354 SimpleValue2: "?" 355 356A question mark represents an uninitialized value. 357 358.. productionlist:: 359 SimpleValue3: "{" [`ValueList`] "}" 360 ValueList: `ValueListNE` 361 ValueListNE: `Value` ("," `Value`)* 362 363This value represents a sequence of bits, which can be used to initialize a 364``bits<``\ *n*\ ``>`` field (note the braces). When doing so, the values 365must represent a total of *n* bits. 366 367.. productionlist:: 368 SimpleValue4: "[" `ValueList` "]" ["<" `Type` ">"] 369 370This value is a list initializer (note the brackets). The values in brackets 371are the elements of the list. The optional :token:`Type` can be used to 372indicate a specific element type; otherwise the element type is inferred 373from the given values. TableGen can usually infer the type, although 374sometimes not when the value is the empty list (``[]``). 375 376.. productionlist:: 377 SimpleValue5: "(" `DagArg` [`DagArgList`] ")" 378 DagArgList: `DagArg` ("," `DagArg`)* 379 DagArg: `Value` [":" `TokVarName`] | `TokVarName` 380 381This represents a DAG initializer (note the parentheses). The first 382:token:`DagArg` is called the "operator" of the DAG and must be a record. 383See `Directed acyclic graphs (DAGs)`_ for more details. 384 385.. productionlist:: 386 SimpleValue6: `TokIdentifier` 387 388The resulting value is the value of the entity named by the identifier. The 389possible identifiers are described here, but the descriptions will make more 390sense after reading the remainder of this guide. 391 392.. The code for this is exceptionally abstruse. These examples are a 393 best-effort attempt. 394 395* A template argument of a ``class``, such as the use of ``Bar`` in:: 396 397 class Foo <int Bar> { 398 int Baz = Bar; 399 } 400 401* The implicit template argument ``NAME`` in a ``class`` or ``multiclass`` 402 definition (see `NAME`_). 403 404* A field local to a ``class``, such as the use of ``Bar`` in:: 405 406 class Foo { 407 int Bar = 5; 408 int Baz = Bar; 409 } 410 411* The name of a record definition, such as the use of ``Bar`` in the 412 definition of ``Foo``:: 413 414 def Bar : SomeClass { 415 int X = 5; 416 } 417 418 def Foo { 419 SomeClass Baz = Bar; 420 } 421 422* A field local to a record definition, such as the use of ``Bar`` in:: 423 424 def Foo { 425 int Bar = 5; 426 int Baz = Bar; 427 } 428 429 Fields inherited from the record's parent classes can be accessed the same way. 430 431* A template argument of a ``multiclass``, such as the use of ``Bar`` in:: 432 433 multiclass Foo <int Bar> { 434 def : SomeClass<Bar>; 435 } 436 437* A variable defined with the ``defvar`` or ``defset`` statements. 438 439* The iteration variable of a ``foreach``, such as the use of ``i`` in:: 440 441 foreach i = 0...5 in 442 def Foo#i; 443 444.. productionlist:: 445 SimpleValue7: `ClassID` "<" `ValueListNE` ">" 446 447This form creates a new anonymous record definition (as would be created by an 448unnamed ``def`` inheriting from the given class with the given template 449arguments; see `def`_) and the value is that record. A field of the record can be 450obtained using a suffix; see `Suffixed Values`_. 451 452Invoking a class in this manner can provide a simple subroutine facility. 453See `Using Classes as Subroutines`_ for more information. 454 455.. productionlist:: 456 SimpleValue8: `BangOperator` ["<" `Type` ">"] "(" `ValueListNE` ")" 457 :| `CondOperator` "(" `CondClause` ("," `CondClause`)* ")" 458 CondClause: `Value` ":" `Value` 459 460The bang operators provide functions that are not available with the other 461simple values. Except in the case of ``!cond``, a bang 462operator takes a list of arguments enclosed in parentheses and performs some 463function on those arguments, producing a value for that 464bang operator. The ``!cond`` operator takes a list of pairs of arguments 465separated by colons. See `Appendix A: Bang Operators`_ for a description of 466each bang operator. 467 468 469Suffixed values 470--------------- 471 472The :token:`SimpleValue` values described above can be specified with 473certain suffixes. The purpose of a suffix is to obtain a subvalue of the 474primary value. Here are the possible suffixes for some primary *value*. 475 476*value*\ ``{17}`` 477 The final value is bit 17 of the integer *value* (note the braces). 478 479*value*\ ``{8...15}`` 480 The final value is bits 8--15 of the integer *value*. The order of the 481 bits can be reversed by specifying ``{15...8}``. 482 483*value*\ ``[4...7,17,2...3,4]`` 484 The final value is a new list that is a slice of the list *value* (note 485 the brackets). The 486 new list contains elements 4, 5, 6, 7, 17, 2, 3, and 4. Elements may be 487 included multiple times and in any order. 488 489*value*\ ``.`` *field* 490 The final value is the value of the specified *field* in the specified 491 record *value*. 492 493Statements 494========== 495 496The following statements may appear at the top level of TableGen source 497files. 498 499.. productionlist:: 500 TableGenFile: `Statement`* 501 Statement: `Class` | `Def` | `Defm` | `Defset` | `Defvar` | `Foreach` 502 :| `If` | `Let` | `MultiClass` 503 504The following sections describe each of these top-level statements. 505 506 507``class`` --- define an abstract record class 508--------------------------------------------- 509 510A ``class`` statement defines an abstract record class from which other 511classes and records can inherit. 512 513.. productionlist:: 514 Class: "class" `ClassID` [`TemplateArgList`] `RecordBody` 515 TemplateArgList: "<" `TemplateArgDecl` ("," `TemplateArgDecl`)* ">" 516 TemplateArgDecl: `Type` `TokIdentifier` ["=" `Value`] 517 518A class can be parameterized by a list of "template arguments," whose values 519can be used in the class's record body. These template arguments are 520specified each time the class is inherited by another class or record. 521 522If a template argument is not assigned a default value with ``=``, it is 523uninitialized (has the "value" ``?``) and must be specified in the template 524argument list when the class is inherited. If an argument is assigned a 525default value, then it need not be specified in the argument list. The 526template argument default values are evaluated from left to right. 527 528The :token:`RecordBody` is defined below. It can include a list of 529superclasses from which the current class inherits, along with field definitions 530and other statements. When a class ``C`` inherits from another class ``D``, 531the fields of ``D`` are effectively merged into the fields of ``C``. 532 533A given class can only be defined once. A ``class`` statement is 534considered to define the class if *any* of the following are true (the 535:token:`RecordBody` elements are described below). 536 537* The :token:`TemplateArgList` is present, or 538* The :token:`ParentClassList` in the :token:`RecordBody` is present, or 539* The :token:`Body` in the :token:`RecordBody` is present and not empty. 540 541You can declare an empty class by specifying an empty :token:`TemplateArgList` 542and an empty :token:`RecordBody`. This can serve as a restricted form of 543forward declaration. Note that records derived from a forward-declared 544class will inherit no fields from it, because those records are built when 545their declarations are parsed, and thus before the class is finally defined. 546 547.. _NAME: 548 549Every class has an implicit template argument named ``NAME`` (uppercase), 550which is bound to the name of the :token:`Def` or :token:`Defm` inheriting 551the class. The value of ``NAME`` is undefined if the class is inherited by 552an anonymous record. 553 554See `Examples: classes and records`_ for examples. 555 556Record Bodies 557````````````` 558 559Record bodies appear in both class and record definitions. A record body can 560include a parent class list, which specifies the classes from which the 561current class or record inherits fields. Such classes are called the 562superclasses or parent classes of the class or record. The record body also 563includes the main body of the definition, which contains the specification 564of the fields of the class or record. 565 566.. productionlist:: 567 RecordBody: `ParentClassList` `Body` 568 ParentClassList: [":" `ParentClassListNE`] 569 ParentClassListNE: `ClassRef` ("," `ClassRef`)* 570 ClassRef: (`ClassID` | `MultiClassID`) ["<" `ValueList` ">"] 571 572A :token:`ParentClassList` containing a :token:`MultiClassID` is valid only 573in the class list of a ``defm`` statement. In that case, the ID must be the 574name of a multiclass. 575 576.. productionlist:: 577 Body: ";" | "{" `BodyItem`* "}" 578 BodyItem: `Type` `TokIdentifier` ["=" `Value`] ";" 579 :| "let" `TokIdentifier` ["{" `RangeList` "}"] "=" `Value` ";" 580 :| "defvar" `TokIdentifier` "=" `Value` ";" 581 582A field definition in the body specifies a field to be included in the class 583or record. If no initial value is specified, then the field's value is 584uninitialized. The type must be specified; TableGen will not infer it from 585the value. 586 587The ``let`` form is used to reset a field to a new value. This can be done 588for fields defined directly in the body or fields inherited from 589superclasses. A :token:`RangeList` can be specified to reset certain bits 590in a ``bit<n>`` field. 591 592The ``defvar`` form defines a variable whose value can be used in other 593value expressions within the body. The variable is not a field: it does not 594become a field of the class or record being defined. Variables are provided 595to hold temporary values while processing the body. See `Defvar in a Record 596Body`_ for more details. 597 598When class ``C2`` inherits from class ``C1``, it acquires all the field 599definitions of ``C1``. As those definitions are merged into class ``C2``, any 600template arguments passed to ``C1`` by ``C2`` are substituted into the 601definitions. In other words, the abstract record fields defined by ``C1`` are 602expanded with the template arguments before being merged into ``C2``. 603 604 605.. _def: 606 607``def`` --- define a concrete record 608------------------------------------ 609 610A ``def`` statement defines a new concrete record. 611 612.. productionlist:: 613 Def: "def" [`NameValue`] `RecordBody` 614 NameValue: `Value` 615 616The name value is optional. If specified, it is parsed in a special mode 617where undefined (unrecognized) identifiers are interpreted as literal 618strings. In particular, global identifiers are considered unrecognized. 619These include global variables defined by ``defvar`` and ``defset``. 620 621If no name value is given, the record is *anonymous*. The final name of an 622anonymous record is unspecified but globally unique. 623 624Special handling occurs if a ``def`` appears inside a ``multiclass`` 625statement. See the ``multiclass`` section below for details. 626 627A record can inherit from one or more classes by specifying the 628:token:`ParentClassList` clause at the beginning of its record body. All of 629the fields in the parent classes are added to the record. If two or more 630parent classes provide the same field, the record ends up with the field value 631of the last parent class. 632 633As a special case, the name of a record can be passed in a template argument 634to that record's superclasses. For example: 635 636.. code-block:: text 637 638 class A <dag d> { 639 dag the_dag = d; 640 } 641 642 def rec1 : A<(ops rec1)> 643 644The DAG ``(ops rec1)`` is passed as a template argument to class ``A``. Notice 645that the DAG includes ``rec1``, the record being defined. 646 647The steps taken to create a new record are somewhat complex. See `How 648records are built`_. 649 650See `Examples: classes and records`_ for examples. 651 652 653Examples: classes and records 654----------------------------- 655 656Here is a simple TableGen file with one class and two record definitions. 657 658.. code-block:: text 659 660 class C { 661 bit V = 1; 662 } 663 664 def X : C; 665 def Y : C { 666 let V = 0; 667 string Greeting = "Hello!"; 668 } 669 670First, the abstract class ``C`` is defined. It has one field named ``V`` 671that is a bit initialized to 1. 672 673Next, two records are defined, derived from class ``C``; that is, with ``C`` 674as their superclass. Thus they both inherit the ``V`` field. Record ``Y`` 675also defines another string field, ``Greeting``, which is initialized to 676``"Hello!"``. In addition, ``Y`` overrides the inherited ``V`` field, 677setting it to 0. 678 679A class is useful for isolating the common features of multiple records in 680one place. A class can initialize common fields to default values, but 681records inheriting from that class can override the defaults. 682 683TableGen supports the definition of parameterized classes as well as 684nonparameterized ones. Parameterized classes specify a list of variable 685declarations, which may optionally have defaults, that are bound when the 686class is specified as a superclass of another class or record. 687 688.. code-block:: text 689 690 class FPFormat <bits<3> val> { 691 bits<3> Value = val; 692 } 693 694 def NotFP : FPFormat<0>; 695 def ZeroArgFP : FPFormat<1>; 696 def OneArgFP : FPFormat<2>; 697 def OneArgFPRW : FPFormat<3>; 698 def TwoArgFP : FPFormat<4>; 699 def CompareFP : FPFormat<5>; 700 def CondMovFP : FPFormat<6>; 701 def SpecialFP : FPFormat<7>; 702 703The purpose of the ``FPFormat`` class is to act as a sort of enumerated 704type. It provides a single field, ``Value``, which holds a 3-bit number. Its 705template argument, ``val``, is used to set the ``Value`` field. 706Each of the eight records is defined with ``FPFormat`` as its superclass. The 707enumeration value is passed in angle brackets as the template argument. Each 708record will inherent the ``Value`` field with the appropriate enumeration 709value. 710 711Here is a more complex example of classes with template arguments. First, we 712define a class similar to the ``FPFormat`` class above. It takes a template 713argument and uses it to initialize a field named ``Value``. Then we define 714four records that inherit the ``Value`` field with its four different 715integer values. 716 717.. code-block:: text 718 719 class ModRefVal <bits<2> val> { 720 bits<2> Value = val; 721 } 722 723 def None : ModRefVal<0>; 724 def Mod : ModRefVal<1>; 725 def Ref : ModRefVal<2>; 726 def ModRef : ModRefVal<3>; 727 728This is somewhat contrived, but let's say we would like to examine the two 729bits of the ``Value`` field independently. We can define a class that 730accepts a ``ModRefVal`` record as a template argument and splits up its 731value into two fields, one bit each. Then we can define records that inherit from 732``ModRefBits`` and so acquire two fields from it, one for each bit in the 733``ModRefVal`` record passed as the template argument. 734 735.. code-block:: text 736 737 class ModRefBits <ModRefVal mrv> { 738 // Break the value up into its bits, which can provide a nice 739 // interface to the ModRefVal values. 740 bit isMod = mrv.Value{0}; 741 bit isRef = mrv.Value{1}; 742 } 743 744 // Example uses. 745 def foo : ModRefBits<Mod>; 746 def bar : ModRefBits<Ref>; 747 def snork : ModRefBits<ModRef>; 748 749This illustrates how one class can be defined to reorganize the 750fields in another class, thus hiding the internal representation of that 751other class. 752 753Running ``llvm-tblgen`` on the example prints the following definitions: 754 755.. code-block:: text 756 757 def bar { // Value 758 bit isMod = 0; 759 bit isRef = 1; 760 } 761 def foo { // Value 762 bit isMod = 1; 763 bit isRef = 0; 764 } 765 def snork { // Value 766 bit isMod = 1; 767 bit isRef = 1; 768 } 769 770``let`` --- override fields in classes or records 771------------------------------------------------- 772 773A ``let`` statement collects a set of field values (sometimes called 774*bindings*) and applies them to all the classes and records defined by 775statements within the scope of the ``let``. 776 777.. productionlist:: 778 Let: "let" `LetList` "in" "{" `Statement`* "}" 779 :| "let" `LetList` "in" `Statement` 780 LetList: `LetItem` ("," `LetItem`)* 781 LetItem: `TokIdentifier` ["<" `RangeList` ">"] "=" `Value` 782 783The ``let`` statement establishes a scope, which is a sequence of statements 784in braces or a single statement with no braces. The bindings in the 785:token:`LetList` apply to the statements in that scope. 786 787The field names in the :token:`LetList` must name fields in classes inherited by 788the classes and records defined in the statements. The field values are 789applied to the classes and records *after* the records inherit all the fields from 790their superclasses. So the ``let`` acts to override inherited field 791values. A ``let`` cannot override the value of a template argument. 792 793Top-level ``let`` statements are often useful when a few fields need to be 794overriden in several records. Here are two examples. Note that ``let`` 795statements can be nested. 796 797.. code-block:: text 798 799 let isTerminator = 1, isReturn = 1, isBarrier = 1, hasCtrlDep = 1 in 800 def RET : I<0xC3, RawFrm, (outs), (ins), "ret", [(X86retflag 0)]>; 801 802 let isCall = 1 in 803 // All calls clobber the non-callee saved registers... 804 let Defs = [EAX, ECX, EDX, FP0, FP1, FP2, FP3, FP4, FP5, FP6, ST0, 805 MM0, MM1, MM2, MM3, MM4, MM5, MM6, MM7, XMM0, XMM1, XMM2, 806 XMM3, XMM4, XMM5, XMM6, XMM7, EFLAGS] in { 807 def CALLpcrel32 : Ii32<0xE8, RawFrm, (outs), (ins i32imm:$dst, variable_ops), 808 "call\t${dst:call}", []>; 809 def CALL32r : I<0xFF, MRM2r, (outs), (ins GR32:$dst, variable_ops), 810 "call\t{*}$dst", [(X86call GR32:$dst)]>; 811 def CALL32m : I<0xFF, MRM2m, (outs), (ins i32mem:$dst, variable_ops), 812 "call\t{*}$dst", []>; 813 } 814 815Note that a top-level ``let`` will not override fields defined in the classes or records 816themselves. 817 818 819``multiclass`` --- define multiple records 820------------------------------------------ 821 822While classes with template arguments are a good way to factor out commonality 823between multiple records, multiclasses allow a convenient method for 824defining multiple records at once. For example, consider a 3-address 825instruction architecture whose instructions come in two formats: ``reg = reg 826op reg`` and ``reg = reg op imm`` (e.g., SPARC). We would like to specify in 827one place that these two common formats exist, then in a separate place 828specify what all the operations are. The ``multiclass`` and ``defm`` 829statements accomplish this goal. You can think of a multiclass as a macro or 830template that expands into multiple records. 831 832.. productionlist:: 833 MultiClass: "multiclass" `TokIdentifier` [`TemplateArgList`] 834 : [":" `ParentMultiClassList`] 835 : "{" `Statement`+ "}" 836 ParentMultiClassList: `MultiClassID` ("," `MultiClassID`)* 837 MultiClassID: `TokIdentifier` 838 839As with regular classes, the multiclass has a name and can accept template 840arguments. A multiclass can inherit from other multiclasses, which causes 841the other multiclasses to be expanded and contribute to the record 842definitions in the inheriting multiclass. The body of the multiclass 843contains a series of statements that define records, using :token:`Def` and 844:token:`Defm`. In addition, :token:`Defvar`, :token:`Foreach`, and 845:token:`Let` statements can be used to factor out even more common elements. 846The :token:`If` statement can also be used. 847 848Also as with regular classes, the multiclass has the implicit template 849argument ``NAME`` (see NAME_). When a named (non-anonymous) record is 850defined in a multiclass and the record's name does not contain a use of the 851template argument ``NAME``, such a use is automatically prepended 852to the name. That is, the following are equivalent inside a multiclass:: 853 854 def Foo ... 855 def NAME#Foo ... 856 857The records defined in a multiclass are instantiated when the multiclass is 858"invoked" by a ``defm`` statement outside the multiclass definition. Each 859``def`` statement produces a record. As with top-level ``def`` statements, 860these definitions can inherit from multiple superclasses. 861 862See `Examples: multiclasses and defms`_ for examples. 863 864 865``defm`` --- invoke multiclasses to define multiple records 866----------------------------------------------------------- 867 868Once multiclasses have been defined, you use the ``defm`` statement to 869"invoke" multiclasses and process the multiple record definitions in those 870multiclasses. Those record definitions are specified by ``def`` 871statements in the multiclasses, and indirectly by ``defm`` statements. 872 873.. productionlist:: 874 Defm: "defm" [`NameValue`] `ParentClassList` ";" 875 876The optional :token:`NameValue` is formed in the same way as the name of a 877``def``. The :token:`ParentClassList` is a colon followed by a list of at least one 878multiclass and any number of regular classes. The multiclasses must 879precede the regular classes. Note that the ``defm`` does not have a body. 880 881This statement instantiates all the records defined in all the specified 882multiclasses, either directly by ``def`` statements or indirectly by 883``defm`` statements. These records also receive the fields defined in any 884regular classes included in the parent class list. This is useful for adding 885a common set of fields to all the records created by the ``defm``. 886 887The name is parsed in the same special mode used by ``def``. If the name is 888not included, a globally unique name is provided. That is, the following 889examples end up with different names:: 890 891 defm : SomeMultiClass<...>; // A globally unique name. 892 defm "" : SomeMultiClass<...>; // An empty name. 893 894The ``defm`` statement can be used in a multiclass body. When this occurs, 895the second variant is equivalent to:: 896 897 defm NAME : SomeMultiClass<...>; 898 899More generally, when ``defm`` occurs in a multiclass and its name does not 900include a use of the implicit template argument ``NAME``, then ``NAME`` will 901be prepended automatically. That is, the following are equivalent inside a 902multiclass:: 903 904 defm Foo : SomeMultiClass<...>; 905 defm NAME#Foo : SomeMultiClass<...>; 906 907See `Examples: multiclasses and defms`_ for examples. 908 909Examples: multiclasses and defms 910-------------------------------- 911 912Here is a simple example using ``multiclass`` and ``defm``. Consider a 9133-address instruction architecture whose instructions come in two formats: 914``reg = reg op reg`` and ``reg = reg op imm`` (immediate). The SPARC is an 915example of such an architecture. 916 917.. code-block:: text 918 919 def ops; 920 def GPR; 921 def Imm; 922 class inst <int opc, string asmstr, dag operandlist>; 923 924 multiclass ri_inst <int opc, string asmstr> { 925 def _rr : inst<opc, !strconcat(asmstr, " $dst, $src1, $src2"), 926 (ops GPR:$dst, GPR:$src1, GPR:$src2)>; 927 def _ri : inst<opc, !strconcat(asmstr, " $dst, $src1, $src2"), 928 (ops GPR:$dst, GPR:$src1, Imm:$src2)>; 929 } 930 931 // Define records for each instruction in the RR and RI formats. 932 defm ADD : ri_inst<0b111, "add">; 933 defm SUB : ri_inst<0b101, "sub">; 934 defm MUL : ri_inst<0b100, "mul">; 935 936Each use of the ``ri_inst`` multiclass defines two records, one with the 937``_rr`` suffix and one with ``_ri``. Recall that the name of the ``defm`` 938that uses a multiclass is prepended to the names of the records defined in 939that multiclass. So the resulting definitions are named:: 940 941 ADD_rr, ADD_ri 942 SUB_rr, SUB_ri 943 MUL_rr, MUL_ri 944 945Without the ``multiclass`` feature, the instructions would have to be 946defined as follows. 947 948.. code-block:: text 949 950 def ops; 951 def GPR; 952 def Imm; 953 class inst <int opc, string asmstr, dag operandlist>; 954 955 class rrinst <int opc, string asmstr> 956 : inst<opc, !strconcat(asmstr, " $dst, $src1, $src2"), 957 (ops GPR:$dst, GPR:$src1, GPR:$src2)>; 958 959 class riinst <int opc, string asmstr> 960 : inst<opc, !strconcat(asmstr, " $dst, $src1, $src2"), 961 (ops GPR:$dst, GPR:$src1, Imm:$src2)>; 962 963 // Define records for each instruction in the RR and RI formats. 964 def ADD_rr : rrinst<0b111, "add">; 965 def ADD_ri : riinst<0b111, "add">; 966 def SUB_rr : rrinst<0b101, "sub">; 967 def SUB_ri : riinst<0b101, "sub">; 968 def MUL_rr : rrinst<0b100, "mul">; 969 def MUL_ri : riinst<0b100, "mul">; 970 971A ``defm`` can be used in a multiclass to "invoke" other multiclasses and 972create the records defined in those multiclasses in addition to the records 973defined in the current multiclass. In the following example, the ``basic_s`` 974and ``basic_p`` multiclasses contain ``defm`` statements that refer to the 975``basic_r`` multiclass. The ``basic_r`` multiclass contains only ``def`` 976statements. 977 978.. code-block:: text 979 980 class Instruction <bits<4> opc, string Name> { 981 bits<4> opcode = opc; 982 string name = Name; 983 } 984 985 multiclass basic_r <bits<4> opc> { 986 def rr : Instruction<opc, "rr">; 987 def rm : Instruction<opc, "rm">; 988 } 989 990 multiclass basic_s <bits<4> opc> { 991 defm SS : basic_r<opc>; 992 defm SD : basic_r<opc>; 993 def X : Instruction<opc, "x">; 994 } 995 996 multiclass basic_p <bits<4> opc> { 997 defm PS : basic_r<opc>; 998 defm PD : basic_r<opc>; 999 def Y : Instruction<opc, "y">; 1000 } 1001 1002 defm ADD : basic_s<0xf>, basic_p<0xf>; 1003 1004The final ``defm`` creates the following records, five from the ``basic_s`` 1005multiclass and five from the ``basic_p`` multiclass:: 1006 1007 ADDSSrr, ADDSSrm 1008 ADDSDrr, ADDSDrm 1009 ADDX 1010 ADDPSrr, ADDPSrm 1011 ADDPDrr, ADDPDrm 1012 ADDY 1013 1014A ``defm`` statement, both at top level and in a multiclass, can inherit 1015from regular classes in addition to multiclasses. The rule is that the 1016regular classes must be listed after the multiclasses, and there must be at least 1017one multiclass. 1018 1019.. code-block:: text 1020 1021 class XD { 1022 bits<4> Prefix = 11; 1023 } 1024 class XS { 1025 bits<4> Prefix = 12; 1026 } 1027 class I <bits<4> op> { 1028 bits<4> opcode = op; 1029 } 1030 1031 multiclass R { 1032 def rr : I<4>; 1033 def rm : I<2>; 1034 } 1035 1036 multiclass Y { 1037 defm SS : R, XD; // First multiclass R, then regular class XD. 1038 defm SD : R, XS; 1039 } 1040 1041 defm Instr : Y; 1042 1043This example will create four records, shown here in alphabetical order with 1044their fields. 1045 1046.. code-block:: text 1047 1048 def InstrSDrm { 1049 bits<4> opcode = { 0, 0, 1, 0 }; 1050 bits<4> Prefix = { 1, 1, 0, 0 }; 1051 } 1052 1053 def InstrSDrr { 1054 bits<4> opcode = { 0, 1, 0, 0 }; 1055 bits<4> Prefix = { 1, 1, 0, 0 }; 1056 } 1057 1058 def InstrSSrm { 1059 bits<4> opcode = { 0, 0, 1, 0 }; 1060 bits<4> Prefix = { 1, 0, 1, 1 }; 1061 } 1062 1063 def InstrSSrr { 1064 bits<4> opcode = { 0, 1, 0, 0 }; 1065 bits<4> Prefix = { 1, 0, 1, 1 }; 1066 } 1067 1068It's also possible to use ``let`` statements inside multiclasses, providing 1069another way to factor out commonality from the records, especially when 1070using several levels of multiclass instantiations. 1071 1072.. code-block:: text 1073 1074 multiclass basic_r <bits<4> opc> { 1075 let Predicates = [HasSSE2] in { 1076 def rr : Instruction<opc, "rr">; 1077 def rm : Instruction<opc, "rm">; 1078 } 1079 let Predicates = [HasSSE3] in 1080 def rx : Instruction<opc, "rx">; 1081 } 1082 1083 multiclass basic_ss <bits<4> opc> { 1084 let IsDouble = 0 in 1085 defm SS : basic_r<opc>; 1086 1087 let IsDouble = 1 in 1088 defm SD : basic_r<opc>; 1089 } 1090 1091 defm ADD : basic_ss<0xf>; 1092 1093 1094``defset`` --- create a definition set 1095-------------------------------------- 1096 1097The ``defset`` statement is used to collect a set of records into a global 1098list of records. 1099 1100.. productionlist:: 1101 Defset: "defset" `Type` `TokIdentifier` "=" "{" `Statement`* "}" 1102 1103All records defined inside the braces via ``def`` and ``defm`` are defined 1104as usual, and they are also collected in a global list of the given name 1105(:token:`TokIdentifier`). 1106 1107The specified type must be ``list<``\ *class*\ ``>``, where *class* is some 1108record class. The ``defset`` statement establishes a scope for its 1109statements. It is an error to define a record in the scope of the 1110``defset`` that is not of type *class*. 1111 1112The ``defset`` statement can be nested. The inner ``defset`` adds the 1113records to its own set, and all those records are also added to the outer 1114set. 1115 1116Anonymous records created inside initialization expressions using the 1117``ClassID<...>`` syntax are not collected in the set. 1118 1119 1120``defvar`` --- define a variable 1121-------------------------------- 1122 1123A ``defvar`` statement defines a global variable. Its value can be used 1124throughout the statements that follow the definition. 1125 1126.. productionlist:: 1127 Defvar: "defvar" `TokIdentifier` "=" `Value` ";" 1128 1129The identifier on the left of the ``=`` is defined to be a global variable 1130whose value is given by the value expression on the right of the ``=``. The 1131type of the variable is automatically inferred. 1132 1133Once a variable has been defined, it cannot be set to another value. 1134 1135Variables defined in a top-level ``foreach`` go out of scope at the end of 1136each loop iteration, so their value in one iteration is not available in 1137the next iteration. The following ``defvar`` will not work:: 1138 1139 defvar i = !add(i, 1) 1140 1141Variables can also be defined with ``defvar`` in a record body. See 1142`Defvar in a Record Body`_ for more details. 1143 1144``foreach`` --- iterate over a sequence of statements 1145----------------------------------------------------- 1146 1147The ``foreach`` statement iterates over a series of statements, varying a 1148variable over a sequence of values. 1149 1150.. productionlist:: 1151 Foreach: "foreach" `ForeachIterator` "in" "{" `Statement`* "}" 1152 :| "foreach" `ForeachIterator` "in" `Statement` 1153 ForeachIterator: `TokIdentifier` "=" ("{" `RangeList` "}" | `RangePiece` | `Value`) 1154 1155The body of the ``foreach`` is a series of statements in braces or a 1156single statement with no braces. The statements are re-evaluated once for 1157each value in the range list, range piece, or single value. On each 1158iteration, the :token:`TokIdentifier` variable is set to the value and can 1159be used in the statements. 1160 1161The statement list establishes an inner scope. Variables local to a 1162``foreach`` go out of scope at the end of each loop iteration, so their 1163values do not carry over from one iteration to the next. Foreach loops may 1164be nested. 1165 1166The ``foreach`` statement can also be used in a record :token:`Body`. 1167 1168.. Note that the productions involving RangeList and RangePiece have precedence 1169 over the more generic value parsing based on the first token. 1170 1171.. code-block:: text 1172 1173 foreach i = [0, 1, 2, 3] in { 1174 def R#i : Register<...>; 1175 def F#i : Register<...>; 1176 } 1177 1178This loop defines records named ``R0``, ``R1``, ``R2``, and ``R3``, along 1179with ``F0``, ``F1``, ``F2``, and ``F3``. 1180 1181 1182``if`` --- select statements based on a test 1183-------------------------------------------- 1184 1185The ``if`` statement allows one of two statement groups to be selected based 1186on the value of an expression. 1187 1188.. productionlist:: 1189 If: "if" `Value` "then" `IfBody` 1190 :| "if" `Value` "then" `IfBody` "else" `IfBody` 1191 IfBody: "{" `Statement`* "}" | `Statement` 1192 1193The value expression is evaluated. If it evaluates to true (in the same 1194sense used by the bang operators), then the statements following the 1195``then`` reserved word are processed. Otherwise, if there is an ``else`` 1196reserved word, the statements following the ``else`` are processed. If the 1197value is false and there is no ``else`` arm, no statements are processed. 1198 1199Because the braces around the ``then`` statements are optional, this grammar rule 1200has the usual ambiguity with "dangling else" clauses, and it is resolved in 1201the usual way: in a case like ``if v1 then if v2 then {...} else {...}``, the 1202``else`` associates with the inner ``if`` rather than the outer one. 1203 1204The :token:`IfBody` of the then and else arms of the ``if`` establish an 1205inner scope. Any ``defvar`` variables defined in the bodies go out of scope 1206when the bodies are finished (see `Defvar in a Record Body`_ for more details). 1207 1208The ``if`` statement can also be used in a record :token:`Body`. 1209 1210 1211Additional Details 1212================== 1213 1214Directed acyclic graphs (DAGs) 1215------------------------------ 1216 1217A directed acyclic graph can be represented directly in TableGen using the 1218``dag`` datatype. A DAG node consists of an operator and zero or more 1219arguments (or operands). Each argument can be of any desired type. By using 1220another DAG node as an argument, an arbitrary graph of DAG nodes can be 1221built. 1222 1223The syntax of a ``dag`` instance is: 1224 1225 ``(`` *operator* *argument1*\ ``,`` *argument2*\ ``,`` ... ``)`` 1226 1227The operator must be present and must be a record. There can be zero or more 1228arguments, separated by commas. The operator and arguments can have three 1229formats. 1230 1231====================== ============================================= 1232Format Meaning 1233====================== ============================================= 1234*value* argument value 1235*value*\ ``:``\ *name* argument value and associated name 1236*name* argument name with unset (uninitialized) value 1237====================== ============================================= 1238 1239The *value* can be any TableGen value. The *name*, if present, must be a 1240:token:`TokVarName`, which starts with a dollar sign (``$``). The purpose of 1241a name is to tag an operator or argument in a DAG with a particular meaning, 1242or to associate an argument in one DAG with a like-named argument in another 1243DAG. 1244 1245The following bang operators are useful for working with DAGs: 1246``!con``, ``!dag``, ``!empty``, ``!foreach``, ``!getop``, ``!setop``, ``!size``. 1247 1248Defvar in a record body 1249----------------------- 1250 1251In addition to defining global variables, the ``defvar`` statement can 1252be used inside the :token:`Body` of a class or record definition to define 1253local variables. The scope of the variable extends from the ``defvar`` 1254statement to the end of the body. It cannot be set to a different value 1255within its scope. The ``defvar`` statement can also be used in the statement 1256list of a ``foreach``, which establishes a scope. 1257 1258A variable named ``V`` in an inner scope shadows (hides) any variables ``V`` 1259in outer scopes. In particular, ``V`` in a record body shadows a global 1260``V``, and ``V`` in a ``foreach`` statement list shadows any ``V`` in 1261surrounding record or global scopes. 1262 1263Variables defined in a ``foreach`` go out of scope at the end of 1264each loop iteration, so their value in one iteration is not available in 1265the next iteration. The following ``defvar`` will not work:: 1266 1267 defvar i = !add(i, 1) 1268 1269How records are built 1270--------------------- 1271 1272The following steps are taken by TableGen when a record is built. Classes are simply 1273abstract records and so go through the same steps. 1274 12751. Build the record name (:token:`NameValue`) and create an empty record. 1276 12772. Parse the superclasses in the :token:`ParentClassList` from left to 1278 right, visiting each superclass's ancestor classes from top to bottom. 1279 1280 a. Add the fields from the superclass to the record. 1281 b. Substitute the template arguments into those fields. 1282 c. Add the superclass to the record's list of inherited classes. 1283 12843. Apply any top-level ``let`` bindings to the record. Recall that top-level 1285 bindings only apply to inherited fields. 1286 12874. Parse the body of the record. 1288 1289 * Add any fields to the record. 1290 * Modify the values of fields according to local ``let`` statements. 1291 * Define any ``defvar`` variables. 1292 12935. Make a pass over all the fields to resolve any inter-field references. 1294 12956. Add the record to the master record list. 1296 1297Because references between fields are resolved (step 5) after ``let`` bindings are 1298applied (step 3), the ``let`` statement has unusual power. For example: 1299 1300.. code-block:: text 1301 1302 class C <int x> { 1303 int Y = x; 1304 int Yplus1 = !add(Y, 1); 1305 int xplus1 = !add(x, 1); 1306 } 1307 1308 let Y = 10 in { 1309 def rec1 : C<5> { 1310 } 1311 } 1312 1313 def rec2 : C<5> { 1314 let Y = 10; 1315 } 1316 1317In both cases, one where a top-level ``let`` is used to bind ``Y`` and one 1318where a local ``let`` does the same thing, the results are: 1319 1320.. code-block:: text 1321 1322 def rec1 { // C 1323 int Y = 10; 1324 int Yplus1 = 11; 1325 int xplus1 = 6; 1326 } 1327 def rec2 { // C 1328 int Y = 10; 1329 int Yplus1 = 11; 1330 int xplus1 = 6; 1331 } 1332 1333``Yplus1`` is 11 because the ``let Y`` is performed before the ``!add(Y, 13341)`` is resolved. Use this power wisely. 1335 1336 1337Using Classes as Subroutines 1338============================ 1339 1340As described in `Simple values`_, a class can be invoked in an expression 1341and passed template arguments. This causes TableGen to create a new anonymous 1342record inheriting from that class. As usual, the record receives all the 1343fields defined in the class. 1344 1345This feature can be employed as a simple subroutine facility. The class can 1346use the template arguments to define various variables and fields, which end 1347up in the anonymous record. Those fields can then be retrieved in the 1348expression invoking the class as follows. Assume that the field ``ret`` 1349contains the final value of the subroutine. 1350 1351.. code-block:: text 1352 1353 int Result = ... CalcValue<arg>.ret ...; 1354 1355The ``CalcValue`` class is invoked with the template argument ``arg``. It 1356calculates a value for the ``ret`` field, which is then retrieved at the 1357"point of call" in the initialization for the Result field. The anonymous 1358record created in this example serves no other purpose than to carry the 1359result value. 1360 1361Here is a practical example. The class ``isValidSize`` determines whether a 1362specified number of bytes represents a valid data size. The bit ``ret`` is 1363set appropriately. The field ``ValidSize`` obtains its initial value by 1364invoking ``isValidSize`` with the data size and retrieving the ``ret`` field 1365from the resulting anonymous record. 1366 1367.. code-block:: text 1368 1369 class isValidSize<int size> { 1370 bit ret = !cond(!eq(size, 1): 1, 1371 !eq(size, 2): 1, 1372 !eq(size, 4): 1, 1373 !eq(size, 8): 1, 1374 !eq(size, 16): 1, 1375 1: 0); 1376 } 1377 1378 def Data1 { 1379 int Size = ...; 1380 bit ValidSize = isValidSize<Size>.ret; 1381 } 1382 1383Preprocessing Facilities 1384======================== 1385 1386The preprocessor embedded in TableGen is intended only for simple 1387conditional compilation. It supports the following directives, which are 1388specified somewhat informally. 1389 1390.. productionlist:: 1391 LineBegin: beginning of line 1392 LineEnd: newline | return | EOF 1393 WhiteSpace: space | tab 1394 CComment: "/*" ... "*/" 1395 BCPLComment: "//" ... `LineEnd` 1396 WhiteSpaceOrCComment: `WhiteSpace` | `CComment` 1397 WhiteSpaceOrAnyComment: `WhiteSpace` | `CComment` | `BCPLComment` 1398 MacroName: `ualpha` (`ualpha` | "0"..."9")* 1399 PreDefine: `LineBegin` (`WhiteSpaceOrCComment`)* 1400 : "#define" (`WhiteSpace`)+ `MacroName` 1401 : (`WhiteSpaceOrAnyComment`)* `LineEnd` 1402 PreIfdef: `LineBegin` (`WhiteSpaceOrCComment`)* 1403 : ("#ifdef" | "#ifndef") (`WhiteSpace`)+ `MacroName` 1404 : (`WhiteSpaceOrAnyComment`)* `LineEnd` 1405 PreElse: `LineBegin` (`WhiteSpaceOrCComment`)* 1406 : "#else" (`WhiteSpaceOrAnyComment`)* `LineEnd` 1407 PreEndif: `LineBegin` (`WhiteSpaceOrCComment`)* 1408 : "#endif" (`WhiteSpaceOrAnyComment`)* `LineEnd` 1409 1410.. 1411 PreRegContentException: `PreIfdef` | `PreElse` | `PreEndif` | EOF 1412 PreRegion: .* - `PreRegContentException` 1413 :| `PreIfdef` 1414 : (`PreRegion`)* 1415 : [`PreElse`] 1416 : (`PreRegion`)* 1417 : `PreEndif` 1418 1419A :token:`MacroName` can be defined anywhere in a TableGen file. The name has 1420no value; it can only be tested to see whether it is defined. 1421 1422A macro test region begins with an ``#ifdef`` or ``#ifndef`` directive. If 1423the macro name is defined (``#ifdef``) or undefined (``#ifndef``), then the 1424source code between the directive and the corresponding ``#else`` or 1425``#endif`` is processed. If the test fails but there is an ``#else`` 1426clause, the source code between the ``#else`` and the ``#endif`` is 1427processed. If the test fails and there is no ``#else`` clause, then no 1428source code in the test region is processed. 1429 1430Test regions may be nested, but they must be properly nested. A region 1431started in a file must end in that file; that is, must have its 1432``#endif`` in the same file. 1433 1434A :token:`MacroName` may be defined externally using the ``-D`` option on the 1435``xxx-tblgen`` command line:: 1436 1437 llvm-tblgen self-reference.td -Dmacro1 -Dmacro3 1438 1439Appendix A: Bang Operators 1440========================== 1441 1442Bang operators act as functions in value expressions. A bang operator takes 1443one or more arguments, operates on them, and produces a result. If the 1444operator produces a boolean result, the result value will be 1 for true or 0 1445for false. When an operator tests a boolean argument, it interprets 0 as false 1446and non-0 as true. 1447 1448``!add(``\ *a*\ ``,`` *b*\ ``, ...)`` 1449 This operator adds *a*, *b*, etc., and produces the sum. 1450 1451``!and(``\ *a*\ ``,`` *b*\ ``, ...)`` 1452 This operator does a bitwise AND on *a*, *b*, etc., and produces the 1453 result. A logical AND can be performed if all the arguments are either 1454 0 or 1. 1455 1456``!cast<``\ *type*\ ``>(``\ *a*\ ``)`` 1457 This operator performs a cast on *a* and produces the result. 1458 If *a* is not a string, then a straightforward cast is performed, say 1459 between an ``int`` and a ``bit``, or between record types. This allows 1460 casting a record to a class. If a record is cast to ``string``, the 1461 record's name is produced. 1462 1463 If *a* is a string, then it is treated as a record name and looked up in 1464 the list of all defined records. The resulting record is expected to be of 1465 the specified *type*. 1466 1467 For example, if ``!cast<``\ *type*\ ``>(``\ *name*\ ``)`` 1468 appears in a multiclass definition, or in a 1469 class instantiated inside a multiclass definition, and the *name* does not 1470 reference any template arguments of the multiclass, then a record by 1471 that name must have been instantiated earlier 1472 in the source file. If *name* does reference 1473 a template argument, then the lookup is delayed until ``defm`` statements 1474 instantiating the multiclass (or later, if the defm occurs in another 1475 multiclass and template arguments of the inner multiclass that are 1476 referenced by *name* are substituted by values that themselves contain 1477 references to template arguments of the outer multiclass). 1478 1479 If the type of *a* does not match *type*, TableGen raises an error. 1480 1481``!con(``\ *a*\ ``,`` *b*\ ``, ...)`` 1482 This operator concatenates the DAG nodes *a*, *b*, etc. Their operations 1483 must equal. 1484 1485 ``!con((op a1:$name1, a2:$name2), (op b1:$name3))`` 1486 1487 results in the DAG node ``(op a1:$name1, a2:$name2, b1:$name3)``. 1488 1489``!cond(``\ *cond1* ``:`` *val1*\ ``,`` *cond2* ``:`` *val2*\ ``, ...,`` *condn* ``:`` *valn*\ ``)`` 1490 This operator tests *cond1* and returns *val1* if the result is true. 1491 If false, the operator tests *cond2* and returns *val2* if the result is 1492 true. And so forth. An error is reported if no conditions are true. 1493 1494 This example produces the sign word for an integer:: 1495 1496 !cond(!lt(x, 0) : "negative", !eq(x, 0) : "zero", 1 : "positive") 1497 1498``!dag(``\ *op*\ ``,`` *children*\ ``,`` *names*\ ``)`` 1499 This operator creates a DAG node. 1500 The *children* and *names* arguments must be lists 1501 of equal length or uninitialized (``?``). The *names* argument 1502 must be of type ``list<string>``. 1503 1504 Due to limitations of the type system, *children* must be a list of items 1505 of a common type. In practice, this means that they should either have the 1506 same type or be records with a common superclass. Mixing ``dag`` and 1507 non-``dag`` items is not possible. However, ``?`` can be used. 1508 1509 Example: ``!dag(op, [a1, a2, ?], ["name1", "name2", "name3"])`` results in 1510 ``(op a1:$name1, a2:$name2, ?:$name3)``. 1511 1512``!empty(``\ *a*\ ``)`` 1513 This operator produces 1 if the string, list, or DAG *a* is empty; 0 otherwise. 1514 A dag is empty if it has no arguments; the operator does not count. 1515 1516``!eq(`` *a*\ `,` *b*\ ``)`` 1517 This operator produces 1 if *a* is equal to *b*; 0 otherwise. 1518 The arguments must be ``bit``, ``int``, or ``string`` values. 1519 Use ``!cast<string>`` to compare other types of objects. 1520 1521``!foldl(``\ *start*\ ``,`` *list*\ ``,`` *a*\ ``,`` *b*\ ``,`` *expr*\ ``)`` 1522 This operator performs a left-fold over the items in *list*. The 1523 variable *a* acts as the accumulator and is initialized to *start*. 1524 The variable *b* is bound to each element in the *list*. The *expr* 1525 expression is evaluated for each element and presumably uses *a* and *b* 1526 to calculate the accumulated value, which ``!foldl`` stores in *a*. The 1527 type of *a* is the same as *start*; the type of *b* is the same as the 1528 elements of *list*; *expr* must have the same type as *start*. 1529 1530 The following example computes the total of the ``Number`` field in the 1531 list of records in ``RecList``:: 1532 1533 int x = !foldl(0, RecList, total, rec, !add(total, rec.Number)); 1534 1535``!foreach(``\ *var*\ ``,`` *seq*\ ``,`` *form*\ ``)`` 1536 This operator creates a new ``list``/``dag`` in which each element is a 1537 function of the corresponding element in the *seq* ``list``/``dag``. To 1538 perform the function, TableGen binds the variable *var* to an element and 1539 then evaluates the *form* expression. The form presumably refers to the 1540 variable *var* and calculates the result value. 1541 1542``!ge(``\ *a*\ `,` *b*\ ``)`` 1543 This operator produces 1 if *a* is greater than or equal to *b*; 0 otherwise. 1544 The arguments must be ``bit``, ``int``, or ``string`` values. 1545 Use ``!cast<string>`` to compare other types of objects. 1546 1547``!getop(``\ *dag*\ ``)`` --or-- ``!getop<``\ *type*\ ``>(``\ *dag*\ ``)`` 1548 This operator produces the operator of the given *dag* node. 1549 Example: ``!getop((foo 1, 2))`` results in ``foo``. 1550 1551 The result of ``!getop`` can be used directly in a context where 1552 any record value at all is acceptable (typically placing it into 1553 another dag value). But in other contexts, it must be explicitly 1554 cast to a particular class type. The ``<``\ *type*\ ``>`` syntax is 1555 provided to make this easy. 1556 1557 For example, to assign the result to a value of type ``BaseClass``, you 1558 could write either of these:: 1559 1560 BaseClass b = !getop<BaseClass>(someDag); 1561 BaseClass b = !cast<BaseClass>(!getop(someDag)); 1562 1563 But to create a new DAG node that reuses the operator from another, no 1564 cast is necessary:: 1565 1566 dag d = !dag(!getop(someDag), args, names); 1567 1568``!gt(``\ *a*\ `,` *b*\ ``)`` 1569 This operator produces 1 if *a* is greater than *b*; 0 otherwise. 1570 The arguments must be ``bit``, ``int``, or ``string`` values. 1571 Use ``!cast<string>`` to compare other types of objects. 1572 1573``!head(``\ *a*\ ``)`` 1574 This operator produces the zeroth element of the list *a*. 1575 (See also ``!tail``.) 1576 1577``!if(``\ *test*\ ``,`` *then*\ ``,`` *else*\ ``)`` 1578 This operator evaluates the *test*, which must produce a ``bit`` or 1579 ``int``. If the result is not 0, the *then* expression is produced; otherwise 1580 the *else* expression is produced. 1581 1582``!isa<``\ *type*\ ``>(``\ *a*\ ``)`` 1583 This operator produces 1 if the type of *a* is a subtype of the given *type*; 0 1584 otherwise. 1585 1586``!le(``\ *a*\ ``,`` *b*\ ``)`` 1587 This operator produces 1 if *a* is less than or equal to *b*; 0 otherwise. 1588 The arguments must be ``bit``, ``int``, or ``string`` values. 1589 Use ``!cast<string>`` to compare other types of objects. 1590 1591``!listconcat(``\ *list1*\ ``,`` *list2*\ ``, ...)`` 1592 This operator concatenates the list arguments *list1*, *list2*, etc., and 1593 produces the resulting list. The lists must have the same element type. 1594 1595``!listsplat(``\ *value*\ ``,`` *count*\ ``)`` 1596 This operator produces a list of length *count* whose elements are all 1597 equal to the *value*. For example, ``!listsplat(42, 3)`` results in 1598 ``[42, 42, 42]``. 1599 1600``!lt(``\ *a*\ `,` *b*\ ``)`` 1601 This operator produces 1 if *a* is less than *b*; 0 otherwise. 1602 The arguments must be ``bit``, ``int``, or ``string`` values. 1603 Use ``!cast<string>`` to compare other types of objects. 1604 1605``!mul(``\ *a*\ ``,`` *b*\ ``, ...)`` 1606 This operator multiplies *a*, *b*, etc., and produces the product. 1607 1608``!ne(``\ *a*\ `,` *b*\ ``)`` 1609 This operator produces 1 if *a* is not equal to *b*; 0 otherwise. 1610 The arguments must be ``bit``, ``int``, or ``string`` values. 1611 Use ``!cast<string>`` to compare other types of objects. 1612 1613``!not(``\ *a*\ ``)`` 1614 This operator performs a logical NOT on *a*, which must be 1615 an integer. The argument 0 results in 1 (true); any other 1616 argument results in 0 (false). 1617 1618``!or(``\ *a*\ ``,`` *b*\ ``, ...)`` 1619 This operator does a bitwise OR on *a*, *b*, etc., and produces the 1620 result. A logical OR can be performed if all the arguments are either 1621 0 or 1. 1622 1623``!setop(``\ *dag*\ ``,`` *op*\ ``)`` 1624 This operator produces a DAG node with the same arguments as *dag*, but with its 1625 operator replaced with *op*. 1626 1627 Example: ``!setop((foo 1, 2), bar)`` results in ``(bar 1, 2)``. 1628 1629``!shl(``\ *a*\ ``,`` *count*\ ``)`` 1630 This operator shifts *a* left logically by *count* bits and produces the resulting 1631 value. The operation is performed on a 64-bit integer; the result 1632 is undefined for shift counts outside 0...63. 1633 1634``!size(``\ *a*\ ``)`` 1635 This operator produces the size of the string, list, or dag *a*. 1636 The size of a DAG is the number of arguments; the operator does not count. 1637 1638``!sra(``\ *a*\ ``,`` *count*\ ``)`` 1639 This operator shifts *a* right arithmetically by *count* bits and produces the resulting 1640 value. The operation is performed on a 64-bit integer; the result 1641 is undefined for shift counts outside 0...63. 1642 1643``!srl(``\ *a*\ ``,`` *count*\ ``)`` 1644 This operator shifts *a* right logically by *count* bits and produces the resulting 1645 value. The operation is performed on a 64-bit integer; the result 1646 is undefined for shift counts outside 0...63. 1647 1648``!strconcat(``\ *str1*\ ``,`` *str2*\ ``, ...)`` 1649 This operator concatenates the string arguments *str1*, *str2*, etc., and 1650 produces the resulting string. 1651 1652*str1*\ ``#``\ *str2* 1653 The paste operator (``#``) is a shorthand for 1654 ``!strconcat`` with two arguments. It can be used to concatenate operands that 1655 are not strings, in which 1656 case an implicit ``!cast<string>`` is done on those operands. 1657 1658``!subst(``\ *target*\ ``,`` *repl*\ ``,`` *value*\ ``)`` 1659 This operator replaces all occurrences of the *target* in the *value* with 1660 the *repl* and produces the resulting value. For strings, this is straightforward. 1661 1662 If the arguments are record names, the function produces the *repl* 1663 record if the *target* record name equals the *value* record name; otherwise it 1664 produces the *value*. 1665 1666``!tail(``\ *a*\ ``)`` 1667 This operator produces a new list with all the elements 1668 of the list *a* except for the zeroth one. (See also ``!head``.) 1669 1670``!xor(``\ *a*\ ``,`` *b*\ ``, ...)`` 1671 This operator does a bitwise EXCLUSIVE OR on *a*, *b*, etc., and produces 1672 the result. A logical XOR can be performed if all the arguments are either 1673 0 or 1. 1674 1675 1676Appendix B: Sample Record 1677========================= 1678 1679One target machine supported by LLVM is the Intel x86. The following output 1680from TableGen shows the record that is created to represent the 32-bit 1681register-to-register ADD instruction. 1682 1683.. code-block:: text 1684 1685 def ADD32rr { // InstructionEncoding Instruction X86Inst I ITy Sched BinOpRR BinOpRR_RF 1686 int Size = 0; 1687 string DecoderNamespace = ""; 1688 list<Predicate> Predicates = []; 1689 string DecoderMethod = ""; 1690 bit hasCompleteDecoder = 1; 1691 string Namespace = "X86"; 1692 dag OutOperandList = (outs GR32:$dst); 1693 dag InOperandList = (ins GR32:$src1, GR32:$src2); 1694 string AsmString = "add{l} {$src2, $src1|$src1, $src2}"; 1695 EncodingByHwMode EncodingInfos = ?; 1696 list<dag> Pattern = [(set GR32:$dst, EFLAGS, (X86add_flag GR32:$src1, GR32:$src2))]; 1697 list<Register> Uses = []; 1698 list<Register> Defs = [EFLAGS]; 1699 int CodeSize = 3; 1700 int AddedComplexity = 0; 1701 bit isPreISelOpcode = 0; 1702 bit isReturn = 0; 1703 bit isBranch = 0; 1704 bit isEHScopeReturn = 0; 1705 bit isIndirectBranch = 0; 1706 bit isCompare = 0; 1707 bit isMoveImm = 0; 1708 bit isMoveReg = 0; 1709 bit isBitcast = 0; 1710 bit isSelect = 0; 1711 bit isBarrier = 0; 1712 bit isCall = 0; 1713 bit isAdd = 0; 1714 bit isTrap = 0; 1715 bit canFoldAsLoad = 0; 1716 bit mayLoad = ?; 1717 bit mayStore = ?; 1718 bit mayRaiseFPException = 0; 1719 bit isConvertibleToThreeAddress = 1; 1720 bit isCommutable = 1; 1721 bit isTerminator = 0; 1722 bit isReMaterializable = 0; 1723 bit isPredicable = 0; 1724 bit isUnpredicable = 0; 1725 bit hasDelaySlot = 0; 1726 bit usesCustomInserter = 0; 1727 bit hasPostISelHook = 0; 1728 bit hasCtrlDep = 0; 1729 bit isNotDuplicable = 0; 1730 bit isConvergent = 0; 1731 bit isAuthenticated = 0; 1732 bit isAsCheapAsAMove = 0; 1733 bit hasExtraSrcRegAllocReq = 0; 1734 bit hasExtraDefRegAllocReq = 0; 1735 bit isRegSequence = 0; 1736 bit isPseudo = 0; 1737 bit isExtractSubreg = 0; 1738 bit isInsertSubreg = 0; 1739 bit variadicOpsAreDefs = 0; 1740 bit hasSideEffects = ?; 1741 bit isCodeGenOnly = 0; 1742 bit isAsmParserOnly = 0; 1743 bit hasNoSchedulingInfo = 0; 1744 InstrItinClass Itinerary = NoItinerary; 1745 list<SchedReadWrite> SchedRW = [WriteALU]; 1746 string Constraints = "$src1 = $dst"; 1747 string DisableEncoding = ""; 1748 string PostEncoderMethod = ""; 1749 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 }; 1750 string AsmMatchConverter = ""; 1751 string TwoOperandAliasConstraint = ""; 1752 string AsmVariantName = ""; 1753 bit UseNamedOperandTable = 0; 1754 bit FastISelShouldIgnore = 0; 1755 bits<8> Opcode = { 0, 0, 0, 0, 0, 0, 0, 1 }; 1756 Format Form = MRMDestReg; 1757 bits<7> FormBits = { 0, 1, 0, 1, 0, 0, 0 }; 1758 ImmType ImmT = NoImm; 1759 bit ForceDisassemble = 0; 1760 OperandSize OpSize = OpSize32; 1761 bits<2> OpSizeBits = { 1, 0 }; 1762 AddressSize AdSize = AdSizeX; 1763 bits<2> AdSizeBits = { 0, 0 }; 1764 Prefix OpPrefix = NoPrfx; 1765 bits<3> OpPrefixBits = { 0, 0, 0 }; 1766 Map OpMap = OB; 1767 bits<3> OpMapBits = { 0, 0, 0 }; 1768 bit hasREX_WPrefix = 0; 1769 FPFormat FPForm = NotFP; 1770 bit hasLockPrefix = 0; 1771 Domain ExeDomain = GenericDomain; 1772 bit hasREPPrefix = 0; 1773 Encoding OpEnc = EncNormal; 1774 bits<2> OpEncBits = { 0, 0 }; 1775 bit HasVEX_W = 0; 1776 bit IgnoresVEX_W = 0; 1777 bit EVEX_W1_VEX_W0 = 0; 1778 bit hasVEX_4V = 0; 1779 bit hasVEX_L = 0; 1780 bit ignoresVEX_L = 0; 1781 bit hasEVEX_K = 0; 1782 bit hasEVEX_Z = 0; 1783 bit hasEVEX_L2 = 0; 1784 bit hasEVEX_B = 0; 1785 bits<3> CD8_Form = { 0, 0, 0 }; 1786 int CD8_EltSize = 0; 1787 bit hasEVEX_RC = 0; 1788 bit hasNoTrackPrefix = 0; 1789 bits<7> VectSize = { 0, 0, 1, 0, 0, 0, 0 }; 1790 bits<7> CD8_Scale = { 0, 0, 0, 0, 0, 0, 0 }; 1791 string FoldGenRegForm = ?; 1792 string EVEX2VEXOverride = ?; 1793 bit isMemoryFoldable = 1; 1794 bit notEVEX2VEXConvertible = 0; 1795 } 1796 1797On the first line of the record, you can see that the ``ADD32rr`` record 1798inherited from eight classes. Although the inheritance hierarchy is complex, 1799using superclasses is much simpler than specifying the 109 individual fields for each 1800instruction. 1801 1802Here is the code fragment used to define ``ADD32rr`` and multiple other 1803``ADD`` instructions: 1804 1805.. code-block:: text 1806 1807 defm ADD : ArithBinOp_RF<0x00, 0x02, 0x04, "add", MRM0r, MRM0m, 1808 X86add_flag, add, 1, 1, 1>; 1809 1810The ``defm`` statement tells TableGen that ``ArithBinOp_RF`` is a 1811multiclass, which contains multiple concrete record definitions that inherit 1812from ``BinOpRR_RF``. That class, in turn, inherits from ``BinOpRR``, which 1813inherits from ``ITy`` and ``Sched``, and so forth. The fields are inherited 1814from all the parent classes; for example, ``IsIndirectBranch`` is inherited 1815from the ``Instruction`` class. 1816