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::ConstStringVal: // Is it a string const pool reference?
334 cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
338 case ValID::ConstFPVal: // Is it a floating point const pool reference?
339 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
340 ThrowException("FP constant invalid for type!!");
341 return ConstantFP::get(Ty, D.ConstPoolFP);
343 case ValID::ConstNullVal: // Is it a null value?
344 if (!Ty->isPointerType())
345 ThrowException("Cannot create a a non pointer null!");
346 return ConstantPointerNull::get(cast<PointerType>(Ty));
349 assert(0 && "Unhandled case!");
353 assert(0 && "Unhandled case!");
358 // getVal - This function is identical to getValNonImprovising, except that if a
359 // value is not already defined, it "improvises" by creating a placeholder var
360 // that looks and acts just like the requested variable. When the value is
361 // defined later, all uses of the placeholder variable are replaced with the
364 static Value *getVal(const Type *Ty, const ValID &D) {
365 assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
367 // See if the value has already been defined...
368 Value *V = getValNonImprovising(Ty, D);
371 // If we reached here, we referenced either a symbol that we don't know about
372 // or an id number that hasn't been read yet. We may be referencing something
373 // forward, so just create an entry to be resolved later and get to it...
376 switch (Ty->getPrimitiveID()) {
377 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
378 default: d = new ValuePlaceHolder(Ty, D); break;
381 assert(d != 0 && "How did we not make something?");
382 if (inFunctionScope())
383 InsertValue(d, CurMeth.LateResolveValues);
385 InsertValue(d, CurModule.LateResolveValues);
390 //===----------------------------------------------------------------------===//
391 // Code to handle forward references in instructions
392 //===----------------------------------------------------------------------===//
394 // This code handles the late binding needed with statements that reference
395 // values not defined yet... for example, a forward branch, or the PHI node for
398 // This keeps a table (CurMeth.LateResolveValues) of all such forward references
399 // and back patchs after we are done.
402 // ResolveDefinitions - If we could not resolve some defs at parsing
403 // time (forward branches, phi functions for loops, etc...) resolve the
406 static void ResolveDefinitions(vector<ValueList> &LateResolvers,
407 vector<ValueList> *FutureLateResolvers = 0) {
408 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
409 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
410 while (!LateResolvers[ty].empty()) {
411 Value *V = LateResolvers[ty].back();
412 assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
414 LateResolvers[ty].pop_back();
415 ValID &DID = getValIDFromPlaceHolder(V);
417 Value *TheRealValue = getValNonImprovising(Type::getUniqueIDType(ty),DID);
419 V->replaceAllUsesWith(TheRealValue);
421 } else if (FutureLateResolvers) {
422 // Functions have their unresolved items forwarded to the module late
424 InsertValue(V, *FutureLateResolvers);
427 ThrowException("Reference to an invalid definition: '" +DID.getName()+
428 "' of type '" + V->getType()->getDescription() + "'",
429 getLineNumFromPlaceHolder(V));
431 ThrowException("Reference to an invalid definition: #" +
432 itostr(DID.Num) + " of type '" +
433 V->getType()->getDescription() + "'",
434 getLineNumFromPlaceHolder(V));
439 LateResolvers.clear();
442 // ResolveTypeTo - A brand new type was just declared. This means that (if
443 // name is not null) things referencing Name can be resolved. Otherwise, things
444 // refering to the number can be resolved. Do this now.
446 static void ResolveTypeTo(char *Name, const Type *ToTy) {
447 vector<PATypeHolder> &Types = inFunctionScope() ?
448 CurMeth.Types : CurModule.Types;
451 if (Name) D = ValID::create(Name);
452 else D = ValID::create((int)Types.size());
454 map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
455 CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
457 map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
458 if (I != LateResolver.end()) {
459 cast<DerivedType>(I->second.get())->refineAbstractTypeTo(ToTy);
460 LateResolver.erase(I);
464 // ResolveTypes - At this point, all types should be resolved. Any that aren't
467 static void ResolveTypes(map<ValID, PATypeHolder> &LateResolveTypes) {
468 if (!LateResolveTypes.empty()) {
469 const ValID &DID = LateResolveTypes.begin()->first;
471 if (DID.Type == ValID::NameVal)
472 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
474 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
479 // setValueName - Set the specified value to the name given. The name may be
480 // null potentially, in which case this is a noop. The string passed in is
481 // assumed to be a malloc'd string buffer, and is freed by this function.
483 // This function returns true if the value has already been defined, but is
484 // allowed to be redefined in the specified context. If the name is a new name
485 // for the typeplane, false is returned.
487 static bool setValueName(Value *V, char *NameStr) {
488 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 = inFunctionScope() ?
498 CurMeth.CurrentFunction->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 HandleUpRefs(const Type *ty) {
564 UR_OUT("Type '" << ty->getDescription() <<
565 "' newly formed. Resolving upreferences.\n" <<
566 UpRefs.size() << " upreferences active!\n");
567 for (unsigned i = 0; i < UpRefs.size(); ) {
568 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
569 << UpRefs[i].second->getDescription() << ") = "
570 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << endl);
571 if (TypeContains(Ty, UpRefs[i].second)) {
572 unsigned Level = --UpRefs[i].first; // Decrement level of upreference
573 UR_OUT(" Uplevel Ref Level = " << Level << endl);
574 if (Level == 0) { // Upreference should be resolved!
575 UR_OUT(" * Resolving upreference for "
576 << UpRefs[i].second->getDescription() << endl;
577 string OldName = UpRefs[i].second->getDescription());
578 UpRefs[i].second->refineAbstractTypeTo(Ty);
579 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
580 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
581 << (const void*)Ty << ", " << Ty->getDescription() << endl);
586 ++i; // Otherwise, no resolve, move on...
588 // FIXME: TODO: this should return the updated type
593 //===----------------------------------------------------------------------===//
594 // RunVMAsmParser - Define an interface to this parser
595 //===----------------------------------------------------------------------===//
597 Module *RunVMAsmParser(const string &Filename, FILE *F) {
599 CurFilename = Filename;
600 llvmAsmlineno = 1; // Reset the current line number...
602 CurModule.CurrentModule = new Module(); // Allocate a new module to read
603 yyparse(); // Parse the file.
604 Module *Result = ParserResult;
605 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
615 Function *FunctionVal;
616 std::pair<Argument*, char*> *ArgVal;
617 BasicBlock *BasicBlockVal;
618 TerminatorInst *TermInstVal;
619 Instruction *InstVal;
622 const Type *PrimType;
623 PATypeHolder *TypeVal;
626 std::list<std::pair<Argument*,char*> > *ArgList;
627 std::vector<Value*> *ValueList;
628 std::list<PATypeHolder> *TypeList;
629 std::list<std::pair<Value*,
630 BasicBlock*> > *PHIList; // Represent the RHS of PHI node
631 std::vector<std::pair<Constant*, BasicBlock*> > *JumpTable;
632 std::vector<Constant*> *ConstVector;
641 char *StrVal; // This memory is strdup'd!
642 ValID ValIDVal; // strdup'd memory maybe!
644 Instruction::UnaryOps UnaryOpVal;
645 Instruction::BinaryOps BinaryOpVal;
646 Instruction::TermOps TermOpVal;
647 Instruction::MemoryOps MemOpVal;
648 Instruction::OtherOps OtherOpVal;
651 %type <ModuleVal> Module FunctionList
652 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
653 %type <BasicBlockVal> BasicBlock InstructionList
654 %type <TermInstVal> BBTerminatorInst
655 %type <InstVal> Inst InstVal MemoryInst
656 %type <ConstVal> ConstVal
657 %type <ConstVector> ConstVector
658 %type <ArgList> ArgList ArgListH
659 %type <ArgVal> ArgVal
660 %type <PHIList> PHIList
661 %type <ValueList> ValueRefList ValueRefListE // For call param lists
662 %type <ValueList> IndexList // For GEP derived indices
663 %type <TypeList> TypeListI ArgTypeListI
664 %type <JumpTable> JumpTable
665 %type <BoolVal> GlobalType OptInternal // GLOBAL or CONSTANT? Intern?
667 // ValueRef - Unresolved reference to a definition or BB
668 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
669 %type <ValueVal> ResolvedVal // <type> <valref> pair
670 // Tokens and types for handling constant integer values
672 // ESINT64VAL - A negative number within long long range
673 %token <SInt64Val> ESINT64VAL
675 // EUINT64VAL - A positive number within uns. long long range
676 %token <UInt64Val> EUINT64VAL
677 %type <SInt64Val> EINT64VAL
679 %token <SIntVal> SINTVAL // Signed 32 bit ints...
680 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
681 %type <SIntVal> INTVAL
682 %token <FPVal> FPVAL // Float or Double constant
685 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
686 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
687 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
688 %token <PrimType> FLOAT DOUBLE TYPE LABEL
690 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
691 %type <StrVal> OptVAR_ID OptAssign
694 %token IMPLEMENTATION TRUE FALSE BEGINTOK END DECLARE GLOBAL CONSTANT UNINIT
695 %token TO EXCEPT DOTDOTDOT STRING NULL_TOK CONST INTERNAL OPAQUE
697 // Basic Block Terminating Operators
698 %token <TermOpVal> RET BR SWITCH
701 %type <UnaryOpVal> UnaryOps // all the unary operators
702 %token <UnaryOpVal> NOT
705 %type <BinaryOpVal> BinaryOps // all the binary operators
706 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
707 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
709 // Memory Instructions
710 %token <MemoryOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
713 %type <OtherOpVal> ShiftOps
714 %token <OtherOpVal> PHI CALL INVOKE CAST SHL SHR
719 // Handle constant integer size restriction and conversion...
724 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
725 ThrowException("Value too large for type!");
730 EINT64VAL : ESINT64VAL // These have same type and can't cause problems...
731 EINT64VAL : EUINT64VAL {
732 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
733 ThrowException("Value too large for type!");
737 // Operations that are notably excluded from this list include:
738 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
741 BinaryOps : ADD | SUB | MUL | DIV | REM | AND | OR | XOR
742 BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
745 // These are some types that allow classification if we only want a particular
746 // thing... for example, only a signed, unsigned, or integral type.
747 SIntType : LONG | INT | SHORT | SBYTE
748 UIntType : ULONG | UINT | USHORT | UBYTE
749 IntType : SIntType | UIntType
750 FPType : FLOAT | DOUBLE
752 // OptAssign - Value producing statements have an optional assignment component
753 OptAssign : VAR_ID '=' {
760 OptInternal : INTERNAL { $$ = true; } | /*empty*/ { $$ = false; }
762 //===----------------------------------------------------------------------===//
763 // Types includes all predefined types... except void, because it can only be
764 // used in specific contexts (method returning void for example). To have
765 // access to it, a user must explicitly use TypesV.
768 // TypesV includes all of 'Types', but it also includes the void type.
769 TypesV : Types | VOID { $$ = new PATypeHolder($1); }
770 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); }
774 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
779 // Derived types are added later...
781 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
782 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL
784 $$ = new PATypeHolder(OpaqueType::get());
787 $$ = new PATypeHolder($1);
789 UpRTypes : ValueRef { // Named types are also simple types...
790 $$ = new PATypeHolder(getTypeVal($1));
793 // Include derived types in the Types production.
795 UpRTypes : '\\' EUINT64VAL { // Type UpReference
796 if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
797 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
798 UpRefs.push_back(make_pair((unsigned)$2, OT)); // Add to vector...
799 $$ = new PATypeHolder(OT);
800 UR_OUT("New Upreference!\n");
802 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
803 vector<const Type*> Params;
804 mapto($3->begin(), $3->end(), std::back_inserter(Params),
805 std::mem_fun_ref(&PATypeHandle<Type>::get));
806 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
807 if (isVarArg) Params.pop_back();
809 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
810 delete $3; // Delete the argument list
811 delete $1; // Delete the old type handle
813 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
814 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
817 | '{' TypeListI '}' { // Structure type?
818 vector<const Type*> Elements;
819 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
820 std::mem_fun_ref(&PATypeHandle<Type>::get));
822 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
825 | '{' '}' { // Empty structure type?
826 $$ = new PATypeHolder(StructType::get(vector<const Type*>()));
828 | UpRTypes '*' { // Pointer type?
829 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
833 // TypeList - Used for struct declarations and as a basis for method type
834 // declaration type lists
836 TypeListI : UpRTypes {
837 $$ = new list<PATypeHolder>();
838 $$->push_back(*$1); delete $1;
840 | TypeListI ',' UpRTypes {
841 ($$=$1)->push_back(*$3); delete $3;
844 // ArgTypeList - List of types for a method type declaration...
845 ArgTypeListI : TypeListI
846 | TypeListI ',' DOTDOTDOT {
847 ($$=$1)->push_back(Type::VoidTy);
850 ($$ = new list<PATypeHolder>())->push_back(Type::VoidTy);
853 $$ = new list<PATypeHolder>();
857 // ConstVal - The various declarations that go into the constant pool. This
858 // includes all forward declarations of types, constants, and functions.
860 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
861 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
863 ThrowException("Cannot make array constant with type: '" +
864 (*$1)->getDescription() + "'!");
865 const Type *ETy = ATy->getElementType();
866 int NumElements = ATy->getNumElements();
868 // Verify that we have the correct size...
869 if (NumElements != -1 && NumElements != (int)$3->size())
870 ThrowException("Type mismatch: constant sized array initialized with " +
871 utostr($3->size()) + " arguments, but has size of " +
872 itostr(NumElements) + "!");
874 // Verify all elements are correct type!
875 for (unsigned i = 0; i < $3->size(); i++) {
876 if (ETy != (*$3)[i]->getType())
877 ThrowException("Element #" + utostr(i) + " is not of type '" +
878 ETy->getDescription() +"' as required!\nIt is of type '"+
879 (*$3)[i]->getType()->getDescription() + "'.");
882 $$ = ConstantArray::get(ATy, *$3);
883 delete $1; delete $3;
886 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
888 ThrowException("Cannot make array constant with type: '" +
889 (*$1)->getDescription() + "'!");
891 int NumElements = ATy->getNumElements();
892 if (NumElements != -1 && NumElements != 0)
893 ThrowException("Type mismatch: constant sized array initialized with 0"
894 " arguments, but has size of " + itostr(NumElements) +"!");
895 $$ = ConstantArray::get(ATy, vector<Constant*>());
898 | Types 'c' STRINGCONSTANT {
899 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
901 ThrowException("Cannot make array constant with type: '" +
902 (*$1)->getDescription() + "'!");
904 int NumElements = ATy->getNumElements();
905 const Type *ETy = ATy->getElementType();
906 char *EndStr = UnEscapeLexed($3, true);
907 if (NumElements != -1 && NumElements != (EndStr-$3))
908 ThrowException("Can't build string constant of size " +
909 itostr((int)(EndStr-$3)) +
910 " when array has size " + itostr(NumElements) + "!");
911 vector<Constant*> Vals;
912 if (ETy == Type::SByteTy) {
913 for (char *C = $3; C != EndStr; ++C)
914 Vals.push_back(ConstantSInt::get(ETy, *C));
915 } else if (ETy == Type::UByteTy) {
916 for (char *C = $3; C != EndStr; ++C)
917 Vals.push_back(ConstantUInt::get(ETy, *C));
920 ThrowException("Cannot build string arrays of non byte sized elements!");
923 $$ = ConstantArray::get(ATy, Vals);
926 | Types '{' ConstVector '}' {
927 const StructType *STy = dyn_cast<const StructType>($1->get());
929 ThrowException("Cannot make struct constant with type: '" +
930 (*$1)->getDescription() + "'!");
931 // FIXME: TODO: Check to see that the constants are compatible with the type
933 $$ = ConstantStruct::get(STy, *$3);
934 delete $1; delete $3;
937 const PointerType *PTy = dyn_cast<const PointerType>($1->get());
939 ThrowException("Cannot make null pointer constant with type: '" +
940 (*$1)->getDescription() + "'!");
942 $$ = ConstantPointerNull::get(PTy);
945 | Types SymbolicValueRef {
946 const PointerType *Ty = dyn_cast<const PointerType>($1->get());
948 ThrowException("Global const reference must be a pointer type!");
950 Value *V = getValNonImprovising(Ty, $2);
952 // If this is an initializer for a constant pointer, which is referencing a
953 // (currently) undefined variable, create a stub now that shall be replaced
954 // in the future with the right type of variable.
957 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
958 const PointerType *PT = cast<PointerType>(Ty);
960 // First check to see if the forward references value is already created!
961 PerModuleInfo::GlobalRefsType::iterator I =
962 CurModule.GlobalRefs.find(make_pair(PT, $2));
964 if (I != CurModule.GlobalRefs.end()) {
965 V = I->second; // Placeholder already exists, use it...
967 // TODO: Include line number info by creating a subclass of
968 // TODO: GlobalVariable here that includes the said information!
970 // Create a placeholder for the global variable reference...
971 GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
973 // Keep track of the fact that we have a forward ref to recycle it
974 CurModule.GlobalRefs.insert(make_pair(make_pair(PT, $2), GV));
976 // Must temporarily push this value into the module table...
977 CurModule.CurrentModule->getGlobalList().push_back(GV);
982 GlobalValue *GV = cast<GlobalValue>(V);
983 $$ = ConstantPointerRef::get(GV);
984 delete $1; // Free the type handle
988 ConstVal : SIntType EINT64VAL { // integral constants
989 if (!ConstantSInt::isValueValidForType($1, $2))
990 ThrowException("Constant value doesn't fit in type!");
991 $$ = ConstantSInt::get($1, $2);
993 | UIntType EUINT64VAL { // integral constants
994 if (!ConstantUInt::isValueValidForType($1, $2))
995 ThrowException("Constant value doesn't fit in type!");
996 $$ = ConstantUInt::get($1, $2);
998 | BOOL TRUE { // Boolean constants
999 $$ = ConstantBool::True;
1001 | BOOL FALSE { // Boolean constants
1002 $$ = ConstantBool::False;
1004 | FPType FPVAL { // Float & Double constants
1005 $$ = ConstantFP::get($1, $2);
1008 // ConstVector - A list of comma seperated constants.
1009 ConstVector : ConstVector ',' ConstVal {
1010 ($$ = $1)->push_back($3);
1013 $$ = new vector<Constant*>();
1018 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1019 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; }
1022 // ConstPool - Constants with optional names assigned to them.
1023 ConstPool : ConstPool OptAssign CONST ConstVal {
1024 if (setValueName($4, $2)) { assert(0 && "No redefinitions allowed!"); }
1027 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1028 // Eagerly resolve types. This is not an optimization, this is a
1029 // requirement that is due to the fact that we could have this:
1031 // %list = type { %list * }
1032 // %list = type { %list * } ; repeated type decl
1034 // If types are not resolved eagerly, then the two types will not be
1035 // determined to be the same type!
1037 ResolveTypeTo($2, $4->get());
1039 // TODO: FIXME when Type are not const
1040 if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1041 // If this is not a redefinition of a type...
1043 InsertType($4->get(),
1044 inFunctionScope() ? CurMeth.Types : CurModule.Types);
1050 | ConstPool FunctionProto { // Function prototypes can be in const pool
1052 | ConstPool OptAssign OptInternal GlobalType ConstVal {
1053 const Type *Ty = $5->getType();
1054 // Global declarations appear in Constant Pool
1055 Constant *Initializer = $5;
1056 if (Initializer == 0)
1057 ThrowException("Global value initializer is not a constant!");
1059 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1060 if (!setValueName(GV, $2)) { // If not redefining...
1061 CurModule.CurrentModule->getGlobalList().push_back(GV);
1062 int Slot = InsertValue(GV, CurModule.Values);
1065 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1067 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1068 (char*)GV->getName().c_str()));
1072 | ConstPool OptAssign OptInternal UNINIT GlobalType Types {
1073 const Type *Ty = *$6;
1074 // Global declarations appear in Constant Pool
1075 GlobalVariable *GV = new GlobalVariable(Ty, $5, $3);
1076 if (!setValueName(GV, $2)) { // If not redefining...
1077 CurModule.CurrentModule->getGlobalList().push_back(GV);
1078 int Slot = InsertValue(GV, CurModule.Values);
1081 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1083 assert(GV->hasName() && "Not named and not numbered!?");
1084 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1085 (char*)GV->getName().c_str()));
1090 | /* empty: end of list */ {
1094 //===----------------------------------------------------------------------===//
1095 // Rules to match Modules
1096 //===----------------------------------------------------------------------===//
1098 // Module rule: Capture the result of parsing the whole file into a result
1101 Module : FunctionList {
1102 $$ = ParserResult = $1;
1103 CurModule.ModuleDone();
1106 // FunctionList - A list of methods, preceeded by a constant pool.
1108 FunctionList : FunctionList Function {
1110 assert($2->getParent() == 0 && "Function already in module!");
1111 $1->getFunctionList().push_back($2);
1112 CurMeth.FunctionDone();
1114 | FunctionList FunctionProto {
1117 | ConstPool IMPLEMENTATION {
1118 $$ = CurModule.CurrentModule;
1119 // Resolve circular types before we parse the body of the module
1120 ResolveTypes(CurModule.LateResolveTypes);
1124 //===----------------------------------------------------------------------===//
1125 // Rules to match Function Headers
1126 //===----------------------------------------------------------------------===//
1128 OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; }
1130 ArgVal : Types OptVAR_ID {
1131 $$ = new pair<Argument*, char*>(new Argument(*$1), $2);
1132 delete $1; // Delete the type handle..
1135 ArgListH : ArgVal ',' ArgListH {
1137 $3->push_front(*$1);
1141 $$ = new list<pair<Argument*,char*> >();
1142 $$->push_front(*$1);
1146 $$ = new list<pair<Argument*, char*> >();
1147 $$->push_front(pair<Argument*,char*>(new Argument(Type::VoidTy), 0));
1150 ArgList : ArgListH {
1157 FunctionHeaderH : OptInternal TypesV STRINGCONSTANT '(' ArgList ')' {
1159 string FunctionName($3);
1161 vector<const Type*> ParamTypeList;
1163 for (list<pair<Argument*,char*> >::iterator I = $5->begin();
1164 I != $5->end(); ++I)
1165 ParamTypeList.push_back(I->first->getType());
1167 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1168 if (isVarArg) ParamTypeList.pop_back();
1170 const FunctionType *MT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1171 const PointerType *PMT = PointerType::get(MT);
1175 if (SymbolTable *ST = CurModule.CurrentModule->getSymbolTable()) {
1176 // Is the function already in symtab?
1177 if (Value *V = ST->lookup(PMT, FunctionName)) {
1178 M = cast<Function>(V);
1180 // Yes it is. If this is the case, either we need to be a forward decl,
1181 // or it needs to be.
1182 if (!CurMeth.isDeclare && !M->isExternal())
1183 ThrowException("Redefinition of method '" + FunctionName + "'!");
1185 // If we found a preexisting method prototype, remove it from the module,
1186 // so that we don't get spurious conflicts with global & local variables.
1188 CurModule.CurrentModule->getFunctionList().remove(M);
1192 if (M == 0) { // Not already defined?
1193 M = new Function(MT, $1, FunctionName);
1194 InsertValue(M, CurModule.Values);
1195 CurModule.DeclareNewGlobalValue(M, ValID::create($3));
1197 free($3); // Free strdup'd memory!
1199 CurMeth.FunctionStart(M);
1201 // Add all of the arguments we parsed to the method...
1202 if ($5 && !CurMeth.isDeclare) { // Is null if empty...
1203 Function::ArgumentListType &ArgList = M->getArgumentList();
1205 for (list<pair<Argument*, char*> >::iterator I = $5->begin();
1206 I != $5->end(); ++I) {
1207 if (setValueName(I->first, I->second)) { // Insert into symtab...
1208 assert(0 && "No arg redef allowed!");
1211 InsertValue(I->first);
1212 ArgList.push_back(I->first);
1214 delete $5; // We're now done with the argument list
1216 // If we are a declaration, we should free the memory for the argument list!
1217 for (list<pair<Argument*, char*> >::iterator I = $5->begin(), E = $5->end();
1219 if (I->second) free(I->second); // Free the memory for the name...
1220 delete I->first; // Free the unused function argument
1222 delete $5; // Free the memory for the list itself
1226 FunctionHeader : FunctionHeaderH ConstPool BEGINTOK {
1227 $$ = CurMeth.CurrentFunction;
1229 // Resolve circular types before we parse the body of the method.
1230 ResolveTypes(CurMeth.LateResolveTypes);
1233 Function : BasicBlockList END {
1237 FunctionProto : DECLARE { CurMeth.isDeclare = true; } FunctionHeaderH {
1238 $$ = CurMeth.CurrentFunction;
1239 assert($$->getParent() == 0 && "Function already in module!");
1240 CurModule.CurrentModule->getFunctionList().push_back($$);
1241 CurMeth.FunctionDone();
1244 //===----------------------------------------------------------------------===//
1245 // Rules to match Basic Blocks
1246 //===----------------------------------------------------------------------===//
1248 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1249 $$ = ValID::create($1);
1252 $$ = ValID::create($1);
1254 | FPVAL { // Perhaps it's an FP constant?
1255 $$ = ValID::create($1);
1258 $$ = ValID::create((int64_t)1);
1261 $$ = ValID::create((int64_t)0);
1264 $$ = ValID::createNull();
1268 | STRINGCONSTANT { // Quoted strings work too... especially for methods
1269 $$ = ValID::create_conststr($1);
1273 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1276 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1277 $$ = ValID::create($1);
1279 | VAR_ID { // Is it a named reference...?
1280 $$ = ValID::create($1);
1283 // ValueRef - A reference to a definition... either constant or symbolic
1284 ValueRef : SymbolicValueRef | ConstValueRef
1287 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1288 // type immediately preceeds the value reference, and allows complex constant
1289 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1290 ResolvedVal : Types ValueRef {
1291 $$ = getVal(*$1, $2); delete $1;
1295 BasicBlockList : BasicBlockList BasicBlock {
1296 ($$ = $1)->getBasicBlocks().push_back($2);
1298 | FunctionHeader BasicBlock { // Do not allow methods with 0 basic blocks
1299 ($$ = $1)->getBasicBlocks().push_back($2);
1303 // Basic blocks are terminated by branching instructions:
1304 // br, br/cc, switch, ret
1306 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1307 if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1310 $1->getInstList().push_back($3);
1314 | LABELSTR InstructionList OptAssign BBTerminatorInst {
1315 if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1318 $2->getInstList().push_back($4);
1319 if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1325 InstructionList : InstructionList Inst {
1326 $1->getInstList().push_back($2);
1330 $$ = new BasicBlock();
1333 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1334 $$ = new ReturnInst($2);
1336 | RET VOID { // Return with no result...
1337 $$ = new ReturnInst();
1339 | BR LABEL ValueRef { // Unconditional Branch...
1340 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1341 } // Conditional Branch...
1342 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1343 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1344 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1345 getVal(Type::BoolTy, $3));
1347 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1348 SwitchInst *S = new SwitchInst(getVal($2, $3),
1349 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1352 vector<pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1355 S->dest_push_back(I->first, I->second);
1357 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal
1358 EXCEPT ResolvedVal {
1359 const PointerType *PMTy;
1360 const FunctionType *Ty;
1362 if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1363 !(Ty = dyn_cast<FunctionType>(PMTy->getElementType()))) {
1364 // Pull out the types of all of the arguments...
1365 vector<const Type*> ParamTypes;
1367 for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1368 ParamTypes.push_back((*I)->getType());
1371 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1372 if (isVarArg) ParamTypes.pop_back();
1374 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1375 PMTy = PointerType::get(Ty);
1379 Value *V = getVal(PMTy, $3); // Get the method we're calling...
1381 BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1382 BasicBlock *Except = dyn_cast<BasicBlock>($10);
1384 if (Normal == 0 || Except == 0)
1385 ThrowException("Invoke instruction without label destinations!");
1387 // Create the call node...
1388 if (!$5) { // Has no arguments?
1389 $$ = new InvokeInst(V, Normal, Except, vector<Value*>());
1390 } else { // Has arguments?
1391 // Loop through FunctionType's arguments and ensure they are specified
1394 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1395 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1396 vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1398 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1399 if ((*ArgI)->getType() != *I)
1400 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1401 (*I)->getDescription() + "'!");
1403 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1404 ThrowException("Invalid number of parameters detected!");
1406 $$ = new InvokeInst(V, Normal, Except, *$5);
1413 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1415 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1417 ThrowException("May only switch on a constant pool value!");
1419 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1421 | IntType ConstValueRef ',' LABEL ValueRef {
1422 $$ = new vector<pair<Constant*, BasicBlock*> >();
1423 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1426 ThrowException("May only switch on a constant pool value!");
1428 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1431 Inst : OptAssign InstVal {
1432 // Is this definition named?? if so, assign the name...
1433 if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1438 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1439 $$ = new list<pair<Value*, BasicBlock*> >();
1440 $$->push_back(make_pair(getVal(*$1, $3),
1441 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1444 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1446 $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
1447 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1451 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1452 $$ = new vector<Value*>();
1455 | ValueRefList ',' ResolvedVal {
1460 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1461 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; }
1463 InstVal : BinaryOps Types ValueRef ',' ValueRef {
1464 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1466 ThrowException("binary operator returned null!");
1469 | UnaryOps ResolvedVal {
1470 $$ = UnaryOperator::create($1, $2);
1472 ThrowException("unary operator returned null!");
1474 | ShiftOps ResolvedVal ',' ResolvedVal {
1475 if ($4->getType() != Type::UByteTy)
1476 ThrowException("Shift amount must be ubyte!");
1477 $$ = new ShiftInst($1, $2, $4);
1479 | CAST ResolvedVal TO Types {
1480 $$ = new CastInst($2, *$4);
1484 const Type *Ty = $2->front().first->getType();
1485 $$ = new PHINode(Ty);
1486 while ($2->begin() != $2->end()) {
1487 if ($2->front().first->getType() != Ty)
1488 ThrowException("All elements of a PHI node must be of the same type!");
1489 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1492 delete $2; // Free the list...
1494 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1495 const PointerType *PMTy;
1496 const FunctionType *Ty;
1498 if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1499 !(Ty = dyn_cast<FunctionType>(PMTy->getElementType()))) {
1500 // Pull out the types of all of the arguments...
1501 vector<const Type*> ParamTypes;
1503 for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1504 ParamTypes.push_back((*I)->getType());
1507 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1508 if (isVarArg) ParamTypes.pop_back();
1510 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1511 PMTy = PointerType::get(Ty);
1515 Value *V = getVal(PMTy, $3); // Get the method we're calling...
1517 // Create the call node...
1518 if (!$5) { // Has no arguments?
1519 $$ = new CallInst(V, vector<Value*>());
1520 } else { // Has arguments?
1521 // Loop through FunctionType's arguments and ensure they are specified
1524 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1525 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1526 vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1528 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1529 if ((*ArgI)->getType() != *I)
1530 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1531 (*I)->getDescription() + "'!");
1533 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1534 ThrowException("Invalid number of parameters detected!");
1536 $$ = new CallInst(V, *$5);
1545 // IndexList - List of indices for GEP based instructions...
1546 IndexList : ',' ValueRefList {
1549 $$ = new vector<Value*>();
1552 MemoryInst : MALLOC Types {
1553 $$ = new MallocInst(PointerType::get(*$2));
1556 | MALLOC Types ',' UINT ValueRef {
1557 const Type *Ty = PointerType::get(*$2);
1558 $$ = new MallocInst(Ty, getVal($4, $5));
1562 $$ = new AllocaInst(PointerType::get(*$2));
1565 | ALLOCA Types ',' UINT ValueRef {
1566 const Type *Ty = PointerType::get(*$2);
1567 Value *ArrSize = getVal($4, $5);
1568 $$ = new AllocaInst(Ty, ArrSize);
1571 | FREE ResolvedVal {
1572 if (!$2->getType()->isPointerType())
1573 ThrowException("Trying to free nonpointer type " +
1574 $2->getType()->getDescription() + "!");
1575 $$ = new FreeInst($2);
1578 | LOAD Types ValueRef IndexList {
1579 if (!(*$2)->isPointerType())
1580 ThrowException("Can't load from nonpointer type: " +
1581 (*$2)->getDescription());
1582 if (LoadInst::getIndexedType(*$2, *$4) == 0)
1583 ThrowException("Invalid indices for load instruction!");
1585 $$ = new LoadInst(getVal(*$2, $3), *$4);
1586 delete $4; // Free the vector...
1589 | STORE ResolvedVal ',' Types ValueRef IndexList {
1590 if (!(*$4)->isPointerType())
1591 ThrowException("Can't store to a nonpointer type: " +
1592 (*$4)->getDescription());
1593 const Type *ElTy = StoreInst::getIndexedType(*$4, *$6);
1595 ThrowException("Can't store into that field list!");
1596 if (ElTy != $2->getType())
1597 ThrowException("Can't store '" + $2->getType()->getDescription() +
1598 "' into space of type '" + ElTy->getDescription() + "'!");
1599 $$ = new StoreInst($2, getVal(*$4, $5), *$6);
1600 delete $4; delete $6;
1602 | GETELEMENTPTR Types ValueRef IndexList {
1603 if (!(*$2)->isPointerType())
1604 ThrowException("getelementptr insn requires pointer operand!");
1605 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1606 ThrowException("Can't get element ptr '" + (*$2)->getDescription()+ "'!");
1607 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1608 delete $2; delete $4;
1612 int yyerror(const char *ErrorMsg) {
1613 ThrowException(string("Parse error: ") + ErrorMsg);