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