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