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