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