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/iOperators.h"
14 #include "llvm/iPHINode.h"
15 #include "Support/STLExtras.h"
16 #include "Support/DepthFirstIterator.h"
28 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
29 int yylex(); // declaration" of xxx warnings.
32 static Module *ParserResult;
35 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
36 // relating to upreferences in the input stream.
38 //#define DEBUG_UPREFS 1
40 #define UR_OUT(X) std::cerr << X
45 #define YYERROR_VERBOSE 1
47 // HACK ALERT: This variable is used to implement the automatic conversion of
48 // load/store instructions with indexes into a load/store + getelementptr pair
49 // of instructions. When this compatiblity "Feature" is removed, this should be
52 static BasicBlock *CurBB;
55 // This contains info used when building the body of a function. It is
56 // destroyed when the function is completed.
58 typedef vector<Value *> ValueList; // Numbered defs
59 static void ResolveDefinitions(vector<ValueList> &LateResolvers,
60 vector<ValueList> *FutureLateResolvers = 0);
62 static struct PerModuleInfo {
63 Module *CurrentModule;
64 vector<ValueList> Values; // Module level numbered definitions
65 vector<ValueList> LateResolveValues;
66 vector<PATypeHolder> Types;
67 map<ValID, PATypeHolder> LateResolveTypes;
69 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
70 // references to global values. Global values may be referenced before they
71 // are defined, and if so, the temporary object that they represent is held
72 // here. This is used for forward references of ConstantPointerRefs.
74 typedef map<pair<const PointerType *, ValID>, GlobalVariable*> GlobalRefsType;
75 GlobalRefsType GlobalRefs;
78 // If we could not resolve some functions at function compilation time
79 // (calls to functions before they are defined), resolve them now... Types
80 // are resolved when the constant pool has been completely parsed.
82 ResolveDefinitions(LateResolveValues);
84 // Check to make sure that all global value forward references have been
87 if (!GlobalRefs.empty()) {
88 string UndefinedReferences = "Unresolved global references exist:\n";
90 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
92 UndefinedReferences += " " + I->first.first->getDescription() + " " +
93 I->first.second.getName() + "\n";
95 ThrowException(UndefinedReferences);
98 Values.clear(); // Clear out function local definitions
104 // DeclareNewGlobalValue - Called every time a new GV has been defined. This
105 // is used to remove things from the forward declaration map, resolving them
106 // to the correct thing as needed.
108 void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
109 // Check to see if there is a forward reference to this global variable...
110 // if there is, eliminate it and patch the reference to use the new def'n.
111 GlobalRefsType::iterator I = GlobalRefs.find(make_pair(GV->getType(), D));
113 if (I != GlobalRefs.end()) {
114 GlobalVariable *OldGV = I->second; // Get the placeholder...
115 I->first.second.destroy(); // Free string memory if neccesary
117 // Loop over all of the uses of the GlobalValue. The only thing they are
118 // allowed to be is ConstantPointerRef's.
119 assert(OldGV->use_size() == 1 && "Only one reference should exist!");
120 User *U = OldGV->use_back(); // Must be a ConstantPointerRef...
121 ConstantPointerRef *CPR = cast<ConstantPointerRef>(U);
123 // Change the const pool reference to point to the real global variable
124 // now. This should drop a use from the OldGV.
125 CPR->mutateReferences(OldGV, GV);
126 assert(OldGV->use_empty() && "All uses should be gone now!");
128 // Remove OldGV 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 function 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 function 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 function local definitions
169 } CurMeth; // Info for the current function...
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 ValID::NumberVal: { // 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 ValID::NameVal: { // 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 function
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("Internal parser error: 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() :
256 CurModule.CurrentModule->getSymbolTable();
257 return SymTab ? SymTab->lookup(Ty, Name) : 0;
260 // getValNonImprovising - Look up the value specified by the provided type and
261 // the provided ValID. If the value exists and has already been defined, return
262 // it. Otherwise return null.
264 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
265 if (isa<FunctionType>(Ty))
266 ThrowException("Functions are not values and "
267 "must be referenced as pointers");
270 case ValID::NumberVal: { // Is it a numbered definition?
271 unsigned type = Ty->getUniqueID();
272 unsigned Num = (unsigned)D.Num;
274 // Module constants occupy the lowest numbered slots...
275 if (type < CurModule.Values.size()) {
276 if (Num < CurModule.Values[type].size())
277 return CurModule.Values[type][Num];
279 Num -= CurModule.Values[type].size();
282 // Make sure that our type is within bounds
283 if (CurMeth.Values.size() <= type) return 0;
285 // Check that the number is within bounds...
286 if (CurMeth.Values[type].size() <= Num) return 0;
288 return CurMeth.Values[type][Num];
291 case ValID::NameVal: { // Is it a named definition?
292 Value *N = lookupInSymbolTable(Ty, string(D.Name));
293 if (N == 0) return 0;
295 D.destroy(); // Free old strdup'd memory...
299 // Check to make sure that "Ty" is an integral type, and that our
300 // value will fit into the specified type...
301 case ValID::ConstSIntVal: // Is it a constant pool reference??
302 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
303 ThrowException("Signed integral constant '" +
304 itostr(D.ConstPool64) + "' is invalid for type '" +
305 Ty->getDescription() + "'!");
306 return ConstantSInt::get(Ty, D.ConstPool64);
308 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
309 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
310 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
311 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
312 "' is invalid or out of range!");
313 } else { // This is really a signed reference. Transmogrify.
314 return ConstantSInt::get(Ty, D.ConstPool64);
317 return ConstantUInt::get(Ty, D.UConstPool64);
320 case ValID::ConstFPVal: // Is it a floating point const pool reference?
321 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
322 ThrowException("FP constant invalid for type!!");
323 return ConstantFP::get(Ty, D.ConstPoolFP);
325 case ValID::ConstNullVal: // Is it a null value?
326 if (!isa<PointerType>(Ty))
327 ThrowException("Cannot create a a non pointer null!");
328 return ConstantPointerNull::get(cast<PointerType>(Ty));
330 case ValID::ConstantVal: // Fully resolved constant?
331 if (D.ConstantValue->getType() != Ty)
332 ThrowException("Constant expression type different from required type!");
333 return D.ConstantValue;
336 assert(0 && "Unhandled case!");
340 assert(0 && "Unhandled case!");
345 // getVal - This function is identical to getValNonImprovising, except that if a
346 // value is not already defined, it "improvises" by creating a placeholder var
347 // that looks and acts just like the requested variable. When the value is
348 // defined later, all uses of the placeholder variable are replaced with the
351 static Value *getVal(const Type *Ty, const ValID &D) {
352 assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
354 // See if the value has already been defined...
355 Value *V = getValNonImprovising(Ty, D);
358 // If we reached here, we referenced either a symbol that we don't know about
359 // or an id number that hasn't been read yet. We may be referencing something
360 // forward, so just create an entry to be resolved later and get to it...
363 switch (Ty->getPrimitiveID()) {
364 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
365 default: d = new ValuePlaceHolder(Ty, D); break;
368 assert(d != 0 && "How did we not make something?");
369 if (inFunctionScope())
370 InsertValue(d, CurMeth.LateResolveValues);
372 InsertValue(d, CurModule.LateResolveValues);
377 //===----------------------------------------------------------------------===//
378 // Code to handle forward references in instructions
379 //===----------------------------------------------------------------------===//
381 // This code handles the late binding needed with statements that reference
382 // values not defined yet... for example, a forward branch, or the PHI node for
385 // This keeps a table (CurMeth.LateResolveValues) of all such forward references
386 // and back patchs after we are done.
389 // ResolveDefinitions - If we could not resolve some defs at parsing
390 // time (forward branches, phi functions for loops, etc...) resolve the
393 static void ResolveDefinitions(vector<ValueList> &LateResolvers,
394 vector<ValueList> *FutureLateResolvers) {
395 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
396 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
397 while (!LateResolvers[ty].empty()) {
398 Value *V = LateResolvers[ty].back();
399 assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
401 LateResolvers[ty].pop_back();
402 ValID &DID = getValIDFromPlaceHolder(V);
404 Value *TheRealValue = getValNonImprovising(Type::getUniqueIDType(ty),DID);
406 V->replaceAllUsesWith(TheRealValue);
408 } else if (FutureLateResolvers) {
409 // Functions have their unresolved items forwarded to the module late
411 InsertValue(V, *FutureLateResolvers);
413 if (DID.Type == ValID::NameVal)
414 ThrowException("Reference to an invalid definition: '" +DID.getName()+
415 "' of type '" + V->getType()->getDescription() + "'",
416 getLineNumFromPlaceHolder(V));
418 ThrowException("Reference to an invalid definition: #" +
419 itostr(DID.Num) + " of type '" +
420 V->getType()->getDescription() + "'",
421 getLineNumFromPlaceHolder(V));
426 LateResolvers.clear();
429 // ResolveTypeTo - A brand new type was just declared. This means that (if
430 // name is not null) things referencing Name can be resolved. Otherwise, things
431 // refering to the number can be resolved. Do this now.
433 static void ResolveTypeTo(char *Name, const Type *ToTy) {
434 vector<PATypeHolder> &Types = inFunctionScope() ?
435 CurMeth.Types : CurModule.Types;
438 if (Name) D = ValID::create(Name);
439 else D = ValID::create((int)Types.size());
441 map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
442 CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
444 map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
445 if (I != LateResolver.end()) {
446 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
447 LateResolver.erase(I);
451 // ResolveTypes - At this point, all types should be resolved. Any that aren't
454 static void ResolveTypes(map<ValID, PATypeHolder> &LateResolveTypes) {
455 if (!LateResolveTypes.empty()) {
456 const ValID &DID = LateResolveTypes.begin()->first;
458 if (DID.Type == ValID::NameVal)
459 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
461 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
466 // setValueName - Set the specified value to the name given. The name may be
467 // null potentially, in which case this is a noop. The string passed in is
468 // assumed to be a malloc'd string buffer, and is freed by this function.
470 // This function returns true if the value has already been defined, but is
471 // allowed to be redefined in the specified context. If the name is a new name
472 // for the typeplane, false is returned.
474 static bool setValueName(Value *V, char *NameStr) {
475 if (NameStr == 0) return false;
477 string Name(NameStr); // Copy string
478 free(NameStr); // Free old string
480 if (V->getType() == Type::VoidTy)
481 ThrowException("Can't assign name '" + Name +
482 "' to a null valued instruction!");
484 SymbolTable *ST = inFunctionScope() ?
485 CurMeth.CurrentFunction->getSymbolTableSure() :
486 CurModule.CurrentModule->getSymbolTableSure();
488 Value *Existing = ST->lookup(V->getType(), Name);
489 if (Existing) { // Inserting a name that is already defined???
490 // There is only one case where this is allowed: when we are refining an
491 // opaque type. In this case, Existing will be an opaque type.
492 if (const Type *Ty = dyn_cast<const Type>(Existing)) {
493 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Ty)) {
494 // We ARE replacing an opaque type!
495 ((OpaqueType*)OpTy)->refineAbstractTypeTo(cast<Type>(V));
500 // Otherwise, we are a simple redefinition of a value, check to see if it
501 // is defined the same as the old one...
502 if (const Type *Ty = dyn_cast<const Type>(Existing)) {
503 if (Ty == cast<const Type>(V)) return true; // Yes, it's equal.
504 // std::cerr << "Type: " << Ty->getDescription() << " != "
505 // << cast<const Type>(V)->getDescription() << "!\n";
506 } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
507 // We are allowed to redefine a global variable in two circumstances:
508 // 1. If at least one of the globals is uninitialized or
509 // 2. If both initializers have the same value.
511 // This can only be done if the const'ness of the vars is the same.
513 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
514 if (EGV->isConstant() == GV->isConstant() &&
515 (!EGV->hasInitializer() || !GV->hasInitializer() ||
516 EGV->getInitializer() == GV->getInitializer())) {
518 // Make sure the existing global version gets the initializer!
519 if (GV->hasInitializer() && !EGV->hasInitializer())
520 EGV->setInitializer(GV->getInitializer());
522 delete GV; // Destroy the duplicate!
523 return true; // They are equivalent!
527 ThrowException("Redefinition of value named '" + Name + "' in the '" +
528 V->getType()->getDescription() + "' type plane!");
531 V->setName(Name, ST);
536 //===----------------------------------------------------------------------===//
537 // Code for handling upreferences in type names...
540 // TypeContains - Returns true if Ty contains E in it.
542 static bool TypeContains(const Type *Ty, const Type *E) {
543 return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
547 static vector<pair<unsigned, OpaqueType *> > UpRefs;
549 static PATypeHolder HandleUpRefs(const Type *ty) {
551 UR_OUT("Type '" << ty->getDescription() <<
552 "' newly formed. Resolving upreferences.\n" <<
553 UpRefs.size() << " upreferences active!\n");
554 for (unsigned i = 0; i < UpRefs.size(); ) {
555 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
556 << UpRefs[i].second->getDescription() << ") = "
557 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << endl);
558 if (TypeContains(Ty, UpRefs[i].second)) {
559 unsigned Level = --UpRefs[i].first; // Decrement level of upreference
560 UR_OUT(" Uplevel Ref Level = " << Level << endl);
561 if (Level == 0) { // Upreference should be resolved!
562 UR_OUT(" * Resolving upreference for "
563 << UpRefs[i].second->getDescription() << endl;
564 string OldName = UpRefs[i].second->getDescription());
565 UpRefs[i].second->refineAbstractTypeTo(Ty);
566 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
567 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
568 << (const void*)Ty << ", " << Ty->getDescription() << endl);
573 ++i; // Otherwise, no resolve, move on...
575 // FIXME: TODO: this should return the updated type
580 //===----------------------------------------------------------------------===//
581 // RunVMAsmParser - Define an interface to this parser
582 //===----------------------------------------------------------------------===//
584 Module *RunVMAsmParser(const string &Filename, FILE *F) {
586 CurFilename = Filename;
587 llvmAsmlineno = 1; // Reset the current line number...
589 CurModule.CurrentModule = new Module(); // Allocate a new module to read
590 yyparse(); // Parse the file.
591 Module *Result = ParserResult;
592 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
602 Function *FunctionVal;
603 std::pair<PATypeHolder*, char*> *ArgVal;
604 BasicBlock *BasicBlockVal;
605 TerminatorInst *TermInstVal;
606 Instruction *InstVal;
609 const Type *PrimType;
610 PATypeHolder *TypeVal;
613 std::vector<std::pair<PATypeHolder*,char*> > *ArgList;
614 std::vector<Value*> *ValueList;
615 std::list<PATypeHolder> *TypeList;
616 std::list<std::pair<Value*,
617 BasicBlock*> > *PHIList; // Represent the RHS of PHI node
618 std::vector<std::pair<Constant*, BasicBlock*> > *JumpTable;
619 std::vector<Constant*> *ConstVector;
628 char *StrVal; // This memory is strdup'd!
629 ValID ValIDVal; // strdup'd memory maybe!
631 Instruction::BinaryOps BinaryOpVal;
632 Instruction::TermOps TermOpVal;
633 Instruction::MemoryOps MemOpVal;
634 Instruction::OtherOps OtherOpVal;
637 %type <ModuleVal> Module FunctionList
638 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
639 %type <BasicBlockVal> BasicBlock InstructionList
640 %type <TermInstVal> BBTerminatorInst
641 %type <InstVal> Inst InstVal MemoryInst
642 %type <ConstVal> ConstVal ConstExpr
643 %type <ConstVector> ConstVector
644 %type <ArgList> ArgList ArgListH
645 %type <ArgVal> ArgVal
646 %type <PHIList> PHIList
647 %type <ValueList> ValueRefList ValueRefListE // For call param lists
648 %type <ValueList> IndexList // For GEP derived indices
649 %type <TypeList> TypeListI ArgTypeListI
650 %type <JumpTable> JumpTable
651 %type <BoolVal> GlobalType OptInternal // GLOBAL or CONSTANT? Intern?
653 // ValueRef - Unresolved reference to a definition or BB
654 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
655 %type <ValueVal> ResolvedVal // <type> <valref> pair
656 // Tokens and types for handling constant integer values
658 // ESINT64VAL - A negative number within long long range
659 %token <SInt64Val> ESINT64VAL
661 // EUINT64VAL - A positive number within uns. long long range
662 %token <UInt64Val> EUINT64VAL
663 %type <SInt64Val> EINT64VAL
665 %token <SIntVal> SINTVAL // Signed 32 bit ints...
666 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
667 %type <SIntVal> INTVAL
668 %token <FPVal> FPVAL // Float or Double constant
671 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
672 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
673 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
674 %token <PrimType> FLOAT DOUBLE TYPE LABEL
676 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
677 %type <StrVal> OptVAR_ID OptAssign FuncName
680 %token IMPLEMENTATION TRUE FALSE BEGINTOK ENDTOK DECLARE GLOBAL CONSTANT
681 %token TO EXCEPT DOTDOTDOT NULL_TOK CONST INTERNAL OPAQUE NOT EXTERNAL
683 // Basic Block Terminating Operators
684 %token <TermOpVal> RET BR SWITCH
687 %type <BinaryOpVal> BinaryOps // all the binary operators
688 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
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 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
724 LogicalOps : AND | OR | XOR;
725 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
726 BinaryOps : ArithmeticOps | LogicalOps | SetCondOps;
728 ShiftOps : SHL | SHR;
730 // These are some types that allow classification if we only want a particular
731 // thing... for example, only a signed, unsigned, or integral type.
732 SIntType : LONG | INT | SHORT | SBYTE;
733 UIntType : ULONG | UINT | USHORT | UBYTE;
734 IntType : SIntType | UIntType;
735 FPType : FLOAT | DOUBLE;
737 // OptAssign - Value producing statements have an optional assignment component
738 OptAssign : VAR_ID '=' {
745 OptInternal : INTERNAL { $$ = true; } | /*empty*/ { $$ = false; };
747 //===----------------------------------------------------------------------===//
748 // Types includes all predefined types... except void, because it can only be
749 // used in specific contexts (function returning void for example). To have
750 // access to it, a user must explicitly use TypesV.
753 // TypesV includes all of 'Types', but it also includes the void type.
754 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
755 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
759 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
764 // Derived types are added later...
766 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
767 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
769 $$ = new PATypeHolder(OpaqueType::get());
772 $$ = new PATypeHolder($1);
774 UpRTypes : SymbolicValueRef { // Named types are also simple types...
775 $$ = new PATypeHolder(getTypeVal($1));
778 // Include derived types in the Types production.
780 UpRTypes : '\\' EUINT64VAL { // Type UpReference
781 if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
782 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
783 UpRefs.push_back(make_pair((unsigned)$2, OT)); // Add to vector...
784 $$ = new PATypeHolder(OT);
785 UR_OUT("New Upreference!\n");
787 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
788 vector<const Type*> Params;
789 mapto($3->begin(), $3->end(), std::back_inserter(Params),
790 std::mem_fun_ref(&PATypeHandle<Type>::get));
791 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
792 if (isVarArg) Params.pop_back();
794 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
795 delete $3; // Delete the argument list
796 delete $1; // Delete the old type handle
798 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
799 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
802 | '{' TypeListI '}' { // Structure type?
803 vector<const Type*> Elements;
804 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
805 std::mem_fun_ref(&PATypeHandle<Type>::get));
807 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
810 | '{' '}' { // Empty structure type?
811 $$ = new PATypeHolder(StructType::get(vector<const Type*>()));
813 | UpRTypes '*' { // Pointer type?
814 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
818 // TypeList - Used for struct declarations and as a basis for function type
819 // declaration type lists
821 TypeListI : UpRTypes {
822 $$ = new list<PATypeHolder>();
823 $$->push_back(*$1); delete $1;
825 | TypeListI ',' UpRTypes {
826 ($$=$1)->push_back(*$3); delete $3;
829 // ArgTypeList - List of types for a function type declaration...
830 ArgTypeListI : TypeListI
831 | TypeListI ',' DOTDOTDOT {
832 ($$=$1)->push_back(Type::VoidTy);
835 ($$ = new list<PATypeHolder>())->push_back(Type::VoidTy);
838 $$ = new list<PATypeHolder>();
841 // ConstVal - The various declarations that go into the constant pool. This
842 // production is used ONLY to represent constants that show up AFTER a 'const',
843 // 'constant' or 'global' token at global scope. Constants that can be inlined
844 // into other expressions (such as integers and constexprs) are handled by the
845 // ResolvedVal, ValueRef and ConstValueRef productions.
847 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
848 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
850 ThrowException("Cannot make array constant with type: '" +
851 (*$1)->getDescription() + "'!");
852 const Type *ETy = ATy->getElementType();
853 int NumElements = ATy->getNumElements();
855 // Verify that we have the correct size...
856 if (NumElements != -1 && NumElements != (int)$3->size())
857 ThrowException("Type mismatch: constant sized array initialized with " +
858 utostr($3->size()) + " arguments, but has size of " +
859 itostr(NumElements) + "!");
861 // Verify all elements are correct type!
862 for (unsigned i = 0; i < $3->size(); i++) {
863 if (ETy != (*$3)[i]->getType())
864 ThrowException("Element #" + utostr(i) + " is not of type '" +
865 ETy->getDescription() +"' as required!\nIt is of type '"+
866 (*$3)[i]->getType()->getDescription() + "'.");
869 $$ = ConstantArray::get(ATy, *$3);
870 delete $1; delete $3;
873 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
875 ThrowException("Cannot make array constant with type: '" +
876 (*$1)->getDescription() + "'!");
878 int NumElements = ATy->getNumElements();
879 if (NumElements != -1 && NumElements != 0)
880 ThrowException("Type mismatch: constant sized array initialized with 0"
881 " arguments, but has size of " + itostr(NumElements) +"!");
882 $$ = ConstantArray::get(ATy, vector<Constant*>());
885 | Types 'c' STRINGCONSTANT {
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 const Type *ETy = ATy->getElementType();
893 char *EndStr = UnEscapeLexed($3, true);
894 if (NumElements != -1 && NumElements != (EndStr-$3))
895 ThrowException("Can't build string constant of size " +
896 itostr((int)(EndStr-$3)) +
897 " when array has size " + itostr(NumElements) + "!");
898 vector<Constant*> Vals;
899 if (ETy == Type::SByteTy) {
900 for (char *C = $3; C != EndStr; ++C)
901 Vals.push_back(ConstantSInt::get(ETy, *C));
902 } else if (ETy == Type::UByteTy) {
903 for (char *C = $3; C != EndStr; ++C)
904 Vals.push_back(ConstantUInt::get(ETy, *C));
907 ThrowException("Cannot build string arrays of non byte sized elements!");
910 $$ = ConstantArray::get(ATy, Vals);
913 | Types '{' ConstVector '}' {
914 const StructType *STy = dyn_cast<const StructType>($1->get());
916 ThrowException("Cannot make struct constant with type: '" +
917 (*$1)->getDescription() + "'!");
918 // FIXME: TODO: Check to see that the constants are compatible with the type
920 $$ = ConstantStruct::get(STy, *$3);
921 delete $1; delete $3;
924 const PointerType *PTy = dyn_cast<const PointerType>($1->get());
926 ThrowException("Cannot make null pointer constant with type: '" +
927 (*$1)->getDescription() + "'!");
929 $$ = ConstantPointerNull::get(PTy);
932 | Types SymbolicValueRef {
933 const PointerType *Ty = dyn_cast<const PointerType>($1->get());
935 ThrowException("Global const reference must be a pointer type!");
937 // ConstExprs can exist in the body of a function, thus creating
938 // ConstantPointerRefs whenever they refer to a variable. Because we are in
939 // the context of a function, getValNonImprovising will search the functions
940 // symbol table instead of the module symbol table for the global symbol,
941 // which throws things all off. To get around this, we just tell
942 // getValNonImprovising that we are at global scope here.
944 Function *SavedCurFn = CurMeth.CurrentFunction;
945 CurMeth.CurrentFunction = 0;
947 Value *V = getValNonImprovising(Ty, $2);
949 CurMeth.CurrentFunction = SavedCurFn;
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
987 if ($1->get() != $2->getType())
988 ThrowException("Mismatched types for constant expression!");
993 ConstVal : SIntType EINT64VAL { // integral constants
994 if (!ConstantSInt::isValueValidForType($1, $2))
995 ThrowException("Constant value doesn't fit in type!");
996 $$ = ConstantSInt::get($1, $2);
998 | UIntType EUINT64VAL { // integral constants
999 if (!ConstantUInt::isValueValidForType($1, $2))
1000 ThrowException("Constant value doesn't fit in type!");
1001 $$ = ConstantUInt::get($1, $2);
1003 | BOOL TRUE { // Boolean constants
1004 $$ = ConstantBool::True;
1006 | BOOL FALSE { // Boolean constants
1007 $$ = ConstantBool::False;
1009 | FPType FPVAL { // Float & Double constants
1010 $$ = ConstantFP::get($1, $2);
1014 ConstExpr: CAST '(' ConstVal TO Types ')' {
1015 $$ = ConstantExpr::getCast($3, $5->get());
1018 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1019 if (!isa<PointerType>($3->getType()))
1020 ThrowException("GetElementPtr requires a pointer operand!");
1023 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1025 ThrowException("Index list invalid for constant getelementptr!");
1027 vector<Constant*> IdxVec;
1028 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1029 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1030 IdxVec.push_back(C);
1032 ThrowException("Indices to constant getelementptr must be constants!");
1036 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1038 | BinaryOps '(' ConstVal ',' ConstVal ')' {
1039 if ($3->getType() != $5->getType())
1040 ThrowException("Binary operator types must match!");
1041 $$ = ConstantExpr::get($1, $3, $5);
1043 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1044 if ($5->getType() != Type::UByteTy)
1045 ThrowException("Shift count for shift constant must be unsigned byte!");
1046 $$ = ConstantExpr::get($1, $3, $5);
1050 // ConstVector - A list of comma seperated constants.
1051 ConstVector : ConstVector ',' ConstVal {
1052 ($$ = $1)->push_back($3);
1055 $$ = new vector<Constant*>();
1060 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1061 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1064 //===----------------------------------------------------------------------===//
1065 // Rules to match Modules
1066 //===----------------------------------------------------------------------===//
1068 // Module rule: Capture the result of parsing the whole file into a result
1071 Module : FunctionList {
1072 $$ = ParserResult = $1;
1073 CurModule.ModuleDone();
1076 // FunctionList - A list of functions, preceeded by a constant pool.
1078 FunctionList : FunctionList Function {
1080 assert($2->getParent() == 0 && "Function already in module!");
1081 $1->getFunctionList().push_back($2);
1082 CurMeth.FunctionDone();
1084 | FunctionList FunctionProto {
1087 | FunctionList IMPLEMENTATION {
1091 $$ = CurModule.CurrentModule;
1092 // Resolve circular types before we parse the body of the module
1093 ResolveTypes(CurModule.LateResolveTypes);
1096 // ConstPool - Constants with optional names assigned to them.
1097 ConstPool : ConstPool OptAssign CONST ConstVal {
1098 if (setValueName($4, $2)) { assert(0 && "No redefinitions allowed!"); }
1101 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1102 // Eagerly resolve types. This is not an optimization, this is a
1103 // requirement that is due to the fact that we could have this:
1105 // %list = type { %list * }
1106 // %list = type { %list * } ; repeated type decl
1108 // If types are not resolved eagerly, then the two types will not be
1109 // determined to be the same type!
1111 ResolveTypeTo($2, $4->get());
1113 // TODO: FIXME when Type are not const
1114 if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1115 // If this is not a redefinition of a type...
1117 InsertType($4->get(),
1118 inFunctionScope() ? CurMeth.Types : CurModule.Types);
1124 | ConstPool FunctionProto { // Function prototypes can be in const pool
1126 | ConstPool OptAssign OptInternal GlobalType ConstVal {
1127 const Type *Ty = $5->getType();
1128 // Global declarations appear in Constant Pool
1129 Constant *Initializer = $5;
1130 if (Initializer == 0)
1131 ThrowException("Global value initializer is not a constant!");
1133 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1134 if (!setValueName(GV, $2)) { // If not redefining...
1135 CurModule.CurrentModule->getGlobalList().push_back(GV);
1136 int Slot = InsertValue(GV, CurModule.Values);
1139 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1141 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1142 (char*)GV->getName().c_str()));
1146 | ConstPool OptAssign OptInternal EXTERNAL GlobalType Types {
1147 const Type *Ty = *$6;
1148 // Global declarations appear in Constant Pool
1149 GlobalVariable *GV = new GlobalVariable(Ty, $5, $3);
1150 if (!setValueName(GV, $2)) { // If not redefining...
1151 CurModule.CurrentModule->getGlobalList().push_back(GV);
1152 int Slot = InsertValue(GV, CurModule.Values);
1155 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1157 assert(GV->hasName() && "Not named and not numbered!?");
1158 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1159 (char*)GV->getName().c_str()));
1164 | /* empty: end of list */ {
1168 //===----------------------------------------------------------------------===//
1169 // Rules to match Function Headers
1170 //===----------------------------------------------------------------------===//
1172 OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; };
1174 ArgVal : Types OptVAR_ID {
1175 if (*$1 == Type::VoidTy)
1176 ThrowException("void typed arguments are invalid!");
1177 $$ = new pair<PATypeHolder*, char*>($1, $2);
1180 ArgListH : ArgListH ',' ArgVal {
1186 $$ = new vector<pair<PATypeHolder*,char*> >();
1191 ArgList : ArgListH {
1194 | ArgListH ',' DOTDOTDOT {
1196 $$->push_back(pair<PATypeHolder*, char*>(new PATypeHolder(Type::VoidTy),0));
1199 $$ = new vector<pair<PATypeHolder*,char*> >();
1200 $$->push_back(pair<PATypeHolder*, char*>(new PATypeHolder(Type::VoidTy),0));
1206 FuncName : VAR_ID | STRINGCONSTANT;
1208 FunctionHeaderH : OptInternal TypesV FuncName '(' ArgList ')' {
1210 string FunctionName($3);
1212 vector<const Type*> ParamTypeList;
1213 if ($5) { // If there are arguments...
1214 for (vector<pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1215 I != $5->end(); ++I)
1216 ParamTypeList.push_back(I->first->get());
1219 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1220 if (isVarArg) ParamTypeList.pop_back();
1222 const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1223 const PointerType *PFT = PointerType::get(FT);
1227 // Is the function already in symtab?
1228 if ((Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1229 // Yes it is. If this is the case, either we need to be a forward decl,
1230 // or it needs to be.
1231 if (!CurMeth.isDeclare && !Fn->isExternal())
1232 ThrowException("Redefinition of function '" + FunctionName + "'!");
1234 // Make sure that we keep track of the internal marker, even if there was
1235 // a previous "declare".
1237 Fn->setInternalLinkage(true);
1239 // If we found a preexisting function prototype, remove it from the
1240 // module, so that we don't get spurious conflicts with global & local
1243 CurModule.CurrentModule->getFunctionList().remove(Fn);
1245 // Make sure to strip off any argument names so we can't get conflicts...
1246 for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend(); AI != AE; ++AI)
1249 } else { // Not already defined?
1250 Fn = new Function(FT, $1, FunctionName);
1251 InsertValue(Fn, CurModule.Values);
1252 CurModule.DeclareNewGlobalValue(Fn, ValID::create($3));
1254 free($3); // Free strdup'd memory!
1256 CurMeth.FunctionStart(Fn);
1258 // Add all of the arguments we parsed to the function...
1259 if ($5) { // Is null if empty...
1260 if (isVarArg) { // Nuke the last entry
1261 assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1262 "Not a varargs marker!");
1263 delete $5->back().first;
1264 $5->pop_back(); // Delete the last entry
1266 Function::aiterator ArgIt = Fn->abegin();
1267 for (vector<pair<PATypeHolder*, char*> >::iterator I = $5->begin();
1268 I != $5->end(); ++I, ++ArgIt) {
1269 delete I->first; // Delete the typeholder...
1271 if (setValueName(ArgIt, I->second)) // Insert arg into symtab...
1272 assert(0 && "No arg redef allowed!");
1277 delete $5; // We're now done with the argument list
1281 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1283 FunctionHeader : FunctionHeaderH BEGIN {
1284 $$ = CurMeth.CurrentFunction;
1286 // Resolve circular types before we parse the body of the function.
1287 ResolveTypes(CurMeth.LateResolveTypes);
1290 END : ENDTOK | '}'; // Allow end of '}' to end a function
1292 Function : BasicBlockList END {
1296 FunctionProto : DECLARE { CurMeth.isDeclare = true; } FunctionHeaderH {
1297 $$ = CurMeth.CurrentFunction;
1298 assert($$->getParent() == 0 && "Function already in module!");
1299 CurModule.CurrentModule->getFunctionList().push_back($$);
1300 CurMeth.FunctionDone();
1303 //===----------------------------------------------------------------------===//
1304 // Rules to match Basic Blocks
1305 //===----------------------------------------------------------------------===//
1307 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1308 $$ = ValID::create($1);
1311 $$ = ValID::create($1);
1313 | FPVAL { // Perhaps it's an FP constant?
1314 $$ = ValID::create($1);
1317 $$ = ValID::create(ConstantBool::True);
1320 $$ = ValID::create(ConstantBool::False);
1323 $$ = ValID::createNull();
1326 $$ = ValID::create($1);
1329 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1332 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1333 $$ = ValID::create($1);
1335 | VAR_ID { // Is it a named reference...?
1336 $$ = ValID::create($1);
1339 // ValueRef - A reference to a definition... either constant or symbolic
1340 ValueRef : SymbolicValueRef | ConstValueRef;
1343 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1344 // type immediately preceeds the value reference, and allows complex constant
1345 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1346 ResolvedVal : Types ValueRef {
1347 $$ = getVal(*$1, $2); delete $1;
1350 BasicBlockList : BasicBlockList BasicBlock {
1351 ($$ = $1)->getBasicBlockList().push_back($2);
1353 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1354 ($$ = $1)->getBasicBlockList().push_back($2);
1358 // Basic blocks are terminated by branching instructions:
1359 // br, br/cc, switch, ret
1361 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1362 if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1365 $1->getInstList().push_back($3);
1369 | LABELSTR InstructionList OptAssign BBTerminatorInst {
1370 if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1373 $2->getInstList().push_back($4);
1374 if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1380 InstructionList : InstructionList Inst {
1381 $1->getInstList().push_back($2);
1385 $$ = CurBB = new BasicBlock();
1388 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1389 $$ = new ReturnInst($2);
1391 | RET VOID { // Return with no result...
1392 $$ = new ReturnInst();
1394 | BR LABEL ValueRef { // Unconditional Branch...
1395 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1396 } // Conditional Branch...
1397 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1398 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1399 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1400 getVal(Type::BoolTy, $3));
1402 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1403 SwitchInst *S = new SwitchInst(getVal($2, $3),
1404 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1407 vector<pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1410 S->dest_push_back(I->first, I->second);
1412 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal
1413 EXCEPT ResolvedVal {
1414 const PointerType *PFTy;
1415 const FunctionType *Ty;
1417 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1418 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1419 // Pull out the types of all of the arguments...
1420 vector<const Type*> ParamTypes;
1422 for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1423 ParamTypes.push_back((*I)->getType());
1426 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1427 if (isVarArg) ParamTypes.pop_back();
1429 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1430 PFTy = PointerType::get(Ty);
1434 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1436 BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1437 BasicBlock *Except = dyn_cast<BasicBlock>($10);
1439 if (Normal == 0 || Except == 0)
1440 ThrowException("Invoke instruction without label destinations!");
1442 // Create the call node...
1443 if (!$5) { // Has no arguments?
1444 $$ = new InvokeInst(V, Normal, Except, vector<Value*>());
1445 } else { // Has arguments?
1446 // Loop through FunctionType's arguments and ensure they are specified
1449 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1450 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1451 vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1453 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1454 if ((*ArgI)->getType() != *I)
1455 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1456 (*I)->getDescription() + "'!");
1458 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1459 ThrowException("Invalid number of parameters detected!");
1461 $$ = new InvokeInst(V, Normal, Except, *$5);
1468 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1470 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1472 ThrowException("May only switch on a constant pool value!");
1474 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1476 | IntType ConstValueRef ',' LABEL ValueRef {
1477 $$ = new vector<pair<Constant*, BasicBlock*> >();
1478 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1481 ThrowException("May only switch on a constant pool value!");
1483 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1486 Inst : OptAssign InstVal {
1487 // Is this definition named?? if so, assign the name...
1488 if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1493 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1494 $$ = new list<pair<Value*, BasicBlock*> >();
1495 $$->push_back(make_pair(getVal(*$1, $3),
1496 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1499 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1501 $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
1502 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1506 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1507 $$ = new vector<Value*>();
1510 | ValueRefList ',' ResolvedVal {
1515 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1516 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1518 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1519 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint())
1520 ThrowException("Arithmetic operator requires integer or FP operands!");
1521 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1523 ThrowException("binary operator returned null!");
1526 | LogicalOps Types ValueRef ',' ValueRef {
1527 if (!(*$2)->isIntegral())
1528 ThrowException("Logical operator requires integral operands!");
1529 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1531 ThrowException("binary operator returned null!");
1534 | SetCondOps Types ValueRef ',' ValueRef {
1535 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1537 ThrowException("binary operator returned null!");
1541 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1542 << " Replacing with 'xor'.\n";
1544 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1546 ThrowException("Expected integral type for not instruction!");
1548 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1550 ThrowException("Could not create a xor instruction!");
1552 | ShiftOps ResolvedVal ',' ResolvedVal {
1553 if ($4->getType() != Type::UByteTy)
1554 ThrowException("Shift amount must be ubyte!");
1555 $$ = new ShiftInst($1, $2, $4);
1557 | CAST ResolvedVal TO Types {
1558 $$ = new CastInst($2, *$4);
1562 const Type *Ty = $2->front().first->getType();
1563 $$ = new PHINode(Ty);
1564 while ($2->begin() != $2->end()) {
1565 if ($2->front().first->getType() != Ty)
1566 ThrowException("All elements of a PHI node must be of the same type!");
1567 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1570 delete $2; // Free the list...
1572 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1573 const PointerType *PFTy;
1574 const FunctionType *Ty;
1576 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1577 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1578 // Pull out the types of all of the arguments...
1579 vector<const Type*> ParamTypes;
1581 for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1582 ParamTypes.push_back((*I)->getType());
1585 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1586 if (isVarArg) ParamTypes.pop_back();
1588 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1589 PFTy = PointerType::get(Ty);
1593 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1595 // Create the call node...
1596 if (!$5) { // Has no arguments?
1597 // Make sure no arguments is a good thing!
1598 if (Ty->getNumParams() != 0)
1599 ThrowException("No arguments passed to a function that "
1600 "expects arguments!");
1602 $$ = new CallInst(V, vector<Value*>());
1603 } else { // Has arguments?
1604 // Loop through FunctionType's arguments and ensure they are specified
1607 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1608 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1609 vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1611 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1612 if ((*ArgI)->getType() != *I)
1613 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1614 (*I)->getDescription() + "'!");
1616 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1617 ThrowException("Invalid number of parameters detected!");
1619 $$ = new CallInst(V, *$5);
1628 // IndexList - List of indices for GEP based instructions...
1629 IndexList : ',' ValueRefList {
1632 $$ = new vector<Value*>();
1635 MemoryInst : MALLOC Types {
1636 $$ = new MallocInst(*$2);
1639 | MALLOC Types ',' UINT ValueRef {
1640 $$ = new MallocInst(*$2, getVal($4, $5));
1644 $$ = new AllocaInst(*$2);
1647 | ALLOCA Types ',' UINT ValueRef {
1648 $$ = new AllocaInst(*$2, getVal($4, $5));
1651 | FREE ResolvedVal {
1652 if (!isa<PointerType>($2->getType()))
1653 ThrowException("Trying to free nonpointer type " +
1654 $2->getType()->getDescription() + "!");
1655 $$ = new FreeInst($2);
1658 | LOAD Types ValueRef IndexList {
1659 if (!isa<PointerType>($2->get()))
1660 ThrowException("Can't load from nonpointer type: " +
1661 (*$2)->getDescription());
1662 if (GetElementPtrInst::getIndexedType(*$2, *$4) == 0)
1663 ThrowException("Invalid indices for load instruction!");
1665 Value *Src = getVal(*$2, $3);
1667 std::cerr << "WARNING: Use of index load instruction:"
1668 << " replacing with getelementptr/load pair.\n";
1669 // Create a getelementptr hack instruction to do the right thing for
1672 Instruction *I = new GetElementPtrInst(Src, *$4);
1673 CurBB->getInstList().push_back(I);
1677 $$ = new LoadInst(Src);
1678 delete $4; // Free the vector...
1681 | STORE ResolvedVal ',' Types ValueRef IndexList {
1682 if (!isa<PointerType>($4->get()))
1683 ThrowException("Can't store to a nonpointer type: " +
1684 (*$4)->getDescription());
1685 const Type *ElTy = GetElementPtrInst::getIndexedType(*$4, *$6);
1687 ThrowException("Can't store into that field list!");
1688 if (ElTy != $2->getType())
1689 ThrowException("Can't store '" + $2->getType()->getDescription() +
1690 "' into space of type '" + ElTy->getDescription() + "'!");
1692 Value *Ptr = getVal(*$4, $5);
1694 std::cerr << "WARNING: Use of index store instruction:"
1695 << " replacing with getelementptr/store pair.\n";
1696 // Create a getelementptr hack instruction to do the right thing for
1699 Instruction *I = new GetElementPtrInst(Ptr, *$6);
1700 CurBB->getInstList().push_back(I);
1704 $$ = new StoreInst($2, Ptr);
1705 delete $4; delete $6;
1707 | GETELEMENTPTR Types ValueRef IndexList {
1708 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
1709 if ((*$4)[i]->getType() == Type::UIntTy) {
1710 std::cerr << "WARNING: Use of uint type indexes to getelementptr "
1711 << "instruction: replacing with casts to long type.\n";
1712 Instruction *I = new CastInst((*$4)[i], Type::LongTy);
1713 CurBB->getInstList().push_back(I);
1718 if (!isa<PointerType>($2->get()))
1719 ThrowException("getelementptr insn requires pointer operand!");
1720 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1721 ThrowException("Can't get element ptr '" + (*$2)->getDescription()+ "'!");
1722 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1723 delete $2; delete $4;
1727 int yyerror(const char *ErrorMsg) {
1728 string where = string((CurFilename == "-")? string("<stdin>") : CurFilename)
1729 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
1730 string errMsg = string(ErrorMsg) + string("\n") + where + " while reading ";
1731 if (yychar == YYEMPTY)
1732 errMsg += "end-of-file.";
1734 errMsg += "token: '" + string(llvmAsmtext, llvmAsmleng) + "'";
1735 ThrowException(errMsg);