blob: b3d521b4820eb9829badfbb0f15178abf9852a30 [file] [log] [blame]
Chris Lattner00950542001-06-06 20:29:01 +00001//===-- llvmAsmParser.y - Parser for llvm assembly files ---------*- C++ -*--=//
2//
3// This file implements the bison parser for LLVM assembly languages files.
4//
5//===------------------------------------------------------------------------=//
6
7//
8// TODO: Parse comments and add them to an internal node... so that they may
9// be saved in the bytecode format as well as everything else. Very important
10// for a general IR format.
11//
12
13%{
14#include "ParserInternals.h"
15#include "llvm/BasicBlock.h"
16#include "llvm/Method.h"
17#include "llvm/SymbolTable.h"
18#include "llvm/Module.h"
19#include "llvm/Type.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Assembly/Parser.h"
22#include "llvm/ConstantPool.h"
23#include "llvm/iTerminators.h"
24#include "llvm/iMemory.h"
25#include <list>
26#include <utility> // Get definition of pair class
27#include <stdio.h> // This embarasment is due to our flex lexer...
28
Chris Lattner09083092001-07-08 04:57:15 +000029int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
30int yylex(); // declaration" of xxx warnings.
Chris Lattner00950542001-06-06 20:29:01 +000031int yyparse();
32
33static Module *ParserResult;
34const ToolCommandLine *CurOptions = 0;
35
36// This contains info used when building the body of a method. It is destroyed
37// when the method is completed.
38//
39typedef vector<Value *> ValueList; // Numbered defs
40static void ResolveDefinitions(vector<ValueList> &LateResolvers);
41
42static struct PerModuleInfo {
43 Module *CurrentModule;
44 vector<ValueList> Values; // Module level numbered definitions
45 vector<ValueList> LateResolveValues;
46
47 void ModuleDone() {
48 // If we could not resolve some blocks at parsing time (forward branches)
49 // resolve the branches now...
50 ResolveDefinitions(LateResolveValues);
51
52 Values.clear(); // Clear out method local definitions
53 CurrentModule = 0;
54 }
55} CurModule;
56
57static struct PerMethodInfo {
58 Method *CurrentMethod; // Pointer to current method being created
59
60 vector<ValueList> Values; // Keep track of numbered definitions
61 vector<ValueList> LateResolveValues;
62
63 inline PerMethodInfo() {
64 CurrentMethod = 0;
65 }
66
67 inline ~PerMethodInfo() {}
68
69 inline void MethodStart(Method *M) {
70 CurrentMethod = M;
71 }
72
73 void MethodDone() {
74 // If we could not resolve some blocks at parsing time (forward branches)
75 // resolve the branches now...
76 ResolveDefinitions(LateResolveValues);
77
78 Values.clear(); // Clear out method local definitions
79 CurrentMethod = 0;
80 }
81} CurMeth; // Info for the current method...
82
83
84//===----------------------------------------------------------------------===//
85// Code to handle definitions of all the types
86//===----------------------------------------------------------------------===//
87
88static void InsertValue(Value *D, vector<ValueList> &ValueTab = CurMeth.Values) {
89 if (!D->hasName()) { // Is this a numbered definition?
90 unsigned type = D->getType()->getUniqueID();
91 if (ValueTab.size() <= type)
92 ValueTab.resize(type+1, ValueList());
93 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
94 ValueTab[type].push_back(D);
95 }
96}
97
98static Value *getVal(const Type *Type, ValID &D,
99 bool DoNotImprovise = false) {
100 switch (D.Type) {
101 case 0: { // Is it a numbered definition?
102 unsigned type = Type->getUniqueID();
103 unsigned Num = (unsigned)D.Num;
104
105 // Module constants occupy the lowest numbered slots...
106 if (type < CurModule.Values.size()) {
107 if (Num < CurModule.Values[type].size())
108 return CurModule.Values[type][Num];
109
110 Num -= CurModule.Values[type].size();
111 }
112
113 // Make sure that our type is within bounds
114 if (CurMeth.Values.size() <= type)
115 break;
116
117 // Check that the number is within bounds...
118 if (CurMeth.Values[type].size() <= Num)
119 break;
120
121 return CurMeth.Values[type][Num];
122 }
123 case 1: { // Is it a named definition?
124 string Name(D.Name);
125 SymbolTable *SymTab = 0;
126 if (CurMeth.CurrentMethod)
127 SymTab = CurMeth.CurrentMethod->getSymbolTable();
128 Value *N = SymTab ? SymTab->lookup(Type, Name) : 0;
129
130 if (N == 0) {
131 SymTab = CurModule.CurrentModule->getSymbolTable();
132 if (SymTab)
133 N = SymTab->lookup(Type, Name);
134 if (N == 0) break;
135 }
136
137 D.destroy(); // Free old strdup'd memory...
138 return N;
139 }
140
141 case 2: // Is it a constant pool reference??
142 case 3: // Is it an unsigned const pool reference?
143 case 4:{ // Is it a string const pool reference?
144 ConstPoolVal *CPV = 0;
145
146 // Check to make sure that "Type" is an integral type, and that our
147 // value will fit into the specified type...
148 switch (D.Type) {
149 case 2:
150 if (Type == Type::BoolTy) { // Special handling for boolean data
151 CPV = new ConstPoolBool(D.ConstPool64 != 0);
152 } else {
153 if (!ConstPoolSInt::isValueValidForType(Type, D.ConstPool64))
154 ThrowException("Symbolic constant pool reference is invalid!");
155 CPV = new ConstPoolSInt(Type, D.ConstPool64);
156 }
157 break;
158 case 3:
159 if (!ConstPoolUInt::isValueValidForType(Type, D.UConstPool64)) {
160 if (!ConstPoolSInt::isValueValidForType(Type, D.ConstPool64)) {
161 ThrowException("Symbolic constant pool reference is invalid!");
162 } else { // This is really a signed reference. Transmogrify.
163 CPV = new ConstPoolSInt(Type, D.ConstPool64);
164 }
165 } else {
166 CPV = new ConstPoolUInt(Type, D.UConstPool64);
167 }
168 break;
169 case 4:
170 cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
171 abort();
172 //CPV = new ConstPoolString(D.Name);
173 D.destroy(); // Free the string memory
174 break;
175 }
176 assert(CPV && "How did we escape creating a constant??");
177
178 // Scan through the constant table and see if we already have loaded this
179 // constant.
180 //
181 ConstantPool &CP = CurMeth.CurrentMethod ?
182 CurMeth.CurrentMethod->getConstantPool() :
183 CurModule.CurrentModule->getConstantPool();
184 ConstPoolVal *C = CP.find(CPV); // Already have this constant?
185 if (C) {
186 delete CPV; // Didn't need this after all, oh well.
187 return C; // Yup, we already have one, recycle it!
188 }
189 CP.insert(CPV);
190
191 // Success, everything is kosher. Lets go!
192 return CPV;
193 } // End of case 2,3,4
194 } // End of switch
195
196
197 // If we reached here, we referenced either a symbol that we don't know about
198 // or an id number that hasn't been read yet. We may be referencing something
199 // forward, so just create an entry to be resolved later and get to it...
200 //
201 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
202
203 // TODO: Attempt to coallecse nodes that are the same with previous ones.
204 Value *d = 0;
205 switch (Type->getPrimitiveID()) {
206 case Type::LabelTyID: d = new BBPlaceHolder(Type, D); break;
207 case Type::MethodTyID:
208 d = new MethPlaceHolder(Type, D);
209 InsertValue(d, CurModule.LateResolveValues);
210 return d;
211//case Type::ClassTyID: d = new ClassPlaceHolder(Type, D); break;
212 default: d = new DefPlaceHolder(Type, D); break;
213 }
214
215 assert(d != 0 && "How did we not make something?");
216 InsertValue(d, CurMeth.LateResolveValues);
217 return d;
218}
219
220
221//===----------------------------------------------------------------------===//
222// Code to handle forward references in instructions
223//===----------------------------------------------------------------------===//
224//
225// This code handles the late binding needed with statements that reference
226// values not defined yet... for example, a forward branch, or the PHI node for
227// a loop body.
228//
229// This keeps a table (CurMeth.LateResolveValues) of all such forward references
230// and back patchs after we are done.
231//
232
233// ResolveDefinitions - If we could not resolve some defs at parsing
234// time (forward branches, phi functions for loops, etc...) resolve the
235// defs now...
236//
237static void ResolveDefinitions(vector<ValueList> &LateResolvers) {
238 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
239 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
240 while (!LateResolvers[ty].empty()) {
241 Value *V = LateResolvers[ty].back();
242 LateResolvers[ty].pop_back();
243 ValID &DID = getValIDFromPlaceHolder(V);
244
245 Value *TheRealValue = getVal(Type::getUniqueIDType(ty), DID, true);
246
247 if (TheRealValue == 0 && DID.Type == 1)
248 ThrowException("Reference to an invalid definition: '" +DID.getName() +
249 "' of type '" + V->getType()->getName() + "'");
250 else if (TheRealValue == 0)
251 ThrowException("Reference to an invalid definition: #" +itostr(DID.Num)+
252 " of type '" + V->getType()->getName() + "'");
253
254 V->replaceAllUsesWith(TheRealValue);
255 assert(V->use_empty());
256 delete V;
257 }
258 }
259
260 LateResolvers.clear();
261}
262
263// addConstValToConstantPool - This code is used to insert a constant into the
264// current constant pool. This is designed to make maximal (but not more than
265// possible) reuse (merging) of constants in the constant pool. This means that
266// multiple references to %4, for example will all get merged.
267//
268static ConstPoolVal *addConstValToConstantPool(ConstPoolVal *C) {
269 vector<ValueList> &ValTab = CurMeth.CurrentMethod ?
270 CurMeth.Values : CurModule.Values;
271 ConstantPool &CP = CurMeth.CurrentMethod ?
272 CurMeth.CurrentMethod->getConstantPool() :
273 CurModule.CurrentModule->getConstantPool();
274
275 if (ConstPoolVal *CPV = CP.find(C)) {
276 // Constant already in constant pool. Try to merge the two constants
277 if (CPV->hasName() && !C->hasName()) {
278 // Merge the two values, we inherit the existing CPV's name.
279 // InsertValue requires that the value have no name to insert correctly
280 // (because we want to fill the slot this constant would have filled)
281 //
282 string Name = CPV->getName();
283 CPV->setName("");
284 InsertValue(CPV, ValTab);
285 CPV->setName(Name);
286 delete C;
287 return CPV;
288 } else if (!CPV->hasName() && C->hasName()) {
289 // If we have a name on this value and there isn't one in the const
290 // pool val already, propogate it.
291 //
292 CPV->setName(C->getName());
293 delete C; // Sorry, you're toast
294 return CPV;
295 } else if (CPV->hasName() && C->hasName()) {
296 // Both values have distinct names. We cannot merge them.
297 CP.insert(C);
298 InsertValue(C, ValTab);
299 return C;
300 } else if (!CPV->hasName() && !C->hasName()) {
301 // Neither value has a name, trivially merge them.
302 InsertValue(CPV, ValTab);
303 delete C;
304 return CPV;
305 }
306
307 assert(0 && "Not reached!");
308 return 0;
309 } else { // No duplication of value.
310 CP.insert(C);
311 InsertValue(C, ValTab);
312 return C;
313 }
314}
315
316//===----------------------------------------------------------------------===//
317// RunVMAsmParser - Define an interface to this parser
318//===----------------------------------------------------------------------===//
319//
320Module *RunVMAsmParser(const ToolCommandLine &Opts, FILE *F) {
321 llvmAsmin = F;
322 CurOptions = &Opts;
323 llvmAsmlineno = 1; // Reset the current line number...
324
325 CurModule.CurrentModule = new Module(); // Allocate a new module to read
326 yyparse(); // Parse the file.
327 Module *Result = ParserResult;
328 CurOptions = 0;
329 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
330 ParserResult = 0;
331
332 return Result;
333}
334
335%}
336
337%union {
338 Module *ModuleVal;
339 Method *MethodVal;
340 MethodArgument *MethArgVal;
341 BasicBlock *BasicBlockVal;
342 TerminatorInst *TermInstVal;
343 Instruction *InstVal;
344 ConstPoolVal *ConstVal;
345 const Type *TypeVal;
346
347 list<MethodArgument*> *MethodArgList;
348 list<Value*> *ValueList;
349 list<const Type*> *TypeList;
Chris Lattnerc24d2082001-06-11 15:04:20 +0000350 list<pair<Value*, BasicBlock*> > *PHIList; // Represent the RHS of PHI node
Chris Lattner00950542001-06-06 20:29:01 +0000351 list<pair<ConstPoolVal*, BasicBlock*> > *JumpTable;
352 vector<ConstPoolVal*> *ConstVector;
353
354 int64_t SInt64Val;
355 uint64_t UInt64Val;
356 int SIntVal;
357 unsigned UIntVal;
358
359 char *StrVal; // This memory is allocated by strdup!
360 ValID ValIDVal; // May contain memory allocated by strdup
361
362 Instruction::UnaryOps UnaryOpVal;
363 Instruction::BinaryOps BinaryOpVal;
364 Instruction::TermOps TermOpVal;
365 Instruction::MemoryOps MemOpVal;
366}
367
368%type <ModuleVal> Module MethodList
369%type <MethodVal> Method MethodHeader BasicBlockList
370%type <BasicBlockVal> BasicBlock InstructionList
371%type <TermInstVal> BBTerminatorInst
372%type <InstVal> Inst InstVal MemoryInst
373%type <ConstVal> ConstVal
374%type <ConstVector> ConstVector
375%type <MethodArgList> ArgList ArgListH
376%type <MethArgVal> ArgVal
Chris Lattnerc24d2082001-06-11 15:04:20 +0000377%type <PHIList> PHIList
Chris Lattner00950542001-06-06 20:29:01 +0000378%type <ValueList> ValueRefList ValueRefListE
379%type <TypeList> TypeList
380%type <JumpTable> JumpTable
381
382%type <ValIDVal> ValueRef ConstValueRef // Reference to a definition or BB
383
384// Tokens and types for handling constant integer values
385//
386// ESINT64VAL - A negative number within long long range
387%token <SInt64Val> ESINT64VAL
388
389// EUINT64VAL - A positive number within uns. long long range
390%token <UInt64Val> EUINT64VAL
391%type <SInt64Val> EINT64VAL
392
393%token <SIntVal> SINTVAL // Signed 32 bit ints...
394%token <UIntVal> UINTVAL // Unsigned 32 bit ints...
395%type <SIntVal> INTVAL
396
397// Built in types...
398%type <TypeVal> Types TypesV SIntType UIntType IntType
399%token <TypeVal> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
400%token <TypeVal> FLOAT DOUBLE STRING TYPE LABEL
401
402%token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
403%type <StrVal> OptVAR_ID OptAssign
404
405
Chris Lattner09083092001-07-08 04:57:15 +0000406%token IMPLEMENTATION TRUE FALSE BEGINTOK END DECLARE TO
Chris Lattner00950542001-06-06 20:29:01 +0000407%token PHI CALL
408
409// Basic Block Terminating Operators
410%token <TermOpVal> RET BR SWITCH
411
412// Unary Operators
413%type <UnaryOpVal> UnaryOps // all the unary operators
Chris Lattner09083092001-07-08 04:57:15 +0000414%token <UnaryOpVal> NOT CAST
Chris Lattner00950542001-06-06 20:29:01 +0000415
416// Binary Operators
417%type <BinaryOpVal> BinaryOps // all the binary operators
418%token <BinaryOpVal> ADD SUB MUL DIV REM
419
420// Binary Comarators
421%token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE
422
423// Memory Instructions
424%token <MemoryOpVal> MALLOC ALLOCA FREE LOAD STORE GETFIELD PUTFIELD
425
426%start Module
427%%
428
429// Handle constant integer size restriction and conversion...
430//
431
432INTVAL : SINTVAL
433INTVAL : UINTVAL {
434 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
435 ThrowException("Value too large for type!");
436 $$ = (int32_t)$1;
437}
438
439
440EINT64VAL : ESINT64VAL // These have same type and can't cause problems...
441EINT64VAL : EUINT64VAL {
442 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
443 ThrowException("Value too large for type!");
444 $$ = (int64_t)$1;
445}
446
447// Types includes all predefined types... except void, because you can't do
448// anything with it except for certain specific things...
449//
450// User defined types are added latter...
451//
452Types : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
453Types : LONG | ULONG | FLOAT | DOUBLE | STRING | TYPE | LABEL
454
455// TypesV includes all of 'Types', but it also includes the void type.
456TypesV : Types | VOID
457
458// Operations that are notably excluded from this list include:
459// RET, BR, & SWITCH because they end basic blocks and are treated specially.
460//
Chris Lattner09083092001-07-08 04:57:15 +0000461UnaryOps : NOT
Chris Lattner00950542001-06-06 20:29:01 +0000462BinaryOps : ADD | SUB | MUL | DIV | REM
463BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
464
465// Valueine some types that allow classification if we only want a particular
466// thing...
467SIntType : LONG | INT | SHORT | SBYTE
468UIntType : ULONG | UINT | USHORT | UBYTE
469IntType : SIntType | UIntType
470
471OptAssign : VAR_ID '=' {
472 $$ = $1;
473 }
474 | /*empty*/ {
475 $$ = 0;
476 }
477
478ConstVal : SIntType EINT64VAL { // integral constants
479 if (!ConstPoolSInt::isValueValidForType($1, $2))
480 ThrowException("Constant value doesn't fit in type!");
481 $$ = new ConstPoolSInt($1, $2);
482 }
483 | UIntType EUINT64VAL { // integral constants
484 if (!ConstPoolUInt::isValueValidForType($1, $2))
485 ThrowException("Constant value doesn't fit in type!");
486 $$ = new ConstPoolUInt($1, $2);
487 }
488 | BOOL TRUE { // Boolean constants
489 $$ = new ConstPoolBool(true);
490 }
491 | BOOL FALSE { // Boolean constants
492 $$ = new ConstPoolBool(false);
493 }
494 | STRING STRINGCONSTANT { // String constants
495 cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
496 abort();
497 //$$ = new ConstPoolString($2);
498 free($2);
499 }
500 | TYPE Types { // Type constants
501 $$ = new ConstPoolType($2);
502 }
503 | '[' Types ']' '[' ConstVector ']' { // Nonempty array constant
504 // Verify all elements are correct type!
505 const ArrayType *AT = ArrayType::getArrayType($2);
506 for (unsigned i = 0; i < $5->size(); i++) {
507 if ($2 != (*$5)[i]->getType())
508 ThrowException("Element #" + utostr(i) + " is not of type '" +
509 $2->getName() + "' as required!\nIt is of type '" +
510 (*$5)[i]->getType()->getName() + "'.");
511 }
512
513 $$ = new ConstPoolArray(AT, *$5);
514 delete $5;
515 }
516 | '[' Types ']' '[' ']' { // Empty array constant
517 vector<ConstPoolVal*> Empty;
518 $$ = new ConstPoolArray(ArrayType::getArrayType($2), Empty);
519 }
520 | '[' EUINT64VAL 'x' Types ']' '[' ConstVector ']' {
521 // Verify all elements are correct type!
522 const ArrayType *AT = ArrayType::getArrayType($4, (int)$2);
523 if ($2 != $7->size())
524 ThrowException("Type mismatch: constant sized array initialized with " +
525 utostr($7->size()) + " arguments, but has size of " +
526 itostr((int)$2) + "!");
527
528 for (unsigned i = 0; i < $7->size(); i++) {
529 if ($4 != (*$7)[i]->getType())
530 ThrowException("Element #" + utostr(i) + " is not of type '" +
531 $4->getName() + "' as required!\nIt is of type '" +
532 (*$7)[i]->getType()->getName() + "'.");
533 }
534
535 $$ = new ConstPoolArray(AT, *$7);
536 delete $7;
537 }
538 | '[' EUINT64VAL 'x' Types ']' '[' ']' {
539 if ($2 != 0)
540 ThrowException("Type mismatch: constant sized array initialized with 0"
541 " arguments, but has size of " + itostr((int)$2) + "!");
542 vector<ConstPoolVal*> Empty;
543 $$ = new ConstPoolArray(ArrayType::getArrayType($4, 0), Empty);
544 }
545 | '{' TypeList '}' '{' ConstVector '}' {
546 StructType::ElementTypes Types($2->begin(), $2->end());
547 delete $2;
548
549 const StructType *St = StructType::getStructType(Types);
550 $$ = new ConstPoolStruct(St, *$5);
551 delete $5;
552 }
553 | '{' '}' '{' '}' {
554 const StructType *St =
555 StructType::getStructType(StructType::ElementTypes());
556 vector<ConstPoolVal*> Empty;
557 $$ = new ConstPoolStruct(St, Empty);
558 }
559/*
560 | Types '*' ConstVal {
561 assert(0);
562 $$ = 0;
563 }
564*/
565
566
567ConstVector : ConstVector ',' ConstVal {
568 ($$ = $1)->push_back(addConstValToConstantPool($3));
569 }
570 | ConstVal {
571 $$ = new vector<ConstPoolVal*>();
572 $$->push_back(addConstValToConstantPool($1));
573 }
574
575
576ConstPool : ConstPool OptAssign ConstVal {
577 if ($2) {
578 $3->setName($2);
579 free($2);
580 }
581
582 addConstValToConstantPool($3);
583 }
584 | /* empty: end of list */ {
585 }
586
587
588//===----------------------------------------------------------------------===//
589// Rules to match Modules
590//===----------------------------------------------------------------------===//
591
592// Module rule: Capture the result of parsing the whole file into a result
593// variable...
594//
595Module : MethodList {
596 $$ = ParserResult = $1;
597 CurModule.ModuleDone();
598}
599
600MethodList : MethodList Method {
601 $1->getMethodList().push_back($2);
602 CurMeth.MethodDone();
603 $$ = $1;
604 }
605 | ConstPool IMPLEMENTATION {
606 $$ = CurModule.CurrentModule;
607 }
608
609
610//===----------------------------------------------------------------------===//
611// Rules to match Method Headers
612//===----------------------------------------------------------------------===//
613
614OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; }
615
616ArgVal : Types OptVAR_ID {
617 $$ = new MethodArgument($1);
618 if ($2) { // Was the argument named?
619 $$->setName($2);
620 free($2); // The string was strdup'd, so free it now.
621 }
622}
623
624ArgListH : ArgVal ',' ArgListH {
625 $$ = $3;
626 $3->push_front($1);
627 }
628 | ArgVal {
629 $$ = new list<MethodArgument*>();
630 $$->push_front($1);
631 }
632
633ArgList : ArgListH {
634 $$ = $1;
635 }
636 | /* empty */ {
637 $$ = 0;
638 }
639
640MethodHeaderH : TypesV STRINGCONSTANT '(' ArgList ')' {
641 MethodType::ParamTypes ParamTypeList;
642 if ($4)
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000643 for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I)
Chris Lattner00950542001-06-06 20:29:01 +0000644 ParamTypeList.push_back((*I)->getType());
645
646 const MethodType *MT = MethodType::getMethodType($1, ParamTypeList);
647
648 Method *M = new Method(MT, $2);
649 free($2); // Free strdup'd memory!
650
651 InsertValue(M, CurModule.Values);
652
653 CurMeth.MethodStart(M);
654
655 // Add all of the arguments we parsed to the method...
656 if ($4) { // Is null if empty...
657 Method::ArgumentListType &ArgList = M->getArgumentList();
658
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000659 for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I) {
Chris Lattner00950542001-06-06 20:29:01 +0000660 InsertValue(*I);
661 ArgList.push_back(*I);
662 }
663 delete $4; // We're now done with the argument list
664 }
665}
666
667MethodHeader : MethodHeaderH ConstPool BEGINTOK {
668 $$ = CurMeth.CurrentMethod;
669}
670
671Method : BasicBlockList END {
672 $$ = $1;
673}
674
675
676//===----------------------------------------------------------------------===//
677// Rules to match Basic Blocks
678//===----------------------------------------------------------------------===//
679
680ConstValueRef : ESINT64VAL { // A reference to a direct constant
681 $$ = ValID::create($1);
682 }
683 | EUINT64VAL {
684 $$ = ValID::create($1);
685 }
686 | TRUE {
687 $$ = ValID::create((int64_t)1);
688 }
689 | FALSE {
690 $$ = ValID::create((int64_t)0);
691 }
692 | STRINGCONSTANT { // Quoted strings work too... especially for methods
693 $$ = ValID::create_conststr($1);
694 }
695
696// ValueRef - A reference to a definition...
697ValueRef : INTVAL { // Is it an integer reference...?
698 $$ = ValID::create($1);
699 }
700 | VAR_ID { // It must be a named reference then...
701 $$ = ValID::create($1);
702 }
703 | ConstValueRef {
704 $$ = $1;
705 }
706
707// The user may refer to a user defined type by its typeplane... check for this
708// now...
709//
710Types : ValueRef {
711 Value *D = getVal(Type::TypeTy, $1, true);
712 if (D == 0) ThrowException("Invalid user defined type: " + $1.getName());
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000713
714 // User defined type not in const pool!
715 ConstPoolType *CPT = (ConstPoolType*)D->castConstantAsserting();
Chris Lattner00950542001-06-06 20:29:01 +0000716 $$ = CPT->getValue();
717 }
718 | TypesV '(' TypeList ')' { // Method derived type?
719 MethodType::ParamTypes Params($3->begin(), $3->end());
720 delete $3;
721 $$ = MethodType::getMethodType($1, Params);
722 }
723 | TypesV '(' ')' { // Method derived type?
724 MethodType::ParamTypes Params; // Empty list
725 $$ = MethodType::getMethodType($1, Params);
726 }
727 | '[' Types ']' {
728 $$ = ArrayType::getArrayType($2);
729 }
730 | '[' EUINT64VAL 'x' Types ']' {
731 $$ = ArrayType::getArrayType($4, (int)$2);
732 }
733 | '{' TypeList '}' {
734 StructType::ElementTypes Elements($2->begin(), $2->end());
735 delete $2;
736 $$ = StructType::getStructType(Elements);
737 }
738 | '{' '}' {
739 $$ = StructType::getStructType(StructType::ElementTypes());
740 }
741 | Types '*' {
742 $$ = PointerType::getPointerType($1);
743 }
744
745
746TypeList : Types {
747 $$ = new list<const Type*>();
748 $$->push_back($1);
749 }
750 | TypeList ',' Types {
751 ($$=$1)->push_back($3);
752 }
753
754
755BasicBlockList : BasicBlockList BasicBlock {
756 $1->getBasicBlocks().push_back($2);
757 $$ = $1;
758 }
759 | MethodHeader BasicBlock { // Do not allow methods with 0 basic blocks
760 $$ = $1; // in them...
761 $1->getBasicBlocks().push_back($2);
762 }
763
764
765// Basic blocks are terminated by branching instructions:
766// br, br/cc, switch, ret
767//
768BasicBlock : InstructionList BBTerminatorInst {
769 $1->getInstList().push_back($2);
770 InsertValue($1);
771 $$ = $1;
772 }
773 | LABELSTR InstructionList BBTerminatorInst {
774 $2->getInstList().push_back($3);
775 $2->setName($1);
776 free($1); // Free the strdup'd memory...
777
778 InsertValue($2);
779 $$ = $2;
780 }
781
782InstructionList : InstructionList Inst {
783 $1->getInstList().push_back($2);
784 $$ = $1;
785 }
786 | /* empty */ {
787 $$ = new BasicBlock();
788 }
789
790BBTerminatorInst : RET Types ValueRef { // Return with a result...
791 $$ = new ReturnInst(getVal($2, $3));
792 }
793 | RET VOID { // Return with no result...
794 $$ = new ReturnInst();
795 }
796 | BR LABEL ValueRef { // Unconditional Branch...
797 $$ = new BranchInst((BasicBlock*)getVal(Type::LabelTy, $3));
798 } // Conditional Branch...
799 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
800 $$ = new BranchInst((BasicBlock*)getVal(Type::LabelTy, $6),
801 (BasicBlock*)getVal(Type::LabelTy, $9),
802 getVal(Type::BoolTy, $3));
803 }
804 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
805 SwitchInst *S = new SwitchInst(getVal($2, $3),
806 (BasicBlock*)getVal(Type::LabelTy, $6));
807 $$ = S;
808
809 list<pair<ConstPoolVal*, BasicBlock*> >::iterator I = $8->begin(),
810 end = $8->end();
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000811 for (; I != end; ++I)
Chris Lattner00950542001-06-06 20:29:01 +0000812 S->dest_push_back(I->first, I->second);
813 }
814
815JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
816 $$ = $1;
817 ConstPoolVal *V = (ConstPoolVal*)getVal($2, $3, true);
818 if (V == 0)
819 ThrowException("May only switch on a constant pool value!");
820
821 $$->push_back(make_pair(V, (BasicBlock*)getVal($5, $6)));
822 }
823 | IntType ConstValueRef ',' LABEL ValueRef {
824 $$ = new list<pair<ConstPoolVal*, BasicBlock*> >();
825 ConstPoolVal *V = (ConstPoolVal*)getVal($1, $2, true);
826
827 if (V == 0)
828 ThrowException("May only switch on a constant pool value!");
829
830 $$->push_back(make_pair(V, (BasicBlock*)getVal($4, $5)));
831 }
832
833Inst : OptAssign InstVal {
834 if ($1) // Is this definition named??
835 $2->setName($1); // if so, assign the name...
836
837 InsertValue($2);
838 $$ = $2;
839}
840
Chris Lattnerc24d2082001-06-11 15:04:20 +0000841PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
842 $$ = new list<pair<Value*, BasicBlock*> >();
843 $$->push_back(make_pair(getVal($1, $3),
844 (BasicBlock*)getVal(Type::LabelTy, $5)));
845 }
846 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
847 $$ = $1;
848 $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
849 (BasicBlock*)getVal(Type::LabelTy, $6)));
850 }
851
852
853ValueRefList : Types ValueRef { // Used for call statements...
Chris Lattner00950542001-06-06 20:29:01 +0000854 $$ = new list<Value*>();
855 $$->push_back(getVal($1, $2));
856 }
857 | ValueRefList ',' ValueRef {
858 $$ = $1;
859 $1->push_back(getVal($1->front()->getType(), $3));
860 }
861
862// ValueRefListE - Just like ValueRefList, except that it may also be empty!
863ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; }
864
865InstVal : BinaryOps Types ValueRef ',' ValueRef {
Chris Lattnerbebd60d2001-06-25 07:31:31 +0000866 $$ = BinaryOperator::create($1, getVal($2, $3), getVal($2, $5));
Chris Lattner00950542001-06-06 20:29:01 +0000867 if ($$ == 0)
868 ThrowException("binary operator returned null!");
869 }
870 | UnaryOps Types ValueRef {
Chris Lattnerbebd60d2001-06-25 07:31:31 +0000871 $$ = UnaryOperator::create($1, getVal($2, $3));
Chris Lattner00950542001-06-06 20:29:01 +0000872 if ($$ == 0)
873 ThrowException("unary operator returned null!");
Chris Lattner09083092001-07-08 04:57:15 +0000874 }
875 | CAST Types ValueRef TO Types {
876 $$ = UnaryOperator::create($1, getVal($2, $3), $5);
877 }
Chris Lattnerc24d2082001-06-11 15:04:20 +0000878 | PHI PHIList {
879 const Type *Ty = $2->front().first->getType();
880 $$ = new PHINode(Ty);
Chris Lattner00950542001-06-06 20:29:01 +0000881 while ($2->begin() != $2->end()) {
Chris Lattnerc24d2082001-06-11 15:04:20 +0000882 if ($2->front().first->getType() != Ty)
883 ThrowException("All elements of a PHI node must be of the same type!");
884 ((PHINode*)$$)->addIncoming($2->front().first, $2->front().second);
Chris Lattner00950542001-06-06 20:29:01 +0000885 $2->pop_front();
886 }
887 delete $2; // Free the list...
888 }
889 | CALL Types ValueRef '(' ValueRefListE ')' {
890 if (!$2->isMethodType())
891 ThrowException("Can only call methods: invalid type '" +
892 $2->getName() + "'!");
893
894 const MethodType *Ty = (const MethodType*)$2;
895
896 Value *V = getVal(Ty, $3);
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000897 if (!V->isMethod() || V->getType() != Ty)
Chris Lattner00950542001-06-06 20:29:01 +0000898 ThrowException("Cannot call: " + $3.getName() + "!");
899
900 // Create or access a new type that corresponds to the function call...
901 vector<Value *> Params;
902
903 if ($5) {
904 // Pull out just the arguments...
905 Params.insert(Params.begin(), $5->begin(), $5->end());
906 delete $5;
907
908 // Loop through MethodType's arguments and ensure they are specified
909 // correctly!
910 //
911 MethodType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
912 unsigned i;
913 for (i = 0; i < Params.size() && I != Ty->getParamTypes().end(); ++i,++I){
914 if (Params[i]->getType() != *I)
915 ThrowException("Parameter " + utostr(i) + " is not of type '" +
916 (*I)->getName() + "'!");
917 }
918
919 if (i != Params.size() || I != Ty->getParamTypes().end())
920 ThrowException("Invalid number of parameters detected!");
921 }
922
923 // Create the call node...
924 $$ = new CallInst((Method*)V, Params);
925 }
926 | MemoryInst {
927 $$ = $1;
928 }
929
930MemoryInst : MALLOC Types {
Chris Lattnerf0d0e9c2001-07-07 08:36:30 +0000931 const Type *Ty = PointerType::getPointerType($2);
932 addConstValToConstantPool(new ConstPoolType(Ty));
933 $$ = new MallocInst(Ty);
Chris Lattner00950542001-06-06 20:29:01 +0000934 }
935 | MALLOC Types ',' UINT ValueRef {
936 if (!$2->isArrayType() || ((const ArrayType*)$2)->isSized())
937 ThrowException("Trying to allocate " + $2->getName() +
938 " as unsized array!");
Chris Lattnerf0d0e9c2001-07-07 08:36:30 +0000939 const Type *Ty = PointerType::getPointerType($2);
940 addConstValToConstantPool(new ConstPoolType(Ty));
Chris Lattner00950542001-06-06 20:29:01 +0000941 Value *ArrSize = getVal($4, $5);
Chris Lattnerf0d0e9c2001-07-07 08:36:30 +0000942 $$ = new MallocInst(Ty, ArrSize);
Chris Lattner00950542001-06-06 20:29:01 +0000943 }
944 | ALLOCA Types {
Chris Lattnerf0d0e9c2001-07-07 08:36:30 +0000945 const Type *Ty = PointerType::getPointerType($2);
946 addConstValToConstantPool(new ConstPoolType(Ty));
947 $$ = new AllocaInst(Ty);
Chris Lattner00950542001-06-06 20:29:01 +0000948 }
949 | ALLOCA Types ',' UINT ValueRef {
950 if (!$2->isArrayType() || ((const ArrayType*)$2)->isSized())
951 ThrowException("Trying to allocate " + $2->getName() +
952 " as unsized array!");
Chris Lattnerf0d0e9c2001-07-07 08:36:30 +0000953 const Type *Ty = PointerType::getPointerType($2);
954 addConstValToConstantPool(new ConstPoolType(Ty));
Chris Lattner00950542001-06-06 20:29:01 +0000955 Value *ArrSize = getVal($4, $5);
Chris Lattnerf0d0e9c2001-07-07 08:36:30 +0000956 $$ = new AllocaInst(Ty, ArrSize);
Chris Lattner00950542001-06-06 20:29:01 +0000957 }
958 | FREE Types ValueRef {
959 if (!$2->isPointerType())
960 ThrowException("Trying to free nonpointer type " + $2->getName() + "!");
961 $$ = new FreeInst(getVal($2, $3));
962 }
963
964%%
Chris Lattner09083092001-07-08 04:57:15 +0000965int yyerror(const char *ErrorMsg) {
Chris Lattner00950542001-06-06 20:29:01 +0000966 ThrowException(string("Parse error: ") + ErrorMsg);
967 return 0;
968}