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