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