blob: fdfda7ef75cd3f0e1e661c7a3b2f76f3bfab44d4 [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
Chris Lattner8896eda2001-07-09 19:38:36 +000027#include <algorithm> // Get definition of find_if
Chris Lattner00950542001-06-06 20:29:01 +000028#include <stdio.h> // This embarasment is due to our flex lexer...
29
Chris Lattner09083092001-07-08 04:57:15 +000030int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
31int yylex(); // declaration" of xxx warnings.
Chris Lattner00950542001-06-06 20:29:01 +000032int yyparse();
33
34static Module *ParserResult;
35const ToolCommandLine *CurOptions = 0;
36
37// This contains info used when building the body of a method. It is destroyed
38// when the method is completed.
39//
40typedef vector<Value *> ValueList; // Numbered defs
41static void ResolveDefinitions(vector<ValueList> &LateResolvers);
42
43static struct PerModuleInfo {
44 Module *CurrentModule;
45 vector<ValueList> Values; // Module level numbered definitions
46 vector<ValueList> LateResolveValues;
47
48 void ModuleDone() {
49 // If we could not resolve some blocks at parsing time (forward branches)
50 // resolve the branches now...
51 ResolveDefinitions(LateResolveValues);
52
53 Values.clear(); // Clear out method local definitions
54 CurrentModule = 0;
55 }
56} CurModule;
57
58static struct PerMethodInfo {
59 Method *CurrentMethod; // Pointer to current method being created
60
61 vector<ValueList> Values; // Keep track of numbered definitions
62 vector<ValueList> LateResolveValues;
63
64 inline PerMethodInfo() {
65 CurrentMethod = 0;
66 }
67
68 inline ~PerMethodInfo() {}
69
70 inline void MethodStart(Method *M) {
71 CurrentMethod = M;
72 }
73
74 void MethodDone() {
75 // If we could not resolve some blocks at parsing time (forward branches)
76 // resolve the branches now...
77 ResolveDefinitions(LateResolveValues);
78
79 Values.clear(); // Clear out method local definitions
80 CurrentMethod = 0;
81 }
82} CurMeth; // Info for the current method...
83
84
85//===----------------------------------------------------------------------===//
86// Code to handle definitions of all the types
87//===----------------------------------------------------------------------===//
88
89static void InsertValue(Value *D, vector<ValueList> &ValueTab = CurMeth.Values) {
90 if (!D->hasName()) { // Is this a numbered definition?
91 unsigned type = D->getType()->getUniqueID();
92 if (ValueTab.size() <= type)
93 ValueTab.resize(type+1, ValueList());
94 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
95 ValueTab[type].push_back(D);
96 }
97}
98
99static Value *getVal(const Type *Type, ValID &D,
100 bool DoNotImprovise = false) {
101 switch (D.Type) {
102 case 0: { // Is it a numbered definition?
103 unsigned type = Type->getUniqueID();
104 unsigned Num = (unsigned)D.Num;
105
106 // Module constants occupy the lowest numbered slots...
107 if (type < CurModule.Values.size()) {
108 if (Num < CurModule.Values[type].size())
109 return CurModule.Values[type][Num];
110
111 Num -= CurModule.Values[type].size();
112 }
113
114 // Make sure that our type is within bounds
115 if (CurMeth.Values.size() <= type)
116 break;
117
118 // Check that the number is within bounds...
119 if (CurMeth.Values[type].size() <= Num)
120 break;
121
122 return CurMeth.Values[type][Num];
123 }
124 case 1: { // Is it a named definition?
125 string Name(D.Name);
126 SymbolTable *SymTab = 0;
127 if (CurMeth.CurrentMethod)
128 SymTab = CurMeth.CurrentMethod->getSymbolTable();
129 Value *N = SymTab ? SymTab->lookup(Type, Name) : 0;
130
131 if (N == 0) {
132 SymTab = CurModule.CurrentModule->getSymbolTable();
133 if (SymTab)
134 N = SymTab->lookup(Type, Name);
135 if (N == 0) break;
136 }
137
138 D.destroy(); // Free old strdup'd memory...
139 return N;
140 }
141
142 case 2: // Is it a constant pool reference??
143 case 3: // Is it an unsigned const pool reference?
Chris Lattner3d52b2f2001-07-15 00:17:01 +0000144 case 4: // Is it a string const pool reference?
145 case 5:{ // Is it a floating point const pool reference?
Chris Lattner00950542001-06-06 20:29:01 +0000146 ConstPoolVal *CPV = 0;
147
148 // Check to make sure that "Type" is an integral type, and that our
149 // value will fit into the specified type...
150 switch (D.Type) {
151 case 2:
152 if (Type == Type::BoolTy) { // Special handling for boolean data
153 CPV = new ConstPoolBool(D.ConstPool64 != 0);
154 } else {
155 if (!ConstPoolSInt::isValueValidForType(Type, D.ConstPool64))
Chris Lattner3d52b2f2001-07-15 00:17:01 +0000156 ThrowException("Symbolic constant pool value '" +
157 itostr(D.ConstPool64) + "' is invalid for type '" +
158 Type->getName() + "'!");
Chris Lattner00950542001-06-06 20:29:01 +0000159 CPV = new ConstPoolSInt(Type, D.ConstPool64);
160 }
161 break;
162 case 3:
163 if (!ConstPoolUInt::isValueValidForType(Type, D.UConstPool64)) {
164 if (!ConstPoolSInt::isValueValidForType(Type, D.ConstPool64)) {
Chris Lattner3d52b2f2001-07-15 00:17:01 +0000165 ThrowException("Integral constant pool reference is invalid!");
Chris Lattner00950542001-06-06 20:29:01 +0000166 } else { // This is really a signed reference. Transmogrify.
167 CPV = new ConstPoolSInt(Type, D.ConstPool64);
168 }
169 } else {
170 CPV = new ConstPoolUInt(Type, D.UConstPool64);
171 }
172 break;
173 case 4:
174 cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
175 abort();
176 //CPV = new ConstPoolString(D.Name);
177 D.destroy(); // Free the string memory
178 break;
Chris Lattner3d52b2f2001-07-15 00:17:01 +0000179 case 5:
180 if (!ConstPoolFP::isValueValidForType(Type, D.ConstPoolFP))
181 ThrowException("FP constant invalid for type!!");
182 else
183 CPV = new ConstPoolFP(Type, D.ConstPoolFP);
184 break;
Chris Lattner00950542001-06-06 20:29:01 +0000185 }
186 assert(CPV && "How did we escape creating a constant??");
187
188 // Scan through the constant table and see if we already have loaded this
189 // constant.
190 //
191 ConstantPool &CP = CurMeth.CurrentMethod ?
192 CurMeth.CurrentMethod->getConstantPool() :
193 CurModule.CurrentModule->getConstantPool();
194 ConstPoolVal *C = CP.find(CPV); // Already have this constant?
195 if (C) {
196 delete CPV; // Didn't need this after all, oh well.
197 return C; // Yup, we already have one, recycle it!
198 }
199 CP.insert(CPV);
200
201 // Success, everything is kosher. Lets go!
202 return CPV;
203 } // End of case 2,3,4
204 } // End of switch
205
206
207 // If we reached here, we referenced either a symbol that we don't know about
208 // or an id number that hasn't been read yet. We may be referencing something
209 // forward, so just create an entry to be resolved later and get to it...
210 //
211 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
212
213 // TODO: Attempt to coallecse nodes that are the same with previous ones.
214 Value *d = 0;
215 switch (Type->getPrimitiveID()) {
216 case Type::LabelTyID: d = new BBPlaceHolder(Type, D); break;
217 case Type::MethodTyID:
218 d = new MethPlaceHolder(Type, D);
219 InsertValue(d, CurModule.LateResolveValues);
220 return d;
221//case Type::ClassTyID: d = new ClassPlaceHolder(Type, D); break;
222 default: d = new DefPlaceHolder(Type, D); break;
223 }
224
225 assert(d != 0 && "How did we not make something?");
226 InsertValue(d, CurMeth.LateResolveValues);
227 return d;
228}
229
230
231//===----------------------------------------------------------------------===//
232// Code to handle forward references in instructions
233//===----------------------------------------------------------------------===//
234//
235// This code handles the late binding needed with statements that reference
236// values not defined yet... for example, a forward branch, or the PHI node for
237// a loop body.
238//
239// This keeps a table (CurMeth.LateResolveValues) of all such forward references
240// and back patchs after we are done.
241//
242
243// ResolveDefinitions - If we could not resolve some defs at parsing
244// time (forward branches, phi functions for loops, etc...) resolve the
245// defs now...
246//
247static void ResolveDefinitions(vector<ValueList> &LateResolvers) {
248 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
249 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
250 while (!LateResolvers[ty].empty()) {
251 Value *V = LateResolvers[ty].back();
252 LateResolvers[ty].pop_back();
253 ValID &DID = getValIDFromPlaceHolder(V);
254
255 Value *TheRealValue = getVal(Type::getUniqueIDType(ty), DID, true);
256
257 if (TheRealValue == 0 && DID.Type == 1)
258 ThrowException("Reference to an invalid definition: '" +DID.getName() +
259 "' of type '" + V->getType()->getName() + "'");
260 else if (TheRealValue == 0)
261 ThrowException("Reference to an invalid definition: #" +itostr(DID.Num)+
262 " of type '" + V->getType()->getName() + "'");
263
264 V->replaceAllUsesWith(TheRealValue);
265 assert(V->use_empty());
266 delete V;
267 }
268 }
269
270 LateResolvers.clear();
271}
272
273// addConstValToConstantPool - This code is used to insert a constant into the
274// current constant pool. This is designed to make maximal (but not more than
275// possible) reuse (merging) of constants in the constant pool. This means that
276// multiple references to %4, for example will all get merged.
277//
278static ConstPoolVal *addConstValToConstantPool(ConstPoolVal *C) {
279 vector<ValueList> &ValTab = CurMeth.CurrentMethod ?
280 CurMeth.Values : CurModule.Values;
281 ConstantPool &CP = CurMeth.CurrentMethod ?
282 CurMeth.CurrentMethod->getConstantPool() :
283 CurModule.CurrentModule->getConstantPool();
284
285 if (ConstPoolVal *CPV = CP.find(C)) {
286 // Constant already in constant pool. Try to merge the two constants
287 if (CPV->hasName() && !C->hasName()) {
288 // Merge the two values, we inherit the existing CPV's name.
289 // InsertValue requires that the value have no name to insert correctly
290 // (because we want to fill the slot this constant would have filled)
291 //
292 string Name = CPV->getName();
293 CPV->setName("");
294 InsertValue(CPV, ValTab);
295 CPV->setName(Name);
296 delete C;
297 return CPV;
298 } else if (!CPV->hasName() && C->hasName()) {
299 // If we have a name on this value and there isn't one in the const
300 // pool val already, propogate it.
301 //
302 CPV->setName(C->getName());
303 delete C; // Sorry, you're toast
304 return CPV;
305 } else if (CPV->hasName() && C->hasName()) {
306 // Both values have distinct names. We cannot merge them.
307 CP.insert(C);
308 InsertValue(C, ValTab);
309 return C;
310 } else if (!CPV->hasName() && !C->hasName()) {
311 // Neither value has a name, trivially merge them.
312 InsertValue(CPV, ValTab);
313 delete C;
314 return CPV;
315 }
316
317 assert(0 && "Not reached!");
318 return 0;
319 } else { // No duplication of value.
320 CP.insert(C);
321 InsertValue(C, ValTab);
322 return C;
323 }
324}
325
Chris Lattner8896eda2001-07-09 19:38:36 +0000326
327struct EqualsType {
328 const Type *T;
329 inline EqualsType(const Type *t) { T = t; }
330 inline bool operator()(const ConstPoolVal *CPV) const {
331 return static_cast<const ConstPoolType*>(CPV)->getValue() == T;
332 }
333};
334
335
336// checkNewType - We have to be careful to add all types referenced by the
337// program to the constant pool of the method or module. Because of this, we
338// often want to check to make sure that types used are in the constant pool,
339// and add them if they aren't. That's what this function does.
340//
341static const Type *checkNewType(const Type *Ty) {
342 ConstantPool &CP = CurMeth.CurrentMethod ?
343 CurMeth.CurrentMethod->getConstantPool() :
344 CurModule.CurrentModule->getConstantPool();
345
346 // Get the type type plane...
347 ConstantPool::PlaneType &P = CP.getPlane(Type::TypeTy);
348 ConstantPool::PlaneType::const_iterator PI = find_if(P.begin(), P.end(),
349 EqualsType(Ty));
350 if (PI == P.end()) {
351 vector<ValueList> &ValTab = CurMeth.CurrentMethod ?
352 CurMeth.Values : CurModule.Values;
353 ConstPoolVal *CPT = new ConstPoolType(Ty);
354 CP.insert(CPT);
355 InsertValue(CPT, ValTab);
356 }
357 return Ty;
358}
359
360
Chris Lattner00950542001-06-06 20:29:01 +0000361//===----------------------------------------------------------------------===//
362// RunVMAsmParser - Define an interface to this parser
363//===----------------------------------------------------------------------===//
364//
365Module *RunVMAsmParser(const ToolCommandLine &Opts, FILE *F) {
366 llvmAsmin = F;
367 CurOptions = &Opts;
368 llvmAsmlineno = 1; // Reset the current line number...
369
370 CurModule.CurrentModule = new Module(); // Allocate a new module to read
371 yyparse(); // Parse the file.
372 Module *Result = ParserResult;
373 CurOptions = 0;
374 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
375 ParserResult = 0;
376
377 return Result;
378}
379
380%}
381
382%union {
383 Module *ModuleVal;
384 Method *MethodVal;
385 MethodArgument *MethArgVal;
386 BasicBlock *BasicBlockVal;
387 TerminatorInst *TermInstVal;
388 Instruction *InstVal;
389 ConstPoolVal *ConstVal;
390 const Type *TypeVal;
391
392 list<MethodArgument*> *MethodArgList;
393 list<Value*> *ValueList;
394 list<const Type*> *TypeList;
Chris Lattnerc24d2082001-06-11 15:04:20 +0000395 list<pair<Value*, BasicBlock*> > *PHIList; // Represent the RHS of PHI node
Chris Lattner00950542001-06-06 20:29:01 +0000396 list<pair<ConstPoolVal*, BasicBlock*> > *JumpTable;
397 vector<ConstPoolVal*> *ConstVector;
398
399 int64_t SInt64Val;
400 uint64_t UInt64Val;
401 int SIntVal;
402 unsigned UIntVal;
Chris Lattner3d52b2f2001-07-15 00:17:01 +0000403 double FPVal;
Chris Lattner00950542001-06-06 20:29:01 +0000404
405 char *StrVal; // This memory is allocated by strdup!
406 ValID ValIDVal; // May contain memory allocated by strdup
407
408 Instruction::UnaryOps UnaryOpVal;
409 Instruction::BinaryOps BinaryOpVal;
410 Instruction::TermOps TermOpVal;
411 Instruction::MemoryOps MemOpVal;
Chris Lattner027dcc52001-07-08 21:10:27 +0000412 Instruction::OtherOps OtherOpVal;
Chris Lattner00950542001-06-06 20:29:01 +0000413}
414
415%type <ModuleVal> Module MethodList
416%type <MethodVal> Method MethodHeader BasicBlockList
417%type <BasicBlockVal> BasicBlock InstructionList
418%type <TermInstVal> BBTerminatorInst
419%type <InstVal> Inst InstVal MemoryInst
420%type <ConstVal> ConstVal
Chris Lattner027dcc52001-07-08 21:10:27 +0000421%type <ConstVector> ConstVector UByteList
Chris Lattner00950542001-06-06 20:29:01 +0000422%type <MethodArgList> ArgList ArgListH
423%type <MethArgVal> ArgVal
Chris Lattnerc24d2082001-06-11 15:04:20 +0000424%type <PHIList> PHIList
Chris Lattnerab5ac6b2001-07-08 23:22:50 +0000425%type <ValueList> ValueRefList ValueRefListE // For call param lists
Chris Lattner00950542001-06-06 20:29:01 +0000426%type <TypeList> TypeList
427%type <JumpTable> JumpTable
428
429%type <ValIDVal> ValueRef ConstValueRef // Reference to a definition or BB
430
431// Tokens and types for handling constant integer values
432//
433// ESINT64VAL - A negative number within long long range
434%token <SInt64Val> ESINT64VAL
435
436// EUINT64VAL - A positive number within uns. long long range
437%token <UInt64Val> EUINT64VAL
438%type <SInt64Val> EINT64VAL
439
440%token <SIntVal> SINTVAL // Signed 32 bit ints...
441%token <UIntVal> UINTVAL // Unsigned 32 bit ints...
442%type <SIntVal> INTVAL
Chris Lattner3d52b2f2001-07-15 00:17:01 +0000443%token <FPVal> FPVAL // Float or Double constant
Chris Lattner00950542001-06-06 20:29:01 +0000444
445// Built in types...
Chris Lattner3d52b2f2001-07-15 00:17:01 +0000446%type <TypeVal> Types TypesV SIntType UIntType IntType FPType
Chris Lattner00950542001-06-06 20:29:01 +0000447%token <TypeVal> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
448%token <TypeVal> FLOAT DOUBLE STRING TYPE LABEL
449
450%token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
451%type <StrVal> OptVAR_ID OptAssign
452
453
Chris Lattner09083092001-07-08 04:57:15 +0000454%token IMPLEMENTATION TRUE FALSE BEGINTOK END DECLARE TO
Chris Lattner00950542001-06-06 20:29:01 +0000455
456// Basic Block Terminating Operators
457%token <TermOpVal> RET BR SWITCH
458
459// Unary Operators
460%type <UnaryOpVal> UnaryOps // all the unary operators
Chris Lattner71496b32001-07-08 19:03:27 +0000461%token <UnaryOpVal> NOT
Chris Lattner00950542001-06-06 20:29:01 +0000462
463// Binary Operators
464%type <BinaryOpVal> BinaryOps // all the binary operators
465%token <BinaryOpVal> ADD SUB MUL DIV REM
Chris Lattner027dcc52001-07-08 21:10:27 +0000466%token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
Chris Lattner00950542001-06-06 20:29:01 +0000467
468// Memory Instructions
Chris Lattnerab5ac6b2001-07-08 23:22:50 +0000469%token <MemoryOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
Chris Lattner00950542001-06-06 20:29:01 +0000470
Chris Lattner027dcc52001-07-08 21:10:27 +0000471// Other Operators
472%type <OtherOpVal> ShiftOps
473%token <OtherOpVal> PHI CALL CAST SHL SHR
474
Chris Lattner00950542001-06-06 20:29:01 +0000475%start Module
476%%
477
478// Handle constant integer size restriction and conversion...
479//
480
481INTVAL : SINTVAL
482INTVAL : UINTVAL {
483 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
484 ThrowException("Value too large for type!");
485 $$ = (int32_t)$1;
486}
487
488
489EINT64VAL : ESINT64VAL // These have same type and can't cause problems...
490EINT64VAL : EUINT64VAL {
491 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
492 ThrowException("Value too large for type!");
493 $$ = (int64_t)$1;
494}
495
496// Types includes all predefined types... except void, because you can't do
497// anything with it except for certain specific things...
498//
Chris Lattnere98dda62001-07-14 06:10:16 +0000499// User defined types are added later...
Chris Lattner00950542001-06-06 20:29:01 +0000500//
501Types : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
502Types : LONG | ULONG | FLOAT | DOUBLE | STRING | TYPE | LABEL
503
504// TypesV includes all of 'Types', but it also includes the void type.
505TypesV : Types | VOID
506
507// Operations that are notably excluded from this list include:
508// RET, BR, & SWITCH because they end basic blocks and are treated specially.
509//
Chris Lattner09083092001-07-08 04:57:15 +0000510UnaryOps : NOT
Chris Lattner00950542001-06-06 20:29:01 +0000511BinaryOps : ADD | SUB | MUL | DIV | REM
512BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
Chris Lattner027dcc52001-07-08 21:10:27 +0000513ShiftOps : SHL | SHR
Chris Lattner00950542001-06-06 20:29:01 +0000514
Chris Lattnere98dda62001-07-14 06:10:16 +0000515// These are some types that allow classification if we only want a particular
516// thing... for example, only a signed, unsigned, or integral type.
Chris Lattner00950542001-06-06 20:29:01 +0000517SIntType : LONG | INT | SHORT | SBYTE
518UIntType : ULONG | UINT | USHORT | UBYTE
519IntType : SIntType | UIntType
Chris Lattner3d52b2f2001-07-15 00:17:01 +0000520FPType : FLOAT | DOUBLE
Chris Lattner00950542001-06-06 20:29:01 +0000521
Chris Lattnere98dda62001-07-14 06:10:16 +0000522// OptAssign - Value producing statements have an optional assignment component
Chris Lattner00950542001-06-06 20:29:01 +0000523OptAssign : VAR_ID '=' {
524 $$ = $1;
525 }
526 | /*empty*/ {
527 $$ = 0;
528 }
529
Chris Lattnere98dda62001-07-14 06:10:16 +0000530// ConstVal - The various declarations that go into the constant pool. This
531// includes all forward declarations of types, constants, and functions.
532//
Chris Lattner00950542001-06-06 20:29:01 +0000533ConstVal : SIntType EINT64VAL { // integral constants
534 if (!ConstPoolSInt::isValueValidForType($1, $2))
535 ThrowException("Constant value doesn't fit in type!");
536 $$ = new ConstPoolSInt($1, $2);
537 }
538 | UIntType EUINT64VAL { // integral constants
539 if (!ConstPoolUInt::isValueValidForType($1, $2))
540 ThrowException("Constant value doesn't fit in type!");
541 $$ = new ConstPoolUInt($1, $2);
542 }
543 | BOOL TRUE { // Boolean constants
544 $$ = new ConstPoolBool(true);
545 }
546 | BOOL FALSE { // Boolean constants
547 $$ = new ConstPoolBool(false);
548 }
Chris Lattner3d52b2f2001-07-15 00:17:01 +0000549 | FPType FPVAL { // Float & Double constants
550 $$ = new ConstPoolFP($1, $2);
551 }
Chris Lattner00950542001-06-06 20:29:01 +0000552 | STRING STRINGCONSTANT { // String constants
553 cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
554 abort();
555 //$$ = new ConstPoolString($2);
556 free($2);
557 }
558 | TYPE Types { // Type constants
559 $$ = new ConstPoolType($2);
560 }
561 | '[' Types ']' '[' ConstVector ']' { // Nonempty array constant
562 // Verify all elements are correct type!
563 const ArrayType *AT = ArrayType::getArrayType($2);
564 for (unsigned i = 0; i < $5->size(); i++) {
565 if ($2 != (*$5)[i]->getType())
566 ThrowException("Element #" + utostr(i) + " is not of type '" +
567 $2->getName() + "' as required!\nIt is of type '" +
568 (*$5)[i]->getType()->getName() + "'.");
569 }
570
571 $$ = new ConstPoolArray(AT, *$5);
572 delete $5;
573 }
574 | '[' Types ']' '[' ']' { // Empty array constant
575 vector<ConstPoolVal*> Empty;
576 $$ = new ConstPoolArray(ArrayType::getArrayType($2), Empty);
577 }
578 | '[' EUINT64VAL 'x' Types ']' '[' ConstVector ']' {
579 // Verify all elements are correct type!
580 const ArrayType *AT = ArrayType::getArrayType($4, (int)$2);
581 if ($2 != $7->size())
582 ThrowException("Type mismatch: constant sized array initialized with " +
583 utostr($7->size()) + " arguments, but has size of " +
584 itostr((int)$2) + "!");
585
586 for (unsigned i = 0; i < $7->size(); i++) {
587 if ($4 != (*$7)[i]->getType())
588 ThrowException("Element #" + utostr(i) + " is not of type '" +
589 $4->getName() + "' as required!\nIt is of type '" +
590 (*$7)[i]->getType()->getName() + "'.");
591 }
592
593 $$ = new ConstPoolArray(AT, *$7);
594 delete $7;
595 }
596 | '[' EUINT64VAL 'x' Types ']' '[' ']' {
597 if ($2 != 0)
598 ThrowException("Type mismatch: constant sized array initialized with 0"
599 " arguments, but has size of " + itostr((int)$2) + "!");
600 vector<ConstPoolVal*> Empty;
601 $$ = new ConstPoolArray(ArrayType::getArrayType($4, 0), Empty);
602 }
603 | '{' TypeList '}' '{' ConstVector '}' {
604 StructType::ElementTypes Types($2->begin(), $2->end());
605 delete $2;
606
607 const StructType *St = StructType::getStructType(Types);
608 $$ = new ConstPoolStruct(St, *$5);
609 delete $5;
610 }
611 | '{' '}' '{' '}' {
612 const StructType *St =
613 StructType::getStructType(StructType::ElementTypes());
614 vector<ConstPoolVal*> Empty;
615 $$ = new ConstPoolStruct(St, Empty);
616 }
617/*
618 | Types '*' ConstVal {
619 assert(0);
620 $$ = 0;
621 }
622*/
623
Chris Lattnere98dda62001-07-14 06:10:16 +0000624// ConstVector - A list of comma seperated constants.
Chris Lattner00950542001-06-06 20:29:01 +0000625ConstVector : ConstVector ',' ConstVal {
626 ($$ = $1)->push_back(addConstValToConstantPool($3));
627 }
628 | ConstVal {
629 $$ = new vector<ConstPoolVal*>();
630 $$->push_back(addConstValToConstantPool($1));
631 }
632
Chris Lattnere98dda62001-07-14 06:10:16 +0000633//ExternMethodDecl : EXTERNAL TypesV '(' TypeList ')' {
634// }
635//ExternVarDecl :
Chris Lattner00950542001-06-06 20:29:01 +0000636
Chris Lattnere98dda62001-07-14 06:10:16 +0000637// ConstPool - Constants with optional names assigned to them.
Chris Lattner00950542001-06-06 20:29:01 +0000638ConstPool : ConstPool OptAssign ConstVal {
639 if ($2) {
640 $3->setName($2);
641 free($2);
642 }
643
644 addConstValToConstantPool($3);
645 }
Chris Lattnere98dda62001-07-14 06:10:16 +0000646/*
647 | ConstPool OptAssign GlobalDecl { // Global declarations appear in CP
648 if ($2) {
649 $3->setName($2);
650 free($2);
651 }
652 //CurModule.CurrentModule->
653 }
654*/
Chris Lattner00950542001-06-06 20:29:01 +0000655 | /* empty: end of list */ {
656 }
657
658
659//===----------------------------------------------------------------------===//
660// Rules to match Modules
661//===----------------------------------------------------------------------===//
662
663// Module rule: Capture the result of parsing the whole file into a result
664// variable...
665//
666Module : MethodList {
667 $$ = ParserResult = $1;
668 CurModule.ModuleDone();
669}
670
Chris Lattnere98dda62001-07-14 06:10:16 +0000671// MethodList - A list of methods, preceeded by a constant pool.
672//
Chris Lattner00950542001-06-06 20:29:01 +0000673MethodList : MethodList Method {
674 $1->getMethodList().push_back($2);
675 CurMeth.MethodDone();
676 $$ = $1;
677 }
678 | ConstPool IMPLEMENTATION {
679 $$ = CurModule.CurrentModule;
680 }
681
682
683//===----------------------------------------------------------------------===//
684// Rules to match Method Headers
685//===----------------------------------------------------------------------===//
686
687OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; }
688
689ArgVal : Types OptVAR_ID {
690 $$ = new MethodArgument($1);
691 if ($2) { // Was the argument named?
692 $$->setName($2);
693 free($2); // The string was strdup'd, so free it now.
694 }
695}
696
697ArgListH : ArgVal ',' ArgListH {
698 $$ = $3;
699 $3->push_front($1);
700 }
701 | ArgVal {
702 $$ = new list<MethodArgument*>();
703 $$->push_front($1);
704 }
705
706ArgList : ArgListH {
707 $$ = $1;
708 }
709 | /* empty */ {
710 $$ = 0;
711 }
712
713MethodHeaderH : TypesV STRINGCONSTANT '(' ArgList ')' {
714 MethodType::ParamTypes ParamTypeList;
715 if ($4)
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000716 for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I)
Chris Lattner00950542001-06-06 20:29:01 +0000717 ParamTypeList.push_back((*I)->getType());
718
719 const MethodType *MT = MethodType::getMethodType($1, ParamTypeList);
720
721 Method *M = new Method(MT, $2);
722 free($2); // Free strdup'd memory!
723
724 InsertValue(M, CurModule.Values);
725
726 CurMeth.MethodStart(M);
727
728 // Add all of the arguments we parsed to the method...
729 if ($4) { // Is null if empty...
730 Method::ArgumentListType &ArgList = M->getArgumentList();
731
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000732 for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I) {
Chris Lattner00950542001-06-06 20:29:01 +0000733 InsertValue(*I);
734 ArgList.push_back(*I);
735 }
736 delete $4; // We're now done with the argument list
737 }
738}
739
740MethodHeader : MethodHeaderH ConstPool BEGINTOK {
741 $$ = CurMeth.CurrentMethod;
742}
743
744Method : BasicBlockList END {
745 $$ = $1;
746}
747
748
749//===----------------------------------------------------------------------===//
750// Rules to match Basic Blocks
751//===----------------------------------------------------------------------===//
752
753ConstValueRef : ESINT64VAL { // A reference to a direct constant
754 $$ = ValID::create($1);
755 }
756 | EUINT64VAL {
757 $$ = ValID::create($1);
758 }
Chris Lattner3d52b2f2001-07-15 00:17:01 +0000759 | FPVAL { // Perhaps it's an FP constant?
760 $$ = ValID::create($1);
761 }
Chris Lattner00950542001-06-06 20:29:01 +0000762 | TRUE {
763 $$ = ValID::create((int64_t)1);
764 }
765 | FALSE {
766 $$ = ValID::create((int64_t)0);
767 }
768 | STRINGCONSTANT { // Quoted strings work too... especially for methods
769 $$ = ValID::create_conststr($1);
770 }
771
772// ValueRef - A reference to a definition...
773ValueRef : INTVAL { // Is it an integer reference...?
774 $$ = ValID::create($1);
775 }
Chris Lattner3d52b2f2001-07-15 00:17:01 +0000776 | VAR_ID { // Is it a named reference...?
Chris Lattner00950542001-06-06 20:29:01 +0000777 $$ = ValID::create($1);
778 }
779 | ConstValueRef {
780 $$ = $1;
781 }
782
783// The user may refer to a user defined type by its typeplane... check for this
784// now...
785//
786Types : ValueRef {
787 Value *D = getVal(Type::TypeTy, $1, true);
788 if (D == 0) ThrowException("Invalid user defined type: " + $1.getName());
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000789
790 // User defined type not in const pool!
791 ConstPoolType *CPT = (ConstPoolType*)D->castConstantAsserting();
Chris Lattner00950542001-06-06 20:29:01 +0000792 $$ = CPT->getValue();
793 }
794 | TypesV '(' TypeList ')' { // Method derived type?
795 MethodType::ParamTypes Params($3->begin(), $3->end());
796 delete $3;
Chris Lattner8896eda2001-07-09 19:38:36 +0000797 $$ = checkNewType(MethodType::getMethodType($1, Params));
Chris Lattner00950542001-06-06 20:29:01 +0000798 }
799 | TypesV '(' ')' { // Method derived type?
800 MethodType::ParamTypes Params; // Empty list
Chris Lattner8896eda2001-07-09 19:38:36 +0000801 $$ = checkNewType(MethodType::getMethodType($1, Params));
Chris Lattner00950542001-06-06 20:29:01 +0000802 }
803 | '[' Types ']' {
Chris Lattner8896eda2001-07-09 19:38:36 +0000804 $$ = checkNewType(ArrayType::getArrayType($2));
Chris Lattner00950542001-06-06 20:29:01 +0000805 }
806 | '[' EUINT64VAL 'x' Types ']' {
Chris Lattner8896eda2001-07-09 19:38:36 +0000807 $$ = checkNewType(ArrayType::getArrayType($4, (int)$2));
Chris Lattner00950542001-06-06 20:29:01 +0000808 }
809 | '{' TypeList '}' {
810 StructType::ElementTypes Elements($2->begin(), $2->end());
811 delete $2;
Chris Lattner8896eda2001-07-09 19:38:36 +0000812 $$ = checkNewType(StructType::getStructType(Elements));
Chris Lattner00950542001-06-06 20:29:01 +0000813 }
814 | '{' '}' {
Chris Lattner8896eda2001-07-09 19:38:36 +0000815 $$ = checkNewType(StructType::getStructType(StructType::ElementTypes()));
Chris Lattner00950542001-06-06 20:29:01 +0000816 }
817 | Types '*' {
Chris Lattner8896eda2001-07-09 19:38:36 +0000818 $$ = checkNewType(PointerType::getPointerType($1));
Chris Lattner00950542001-06-06 20:29:01 +0000819 }
820
821
822TypeList : Types {
823 $$ = new list<const Type*>();
824 $$->push_back($1);
825 }
826 | TypeList ',' Types {
827 ($$=$1)->push_back($3);
828 }
829
830
831BasicBlockList : BasicBlockList BasicBlock {
832 $1->getBasicBlocks().push_back($2);
833 $$ = $1;
834 }
835 | MethodHeader BasicBlock { // Do not allow methods with 0 basic blocks
836 $$ = $1; // in them...
837 $1->getBasicBlocks().push_back($2);
838 }
839
840
841// Basic blocks are terminated by branching instructions:
842// br, br/cc, switch, ret
843//
844BasicBlock : InstructionList BBTerminatorInst {
845 $1->getInstList().push_back($2);
846 InsertValue($1);
847 $$ = $1;
848 }
849 | LABELSTR InstructionList BBTerminatorInst {
850 $2->getInstList().push_back($3);
851 $2->setName($1);
852 free($1); // Free the strdup'd memory...
853
854 InsertValue($2);
855 $$ = $2;
856 }
857
858InstructionList : InstructionList Inst {
859 $1->getInstList().push_back($2);
860 $$ = $1;
861 }
862 | /* empty */ {
863 $$ = new BasicBlock();
864 }
865
866BBTerminatorInst : RET Types ValueRef { // Return with a result...
867 $$ = new ReturnInst(getVal($2, $3));
868 }
869 | RET VOID { // Return with no result...
870 $$ = new ReturnInst();
871 }
872 | BR LABEL ValueRef { // Unconditional Branch...
873 $$ = new BranchInst((BasicBlock*)getVal(Type::LabelTy, $3));
874 } // Conditional Branch...
875 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
876 $$ = new BranchInst((BasicBlock*)getVal(Type::LabelTy, $6),
877 (BasicBlock*)getVal(Type::LabelTy, $9),
878 getVal(Type::BoolTy, $3));
879 }
880 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
881 SwitchInst *S = new SwitchInst(getVal($2, $3),
882 (BasicBlock*)getVal(Type::LabelTy, $6));
883 $$ = S;
884
885 list<pair<ConstPoolVal*, BasicBlock*> >::iterator I = $8->begin(),
886 end = $8->end();
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000887 for (; I != end; ++I)
Chris Lattner00950542001-06-06 20:29:01 +0000888 S->dest_push_back(I->first, I->second);
889 }
890
891JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
892 $$ = $1;
893 ConstPoolVal *V = (ConstPoolVal*)getVal($2, $3, true);
894 if (V == 0)
895 ThrowException("May only switch on a constant pool value!");
896
897 $$->push_back(make_pair(V, (BasicBlock*)getVal($5, $6)));
898 }
899 | IntType ConstValueRef ',' LABEL ValueRef {
900 $$ = new list<pair<ConstPoolVal*, BasicBlock*> >();
901 ConstPoolVal *V = (ConstPoolVal*)getVal($1, $2, true);
902
903 if (V == 0)
904 ThrowException("May only switch on a constant pool value!");
905
906 $$->push_back(make_pair(V, (BasicBlock*)getVal($4, $5)));
907 }
908
909Inst : OptAssign InstVal {
910 if ($1) // Is this definition named??
911 $2->setName($1); // if so, assign the name...
912
913 InsertValue($2);
914 $$ = $2;
915}
916
Chris Lattnerc24d2082001-06-11 15:04:20 +0000917PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
918 $$ = new list<pair<Value*, BasicBlock*> >();
919 $$->push_back(make_pair(getVal($1, $3),
920 (BasicBlock*)getVal(Type::LabelTy, $5)));
921 }
922 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
923 $$ = $1;
924 $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
925 (BasicBlock*)getVal(Type::LabelTy, $6)));
926 }
927
928
929ValueRefList : Types ValueRef { // Used for call statements...
Chris Lattner00950542001-06-06 20:29:01 +0000930 $$ = new list<Value*>();
931 $$->push_back(getVal($1, $2));
932 }
Chris Lattnerab5ac6b2001-07-08 23:22:50 +0000933 | ValueRefList ',' Types ValueRef {
Chris Lattner00950542001-06-06 20:29:01 +0000934 $$ = $1;
Chris Lattnerab5ac6b2001-07-08 23:22:50 +0000935 $1->push_back(getVal($3, $4));
Chris Lattner00950542001-06-06 20:29:01 +0000936 }
937
938// ValueRefListE - Just like ValueRefList, except that it may also be empty!
939ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; }
940
941InstVal : BinaryOps Types ValueRef ',' ValueRef {
Chris Lattnerbebd60d2001-06-25 07:31:31 +0000942 $$ = BinaryOperator::create($1, getVal($2, $3), getVal($2, $5));
Chris Lattner00950542001-06-06 20:29:01 +0000943 if ($$ == 0)
944 ThrowException("binary operator returned null!");
945 }
946 | UnaryOps Types ValueRef {
Chris Lattnerbebd60d2001-06-25 07:31:31 +0000947 $$ = UnaryOperator::create($1, getVal($2, $3));
Chris Lattner00950542001-06-06 20:29:01 +0000948 if ($$ == 0)
949 ThrowException("unary operator returned null!");
Chris Lattner09083092001-07-08 04:57:15 +0000950 }
Chris Lattner027dcc52001-07-08 21:10:27 +0000951 | ShiftOps Types ValueRef ',' Types ValueRef {
952 if ($5 != Type::UByteTy) ThrowException("Shift amount must be ubyte!");
953 $$ = new ShiftInst($1, getVal($2, $3), getVal($5, $6));
954 }
Chris Lattner09083092001-07-08 04:57:15 +0000955 | CAST Types ValueRef TO Types {
Chris Lattner71496b32001-07-08 19:03:27 +0000956 $$ = new CastInst(getVal($2, $3), $5);
Chris Lattner09083092001-07-08 04:57:15 +0000957 }
Chris Lattnerc24d2082001-06-11 15:04:20 +0000958 | PHI PHIList {
959 const Type *Ty = $2->front().first->getType();
960 $$ = new PHINode(Ty);
Chris Lattner00950542001-06-06 20:29:01 +0000961 while ($2->begin() != $2->end()) {
Chris Lattnerc24d2082001-06-11 15:04:20 +0000962 if ($2->front().first->getType() != Ty)
963 ThrowException("All elements of a PHI node must be of the same type!");
964 ((PHINode*)$$)->addIncoming($2->front().first, $2->front().second);
Chris Lattner00950542001-06-06 20:29:01 +0000965 $2->pop_front();
966 }
967 delete $2; // Free the list...
968 }
969 | CALL Types ValueRef '(' ValueRefListE ')' {
970 if (!$2->isMethodType())
971 ThrowException("Can only call methods: invalid type '" +
972 $2->getName() + "'!");
973
974 const MethodType *Ty = (const MethodType*)$2;
975
976 Value *V = getVal(Ty, $3);
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000977 if (!V->isMethod() || V->getType() != Ty)
Chris Lattner00950542001-06-06 20:29:01 +0000978 ThrowException("Cannot call: " + $3.getName() + "!");
979
980 // Create or access a new type that corresponds to the function call...
981 vector<Value *> Params;
982
983 if ($5) {
984 // Pull out just the arguments...
985 Params.insert(Params.begin(), $5->begin(), $5->end());
986 delete $5;
987
988 // Loop through MethodType's arguments and ensure they are specified
989 // correctly!
990 //
991 MethodType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
992 unsigned i;
993 for (i = 0; i < Params.size() && I != Ty->getParamTypes().end(); ++i,++I){
994 if (Params[i]->getType() != *I)
995 ThrowException("Parameter " + utostr(i) + " is not of type '" +
996 (*I)->getName() + "'!");
997 }
998
999 if (i != Params.size() || I != Ty->getParamTypes().end())
1000 ThrowException("Invalid number of parameters detected!");
1001 }
1002
1003 // Create the call node...
1004 $$ = new CallInst((Method*)V, Params);
1005 }
1006 | MemoryInst {
1007 $$ = $1;
1008 }
1009
Chris Lattner027dcc52001-07-08 21:10:27 +00001010// UByteList - List of ubyte values for load and store instructions
1011UByteList : ',' ConstVector {
1012 $$ = $2;
1013} | /* empty */ {
1014 $$ = new vector<ConstPoolVal*>();
1015}
1016
Chris Lattner00950542001-06-06 20:29:01 +00001017MemoryInst : MALLOC Types {
Chris Lattner8896eda2001-07-09 19:38:36 +00001018 $$ = new MallocInst(checkNewType(PointerType::getPointerType($2)));
Chris Lattner00950542001-06-06 20:29:01 +00001019 }
1020 | MALLOC Types ',' UINT ValueRef {
1021 if (!$2->isArrayType() || ((const ArrayType*)$2)->isSized())
1022 ThrowException("Trying to allocate " + $2->getName() +
1023 " as unsized array!");
Chris Lattner8896eda2001-07-09 19:38:36 +00001024 const Type *Ty = checkNewType(PointerType::getPointerType($2));
1025 $$ = new MallocInst(Ty, getVal($4, $5));
Chris Lattner00950542001-06-06 20:29:01 +00001026 }
1027 | ALLOCA Types {
Chris Lattner8896eda2001-07-09 19:38:36 +00001028 $$ = new AllocaInst(checkNewType(PointerType::getPointerType($2)));
Chris Lattner00950542001-06-06 20:29:01 +00001029 }
1030 | ALLOCA Types ',' UINT ValueRef {
1031 if (!$2->isArrayType() || ((const ArrayType*)$2)->isSized())
1032 ThrowException("Trying to allocate " + $2->getName() +
1033 " as unsized array!");
Chris Lattner8896eda2001-07-09 19:38:36 +00001034 const Type *Ty = checkNewType(PointerType::getPointerType($2));
Chris Lattner00950542001-06-06 20:29:01 +00001035 Value *ArrSize = getVal($4, $5);
Chris Lattnerf0d0e9c2001-07-07 08:36:30 +00001036 $$ = new AllocaInst(Ty, ArrSize);
Chris Lattner00950542001-06-06 20:29:01 +00001037 }
1038 | FREE Types ValueRef {
1039 if (!$2->isPointerType())
1040 ThrowException("Trying to free nonpointer type " + $2->getName() + "!");
1041 $$ = new FreeInst(getVal($2, $3));
1042 }
1043
Chris Lattner027dcc52001-07-08 21:10:27 +00001044 | LOAD Types ValueRef UByteList {
1045 if (!$2->isPointerType())
1046 ThrowException("Can't load from nonpointer type: " + $2->getName());
1047 if (LoadInst::getIndexedType($2, *$4) == 0)
1048 ThrowException("Invalid indices for load instruction!");
1049
1050 $$ = new LoadInst(getVal($2, $3), *$4);
1051 delete $4; // Free the vector...
1052 }
Chris Lattnerab5ac6b2001-07-08 23:22:50 +00001053 | STORE Types ValueRef ',' Types ValueRef UByteList {
1054 if (!$5->isPointerType())
1055 ThrowException("Can't store to a nonpointer type: " + $5->getName());
1056 const Type *ElTy = StoreInst::getIndexedType($5, *$7);
1057 if (ElTy == 0)
1058 ThrowException("Can't store into that field list!");
1059 if (ElTy != $2)
1060 ThrowException("Can't store '" + $2->getName() + "' into space of type '"+
1061 ElTy->getName() + "'!");
1062 $$ = new StoreInst(getVal($2, $3), getVal($5, $6), *$7);
1063 delete $7;
1064 }
1065 | GETELEMENTPTR Types ValueRef UByteList {
1066 if (!$2->isPointerType())
1067 ThrowException("getelementptr insn requires pointer operand!");
1068 if (!GetElementPtrInst::getIndexedType($2, *$4, true))
1069 ThrowException("Can't get element ptr '" + $2->getName() + "'!");
1070 $$ = new GetElementPtrInst(getVal($2, $3), *$4);
1071 delete $4;
Chris Lattner8896eda2001-07-09 19:38:36 +00001072 checkNewType($$->getType());
Chris Lattnerab5ac6b2001-07-08 23:22:50 +00001073 }
Chris Lattner027dcc52001-07-08 21:10:27 +00001074
Chris Lattner00950542001-06-06 20:29:01 +00001075%%
Chris Lattner09083092001-07-08 04:57:15 +00001076int yyerror(const char *ErrorMsg) {
Chris Lattner00950542001-06-06 20:29:01 +00001077 ThrowException(string("Parse error: ") + ErrorMsg);
1078 return 0;
1079}