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