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