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