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