1 //===-- llvmAsmParser.y - Parser for llvm assembly files ---------*- C++ -*--=//
3 // This file implements the bison parser for LLVM assembly languages files.
5 //===------------------------------------------------------------------------=//
8 #include "ParserInternals.h"
9 #include "llvm/Assembly/Parser.h"
10 #include "llvm/SymbolTable.h"
11 #include "llvm/Module.h"
12 #include "llvm/GlobalVariable.h"
13 #include "llvm/Function.h"
14 #include "llvm/BasicBlock.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/iTerminators.h"
17 #include "llvm/iMemory.h"
18 #include "llvm/iPHINode.h"
19 #include "llvm/Argument.h"
20 #include "Support/STLExtras.h"
21 #include "Support/DepthFirstIterator.h"
23 #include <utility> // Get definition of pair class
25 #include <stdio.h> // This embarasment is due to our flex lexer...
36 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
37 int yylex(); // declaration" of xxx warnings.
40 static Module *ParserResult;
43 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
44 // relating to upreferences in the input stream.
46 //#define DEBUG_UPREFS 1
48 #define UR_OUT(X) cerr << X
53 // This contains info used when building the body of a method. It is destroyed
54 // when the method is completed.
56 typedef vector<Value *> ValueList; // Numbered defs
57 static void ResolveDefinitions(vector<ValueList> &LateResolvers,
58 vector<ValueList> *FutureLateResolvers = 0);
60 static struct PerModuleInfo {
61 Module *CurrentModule;
62 vector<ValueList> Values; // Module level numbered definitions
63 vector<ValueList> LateResolveValues;
64 vector<PATypeHolder> Types;
65 map<ValID, PATypeHolder> LateResolveTypes;
67 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
68 // references to global values. Global values may be referenced before they
69 // are defined, and if so, the temporary object that they represent is held
70 // here. This is used for forward references of ConstantPointerRefs.
72 typedef map<pair<const PointerType *, ValID>, GlobalVariable*> GlobalRefsType;
73 GlobalRefsType GlobalRefs;
76 // If we could not resolve some methods at method compilation time (calls to
77 // methods before they are defined), resolve them now... Types are resolved
78 // when the constant pool has been completely parsed.
80 ResolveDefinitions(LateResolveValues);
82 // Check to make sure that all global value forward references have been
85 if (!GlobalRefs.empty()) {
86 string UndefinedReferences = "Unresolved global references exist:\n";
88 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
90 UndefinedReferences += " " + I->first.first->getDescription() + " " +
91 I->first.second.getName() + "\n";
93 ThrowException(UndefinedReferences);
96 Values.clear(); // Clear out method local definitions
102 // DeclareNewGlobalValue - Called every type a new GV has been defined. This
103 // is used to remove things from the forward declaration map, resolving them
104 // to the correct thing as needed.
106 void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
107 // Check to see if there is a forward reference to this global variable...
108 // if there is, eliminate it and patch the reference to use the new def'n.
109 GlobalRefsType::iterator I = GlobalRefs.find(make_pair(GV->getType(), D));
111 if (I != GlobalRefs.end()) {
112 GlobalVariable *OldGV = I->second; // Get the placeholder...
113 I->first.second.destroy(); // Free string memory if neccesary
115 // Loop over all of the uses of the GlobalValue. The only thing they are
116 // allowed to be at this point is ConstantPointerRef's.
117 assert(OldGV->use_size() == 1 && "Only one reference should exist!");
118 while (!OldGV->use_empty()) {
119 User *U = OldGV->use_back(); // Must be a ConstantPointerRef...
120 ConstantPointerRef *CPPR = cast<ConstantPointerRef>(U);
121 assert(CPPR->getValue() == OldGV && "Something isn't happy");
123 // Change the const pool reference to point to the real global variable
124 // now. This should drop a use from the OldGV.
125 CPPR->mutateReference(GV);
128 // Remove GV from the module...
129 CurrentModule->getGlobalList().remove(OldGV);
130 delete OldGV; // Delete the old placeholder
132 // Remove the map entry for the global now that it has been created...
139 static struct PerFunctionInfo {
140 Function *CurrentFunction; // Pointer to current method being created
142 vector<ValueList> Values; // Keep track of numbered definitions
143 vector<ValueList> LateResolveValues;
144 vector<PATypeHolder> Types;
145 map<ValID, PATypeHolder> LateResolveTypes;
146 bool isDeclare; // Is this method a forward declararation?
148 inline PerFunctionInfo() {
153 inline ~PerFunctionInfo() {}
155 inline void FunctionStart(Function *M) {
159 void FunctionDone() {
160 // If we could not resolve some blocks at parsing time (forward branches)
161 // resolve the branches now...
162 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
164 Values.clear(); // Clear out method local definitions
169 } CurMeth; // Info for the current method...
171 static bool inFunctionScope() { return CurMeth.CurrentFunction != 0; }
174 //===----------------------------------------------------------------------===//
175 // Code to handle definitions of all the types
176 //===----------------------------------------------------------------------===//
178 static int InsertValue(Value *D, vector<ValueList> &ValueTab = CurMeth.Values) {
179 if (D->hasName()) return -1; // Is this a numbered definition?
181 // Yes, insert the value into the value table...
182 unsigned type = D->getType()->getUniqueID();
183 if (ValueTab.size() <= type)
184 ValueTab.resize(type+1, ValueList());
185 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
186 ValueTab[type].push_back(D);
187 return ValueTab[type].size()-1;
190 // TODO: FIXME when Type are not const
191 static void InsertType(const Type *Ty, vector<PATypeHolder> &Types) {
195 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
197 case 0: { // Is it a numbered definition?
198 unsigned Num = (unsigned)D.Num;
200 // Module constants occupy the lowest numbered slots...
201 if (Num < CurModule.Types.size())
202 return CurModule.Types[Num];
204 Num -= CurModule.Types.size();
206 // Check that the number is within bounds...
207 if (Num <= CurMeth.Types.size())
208 return CurMeth.Types[Num];
211 case 1: { // Is it a named definition?
213 SymbolTable *SymTab = 0;
214 if (inFunctionScope()) SymTab = CurMeth.CurrentFunction->getSymbolTable();
215 Value *N = SymTab ? SymTab->lookup(Type::TypeTy, Name) : 0;
218 // Symbol table doesn't automatically chain yet... because the method
219 // hasn't been added to the module...
221 SymTab = CurModule.CurrentModule->getSymbolTable();
223 N = SymTab->lookup(Type::TypeTy, Name);
227 D.destroy(); // Free old strdup'd memory...
228 return cast<const Type>(N);
231 ThrowException("Invalid symbol type reference!");
234 // If we reached here, we referenced either a symbol that we don't know about
235 // or an id number that hasn't been read yet. We may be referencing something
236 // forward, so just create an entry to be resolved later and get to it...
238 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
240 map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
241 CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
243 map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
244 if (I != LateResolver.end()) {
248 Type *Typ = OpaqueType::get();
249 LateResolver.insert(make_pair(D, Typ));
253 static Value *lookupInSymbolTable(const Type *Ty, const string &Name) {
254 SymbolTable *SymTab =
255 inFunctionScope() ? CurMeth.CurrentFunction->getSymbolTable() : 0;
256 Value *N = SymTab ? SymTab->lookup(Ty, Name) : 0;
259 // Symbol table doesn't automatically chain yet... because the method
260 // hasn't been added to the module...
262 SymTab = CurModule.CurrentModule->getSymbolTable();
264 N = SymTab->lookup(Ty, Name);
270 // getValNonImprovising - Look up the value specified by the provided type and
271 // the provided ValID. If the value exists and has already been defined, return
272 // it. Otherwise return null.
274 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
275 if (isa<FunctionType>(Ty))
276 ThrowException("Functions are not values and "
277 "must be referenced as pointers");
280 case ValID::NumberVal: { // Is it a numbered definition?
281 unsigned type = Ty->getUniqueID();
282 unsigned Num = (unsigned)D.Num;
284 // Module constants occupy the lowest numbered slots...
285 if (type < CurModule.Values.size()) {
286 if (Num < CurModule.Values[type].size())
287 return CurModule.Values[type][Num];
289 Num -= CurModule.Values[type].size();
292 // Make sure that our type is within bounds
293 if (CurMeth.Values.size() <= type) return 0;
295 // Check that the number is within bounds...
296 if (CurMeth.Values[type].size() <= Num) return 0;
298 return CurMeth.Values[type][Num];
301 case ValID::NameVal: { // Is it a named definition?
302 Value *N = lookupInSymbolTable(Ty, string(D.Name));
303 if (N == 0) return 0;
305 D.destroy(); // Free old strdup'd memory...
309 // Check to make sure that "Ty" is an integral type, and that our
310 // value will fit into the specified type...
311 case ValID::ConstSIntVal: // Is it a constant pool reference??
312 if (Ty == Type::BoolTy) { // Special handling for boolean data
313 return ConstantBool::get(D.ConstPool64 != 0);
315 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
316 ThrowException("Symbolic constant pool value '" +
317 itostr(D.ConstPool64) + "' is invalid for type '" +
318 Ty->getDescription() + "'!");
319 return ConstantSInt::get(Ty, D.ConstPool64);
322 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
323 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
324 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
325 ThrowException("Integral constant pool reference is invalid!");
326 } else { // This is really a signed reference. Transmogrify.
327 return ConstantSInt::get(Ty, D.ConstPool64);
330 return ConstantUInt::get(Ty, D.UConstPool64);
333 case ValID::ConstFPVal: // Is it a floating point const pool reference?
334 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
335 ThrowException("FP constant invalid for type!!");
336 return ConstantFP::get(Ty, D.ConstPoolFP);
338 case ValID::ConstNullVal: // Is it a null value?
339 if (!Ty->isPointerType())
340 ThrowException("Cannot create a a non pointer null!");
341 return ConstantPointerNull::get(cast<PointerType>(Ty));
344 assert(0 && "Unhandled case!");
348 assert(0 && "Unhandled case!");
353 // getVal - This function is identical to getValNonImprovising, except that if a
354 // value is not already defined, it "improvises" by creating a placeholder var
355 // that looks and acts just like the requested variable. When the value is
356 // defined later, all uses of the placeholder variable are replaced with the
359 static Value *getVal(const Type *Ty, const ValID &D) {
360 assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
362 // See if the value has already been defined...
363 Value *V = getValNonImprovising(Ty, D);
366 // If we reached here, we referenced either a symbol that we don't know about
367 // or an id number that hasn't been read yet. We may be referencing something
368 // forward, so just create an entry to be resolved later and get to it...
371 switch (Ty->getPrimitiveID()) {
372 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
373 default: d = new ValuePlaceHolder(Ty, D); break;
376 assert(d != 0 && "How did we not make something?");
377 if (inFunctionScope())
378 InsertValue(d, CurMeth.LateResolveValues);
380 InsertValue(d, CurModule.LateResolveValues);
385 //===----------------------------------------------------------------------===//
386 // Code to handle forward references in instructions
387 //===----------------------------------------------------------------------===//
389 // This code handles the late binding needed with statements that reference
390 // values not defined yet... for example, a forward branch, or the PHI node for
393 // This keeps a table (CurMeth.LateResolveValues) of all such forward references
394 // and back patchs after we are done.
397 // ResolveDefinitions - If we could not resolve some defs at parsing
398 // time (forward branches, phi functions for loops, etc...) resolve the
401 static void ResolveDefinitions(vector<ValueList> &LateResolvers,
402 vector<ValueList> *FutureLateResolvers = 0) {
403 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
404 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
405 while (!LateResolvers[ty].empty()) {
406 Value *V = LateResolvers[ty].back();
407 assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
409 LateResolvers[ty].pop_back();
410 ValID &DID = getValIDFromPlaceHolder(V);
412 Value *TheRealValue = getValNonImprovising(Type::getUniqueIDType(ty),DID);
414 V->replaceAllUsesWith(TheRealValue);
416 } else if (FutureLateResolvers) {
417 // Functions have their unresolved items forwarded to the module late
419 InsertValue(V, *FutureLateResolvers);
422 ThrowException("Reference to an invalid definition: '" +DID.getName()+
423 "' of type '" + V->getType()->getDescription() + "'",
424 getLineNumFromPlaceHolder(V));
426 ThrowException("Reference to an invalid definition: #" +
427 itostr(DID.Num) + " of type '" +
428 V->getType()->getDescription() + "'",
429 getLineNumFromPlaceHolder(V));
434 LateResolvers.clear();
437 // ResolveTypeTo - A brand new type was just declared. This means that (if
438 // name is not null) things referencing Name can be resolved. Otherwise, things
439 // refering to the number can be resolved. Do this now.
441 static void ResolveTypeTo(char *Name, const Type *ToTy) {
442 vector<PATypeHolder> &Types = inFunctionScope() ?
443 CurMeth.Types : CurModule.Types;
446 if (Name) D = ValID::create(Name);
447 else D = ValID::create((int)Types.size());
449 map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
450 CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
452 map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
453 if (I != LateResolver.end()) {
454 cast<DerivedType>(I->second.get())->refineAbstractTypeTo(ToTy);
455 LateResolver.erase(I);
459 // ResolveTypes - At this point, all types should be resolved. Any that aren't
462 static void ResolveTypes(map<ValID, PATypeHolder> &LateResolveTypes) {
463 if (!LateResolveTypes.empty()) {
464 const ValID &DID = LateResolveTypes.begin()->first;
466 if (DID.Type == ValID::NameVal)
467 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
469 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
474 // setValueName - Set the specified value to the name given. The name may be
475 // null potentially, in which case this is a noop. The string passed in is
476 // assumed to be a malloc'd string buffer, and is freed by this function.
478 // This function returns true if the value has already been defined, but is
479 // allowed to be redefined in the specified context. If the name is a new name
480 // for the typeplane, false is returned.
482 static bool setValueName(Value *V, char *NameStr) {
483 if (NameStr == 0) return false;
485 string Name(NameStr); // Copy string
486 free(NameStr); // Free old string
488 if (V->getType() == Type::VoidTy)
489 ThrowException("Can't assign name '" + Name +
490 "' to a null valued instruction!");
492 SymbolTable *ST = inFunctionScope() ?
493 CurMeth.CurrentFunction->getSymbolTableSure() :
494 CurModule.CurrentModule->getSymbolTableSure();
496 Value *Existing = ST->lookup(V->getType(), Name);
497 if (Existing) { // Inserting a name that is already defined???
498 // There is only one case where this is allowed: when we are refining an
499 // opaque type. In this case, Existing will be an opaque type.
500 if (const Type *Ty = dyn_cast<const Type>(Existing)) {
501 if (OpaqueType *OpTy = dyn_cast<OpaqueType>(Ty)) {
502 // We ARE replacing an opaque type!
503 OpTy->refineAbstractTypeTo(cast<Type>(V));
508 // Otherwise, we are a simple redefinition of a value, check to see if it
509 // is defined the same as the old one...
510 if (const Type *Ty = dyn_cast<const Type>(Existing)) {
511 if (Ty == cast<const Type>(V)) return true; // Yes, it's equal.
512 // cerr << "Type: " << Ty->getDescription() << " != "
513 // << cast<const Type>(V)->getDescription() << "!\n";
514 } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
515 // We are allowed to redefine a global variable in two circumstances:
516 // 1. If at least one of the globals is uninitialized or
517 // 2. If both initializers have the same value.
519 // This can only be done if the const'ness of the vars is the same.
521 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
522 if (EGV->isConstant() == GV->isConstant() &&
523 (!EGV->hasInitializer() || !GV->hasInitializer() ||
524 EGV->getInitializer() == GV->getInitializer())) {
526 // Make sure the existing global version gets the initializer!
527 if (GV->hasInitializer() && !EGV->hasInitializer())
528 EGV->setInitializer(GV->getInitializer());
530 delete GV; // Destroy the duplicate!
531 return true; // They are equivalent!
535 ThrowException("Redefinition of value named '" + Name + "' in the '" +
536 V->getType()->getDescription() + "' type plane!");
539 V->setName(Name, ST);
544 //===----------------------------------------------------------------------===//
545 // Code for handling upreferences in type names...
548 // TypeContains - Returns true if Ty contains E in it.
550 static bool TypeContains(const Type *Ty, const Type *E) {
551 return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
555 static vector<pair<unsigned, OpaqueType *> > UpRefs;
557 static PATypeHolder HandleUpRefs(const Type *ty) {
559 UR_OUT("Type '" << ty->getDescription() <<
560 "' newly formed. Resolving upreferences.\n" <<
561 UpRefs.size() << " upreferences active!\n");
562 for (unsigned i = 0; i < UpRefs.size(); ) {
563 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
564 << UpRefs[i].second->getDescription() << ") = "
565 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << endl);
566 if (TypeContains(Ty, UpRefs[i].second)) {
567 unsigned Level = --UpRefs[i].first; // Decrement level of upreference
568 UR_OUT(" Uplevel Ref Level = " << Level << endl);
569 if (Level == 0) { // Upreference should be resolved!
570 UR_OUT(" * Resolving upreference for "
571 << UpRefs[i].second->getDescription() << endl;
572 string OldName = UpRefs[i].second->getDescription());
573 UpRefs[i].second->refineAbstractTypeTo(Ty);
574 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
575 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
576 << (const void*)Ty << ", " << Ty->getDescription() << endl);
581 ++i; // Otherwise, no resolve, move on...
583 // FIXME: TODO: this should return the updated type
588 //===----------------------------------------------------------------------===//
589 // RunVMAsmParser - Define an interface to this parser
590 //===----------------------------------------------------------------------===//
592 Module *RunVMAsmParser(const string &Filename, FILE *F) {
594 CurFilename = Filename;
595 llvmAsmlineno = 1; // Reset the current line number...
597 CurModule.CurrentModule = new Module(); // Allocate a new module to read
598 yyparse(); // Parse the file.
599 Module *Result = ParserResult;
600 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
610 Function *FunctionVal;
611 std::pair<Argument*, char*> *ArgVal;
612 BasicBlock *BasicBlockVal;
613 TerminatorInst *TermInstVal;
614 Instruction *InstVal;
617 const Type *PrimType;
618 PATypeHolder *TypeVal;
621 std::list<std::pair<Argument*,char*> > *ArgList;
622 std::vector<Value*> *ValueList;
623 std::list<PATypeHolder> *TypeList;
624 std::list<std::pair<Value*,
625 BasicBlock*> > *PHIList; // Represent the RHS of PHI node
626 std::vector<std::pair<Constant*, BasicBlock*> > *JumpTable;
627 std::vector<Constant*> *ConstVector;
636 char *StrVal; // This memory is strdup'd!
637 ValID ValIDVal; // strdup'd memory maybe!
639 Instruction::UnaryOps UnaryOpVal;
640 Instruction::BinaryOps BinaryOpVal;
641 Instruction::TermOps TermOpVal;
642 Instruction::MemoryOps MemOpVal;
643 Instruction::OtherOps OtherOpVal;
646 %type <ModuleVal> Module FunctionList
647 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
648 %type <BasicBlockVal> BasicBlock InstructionList
649 %type <TermInstVal> BBTerminatorInst
650 %type <InstVal> Inst InstVal MemoryInst
651 %type <ConstVal> ConstVal
652 %type <ConstVector> ConstVector
653 %type <ArgList> ArgList ArgListH
654 %type <ArgVal> ArgVal
655 %type <PHIList> PHIList
656 %type <ValueList> ValueRefList ValueRefListE // For call param lists
657 %type <ValueList> IndexList // For GEP derived indices
658 %type <TypeList> TypeListI ArgTypeListI
659 %type <JumpTable> JumpTable
660 %type <BoolVal> GlobalType OptInternal // GLOBAL or CONSTANT? Intern?
662 // ValueRef - Unresolved reference to a definition or BB
663 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
664 %type <ValueVal> ResolvedVal // <type> <valref> pair
665 // Tokens and types for handling constant integer values
667 // ESINT64VAL - A negative number within long long range
668 %token <SInt64Val> ESINT64VAL
670 // EUINT64VAL - A positive number within uns. long long range
671 %token <UInt64Val> EUINT64VAL
672 %type <SInt64Val> EINT64VAL
674 %token <SIntVal> SINTVAL // Signed 32 bit ints...
675 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
676 %type <SIntVal> INTVAL
677 %token <FPVal> FPVAL // Float or Double constant
680 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
681 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
682 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
683 %token <PrimType> FLOAT DOUBLE TYPE LABEL
685 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
686 %type <StrVal> OptVAR_ID OptAssign
689 %token IMPLEMENTATION TRUE FALSE BEGINTOK END DECLARE GLOBAL CONSTANT UNINIT
690 %token TO EXCEPT DOTDOTDOT STRING NULL_TOK CONST INTERNAL OPAQUE
692 // Basic Block Terminating Operators
693 %token <TermOpVal> RET BR SWITCH
696 %type <UnaryOpVal> UnaryOps // all the unary operators
697 %token <UnaryOpVal> NOT
700 %type <BinaryOpVal> BinaryOps // all the binary operators
701 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
702 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
704 // Memory Instructions
705 %token <MemoryOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
708 %type <OtherOpVal> ShiftOps
709 %token <OtherOpVal> PHI CALL INVOKE CAST SHL SHR
714 // Handle constant integer size restriction and conversion...
719 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
720 ThrowException("Value too large for type!");
725 EINT64VAL : ESINT64VAL // These have same type and can't cause problems...
726 EINT64VAL : EUINT64VAL {
727 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
728 ThrowException("Value too large for type!");
732 // Operations that are notably excluded from this list include:
733 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
736 BinaryOps : ADD | SUB | MUL | DIV | REM | AND | OR | XOR
737 BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
740 // These are some types that allow classification if we only want a particular
741 // thing... for example, only a signed, unsigned, or integral type.
742 SIntType : LONG | INT | SHORT | SBYTE
743 UIntType : ULONG | UINT | USHORT | UBYTE
744 IntType : SIntType | UIntType
745 FPType : FLOAT | DOUBLE
747 // OptAssign - Value producing statements have an optional assignment component
748 OptAssign : VAR_ID '=' {
755 OptInternal : INTERNAL { $$ = true; } | /*empty*/ { $$ = false; }
757 //===----------------------------------------------------------------------===//
758 // Types includes all predefined types... except void, because it can only be
759 // used in specific contexts (method returning void for example). To have
760 // access to it, a user must explicitly use TypesV.
763 // TypesV includes all of 'Types', but it also includes the void type.
764 TypesV : Types | VOID { $$ = new PATypeHolder($1); }
765 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); }
769 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
774 // Derived types are added later...
776 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
777 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL
779 $$ = new PATypeHolder(OpaqueType::get());
782 $$ = new PATypeHolder($1);
784 UpRTypes : ValueRef { // Named types are also simple types...
785 $$ = new PATypeHolder(getTypeVal($1));
788 // Include derived types in the Types production.
790 UpRTypes : '\\' EUINT64VAL { // Type UpReference
791 if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
792 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
793 UpRefs.push_back(make_pair((unsigned)$2, OT)); // Add to vector...
794 $$ = new PATypeHolder(OT);
795 UR_OUT("New Upreference!\n");
797 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
798 vector<const Type*> Params;
799 mapto($3->begin(), $3->end(), std::back_inserter(Params),
800 std::mem_fun_ref(&PATypeHandle<Type>::get));
801 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
802 if (isVarArg) Params.pop_back();
804 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
805 delete $3; // Delete the argument list
806 delete $1; // Delete the old type handle
808 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
809 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
812 | '{' TypeListI '}' { // Structure type?
813 vector<const Type*> Elements;
814 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
815 std::mem_fun_ref(&PATypeHandle<Type>::get));
817 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
820 | '{' '}' { // Empty structure type?
821 $$ = new PATypeHolder(StructType::get(vector<const Type*>()));
823 | UpRTypes '*' { // Pointer type?
824 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
828 // TypeList - Used for struct declarations and as a basis for method type
829 // declaration type lists
831 TypeListI : UpRTypes {
832 $$ = new list<PATypeHolder>();
833 $$->push_back(*$1); delete $1;
835 | TypeListI ',' UpRTypes {
836 ($$=$1)->push_back(*$3); delete $3;
839 // ArgTypeList - List of types for a method type declaration...
840 ArgTypeListI : TypeListI
841 | TypeListI ',' DOTDOTDOT {
842 ($$=$1)->push_back(Type::VoidTy);
845 ($$ = new list<PATypeHolder>())->push_back(Type::VoidTy);
848 $$ = new list<PATypeHolder>();
852 // ConstVal - The various declarations that go into the constant pool. This
853 // includes all forward declarations of types, constants, and functions.
855 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
856 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
858 ThrowException("Cannot make array constant with type: '" +
859 (*$1)->getDescription() + "'!");
860 const Type *ETy = ATy->getElementType();
861 int NumElements = ATy->getNumElements();
863 // Verify that we have the correct size...
864 if (NumElements != -1 && NumElements != (int)$3->size())
865 ThrowException("Type mismatch: constant sized array initialized with " +
866 utostr($3->size()) + " arguments, but has size of " +
867 itostr(NumElements) + "!");
869 // Verify all elements are correct type!
870 for (unsigned i = 0; i < $3->size(); i++) {
871 if (ETy != (*$3)[i]->getType())
872 ThrowException("Element #" + utostr(i) + " is not of type '" +
873 ETy->getDescription() +"' as required!\nIt is of type '"+
874 (*$3)[i]->getType()->getDescription() + "'.");
877 $$ = ConstantArray::get(ATy, *$3);
878 delete $1; delete $3;
881 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
883 ThrowException("Cannot make array constant with type: '" +
884 (*$1)->getDescription() + "'!");
886 int NumElements = ATy->getNumElements();
887 if (NumElements != -1 && NumElements != 0)
888 ThrowException("Type mismatch: constant sized array initialized with 0"
889 " arguments, but has size of " + itostr(NumElements) +"!");
890 $$ = ConstantArray::get(ATy, vector<Constant*>());
893 | Types 'c' STRINGCONSTANT {
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 const Type *ETy = ATy->getElementType();
901 char *EndStr = UnEscapeLexed($3, true);
902 if (NumElements != -1 && NumElements != (EndStr-$3))
903 ThrowException("Can't build string constant of size " +
904 itostr((int)(EndStr-$3)) +
905 " when array has size " + itostr(NumElements) + "!");
906 vector<Constant*> Vals;
907 if (ETy == Type::SByteTy) {
908 for (char *C = $3; C != EndStr; ++C)
909 Vals.push_back(ConstantSInt::get(ETy, *C));
910 } else if (ETy == Type::UByteTy) {
911 for (char *C = $3; C != EndStr; ++C)
912 Vals.push_back(ConstantUInt::get(ETy, *C));
915 ThrowException("Cannot build string arrays of non byte sized elements!");
918 $$ = ConstantArray::get(ATy, Vals);
921 | Types '{' ConstVector '}' {
922 const StructType *STy = dyn_cast<const StructType>($1->get());
924 ThrowException("Cannot make struct constant with type: '" +
925 (*$1)->getDescription() + "'!");
926 // FIXME: TODO: Check to see that the constants are compatible with the type
928 $$ = ConstantStruct::get(STy, *$3);
929 delete $1; delete $3;
932 const PointerType *PTy = dyn_cast<const PointerType>($1->get());
934 ThrowException("Cannot make null pointer constant with type: '" +
935 (*$1)->getDescription() + "'!");
937 $$ = ConstantPointerNull::get(PTy);
940 | Types SymbolicValueRef {
941 const PointerType *Ty = dyn_cast<const PointerType>($1->get());
943 ThrowException("Global const reference must be a pointer type!");
945 Value *V = getValNonImprovising(Ty, $2);
947 // If this is an initializer for a constant pointer, which is referencing a
948 // (currently) undefined variable, create a stub now that shall be replaced
949 // in the future with the right type of variable.
952 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
953 const PointerType *PT = cast<PointerType>(Ty);
955 // First check to see if the forward references value is already created!
956 PerModuleInfo::GlobalRefsType::iterator I =
957 CurModule.GlobalRefs.find(make_pair(PT, $2));
959 if (I != CurModule.GlobalRefs.end()) {
960 V = I->second; // Placeholder already exists, use it...
962 // TODO: Include line number info by creating a subclass of
963 // TODO: GlobalVariable here that includes the said information!
965 // Create a placeholder for the global variable reference...
966 GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
968 // Keep track of the fact that we have a forward ref to recycle it
969 CurModule.GlobalRefs.insert(make_pair(make_pair(PT, $2), GV));
971 // Must temporarily push this value into the module table...
972 CurModule.CurrentModule->getGlobalList().push_back(GV);
977 GlobalValue *GV = cast<GlobalValue>(V);
978 $$ = ConstantPointerRef::get(GV);
979 delete $1; // Free the type handle
983 ConstVal : SIntType EINT64VAL { // integral constants
984 if (!ConstantSInt::isValueValidForType($1, $2))
985 ThrowException("Constant value doesn't fit in type!");
986 $$ = ConstantSInt::get($1, $2);
988 | UIntType EUINT64VAL { // integral constants
989 if (!ConstantUInt::isValueValidForType($1, $2))
990 ThrowException("Constant value doesn't fit in type!");
991 $$ = ConstantUInt::get($1, $2);
993 | BOOL TRUE { // Boolean constants
994 $$ = ConstantBool::True;
996 | BOOL FALSE { // Boolean constants
997 $$ = ConstantBool::False;
999 | FPType FPVAL { // Float & Double constants
1000 $$ = ConstantFP::get($1, $2);
1003 // ConstVector - A list of comma seperated constants.
1004 ConstVector : ConstVector ',' ConstVal {
1005 ($$ = $1)->push_back($3);
1008 $$ = new vector<Constant*>();
1013 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1014 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; }
1017 // ConstPool - Constants with optional names assigned to them.
1018 ConstPool : ConstPool OptAssign CONST ConstVal {
1019 if (setValueName($4, $2)) { assert(0 && "No redefinitions allowed!"); }
1022 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1023 // Eagerly resolve types. This is not an optimization, this is a
1024 // requirement that is due to the fact that we could have this:
1026 // %list = type { %list * }
1027 // %list = type { %list * } ; repeated type decl
1029 // If types are not resolved eagerly, then the two types will not be
1030 // determined to be the same type!
1032 ResolveTypeTo($2, $4->get());
1034 // TODO: FIXME when Type are not const
1035 if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1036 // If this is not a redefinition of a type...
1038 InsertType($4->get(),
1039 inFunctionScope() ? CurMeth.Types : CurModule.Types);
1045 | ConstPool FunctionProto { // Function prototypes can be in const pool
1047 | ConstPool OptAssign OptInternal GlobalType ConstVal {
1048 const Type *Ty = $5->getType();
1049 // Global declarations appear in Constant Pool
1050 Constant *Initializer = $5;
1051 if (Initializer == 0)
1052 ThrowException("Global value initializer is not a constant!");
1054 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1055 if (!setValueName(GV, $2)) { // If not redefining...
1056 CurModule.CurrentModule->getGlobalList().push_back(GV);
1057 int Slot = InsertValue(GV, CurModule.Values);
1060 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1062 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1063 (char*)GV->getName().c_str()));
1067 | ConstPool OptAssign OptInternal UNINIT GlobalType Types {
1068 const Type *Ty = *$6;
1069 // Global declarations appear in Constant Pool
1070 GlobalVariable *GV = new GlobalVariable(Ty, $5, $3);
1071 if (!setValueName(GV, $2)) { // If not redefining...
1072 CurModule.CurrentModule->getGlobalList().push_back(GV);
1073 int Slot = InsertValue(GV, CurModule.Values);
1076 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1078 assert(GV->hasName() && "Not named and not numbered!?");
1079 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1080 (char*)GV->getName().c_str()));
1085 | /* empty: end of list */ {
1089 //===----------------------------------------------------------------------===//
1090 // Rules to match Modules
1091 //===----------------------------------------------------------------------===//
1093 // Module rule: Capture the result of parsing the whole file into a result
1096 Module : FunctionList {
1097 $$ = ParserResult = $1;
1098 CurModule.ModuleDone();
1101 // FunctionList - A list of methods, preceeded by a constant pool.
1103 FunctionList : FunctionList Function {
1105 assert($2->getParent() == 0 && "Function already in module!");
1106 $1->getFunctionList().push_back($2);
1107 CurMeth.FunctionDone();
1109 | FunctionList FunctionProto {
1112 | ConstPool IMPLEMENTATION {
1113 $$ = CurModule.CurrentModule;
1114 // Resolve circular types before we parse the body of the module
1115 ResolveTypes(CurModule.LateResolveTypes);
1119 //===----------------------------------------------------------------------===//
1120 // Rules to match Function Headers
1121 //===----------------------------------------------------------------------===//
1123 OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; }
1125 ArgVal : Types OptVAR_ID {
1126 $$ = new pair<Argument*, char*>(new Argument(*$1), $2);
1127 delete $1; // Delete the type handle..
1130 ArgListH : ArgVal ',' ArgListH {
1132 $3->push_front(*$1);
1136 $$ = new list<pair<Argument*,char*> >();
1137 $$->push_front(*$1);
1141 $$ = new list<pair<Argument*, char*> >();
1142 $$->push_front(pair<Argument*,char*>(new Argument(Type::VoidTy), 0));
1145 ArgList : ArgListH {
1152 FunctionHeaderH : OptInternal TypesV STRINGCONSTANT '(' ArgList ')' {
1154 string FunctionName($3);
1156 vector<const Type*> ParamTypeList;
1158 for (list<pair<Argument*,char*> >::iterator I = $5->begin();
1159 I != $5->end(); ++I)
1160 ParamTypeList.push_back(I->first->getType());
1162 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1163 if (isVarArg) ParamTypeList.pop_back();
1165 const FunctionType *MT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1166 const PointerType *PMT = PointerType::get(MT);
1170 if (SymbolTable *ST = CurModule.CurrentModule->getSymbolTable()) {
1171 // Is the function already in symtab?
1172 if (Value *V = ST->lookup(PMT, FunctionName)) {
1173 M = cast<Function>(V);
1175 // Yes it is. If this is the case, either we need to be a forward decl,
1176 // or it needs to be.
1177 if (!CurMeth.isDeclare && !M->isExternal())
1178 ThrowException("Redefinition of method '" + FunctionName + "'!");
1180 // If we found a preexisting method prototype, remove it from the module,
1181 // so that we don't get spurious conflicts with global & local variables.
1183 CurModule.CurrentModule->getFunctionList().remove(M);
1187 if (M == 0) { // Not already defined?
1188 M = new Function(MT, $1, FunctionName);
1189 InsertValue(M, CurModule.Values);
1190 CurModule.DeclareNewGlobalValue(M, ValID::create($3));
1192 free($3); // Free strdup'd memory!
1194 CurMeth.FunctionStart(M);
1196 // Add all of the arguments we parsed to the method...
1197 if ($5 && !CurMeth.isDeclare) { // Is null if empty...
1198 Function::ArgumentListType &ArgList = M->getArgumentList();
1200 for (list<pair<Argument*, char*> >::iterator I = $5->begin();
1201 I != $5->end(); ++I) {
1202 if (setValueName(I->first, I->second)) { // Insert into symtab...
1203 assert(0 && "No arg redef allowed!");
1206 InsertValue(I->first);
1207 ArgList.push_back(I->first);
1209 delete $5; // We're now done with the argument list
1211 // If we are a declaration, we should free the memory for the argument list!
1212 for (list<pair<Argument*, char*> >::iterator I = $5->begin(), E = $5->end();
1214 if (I->second) free(I->second); // Free the memory for the name...
1215 delete I->first; // Free the unused function argument
1217 delete $5; // Free the memory for the list itself
1221 FunctionHeader : FunctionHeaderH ConstPool BEGINTOK {
1222 $$ = CurMeth.CurrentFunction;
1224 // Resolve circular types before we parse the body of the method.
1225 ResolveTypes(CurMeth.LateResolveTypes);
1228 Function : BasicBlockList END {
1232 FunctionProto : DECLARE { CurMeth.isDeclare = true; } FunctionHeaderH {
1233 $$ = CurMeth.CurrentFunction;
1234 assert($$->getParent() == 0 && "Function already in module!");
1235 CurModule.CurrentModule->getFunctionList().push_back($$);
1236 CurMeth.FunctionDone();
1239 //===----------------------------------------------------------------------===//
1240 // Rules to match Basic Blocks
1241 //===----------------------------------------------------------------------===//
1243 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1244 $$ = ValID::create($1);
1247 $$ = ValID::create($1);
1249 | FPVAL { // Perhaps it's an FP constant?
1250 $$ = ValID::create($1);
1253 $$ = ValID::create((int64_t)1);
1256 $$ = ValID::create((int64_t)0);
1259 $$ = ValID::createNull();
1263 | STRINGCONSTANT { // Quoted strings work too... especially for methods
1264 $$ = ValID::create_conststr($1);
1268 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1271 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1272 $$ = ValID::create($1);
1274 | VAR_ID { // Is it a named reference...?
1275 $$ = ValID::create($1);
1278 // ValueRef - A reference to a definition... either constant or symbolic
1279 ValueRef : SymbolicValueRef | ConstValueRef
1282 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1283 // type immediately preceeds the value reference, and allows complex constant
1284 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1285 ResolvedVal : Types ValueRef {
1286 $$ = getVal(*$1, $2); delete $1;
1290 BasicBlockList : BasicBlockList BasicBlock {
1291 ($$ = $1)->getBasicBlocks().push_back($2);
1293 | FunctionHeader BasicBlock { // Do not allow methods with 0 basic blocks
1294 ($$ = $1)->getBasicBlocks().push_back($2);
1298 // Basic blocks are terminated by branching instructions:
1299 // br, br/cc, switch, ret
1301 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1302 if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1305 $1->getInstList().push_back($3);
1309 | LABELSTR InstructionList OptAssign BBTerminatorInst {
1310 if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1313 $2->getInstList().push_back($4);
1314 if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1320 InstructionList : InstructionList Inst {
1321 $1->getInstList().push_back($2);
1325 $$ = new BasicBlock();
1328 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1329 $$ = new ReturnInst($2);
1331 | RET VOID { // Return with no result...
1332 $$ = new ReturnInst();
1334 | BR LABEL ValueRef { // Unconditional Branch...
1335 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1336 } // Conditional Branch...
1337 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1338 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1339 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1340 getVal(Type::BoolTy, $3));
1342 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1343 SwitchInst *S = new SwitchInst(getVal($2, $3),
1344 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1347 vector<pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1350 S->dest_push_back(I->first, I->second);
1352 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal
1353 EXCEPT ResolvedVal {
1354 const PointerType *PMTy;
1355 const FunctionType *Ty;
1357 if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1358 !(Ty = dyn_cast<FunctionType>(PMTy->getElementType()))) {
1359 // Pull out the types of all of the arguments...
1360 vector<const Type*> ParamTypes;
1362 for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1363 ParamTypes.push_back((*I)->getType());
1366 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1367 if (isVarArg) ParamTypes.pop_back();
1369 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1370 PMTy = PointerType::get(Ty);
1374 Value *V = getVal(PMTy, $3); // Get the method we're calling...
1376 BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1377 BasicBlock *Except = dyn_cast<BasicBlock>($10);
1379 if (Normal == 0 || Except == 0)
1380 ThrowException("Invoke instruction without label destinations!");
1382 // Create the call node...
1383 if (!$5) { // Has no arguments?
1384 $$ = new InvokeInst(V, Normal, Except, vector<Value*>());
1385 } else { // Has arguments?
1386 // Loop through FunctionType's arguments and ensure they are specified
1389 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1390 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1391 vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1393 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1394 if ((*ArgI)->getType() != *I)
1395 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1396 (*I)->getDescription() + "'!");
1398 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1399 ThrowException("Invalid number of parameters detected!");
1401 $$ = new InvokeInst(V, Normal, Except, *$5);
1408 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1410 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1412 ThrowException("May only switch on a constant pool value!");
1414 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1416 | IntType ConstValueRef ',' LABEL ValueRef {
1417 $$ = new vector<pair<Constant*, BasicBlock*> >();
1418 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1421 ThrowException("May only switch on a constant pool value!");
1423 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1426 Inst : OptAssign InstVal {
1427 // Is this definition named?? if so, assign the name...
1428 if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1433 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1434 $$ = new list<pair<Value*, BasicBlock*> >();
1435 $$->push_back(make_pair(getVal(*$1, $3),
1436 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1439 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1441 $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
1442 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1446 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1447 $$ = new vector<Value*>();
1450 | ValueRefList ',' ResolvedVal {
1455 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1456 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; }
1458 InstVal : BinaryOps Types ValueRef ',' ValueRef {
1459 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1461 ThrowException("binary operator returned null!");
1464 | UnaryOps ResolvedVal {
1465 $$ = UnaryOperator::create($1, $2);
1467 ThrowException("unary operator returned null!");
1469 | ShiftOps ResolvedVal ',' ResolvedVal {
1470 if ($4->getType() != Type::UByteTy)
1471 ThrowException("Shift amount must be ubyte!");
1472 $$ = new ShiftInst($1, $2, $4);
1474 | CAST ResolvedVal TO Types {
1475 $$ = new CastInst($2, *$4);
1479 const Type *Ty = $2->front().first->getType();
1480 $$ = new PHINode(Ty);
1481 while ($2->begin() != $2->end()) {
1482 if ($2->front().first->getType() != Ty)
1483 ThrowException("All elements of a PHI node must be of the same type!");
1484 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1487 delete $2; // Free the list...
1489 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1490 const PointerType *PMTy;
1491 const FunctionType *Ty;
1493 if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1494 !(Ty = dyn_cast<FunctionType>(PMTy->getElementType()))) {
1495 // Pull out the types of all of the arguments...
1496 vector<const Type*> ParamTypes;
1498 for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1499 ParamTypes.push_back((*I)->getType());
1502 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1503 if (isVarArg) ParamTypes.pop_back();
1505 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1506 PMTy = PointerType::get(Ty);
1510 Value *V = getVal(PMTy, $3); // Get the method we're calling...
1512 // Create the call node...
1513 if (!$5) { // Has no arguments?
1514 $$ = new CallInst(V, vector<Value*>());
1515 } else { // Has arguments?
1516 // Loop through FunctionType's arguments and ensure they are specified
1519 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1520 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1521 vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1523 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1524 if ((*ArgI)->getType() != *I)
1525 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1526 (*I)->getDescription() + "'!");
1528 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1529 ThrowException("Invalid number of parameters detected!");
1531 $$ = new CallInst(V, *$5);
1540 // IndexList - List of indices for GEP based instructions...
1541 IndexList : ',' ValueRefList {
1544 $$ = new vector<Value*>();
1547 MemoryInst : MALLOC Types {
1548 $$ = new MallocInst(PointerType::get(*$2));
1551 | MALLOC Types ',' UINT ValueRef {
1552 const Type *Ty = PointerType::get(*$2);
1553 $$ = new MallocInst(Ty, getVal($4, $5));
1557 $$ = new AllocaInst(PointerType::get(*$2));
1560 | ALLOCA Types ',' UINT ValueRef {
1561 const Type *Ty = PointerType::get(*$2);
1562 Value *ArrSize = getVal($4, $5);
1563 $$ = new AllocaInst(Ty, ArrSize);
1566 | FREE ResolvedVal {
1567 if (!$2->getType()->isPointerType())
1568 ThrowException("Trying to free nonpointer type " +
1569 $2->getType()->getDescription() + "!");
1570 $$ = new FreeInst($2);
1573 | LOAD Types ValueRef IndexList {
1574 if (!(*$2)->isPointerType())
1575 ThrowException("Can't load from nonpointer type: " +
1576 (*$2)->getDescription());
1577 if (LoadInst::getIndexedType(*$2, *$4) == 0)
1578 ThrowException("Invalid indices for load instruction!");
1580 $$ = new LoadInst(getVal(*$2, $3), *$4);
1581 delete $4; // Free the vector...
1584 | STORE ResolvedVal ',' Types ValueRef IndexList {
1585 if (!(*$4)->isPointerType())
1586 ThrowException("Can't store to a nonpointer type: " +
1587 (*$4)->getDescription());
1588 const Type *ElTy = StoreInst::getIndexedType(*$4, *$6);
1590 ThrowException("Can't store into that field list!");
1591 if (ElTy != $2->getType())
1592 ThrowException("Can't store '" + $2->getType()->getDescription() +
1593 "' into space of type '" + ElTy->getDescription() + "'!");
1594 $$ = new StoreInst($2, getVal(*$4, $5), *$6);
1595 delete $4; delete $6;
1597 | GETELEMENTPTR Types ValueRef IndexList {
1598 if (!(*$2)->isPointerType())
1599 ThrowException("getelementptr insn requires pointer operand!");
1600 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1601 ThrowException("Can't get element ptr '" + (*$2)->getDescription()+ "'!");
1602 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1603 delete $2; delete $4;
1607 int yyerror(const char *ErrorMsg) {
1608 ThrowException(string("Parse error: ") + ErrorMsg);