regenerate
[oota-llvm.git] / lib / AsmParser / llvmAsmParser.y.cvs
1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the bison parser for LLVM assembly languages files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 %{
15 #include "ParserInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/SymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/Streams.h"
26 #include <algorithm>
27 #include <list>
28 #include <utility>
29 #ifndef NDEBUG
30 #define YYDEBUG 1
31 #endif
32
33 // The following is a gross hack. In order to rid the libAsmParser library of
34 // exceptions, we have to have a way of getting the yyparse function to go into
35 // an error situation. So, whenever we want an error to occur, the GenerateError
36 // function (see bottom of file) sets TriggerError. Then, at the end of each 
37 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR 
38 // (a goto) to put YACC in error state. Furthermore, several calls to 
39 // GenerateError are made from inside productions and they must simulate the
40 // previous exception behavior by exiting the production immediately. We have
41 // replaced these with the GEN_ERROR macro which calls GeneratError and then
42 // immediately invokes YYERROR. This would be so much cleaner if it was a 
43 // recursive descent parser.
44 static bool TriggerError = false;
45 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
46 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
47
48 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
49 int yylex();                       // declaration" of xxx warnings.
50 int yyparse();
51
52 namespace llvm {
53   std::string CurFilename;
54 #if YYDEBUG
55 static cl::opt<bool>
56 Debug("debug-yacc", cl::desc("Print yacc debug state changes"), 
57       cl::Hidden, cl::init(false));
58 #endif
59 }
60 using namespace llvm;
61
62 static Module *ParserResult;
63
64 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
65 // relating to upreferences in the input stream.
66 //
67 //#define DEBUG_UPREFS 1
68 #ifdef DEBUG_UPREFS
69 #define UR_OUT(X) cerr << X
70 #else
71 #define UR_OUT(X)
72 #endif
73
74 #define YYERROR_VERBOSE 1
75
76 static GlobalVariable *CurGV;
77
78
79 // This contains info used when building the body of a function.  It is
80 // destroyed when the function is completed.
81 //
82 typedef std::vector<Value *> ValueList;           // Numbered defs
83
84 static void 
85 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
86                    std::map<const Type *,ValueList> *FutureLateResolvers = 0);
87
88 static struct PerModuleInfo {
89   Module *CurrentModule;
90   std::map<const Type *, ValueList> Values; // Module level numbered definitions
91   std::map<const Type *,ValueList> LateResolveValues;
92   std::vector<PATypeHolder>    Types;
93   std::map<ValID, PATypeHolder> LateResolveTypes;
94
95   /// PlaceHolderInfo - When temporary placeholder objects are created, remember
96   /// how they were referenced and on which line of the input they came from so
97   /// that we can resolve them later and print error messages as appropriate.
98   std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
99
100   // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
101   // references to global values.  Global values may be referenced before they
102   // are defined, and if so, the temporary object that they represent is held
103   // here.  This is used for forward references of GlobalValues.
104   //
105   typedef std::map<std::pair<const PointerType *,
106                              ValID>, GlobalValue*> GlobalRefsType;
107   GlobalRefsType GlobalRefs;
108
109   void ModuleDone() {
110     // If we could not resolve some functions at function compilation time
111     // (calls to functions before they are defined), resolve them now...  Types
112     // are resolved when the constant pool has been completely parsed.
113     //
114     ResolveDefinitions(LateResolveValues);
115     if (TriggerError)
116       return;
117
118     // Check to make sure that all global value forward references have been
119     // resolved!
120     //
121     if (!GlobalRefs.empty()) {
122       std::string UndefinedReferences = "Unresolved global references exist:\n";
123
124       for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
125            I != E; ++I) {
126         UndefinedReferences += "  " + I->first.first->getDescription() + " " +
127                                I->first.second.getName() + "\n";
128       }
129       GenerateError(UndefinedReferences);
130       return;
131     }
132
133     Values.clear();         // Clear out function local definitions
134     Types.clear();
135     CurrentModule = 0;
136   }
137
138   // GetForwardRefForGlobal - Check to see if there is a forward reference
139   // for this global.  If so, remove it from the GlobalRefs map and return it.
140   // If not, just return null.
141   GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
142     // Check to see if there is a forward reference to this global variable...
143     // if there is, eliminate it and patch the reference to use the new def'n.
144     GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
145     GlobalValue *Ret = 0;
146     if (I != GlobalRefs.end()) {
147       Ret = I->second;
148       GlobalRefs.erase(I);
149     }
150     return Ret;
151   }
152
153   bool TypeIsUnresolved(PATypeHolder* PATy) {
154     // If it isn't abstract, its resolved
155     const Type* Ty = PATy->get();
156     if (!Ty->isAbstract())
157       return false;
158     // Traverse the type looking for abstract types. If it isn't abstract then
159     // we don't need to traverse that leg of the type. 
160     std::vector<const Type*> WorkList, SeenList;
161     WorkList.push_back(Ty);
162     while (!WorkList.empty()) {
163       const Type* Ty = WorkList.back();
164       SeenList.push_back(Ty);
165       WorkList.pop_back();
166       if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
167         // Check to see if this is an unresolved type
168         std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
169         std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
170         for ( ; I != E; ++I) {
171           if (I->second.get() == OpTy)
172             return true;
173         }
174       } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
175         const Type* TheTy = SeqTy->getElementType();
176         if (TheTy->isAbstract() && TheTy != Ty) {
177           std::vector<const Type*>::iterator I = SeenList.begin(), 
178                                              E = SeenList.end();
179           for ( ; I != E; ++I)
180             if (*I == TheTy)
181               break;
182           if (I == E)
183             WorkList.push_back(TheTy);
184         }
185       } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
186         for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
187           const Type* TheTy = StrTy->getElementType(i);
188           if (TheTy->isAbstract() && TheTy != Ty) {
189             std::vector<const Type*>::iterator I = SeenList.begin(), 
190                                                E = SeenList.end();
191             for ( ; I != E; ++I)
192               if (*I == TheTy)
193                 break;
194             if (I == E)
195               WorkList.push_back(TheTy);
196           }
197         }
198       }
199     }
200     return false;
201   }
202
203
204 } CurModule;
205
206 static struct PerFunctionInfo {
207   Function *CurrentFunction;     // Pointer to current function being created
208
209   std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
210   std::map<const Type*, ValueList> LateResolveValues;
211   bool isDeclare;                    // Is this function a forward declararation?
212   GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
213   GlobalValue::VisibilityTypes Visibility;
214
215   /// BBForwardRefs - When we see forward references to basic blocks, keep
216   /// track of them here.
217   std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
218   std::vector<BasicBlock*> NumberedBlocks;
219   unsigned NextBBNum;
220
221   inline PerFunctionInfo() {
222     CurrentFunction = 0;
223     isDeclare = false;
224     Linkage = GlobalValue::ExternalLinkage;
225     Visibility = GlobalValue::DefaultVisibility;
226   }
227
228   inline void FunctionStart(Function *M) {
229     CurrentFunction = M;
230     NextBBNum = 0;
231   }
232
233   void FunctionDone() {
234     NumberedBlocks.clear();
235
236     // Any forward referenced blocks left?
237     if (!BBForwardRefs.empty()) {
238       GenerateError("Undefined reference to label " +
239                      BBForwardRefs.begin()->first->getName());
240       return;
241     }
242
243     // Resolve all forward references now.
244     ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
245
246     Values.clear();         // Clear out function local definitions
247     CurrentFunction = 0;
248     isDeclare = false;
249     Linkage = GlobalValue::ExternalLinkage;
250     Visibility = GlobalValue::DefaultVisibility;
251   }
252 } CurFun;  // Info for the current function...
253
254 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
255
256
257 //===----------------------------------------------------------------------===//
258 //               Code to handle definitions of all the types
259 //===----------------------------------------------------------------------===//
260
261 static int InsertValue(Value *V,
262                   std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
263   if (V->hasName()) return -1;           // Is this a numbered definition?
264
265   // Yes, insert the value into the value table...
266   ValueList &List = ValueTab[V->getType()];
267   List.push_back(V);
268   return List.size()-1;
269 }
270
271 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
272   switch (D.Type) {
273   case ValID::NumberVal:               // Is it a numbered definition?
274     // Module constants occupy the lowest numbered slots...
275     if ((unsigned)D.Num < CurModule.Types.size())
276       return CurModule.Types[(unsigned)D.Num];
277     break;
278   case ValID::NameVal:                 // Is it a named definition?
279     if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
280       D.destroy();  // Free old strdup'd memory...
281       return N;
282     }
283     break;
284   default:
285     GenerateError("Internal parser error: Invalid symbol type reference!");
286     return 0;
287   }
288
289   // If we reached here, we referenced either a symbol that we don't know about
290   // or an id number that hasn't been read yet.  We may be referencing something
291   // forward, so just create an entry to be resolved later and get to it...
292   //
293   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
294
295
296   if (inFunctionScope()) {
297     if (D.Type == ValID::NameVal) {
298       GenerateError("Reference to an undefined type: '" + D.getName() + "'");
299       return 0;
300     } else {
301       GenerateError("Reference to an undefined type: #" + itostr(D.Num));
302       return 0;
303     }
304   }
305
306   std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
307   if (I != CurModule.LateResolveTypes.end())
308     return I->second;
309
310   Type *Typ = OpaqueType::get();
311   CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
312   return Typ;
313  }
314
315 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
316   SymbolTable &SymTab =
317     inFunctionScope() ? CurFun.CurrentFunction->getValueSymbolTable() :
318                         CurModule.CurrentModule->getValueSymbolTable();
319   return SymTab.lookup(Ty, Name);
320 }
321
322 // getValNonImprovising - Look up the value specified by the provided type and
323 // the provided ValID.  If the value exists and has already been defined, return
324 // it.  Otherwise return null.
325 //
326 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
327   if (isa<FunctionType>(Ty)) {
328     GenerateError("Functions are not values and "
329                    "must be referenced as pointers");
330     return 0;
331   }
332
333   switch (D.Type) {
334   case ValID::NumberVal: {                 // Is it a numbered definition?
335     unsigned Num = (unsigned)D.Num;
336
337     // Module constants occupy the lowest numbered slots...
338     std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
339     if (VI != CurModule.Values.end()) {
340       if (Num < VI->second.size())
341         return VI->second[Num];
342       Num -= VI->second.size();
343     }
344
345     // Make sure that our type is within bounds
346     VI = CurFun.Values.find(Ty);
347     if (VI == CurFun.Values.end()) return 0;
348
349     // Check that the number is within bounds...
350     if (VI->second.size() <= Num) return 0;
351
352     return VI->second[Num];
353   }
354
355   case ValID::NameVal: {                // Is it a named definition?
356     Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
357     if (N == 0) return 0;
358
359     D.destroy();  // Free old strdup'd memory...
360     return N;
361   }
362
363   // Check to make sure that "Ty" is an integral type, and that our
364   // value will fit into the specified type...
365   case ValID::ConstSIntVal:    // Is it a constant pool reference??
366     if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
367       GenerateError("Signed integral constant '" +
368                      itostr(D.ConstPool64) + "' is invalid for type '" +
369                      Ty->getDescription() + "'!");
370       return 0;
371     }
372     return ConstantInt::get(Ty, D.ConstPool64);
373
374   case ValID::ConstUIntVal:     // Is it an unsigned const pool reference?
375     if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
376       if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
377         GenerateError("Integral constant '" + utostr(D.UConstPool64) +
378                        "' is invalid or out of range!");
379         return 0;
380       } else {     // This is really a signed reference.  Transmogrify.
381         return ConstantInt::get(Ty, D.ConstPool64);
382       }
383     } else {
384       return ConstantInt::get(Ty, D.UConstPool64);
385     }
386
387   case ValID::ConstFPVal:        // Is it a floating point const pool reference?
388     if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
389       GenerateError("FP constant invalid for type!!");
390       return 0;
391     }
392     return ConstantFP::get(Ty, D.ConstPoolFP);
393
394   case ValID::ConstNullVal:      // Is it a null value?
395     if (!isa<PointerType>(Ty)) {
396       GenerateError("Cannot create a a non pointer null!");
397       return 0;
398     }
399     return ConstantPointerNull::get(cast<PointerType>(Ty));
400
401   case ValID::ConstUndefVal:      // Is it an undef value?
402     return UndefValue::get(Ty);
403
404   case ValID::ConstZeroVal:      // Is it a zero value?
405     return Constant::getNullValue(Ty);
406     
407   case ValID::ConstantVal:       // Fully resolved constant?
408     if (D.ConstantValue->getType() != Ty) {
409       GenerateError("Constant expression type different from required type!");
410       return 0;
411     }
412     return D.ConstantValue;
413
414   case ValID::InlineAsmVal: {    // Inline asm expression
415     const PointerType *PTy = dyn_cast<PointerType>(Ty);
416     const FunctionType *FTy =
417       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
418     if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
419       GenerateError("Invalid type for asm constraint string!");
420       return 0;
421     }
422     InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
423                                    D.IAD->HasSideEffects);
424     D.destroy();   // Free InlineAsmDescriptor.
425     return IA;
426   }
427   default:
428     assert(0 && "Unhandled case!");
429     return 0;
430   }   // End of switch
431
432   assert(0 && "Unhandled case!");
433   return 0;
434 }
435
436 // getVal - This function is identical to getValNonImprovising, except that if a
437 // value is not already defined, it "improvises" by creating a placeholder var
438 // that looks and acts just like the requested variable.  When the value is
439 // defined later, all uses of the placeholder variable are replaced with the
440 // real thing.
441 //
442 static Value *getVal(const Type *Ty, const ValID &ID) {
443   if (Ty == Type::LabelTy) {
444     GenerateError("Cannot use a basic block here");
445     return 0;
446   }
447
448   // See if the value has already been defined.
449   Value *V = getValNonImprovising(Ty, ID);
450   if (V) return V;
451   if (TriggerError) return 0;
452
453   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
454     GenerateError("Invalid use of a composite type!");
455     return 0;
456   }
457
458   // If we reached here, we referenced either a symbol that we don't know about
459   // or an id number that hasn't been read yet.  We may be referencing something
460   // forward, so just create an entry to be resolved later and get to it...
461   //
462   V = new Argument(Ty);
463
464   // Remember where this forward reference came from.  FIXME, shouldn't we try
465   // to recycle these things??
466   CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
467                                                                llvmAsmlineno)));
468
469   if (inFunctionScope())
470     InsertValue(V, CurFun.LateResolveValues);
471   else
472     InsertValue(V, CurModule.LateResolveValues);
473   return V;
474 }
475
476 /// getBBVal - This is used for two purposes:
477 ///  * If isDefinition is true, a new basic block with the specified ID is being
478 ///    defined.
479 ///  * If isDefinition is true, this is a reference to a basic block, which may
480 ///    or may not be a forward reference.
481 ///
482 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
483   assert(inFunctionScope() && "Can't get basic block at global scope!");
484
485   std::string Name;
486   BasicBlock *BB = 0;
487   switch (ID.Type) {
488   default: 
489     GenerateError("Illegal label reference " + ID.getName());
490     return 0;
491   case ValID::NumberVal:                // Is it a numbered definition?
492     if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
493       CurFun.NumberedBlocks.resize(ID.Num+1);
494     BB = CurFun.NumberedBlocks[ID.Num];
495     break;
496   case ValID::NameVal:                  // Is it a named definition?
497     Name = ID.Name;
498     if (Value *N = CurFun.CurrentFunction->
499                    getValueSymbolTable().lookup(Type::LabelTy, Name))
500       BB = cast<BasicBlock>(N);
501     break;
502   }
503
504   // See if the block has already been defined.
505   if (BB) {
506     // If this is the definition of the block, make sure the existing value was
507     // just a forward reference.  If it was a forward reference, there will be
508     // an entry for it in the PlaceHolderInfo map.
509     if (isDefinition && !CurFun.BBForwardRefs.erase(BB)) {
510       // The existing value was a definition, not a forward reference.
511       GenerateError("Redefinition of label " + ID.getName());
512       return 0;
513     }
514
515     ID.destroy();                       // Free strdup'd memory.
516     return BB;
517   }
518
519   // Otherwise this block has not been seen before.
520   BB = new BasicBlock("", CurFun.CurrentFunction);
521   if (ID.Type == ValID::NameVal) {
522     BB->setName(ID.Name);
523   } else {
524     CurFun.NumberedBlocks[ID.Num] = BB;
525   }
526
527   // If this is not a definition, keep track of it so we can use it as a forward
528   // reference.
529   if (!isDefinition) {
530     // Remember where this forward reference came from.
531     CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
532   } else {
533     // The forward declaration could have been inserted anywhere in the
534     // function: insert it into the correct place now.
535     CurFun.CurrentFunction->getBasicBlockList().remove(BB);
536     CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
537   }
538   ID.destroy();
539   return BB;
540 }
541
542
543 //===----------------------------------------------------------------------===//
544 //              Code to handle forward references in instructions
545 //===----------------------------------------------------------------------===//
546 //
547 // This code handles the late binding needed with statements that reference
548 // values not defined yet... for example, a forward branch, or the PHI node for
549 // a loop body.
550 //
551 // This keeps a table (CurFun.LateResolveValues) of all such forward references
552 // and back patchs after we are done.
553 //
554
555 // ResolveDefinitions - If we could not resolve some defs at parsing
556 // time (forward branches, phi functions for loops, etc...) resolve the
557 // defs now...
558 //
559 static void 
560 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
561                    std::map<const Type*,ValueList> *FutureLateResolvers) {
562   // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
563   for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
564          E = LateResolvers.end(); LRI != E; ++LRI) {
565     ValueList &List = LRI->second;
566     while (!List.empty()) {
567       Value *V = List.back();
568       List.pop_back();
569
570       std::map<Value*, std::pair<ValID, int> >::iterator PHI =
571         CurModule.PlaceHolderInfo.find(V);
572       assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
573
574       ValID &DID = PHI->second.first;
575
576       Value *TheRealValue = getValNonImprovising(LRI->first, DID);
577       if (TriggerError)
578         return;
579       if (TheRealValue) {
580         V->replaceAllUsesWith(TheRealValue);
581         delete V;
582         CurModule.PlaceHolderInfo.erase(PHI);
583       } else if (FutureLateResolvers) {
584         // Functions have their unresolved items forwarded to the module late
585         // resolver table
586         InsertValue(V, *FutureLateResolvers);
587       } else {
588         if (DID.Type == ValID::NameVal) {
589           GenerateError("Reference to an invalid definition: '" +DID.getName()+
590                          "' of type '" + V->getType()->getDescription() + "'",
591                          PHI->second.second);
592           return;
593         } else {
594           GenerateError("Reference to an invalid definition: #" +
595                          itostr(DID.Num) + " of type '" +
596                          V->getType()->getDescription() + "'",
597                          PHI->second.second);
598           return;
599         }
600       }
601     }
602   }
603
604   LateResolvers.clear();
605 }
606
607 // ResolveTypeTo - A brand new type was just declared.  This means that (if
608 // name is not null) things referencing Name can be resolved.  Otherwise, things
609 // refering to the number can be resolved.  Do this now.
610 //
611 static void ResolveTypeTo(char *Name, const Type *ToTy) {
612   ValID D;
613   if (Name) D = ValID::create(Name);
614   else      D = ValID::create((int)CurModule.Types.size());
615
616   std::map<ValID, PATypeHolder>::iterator I =
617     CurModule.LateResolveTypes.find(D);
618   if (I != CurModule.LateResolveTypes.end()) {
619     ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
620     CurModule.LateResolveTypes.erase(I);
621   }
622 }
623
624 // setValueName - Set the specified value to the name given.  The name may be
625 // null potentially, in which case this is a noop.  The string passed in is
626 // assumed to be a malloc'd string buffer, and is free'd by this function.
627 //
628 static void setValueName(Value *V, char *NameStr) {
629   if (NameStr) {
630     std::string Name(NameStr);      // Copy string
631     free(NameStr);                  // Free old string
632
633     if (V->getType() == Type::VoidTy) {
634       GenerateError("Can't assign name '" + Name+"' to value with void type!");
635       return;
636     }
637
638     assert(inFunctionScope() && "Must be in function scope!");
639     SymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
640     if (ST.lookup(V->getType(), Name)) {
641       GenerateError("Redefinition of value '" + Name + "' of type '" +
642                      V->getType()->getDescription() + "'!");
643       return;
644     }
645
646     // Set the name.
647     V->setName(Name);
648   }
649 }
650
651 /// ParseGlobalVariable - Handle parsing of a global.  If Initializer is null,
652 /// this is a declaration, otherwise it is a definition.
653 static GlobalVariable *
654 ParseGlobalVariable(char *NameStr,
655                     GlobalValue::LinkageTypes Linkage,
656                     GlobalValue::VisibilityTypes Visibility,
657                     bool isConstantGlobal, const Type *Ty,
658                     Constant *Initializer) {
659   if (isa<FunctionType>(Ty)) {
660     GenerateError("Cannot declare global vars of function type!");
661     return 0;
662   }
663
664   const PointerType *PTy = PointerType::get(Ty);
665
666   std::string Name;
667   if (NameStr) {
668     Name = NameStr;      // Copy string
669     free(NameStr);       // Free old string
670   }
671
672   // See if this global value was forward referenced.  If so, recycle the
673   // object.
674   ValID ID;
675   if (!Name.empty()) {
676     ID = ValID::create((char*)Name.c_str());
677   } else {
678     ID = ValID::create((int)CurModule.Values[PTy].size());
679   }
680
681   if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
682     // Move the global to the end of the list, from whereever it was
683     // previously inserted.
684     GlobalVariable *GV = cast<GlobalVariable>(FWGV);
685     CurModule.CurrentModule->getGlobalList().remove(GV);
686     CurModule.CurrentModule->getGlobalList().push_back(GV);
687     GV->setInitializer(Initializer);
688     GV->setLinkage(Linkage);
689     GV->setVisibility(Visibility);
690     GV->setConstant(isConstantGlobal);
691     InsertValue(GV, CurModule.Values);
692     return GV;
693   }
694
695   // If this global has a name, check to see if there is already a definition
696   // of this global in the module.  If so, it is an error.
697   if (!Name.empty()) {
698     // We are a simple redefinition of a value, check to see if it is defined
699     // the same as the old one.
700     if (CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
701       GenerateError("Redefinition of global variable named '" + Name +
702                      "' of type '" + Ty->getDescription() + "'!");
703       return 0;
704     }
705   }
706
707   // Otherwise there is no existing GV to use, create one now.
708   GlobalVariable *GV =
709     new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
710                        CurModule.CurrentModule);
711   GV->setVisibility(Visibility);
712   InsertValue(GV, CurModule.Values);
713   return GV;
714 }
715
716 // setTypeName - Set the specified type to the name given.  The name may be
717 // null potentially, in which case this is a noop.  The string passed in is
718 // assumed to be a malloc'd string buffer, and is freed by this function.
719 //
720 // This function returns true if the type has already been defined, but is
721 // allowed to be redefined in the specified context.  If the name is a new name
722 // for the type plane, it is inserted and false is returned.
723 static bool setTypeName(const Type *T, char *NameStr) {
724   assert(!inFunctionScope() && "Can't give types function-local names!");
725   if (NameStr == 0) return false;
726  
727   std::string Name(NameStr);      // Copy string
728   free(NameStr);                  // Free old string
729
730   // We don't allow assigning names to void type
731   if (T == Type::VoidTy) {
732     GenerateError("Can't assign name '" + Name + "' to the void type!");
733     return false;
734   }
735
736   // Set the type name, checking for conflicts as we do so.
737   bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
738
739   if (AlreadyExists) {   // Inserting a name that is already defined???
740     const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
741     assert(Existing && "Conflict but no matching type?");
742
743     // There is only one case where this is allowed: when we are refining an
744     // opaque type.  In this case, Existing will be an opaque type.
745     if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
746       // We ARE replacing an opaque type!
747       const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
748       return true;
749     }
750
751     // Otherwise, this is an attempt to redefine a type. That's okay if
752     // the redefinition is identical to the original. This will be so if
753     // Existing and T point to the same Type object. In this one case we
754     // allow the equivalent redefinition.
755     if (Existing == T) return true;  // Yes, it's equal.
756
757     // Any other kind of (non-equivalent) redefinition is an error.
758     GenerateError("Redefinition of type named '" + Name + "' of type '" +
759                    T->getDescription() + "'!");
760   }
761
762   return false;
763 }
764
765 //===----------------------------------------------------------------------===//
766 // Code for handling upreferences in type names...
767 //
768
769 // TypeContains - Returns true if Ty directly contains E in it.
770 //
771 static bool TypeContains(const Type *Ty, const Type *E) {
772   return std::find(Ty->subtype_begin(), Ty->subtype_end(),
773                    E) != Ty->subtype_end();
774 }
775
776 namespace {
777   struct UpRefRecord {
778     // NestingLevel - The number of nesting levels that need to be popped before
779     // this type is resolved.
780     unsigned NestingLevel;
781
782     // LastContainedTy - This is the type at the current binding level for the
783     // type.  Every time we reduce the nesting level, this gets updated.
784     const Type *LastContainedTy;
785
786     // UpRefTy - This is the actual opaque type that the upreference is
787     // represented with.
788     OpaqueType *UpRefTy;
789
790     UpRefRecord(unsigned NL, OpaqueType *URTy)
791       : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
792   };
793 }
794
795 // UpRefs - A list of the outstanding upreferences that need to be resolved.
796 static std::vector<UpRefRecord> UpRefs;
797
798 /// HandleUpRefs - Every time we finish a new layer of types, this function is
799 /// called.  It loops through the UpRefs vector, which is a list of the
800 /// currently active types.  For each type, if the up reference is contained in
801 /// the newly completed type, we decrement the level count.  When the level
802 /// count reaches zero, the upreferenced type is the type that is passed in:
803 /// thus we can complete the cycle.
804 ///
805 static PATypeHolder HandleUpRefs(const Type *ty) {
806   // If Ty isn't abstract, or if there are no up-references in it, then there is
807   // nothing to resolve here.
808   if (!ty->isAbstract() || UpRefs.empty()) return ty;
809   
810   PATypeHolder Ty(ty);
811   UR_OUT("Type '" << Ty->getDescription() <<
812          "' newly formed.  Resolving upreferences.\n" <<
813          UpRefs.size() << " upreferences active!\n");
814
815   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
816   // to zero), we resolve them all together before we resolve them to Ty.  At
817   // the end of the loop, if there is anything to resolve to Ty, it will be in
818   // this variable.
819   OpaqueType *TypeToResolve = 0;
820
821   for (unsigned i = 0; i != UpRefs.size(); ++i) {
822     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
823            << UpRefs[i].second->getDescription() << ") = "
824            << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
825     if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
826       // Decrement level of upreference
827       unsigned Level = --UpRefs[i].NestingLevel;
828       UpRefs[i].LastContainedTy = Ty;
829       UR_OUT("  Uplevel Ref Level = " << Level << "\n");
830       if (Level == 0) {                     // Upreference should be resolved!
831         if (!TypeToResolve) {
832           TypeToResolve = UpRefs[i].UpRefTy;
833         } else {
834           UR_OUT("  * Resolving upreference for "
835                  << UpRefs[i].second->getDescription() << "\n";
836                  std::string OldName = UpRefs[i].UpRefTy->getDescription());
837           UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
838           UR_OUT("  * Type '" << OldName << "' refined upreference to: "
839                  << (const void*)Ty << ", " << Ty->getDescription() << "\n");
840         }
841         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
842         --i;                                // Do not skip the next element...
843       }
844     }
845   }
846
847   if (TypeToResolve) {
848     UR_OUT("  * Resolving upreference for "
849            << UpRefs[i].second->getDescription() << "\n";
850            std::string OldName = TypeToResolve->getDescription());
851     TypeToResolve->refineAbstractTypeTo(Ty);
852   }
853
854   return Ty;
855 }
856
857 //===----------------------------------------------------------------------===//
858 //            RunVMAsmParser - Define an interface to this parser
859 //===----------------------------------------------------------------------===//
860 //
861 static Module* RunParser(Module * M);
862
863 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
864   set_scan_file(F);
865
866   CurFilename = Filename;
867   return RunParser(new Module(CurFilename));
868 }
869
870 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
871   set_scan_string(AsmString);
872
873   CurFilename = "from_memory";
874   if (M == NULL) {
875     return RunParser(new Module (CurFilename));
876   } else {
877     return RunParser(M);
878   }
879 }
880
881 %}
882
883 %union {
884   llvm::Module                           *ModuleVal;
885   llvm::Function                         *FunctionVal;
886   llvm::BasicBlock                       *BasicBlockVal;
887   llvm::TerminatorInst                   *TermInstVal;
888   llvm::Instruction                      *InstVal;
889   llvm::Constant                         *ConstVal;
890
891   const llvm::Type                       *PrimType;
892   std::list<llvm::PATypeHolder>          *TypeList;
893   llvm::PATypeHolder                     *TypeVal;
894   llvm::Value                            *ValueVal;
895   std::vector<llvm::Value*>              *ValueList;
896   llvm::ArgListType                      *ArgList;
897   llvm::TypeWithAttrs                     TypeWithAttrs;
898   llvm::TypeWithAttrsList                *TypeWithAttrsList;
899   llvm::ValueRefList                     *ValueRefList;
900
901   // Represent the RHS of PHI node
902   std::list<std::pair<llvm::Value*,
903                       llvm::BasicBlock*> > *PHIList;
904   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
905   std::vector<llvm::Constant*>           *ConstVector;
906
907   llvm::GlobalValue::LinkageTypes         Linkage;
908   llvm::GlobalValue::VisibilityTypes      Visibility;
909   llvm::FunctionType::ParameterAttributes ParamAttrs;
910   int64_t                           SInt64Val;
911   uint64_t                          UInt64Val;
912   int                               SIntVal;
913   unsigned                          UIntVal;
914   double                            FPVal;
915   bool                              BoolVal;
916
917   char                             *StrVal;   // This memory is strdup'd!
918   llvm::ValID                       ValIDVal; // strdup'd memory maybe!
919
920   llvm::Instruction::BinaryOps      BinaryOpVal;
921   llvm::Instruction::TermOps        TermOpVal;
922   llvm::Instruction::MemoryOps      MemOpVal;
923   llvm::Instruction::CastOps        CastOpVal;
924   llvm::Instruction::OtherOps       OtherOpVal;
925   llvm::Module::Endianness          Endianness;
926   llvm::ICmpInst::Predicate         IPredicate;
927   llvm::FCmpInst::Predicate         FPredicate;
928 }
929
930 %type <ModuleVal>     Module 
931 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
932 %type <BasicBlockVal> BasicBlock InstructionList
933 %type <TermInstVal>   BBTerminatorInst
934 %type <InstVal>       Inst InstVal MemoryInst
935 %type <ConstVal>      ConstVal ConstExpr
936 %type <ConstVector>   ConstVector
937 %type <ArgList>       ArgList ArgListH
938 %type <PHIList>       PHIList
939 %type <ValueRefList>  ValueRefList      // For call param lists & GEP indices
940 %type <ValueList>     IndexList         // For GEP indices
941 %type <TypeList>      TypeListI 
942 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
943 %type <TypeWithAttrs> ArgType
944 %type <JumpTable>     JumpTable
945 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
946 %type <BoolVal>       OptVolatile                 // 'volatile' or not
947 %type <BoolVal>       OptTailCall                 // TAIL CALL or plain CALL.
948 %type <BoolVal>       OptSideEffect               // 'sideeffect' or not.
949 %type <Linkage>       GVInternalLinkage GVExternalLinkage
950 %type <Linkage>       FunctionDefineLinkage FunctionDeclareLinkage
951 %type <Visibility>    GVVisibilityStyle
952 %type <Endianness>    BigOrLittle
953
954 // ValueRef - Unresolved reference to a definition or BB
955 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
956 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
957 // Tokens and types for handling constant integer values
958 //
959 // ESINT64VAL - A negative number within long long range
960 %token <SInt64Val> ESINT64VAL
961
962 // EUINT64VAL - A positive number within uns. long long range
963 %token <UInt64Val> EUINT64VAL
964
965 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
966 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
967 %type   <SIntVal>   INTVAL
968 %token  <FPVal>     FPVAL     // Float or Double constant
969
970 // Built in types...
971 %type  <TypeVal> Types ResultTypes
972 %type  <PrimType> IntType FPType PrimType           // Classifications
973 %token <PrimType> VOID INTTYPE 
974 %token <PrimType> FLOAT DOUBLE LABEL
975 %token TYPE
976
977 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
978 %type  <StrVal> Name OptName OptAssign
979 %type  <UIntVal> OptAlign OptCAlign
980 %type <StrVal> OptSection SectionString
981
982 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
983 %token DECLARE DEFINE GLOBAL CONSTANT SECTION VOLATILE
984 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
985 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
986 %token OPAQUE EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
987 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
988 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
989 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
990 %token DATALAYOUT
991 %type <UIntVal> OptCallingConv
992 %type <ParamAttrs> OptParamAttrs ParamAttr 
993 %type <ParamAttrs> OptFuncAttrs  FuncAttr
994
995 // Basic Block Terminating Operators
996 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
997
998 // Binary Operators
999 %type  <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1000 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1001 %token <OtherOpVal> ICMP FCMP
1002 %type  <IPredicate> IPredicates
1003 %type  <FPredicate> FPredicates
1004 %token  EQ NE SLT SGT SLE SGE ULT UGT ULE UGE 
1005 %token  OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1006
1007 // Memory Instructions
1008 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1009
1010 // Cast Operators
1011 %type <CastOpVal> CastOps
1012 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1013 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1014
1015 // Other Operators
1016 %type  <OtherOpVal> ShiftOps
1017 %token <OtherOpVal> PHI_TOK SELECT SHL LSHR ASHR VAARG
1018 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1019
1020 // Function Attributes
1021 %token NORETURN
1022
1023 // Visibility Styles
1024 %token DEFAULT HIDDEN
1025
1026 %start Module
1027 %%
1028
1029 // Handle constant integer size restriction and conversion...
1030 //
1031 INTVAL : SINTVAL;
1032 INTVAL : UINTVAL {
1033   if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
1034     GEN_ERROR("Value too large for type!");
1035   $$ = (int32_t)$1;
1036   CHECK_FOR_ERROR
1037 };
1038
1039 // Operations that are notably excluded from this list include:
1040 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1041 //
1042 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1043 LogicalOps   : AND | OR | XOR;
1044 CastOps      : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST | 
1045                UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1046 ShiftOps     : SHL | LSHR | ASHR;
1047 IPredicates  
1048   : EQ   { $$ = ICmpInst::ICMP_EQ; }  | NE   { $$ = ICmpInst::ICMP_NE; }
1049   | SLT  { $$ = ICmpInst::ICMP_SLT; } | SGT  { $$ = ICmpInst::ICMP_SGT; }
1050   | SLE  { $$ = ICmpInst::ICMP_SLE; } | SGE  { $$ = ICmpInst::ICMP_SGE; }
1051   | ULT  { $$ = ICmpInst::ICMP_ULT; } | UGT  { $$ = ICmpInst::ICMP_UGT; }
1052   | ULE  { $$ = ICmpInst::ICMP_ULE; } | UGE  { $$ = ICmpInst::ICMP_UGE; } 
1053   ;
1054
1055 FPredicates  
1056   : OEQ  { $$ = FCmpInst::FCMP_OEQ; } | ONE  { $$ = FCmpInst::FCMP_ONE; }
1057   | OLT  { $$ = FCmpInst::FCMP_OLT; } | OGT  { $$ = FCmpInst::FCMP_OGT; }
1058   | OLE  { $$ = FCmpInst::FCMP_OLE; } | OGE  { $$ = FCmpInst::FCMP_OGE; }
1059   | ORD  { $$ = FCmpInst::FCMP_ORD; } | UNO  { $$ = FCmpInst::FCMP_UNO; }
1060   | UEQ  { $$ = FCmpInst::FCMP_UEQ; } | UNE  { $$ = FCmpInst::FCMP_UNE; }
1061   | ULT  { $$ = FCmpInst::FCMP_ULT; } | UGT  { $$ = FCmpInst::FCMP_UGT; }
1062   | ULE  { $$ = FCmpInst::FCMP_ULE; } | UGE  { $$ = FCmpInst::FCMP_UGE; }
1063   | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1064   | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1065   ;
1066
1067 // These are some types that allow classification if we only want a particular 
1068 // thing... for example, only a signed, unsigned, or integral type.
1069 IntType :  INTTYPE;
1070 FPType   : FLOAT | DOUBLE;
1071
1072 // OptAssign - Value producing statements have an optional assignment component
1073 OptAssign : Name '=' {
1074     $$ = $1;
1075     CHECK_FOR_ERROR
1076   }
1077   | /*empty*/ {
1078     $$ = 0;
1079     CHECK_FOR_ERROR
1080   };
1081
1082 GVInternalLinkage 
1083   : INTERNAL    { $$ = GlobalValue::InternalLinkage; } 
1084   | WEAK        { $$ = GlobalValue::WeakLinkage; } 
1085   | LINKONCE    { $$ = GlobalValue::LinkOnceLinkage; }
1086   | APPENDING   { $$ = GlobalValue::AppendingLinkage; }
1087   | DLLEXPORT   { $$ = GlobalValue::DLLExportLinkage; } 
1088   ;
1089
1090 GVExternalLinkage
1091   : DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; }
1092   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1093   | EXTERNAL    { $$ = GlobalValue::ExternalLinkage; }
1094   ;
1095
1096 GVVisibilityStyle
1097   : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1098   | HIDDEN    { $$ = GlobalValue::HiddenVisibility;  }
1099   ;
1100
1101 FunctionDeclareLinkage
1102   : /*empty*/   { $$ = GlobalValue::ExternalLinkage; }
1103   | DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; } 
1104   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1105   ;
1106   
1107 FunctionDefineLinkage 
1108   : /*empty*/   { $$ = GlobalValue::ExternalLinkage; }
1109   | INTERNAL    { $$ = GlobalValue::InternalLinkage; }
1110   | LINKONCE    { $$ = GlobalValue::LinkOnceLinkage; }
1111   | WEAK        { $$ = GlobalValue::WeakLinkage; }
1112   | DLLEXPORT   { $$ = GlobalValue::DLLExportLinkage; } 
1113   ; 
1114
1115 OptCallingConv : /*empty*/          { $$ = CallingConv::C; } |
1116                  CCC_TOK            { $$ = CallingConv::C; } |
1117                  CSRETCC_TOK        { $$ = CallingConv::CSRet; } |
1118                  FASTCC_TOK         { $$ = CallingConv::Fast; } |
1119                  COLDCC_TOK         { $$ = CallingConv::Cold; } |
1120                  X86_STDCALLCC_TOK  { $$ = CallingConv::X86_StdCall; } |
1121                  X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1122                  CC_TOK EUINT64VAL  {
1123                    if ((unsigned)$2 != $2)
1124                      GEN_ERROR("Calling conv too large!");
1125                    $$ = $2;
1126                   CHECK_FOR_ERROR
1127                  };
1128
1129 ParamAttr     : ZEXT { $$ = FunctionType::ZExtAttribute; }
1130               | SEXT { $$ = FunctionType::SExtAttribute; }
1131               ;
1132
1133 OptParamAttrs : /* empty */  { $$ = FunctionType::NoAttributeSet; }
1134               | OptParamAttrs ParamAttr {
1135                 $$ = FunctionType::ParameterAttributes($1 | $2);
1136               }
1137               ;
1138
1139 FuncAttr      : NORETURN { $$ = FunctionType::NoReturnAttribute; }
1140               | ParamAttr
1141               ;
1142
1143 OptFuncAttrs  : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1144               | OptFuncAttrs FuncAttr {
1145                 $$ = FunctionType::ParameterAttributes($1 | $2);
1146               }
1147               ;
1148
1149 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1150 // a comma before it.
1151 OptAlign : /*empty*/        { $$ = 0; } |
1152            ALIGN EUINT64VAL {
1153   $$ = $2;
1154   if ($$ != 0 && !isPowerOf2_32($$))
1155     GEN_ERROR("Alignment must be a power of two!");
1156   CHECK_FOR_ERROR
1157 };
1158 OptCAlign : /*empty*/            { $$ = 0; } |
1159             ',' ALIGN EUINT64VAL {
1160   $$ = $3;
1161   if ($$ != 0 && !isPowerOf2_32($$))
1162     GEN_ERROR("Alignment must be a power of two!");
1163   CHECK_FOR_ERROR
1164 };
1165
1166
1167 SectionString : SECTION STRINGCONSTANT {
1168   for (unsigned i = 0, e = strlen($2); i != e; ++i)
1169     if ($2[i] == '"' || $2[i] == '\\')
1170       GEN_ERROR("Invalid character in section name!");
1171   $$ = $2;
1172   CHECK_FOR_ERROR
1173 };
1174
1175 OptSection : /*empty*/ { $$ = 0; } |
1176              SectionString { $$ = $1; };
1177
1178 // GlobalVarAttributes - Used to pass the attributes string on a global.  CurGV
1179 // is set to be the global we are processing.
1180 //
1181 GlobalVarAttributes : /* empty */ {} |
1182                      ',' GlobalVarAttribute GlobalVarAttributes {};
1183 GlobalVarAttribute : SectionString {
1184     CurGV->setSection($1);
1185     free($1);
1186     CHECK_FOR_ERROR
1187   } 
1188   | ALIGN EUINT64VAL {
1189     if ($2 != 0 && !isPowerOf2_32($2))
1190       GEN_ERROR("Alignment must be a power of two!");
1191     CurGV->setAlignment($2);
1192     CHECK_FOR_ERROR
1193   };
1194
1195 //===----------------------------------------------------------------------===//
1196 // Types includes all predefined types... except void, because it can only be
1197 // used in specific contexts (function returning void for example).  
1198
1199 // Derived types are added later...
1200 //
1201 PrimType : INTTYPE | FLOAT | DOUBLE | LABEL ;
1202
1203 Types 
1204   : OPAQUE {
1205     $$ = new PATypeHolder(OpaqueType::get());
1206     CHECK_FOR_ERROR
1207   }
1208   | PrimType {
1209     $$ = new PATypeHolder($1);
1210     CHECK_FOR_ERROR
1211   }
1212   | Types '*' {                             // Pointer type?
1213     if (*$1 == Type::LabelTy)
1214       GEN_ERROR("Cannot form a pointer to a basic block");
1215     $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1216     delete $1;
1217     CHECK_FOR_ERROR
1218   }
1219   | SymbolicValueRef {            // Named types are also simple types...
1220     const Type* tmp = getTypeVal($1);
1221     CHECK_FOR_ERROR
1222     $$ = new PATypeHolder(tmp);
1223   }
1224   | '\\' EUINT64VAL {                   // Type UpReference
1225     if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
1226     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1227     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1228     $$ = new PATypeHolder(OT);
1229     UR_OUT("New Upreference!\n");
1230     CHECK_FOR_ERROR
1231   }
1232   | Types '(' ArgTypeListI ')' OptFuncAttrs {
1233     std::vector<const Type*> Params;
1234     std::vector<FunctionType::ParameterAttributes> Attrs;
1235     Attrs.push_back($5);
1236     for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1237       Params.push_back(I->Ty->get());
1238       if (I->Ty->get() != Type::VoidTy)
1239         Attrs.push_back(I->Attrs);
1240     }
1241     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1242     if (isVarArg) Params.pop_back();
1243
1244     FunctionType *FT = FunctionType::get(*$1, Params, isVarArg, Attrs);
1245     delete $3;   // Delete the argument list
1246     delete $1;   // Delete the return type handle
1247     $$ = new PATypeHolder(HandleUpRefs(FT)); 
1248     CHECK_FOR_ERROR
1249   }
1250   | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1251     std::vector<const Type*> Params;
1252     std::vector<FunctionType::ParameterAttributes> Attrs;
1253     Attrs.push_back($5);
1254     for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1255       Params.push_back(I->Ty->get());
1256       if (I->Ty->get() != Type::VoidTy)
1257         Attrs.push_back(I->Attrs);
1258     }
1259     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1260     if (isVarArg) Params.pop_back();
1261
1262     FunctionType *FT = FunctionType::get($1, Params, isVarArg, Attrs);
1263     delete $3;      // Delete the argument list
1264     $$ = new PATypeHolder(HandleUpRefs(FT)); 
1265     CHECK_FOR_ERROR
1266   }
1267
1268   | '[' EUINT64VAL 'x' Types ']' {          // Sized array type?
1269     $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1270     delete $4;
1271     CHECK_FOR_ERROR
1272   }
1273   | '<' EUINT64VAL 'x' Types '>' {          // Packed array type?
1274      const llvm::Type* ElemTy = $4->get();
1275      if ((unsigned)$2 != $2)
1276         GEN_ERROR("Unsigned result not equal to signed result");
1277      if (!ElemTy->isFloatingPoint() && !ElemTy->isIntegral())
1278         GEN_ERROR("Element type of a PackedType must be primitive");
1279      if (!isPowerOf2_32($2))
1280        GEN_ERROR("Vector length should be a power of 2!");
1281      $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1282      delete $4;
1283      CHECK_FOR_ERROR
1284   }
1285   | '{' TypeListI '}' {                        // Structure type?
1286     std::vector<const Type*> Elements;
1287     for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1288            E = $2->end(); I != E; ++I)
1289       Elements.push_back(*I);
1290
1291     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1292     delete $2;
1293     CHECK_FOR_ERROR
1294   }
1295   | '{' '}' {                                  // Empty structure type?
1296     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1297     CHECK_FOR_ERROR
1298   }
1299   | '<' '{' TypeListI '}' '>' {
1300     std::vector<const Type*> Elements;
1301     for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1302            E = $3->end(); I != E; ++I)
1303       Elements.push_back(*I);
1304
1305     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1306     delete $3;
1307     CHECK_FOR_ERROR
1308   }
1309   | '<' '{' '}' '>' {                         // Empty structure type?
1310     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1311     CHECK_FOR_ERROR
1312   }
1313   ;
1314
1315 ArgType 
1316   : Types OptParamAttrs { 
1317     $$.Ty = $1; 
1318     $$.Attrs = $2; 
1319   }
1320   ;
1321
1322 ResultTypes
1323   : Types {
1324     if (!UpRefs.empty())
1325       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1326     if (!(*$1)->isFirstClassType())
1327       GEN_ERROR("LLVM functions cannot return aggregate types!");
1328     $$ = $1;
1329   }
1330   | VOID {
1331     $$ = new PATypeHolder(Type::VoidTy);
1332   }
1333   ;
1334
1335 ArgTypeList : ArgType {
1336     $$ = new TypeWithAttrsList();
1337     $$->push_back($1);
1338     CHECK_FOR_ERROR
1339   }
1340   | ArgTypeList ',' ArgType {
1341     ($$=$1)->push_back($3);
1342     CHECK_FOR_ERROR
1343   }
1344   ;
1345
1346 ArgTypeListI 
1347   : ArgTypeList
1348   | ArgTypeList ',' DOTDOTDOT {
1349     $$=$1;
1350     TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1351     TWA.Ty = new PATypeHolder(Type::VoidTy);
1352     $$->push_back(TWA);
1353     CHECK_FOR_ERROR
1354   }
1355   | DOTDOTDOT {
1356     $$ = new TypeWithAttrsList;
1357     TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1358     TWA.Ty = new PATypeHolder(Type::VoidTy);
1359     $$->push_back(TWA);
1360     CHECK_FOR_ERROR
1361   }
1362   | /*empty*/ {
1363     $$ = new TypeWithAttrsList();
1364     CHECK_FOR_ERROR
1365   };
1366
1367 // TypeList - Used for struct declarations and as a basis for function type 
1368 // declaration type lists
1369 //
1370 TypeListI : Types {
1371     $$ = new std::list<PATypeHolder>();
1372     $$->push_back(*$1); delete $1;
1373     CHECK_FOR_ERROR
1374   }
1375   | TypeListI ',' Types {
1376     ($$=$1)->push_back(*$3); delete $3;
1377     CHECK_FOR_ERROR
1378   };
1379
1380 // ConstVal - The various declarations that go into the constant pool.  This
1381 // production is used ONLY to represent constants that show up AFTER a 'const',
1382 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1383 // into other expressions (such as integers and constexprs) are handled by the
1384 // ResolvedVal, ValueRef and ConstValueRef productions.
1385 //
1386 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1387     if (!UpRefs.empty())
1388       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1389     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1390     if (ATy == 0)
1391       GEN_ERROR("Cannot make array constant with type: '" + 
1392                      (*$1)->getDescription() + "'!");
1393     const Type *ETy = ATy->getElementType();
1394     int NumElements = ATy->getNumElements();
1395
1396     // Verify that we have the correct size...
1397     if (NumElements != -1 && NumElements != (int)$3->size())
1398       GEN_ERROR("Type mismatch: constant sized array initialized with " +
1399                      utostr($3->size()) +  " arguments, but has size of " + 
1400                      itostr(NumElements) + "!");
1401
1402     // Verify all elements are correct type!
1403     for (unsigned i = 0; i < $3->size(); i++) {
1404       if (ETy != (*$3)[i]->getType())
1405         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
1406                        ETy->getDescription() +"' as required!\nIt is of type '"+
1407                        (*$3)[i]->getType()->getDescription() + "'.");
1408     }
1409
1410     $$ = ConstantArray::get(ATy, *$3);
1411     delete $1; delete $3;
1412     CHECK_FOR_ERROR
1413   }
1414   | Types '[' ']' {
1415     if (!UpRefs.empty())
1416       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1417     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1418     if (ATy == 0)
1419       GEN_ERROR("Cannot make array constant with type: '" + 
1420                      (*$1)->getDescription() + "'!");
1421
1422     int NumElements = ATy->getNumElements();
1423     if (NumElements != -1 && NumElements != 0) 
1424       GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1425                      " arguments, but has size of " + itostr(NumElements) +"!");
1426     $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1427     delete $1;
1428     CHECK_FOR_ERROR
1429   }
1430   | Types 'c' STRINGCONSTANT {
1431     if (!UpRefs.empty())
1432       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1433     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1434     if (ATy == 0)
1435       GEN_ERROR("Cannot make array constant with type: '" + 
1436                      (*$1)->getDescription() + "'!");
1437
1438     int NumElements = ATy->getNumElements();
1439     const Type *ETy = ATy->getElementType();
1440     char *EndStr = UnEscapeLexed($3, true);
1441     if (NumElements != -1 && NumElements != (EndStr-$3))
1442       GEN_ERROR("Can't build string constant of size " + 
1443                      itostr((int)(EndStr-$3)) +
1444                      " when array has size " + itostr(NumElements) + "!");
1445     std::vector<Constant*> Vals;
1446     if (ETy == Type::Int8Ty) {
1447       for (unsigned char *C = (unsigned char *)$3; 
1448         C != (unsigned char*)EndStr; ++C)
1449       Vals.push_back(ConstantInt::get(ETy, *C));
1450     } else {
1451       free($3);
1452       GEN_ERROR("Cannot build string arrays of non byte sized elements!");
1453     }
1454     free($3);
1455     $$ = ConstantArray::get(ATy, Vals);
1456     delete $1;
1457     CHECK_FOR_ERROR
1458   }
1459   | Types '<' ConstVector '>' { // Nonempty unsized arr
1460     if (!UpRefs.empty())
1461       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1462     const PackedType *PTy = dyn_cast<PackedType>($1->get());
1463     if (PTy == 0)
1464       GEN_ERROR("Cannot make packed constant with type: '" + 
1465                      (*$1)->getDescription() + "'!");
1466     const Type *ETy = PTy->getElementType();
1467     int NumElements = PTy->getNumElements();
1468
1469     // Verify that we have the correct size...
1470     if (NumElements != -1 && NumElements != (int)$3->size())
1471       GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1472                      utostr($3->size()) +  " arguments, but has size of " + 
1473                      itostr(NumElements) + "!");
1474
1475     // Verify all elements are correct type!
1476     for (unsigned i = 0; i < $3->size(); i++) {
1477       if (ETy != (*$3)[i]->getType())
1478         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
1479            ETy->getDescription() +"' as required!\nIt is of type '"+
1480            (*$3)[i]->getType()->getDescription() + "'.");
1481     }
1482
1483     $$ = ConstantPacked::get(PTy, *$3);
1484     delete $1; delete $3;
1485     CHECK_FOR_ERROR
1486   }
1487   | Types '{' ConstVector '}' {
1488     const StructType *STy = dyn_cast<StructType>($1->get());
1489     if (STy == 0)
1490       GEN_ERROR("Cannot make struct constant with type: '" + 
1491                      (*$1)->getDescription() + "'!");
1492
1493     if ($3->size() != STy->getNumContainedTypes())
1494       GEN_ERROR("Illegal number of initializers for structure type!");
1495
1496     // Check to ensure that constants are compatible with the type initializer!
1497     for (unsigned i = 0, e = $3->size(); i != e; ++i)
1498       if ((*$3)[i]->getType() != STy->getElementType(i))
1499         GEN_ERROR("Expected type '" +
1500                        STy->getElementType(i)->getDescription() +
1501                        "' for element #" + utostr(i) +
1502                        " of structure initializer!");
1503
1504     // Check to ensure that Type is not packed
1505     if (STy->isPacked())
1506       GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1507
1508     $$ = ConstantStruct::get(STy, *$3);
1509     delete $1; delete $3;
1510     CHECK_FOR_ERROR
1511   }
1512   | Types '{' '}' {
1513     if (!UpRefs.empty())
1514       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1515     const StructType *STy = dyn_cast<StructType>($1->get());
1516     if (STy == 0)
1517       GEN_ERROR("Cannot make struct constant with type: '" + 
1518                      (*$1)->getDescription() + "'!");
1519
1520     if (STy->getNumContainedTypes() != 0)
1521       GEN_ERROR("Illegal number of initializers for structure type!");
1522
1523     // Check to ensure that Type is not packed
1524     if (STy->isPacked())
1525       GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1526
1527     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1528     delete $1;
1529     CHECK_FOR_ERROR
1530   }
1531   | Types '<' '{' ConstVector '}' '>' {
1532     const StructType *STy = dyn_cast<StructType>($1->get());
1533     if (STy == 0)
1534       GEN_ERROR("Cannot make struct constant with type: '" + 
1535                      (*$1)->getDescription() + "'!");
1536
1537     if ($4->size() != STy->getNumContainedTypes())
1538       GEN_ERROR("Illegal number of initializers for structure type!");
1539
1540     // Check to ensure that constants are compatible with the type initializer!
1541     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1542       if ((*$4)[i]->getType() != STy->getElementType(i))
1543         GEN_ERROR("Expected type '" +
1544                        STy->getElementType(i)->getDescription() +
1545                        "' for element #" + utostr(i) +
1546                        " of structure initializer!");
1547
1548     // Check to ensure that Type is packed
1549     if (!STy->isPacked())
1550       GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1551
1552     $$ = ConstantStruct::get(STy, *$4);
1553     delete $1; delete $4;
1554     CHECK_FOR_ERROR
1555   }
1556   | Types '<' '{' '}' '>' {
1557     if (!UpRefs.empty())
1558       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1559     const StructType *STy = dyn_cast<StructType>($1->get());
1560     if (STy == 0)
1561       GEN_ERROR("Cannot make struct constant with type: '" + 
1562                      (*$1)->getDescription() + "'!");
1563
1564     if (STy->getNumContainedTypes() != 0)
1565       GEN_ERROR("Illegal number of initializers for structure type!");
1566
1567     // Check to ensure that Type is packed
1568     if (!STy->isPacked())
1569       GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1570
1571     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1572     delete $1;
1573     CHECK_FOR_ERROR
1574   }
1575   | Types NULL_TOK {
1576     if (!UpRefs.empty())
1577       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1578     const PointerType *PTy = dyn_cast<PointerType>($1->get());
1579     if (PTy == 0)
1580       GEN_ERROR("Cannot make null pointer constant with type: '" + 
1581                      (*$1)->getDescription() + "'!");
1582
1583     $$ = ConstantPointerNull::get(PTy);
1584     delete $1;
1585     CHECK_FOR_ERROR
1586   }
1587   | Types UNDEF {
1588     if (!UpRefs.empty())
1589       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1590     $$ = UndefValue::get($1->get());
1591     delete $1;
1592     CHECK_FOR_ERROR
1593   }
1594   | Types SymbolicValueRef {
1595     if (!UpRefs.empty())
1596       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1597     const PointerType *Ty = dyn_cast<PointerType>($1->get());
1598     if (Ty == 0)
1599       GEN_ERROR("Global const reference must be a pointer type!");
1600
1601     // ConstExprs can exist in the body of a function, thus creating
1602     // GlobalValues whenever they refer to a variable.  Because we are in
1603     // the context of a function, getValNonImprovising will search the functions
1604     // symbol table instead of the module symbol table for the global symbol,
1605     // which throws things all off.  To get around this, we just tell
1606     // getValNonImprovising that we are at global scope here.
1607     //
1608     Function *SavedCurFn = CurFun.CurrentFunction;
1609     CurFun.CurrentFunction = 0;
1610
1611     Value *V = getValNonImprovising(Ty, $2);
1612     CHECK_FOR_ERROR
1613
1614     CurFun.CurrentFunction = SavedCurFn;
1615
1616     // If this is an initializer for a constant pointer, which is referencing a
1617     // (currently) undefined variable, create a stub now that shall be replaced
1618     // in the future with the right type of variable.
1619     //
1620     if (V == 0) {
1621       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1622       const PointerType *PT = cast<PointerType>(Ty);
1623
1624       // First check to see if the forward references value is already created!
1625       PerModuleInfo::GlobalRefsType::iterator I =
1626         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1627     
1628       if (I != CurModule.GlobalRefs.end()) {
1629         V = I->second;             // Placeholder already exists, use it...
1630         $2.destroy();
1631       } else {
1632         std::string Name;
1633         if ($2.Type == ValID::NameVal) Name = $2.Name;
1634
1635         // Create the forward referenced global.
1636         GlobalValue *GV;
1637         if (const FunctionType *FTy = 
1638                  dyn_cast<FunctionType>(PT->getElementType())) {
1639           GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1640                             CurModule.CurrentModule);
1641         } else {
1642           GV = new GlobalVariable(PT->getElementType(), false,
1643                                   GlobalValue::ExternalLinkage, 0,
1644                                   Name, CurModule.CurrentModule);
1645         }
1646
1647         // Keep track of the fact that we have a forward ref to recycle it
1648         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1649         V = GV;
1650       }
1651     }
1652
1653     $$ = cast<GlobalValue>(V);
1654     delete $1;            // Free the type handle
1655     CHECK_FOR_ERROR
1656   }
1657   | Types ConstExpr {
1658     if (!UpRefs.empty())
1659       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1660     if ($1->get() != $2->getType())
1661       GEN_ERROR("Mismatched types for constant expression: " + 
1662         (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1663     $$ = $2;
1664     delete $1;
1665     CHECK_FOR_ERROR
1666   }
1667   | Types ZEROINITIALIZER {
1668     if (!UpRefs.empty())
1669       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1670     const Type *Ty = $1->get();
1671     if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1672       GEN_ERROR("Cannot create a null initialized value of this type!");
1673     $$ = Constant::getNullValue(Ty);
1674     delete $1;
1675     CHECK_FOR_ERROR
1676   }
1677   | IntType ESINT64VAL {      // integral constants
1678     if (!ConstantInt::isValueValidForType($1, $2))
1679       GEN_ERROR("Constant value doesn't fit in type!");
1680     $$ = ConstantInt::get($1, $2);
1681     CHECK_FOR_ERROR
1682   }
1683   | IntType EUINT64VAL {      // integral constants
1684     if (!ConstantInt::isValueValidForType($1, $2))
1685       GEN_ERROR("Constant value doesn't fit in type!");
1686     $$ = ConstantInt::get($1, $2);
1687     CHECK_FOR_ERROR
1688   }
1689   | INTTYPE TRUETOK {                      // Boolean constants
1690     assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1691     $$ = ConstantInt::getTrue();
1692     CHECK_FOR_ERROR
1693   }
1694   | INTTYPE FALSETOK {                     // Boolean constants
1695     assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1696     $$ = ConstantInt::getFalse();
1697     CHECK_FOR_ERROR
1698   }
1699   | FPType FPVAL {                   // Float & Double constants
1700     if (!ConstantFP::isValueValidForType($1, $2))
1701       GEN_ERROR("Floating point constant invalid for type!!");
1702     $$ = ConstantFP::get($1, $2);
1703     CHECK_FOR_ERROR
1704   };
1705
1706
1707 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1708     if (!UpRefs.empty())
1709       GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1710     Constant *Val = $3;
1711     const Type *Ty = $5->get();
1712     if (!Val->getType()->isFirstClassType())
1713       GEN_ERROR("cast constant expression from a non-primitive type: '" +
1714                      Val->getType()->getDescription() + "'!");
1715     if (!Ty->isFirstClassType())
1716       GEN_ERROR("cast constant expression to a non-primitive type: '" +
1717                 Ty->getDescription() + "'!");
1718     $$ = ConstantExpr::getCast($1, $3, $5->get());
1719     delete $5;
1720   }
1721   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1722     if (!isa<PointerType>($3->getType()))
1723       GEN_ERROR("GetElementPtr requires a pointer operand!");
1724
1725     const Type *IdxTy =
1726       GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1727     if (!IdxTy)
1728       GEN_ERROR("Index list invalid for constant getelementptr!");
1729
1730     std::vector<Constant*> IdxVec;
1731     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1732       if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1733         IdxVec.push_back(C);
1734       else
1735         GEN_ERROR("Indices to constant getelementptr must be constants!");
1736
1737     delete $4;
1738
1739     $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1740     CHECK_FOR_ERROR
1741   }
1742   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1743     if ($3->getType() != Type::Int1Ty)
1744       GEN_ERROR("Select condition must be of boolean type!");
1745     if ($5->getType() != $7->getType())
1746       GEN_ERROR("Select operand types must match!");
1747     $$ = ConstantExpr::getSelect($3, $5, $7);
1748     CHECK_FOR_ERROR
1749   }
1750   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1751     if ($3->getType() != $5->getType())
1752       GEN_ERROR("Binary operator types must match!");
1753     CHECK_FOR_ERROR;
1754     $$ = ConstantExpr::get($1, $3, $5);
1755   }
1756   | LogicalOps '(' ConstVal ',' ConstVal ')' {
1757     if ($3->getType() != $5->getType())
1758       GEN_ERROR("Logical operator types must match!");
1759     if (!$3->getType()->isIntegral()) {
1760       if (!isa<PackedType>($3->getType()) || 
1761           !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1762         GEN_ERROR("Logical operator requires integral operands!");
1763     }
1764     $$ = ConstantExpr::get($1, $3, $5);
1765     CHECK_FOR_ERROR
1766   }
1767   | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1768     if ($4->getType() != $6->getType())
1769       GEN_ERROR("icmp operand types must match!");
1770     $$ = ConstantExpr::getICmp($2, $4, $6);
1771   }
1772   | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1773     if ($4->getType() != $6->getType())
1774       GEN_ERROR("fcmp operand types must match!");
1775     $$ = ConstantExpr::getFCmp($2, $4, $6);
1776   }
1777   | ShiftOps '(' ConstVal ',' ConstVal ')' {
1778     if ($5->getType() != Type::Int8Ty)
1779       GEN_ERROR("Shift count for shift constant must be i8 type!");
1780     if (!$3->getType()->isIntegral())
1781       GEN_ERROR("Shift constant expression requires integer operand!");
1782     CHECK_FOR_ERROR;
1783     $$ = ConstantExpr::get($1, $3, $5);
1784     CHECK_FOR_ERROR
1785   }
1786   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1787     if (!ExtractElementInst::isValidOperands($3, $5))
1788       GEN_ERROR("Invalid extractelement operands!");
1789     $$ = ConstantExpr::getExtractElement($3, $5);
1790     CHECK_FOR_ERROR
1791   }
1792   | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1793     if (!InsertElementInst::isValidOperands($3, $5, $7))
1794       GEN_ERROR("Invalid insertelement operands!");
1795     $$ = ConstantExpr::getInsertElement($3, $5, $7);
1796     CHECK_FOR_ERROR
1797   }
1798   | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1799     if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1800       GEN_ERROR("Invalid shufflevector operands!");
1801     $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1802     CHECK_FOR_ERROR
1803   };
1804
1805
1806 // ConstVector - A list of comma separated constants.
1807 ConstVector : ConstVector ',' ConstVal {
1808     ($$ = $1)->push_back($3);
1809     CHECK_FOR_ERROR
1810   }
1811   | ConstVal {
1812     $$ = new std::vector<Constant*>();
1813     $$->push_back($1);
1814     CHECK_FOR_ERROR
1815   };
1816
1817
1818 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1819 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1820
1821
1822 //===----------------------------------------------------------------------===//
1823 //                             Rules to match Modules
1824 //===----------------------------------------------------------------------===//
1825
1826 // Module rule: Capture the result of parsing the whole file into a result
1827 // variable...
1828 //
1829 Module 
1830   : DefinitionList {
1831     $$ = ParserResult = CurModule.CurrentModule;
1832     CurModule.ModuleDone();
1833     CHECK_FOR_ERROR;
1834   }
1835   | /*empty*/ {
1836     $$ = ParserResult = CurModule.CurrentModule;
1837     CurModule.ModuleDone();
1838     CHECK_FOR_ERROR;
1839   }
1840   ;
1841
1842 DefinitionList
1843   : Definition
1844   | DefinitionList Definition
1845   ;
1846
1847 Definition 
1848   : DEFINE { CurFun.isDeclare = false } Function {
1849     CurFun.FunctionDone();
1850     CHECK_FOR_ERROR
1851   }
1852   | DECLARE { CurFun.isDeclare = true; } FunctionProto {
1853     CHECK_FOR_ERROR
1854   }
1855   | MODULE ASM_TOK AsmBlock {
1856     CHECK_FOR_ERROR
1857   }  
1858   | IMPLEMENTATION {
1859     // Emit an error if there are any unresolved types left.
1860     if (!CurModule.LateResolveTypes.empty()) {
1861       const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1862       if (DID.Type == ValID::NameVal) {
1863         GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1864       } else {
1865         GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1866       }
1867     }
1868     CHECK_FOR_ERROR
1869   }
1870   | OptAssign TYPE Types {
1871     if (!UpRefs.empty())
1872       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1873     // Eagerly resolve types.  This is not an optimization, this is a
1874     // requirement that is due to the fact that we could have this:
1875     //
1876     // %list = type { %list * }
1877     // %list = type { %list * }    ; repeated type decl
1878     //
1879     // If types are not resolved eagerly, then the two types will not be
1880     // determined to be the same type!
1881     //
1882     ResolveTypeTo($1, *$3);
1883
1884     if (!setTypeName(*$3, $1) && !$1) {
1885       CHECK_FOR_ERROR
1886       // If this is a named type that is not a redefinition, add it to the slot
1887       // table.
1888       CurModule.Types.push_back(*$3);
1889     }
1890
1891     delete $3;
1892     CHECK_FOR_ERROR
1893   }
1894   | OptAssign TYPE VOID {
1895     ResolveTypeTo($1, $3);
1896
1897     if (!setTypeName($3, $1) && !$1) {
1898       CHECK_FOR_ERROR
1899       // If this is a named type that is not a redefinition, add it to the slot
1900       // table.
1901       CurModule.Types.push_back($3);
1902     }
1903     CHECK_FOR_ERROR
1904   }
1905   | OptAssign GVVisibilityStyle GlobalType ConstVal { /* "Externally Visible" Linkage */
1906     if ($4 == 0) 
1907       GEN_ERROR("Global value initializer is not a constant!");
1908     CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
1909                                 $2, $3, $4->getType(), $4);
1910     CHECK_FOR_ERROR
1911   } GlobalVarAttributes {
1912     CurGV = 0;
1913   }
1914   | OptAssign GVInternalLinkage GVVisibilityStyle GlobalType ConstVal {
1915     if ($5 == 0) 
1916       GEN_ERROR("Global value initializer is not a constant!");
1917     CurGV = ParseGlobalVariable($1, $2, $3, $4, $5->getType(), $5);
1918     CHECK_FOR_ERROR
1919   } GlobalVarAttributes {
1920     CurGV = 0;
1921   }
1922   | OptAssign GVExternalLinkage GVVisibilityStyle GlobalType Types {
1923     if (!UpRefs.empty())
1924       GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1925     CurGV = ParseGlobalVariable($1, $2, $3, $4, *$5, 0);
1926     CHECK_FOR_ERROR
1927     delete $5;
1928   } GlobalVarAttributes {
1929     CurGV = 0;
1930     CHECK_FOR_ERROR
1931   }
1932   | TARGET TargetDefinition { 
1933     CHECK_FOR_ERROR
1934   }
1935   | DEPLIBS '=' LibrariesDefinition {
1936     CHECK_FOR_ERROR
1937   }
1938   ;
1939
1940
1941 AsmBlock : STRINGCONSTANT {
1942   const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1943   char *EndStr = UnEscapeLexed($1, true);
1944   std::string NewAsm($1, EndStr);
1945   free($1);
1946
1947   if (AsmSoFar.empty())
1948     CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1949   else
1950     CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1951   CHECK_FOR_ERROR
1952 };
1953
1954 BigOrLittle : BIG    { $$ = Module::BigEndian; };
1955 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1956
1957 TargetDefinition : ENDIAN '=' BigOrLittle {
1958     CurModule.CurrentModule->setEndianness($3);
1959     CHECK_FOR_ERROR
1960   }
1961   | POINTERSIZE '=' EUINT64VAL {
1962     if ($3 == 32)
1963       CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1964     else if ($3 == 64)
1965       CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1966     else
1967       GEN_ERROR("Invalid pointer size: '" + utostr($3) + "'!");
1968     CHECK_FOR_ERROR
1969   }
1970   | TRIPLE '=' STRINGCONSTANT {
1971     CurModule.CurrentModule->setTargetTriple($3);
1972     free($3);
1973   }
1974   | DATALAYOUT '=' STRINGCONSTANT {
1975     CurModule.CurrentModule->setDataLayout($3);
1976     free($3);
1977   };
1978
1979 LibrariesDefinition : '[' LibList ']';
1980
1981 LibList : LibList ',' STRINGCONSTANT {
1982           CurModule.CurrentModule->addLibrary($3);
1983           free($3);
1984           CHECK_FOR_ERROR
1985         }
1986         | STRINGCONSTANT {
1987           CurModule.CurrentModule->addLibrary($1);
1988           free($1);
1989           CHECK_FOR_ERROR
1990         }
1991         | /* empty: end of list */ {
1992           CHECK_FOR_ERROR
1993         }
1994         ;
1995
1996 //===----------------------------------------------------------------------===//
1997 //                       Rules to match Function Headers
1998 //===----------------------------------------------------------------------===//
1999
2000 Name : VAR_ID | STRINGCONSTANT;
2001 OptName : Name | /*empty*/ { $$ = 0; };
2002
2003 ArgListH : ArgListH ',' Types OptParamAttrs OptName {
2004     if (!UpRefs.empty())
2005       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2006     if (*$3 == Type::VoidTy)
2007       GEN_ERROR("void typed arguments are invalid!");
2008     ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2009     $$ = $1;
2010     $1->push_back(E);
2011     CHECK_FOR_ERROR
2012   }
2013   | Types OptParamAttrs OptName {
2014     if (!UpRefs.empty())
2015       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2016     if (*$1 == Type::VoidTy)
2017       GEN_ERROR("void typed arguments are invalid!");
2018     ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2019     $$ = new ArgListType;
2020     $$->push_back(E);
2021     CHECK_FOR_ERROR
2022   };
2023
2024 ArgList : ArgListH {
2025     $$ = $1;
2026     CHECK_FOR_ERROR
2027   }
2028   | ArgListH ',' DOTDOTDOT {
2029     $$ = $1;
2030     struct ArgListEntry E;
2031     E.Ty = new PATypeHolder(Type::VoidTy);
2032     E.Name = 0;
2033     E.Attrs = FunctionType::NoAttributeSet;
2034     $$->push_back(E);
2035     CHECK_FOR_ERROR
2036   }
2037   | DOTDOTDOT {
2038     $$ = new ArgListType;
2039     struct ArgListEntry E;
2040     E.Ty = new PATypeHolder(Type::VoidTy);
2041     E.Name = 0;
2042     E.Attrs = FunctionType::NoAttributeSet;
2043     $$->push_back(E);
2044     CHECK_FOR_ERROR
2045   }
2046   | /* empty */ {
2047     $$ = 0;
2048     CHECK_FOR_ERROR
2049   };
2050
2051 FunctionHeaderH : OptCallingConv ResultTypes Name '(' ArgList ')' 
2052                   OptFuncAttrs OptSection OptAlign {
2053   UnEscapeLexed($3);
2054   std::string FunctionName($3);
2055   free($3);  // Free strdup'd memory!
2056   
2057   // Check the function result for abstractness if this is a define. We should
2058   // have no abstract types at this point
2059   if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2060     GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2061
2062   std::vector<const Type*> ParamTypeList;
2063   std::vector<FunctionType::ParameterAttributes> ParamAttrs;
2064   ParamAttrs.push_back($7);
2065   if ($5) {   // If there are arguments...
2066     for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I) {
2067       const Type* Ty = I->Ty->get();
2068       if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2069         GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2070       ParamTypeList.push_back(Ty);
2071       if (Ty != Type::VoidTy)
2072         ParamAttrs.push_back(I->Attrs);
2073     }
2074   }
2075
2076   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2077   if (isVarArg) ParamTypeList.pop_back();
2078
2079   FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg,
2080                                        ParamAttrs);
2081   const PointerType *PFT = PointerType::get(FT);
2082   delete $2;
2083
2084   ValID ID;
2085   if (!FunctionName.empty()) {
2086     ID = ValID::create((char*)FunctionName.c_str());
2087   } else {
2088     ID = ValID::create((int)CurModule.Values[PFT].size());
2089   }
2090
2091   Function *Fn = 0;
2092   // See if this function was forward referenced.  If so, recycle the object.
2093   if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2094     // Move the function to the end of the list, from whereever it was 
2095     // previously inserted.
2096     Fn = cast<Function>(FWRef);
2097     CurModule.CurrentModule->getFunctionList().remove(Fn);
2098     CurModule.CurrentModule->getFunctionList().push_back(Fn);
2099   } else if (!FunctionName.empty() &&     // Merge with an earlier prototype?
2100              (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2101     // If this is the case, either we need to be a forward decl, or it needs 
2102     // to be.
2103     if (!CurFun.isDeclare && !Fn->isExternal())
2104       GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
2105     
2106     // Make sure to strip off any argument names so we can't get conflicts.
2107     if (Fn->isExternal())
2108       for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2109            AI != AE; ++AI)
2110         AI->setName("");
2111   } else  {  // Not already defined?
2112     Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2113                       CurModule.CurrentModule);
2114
2115     InsertValue(Fn, CurModule.Values);
2116   }
2117
2118   CurFun.FunctionStart(Fn);
2119
2120   if (CurFun.isDeclare) {
2121     // If we have declaration, always overwrite linkage.  This will allow us to
2122     // correctly handle cases, when pointer to function is passed as argument to
2123     // another function.
2124     Fn->setLinkage(CurFun.Linkage);
2125     Fn->setVisibility(CurFun.Visibility);
2126   }
2127   Fn->setCallingConv($1);
2128   Fn->setAlignment($9);
2129   if ($8) {
2130     Fn->setSection($8);
2131     free($8);
2132   }
2133
2134   // Add all of the arguments we parsed to the function...
2135   if ($5) {                     // Is null if empty...
2136     if (isVarArg) {  // Nuke the last entry
2137       assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0&&
2138              "Not a varargs marker!");
2139       delete $5->back().Ty;
2140       $5->pop_back();  // Delete the last entry
2141     }
2142     Function::arg_iterator ArgIt = Fn->arg_begin();
2143     unsigned Idx = 1;
2144     for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++ArgIt) {
2145       delete I->Ty;                          // Delete the typeholder...
2146       setValueName(ArgIt, I->Name);           // Insert arg into symtab...
2147       CHECK_FOR_ERROR
2148       InsertValue(ArgIt);
2149       Idx++;
2150     }
2151
2152     delete $5;                     // We're now done with the argument list
2153   }
2154   CHECK_FOR_ERROR
2155 };
2156
2157 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
2158
2159 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2160   $$ = CurFun.CurrentFunction;
2161
2162   // Make sure that we keep track of the linkage type even if there was a
2163   // previous "declare".
2164   $$->setLinkage($1);
2165   $$->setVisibility($2);
2166 };
2167
2168 END : ENDTOK | '}';                    // Allow end of '}' to end a function
2169
2170 Function : BasicBlockList END {
2171   $$ = $1;
2172   CHECK_FOR_ERROR
2173 };
2174
2175 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2176     CurFun.CurrentFunction->setLinkage($1);
2177     CurFun.CurrentFunction->setVisibility($2);
2178     $$ = CurFun.CurrentFunction;
2179     CurFun.FunctionDone();
2180     CHECK_FOR_ERROR
2181   };
2182
2183 //===----------------------------------------------------------------------===//
2184 //                        Rules to match Basic Blocks
2185 //===----------------------------------------------------------------------===//
2186
2187 OptSideEffect : /* empty */ {
2188     $$ = false;
2189     CHECK_FOR_ERROR
2190   }
2191   | SIDEEFFECT {
2192     $$ = true;
2193     CHECK_FOR_ERROR
2194   };
2195
2196 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
2197     $$ = ValID::create($1);
2198     CHECK_FOR_ERROR
2199   }
2200   | EUINT64VAL {
2201     $$ = ValID::create($1);
2202     CHECK_FOR_ERROR
2203   }
2204   | FPVAL {                     // Perhaps it's an FP constant?
2205     $$ = ValID::create($1);
2206     CHECK_FOR_ERROR
2207   }
2208   | TRUETOK {
2209     $$ = ValID::create(ConstantInt::getTrue());
2210     CHECK_FOR_ERROR
2211   } 
2212   | FALSETOK {
2213     $$ = ValID::create(ConstantInt::getFalse());
2214     CHECK_FOR_ERROR
2215   }
2216   | NULL_TOK {
2217     $$ = ValID::createNull();
2218     CHECK_FOR_ERROR
2219   }
2220   | UNDEF {
2221     $$ = ValID::createUndef();
2222     CHECK_FOR_ERROR
2223   }
2224   | ZEROINITIALIZER {     // A vector zero constant.
2225     $$ = ValID::createZeroInit();
2226     CHECK_FOR_ERROR
2227   }
2228   | '<' ConstVector '>' { // Nonempty unsized packed vector
2229     const Type *ETy = (*$2)[0]->getType();
2230     int NumElements = $2->size(); 
2231     
2232     PackedType* pt = PackedType::get(ETy, NumElements);
2233     PATypeHolder* PTy = new PATypeHolder(
2234                                          HandleUpRefs(
2235                                             PackedType::get(
2236                                                 ETy, 
2237                                                 NumElements)
2238                                             )
2239                                          );
2240     
2241     // Verify all elements are correct type!
2242     for (unsigned i = 0; i < $2->size(); i++) {
2243       if (ETy != (*$2)[i]->getType())
2244         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
2245                      ETy->getDescription() +"' as required!\nIt is of type '" +
2246                      (*$2)[i]->getType()->getDescription() + "'.");
2247     }
2248
2249     $$ = ValID::create(ConstantPacked::get(pt, *$2));
2250     delete PTy; delete $2;
2251     CHECK_FOR_ERROR
2252   }
2253   | ConstExpr {
2254     $$ = ValID::create($1);
2255     CHECK_FOR_ERROR
2256   }
2257   | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2258     char *End = UnEscapeLexed($3, true);
2259     std::string AsmStr = std::string($3, End);
2260     End = UnEscapeLexed($5, true);
2261     std::string Constraints = std::string($5, End);
2262     $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2263     free($3);
2264     free($5);
2265     CHECK_FOR_ERROR
2266   };
2267
2268 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2269 // another value.
2270 //
2271 SymbolicValueRef : INTVAL {  // Is it an integer reference...?
2272     $$ = ValID::create($1);
2273     CHECK_FOR_ERROR
2274   }
2275   | Name {                   // Is it a named reference...?
2276     $$ = ValID::create($1);
2277     CHECK_FOR_ERROR
2278   };
2279
2280 // ValueRef - A reference to a definition... either constant or symbolic
2281 ValueRef : SymbolicValueRef | ConstValueRef;
2282
2283
2284 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
2285 // type immediately preceeds the value reference, and allows complex constant
2286 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2287 ResolvedVal : Types ValueRef {
2288     if (!UpRefs.empty())
2289       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2290     $$ = getVal(*$1, $2); 
2291     delete $1;
2292     CHECK_FOR_ERROR
2293   }
2294   ;
2295
2296 BasicBlockList : BasicBlockList BasicBlock {
2297     $$ = $1;
2298     CHECK_FOR_ERROR
2299   }
2300   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
2301     $$ = $1;
2302     CHECK_FOR_ERROR
2303   };
2304
2305
2306 // Basic blocks are terminated by branching instructions: 
2307 // br, br/cc, switch, ret
2308 //
2309 BasicBlock : InstructionList OptAssign BBTerminatorInst  {
2310     setValueName($3, $2);
2311     CHECK_FOR_ERROR
2312     InsertValue($3);
2313
2314     $1->getInstList().push_back($3);
2315     InsertValue($1);
2316     $$ = $1;
2317     CHECK_FOR_ERROR
2318   };
2319
2320 InstructionList : InstructionList Inst {
2321     if (CastInst *CI1 = dyn_cast<CastInst>($2))
2322       if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2323         if (CI2->getParent() == 0)
2324           $1->getInstList().push_back(CI2);
2325     $1->getInstList().push_back($2);
2326     $$ = $1;
2327     CHECK_FOR_ERROR
2328   }
2329   | /* empty */ {
2330     $$ = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2331     CHECK_FOR_ERROR
2332
2333     // Make sure to move the basic block to the correct location in the
2334     // function, instead of leaving it inserted wherever it was first
2335     // referenced.
2336     Function::BasicBlockListType &BBL = 
2337       CurFun.CurrentFunction->getBasicBlockList();
2338     BBL.splice(BBL.end(), BBL, $$);
2339     CHECK_FOR_ERROR
2340   }
2341   | LABELSTR {
2342     $$ = getBBVal(ValID::create($1), true);
2343     CHECK_FOR_ERROR
2344
2345     // Make sure to move the basic block to the correct location in the
2346     // function, instead of leaving it inserted wherever it was first
2347     // referenced.
2348     Function::BasicBlockListType &BBL = 
2349       CurFun.CurrentFunction->getBasicBlockList();
2350     BBL.splice(BBL.end(), BBL, $$);
2351     CHECK_FOR_ERROR
2352   };
2353
2354 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
2355     $$ = new ReturnInst($2);
2356     CHECK_FOR_ERROR
2357   }
2358   | RET VOID {                                       // Return with no result...
2359     $$ = new ReturnInst();
2360     CHECK_FOR_ERROR
2361   }
2362   | BR LABEL ValueRef {                         // Unconditional Branch...
2363     BasicBlock* tmpBB = getBBVal($3);
2364     CHECK_FOR_ERROR
2365     $$ = new BranchInst(tmpBB);
2366   }                                                  // Conditional Branch...
2367   | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
2368     assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2369     BasicBlock* tmpBBA = getBBVal($6);
2370     CHECK_FOR_ERROR
2371     BasicBlock* tmpBBB = getBBVal($9);
2372     CHECK_FOR_ERROR
2373     Value* tmpVal = getVal(Type::Int1Ty, $3);
2374     CHECK_FOR_ERROR
2375     $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2376   }
2377   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2378     Value* tmpVal = getVal($2, $3);
2379     CHECK_FOR_ERROR
2380     BasicBlock* tmpBB = getBBVal($6);
2381     CHECK_FOR_ERROR
2382     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2383     $$ = S;
2384
2385     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2386       E = $8->end();
2387     for (; I != E; ++I) {
2388       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2389           S->addCase(CI, I->second);
2390       else
2391         GEN_ERROR("Switch case is constant, but not a simple integer!");
2392     }
2393     delete $8;
2394     CHECK_FOR_ERROR
2395   }
2396   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2397     Value* tmpVal = getVal($2, $3);
2398     CHECK_FOR_ERROR
2399     BasicBlock* tmpBB = getBBVal($6);
2400     CHECK_FOR_ERROR
2401     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2402     $$ = S;
2403     CHECK_FOR_ERROR
2404   }
2405   | INVOKE OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' OptFuncAttrs
2406     TO LABEL ValueRef UNWIND LABEL ValueRef {
2407
2408     // Handle the short syntax
2409     const PointerType *PFTy = 0;
2410     const FunctionType *Ty = 0;
2411     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2412         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2413       // Pull out the types of all of the arguments...
2414       std::vector<const Type*> ParamTypes;
2415       FunctionType::ParamAttrsList ParamAttrs;
2416       ParamAttrs.push_back($8);
2417       for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2418         const Type *Ty = I->Val->getType();
2419         if (Ty == Type::VoidTy)
2420           GEN_ERROR("Short call syntax cannot be used with varargs");
2421         ParamTypes.push_back(Ty);
2422         ParamAttrs.push_back(I->Attrs);
2423       }
2424
2425       Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2426       PFTy = PointerType::get(Ty);
2427     }
2428
2429     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2430     CHECK_FOR_ERROR
2431     BasicBlock *Normal = getBBVal($11);
2432     CHECK_FOR_ERROR
2433     BasicBlock *Except = getBBVal($14);
2434     CHECK_FOR_ERROR
2435
2436     // Check the arguments
2437     ValueList Args;
2438     if ($6->empty()) {                                   // Has no arguments?
2439       // Make sure no arguments is a good thing!
2440       if (Ty->getNumParams() != 0)
2441         GEN_ERROR("No arguments passed to a function that "
2442                        "expects arguments!");
2443     } else {                                     // Has arguments?
2444       // Loop through FunctionType's arguments and ensure they are specified
2445       // correctly!
2446       FunctionType::param_iterator I = Ty->param_begin();
2447       FunctionType::param_iterator E = Ty->param_end();
2448       ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2449
2450       for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2451         if (ArgI->Val->getType() != *I)
2452           GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2453                          (*I)->getDescription() + "'!");
2454         Args.push_back(ArgI->Val);
2455       }
2456
2457       if (Ty->isVarArg()) {
2458         if (I == E)
2459           for (; ArgI != ArgE; ++ArgI)
2460             Args.push_back(ArgI->Val); // push the remaining varargs
2461       } else if (I != E || ArgI != ArgE)
2462         GEN_ERROR("Invalid number of parameters detected!");
2463     }
2464
2465     // Create the InvokeInst
2466     InvokeInst *II = new InvokeInst(V, Normal, Except, Args);
2467     II->setCallingConv($2);
2468     $$ = II;
2469     delete $6;
2470     CHECK_FOR_ERROR
2471   }
2472   | UNWIND {
2473     $$ = new UnwindInst();
2474     CHECK_FOR_ERROR
2475   }
2476   | UNREACHABLE {
2477     $$ = new UnreachableInst();
2478     CHECK_FOR_ERROR
2479   };
2480
2481
2482
2483 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2484     $$ = $1;
2485     Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2486     CHECK_FOR_ERROR
2487     if (V == 0)
2488       GEN_ERROR("May only switch on a constant pool value!");
2489
2490     BasicBlock* tmpBB = getBBVal($6);
2491     CHECK_FOR_ERROR
2492     $$->push_back(std::make_pair(V, tmpBB));
2493   }
2494   | IntType ConstValueRef ',' LABEL ValueRef {
2495     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2496     Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2497     CHECK_FOR_ERROR
2498
2499     if (V == 0)
2500       GEN_ERROR("May only switch on a constant pool value!");
2501
2502     BasicBlock* tmpBB = getBBVal($5);
2503     CHECK_FOR_ERROR
2504     $$->push_back(std::make_pair(V, tmpBB)); 
2505   };
2506
2507 Inst : OptAssign InstVal {
2508   // Is this definition named?? if so, assign the name...
2509   setValueName($2, $1);
2510   CHECK_FOR_ERROR
2511   InsertValue($2);
2512   $$ = $2;
2513   CHECK_FOR_ERROR
2514 };
2515
2516 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
2517     if (!UpRefs.empty())
2518       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2519     $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2520     Value* tmpVal = getVal(*$1, $3);
2521     CHECK_FOR_ERROR
2522     BasicBlock* tmpBB = getBBVal($5);
2523     CHECK_FOR_ERROR
2524     $$->push_back(std::make_pair(tmpVal, tmpBB));
2525     delete $1;
2526   }
2527   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2528     $$ = $1;
2529     Value* tmpVal = getVal($1->front().first->getType(), $4);
2530     CHECK_FOR_ERROR
2531     BasicBlock* tmpBB = getBBVal($6);
2532     CHECK_FOR_ERROR
2533     $1->push_back(std::make_pair(tmpVal, tmpBB));
2534   };
2535
2536
2537 ValueRefList : Types ValueRef OptParamAttrs {    
2538     if (!UpRefs.empty())
2539       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2540     // Used for call and invoke instructions
2541     $$ = new ValueRefList();
2542     ValueRefListEntry E; E.Attrs = $3; E.Val = getVal($1->get(), $2);
2543     $$->push_back(E);
2544   }
2545   | ValueRefList ',' Types ValueRef OptParamAttrs {
2546     if (!UpRefs.empty())
2547       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2548     $$ = $1;
2549     ValueRefListEntry E; E.Attrs = $5; E.Val = getVal($3->get(), $4);
2550     $$->push_back(E);
2551     CHECK_FOR_ERROR
2552   }
2553   | /*empty*/ { $$ = new ValueRefList(); };
2554
2555 IndexList       // Used for gep instructions and constant expressions
2556   : /*empty*/ { $$ = new std::vector<Value*>(); }
2557   | IndexList ',' ResolvedVal {
2558     $$ = $1;
2559     $$->push_back($3);
2560     CHECK_FOR_ERROR
2561   }
2562   ;
2563
2564 OptTailCall : TAIL CALL {
2565     $$ = true;
2566     CHECK_FOR_ERROR
2567   }
2568   | CALL {
2569     $$ = false;
2570     CHECK_FOR_ERROR
2571   };
2572
2573 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2574     if (!UpRefs.empty())
2575       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2576     if (!(*$2)->isIntegral() && !(*$2)->isFloatingPoint() && 
2577         !isa<PackedType>((*$2).get()))
2578       GEN_ERROR(
2579         "Arithmetic operator requires integer, FP, or packed operands!");
2580     if (isa<PackedType>((*$2).get()) && 
2581         ($1 == Instruction::URem || 
2582          $1 == Instruction::SRem ||
2583          $1 == Instruction::FRem))
2584       GEN_ERROR("U/S/FRem not supported on packed types!");
2585     Value* val1 = getVal(*$2, $3); 
2586     CHECK_FOR_ERROR
2587     Value* val2 = getVal(*$2, $5);
2588     CHECK_FOR_ERROR
2589     $$ = BinaryOperator::create($1, val1, val2);
2590     if ($$ == 0)
2591       GEN_ERROR("binary operator returned null!");
2592     delete $2;
2593   }
2594   | LogicalOps Types ValueRef ',' ValueRef {
2595     if (!UpRefs.empty())
2596       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2597     if (!(*$2)->isIntegral()) {
2598       if (!isa<PackedType>($2->get()) ||
2599           !cast<PackedType>($2->get())->getElementType()->isIntegral())
2600         GEN_ERROR("Logical operator requires integral operands!");
2601     }
2602     Value* tmpVal1 = getVal(*$2, $3);
2603     CHECK_FOR_ERROR
2604     Value* tmpVal2 = getVal(*$2, $5);
2605     CHECK_FOR_ERROR
2606     $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2607     if ($$ == 0)
2608       GEN_ERROR("binary operator returned null!");
2609     delete $2;
2610   }
2611   | ICMP IPredicates Types ValueRef ',' ValueRef  {
2612     if (!UpRefs.empty())
2613       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2614     if (isa<PackedType>((*$3).get()))
2615       GEN_ERROR("Packed types not supported by icmp instruction");
2616     Value* tmpVal1 = getVal(*$3, $4);
2617     CHECK_FOR_ERROR
2618     Value* tmpVal2 = getVal(*$3, $6);
2619     CHECK_FOR_ERROR
2620     $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2621     if ($$ == 0)
2622       GEN_ERROR("icmp operator returned null!");
2623   }
2624   | FCMP FPredicates Types ValueRef ',' ValueRef  {
2625     if (!UpRefs.empty())
2626       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2627     if (isa<PackedType>((*$3).get()))
2628       GEN_ERROR("Packed types not supported by fcmp instruction");
2629     Value* tmpVal1 = getVal(*$3, $4);
2630     CHECK_FOR_ERROR
2631     Value* tmpVal2 = getVal(*$3, $6);
2632     CHECK_FOR_ERROR
2633     $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2634     if ($$ == 0)
2635       GEN_ERROR("fcmp operator returned null!");
2636   }
2637   | ShiftOps ResolvedVal ',' ResolvedVal {
2638     if ($4->getType() != Type::Int8Ty)
2639       GEN_ERROR("Shift amount must be i8 type!");
2640     if (!$2->getType()->isIntegral())
2641       GEN_ERROR("Shift constant expression requires integer operand!");
2642     CHECK_FOR_ERROR;
2643     $$ = new ShiftInst($1, $2, $4);
2644     CHECK_FOR_ERROR
2645   }
2646   | CastOps ResolvedVal TO Types {
2647     if (!UpRefs.empty())
2648       GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2649     Value* Val = $2;
2650     const Type* Ty = $4->get();
2651     if (!Val->getType()->isFirstClassType())
2652       GEN_ERROR("cast from a non-primitive type: '" +
2653                 Val->getType()->getDescription() + "'!");
2654     if (!Ty->isFirstClassType())
2655       GEN_ERROR("cast to a non-primitive type: '" + Ty->getDescription() +"'!");
2656     $$ = CastInst::create($1, Val, $4->get());
2657     delete $4;
2658   }
2659   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2660     if ($2->getType() != Type::Int1Ty)
2661       GEN_ERROR("select condition must be boolean!");
2662     if ($4->getType() != $6->getType())
2663       GEN_ERROR("select value types should match!");
2664     $$ = new SelectInst($2, $4, $6);
2665     CHECK_FOR_ERROR
2666   }
2667   | VAARG ResolvedVal ',' Types {
2668     if (!UpRefs.empty())
2669       GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2670     $$ = new VAArgInst($2, *$4);
2671     delete $4;
2672     CHECK_FOR_ERROR
2673   }
2674   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2675     if (!ExtractElementInst::isValidOperands($2, $4))
2676       GEN_ERROR("Invalid extractelement operands!");
2677     $$ = new ExtractElementInst($2, $4);
2678     CHECK_FOR_ERROR
2679   }
2680   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2681     if (!InsertElementInst::isValidOperands($2, $4, $6))
2682       GEN_ERROR("Invalid insertelement operands!");
2683     $$ = new InsertElementInst($2, $4, $6);
2684     CHECK_FOR_ERROR
2685   }
2686   | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2687     if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2688       GEN_ERROR("Invalid shufflevector operands!");
2689     $$ = new ShuffleVectorInst($2, $4, $6);
2690     CHECK_FOR_ERROR
2691   }
2692   | PHI_TOK PHIList {
2693     const Type *Ty = $2->front().first->getType();
2694     if (!Ty->isFirstClassType())
2695       GEN_ERROR("PHI node operands must be of first class type!");
2696     $$ = new PHINode(Ty);
2697     ((PHINode*)$$)->reserveOperandSpace($2->size());
2698     while ($2->begin() != $2->end()) {
2699       if ($2->front().first->getType() != Ty) 
2700         GEN_ERROR("All elements of a PHI node must be of the same type!");
2701       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2702       $2->pop_front();
2703     }
2704     delete $2;  // Free the list...
2705     CHECK_FOR_ERROR
2706   }
2707   | OptTailCall OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' 
2708     OptFuncAttrs {
2709
2710     // Handle the short syntax
2711     const PointerType *PFTy = 0;
2712     const FunctionType *Ty = 0;
2713     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2714         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2715       // Pull out the types of all of the arguments...
2716       std::vector<const Type*> ParamTypes;
2717       FunctionType::ParamAttrsList ParamAttrs;
2718       ParamAttrs.push_back($8);
2719       for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2720         const Type *Ty = I->Val->getType();
2721         if (Ty == Type::VoidTy)
2722           GEN_ERROR("Short call syntax cannot be used with varargs");
2723         ParamTypes.push_back(Ty);
2724         ParamAttrs.push_back(I->Attrs);
2725       }
2726
2727       Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2728       PFTy = PointerType::get(Ty);
2729     }
2730
2731     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2732     CHECK_FOR_ERROR
2733
2734     // Check the arguments 
2735     ValueList Args;
2736     if ($6->empty()) {                                   // Has no arguments?
2737       // Make sure no arguments is a good thing!
2738       if (Ty->getNumParams() != 0)
2739         GEN_ERROR("No arguments passed to a function that "
2740                        "expects arguments!");
2741     } else {                                     // Has arguments?
2742       // Loop through FunctionType's arguments and ensure they are specified
2743       // correctly!
2744       //
2745       FunctionType::param_iterator I = Ty->param_begin();
2746       FunctionType::param_iterator E = Ty->param_end();
2747       ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2748
2749       for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2750         if (ArgI->Val->getType() != *I)
2751           GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2752                          (*I)->getDescription() + "'!");
2753         Args.push_back(ArgI->Val);
2754       }
2755       if (Ty->isVarArg()) {
2756         if (I == E)
2757           for (; ArgI != ArgE; ++ArgI)
2758             Args.push_back(ArgI->Val); // push the remaining varargs
2759       } else if (I != E || ArgI != ArgE)
2760         GEN_ERROR("Invalid number of parameters detected!");
2761     }
2762     // Create the call node
2763     CallInst *CI = new CallInst(V, Args);
2764     CI->setTailCall($1);
2765     CI->setCallingConv($2);
2766     $$ = CI;
2767     delete $6;
2768     CHECK_FOR_ERROR
2769   }
2770   | MemoryInst {
2771     $$ = $1;
2772     CHECK_FOR_ERROR
2773   };
2774
2775 OptVolatile : VOLATILE {
2776     $$ = true;
2777     CHECK_FOR_ERROR
2778   }
2779   | /* empty */ {
2780     $$ = false;
2781     CHECK_FOR_ERROR
2782   };
2783
2784
2785
2786 MemoryInst : MALLOC Types OptCAlign {
2787     if (!UpRefs.empty())
2788       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2789     $$ = new MallocInst(*$2, 0, $3);
2790     delete $2;
2791     CHECK_FOR_ERROR
2792   }
2793   | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
2794     if (!UpRefs.empty())
2795       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2796     Value* tmpVal = getVal($4, $5);
2797     CHECK_FOR_ERROR
2798     $$ = new MallocInst(*$2, tmpVal, $6);
2799     delete $2;
2800   }
2801   | ALLOCA Types OptCAlign {
2802     if (!UpRefs.empty())
2803       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2804     $$ = new AllocaInst(*$2, 0, $3);
2805     delete $2;
2806     CHECK_FOR_ERROR
2807   }
2808   | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
2809     if (!UpRefs.empty())
2810       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2811     Value* tmpVal = getVal($4, $5);
2812     CHECK_FOR_ERROR
2813     $$ = new AllocaInst(*$2, tmpVal, $6);
2814     delete $2;
2815   }
2816   | FREE ResolvedVal {
2817     if (!isa<PointerType>($2->getType()))
2818       GEN_ERROR("Trying to free nonpointer type " + 
2819                      $2->getType()->getDescription() + "!");
2820     $$ = new FreeInst($2);
2821     CHECK_FOR_ERROR
2822   }
2823
2824   | OptVolatile LOAD Types ValueRef {
2825     if (!UpRefs.empty())
2826       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2827     if (!isa<PointerType>($3->get()))
2828       GEN_ERROR("Can't load from nonpointer type: " +
2829                      (*$3)->getDescription());
2830     if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2831       GEN_ERROR("Can't load from pointer of non-first-class type: " +
2832                      (*$3)->getDescription());
2833     Value* tmpVal = getVal(*$3, $4);
2834     CHECK_FOR_ERROR
2835     $$ = new LoadInst(tmpVal, "", $1);
2836     delete $3;
2837   }
2838   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2839     if (!UpRefs.empty())
2840       GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
2841     const PointerType *PT = dyn_cast<PointerType>($5->get());
2842     if (!PT)
2843       GEN_ERROR("Can't store to a nonpointer type: " +
2844                      (*$5)->getDescription());
2845     const Type *ElTy = PT->getElementType();
2846     if (ElTy != $3->getType())
2847       GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2848                      "' into space of type '" + ElTy->getDescription() + "'!");
2849
2850     Value* tmpVal = getVal(*$5, $6);
2851     CHECK_FOR_ERROR
2852     $$ = new StoreInst($3, tmpVal, $1);
2853     delete $5;
2854   }
2855   | GETELEMENTPTR Types ValueRef IndexList {
2856     if (!UpRefs.empty())
2857       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2858     if (!isa<PointerType>($2->get()))
2859       GEN_ERROR("getelementptr insn requires pointer operand!");
2860
2861     if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2862       GEN_ERROR("Invalid getelementptr indices for type '" +
2863                      (*$2)->getDescription()+ "'!");
2864     Value* tmpVal = getVal(*$2, $3);
2865     CHECK_FOR_ERROR
2866     $$ = new GetElementPtrInst(tmpVal, *$4);
2867     delete $2; 
2868     delete $4;
2869   };
2870
2871
2872 %%
2873
2874 // common code from the two 'RunVMAsmParser' functions
2875 static Module* RunParser(Module * M) {
2876
2877   llvmAsmlineno = 1;      // Reset the current line number...
2878   CurModule.CurrentModule = M;
2879 #if YYDEBUG
2880   yydebug = Debug;
2881 #endif
2882
2883   // Check to make sure the parser succeeded
2884   if (yyparse()) {
2885     if (ParserResult)
2886       delete ParserResult;
2887     return 0;
2888   }
2889
2890   // Check to make sure that parsing produced a result
2891   if (!ParserResult)
2892     return 0;
2893
2894   // Reset ParserResult variable while saving its value for the result.
2895   Module *Result = ParserResult;
2896   ParserResult = 0;
2897
2898   return Result;
2899 }
2900
2901 void llvm::GenerateError(const std::string &message, int LineNo) {
2902   if (LineNo == -1) LineNo = llvmAsmlineno;
2903   // TODO: column number in exception
2904   if (TheParseError)
2905     TheParseError->setError(CurFilename, message, LineNo);
2906   TriggerError = 1;
2907 }
2908
2909 int yyerror(const char *ErrorMsg) {
2910   std::string where 
2911     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2912                   + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2913   std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2914   if (yychar == YYEMPTY || yychar == 0)
2915     errMsg += "end-of-file.";
2916   else
2917     errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2918   GenerateError(errMsg);
2919   return 0;
2920 }