Rewrite the tblgen parser in a recursive descent style, eliminating the bison parser.

This makes the parser much easier to understand, eliminates a ton of global variables,
and gives tblgen nice caret diagnostics.  It is also faster, but tblgen probably doesn't
care about performance.

There are a couple of FIXMEs which I will take care of next.


git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@44274 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Chris Lattner 2007-11-22 20:49:04 +00:00
parent ed4a2f1688
commit f460165a4c
10 changed files with 1663 additions and 3930 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,40 +0,0 @@
typedef union {
std::string* StrVal;
int IntVal;
llvm::RecTy* Ty;
llvm::Init* Initializer;
std::vector<llvm::Init*>* FieldList;
std::vector<unsigned>* BitList;
llvm::Record* Rec;
std::vector<llvm::Record*>* RecList;
SubClassRefTy* SubClassRef;
std::vector<SubClassRefTy>* SubClassList;
std::vector<std::pair<llvm::Init*, std::string> >* DagValueList;
} YYSTYPE;
#define INT 257
#define BIT 258
#define STRING 259
#define BITS 260
#define LIST 261
#define CODE 262
#define DAG 263
#define CLASS 264
#define DEF 265
#define MULTICLASS 266
#define DEFM 267
#define FIELD 268
#define LET 269
#define IN 270
#define CONCATTOK 271
#define SHLTOK 272
#define SRATOK 273
#define SRLTOK 274
#define STRCONCATTOK 275
#define INTVAL 276
#define ID 277
#define VARNAME 278
#define STRVAL 279
#define CODEFRAGMENT 280
extern YYSTYPE Filelval;

View File

@ -1,806 +0,0 @@
//===-- FileParser.y - Parser for TableGen files ----------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the bison parser for Table Generator files...
//
//===----------------------------------------------------------------------===//
%{
#include "Record.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Streams.h"
#include <algorithm>
#include <cstdio>
#define YYERROR_VERBOSE 1
int yyerror(const char *ErrorMsg);
int yylex();
namespace llvm {
struct MultiClass {
Record Rec; // Placeholder for template args and Name.
std::vector<Record*> DefPrototypes;
MultiClass(const std::string &Name) : Rec(Name) {}
};
static std::map<std::string, MultiClass*> MultiClasses;
extern int Filelineno;
static MultiClass *CurMultiClass = 0; // Set while parsing a multiclass.
static std::string *CurDefmPrefix = 0; // Set while parsing defm.
static Record *CurRec = 0;
static bool ParsingTemplateArgs = false;
typedef std::pair<Record*, std::vector<Init*>*> SubClassRefTy;
struct LetRecord {
std::string Name;
std::vector<unsigned> Bits;
Init *Value;
bool HasBits;
LetRecord(const std::string &N, std::vector<unsigned> *B, Init *V)
: Name(N), Value(V), HasBits(B != 0) {
if (HasBits) Bits = *B;
}
};
static std::vector<std::vector<LetRecord> > LetStack;
extern std::ostream &err();
/// getActiveRec - If inside a def/class definition, return the def/class.
/// Otherwise, if within a multidef, return it.
static Record *getActiveRec() {
return CurRec ? CurRec : &CurMultiClass->Rec;
}
static void addValue(const RecordVal &RV) {
Record *TheRec = getActiveRec();
if (RecordVal *ERV = TheRec->getValue(RV.getName())) {
// The value already exists in the class, treat this as a set...
if (ERV->setValue(RV.getValue())) {
err() << "New definition of '" << RV.getName() << "' of type '"
<< *RV.getType() << "' is incompatible with previous "
<< "definition of type '" << *ERV->getType() << "'!\n";
exit(1);
}
} else {
TheRec->addValue(RV);
}
}
static void addSuperClass(Record *SC) {
if (CurRec->isSubClassOf(SC)) {
err() << "Already subclass of '" << SC->getName() << "'!\n";
exit(1);
}
CurRec->addSuperClass(SC);
}
static void setValue(const std::string &ValName,
std::vector<unsigned> *BitList, Init *V) {
if (!V) return;
Record *TheRec = getActiveRec();
RecordVal *RV = TheRec->getValue(ValName);
if (RV == 0) {
err() << "Value '" << ValName << "' unknown!\n";
exit(1);
}
// Do not allow assignments like 'X = X'. This will just cause infinite loops
// in the resolution machinery.
if (!BitList)
if (VarInit *VI = dynamic_cast<VarInit*>(V))
if (VI->getName() == ValName)
return;
// If we are assigning to a subset of the bits in the value... then we must be
// assigning to a field of BitsRecTy, which must have a BitsInit
// initializer...
//
if (BitList) {
BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
if (CurVal == 0) {
err() << "Value '" << ValName << "' is not a bits type!\n";
exit(1);
}
// Convert the incoming value to a bits type of the appropriate size...
Init *BI = V->convertInitializerTo(new BitsRecTy(BitList->size()));
if (BI == 0) {
V->convertInitializerTo(new BitsRecTy(BitList->size()));
err() << "Initializer '" << *V << "' not compatible with bit range!\n";
exit(1);
}
// We should have a BitsInit type now...
assert(dynamic_cast<BitsInit*>(BI) != 0 || (cerr << *BI).stream() == 0);
BitsInit *BInit = (BitsInit*)BI;
BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
// Loop over bits, assigning values as appropriate...
for (unsigned i = 0, e = BitList->size(); i != e; ++i) {
unsigned Bit = (*BitList)[i];
if (NewVal->getBit(Bit)) {
err() << "Cannot set bit #" << Bit << " of value '" << ValName
<< "' more than once!\n";
exit(1);
}
NewVal->setBit(Bit, BInit->getBit(i));
}
for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
if (NewVal->getBit(i) == 0)
NewVal->setBit(i, CurVal->getBit(i));
V = NewVal;
}
if (RV->setValue(V)) {
err() << "Value '" << ValName << "' of type '" << *RV->getType()
<< "' is incompatible with initializer '" << *V << "'!\n";
exit(1);
}
}
// addSubClass - Add SC as a subclass to CurRec, resolving TemplateArgs as SC's
// template arguments.
static void addSubClass(Record *SC, const std::vector<Init*> &TemplateArgs) {
// Add all of the values in the subclass into the current class...
const std::vector<RecordVal> &Vals = SC->getValues();
for (unsigned i = 0, e = Vals.size(); i != e; ++i)
addValue(Vals[i]);
const std::vector<std::string> &TArgs = SC->getTemplateArgs();
// Ensure that an appropriate number of template arguments are specified...
if (TArgs.size() < TemplateArgs.size()) {
err() << "ERROR: More template args specified than expected!\n";
exit(1);
}
// Loop over all of the template arguments, setting them to the specified
// value or leaving them as the default if necessary.
for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
if (i < TemplateArgs.size()) { // A value is specified for this temp-arg?
// Set it now.
setValue(TArgs[i], 0, TemplateArgs[i]);
// Resolve it next.
CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
// Now remove it.
CurRec->removeValue(TArgs[i]);
} else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
err() << "ERROR: Value not specified for template argument #"
<< i << " (" << TArgs[i] << ") of subclass '" << SC->getName()
<< "'!\n";
exit(1);
}
}
// Since everything went well, we can now set the "superclass" list for the
// current record.
const std::vector<Record*> &SCs = SC->getSuperClasses();
for (unsigned i = 0, e = SCs.size(); i != e; ++i)
addSuperClass(SCs[i]);
addSuperClass(SC);
}
} // End llvm namespace
using namespace llvm;
%}
%union {
std::string* StrVal;
int IntVal;
llvm::RecTy* Ty;
llvm::Init* Initializer;
std::vector<llvm::Init*>* FieldList;
std::vector<unsigned>* BitList;
llvm::Record* Rec;
std::vector<llvm::Record*>* RecList;
SubClassRefTy* SubClassRef;
std::vector<SubClassRefTy>* SubClassList;
std::vector<std::pair<llvm::Init*, std::string> >* DagValueList;
};
%token INT BIT STRING BITS LIST CODE DAG CLASS DEF MULTICLASS DEFM FIELD LET IN
%token CONCATTOK SHLTOK SRATOK SRLTOK STRCONCATTOK
%token <IntVal> INTVAL
%token <StrVal> ID VARNAME STRVAL CODEFRAGMENT
%type <Ty> Type
%type <Rec> ClassInst DefInst MultiClassDef ObjectBody ClassID
%type <RecList> MultiClassBody
%type <SubClassRef> SubClassRef
%type <SubClassList> ClassList ClassListNE
%type <IntVal> OptPrefix
%type <Initializer> Value OptValue IDValue
%type <DagValueList> DagArgList DagArgListNE
%type <FieldList> ValueList ValueListNE
%type <BitList> BitList OptBitList RBitList
%type <StrVal> Declaration OptID OptVarName ObjectName
%start File
%%
ClassID : ID {
if (CurDefmPrefix) {
// If CurDefmPrefix is set, we're parsing a defm, which means that this is
// actually the name of a multiclass.
MultiClass *MC = MultiClasses[*$1];
if (MC == 0) {
err() << "Couldn't find class '" << *$1 << "'!\n";
exit(1);
}
$$ = &MC->Rec;
} else {
$$ = Records.getClass(*$1);
}
if ($$ == 0) {
err() << "Couldn't find class '" << *$1 << "'!\n";
exit(1);
}
delete $1;
};
// TableGen types...
Type : STRING { // string type
$$ = new StringRecTy();
} | BIT { // bit type
$$ = new BitRecTy();
} | BITS '<' INTVAL '>' { // bits<x> type
$$ = new BitsRecTy($3);
} | INT { // int type
$$ = new IntRecTy();
} | LIST '<' Type '>' { // list<x> type
$$ = new ListRecTy($3);
} | CODE { // code type
$$ = new CodeRecTy();
} | DAG { // dag type
$$ = new DagRecTy();
} | ClassID { // Record Type
$$ = new RecordRecTy($1);
};
OptPrefix : /*empty*/ { $$ = 0; } | FIELD { $$ = 1; };
OptValue : /*empty*/ { $$ = 0; } | '=' Value { $$ = $2; };
IDValue : ID {
if (const RecordVal *RV = (CurRec ? CurRec->getValue(*$1) : 0)) {
$$ = new VarInit(*$1, RV->getType());
} else if (CurRec && CurRec->isTemplateArg(CurRec->getName()+":"+*$1)) {
const RecordVal *RV = CurRec->getValue(CurRec->getName()+":"+*$1);
assert(RV && "Template arg doesn't exist??");
$$ = new VarInit(CurRec->getName()+":"+*$1, RV->getType());
} else if (CurMultiClass &&
CurMultiClass->Rec.isTemplateArg(CurMultiClass->Rec.getName()+"::"+*$1)) {
std::string Name = CurMultiClass->Rec.getName()+"::"+*$1;
const RecordVal *RV = CurMultiClass->Rec.getValue(Name);
assert(RV && "Template arg doesn't exist??");
$$ = new VarInit(Name, RV->getType());
} else if (Record *D = Records.getDef(*$1)) {
$$ = new DefInit(D);
} else {
err() << "Variable not defined: '" << *$1 << "'!\n";
exit(1);
}
delete $1;
};
Value : IDValue {
$$ = $1;
} | INTVAL {
$$ = new IntInit($1);
} | STRVAL {
$$ = new StringInit(*$1);
delete $1;
} | CODEFRAGMENT {
$$ = new CodeInit(*$1);
delete $1;
} | '?' {
$$ = new UnsetInit();
} | '{' ValueList '}' {
BitsInit *Init = new BitsInit($2->size());
for (unsigned i = 0, e = $2->size(); i != e; ++i) {
struct Init *Bit = (*$2)[i]->convertInitializerTo(new BitRecTy());
if (Bit == 0) {
err() << "Element #" << i << " (" << *(*$2)[i]
<< ") is not convertable to a bit!\n";
exit(1);
}
Init->setBit($2->size()-i-1, Bit);
}
$$ = Init;
delete $2;
} | ID '<' ValueListNE '>' {
// This is a CLASS<initvalslist> expression. This is supposed to synthesize
// a new anonymous definition, deriving from CLASS<initvalslist> with no
// body.
Record *Class = Records.getClass(*$1);
if (!Class) {
err() << "Expected a class, got '" << *$1 << "'!\n";
exit(1);
}
delete $1;
static unsigned AnonCounter = 0;
Record *OldRec = CurRec; // Save CurRec.
// Create the new record, set it as CurRec temporarily.
CurRec = new Record("anonymous.val."+utostr(AnonCounter++));
addSubClass(Class, *$3); // Add info about the subclass to CurRec.
delete $3; // Free up the template args.
CurRec->resolveReferences();
Records.addDef(CurRec);
// The result of the expression is a reference to the new record.
$$ = new DefInit(CurRec);
// Restore the old CurRec
CurRec = OldRec;
} | Value '{' BitList '}' {
$$ = $1->convertInitializerBitRange(*$3);
if ($$ == 0) {
err() << "Invalid bit range for value '" << *$1 << "'!\n";
exit(1);
}
delete $3;
} | '[' ValueList ']' {
$$ = new ListInit(*$2);
delete $2;
} | Value '.' ID {
if (!$1->getFieldType(*$3)) {
err() << "Cannot access field '" << *$3 << "' of value '" << *$1 << "!\n";
exit(1);
}
$$ = new FieldInit($1, *$3);
delete $3;
} | '(' IDValue DagArgList ')' {
$$ = new DagInit($2, *$3);
delete $3;
} | Value '[' BitList ']' {
std::reverse($3->begin(), $3->end());
$$ = $1->convertInitListSlice(*$3);
if ($$ == 0) {
err() << "Invalid list slice for value '" << *$1 << "'!\n";
exit(1);
}
delete $3;
} | CONCATTOK '(' Value ',' Value ')' {
$$ = (new BinOpInit(BinOpInit::CONCAT, $3, $5))->Fold();
} | SHLTOK '(' Value ',' Value ')' {
$$ = (new BinOpInit(BinOpInit::SHL, $3, $5))->Fold();
} | SRATOK '(' Value ',' Value ')' {
$$ = (new BinOpInit(BinOpInit::SRA, $3, $5))->Fold();
} | SRLTOK '(' Value ',' Value ')' {
$$ = (new BinOpInit(BinOpInit::SRL, $3, $5))->Fold();
} | STRCONCATTOK '(' Value ',' Value ')' {
$$ = (new BinOpInit(BinOpInit::STRCONCAT, $3, $5))->Fold();
};
OptVarName : /* empty */ {
$$ = new std::string();
}
| ':' VARNAME {
$$ = $2;
};
DagArgListNE : Value OptVarName {
$$ = new std::vector<std::pair<Init*, std::string> >();
$$->push_back(std::make_pair($1, *$2));
delete $2;
}
| DagArgListNE ',' Value OptVarName {
$1->push_back(std::make_pair($3, *$4));
delete $4;
$$ = $1;
};
DagArgList : /*empty*/ {
$$ = new std::vector<std::pair<Init*, std::string> >();
}
| DagArgListNE { $$ = $1; };
RBitList : INTVAL {
$$ = new std::vector<unsigned>();
$$->push_back($1);
} | INTVAL '-' INTVAL {
if ($1 < 0 || $3 < 0) {
err() << "Invalid range: " << $1 << "-" << $3 << "!\n";
exit(1);
}
$$ = new std::vector<unsigned>();
if ($1 < $3) {
for (int i = $1; i <= $3; ++i)
$$->push_back(i);
} else {
for (int i = $1; i >= $3; --i)
$$->push_back(i);
}
} | INTVAL INTVAL {
$2 = -$2;
if ($1 < 0 || $2 < 0) {
err() << "Invalid range: " << $1 << "-" << $2 << "!\n";
exit(1);
}
$$ = new std::vector<unsigned>();
if ($1 < $2) {
for (int i = $1; i <= $2; ++i)
$$->push_back(i);
} else {
for (int i = $1; i >= $2; --i)
$$->push_back(i);
}
} | RBitList ',' INTVAL {
($$=$1)->push_back($3);
} | RBitList ',' INTVAL '-' INTVAL {
if ($3 < 0 || $5 < 0) {
err() << "Invalid range: " << $3 << "-" << $5 << "!\n";
exit(1);
}
$$ = $1;
if ($3 < $5) {
for (int i = $3; i <= $5; ++i)
$$->push_back(i);
} else {
for (int i = $3; i >= $5; --i)
$$->push_back(i);
}
} | RBitList ',' INTVAL INTVAL {
$4 = -$4;
if ($3 < 0 || $4 < 0) {
err() << "Invalid range: " << $3 << "-" << $4 << "!\n";
exit(1);
}
$$ = $1;
if ($3 < $4) {
for (int i = $3; i <= $4; ++i)
$$->push_back(i);
} else {
for (int i = $3; i >= $4; --i)
$$->push_back(i);
}
};
BitList : RBitList { $$ = $1; std::reverse($1->begin(), $1->end()); };
OptBitList : /*empty*/ { $$ = 0; } | '{' BitList '}' { $$ = $2; };
ValueList : /*empty*/ {
$$ = new std::vector<Init*>();
} | ValueListNE {
$$ = $1;
};
ValueListNE : Value {
$$ = new std::vector<Init*>();
$$->push_back($1);
} | ValueListNE ',' Value {
($$ = $1)->push_back($3);
};
Declaration : OptPrefix Type ID OptValue {
std::string DecName = *$3;
if (ParsingTemplateArgs) {
if (CurRec) {
DecName = CurRec->getName() + ":" + DecName;
} else {
assert(CurMultiClass);
}
if (CurMultiClass)
DecName = CurMultiClass->Rec.getName() + "::" + DecName;
}
addValue(RecordVal(DecName, $2, $1));
setValue(DecName, 0, $4);
$$ = new std::string(DecName);
};
BodyItem : Declaration ';' {
delete $1;
} | LET ID OptBitList '=' Value ';' {
setValue(*$2, $3, $5);
delete $2;
delete $3;
};
BodyList : /*empty*/ | BodyList BodyItem;
Body : ';' | '{' BodyList '}';
SubClassRef : ClassID {
$$ = new SubClassRefTy($1, new std::vector<Init*>());
} | ClassID '<' ValueListNE '>' {
$$ = new SubClassRefTy($1, $3);
};
ClassListNE : SubClassRef {
$$ = new std::vector<SubClassRefTy>();
$$->push_back(*$1);
delete $1;
}
| ClassListNE ',' SubClassRef {
($$=$1)->push_back(*$3);
delete $3;
};
ClassList : /*empty */ {
$$ = new std::vector<SubClassRefTy>();
}
| ':' ClassListNE {
$$ = $2;
};
DeclListNE : Declaration {
getActiveRec()->addTemplateArg(*$1);
delete $1;
} | DeclListNE ',' Declaration {
getActiveRec()->addTemplateArg(*$3);
delete $3;
};
TemplateArgList : '<' DeclListNE '>' {};
OptTemplateArgList : /*empty*/ | TemplateArgList;
OptID : ID { $$ = $1; } | /*empty*/ { $$ = new std::string(); };
ObjectName : OptID {
static unsigned AnonCounter = 0;
if ($1->empty())
*$1 = "anonymous."+utostr(AnonCounter++);
$$ = $1;
};
ClassName : ObjectName {
// If a class of this name already exists, it must be a forward ref.
if ((CurRec = Records.getClass(*$1))) {
// If the body was previously defined, this is an error.
if (!CurRec->getValues().empty() ||
!CurRec->getSuperClasses().empty() ||
!CurRec->getTemplateArgs().empty()) {
err() << "Class '" << CurRec->getName() << "' already defined!\n";
exit(1);
}
} else {
// If this is the first reference to this class, create and add it.
CurRec = new Record(*$1);
Records.addClass(CurRec);
}
delete $1;
};
DefName : ObjectName {
CurRec = new Record(*$1);
delete $1;
if (!CurMultiClass) {
// Top-level def definition.
// Ensure redefinition doesn't happen.
if (Records.getDef(CurRec->getName())) {
err() << "def '" << CurRec->getName() << "' already defined!\n";
exit(1);
}
Records.addDef(CurRec);
} else {
// Otherwise, a def inside a multiclass, add it to the multiclass.
for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
err() << "def '" << CurRec->getName()
<< "' already defined in this multiclass!\n";
exit(1);
}
CurMultiClass->DefPrototypes.push_back(CurRec);
}
};
ObjectBody : ClassList {
for (unsigned i = 0, e = $1->size(); i != e; ++i) {
addSubClass((*$1)[i].first, *(*$1)[i].second);
// Delete the template arg values for the class
delete (*$1)[i].second;
}
delete $1; // Delete the class list.
// Process any variables on the let stack.
for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
setValue(LetStack[i][j].Name,
LetStack[i][j].HasBits ? &LetStack[i][j].Bits : 0,
LetStack[i][j].Value);
} Body {
$$ = CurRec;
CurRec = 0;
};
ClassInst : CLASS ClassName {
ParsingTemplateArgs = true;
} OptTemplateArgList {
ParsingTemplateArgs = false;
} ObjectBody {
$$ = $6;
};
DefInst : DEF DefName ObjectBody {
if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
$3->resolveReferences();
// If ObjectBody has template arguments, it's an error.
assert($3->getTemplateArgs().empty() && "How'd this get template args?");
$$ = $3;
};
// MultiClassDef - A def instance specified inside a multiclass.
MultiClassDef : DefInst {
$$ = $1;
// Copy the template arguments for the multiclass into the def.
const std::vector<std::string> &TArgs = CurMultiClass->Rec.getTemplateArgs();
for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
assert(RV && "Template arg doesn't exist?");
$$->addValue(*RV);
}
};
// MultiClassBody - Sequence of def's that are instantiated when a multiclass is
// used.
MultiClassBody : MultiClassDef {
$$ = new std::vector<Record*>();
$$->push_back($1);
} | MultiClassBody MultiClassDef {
$$->push_back($2);
};
MultiClassName : ID {
MultiClass *&MCE = MultiClasses[*$1];
if (MCE) {
err() << "multiclass '" << *$1 << "' already defined!\n";
exit(1);
}
MCE = CurMultiClass = new MultiClass(*$1);
delete $1;
};
// MultiClass - Multiple definitions.
MultiClassInst : MULTICLASS MultiClassName {
ParsingTemplateArgs = true;
} OptTemplateArgList {
ParsingTemplateArgs = false;
}'{' MultiClassBody '}' {
CurMultiClass = 0;
};
// DefMInst - Instantiate a multiclass.
DefMInst : DEFM ID { CurDefmPrefix = $2; } ':' SubClassRef ';' {
// To instantiate a multiclass, we need to first get the multiclass, then
// instantiate each def contained in the multiclass with the SubClassRef
// template parameters.
MultiClass *MC = MultiClasses[$5->first->getName()];
assert(MC && "Didn't lookup multiclass correctly?");
std::vector<Init*> &TemplateVals = *$5->second;
delete $5;
// Verify that the correct number of template arguments were specified.
const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
if (TArgs.size() < TemplateVals.size()) {
err() << "ERROR: More template args specified than multiclass expects!\n";
exit(1);
}
// Loop over all the def's in the multiclass, instantiating each one.
for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
Record *DefProto = MC->DefPrototypes[i];
// Add the suffix to the defm name to get the new name.
assert(CurRec == 0 && "A def is current?");
CurRec = new Record(*$2 + DefProto->getName());
addSubClass(DefProto, std::vector<Init*>());
// Loop over all of the template arguments, setting them to the specified
// value or leaving them as the default if necessary.
for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
if (i < TemplateVals.size()) { // A value is specified for this temp-arg?
// Set it now.
setValue(TArgs[i], 0, TemplateVals[i]);
// Resolve it next.
CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
// Now remove it.
CurRec->removeValue(TArgs[i]);
} else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
err() << "ERROR: Value not specified for template argument #"
<< i << " (" << TArgs[i] << ") of multiclassclass '"
<< MC->Rec.getName() << "'!\n";
exit(1);
}
}
// If the mdef is inside a 'let' expression, add to each def.
for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
setValue(LetStack[i][j].Name,
LetStack[i][j].HasBits ? &LetStack[i][j].Bits : 0,
LetStack[i][j].Value);
// Ensure redefinition doesn't happen.
if (Records.getDef(CurRec->getName())) {
err() << "def '" << CurRec->getName() << "' already defined, "
<< "instantiating defm '" << *$2 << "' with subdef '"
<< DefProto->getName() << "'!\n";
exit(1);
}
Records.addDef(CurRec);
CurRec->resolveReferences();
CurRec = 0;
}
delete &TemplateVals;
delete $2;
CurDefmPrefix = 0;
};
Object : ClassInst {} | DefInst {};
Object : MultiClassInst | DefMInst;
LETItem : ID OptBitList '=' Value {
LetStack.back().push_back(LetRecord(*$1, $2, $4));
delete $1; delete $2;
};
LETList : LETItem | LETList ',' LETItem;
// LETCommand - A 'LET' statement start...
LETCommand : LET { LetStack.push_back(std::vector<LetRecord>()); } LETList IN;
// Support Set commands wrapping objects... both with and without braces.
Object : LETCommand '{' ObjectList '}' {
LetStack.pop_back();
}
| LETCommand Object {
LetStack.pop_back();
};
ObjectList : Object {} | ObjectList Object {};
File : ObjectList;
%%
int yyerror(const char *ErrorMsg) {
err() << "Error parsing: " << ErrorMsg << "\n";
exit(1);
}

View File

@ -1,806 +0,0 @@
//===-- FileParser.y - Parser for TableGen files ----------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the bison parser for Table Generator files...
//
//===----------------------------------------------------------------------===//
%{
#include "Record.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Streams.h"
#include <algorithm>
#include <cstdio>
#define YYERROR_VERBOSE 1
int yyerror(const char *ErrorMsg);
int yylex();
namespace llvm {
struct MultiClass {
Record Rec; // Placeholder for template args and Name.
std::vector<Record*> DefPrototypes;
MultiClass(const std::string &Name) : Rec(Name) {}
};
static std::map<std::string, MultiClass*> MultiClasses;
extern int Filelineno;
static MultiClass *CurMultiClass = 0; // Set while parsing a multiclass.
static std::string *CurDefmPrefix = 0; // Set while parsing defm.
static Record *CurRec = 0;
static bool ParsingTemplateArgs = false;
typedef std::pair<Record*, std::vector<Init*>*> SubClassRefTy;
struct LetRecord {
std::string Name;
std::vector<unsigned> Bits;
Init *Value;
bool HasBits;
LetRecord(const std::string &N, std::vector<unsigned> *B, Init *V)
: Name(N), Value(V), HasBits(B != 0) {
if (HasBits) Bits = *B;
}
};
static std::vector<std::vector<LetRecord> > LetStack;
extern std::ostream &err();
/// getActiveRec - If inside a def/class definition, return the def/class.
/// Otherwise, if within a multidef, return it.
static Record *getActiveRec() {
return CurRec ? CurRec : &CurMultiClass->Rec;
}
static void addValue(const RecordVal &RV) {
Record *TheRec = getActiveRec();
if (RecordVal *ERV = TheRec->getValue(RV.getName())) {
// The value already exists in the class, treat this as a set...
if (ERV->setValue(RV.getValue())) {
err() << "New definition of '" << RV.getName() << "' of type '"
<< *RV.getType() << "' is incompatible with previous "
<< "definition of type '" << *ERV->getType() << "'!\n";
exit(1);
}
} else {
TheRec->addValue(RV);
}
}
static void addSuperClass(Record *SC) {
if (CurRec->isSubClassOf(SC)) {
err() << "Already subclass of '" << SC->getName() << "'!\n";
exit(1);
}
CurRec->addSuperClass(SC);
}
static void setValue(const std::string &ValName,
std::vector<unsigned> *BitList, Init *V) {
if (!V) return;
Record *TheRec = getActiveRec();
RecordVal *RV = TheRec->getValue(ValName);
if (RV == 0) {
err() << "Value '" << ValName << "' unknown!\n";
exit(1);
}
// Do not allow assignments like 'X = X'. This will just cause infinite loops
// in the resolution machinery.
if (!BitList)
if (VarInit *VI = dynamic_cast<VarInit*>(V))
if (VI->getName() == ValName)
return;
// If we are assigning to a subset of the bits in the value... then we must be
// assigning to a field of BitsRecTy, which must have a BitsInit
// initializer...
//
if (BitList) {
BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
if (CurVal == 0) {
err() << "Value '" << ValName << "' is not a bits type!\n";
exit(1);
}
// Convert the incoming value to a bits type of the appropriate size...
Init *BI = V->convertInitializerTo(new BitsRecTy(BitList->size()));
if (BI == 0) {
V->convertInitializerTo(new BitsRecTy(BitList->size()));
err() << "Initializer '" << *V << "' not compatible with bit range!\n";
exit(1);
}
// We should have a BitsInit type now...
assert(dynamic_cast<BitsInit*>(BI) != 0 || (cerr << *BI).stream() == 0);
BitsInit *BInit = (BitsInit*)BI;
BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
// Loop over bits, assigning values as appropriate...
for (unsigned i = 0, e = BitList->size(); i != e; ++i) {
unsigned Bit = (*BitList)[i];
if (NewVal->getBit(Bit)) {
err() << "Cannot set bit #" << Bit << " of value '" << ValName
<< "' more than once!\n";
exit(1);
}
NewVal->setBit(Bit, BInit->getBit(i));
}
for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
if (NewVal->getBit(i) == 0)
NewVal->setBit(i, CurVal->getBit(i));
V = NewVal;
}
if (RV->setValue(V)) {
err() << "Value '" << ValName << "' of type '" << *RV->getType()
<< "' is incompatible with initializer '" << *V << "'!\n";
exit(1);
}
}
// addSubClass - Add SC as a subclass to CurRec, resolving TemplateArgs as SC's
// template arguments.
static void addSubClass(Record *SC, const std::vector<Init*> &TemplateArgs) {
// Add all of the values in the subclass into the current class...
const std::vector<RecordVal> &Vals = SC->getValues();
for (unsigned i = 0, e = Vals.size(); i != e; ++i)
addValue(Vals[i]);
const std::vector<std::string> &TArgs = SC->getTemplateArgs();
// Ensure that an appropriate number of template arguments are specified...
if (TArgs.size() < TemplateArgs.size()) {
err() << "ERROR: More template args specified than expected!\n";
exit(1);
}
// Loop over all of the template arguments, setting them to the specified
// value or leaving them as the default if necessary.
for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
if (i < TemplateArgs.size()) { // A value is specified for this temp-arg?
// Set it now.
setValue(TArgs[i], 0, TemplateArgs[i]);
// Resolve it next.
CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
// Now remove it.
CurRec->removeValue(TArgs[i]);
} else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
err() << "ERROR: Value not specified for template argument #"
<< i << " (" << TArgs[i] << ") of subclass '" << SC->getName()
<< "'!\n";
exit(1);
}
}
// Since everything went well, we can now set the "superclass" list for the
// current record.
const std::vector<Record*> &SCs = SC->getSuperClasses();
for (unsigned i = 0, e = SCs.size(); i != e; ++i)
addSuperClass(SCs[i]);
addSuperClass(SC);
}
} // End llvm namespace
using namespace llvm;
%}
%union {
std::string* StrVal;
int IntVal;
llvm::RecTy* Ty;
llvm::Init* Initializer;
std::vector<llvm::Init*>* FieldList;
std::vector<unsigned>* BitList;
llvm::Record* Rec;
std::vector<llvm::Record*>* RecList;
SubClassRefTy* SubClassRef;
std::vector<SubClassRefTy>* SubClassList;
std::vector<std::pair<llvm::Init*, std::string> >* DagValueList;
};
%token INT BIT STRING BITS LIST CODE DAG CLASS DEF MULTICLASS DEFM FIELD LET IN
%token CONCATTOK SHLTOK SRATOK SRLTOK STRCONCATTOK
%token <IntVal> INTVAL
%token <StrVal> ID VARNAME STRVAL CODEFRAGMENT
%type <Ty> Type
%type <Rec> ClassInst DefInst MultiClassDef ObjectBody ClassID
%type <RecList> MultiClassBody
%type <SubClassRef> SubClassRef
%type <SubClassList> ClassList ClassListNE
%type <IntVal> OptPrefix
%type <Initializer> Value OptValue IDValue
%type <DagValueList> DagArgList DagArgListNE
%type <FieldList> ValueList ValueListNE
%type <BitList> BitList OptBitList RBitList
%type <StrVal> Declaration OptID OptVarName ObjectName
%start File
%%
ClassID : ID {
if (CurDefmPrefix) {
// If CurDefmPrefix is set, we're parsing a defm, which means that this is
// actually the name of a multiclass.
MultiClass *MC = MultiClasses[*$1];
if (MC == 0) {
err() << "Couldn't find class '" << *$1 << "'!\n";
exit(1);
}
$$ = &MC->Rec;
} else {
$$ = Records.getClass(*$1);
}
if ($$ == 0) {
err() << "Couldn't find class '" << *$1 << "'!\n";
exit(1);
}
delete $1;
};
// TableGen types...
Type : STRING { // string type
$$ = new StringRecTy();
} | BIT { // bit type
$$ = new BitRecTy();
} | BITS '<' INTVAL '>' { // bits<x> type
$$ = new BitsRecTy($3);
} | INT { // int type
$$ = new IntRecTy();
} | LIST '<' Type '>' { // list<x> type
$$ = new ListRecTy($3);
} | CODE { // code type
$$ = new CodeRecTy();
} | DAG { // dag type
$$ = new DagRecTy();
} | ClassID { // Record Type
$$ = new RecordRecTy($1);
};
OptPrefix : /*empty*/ { $$ = 0; } | FIELD { $$ = 1; };
OptValue : /*empty*/ { $$ = 0; } | '=' Value { $$ = $2; };
IDValue : ID {
if (const RecordVal *RV = (CurRec ? CurRec->getValue(*$1) : 0)) {
$$ = new VarInit(*$1, RV->getType());
} else if (CurRec && CurRec->isTemplateArg(CurRec->getName()+":"+*$1)) {
const RecordVal *RV = CurRec->getValue(CurRec->getName()+":"+*$1);
assert(RV && "Template arg doesn't exist??");
$$ = new VarInit(CurRec->getName()+":"+*$1, RV->getType());
} else if (CurMultiClass &&
CurMultiClass->Rec.isTemplateArg(CurMultiClass->Rec.getName()+"::"+*$1)) {
std::string Name = CurMultiClass->Rec.getName()+"::"+*$1;
const RecordVal *RV = CurMultiClass->Rec.getValue(Name);
assert(RV && "Template arg doesn't exist??");
$$ = new VarInit(Name, RV->getType());
} else if (Record *D = Records.getDef(*$1)) {
$$ = new DefInit(D);
} else {
err() << "Variable not defined: '" << *$1 << "'!\n";
exit(1);
}
delete $1;
};
Value : IDValue {
$$ = $1;
} | INTVAL {
$$ = new IntInit($1);
} | STRVAL {
$$ = new StringInit(*$1);
delete $1;
} | CODEFRAGMENT {
$$ = new CodeInit(*$1);
delete $1;
} | '?' {
$$ = new UnsetInit();
} | '{' ValueList '}' {
BitsInit *Init = new BitsInit($2->size());
for (unsigned i = 0, e = $2->size(); i != e; ++i) {
struct Init *Bit = (*$2)[i]->convertInitializerTo(new BitRecTy());
if (Bit == 0) {
err() << "Element #" << i << " (" << *(*$2)[i]
<< ") is not convertable to a bit!\n";
exit(1);
}
Init->setBit($2->size()-i-1, Bit);
}
$$ = Init;
delete $2;
} | ID '<' ValueListNE '>' {
// This is a CLASS<initvalslist> expression. This is supposed to synthesize
// a new anonymous definition, deriving from CLASS<initvalslist> with no
// body.
Record *Class = Records.getClass(*$1);
if (!Class) {
err() << "Expected a class, got '" << *$1 << "'!\n";
exit(1);
}
delete $1;
static unsigned AnonCounter = 0;
Record *OldRec = CurRec; // Save CurRec.
// Create the new record, set it as CurRec temporarily.
CurRec = new Record("anonymous.val."+utostr(AnonCounter++));
addSubClass(Class, *$3); // Add info about the subclass to CurRec.
delete $3; // Free up the template args.
CurRec->resolveReferences();
Records.addDef(CurRec);
// The result of the expression is a reference to the new record.
$$ = new DefInit(CurRec);
// Restore the old CurRec
CurRec = OldRec;
} | Value '{' BitList '}' {
$$ = $1->convertInitializerBitRange(*$3);
if ($$ == 0) {
err() << "Invalid bit range for value '" << *$1 << "'!\n";
exit(1);
}
delete $3;
} | '[' ValueList ']' {
$$ = new ListInit(*$2);
delete $2;
} | Value '.' ID {
if (!$1->getFieldType(*$3)) {
err() << "Cannot access field '" << *$3 << "' of value '" << *$1 << "!\n";
exit(1);
}
$$ = new FieldInit($1, *$3);
delete $3;
} | '(' IDValue DagArgList ')' {
$$ = new DagInit($2, *$3);
delete $3;
} | Value '[' BitList ']' {
std::reverse($3->begin(), $3->end());
$$ = $1->convertInitListSlice(*$3);
if ($$ == 0) {
err() << "Invalid list slice for value '" << *$1 << "'!\n";
exit(1);
}
delete $3;
} | CONCATTOK '(' Value ',' Value ')' {
$$ = (new BinOpInit(BinOpInit::CONCAT, $3, $5))->Fold();
} | SHLTOK '(' Value ',' Value ')' {
$$ = (new BinOpInit(BinOpInit::SHL, $3, $5))->Fold();
} | SRATOK '(' Value ',' Value ')' {
$$ = (new BinOpInit(BinOpInit::SRA, $3, $5))->Fold();
} | SRLTOK '(' Value ',' Value ')' {
$$ = (new BinOpInit(BinOpInit::SRL, $3, $5))->Fold();
} | STRCONCATTOK '(' Value ',' Value ')' {
$$ = (new BinOpInit(BinOpInit::STRCONCAT, $3, $5))->Fold();
};
OptVarName : /* empty */ {
$$ = new std::string();
}
| ':' VARNAME {
$$ = $2;
};
DagArgListNE : Value OptVarName {
$$ = new std::vector<std::pair<Init*, std::string> >();
$$->push_back(std::make_pair($1, *$2));
delete $2;
}
| DagArgListNE ',' Value OptVarName {
$1->push_back(std::make_pair($3, *$4));
delete $4;
$$ = $1;
};
DagArgList : /*empty*/ {
$$ = new std::vector<std::pair<Init*, std::string> >();
}
| DagArgListNE { $$ = $1; };
RBitList : INTVAL {
$$ = new std::vector<unsigned>();
$$->push_back($1);
} | INTVAL '-' INTVAL {
if ($1 < 0 || $3 < 0) {
err() << "Invalid range: " << $1 << "-" << $3 << "!\n";
exit(1);
}
$$ = new std::vector<unsigned>();
if ($1 < $3) {
for (int i = $1; i <= $3; ++i)
$$->push_back(i);
} else {
for (int i = $1; i >= $3; --i)
$$->push_back(i);
}
} | INTVAL INTVAL {
$2 = -$2;
if ($1 < 0 || $2 < 0) {
err() << "Invalid range: " << $1 << "-" << $2 << "!\n";
exit(1);
}
$$ = new std::vector<unsigned>();
if ($1 < $2) {
for (int i = $1; i <= $2; ++i)
$$->push_back(i);
} else {
for (int i = $1; i >= $2; --i)
$$->push_back(i);
}
} | RBitList ',' INTVAL {
($$=$1)->push_back($3);
} | RBitList ',' INTVAL '-' INTVAL {
if ($3 < 0 || $5 < 0) {
err() << "Invalid range: " << $3 << "-" << $5 << "!\n";
exit(1);
}
$$ = $1;
if ($3 < $5) {
for (int i = $3; i <= $5; ++i)
$$->push_back(i);
} else {
for (int i = $3; i >= $5; --i)
$$->push_back(i);
}
} | RBitList ',' INTVAL INTVAL {
$4 = -$4;
if ($3 < 0 || $4 < 0) {
err() << "Invalid range: " << $3 << "-" << $4 << "!\n";
exit(1);
}
$$ = $1;
if ($3 < $4) {
for (int i = $3; i <= $4; ++i)
$$->push_back(i);
} else {
for (int i = $3; i >= $4; --i)
$$->push_back(i);
}
};
BitList : RBitList { $$ = $1; std::reverse($1->begin(), $1->end()); };
OptBitList : /*empty*/ { $$ = 0; } | '{' BitList '}' { $$ = $2; };
ValueList : /*empty*/ {
$$ = new std::vector<Init*>();
} | ValueListNE {
$$ = $1;
};
ValueListNE : Value {
$$ = new std::vector<Init*>();
$$->push_back($1);
} | ValueListNE ',' Value {
($$ = $1)->push_back($3);
};
Declaration : OptPrefix Type ID OptValue {
std::string DecName = *$3;
if (ParsingTemplateArgs) {
if (CurRec) {
DecName = CurRec->getName() + ":" + DecName;
} else {
assert(CurMultiClass);
}
if (CurMultiClass)
DecName = CurMultiClass->Rec.getName() + "::" + DecName;
}
addValue(RecordVal(DecName, $2, $1));
setValue(DecName, 0, $4);
$$ = new std::string(DecName);
};
BodyItem : Declaration ';' {
delete $1;
} | LET ID OptBitList '=' Value ';' {
setValue(*$2, $3, $5);
delete $2;
delete $3;
};
BodyList : /*empty*/ | BodyList BodyItem;
Body : ';' | '{' BodyList '}';
SubClassRef : ClassID {
$$ = new SubClassRefTy($1, new std::vector<Init*>());
} | ClassID '<' ValueListNE '>' {
$$ = new SubClassRefTy($1, $3);
};
ClassListNE : SubClassRef {
$$ = new std::vector<SubClassRefTy>();
$$->push_back(*$1);
delete $1;
}
| ClassListNE ',' SubClassRef {
($$=$1)->push_back(*$3);
delete $3;
};
ClassList : /*empty */ {
$$ = new std::vector<SubClassRefTy>();
}
| ':' ClassListNE {
$$ = $2;
};
DeclListNE : Declaration {
getActiveRec()->addTemplateArg(*$1);
delete $1;
} | DeclListNE ',' Declaration {
getActiveRec()->addTemplateArg(*$3);
delete $3;
};
TemplateArgList : '<' DeclListNE '>' {};
OptTemplateArgList : /*empty*/ | TemplateArgList;
OptID : ID { $$ = $1; } | /*empty*/ { $$ = new std::string(); };
ObjectName : OptID {
static unsigned AnonCounter = 0;
if ($1->empty())
*$1 = "anonymous."+utostr(AnonCounter++);
$$ = $1;
};
ClassName : ObjectName {
// If a class of this name already exists, it must be a forward ref.
if ((CurRec = Records.getClass(*$1))) {
// If the body was previously defined, this is an error.
if (!CurRec->getValues().empty() ||
!CurRec->getSuperClasses().empty() ||
!CurRec->getTemplateArgs().empty()) {
err() << "Class '" << CurRec->getName() << "' already defined!\n";
exit(1);
}
} else {
// If this is the first reference to this class, create and add it.
CurRec = new Record(*$1);
Records.addClass(CurRec);
}
delete $1;
};
DefName : ObjectName {
CurRec = new Record(*$1);
delete $1;
if (!CurMultiClass) {
// Top-level def definition.
// Ensure redefinition doesn't happen.
if (Records.getDef(CurRec->getName())) {
err() << "def '" << CurRec->getName() << "' already defined!\n";
exit(1);
}
Records.addDef(CurRec);
} else {
// Otherwise, a def inside a multiclass, add it to the multiclass.
for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
err() << "def '" << CurRec->getName()
<< "' already defined in this multiclass!\n";
exit(1);
}
CurMultiClass->DefPrototypes.push_back(CurRec);
}
};
ObjectBody : ClassList {
for (unsigned i = 0, e = $1->size(); i != e; ++i) {
addSubClass((*$1)[i].first, *(*$1)[i].second);
// Delete the template arg values for the class
delete (*$1)[i].second;
}
delete $1; // Delete the class list.
// Process any variables on the let stack.
for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
setValue(LetStack[i][j].Name,
LetStack[i][j].HasBits ? &LetStack[i][j].Bits : 0,
LetStack[i][j].Value);
} Body {
$$ = CurRec;
CurRec = 0;
};
ClassInst : CLASS ClassName {
ParsingTemplateArgs = true;
} OptTemplateArgList {
ParsingTemplateArgs = false;
} ObjectBody {
$$ = $6;
};
DefInst : DEF DefName ObjectBody {
if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
$3->resolveReferences();
// If ObjectBody has template arguments, it's an error.
assert($3->getTemplateArgs().empty() && "How'd this get template args?");
$$ = $3;
};
// MultiClassDef - A def instance specified inside a multiclass.
MultiClassDef : DefInst {
$$ = $1;
// Copy the template arguments for the multiclass into the def.
const std::vector<std::string> &TArgs = CurMultiClass->Rec.getTemplateArgs();
for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
assert(RV && "Template arg doesn't exist?");
$$->addValue(*RV);
}
};
// MultiClassBody - Sequence of def's that are instantiated when a multiclass is
// used.
MultiClassBody : MultiClassDef {
$$ = new std::vector<Record*>();
$$->push_back($1);
} | MultiClassBody MultiClassDef {
$$->push_back($2);
};
MultiClassName : ID {
MultiClass *&MCE = MultiClasses[*$1];
if (MCE) {
err() << "multiclass '" << *$1 << "' already defined!\n";
exit(1);
}
MCE = CurMultiClass = new MultiClass(*$1);
delete $1;
};
// MultiClass - Multiple definitions.
MultiClassInst : MULTICLASS MultiClassName {
ParsingTemplateArgs = true;
} OptTemplateArgList {
ParsingTemplateArgs = false;
}'{' MultiClassBody '}' {
CurMultiClass = 0;
};
// DefMInst - Instantiate a multiclass.
DefMInst : DEFM ID { CurDefmPrefix = $2; } ':' SubClassRef ';' {
// To instantiate a multiclass, we need to first get the multiclass, then
// instantiate each def contained in the multiclass with the SubClassRef
// template parameters.
MultiClass *MC = MultiClasses[$5->first->getName()];
assert(MC && "Didn't lookup multiclass correctly?");
std::vector<Init*> &TemplateVals = *$5->second;
delete $5;
// Verify that the correct number of template arguments were specified.
const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
if (TArgs.size() < TemplateVals.size()) {
err() << "ERROR: More template args specified than multiclass expects!\n";
exit(1);
}
// Loop over all the def's in the multiclass, instantiating each one.
for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
Record *DefProto = MC->DefPrototypes[i];
// Add the suffix to the defm name to get the new name.
assert(CurRec == 0 && "A def is current?");
CurRec = new Record(*$2 + DefProto->getName());
addSubClass(DefProto, std::vector<Init*>());
// Loop over all of the template arguments, setting them to the specified
// value or leaving them as the default if necessary.
for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
if (i < TemplateVals.size()) { // A value is specified for this temp-arg?
// Set it now.
setValue(TArgs[i], 0, TemplateVals[i]);
// Resolve it next.
CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
// Now remove it.
CurRec->removeValue(TArgs[i]);
} else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
err() << "ERROR: Value not specified for template argument #"
<< i << " (" << TArgs[i] << ") of multiclassclass '"
<< MC->Rec.getName() << "'!\n";
exit(1);
}
}
// If the mdef is inside a 'let' expression, add to each def.
for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
setValue(LetStack[i][j].Name,
LetStack[i][j].HasBits ? &LetStack[i][j].Bits : 0,
LetStack[i][j].Value);
// Ensure redefinition doesn't happen.
if (Records.getDef(CurRec->getName())) {
err() << "def '" << CurRec->getName() << "' already defined, "
<< "instantiating defm '" << *$2 << "' with subdef '"
<< DefProto->getName() << "'!\n";
exit(1);
}
Records.addDef(CurRec);
CurRec->resolveReferences();
CurRec = 0;
}
delete &TemplateVals;
delete $2;
CurDefmPrefix = 0;
};
Object : ClassInst {} | DefInst {};
Object : MultiClassInst | DefMInst;
LETItem : ID OptBitList '=' Value {
LetStack.back().push_back(LetRecord(*$1, $2, $4));
delete $1; delete $2;
};
LETList : LETItem | LETList ',' LETItem;
// LETCommand - A 'LET' statement start...
LETCommand : LET { LetStack.push_back(std::vector<LetRecord>()); } LETList IN;
// Support Set commands wrapping objects... both with and without braces.
Object : LETCommand '{' ObjectList '}' {
LetStack.pop_back();
}
| LETCommand Object {
LetStack.pop_back();
};
ObjectList : Object {} | ObjectList Object {};
File : ObjectList;
%%
int yyerror(const char *ErrorMsg) {
err() << "Error parsing: " << ErrorMsg << "\n";
exit(1);
}

View File

@ -11,20 +11,8 @@ LEVEL = ../..
TOOLNAME = tblgen
NO_INSTALL = 1;
USEDLIBS = LLVMSupport.a LLVMSystem.a
EXTRA_DIST = FileParser.cpp.cvs FileParser.h.cvs FileParser.y.cvs
REQUIRES_EH := 1
REQUIRES_RTTI := 1
include $(LEVEL)/Makefile.common
# Disable -pedantic for tblgen
CompileCommonOpts := $(filter-out -pedantic,$(CompileCommonOpts))
CompileCommonOpts := $(filter-out -Wno-long-long,$(CompileCommonOpts))
#
# Make the source file depend on the header file. In this way, dependencies
# (which depend on the source file) won't get generated until bison is done
# generating the C source and header files for the parser.
#
$(ObjDir)/TGLexer.o : $(PROJ_SRC_DIR)/FileParser.h

View File

@ -12,20 +12,13 @@
//===----------------------------------------------------------------------===//
#include "TGLexer.h"
#include "Record.h"
#include "llvm/Support/Streams.h"
#include "Record.h"
#include "llvm/Support/MemoryBuffer.h"
typedef std::pair<llvm::Record*, std::vector<llvm::Init*>*> SubClassRefTy;
#include "FileParser.h"
#include <ostream>
#include "llvm/Config/config.h"
#include <cctype>
using namespace llvm;
// FIXME: REMOVE THIS.
#define YYEOF 0
#define YYERROR -2
TGLexer::TGLexer(MemoryBuffer *StartBuf) : CurLineNo(1), CurBuf(StartBuf) {
CurPtr = CurBuf->getBufferStart();
TokStart = 0;
@ -40,18 +33,12 @@ TGLexer::~TGLexer() {
}
/// ReturnError - Set the error to the specified string at the specified
/// location. This is defined to always return YYERROR.
int TGLexer::ReturnError(const char *Loc, const std::string &Msg) {
/// location. This is defined to always return tgtok::Error.
tgtok::TokKind TGLexer::ReturnError(const char *Loc, const std::string &Msg) {
PrintError(Loc, Msg);
return YYERROR;
return tgtok::Error;
}
std::ostream &TGLexer::err() const {
PrintIncludeStack(*cerr.stream());
return *cerr.stream();
}
void TGLexer::PrintIncludeStack(std::ostream &OS) const {
for (unsigned i = 0, e = IncludeStack.size(); i != e; ++i)
OS << "Included from " << IncludeStack[i].Buffer->getBufferIdentifier()
@ -62,7 +49,8 @@ void TGLexer::PrintIncludeStack(std::ostream &OS) const {
/// PrintError - Print the error at the specified location.
void TGLexer::PrintError(const char *ErrorLoc, const std::string &Msg) const {
err() << Msg << "\n";
PrintIncludeStack(*cerr.stream());
cerr << Msg << "\n";
assert(ErrorLoc && "Location not specified!");
// Scan backward to find the start of the line.
@ -122,7 +110,7 @@ int TGLexer::getNextChar() {
}
}
int TGLexer::LexToken() {
tgtok::TokKind TGLexer::LexToken() {
TokStart = CurPtr;
// This always consumes at least one character.
int CurChar = getNextChar();
@ -133,9 +121,23 @@ int TGLexer::LexToken() {
if (isalpha(CurChar) || CurChar == '_')
return LexIdentifier();
// Unknown character, return the char itself.
return (unsigned char)CurChar;
case EOF: return YYEOF;
// Unknown character, emit an error.
return ReturnError(TokStart, "Unexpected character");
case EOF: return tgtok::Eof;
case ':': return tgtok::colon;
case ';': return tgtok::semi;
case '.': return tgtok::period;
case ',': return tgtok::comma;
case '<': return tgtok::less;
case '>': return tgtok::greater;
case ']': return tgtok::r_square;
case '{': return tgtok::l_brace;
case '}': return tgtok::r_brace;
case '(': return tgtok::l_paren;
case ')': return tgtok::r_paren;
case '=': return tgtok::equal;
case '?': return tgtok::question;
case 0:
case ' ':
case '\t':
@ -150,9 +152,9 @@ int TGLexer::LexToken() {
SkipBCPLComment();
else if (*CurPtr == '*') {
if (SkipCComment())
return YYERROR;
} else // Otherwise, return this / as a token.
return CurChar;
return tgtok::Error;
} else // Otherwise, this is an error.
return ReturnError(TokStart, "Unexpected character");
return LexToken();
case '-': case '+':
case '0': case '1': case '2': case '3': case '4': case '5': case '6':
@ -166,7 +168,7 @@ int TGLexer::LexToken() {
}
/// LexString - Lex "[^"]*"
int TGLexer::LexString() {
tgtok::TokKind TGLexer::LexString() {
const char *StrStart = CurPtr;
while (*CurPtr != '"') {
@ -180,14 +182,14 @@ int TGLexer::LexString() {
++CurPtr;
}
Filelval.StrVal = new std::string(StrStart, CurPtr);
CurStrVal.assign(StrStart, CurPtr);
++CurPtr;
return STRVAL;
return tgtok::StrVal;
}
int TGLexer::LexVarName() {
tgtok::TokKind TGLexer::LexVarName() {
if (!isalpha(CurPtr[0]) && CurPtr[0] != '_')
return '$'; // Invalid varname.
return ReturnError(TokStart, "Invalid variable name");
// Otherwise, we're ok, consume the rest of the characters.
const char *VarNameStart = CurPtr++;
@ -195,14 +197,14 @@ int TGLexer::LexVarName() {
while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
++CurPtr;
Filelval.StrVal = new std::string(VarNameStart, CurPtr);
return VARNAME;
CurStrVal.assign(VarNameStart, CurPtr);
return tgtok::VarName;
}
int TGLexer::LexIdentifier() {
tgtok::TokKind TGLexer::LexIdentifier() {
// The first letter is [a-zA-Z_].
const char *IdentStart = CurPtr-1;
const char *IdentStart = TokStart;
// Match the rest of the identifier regex: [0-9a-zA-Z_]*
while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
@ -211,45 +213,45 @@ int TGLexer::LexIdentifier() {
// Check to see if this identifier is a keyword.
unsigned Len = CurPtr-IdentStart;
if (Len == 3 && !memcmp(IdentStart, "int", 3)) return INT;
if (Len == 3 && !memcmp(IdentStart, "bit", 3)) return BIT;
if (Len == 4 && !memcmp(IdentStart, "bits", 4)) return BITS;
if (Len == 6 && !memcmp(IdentStart, "string", 6)) return STRING;
if (Len == 4 && !memcmp(IdentStart, "list", 4)) return LIST;
if (Len == 4 && !memcmp(IdentStart, "code", 4)) return CODE;
if (Len == 3 && !memcmp(IdentStart, "dag", 3)) return DAG;
if (Len == 3 && !memcmp(IdentStart, "int", 3)) return tgtok::Int;
if (Len == 3 && !memcmp(IdentStart, "bit", 3)) return tgtok::Bit;
if (Len == 4 && !memcmp(IdentStart, "bits", 4)) return tgtok::Bits;
if (Len == 6 && !memcmp(IdentStart, "string", 6)) return tgtok::String;
if (Len == 4 && !memcmp(IdentStart, "list", 4)) return tgtok::List;
if (Len == 4 && !memcmp(IdentStart, "code", 4)) return tgtok::Code;
if (Len == 3 && !memcmp(IdentStart, "dag", 3)) return tgtok::Dag;
if (Len == 5 && !memcmp(IdentStart, "class", 5)) return CLASS;
if (Len == 3 && !memcmp(IdentStart, "def", 3)) return DEF;
if (Len == 4 && !memcmp(IdentStart, "defm", 4)) return DEFM;
if (Len == 10 && !memcmp(IdentStart, "multiclass", 10)) return MULTICLASS;
if (Len == 5 && !memcmp(IdentStart, "field", 5)) return FIELD;
if (Len == 3 && !memcmp(IdentStart, "let", 3)) return LET;
if (Len == 2 && !memcmp(IdentStart, "in", 2)) return IN;
if (Len == 5 && !memcmp(IdentStart, "class", 5)) return tgtok::Class;
if (Len == 3 && !memcmp(IdentStart, "def", 3)) return tgtok::Def;
if (Len == 4 && !memcmp(IdentStart, "defm", 4)) return tgtok::Defm;
if (Len == 10 && !memcmp(IdentStart, "multiclass", 10))
return tgtok::MultiClass;
if (Len == 5 && !memcmp(IdentStart, "field", 5)) return tgtok::Field;
if (Len == 3 && !memcmp(IdentStart, "let", 3)) return tgtok::Let;
if (Len == 2 && !memcmp(IdentStart, "in", 2)) return tgtok::In;
if (Len == 7 && !memcmp(IdentStart, "include", 7)) {
if (LexInclude()) return YYERROR;
return LexToken();
if (LexInclude()) return tgtok::Error;
return Lex();
}
Filelval.StrVal = new std::string(IdentStart, CurPtr);
return ID;
CurStrVal.assign(IdentStart, CurPtr);
return tgtok::Id;
}
/// LexInclude - We just read the "include" token. Get the string token that
/// comes next and enter the include.
bool TGLexer::LexInclude() {
// The token after the include must be a string.
int Tok = LexToken();
if (Tok == YYERROR) return true;
if (Tok != STRVAL) {
PrintError(getTokenStart(), "Expected filename after include");
tgtok::TokKind Tok = LexToken();
if (Tok == tgtok::Error) return true;
if (Tok != tgtok::StrVal) {
PrintError(getLoc(), "Expected filename after include");
return true;
}
// Get the string.
std::string Filename = *Filelval.StrVal;
delete Filelval.StrVal;
std::string Filename = CurStrVal;
// Try to find the file.
MemoryBuffer *NewBuf = MemoryBuffer::getFile(&Filename[0], Filename.size());
@ -261,8 +263,7 @@ bool TGLexer::LexInclude() {
}
if (NewBuf == 0) {
PrintError(getTokenStart(),
"Could not find include file '" + Filename + "'");
PrintError(getLoc(), "Could not find include file '" + Filename + "'");
return true;
}
@ -296,7 +297,6 @@ void TGLexer::SkipBCPLComment() {
/// SkipCComment - This skips C-style /**/ comments. The only difference from C
/// is that we allow nesting.
bool TGLexer::SkipCComment() {
const char *CommentStart = CurPtr-1;
++CurPtr; // skip the star.
unsigned CommentDepth = 1;
@ -304,7 +304,7 @@ bool TGLexer::SkipCComment() {
int CurChar = getNextChar();
switch (CurChar) {
case EOF:
PrintError(CommentStart, "Unterminated comment!");
PrintError(TokStart, "Unterminated comment!");
return true;
case '*':
// End of the comment?
@ -328,13 +328,11 @@ bool TGLexer::SkipCComment() {
/// [-+]?[0-9]+
/// 0x[0-9a-fA-F]+
/// 0b[01]+
int TGLexer::LexNumber() {
const char *NumStart = CurPtr-1;
tgtok::TokKind TGLexer::LexNumber() {
if (CurPtr[-1] == '0') {
if (CurPtr[0] == 'x') {
++CurPtr;
NumStart = CurPtr;
const char *NumStart = CurPtr;
while (isxdigit(CurPtr[0]))
++CurPtr;
@ -342,42 +340,41 @@ int TGLexer::LexNumber() {
if (CurPtr == NumStart)
return ReturnError(CurPtr-2, "Invalid hexadecimal number");
Filelval.IntVal = strtoll(NumStart, 0, 16);
return INTVAL;
CurIntVal = strtoll(NumStart, 0, 16);
return tgtok::IntVal;
} else if (CurPtr[0] == 'b') {
++CurPtr;
NumStart = CurPtr;
const char *NumStart = CurPtr;
while (CurPtr[0] == '0' || CurPtr[0] == '1')
++CurPtr;
// Requires at least one binary digit.
if (CurPtr == NumStart)
return ReturnError(CurPtr-2, "Invalid binary number");
Filelval.IntVal = strtoll(NumStart, 0, 2);
return INTVAL;
CurIntVal = strtoll(NumStart, 0, 2);
return tgtok::IntVal;
}
}
// Check for a sign without a digit.
if (CurPtr[-1] == '-' || CurPtr[-1] == '+') {
if (!isdigit(CurPtr[0]))
return CurPtr[-1];
if (!isdigit(CurPtr[0])) {
if (CurPtr[-1] == '-')
return tgtok::minus;
else if (CurPtr[-1] == '+')
return tgtok::plus;
}
while (isdigit(CurPtr[0]))
++CurPtr;
Filelval.IntVal = strtoll(NumStart, 0, 10);
return INTVAL;
CurIntVal = strtoll(TokStart, 0, 10);
return tgtok::IntVal;
}
/// LexBracket - We just read '['. If this is a code block, return it,
/// otherwise return the bracket. Match: '[' and '[{ ( [^}]+ | }[^]] )* }]'
int TGLexer::LexBracket() {
tgtok::TokKind TGLexer::LexBracket() {
if (CurPtr[0] != '{')
return '[';
return tgtok::l_square;
++CurPtr;
const char *CodeStart = CurPtr;
while (1) {
@ -389,8 +386,8 @@ int TGLexer::LexBracket() {
Char = getNextChar();
if (Char == EOF) break;
if (Char == ']') {
Filelval.StrVal = new std::string(CodeStart, CurPtr-2);
return CODEFRAGMENT;
CurStrVal.assign(CodeStart, CurPtr-2);
return tgtok::CodeFragment;
}
}
@ -398,9 +395,9 @@ int TGLexer::LexBracket() {
}
/// LexExclaim - Lex '!' and '![a-zA-Z]+'.
int TGLexer::LexExclaim() {
tgtok::TokKind TGLexer::LexExclaim() {
if (!isalpha(*CurPtr))
return '!';
return ReturnError(CurPtr-1, "Invalid \"!operator\"");
const char *Start = CurPtr++;
while (isalpha(*CurPtr))
@ -409,61 +406,12 @@ int TGLexer::LexExclaim() {
// Check to see which operator this is.
unsigned Len = CurPtr-Start;
if (Len == 3 && !memcmp(Start, "con", 3)) return CONCATTOK;
if (Len == 3 && !memcmp(Start, "sra", 3)) return SRATOK;
if (Len == 3 && !memcmp(Start, "srl", 3)) return SRLTOK;
if (Len == 3 && !memcmp(Start, "shl", 3)) return SHLTOK;
if (Len == 9 && !memcmp(Start, "strconcat", 9)) return STRCONCATTOK;
if (Len == 3 && !memcmp(Start, "con", 3)) return tgtok::XConcat;
if (Len == 3 && !memcmp(Start, "sra", 3)) return tgtok::XSRA;
if (Len == 3 && !memcmp(Start, "srl", 3)) return tgtok::XSRL;
if (Len == 3 && !memcmp(Start, "shl", 3)) return tgtok::XSHL;
if (Len == 9 && !memcmp(Start, "strconcat", 9)) return tgtok::XStrConcat;
return ReturnError(Start-1, "Unknown operator");
}
//===----------------------------------------------------------------------===//
// Interfaces used by the Bison parser.
//===----------------------------------------------------------------------===//
int Fileparse();
static TGLexer *TheLexer;
namespace llvm {
std::ostream &err() {
return TheLexer->err();
}
/// ParseFile - this function begins the parsing of the specified tablegen
/// file.
///
void ParseFile(const std::string &Filename,
const std::vector<std::string> &IncludeDirs) {
std::string ErrorStr;
MemoryBuffer *F = MemoryBuffer::getFileOrSTDIN(&Filename[0], Filename.size(),
&ErrorStr);
if (F == 0) {
cerr << "Could not open input file '" + Filename + "': " << ErrorStr <<"\n";
exit(1);
}
assert(!TheLexer && "Lexer isn't reentrant yet!");
TheLexer = new TGLexer(F);
// Record the location of the include directory so that the lexer can find
// it later.
TheLexer->setIncludeDirs(IncludeDirs);
Fileparse();
// Cleanup
delete TheLexer;
TheLexer = 0;
}
} // End llvm namespace
int Filelex() {
assert(TheLexer && "No lexer setup yet!");
int Tok = TheLexer->LexToken();
if (Tok == YYERROR)
exit(1);
return Tok;
}

View File

@ -20,12 +20,49 @@
namespace llvm {
class MemoryBuffer;
namespace tgtok {
enum TokKind {
// Markers
Eof, Error,
// Tokens with no info.
minus, plus, // - +
l_square, r_square, // [ ]
l_brace, r_brace, // { }
l_paren, r_paren, // ( )
less, greater, // < >
colon, semi, // ; :
comma, period, // , .
equal, question, // = ?
// Keywords.
Bit, Bits, Class, Code, Dag, Def, Defm, Field, In, Int, Let, List,
MultiClass, String,
// !keywords.
XConcat, XSRA, XSRL, XSHL, XStrConcat,
// Integer value.
IntVal,
// String valued tokens.
Id, StrVal, VarName, CodeFragment
};
}
/// TGLexer - TableGen Lexer class.
class TGLexer {
const char *CurPtr;
unsigned CurLineNo;
MemoryBuffer *CurBuf;
// Information about the current token.
const char *TokStart;
tgtok::TokKind CurCode;
std::string CurStrVal; // This is valid for ID, STRVAL, VARNAME, CODEFRAGMENT
int CurIntVal; // This is valid for INTVAL.
/// IncludeRec / IncludeStack - This captures the current set of include
/// directives we are nested within.
struct IncludeRec {
@ -40,7 +77,6 @@ class TGLexer {
// IncludeDirectories - This is the list of directories we should search for
// include files in.
std::vector<std::string> IncludeDirectories;
const char *TokStart;
public:
TGLexer(MemoryBuffer *StartBuf);
~TGLexer();
@ -49,29 +85,46 @@ public:
IncludeDirectories = Dirs;
}
int LexToken();
typedef const char* LocationTy;
LocationTy getTokenStart() const { return TokStart; }
void PrintError(LocationTy Loc, const std::string &Msg) const;
tgtok::TokKind Lex() {
return CurCode = LexToken();
}
tgtok::TokKind getCode() const { return CurCode; }
const std::string &getCurStrVal() const {
assert((CurCode == tgtok::Id || CurCode == tgtok::StrVal ||
CurCode == tgtok::VarName || CurCode == tgtok::CodeFragment) &&
"This token doesn't have a string value");
return CurStrVal;
}
int getCurIntVal() const {
assert(CurCode == tgtok::IntVal && "This token isn't an integer");
return CurIntVal;
}
typedef const char* LocTy;
LocTy getLoc() const { return TokStart; }
void PrintError(LocTy Loc, const std::string &Msg) const;
std::ostream &err() const;
void PrintIncludeStack(std::ostream &OS) const;
private:
int ReturnError(const char *Loc, const std::string &Msg);
/// LexToken - Read the next token and return its code.
tgtok::TokKind LexToken();
tgtok::TokKind ReturnError(const char *Loc, const std::string &Msg);
int getNextChar();
void SkipBCPLComment();
bool SkipCComment();
int LexIdentifier();
tgtok::TokKind LexIdentifier();
bool LexInclude();
int LexString();
int LexVarName();
int LexNumber();
int LexBracket();
int LexExclaim();
tgtok::TokKind LexString();
tgtok::TokKind LexVarName();
tgtok::TokKind LexNumber();
tgtok::TokKind LexBracket();
tgtok::TokKind LexExclaim();
};
} // end namespace llvm

1372
utils/TableGen/TGParser.cpp Normal file

File diff suppressed because it is too large Load Diff

109
utils/TableGen/TGParser.h Normal file
View File

@ -0,0 +1,109 @@
//===- TGParser.h - Parser for TableGen Files -------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class represents the Parser for tablegen files.
//
//===----------------------------------------------------------------------===//
#ifndef TGPARSER_H
#define TGPARSER_H
#include "TGLexer.h"
#include <map>
namespace llvm {
class Record;
class RecordVal;
class RecTy;
class Init;
struct MultiClass;
struct SubClassReference;
struct LetRecord {
std::string Name;
std::vector<unsigned> Bits;
Init *Value;
TGLexer::LocTy Loc;
LetRecord(const std::string &N, const std::vector<unsigned> &B, Init *V,
TGLexer::LocTy L)
: Name(N), Bits(B), Value(V), Loc(L) {
}
};
class TGParser {
TGLexer Lex;
std::vector<std::vector<LetRecord> > LetStack;
std::map<std::string, MultiClass*> MultiClasses;
/// CurMultiClass - If we are parsing a 'multiclass' definition, this is the
/// current value.
MultiClass *CurMultiClass;
public:
typedef TGLexer::LocTy LocTy;
TGParser(MemoryBuffer *StartBuf) : Lex(StartBuf), CurMultiClass(0) {}
void setIncludeDirs(const std::vector<std::string> &D){Lex.setIncludeDirs(D);}
/// ParseFile - Main entrypoint for parsing a tblgen file. These parser
/// routines return true on error, or false on success.
bool ParseFile();
bool Error(LocTy L, const std::string &Msg) const {
Lex.PrintError(L, Msg);
return true;
}
bool TokError(const std::string &Msg) const {
return Error(Lex.getLoc(), Msg);
}
private: // Semantic analysis methods.
bool AddValue(Record *TheRec, LocTy Loc, const RecordVal &RV);
bool SetValue(Record *TheRec, LocTy Loc, const std::string &ValName,
const std::vector<unsigned> &BitList, Init *V);
bool AddSubClass(Record *Rec, class SubClassReference &SubClass);
private: // Parser methods.
bool ParseObjectList();
bool ParseObject();
bool ParseClass();
bool ParseMultiClass();
bool ParseMultiClassDef(MultiClass *CurMC);
bool ParseDefm();
bool ParseTopLevelLet();
std::vector<LetRecord> ParseLetList();
Record *ParseDef(MultiClass *CurMultiClass);
bool ParseObjectBody(Record *CurRec);
bool ParseBody(Record *CurRec);
bool ParseBodyItem(Record *CurRec);
bool ParseTemplateArgList(Record *CurRec);
std::string ParseDeclaration(Record *CurRec, bool ParsingTemplateArgs);
SubClassReference ParseSubClassReference(Record *CurRec, bool isDefm);
Init *ParseIDValue(Record *CurRec);
Init *ParseIDValue(Record *CurRec, const std::string &Name, LocTy NameLoc);
Init *ParseSimpleValue(Record *CurRec);
Init *ParseValue(Record *CurRec);
std::vector<Init*> ParseValueList(Record *CurRec);
std::vector<std::pair<llvm::Init*, std::string> > ParseDagArgList(Record *);
bool ParseOptionalRangeList(std::vector<unsigned> &Ranges);
bool ParseOptionalBitList(std::vector<unsigned> &Ranges);
std::vector<unsigned> ParseRangeList();
bool ParseRangePiece(std::vector<unsigned> &Ranges);
RecTy *ParseType();
std::string ParseObjectName();
Record *ParseClassID();
Record *ParseDefmID();
};
} // end namespace llvm
#endif

View File

@ -16,10 +16,12 @@
//===----------------------------------------------------------------------===//
#include "Record.h"
#include "TGParser.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Streams.h"
#include "llvm/System/Signals.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/MemoryBuffer.h"
#include "CallingConvEmitter.h"
#include "CodeEmitterGen.h"
#include "RegisterInfoEmitter.h"
@ -93,16 +95,35 @@ namespace {
cl::value_desc("directory"), cl::Prefix);
}
namespace llvm {
void ParseFile(const std::string &Filename,
const std::vector<std::string> &IncludeDirs);
}
RecordKeeper llvm::Records;
/// ParseFile - this function begins the parsing of the specified tablegen
/// file.
static bool ParseFile(const std::string &Filename,
const std::vector<std::string> &IncludeDirs) {
std::string ErrorStr;
MemoryBuffer *F = MemoryBuffer::getFileOrSTDIN(&Filename[0], Filename.size(),
&ErrorStr);
if (F == 0) {
cerr << "Could not open input file '" + Filename + "': " << ErrorStr <<"\n";
return true;
}
TGParser Parser(F);
// Record the location of the include directory so that the lexer can find
// it later.
Parser.setIncludeDirs(IncludeDirs);
return Parser.ParseFile();
}
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv);
ParseFile(InputFilename, IncludeDirs);
// Parse the input file.
if (ParseFile(InputFilename, IncludeDirs))
return 1;
std::ostream *Out = cout.stream();
if (OutputFilename != "-") {