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