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