1 //===-- llvmAsmParser.y - Parser for llvm assembly files ---------*- C++ -*--=//
3 // This file implements the bison parser for LLVM assembly languages files.
5 //===------------------------------------------------------------------------=//
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.
14 #include "ParserInternals.h"
15 #include "llvm/Assembly/Parser.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Module.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/Method.h"
20 #include "llvm/BasicBlock.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/iTerminators.h"
23 #include "llvm/iMemory.h"
24 #include "llvm/Support/STLExtras.h"
25 #include "llvm/Support/DepthFirstIterator.h"
27 #include <utility> // Get definition of pair class
29 #include <stdio.h> // This embarasment is due to our flex lexer...
31 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
32 int yylex(); // declaration" of xxx warnings.
35 static Module *ParserResult;
38 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
39 // relating to upreferences in the input stream.
41 //#define DEBUG_UPREFS 1
43 #define UR_OUT(X) cerr << X
48 // This contains info used when building the body of a method. It is destroyed
49 // when the method is completed.
51 typedef vector<Value *> ValueList; // Numbered defs
52 static void ResolveDefinitions(vector<ValueList> &LateResolvers);
53 static void ResolveTypes (vector<PATypeHolder<Type> > &LateResolveTypes);
55 static struct PerModuleInfo {
56 Module *CurrentModule;
57 vector<ValueList> Values; // Module level numbered definitions
58 vector<ValueList> LateResolveValues;
59 vector<PATypeHolder<Type> > Types, LateResolveTypes;
61 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
62 // references to global values. Global values may be referenced before they
63 // are defined, and if so, the temporary object that they represent is held
64 // here. This is used for forward references of ConstPoolPointerReferences.
66 typedef map<pair<const PointerType *, ValID>, GlobalVariable*> GlobalRefsType;
67 GlobalRefsType GlobalRefs;
70 // If we could not resolve some methods at method compilation time (calls to
71 // methods before they are defined), resolve them now... Types are resolved
72 // when the constant pool has been completely parsed.
74 ResolveDefinitions(LateResolveValues);
76 // Check to make sure that all global value forward references have been
79 if (!GlobalRefs.empty()) {
80 // TODO: Make this more detailed! Loop over each undef value and print
82 ThrowException("TODO: Make better error - Unresolved forward constant references exist!");
85 Values.clear(); // Clear out method local definitions
91 // DeclareNewGlobalValue - Called every type a new GV has been defined. This
92 // is used to remove things from the forward declaration map, resolving them
93 // to the correct thing as needed.
95 void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
96 // Check to see if there is a forward reference to this global variable...
97 // if there is, eliminate it and patch the reference to use the new def'n.
98 GlobalRefsType::iterator I = GlobalRefs.find(make_pair(GV->getType(), D));
100 if (I != GlobalRefs.end()) {
101 GlobalVariable *OldGV = I->second; // Get the placeholder...
102 I->first.second.destroy(); // Free string memory if neccesary
104 // Loop over all of the uses of the GlobalValue. The only thing they are
105 // allowed to be at this point is ConstPoolPointerReference's.
106 assert(OldGV->use_size() == 1 && "Only one reference should exist!");
107 while (!OldGV->use_empty()) {
108 User *U = OldGV->use_back(); // Must be a ConstPoolPointerReference...
109 ConstPoolPointerReference *CPPR = cast<ConstPoolPointerReference>(U);
110 assert(CPPR->getValue() == OldGV && "Something isn't happy");
112 // Change the const pool reference to point to the real global variable
113 // now. This should drop a use from the OldGV.
114 CPPR->mutateReference(GV);
117 // Remove GV from the module...
118 CurrentModule->getGlobalList().remove(OldGV);
119 delete OldGV; // Delete the old placeholder
121 // Remove the map entry for the global now that it has been created...
128 static struct PerMethodInfo {
129 Method *CurrentMethod; // Pointer to current method being created
131 vector<ValueList> Values; // Keep track of numbered definitions
132 vector<ValueList> LateResolveValues;
133 vector<PATypeHolder<Type> > Types, LateResolveTypes;
134 bool isDeclare; // Is this method a forward declararation?
136 inline PerMethodInfo() {
141 inline ~PerMethodInfo() {}
143 inline void MethodStart(Method *M) {
148 // If we could not resolve some blocks at parsing time (forward branches)
149 // resolve the branches now...
150 ResolveDefinitions(LateResolveValues);
152 Values.clear(); // Clear out method local definitions
157 } CurMeth; // Info for the current method...
159 static bool inMethodScope() { return CurMeth.CurrentMethod != 0; }
162 //===----------------------------------------------------------------------===//
163 // Code to handle definitions of all the types
164 //===----------------------------------------------------------------------===//
166 static int InsertValue(Value *D, vector<ValueList> &ValueTab = CurMeth.Values) {
167 if (D->hasName()) return -1; // Is this a numbered definition?
169 // Yes, insert the value into the value table...
170 unsigned type = D->getType()->getUniqueID();
171 if (ValueTab.size() <= type)
172 ValueTab.resize(type+1, ValueList());
173 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
174 ValueTab[type].push_back(D);
175 return ValueTab[type].size()-1;
178 // TODO: FIXME when Type are not const
179 static void InsertType(const Type *Ty, vector<PATypeHolder<Type> > &Types) {
183 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
185 case 0: { // Is it a numbered definition?
186 unsigned Num = (unsigned)D.Num;
188 // Module constants occupy the lowest numbered slots...
189 if (Num < CurModule.Types.size())
190 return CurModule.Types[Num];
192 Num -= CurModule.Types.size();
194 // Check that the number is within bounds...
195 if (Num <= CurMeth.Types.size())
196 return CurMeth.Types[Num];
198 case 1: { // Is it a named definition?
200 SymbolTable *SymTab = 0;
201 if (inMethodScope()) SymTab = CurMeth.CurrentMethod->getSymbolTable();
202 Value *N = SymTab ? SymTab->lookup(Type::TypeTy, Name) : 0;
205 // Symbol table doesn't automatically chain yet... because the method
206 // hasn't been added to the module...
208 SymTab = CurModule.CurrentModule->getSymbolTable();
210 N = SymTab->lookup(Type::TypeTy, Name);
214 D.destroy(); // Free old strdup'd memory...
215 return cast<const Type>(N);
218 ThrowException("Invalid symbol type reference!");
221 // If we reached here, we referenced either a symbol that we don't know about
222 // or an id number that hasn't been read yet. We may be referencing something
223 // forward, so just create an entry to be resolved later and get to it...
225 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
227 vector<PATypeHolder<Type> > *LateResolver = inMethodScope() ?
228 &CurMeth.LateResolveTypes : &CurModule.LateResolveTypes;
230 Type *Typ = new TypePlaceHolder(Type::TypeTy, D);
231 InsertType(Typ, *LateResolver);
235 static Value *lookupInSymbolTable(const Type *Ty, const string &Name) {
236 SymbolTable *SymTab =
237 inMethodScope() ? CurMeth.CurrentMethod->getSymbolTable() : 0;
238 Value *N = SymTab ? SymTab->lookup(Ty, Name) : 0;
241 // Symbol table doesn't automatically chain yet... because the method
242 // hasn't been added to the module...
244 SymTab = CurModule.CurrentModule->getSymbolTable();
246 N = SymTab->lookup(Ty, Name);
252 // getValNonImprovising - Look up the value specified by the provided type and
253 // the provided ValID. If the value exists and has already been defined, return
254 // it. Otherwise return null.
256 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
258 case ValID::NumberVal: { // Is it a numbered definition?
259 unsigned type = Ty->getUniqueID();
260 unsigned Num = (unsigned)D.Num;
262 // Module constants occupy the lowest numbered slots...
263 if (type < CurModule.Values.size()) {
264 if (Num < CurModule.Values[type].size())
265 return CurModule.Values[type][Num];
267 Num -= CurModule.Values[type].size();
270 // Make sure that our type is within bounds
271 if (CurMeth.Values.size() <= type) return 0;
273 // Check that the number is within bounds...
274 if (CurMeth.Values[type].size() <= Num) return 0;
276 return CurMeth.Values[type][Num];
279 case ValID::NameVal: { // Is it a named definition?
280 Value *N = lookupInSymbolTable(Ty, string(D.Name));
281 if (N == 0) return 0;
283 D.destroy(); // Free old strdup'd memory...
287 // Check to make sure that "Ty" is an integral type, and that our
288 // value will fit into the specified type...
289 case ValID::ConstSIntVal: // Is it a constant pool reference??
290 if (Ty == Type::BoolTy) { // Special handling for boolean data
291 return ConstPoolBool::get(D.ConstPool64 != 0);
293 if (!ConstPoolSInt::isValueValidForType(Ty, D.ConstPool64))
294 ThrowException("Symbolic constant pool value '" +
295 itostr(D.ConstPool64) + "' is invalid for type '" +
296 Ty->getName() + "'!");
297 return ConstPoolSInt::get(Ty, D.ConstPool64);
300 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
301 if (!ConstPoolUInt::isValueValidForType(Ty, D.UConstPool64)) {
302 if (!ConstPoolSInt::isValueValidForType(Ty, D.ConstPool64)) {
303 ThrowException("Integral constant pool reference is invalid!");
304 } else { // This is really a signed reference. Transmogrify.
305 return ConstPoolSInt::get(Ty, D.ConstPool64);
308 return ConstPoolUInt::get(Ty, D.UConstPool64);
311 case ValID::ConstStringVal: // Is it a string const pool reference?
312 cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
316 case ValID::ConstFPVal: // Is it a floating point const pool reference?
317 if (!ConstPoolFP::isValueValidForType(Ty, D.ConstPoolFP))
318 ThrowException("FP constant invalid for type!!");
319 return ConstPoolFP::get(Ty, D.ConstPoolFP);
321 case ValID::ConstNullVal: // Is it a null value?
322 if (!Ty->isPointerType())
323 ThrowException("Cannot create a a non pointer null!");
324 return ConstPoolPointerNull::get(cast<PointerType>(Ty));
327 assert(0 && "Unhandled case!");
331 assert(0 && "Unhandled case!");
336 // getVal - This function is identical to getValNonImprovising, except that if a
337 // value is not already defined, it "improvises" by creating a placeholder var
338 // that looks and acts just like the requested variable. When the value is
339 // defined later, all uses of the placeholder variable are replaced with the
342 static Value *getVal(const Type *Ty, const ValID &D) {
343 assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
345 // See if the value has already been defined...
346 Value *V = getValNonImprovising(Ty, D);
349 // If we reached here, we referenced either a symbol that we don't know about
350 // or an id number that hasn't been read yet. We may be referencing something
351 // forward, so just create an entry to be resolved later and get to it...
354 vector<ValueList> *LateResolver = inMethodScope() ?
355 &CurMeth.LateResolveValues : &CurModule.LateResolveValues;
357 if (isa<MethodType>(Ty))
358 ThrowException("Methods are not values and must be referenced as pointers");
360 if (const PointerType *PTy = dyn_cast<PointerType>(Ty))
361 if (const MethodType *MTy = dyn_cast<MethodType>(PTy->getValueType()))
362 Ty = MTy; // Convert pointer to method to method type
364 switch (Ty->getPrimitiveID()) {
365 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
366 case Type::MethodTyID: d = new MethPlaceHolder(Ty, D);
367 LateResolver = &CurModule.LateResolveValues; break;
368 default: d = new ValuePlaceHolder(Ty, D); break;
371 assert(d != 0 && "How did we not make something?");
372 InsertValue(d, *LateResolver);
377 //===----------------------------------------------------------------------===//
378 // Code to handle forward references in instructions
379 //===----------------------------------------------------------------------===//
381 // This code handles the late binding needed with statements that reference
382 // values not defined yet... for example, a forward branch, or the PHI node for
385 // This keeps a table (CurMeth.LateResolveValues) of all such forward references
386 // and back patchs after we are done.
389 // ResolveDefinitions - If we could not resolve some defs at parsing
390 // time (forward branches, phi functions for loops, etc...) resolve the
393 static void ResolveDefinitions(vector<ValueList> &LateResolvers) {
394 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
395 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
396 while (!LateResolvers[ty].empty()) {
397 Value *V = LateResolvers[ty].back();
398 LateResolvers[ty].pop_back();
399 ValID &DID = getValIDFromPlaceHolder(V);
401 Value *TheRealValue = getValNonImprovising(Type::getUniqueIDType(ty),DID);
402 if (TheRealValue == 0) {
404 ThrowException("Reference to an invalid definition: '" +DID.getName()+
405 "' of type '" + V->getType()->getDescription() + "'",
406 getLineNumFromPlaceHolder(V));
408 ThrowException("Reference to an invalid definition: #" +
409 itostr(DID.Num) + " of type '" +
410 V->getType()->getDescription() + "'",
411 getLineNumFromPlaceHolder(V));
414 assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
416 V->replaceAllUsesWith(TheRealValue);
421 LateResolvers.clear();
424 // ResolveType - Take a specified unresolved type and resolve it. If there is
425 // nothing to resolve it to yet, return true. Otherwise resolve it and return
428 static bool ResolveType(PATypeHolder<Type> &T) {
430 ValID &DID = getValIDFromPlaceHolder(Ty);
432 const Type *TheRealType = getTypeVal(DID, true);
433 if (TheRealType == 0) return true;
435 // Refine the opaque type we had to the new type we are getting.
436 cast<DerivedType>(Ty)->refineAbstractTypeTo(TheRealType);
441 // ResolveTypes - This goes through the forward referenced type table and makes
442 // sure that all type references are complete. This code is executed after the
443 // constant pool of a method or module is completely parsed.
445 static void ResolveTypes(vector<PATypeHolder<Type> > &LateResolveTypes) {
446 while (!LateResolveTypes.empty()) {
447 if (ResolveType(LateResolveTypes.back())) {
448 const Type *Ty = LateResolveTypes.back();
449 ValID &DID = getValIDFromPlaceHolder(Ty);
451 if (DID.Type == ValID::NameVal)
452 ThrowException("Reference to an invalid type: '" +DID.getName(),
453 getLineNumFromPlaceHolder(Ty));
455 ThrowException("Reference to an invalid type: #" + itostr(DID.Num),
456 getLineNumFromPlaceHolder(Ty));
459 // No need to delete type, refine does that for us.
460 LateResolveTypes.pop_back();
465 // ResolveSomeTypes - This goes through the forward referenced type table and
466 // completes references that are now done. This is so that types are
467 // immediately resolved to be as concrete as possible. This does not cause
468 // thrown exceptions if not everything is resolved.
470 static void ResolveSomeTypes(vector<PATypeHolder<Type> > &LateResolveTypes) {
471 for (unsigned i = 0; i < LateResolveTypes.size(); ) {
472 if (ResolveType(LateResolveTypes[i]))
473 ++i; // Type didn't resolve
475 LateResolveTypes.erase(LateResolveTypes.begin()+i); // Type resolved!
480 // setValueName - Set the specified value to the name given. The name may be
481 // null potentially, in which case this is a noop. The string passed in is
482 // assumed to be a malloc'd string buffer, and is freed by this function.
484 // This function returns true if the value has already been defined, but is
485 // allowed to be redefined in the specified context. If the name is a new name
486 // for the typeplane, false is returned.
488 static bool setValueName(Value *V, char *NameStr) {
489 if (NameStr == 0) return false;
490 string Name(NameStr); // Copy string
491 free(NameStr); // Free old string
493 if (V->getType() == Type::VoidTy)
494 ThrowException("Can't assign name '" + Name +
495 "' to a null valued instruction!");
497 SymbolTable *ST = inMethodScope() ?
498 CurMeth.CurrentMethod->getSymbolTableSure() :
499 CurModule.CurrentModule->getSymbolTableSure();
501 Value *Existing = ST->lookup(V->getType(), Name);
502 if (Existing) { // Inserting a name that is already defined???
503 // There is only one case where this is allowed: when we are refining an
504 // opaque type. In this case, Existing will be an opaque type.
505 if (const Type *Ty = dyn_cast<const Type>(Existing)) {
506 if (OpaqueType *OpTy = dyn_cast<OpaqueType>(Ty)) {
507 // We ARE replacing an opaque type!
508 OpTy->refineAbstractTypeTo(cast<Type>(V));
513 // Otherwise, we are a simple redefinition of a value, check to see if it
514 // is defined the same as the old one...
515 if (const Type *Ty = dyn_cast<const Type>(Existing)) {
516 if (Ty == cast<const Type>(V)) return true; // Yes, it's equal.
517 // cerr << "Type: " << Ty->getDescription() << " != "
518 // << cast<const Type>(V)->getDescription() << "!\n";
519 } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
520 // We are allowed to redefine a global variable in two circumstances:
521 // 1. If at least one of the globals is uninitialized or
522 // 2. If both initializers have the same value.
524 // This can only be done if the const'ness of the vars is the same.
526 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
527 if (EGV->isConstant() == GV->isConstant() &&
528 (!EGV->hasInitializer() || !GV->hasInitializer() ||
529 EGV->getInitializer() == GV->getInitializer())) {
531 // Make sure the existing global version gets the initializer!
532 if (GV->hasInitializer() && !EGV->hasInitializer())
533 EGV->setInitializer(GV->getInitializer());
535 delete GV; // Destroy the duplicate!
536 return true; // They are equivalent!
540 ThrowException("Redefinition of value named '" + Name + "' in the '" +
541 V->getType()->getDescription() + "' type plane!");
544 V->setName(Name, ST);
549 //===----------------------------------------------------------------------===//
550 // Code for handling upreferences in type names...
553 // TypeContains - Returns true if Ty contains E in it.
555 static bool TypeContains(const Type *Ty, const Type *E) {
556 return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
560 static vector<pair<unsigned, OpaqueType *> > UpRefs;
562 static PATypeHolder<Type> HandleUpRefs(const Type *ty) {
563 PATypeHolder<Type> Ty(ty);
564 UR_OUT(UpRefs.size() << " upreferences active!\n");
565 for (unsigned i = 0; i < UpRefs.size(); ) {
566 UR_OUT("TypeContains(" << Ty->getDescription() << ", "
567 << UpRefs[i].second->getDescription() << ") = "
568 << TypeContains(Ty, UpRefs[i].second) << endl);
569 if (TypeContains(Ty, UpRefs[i].second)) {
570 unsigned Level = --UpRefs[i].first; // Decrement level of upreference
571 UR_OUT("Uplevel Ref Level = " << Level << endl);
572 if (Level == 0) { // Upreference should be resolved!
573 UR_OUT("About to resolve upreference!\n";
574 string OldName = UpRefs[i].second->getDescription());
575 UpRefs[i].second->refineAbstractTypeTo(Ty);
576 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
577 UR_OUT("Type '" << OldName << "' refined upreference to: "
578 << (const void*)Ty << ", " << Ty->getDescription() << endl);
583 ++i; // Otherwise, no resolve, move on...
585 // FIXME: TODO: this should return the updated type
589 template <class TypeTy>
590 inline static void TypeDone(PATypeHolder<TypeTy> *Ty) {
592 ThrowException("Invalid upreference in type: " + (*Ty)->getDescription());
595 // newTH - Allocate a new type holder for the specified type
596 template <class TypeTy>
597 inline static PATypeHolder<TypeTy> *newTH(const TypeTy *Ty) {
598 return new PATypeHolder<TypeTy>(Ty);
600 template <class TypeTy>
601 inline static PATypeHolder<TypeTy> *newTH(const PATypeHolder<TypeTy> &TH) {
602 return new PATypeHolder<TypeTy>(TH);
606 //===----------------------------------------------------------------------===//
607 // RunVMAsmParser - Define an interface to this parser
608 //===----------------------------------------------------------------------===//
610 Module *RunVMAsmParser(const string &Filename, FILE *F) {
612 CurFilename = Filename;
613 llvmAsmlineno = 1; // Reset the current line number...
615 CurModule.CurrentModule = new Module(); // Allocate a new module to read
616 yyparse(); // Parse the file.
617 Module *Result = ParserResult;
618 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
629 MethodArgument *MethArgVal;
630 BasicBlock *BasicBlockVal;
631 TerminatorInst *TermInstVal;
632 Instruction *InstVal;
633 ConstPoolVal *ConstVal;
635 const Type *PrimType;
636 PATypeHolder<Type> *TypeVal;
639 list<MethodArgument*> *MethodArgList;
640 list<Value*> *ValueList;
641 list<PATypeHolder<Type> > *TypeList;
642 list<pair<Value*, BasicBlock*> > *PHIList; // Represent the RHS of PHI node
643 list<pair<ConstPoolVal*, BasicBlock*> > *JumpTable;
644 vector<ConstPoolVal*> *ConstVector;
653 char *StrVal; // This memory is strdup'd!
654 ValID ValIDVal; // strdup'd memory maybe!
656 Instruction::UnaryOps UnaryOpVal;
657 Instruction::BinaryOps BinaryOpVal;
658 Instruction::TermOps TermOpVal;
659 Instruction::MemoryOps MemOpVal;
660 Instruction::OtherOps OtherOpVal;
663 %type <ModuleVal> Module MethodList
664 %type <MethodVal> Method MethodProto MethodHeader BasicBlockList
665 %type <BasicBlockVal> BasicBlock InstructionList
666 %type <TermInstVal> BBTerminatorInst
667 %type <InstVal> Inst InstVal MemoryInst
668 %type <ConstVal> ConstVal
669 %type <ConstVector> ConstVector UByteList
670 %type <MethodArgList> ArgList ArgListH
671 %type <MethArgVal> ArgVal
672 %type <PHIList> PHIList
673 %type <ValueList> ValueRefList ValueRefListE // For call param lists
674 %type <TypeList> TypeListI ArgTypeListI
675 %type <JumpTable> JumpTable
676 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
678 // ValueRef - Unresolved reference to a definition or BB
679 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
680 %type <ValueVal> ResolvedVal // <type> <valref> pair
681 // Tokens and types for handling constant integer values
683 // ESINT64VAL - A negative number within long long range
684 %token <SInt64Val> ESINT64VAL
686 // EUINT64VAL - A positive number within uns. long long range
687 %token <UInt64Val> EUINT64VAL
688 %type <SInt64Val> EINT64VAL
690 %token <SIntVal> SINTVAL // Signed 32 bit ints...
691 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
692 %type <SIntVal> INTVAL
693 %token <FPVal> FPVAL // Float or Double constant
696 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
697 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
698 %token <TypeVal> OPAQUE
699 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
700 %token <PrimType> FLOAT DOUBLE TYPE LABEL
702 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
703 %type <StrVal> OptVAR_ID OptAssign
706 %token IMPLEMENTATION TRUE FALSE BEGINTOK END DECLARE GLOBAL CONSTANT UNINIT
707 %token TO EXCEPT DOTDOTDOT STRING NULL_TOK CONST
709 // Basic Block Terminating Operators
710 %token <TermOpVal> RET BR SWITCH
713 %type <UnaryOpVal> UnaryOps // all the unary operators
714 %token <UnaryOpVal> NOT
717 %type <BinaryOpVal> BinaryOps // all the binary operators
718 %token <BinaryOpVal> ADD SUB MUL DIV REM
719 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
721 // Memory Instructions
722 %token <MemoryOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
725 %type <OtherOpVal> ShiftOps
726 %token <OtherOpVal> PHI CALL INVOKE CAST SHL SHR
731 // Handle constant integer size restriction and conversion...
736 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
737 ThrowException("Value too large for type!");
742 EINT64VAL : ESINT64VAL // These have same type and can't cause problems...
743 EINT64VAL : EUINT64VAL {
744 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
745 ThrowException("Value too large for type!");
749 // Operations that are notably excluded from this list include:
750 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
753 BinaryOps : ADD | SUB | MUL | DIV | REM
754 BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
757 // These are some types that allow classification if we only want a particular
758 // thing... for example, only a signed, unsigned, or integral type.
759 SIntType : LONG | INT | SHORT | SBYTE
760 UIntType : ULONG | UINT | USHORT | UBYTE
761 IntType : SIntType | UIntType
762 FPType : FLOAT | DOUBLE
764 // OptAssign - Value producing statements have an optional assignment component
765 OptAssign : VAR_ID '=' {
773 //===----------------------------------------------------------------------===//
774 // Types includes all predefined types... except void, because it can only be
775 // used in specific contexts (method returning void for example). To have
776 // access to it, a user must explicitly use TypesV.
779 // TypesV includes all of 'Types', but it also includes the void type.
780 TypesV : Types | VOID { $$ = newTH($1); }
781 UpRTypesV : UpRTypes | VOID { $$ = newTH($1); }
788 // Derived types are added later...
790 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
791 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL
792 UpRTypes : OPAQUE | PrimType { $$ = newTH($1); }
793 UpRTypes : ValueRef { // Named types are also simple types...
794 $$ = newTH(getTypeVal($1));
797 // Include derived types in the Types production.
799 UpRTypes : '\\' EUINT64VAL { // Type UpReference
800 if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
801 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
802 UpRefs.push_back(make_pair((unsigned)$2, OT)); // Add to vector...
803 $$ = newTH<Type>(OT);
804 UR_OUT("New Upreference!\n");
806 | UpRTypesV '(' ArgTypeListI ')' { // Method derived type?
807 vector<const Type*> Params;
808 mapto($3->begin(), $3->end(), back_inserter(Params),
809 mem_fun_ref(&PATypeHandle<Type>::get));
810 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
811 if (isVarArg) Params.pop_back();
813 $$ = newTH(HandleUpRefs(MethodType::get(*$1, Params, isVarArg)));
814 delete $3; // Delete the argument list
815 delete $1; // Delete the old type handle
817 | '[' UpRTypesV ']' { // Unsized array type?
818 $$ = newTH<Type>(HandleUpRefs(ArrayType::get(*$2)));
821 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
822 $$ = newTH<Type>(HandleUpRefs(ArrayType::get(*$4, (int)$2)));
825 | '{' TypeListI '}' { // Structure type?
826 vector<const Type*> Elements;
827 mapto($2->begin(), $2->end(), back_inserter(Elements),
828 mem_fun_ref(&PATypeHandle<Type>::get));
830 $$ = newTH<Type>(HandleUpRefs(StructType::get(Elements)));
833 | '{' '}' { // Empty structure type?
834 $$ = newTH<Type>(StructType::get(vector<const Type*>()));
836 | UpRTypes '*' { // Pointer type?
837 $$ = newTH<Type>(HandleUpRefs(PointerType::get(*$1)));
841 // TypeList - Used for struct declarations and as a basis for method type
842 // declaration type lists
844 TypeListI : UpRTypes {
845 $$ = new list<PATypeHolder<Type> >();
846 $$->push_back(*$1); delete $1;
848 | TypeListI ',' UpRTypes {
849 ($$=$1)->push_back(*$3); delete $3;
852 // ArgTypeList - List of types for a method type declaration...
853 ArgTypeListI : TypeListI
854 | TypeListI ',' DOTDOTDOT {
855 ($$=$1)->push_back(Type::VoidTy);
858 ($$ = new list<PATypeHolder<Type> >())->push_back(Type::VoidTy);
861 $$ = new list<PATypeHolder<Type> >();
865 // ConstVal - The various declarations that go into the constant pool. This
866 // includes all forward declarations of types, constants, and functions.
868 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
869 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
871 ThrowException("Cannot make array constant with type: '" +
872 (*$1)->getDescription() + "'!");
873 const Type *ETy = ATy->getElementType();
874 int NumElements = ATy->getNumElements();
876 // Verify that we have the correct size...
877 if (NumElements != -1 && NumElements != (int)$3->size())
878 ThrowException("Type mismatch: constant sized array initialized with " +
879 utostr($3->size()) + " arguments, but has size of " +
880 itostr(NumElements) + "!");
882 // Verify all elements are correct type!
883 for (unsigned i = 0; i < $3->size(); i++) {
884 if (ETy != (*$3)[i]->getType())
885 ThrowException("Element #" + utostr(i) + " is not of type '" +
886 ETy->getName() + "' as required!\nIt is of type '" +
887 (*$3)[i]->getType()->getName() + "'.");
890 $$ = ConstPoolArray::get(ATy, *$3);
891 delete $1; delete $3;
894 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
896 ThrowException("Cannot make array constant with type: '" +
897 (*$1)->getDescription() + "'!");
899 int NumElements = ATy->getNumElements();
900 if (NumElements != -1 && NumElements != 0)
901 ThrowException("Type mismatch: constant sized array initialized with 0"
902 " arguments, but has size of " + itostr(NumElements) +"!");
903 $$ = ConstPoolArray::get(ATy, vector<ConstPoolVal*>());
906 | Types 'c' STRINGCONSTANT {
907 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
909 ThrowException("Cannot make array constant with type: '" +
910 (*$1)->getDescription() + "'!");
912 int NumElements = ATy->getNumElements();
913 const Type *ETy = ATy->getElementType();
914 char *EndStr = UnEscapeLexed($3, true);
915 if (NumElements != -1 && NumElements != (EndStr-$3))
916 ThrowException("Can't build string constant of size " +
917 itostr((int)(EndStr-$3)) +
918 " when array has size " + itostr(NumElements) + "!");
919 vector<ConstPoolVal*> Vals;
920 if (ETy == Type::SByteTy) {
921 for (char *C = $3; C != EndStr; ++C)
922 Vals.push_back(ConstPoolSInt::get(ETy, *C));
923 } else if (ETy == Type::UByteTy) {
924 for (char *C = $3; C != EndStr; ++C)
925 Vals.push_back(ConstPoolUInt::get(ETy, *C));
928 ThrowException("Cannot build string arrays of non byte sized elements!");
931 $$ = ConstPoolArray::get(ATy, Vals);
934 | Types '{' ConstVector '}' {
935 const StructType *STy = dyn_cast<const StructType>($1->get());
937 ThrowException("Cannot make struct constant with type: '" +
938 (*$1)->getDescription() + "'!");
939 // FIXME: TODO: Check to see that the constants are compatible with the type
941 $$ = ConstPoolStruct::get(STy, *$3);
942 delete $1; delete $3;
945 const PointerType *PTy = dyn_cast<const PointerType>($1->get());
947 ThrowException("Cannot make null pointer constant with type: '" +
948 (*$1)->getDescription() + "'!");
950 $$ = ConstPoolPointerNull::get(PTy);
953 | Types SymbolicValueRef {
954 const PointerType *Ty = dyn_cast<const PointerType>($1->get());
956 ThrowException("Global const reference must be a pointer type!");
958 Value *V = getValNonImprovising(Ty, $2);
960 // If this is an initializer for a constant pointer, which is referencing a
961 // (currently) undefined variable, create a stub now that shall be replaced
962 // in the future with the right type of variable.
965 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
966 const PointerType *PT = cast<PointerType>(Ty);
968 // First check to see if the forward references value is already created!
969 PerModuleInfo::GlobalRefsType::iterator I =
970 CurModule.GlobalRefs.find(make_pair(PT, $2));
972 if (I != CurModule.GlobalRefs.end()) {
973 V = I->second; // Placeholder already exists, use it...
975 // TODO: Include line number info by creating a subclass of
976 // TODO: GlobalVariable here that includes the said information!
978 // Create a placeholder for the global variable reference...
979 GlobalVariable *GV = new GlobalVariable(PT->getValueType(), false);
980 // Keep track of the fact that we have a forward ref to recycle it
981 CurModule.GlobalRefs.insert(make_pair(make_pair(PT, $2), GV));
983 // Must temporarily push this value into the module table...
984 CurModule.CurrentModule->getGlobalList().push_back(GV);
989 GlobalValue *GV = cast<GlobalValue>(V);
990 $$ = ConstPoolPointerReference::get(GV);
991 delete $1; // Free the type handle
995 ConstVal : SIntType EINT64VAL { // integral constants
996 if (!ConstPoolSInt::isValueValidForType($1, $2))
997 ThrowException("Constant value doesn't fit in type!");
998 $$ = ConstPoolSInt::get($1, $2);
1000 | UIntType EUINT64VAL { // integral constants
1001 if (!ConstPoolUInt::isValueValidForType($1, $2))
1002 ThrowException("Constant value doesn't fit in type!");
1003 $$ = ConstPoolUInt::get($1, $2);
1005 | BOOL TRUE { // Boolean constants
1006 $$ = ConstPoolBool::True;
1008 | BOOL FALSE { // Boolean constants
1009 $$ = ConstPoolBool::False;
1011 | FPType FPVAL { // Float & Double constants
1012 $$ = ConstPoolFP::get($1, $2);
1015 // ConstVector - A list of comma seperated constants.
1016 ConstVector : ConstVector ',' ConstVal {
1017 ($$ = $1)->push_back($3);
1020 $$ = new vector<ConstPoolVal*>();
1025 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1026 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; }
1029 // ConstPool - Constants with optional names assigned to them.
1030 ConstPool : ConstPool OptAssign CONST ConstVal {
1031 if (setValueName($4, $2)) { assert(0 && "No redefinitions allowed!"); }
1034 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1035 // TODO: FIXME when Type are not const
1036 if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1037 // If this is not a redefinition of a type...
1039 InsertType($4->get(),
1040 inMethodScope() ? CurMeth.Types : CurModule.Types);
1044 ResolveSomeTypes(inMethodScope() ? CurMeth.LateResolveTypes :
1045 CurModule.LateResolveTypes);
1048 | ConstPool MethodProto { // Method prototypes can be in const pool
1050 | ConstPool OptAssign GlobalType ConstVal {
1051 const Type *Ty = $4->getType();
1052 // Global declarations appear in Constant Pool
1053 ConstPoolVal *Initializer = $4;
1054 if (Initializer == 0)
1055 ThrowException("Global value initializer is not a constant!");
1057 GlobalVariable *GV = new GlobalVariable(Ty, $3, Initializer);
1058 if (!setValueName(GV, $2)) { // If not redefining...
1059 CurModule.CurrentModule->getGlobalList().push_back(GV);
1060 int Slot = InsertValue(GV, CurModule.Values);
1063 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1065 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1066 (char*)GV->getName().c_str()));
1070 | ConstPool OptAssign UNINIT GlobalType Types {
1071 const Type *Ty = *$5;
1072 // Global declarations appear in Constant Pool
1073 if (isa<ArrayType>(Ty) && cast<ArrayType>(Ty)->isUnsized()) {
1074 ThrowException("Type '" + Ty->getDescription() +
1075 "' is not a sized type!");
1078 GlobalVariable *GV = new GlobalVariable(Ty, $4);
1079 if (!setValueName(GV, $2)) { // If not redefining...
1080 CurModule.CurrentModule->getGlobalList().push_back(GV);
1081 int Slot = InsertValue(GV, CurModule.Values);
1084 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1086 assert(GV->hasName() && "Not named and not numbered!?");
1087 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1088 (char*)GV->getName().c_str()));
1092 | /* empty: end of list */ {
1096 //===----------------------------------------------------------------------===//
1097 // Rules to match Modules
1098 //===----------------------------------------------------------------------===//
1100 // Module rule: Capture the result of parsing the whole file into a result
1103 Module : MethodList {
1104 $$ = ParserResult = $1;
1105 CurModule.ModuleDone();
1108 // MethodList - A list of methods, preceeded by a constant pool.
1110 MethodList : MethodList Method {
1112 if (!$2->getParent())
1113 $1->getMethodList().push_back($2);
1114 CurMeth.MethodDone();
1116 | MethodList MethodProto {
1119 | ConstPool IMPLEMENTATION {
1120 $$ = CurModule.CurrentModule;
1121 // Resolve circular types before we parse the body of the module
1122 ResolveTypes(CurModule.LateResolveTypes);
1126 //===----------------------------------------------------------------------===//
1127 // Rules to match Method Headers
1128 //===----------------------------------------------------------------------===//
1130 OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; }
1132 ArgVal : Types OptVAR_ID {
1133 $$ = new MethodArgument(*$1); delete $1;
1134 if (setValueName($$, $2)) { assert(0 && "No arg redef allowed!"); }
1137 ArgListH : ArgVal ',' ArgListH {
1142 $$ = new list<MethodArgument*>();
1146 $$ = new list<MethodArgument*>();
1147 $$->push_front(new MethodArgument(Type::VoidTy));
1150 ArgList : ArgListH {
1157 MethodHeaderH : TypesV STRINGCONSTANT '(' ArgList ')' {
1159 vector<const Type*> ParamTypeList;
1161 for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I)
1162 ParamTypeList.push_back((*I)->getType());
1164 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1165 if (isVarArg) ParamTypeList.pop_back();
1167 const MethodType *MT = MethodType::get(*$1, ParamTypeList, isVarArg);
1168 const PointerType *PMT = PointerType::get(MT);
1172 if (SymbolTable *ST = CurModule.CurrentModule->getSymbolTable()) {
1173 if (Value *V = ST->lookup(PMT, $2)) { // Method already in symtab?
1174 M = cast<Method>(V);
1176 // Yes it is. If this is the case, either we need to be a forward decl,
1177 // or it needs to be.
1178 if (!CurMeth.isDeclare && !M->isExternal())
1179 ThrowException("Redefinition of method '" + string($2) + "'!");
1183 if (M == 0) { // Not already defined?
1184 M = new Method(MT, $2);
1185 InsertValue(M, CurModule.Values);
1186 CurModule.DeclareNewGlobalValue(M, ValID::create($2));
1189 free($2); // Free strdup'd memory!
1191 CurMeth.MethodStart(M);
1193 // Add all of the arguments we parsed to the method...
1194 if ($4 && !CurMeth.isDeclare) { // Is null if empty...
1195 Method::ArgumentListType &ArgList = M->getArgumentList();
1197 for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I) {
1199 ArgList.push_back(*I);
1201 delete $4; // We're now done with the argument list
1205 MethodHeader : MethodHeaderH ConstPool BEGINTOK {
1206 $$ = CurMeth.CurrentMethod;
1208 // Resolve circular types before we parse the body of the method.
1209 ResolveTypes(CurMeth.LateResolveTypes);
1212 Method : BasicBlockList END {
1216 MethodProto : DECLARE { CurMeth.isDeclare = true; } MethodHeaderH {
1217 $$ = CurMeth.CurrentMethod;
1218 if (!$$->getParent())
1219 CurModule.CurrentModule->getMethodList().push_back($$);
1220 CurMeth.MethodDone();
1223 //===----------------------------------------------------------------------===//
1224 // Rules to match Basic Blocks
1225 //===----------------------------------------------------------------------===//
1227 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1228 $$ = ValID::create($1);
1231 $$ = ValID::create($1);
1233 | FPVAL { // Perhaps it's an FP constant?
1234 $$ = ValID::create($1);
1237 $$ = ValID::create((int64_t)1);
1240 $$ = ValID::create((int64_t)0);
1243 $$ = ValID::createNull();
1247 | STRINGCONSTANT { // Quoted strings work too... especially for methods
1248 $$ = ValID::create_conststr($1);
1252 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1255 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1256 $$ = ValID::create($1);
1258 | VAR_ID { // Is it a named reference...?
1259 $$ = ValID::create($1);
1262 // ValueRef - A reference to a definition... either constant or symbolic
1263 ValueRef : SymbolicValueRef | ConstValueRef
1266 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1267 // type immediately preceeds the value reference, and allows complex constant
1268 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1269 ResolvedVal : Types ValueRef {
1270 $$ = getVal(*$1, $2); delete $1;
1274 BasicBlockList : BasicBlockList BasicBlock {
1275 ($$ = $1)->getBasicBlocks().push_back($2);
1277 | MethodHeader BasicBlock { // Do not allow methods with 0 basic blocks
1278 ($$ = $1)->getBasicBlocks().push_back($2);
1282 // Basic blocks are terminated by branching instructions:
1283 // br, br/cc, switch, ret
1285 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1286 if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1289 $1->getInstList().push_back($3);
1293 | LABELSTR InstructionList OptAssign BBTerminatorInst {
1294 if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1297 $2->getInstList().push_back($4);
1298 if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1304 InstructionList : InstructionList Inst {
1305 $1->getInstList().push_back($2);
1309 $$ = new BasicBlock();
1312 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1313 $$ = new ReturnInst($2);
1315 | RET VOID { // Return with no result...
1316 $$ = new ReturnInst();
1318 | BR LABEL ValueRef { // Unconditional Branch...
1319 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1320 } // Conditional Branch...
1321 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1322 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1323 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1324 getVal(Type::BoolTy, $3));
1326 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1327 SwitchInst *S = new SwitchInst(getVal($2, $3),
1328 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1331 list<pair<ConstPoolVal*, BasicBlock*> >::iterator I = $8->begin(),
1333 for (; I != end; ++I)
1334 S->dest_push_back(I->first, I->second);
1336 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal
1337 EXCEPT ResolvedVal {
1338 const PointerType *PMTy;
1339 const MethodType *Ty;
1341 if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1342 !(Ty = dyn_cast<MethodType>(PMTy->getValueType()))) {
1343 // Pull out the types of all of the arguments...
1344 vector<const Type*> ParamTypes;
1346 for (list<Value*>::iterator I = $5->begin(), E = $5->end(); I != E; ++I)
1347 ParamTypes.push_back((*I)->getType());
1350 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1351 if (isVarArg) ParamTypes.pop_back();
1353 Ty = MethodType::get($2->get(), ParamTypes, isVarArg);
1354 PMTy = PointerType::get(Ty);
1358 Value *V = getVal(PMTy, $3); // Get the method we're calling...
1360 BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1361 BasicBlock *Except = dyn_cast<BasicBlock>($10);
1363 if (Normal == 0 || Except == 0)
1364 ThrowException("Invoke instruction without label destinations!");
1366 // Create the call node...
1367 if (!$5) { // Has no arguments?
1368 $$ = new InvokeInst(cast<Method>(V), Normal, Except, vector<Value*>());
1369 } else { // Has arguments?
1370 // Loop through MethodType's arguments and ensure they are specified
1373 MethodType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1374 MethodType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1375 list<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1377 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1378 if ((*ArgI)->getType() != *I)
1379 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1380 (*I)->getName() + "'!");
1382 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1383 ThrowException("Invalid number of parameters detected!");
1385 $$ = new InvokeInst(cast<Method>(V), Normal, Except,
1386 vector<Value*>($5->begin(), $5->end()));
1393 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1395 ConstPoolVal *V = cast<ConstPoolVal>(getValNonImprovising($2, $3));
1397 ThrowException("May only switch on a constant pool value!");
1399 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1401 | IntType ConstValueRef ',' LABEL ValueRef {
1402 $$ = new list<pair<ConstPoolVal*, BasicBlock*> >();
1403 ConstPoolVal *V = cast<ConstPoolVal>(getValNonImprovising($1, $2));
1406 ThrowException("May only switch on a constant pool value!");
1408 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1411 Inst : OptAssign InstVal {
1412 // Is this definition named?? if so, assign the name...
1413 if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1418 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1419 $$ = new list<pair<Value*, BasicBlock*> >();
1420 $$->push_back(make_pair(getVal(*$1, $3),
1421 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1424 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1426 $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
1427 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1431 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1432 $$ = new list<Value*>();
1435 | ValueRefList ',' ResolvedVal {
1440 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1441 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; }
1443 InstVal : BinaryOps Types ValueRef ',' ValueRef {
1444 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1446 ThrowException("binary operator returned null!");
1449 | UnaryOps ResolvedVal {
1450 $$ = UnaryOperator::create($1, $2);
1452 ThrowException("unary operator returned null!");
1454 | ShiftOps ResolvedVal ',' ResolvedVal {
1455 if ($4->getType() != Type::UByteTy)
1456 ThrowException("Shift amount must be ubyte!");
1457 $$ = new ShiftInst($1, $2, $4);
1459 | CAST ResolvedVal TO Types {
1460 $$ = new CastInst($2, *$4);
1464 const Type *Ty = $2->front().first->getType();
1465 $$ = new PHINode(Ty);
1466 while ($2->begin() != $2->end()) {
1467 if ($2->front().first->getType() != Ty)
1468 ThrowException("All elements of a PHI node must be of the same type!");
1469 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1472 delete $2; // Free the list...
1474 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1475 const PointerType *PMTy;
1476 const MethodType *Ty;
1478 if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1479 !(Ty = dyn_cast<MethodType>(PMTy->getValueType()))) {
1480 // Pull out the types of all of the arguments...
1481 vector<const Type*> ParamTypes;
1483 for (list<Value*>::iterator I = $5->begin(), E = $5->end(); I != E; ++I)
1484 ParamTypes.push_back((*I)->getType());
1487 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1488 if (isVarArg) ParamTypes.pop_back();
1490 Ty = MethodType::get($2->get(), ParamTypes, isVarArg);
1491 PMTy = PointerType::get(Ty);
1495 Value *V = getVal(PMTy, $3); // Get the method we're calling...
1497 // Create the call node...
1498 if (!$5) { // Has no arguments?
1499 $$ = new CallInst(cast<Method>(V), vector<Value*>());
1500 } else { // Has arguments?
1501 // Loop through MethodType's arguments and ensure they are specified
1504 MethodType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1505 MethodType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1506 list<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1508 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1509 if ((*ArgI)->getType() != *I)
1510 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1511 (*I)->getName() + "'!");
1513 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1514 ThrowException("Invalid number of parameters detected!");
1516 $$ = new CallInst(V, vector<Value*>($5->begin(), $5->end()));
1524 // UByteList - List of ubyte values for load and store instructions
1525 UByteList : ',' ConstVector {
1528 $$ = new vector<ConstPoolVal*>();
1531 MemoryInst : MALLOC Types {
1532 $$ = new MallocInst(PointerType::get(*$2));
1535 | MALLOC Types ',' UINT ValueRef {
1536 if (!(*$2)->isArrayType() || cast<const ArrayType>($2->get())->isSized())
1537 ThrowException("Trying to allocate " + (*$2)->getName() +
1538 " as unsized array!");
1539 const Type *Ty = PointerType::get(*$2);
1540 $$ = new MallocInst(Ty, getVal($4, $5));
1544 $$ = new AllocaInst(PointerType::get(*$2));
1547 | ALLOCA Types ',' UINT ValueRef {
1548 if (!(*$2)->isArrayType() || cast<const ArrayType>($2->get())->isSized())
1549 ThrowException("Trying to allocate " + (*$2)->getName() +
1550 " as unsized array!");
1551 const Type *Ty = PointerType::get(*$2);
1552 Value *ArrSize = getVal($4, $5);
1553 $$ = new AllocaInst(Ty, ArrSize);
1556 | FREE ResolvedVal {
1557 if (!$2->getType()->isPointerType())
1558 ThrowException("Trying to free nonpointer type " +
1559 $2->getType()->getName() + "!");
1560 $$ = new FreeInst($2);
1563 | LOAD Types ValueRef UByteList {
1564 if (!(*$2)->isPointerType())
1565 ThrowException("Can't load from nonpointer type: " +
1566 (*$2)->getDescription());
1567 if (LoadInst::getIndexedType(*$2, *$4) == 0)
1568 ThrowException("Invalid indices for load instruction!");
1570 $$ = new LoadInst(getVal(*$2, $3), *$4);
1571 delete $4; // Free the vector...
1574 | STORE ResolvedVal ',' Types ValueRef UByteList {
1575 if (!(*$4)->isPointerType())
1576 ThrowException("Can't store to a nonpointer type: " + (*$4)->getName());
1577 const Type *ElTy = StoreInst::getIndexedType(*$4, *$6);
1579 ThrowException("Can't store into that field list!");
1580 if (ElTy != $2->getType())
1581 ThrowException("Can't store '" + $2->getType()->getName() +
1582 "' into space of type '" + ElTy->getName() + "'!");
1583 $$ = new StoreInst($2, getVal(*$4, $5), *$6);
1584 delete $4; delete $6;
1586 | GETELEMENTPTR Types ValueRef UByteList {
1587 if (!(*$2)->isPointerType())
1588 ThrowException("getelementptr insn requires pointer operand!");
1589 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1590 ThrowException("Can't get element ptr '" + (*$2)->getName() + "'!");
1591 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1592 delete $2; delete $4;
1596 int yyerror(const char *ErrorMsg) {
1597 ThrowException(string("Parse error: ") + ErrorMsg);