Add breaks
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Instructions.h"
17 #include "llvm/Module.h"
18 #include "llvm/SymbolTable.h"
19 #include "llvm/Support/GetElementPtrTypeIterator.h"
20 #include "Support/STLExtras.h"
21 #include <algorithm>
22 #include <iostream>
23 #include <list>
24 #include <utility>
25
26 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
27 int yylex();                       // declaration" of xxx warnings.
28 int yyparse();
29
30 namespace llvm {
31   std::string CurFilename;
32 }
33 using namespace llvm;
34
35 static Module *ParserResult;
36
37 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
38 // relating to upreferences in the input stream.
39 //
40 //#define DEBUG_UPREFS 1
41 #ifdef DEBUG_UPREFS
42 #define UR_OUT(X) std::cerr << X
43 #else
44 #define UR_OUT(X)
45 #endif
46
47 #define YYERROR_VERBOSE 1
48
49 // HACK ALERT: This variable is used to implement the automatic conversion of
50 // variable argument instructions from their old to new forms.  When this
51 // compatiblity "Feature" is removed, this should be too.
52 //
53 static BasicBlock *CurBB;
54 static bool ObsoleteVarArgs;
55
56
57 // This contains info used when building the body of a function.  It is
58 // destroyed when the function is completed.
59 //
60 typedef std::vector<Value *> ValueList;           // Numbered defs
61 static void ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
62                                std::map<const Type *,ValueList> *FutureLateResolvers = 0);
63
64 static struct PerModuleInfo {
65   Module *CurrentModule;
66   std::map<const Type *, ValueList> Values; // Module level numbered definitions
67   std::map<const Type *,ValueList> LateResolveValues;
68   std::vector<PATypeHolder>    Types;
69   std::map<ValID, PATypeHolder> LateResolveTypes;
70
71   /// PlaceHolderInfo - When temporary placeholder objects are created, remember
72   /// how they were referenced and one which line of the input they came from so
73   /// that we can resolve them later and print error messages as appropriate.
74   std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
75
76   // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
77   // references to global values.  Global values may be referenced before they
78   // are defined, and if so, the temporary object that they represent is held
79   // here.  This is used for forward references of GlobalValues.
80   //
81   typedef std::map<std::pair<const PointerType *,
82                              ValID>, GlobalValue*> GlobalRefsType;
83   GlobalRefsType GlobalRefs;
84
85   void ModuleDone() {
86     // If we could not resolve some functions at function compilation time
87     // (calls to functions before they are defined), resolve them now...  Types
88     // are resolved when the constant pool has been completely parsed.
89     //
90     ResolveDefinitions(LateResolveValues);
91
92     // Check to make sure that all global value forward references have been
93     // resolved!
94     //
95     if (!GlobalRefs.empty()) {
96       std::string UndefinedReferences = "Unresolved global references exist:\n";
97       
98       for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
99            I != E; ++I) {
100         UndefinedReferences += "  " + I->first.first->getDescription() + " " +
101                                I->first.second.getName() + "\n";
102       }
103       ThrowException(UndefinedReferences);
104     }
105
106     Values.clear();         // Clear out function local definitions
107     Types.clear();
108     CurrentModule = 0;
109   }
110
111
112   // GetForwardRefForGlobal - Check to see if there is a forward reference
113   // for this global.  If so, remove it from the GlobalRefs map and return it.
114   // If not, just return null.
115   GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
116     // Check to see if there is a forward reference to this global variable...
117     // if there is, eliminate it and patch the reference to use the new def'n.
118     GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
119     GlobalValue *Ret = 0;
120     if (I != GlobalRefs.end()) {
121       Ret = I->second;
122       GlobalRefs.erase(I);
123     }
124     return Ret;
125   }
126 } CurModule;
127
128 static struct PerFunctionInfo {
129   Function *CurrentFunction;     // Pointer to current function being created
130
131   std::map<const Type*, ValueList> Values;   // Keep track of #'d definitions
132   std::map<const Type*, ValueList> LateResolveValues;
133   std::vector<PATypeHolder> Types;
134   std::map<ValID, PATypeHolder> LateResolveTypes;
135   bool isDeclare;                // Is this function a forward declararation?
136
137   /// BBForwardRefs - When we see forward references to basic blocks, keep
138   /// track of them here.
139   std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
140   std::vector<BasicBlock*> NumberedBlocks;
141   unsigned NextBBNum;
142
143   inline PerFunctionInfo() {
144     CurrentFunction = 0;
145     isDeclare = false;
146   }
147
148   inline void FunctionStart(Function *M) {
149     CurrentFunction = M;
150     NextBBNum = 0;
151   }
152
153   void FunctionDone() {
154     NumberedBlocks.clear();
155
156     // Any forward referenced blocks left?
157     if (!BBForwardRefs.empty())
158       ThrowException("Undefined reference to label " +
159                      BBForwardRefs.begin()->second.first.getName());
160
161     // Resolve all forward references now.
162     ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
163
164     Values.clear();         // Clear out function local definitions
165     Types.clear();          // Clear out function local types
166     CurrentFunction = 0;
167     isDeclare = false;
168   }
169 } CurFun;  // Info for the current function...
170
171 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
172
173
174 //===----------------------------------------------------------------------===//
175 //               Code to handle definitions of all the types
176 //===----------------------------------------------------------------------===//
177
178 static int InsertValue(Value *V,
179                   std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
180   if (V->hasName()) return -1;           // Is this a numbered definition?
181
182   // Yes, insert the value into the value table...
183   ValueList &List = ValueTab[V->getType()];
184   List.push_back(V);
185   return List.size()-1;
186 }
187
188 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
189   switch (D.Type) {
190   case ValID::NumberVal:               // Is it a numbered definition?
191     // Module constants occupy the lowest numbered slots...
192     if ((unsigned)D.Num < CurModule.Types.size()) 
193       return CurModule.Types[(unsigned)D.Num];
194     break;
195   case ValID::NameVal:                 // Is it a named definition?
196     if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
197       D.destroy();  // Free old strdup'd memory...
198       return N;
199     }
200     break;
201   default:
202     ThrowException("Internal parser error: Invalid symbol type reference!");
203   }
204
205   // If we reached here, we referenced either a symbol that we don't know about
206   // or an id number that hasn't been read yet.  We may be referencing something
207   // forward, so just create an entry to be resolved later and get to it...
208   //
209   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
210
211   std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ? 
212     CurFun.LateResolveTypes : CurModule.LateResolveTypes;
213   
214   std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
215   if (I != LateResolver.end()) {
216     return I->second;
217   }
218
219   Type *Typ = OpaqueType::get();
220   LateResolver.insert(std::make_pair(D, Typ));
221   return Typ;
222 }
223
224 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
225   SymbolTable &SymTab = 
226     inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
227                         CurModule.CurrentModule->getSymbolTable();
228   return SymTab.lookup(Ty, Name);
229 }
230
231 // getValNonImprovising - Look up the value specified by the provided type and
232 // the provided ValID.  If the value exists and has already been defined, return
233 // it.  Otherwise return null.
234 //
235 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
236   if (isa<FunctionType>(Ty))
237     ThrowException("Functions are not values and "
238                    "must be referenced as pointers");
239
240   switch (D.Type) {
241   case ValID::NumberVal: {                 // Is it a numbered definition?
242     unsigned Num = (unsigned)D.Num;
243
244     // Module constants occupy the lowest numbered slots...
245     std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
246     if (VI != CurModule.Values.end()) {
247       if (Num < VI->second.size()) 
248         return VI->second[Num];
249       Num -= VI->second.size();
250     }
251
252     // Make sure that our type is within bounds
253     VI = CurFun.Values.find(Ty);
254     if (VI == CurFun.Values.end()) return 0;
255
256     // Check that the number is within bounds...
257     if (VI->second.size() <= Num) return 0;
258   
259     return VI->second[Num];
260   }
261
262   case ValID::NameVal: {                // Is it a named definition?
263     Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
264     if (N == 0) return 0;
265
266     D.destroy();  // Free old strdup'd memory...
267     return N;
268   }
269
270   // Check to make sure that "Ty" is an integral type, and that our 
271   // value will fit into the specified type...
272   case ValID::ConstSIntVal:    // Is it a constant pool reference??
273     if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
274       ThrowException("Signed integral constant '" +
275                      itostr(D.ConstPool64) + "' is invalid for type '" + 
276                      Ty->getDescription() + "'!");
277     return ConstantSInt::get(Ty, D.ConstPool64);
278
279   case ValID::ConstUIntVal:     // Is it an unsigned const pool reference?
280     if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
281       if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
282         ThrowException("Integral constant '" + utostr(D.UConstPool64) +
283                        "' is invalid or out of range!");
284       } else {     // This is really a signed reference.  Transmogrify.
285         return ConstantSInt::get(Ty, D.ConstPool64);
286       }
287     } else {
288       return ConstantUInt::get(Ty, D.UConstPool64);
289     }
290
291   case ValID::ConstFPVal:        // Is it a floating point const pool reference?
292     if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
293       ThrowException("FP constant invalid for type!!");
294     return ConstantFP::get(Ty, D.ConstPoolFP);
295     
296   case ValID::ConstNullVal:      // Is it a null value?
297     if (!isa<PointerType>(Ty))
298       ThrowException("Cannot create a a non pointer null!");
299     return ConstantPointerNull::get(cast<PointerType>(Ty));
300     
301   case ValID::ConstantVal:       // Fully resolved constant?
302     if (D.ConstantValue->getType() != Ty)
303       ThrowException("Constant expression type different from required type!");
304     return D.ConstantValue;
305
306   default:
307     assert(0 && "Unhandled case!");
308     return 0;
309   }   // End of switch
310
311   assert(0 && "Unhandled case!");
312   return 0;
313 }
314
315 // getVal - This function is identical to getValNonImprovising, except that if a
316 // value is not already defined, it "improvises" by creating a placeholder var
317 // that looks and acts just like the requested variable.  When the value is
318 // defined later, all uses of the placeholder variable are replaced with the
319 // real thing.
320 //
321 static Value *getVal(const Type *Ty, const ValID &ID) {
322   if (Ty == Type::LabelTy)
323     ThrowException("Cannot use a basic block here");
324
325   // See if the value has already been defined.
326   Value *V = getValNonImprovising(Ty, ID);
327   if (V) return V;
328
329   // If we reached here, we referenced either a symbol that we don't know about
330   // or an id number that hasn't been read yet.  We may be referencing something
331   // forward, so just create an entry to be resolved later and get to it...
332   //
333   V = new Argument(Ty);
334
335   // Remember where this forward reference came from.  FIXME, shouldn't we try
336   // to recycle these things??
337   CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
338                                                                llvmAsmlineno)));
339
340   if (inFunctionScope())
341     InsertValue(V, CurFun.LateResolveValues);
342   else 
343     InsertValue(V, CurModule.LateResolveValues);
344   return V;
345 }
346
347 /// getBBVal - This is used for two purposes:
348 ///  * If isDefinition is true, a new basic block with the specified ID is being
349 ///    defined.
350 ///  * If isDefinition is true, this is a reference to a basic block, which may
351 ///    or may not be a forward reference.
352 ///
353 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
354   assert(inFunctionScope() && "Can't get basic block at global scope!");
355
356   std::string Name;
357   BasicBlock *BB = 0;
358   switch (ID.Type) {
359   default: ThrowException("Illegal label reference " + ID.getName());
360   case ValID::NumberVal:                // Is it a numbered definition?
361     if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
362       CurFun.NumberedBlocks.resize(ID.Num+1);
363     BB = CurFun.NumberedBlocks[ID.Num];
364     break;
365   case ValID::NameVal:                  // Is it a named definition?
366     Name = ID.Name;
367     if (Value *N = CurFun.CurrentFunction->
368                    getSymbolTable().lookup(Type::LabelTy, Name))
369       BB = cast<BasicBlock>(N);
370     break;
371   }
372
373   // See if the block has already been defined.
374   if (BB) {
375     // If this is the definition of the block, make sure the existing value was
376     // just a forward reference.  If it was a forward reference, there will be
377     // an entry for it in the PlaceHolderInfo map.
378     if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
379       // The existing value was a definition, not a forward reference.
380       ThrowException("Redefinition of label " + ID.getName());
381
382     ID.destroy();                       // Free strdup'd memory.
383     return BB;
384   }
385
386   // Otherwise this block has not been seen before.
387   BB = new BasicBlock("", CurFun.CurrentFunction);
388   if (ID.Type == ValID::NameVal) {
389     BB->setName(ID.Name);
390   } else {
391     CurFun.NumberedBlocks[ID.Num] = BB;
392   }
393
394   // If this is not a definition, keep track of it so we can use it as a forward
395   // reference.
396   if (!isDefinition) {
397     // Remember where this forward reference came from.
398     CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
399   } else {
400     // The forward declaration could have been inserted anywhere in the
401     // function: insert it into the correct place now.
402     CurFun.CurrentFunction->getBasicBlockList().remove(BB);
403     CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
404   }
405
406   return BB;
407 }
408
409
410 //===----------------------------------------------------------------------===//
411 //              Code to handle forward references in instructions
412 //===----------------------------------------------------------------------===//
413 //
414 // This code handles the late binding needed with statements that reference
415 // values not defined yet... for example, a forward branch, or the PHI node for
416 // a loop body.
417 //
418 // This keeps a table (CurFun.LateResolveValues) of all such forward references
419 // and back patchs after we are done.
420 //
421
422 // ResolveDefinitions - If we could not resolve some defs at parsing 
423 // time (forward branches, phi functions for loops, etc...) resolve the 
424 // defs now...
425 //
426 static void ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
427                                std::map<const Type*,ValueList> *FutureLateResolvers) {
428   // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
429   for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
430          E = LateResolvers.end(); LRI != E; ++LRI) {
431     ValueList &List = LRI->second;
432     while (!List.empty()) {
433       Value *V = List.back();
434       List.pop_back();
435
436       std::map<Value*, std::pair<ValID, int> >::iterator PHI =
437         CurModule.PlaceHolderInfo.find(V);
438       assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
439
440       ValID &DID = PHI->second.first;
441
442       Value *TheRealValue = getValNonImprovising(LRI->first, DID);
443       if (TheRealValue) {
444         V->replaceAllUsesWith(TheRealValue);
445         delete V;
446         CurModule.PlaceHolderInfo.erase(PHI);
447       } else if (FutureLateResolvers) {
448         // Functions have their unresolved items forwarded to the module late
449         // resolver table
450         InsertValue(V, *FutureLateResolvers);
451       } else {
452         if (DID.Type == ValID::NameVal)
453           ThrowException("Reference to an invalid definition: '" +DID.getName()+
454                          "' of type '" + V->getType()->getDescription() + "'",
455                          PHI->second.second);
456         else
457           ThrowException("Reference to an invalid definition: #" +
458                          itostr(DID.Num) + " of type '" + 
459                          V->getType()->getDescription() + "'",
460                          PHI->second.second);
461       }
462     }
463   }
464
465   LateResolvers.clear();
466 }
467
468 // ResolveTypeTo - A brand new type was just declared.  This means that (if
469 // name is not null) things referencing Name can be resolved.  Otherwise, things
470 // refering to the number can be resolved.  Do this now.
471 //
472 static void ResolveTypeTo(char *Name, const Type *ToTy) {
473   std::vector<PATypeHolder> &Types = inFunctionScope() ? 
474      CurFun.Types : CurModule.Types;
475
476    ValID D;
477    if (Name) D = ValID::create(Name);
478    else      D = ValID::create((int)Types.size());
479
480    std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ? 
481      CurFun.LateResolveTypes : CurModule.LateResolveTypes;
482   
483    std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
484    if (I != LateResolver.end()) {
485      ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
486      LateResolver.erase(I);
487    }
488 }
489
490 // ResolveTypes - At this point, all types should be resolved.  Any that aren't
491 // are errors.
492 //
493 static void ResolveTypes(std::map<ValID, PATypeHolder> &LateResolveTypes) {
494   if (!LateResolveTypes.empty()) {
495     const ValID &DID = LateResolveTypes.begin()->first;
496
497     if (DID.Type == ValID::NameVal)
498       ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
499     else
500       ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
501   }
502 }
503
504 // setValueName - Set the specified value to the name given.  The name may be
505 // null potentially, in which case this is a noop.  The string passed in is
506 // assumed to be a malloc'd string buffer, and is free'd by this function.
507 //
508 static void setValueName(Value *V, char *NameStr) {
509   if (NameStr) {
510     std::string Name(NameStr);      // Copy string
511     free(NameStr);                  // Free old string
512
513     if (V->getType() == Type::VoidTy) 
514       ThrowException("Can't assign name '" + Name+"' to value with void type!");
515     
516     assert(inFunctionScope() && "Must be in function scope!");
517     SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
518     if (ST.lookup(V->getType(), Name))
519       ThrowException("Redefinition of value named '" + Name + "' in the '" +
520                      V->getType()->getDescription() + "' type plane!");
521     
522     // Set the name.
523     V->setName(Name, &ST);
524   }
525 }
526
527 /// ParseGlobalVariable - Handle parsing of a global.  If Initializer is null,
528 /// this is a declaration, otherwise it is a definition.
529 static void ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
530                                 bool isConstantGlobal, const Type *Ty,
531                                 Constant *Initializer) {
532   if (isa<FunctionType>(Ty))
533     ThrowException("Cannot declare global vars of function type!");
534
535   const PointerType *PTy = PointerType::get(Ty); 
536
537   std::string Name;
538   if (NameStr) {
539     Name = NameStr;      // Copy string
540     free(NameStr);       // Free old string
541   }
542
543   // See if this global value was forward referenced.  If so, recycle the
544   // object.
545   ValID ID; 
546   if (!Name.empty()) {
547     ID = ValID::create((char*)Name.c_str());
548   } else {
549     ID = ValID::create((int)CurModule.Values[PTy].size());
550   }
551
552   if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
553     // Move the global to the end of the list, from whereever it was 
554     // previously inserted.
555     GlobalVariable *GV = cast<GlobalVariable>(FWGV);
556     CurModule.CurrentModule->getGlobalList().remove(GV);
557     CurModule.CurrentModule->getGlobalList().push_back(GV);
558     GV->setInitializer(Initializer);
559     GV->setLinkage(Linkage);
560     GV->setConstant(isConstantGlobal);
561     InsertValue(GV, CurModule.Values);
562     return;
563   }
564
565   // If this global has a name, check to see if there is already a definition
566   // of this global in the module.  If so, merge as appropriate.  Note that
567   // this is really just a hack around problems in the CFE.  :(
568   if (!Name.empty()) {
569     // We are a simple redefinition of a value, check to see if it is defined
570     // the same as the old one.
571     if (GlobalVariable *EGV = 
572                 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
573       // We are allowed to redefine a global variable in two circumstances:
574       // 1. If at least one of the globals is uninitialized or 
575       // 2. If both initializers have the same value.
576       //
577       if (!EGV->hasInitializer() || !Initializer ||
578           EGV->getInitializer() == Initializer) {
579
580         // Make sure the existing global version gets the initializer!  Make
581         // sure that it also gets marked const if the new version is.
582         if (Initializer && !EGV->hasInitializer())
583           EGV->setInitializer(Initializer);
584         if (isConstantGlobal)
585           EGV->setConstant(true);
586         EGV->setLinkage(Linkage);
587         return;
588       }
589
590       ThrowException("Redefinition of global variable named '" + Name + 
591                      "' in the '" + Ty->getDescription() + "' type plane!");
592     }
593   }
594
595   // Otherwise there is no existing GV to use, create one now.
596   GlobalVariable *GV =
597     new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name, 
598                        CurModule.CurrentModule);
599   InsertValue(GV, CurModule.Values);
600 }
601
602 // setTypeName - Set the specified type to the name given.  The name may be
603 // null potentially, in which case this is a noop.  The string passed in is
604 // assumed to be a malloc'd string buffer, and is freed by this function.
605 //
606 // This function returns true if the type has already been defined, but is
607 // allowed to be redefined in the specified context.  If the name is a new name
608 // for the type plane, it is inserted and false is returned.
609 static bool setTypeName(const Type *T, char *NameStr) {
610   assert(!inFunctionScope() && "Can't give types function-local names!");
611   if (NameStr == 0) return false;
612   
613   std::string Name(NameStr);      // Copy string
614   free(NameStr);                  // Free old string
615
616   // We don't allow assigning names to void type
617   if (T == Type::VoidTy) 
618     ThrowException("Can't assign name '" + Name + "' to the void type!");
619
620   // Set the type name, checking for conflicts as we do so.
621   bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
622
623   if (AlreadyExists) {   // Inserting a name that is already defined???
624     const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
625     assert(Existing && "Conflict but no matching type?");
626
627     // There is only one case where this is allowed: when we are refining an
628     // opaque type.  In this case, Existing will be an opaque type.
629     if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
630       // We ARE replacing an opaque type!
631       const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
632       return true;
633     }
634
635     // Otherwise, this is an attempt to redefine a type. That's okay if
636     // the redefinition is identical to the original. This will be so if
637     // Existing and T point to the same Type object. In this one case we
638     // allow the equivalent redefinition.
639     if (Existing == T) return true;  // Yes, it's equal.
640
641     // Any other kind of (non-equivalent) redefinition is an error.
642     ThrowException("Redefinition of type named '" + Name + "' in the '" +
643                    T->getDescription() + "' type plane!");
644   }
645
646   return false;
647 }
648
649 //===----------------------------------------------------------------------===//
650 // Code for handling upreferences in type names...
651 //
652
653 // TypeContains - Returns true if Ty directly contains E in it.
654 //
655 static bool TypeContains(const Type *Ty, const Type *E) {
656   return find(Ty->subtype_begin(), Ty->subtype_end(), E) != Ty->subtype_end();
657 }
658
659 namespace {
660   struct UpRefRecord {
661     // NestingLevel - The number of nesting levels that need to be popped before
662     // this type is resolved.
663     unsigned NestingLevel;
664     
665     // LastContainedTy - This is the type at the current binding level for the
666     // type.  Every time we reduce the nesting level, this gets updated.
667     const Type *LastContainedTy;
668
669     // UpRefTy - This is the actual opaque type that the upreference is
670     // represented with.
671     OpaqueType *UpRefTy;
672
673     UpRefRecord(unsigned NL, OpaqueType *URTy)
674       : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
675   };
676 }
677
678 // UpRefs - A list of the outstanding upreferences that need to be resolved.
679 static std::vector<UpRefRecord> UpRefs;
680
681 /// HandleUpRefs - Every time we finish a new layer of types, this function is
682 /// called.  It loops through the UpRefs vector, which is a list of the
683 /// currently active types.  For each type, if the up reference is contained in
684 /// the newly completed type, we decrement the level count.  When the level
685 /// count reaches zero, the upreferenced type is the type that is passed in:
686 /// thus we can complete the cycle.
687 ///
688 static PATypeHolder HandleUpRefs(const Type *ty) {
689   if (!ty->isAbstract()) return ty;
690   PATypeHolder Ty(ty);
691   UR_OUT("Type '" << Ty->getDescription() << 
692          "' newly formed.  Resolving upreferences.\n" <<
693          UpRefs.size() << " upreferences active!\n");
694
695   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
696   // to zero), we resolve them all together before we resolve them to Ty.  At
697   // the end of the loop, if there is anything to resolve to Ty, it will be in
698   // this variable.
699   OpaqueType *TypeToResolve = 0;
700
701   for (unsigned i = 0; i != UpRefs.size(); ++i) {
702     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", " 
703            << UpRefs[i].second->getDescription() << ") = " 
704            << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
705     if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
706       // Decrement level of upreference
707       unsigned Level = --UpRefs[i].NestingLevel;
708       UpRefs[i].LastContainedTy = Ty;
709       UR_OUT("  Uplevel Ref Level = " << Level << "\n");
710       if (Level == 0) {                     // Upreference should be resolved! 
711         if (!TypeToResolve) {
712           TypeToResolve = UpRefs[i].UpRefTy;
713         } else {
714           UR_OUT("  * Resolving upreference for "
715                  << UpRefs[i].second->getDescription() << "\n";
716                  std::string OldName = UpRefs[i].UpRefTy->getDescription());
717           UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
718           UR_OUT("  * Type '" << OldName << "' refined upreference to: "
719                  << (const void*)Ty << ", " << Ty->getDescription() << "\n");
720         }
721         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
722         --i;                                // Do not skip the next element...
723       }
724     }
725   }
726
727   if (TypeToResolve) {
728     UR_OUT("  * Resolving upreference for "
729            << UpRefs[i].second->getDescription() << "\n";
730            std::string OldName = TypeToResolve->getDescription());
731     TypeToResolve->refineAbstractTypeTo(Ty);
732   }
733
734   return Ty;
735 }
736
737
738 //===----------------------------------------------------------------------===//
739 //            RunVMAsmParser - Define an interface to this parser
740 //===----------------------------------------------------------------------===//
741 //
742 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
743   llvmAsmin = F;
744   CurFilename = Filename;
745   llvmAsmlineno = 1;      // Reset the current line number...
746   ObsoleteVarArgs = false;
747
748   // Allocate a new module to read
749   CurModule.CurrentModule = new Module(Filename);
750
751   yyparse();       // Parse the file, potentially throwing exception
752
753   Module *Result = ParserResult;
754
755   // Check to see if they called va_start but not va_arg..
756   if (!ObsoleteVarArgs)
757     if (Function *F = Result->getNamedFunction("llvm.va_start"))
758       if (F->asize() == 1) {
759         std::cerr << "WARNING: this file uses obsolete features.  "
760                   << "Assemble and disassemble to update it.\n";
761         ObsoleteVarArgs = true;
762       }
763
764   if (ObsoleteVarArgs) {
765     // If the user is making use of obsolete varargs intrinsics, adjust them for
766     // the user.
767     if (Function *F = Result->getNamedFunction("llvm.va_start")) {
768       assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
769
770       const Type *RetTy = F->getFunctionType()->getParamType(0);
771       RetTy = cast<PointerType>(RetTy)->getElementType();
772       Function *NF = Result->getOrInsertFunction("llvm.va_start", RetTy, 0);
773       
774       while (!F->use_empty()) {
775         CallInst *CI = cast<CallInst>(F->use_back());
776         Value *V = new CallInst(NF, "", CI);
777         new StoreInst(V, CI->getOperand(1), CI);
778         CI->getParent()->getInstList().erase(CI);
779       }
780       Result->getFunctionList().erase(F);
781     }
782     
783     if (Function *F = Result->getNamedFunction("llvm.va_end")) {
784       assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
785       const Type *ArgTy = F->getFunctionType()->getParamType(0);
786       ArgTy = cast<PointerType>(ArgTy)->getElementType();
787       Function *NF = Result->getOrInsertFunction("llvm.va_end", Type::VoidTy,
788                                                  ArgTy, 0);
789
790       while (!F->use_empty()) {
791         CallInst *CI = cast<CallInst>(F->use_back());
792         Value *V = new LoadInst(CI->getOperand(1), "", CI);
793         new CallInst(NF, V, "", CI);
794         CI->getParent()->getInstList().erase(CI);
795       }
796       Result->getFunctionList().erase(F);
797     }
798
799     if (Function *F = Result->getNamedFunction("llvm.va_copy")) {
800       assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
801       const Type *ArgTy = F->getFunctionType()->getParamType(0);
802       ArgTy = cast<PointerType>(ArgTy)->getElementType();
803       Function *NF = Result->getOrInsertFunction("llvm.va_copy", ArgTy,
804                                                  ArgTy, 0);
805
806       while (!F->use_empty()) {
807         CallInst *CI = cast<CallInst>(F->use_back());
808         Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
809         new StoreInst(V, CI->getOperand(1), CI);
810         CI->getParent()->getInstList().erase(CI);
811       }
812       Result->getFunctionList().erase(F);
813     }
814   }
815
816   llvmAsmin = stdin;    // F is about to go away, don't use it anymore...
817   ParserResult = 0;
818
819   return Result;
820 }
821
822 %}
823
824 %union {
825   llvm::Module                           *ModuleVal;
826   llvm::Function                         *FunctionVal;
827   std::pair<llvm::PATypeHolder*, char*>  *ArgVal;
828   llvm::BasicBlock                       *BasicBlockVal;
829   llvm::TerminatorInst                   *TermInstVal;
830   llvm::Instruction                      *InstVal;
831   llvm::Constant                         *ConstVal;
832
833   const llvm::Type                       *PrimType;
834   llvm::PATypeHolder                     *TypeVal;
835   llvm::Value                            *ValueVal;
836
837   std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
838   std::vector<llvm::Value*>              *ValueList;
839   std::list<llvm::PATypeHolder>          *TypeList;
840   std::list<std::pair<llvm::Value*,
841                       llvm::BasicBlock*> > *PHIList; // Represent the RHS of PHI node
842   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
843   std::vector<llvm::Constant*>           *ConstVector;
844
845   llvm::GlobalValue::LinkageTypes         Linkage;
846   int64_t                           SInt64Val;
847   uint64_t                          UInt64Val;
848   int                               SIntVal;
849   unsigned                          UIntVal;
850   double                            FPVal;
851   bool                              BoolVal;
852
853   char                             *StrVal;   // This memory is strdup'd!
854   llvm::ValID                             ValIDVal; // strdup'd memory maybe!
855
856   llvm::Instruction::BinaryOps            BinaryOpVal;
857   llvm::Instruction::TermOps              TermOpVal;
858   llvm::Instruction::MemoryOps            MemOpVal;
859   llvm::Instruction::OtherOps             OtherOpVal;
860   llvm::Module::Endianness                Endianness;
861 }
862
863 %type <ModuleVal>     Module FunctionList
864 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
865 %type <BasicBlockVal> BasicBlock InstructionList
866 %type <TermInstVal>   BBTerminatorInst
867 %type <InstVal>       Inst InstVal MemoryInst
868 %type <ConstVal>      ConstVal ConstExpr
869 %type <ConstVector>   ConstVector
870 %type <ArgList>       ArgList ArgListH
871 %type <ArgVal>        ArgVal
872 %type <PHIList>       PHIList
873 %type <ValueList>     ValueRefList ValueRefListE  // For call param lists
874 %type <ValueList>     IndexList                   // For GEP derived indices
875 %type <TypeList>      TypeListI ArgTypeListI
876 %type <JumpTable>     JumpTable
877 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
878 %type <BoolVal>       OptVolatile                 // 'volatile' or not
879 %type <Linkage>       OptLinkage
880 %type <Endianness>    BigOrLittle
881
882 // ValueRef - Unresolved reference to a definition or BB
883 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
884 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
885 // Tokens and types for handling constant integer values
886 //
887 // ESINT64VAL - A negative number within long long range
888 %token <SInt64Val> ESINT64VAL
889
890 // EUINT64VAL - A positive number within uns. long long range
891 %token <UInt64Val> EUINT64VAL
892 %type  <SInt64Val> EINT64VAL
893
894 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
895 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
896 %type   <SIntVal>   INTVAL
897 %token  <FPVal>     FPVAL     // Float or Double constant
898
899 // Built in types...
900 %type  <TypeVal> Types TypesV UpRTypes UpRTypesV
901 %type  <PrimType> SIntType UIntType IntType FPType PrimType   // Classifications
902 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
903 %token <PrimType> FLOAT DOUBLE TYPE LABEL
904
905 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
906 %type  <StrVal> Name OptName OptAssign
907
908
909 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
910 %token DECLARE GLOBAL CONSTANT VOLATILE
911 %token TO DOTDOTDOT NULL_TOK CONST INTERNAL LINKONCE WEAK  APPENDING
912 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG
913 %token DEPLIBS
914
915 // Basic Block Terminating Operators 
916 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND
917
918 // Binary Operators 
919 %type  <BinaryOpVal> BinaryOps  // all the binary operators
920 %type  <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
921 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
922 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comarators
923
924 // Memory Instructions
925 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
926
927 // Other Operators
928 %type  <OtherOpVal> ShiftOps
929 %token <OtherOpVal> PHI_TOK CALL CAST SELECT SHL SHR VAARG VANEXT
930 %token VA_ARG // FIXME: OBSOLETE
931
932 %start Module
933 %%
934
935 // Handle constant integer size restriction and conversion...
936 //
937 INTVAL : SINTVAL;
938 INTVAL : UINTVAL {
939   if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
940     ThrowException("Value too large for type!");
941   $$ = (int32_t)$1;
942 };
943
944
945 EINT64VAL : ESINT64VAL;      // These have same type and can't cause problems...
946 EINT64VAL : EUINT64VAL {
947   if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
948     ThrowException("Value too large for type!");
949   $$ = (int64_t)$1;
950 };
951
952 // Operations that are notably excluded from this list include: 
953 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
954 //
955 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
956 LogicalOps   : AND | OR | XOR;
957 SetCondOps   : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
958 BinaryOps : ArithmeticOps | LogicalOps | SetCondOps;
959
960 ShiftOps  : SHL | SHR;
961
962 // These are some types that allow classification if we only want a particular 
963 // thing... for example, only a signed, unsigned, or integral type.
964 SIntType :  LONG |  INT |  SHORT | SBYTE;
965 UIntType : ULONG | UINT | USHORT | UBYTE;
966 IntType  : SIntType | UIntType;
967 FPType   : FLOAT | DOUBLE;
968
969 // OptAssign - Value producing statements have an optional assignment component
970 OptAssign : Name '=' {
971     $$ = $1;
972   }
973   | /*empty*/ { 
974     $$ = 0; 
975   };
976
977 OptLinkage : INTERNAL  { $$ = GlobalValue::InternalLinkage; } |
978              LINKONCE  { $$ = GlobalValue::LinkOnceLinkage; } |
979              WEAK      { $$ = GlobalValue::WeakLinkage; } |
980              APPENDING { $$ = GlobalValue::AppendingLinkage; } |
981              /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
982
983 //===----------------------------------------------------------------------===//
984 // Types includes all predefined types... except void, because it can only be
985 // used in specific contexts (function returning void for example).  To have
986 // access to it, a user must explicitly use TypesV.
987 //
988
989 // TypesV includes all of 'Types', but it also includes the void type.
990 TypesV    : Types    | VOID { $$ = new PATypeHolder($1); };
991 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
992
993 Types     : UpRTypes {
994     if (!UpRefs.empty())
995       ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
996     $$ = $1;
997   };
998
999
1000 // Derived types are added later...
1001 //
1002 PrimType : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT ;
1003 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE   | LABEL;
1004 UpRTypes : OPAQUE {
1005     $$ = new PATypeHolder(OpaqueType::get());
1006   }
1007   | PrimType {
1008     $$ = new PATypeHolder($1);
1009   };
1010 UpRTypes : SymbolicValueRef {            // Named types are also simple types...
1011   $$ = new PATypeHolder(getTypeVal($1));
1012 };
1013
1014 // Include derived types in the Types production.
1015 //
1016 UpRTypes : '\\' EUINT64VAL {                   // Type UpReference
1017     if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1018     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1019     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1020     $$ = new PATypeHolder(OT);
1021     UR_OUT("New Upreference!\n");
1022   }
1023   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
1024     std::vector<const Type*> Params;
1025     mapto($3->begin(), $3->end(), std::back_inserter(Params), 
1026           std::mem_fun_ref(&PATypeHolder::get));
1027     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1028     if (isVarArg) Params.pop_back();
1029
1030     $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1031     delete $3;      // Delete the argument list
1032     delete $1;      // Delete the return type handle
1033   }
1034   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
1035     $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1036     delete $4;
1037   }
1038   | '{' TypeListI '}' {                        // Structure type?
1039     std::vector<const Type*> Elements;
1040     mapto($2->begin(), $2->end(), std::back_inserter(Elements), 
1041         std::mem_fun_ref(&PATypeHolder::get));
1042
1043     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1044     delete $2;
1045   }
1046   | '{' '}' {                                  // Empty structure type?
1047     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1048   }
1049   | UpRTypes '*' {                             // Pointer type?
1050     $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1051     delete $1;
1052   };
1053
1054 // TypeList - Used for struct declarations and as a basis for function type 
1055 // declaration type lists
1056 //
1057 TypeListI : UpRTypes {
1058     $$ = new std::list<PATypeHolder>();
1059     $$->push_back(*$1); delete $1;
1060   }
1061   | TypeListI ',' UpRTypes {
1062     ($$=$1)->push_back(*$3); delete $3;
1063   };
1064
1065 // ArgTypeList - List of types for a function type declaration...
1066 ArgTypeListI : TypeListI
1067   | TypeListI ',' DOTDOTDOT {
1068     ($$=$1)->push_back(Type::VoidTy);
1069   }
1070   | DOTDOTDOT {
1071     ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1072   }
1073   | /*empty*/ {
1074     $$ = new std::list<PATypeHolder>();
1075   };
1076
1077 // ConstVal - The various declarations that go into the constant pool.  This
1078 // production is used ONLY to represent constants that show up AFTER a 'const',
1079 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1080 // into other expressions (such as integers and constexprs) are handled by the
1081 // ResolvedVal, ValueRef and ConstValueRef productions.
1082 //
1083 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1084     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1085     if (ATy == 0)
1086       ThrowException("Cannot make array constant with type: '" + 
1087                      (*$1)->getDescription() + "'!");
1088     const Type *ETy = ATy->getElementType();
1089     int NumElements = ATy->getNumElements();
1090
1091     // Verify that we have the correct size...
1092     if (NumElements != -1 && NumElements != (int)$3->size())
1093       ThrowException("Type mismatch: constant sized array initialized with " +
1094                      utostr($3->size()) +  " arguments, but has size of " + 
1095                      itostr(NumElements) + "!");
1096
1097     // Verify all elements are correct type!
1098     for (unsigned i = 0; i < $3->size(); i++) {
1099       if (ETy != (*$3)[i]->getType())
1100         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1101                        ETy->getDescription() +"' as required!\nIt is of type '"+
1102                        (*$3)[i]->getType()->getDescription() + "'.");
1103     }
1104
1105     $$ = ConstantArray::get(ATy, *$3);
1106     delete $1; delete $3;
1107   }
1108   | Types '[' ']' {
1109     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1110     if (ATy == 0)
1111       ThrowException("Cannot make array constant with type: '" + 
1112                      (*$1)->getDescription() + "'!");
1113
1114     int NumElements = ATy->getNumElements();
1115     if (NumElements != -1 && NumElements != 0) 
1116       ThrowException("Type mismatch: constant sized array initialized with 0"
1117                      " arguments, but has size of " + itostr(NumElements) +"!");
1118     $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1119     delete $1;
1120   }
1121   | Types 'c' STRINGCONSTANT {
1122     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1123     if (ATy == 0)
1124       ThrowException("Cannot make array constant with type: '" + 
1125                      (*$1)->getDescription() + "'!");
1126
1127     int NumElements = ATy->getNumElements();
1128     const Type *ETy = ATy->getElementType();
1129     char *EndStr = UnEscapeLexed($3, true);
1130     if (NumElements != -1 && NumElements != (EndStr-$3))
1131       ThrowException("Can't build string constant of size " + 
1132                      itostr((int)(EndStr-$3)) +
1133                      " when array has size " + itostr(NumElements) + "!");
1134     std::vector<Constant*> Vals;
1135     if (ETy == Type::SByteTy) {
1136       for (char *C = $3; C != EndStr; ++C)
1137         Vals.push_back(ConstantSInt::get(ETy, *C));
1138     } else if (ETy == Type::UByteTy) {
1139       for (char *C = $3; C != EndStr; ++C)
1140         Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1141     } else {
1142       free($3);
1143       ThrowException("Cannot build string arrays of non byte sized elements!");
1144     }
1145     free($3);
1146     $$ = ConstantArray::get(ATy, Vals);
1147     delete $1;
1148   }
1149   | Types '{' ConstVector '}' {
1150     const StructType *STy = dyn_cast<StructType>($1->get());
1151     if (STy == 0)
1152       ThrowException("Cannot make struct constant with type: '" + 
1153                      (*$1)->getDescription() + "'!");
1154
1155     if ($3->size() != STy->getNumContainedTypes())
1156       ThrowException("Illegal number of initializers for structure type!");
1157
1158     // Check to ensure that constants are compatible with the type initializer!
1159     for (unsigned i = 0, e = $3->size(); i != e; ++i)
1160       if ((*$3)[i]->getType() != STy->getElementType(i))
1161         ThrowException("Expected type '" +
1162                        STy->getElementType(i)->getDescription() +
1163                        "' for element #" + utostr(i) +
1164                        " of structure initializer!");
1165
1166     $$ = ConstantStruct::get(STy, *$3);
1167     delete $1; delete $3;
1168   }
1169   | Types '{' '}' {
1170     const StructType *STy = dyn_cast<StructType>($1->get());
1171     if (STy == 0)
1172       ThrowException("Cannot make struct constant with type: '" + 
1173                      (*$1)->getDescription() + "'!");
1174
1175     if (STy->getNumContainedTypes() != 0)
1176       ThrowException("Illegal number of initializers for structure type!");
1177
1178     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1179     delete $1;
1180   }
1181   | Types NULL_TOK {
1182     const PointerType *PTy = dyn_cast<PointerType>($1->get());
1183     if (PTy == 0)
1184       ThrowException("Cannot make null pointer constant with type: '" + 
1185                      (*$1)->getDescription() + "'!");
1186
1187     $$ = ConstantPointerNull::get(PTy);
1188     delete $1;
1189   }
1190   | Types SymbolicValueRef {
1191     const PointerType *Ty = dyn_cast<PointerType>($1->get());
1192     if (Ty == 0)
1193       ThrowException("Global const reference must be a pointer type!");
1194
1195     // ConstExprs can exist in the body of a function, thus creating
1196     // GlobalValues whenever they refer to a variable.  Because we are in
1197     // the context of a function, getValNonImprovising will search the functions
1198     // symbol table instead of the module symbol table for the global symbol,
1199     // which throws things all off.  To get around this, we just tell
1200     // getValNonImprovising that we are at global scope here.
1201     //
1202     Function *SavedCurFn = CurFun.CurrentFunction;
1203     CurFun.CurrentFunction = 0;
1204
1205     Value *V = getValNonImprovising(Ty, $2);
1206
1207     CurFun.CurrentFunction = SavedCurFn;
1208
1209     // If this is an initializer for a constant pointer, which is referencing a
1210     // (currently) undefined variable, create a stub now that shall be replaced
1211     // in the future with the right type of variable.
1212     //
1213     if (V == 0) {
1214       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1215       const PointerType *PT = cast<PointerType>(Ty);
1216
1217       // First check to see if the forward references value is already created!
1218       PerModuleInfo::GlobalRefsType::iterator I =
1219         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1220     
1221       if (I != CurModule.GlobalRefs.end()) {
1222         V = I->second;             // Placeholder already exists, use it...
1223         $2.destroy();
1224       } else {
1225         std::string Name;
1226         if ($2.Type == ValID::NameVal) Name = $2.Name;
1227
1228         // Create the forward referenced global.
1229         GlobalValue *GV;
1230         if (const FunctionType *FTy = 
1231                  dyn_cast<FunctionType>(PT->getElementType())) {
1232           GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1233                             CurModule.CurrentModule);
1234         } else {
1235           GV = new GlobalVariable(PT->getElementType(), false,
1236                                   GlobalValue::ExternalLinkage, 0,
1237                                   Name, CurModule.CurrentModule);
1238         }
1239
1240         // Keep track of the fact that we have a forward ref to recycle it
1241         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1242         V = GV;
1243       }
1244     }
1245
1246     $$ = cast<GlobalValue>(V);
1247     delete $1;            // Free the type handle
1248   }
1249   | Types ConstExpr {
1250     if ($1->get() != $2->getType())
1251       ThrowException("Mismatched types for constant expression!");
1252     $$ = $2;
1253     delete $1;
1254   }
1255   | Types ZEROINITIALIZER {
1256     $$ = Constant::getNullValue($1->get());
1257     delete $1;
1258   };
1259
1260 ConstVal : SIntType EINT64VAL {      // integral constants
1261     if (!ConstantSInt::isValueValidForType($1, $2))
1262       ThrowException("Constant value doesn't fit in type!");
1263     $$ = ConstantSInt::get($1, $2);
1264   }
1265   | UIntType EUINT64VAL {            // integral constants
1266     if (!ConstantUInt::isValueValidForType($1, $2))
1267       ThrowException("Constant value doesn't fit in type!");
1268     $$ = ConstantUInt::get($1, $2);
1269   }
1270   | BOOL TRUETOK {                      // Boolean constants
1271     $$ = ConstantBool::True;
1272   }
1273   | BOOL FALSETOK {                     // Boolean constants
1274     $$ = ConstantBool::False;
1275   }
1276   | FPType FPVAL {                   // Float & Double constants
1277     $$ = ConstantFP::get($1, $2);
1278   };
1279
1280
1281 ConstExpr: CAST '(' ConstVal TO Types ')' {
1282     if (!$3->getType()->isFirstClassType())
1283       ThrowException("cast constant expression from a non-primitive type: '" +
1284                      $3->getType()->getDescription() + "'!");
1285     if (!$5->get()->isFirstClassType())
1286       ThrowException("cast constant expression to a non-primitive type: '" +
1287                      $5->get()->getDescription() + "'!");
1288     $$ = ConstantExpr::getCast($3, $5->get());
1289     delete $5;
1290   }
1291   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1292     if (!isa<PointerType>($3->getType()))
1293       ThrowException("GetElementPtr requires a pointer operand!");
1294
1295     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
1296     // indices to uint struct indices for compatibility.
1297     generic_gep_type_iterator<std::vector<Value*>::iterator>
1298       GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1299       GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1300     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1301       if (isa<StructType>(*GTI))        // Only change struct indices
1302         if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1303           if (CUI->getType() == Type::UByteTy)
1304             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1305
1306     const Type *IdxTy =
1307       GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1308     if (!IdxTy)
1309       ThrowException("Index list invalid for constant getelementptr!");
1310
1311     std::vector<Constant*> IdxVec;
1312     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1313       if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1314         IdxVec.push_back(C);
1315       else
1316         ThrowException("Indices to constant getelementptr must be constants!");
1317
1318     delete $4;
1319
1320     $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1321   }
1322   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1323     if ($3->getType() != Type::BoolTy)
1324       ThrowException("Select condition must be of boolean type!");
1325     if ($5->getType() != $7->getType())
1326       ThrowException("Select operand types must match!");
1327     $$ = ConstantExpr::getSelect($3, $5, $7);
1328   }
1329   | BinaryOps '(' ConstVal ',' ConstVal ')' {
1330     if ($3->getType() != $5->getType())
1331       ThrowException("Binary operator types must match!");
1332     $$ = ConstantExpr::get($1, $3, $5);
1333   }
1334   | ShiftOps '(' ConstVal ',' ConstVal ')' {
1335     if ($5->getType() != Type::UByteTy)
1336       ThrowException("Shift count for shift constant must be unsigned byte!");
1337     if (!$3->getType()->isInteger())
1338       ThrowException("Shift constant expression requires integer operand!");
1339     $$ = ConstantExpr::get($1, $3, $5);
1340   };
1341
1342
1343 // ConstVector - A list of comma separated constants.
1344 ConstVector : ConstVector ',' ConstVal {
1345     ($$ = $1)->push_back($3);
1346   }
1347   | ConstVal {
1348     $$ = new std::vector<Constant*>();
1349     $$->push_back($1);
1350   };
1351
1352
1353 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1354 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1355
1356
1357 //===----------------------------------------------------------------------===//
1358 //                             Rules to match Modules
1359 //===----------------------------------------------------------------------===//
1360
1361 // Module rule: Capture the result of parsing the whole file into a result
1362 // variable...
1363 //
1364 Module : FunctionList {
1365   $$ = ParserResult = $1;
1366   CurModule.ModuleDone();
1367 };
1368
1369 // FunctionList - A list of functions, preceeded by a constant pool.
1370 //
1371 FunctionList : FunctionList Function {
1372     $$ = $1;
1373     CurFun.FunctionDone();
1374   } 
1375   | FunctionList FunctionProto {
1376     $$ = $1;
1377   }
1378   | FunctionList IMPLEMENTATION {
1379     $$ = $1;
1380   }
1381   | ConstPool {
1382     $$ = CurModule.CurrentModule;
1383     // Resolve circular types before we parse the body of the module
1384     ResolveTypes(CurModule.LateResolveTypes);
1385   };
1386
1387 // ConstPool - Constants with optional names assigned to them.
1388 ConstPool : ConstPool OptAssign TYPE TypesV {  // Types can be defined in the const pool
1389     // Eagerly resolve types.  This is not an optimization, this is a
1390     // requirement that is due to the fact that we could have this:
1391     //
1392     // %list = type { %list * }
1393     // %list = type { %list * }    ; repeated type decl
1394     //
1395     // If types are not resolved eagerly, then the two types will not be
1396     // determined to be the same type!
1397     //
1398     ResolveTypeTo($2, *$4);
1399
1400     if (!setTypeName(*$4, $2) && !$2) {
1401       // If this is a named type that is not a redefinition, add it to the slot
1402       // table.
1403       if (inFunctionScope())
1404         CurFun.Types.push_back(*$4);
1405       else
1406         CurModule.Types.push_back(*$4);
1407     }
1408
1409     delete $4;
1410   }
1411   | ConstPool FunctionProto {       // Function prototypes can be in const pool
1412   }
1413   | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1414     if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1415     ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1416   }
1417   | ConstPool OptAssign EXTERNAL GlobalType Types {
1418     ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, *$5, 0);
1419     delete $5;
1420   }
1421   | ConstPool TARGET TargetDefinition { 
1422   }
1423   | ConstPool DEPLIBS '=' LibrariesDefinition {
1424   }
1425   | /* empty: end of list */ { 
1426   };
1427
1428
1429
1430 BigOrLittle : BIG    { $$ = Module::BigEndian; };
1431 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1432
1433 TargetDefinition : ENDIAN '=' BigOrLittle {
1434     CurModule.CurrentModule->setEndianness($3);
1435   }
1436   | POINTERSIZE '=' EUINT64VAL {
1437     if ($3 == 32)
1438       CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1439     else if ($3 == 64)
1440       CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1441     else
1442       ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1443   }
1444   | TRIPLE '=' STRINGCONSTANT {
1445     CurModule.CurrentModule->setTargetTriple($3);
1446     free($3);
1447   };
1448
1449 LibrariesDefinition : '[' LibList ']';
1450
1451 LibList : LibList ',' STRINGCONSTANT {
1452           CurModule.CurrentModule->addLibrary($3);
1453           free($3);
1454         }
1455         | STRINGCONSTANT {
1456           CurModule.CurrentModule->addLibrary($1);
1457           free($1);
1458         }
1459         | /* empty: end of list */ {
1460         }
1461         ;
1462
1463 //===----------------------------------------------------------------------===//
1464 //                       Rules to match Function Headers
1465 //===----------------------------------------------------------------------===//
1466
1467 Name : VAR_ID | STRINGCONSTANT;
1468 OptName : Name | /*empty*/ { $$ = 0; };
1469
1470 ArgVal : Types OptName {
1471   if (*$1 == Type::VoidTy)
1472     ThrowException("void typed arguments are invalid!");
1473   $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1474 };
1475
1476 ArgListH : ArgListH ',' ArgVal {
1477     $$ = $1;
1478     $1->push_back(*$3);
1479     delete $3;
1480   }
1481   | ArgVal {
1482     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1483     $$->push_back(*$1);
1484     delete $1;
1485   };
1486
1487 ArgList : ArgListH {
1488     $$ = $1;
1489   }
1490   | ArgListH ',' DOTDOTDOT {
1491     $$ = $1;
1492     $$->push_back(std::pair<PATypeHolder*,
1493                             char*>(new PATypeHolder(Type::VoidTy), 0));
1494   }
1495   | DOTDOTDOT {
1496     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1497     $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1498   }
1499   | /* empty */ {
1500     $$ = 0;
1501   };
1502
1503 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1504   UnEscapeLexed($2);
1505   std::string FunctionName($2);
1506   free($2);  // Free strdup'd memory!
1507   
1508   if (!(*$1)->isFirstClassType() && *$1 != Type::VoidTy)
1509     ThrowException("LLVM functions cannot return aggregate types!");
1510
1511   std::vector<const Type*> ParamTypeList;
1512   if ($4) {   // If there are arguments...
1513     for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1514          I != $4->end(); ++I)
1515       ParamTypeList.push_back(I->first->get());
1516   }
1517
1518   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1519   if (isVarArg) ParamTypeList.pop_back();
1520
1521   const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1522   const PointerType *PFT = PointerType::get(FT);
1523   delete $1;
1524
1525   ValID ID;
1526   if (!FunctionName.empty()) {
1527     ID = ValID::create((char*)FunctionName.c_str());
1528   } else {
1529     ID = ValID::create((int)CurModule.Values[PFT].size());
1530   }
1531
1532   Function *Fn = 0;
1533   // See if this function was forward referenced.  If so, recycle the object.
1534   if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1535     // Move the function to the end of the list, from whereever it was 
1536     // previously inserted.
1537     Fn = cast<Function>(FWRef);
1538     CurModule.CurrentModule->getFunctionList().remove(Fn);
1539     CurModule.CurrentModule->getFunctionList().push_back(Fn);
1540   } else if (!FunctionName.empty() &&     // Merge with an earlier prototype?
1541              (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1542     // If this is the case, either we need to be a forward decl, or it needs 
1543     // to be.
1544     if (!CurFun.isDeclare && !Fn->isExternal())
1545       ThrowException("Redefinition of function '" + FunctionName + "'!");
1546     
1547     // Make sure to strip off any argument names so we can't get conflicts.
1548     if (Fn->isExternal())
1549       for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend();
1550            AI != AE; ++AI)
1551         AI->setName("");
1552
1553   } else  {  // Not already defined?
1554     Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1555                       CurModule.CurrentModule);
1556     InsertValue(Fn, CurModule.Values);
1557   }
1558
1559   CurFun.FunctionStart(Fn);
1560
1561   // Add all of the arguments we parsed to the function...
1562   if ($4) {                     // Is null if empty...
1563     if (isVarArg) {  // Nuke the last entry
1564       assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1565              "Not a varargs marker!");
1566       delete $4->back().first;
1567       $4->pop_back();  // Delete the last entry
1568     }
1569     Function::aiterator ArgIt = Fn->abegin();
1570     for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1571          I != $4->end(); ++I, ++ArgIt) {
1572       delete I->first;                          // Delete the typeholder...
1573
1574       setValueName(ArgIt, I->second);           // Insert arg into symtab...
1575       InsertValue(ArgIt);
1576     }
1577
1578     delete $4;                     // We're now done with the argument list
1579   }
1580 };
1581
1582 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
1583
1584 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1585   $$ = CurFun.CurrentFunction;
1586
1587   // Make sure that we keep track of the linkage type even if there was a
1588   // previous "declare".
1589   $$->setLinkage($1);
1590
1591   // Resolve circular types before we parse the body of the function.
1592   ResolveTypes(CurFun.LateResolveTypes);
1593 };
1594
1595 END : ENDTOK | '}';                    // Allow end of '}' to end a function
1596
1597 Function : BasicBlockList END {
1598   $$ = $1;
1599 };
1600
1601 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1602   $$ = CurFun.CurrentFunction;
1603   CurFun.FunctionDone();
1604 };
1605
1606 //===----------------------------------------------------------------------===//
1607 //                        Rules to match Basic Blocks
1608 //===----------------------------------------------------------------------===//
1609
1610 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
1611     $$ = ValID::create($1);
1612   }
1613   | EUINT64VAL {
1614     $$ = ValID::create($1);
1615   }
1616   | FPVAL {                     // Perhaps it's an FP constant?
1617     $$ = ValID::create($1);
1618   }
1619   | TRUETOK {
1620     $$ = ValID::create(ConstantBool::True);
1621   } 
1622   | FALSETOK {
1623     $$ = ValID::create(ConstantBool::False);
1624   }
1625   | NULL_TOK {
1626     $$ = ValID::createNull();
1627   }
1628   | ConstExpr {
1629     $$ = ValID::create($1);
1630   };
1631
1632 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1633 // another value.
1634 //
1635 SymbolicValueRef : INTVAL {  // Is it an integer reference...?
1636     $$ = ValID::create($1);
1637   }
1638   | Name {                   // Is it a named reference...?
1639     $$ = ValID::create($1);
1640   };
1641
1642 // ValueRef - A reference to a definition... either constant or symbolic
1643 ValueRef : SymbolicValueRef | ConstValueRef;
1644
1645
1646 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
1647 // type immediately preceeds the value reference, and allows complex constant
1648 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1649 ResolvedVal : Types ValueRef {
1650     $$ = getVal(*$1, $2); delete $1;
1651   };
1652
1653 BasicBlockList : BasicBlockList BasicBlock {
1654     $$ = $1;
1655   }
1656   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
1657     $$ = $1;
1658   };
1659
1660
1661 // Basic blocks are terminated by branching instructions: 
1662 // br, br/cc, switch, ret
1663 //
1664 BasicBlock : InstructionList OptAssign BBTerminatorInst  {
1665     setValueName($3, $2);
1666     InsertValue($3);
1667
1668     $1->getInstList().push_back($3);
1669     InsertValue($1);
1670     $$ = $1;
1671   };
1672
1673 InstructionList : InstructionList Inst {
1674     $1->getInstList().push_back($2);
1675     $$ = $1;
1676   }
1677   | /* empty */ {
1678     $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1679
1680     // Make sure to move the basic block to the correct location in the
1681     // function, instead of leaving it inserted wherever it was first
1682     // referenced.
1683     CurFun.CurrentFunction->getBasicBlockList().remove(CurBB);
1684     CurFun.CurrentFunction->getBasicBlockList().push_back(CurBB);
1685   }
1686   | LABELSTR {
1687     $$ = CurBB = getBBVal(ValID::create($1), true);
1688
1689     // Make sure to move the basic block to the correct location in the
1690     // function, instead of leaving it inserted wherever it was first
1691     // referenced.
1692     CurFun.CurrentFunction->getBasicBlockList().remove(CurBB);
1693     CurFun.CurrentFunction->getBasicBlockList().push_back(CurBB);
1694   };
1695
1696 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
1697     $$ = new ReturnInst($2);
1698   }
1699   | RET VOID {                                       // Return with no result...
1700     $$ = new ReturnInst();
1701   }
1702   | BR LABEL ValueRef {                         // Unconditional Branch...
1703     $$ = new BranchInst(getBBVal($3));
1704   }                                                  // Conditional Branch...
1705   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
1706     $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1707   }
1708   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1709     SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6));
1710     $$ = S;
1711
1712     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1713       E = $8->end();
1714     for (; I != E; ++I)
1715       S->addCase(I->first, I->second);
1716     delete $8;
1717   }
1718   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1719     SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6));
1720     $$ = S;
1721   }
1722   | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO LABEL ValueRef
1723     UNWIND LABEL ValueRef {
1724     const PointerType *PFTy;
1725     const FunctionType *Ty;
1726
1727     if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1728         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1729       // Pull out the types of all of the arguments...
1730       std::vector<const Type*> ParamTypes;
1731       if ($5) {
1732         for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1733              I != E; ++I)
1734           ParamTypes.push_back((*I)->getType());
1735       }
1736
1737       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1738       if (isVarArg) ParamTypes.pop_back();
1739
1740       Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1741       PFTy = PointerType::get(Ty);
1742     }
1743
1744     Value *V = getVal(PFTy, $3);   // Get the function we're calling...
1745
1746     BasicBlock *Normal = getBBVal($9);
1747     BasicBlock *Except = getBBVal($12);
1748
1749     // Create the call node...
1750     if (!$5) {                                   // Has no arguments?
1751       $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1752     } else {                                     // Has arguments?
1753       // Loop through FunctionType's arguments and ensure they are specified
1754       // correctly!
1755       //
1756       FunctionType::param_iterator I = Ty->param_begin();
1757       FunctionType::param_iterator E = Ty->param_end();
1758       std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1759
1760       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1761         if ((*ArgI)->getType() != *I)
1762           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1763                          (*I)->getDescription() + "'!");
1764
1765       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1766         ThrowException("Invalid number of parameters detected!");
1767
1768       $$ = new InvokeInst(V, Normal, Except, *$5);
1769     }
1770     delete $2;
1771     delete $5;
1772   }
1773   | UNWIND {
1774     $$ = new UnwindInst();
1775   };
1776
1777
1778
1779 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1780     $$ = $1;
1781     Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1782     if (V == 0)
1783       ThrowException("May only switch on a constant pool value!");
1784
1785     $$->push_back(std::make_pair(V, getBBVal($6)));
1786   }
1787   | IntType ConstValueRef ',' LABEL ValueRef {
1788     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1789     Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1790
1791     if (V == 0)
1792       ThrowException("May only switch on a constant pool value!");
1793
1794     $$->push_back(std::make_pair(V, getBBVal($5)));
1795   };
1796
1797 Inst : OptAssign InstVal {
1798   // Is this definition named?? if so, assign the name...
1799   setValueName($2, $1);
1800   InsertValue($2);
1801   $$ = $2;
1802 };
1803
1804 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
1805     $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1806     $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
1807     delete $1;
1808   }
1809   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1810     $$ = $1;
1811     $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1812                                  getBBVal($6)));
1813   };
1814
1815
1816 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
1817     $$ = new std::vector<Value*>();
1818     $$->push_back($1);
1819   }
1820   | ValueRefList ',' ResolvedVal {
1821     $$ = $1;
1822     $1->push_back($3);
1823   };
1824
1825 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1826 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1827
1828 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1829     if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint())
1830       ThrowException("Arithmetic operator requires integer or FP operands!");
1831     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1832     if ($$ == 0)
1833       ThrowException("binary operator returned null!");
1834     delete $2;
1835   }
1836   | LogicalOps Types ValueRef ',' ValueRef {
1837     if (!(*$2)->isIntegral())
1838       ThrowException("Logical operator requires integral operands!");
1839     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1840     if ($$ == 0)
1841       ThrowException("binary operator returned null!");
1842     delete $2;
1843   }
1844   | SetCondOps Types ValueRef ',' ValueRef {
1845     $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1846     if ($$ == 0)
1847       ThrowException("binary operator returned null!");
1848     delete $2;
1849   }
1850   | NOT ResolvedVal {
1851     std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1852               << " Replacing with 'xor'.\n";
1853
1854     Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1855     if (Ones == 0)
1856       ThrowException("Expected integral type for not instruction!");
1857
1858     $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1859     if ($$ == 0)
1860       ThrowException("Could not create a xor instruction!");
1861   }
1862   | ShiftOps ResolvedVal ',' ResolvedVal {
1863     if ($4->getType() != Type::UByteTy)
1864       ThrowException("Shift amount must be ubyte!");
1865     if (!$2->getType()->isInteger())
1866       ThrowException("Shift constant expression requires integer operand!");
1867     $$ = new ShiftInst($1, $2, $4);
1868   }
1869   | CAST ResolvedVal TO Types {
1870     if (!$4->get()->isFirstClassType())
1871       ThrowException("cast instruction to a non-primitive type: '" +
1872                      $4->get()->getDescription() + "'!");
1873     $$ = new CastInst($2, *$4);
1874     delete $4;
1875   }
1876   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1877     if ($2->getType() != Type::BoolTy)
1878       ThrowException("select condition must be boolean!");
1879     if ($4->getType() != $6->getType())
1880       ThrowException("select value types should match!");
1881     $$ = new SelectInst($2, $4, $6);
1882   }
1883   | VA_ARG ResolvedVal ',' Types {
1884     // FIXME: This is emulation code for an obsolete syntax.  This should be
1885     // removed at some point.
1886     if (!ObsoleteVarArgs) {
1887       std::cerr << "WARNING: this file uses obsolete features.  "
1888                 << "Assemble and disassemble to update it.\n";
1889       ObsoleteVarArgs = true;
1890     }
1891
1892     // First, load the valist...
1893     Instruction *CurVAList = new LoadInst($2, "");
1894     CurBB->getInstList().push_back(CurVAList);
1895
1896     // Emit the vaarg instruction.
1897     $$ = new VAArgInst(CurVAList, *$4);
1898     
1899     // Now we must advance the pointer and update it in memory.
1900     Instruction *TheVANext = new VANextInst(CurVAList, *$4);
1901     CurBB->getInstList().push_back(TheVANext);
1902
1903     CurBB->getInstList().push_back(new StoreInst(TheVANext, $2));
1904     delete $4;
1905   }
1906   | VAARG ResolvedVal ',' Types {
1907     $$ = new VAArgInst($2, *$4);
1908     delete $4;
1909   }
1910   | VANEXT ResolvedVal ',' Types {
1911     $$ = new VANextInst($2, *$4);
1912     delete $4;
1913   }
1914   | PHI_TOK PHIList {
1915     const Type *Ty = $2->front().first->getType();
1916     if (!Ty->isFirstClassType())
1917       ThrowException("PHI node operands must be of first class type!");
1918     $$ = new PHINode(Ty);
1919     $$->op_reserve($2->size()*2);
1920     while ($2->begin() != $2->end()) {
1921       if ($2->front().first->getType() != Ty) 
1922         ThrowException("All elements of a PHI node must be of the same type!");
1923       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1924       $2->pop_front();
1925     }
1926     delete $2;  // Free the list...
1927   } 
1928   | CALL TypesV ValueRef '(' ValueRefListE ')' {
1929     const PointerType *PFTy;
1930     const FunctionType *Ty;
1931
1932     if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1933         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1934       // Pull out the types of all of the arguments...
1935       std::vector<const Type*> ParamTypes;
1936       if ($5) {
1937         for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1938              I != E; ++I)
1939           ParamTypes.push_back((*I)->getType());
1940       }
1941
1942       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1943       if (isVarArg) ParamTypes.pop_back();
1944
1945       Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1946       PFTy = PointerType::get(Ty);
1947     }
1948
1949     Value *V = getVal(PFTy, $3);   // Get the function we're calling...
1950
1951     // Create the call node...
1952     if (!$5) {                                   // Has no arguments?
1953       // Make sure no arguments is a good thing!
1954       if (Ty->getNumParams() != 0)
1955         ThrowException("No arguments passed to a function that "
1956                        "expects arguments!");
1957
1958       $$ = new CallInst(V, std::vector<Value*>());
1959     } else {                                     // Has arguments?
1960       // Loop through FunctionType's arguments and ensure they are specified
1961       // correctly!
1962       //
1963       FunctionType::param_iterator I = Ty->param_begin();
1964       FunctionType::param_iterator E = Ty->param_end();
1965       std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1966
1967       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1968         if ((*ArgI)->getType() != *I)
1969           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1970                          (*I)->getDescription() + "'!");
1971
1972       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1973         ThrowException("Invalid number of parameters detected!");
1974
1975       $$ = new CallInst(V, *$5);
1976     }
1977     delete $2;
1978     delete $5;
1979   }
1980   | MemoryInst {
1981     $$ = $1;
1982   };
1983
1984
1985 // IndexList - List of indices for GEP based instructions...
1986 IndexList : ',' ValueRefList { 
1987     $$ = $2; 
1988   } | /* empty */ { 
1989     $$ = new std::vector<Value*>(); 
1990   };
1991
1992 OptVolatile : VOLATILE {
1993     $$ = true;
1994   }
1995   | /* empty */ {
1996     $$ = false;
1997   };
1998
1999
2000 MemoryInst : MALLOC Types {
2001     $$ = new MallocInst(*$2);
2002     delete $2;
2003   }
2004   | MALLOC Types ',' UINT ValueRef {
2005     $$ = new MallocInst(*$2, getVal($4, $5));
2006     delete $2;
2007   }
2008   | ALLOCA Types {
2009     $$ = new AllocaInst(*$2);
2010     delete $2;
2011   }
2012   | ALLOCA Types ',' UINT ValueRef {
2013     $$ = new AllocaInst(*$2, getVal($4, $5));
2014     delete $2;
2015   }
2016   | FREE ResolvedVal {
2017     if (!isa<PointerType>($2->getType()))
2018       ThrowException("Trying to free nonpointer type " + 
2019                      $2->getType()->getDescription() + "!");
2020     $$ = new FreeInst($2);
2021   }
2022
2023   | OptVolatile LOAD Types ValueRef {
2024     if (!isa<PointerType>($3->get()))
2025       ThrowException("Can't load from nonpointer type: " +
2026                      (*$3)->getDescription());
2027     $$ = new LoadInst(getVal(*$3, $4), "", $1);
2028     delete $3;
2029   }
2030   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2031     const PointerType *PT = dyn_cast<PointerType>($5->get());
2032     if (!PT)
2033       ThrowException("Can't store to a nonpointer type: " +
2034                      (*$5)->getDescription());
2035     const Type *ElTy = PT->getElementType();
2036     if (ElTy != $3->getType())
2037       ThrowException("Can't store '" + $3->getType()->getDescription() +
2038                      "' into space of type '" + ElTy->getDescription() + "'!");
2039
2040     $$ = new StoreInst($3, getVal(*$5, $6), $1);
2041     delete $5;
2042   }
2043   | GETELEMENTPTR Types ValueRef IndexList {
2044     if (!isa<PointerType>($2->get()))
2045       ThrowException("getelementptr insn requires pointer operand!");
2046
2047     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
2048     // indices to uint struct indices for compatibility.
2049     generic_gep_type_iterator<std::vector<Value*>::iterator>
2050       GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2051       GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2052     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2053       if (isa<StructType>(*GTI))        // Only change struct indices
2054         if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2055           if (CUI->getType() == Type::UByteTy)
2056             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2057
2058     if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2059       ThrowException("Invalid getelementptr indices for type '" +
2060                      (*$2)->getDescription()+ "'!");
2061     $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2062     delete $2; delete $4;
2063   };
2064
2065
2066 %%
2067 int yyerror(const char *ErrorMsg) {
2068   std::string where 
2069     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2070                   + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2071   std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2072   if (yychar == YYEMPTY || yychar == 0)
2073     errMsg += "end-of-file.";
2074   else
2075     errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2076   ThrowException(errMsg);
2077   return 0;
2078 }