Changes For Bug 352
[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 "llvm/ADT/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> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
920 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
921 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comarators
922
923 // Memory Instructions
924 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
925
926 // Other Operators
927 %type  <OtherOpVal> ShiftOps
928 %token <OtherOpVal> PHI_TOK CALL CAST SELECT SHL SHR VAARG VANEXT
929 %token VA_ARG // FIXME: OBSOLETE
930
931 %start Module
932 %%
933
934 // Handle constant integer size restriction and conversion...
935 //
936 INTVAL : SINTVAL;
937 INTVAL : UINTVAL {
938   if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
939     ThrowException("Value too large for type!");
940   $$ = (int32_t)$1;
941 };
942
943
944 EINT64VAL : ESINT64VAL;      // These have same type and can't cause problems...
945 EINT64VAL : EUINT64VAL {
946   if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
947     ThrowException("Value too large for type!");
948   $$ = (int64_t)$1;
949 };
950
951 // Operations that are notably excluded from this list include: 
952 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
953 //
954 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
955 LogicalOps   : AND | OR | XOR;
956 SetCondOps   : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
957
958 ShiftOps  : SHL | SHR;
959
960 // These are some types that allow classification if we only want a particular 
961 // thing... for example, only a signed, unsigned, or integral type.
962 SIntType :  LONG |  INT |  SHORT | SBYTE;
963 UIntType : ULONG | UINT | USHORT | UBYTE;
964 IntType  : SIntType | UIntType;
965 FPType   : FLOAT | DOUBLE;
966
967 // OptAssign - Value producing statements have an optional assignment component
968 OptAssign : Name '=' {
969     $$ = $1;
970   }
971   | /*empty*/ { 
972     $$ = 0; 
973   };
974
975 OptLinkage : INTERNAL  { $$ = GlobalValue::InternalLinkage; } |
976              LINKONCE  { $$ = GlobalValue::LinkOnceLinkage; } |
977              WEAK      { $$ = GlobalValue::WeakLinkage; } |
978              APPENDING { $$ = GlobalValue::AppendingLinkage; } |
979              /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
980
981 //===----------------------------------------------------------------------===//
982 // Types includes all predefined types... except void, because it can only be
983 // used in specific contexts (function returning void for example).  To have
984 // access to it, a user must explicitly use TypesV.
985 //
986
987 // TypesV includes all of 'Types', but it also includes the void type.
988 TypesV    : Types    | VOID { $$ = new PATypeHolder($1); };
989 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
990
991 Types     : UpRTypes {
992     if (!UpRefs.empty())
993       ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
994     $$ = $1;
995   };
996
997
998 // Derived types are added later...
999 //
1000 PrimType : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT ;
1001 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE   | LABEL;
1002 UpRTypes : OPAQUE {
1003     $$ = new PATypeHolder(OpaqueType::get());
1004   }
1005   | PrimType {
1006     $$ = new PATypeHolder($1);
1007   };
1008 UpRTypes : SymbolicValueRef {            // Named types are also simple types...
1009   $$ = new PATypeHolder(getTypeVal($1));
1010 };
1011
1012 // Include derived types in the Types production.
1013 //
1014 UpRTypes : '\\' EUINT64VAL {                   // Type UpReference
1015     if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1016     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1017     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1018     $$ = new PATypeHolder(OT);
1019     UR_OUT("New Upreference!\n");
1020   }
1021   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
1022     std::vector<const Type*> Params;
1023     mapto($3->begin(), $3->end(), std::back_inserter(Params), 
1024           std::mem_fun_ref(&PATypeHolder::get));
1025     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1026     if (isVarArg) Params.pop_back();
1027
1028     $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1029     delete $3;      // Delete the argument list
1030     delete $1;      // Delete the return type handle
1031   }
1032   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
1033     $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1034     delete $4;
1035   }
1036   | '<' EUINT64VAL 'x' UpRTypes '>' {          // Packed array type?
1037      const llvm::Type* ElemTy = $4->get();
1038      if ((unsigned)$2 != $2) {
1039         ThrowException("Unsigned result not equal to signed result");
1040      }
1041      if(!ElemTy->isPrimitiveType()) {
1042         ThrowException("Elemental type of a PackedType must be primitive");
1043      }
1044      $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1045      delete $4;
1046   }
1047   | '{' TypeListI '}' {                        // Structure type?
1048     std::vector<const Type*> Elements;
1049     mapto($2->begin(), $2->end(), std::back_inserter(Elements), 
1050         std::mem_fun_ref(&PATypeHolder::get));
1051
1052     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1053     delete $2;
1054   }
1055   | '{' '}' {                                  // Empty structure type?
1056     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1057   }
1058   | UpRTypes '*' {                             // Pointer type?
1059     $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1060     delete $1;
1061   };
1062
1063 // TypeList - Used for struct declarations and as a basis for function type 
1064 // declaration type lists
1065 //
1066 TypeListI : UpRTypes {
1067     $$ = new std::list<PATypeHolder>();
1068     $$->push_back(*$1); delete $1;
1069   }
1070   | TypeListI ',' UpRTypes {
1071     ($$=$1)->push_back(*$3); delete $3;
1072   };
1073
1074 // ArgTypeList - List of types for a function type declaration...
1075 ArgTypeListI : TypeListI
1076   | TypeListI ',' DOTDOTDOT {
1077     ($$=$1)->push_back(Type::VoidTy);
1078   }
1079   | DOTDOTDOT {
1080     ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1081   }
1082   | /*empty*/ {
1083     $$ = new std::list<PATypeHolder>();
1084   };
1085
1086 // ConstVal - The various declarations that go into the constant pool.  This
1087 // production is used ONLY to represent constants that show up AFTER a 'const',
1088 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1089 // into other expressions (such as integers and constexprs) are handled by the
1090 // ResolvedVal, ValueRef and ConstValueRef productions.
1091 //
1092 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1093     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1094     if (ATy == 0)
1095       ThrowException("Cannot make array constant with type: '" + 
1096                      (*$1)->getDescription() + "'!");
1097     const Type *ETy = ATy->getElementType();
1098     int NumElements = ATy->getNumElements();
1099
1100     // Verify that we have the correct size...
1101     if (NumElements != -1 && NumElements != (int)$3->size())
1102       ThrowException("Type mismatch: constant sized array initialized with " +
1103                      utostr($3->size()) +  " arguments, but has size of " + 
1104                      itostr(NumElements) + "!");
1105
1106     // Verify all elements are correct type!
1107     for (unsigned i = 0; i < $3->size(); i++) {
1108       if (ETy != (*$3)[i]->getType())
1109         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1110                        ETy->getDescription() +"' as required!\nIt is of type '"+
1111                        (*$3)[i]->getType()->getDescription() + "'.");
1112     }
1113
1114     $$ = ConstantArray::get(ATy, *$3);
1115     delete $1; delete $3;
1116   }
1117   | Types '[' ']' {
1118     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1119     if (ATy == 0)
1120       ThrowException("Cannot make array constant with type: '" + 
1121                      (*$1)->getDescription() + "'!");
1122
1123     int NumElements = ATy->getNumElements();
1124     if (NumElements != -1 && NumElements != 0) 
1125       ThrowException("Type mismatch: constant sized array initialized with 0"
1126                      " arguments, but has size of " + itostr(NumElements) +"!");
1127     $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1128     delete $1;
1129   }
1130   | Types 'c' STRINGCONSTANT {
1131     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1132     if (ATy == 0)
1133       ThrowException("Cannot make array constant with type: '" + 
1134                      (*$1)->getDescription() + "'!");
1135
1136     int NumElements = ATy->getNumElements();
1137     const Type *ETy = ATy->getElementType();
1138     char *EndStr = UnEscapeLexed($3, true);
1139     if (NumElements != -1 && NumElements != (EndStr-$3))
1140       ThrowException("Can't build string constant of size " + 
1141                      itostr((int)(EndStr-$3)) +
1142                      " when array has size " + itostr(NumElements) + "!");
1143     std::vector<Constant*> Vals;
1144     if (ETy == Type::SByteTy) {
1145       for (char *C = $3; C != EndStr; ++C)
1146         Vals.push_back(ConstantSInt::get(ETy, *C));
1147     } else if (ETy == Type::UByteTy) {
1148       for (char *C = $3; C != EndStr; ++C)
1149         Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1150     } else {
1151       free($3);
1152       ThrowException("Cannot build string arrays of non byte sized elements!");
1153     }
1154     free($3);
1155     $$ = ConstantArray::get(ATy, Vals);
1156     delete $1;
1157   }
1158   | Types '<' ConstVector '>' { // Nonempty unsized arr
1159     const PackedType *PTy = dyn_cast<PackedType>($1->get());
1160     if (PTy == 0)
1161       ThrowException("Cannot make packed constant with type: '" + 
1162                      (*$1)->getDescription() + "'!");
1163     const Type *ETy = PTy->getElementType();
1164     int NumElements = PTy->getNumElements();
1165
1166     // Verify that we have the correct size...
1167     if (NumElements != -1 && NumElements != (int)$3->size())
1168       ThrowException("Type mismatch: constant sized packed initialized with " +
1169                      utostr($3->size()) +  " arguments, but has size of " + 
1170                      itostr(NumElements) + "!");
1171
1172     // Verify all elements are correct type!
1173     for (unsigned i = 0; i < $3->size(); i++) {
1174       if (ETy != (*$3)[i]->getType())
1175         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1176            ETy->getDescription() +"' as required!\nIt is of type '"+
1177            (*$3)[i]->getType()->getDescription() + "'.");
1178     }
1179
1180     $$ = ConstantPacked::get(PTy, *$3);
1181     delete $1; delete $3;
1182   }
1183   | Types '{' ConstVector '}' {
1184     const StructType *STy = dyn_cast<StructType>($1->get());
1185     if (STy == 0)
1186       ThrowException("Cannot make struct constant with type: '" + 
1187                      (*$1)->getDescription() + "'!");
1188
1189     if ($3->size() != STy->getNumContainedTypes())
1190       ThrowException("Illegal number of initializers for structure type!");
1191
1192     // Check to ensure that constants are compatible with the type initializer!
1193     for (unsigned i = 0, e = $3->size(); i != e; ++i)
1194       if ((*$3)[i]->getType() != STy->getElementType(i))
1195         ThrowException("Expected type '" +
1196                        STy->getElementType(i)->getDescription() +
1197                        "' for element #" + utostr(i) +
1198                        " of structure initializer!");
1199
1200     $$ = ConstantStruct::get(STy, *$3);
1201     delete $1; delete $3;
1202   }
1203   | Types '{' '}' {
1204     const StructType *STy = dyn_cast<StructType>($1->get());
1205     if (STy == 0)
1206       ThrowException("Cannot make struct constant with type: '" + 
1207                      (*$1)->getDescription() + "'!");
1208
1209     if (STy->getNumContainedTypes() != 0)
1210       ThrowException("Illegal number of initializers for structure type!");
1211
1212     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1213     delete $1;
1214   }
1215   | Types NULL_TOK {
1216     const PointerType *PTy = dyn_cast<PointerType>($1->get());
1217     if (PTy == 0)
1218       ThrowException("Cannot make null pointer constant with type: '" + 
1219                      (*$1)->getDescription() + "'!");
1220
1221     $$ = ConstantPointerNull::get(PTy);
1222     delete $1;
1223   }
1224   | Types SymbolicValueRef {
1225     const PointerType *Ty = dyn_cast<PointerType>($1->get());
1226     if (Ty == 0)
1227       ThrowException("Global const reference must be a pointer type!");
1228
1229     // ConstExprs can exist in the body of a function, thus creating
1230     // GlobalValues whenever they refer to a variable.  Because we are in
1231     // the context of a function, getValNonImprovising will search the functions
1232     // symbol table instead of the module symbol table for the global symbol,
1233     // which throws things all off.  To get around this, we just tell
1234     // getValNonImprovising that we are at global scope here.
1235     //
1236     Function *SavedCurFn = CurFun.CurrentFunction;
1237     CurFun.CurrentFunction = 0;
1238
1239     Value *V = getValNonImprovising(Ty, $2);
1240
1241     CurFun.CurrentFunction = SavedCurFn;
1242
1243     // If this is an initializer for a constant pointer, which is referencing a
1244     // (currently) undefined variable, create a stub now that shall be replaced
1245     // in the future with the right type of variable.
1246     //
1247     if (V == 0) {
1248       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1249       const PointerType *PT = cast<PointerType>(Ty);
1250
1251       // First check to see if the forward references value is already created!
1252       PerModuleInfo::GlobalRefsType::iterator I =
1253         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1254     
1255       if (I != CurModule.GlobalRefs.end()) {
1256         V = I->second;             // Placeholder already exists, use it...
1257         $2.destroy();
1258       } else {
1259         std::string Name;
1260         if ($2.Type == ValID::NameVal) Name = $2.Name;
1261
1262         // Create the forward referenced global.
1263         GlobalValue *GV;
1264         if (const FunctionType *FTy = 
1265                  dyn_cast<FunctionType>(PT->getElementType())) {
1266           GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1267                             CurModule.CurrentModule);
1268         } else {
1269           GV = new GlobalVariable(PT->getElementType(), false,
1270                                   GlobalValue::ExternalLinkage, 0,
1271                                   Name, CurModule.CurrentModule);
1272         }
1273
1274         // Keep track of the fact that we have a forward ref to recycle it
1275         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1276         V = GV;
1277       }
1278     }
1279
1280     $$ = cast<GlobalValue>(V);
1281     delete $1;            // Free the type handle
1282   }
1283   | Types ConstExpr {
1284     if ($1->get() != $2->getType())
1285       ThrowException("Mismatched types for constant expression!");
1286     $$ = $2;
1287     delete $1;
1288   }
1289   | Types ZEROINITIALIZER {
1290     $$ = Constant::getNullValue($1->get());
1291     delete $1;
1292   };
1293
1294 ConstVal : SIntType EINT64VAL {      // integral constants
1295     if (!ConstantSInt::isValueValidForType($1, $2))
1296       ThrowException("Constant value doesn't fit in type!");
1297     $$ = ConstantSInt::get($1, $2);
1298   }
1299   | UIntType EUINT64VAL {            // integral constants
1300     if (!ConstantUInt::isValueValidForType($1, $2))
1301       ThrowException("Constant value doesn't fit in type!");
1302     $$ = ConstantUInt::get($1, $2);
1303   }
1304   | BOOL TRUETOK {                      // Boolean constants
1305     $$ = ConstantBool::True;
1306   }
1307   | BOOL FALSETOK {                     // Boolean constants
1308     $$ = ConstantBool::False;
1309   }
1310   | FPType FPVAL {                   // Float & Double constants
1311     $$ = ConstantFP::get($1, $2);
1312   };
1313
1314
1315 ConstExpr: CAST '(' ConstVal TO Types ')' {
1316     if (!$3->getType()->isFirstClassType())
1317       ThrowException("cast constant expression from a non-primitive type: '" +
1318                      $3->getType()->getDescription() + "'!");
1319     if (!$5->get()->isFirstClassType())
1320       ThrowException("cast constant expression to a non-primitive type: '" +
1321                      $5->get()->getDescription() + "'!");
1322     $$ = ConstantExpr::getCast($3, $5->get());
1323     delete $5;
1324   }
1325   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1326     if (!isa<PointerType>($3->getType()))
1327       ThrowException("GetElementPtr requires a pointer operand!");
1328
1329     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
1330     // indices to uint struct indices for compatibility.
1331     generic_gep_type_iterator<std::vector<Value*>::iterator>
1332       GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1333       GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1334     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1335       if (isa<StructType>(*GTI))        // Only change struct indices
1336         if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1337           if (CUI->getType() == Type::UByteTy)
1338             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1339
1340     const Type *IdxTy =
1341       GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1342     if (!IdxTy)
1343       ThrowException("Index list invalid for constant getelementptr!");
1344
1345     std::vector<Constant*> IdxVec;
1346     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1347       if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1348         IdxVec.push_back(C);
1349       else
1350         ThrowException("Indices to constant getelementptr must be constants!");
1351
1352     delete $4;
1353
1354     $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1355   }
1356   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1357     if ($3->getType() != Type::BoolTy)
1358       ThrowException("Select condition must be of boolean type!");
1359     if ($5->getType() != $7->getType())
1360       ThrowException("Select operand types must match!");
1361     $$ = ConstantExpr::getSelect($3, $5, $7);
1362   }
1363   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1364     if ($3->getType() != $5->getType())
1365       ThrowException("Binary operator types must match!");
1366     // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1367     // To retain backward compatibility with these early compilers, we emit a
1368     // cast to the appropriate integer type automatically if we are in the
1369     // broken case.  See PR424 for more information.
1370     if (!isa<PointerType>($3->getType())) {
1371       $$ = ConstantExpr::get($1, $3, $5);
1372     } else {
1373       const Type *IntPtrTy = 0;
1374       switch (CurModule.CurrentModule->getPointerSize()) {
1375       case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1376       case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1377       default: ThrowException("invalid pointer binary constant expr!");
1378       }
1379       $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1380                              ConstantExpr::getCast($5, IntPtrTy));
1381       $$ = ConstantExpr::getCast($$, $3->getType());
1382     }
1383   }
1384   | LogicalOps '(' ConstVal ',' ConstVal ')' {
1385     if ($3->getType() != $5->getType())
1386       ThrowException("Logical operator types must match!");
1387     if (!$3->getType()->isIntegral())
1388       ThrowException("Logical operands must have integral types!");
1389     $$ = ConstantExpr::get($1, $3, $5);
1390   }
1391   | SetCondOps '(' ConstVal ',' ConstVal ')' {
1392     if ($3->getType() != $5->getType())
1393       ThrowException("setcc operand types must match!");
1394     $$ = ConstantExpr::get($1, $3, $5);
1395   }
1396   | ShiftOps '(' ConstVal ',' ConstVal ')' {
1397     if ($5->getType() != Type::UByteTy)
1398       ThrowException("Shift count for shift constant must be unsigned byte!");
1399     if (!$3->getType()->isInteger())
1400       ThrowException("Shift constant expression requires integer operand!");
1401     $$ = ConstantExpr::get($1, $3, $5);
1402   };
1403
1404
1405 // ConstVector - A list of comma separated constants.
1406 ConstVector : ConstVector ',' ConstVal {
1407     ($$ = $1)->push_back($3);
1408   }
1409   | ConstVal {
1410     $$ = new std::vector<Constant*>();
1411     $$->push_back($1);
1412   };
1413
1414
1415 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1416 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1417
1418
1419 //===----------------------------------------------------------------------===//
1420 //                             Rules to match Modules
1421 //===----------------------------------------------------------------------===//
1422
1423 // Module rule: Capture the result of parsing the whole file into a result
1424 // variable...
1425 //
1426 Module : FunctionList {
1427   $$ = ParserResult = $1;
1428   CurModule.ModuleDone();
1429 };
1430
1431 // FunctionList - A list of functions, preceeded by a constant pool.
1432 //
1433 FunctionList : FunctionList Function {
1434     $$ = $1;
1435     CurFun.FunctionDone();
1436   } 
1437   | FunctionList FunctionProto {
1438     $$ = $1;
1439   }
1440   | FunctionList IMPLEMENTATION {
1441     $$ = $1;
1442   }
1443   | ConstPool {
1444     $$ = CurModule.CurrentModule;
1445     // Resolve circular types before we parse the body of the module
1446     ResolveTypes(CurModule.LateResolveTypes);
1447   };
1448
1449 // ConstPool - Constants with optional names assigned to them.
1450 ConstPool : ConstPool OptAssign TYPE TypesV {  // Types can be defined in the const pool
1451     // Eagerly resolve types.  This is not an optimization, this is a
1452     // requirement that is due to the fact that we could have this:
1453     //
1454     // %list = type { %list * }
1455     // %list = type { %list * }    ; repeated type decl
1456     //
1457     // If types are not resolved eagerly, then the two types will not be
1458     // determined to be the same type!
1459     //
1460     ResolveTypeTo($2, *$4);
1461
1462     if (!setTypeName(*$4, $2) && !$2) {
1463       // If this is a named type that is not a redefinition, add it to the slot
1464       // table.
1465       if (inFunctionScope())
1466         CurFun.Types.push_back(*$4);
1467       else
1468         CurModule.Types.push_back(*$4);
1469     }
1470
1471     delete $4;
1472   }
1473   | ConstPool FunctionProto {       // Function prototypes can be in const pool
1474   }
1475   | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1476     if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1477     ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1478   }
1479   | ConstPool OptAssign EXTERNAL GlobalType Types {
1480     ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, *$5, 0);
1481     delete $5;
1482   }
1483   | ConstPool TARGET TargetDefinition { 
1484   }
1485   | ConstPool DEPLIBS '=' LibrariesDefinition {
1486   }
1487   | /* empty: end of list */ { 
1488   };
1489
1490
1491
1492 BigOrLittle : BIG    { $$ = Module::BigEndian; };
1493 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1494
1495 TargetDefinition : ENDIAN '=' BigOrLittle {
1496     CurModule.CurrentModule->setEndianness($3);
1497   }
1498   | POINTERSIZE '=' EUINT64VAL {
1499     if ($3 == 32)
1500       CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1501     else if ($3 == 64)
1502       CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1503     else
1504       ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1505   }
1506   | TRIPLE '=' STRINGCONSTANT {
1507     CurModule.CurrentModule->setTargetTriple($3);
1508     free($3);
1509   };
1510
1511 LibrariesDefinition : '[' LibList ']';
1512
1513 LibList : LibList ',' STRINGCONSTANT {
1514           CurModule.CurrentModule->addLibrary($3);
1515           free($3);
1516         }
1517         | STRINGCONSTANT {
1518           CurModule.CurrentModule->addLibrary($1);
1519           free($1);
1520         }
1521         | /* empty: end of list */ {
1522         }
1523         ;
1524
1525 //===----------------------------------------------------------------------===//
1526 //                       Rules to match Function Headers
1527 //===----------------------------------------------------------------------===//
1528
1529 Name : VAR_ID | STRINGCONSTANT;
1530 OptName : Name | /*empty*/ { $$ = 0; };
1531
1532 ArgVal : Types OptName {
1533   if (*$1 == Type::VoidTy)
1534     ThrowException("void typed arguments are invalid!");
1535   $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1536 };
1537
1538 ArgListH : ArgListH ',' ArgVal {
1539     $$ = $1;
1540     $1->push_back(*$3);
1541     delete $3;
1542   }
1543   | ArgVal {
1544     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1545     $$->push_back(*$1);
1546     delete $1;
1547   };
1548
1549 ArgList : ArgListH {
1550     $$ = $1;
1551   }
1552   | ArgListH ',' DOTDOTDOT {
1553     $$ = $1;
1554     $$->push_back(std::pair<PATypeHolder*,
1555                             char*>(new PATypeHolder(Type::VoidTy), 0));
1556   }
1557   | DOTDOTDOT {
1558     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1559     $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1560   }
1561   | /* empty */ {
1562     $$ = 0;
1563   };
1564
1565 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1566   UnEscapeLexed($2);
1567   std::string FunctionName($2);
1568   free($2);  // Free strdup'd memory!
1569   
1570   if (!(*$1)->isFirstClassType() && *$1 != Type::VoidTy)
1571     ThrowException("LLVM functions cannot return aggregate types!");
1572
1573   std::vector<const Type*> ParamTypeList;
1574   if ($4) {   // If there are arguments...
1575     for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1576          I != $4->end(); ++I)
1577       ParamTypeList.push_back(I->first->get());
1578   }
1579
1580   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1581   if (isVarArg) ParamTypeList.pop_back();
1582
1583   const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1584   const PointerType *PFT = PointerType::get(FT);
1585   delete $1;
1586
1587   ValID ID;
1588   if (!FunctionName.empty()) {
1589     ID = ValID::create((char*)FunctionName.c_str());
1590   } else {
1591     ID = ValID::create((int)CurModule.Values[PFT].size());
1592   }
1593
1594   Function *Fn = 0;
1595   // See if this function was forward referenced.  If so, recycle the object.
1596   if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1597     // Move the function to the end of the list, from whereever it was 
1598     // previously inserted.
1599     Fn = cast<Function>(FWRef);
1600     CurModule.CurrentModule->getFunctionList().remove(Fn);
1601     CurModule.CurrentModule->getFunctionList().push_back(Fn);
1602   } else if (!FunctionName.empty() &&     // Merge with an earlier prototype?
1603              (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1604     // If this is the case, either we need to be a forward decl, or it needs 
1605     // to be.
1606     if (!CurFun.isDeclare && !Fn->isExternal())
1607       ThrowException("Redefinition of function '" + FunctionName + "'!");
1608     
1609     // Make sure to strip off any argument names so we can't get conflicts.
1610     if (Fn->isExternal())
1611       for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend();
1612            AI != AE; ++AI)
1613         AI->setName("");
1614
1615   } else  {  // Not already defined?
1616     Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1617                       CurModule.CurrentModule);
1618     InsertValue(Fn, CurModule.Values);
1619   }
1620
1621   CurFun.FunctionStart(Fn);
1622
1623   // Add all of the arguments we parsed to the function...
1624   if ($4) {                     // Is null if empty...
1625     if (isVarArg) {  // Nuke the last entry
1626       assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1627              "Not a varargs marker!");
1628       delete $4->back().first;
1629       $4->pop_back();  // Delete the last entry
1630     }
1631     Function::aiterator ArgIt = Fn->abegin();
1632     for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1633          I != $4->end(); ++I, ++ArgIt) {
1634       delete I->first;                          // Delete the typeholder...
1635
1636       setValueName(ArgIt, I->second);           // Insert arg into symtab...
1637       InsertValue(ArgIt);
1638     }
1639
1640     delete $4;                     // We're now done with the argument list
1641   }
1642 };
1643
1644 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
1645
1646 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1647   $$ = CurFun.CurrentFunction;
1648
1649   // Make sure that we keep track of the linkage type even if there was a
1650   // previous "declare".
1651   $$->setLinkage($1);
1652
1653   // Resolve circular types before we parse the body of the function.
1654   ResolveTypes(CurFun.LateResolveTypes);
1655 };
1656
1657 END : ENDTOK | '}';                    // Allow end of '}' to end a function
1658
1659 Function : BasicBlockList END {
1660   $$ = $1;
1661 };
1662
1663 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1664   $$ = CurFun.CurrentFunction;
1665   CurFun.FunctionDone();
1666 };
1667
1668 //===----------------------------------------------------------------------===//
1669 //                        Rules to match Basic Blocks
1670 //===----------------------------------------------------------------------===//
1671
1672 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
1673     $$ = ValID::create($1);
1674   }
1675   | EUINT64VAL {
1676     $$ = ValID::create($1);
1677   }
1678   | FPVAL {                     // Perhaps it's an FP constant?
1679     $$ = ValID::create($1);
1680   }
1681   | TRUETOK {
1682     $$ = ValID::create(ConstantBool::True);
1683   } 
1684   | FALSETOK {
1685     $$ = ValID::create(ConstantBool::False);
1686   }
1687   | NULL_TOK {
1688     $$ = ValID::createNull();
1689   }
1690   | '<' ConstVector '>' { // Nonempty unsized packed vector
1691     const Type *ETy = (*$2)[0]->getType();
1692     int NumElements = $2->size(); 
1693     
1694     PackedType* pt = PackedType::get(ETy, NumElements);
1695     PATypeHolder* PTy = new PATypeHolder(
1696                                          HandleUpRefs(
1697                                             PackedType::get(
1698                                                 ETy, 
1699                                                 NumElements)
1700                                             )
1701                                          );
1702     
1703     // Verify all elements are correct type!
1704     for (unsigned i = 0; i < $2->size(); i++) {
1705       if (ETy != (*$2)[i]->getType())
1706         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1707                      ETy->getDescription() +"' as required!\nIt is of type '" +
1708                      (*$2)[i]->getType()->getDescription() + "'.");
1709     }
1710
1711     $$ = ValID::create(ConstantPacked::get(pt, *$2));
1712     delete PTy; delete $2;
1713   }
1714   | ConstExpr {
1715     $$ = ValID::create($1);
1716   };
1717
1718 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1719 // another value.
1720 //
1721 SymbolicValueRef : INTVAL {  // Is it an integer reference...?
1722     $$ = ValID::create($1);
1723   }
1724   | Name {                   // Is it a named reference...?
1725     $$ = ValID::create($1);
1726   };
1727
1728 // ValueRef - A reference to a definition... either constant or symbolic
1729 ValueRef : SymbolicValueRef | ConstValueRef;
1730
1731
1732 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
1733 // type immediately preceeds the value reference, and allows complex constant
1734 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1735 ResolvedVal : Types ValueRef {
1736     $$ = getVal(*$1, $2); delete $1;
1737   };
1738
1739 BasicBlockList : BasicBlockList BasicBlock {
1740     $$ = $1;
1741   }
1742   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
1743     $$ = $1;
1744   };
1745
1746
1747 // Basic blocks are terminated by branching instructions: 
1748 // br, br/cc, switch, ret
1749 //
1750 BasicBlock : InstructionList OptAssign BBTerminatorInst  {
1751     setValueName($3, $2);
1752     InsertValue($3);
1753
1754     $1->getInstList().push_back($3);
1755     InsertValue($1);
1756     $$ = $1;
1757   };
1758
1759 InstructionList : InstructionList Inst {
1760     $1->getInstList().push_back($2);
1761     $$ = $1;
1762   }
1763   | /* empty */ {
1764     $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1765
1766     // Make sure to move the basic block to the correct location in the
1767     // function, instead of leaving it inserted wherever it was first
1768     // referenced.
1769     CurFun.CurrentFunction->getBasicBlockList().remove(CurBB);
1770     CurFun.CurrentFunction->getBasicBlockList().push_back(CurBB);
1771   }
1772   | LABELSTR {
1773     $$ = CurBB = getBBVal(ValID::create($1), true);
1774
1775     // Make sure to move the basic block to the correct location in the
1776     // function, instead of leaving it inserted wherever it was first
1777     // referenced.
1778     CurFun.CurrentFunction->getBasicBlockList().remove(CurBB);
1779     CurFun.CurrentFunction->getBasicBlockList().push_back(CurBB);
1780   };
1781
1782 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
1783     $$ = new ReturnInst($2);
1784   }
1785   | RET VOID {                                       // Return with no result...
1786     $$ = new ReturnInst();
1787   }
1788   | BR LABEL ValueRef {                         // Unconditional Branch...
1789     $$ = new BranchInst(getBBVal($3));
1790   }                                                  // Conditional Branch...
1791   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
1792     $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1793   }
1794   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1795     SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6));
1796     $$ = S;
1797
1798     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1799       E = $8->end();
1800     for (; I != E; ++I)
1801       S->addCase(I->first, I->second);
1802     delete $8;
1803   }
1804   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1805     SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6));
1806     $$ = S;
1807   }
1808   | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO LABEL ValueRef
1809     UNWIND LABEL ValueRef {
1810     const PointerType *PFTy;
1811     const FunctionType *Ty;
1812
1813     if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1814         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1815       // Pull out the types of all of the arguments...
1816       std::vector<const Type*> ParamTypes;
1817       if ($5) {
1818         for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1819              I != E; ++I)
1820           ParamTypes.push_back((*I)->getType());
1821       }
1822
1823       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1824       if (isVarArg) ParamTypes.pop_back();
1825
1826       Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1827       PFTy = PointerType::get(Ty);
1828     }
1829
1830     Value *V = getVal(PFTy, $3);   // Get the function we're calling...
1831
1832     BasicBlock *Normal = getBBVal($9);
1833     BasicBlock *Except = getBBVal($12);
1834
1835     // Create the call node...
1836     if (!$5) {                                   // Has no arguments?
1837       $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1838     } else {                                     // Has arguments?
1839       // Loop through FunctionType's arguments and ensure they are specified
1840       // correctly!
1841       //
1842       FunctionType::param_iterator I = Ty->param_begin();
1843       FunctionType::param_iterator E = Ty->param_end();
1844       std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1845
1846       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1847         if ((*ArgI)->getType() != *I)
1848           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1849                          (*I)->getDescription() + "'!");
1850
1851       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1852         ThrowException("Invalid number of parameters detected!");
1853
1854       $$ = new InvokeInst(V, Normal, Except, *$5);
1855     }
1856     delete $2;
1857     delete $5;
1858   }
1859   | UNWIND {
1860     $$ = new UnwindInst();
1861   };
1862
1863
1864
1865 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1866     $$ = $1;
1867     Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1868     if (V == 0)
1869       ThrowException("May only switch on a constant pool value!");
1870
1871     $$->push_back(std::make_pair(V, getBBVal($6)));
1872   }
1873   | IntType ConstValueRef ',' LABEL ValueRef {
1874     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1875     Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1876
1877     if (V == 0)
1878       ThrowException("May only switch on a constant pool value!");
1879
1880     $$->push_back(std::make_pair(V, getBBVal($5)));
1881   };
1882
1883 Inst : OptAssign InstVal {
1884   // Is this definition named?? if so, assign the name...
1885   setValueName($2, $1);
1886   InsertValue($2);
1887   $$ = $2;
1888 };
1889
1890 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
1891     $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1892     $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
1893     delete $1;
1894   }
1895   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1896     $$ = $1;
1897     $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1898                                  getBBVal($6)));
1899   };
1900
1901
1902 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
1903     $$ = new std::vector<Value*>();
1904     $$->push_back($1);
1905   }
1906   | ValueRefList ',' ResolvedVal {
1907     $$ = $1;
1908     $1->push_back($3);
1909   };
1910
1911 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1912 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1913
1914 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1915     if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() && 
1916         !isa<PackedType>((*$2).get()))
1917       ThrowException(
1918         "Arithmetic operator requires integer, FP, or packed operands!");
1919     if(isa<PackedType>((*$2).get()) && $1 == Instruction::Rem) {
1920       ThrowException(
1921         "Rem not supported on packed types!");
1922     }
1923     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1924     if ($$ == 0)
1925       ThrowException("binary operator returned null!");
1926     delete $2;
1927   }
1928   | LogicalOps Types ValueRef ',' ValueRef {
1929     if (!(*$2)->isIntegral())
1930       ThrowException("Logical operator requires integral operands!");
1931     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1932     if ($$ == 0)
1933       ThrowException("binary operator returned null!");
1934     delete $2;
1935   }
1936   | SetCondOps Types ValueRef ',' ValueRef {
1937     if(isa<PackedType>((*$2).get())) {
1938       ThrowException(
1939         "PackedTypes currently not supported in setcc instructions!");
1940     }
1941     $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1942     if ($$ == 0)
1943       ThrowException("binary operator returned null!");
1944     delete $2;
1945   }
1946   | NOT ResolvedVal {
1947     std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1948               << " Replacing with 'xor'.\n";
1949
1950     Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1951     if (Ones == 0)
1952       ThrowException("Expected integral type for not instruction!");
1953
1954     $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1955     if ($$ == 0)
1956       ThrowException("Could not create a xor instruction!");
1957   }
1958   | ShiftOps ResolvedVal ',' ResolvedVal {
1959     if ($4->getType() != Type::UByteTy)
1960       ThrowException("Shift amount must be ubyte!");
1961     if (!$2->getType()->isInteger())
1962       ThrowException("Shift constant expression requires integer operand!");
1963     $$ = new ShiftInst($1, $2, $4);
1964   }
1965   | CAST ResolvedVal TO Types {
1966     if (!$4->get()->isFirstClassType())
1967       ThrowException("cast instruction to a non-primitive type: '" +
1968                      $4->get()->getDescription() + "'!");
1969     $$ = new CastInst($2, *$4);
1970     delete $4;
1971   }
1972   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1973     if ($2->getType() != Type::BoolTy)
1974       ThrowException("select condition must be boolean!");
1975     if ($4->getType() != $6->getType())
1976       ThrowException("select value types should match!");
1977     $$ = new SelectInst($2, $4, $6);
1978   }
1979   | VA_ARG ResolvedVal ',' Types {
1980     // FIXME: This is emulation code for an obsolete syntax.  This should be
1981     // removed at some point.
1982     if (!ObsoleteVarArgs) {
1983       std::cerr << "WARNING: this file uses obsolete features.  "
1984                 << "Assemble and disassemble to update it.\n";
1985       ObsoleteVarArgs = true;
1986     }
1987
1988     // First, load the valist...
1989     Instruction *CurVAList = new LoadInst($2, "");
1990     CurBB->getInstList().push_back(CurVAList);
1991
1992     // Emit the vaarg instruction.
1993     $$ = new VAArgInst(CurVAList, *$4);
1994     
1995     // Now we must advance the pointer and update it in memory.
1996     Instruction *TheVANext = new VANextInst(CurVAList, *$4);
1997     CurBB->getInstList().push_back(TheVANext);
1998
1999     CurBB->getInstList().push_back(new StoreInst(TheVANext, $2));
2000     delete $4;
2001   }
2002   | VAARG ResolvedVal ',' Types {
2003     $$ = new VAArgInst($2, *$4);
2004     delete $4;
2005   }
2006   | VANEXT ResolvedVal ',' Types {
2007     $$ = new VANextInst($2, *$4);
2008     delete $4;
2009   }
2010   | PHI_TOK PHIList {
2011     const Type *Ty = $2->front().first->getType();
2012     if (!Ty->isFirstClassType())
2013       ThrowException("PHI node operands must be of first class type!");
2014     $$ = new PHINode(Ty);
2015     $$->op_reserve($2->size()*2);
2016     while ($2->begin() != $2->end()) {
2017       if ($2->front().first->getType() != Ty) 
2018         ThrowException("All elements of a PHI node must be of the same type!");
2019       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2020       $2->pop_front();
2021     }
2022     delete $2;  // Free the list...
2023   } 
2024   | CALL TypesV ValueRef '(' ValueRefListE ')' {
2025     const PointerType *PFTy;
2026     const FunctionType *Ty;
2027
2028     if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
2029         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2030       // Pull out the types of all of the arguments...
2031       std::vector<const Type*> ParamTypes;
2032       if ($5) {
2033         for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
2034              I != E; ++I)
2035           ParamTypes.push_back((*I)->getType());
2036       }
2037
2038       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2039       if (isVarArg) ParamTypes.pop_back();
2040
2041       Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
2042       PFTy = PointerType::get(Ty);
2043     }
2044
2045     Value *V = getVal(PFTy, $3);   // Get the function we're calling...
2046
2047     // Create the call node...
2048     if (!$5) {                                   // Has no arguments?
2049       // Make sure no arguments is a good thing!
2050       if (Ty->getNumParams() != 0)
2051         ThrowException("No arguments passed to a function that "
2052                        "expects arguments!");
2053
2054       $$ = new CallInst(V, std::vector<Value*>());
2055     } else {                                     // Has arguments?
2056       // Loop through FunctionType's arguments and ensure they are specified
2057       // correctly!
2058       //
2059       FunctionType::param_iterator I = Ty->param_begin();
2060       FunctionType::param_iterator E = Ty->param_end();
2061       std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
2062
2063       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2064         if ((*ArgI)->getType() != *I)
2065           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2066                          (*I)->getDescription() + "'!");
2067
2068       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2069         ThrowException("Invalid number of parameters detected!");
2070
2071       $$ = new CallInst(V, *$5);
2072     }
2073     delete $2;
2074     delete $5;
2075   }
2076   | MemoryInst {
2077     $$ = $1;
2078   };
2079
2080
2081 // IndexList - List of indices for GEP based instructions...
2082 IndexList : ',' ValueRefList { 
2083     $$ = $2; 
2084   } | /* empty */ { 
2085     $$ = new std::vector<Value*>(); 
2086   };
2087
2088 OptVolatile : VOLATILE {
2089     $$ = true;
2090   }
2091   | /* empty */ {
2092     $$ = false;
2093   };
2094
2095
2096 MemoryInst : MALLOC Types {
2097     $$ = new MallocInst(*$2);
2098     delete $2;
2099   }
2100   | MALLOC Types ',' UINT ValueRef {
2101     $$ = new MallocInst(*$2, getVal($4, $5));
2102     delete $2;
2103   }
2104   | ALLOCA Types {
2105     $$ = new AllocaInst(*$2);
2106     delete $2;
2107   }
2108   | ALLOCA Types ',' UINT ValueRef {
2109     $$ = new AllocaInst(*$2, getVal($4, $5));
2110     delete $2;
2111   }
2112   | FREE ResolvedVal {
2113     if (!isa<PointerType>($2->getType()))
2114       ThrowException("Trying to free nonpointer type " + 
2115                      $2->getType()->getDescription() + "!");
2116     $$ = new FreeInst($2);
2117   }
2118
2119   | OptVolatile LOAD Types ValueRef {
2120     if (!isa<PointerType>($3->get()))
2121       ThrowException("Can't load from nonpointer type: " +
2122                      (*$3)->getDescription());
2123     $$ = new LoadInst(getVal(*$3, $4), "", $1);
2124     delete $3;
2125   }
2126   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2127     const PointerType *PT = dyn_cast<PointerType>($5->get());
2128     if (!PT)
2129       ThrowException("Can't store to a nonpointer type: " +
2130                      (*$5)->getDescription());
2131     const Type *ElTy = PT->getElementType();
2132     if (ElTy != $3->getType())
2133       ThrowException("Can't store '" + $3->getType()->getDescription() +
2134                      "' into space of type '" + ElTy->getDescription() + "'!");
2135
2136     $$ = new StoreInst($3, getVal(*$5, $6), $1);
2137     delete $5;
2138   }
2139   | GETELEMENTPTR Types ValueRef IndexList {
2140     if (!isa<PointerType>($2->get()))
2141       ThrowException("getelementptr insn requires pointer operand!");
2142
2143     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
2144     // indices to uint struct indices for compatibility.
2145     generic_gep_type_iterator<std::vector<Value*>::iterator>
2146       GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2147       GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2148     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2149       if (isa<StructType>(*GTI))        // Only change struct indices
2150         if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2151           if (CUI->getType() == Type::UByteTy)
2152             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2153
2154     if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2155       ThrowException("Invalid getelementptr indices for type '" +
2156                      (*$2)->getDescription()+ "'!");
2157     $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2158     delete $2; delete $4;
2159   };
2160
2161
2162 %%
2163 int yyerror(const char *ErrorMsg) {
2164   std::string where 
2165     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2166                   + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2167   std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2168   if (yychar == YYEMPTY || yychar == 0)
2169     errMsg += "end-of-file.";
2170   else
2171     errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2172   ThrowException(errMsg);
2173   return 0;
2174 }