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