202c384129efb787973f36466dfed474d5640d01
[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/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/SymbolTable.h"
21 #include "llvm/Assembly/AutoUpgrade.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/MathExtras.h"
25 #include <algorithm>
26 #include <iostream>
27 #include <list>
28 #include <utility>
29
30 // The following is a gross hack. In order to rid the libAsmParser library of
31 // exceptions, we have to have a way of getting the yyparse function to go into
32 // an error situation. So, whenever we want an error to occur, the GenerateError
33 // function (see bottom of file) sets TriggerError. Then, at the end of each 
34 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR 
35 // (a goto) to put YACC in error state. Furthermore, several calls to 
36 // GenerateError are made from inside productions and they must simulate the
37 // previous exception behavior by exiting the production immediately. We have
38 // replaced these with the GEN_ERROR macro which calls GeneratError and then
39 // immediately invokes YYERROR. This would be so much cleaner if it was a 
40 // recursive descent parser.
41 static bool TriggerError = false;
42 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
43 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
44
45 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
46 int yylex();                       // declaration" of xxx warnings.
47 int yyparse();
48
49 namespace llvm {
50   std::string CurFilename;
51 }
52 using namespace llvm;
53
54 static Module *ParserResult;
55
56 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
57 // relating to upreferences in the input stream.
58 //
59 //#define DEBUG_UPREFS 1
60 #ifdef DEBUG_UPREFS
61 #define UR_OUT(X) std::cerr << X
62 #else
63 #define UR_OUT(X)
64 #endif
65
66 #define YYERROR_VERBOSE 1
67
68 static bool ObsoleteVarArgs;
69 static bool NewVarArgs;
70 static BasicBlock *CurBB;
71 static GlobalVariable *CurGV;
72
73
74 // This contains info used when building the body of a function.  It is
75 // destroyed when the function is completed.
76 //
77 typedef std::vector<Value *> ValueList;           // Numbered defs
78 static void 
79 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
80                    std::map<const Type *,ValueList> *FutureLateResolvers = 0);
81
82 static struct PerModuleInfo {
83   Module *CurrentModule;
84   std::map<const Type *, ValueList> Values; // Module level numbered definitions
85   std::map<const Type *,ValueList> LateResolveValues;
86   std::vector<TypeInfo>    Types;
87   std::map<ValID, TypeInfo> LateResolveTypes;
88
89   /// PlaceHolderInfo - When temporary placeholder objects are created, remember
90   /// how they were referenced and on which line of the input they came from so
91   /// that we can resolve them later and print error messages as appropriate.
92   std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
93
94   // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
95   // references to global values.  Global values may be referenced before they
96   // are defined, and if so, the temporary object that they represent is held
97   // here.  This is used for forward references of GlobalValues.
98   //
99   typedef std::map<std::pair<const PointerType *,
100                              ValID>, GlobalValue*> GlobalRefsType;
101   GlobalRefsType GlobalRefs;
102
103   void ModuleDone() {
104     // If we could not resolve some functions at function compilation time
105     // (calls to functions before they are defined), resolve them now...  Types
106     // are resolved when the constant pool has been completely parsed.
107     //
108     ResolveDefinitions(LateResolveValues);
109     if (TriggerError)
110       return;
111
112     // Check to make sure that all global value forward references have been
113     // resolved!
114     //
115     if (!GlobalRefs.empty()) {
116       std::string UndefinedReferences = "Unresolved global references exist:\n";
117
118       for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
119            I != E; ++I) {
120         UndefinedReferences += "  " + I->first.first->getDescription() + " " +
121                                I->first.second.getName() + "\n";
122       }
123       GenerateError(UndefinedReferences);
124       return;
125     }
126
127     // Look for intrinsic functions and CallInst that need to be upgraded
128     for (Module::iterator FI = CurrentModule->begin(),
129          FE = CurrentModule->end(); FI != FE; )
130       UpgradeCallsToIntrinsic(FI++);
131
132     Values.clear();         // Clear out function local definitions
133     Types.clear();
134     CurrentModule = 0;
135   }
136
137   // GetForwardRefForGlobal - Check to see if there is a forward reference
138   // for this global.  If so, remove it from the GlobalRefs map and return it.
139   // If not, just return null.
140   GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
141     // Check to see if there is a forward reference to this global variable...
142     // if there is, eliminate it and patch the reference to use the new def'n.
143     GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
144     GlobalValue *Ret = 0;
145     if (I != GlobalRefs.end()) {
146       Ret = I->second;
147       GlobalRefs.erase(I);
148     }
149     return Ret;
150   }
151 } CurModule;
152
153 static struct PerFunctionInfo {
154   Function *CurrentFunction;     // Pointer to current function being created
155
156   std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
157   std::map<const Type*, ValueList> LateResolveValues;
158   bool isDeclare;                    // Is this function a forward declararation?
159   GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
160
161   /// BBForwardRefs - When we see forward references to basic blocks, keep
162   /// track of them here.
163   std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
164   std::vector<BasicBlock*> NumberedBlocks;
165   unsigned NextBBNum;
166
167   inline PerFunctionInfo() {
168     CurrentFunction = 0;
169     isDeclare = false;
170     Linkage = GlobalValue::ExternalLinkage;    
171   }
172
173   inline void FunctionStart(Function *M) {
174     CurrentFunction = M;
175     NextBBNum = 0;
176   }
177
178   void FunctionDone() {
179     NumberedBlocks.clear();
180
181     // Any forward referenced blocks left?
182     if (!BBForwardRefs.empty()) {
183       GenerateError("Undefined reference to label " +
184                      BBForwardRefs.begin()->first->getName());
185       return;
186     }
187
188     // Resolve all forward references now.
189     ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
190
191     Values.clear();         // Clear out function local definitions
192     CurrentFunction = 0;
193     isDeclare = false;
194     Linkage = GlobalValue::ExternalLinkage;
195   }
196 } CurFun;  // Info for the current function...
197
198 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
199
200
201 //===----------------------------------------------------------------------===//
202 //               Code to handle definitions of all the types
203 //===----------------------------------------------------------------------===//
204
205 static int InsertValue(Value *V,
206                   std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
207   if (V->hasName()) return -1;           // Is this a numbered definition?
208
209   // Yes, insert the value into the value table...
210   ValueList &List = ValueTab[V->getType()];
211   List.push_back(V);
212   return List.size()-1;
213 }
214
215 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
216   switch (D.Type) {
217   case ValID::NumberVal:               // Is it a numbered definition?
218     // Module constants occupy the lowest numbered slots...
219     if ((unsigned)D.Num < CurModule.Types.size())
220       return CurModule.Types[(unsigned)D.Num].type->get();
221     break;
222   case ValID::NameVal:                 // Is it a named definition?
223     if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
224       D.destroy();  // Free old strdup'd memory...
225       return N;
226     }
227     break;
228   default:
229     GenerateError("Internal parser error: Invalid symbol type reference!");
230     return 0;
231   }
232
233   // If we reached here, we referenced either a symbol that we don't know about
234   // or an id number that hasn't been read yet.  We may be referencing something
235   // forward, so just create an entry to be resolved later and get to it...
236   //
237   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
238
239
240   if (inFunctionScope()) {
241     if (D.Type == ValID::NameVal) {
242       GenerateError("Reference to an undefined type: '" + D.getName() + "'");
243       return 0;
244     } else {
245       GenerateError("Reference to an undefined type: #" + itostr(D.Num));
246       return 0;
247     }
248   }
249
250   std::map<ValID, TypeInfo>::iterator I =CurModule.LateResolveTypes.find(D);
251   if (I != CurModule.LateResolveTypes.end())
252     return I->second.type->get();
253
254   TypeInfo TI;
255   TI.type = new PATypeHolder(OpaqueType::get());
256   TI.signedness = isSignless;
257   CurModule.LateResolveTypes.insert(std::make_pair(D, TI));
258   return TI.type->get();
259  }
260
261 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
262   SymbolTable &SymTab =
263     inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
264                         CurModule.CurrentModule->getSymbolTable();
265   return SymTab.lookup(Ty, Name);
266 }
267
268 // getValNonImprovising - Look up the value specified by the provided type and
269 // the provided ValID.  If the value exists and has already been defined, return
270 // it.  Otherwise return null.
271 //
272 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
273   if (isa<FunctionType>(Ty)) {
274     GenerateError("Functions are not values and "
275                    "must be referenced as pointers");
276     return 0;
277   }
278
279   switch (D.Type) {
280   case ValID::NumberVal: {                 // Is it a numbered definition?
281     unsigned Num = (unsigned)D.Num;
282
283     // Module constants occupy the lowest numbered slots...
284     std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
285     if (VI != CurModule.Values.end()) {
286       if (Num < VI->second.size())
287         return VI->second[Num];
288       Num -= VI->second.size();
289     }
290
291     // Make sure that our type is within bounds
292     VI = CurFun.Values.find(Ty);
293     if (VI == CurFun.Values.end()) return 0;
294
295     // Check that the number is within bounds...
296     if (VI->second.size() <= Num) return 0;
297
298     return VI->second[Num];
299   }
300
301   case ValID::NameVal: {                // Is it a named definition?
302     Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
303     if (N == 0) return 0;
304
305     D.destroy();  // Free old strdup'd memory...
306     return N;
307   }
308
309   // Check to make sure that "Ty" is an integral type, and that our
310   // value will fit into the specified type...
311   case ValID::ConstSIntVal:    // Is it a constant pool reference??
312     if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
313       GenerateError("Signed integral constant '" +
314                      itostr(D.ConstPool64) + "' is invalid for type '" +
315                      Ty->getDescription() + "'!");
316       return 0;
317     }
318     return ConstantInt::get(Ty, D.ConstPool64);
319
320   case ValID::ConstUIntVal:     // Is it an unsigned const pool reference?
321     if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
322       if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
323         GenerateError("Integral constant '" + utostr(D.UConstPool64) +
324                        "' is invalid or out of range!");
325         return 0;
326       } else {     // This is really a signed reference.  Transmogrify.
327         return ConstantInt::get(Ty, D.ConstPool64);
328       }
329     } else {
330       return ConstantInt::get(Ty, D.UConstPool64);
331     }
332
333   case ValID::ConstFPVal:        // Is it a floating point const pool reference?
334     if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
335       GenerateError("FP constant invalid for type!!");
336       return 0;
337     }
338     return ConstantFP::get(Ty, D.ConstPoolFP);
339
340   case ValID::ConstNullVal:      // Is it a null value?
341     if (!isa<PointerType>(Ty)) {
342       GenerateError("Cannot create a a non pointer null!");
343       return 0;
344     }
345     return ConstantPointerNull::get(cast<PointerType>(Ty));
346
347   case ValID::ConstUndefVal:      // Is it an undef value?
348     return UndefValue::get(Ty);
349
350   case ValID::ConstZeroVal:      // Is it a zero value?
351     return Constant::getNullValue(Ty);
352     
353   case ValID::ConstantVal:       // Fully resolved constant?
354     if (D.ConstantValue->getType() != Ty) {
355       GenerateError("Constant expression type different from required type!");
356       return 0;
357     }
358     return D.ConstantValue;
359
360   case ValID::InlineAsmVal: {    // Inline asm expression
361     const PointerType *PTy = dyn_cast<PointerType>(Ty);
362     const FunctionType *FTy =
363       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
364     if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
365       GenerateError("Invalid type for asm constraint string!");
366       return 0;
367     }
368     InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
369                                    D.IAD->HasSideEffects);
370     D.destroy();   // Free InlineAsmDescriptor.
371     return IA;
372   }
373   default:
374     assert(0 && "Unhandled case!");
375     return 0;
376   }   // End of switch
377
378   assert(0 && "Unhandled case!");
379   return 0;
380 }
381
382 // getVal - This function is identical to getValNonImprovising, except that if a
383 // value is not already defined, it "improvises" by creating a placeholder var
384 // that looks and acts just like the requested variable.  When the value is
385 // defined later, all uses of the placeholder variable are replaced with the
386 // real thing.
387 //
388 static Value *getVal(const Type *Ty, const ValID &ID) {
389   if (Ty == Type::LabelTy) {
390     GenerateError("Cannot use a basic block here");
391     return 0;
392   }
393
394   // See if the value has already been defined.
395   Value *V = getValNonImprovising(Ty, ID);
396   if (V) return V;
397   if (TriggerError) return 0;
398
399   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
400     GenerateError("Invalid use of a composite type!");
401     return 0;
402   }
403
404   // If we reached here, we referenced either a symbol that we don't know about
405   // or an id number that hasn't been read yet.  We may be referencing something
406   // forward, so just create an entry to be resolved later and get to it...
407   //
408   V = new Argument(Ty);
409
410   // Remember where this forward reference came from.  FIXME, shouldn't we try
411   // to recycle these things??
412   CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
413                                                                llvmAsmlineno)));
414
415   if (inFunctionScope())
416     InsertValue(V, CurFun.LateResolveValues);
417   else
418     InsertValue(V, CurModule.LateResolveValues);
419   return V;
420 }
421
422 /// getBBVal - This is used for two purposes:
423 ///  * If isDefinition is true, a new basic block with the specified ID is being
424 ///    defined.
425 ///  * If isDefinition is true, this is a reference to a basic block, which may
426 ///    or may not be a forward reference.
427 ///
428 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
429   assert(inFunctionScope() && "Can't get basic block at global scope!");
430
431   std::string Name;
432   BasicBlock *BB = 0;
433   switch (ID.Type) {
434   default: 
435     GenerateError("Illegal label reference " + ID.getName());
436     return 0;
437   case ValID::NumberVal:                // Is it a numbered definition?
438     if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
439       CurFun.NumberedBlocks.resize(ID.Num+1);
440     BB = CurFun.NumberedBlocks[ID.Num];
441     break;
442   case ValID::NameVal:                  // Is it a named definition?
443     Name = ID.Name;
444     if (Value *N = CurFun.CurrentFunction->
445                    getSymbolTable().lookup(Type::LabelTy, Name))
446       BB = cast<BasicBlock>(N);
447     break;
448   }
449
450   // See if the block has already been defined.
451   if (BB) {
452     // If this is the definition of the block, make sure the existing value was
453     // just a forward reference.  If it was a forward reference, there will be
454     // an entry for it in the PlaceHolderInfo map.
455     if (isDefinition && !CurFun.BBForwardRefs.erase(BB)) {
456       // The existing value was a definition, not a forward reference.
457       GenerateError("Redefinition of label " + ID.getName());
458       return 0;
459     }
460
461     ID.destroy();                       // Free strdup'd memory.
462     return BB;
463   }
464
465   // Otherwise this block has not been seen before.
466   BB = new BasicBlock("", CurFun.CurrentFunction);
467   if (ID.Type == ValID::NameVal) {
468     BB->setName(ID.Name);
469   } else {
470     CurFun.NumberedBlocks[ID.Num] = BB;
471   }
472
473   // If this is not a definition, keep track of it so we can use it as a forward
474   // reference.
475   if (!isDefinition) {
476     // Remember where this forward reference came from.
477     CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
478   } else {
479     // The forward declaration could have been inserted anywhere in the
480     // function: insert it into the correct place now.
481     CurFun.CurrentFunction->getBasicBlockList().remove(BB);
482     CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
483   }
484   ID.destroy();
485   return BB;
486 }
487
488
489 //===----------------------------------------------------------------------===//
490 //              Code to handle forward references in instructions
491 //===----------------------------------------------------------------------===//
492 //
493 // This code handles the late binding needed with statements that reference
494 // values not defined yet... for example, a forward branch, or the PHI node for
495 // a loop body.
496 //
497 // This keeps a table (CurFun.LateResolveValues) of all such forward references
498 // and back patchs after we are done.
499 //
500
501 // ResolveDefinitions - If we could not resolve some defs at parsing
502 // time (forward branches, phi functions for loops, etc...) resolve the
503 // defs now...
504 //
505 static void 
506 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
507                    std::map<const Type*,ValueList> *FutureLateResolvers) {
508   // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
509   for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
510          E = LateResolvers.end(); LRI != E; ++LRI) {
511     ValueList &List = LRI->second;
512     while (!List.empty()) {
513       Value *V = List.back();
514       List.pop_back();
515
516       std::map<Value*, std::pair<ValID, int> >::iterator PHI =
517         CurModule.PlaceHolderInfo.find(V);
518       assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
519
520       ValID &DID = PHI->second.first;
521
522       Value *TheRealValue = getValNonImprovising(LRI->first, DID);
523       if (TriggerError)
524         return;
525       if (TheRealValue) {
526         V->replaceAllUsesWith(TheRealValue);
527         delete V;
528         CurModule.PlaceHolderInfo.erase(PHI);
529       } else if (FutureLateResolvers) {
530         // Functions have their unresolved items forwarded to the module late
531         // resolver table
532         InsertValue(V, *FutureLateResolvers);
533       } else {
534         if (DID.Type == ValID::NameVal) {
535           GenerateError("Reference to an invalid definition: '" +DID.getName()+
536                          "' of type '" + V->getType()->getDescription() + "'",
537                          PHI->second.second);
538           return;
539         } else {
540           GenerateError("Reference to an invalid definition: #" +
541                          itostr(DID.Num) + " of type '" +
542                          V->getType()->getDescription() + "'",
543                          PHI->second.second);
544           return;
545         }
546       }
547     }
548   }
549
550   LateResolvers.clear();
551 }
552
553 // ResolveTypeTo - A brand new type was just declared.  This means that (if
554 // name is not null) things referencing Name can be resolved.  Otherwise, things
555 // refering to the number can be resolved.  Do this now.
556 //
557 static void ResolveTypeTo(char *Name, const Type *ToTy) {
558   ValID D;
559   if (Name) D = ValID::create(Name);
560   else      D = ValID::create((int)CurModule.Types.size());
561
562   std::map<ValID, TypeInfo>::iterator I =
563     CurModule.LateResolveTypes.find(D);
564   if (I != CurModule.LateResolveTypes.end()) {
565     ((DerivedType*)I->second.type->get())->refineAbstractTypeTo(ToTy);
566     CurModule.LateResolveTypes.erase(I);
567   }
568 }
569
570 // setValueName - Set the specified value to the name given.  The name may be
571 // null potentially, in which case this is a noop.  The string passed in is
572 // assumed to be a malloc'd string buffer, and is free'd by this function.
573 //
574 static void setValueName(Value *V, char *NameStr) {
575   if (NameStr) {
576     std::string Name(NameStr);      // Copy string
577     free(NameStr);                  // Free old string
578
579     if (V->getType() == Type::VoidTy) {
580       GenerateError("Can't assign name '" + Name+"' to value with void type!");
581       return;
582     }
583
584     assert(inFunctionScope() && "Must be in function scope!");
585     SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
586     if (ST.lookup(V->getType(), Name)) {
587       GenerateError("Redefinition of value named '" + Name + "' in the '" +
588                      V->getType()->getDescription() + "' type plane!");
589       return;
590     }
591
592     // Set the name.
593     V->setName(Name);
594   }
595 }
596
597 /// ParseGlobalVariable - Handle parsing of a global.  If Initializer is null,
598 /// this is a declaration, otherwise it is a definition.
599 static GlobalVariable *
600 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
601                     bool isConstantGlobal, const Type *Ty,
602                     Constant *Initializer) {
603   if (isa<FunctionType>(Ty)) {
604     GenerateError("Cannot declare global vars of function type!");
605     return 0;
606   }
607
608   const PointerType *PTy = PointerType::get(Ty);
609
610   std::string Name;
611   if (NameStr) {
612     Name = NameStr;      // Copy string
613     free(NameStr);       // Free old string
614   }
615
616   // See if this global value was forward referenced.  If so, recycle the
617   // object.
618   ValID ID;
619   if (!Name.empty()) {
620     ID = ValID::create((char*)Name.c_str());
621   } else {
622     ID = ValID::create((int)CurModule.Values[PTy].size());
623   }
624
625   if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
626     // Move the global to the end of the list, from whereever it was
627     // previously inserted.
628     GlobalVariable *GV = cast<GlobalVariable>(FWGV);
629     CurModule.CurrentModule->getGlobalList().remove(GV);
630     CurModule.CurrentModule->getGlobalList().push_back(GV);
631     GV->setInitializer(Initializer);
632     GV->setLinkage(Linkage);
633     GV->setConstant(isConstantGlobal);
634     InsertValue(GV, CurModule.Values);
635     return GV;
636   }
637
638   // If this global has a name, check to see if there is already a definition
639   // of this global in the module.  If so, merge as appropriate.  Note that
640   // this is really just a hack around problems in the CFE.  :(
641   if (!Name.empty()) {
642     // We are a simple redefinition of a value, check to see if it is defined
643     // the same as the old one.
644     if (GlobalVariable *EGV =
645                 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
646       // We are allowed to redefine a global variable in two circumstances:
647       // 1. If at least one of the globals is uninitialized or
648       // 2. If both initializers have the same value.
649       //
650       if (!EGV->hasInitializer() || !Initializer ||
651           EGV->getInitializer() == Initializer) {
652
653         // Make sure the existing global version gets the initializer!  Make
654         // sure that it also gets marked const if the new version is.
655         if (Initializer && !EGV->hasInitializer())
656           EGV->setInitializer(Initializer);
657         if (isConstantGlobal)
658           EGV->setConstant(true);
659         EGV->setLinkage(Linkage);
660         return EGV;
661       }
662
663       GenerateError("Redefinition of global variable named '" + Name +
664                      "' in the '" + Ty->getDescription() + "' type plane!");
665       return 0;
666     }
667   }
668
669   // Otherwise there is no existing GV to use, create one now.
670   GlobalVariable *GV =
671     new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
672                        CurModule.CurrentModule);
673   InsertValue(GV, CurModule.Values);
674   return GV;
675 }
676
677 // setTypeName - Set the specified type to the name given.  The name may be
678 // null potentially, in which case this is a noop.  The string passed in is
679 // assumed to be a malloc'd string buffer, and is freed by this function.
680 //
681 // This function returns true if the type has already been defined, but is
682 // allowed to be redefined in the specified context.  If the name is a new name
683 // for the type plane, it is inserted and false is returned.
684 static bool setTypeName(const Type *T, char *NameStr) {
685   assert(!inFunctionScope() && "Can't give types function-local names!");
686   if (NameStr == 0) return false;
687  
688   std::string Name(NameStr);      // Copy string
689   free(NameStr);                  // Free old string
690
691   // We don't allow assigning names to void type
692   if (T == Type::VoidTy) {
693     GenerateError("Can't assign name '" + Name + "' to the void type!");
694     return false;
695   }
696
697   // Set the type name, checking for conflicts as we do so.
698   bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
699
700   if (AlreadyExists) {   // Inserting a name that is already defined???
701     const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
702     assert(Existing && "Conflict but no matching type?");
703
704     // There is only one case where this is allowed: when we are refining an
705     // opaque type.  In this case, Existing will be an opaque type.
706     if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
707       // We ARE replacing an opaque type!
708       const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
709       return true;
710     }
711
712     // Otherwise, this is an attempt to redefine a type. That's okay if
713     // the redefinition is identical to the original. This will be so if
714     // Existing and T point to the same Type object. In this one case we
715     // allow the equivalent redefinition.
716     if (Existing == T) return true;  // Yes, it's equal.
717
718     // Any other kind of (non-equivalent) redefinition is an error.
719     GenerateError("Redefinition of type named '" + Name + "' in the '" +
720                    T->getDescription() + "' type plane!");
721   }
722
723   return false;
724 }
725
726 //===----------------------------------------------------------------------===//
727 // Code for handling upreferences in type names...
728 //
729
730 // TypeContains - Returns true if Ty directly contains E in it.
731 //
732 static bool TypeContains(const Type *Ty, const Type *E) {
733   return std::find(Ty->subtype_begin(), Ty->subtype_end(),
734                    E) != Ty->subtype_end();
735 }
736
737 namespace {
738   struct UpRefRecord {
739     // NestingLevel - The number of nesting levels that need to be popped before
740     // this type is resolved.
741     unsigned NestingLevel;
742
743     // LastContainedTy - This is the type at the current binding level for the
744     // type.  Every time we reduce the nesting level, this gets updated.
745     const Type *LastContainedTy;
746
747     // UpRefTy - This is the actual opaque type that the upreference is
748     // represented with.
749     OpaqueType *UpRefTy;
750
751     UpRefRecord(unsigned NL, OpaqueType *URTy)
752       : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
753   };
754 }
755
756 // UpRefs - A list of the outstanding upreferences that need to be resolved.
757 static std::vector<UpRefRecord> UpRefs;
758
759 /// HandleUpRefs - Every time we finish a new layer of types, this function is
760 /// called.  It loops through the UpRefs vector, which is a list of the
761 /// currently active types.  For each type, if the up reference is contained in
762 /// the newly completed type, we decrement the level count.  When the level
763 /// count reaches zero, the upreferenced type is the type that is passed in:
764 /// thus we can complete the cycle.
765 ///
766 static PATypeHolder HandleUpRefs(const Type *ty) {
767   // If Ty isn't abstract, or if there are no up-references in it, then there is
768   // nothing to resolve here.
769   if (!ty->isAbstract() || UpRefs.empty()) return ty;
770   
771   PATypeHolder Ty(ty);
772   UR_OUT("Type '" << Ty->getDescription() <<
773          "' newly formed.  Resolving upreferences.\n" <<
774          UpRefs.size() << " upreferences active!\n");
775
776   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
777   // to zero), we resolve them all together before we resolve them to Ty.  At
778   // the end of the loop, if there is anything to resolve to Ty, it will be in
779   // this variable.
780   OpaqueType *TypeToResolve = 0;
781
782   for (unsigned i = 0; i != UpRefs.size(); ++i) {
783     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
784            << UpRefs[i].second->getDescription() << ") = "
785            << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
786     if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
787       // Decrement level of upreference
788       unsigned Level = --UpRefs[i].NestingLevel;
789       UpRefs[i].LastContainedTy = Ty;
790       UR_OUT("  Uplevel Ref Level = " << Level << "\n");
791       if (Level == 0) {                     // Upreference should be resolved!
792         if (!TypeToResolve) {
793           TypeToResolve = UpRefs[i].UpRefTy;
794         } else {
795           UR_OUT("  * Resolving upreference for "
796                  << UpRefs[i].second->getDescription() << "\n";
797                  std::string OldName = UpRefs[i].UpRefTy->getDescription());
798           UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
799           UR_OUT("  * Type '" << OldName << "' refined upreference to: "
800                  << (const void*)Ty << ", " << Ty->getDescription() << "\n");
801         }
802         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
803         --i;                                // Do not skip the next element...
804       }
805     }
806   }
807
808   if (TypeToResolve) {
809     UR_OUT("  * Resolving upreference for "
810            << UpRefs[i].second->getDescription() << "\n";
811            std::string OldName = TypeToResolve->getDescription());
812     TypeToResolve->refineAbstractTypeTo(Ty);
813   }
814
815   return Ty;
816 }
817
818 /// This function is used to obtain the correct opcode for an instruction when 
819 /// an obsolete opcode is encountered. The OI parameter (OpcodeInfo) has both 
820 /// an opcode and an "obsolete" flag. These are generated by the lexer and 
821 /// the "obsolete" member will be true when the lexer encounters the token for
822 /// an obsolete opcode. For example, "div" was replaced by [usf]div but we need
823 /// to maintain backwards compatibility for asm files that still have the "div"
824 /// instruction. This function handles converting div -> [usf]div appropriately.
825 /// @brief Convert obsolete BinaryOps opcodes to new values
826 static void 
827 sanitizeOpcode(OpcodeInfo<Instruction::BinaryOps> &OI, const Type *Ty)
828 {
829   // If its not obsolete, don't do anything
830   if (!OI.obsolete) 
831     return;
832
833   // If its a packed type we want to use the element type
834   if (const PackedType *PTy = dyn_cast<PackedType>(Ty))
835     Ty = PTy->getElementType();
836
837   // Depending on the opcode ..
838   switch (OI.opcode) {
839     default:
840       GenerateError("Invalid obsolete opCode (check Lexer.l)");
841       break;
842     case Instruction::UDiv:
843       // Handle cases where the opcode needs to change
844       if (Ty->isFloatingPoint()) 
845         OI.opcode = Instruction::FDiv;
846       else if (Ty->isSigned())
847         OI.opcode = Instruction::SDiv;
848       break;
849     case Instruction::URem:
850       if (Ty->isFloatingPoint()) 
851         OI.opcode = Instruction::FRem;
852       else if (Ty->isSigned())
853         OI.opcode = Instruction::SRem;
854       break;
855   }
856   // Its not obsolete any more, we fixed it.
857   OI.obsolete = false;
858 }
859
860 /// This function is similar to the previous overload of sanitizeOpcode but
861 /// operates on Instruction::OtherOps instead of Instruction::BinaryOps.
862 /// @brief Convert obsolete OtherOps opcodes to new values
863 static void 
864 sanitizeOpcode(OpcodeInfo<Instruction::OtherOps> &OI, const Type *Ty)
865 {
866   // If its not obsolete, don't do anything
867   if (!OI.obsolete) 
868     return;
869
870   switch (OI.opcode) {
871   default:
872     GenerateError("Invalid obsolete opcode (check Lexer.l)");
873     break;
874   case Instruction::LShr:
875     if (Ty->isSigned())
876       OI.opcode = Instruction::AShr;
877     break;
878   }
879   // Its not obsolete any more, we fixed it.
880   OI.obsolete = false;
881 }
882
883 // common code from the two 'RunVMAsmParser' functions
884 static Module* RunParser(Module * M) {
885
886   llvmAsmlineno = 1;      // Reset the current line number...
887   ObsoleteVarArgs = false;
888   NewVarArgs = false;
889   CurModule.CurrentModule = M;
890
891   // Check to make sure the parser succeeded
892   if (yyparse()) {
893     if (ParserResult)
894       delete ParserResult;
895     return 0;
896   }
897
898   // Check to make sure that parsing produced a result
899   if (!ParserResult)
900     return 0;
901
902   // Reset ParserResult variable while saving its value for the result.
903   Module *Result = ParserResult;
904   ParserResult = 0;
905
906   //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
907   {
908     Function* F;
909     if ((F = Result->getNamedFunction("llvm.va_start"))
910         && F->getFunctionType()->getNumParams() == 0)
911       ObsoleteVarArgs = true;
912     if((F = Result->getNamedFunction("llvm.va_copy"))
913        && F->getFunctionType()->getNumParams() == 1)
914       ObsoleteVarArgs = true;
915   }
916
917   if (ObsoleteVarArgs && NewVarArgs) {
918     GenerateError(
919       "This file is corrupt: it uses both new and old style varargs");
920     return 0;
921   }
922
923   if(ObsoleteVarArgs) {
924     if(Function* F = Result->getNamedFunction("llvm.va_start")) {
925       if (F->arg_size() != 0) {
926         GenerateError("Obsolete va_start takes 0 argument!");
927         return 0;
928       }
929       
930       //foo = va_start()
931       // ->
932       //bar = alloca typeof(foo)
933       //va_start(bar)
934       //foo = load bar
935
936       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
937       const Type* ArgTy = F->getFunctionType()->getReturnType();
938       const Type* ArgTyPtr = PointerType::get(ArgTy);
939       Function* NF = Result->getOrInsertFunction("llvm.va_start", 
940                                                  RetTy, ArgTyPtr, (Type *)0);
941
942       while (!F->use_empty()) {
943         CallInst* CI = cast<CallInst>(F->use_back());
944         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
945         new CallInst(NF, bar, "", CI);
946         Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
947         CI->replaceAllUsesWith(foo);
948         CI->getParent()->getInstList().erase(CI);
949       }
950       Result->getFunctionList().erase(F);
951     }
952     
953     if(Function* F = Result->getNamedFunction("llvm.va_end")) {
954       if(F->arg_size() != 1) {
955         GenerateError("Obsolete va_end takes 1 argument!");
956         return 0;
957       }
958
959       //vaend foo
960       // ->
961       //bar = alloca 1 of typeof(foo)
962       //vaend bar
963       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
964       const Type* ArgTy = F->getFunctionType()->getParamType(0);
965       const Type* ArgTyPtr = PointerType::get(ArgTy);
966       Function* NF = Result->getOrInsertFunction("llvm.va_end", 
967                                                  RetTy, ArgTyPtr, (Type *)0);
968
969       while (!F->use_empty()) {
970         CallInst* CI = cast<CallInst>(F->use_back());
971         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
972         new StoreInst(CI->getOperand(1), bar, CI);
973         new CallInst(NF, bar, "", CI);
974         CI->getParent()->getInstList().erase(CI);
975       }
976       Result->getFunctionList().erase(F);
977     }
978
979     if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
980       if(F->arg_size() != 1) {
981         GenerateError("Obsolete va_copy takes 1 argument!");
982         return 0;
983       }
984       //foo = vacopy(bar)
985       // ->
986       //a = alloca 1 of typeof(foo)
987       //b = alloca 1 of typeof(foo)
988       //store bar -> b
989       //vacopy(a, b)
990       //foo = load a
991       
992       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
993       const Type* ArgTy = F->getFunctionType()->getReturnType();
994       const Type* ArgTyPtr = PointerType::get(ArgTy);
995       Function* NF = Result->getOrInsertFunction("llvm.va_copy", 
996                                                  RetTy, ArgTyPtr, ArgTyPtr,
997                                                  (Type *)0);
998
999       while (!F->use_empty()) {
1000         CallInst* CI = cast<CallInst>(F->use_back());
1001         AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1002         AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1003         new StoreInst(CI->getOperand(1), b, CI);
1004         new CallInst(NF, a, b, "", CI);
1005         Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1006         CI->replaceAllUsesWith(foo);
1007         CI->getParent()->getInstList().erase(CI);
1008       }
1009       Result->getFunctionList().erase(F);
1010     }
1011   }
1012
1013   return Result;
1014 }
1015
1016 //===----------------------------------------------------------------------===//
1017 //            RunVMAsmParser - Define an interface to this parser
1018 //===----------------------------------------------------------------------===//
1019 //
1020 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
1021   set_scan_file(F);
1022
1023   CurFilename = Filename;
1024   return RunParser(new Module(CurFilename));
1025 }
1026
1027 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
1028   set_scan_string(AsmString);
1029
1030   CurFilename = "from_memory";
1031   if (M == NULL) {
1032     return RunParser(new Module (CurFilename));
1033   } else {
1034     return RunParser(M);
1035   }
1036 }
1037
1038 %}
1039
1040 %union {
1041   llvm::Module                           *ModuleVal;
1042   llvm::Function                         *FunctionVal;
1043   std::pair<TypeInfo, char*>             *ArgVal;
1044   llvm::BasicBlock                       *BasicBlockVal;
1045   llvm::TerminatorInst                   *TermInstVal;
1046   llvm::Instruction                      *InstVal;
1047   llvm::Constant                         *ConstVal;
1048
1049   TypeInfo                                TypeVal;
1050   llvm::Value                            *ValueVal;
1051
1052   std::vector<std::pair<TypeInfo,char*> >*ArgList;
1053   std::vector<llvm::Value*>              *ValueList;
1054   std::list<TypeInfo>                    *TypeList;
1055   // Represent the RHS of PHI node
1056   std::list<std::pair<llvm::Value*,
1057                       llvm::BasicBlock*> > *PHIList;
1058   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1059   std::vector<llvm::Constant*>           *ConstVector;
1060
1061   llvm::GlobalValue::LinkageTypes         Linkage;
1062   int64_t                           SInt64Val;
1063   uint64_t                          UInt64Val;
1064   int                               SIntVal;
1065   unsigned                          UIntVal;
1066   double                            FPVal;
1067   bool                              BoolVal;
1068
1069   char                             *StrVal;   // This memory is strdup'd!
1070   llvm::ValID                       ValIDVal; // strdup'd memory maybe!
1071
1072   BinaryOpInfo                      BinaryOpVal;
1073   TermOpInfo                        TermOpVal;
1074   MemOpInfo                         MemOpVal;
1075   CastOpInfo                        CastOpVal;
1076   OtherOpInfo                       OtherOpVal;
1077   llvm::Module::Endianness          Endianness;
1078 }
1079
1080 %type <ModuleVal>     Module FunctionList
1081 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
1082 %type <BasicBlockVal> BasicBlock InstructionList
1083 %type <TermInstVal>   BBTerminatorInst
1084 %type <InstVal>       Inst InstVal MemoryInst
1085 %type <ConstVal>      ConstVal ConstExpr
1086 %type <ConstVector>   ConstVector
1087 %type <ArgList>       ArgList ArgListH
1088 %type <ArgVal>        ArgVal
1089 %type <PHIList>       PHIList
1090 %type <ValueList>     ValueRefList ValueRefListE  // For call param lists
1091 %type <ValueList>     IndexList                   // For GEP derived indices
1092 %type <TypeList>      TypeListI ArgTypeListI
1093 %type <JumpTable>     JumpTable
1094 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
1095 %type <BoolVal>       OptVolatile                 // 'volatile' or not
1096 %type <BoolVal>       OptTailCall                 // TAIL CALL or plain CALL.
1097 %type <BoolVal>       OptSideEffect               // 'sideeffect' or not.
1098 %type <Linkage>       OptLinkage
1099 %type <Endianness>    BigOrLittle
1100
1101 // ValueRef - Unresolved reference to a definition or BB
1102 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
1103 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
1104 // Tokens and types for handling constant integer values
1105 //
1106 // ESINT64VAL - A negative number within long long range
1107 %token <SInt64Val> ESINT64VAL
1108
1109 // EUINT64VAL - A positive number within uns. long long range
1110 %token <UInt64Val> EUINT64VAL
1111 %type  <SInt64Val> EINT64VAL
1112
1113 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
1114 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
1115 %type   <SIntVal>   INTVAL
1116 %token  <FPVal>     FPVAL     // Float or Double constant
1117
1118 // Built in types...
1119 %type  <TypeVal> Types TypesV UpRTypes UpRTypesV
1120 %type  <TypeVal> SIntType UIntType IntType FPType PrimType   // Classifications
1121 %token <TypeVal> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1122 %token <TypeVal> FLOAT DOUBLE TYPE LABEL
1123
1124 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1125 %type  <StrVal> Name OptName OptAssign
1126 %type  <UIntVal> OptAlign OptCAlign
1127 %type <StrVal> OptSection SectionString
1128
1129 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1130 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1131 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1132 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1133 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1134 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1135 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1136 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1137 %token DATALAYOUT
1138 %type <UIntVal> OptCallingConv
1139
1140 // Basic Block Terminating Operators
1141 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1142
1143 // Binary Operators
1144 %type  <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1145 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1146 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comparators
1147
1148 // Memory Instructions
1149 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1150
1151 // Cast Operators
1152 %type <CastOpVal> CastOps
1153 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1154 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1155
1156 // Other Operators
1157 %type  <OtherOpVal> ShiftOps
1158 %token <OtherOpVal> PHI_TOK SELECT SHL LSHR ASHR VAARG
1159 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1160 %token VAARG_old VANEXT_old //OBSOLETE
1161
1162
1163 %start Module
1164 %%
1165
1166 // Handle constant integer size restriction and conversion...
1167 //
1168 INTVAL : SINTVAL;
1169 INTVAL : UINTVAL {
1170   if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
1171     GEN_ERROR("Value too large for type!");
1172   $$ = (int32_t)$1;
1173   CHECK_FOR_ERROR
1174 };
1175
1176
1177 EINT64VAL : ESINT64VAL;      // These have same type and can't cause problems...
1178 EINT64VAL : EUINT64VAL {
1179   if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
1180     GEN_ERROR("Value too large for type!");
1181   $$ = (int64_t)$1;
1182   CHECK_FOR_ERROR
1183 };
1184
1185 // Operations that are notably excluded from this list include:
1186 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1187 //
1188 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1189 LogicalOps   : AND | OR | XOR;
1190 SetCondOps   : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1191 CastOps      : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST | 
1192                UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1193 ShiftOps     : SHL | LSHR | ASHR;
1194
1195 // These are some types that allow classification if we only want a particular 
1196 // thing... for example, only a signed, unsigned, or integral type.
1197 SIntType :  LONG |  INT |  SHORT | SBYTE;
1198 UIntType : ULONG | UINT | USHORT | UBYTE;
1199 IntType  : SIntType | UIntType;
1200 FPType   : FLOAT | DOUBLE;
1201
1202 // OptAssign - Value producing statements have an optional assignment component
1203 OptAssign : Name '=' {
1204     $$ = $1;
1205     CHECK_FOR_ERROR
1206   }
1207   | /*empty*/ {
1208     $$ = 0;
1209     CHECK_FOR_ERROR
1210   };
1211
1212 OptLinkage : INTERNAL    { $$ = GlobalValue::InternalLinkage; } |
1213              LINKONCE    { $$ = GlobalValue::LinkOnceLinkage; } |
1214              WEAK        { $$ = GlobalValue::WeakLinkage; } |
1215              APPENDING   { $$ = GlobalValue::AppendingLinkage; } |
1216              DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; } |
1217              DLLEXPORT   { $$ = GlobalValue::DLLExportLinkage; } |
1218              EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; } |
1219              /*empty*/   { $$ = GlobalValue::ExternalLinkage; };
1220
1221 OptCallingConv : /*empty*/          { $$ = CallingConv::C; } |
1222                  CCC_TOK            { $$ = CallingConv::C; } |
1223                  CSRETCC_TOK        { $$ = CallingConv::CSRet; } |
1224                  FASTCC_TOK         { $$ = CallingConv::Fast; } |
1225                  COLDCC_TOK         { $$ = CallingConv::Cold; } |
1226                  X86_STDCALLCC_TOK  { $$ = CallingConv::X86_StdCall; } |
1227                  X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1228                  CC_TOK EUINT64VAL  {
1229                    if ((unsigned)$2 != $2)
1230                      GEN_ERROR("Calling conv too large!");
1231                    $$ = $2;
1232                   CHECK_FOR_ERROR
1233                  };
1234
1235 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1236 // a comma before it.
1237 OptAlign : /*empty*/        { $$ = 0; } |
1238            ALIGN EUINT64VAL {
1239   $$ = $2;
1240   if ($$ != 0 && !isPowerOf2_32($$))
1241     GEN_ERROR("Alignment must be a power of two!");
1242   CHECK_FOR_ERROR
1243 };
1244 OptCAlign : /*empty*/            { $$ = 0; } |
1245             ',' ALIGN EUINT64VAL {
1246   $$ = $3;
1247   if ($$ != 0 && !isPowerOf2_32($$))
1248     GEN_ERROR("Alignment must be a power of two!");
1249   CHECK_FOR_ERROR
1250 };
1251
1252
1253 SectionString : SECTION STRINGCONSTANT {
1254   for (unsigned i = 0, e = strlen($2); i != e; ++i)
1255     if ($2[i] == '"' || $2[i] == '\\')
1256       GEN_ERROR("Invalid character in section name!");
1257   $$ = $2;
1258   CHECK_FOR_ERROR
1259 };
1260
1261 OptSection : /*empty*/ { $$ = 0; } |
1262              SectionString { $$ = $1; };
1263
1264 // GlobalVarAttributes - Used to pass the attributes string on a global.  CurGV
1265 // is set to be the global we are processing.
1266 //
1267 GlobalVarAttributes : /* empty */ {} |
1268                      ',' GlobalVarAttribute GlobalVarAttributes {};
1269 GlobalVarAttribute : SectionString {
1270     CurGV->setSection($1);
1271     free($1);
1272     CHECK_FOR_ERROR
1273   } 
1274   | ALIGN EUINT64VAL {
1275     if ($2 != 0 && !isPowerOf2_32($2))
1276       GEN_ERROR("Alignment must be a power of two!");
1277     CurGV->setAlignment($2);
1278     CHECK_FOR_ERROR
1279   };
1280
1281 //===----------------------------------------------------------------------===//
1282 // Types includes all predefined types... except void, because it can only be
1283 // used in specific contexts (function returning void for example).  To have
1284 // access to it, a user must explicitly use TypesV.
1285 //
1286
1287 // TypesV includes all of 'Types', but it also includes the void type.
1288 TypesV    : Types    | VOID { 
1289     $$.type = new PATypeHolder($1.type->get());
1290     $$.signedness = $1.signedness;
1291 };
1292 UpRTypesV : UpRTypes | VOID { 
1293     $$.type = new PATypeHolder($1.type->get()); 
1294     $$.signedness = $1.signedness;
1295 };
1296
1297 Types     : UpRTypes {
1298     if (!UpRefs.empty())
1299       GEN_ERROR("Invalid upreference in type: " + 
1300         ($1.type->get())->getDescription());
1301     $$ = $1;
1302     CHECK_FOR_ERROR
1303 };
1304
1305
1306 // Derived types are added later...
1307 //
1308 PrimType : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT ;
1309 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE   | LABEL;
1310 UpRTypes : OPAQUE {
1311     $$.type = new PATypeHolder(OpaqueType::get());
1312     $$.signedness = isSignless;
1313     CHECK_FOR_ERROR
1314   }
1315   | PrimType {
1316     $$ = $1;
1317     CHECK_FOR_ERROR
1318   };
1319 UpRTypes : SymbolicValueRef {            // Named types are also simple types...
1320   const Type* tmp = getTypeVal($1);
1321   CHECK_FOR_ERROR
1322   $$.type = new PATypeHolder(tmp);
1323   $$.signedness = isSignless;
1324 };
1325
1326 // Include derived types in the Types production.
1327 //
1328 UpRTypes : '\\' EUINT64VAL {                   // Type UpReference
1329     if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
1330     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1331     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1332     $$.type = new PATypeHolder(OT);
1333     $$.signedness = isSignless;
1334     UR_OUT("New Upreference!\n");
1335     CHECK_FOR_ERROR
1336   }
1337   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
1338     std::vector<const Type*> Params;
1339     for (std::list<TypeInfo>::iterator I = $3->begin(),
1340            E = $3->end(); I != E; ++I)
1341       Params.push_back(I->type->get());
1342     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1343     if (isVarArg) Params.pop_back();
1344
1345     $$.type = new PATypeHolder(HandleUpRefs(
1346                FunctionType::get($1.type->get(),Params,isVarArg)));
1347     $$.signedness = isSignless;
1348     delete $3;      // Delete the argument list
1349     delete $1.type;
1350     CHECK_FOR_ERROR
1351   }
1352   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
1353     $$.type = new PATypeHolder(HandleUpRefs(
1354       ArrayType::get($4.type->get(), (unsigned)$2)));
1355     $$.signedness = isSignless;
1356     delete $4.type;
1357     CHECK_FOR_ERROR
1358   }
1359   | '<' EUINT64VAL 'x' UpRTypes '>' {          // Packed array type?
1360     const llvm::Type* ElemTy = $4.type->get();
1361     if ((unsigned)$2 != $2)
1362       GEN_ERROR("Unsigned result not equal to signed result");
1363     if (!ElemTy->isPrimitiveType())
1364       GEN_ERROR("Elemental type of a PackedType must be primitive");
1365     if (!isPowerOf2_32($2))
1366       GEN_ERROR("Vector length should be a power of 2!");
1367     $$.type = new PATypeHolder(HandleUpRefs(
1368                 PackedType::get($4.type->get(), (unsigned)$2)));
1369     $$.signedness = isSignless;
1370     delete $4.type;
1371     CHECK_FOR_ERROR
1372   }
1373   | '{' TypeListI '}' {                        // Structure type?
1374     std::vector<const Type*> Elements;
1375     for (std::list<TypeInfo>::iterator I = $2->begin(),
1376            E = $2->end(); I != E; ++I)
1377       Elements.push_back(I->type->get());
1378
1379     $$.type = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1380     $$.signedness = isSignless;
1381     delete $2;
1382     CHECK_FOR_ERROR
1383   }
1384   | '{' '}' {                                  // Empty structure type?
1385     $$.type = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1386     $$.signedness = isSignless;
1387     CHECK_FOR_ERROR
1388   }
1389   | UpRTypes '*' {                             // Pointer type?
1390     if ($1.type->get() == Type::LabelTy)
1391       GEN_ERROR("Cannot form a pointer to a basic block");
1392     $$.type = new PATypeHolder(HandleUpRefs(PointerType::get($1.type->get())));
1393     $$.signedness = $1.signedness;
1394     delete $1.type;
1395     CHECK_FOR_ERROR
1396   };
1397
1398 // TypeList - Used for struct declarations and as a basis for function type 
1399 // declaration type lists
1400 //
1401 TypeListI : UpRTypes {
1402     $$ = new std::list<TypeInfo>();
1403     $$->push_back($1);
1404     CHECK_FOR_ERROR
1405   }
1406   | TypeListI ',' UpRTypes {
1407     ($$=$1)->push_back($3);
1408     CHECK_FOR_ERROR
1409   };
1410
1411 // ArgTypeList - List of types for a function type declaration...
1412 ArgTypeListI : TypeListI
1413   | TypeListI ',' DOTDOTDOT {
1414     TypeInfo TI; 
1415     TI.type = new PATypeHolder(Type::VoidTy); TI.signedness = isSignless;
1416     ($$=$1)->push_back(TI);
1417     CHECK_FOR_ERROR
1418   }
1419   | DOTDOTDOT {
1420     TypeInfo TI; 
1421     TI.type = new PATypeHolder(Type::VoidTy); TI.signedness = isSignless;
1422     ($$ = new std::list<TypeInfo>())->push_back(TI);
1423     CHECK_FOR_ERROR
1424   }
1425   | /*empty*/ {
1426     $$ = new std::list<TypeInfo>();
1427     CHECK_FOR_ERROR
1428   };
1429
1430 // ConstVal - The various declarations that go into the constant pool.  This
1431 // production is used ONLY to represent constants that show up AFTER a 'const',
1432 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1433 // into other expressions (such as integers and constexprs) are handled by the
1434 // ResolvedVal, ValueRef and ConstValueRef productions.
1435 //
1436 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1437     const ArrayType *ATy = dyn_cast<ArrayType>($1.type->get());
1438     if (ATy == 0)
1439       GEN_ERROR("Cannot make array constant with type: '" + 
1440                      ($1.type->get())->getDescription() + "'!");
1441     const Type *ETy = ATy->getElementType();
1442     int NumElements = ATy->getNumElements();
1443
1444     // Verify that we have the correct size...
1445     if (NumElements != -1 && NumElements != (int)$3->size())
1446       GEN_ERROR("Type mismatch: constant sized array initialized with " +
1447                      utostr($3->size()) +  " arguments, but has size of " + 
1448                      itostr(NumElements) + "!");
1449
1450     // Verify all elements are correct type!
1451     for (unsigned i = 0; i < $3->size(); i++) {
1452       if (ETy != (*$3)[i]->getType())
1453         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
1454                        ETy->getDescription() +"' as required!\nIt is of type '"+
1455                        (*$3)[i]->getType()->getDescription() + "'.");
1456     }
1457
1458     $$ = ConstantArray::get(ATy, *$3);
1459     delete $1.type; delete $3;
1460     CHECK_FOR_ERROR
1461   }
1462   | Types '[' ']' {
1463     const ArrayType *ATy = dyn_cast<ArrayType>($1.type->get());
1464     if (ATy == 0)
1465       GEN_ERROR("Cannot make array constant with type: '" + 
1466                      ($1.type->get())->getDescription() + "'!");
1467
1468     int NumElements = ATy->getNumElements();
1469     if (NumElements != -1 && NumElements != 0) 
1470       GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1471                      " arguments, but has size of " + itostr(NumElements) +"!");
1472     $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1473     delete $1.type;
1474     CHECK_FOR_ERROR
1475   }
1476   | Types 'c' STRINGCONSTANT {
1477     const ArrayType *ATy = dyn_cast<ArrayType>($1.type->get());
1478     if (ATy == 0)
1479       GEN_ERROR("Cannot make array constant with type: '" + 
1480                      ($1.type->get())->getDescription() + "'!");
1481
1482     int NumElements = ATy->getNumElements();
1483     const Type *ETy = ATy->getElementType();
1484     char *EndStr = UnEscapeLexed($3, true);
1485     if (NumElements != -1 && NumElements != (EndStr-$3))
1486       GEN_ERROR("Can't build string constant of size " + 
1487                      itostr((int)(EndStr-$3)) +
1488                      " when array has size " + itostr(NumElements) + "!");
1489     std::vector<Constant*> Vals;
1490     if (ETy == Type::SByteTy) {
1491       for (signed char *C = (signed char *)$3; C != (signed char *)EndStr; ++C)
1492         Vals.push_back(ConstantInt::get(ETy, *C));
1493     } else if (ETy == Type::UByteTy) {
1494       for (unsigned char *C = (unsigned char *)$3; 
1495            C != (unsigned char*)EndStr; ++C)
1496         Vals.push_back(ConstantInt::get(ETy, *C));
1497     } else {
1498       free($3);
1499       GEN_ERROR("Cannot build string arrays of non byte sized elements!");
1500     }
1501     free($3);
1502     $$ = ConstantArray::get(ATy, Vals);
1503     delete $1.type;
1504     CHECK_FOR_ERROR
1505   }
1506   | Types '<' ConstVector '>' { // Nonempty unsized arr
1507     const PackedType *PTy = dyn_cast<PackedType>($1.type->get());
1508     if (PTy == 0)
1509       GEN_ERROR("Cannot make packed constant with type: '" + 
1510                      $1.type->get()->getDescription() + "'!");
1511     const Type *ETy = PTy->getElementType();
1512     int NumElements = PTy->getNumElements();
1513
1514     // Verify that we have the correct size...
1515     if (NumElements != -1 && NumElements != (int)$3->size())
1516       GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1517                      utostr($3->size()) +  " arguments, but has size of " + 
1518                      itostr(NumElements) + "!");
1519
1520     // Verify all elements are correct type!
1521     for (unsigned i = 0; i < $3->size(); i++) {
1522       if (ETy != (*$3)[i]->getType())
1523         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
1524            ETy->getDescription() +"' as required!\nIt is of type '"+
1525            (*$3)[i]->getType()->getDescription() + "'.");
1526     }
1527
1528     $$ = ConstantPacked::get(PTy, *$3);
1529     delete $1.type; delete $3;
1530     CHECK_FOR_ERROR
1531   }
1532   | Types '{' ConstVector '}' {
1533     const StructType *STy = dyn_cast<StructType>($1.type->get());
1534     if (STy == 0)
1535       GEN_ERROR("Cannot make struct constant with type: '" + 
1536                      $1.type->get()->getDescription() + "'!");
1537
1538     if ($3->size() != STy->getNumContainedTypes())
1539       GEN_ERROR("Illegal number of initializers for structure type!");
1540
1541     // Check to ensure that constants are compatible with the type initializer!
1542     for (unsigned i = 0, e = $3->size(); i != e; ++i)
1543       if ((*$3)[i]->getType() != STy->getElementType(i))
1544         GEN_ERROR("Expected type '" +
1545                        STy->getElementType(i)->getDescription() +
1546                        "' for element #" + utostr(i) +
1547                        " of structure initializer!");
1548
1549     $$ = ConstantStruct::get(STy, *$3);
1550     delete $1.type; delete $3;
1551     CHECK_FOR_ERROR
1552   }
1553   | Types '{' '}' {
1554     const StructType *STy = dyn_cast<StructType>($1.type->get());
1555     if (STy == 0)
1556       GEN_ERROR("Cannot make struct constant with type: '" + 
1557                      $1.type->get()->getDescription() + "'!");
1558
1559     if (STy->getNumContainedTypes() != 0)
1560       GEN_ERROR("Illegal number of initializers for structure type!");
1561
1562     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1563     delete $1.type;
1564     CHECK_FOR_ERROR
1565   }
1566   | Types NULL_TOK {
1567     const PointerType *PTy = dyn_cast<PointerType>($1.type->get());
1568     if (PTy == 0)
1569       GEN_ERROR("Cannot make null pointer constant with type: '" + 
1570                      $1.type->get()->getDescription() + "'!");
1571
1572     $$ = ConstantPointerNull::get(PTy);
1573     delete $1.type;
1574     CHECK_FOR_ERROR
1575   }
1576   | Types UNDEF {
1577     $$ = UndefValue::get($1.type->get());
1578     delete $1.type;
1579     CHECK_FOR_ERROR
1580   }
1581   | Types SymbolicValueRef {
1582     const PointerType *Ty = dyn_cast<PointerType>($1.type->get());
1583     if (Ty == 0)
1584       GEN_ERROR("Global const reference must be a pointer type!");
1585
1586     // ConstExprs can exist in the body of a function, thus creating
1587     // GlobalValues whenever they refer to a variable.  Because we are in
1588     // the context of a function, getValNonImprovising will search the functions
1589     // symbol table instead of the module symbol table for the global symbol,
1590     // which throws things all off.  To get around this, we just tell
1591     // getValNonImprovising that we are at global scope here.
1592     //
1593     Function *SavedCurFn = CurFun.CurrentFunction;
1594     CurFun.CurrentFunction = 0;
1595
1596     Value *V = getValNonImprovising(Ty, $2);
1597     CHECK_FOR_ERROR
1598
1599     CurFun.CurrentFunction = SavedCurFn;
1600
1601     // If this is an initializer for a constant pointer, which is referencing a
1602     // (currently) undefined variable, create a stub now that shall be replaced
1603     // in the future with the right type of variable.
1604     //
1605     if (V == 0) {
1606       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1607       const PointerType *PT = cast<PointerType>(Ty);
1608
1609       // First check to see if the forward references value is already created!
1610       PerModuleInfo::GlobalRefsType::iterator I =
1611         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1612     
1613       if (I != CurModule.GlobalRefs.end()) {
1614         V = I->second;             // Placeholder already exists, use it...
1615         $2.destroy();
1616       } else {
1617         std::string Name;
1618         if ($2.Type == ValID::NameVal) Name = $2.Name;
1619
1620         // Create the forward referenced global.
1621         GlobalValue *GV;
1622         if (const FunctionType *FTy = 
1623                  dyn_cast<FunctionType>(PT->getElementType())) {
1624           GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1625                             CurModule.CurrentModule);
1626         } else {
1627           GV = new GlobalVariable(PT->getElementType(), false,
1628                                   GlobalValue::ExternalLinkage, 0,
1629                                   Name, CurModule.CurrentModule);
1630         }
1631
1632         // Keep track of the fact that we have a forward ref to recycle it
1633         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1634         V = GV;
1635       }
1636     }
1637
1638     $$ = cast<GlobalValue>(V);
1639     delete $1.type;            // Free the type handle
1640     CHECK_FOR_ERROR
1641   }
1642   | Types ConstExpr {
1643     if ($1.type->get() != $2->getType())
1644       GEN_ERROR("Mismatched types for constant expression!");
1645     $$ = $2;
1646     delete $1.type;
1647     CHECK_FOR_ERROR
1648   }
1649   | Types ZEROINITIALIZER {
1650     const Type *Ty = $1.type->get();
1651     if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1652       GEN_ERROR("Cannot create a null initialized value of this type!");
1653     $$ = Constant::getNullValue(Ty);
1654     delete $1.type;
1655     CHECK_FOR_ERROR
1656   };
1657
1658 ConstVal : SIntType EINT64VAL {      // integral constants
1659     if (!ConstantInt::isValueValidForType($1.type->get(), $2))
1660       GEN_ERROR("Constant value doesn't fit in type!");
1661     $$ = ConstantInt::get($1.type->get(), $2);
1662     CHECK_FOR_ERROR
1663   }
1664   | UIntType EUINT64VAL {            // integral constants
1665     if (!ConstantInt::isValueValidForType($1.type->get(), $2))
1666       GEN_ERROR("Constant value doesn't fit in type!");
1667     $$ = ConstantInt::get($1.type->get(), $2);
1668     CHECK_FOR_ERROR
1669   }
1670   | BOOL TRUETOK {                      // Boolean constants
1671     $$ = ConstantBool::getTrue();
1672     CHECK_FOR_ERROR
1673   }
1674   | BOOL FALSETOK {                     // Boolean constants
1675     $$ = ConstantBool::getFalse();
1676     CHECK_FOR_ERROR
1677   }
1678   | FPType FPVAL {                   // Float & Double constants
1679     if (!ConstantFP::isValueValidForType($1.type->get(), $2))
1680       GEN_ERROR("Floating point constant invalid for type!!");
1681     $$ = ConstantFP::get($1.type->get(), $2);
1682     CHECK_FOR_ERROR
1683   };
1684
1685
1686 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1687     Constant *Val = $3;
1688     const Type *Ty = $5.type->get();
1689     if (!Val->getType()->isFirstClassType())
1690       GEN_ERROR("cast constant expression from a non-primitive type: '" +
1691                      Val->getType()->getDescription() + "'!");
1692     if (!Ty->isFirstClassType())
1693       GEN_ERROR("cast constant expression to a non-primitive type: '" +
1694                 Ty->getDescription() + "'!");
1695     if ($1.obsolete) {
1696       if (Ty == Type::BoolTy) {
1697         // The previous definition of cast to bool was a compare against zero. 
1698         // We have to retain that semantic so we do it here.
1699         $$ = ConstantExpr::get(Instruction::SetNE, Val, 
1700                                Constant::getNullValue(Val->getType()));
1701       } else if (Val->getType()->isFloatingPoint() && isa<PointerType>(Ty)) {
1702         Constant *CE = ConstantExpr::getFPToUI(Val, Type::ULongTy);
1703         $$ = ConstantExpr::getIntToPtr(CE, Ty);
1704       } else {
1705         $$ = ConstantExpr::getCast(Val, Ty);
1706       }
1707     } else {
1708       $$ = ConstantExpr::getCast($1.opcode, $3, $5.type->get());
1709     }
1710     delete $5.type;
1711   }
1712   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1713     if (!isa<PointerType>($3->getType()))
1714       GEN_ERROR("GetElementPtr requires a pointer operand!");
1715
1716     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
1717     // indices to uint struct indices for compatibility.
1718     generic_gep_type_iterator<std::vector<Value*>::iterator>
1719       GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1720       GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1721     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1722       if (isa<StructType>(*GTI))        // Only change struct indices
1723         if (ConstantInt *CUI = dyn_cast<ConstantInt>((*$4)[i]))
1724           if (CUI->getType() == Type::UByteTy)
1725             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1726
1727     const Type *IdxTy =
1728       GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1729     if (!IdxTy)
1730       GEN_ERROR("Index list invalid for constant getelementptr!");
1731
1732     std::vector<Constant*> IdxVec;
1733     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1734       if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1735         IdxVec.push_back(C);
1736       else
1737         GEN_ERROR("Indices to constant getelementptr must be constants!");
1738
1739     delete $4;
1740
1741     $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1742     CHECK_FOR_ERROR
1743   }
1744   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1745     if ($3->getType() != Type::BoolTy)
1746       GEN_ERROR("Select condition must be of boolean type!");
1747     if ($5->getType() != $7->getType())
1748       GEN_ERROR("Select operand types must match!");
1749     $$ = ConstantExpr::getSelect($3, $5, $7);
1750     CHECK_FOR_ERROR
1751   }
1752   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1753     if ($3->getType() != $5->getType())
1754       GEN_ERROR("Binary operator types must match!");
1755     // First, make sure we're dealing with the right opcode by upgrading from
1756     // obsolete versions.
1757     sanitizeOpcode($1, $3->getType());
1758     CHECK_FOR_ERROR;
1759
1760     // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1761     // To retain backward compatibility with these early compilers, we emit a
1762     // cast to the appropriate integer type automatically if we are in the
1763     // broken case.  See PR424 for more information.
1764     if (!isa<PointerType>($3->getType())) {
1765       $$ = ConstantExpr::get($1.opcode, $3, $5);
1766     } else {
1767       const Type *IntPtrTy = 0;
1768       switch (CurModule.CurrentModule->getPointerSize()) {
1769       case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1770       case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1771       default: GEN_ERROR("invalid pointer binary constant expr!");
1772       }
1773       $$ = ConstantExpr::get($1.opcode, ConstantExpr::getCast($3, IntPtrTy),
1774                              ConstantExpr::getCast($5, IntPtrTy));
1775       $$ = ConstantExpr::getCast($$, $3->getType());
1776     }
1777     CHECK_FOR_ERROR
1778   }
1779   | LogicalOps '(' ConstVal ',' ConstVal ')' {
1780     if ($3->getType() != $5->getType())
1781       GEN_ERROR("Logical operator types must match!");
1782     if (!$3->getType()->isIntegral()) {
1783       if (!isa<PackedType>($3->getType()) || 
1784           !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1785         GEN_ERROR("Logical operator requires integral operands!");
1786     }
1787     $$ = ConstantExpr::get($1.opcode, $3, $5);
1788     CHECK_FOR_ERROR
1789   }
1790   | SetCondOps '(' ConstVal ',' ConstVal ')' {
1791     if ($3->getType() != $5->getType())
1792       GEN_ERROR("setcc operand types must match!");
1793     $$ = ConstantExpr::get($1.opcode, $3, $5);
1794     CHECK_FOR_ERROR
1795   }
1796   | ShiftOps '(' ConstVal ',' ConstVal ')' {
1797     if ($5->getType() != Type::UByteTy)
1798       GEN_ERROR("Shift count for shift constant must be unsigned byte!");
1799     if (!$3->getType()->isInteger())
1800       GEN_ERROR("Shift constant expression requires integer operand!");
1801     // Handle opcode upgrade situations
1802     sanitizeOpcode($1, $3->getType());
1803     CHECK_FOR_ERROR;
1804     $$ = ConstantExpr::get($1.opcode, $3, $5);
1805     CHECK_FOR_ERROR
1806   }
1807   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1808     if (!ExtractElementInst::isValidOperands($3, $5))
1809       GEN_ERROR("Invalid extractelement operands!");
1810     $$ = ConstantExpr::getExtractElement($3, $5);
1811     CHECK_FOR_ERROR
1812   }
1813   | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1814     if (!InsertElementInst::isValidOperands($3, $5, $7))
1815       GEN_ERROR("Invalid insertelement operands!");
1816     $$ = ConstantExpr::getInsertElement($3, $5, $7);
1817     CHECK_FOR_ERROR
1818   }
1819   | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1820     if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1821       GEN_ERROR("Invalid shufflevector operands!");
1822     $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1823     CHECK_FOR_ERROR
1824   };
1825
1826
1827 // ConstVector - A list of comma separated constants.
1828 ConstVector : ConstVector ',' ConstVal {
1829     ($$ = $1)->push_back($3);
1830     CHECK_FOR_ERROR
1831   }
1832   | ConstVal {
1833     $$ = new std::vector<Constant*>();
1834     $$->push_back($1);
1835     CHECK_FOR_ERROR
1836   };
1837
1838
1839 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1840 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1841
1842
1843 //===----------------------------------------------------------------------===//
1844 //                             Rules to match Modules
1845 //===----------------------------------------------------------------------===//
1846
1847 // Module rule: Capture the result of parsing the whole file into a result
1848 // variable...
1849 //
1850 Module : FunctionList {
1851   $$ = ParserResult = $1;
1852   CurModule.ModuleDone();
1853   CHECK_FOR_ERROR;
1854 };
1855
1856 // FunctionList - A list of functions, preceeded by a constant pool.
1857 //
1858 FunctionList : FunctionList Function {
1859     $$ = $1;
1860     CurFun.FunctionDone();
1861     CHECK_FOR_ERROR
1862   } 
1863   | FunctionList FunctionProto {
1864     $$ = $1;
1865     CHECK_FOR_ERROR
1866   }
1867   | FunctionList MODULE ASM_TOK AsmBlock {
1868     $$ = $1;
1869     CHECK_FOR_ERROR
1870   }  
1871   | FunctionList IMPLEMENTATION {
1872     $$ = $1;
1873     CHECK_FOR_ERROR
1874   }
1875   | ConstPool {
1876     $$ = CurModule.CurrentModule;
1877     // Emit an error if there are any unresolved types left.
1878     if (!CurModule.LateResolveTypes.empty()) {
1879       const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1880       if (DID.Type == ValID::NameVal) {
1881         GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1882       } else {
1883         GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1884       }
1885     }
1886     CHECK_FOR_ERROR
1887   };
1888
1889 // ConstPool - Constants with optional names assigned to them.
1890 ConstPool : ConstPool OptAssign TYPE TypesV {
1891     // Eagerly resolve types.  This is not an optimization, this is a
1892     // requirement that is due to the fact that we could have this:
1893     //
1894     // %list = type { %list * }
1895     // %list = type { %list * }    ; repeated type decl
1896     //
1897     // If types are not resolved eagerly, then the two types will not be
1898     // determined to be the same type!
1899     //
1900     ResolveTypeTo($2, $4.type->get());
1901
1902     if (!setTypeName($4.type->get(), $2) && !$2) {
1903       CHECK_FOR_ERROR
1904       // If this is a named type that is not a redefinition, add it to the slot
1905       // table.
1906       CurModule.Types.push_back($4);
1907     } else {
1908       delete $4.type;
1909     }
1910     CHECK_FOR_ERROR
1911   }
1912   | ConstPool FunctionProto {       // Function prototypes can be in const pool
1913     CHECK_FOR_ERROR
1914   }
1915   | ConstPool MODULE ASM_TOK AsmBlock {  // Asm blocks can be in the const pool
1916     CHECK_FOR_ERROR
1917   }
1918   | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1919     if ($5 == 0) 
1920       GEN_ERROR("Global value initializer is not a constant!");
1921     CurGV = ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1922     CHECK_FOR_ERROR
1923   } GlobalVarAttributes {
1924     CurGV = 0;
1925   }
1926   | ConstPool OptAssign EXTERNAL GlobalType Types {
1927     CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4,
1928       $5.type->get(), 0);
1929     CHECK_FOR_ERROR
1930     delete $5.type;
1931   } GlobalVarAttributes {
1932     CurGV = 0;
1933     CHECK_FOR_ERROR
1934   }
1935   | ConstPool OptAssign DLLIMPORT GlobalType Types {
1936     CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4,
1937       $5.type->get(), 0);
1938     CHECK_FOR_ERROR
1939     delete $5.type;
1940   } GlobalVarAttributes {
1941     CurGV = 0;
1942     CHECK_FOR_ERROR
1943   }
1944   | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
1945     CurGV = 
1946       ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4,
1947         $5.type->get(), 0);
1948     CHECK_FOR_ERROR
1949     delete $5.type;
1950   } GlobalVarAttributes {
1951     CurGV = 0;
1952     CHECK_FOR_ERROR
1953   }
1954   | ConstPool TARGET TargetDefinition { 
1955     CHECK_FOR_ERROR
1956   }
1957   | ConstPool DEPLIBS '=' LibrariesDefinition {
1958     CHECK_FOR_ERROR
1959   }
1960   | /* empty: end of list */ { 
1961   };
1962
1963
1964 AsmBlock : STRINGCONSTANT {
1965   const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1966   char *EndStr = UnEscapeLexed($1, true);
1967   std::string NewAsm($1, EndStr);
1968   free($1);
1969
1970   if (AsmSoFar.empty())
1971     CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1972   else
1973     CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1974   CHECK_FOR_ERROR
1975 };
1976
1977 BigOrLittle : BIG    { $$ = Module::BigEndian; };
1978 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1979
1980 TargetDefinition : ENDIAN '=' BigOrLittle {
1981     CurModule.CurrentModule->setEndianness($3);
1982     CHECK_FOR_ERROR
1983   }
1984   | POINTERSIZE '=' EUINT64VAL {
1985     if ($3 == 32)
1986       CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1987     else if ($3 == 64)
1988       CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1989     else
1990       GEN_ERROR("Invalid pointer size: '" + utostr($3) + "'!");
1991     CHECK_FOR_ERROR
1992   }
1993   | TRIPLE '=' STRINGCONSTANT {
1994     CurModule.CurrentModule->setTargetTriple($3);
1995     free($3);
1996   }
1997   | DATALAYOUT '=' STRINGCONSTANT {
1998     CurModule.CurrentModule->setDataLayout($3);
1999     free($3);
2000   };
2001
2002 LibrariesDefinition : '[' LibList ']';
2003
2004 LibList : LibList ',' STRINGCONSTANT {
2005           CurModule.CurrentModule->addLibrary($3);
2006           free($3);
2007           CHECK_FOR_ERROR
2008         }
2009         | STRINGCONSTANT {
2010           CurModule.CurrentModule->addLibrary($1);
2011           free($1);
2012           CHECK_FOR_ERROR
2013         }
2014         | /* empty: end of list */ {
2015           CHECK_FOR_ERROR
2016         }
2017         ;
2018
2019 //===----------------------------------------------------------------------===//
2020 //                       Rules to match Function Headers
2021 //===----------------------------------------------------------------------===//
2022
2023 Name : VAR_ID | STRINGCONSTANT;
2024 OptName : Name | /*empty*/ { $$ = 0; };
2025
2026 ArgVal : Types OptName {
2027   if ($1.type->get() == Type::VoidTy)
2028     GEN_ERROR("void typed arguments are invalid!");
2029   $$ = new std::pair<TypeInfo, char*>($1, $2);
2030   CHECK_FOR_ERROR
2031 };
2032
2033 ArgListH : ArgListH ',' ArgVal {
2034     $$ = $1;
2035     $1->push_back(*$3);
2036     delete $3;
2037     CHECK_FOR_ERROR
2038   }
2039   | ArgVal {
2040     $$ = new std::vector<std::pair<TypeInfo,char*> >();
2041     $$->push_back(*$1);
2042     delete $1;
2043     CHECK_FOR_ERROR
2044   };
2045
2046 ArgList : ArgListH {
2047     $$ = $1;
2048     CHECK_FOR_ERROR
2049   }
2050   | ArgListH ',' DOTDOTDOT {
2051     $$ = $1;
2052     TypeInfo TI;
2053     TI.type = new PATypeHolder(Type::VoidTy);
2054     TI.signedness = isSignless;
2055     $$->push_back(std::pair<TypeInfo,char*>(TI,(char*)0));
2056     CHECK_FOR_ERROR
2057   }
2058   | DOTDOTDOT {
2059     $$ = new std::vector<std::pair<TypeInfo,char*> >();
2060     TypeInfo TI;
2061     TI.type = new PATypeHolder(Type::VoidTy);
2062     TI.signedness = isSignless;
2063     $$->push_back(std::make_pair(TI, (char*)0));
2064     CHECK_FOR_ERROR
2065   }
2066   | /* empty */ {
2067     $$ = 0;
2068     CHECK_FOR_ERROR
2069   };
2070
2071 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')' 
2072                   OptSection OptAlign {
2073   UnEscapeLexed($3);
2074   std::string FunctionName($3);
2075   free($3);  // Free strdup'd memory!
2076   
2077   if (!($2.type->get())->isFirstClassType() && $2.type->get() != Type::VoidTy)
2078     GEN_ERROR("LLVM functions cannot return aggregate types!");
2079
2080   std::vector<const Type*> ParamTypeList;
2081   if ($5) {   // If there are arguments...
2082     for (std::vector<std::pair<TypeInfo,char*> >::iterator I = $5->begin();
2083          I != $5->end(); ++I)
2084       ParamTypeList.push_back(I->first.type->get());
2085   }
2086
2087   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2088   if (isVarArg) ParamTypeList.pop_back();
2089
2090   const FunctionType *FT = FunctionType::get($2.type->get(), ParamTypeList, 
2091     isVarArg);
2092   const PointerType *PFT = PointerType::get(FT);
2093   delete $2.type;
2094
2095   ValID ID;
2096   if (!FunctionName.empty()) {
2097     ID = ValID::create((char*)FunctionName.c_str());
2098   } else {
2099     ID = ValID::create((int)CurModule.Values[PFT].size());
2100   }
2101
2102   Function *Fn = 0;
2103   // See if this function was forward referenced.  If so, recycle the object.
2104   if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2105     // Move the function to the end of the list, from whereever it was 
2106     // previously inserted.
2107     Fn = cast<Function>(FWRef);
2108     CurModule.CurrentModule->getFunctionList().remove(Fn);
2109     CurModule.CurrentModule->getFunctionList().push_back(Fn);
2110   } else if (!FunctionName.empty() &&     // Merge with an earlier prototype?
2111              (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2112     // If this is the case, either we need to be a forward decl, or it needs 
2113     // to be.
2114     if (!CurFun.isDeclare && !Fn->isExternal())
2115       GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
2116     
2117     // Make sure to strip off any argument names so we can't get conflicts.
2118     if (Fn->isExternal())
2119       for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2120            AI != AE; ++AI)
2121         AI->setName("");
2122   } else  {  // Not already defined?
2123     Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2124                       CurModule.CurrentModule);
2125
2126     InsertValue(Fn, CurModule.Values);
2127   }
2128
2129   CurFun.FunctionStart(Fn);
2130
2131   if (CurFun.isDeclare) {
2132     // If we have declaration, always overwrite linkage.  This will allow us to
2133     // correctly handle cases, when pointer to function is passed as argument to
2134     // another function.
2135     Fn->setLinkage(CurFun.Linkage);
2136   }
2137   Fn->setCallingConv($1);
2138   Fn->setAlignment($8);
2139   if ($7) {
2140     Fn->setSection($7);
2141     free($7);
2142   }
2143
2144   // Add all of the arguments we parsed to the function...
2145   if ($5) {                     // Is null if empty...
2146     if (isVarArg) {  // Nuke the last entry
2147       assert($5->back().first.type->get() == Type::VoidTy && 
2148              $5->back().second == 0 && "Not a varargs marker!");
2149       delete $5->back().first.type;
2150       $5->pop_back();  // Delete the last entry
2151     }
2152     Function::arg_iterator ArgIt = Fn->arg_begin();
2153     for (std::vector<std::pair<TypeInfo,char*> >::iterator I = $5->begin();
2154          I != $5->end(); ++I, ++ArgIt) {
2155       delete I->first.type;                     // Delete the typeholder...
2156       setValueName(ArgIt, I->second);           // Insert arg into symtab...
2157       CHECK_FOR_ERROR
2158       InsertValue(ArgIt);
2159     }
2160     delete $5;                     // We're now done with the argument list
2161   }
2162   CHECK_FOR_ERROR
2163 };
2164
2165 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
2166
2167 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
2168   $$ = CurFun.CurrentFunction;
2169
2170   // Make sure that we keep track of the linkage type even if there was a
2171   // previous "declare".
2172   $$->setLinkage($1);
2173 };
2174
2175 END : ENDTOK | '}';                    // Allow end of '}' to end a function
2176
2177 Function : BasicBlockList END {
2178   $$ = $1;
2179   CHECK_FOR_ERROR
2180 };
2181
2182 FnDeclareLinkage: /*default*/ |
2183                   DLLIMPORT   { CurFun.Linkage = GlobalValue::DLLImportLinkage; } |
2184                   EXTERN_WEAK { CurFun.Linkage = GlobalValue::DLLImportLinkage; };
2185   
2186 FunctionProto : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
2187     $$ = CurFun.CurrentFunction;
2188     CurFun.FunctionDone();
2189     CHECK_FOR_ERROR
2190   };
2191
2192 //===----------------------------------------------------------------------===//
2193 //                        Rules to match Basic Blocks
2194 //===----------------------------------------------------------------------===//
2195
2196 OptSideEffect : /* empty */ {
2197     $$ = false;
2198     CHECK_FOR_ERROR
2199   }
2200   | SIDEEFFECT {
2201     $$ = true;
2202     CHECK_FOR_ERROR
2203   };
2204
2205 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
2206     $$ = ValID::create($1);
2207     CHECK_FOR_ERROR
2208   }
2209   | EUINT64VAL {
2210     $$ = ValID::create($1);
2211     CHECK_FOR_ERROR
2212   }
2213   | FPVAL {                     // Perhaps it's an FP constant?
2214     $$ = ValID::create($1);
2215     CHECK_FOR_ERROR
2216   }
2217   | TRUETOK {
2218     $$ = ValID::create(ConstantBool::getTrue());
2219     CHECK_FOR_ERROR
2220   } 
2221   | FALSETOK {
2222     $$ = ValID::create(ConstantBool::getFalse());
2223     CHECK_FOR_ERROR
2224   }
2225   | NULL_TOK {
2226     $$ = ValID::createNull();
2227     CHECK_FOR_ERROR
2228   }
2229   | UNDEF {
2230     $$ = ValID::createUndef();
2231     CHECK_FOR_ERROR
2232   }
2233   | ZEROINITIALIZER {     // A vector zero constant.
2234     $$ = ValID::createZeroInit();
2235     CHECK_FOR_ERROR
2236   }
2237   | '<' ConstVector '>' { // Nonempty unsized packed vector
2238     const Type *ETy = (*$2)[0]->getType();
2239     int NumElements = $2->size(); 
2240     
2241     PackedType* pt = PackedType::get(ETy, NumElements);
2242     PATypeHolder* PTy = new PATypeHolder(
2243        HandleUpRefs(PackedType::get( ETy, NumElements)));
2244     
2245     // Verify all elements are correct type!
2246     for (unsigned i = 0; i < $2->size(); i++) {
2247       if (ETy != (*$2)[i]->getType())
2248         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
2249                      ETy->getDescription() +"' as required!\nIt is of type '" +
2250                      (*$2)[i]->getType()->getDescription() + "'.");
2251     }
2252
2253     $$ = ValID::create(ConstantPacked::get(pt, *$2));
2254     delete PTy; delete $2;
2255     CHECK_FOR_ERROR
2256   }
2257   | ConstExpr {
2258     $$ = ValID::create($1);
2259     CHECK_FOR_ERROR
2260   }
2261   | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2262     char *End = UnEscapeLexed($3, true);
2263     std::string AsmStr = std::string($3, End);
2264     End = UnEscapeLexed($5, true);
2265     std::string Constraints = std::string($5, End);
2266     $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2267     free($3);
2268     free($5);
2269     CHECK_FOR_ERROR
2270   };
2271
2272 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2273 // another value.
2274 //
2275 SymbolicValueRef : INTVAL {  // Is it an integer reference...?
2276     $$ = ValID::create($1);
2277     CHECK_FOR_ERROR
2278   }
2279   | Name {                   // Is it a named reference...?
2280     $$ = ValID::create($1);
2281     CHECK_FOR_ERROR
2282   };
2283
2284 // ValueRef - A reference to a definition... either constant or symbolic
2285 ValueRef : SymbolicValueRef | ConstValueRef;
2286
2287
2288 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
2289 // type immediately preceeds the value reference, and allows complex constant
2290 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2291 ResolvedVal : Types ValueRef {
2292     $$ = getVal($1.type->get(), $2); delete $1.type;
2293     CHECK_FOR_ERROR
2294   };
2295
2296 BasicBlockList : BasicBlockList BasicBlock {
2297     $$ = $1;
2298     CHECK_FOR_ERROR
2299   }
2300   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
2301     $$ = $1;
2302     CHECK_FOR_ERROR
2303   };
2304
2305
2306 // Basic blocks are terminated by branching instructions: 
2307 // br, br/cc, switch, ret
2308 //
2309 BasicBlock : InstructionList OptAssign BBTerminatorInst  {
2310     setValueName($3, $2);
2311     CHECK_FOR_ERROR
2312     InsertValue($3);
2313
2314     $1->getInstList().push_back($3);
2315     InsertValue($1);
2316     $$ = $1;
2317     CHECK_FOR_ERROR
2318   };
2319
2320 InstructionList : InstructionList Inst {
2321     if (CastInst *CI1 = dyn_cast<CastInst>($2))
2322       if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2323         if (CI2->getParent() == 0)
2324           $1->getInstList().push_back(CI2);
2325     $1->getInstList().push_back($2);
2326     $$ = $1;
2327     CHECK_FOR_ERROR
2328   }
2329   | /* empty */ {
2330     $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2331     CHECK_FOR_ERROR
2332
2333     // Make sure to move the basic block to the correct location in the
2334     // function, instead of leaving it inserted wherever it was first
2335     // referenced.
2336     Function::BasicBlockListType &BBL = 
2337       CurFun.CurrentFunction->getBasicBlockList();
2338     BBL.splice(BBL.end(), BBL, $$);
2339     CHECK_FOR_ERROR
2340   }
2341   | LABELSTR {
2342     $$ = CurBB = getBBVal(ValID::create($1), true);
2343     CHECK_FOR_ERROR
2344
2345     // Make sure to move the basic block to the correct location in the
2346     // function, instead of leaving it inserted wherever it was first
2347     // referenced.
2348     Function::BasicBlockListType &BBL = 
2349       CurFun.CurrentFunction->getBasicBlockList();
2350     BBL.splice(BBL.end(), BBL, $$);
2351     CHECK_FOR_ERROR
2352   };
2353
2354 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
2355     $$ = new ReturnInst($2);
2356     CHECK_FOR_ERROR
2357   }
2358   | RET VOID {                                       // Return with no result...
2359     $$ = new ReturnInst();
2360     CHECK_FOR_ERROR
2361   }
2362   | BR LABEL ValueRef {                         // Unconditional Branch...
2363     BasicBlock* tmpBB = getBBVal($3);
2364     CHECK_FOR_ERROR
2365     $$ = new BranchInst(tmpBB);
2366   }                                                  // Conditional Branch...
2367   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
2368     BasicBlock* tmpBBA = getBBVal($6);
2369     CHECK_FOR_ERROR
2370     BasicBlock* tmpBBB = getBBVal($9);
2371     CHECK_FOR_ERROR
2372     Value* tmpVal = getVal(Type::BoolTy, $3);
2373     CHECK_FOR_ERROR
2374     $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2375   }
2376   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2377     Value* tmpVal = getVal($2.type->get(), $3);
2378     CHECK_FOR_ERROR
2379     BasicBlock* tmpBB = getBBVal($6);
2380     CHECK_FOR_ERROR
2381     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2382     $$ = S;
2383
2384     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2385       E = $8->end();
2386     for (; I != E; ++I) {
2387       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2388           S->addCase(CI, I->second);
2389       else
2390         GEN_ERROR("Switch case is constant, but not a simple integer!");
2391     }
2392     delete $8;
2393     CHECK_FOR_ERROR
2394   }
2395   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2396     Value* tmpVal = getVal($2.type->get(), $3);
2397     CHECK_FOR_ERROR
2398     BasicBlock* tmpBB = getBBVal($6);
2399     CHECK_FOR_ERROR
2400     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2401     $$ = S;
2402     CHECK_FOR_ERROR
2403   }
2404   | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2405     TO LABEL ValueRef UNWIND LABEL ValueRef {
2406     const PointerType *PFTy;
2407     const FunctionType *Ty;
2408
2409     if (!(PFTy = dyn_cast<PointerType>($3.type->get())) ||
2410         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2411       // Pull out the types of all of the arguments...
2412       std::vector<const Type*> ParamTypes;
2413       if ($6) {
2414         for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2415              I != E; ++I)
2416           ParamTypes.push_back((*I)->getType());
2417       }
2418
2419       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2420       if (isVarArg) ParamTypes.pop_back();
2421
2422       Ty = FunctionType::get($3.type->get(), ParamTypes, isVarArg);
2423       PFTy = PointerType::get(Ty);
2424     }
2425
2426     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2427     CHECK_FOR_ERROR
2428     BasicBlock *Normal = getBBVal($10);
2429     CHECK_FOR_ERROR
2430     BasicBlock *Except = getBBVal($13);
2431     CHECK_FOR_ERROR
2432
2433     // Create the call node...
2434     if (!$6) {                                   // Has no arguments?
2435       $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2436     } else {                                     // Has arguments?
2437       // Loop through FunctionType's arguments and ensure they are specified
2438       // correctly!
2439       //
2440       FunctionType::param_iterator I = Ty->param_begin();
2441       FunctionType::param_iterator E = Ty->param_end();
2442       std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2443
2444       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2445         if ((*ArgI)->getType() != *I)
2446           GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2447                          (*I)->getDescription() + "'!");
2448
2449       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2450         GEN_ERROR("Invalid number of parameters detected!");
2451
2452       $$ = new InvokeInst(V, Normal, Except, *$6);
2453     }
2454     cast<InvokeInst>($$)->setCallingConv($2);
2455   
2456     delete $3.type;
2457     delete $6;
2458     CHECK_FOR_ERROR
2459   }
2460   | UNWIND {
2461     $$ = new UnwindInst();
2462     CHECK_FOR_ERROR
2463   }
2464   | UNREACHABLE {
2465     $$ = new UnreachableInst();
2466     CHECK_FOR_ERROR
2467   };
2468
2469
2470
2471 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2472     $$ = $1;
2473     Constant *V = cast<Constant>(getValNonImprovising($2.type->get(), $3));
2474     CHECK_FOR_ERROR
2475     if (V == 0)
2476       GEN_ERROR("May only switch on a constant pool value!");
2477
2478     BasicBlock* tmpBB = getBBVal($6);
2479     CHECK_FOR_ERROR
2480     $$->push_back(std::make_pair(V, tmpBB));
2481   }
2482   | IntType ConstValueRef ',' LABEL ValueRef {
2483     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2484     Constant *V = cast<Constant>(getValNonImprovising($1.type->get(), $2));
2485     CHECK_FOR_ERROR
2486
2487     if (V == 0)
2488       GEN_ERROR("May only switch on a constant pool value!");
2489
2490     BasicBlock* tmpBB = getBBVal($5);
2491     CHECK_FOR_ERROR
2492     $$->push_back(std::make_pair(V, tmpBB)); 
2493   };
2494
2495 Inst : OptAssign InstVal {
2496   // Is this definition named?? if so, assign the name...
2497   setValueName($2, $1);
2498   CHECK_FOR_ERROR
2499   InsertValue($2);
2500   $$ = $2;
2501   CHECK_FOR_ERROR
2502 };
2503
2504 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
2505     $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2506     Value* tmpVal = getVal($1.type->get(), $3);
2507     CHECK_FOR_ERROR
2508     BasicBlock* tmpBB = getBBVal($5);
2509     CHECK_FOR_ERROR
2510     $$->push_back(std::make_pair(tmpVal, tmpBB));
2511     delete $1.type;
2512   }
2513   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2514     $$ = $1;
2515     Value* tmpVal = getVal($1->front().first->getType(), $4);
2516     CHECK_FOR_ERROR
2517     BasicBlock* tmpBB = getBBVal($6);
2518     CHECK_FOR_ERROR
2519     $1->push_back(std::make_pair(tmpVal, tmpBB));
2520   };
2521
2522
2523 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
2524     $$ = new std::vector<Value*>();
2525     $$->push_back($1);
2526   }
2527   | ValueRefList ',' ResolvedVal {
2528     $$ = $1;
2529     $1->push_back($3);
2530     CHECK_FOR_ERROR
2531   };
2532
2533 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2534 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2535
2536 OptTailCall : TAIL CALL {
2537     $$ = true;
2538     CHECK_FOR_ERROR
2539   }
2540   | CALL {
2541     $$ = false;
2542     CHECK_FOR_ERROR
2543   };
2544
2545 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2546     if (!$2.type->get()->isInteger() && !$2.type->get()->isFloatingPoint() && 
2547         !isa<PackedType>($2.type->get()))
2548       GEN_ERROR(
2549         "Arithmetic operator requires integer, FP, or packed operands!");
2550     if (isa<PackedType>($2.type->get()) && 
2551         ($1.opcode == Instruction::URem || 
2552          $1.opcode == Instruction::SRem ||
2553          $1.opcode == Instruction::FRem))
2554       GEN_ERROR("U/S/FRem not supported on packed types!");
2555     // Upgrade the opcode from obsolete versions before we do anything with it.
2556     sanitizeOpcode($1,$2.type->get());
2557     CHECK_FOR_ERROR;
2558     Value* val1 = getVal($2.type->get(), $3); 
2559     CHECK_FOR_ERROR
2560     Value* val2 = getVal($2.type->get(), $5);
2561     CHECK_FOR_ERROR
2562     $$ = BinaryOperator::create($1.opcode, val1, val2);
2563     if ($$ == 0)
2564       GEN_ERROR("binary operator returned null!");
2565     delete $2.type;
2566   }
2567   | LogicalOps Types ValueRef ',' ValueRef {
2568     if (!$2.type->get()->isIntegral()) {
2569       if (!isa<PackedType>($2.type->get()) ||
2570           !cast<PackedType>($2.type->get())->getElementType()->isIntegral())
2571         GEN_ERROR("Logical operator requires integral operands!");
2572     }
2573     Value* tmpVal1 = getVal($2.type->get(), $3);
2574     CHECK_FOR_ERROR
2575     Value* tmpVal2 = getVal($2.type->get(), $5);
2576     CHECK_FOR_ERROR
2577     $$ = BinaryOperator::create($1.opcode, tmpVal1, tmpVal2);
2578     if ($$ == 0)
2579       GEN_ERROR("binary operator returned null!");
2580     delete $2.type;
2581   }
2582   | SetCondOps Types ValueRef ',' ValueRef {
2583     if(isa<PackedType>($2.type->get())) {
2584       GEN_ERROR(
2585         "PackedTypes currently not supported in setcc instructions!");
2586     }
2587     Value* tmpVal1 = getVal($2.type->get(), $3);
2588     CHECK_FOR_ERROR
2589     Value* tmpVal2 = getVal($2.type->get(), $5);
2590     CHECK_FOR_ERROR
2591     $$ = new SetCondInst($1.opcode, tmpVal1, tmpVal2);
2592     if ($$ == 0)
2593       GEN_ERROR("binary operator returned null!");
2594     delete $2.type;
2595   }
2596   | NOT ResolvedVal {
2597     std::cerr << "WARNING: Use of eliminated 'not' instruction:"
2598               << " Replacing with 'xor'.\n";
2599
2600     Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2601     if (Ones == 0)
2602       GEN_ERROR("Expected integral type for not instruction!");
2603
2604     $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2605     if ($$ == 0)
2606       GEN_ERROR("Could not create a xor instruction!");
2607     CHECK_FOR_ERROR
2608   }
2609   | ShiftOps ResolvedVal ',' ResolvedVal {
2610     if ($4->getType() != Type::UByteTy)
2611       GEN_ERROR("Shift amount must be ubyte!");
2612     if (!$2->getType()->isInteger())
2613       GEN_ERROR("Shift constant expression requires integer operand!");
2614     // Handle opcode upgrade situations
2615     sanitizeOpcode($1, $2->getType());
2616     CHECK_FOR_ERROR;
2617     $$ = new ShiftInst($1.opcode, $2, $4);
2618     CHECK_FOR_ERROR
2619   }
2620   | CastOps ResolvedVal TO Types {
2621     Value* Val = $2;
2622     const Type* Ty = $4.type->get();
2623     if (!Val->getType()->isFirstClassType())
2624       GEN_ERROR("cast from a non-primitive type: '" +
2625                 Val->getType()->getDescription() + "'!");
2626     if (!Ty->isFirstClassType())
2627       GEN_ERROR("cast to a non-primitive type: '" + Ty->getDescription() +"'!");
2628
2629     if ($1.obsolete) {
2630       if (Ty == Type::BoolTy) {
2631         // The previous definition of cast to bool was a compare against zero. 
2632         // We have to retain that semantic so we do it here.
2633         $$ = new SetCondInst(Instruction::SetNE, $2, 
2634                                Constant::getNullValue($2->getType()));
2635       } else if (Val->getType()->isFloatingPoint() && isa<PointerType>(Ty)) {
2636         CastInst *CI = new FPToUIInst(Val, Type::ULongTy);
2637         $$ = new IntToPtrInst(CI, Ty);
2638       } else {
2639         $$ = CastInst::createInferredCast(Val, Ty);
2640       }
2641     } else {
2642       $$ = CastInst::create($1.opcode, $2, $4.type->get());
2643     }
2644     delete $4.type;
2645   }
2646   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2647     if ($2->getType() != Type::BoolTy)
2648       GEN_ERROR("select condition must be boolean!");
2649     if ($4->getType() != $6->getType())
2650       GEN_ERROR("select value types should match!");
2651     $$ = new SelectInst($2, $4, $6);
2652     CHECK_FOR_ERROR
2653   }
2654   | VAARG ResolvedVal ',' Types {
2655     NewVarArgs = true;
2656     $$ = new VAArgInst($2, $4.type->get());
2657     delete $4.type;
2658     CHECK_FOR_ERROR
2659   }
2660   | VAARG_old ResolvedVal ',' Types {
2661     ObsoleteVarArgs = true;
2662     const Type* ArgTy = $2->getType();
2663     Function* NF = CurModule.CurrentModule->
2664       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2665
2666     //b = vaarg a, t -> 
2667     //foo = alloca 1 of t
2668     //bar = vacopy a 
2669     //store bar -> foo
2670     //b = vaarg foo, t
2671     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2672     CurBB->getInstList().push_back(foo);
2673     CallInst* bar = new CallInst(NF, $2);
2674     CurBB->getInstList().push_back(bar);
2675     CurBB->getInstList().push_back(new StoreInst(bar, foo));
2676     $$ = new VAArgInst(foo, $4.type->get());
2677     delete $4.type;
2678     CHECK_FOR_ERROR
2679   }
2680   | VANEXT_old ResolvedVal ',' Types {
2681     ObsoleteVarArgs = true;
2682     const Type* ArgTy = $2->getType();
2683     Function* NF = CurModule.CurrentModule->
2684       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2685
2686     //b = vanext a, t ->
2687     //foo = alloca 1 of t
2688     //bar = vacopy a
2689     //store bar -> foo
2690     //tmp = vaarg foo, t
2691     //b = load foo
2692     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
2693     CurBB->getInstList().push_back(foo);
2694     CallInst* bar = new CallInst(NF, $2);
2695     CurBB->getInstList().push_back(bar);
2696     CurBB->getInstList().push_back(new StoreInst(bar, foo));
2697     Instruction* tmp = new VAArgInst(foo, $4.type->get());
2698     CurBB->getInstList().push_back(tmp);
2699     $$ = new LoadInst(foo);
2700     delete $4.type;
2701     CHECK_FOR_ERROR
2702   }
2703   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2704     if (!ExtractElementInst::isValidOperands($2, $4))
2705       GEN_ERROR("Invalid extractelement operands!");
2706     $$ = new ExtractElementInst($2, $4);
2707     CHECK_FOR_ERROR
2708   }
2709   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2710     if (!InsertElementInst::isValidOperands($2, $4, $6))
2711       GEN_ERROR("Invalid insertelement operands!");
2712     $$ = new InsertElementInst($2, $4, $6);
2713     CHECK_FOR_ERROR
2714   }
2715   | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2716     if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2717       GEN_ERROR("Invalid shufflevector operands!");
2718     $$ = new ShuffleVectorInst($2, $4, $6);
2719     CHECK_FOR_ERROR
2720   }
2721   | PHI_TOK PHIList {
2722     const Type *Ty = $2->front().first->getType();
2723     if (!Ty->isFirstClassType())
2724       GEN_ERROR("PHI node operands must be of first class type!");
2725     $$ = new PHINode(Ty);
2726     ((PHINode*)$$)->reserveOperandSpace($2->size());
2727     while ($2->begin() != $2->end()) {
2728       if ($2->front().first->getType() != Ty) 
2729         GEN_ERROR("All elements of a PHI node must be of the same type!");
2730       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2731       $2->pop_front();
2732     }
2733     delete $2;  // Free the list...
2734     CHECK_FOR_ERROR
2735   }
2736   | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')'  {
2737     const PointerType *PFTy = 0;
2738     const FunctionType *Ty = 0;
2739
2740     if (!(PFTy = dyn_cast<PointerType>($3.type->get())) ||
2741         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2742       // Pull out the types of all of the arguments...
2743       std::vector<const Type*> ParamTypes;
2744       if ($6) {
2745         for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2746              I != E; ++I)
2747           ParamTypes.push_back((*I)->getType());
2748       }
2749
2750       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2751       if (isVarArg) ParamTypes.pop_back();
2752
2753       if (!$3.type->get()->isFirstClassType() && 
2754            $3.type->get() != Type::VoidTy)
2755         GEN_ERROR("LLVM functions cannot return aggregate types!");
2756
2757       Ty = FunctionType::get($3.type->get(), ParamTypes, isVarArg);
2758       PFTy = PointerType::get(Ty);
2759     }
2760
2761     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2762     CHECK_FOR_ERROR
2763
2764     // Create the call node...
2765     if (!$6) {                                   // Has no arguments?
2766       // Make sure no arguments is a good thing!
2767       if (Ty->getNumParams() != 0)
2768         GEN_ERROR("No arguments passed to a function that "
2769                        "expects arguments!");
2770
2771       $$ = new CallInst(V, std::vector<Value*>());
2772     } else {                                     // Has arguments?
2773       // Loop through FunctionType's arguments and ensure they are specified
2774       // correctly!
2775       //
2776       FunctionType::param_iterator I = Ty->param_begin();
2777       FunctionType::param_iterator E = Ty->param_end();
2778       std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2779
2780       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2781         if ((*ArgI)->getType() != *I)
2782           GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2783                          (*I)->getDescription() + "'!");
2784
2785       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2786         GEN_ERROR("Invalid number of parameters detected!");
2787
2788       $$ = new CallInst(V, *$6);
2789     }
2790     cast<CallInst>($$)->setTailCall($1);
2791     cast<CallInst>($$)->setCallingConv($2);
2792     delete $3.type;
2793     delete $6;
2794     CHECK_FOR_ERROR
2795   }
2796   | MemoryInst {
2797     $$ = $1;
2798     CHECK_FOR_ERROR
2799   };
2800
2801
2802 // IndexList - List of indices for GEP based instructions...
2803 IndexList : ',' ValueRefList { 
2804     $$ = $2; 
2805     CHECK_FOR_ERROR
2806   } | /* empty */ { 
2807     $$ = new std::vector<Value*>(); 
2808     CHECK_FOR_ERROR
2809   };
2810
2811 OptVolatile : VOLATILE {
2812     $$ = true;
2813     CHECK_FOR_ERROR
2814   }
2815   | /* empty */ {
2816     $$ = false;
2817     CHECK_FOR_ERROR
2818   };
2819
2820
2821
2822 MemoryInst : MALLOC Types OptCAlign {
2823     $$ = new MallocInst($2.type->get(), 0, $3);
2824     delete $2.type;
2825     CHECK_FOR_ERROR
2826   }
2827   | MALLOC Types ',' UINT ValueRef OptCAlign {
2828     Value* tmpVal = getVal($4.type->get(), $5);
2829     CHECK_FOR_ERROR
2830     $$ = new MallocInst($2.type->get(), tmpVal, $6);
2831     delete $2.type;
2832   }
2833   | ALLOCA Types OptCAlign {
2834     $$ = new AllocaInst($2.type->get(), 0, $3);
2835     delete $2.type;
2836     CHECK_FOR_ERROR
2837   }
2838   | ALLOCA Types ',' UINT ValueRef OptCAlign {
2839     Value* tmpVal = getVal($4.type->get(), $5);
2840     CHECK_FOR_ERROR
2841     $$ = new AllocaInst($2.type->get(), tmpVal, $6);
2842     delete $2.type;
2843   }
2844   | FREE ResolvedVal {
2845     if (!isa<PointerType>($2->getType()))
2846       GEN_ERROR("Trying to free nonpointer type " + 
2847                      $2->getType()->getDescription() + "!");
2848     $$ = new FreeInst($2);
2849     CHECK_FOR_ERROR
2850   }
2851
2852   | OptVolatile LOAD Types ValueRef {
2853     if (!isa<PointerType>($3.type->get()))
2854       GEN_ERROR("Can't load from nonpointer type: " +
2855                      $3.type->get()->getDescription());
2856     if (!cast<PointerType>($3.type->get())->getElementType()->isFirstClassType())
2857       GEN_ERROR("Can't load from pointer of non-first-class type: " +
2858                      $3.type->get()->getDescription());
2859     Value* tmpVal = getVal($3.type->get(), $4);
2860     CHECK_FOR_ERROR
2861     $$ = new LoadInst(tmpVal, "", $1);
2862     delete $3.type;
2863   }
2864   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2865     const PointerType *PT = dyn_cast<PointerType>($5.type->get());
2866     if (!PT)
2867       GEN_ERROR("Can't store to a nonpointer type: " +
2868                      ($5.type->get())->getDescription());
2869     const Type *ElTy = PT->getElementType();
2870     if (ElTy != $3->getType())
2871       GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2872                      "' into space of type '" + ElTy->getDescription() + "'!");
2873
2874     Value* tmpVal = getVal($5.type->get(), $6);
2875     CHECK_FOR_ERROR
2876     $$ = new StoreInst($3, tmpVal, $1);
2877     delete $5.type;
2878   }
2879   | GETELEMENTPTR Types ValueRef IndexList {
2880     if (!isa<PointerType>($2.type->get()))
2881       GEN_ERROR("getelementptr insn requires pointer operand!");
2882
2883     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
2884     // indices to uint struct indices for compatibility.
2885     generic_gep_type_iterator<std::vector<Value*>::iterator>
2886       GTI = gep_type_begin($2.type->get(), $4->begin(), $4->end()),
2887       GTE = gep_type_end($2.type->get(), $4->begin(), $4->end());
2888     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2889       if (isa<StructType>(*GTI))        // Only change struct indices
2890         if (ConstantInt *CUI = dyn_cast<ConstantInt>((*$4)[i]))
2891           if (CUI->getType() == Type::UByteTy)
2892             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2893
2894     if (!GetElementPtrInst::getIndexedType($2.type->get(), *$4, true))
2895       GEN_ERROR("Invalid getelementptr indices for type '" +
2896                      $2.type->get()->getDescription()+ "'!");
2897     Value* tmpVal = getVal($2.type->get(), $3);
2898     CHECK_FOR_ERROR
2899     $$ = new GetElementPtrInst(tmpVal, *$4);
2900     delete $2.type; 
2901     delete $4;
2902   };
2903
2904
2905 %%
2906
2907 void llvm::GenerateError(const std::string &message, int LineNo) {
2908   if (LineNo == -1) LineNo = llvmAsmlineno;
2909   // TODO: column number in exception
2910   if (TheParseError)
2911     TheParseError->setError(CurFilename, message, LineNo);
2912   TriggerError = 1;
2913 }
2914
2915 int yyerror(const char *ErrorMsg) {
2916   std::string where 
2917     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2918                   + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2919   std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2920   if (yychar == YYEMPTY || yychar == 0)
2921     errMsg += "end-of-file.";
2922   else
2923     errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2924   GenerateError(errMsg);
2925   return 0;
2926 }