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