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;
215 if (inFunctionScope()) {
216 SymTab = &CurMeth.CurrentFunction->getSymbolTable();
217 N = SymTab->lookup(Type::TypeTy, Name);
221 // Symbol table doesn't automatically chain yet... because the function
222 // hasn't been added to the module...
224 SymTab = &CurModule.CurrentModule->getSymbolTable();
225 N = SymTab->lookup(Type::TypeTy, Name);
229 D.destroy(); // Free old strdup'd memory...
230 return cast<const Type>(N);
233 ThrowException("Internal parser error: Invalid symbol type reference!");
236 // If we reached here, we referenced either a symbol that we don't know about
237 // or an id number that hasn't been read yet. We may be referencing something
238 // forward, so just create an entry to be resolved later and get to it...
240 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
242 map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
243 CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
245 map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
246 if (I != LateResolver.end()) {
250 Type *Typ = OpaqueType::get();
251 LateResolver.insert(make_pair(D, Typ));
255 static Value *lookupInSymbolTable(const Type *Ty, const string &Name) {
256 SymbolTable &SymTab =
257 inFunctionScope() ? CurMeth.CurrentFunction->getSymbolTable() :
258 CurModule.CurrentModule->getSymbolTable();
259 return SymTab.lookup(Ty, Name);
262 // getValNonImprovising - Look up the value specified by the provided type and
263 // the provided ValID. If the value exists and has already been defined, return
264 // it. Otherwise return null.
266 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
267 if (isa<FunctionType>(Ty))
268 ThrowException("Functions are not values and "
269 "must be referenced as pointers");
272 case ValID::NumberVal: { // Is it a numbered definition?
273 unsigned type = Ty->getUniqueID();
274 unsigned Num = (unsigned)D.Num;
276 // Module constants occupy the lowest numbered slots...
277 if (type < CurModule.Values.size()) {
278 if (Num < CurModule.Values[type].size())
279 return CurModule.Values[type][Num];
281 Num -= CurModule.Values[type].size();
284 // Make sure that our type is within bounds
285 if (CurMeth.Values.size() <= type) return 0;
287 // Check that the number is within bounds...
288 if (CurMeth.Values[type].size() <= Num) return 0;
290 return CurMeth.Values[type][Num];
293 case ValID::NameVal: { // Is it a named definition?
294 Value *N = lookupInSymbolTable(Ty, string(D.Name));
295 if (N == 0) return 0;
297 D.destroy(); // Free old strdup'd memory...
301 // Check to make sure that "Ty" is an integral type, and that our
302 // value will fit into the specified type...
303 case ValID::ConstSIntVal: // Is it a constant pool reference??
304 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
305 ThrowException("Signed integral constant '" +
306 itostr(D.ConstPool64) + "' is invalid for type '" +
307 Ty->getDescription() + "'!");
308 return ConstantSInt::get(Ty, D.ConstPool64);
310 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
311 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
312 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
313 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
314 "' is invalid or out of range!");
315 } else { // This is really a signed reference. Transmogrify.
316 return ConstantSInt::get(Ty, D.ConstPool64);
319 return ConstantUInt::get(Ty, D.UConstPool64);
322 case ValID::ConstFPVal: // Is it a floating point const pool reference?
323 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
324 ThrowException("FP constant invalid for type!!");
325 return ConstantFP::get(Ty, D.ConstPoolFP);
327 case ValID::ConstNullVal: // Is it a null value?
328 if (!isa<PointerType>(Ty))
329 ThrowException("Cannot create a a non pointer null!");
330 return ConstantPointerNull::get(cast<PointerType>(Ty));
332 case ValID::ConstantVal: // Fully resolved constant?
333 if (D.ConstantValue->getType() != Ty)
334 ThrowException("Constant expression type different from required type!");
335 return D.ConstantValue;
338 assert(0 && "Unhandled case!");
342 assert(0 && "Unhandled case!");
347 // getVal - This function is identical to getValNonImprovising, except that if a
348 // value is not already defined, it "improvises" by creating a placeholder var
349 // that looks and acts just like the requested variable. When the value is
350 // defined later, all uses of the placeholder variable are replaced with the
353 static Value *getVal(const Type *Ty, const ValID &D) {
354 assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
356 // See if the value has already been defined...
357 Value *V = getValNonImprovising(Ty, D);
360 // If we reached here, we referenced either a symbol that we don't know about
361 // or an id number that hasn't been read yet. We may be referencing something
362 // forward, so just create an entry to be resolved later and get to it...
365 switch (Ty->getPrimitiveID()) {
366 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
367 default: d = new ValuePlaceHolder(Ty, D); break;
370 assert(d != 0 && "How did we not make something?");
371 if (inFunctionScope())
372 InsertValue(d, CurMeth.LateResolveValues);
374 InsertValue(d, CurModule.LateResolveValues);
379 //===----------------------------------------------------------------------===//
380 // Code to handle forward references in instructions
381 //===----------------------------------------------------------------------===//
383 // This code handles the late binding needed with statements that reference
384 // values not defined yet... for example, a forward branch, or the PHI node for
387 // This keeps a table (CurMeth.LateResolveValues) of all such forward references
388 // and back patchs after we are done.
391 // ResolveDefinitions - If we could not resolve some defs at parsing
392 // time (forward branches, phi functions for loops, etc...) resolve the
395 static void ResolveDefinitions(vector<ValueList> &LateResolvers,
396 vector<ValueList> *FutureLateResolvers) {
397 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
398 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
399 while (!LateResolvers[ty].empty()) {
400 Value *V = LateResolvers[ty].back();
401 assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
403 LateResolvers[ty].pop_back();
404 ValID &DID = getValIDFromPlaceHolder(V);
406 Value *TheRealValue = getValNonImprovising(Type::getUniqueIDType(ty),DID);
408 V->replaceAllUsesWith(TheRealValue);
410 } else if (FutureLateResolvers) {
411 // Functions have their unresolved items forwarded to the module late
413 InsertValue(V, *FutureLateResolvers);
415 if (DID.Type == ValID::NameVal)
416 ThrowException("Reference to an invalid definition: '" +DID.getName()+
417 "' of type '" + V->getType()->getDescription() + "'",
418 getLineNumFromPlaceHolder(V));
420 ThrowException("Reference to an invalid definition: #" +
421 itostr(DID.Num) + " of type '" +
422 V->getType()->getDescription() + "'",
423 getLineNumFromPlaceHolder(V));
428 LateResolvers.clear();
431 // ResolveTypeTo - A brand new type was just declared. This means that (if
432 // name is not null) things referencing Name can be resolved. Otherwise, things
433 // refering to the number can be resolved. Do this now.
435 static void ResolveTypeTo(char *Name, const Type *ToTy) {
436 vector<PATypeHolder> &Types = inFunctionScope() ?
437 CurMeth.Types : CurModule.Types;
440 if (Name) D = ValID::create(Name);
441 else D = ValID::create((int)Types.size());
443 map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
444 CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
446 map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
447 if (I != LateResolver.end()) {
448 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
449 LateResolver.erase(I);
453 // ResolveTypes - At this point, all types should be resolved. Any that aren't
456 static void ResolveTypes(map<ValID, PATypeHolder> &LateResolveTypes) {
457 if (!LateResolveTypes.empty()) {
458 const ValID &DID = LateResolveTypes.begin()->first;
460 if (DID.Type == ValID::NameVal)
461 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
463 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
468 // setValueName - Set the specified value to the name given. The name may be
469 // null potentially, in which case this is a noop. The string passed in is
470 // assumed to be a malloc'd string buffer, and is freed by this function.
472 // This function returns true if the value has already been defined, but is
473 // allowed to be redefined in the specified context. If the name is a new name
474 // for the typeplane, false is returned.
476 static bool setValueName(Value *V, char *NameStr) {
477 if (NameStr == 0) return false;
479 string Name(NameStr); // Copy string
480 free(NameStr); // Free old string
482 if (V->getType() == Type::VoidTy)
483 ThrowException("Can't assign name '" + Name +
484 "' to a null valued instruction!");
486 SymbolTable &ST = inFunctionScope() ?
487 CurMeth.CurrentFunction->getSymbolTable() :
488 CurModule.CurrentModule->getSymbolTable();
490 Value *Existing = ST.lookup(V->getType(), Name);
491 if (Existing) { // Inserting a name that is already defined???
492 // There is only one case where this is allowed: when we are refining an
493 // opaque type. In this case, Existing will be an opaque type.
494 if (const Type *Ty = dyn_cast<const Type>(Existing)) {
495 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Ty)) {
496 // We ARE replacing an opaque type!
497 ((OpaqueType*)OpTy)->refineAbstractTypeTo(cast<Type>(V));
502 // Otherwise, we are a simple redefinition of a value, check to see if it
503 // is defined the same as the old one...
504 if (const Type *Ty = dyn_cast<Type>(Existing)) {
505 if (Ty == cast<Type>(V)) return true; // Yes, it's equal.
506 // std::cerr << "Type: " << Ty->getDescription() << " != "
507 // << cast<const Type>(V)->getDescription() << "!\n";
508 } else if (const Constant *C = dyn_cast<Constant>(Existing)) {
509 if (C == V) return true; // Constants are equal to themselves
510 } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
511 // We are allowed to redefine a global variable in two circumstances:
512 // 1. If at least one of the globals is uninitialized or
513 // 2. If both initializers have the same value.
515 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
516 if (!EGV->hasInitializer() || !GV->hasInitializer() ||
517 EGV->getInitializer() == GV->getInitializer()) {
519 // Make sure the existing global version gets the initializer! Make
520 // sure that it also gets marked const if the new version is.
521 if (GV->hasInitializer() && !EGV->hasInitializer())
522 EGV->setInitializer(GV->getInitializer());
523 if (GV->isConstant())
524 EGV->setConstant(true);
526 delete GV; // Destroy the duplicate!
527 return true; // They are equivalent!
531 ThrowException("Redefinition of value named '" + Name + "' in the '" +
532 V->getType()->getDescription() + "' type plane!");
535 V->setName(Name, &ST);
540 //===----------------------------------------------------------------------===//
541 // Code for handling upreferences in type names...
544 // TypeContains - Returns true if Ty contains E in it.
546 static bool TypeContains(const Type *Ty, const Type *E) {
547 return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
551 static vector<pair<unsigned, OpaqueType *> > UpRefs;
553 static PATypeHolder HandleUpRefs(const Type *ty) {
555 UR_OUT("Type '" << ty->getDescription() <<
556 "' newly formed. Resolving upreferences.\n" <<
557 UpRefs.size() << " upreferences active!\n");
558 for (unsigned i = 0; i < UpRefs.size(); ) {
559 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
560 << UpRefs[i].second->getDescription() << ") = "
561 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << endl);
562 if (TypeContains(Ty, UpRefs[i].second)) {
563 unsigned Level = --UpRefs[i].first; // Decrement level of upreference
564 UR_OUT(" Uplevel Ref Level = " << Level << endl);
565 if (Level == 0) { // Upreference should be resolved!
566 UR_OUT(" * Resolving upreference for "
567 << UpRefs[i].second->getDescription() << endl;
568 string OldName = UpRefs[i].second->getDescription());
569 UpRefs[i].second->refineAbstractTypeTo(Ty);
570 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
571 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
572 << (const void*)Ty << ", " << Ty->getDescription() << endl);
577 ++i; // Otherwise, no resolve, move on...
579 // FIXME: TODO: this should return the updated type
584 //===----------------------------------------------------------------------===//
585 // RunVMAsmParser - Define an interface to this parser
586 //===----------------------------------------------------------------------===//
588 Module *RunVMAsmParser(const string &Filename, FILE *F) {
590 CurFilename = Filename;
591 llvmAsmlineno = 1; // Reset the current line number...
593 CurModule.CurrentModule = new Module(); // Allocate a new module to read
594 yyparse(); // Parse the file.
595 Module *Result = ParserResult;
596 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
606 Function *FunctionVal;
607 std::pair<PATypeHolder*, char*> *ArgVal;
608 BasicBlock *BasicBlockVal;
609 TerminatorInst *TermInstVal;
610 Instruction *InstVal;
613 const Type *PrimType;
614 PATypeHolder *TypeVal;
617 std::vector<std::pair<PATypeHolder*,char*> > *ArgList;
618 std::vector<Value*> *ValueList;
619 std::list<PATypeHolder> *TypeList;
620 std::list<std::pair<Value*,
621 BasicBlock*> > *PHIList; // Represent the RHS of PHI node
622 std::vector<std::pair<Constant*, BasicBlock*> > *JumpTable;
623 std::vector<Constant*> *ConstVector;
632 char *StrVal; // This memory is strdup'd!
633 ValID ValIDVal; // strdup'd memory maybe!
635 Instruction::BinaryOps BinaryOpVal;
636 Instruction::TermOps TermOpVal;
637 Instruction::MemoryOps MemOpVal;
638 Instruction::OtherOps OtherOpVal;
641 %type <ModuleVal> Module FunctionList
642 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
643 %type <BasicBlockVal> BasicBlock InstructionList
644 %type <TermInstVal> BBTerminatorInst
645 %type <InstVal> Inst InstVal MemoryInst
646 %type <ConstVal> ConstVal ConstExpr
647 %type <ConstVector> ConstVector
648 %type <ArgList> ArgList ArgListH
649 %type <ArgVal> ArgVal
650 %type <PHIList> PHIList
651 %type <ValueList> ValueRefList ValueRefListE // For call param lists
652 %type <ValueList> IndexList // For GEP derived indices
653 %type <TypeList> TypeListI ArgTypeListI
654 %type <JumpTable> JumpTable
655 %type <BoolVal> GlobalType OptInternal // GLOBAL or CONSTANT? Intern?
657 // ValueRef - Unresolved reference to a definition or BB
658 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
659 %type <ValueVal> ResolvedVal // <type> <valref> pair
660 // Tokens and types for handling constant integer values
662 // ESINT64VAL - A negative number within long long range
663 %token <SInt64Val> ESINT64VAL
665 // EUINT64VAL - A positive number within uns. long long range
666 %token <UInt64Val> EUINT64VAL
667 %type <SInt64Val> EINT64VAL
669 %token <SIntVal> SINTVAL // Signed 32 bit ints...
670 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
671 %type <SIntVal> INTVAL
672 %token <FPVal> FPVAL // Float or Double constant
675 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
676 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
677 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
678 %token <PrimType> FLOAT DOUBLE TYPE LABEL
680 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
681 %type <StrVal> OptVAR_ID OptAssign FuncName
684 %token IMPLEMENTATION TRUE FALSE BEGINTOK ENDTOK DECLARE GLOBAL CONSTANT
685 %token TO EXCEPT DOTDOTDOT NULL_TOK CONST INTERNAL OPAQUE NOT EXTERNAL
687 // Basic Block Terminating Operators
688 %token <TermOpVal> RET BR SWITCH
691 %type <BinaryOpVal> BinaryOps // all the binary operators
692 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
693 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
694 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
696 // Memory Instructions
697 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
700 %type <OtherOpVal> ShiftOps
701 %token <OtherOpVal> PHI CALL INVOKE CAST SHL SHR
706 // Handle constant integer size restriction and conversion...
711 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
712 ThrowException("Value too large for type!");
717 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
718 EINT64VAL : EUINT64VAL {
719 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
720 ThrowException("Value too large for type!");
724 // Operations that are notably excluded from this list include:
725 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
727 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
728 LogicalOps : AND | OR | XOR;
729 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
730 BinaryOps : ArithmeticOps | LogicalOps | SetCondOps;
732 ShiftOps : SHL | SHR;
734 // These are some types that allow classification if we only want a particular
735 // thing... for example, only a signed, unsigned, or integral type.
736 SIntType : LONG | INT | SHORT | SBYTE;
737 UIntType : ULONG | UINT | USHORT | UBYTE;
738 IntType : SIntType | UIntType;
739 FPType : FLOAT | DOUBLE;
741 // OptAssign - Value producing statements have an optional assignment component
742 OptAssign : VAR_ID '=' {
749 OptInternal : INTERNAL { $$ = true; } | /*empty*/ { $$ = false; };
751 //===----------------------------------------------------------------------===//
752 // Types includes all predefined types... except void, because it can only be
753 // used in specific contexts (function returning void for example). To have
754 // access to it, a user must explicitly use TypesV.
757 // TypesV includes all of 'Types', but it also includes the void type.
758 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
759 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
763 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
768 // Derived types are added later...
770 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
771 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
773 $$ = new PATypeHolder(OpaqueType::get());
776 $$ = new PATypeHolder($1);
778 UpRTypes : SymbolicValueRef { // Named types are also simple types...
779 $$ = new PATypeHolder(getTypeVal($1));
782 // Include derived types in the Types production.
784 UpRTypes : '\\' EUINT64VAL { // Type UpReference
785 if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
786 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
787 UpRefs.push_back(make_pair((unsigned)$2, OT)); // Add to vector...
788 $$ = new PATypeHolder(OT);
789 UR_OUT("New Upreference!\n");
791 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
792 vector<const Type*> Params;
793 mapto($3->begin(), $3->end(), std::back_inserter(Params),
794 std::mem_fun_ref(&PATypeHandle<Type>::get));
795 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
796 if (isVarArg) Params.pop_back();
798 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
799 delete $3; // Delete the argument list
800 delete $1; // Delete the old type handle
802 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
803 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
806 | '{' TypeListI '}' { // Structure type?
807 vector<const Type*> Elements;
808 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
809 std::mem_fun_ref(&PATypeHandle<Type>::get));
811 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
814 | '{' '}' { // Empty structure type?
815 $$ = new PATypeHolder(StructType::get(vector<const Type*>()));
817 | UpRTypes '*' { // Pointer type?
818 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
822 // TypeList - Used for struct declarations and as a basis for function type
823 // declaration type lists
825 TypeListI : UpRTypes {
826 $$ = new list<PATypeHolder>();
827 $$->push_back(*$1); delete $1;
829 | TypeListI ',' UpRTypes {
830 ($$=$1)->push_back(*$3); delete $3;
833 // ArgTypeList - List of types for a function type declaration...
834 ArgTypeListI : TypeListI
835 | TypeListI ',' DOTDOTDOT {
836 ($$=$1)->push_back(Type::VoidTy);
839 ($$ = new list<PATypeHolder>())->push_back(Type::VoidTy);
842 $$ = new list<PATypeHolder>();
845 // ConstVal - The various declarations that go into the constant pool. This
846 // production is used ONLY to represent constants that show up AFTER a 'const',
847 // 'constant' or 'global' token at global scope. Constants that can be inlined
848 // into other expressions (such as integers and constexprs) are handled by the
849 // ResolvedVal, ValueRef and ConstValueRef productions.
851 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
852 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
854 ThrowException("Cannot make array constant with type: '" +
855 (*$1)->getDescription() + "'!");
856 const Type *ETy = ATy->getElementType();
857 int NumElements = ATy->getNumElements();
859 // Verify that we have the correct size...
860 if (NumElements != -1 && NumElements != (int)$3->size())
861 ThrowException("Type mismatch: constant sized array initialized with " +
862 utostr($3->size()) + " arguments, but has size of " +
863 itostr(NumElements) + "!");
865 // Verify all elements are correct type!
866 for (unsigned i = 0; i < $3->size(); i++) {
867 if (ETy != (*$3)[i]->getType())
868 ThrowException("Element #" + utostr(i) + " is not of type '" +
869 ETy->getDescription() +"' as required!\nIt is of type '"+
870 (*$3)[i]->getType()->getDescription() + "'.");
873 $$ = ConstantArray::get(ATy, *$3);
874 delete $1; delete $3;
877 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
879 ThrowException("Cannot make array constant with type: '" +
880 (*$1)->getDescription() + "'!");
882 int NumElements = ATy->getNumElements();
883 if (NumElements != -1 && NumElements != 0)
884 ThrowException("Type mismatch: constant sized array initialized with 0"
885 " arguments, but has size of " + itostr(NumElements) +"!");
886 $$ = ConstantArray::get(ATy, vector<Constant*>());
889 | Types 'c' STRINGCONSTANT {
890 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
892 ThrowException("Cannot make array constant with type: '" +
893 (*$1)->getDescription() + "'!");
895 int NumElements = ATy->getNumElements();
896 const Type *ETy = ATy->getElementType();
897 char *EndStr = UnEscapeLexed($3, true);
898 if (NumElements != -1 && NumElements != (EndStr-$3))
899 ThrowException("Can't build string constant of size " +
900 itostr((int)(EndStr-$3)) +
901 " when array has size " + itostr(NumElements) + "!");
902 vector<Constant*> Vals;
903 if (ETy == Type::SByteTy) {
904 for (char *C = $3; C != EndStr; ++C)
905 Vals.push_back(ConstantSInt::get(ETy, *C));
906 } else if (ETy == Type::UByteTy) {
907 for (char *C = $3; C != EndStr; ++C)
908 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
911 ThrowException("Cannot build string arrays of non byte sized elements!");
914 $$ = ConstantArray::get(ATy, Vals);
917 | Types '{' ConstVector '}' {
918 const StructType *STy = dyn_cast<const StructType>($1->get());
920 ThrowException("Cannot make struct constant with type: '" +
921 (*$1)->getDescription() + "'!");
923 // Check to ensure that constants are compatible with the type initializer!
924 for (unsigned i = 0, e = $3->size(); i != e; ++i)
925 if ((*$3)[i]->getType() != STy->getElementTypes()[i])
926 ThrowException("Expected type '" +
927 STy->getElementTypes()[i]->getDescription() +
928 "' for element #" + utostr(i) +
929 " of structure initializer!");
931 $$ = ConstantStruct::get(STy, *$3);
932 delete $1; delete $3;
935 const PointerType *PTy = dyn_cast<const PointerType>($1->get());
937 ThrowException("Cannot make null pointer constant with type: '" +
938 (*$1)->getDescription() + "'!");
940 $$ = ConstantPointerNull::get(PTy);
943 | Types SymbolicValueRef {
944 const PointerType *Ty = dyn_cast<const PointerType>($1->get());
946 ThrowException("Global const reference must be a pointer type!");
948 // ConstExprs can exist in the body of a function, thus creating
949 // ConstantPointerRefs whenever they refer to a variable. Because we are in
950 // the context of a function, getValNonImprovising will search the functions
951 // symbol table instead of the module symbol table for the global symbol,
952 // which throws things all off. To get around this, we just tell
953 // getValNonImprovising that we are at global scope here.
955 Function *SavedCurFn = CurMeth.CurrentFunction;
956 CurMeth.CurrentFunction = 0;
958 Value *V = getValNonImprovising(Ty, $2);
960 CurMeth.CurrentFunction = SavedCurFn;
963 // If this is an initializer for a constant pointer, which is referencing a
964 // (currently) undefined variable, create a stub now that shall be replaced
965 // in the future with the right type of variable.
968 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
969 const PointerType *PT = cast<PointerType>(Ty);
971 // First check to see if the forward references value is already created!
972 PerModuleInfo::GlobalRefsType::iterator I =
973 CurModule.GlobalRefs.find(make_pair(PT, $2));
975 if (I != CurModule.GlobalRefs.end()) {
976 V = I->second; // Placeholder already exists, use it...
978 // TODO: Include line number info by creating a subclass of
979 // TODO: GlobalVariable here that includes the said information!
981 // Create a placeholder for the global variable reference...
982 GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
984 // Keep track of the fact that we have a forward ref to recycle it
985 CurModule.GlobalRefs.insert(make_pair(make_pair(PT, $2), GV));
987 // Must temporarily push this value into the module table...
988 CurModule.CurrentModule->getGlobalList().push_back(GV);
993 GlobalValue *GV = cast<GlobalValue>(V);
994 $$ = ConstantPointerRef::get(GV);
995 delete $1; // Free the type handle
998 if ($1->get() != $2->getType())
999 ThrowException("Mismatched types for constant expression!");
1004 ConstVal : SIntType EINT64VAL { // integral constants
1005 if (!ConstantSInt::isValueValidForType($1, $2))
1006 ThrowException("Constant value doesn't fit in type!");
1007 $$ = ConstantSInt::get($1, $2);
1009 | UIntType EUINT64VAL { // integral constants
1010 if (!ConstantUInt::isValueValidForType($1, $2))
1011 ThrowException("Constant value doesn't fit in type!");
1012 $$ = ConstantUInt::get($1, $2);
1014 | BOOL TRUE { // Boolean constants
1015 $$ = ConstantBool::True;
1017 | BOOL FALSE { // Boolean constants
1018 $$ = ConstantBool::False;
1020 | FPType FPVAL { // Float & Double constants
1021 $$ = ConstantFP::get($1, $2);
1025 ConstExpr: CAST '(' ConstVal TO Types ')' {
1026 $$ = ConstantExpr::getCast($3, $5->get());
1029 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1030 if (!isa<PointerType>($3->getType()))
1031 ThrowException("GetElementPtr requires a pointer operand!");
1034 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1036 ThrowException("Index list invalid for constant getelementptr!");
1038 vector<Constant*> IdxVec;
1039 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1040 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1041 IdxVec.push_back(C);
1043 ThrowException("Indices to constant getelementptr must be constants!");
1047 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1049 | BinaryOps '(' ConstVal ',' ConstVal ')' {
1050 if ($3->getType() != $5->getType())
1051 ThrowException("Binary operator types must match!");
1052 $$ = ConstantExpr::get($1, $3, $5);
1054 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1055 if ($5->getType() != Type::UByteTy)
1056 ThrowException("Shift count for shift constant must be unsigned byte!");
1057 $$ = ConstantExpr::get($1, $3, $5);
1061 // ConstVector - A list of comma seperated constants.
1062 ConstVector : ConstVector ',' ConstVal {
1063 ($$ = $1)->push_back($3);
1066 $$ = new vector<Constant*>();
1071 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1072 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1075 //===----------------------------------------------------------------------===//
1076 // Rules to match Modules
1077 //===----------------------------------------------------------------------===//
1079 // Module rule: Capture the result of parsing the whole file into a result
1082 Module : FunctionList {
1083 $$ = ParserResult = $1;
1084 CurModule.ModuleDone();
1087 // FunctionList - A list of functions, preceeded by a constant pool.
1089 FunctionList : FunctionList Function {
1091 assert($2->getParent() == 0 && "Function already in module!");
1092 $1->getFunctionList().push_back($2);
1093 CurMeth.FunctionDone();
1095 | FunctionList FunctionProto {
1098 | FunctionList IMPLEMENTATION {
1102 $$ = CurModule.CurrentModule;
1103 // Resolve circular types before we parse the body of the module
1104 ResolveTypes(CurModule.LateResolveTypes);
1107 // ConstPool - Constants with optional names assigned to them.
1108 ConstPool : ConstPool OptAssign CONST ConstVal {
1109 if (!setValueName($4, $2))
1112 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1113 // Eagerly resolve types. This is not an optimization, this is a
1114 // requirement that is due to the fact that we could have this:
1116 // %list = type { %list * }
1117 // %list = type { %list * } ; repeated type decl
1119 // If types are not resolved eagerly, then the two types will not be
1120 // determined to be the same type!
1122 ResolveTypeTo($2, $4->get());
1124 // TODO: FIXME when Type are not const
1125 if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1126 // If this is not a redefinition of a type...
1128 InsertType($4->get(),
1129 inFunctionScope() ? CurMeth.Types : CurModule.Types);
1135 | ConstPool FunctionProto { // Function prototypes can be in const pool
1137 | ConstPool OptAssign OptInternal GlobalType ConstVal {
1138 const Type *Ty = $5->getType();
1139 // Global declarations appear in Constant Pool
1140 Constant *Initializer = $5;
1141 if (Initializer == 0)
1142 ThrowException("Global value initializer is not a constant!");
1144 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1145 if (!setValueName(GV, $2)) { // If not redefining...
1146 CurModule.CurrentModule->getGlobalList().push_back(GV);
1147 int Slot = InsertValue(GV, CurModule.Values);
1150 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1152 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1153 (char*)GV->getName().c_str()));
1157 | ConstPool OptAssign OptInternal EXTERNAL GlobalType Types {
1158 const Type *Ty = *$6;
1159 // Global declarations appear in Constant Pool
1160 GlobalVariable *GV = new GlobalVariable(Ty, $5, $3);
1161 if (!setValueName(GV, $2)) { // If not redefining...
1162 CurModule.CurrentModule->getGlobalList().push_back(GV);
1163 int Slot = InsertValue(GV, CurModule.Values);
1166 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1168 assert(GV->hasName() && "Not named and not numbered!?");
1169 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1170 (char*)GV->getName().c_str()));
1175 | /* empty: end of list */ {
1179 //===----------------------------------------------------------------------===//
1180 // Rules to match Function Headers
1181 //===----------------------------------------------------------------------===//
1183 OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; };
1185 ArgVal : Types OptVAR_ID {
1186 if (*$1 == Type::VoidTy)
1187 ThrowException("void typed arguments are invalid!");
1188 $$ = new pair<PATypeHolder*, char*>($1, $2);
1191 ArgListH : ArgListH ',' ArgVal {
1197 $$ = new vector<pair<PATypeHolder*,char*> >();
1202 ArgList : ArgListH {
1205 | ArgListH ',' DOTDOTDOT {
1207 $$->push_back(pair<PATypeHolder*, char*>(new PATypeHolder(Type::VoidTy),0));
1210 $$ = new vector<pair<PATypeHolder*,char*> >();
1211 $$->push_back(pair<PATypeHolder*, char*>(new PATypeHolder(Type::VoidTy),0));
1217 FuncName : VAR_ID | STRINGCONSTANT;
1219 FunctionHeaderH : OptInternal TypesV FuncName '(' ArgList ')' {
1221 string FunctionName($3);
1223 vector<const Type*> ParamTypeList;
1224 if ($5) { // If there are arguments...
1225 for (vector<pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1226 I != $5->end(); ++I)
1227 ParamTypeList.push_back(I->first->get());
1230 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1231 if (isVarArg) ParamTypeList.pop_back();
1233 const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1234 const PointerType *PFT = PointerType::get(FT);
1238 // Is the function already in symtab?
1239 if ((Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1240 // Yes it is. If this is the case, either we need to be a forward decl,
1241 // or it needs to be.
1242 if (!CurMeth.isDeclare && !Fn->isExternal())
1243 ThrowException("Redefinition of function '" + FunctionName + "'!");
1245 // Make sure that we keep track of the internal marker, even if there was
1246 // a previous "declare".
1248 Fn->setInternalLinkage(true);
1250 // If we found a preexisting function prototype, remove it from the
1251 // module, so that we don't get spurious conflicts with global & local
1254 CurModule.CurrentModule->getFunctionList().remove(Fn);
1256 // Make sure to strip off any argument names so we can't get conflicts...
1257 for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend(); AI != AE; ++AI)
1260 } else { // Not already defined?
1261 Fn = new Function(FT, $1, FunctionName);
1262 InsertValue(Fn, CurModule.Values);
1263 CurModule.DeclareNewGlobalValue(Fn, ValID::create($3));
1265 free($3); // Free strdup'd memory!
1267 CurMeth.FunctionStart(Fn);
1269 // Add all of the arguments we parsed to the function...
1270 if ($5) { // Is null if empty...
1271 if (isVarArg) { // Nuke the last entry
1272 assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1273 "Not a varargs marker!");
1274 delete $5->back().first;
1275 $5->pop_back(); // Delete the last entry
1277 Function::aiterator ArgIt = Fn->abegin();
1278 for (vector<pair<PATypeHolder*, char*> >::iterator I = $5->begin();
1279 I != $5->end(); ++I, ++ArgIt) {
1280 delete I->first; // Delete the typeholder...
1282 if (setValueName(ArgIt, I->second)) // Insert arg into symtab...
1283 assert(0 && "No arg redef allowed!");
1288 delete $5; // We're now done with the argument list
1292 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1294 FunctionHeader : FunctionHeaderH BEGIN {
1295 $$ = CurMeth.CurrentFunction;
1297 // Resolve circular types before we parse the body of the function.
1298 ResolveTypes(CurMeth.LateResolveTypes);
1301 END : ENDTOK | '}'; // Allow end of '}' to end a function
1303 Function : BasicBlockList END {
1307 FunctionProto : DECLARE { CurMeth.isDeclare = true; } FunctionHeaderH {
1308 $$ = CurMeth.CurrentFunction;
1309 assert($$->getParent() == 0 && "Function already in module!");
1310 CurModule.CurrentModule->getFunctionList().push_back($$);
1311 CurMeth.FunctionDone();
1314 //===----------------------------------------------------------------------===//
1315 // Rules to match Basic Blocks
1316 //===----------------------------------------------------------------------===//
1318 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1319 $$ = ValID::create($1);
1322 $$ = ValID::create($1);
1324 | FPVAL { // Perhaps it's an FP constant?
1325 $$ = ValID::create($1);
1328 $$ = ValID::create(ConstantBool::True);
1331 $$ = ValID::create(ConstantBool::False);
1334 $$ = ValID::createNull();
1337 $$ = ValID::create($1);
1340 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1343 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1344 $$ = ValID::create($1);
1346 | VAR_ID { // Is it a named reference...?
1347 $$ = ValID::create($1);
1350 // ValueRef - A reference to a definition... either constant or symbolic
1351 ValueRef : SymbolicValueRef | ConstValueRef;
1354 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1355 // type immediately preceeds the value reference, and allows complex constant
1356 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1357 ResolvedVal : Types ValueRef {
1358 $$ = getVal(*$1, $2); delete $1;
1361 BasicBlockList : BasicBlockList BasicBlock {
1362 ($$ = $1)->getBasicBlockList().push_back($2);
1364 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1365 ($$ = $1)->getBasicBlockList().push_back($2);
1369 // Basic blocks are terminated by branching instructions:
1370 // br, br/cc, switch, ret
1372 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1373 if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1376 $1->getInstList().push_back($3);
1380 | LABELSTR InstructionList OptAssign BBTerminatorInst {
1381 if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1384 $2->getInstList().push_back($4);
1385 if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1391 InstructionList : InstructionList Inst {
1392 $1->getInstList().push_back($2);
1396 $$ = CurBB = new BasicBlock();
1399 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1400 $$ = new ReturnInst($2);
1402 | RET VOID { // Return with no result...
1403 $$ = new ReturnInst();
1405 | BR LABEL ValueRef { // Unconditional Branch...
1406 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1407 } // Conditional Branch...
1408 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1409 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1410 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1411 getVal(Type::BoolTy, $3));
1413 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1414 SwitchInst *S = new SwitchInst(getVal($2, $3),
1415 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1418 vector<pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1421 S->dest_push_back(I->first, I->second);
1423 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal
1424 EXCEPT ResolvedVal {
1425 const PointerType *PFTy;
1426 const FunctionType *Ty;
1428 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1429 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1430 // Pull out the types of all of the arguments...
1431 vector<const Type*> ParamTypes;
1433 for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1434 ParamTypes.push_back((*I)->getType());
1437 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1438 if (isVarArg) ParamTypes.pop_back();
1440 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1441 PFTy = PointerType::get(Ty);
1445 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1447 BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1448 BasicBlock *Except = dyn_cast<BasicBlock>($10);
1450 if (Normal == 0 || Except == 0)
1451 ThrowException("Invoke instruction without label destinations!");
1453 // Create the call node...
1454 if (!$5) { // Has no arguments?
1455 $$ = new InvokeInst(V, Normal, Except, vector<Value*>());
1456 } else { // Has arguments?
1457 // Loop through FunctionType's arguments and ensure they are specified
1460 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1461 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1462 vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1464 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1465 if ((*ArgI)->getType() != *I)
1466 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1467 (*I)->getDescription() + "'!");
1469 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1470 ThrowException("Invalid number of parameters detected!");
1472 $$ = new InvokeInst(V, Normal, Except, *$5);
1479 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1481 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1483 ThrowException("May only switch on a constant pool value!");
1485 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1487 | IntType ConstValueRef ',' LABEL ValueRef {
1488 $$ = new vector<pair<Constant*, BasicBlock*> >();
1489 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1492 ThrowException("May only switch on a constant pool value!");
1494 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1497 Inst : OptAssign InstVal {
1498 // Is this definition named?? if so, assign the name...
1499 if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1504 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1505 $$ = new list<pair<Value*, BasicBlock*> >();
1506 $$->push_back(make_pair(getVal(*$1, $3),
1507 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1510 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1512 $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
1513 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1517 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1518 $$ = new vector<Value*>();
1521 | ValueRefList ',' ResolvedVal {
1526 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1527 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1529 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1530 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint())
1531 ThrowException("Arithmetic operator requires integer or FP operands!");
1532 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1534 ThrowException("binary operator returned null!");
1537 | LogicalOps Types ValueRef ',' ValueRef {
1538 if (!(*$2)->isIntegral())
1539 ThrowException("Logical operator requires integral operands!");
1540 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1542 ThrowException("binary operator returned null!");
1545 | SetCondOps Types ValueRef ',' ValueRef {
1546 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1548 ThrowException("binary operator returned null!");
1552 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1553 << " Replacing with 'xor'.\n";
1555 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1557 ThrowException("Expected integral type for not instruction!");
1559 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1561 ThrowException("Could not create a xor instruction!");
1563 | ShiftOps ResolvedVal ',' ResolvedVal {
1564 if ($4->getType() != Type::UByteTy)
1565 ThrowException("Shift amount must be ubyte!");
1566 $$ = new ShiftInst($1, $2, $4);
1568 | CAST ResolvedVal TO Types {
1569 $$ = new CastInst($2, *$4);
1573 const Type *Ty = $2->front().first->getType();
1574 $$ = new PHINode(Ty);
1575 while ($2->begin() != $2->end()) {
1576 if ($2->front().first->getType() != Ty)
1577 ThrowException("All elements of a PHI node must be of the same type!");
1578 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1581 delete $2; // Free the list...
1583 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1584 const PointerType *PFTy;
1585 const FunctionType *Ty;
1587 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1588 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1589 // Pull out the types of all of the arguments...
1590 vector<const Type*> ParamTypes;
1592 for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1593 ParamTypes.push_back((*I)->getType());
1596 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1597 if (isVarArg) ParamTypes.pop_back();
1599 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1600 PFTy = PointerType::get(Ty);
1604 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1606 // Create the call node...
1607 if (!$5) { // Has no arguments?
1608 // Make sure no arguments is a good thing!
1609 if (Ty->getNumParams() != 0)
1610 ThrowException("No arguments passed to a function that "
1611 "expects arguments!");
1613 $$ = new CallInst(V, vector<Value*>());
1614 } else { // Has arguments?
1615 // Loop through FunctionType's arguments and ensure they are specified
1618 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1619 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1620 vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1622 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1623 if ((*ArgI)->getType() != *I)
1624 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1625 (*I)->getDescription() + "'!");
1627 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1628 ThrowException("Invalid number of parameters detected!");
1630 $$ = new CallInst(V, *$5);
1639 // IndexList - List of indices for GEP based instructions...
1640 IndexList : ',' ValueRefList {
1643 $$ = new vector<Value*>();
1646 MemoryInst : MALLOC Types {
1647 $$ = new MallocInst(*$2);
1650 | MALLOC Types ',' UINT ValueRef {
1651 $$ = new MallocInst(*$2, getVal($4, $5));
1655 $$ = new AllocaInst(*$2);
1658 | ALLOCA Types ',' UINT ValueRef {
1659 $$ = new AllocaInst(*$2, getVal($4, $5));
1662 | FREE ResolvedVal {
1663 if (!isa<PointerType>($2->getType()))
1664 ThrowException("Trying to free nonpointer type " +
1665 $2->getType()->getDescription() + "!");
1666 $$ = new FreeInst($2);
1669 | LOAD Types ValueRef IndexList {
1670 if (!isa<PointerType>($2->get()))
1671 ThrowException("Can't load from nonpointer type: " +
1672 (*$2)->getDescription());
1673 if (GetElementPtrInst::getIndexedType(*$2, *$4) == 0)
1674 ThrowException("Invalid indices for load instruction!");
1676 Value *Src = getVal(*$2, $3);
1678 std::cerr << "WARNING: Use of index load instruction:"
1679 << " replacing with getelementptr/load pair.\n";
1680 // Create a getelementptr hack instruction to do the right thing for
1683 Instruction *I = new GetElementPtrInst(Src, *$4);
1684 CurBB->getInstList().push_back(I);
1688 $$ = new LoadInst(Src);
1689 delete $4; // Free the vector...
1692 | STORE ResolvedVal ',' Types ValueRef IndexList {
1693 if (!isa<PointerType>($4->get()))
1694 ThrowException("Can't store to a nonpointer type: " +
1695 (*$4)->getDescription());
1696 const Type *ElTy = GetElementPtrInst::getIndexedType(*$4, *$6);
1698 ThrowException("Can't store into that field list!");
1699 if (ElTy != $2->getType())
1700 ThrowException("Can't store '" + $2->getType()->getDescription() +
1701 "' into space of type '" + ElTy->getDescription() + "'!");
1703 Value *Ptr = getVal(*$4, $5);
1705 std::cerr << "WARNING: Use of index store instruction:"
1706 << " replacing with getelementptr/store pair.\n";
1707 // Create a getelementptr hack instruction to do the right thing for
1710 Instruction *I = new GetElementPtrInst(Ptr, *$6);
1711 CurBB->getInstList().push_back(I);
1715 $$ = new StoreInst($2, Ptr);
1716 delete $4; delete $6;
1718 | GETELEMENTPTR Types ValueRef IndexList {
1719 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
1720 if ((*$4)[i]->getType() == Type::UIntTy) {
1721 std::cerr << "WARNING: Use of uint type indexes to getelementptr "
1722 << "instruction: replacing with casts to long type.\n";
1723 Instruction *I = new CastInst((*$4)[i], Type::LongTy);
1724 CurBB->getInstList().push_back(I);
1729 if (!isa<PointerType>($2->get()))
1730 ThrowException("getelementptr insn requires pointer operand!");
1731 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1732 ThrowException("Can't get element ptr '" + (*$2)->getDescription()+ "'!");
1733 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1734 delete $2; delete $4;
1738 int yyerror(const char *ErrorMsg) {
1739 string where = string((CurFilename == "-")? string("<stdin>") : CurFilename)
1740 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
1741 string errMsg = string(ErrorMsg) + string("\n") + where + " while reading ";
1742 if (yychar == YYEMPTY)
1743 errMsg += "end-of-file.";
1745 errMsg += "token: '" + string(llvmAsmtext, llvmAsmleng) + "'";
1746 ThrowException(errMsg);