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/SymbolTable.h"
10 #include "llvm/Module.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/iPHINode.h"
14 #include "Support/STLExtras.h"
15 #include "Support/DepthFirstIterator.h"
27 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
28 int yylex(); // declaration" of xxx warnings.
31 static Module *ParserResult;
34 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
35 // relating to upreferences in the input stream.
37 //#define DEBUG_UPREFS 1
39 #define UR_OUT(X) std::cerr << X
44 #define YYERROR_VERBOSE 1
46 // HACK ALERT: This variable is used to implement the automatic conversion of
47 // load/store instructions with indexes into a load/store + getelementptr pair
48 // of instructions. When this compatiblity "Feature" is removed, this should be
51 static BasicBlock *CurBB;
54 // This contains info used when building the body of a function. It is
55 // destroyed when the function is completed.
57 typedef vector<Value *> ValueList; // Numbered defs
58 static void ResolveDefinitions(vector<ValueList> &LateResolvers,
59 vector<ValueList> *FutureLateResolvers = 0);
61 static struct PerModuleInfo {
62 Module *CurrentModule;
63 vector<ValueList> Values; // Module level numbered definitions
64 vector<ValueList> LateResolveValues;
65 vector<PATypeHolder> Types;
66 map<ValID, PATypeHolder> LateResolveTypes;
68 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
69 // references to global values. Global values may be referenced before they
70 // are defined, and if so, the temporary object that they represent is held
71 // here. This is used for forward references of ConstantPointerRefs.
73 typedef map<pair<const PointerType *, ValID>, GlobalVariable*> GlobalRefsType;
74 GlobalRefsType GlobalRefs;
77 // If we could not resolve some functions at function compilation time
78 // (calls to functions before they are defined), resolve them now... Types
79 // are resolved when the constant pool has been completely parsed.
81 ResolveDefinitions(LateResolveValues);
83 // Check to make sure that all global value forward references have been
86 if (!GlobalRefs.empty()) {
87 string UndefinedReferences = "Unresolved global references exist:\n";
89 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
91 UndefinedReferences += " " + I->first.first->getDescription() + " " +
92 I->first.second.getName() + "\n";
94 ThrowException(UndefinedReferences);
97 Values.clear(); // Clear out function local definitions
103 // DeclareNewGlobalValue - Called every time a new GV has been defined. This
104 // is used to remove things from the forward declaration map, resolving them
105 // to the correct thing as needed.
107 void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
108 // Check to see if there is a forward reference to this global variable...
109 // if there is, eliminate it and patch the reference to use the new def'n.
110 GlobalRefsType::iterator I = GlobalRefs.find(make_pair(GV->getType(), D));
112 if (I != GlobalRefs.end()) {
113 GlobalVariable *OldGV = I->second; // Get the placeholder...
114 I->first.second.destroy(); // Free string memory if neccesary
116 // Loop over all of the uses of the GlobalValue. The only thing they are
117 // allowed to be is ConstantPointerRef's.
118 assert(OldGV->use_size() == 1 && "Only one reference should exist!");
119 while (!OldGV->use_empty()) {
120 User *U = OldGV->use_back(); // Must be a ConstantPointerRef...
121 ConstantPointerRef *CPR = cast<ConstantPointerRef>(U);
122 assert(CPR->getValue() == OldGV && "Something isn't happy");
124 // Change the const pool reference to point to the real global variable
125 // now. This should drop a use from the OldGV.
126 CPR->mutateReferences(OldGV, GV);
129 // Remove OldGV from the module...
130 CurrentModule->getGlobalList().remove(OldGV);
131 delete OldGV; // Delete the old placeholder
133 // Remove the map entry for the global now that it has been created...
140 static struct PerFunctionInfo {
141 Function *CurrentFunction; // Pointer to current function being created
143 vector<ValueList> Values; // Keep track of numbered definitions
144 vector<ValueList> LateResolveValues;
145 vector<PATypeHolder> Types;
146 map<ValID, PATypeHolder> LateResolveTypes;
147 bool isDeclare; // Is this function a forward declararation?
149 inline PerFunctionInfo() {
154 inline ~PerFunctionInfo() {}
156 inline void FunctionStart(Function *M) {
160 void FunctionDone() {
161 // If we could not resolve some blocks at parsing time (forward branches)
162 // resolve the branches now...
163 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
165 Values.clear(); // Clear out function local definitions
170 } CurMeth; // Info for the current function...
172 static bool inFunctionScope() { return CurMeth.CurrentFunction != 0; }
175 //===----------------------------------------------------------------------===//
176 // Code to handle definitions of all the types
177 //===----------------------------------------------------------------------===//
179 static int InsertValue(Value *D, vector<ValueList> &ValueTab = CurMeth.Values) {
180 if (D->hasName()) return -1; // Is this a numbered definition?
182 // Yes, insert the value into the value table...
183 unsigned type = D->getType()->getUniqueID();
184 if (ValueTab.size() <= type)
185 ValueTab.resize(type+1, ValueList());
186 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
187 ValueTab[type].push_back(D);
188 return ValueTab[type].size()-1;
191 // TODO: FIXME when Type are not const
192 static void InsertType(const Type *Ty, vector<PATypeHolder> &Types) {
196 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
198 case ValID::NumberVal: { // Is it a numbered definition?
199 unsigned Num = (unsigned)D.Num;
201 // Module constants occupy the lowest numbered slots...
202 if (Num < CurModule.Types.size())
203 return CurModule.Types[Num];
205 Num -= CurModule.Types.size();
207 // Check that the number is within bounds...
208 if (Num <= CurMeth.Types.size())
209 return CurMeth.Types[Num];
212 case ValID::NameVal: { // Is it a named definition?
214 SymbolTable *SymTab = 0;
215 if (inFunctionScope()) SymTab = CurMeth.CurrentFunction->getSymbolTable();
216 Value *N = SymTab ? SymTab->lookup(Type::TypeTy, Name) : 0;
219 // Symbol table doesn't automatically chain yet... because the function
220 // hasn't been added to the module...
222 SymTab = CurModule.CurrentModule->getSymbolTable();
224 N = SymTab->lookup(Type::TypeTy, Name);
228 D.destroy(); // Free old strdup'd memory...
229 return cast<const Type>(N);
232 ThrowException("Internal parser error: Invalid symbol type reference!");
235 // If we reached here, we referenced either a symbol that we don't know about
236 // or an id number that hasn't been read yet. We may be referencing something
237 // forward, so just create an entry to be resolved later and get to it...
239 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
241 map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
242 CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
244 map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
245 if (I != LateResolver.end()) {
249 Type *Typ = OpaqueType::get();
250 LateResolver.insert(make_pair(D, Typ));
254 static Value *lookupInSymbolTable(const Type *Ty, const string &Name) {
255 SymbolTable *SymTab =
256 inFunctionScope() ? CurMeth.CurrentFunction->getSymbolTable() :
257 CurModule.CurrentModule->getSymbolTable();
258 return SymTab ? SymTab->lookup(Ty, Name) : 0;
261 // getValNonImprovising - Look up the value specified by the provided type and
262 // the provided ValID. If the value exists and has already been defined, return
263 // it. Otherwise return null.
265 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
266 if (isa<FunctionType>(Ty))
267 ThrowException("Functions are not values and "
268 "must be referenced as pointers");
271 case ValID::NumberVal: { // Is it a numbered definition?
272 unsigned type = Ty->getUniqueID();
273 unsigned Num = (unsigned)D.Num;
275 // Module constants occupy the lowest numbered slots...
276 if (type < CurModule.Values.size()) {
277 if (Num < CurModule.Values[type].size())
278 return CurModule.Values[type][Num];
280 Num -= CurModule.Values[type].size();
283 // Make sure that our type is within bounds
284 if (CurMeth.Values.size() <= type) return 0;
286 // Check that the number is within bounds...
287 if (CurMeth.Values[type].size() <= Num) return 0;
289 return CurMeth.Values[type][Num];
292 case ValID::NameVal: { // Is it a named definition?
293 Value *N = lookupInSymbolTable(Ty, string(D.Name));
294 if (N == 0) return 0;
296 D.destroy(); // Free old strdup'd memory...
300 // Check to make sure that "Ty" is an integral type, and that our
301 // value will fit into the specified type...
302 case ValID::ConstSIntVal: // Is it a constant pool reference??
303 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
304 ThrowException("Signed integral constant '" +
305 itostr(D.ConstPool64) + "' is invalid for type '" +
306 Ty->getDescription() + "'!");
307 return ConstantSInt::get(Ty, D.ConstPool64);
309 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
310 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
311 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
312 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
313 "' is invalid or out of range!");
314 } else { // This is really a signed reference. Transmogrify.
315 return ConstantSInt::get(Ty, D.ConstPool64);
318 return ConstantUInt::get(Ty, D.UConstPool64);
321 case ValID::ConstFPVal: // Is it a floating point const pool reference?
322 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
323 ThrowException("FP constant invalid for type!!");
324 return ConstantFP::get(Ty, D.ConstPoolFP);
326 case ValID::ConstNullVal: // Is it a null value?
327 if (!isa<PointerType>(Ty))
328 ThrowException("Cannot create a a non pointer null!");
329 return ConstantPointerNull::get(cast<PointerType>(Ty));
331 case ValID::ConstantVal: // Fully resolved constant?
332 if (D.ConstantValue->getType() != Ty)
333 ThrowException("Constant expression type different from required type!");
334 return D.ConstantValue;
337 assert(0 && "Unhandled case!");
341 assert(0 && "Unhandled case!");
346 // getVal - This function is identical to getValNonImprovising, except that if a
347 // value is not already defined, it "improvises" by creating a placeholder var
348 // that looks and acts just like the requested variable. When the value is
349 // defined later, all uses of the placeholder variable are replaced with the
352 static Value *getVal(const Type *Ty, const ValID &D) {
353 assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
355 // See if the value has already been defined...
356 Value *V = getValNonImprovising(Ty, D);
359 // If we reached here, we referenced either a symbol that we don't know about
360 // or an id number that hasn't been read yet. We may be referencing something
361 // forward, so just create an entry to be resolved later and get to it...
364 switch (Ty->getPrimitiveID()) {
365 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
366 default: d = new ValuePlaceHolder(Ty, D); break;
369 assert(d != 0 && "How did we not make something?");
370 if (inFunctionScope())
371 InsertValue(d, CurMeth.LateResolveValues);
373 InsertValue(d, CurModule.LateResolveValues);
378 //===----------------------------------------------------------------------===//
379 // Code to handle forward references in instructions
380 //===----------------------------------------------------------------------===//
382 // This code handles the late binding needed with statements that reference
383 // values not defined yet... for example, a forward branch, or the PHI node for
386 // This keeps a table (CurMeth.LateResolveValues) of all such forward references
387 // and back patchs after we are done.
390 // ResolveDefinitions - If we could not resolve some defs at parsing
391 // time (forward branches, phi functions for loops, etc...) resolve the
394 static void ResolveDefinitions(vector<ValueList> &LateResolvers,
395 vector<ValueList> *FutureLateResolvers) {
396 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
397 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
398 while (!LateResolvers[ty].empty()) {
399 Value *V = LateResolvers[ty].back();
400 assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
402 LateResolvers[ty].pop_back();
403 ValID &DID = getValIDFromPlaceHolder(V);
405 Value *TheRealValue = getValNonImprovising(Type::getUniqueIDType(ty),DID);
407 V->replaceAllUsesWith(TheRealValue);
409 } else if (FutureLateResolvers) {
410 // Functions have their unresolved items forwarded to the module late
412 InsertValue(V, *FutureLateResolvers);
414 if (DID.Type == ValID::NameVal)
415 ThrowException("Reference to an invalid definition: '" +DID.getName()+
416 "' of type '" + V->getType()->getDescription() + "'",
417 getLineNumFromPlaceHolder(V));
419 ThrowException("Reference to an invalid definition: #" +
420 itostr(DID.Num) + " of type '" +
421 V->getType()->getDescription() + "'",
422 getLineNumFromPlaceHolder(V));
427 LateResolvers.clear();
430 // ResolveTypeTo - A brand new type was just declared. This means that (if
431 // name is not null) things referencing Name can be resolved. Otherwise, things
432 // refering to the number can be resolved. Do this now.
434 static void ResolveTypeTo(char *Name, const Type *ToTy) {
435 vector<PATypeHolder> &Types = inFunctionScope() ?
436 CurMeth.Types : CurModule.Types;
439 if (Name) D = ValID::create(Name);
440 else D = ValID::create((int)Types.size());
442 map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
443 CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
445 map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
446 if (I != LateResolver.end()) {
447 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
448 LateResolver.erase(I);
452 // ResolveTypes - At this point, all types should be resolved. Any that aren't
455 static void ResolveTypes(map<ValID, PATypeHolder> &LateResolveTypes) {
456 if (!LateResolveTypes.empty()) {
457 const ValID &DID = LateResolveTypes.begin()->first;
459 if (DID.Type == ValID::NameVal)
460 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
462 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
467 // setValueName - Set the specified value to the name given. The name may be
468 // null potentially, in which case this is a noop. The string passed in is
469 // assumed to be a malloc'd string buffer, and is freed by this function.
471 // This function returns true if the value has already been defined, but is
472 // allowed to be redefined in the specified context. If the name is a new name
473 // for the typeplane, false is returned.
475 static bool setValueName(Value *V, char *NameStr) {
476 if (NameStr == 0) return false;
478 string Name(NameStr); // Copy string
479 free(NameStr); // Free old string
481 if (V->getType() == Type::VoidTy)
482 ThrowException("Can't assign name '" + Name +
483 "' to a null valued instruction!");
485 SymbolTable *ST = inFunctionScope() ?
486 CurMeth.CurrentFunction->getSymbolTableSure() :
487 CurModule.CurrentModule->getSymbolTableSure();
489 Value *Existing = ST->lookup(V->getType(), Name);
490 if (Existing) { // Inserting a name that is already defined???
491 // There is only one case where this is allowed: when we are refining an
492 // opaque type. In this case, Existing will be an opaque type.
493 if (const Type *Ty = dyn_cast<const Type>(Existing)) {
494 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Ty)) {
495 // We ARE replacing an opaque type!
496 ((OpaqueType*)OpTy)->refineAbstractTypeTo(cast<Type>(V));
501 // Otherwise, we are a simple redefinition of a value, check to see if it
502 // is defined the same as the old one...
503 if (const Type *Ty = dyn_cast<const Type>(Existing)) {
504 if (Ty == cast<const Type>(V)) return true; // Yes, it's equal.
505 // std::cerr << "Type: " << Ty->getDescription() << " != "
506 // << cast<const Type>(V)->getDescription() << "!\n";
507 } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
508 // We are allowed to redefine a global variable in two circumstances:
509 // 1. If at least one of the globals is uninitialized or
510 // 2. If both initializers have the same value.
512 // This can only be done if the const'ness of the vars is the same.
514 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
515 if (EGV->isConstant() == GV->isConstant() &&
516 (!EGV->hasInitializer() || !GV->hasInitializer() ||
517 EGV->getInitializer() == GV->getInitializer())) {
519 // Make sure the existing global version gets the initializer!
520 if (GV->hasInitializer() && !EGV->hasInitializer())
521 EGV->setInitializer(GV->getInitializer());
523 delete GV; // Destroy the duplicate!
524 return true; // They are equivalent!
528 ThrowException("Redefinition of value named '" + Name + "' in the '" +
529 V->getType()->getDescription() + "' type plane!");
532 V->setName(Name, ST);
537 //===----------------------------------------------------------------------===//
538 // Code for handling upreferences in type names...
541 // TypeContains - Returns true if Ty contains E in it.
543 static bool TypeContains(const Type *Ty, const Type *E) {
544 return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
548 static vector<pair<unsigned, OpaqueType *> > UpRefs;
550 static PATypeHolder HandleUpRefs(const Type *ty) {
552 UR_OUT("Type '" << ty->getDescription() <<
553 "' newly formed. Resolving upreferences.\n" <<
554 UpRefs.size() << " upreferences active!\n");
555 for (unsigned i = 0; i < UpRefs.size(); ) {
556 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
557 << UpRefs[i].second->getDescription() << ") = "
558 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << endl);
559 if (TypeContains(Ty, UpRefs[i].second)) {
560 unsigned Level = --UpRefs[i].first; // Decrement level of upreference
561 UR_OUT(" Uplevel Ref Level = " << Level << endl);
562 if (Level == 0) { // Upreference should be resolved!
563 UR_OUT(" * Resolving upreference for "
564 << UpRefs[i].second->getDescription() << endl;
565 string OldName = UpRefs[i].second->getDescription());
566 UpRefs[i].second->refineAbstractTypeTo(Ty);
567 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
568 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
569 << (const void*)Ty << ", " << Ty->getDescription() << endl);
574 ++i; // Otherwise, no resolve, move on...
576 // FIXME: TODO: this should return the updated type
581 //===----------------------------------------------------------------------===//
582 // RunVMAsmParser - Define an interface to this parser
583 //===----------------------------------------------------------------------===//
585 Module *RunVMAsmParser(const string &Filename, FILE *F) {
587 CurFilename = Filename;
588 llvmAsmlineno = 1; // Reset the current line number...
590 CurModule.CurrentModule = new Module(); // Allocate a new module to read
591 yyparse(); // Parse the file.
592 Module *Result = ParserResult;
593 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
603 Function *FunctionVal;
604 std::pair<Argument*, char*> *ArgVal;
605 BasicBlock *BasicBlockVal;
606 TerminatorInst *TermInstVal;
607 Instruction *InstVal;
610 const Type *PrimType;
611 PATypeHolder *TypeVal;
614 std::list<std::pair<Argument*,char*> > *ArgList;
615 std::vector<Value*> *ValueList;
616 std::list<PATypeHolder> *TypeList;
617 std::list<std::pair<Value*,
618 BasicBlock*> > *PHIList; // Represent the RHS of PHI node
619 std::vector<std::pair<Constant*, BasicBlock*> > *JumpTable;
620 std::vector<Constant*> *ConstVector;
629 char *StrVal; // This memory is strdup'd!
630 ValID ValIDVal; // strdup'd memory maybe!
632 Instruction::BinaryOps BinaryOpVal;
633 Instruction::TermOps TermOpVal;
634 Instruction::MemoryOps MemOpVal;
635 Instruction::OtherOps OtherOpVal;
638 %type <ModuleVal> Module FunctionList
639 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
640 %type <BasicBlockVal> BasicBlock InstructionList
641 %type <TermInstVal> BBTerminatorInst
642 %type <InstVal> Inst InstVal MemoryInst
643 %type <ConstVal> ConstVal ConstExpr
644 %type <ConstVector> ConstVector
645 %type <ArgList> ArgList ArgListH
646 %type <ArgVal> ArgVal
647 %type <PHIList> PHIList
648 %type <ValueList> ValueRefList ValueRefListE // For call param lists
649 %type <ValueList> IndexList // For GEP derived indices
650 %type <TypeList> TypeListI ArgTypeListI
651 %type <JumpTable> JumpTable
652 %type <BoolVal> GlobalType OptInternal // GLOBAL or CONSTANT? Intern?
654 // ValueRef - Unresolved reference to a definition or BB
655 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
656 %type <ValueVal> ResolvedVal // <type> <valref> pair
657 // Tokens and types for handling constant integer values
659 // ESINT64VAL - A negative number within long long range
660 %token <SInt64Val> ESINT64VAL
662 // EUINT64VAL - A positive number within uns. long long range
663 %token <UInt64Val> EUINT64VAL
664 %type <SInt64Val> EINT64VAL
666 %token <SIntVal> SINTVAL // Signed 32 bit ints...
667 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
668 %type <SIntVal> INTVAL
669 %token <FPVal> FPVAL // Float or Double constant
672 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
673 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
674 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
675 %token <PrimType> FLOAT DOUBLE TYPE LABEL
677 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
678 %type <StrVal> OptVAR_ID OptAssign FuncName
681 %token IMPLEMENTATION TRUE FALSE BEGINTOK ENDTOK DECLARE GLOBAL CONSTANT UNINIT
682 %token TO EXCEPT DOTDOTDOT NULL_TOK CONST INTERNAL OPAQUE NOT
684 // Basic Block Terminating Operators
685 %token <TermOpVal> RET BR SWITCH
688 %type <BinaryOpVal> BinaryOps // all the binary operators
689 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
690 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
692 // Memory Instructions
693 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
696 %type <OtherOpVal> ShiftOps
697 %token <OtherOpVal> PHI CALL INVOKE CAST SHL SHR
702 // Handle constant integer size restriction and conversion...
707 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
708 ThrowException("Value too large for type!");
713 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
714 EINT64VAL : EUINT64VAL {
715 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
716 ThrowException("Value too large for type!");
720 // Operations that are notably excluded from this list include:
721 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
723 BinaryOps : ADD | SUB | MUL | DIV | REM | AND | OR | XOR;
724 BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
725 ShiftOps : SHL | SHR;
727 // These are some types that allow classification if we only want a particular
728 // thing... for example, only a signed, unsigned, or integral type.
729 SIntType : LONG | INT | SHORT | SBYTE;
730 UIntType : ULONG | UINT | USHORT | UBYTE;
731 IntType : SIntType | UIntType;
732 FPType : FLOAT | DOUBLE;
734 // OptAssign - Value producing statements have an optional assignment component
735 OptAssign : VAR_ID '=' {
742 OptInternal : INTERNAL { $$ = true; } | /*empty*/ { $$ = false; };
744 //===----------------------------------------------------------------------===//
745 // Types includes all predefined types... except void, because it can only be
746 // used in specific contexts (function returning void for example). To have
747 // access to it, a user must explicitly use TypesV.
750 // TypesV includes all of 'Types', but it also includes the void type.
751 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
752 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
756 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
761 // Derived types are added later...
763 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
764 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
766 $$ = new PATypeHolder(OpaqueType::get());
769 $$ = new PATypeHolder($1);
771 UpRTypes : SymbolicValueRef { // Named types are also simple types...
772 $$ = new PATypeHolder(getTypeVal($1));
775 // Include derived types in the Types production.
777 UpRTypes : '\\' EUINT64VAL { // Type UpReference
778 if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
779 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
780 UpRefs.push_back(make_pair((unsigned)$2, OT)); // Add to vector...
781 $$ = new PATypeHolder(OT);
782 UR_OUT("New Upreference!\n");
784 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
785 vector<const Type*> Params;
786 mapto($3->begin(), $3->end(), std::back_inserter(Params),
787 std::mem_fun_ref(&PATypeHandle<Type>::get));
788 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
789 if (isVarArg) Params.pop_back();
791 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
792 delete $3; // Delete the argument list
793 delete $1; // Delete the old type handle
795 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
796 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
799 | '{' TypeListI '}' { // Structure type?
800 vector<const Type*> Elements;
801 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
802 std::mem_fun_ref(&PATypeHandle<Type>::get));
804 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
807 | '{' '}' { // Empty structure type?
808 $$ = new PATypeHolder(StructType::get(vector<const Type*>()));
810 | UpRTypes '*' { // Pointer type?
811 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
815 // TypeList - Used for struct declarations and as a basis for function type
816 // declaration type lists
818 TypeListI : UpRTypes {
819 $$ = new list<PATypeHolder>();
820 $$->push_back(*$1); delete $1;
822 | TypeListI ',' UpRTypes {
823 ($$=$1)->push_back(*$3); delete $3;
826 // ArgTypeList - List of types for a function type declaration...
827 ArgTypeListI : TypeListI
828 | TypeListI ',' DOTDOTDOT {
829 ($$=$1)->push_back(Type::VoidTy);
832 ($$ = new list<PATypeHolder>())->push_back(Type::VoidTy);
835 $$ = new list<PATypeHolder>();
838 // ConstVal - The various declarations that go into the constant pool. This
839 // production is used ONLY to represent constants that show up AFTER a 'const',
840 // 'constant' or 'global' token at global scope. Constants that can be inlined
841 // into other expressions (such as integers and constexprs) are handled by the
842 // ResolvedVal, ValueRef and ConstValueRef productions.
844 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
845 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
847 ThrowException("Cannot make array constant with type: '" +
848 (*$1)->getDescription() + "'!");
849 const Type *ETy = ATy->getElementType();
850 int NumElements = ATy->getNumElements();
852 // Verify that we have the correct size...
853 if (NumElements != -1 && NumElements != (int)$3->size())
854 ThrowException("Type mismatch: constant sized array initialized with " +
855 utostr($3->size()) + " arguments, but has size of " +
856 itostr(NumElements) + "!");
858 // Verify all elements are correct type!
859 for (unsigned i = 0; i < $3->size(); i++) {
860 if (ETy != (*$3)[i]->getType())
861 ThrowException("Element #" + utostr(i) + " is not of type '" +
862 ETy->getDescription() +"' as required!\nIt is of type '"+
863 (*$3)[i]->getType()->getDescription() + "'.");
866 $$ = ConstantArray::get(ATy, *$3);
867 delete $1; delete $3;
870 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
872 ThrowException("Cannot make array constant with type: '" +
873 (*$1)->getDescription() + "'!");
875 int NumElements = ATy->getNumElements();
876 if (NumElements != -1 && NumElements != 0)
877 ThrowException("Type mismatch: constant sized array initialized with 0"
878 " arguments, but has size of " + itostr(NumElements) +"!");
879 $$ = ConstantArray::get(ATy, vector<Constant*>());
882 | Types 'c' STRINGCONSTANT {
883 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
885 ThrowException("Cannot make array constant with type: '" +
886 (*$1)->getDescription() + "'!");
888 int NumElements = ATy->getNumElements();
889 const Type *ETy = ATy->getElementType();
890 char *EndStr = UnEscapeLexed($3, true);
891 if (NumElements != -1 && NumElements != (EndStr-$3))
892 ThrowException("Can't build string constant of size " +
893 itostr((int)(EndStr-$3)) +
894 " when array has size " + itostr(NumElements) + "!");
895 vector<Constant*> Vals;
896 if (ETy == Type::SByteTy) {
897 for (char *C = $3; C != EndStr; ++C)
898 Vals.push_back(ConstantSInt::get(ETy, *C));
899 } else if (ETy == Type::UByteTy) {
900 for (char *C = $3; C != EndStr; ++C)
901 Vals.push_back(ConstantUInt::get(ETy, *C));
904 ThrowException("Cannot build string arrays of non byte sized elements!");
907 $$ = ConstantArray::get(ATy, Vals);
910 | Types '{' ConstVector '}' {
911 const StructType *STy = dyn_cast<const StructType>($1->get());
913 ThrowException("Cannot make struct constant with type: '" +
914 (*$1)->getDescription() + "'!");
915 // FIXME: TODO: Check to see that the constants are compatible with the type
917 $$ = ConstantStruct::get(STy, *$3);
918 delete $1; delete $3;
921 const PointerType *PTy = dyn_cast<const PointerType>($1->get());
923 ThrowException("Cannot make null pointer constant with type: '" +
924 (*$1)->getDescription() + "'!");
926 $$ = ConstantPointerNull::get(PTy);
929 | Types SymbolicValueRef {
930 const PointerType *Ty = dyn_cast<const PointerType>($1->get());
932 ThrowException("Global const reference must be a pointer type!");
934 // ConstExprs can exist in the body of a function, thus creating
935 // ConstantPointerRefs whenever they refer to a variable. Because we are in
936 // the context of a function, getValNonImprovising will search the functions
937 // symbol table instead of the module symbol table for the global symbol,
938 // which throws things all off. To get around this, we just tell
939 // getValNonImprovising that we are at global scope here.
941 Function *SavedCurFn = CurMeth.CurrentFunction;
942 CurMeth.CurrentFunction = 0;
944 Value *V = getValNonImprovising(Ty, $2);
946 CurMeth.CurrentFunction = SavedCurFn;
949 // If this is an initializer for a constant pointer, which is referencing a
950 // (currently) undefined variable, create a stub now that shall be replaced
951 // in the future with the right type of variable.
954 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
955 const PointerType *PT = cast<PointerType>(Ty);
957 // First check to see if the forward references value is already created!
958 PerModuleInfo::GlobalRefsType::iterator I =
959 CurModule.GlobalRefs.find(make_pair(PT, $2));
961 if (I != CurModule.GlobalRefs.end()) {
962 V = I->second; // Placeholder already exists, use it...
964 // TODO: Include line number info by creating a subclass of
965 // TODO: GlobalVariable here that includes the said information!
967 // Create a placeholder for the global variable reference...
968 GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
970 // Keep track of the fact that we have a forward ref to recycle it
971 CurModule.GlobalRefs.insert(make_pair(make_pair(PT, $2), GV));
973 // Must temporarily push this value into the module table...
974 CurModule.CurrentModule->getGlobalList().push_back(GV);
979 GlobalValue *GV = cast<GlobalValue>(V);
980 $$ = ConstantPointerRef::get(GV);
981 delete $1; // Free the type handle
984 if ($1->get() != $2->getType())
985 ThrowException("Mismatched types for constant expression!");
990 ConstVal : SIntType EINT64VAL { // integral constants
991 if (!ConstantSInt::isValueValidForType($1, $2))
992 ThrowException("Constant value doesn't fit in type!");
993 $$ = ConstantSInt::get($1, $2);
995 | UIntType EUINT64VAL { // integral constants
996 if (!ConstantUInt::isValueValidForType($1, $2))
997 ThrowException("Constant value doesn't fit in type!");
998 $$ = ConstantUInt::get($1, $2);
1000 | BOOL TRUE { // Boolean constants
1001 $$ = ConstantBool::True;
1003 | BOOL FALSE { // Boolean constants
1004 $$ = ConstantBool::False;
1006 | FPType FPVAL { // Float & Double constants
1007 $$ = ConstantFP::get($1, $2);
1011 ConstExpr: CAST '(' ConstVal TO Types ')' {
1012 $$ = ConstantExpr::getCast($3, $5->get());
1015 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1016 if (!isa<PointerType>($3->getType()))
1017 ThrowException("GetElementPtr requires a pointer operand!");
1020 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1022 ThrowException("Index list invalid for constant getelementptr!");
1024 vector<Constant*> IdxVec;
1025 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1026 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1027 IdxVec.push_back(C);
1029 ThrowException("Indices to constant getelementptr must be constants!");
1033 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1035 | BinaryOps '(' ConstVal ',' ConstVal ')' {
1036 if ($3->getType() != $5->getType())
1037 ThrowException("Binary operator types must match!");
1038 $$ = ConstantExpr::get($1, $3, $5);
1040 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1041 if ($5->getType() != Type::UByteTy)
1042 ThrowException("Shift count for shift constant must be unsigned byte!");
1043 $$ = ConstantExpr::get($1, $3, $5);
1047 // ConstVector - A list of comma seperated constants.
1048 ConstVector : ConstVector ',' ConstVal {
1049 ($$ = $1)->push_back($3);
1052 $$ = new vector<Constant*>();
1057 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1058 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1061 //===----------------------------------------------------------------------===//
1062 // Rules to match Modules
1063 //===----------------------------------------------------------------------===//
1065 // Module rule: Capture the result of parsing the whole file into a result
1068 Module : FunctionList {
1069 $$ = ParserResult = $1;
1070 CurModule.ModuleDone();
1073 // FunctionList - A list of functions, preceeded by a constant pool.
1075 FunctionList : FunctionList Function {
1077 assert($2->getParent() == 0 && "Function already in module!");
1078 $1->getFunctionList().push_back($2);
1079 CurMeth.FunctionDone();
1081 | FunctionList FunctionProto {
1084 | FunctionList IMPLEMENTATION {
1088 $$ = CurModule.CurrentModule;
1089 // Resolve circular types before we parse the body of the module
1090 ResolveTypes(CurModule.LateResolveTypes);
1093 // ConstPool - Constants with optional names assigned to them.
1094 ConstPool : ConstPool OptAssign CONST ConstVal {
1095 if (setValueName($4, $2)) { assert(0 && "No redefinitions allowed!"); }
1098 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1099 // Eagerly resolve types. This is not an optimization, this is a
1100 // requirement that is due to the fact that we could have this:
1102 // %list = type { %list * }
1103 // %list = type { %list * } ; repeated type decl
1105 // If types are not resolved eagerly, then the two types will not be
1106 // determined to be the same type!
1108 ResolveTypeTo($2, $4->get());
1110 // TODO: FIXME when Type are not const
1111 if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1112 // If this is not a redefinition of a type...
1114 InsertType($4->get(),
1115 inFunctionScope() ? CurMeth.Types : CurModule.Types);
1121 | ConstPool FunctionProto { // Function prototypes can be in const pool
1123 | ConstPool OptAssign OptInternal GlobalType ConstVal {
1124 const Type *Ty = $5->getType();
1125 // Global declarations appear in Constant Pool
1126 Constant *Initializer = $5;
1127 if (Initializer == 0)
1128 ThrowException("Global value initializer is not a constant!");
1130 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1131 if (!setValueName(GV, $2)) { // If not redefining...
1132 CurModule.CurrentModule->getGlobalList().push_back(GV);
1133 int Slot = InsertValue(GV, CurModule.Values);
1136 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1138 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1139 (char*)GV->getName().c_str()));
1143 | ConstPool OptAssign OptInternal UNINIT GlobalType Types {
1144 const Type *Ty = *$6;
1145 // Global declarations appear in Constant Pool
1146 GlobalVariable *GV = new GlobalVariable(Ty, $5, $3);
1147 if (!setValueName(GV, $2)) { // If not redefining...
1148 CurModule.CurrentModule->getGlobalList().push_back(GV);
1149 int Slot = InsertValue(GV, CurModule.Values);
1152 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1154 assert(GV->hasName() && "Not named and not numbered!?");
1155 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1156 (char*)GV->getName().c_str()));
1161 | /* empty: end of list */ {
1165 //===----------------------------------------------------------------------===//
1166 // Rules to match Function Headers
1167 //===----------------------------------------------------------------------===//
1169 OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; };
1171 ArgVal : Types OptVAR_ID {
1172 $$ = new pair<Argument*, char*>(new Argument(*$1), $2);
1173 delete $1; // Delete the type handle..
1176 ArgListH : ArgVal ',' ArgListH {
1178 $3->push_front(*$1);
1182 $$ = new list<pair<Argument*,char*> >();
1183 $$->push_front(*$1);
1187 $$ = new list<pair<Argument*, char*> >();
1188 $$->push_front(pair<Argument*,char*>(new Argument(Type::VoidTy), 0));
1191 ArgList : ArgListH {
1198 FuncName : VAR_ID | STRINGCONSTANT;
1200 FunctionHeaderH : OptInternal TypesV FuncName '(' ArgList ')' {
1202 string FunctionName($3);
1204 vector<const Type*> ParamTypeList;
1206 for (list<pair<Argument*,char*> >::iterator I = $5->begin();
1207 I != $5->end(); ++I)
1208 ParamTypeList.push_back(I->first->getType());
1210 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1211 if (isVarArg) ParamTypeList.pop_back();
1213 const FunctionType *MT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1214 const PointerType *PMT = PointerType::get(MT);
1218 if (SymbolTable *ST = CurModule.CurrentModule->getSymbolTable()) {
1219 // Is the function already in symtab?
1220 if (Value *V = ST->lookup(PMT, FunctionName)) {
1221 M = cast<Function>(V);
1223 // Yes it is. If this is the case, either we need to be a forward decl,
1224 // or it needs to be.
1225 if (!CurMeth.isDeclare && !M->isExternal())
1226 ThrowException("Redefinition of function '" + FunctionName + "'!");
1228 // Make sure that we keep track of the internal marker, even if there was
1229 // a previous "declare".
1231 M->setInternalLinkage(true);
1233 // If we found a preexisting function prototype, remove it from the
1234 // module, so that we don't get spurious conflicts with global & local
1237 CurModule.CurrentModule->getFunctionList().remove(M);
1241 if (M == 0) { // Not already defined?
1242 M = new Function(MT, $1, FunctionName);
1243 InsertValue(M, CurModule.Values);
1244 CurModule.DeclareNewGlobalValue(M, ValID::create($3));
1246 free($3); // Free strdup'd memory!
1248 CurMeth.FunctionStart(M);
1250 // Add all of the arguments we parsed to the function...
1251 if ($5 && !CurMeth.isDeclare) { // Is null if empty...
1252 for (list<pair<Argument*, char*> >::iterator I = $5->begin();
1253 I != $5->end(); ++I) {
1254 if (setValueName(I->first, I->second)) { // Insert into symtab...
1255 assert(0 && "No arg redef allowed!");
1258 InsertValue(I->first);
1259 M->getArgumentList().push_back(I->first);
1261 delete $5; // We're now done with the argument list
1263 // If we are a declaration, we should free the memory for the argument list!
1264 for (list<pair<Argument*, char*> >::iterator I = $5->begin(), E = $5->end();
1266 if (I->second) free(I->second); // Free the memory for the name...
1267 delete I->first; // Free the unused function argument
1269 delete $5; // Free the memory for the list itself
1273 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1275 FunctionHeader : FunctionHeaderH BEGIN {
1276 $$ = CurMeth.CurrentFunction;
1278 // Resolve circular types before we parse the body of the function.
1279 ResolveTypes(CurMeth.LateResolveTypes);
1282 END : ENDTOK | '}'; // Allow end of '}' to end a function
1284 Function : BasicBlockList END {
1288 FunctionProto : DECLARE { CurMeth.isDeclare = true; } FunctionHeaderH {
1289 $$ = CurMeth.CurrentFunction;
1290 assert($$->getParent() == 0 && "Function already in module!");
1291 CurModule.CurrentModule->getFunctionList().push_back($$);
1292 CurMeth.FunctionDone();
1295 //===----------------------------------------------------------------------===//
1296 // Rules to match Basic Blocks
1297 //===----------------------------------------------------------------------===//
1299 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1300 $$ = ValID::create($1);
1303 $$ = ValID::create($1);
1305 | FPVAL { // Perhaps it's an FP constant?
1306 $$ = ValID::create($1);
1309 $$ = ValID::create(ConstantBool::True);
1312 $$ = ValID::create(ConstantBool::False);
1315 $$ = ValID::createNull();
1318 $$ = ValID::create($1);
1321 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1324 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1325 $$ = ValID::create($1);
1327 | VAR_ID { // Is it a named reference...?
1328 $$ = ValID::create($1);
1331 // ValueRef - A reference to a definition... either constant or symbolic
1332 ValueRef : SymbolicValueRef | ConstValueRef;
1335 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1336 // type immediately preceeds the value reference, and allows complex constant
1337 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1338 ResolvedVal : Types ValueRef {
1339 $$ = getVal(*$1, $2); delete $1;
1342 BasicBlockList : BasicBlockList BasicBlock {
1343 ($$ = $1)->getBasicBlockList().push_back($2);
1345 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1346 ($$ = $1)->getBasicBlockList().push_back($2);
1350 // Basic blocks are terminated by branching instructions:
1351 // br, br/cc, switch, ret
1353 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1354 if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1357 $1->getInstList().push_back($3);
1361 | LABELSTR InstructionList OptAssign BBTerminatorInst {
1362 if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1365 $2->getInstList().push_back($4);
1366 if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1372 InstructionList : InstructionList Inst {
1373 $1->getInstList().push_back($2);
1377 $$ = CurBB = new BasicBlock();
1380 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1381 $$ = new ReturnInst($2);
1383 | RET VOID { // Return with no result...
1384 $$ = new ReturnInst();
1386 | BR LABEL ValueRef { // Unconditional Branch...
1387 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1388 } // Conditional Branch...
1389 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1390 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1391 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1392 getVal(Type::BoolTy, $3));
1394 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1395 SwitchInst *S = new SwitchInst(getVal($2, $3),
1396 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1399 vector<pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1402 S->dest_push_back(I->first, I->second);
1404 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal
1405 EXCEPT ResolvedVal {
1406 const PointerType *PMTy;
1407 const FunctionType *Ty;
1409 if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1410 !(Ty = dyn_cast<FunctionType>(PMTy->getElementType()))) {
1411 // Pull out the types of all of the arguments...
1412 vector<const Type*> ParamTypes;
1414 for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1415 ParamTypes.push_back((*I)->getType());
1418 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1419 if (isVarArg) ParamTypes.pop_back();
1421 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1422 PMTy = PointerType::get(Ty);
1426 Value *V = getVal(PMTy, $3); // Get the function we're calling...
1428 BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1429 BasicBlock *Except = dyn_cast<BasicBlock>($10);
1431 if (Normal == 0 || Except == 0)
1432 ThrowException("Invoke instruction without label destinations!");
1434 // Create the call node...
1435 if (!$5) { // Has no arguments?
1436 $$ = new InvokeInst(V, Normal, Except, vector<Value*>());
1437 } else { // Has arguments?
1438 // Loop through FunctionType's arguments and ensure they are specified
1441 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1442 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1443 vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1445 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1446 if ((*ArgI)->getType() != *I)
1447 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1448 (*I)->getDescription() + "'!");
1450 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1451 ThrowException("Invalid number of parameters detected!");
1453 $$ = new InvokeInst(V, Normal, Except, *$5);
1460 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1462 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1464 ThrowException("May only switch on a constant pool value!");
1466 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1468 | IntType ConstValueRef ',' LABEL ValueRef {
1469 $$ = new vector<pair<Constant*, BasicBlock*> >();
1470 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1473 ThrowException("May only switch on a constant pool value!");
1475 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1478 Inst : OptAssign InstVal {
1479 // Is this definition named?? if so, assign the name...
1480 if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1485 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1486 $$ = new list<pair<Value*, BasicBlock*> >();
1487 $$->push_back(make_pair(getVal(*$1, $3),
1488 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1491 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1493 $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
1494 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1498 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1499 $$ = new vector<Value*>();
1502 | ValueRefList ',' ResolvedVal {
1507 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1508 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1510 InstVal : BinaryOps Types ValueRef ',' ValueRef {
1511 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1513 ThrowException("binary operator returned null!");
1517 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1518 << " Replacing with 'xor'.\n";
1520 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1522 ThrowException("Expected integral type for not instruction!");
1524 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1526 ThrowException("Could not create a xor instruction!");
1528 | ShiftOps ResolvedVal ',' ResolvedVal {
1529 if ($4->getType() != Type::UByteTy)
1530 ThrowException("Shift amount must be ubyte!");
1531 $$ = new ShiftInst($1, $2, $4);
1533 | CAST ResolvedVal TO Types {
1534 $$ = new CastInst($2, *$4);
1538 const Type *Ty = $2->front().first->getType();
1539 $$ = new PHINode(Ty);
1540 while ($2->begin() != $2->end()) {
1541 if ($2->front().first->getType() != Ty)
1542 ThrowException("All elements of a PHI node must be of the same type!");
1543 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1546 delete $2; // Free the list...
1548 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1549 const PointerType *PMTy;
1550 const FunctionType *Ty;
1552 if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1553 !(Ty = dyn_cast<FunctionType>(PMTy->getElementType()))) {
1554 // Pull out the types of all of the arguments...
1555 vector<const Type*> ParamTypes;
1557 for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1558 ParamTypes.push_back((*I)->getType());
1561 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1562 if (isVarArg) ParamTypes.pop_back();
1564 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1565 PMTy = PointerType::get(Ty);
1569 Value *V = getVal(PMTy, $3); // Get the function we're calling...
1571 // Create the call node...
1572 if (!$5) { // Has no arguments?
1573 // Make sure no arguments is a good thing!
1574 if (Ty->getNumParams() != 0)
1575 ThrowException("No arguments passed to a function that "
1576 "expects arguments!");
1578 $$ = new CallInst(V, vector<Value*>());
1579 } else { // Has arguments?
1580 // Loop through FunctionType's arguments and ensure they are specified
1583 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1584 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1585 vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1587 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1588 if ((*ArgI)->getType() != *I)
1589 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1590 (*I)->getDescription() + "'!");
1592 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1593 ThrowException("Invalid number of parameters detected!");
1595 $$ = new CallInst(V, *$5);
1604 // IndexList - List of indices for GEP based instructions...
1605 IndexList : ',' ValueRefList {
1608 $$ = new vector<Value*>();
1611 MemoryInst : MALLOC Types {
1612 $$ = new MallocInst(PointerType::get(*$2));
1615 | MALLOC Types ',' UINT ValueRef {
1616 const Type *Ty = PointerType::get(*$2);
1617 $$ = new MallocInst(Ty, getVal($4, $5));
1621 $$ = new AllocaInst(PointerType::get(*$2));
1624 | ALLOCA Types ',' UINT ValueRef {
1625 const Type *Ty = PointerType::get(*$2);
1626 Value *ArrSize = getVal($4, $5);
1627 $$ = new AllocaInst(Ty, ArrSize);
1630 | FREE ResolvedVal {
1631 if (!isa<PointerType>($2->getType()))
1632 ThrowException("Trying to free nonpointer type " +
1633 $2->getType()->getDescription() + "!");
1634 $$ = new FreeInst($2);
1637 | LOAD Types ValueRef IndexList {
1638 if (!isa<PointerType>($2->get()))
1639 ThrowException("Can't load from nonpointer type: " +
1640 (*$2)->getDescription());
1641 if (GetElementPtrInst::getIndexedType(*$2, *$4) == 0)
1642 ThrowException("Invalid indices for load instruction!");
1644 Value *Src = getVal(*$2, $3);
1646 std::cerr << "WARNING: Use of index load instruction:"
1647 << " replacing with getelementptr/load pair.\n";
1648 // Create a getelementptr hack instruction to do the right thing for
1651 Instruction *I = new GetElementPtrInst(Src, *$4);
1652 CurBB->getInstList().push_back(I);
1656 $$ = new LoadInst(Src);
1657 delete $4; // Free the vector...
1660 | STORE ResolvedVal ',' Types ValueRef IndexList {
1661 if (!isa<PointerType>($4->get()))
1662 ThrowException("Can't store to a nonpointer type: " +
1663 (*$4)->getDescription());
1664 const Type *ElTy = GetElementPtrInst::getIndexedType(*$4, *$6);
1666 ThrowException("Can't store into that field list!");
1667 if (ElTy != $2->getType())
1668 ThrowException("Can't store '" + $2->getType()->getDescription() +
1669 "' into space of type '" + ElTy->getDescription() + "'!");
1671 Value *Ptr = getVal(*$4, $5);
1673 std::cerr << "WARNING: Use of index store instruction:"
1674 << " replacing with getelementptr/store pair.\n";
1675 // Create a getelementptr hack instruction to do the right thing for
1678 Instruction *I = new GetElementPtrInst(Ptr, *$6);
1679 CurBB->getInstList().push_back(I);
1683 $$ = new StoreInst($2, Ptr);
1684 delete $4; delete $6;
1686 | GETELEMENTPTR Types ValueRef IndexList {
1687 if (!isa<PointerType>($2->get()))
1688 ThrowException("getelementptr insn requires pointer operand!");
1689 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1690 ThrowException("Can't get element ptr '" + (*$2)->getDescription()+ "'!");
1691 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1692 delete $2; delete $4;
1696 int yyerror(const char *ErrorMsg) {
1697 string where = string((CurFilename == "-")? string("<stdin>") : CurFilename)
1698 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
1699 string errMsg = string(ErrorMsg) + string("\n") + where + " while reading ";
1700 if (yychar == YYEMPTY)
1701 errMsg += "end-of-file.";
1703 errMsg += "token: '" + string(llvmAsmtext, llvmAsmleng) + "'";
1704 ThrowException(errMsg);