Fix a bunch of missing semicolon parse errors from bison.
[oota-llvm.git] / tools / llvm-upgrade / UpgradeParser.y
1 //===-- UpgradeParser.y - Upgrade parser for llvm assmbly -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the bison parser for LLVM 1.9 assembly language.
11 //
12 //===----------------------------------------------------------------------===//
13
14 %{
15 #include "UpgradeInternals.h"
16 #include <algorithm>
17 #include <map>
18 #include <utility>
19 #include <iostream>
20
21 #define YYERROR_VERBOSE 1
22 #define YYINCLUDED_STDLIB_H
23 #define YYDEBUG 1
24
25 int yylex();                       // declaration" of xxx warnings.
26 int yyparse();
27 extern int yydebug;
28
29 static std::string CurFilename;
30 static std::ostream *O = 0;
31 std::istream* LexInput = 0;
32 unsigned SizeOfPointer = 32;
33
34
35 // This bool controls whether attributes are ever added to function declarations
36 // definitions and calls.
37 static bool AddAttributes = false;
38
39 static void warning(const std::string& msg);
40
41 void UpgradeAssembly(const std::string &infile, std::istream& in, 
42                      std::ostream &out, bool debug, bool addAttrs)
43 {
44   Upgradelineno = 1; 
45   CurFilename = infile;
46   LexInput = &in;
47   yydebug = debug;
48   AddAttributes = addAttrs;
49   O = &out;
50
51   if (yyparse()) {
52     std::cerr << "llvm-upgrade: parse failed.\n";
53     out << "llvm-upgrade: parse failed.\n";
54     exit(1);
55   }
56 }
57
58 namespace { // Anonymous namespace to keep our implementation local
59
60
61 /// This type is used to keep track of the signedness of values. Instead
62 /// of creating llvm::Value directly, the parser will create Value which
63 /// associates a Value* with a Signedness indication.
64 struct Value {
65   std::string* val;
66   const Type* type;
67   bool constant;
68   bool isConstant() const { return constant; }
69   ~Value() { delete val; }
70 };
71
72
73 /// This type is used to keep track of the signedness of the obsolete
74 /// integer types. Instead of creating an llvm::Type directly, the Lexer will
75 /// create instances of Type which retains the signedness indication so
76 /// it can be used by the parser for upgrade decisions.
77 /// For example if "uint" is encountered then the "first" field will be set 
78 /// to "int32" and the "second" field will be set to "isUnsigned".  If the 
79 /// type is not obsolete then "second" will be set to "isSignless".
80 class Type {
81 public:
82   static const Type* get(const std::string &newType, TypeIDs oldType);
83   static const Type* get(const std::string& newType, TypeIDs oldType, 
84                              const Type* eTy, const Type* rTy);
85
86   static const Type* get(const std::string& newType, TypeIDs oldType, 
87                              const Type *eTy, uint64_t elems);
88
89   static const Type* get(const std::string& newType, TypeIDs oldType, 
90                              TypeList* TL);
91
92   static const Type* get(const std::string& newType, const Type* resTy, 
93                              TypeList* TL);
94
95   const Type* resolve() const;
96   bool operator<(const Type& that) const;
97
98   bool sameNewTyAs(const Type* that) const {
99     return this->newTy == that->newTy;
100   }
101
102   bool sameOldTyAs(const Type* that) const;
103
104   TypeIDs getElementTy() const {
105     if (elemTy) {
106       return elemTy->oldTy;
107     }
108     return UnresolvedTy;
109   }
110
111   unsigned getUpRefNum() const {
112     assert(oldTy == UpRefTy && "Can't getUpRefNum on non upreference");
113     return atoi(&((getNewTy().c_str())[1])); // skip the slash
114   }
115
116   typedef std::vector<const Type*> UpRefStack;
117   void getSignedness(unsigned &sNum, unsigned &uNum, UpRefStack& stk) const;
118   std::string makeUniqueName(const std::string& BaseName) const;
119
120   const std::string& getNewTy() const { return newTy; }
121   const Type* getResultType() const { return resultTy; }
122   const Type* getElementType() const { return elemTy; }
123
124   const Type* getPointerType() const {
125     return get(newTy + "*", PointerTy, this, (Type*)0);
126   }
127
128   bool isUnresolved() const { return oldTy == UnresolvedTy; }
129   bool isUpReference() const { return oldTy == UpRefTy; }
130   bool isVoid() const { return oldTy == VoidTy; }
131   bool isBool() const { return oldTy == BoolTy; }
132   bool isSigned() const {
133     return oldTy == SByteTy || oldTy == ShortTy || 
134            oldTy == IntTy || oldTy == LongTy;
135   }
136
137   bool isUnsigned() const {
138     return oldTy == UByteTy || oldTy == UShortTy || 
139            oldTy == UIntTy || oldTy == ULongTy;
140   }
141   bool isSignless() const { return !isSigned() && !isUnsigned(); }
142   bool isInteger() const { return isSigned() || isUnsigned(); }
143   bool isIntegral() const { return oldTy == BoolTy || isInteger(); }
144   bool isFloatingPoint() const { return oldTy == DoubleTy || oldTy == FloatTy; }
145   bool isPacked() const { return oldTy == PackedTy; }
146   bool isPointer() const { return oldTy == PointerTy; }
147   bool isStruct() const { return oldTy == StructTy || oldTy == PackedStructTy; }
148   bool isArray() const { return oldTy == ArrayTy; }
149   bool isOther() const { 
150     return !isPacked() && !isPointer() && !isFloatingPoint() && !isIntegral(); }
151   bool isFunction() const { return oldTy == FunctionTy; }
152   bool isComposite() const {
153     return isStruct() || isPointer() || isArray() || isPacked();
154   }
155
156   bool isAttributeCandidate() const {
157     return isIntegral() && getBitWidth() < 32;
158   }
159
160   bool isUnresolvedDeep() const;
161
162   unsigned getBitWidth() const;
163
164   const Type* getIndexedType(const Value*  V) const;
165
166   unsigned getNumStructElements() const { 
167     return (elements ? elements->size() : 0);
168   }
169
170   const Type* getElement(unsigned idx) const {
171     if (elements)
172       if (idx < elements->size())
173         return (*elements)[idx];
174     return 0;
175   }
176
177 private:
178   Type() 
179     : newTy(), oldTy(UnresolvedTy), elemTy(0), resultTy(0), elements(0),
180       nelems(0) {
181   }
182
183   Type(const Type& that); // do not implement
184   Type& operator=(const Type& that); // do not implement
185
186   ~Type() { delete elements; }
187
188   struct ltfunctor
189   {
190     bool operator()(const Type* X, const Type* Y) const {
191       assert(X && "Can't compare null pointer");
192       assert(Y && "Can't compare null pointer");
193       return *X < *Y;
194     }
195   };
196
197   typedef std::set<const Type*, ltfunctor> TypeRegMap;
198
199   static const Type* add_new_type(Type* existing);
200
201   std::string newTy;
202   TypeIDs oldTy;
203   Type *elemTy;
204   Type *resultTy;
205   TypeList *elements;
206   uint64_t nelems;
207   static TypeRegMap registry;
208 public:
209   typedef std::vector<const Type*> TypeVector;
210   typedef std::map<std::string,const Type*> TypeMap;
211   typedef std::map<const Type*,std::string> TypePlaneMap;
212   typedef std::map<std::string,TypePlaneMap> GlobalsTypeMap;
213   static TypeVector EnumeratedTypes;
214   static TypeMap NamedTypes;
215   static GlobalsTypeMap Globals;
216 };
217
218 Type::TypeRegMap     Type::registry;
219 Type::TypeVector     Type::EnumeratedTypes;
220 Type::TypeMap        Type::NamedTypes;
221 Type::GlobalsTypeMap Type::Globals;
222
223 const Type* Type::get(const std::string &newType, TypeIDs oldType) {
224   Type* Ty = new Type();
225   Ty->newTy = newType;
226   Ty->oldTy = oldType;
227   return add_new_type(Ty);
228 }
229
230 const Type* Type::get(const std::string& newType, TypeIDs oldType, 
231                               const Type* eTy, const Type* rTy) {
232   Type* Ty= new Type();
233   Ty->newTy = newType;
234   Ty->oldTy = oldType;
235   Ty->elemTy = const_cast<Type*>(eTy);
236   Ty->resultTy = const_cast<Type*>(rTy);
237   return add_new_type(Ty);
238 }
239
240 const Type* Type::get(const std::string& newType, TypeIDs oldType, 
241                               const Type *eTy, uint64_t elems) {
242   Type* Ty = new Type();
243   Ty->newTy = newType;
244   Ty->oldTy = oldType;
245   Ty->elemTy = const_cast<Type*>(eTy);
246   Ty->nelems = elems;
247   return  add_new_type(Ty);
248 }
249
250 const Type* Type::get(const std::string& newType, TypeIDs oldType, 
251                               TypeList* TL) {
252   Type* Ty = new Type();
253   Ty->newTy = newType;
254   Ty->oldTy = oldType;
255   Ty->elements = TL;
256   return add_new_type(Ty);
257 }
258
259 const Type* Type::get(const std::string& newType, const Type* resTy,
260                               TypeList* TL) {
261   Type* Ty = new Type();
262   Ty->newTy = newType;
263   Ty->oldTy = FunctionTy;
264   Ty->resultTy = const_cast<Type*>(resTy);
265   Ty->elements = TL;
266   return add_new_type(Ty);
267 }
268
269 const Type* Type::resolve() const {
270   if (isUnresolved()) {
271     if (getNewTy()[0] == '%' && isdigit(newTy[1])) {
272       unsigned ref = atoi(&((newTy.c_str())[1])); // skip the %
273       if (ref < EnumeratedTypes.size()) {
274         return EnumeratedTypes[ref];
275       } else {
276         std::string msg("Can't resolve numbered type: ");
277         msg += getNewTy();
278         yyerror(msg.c_str());
279       }
280     } else {
281       Type::TypeMap::iterator I = NamedTypes.find(newTy);
282       if (I != NamedTypes.end()) {
283         return I->second;
284       } else {
285         std::string msg("Cannot resolve type: ");
286         msg += getNewTy();
287         yyerror(msg.c_str());
288       }
289     }
290   }
291   // otherwise its already resolved.
292   return this;
293 }
294
295 bool Type::operator<(const Type& that) const {
296   if (this == &that)
297     return false;
298   if (oldTy != that.oldTy)
299     return oldTy < that.oldTy;
300   switch (oldTy) {
301     case UpRefTy: {
302       unsigned thisUp = this->getUpRefNum();
303       unsigned thatUp = that.getUpRefNum();
304       return thisUp < thatUp;
305     }
306     case PackedTy:
307     case ArrayTy:
308       if (this->nelems != that.nelems)
309         return nelems < that.nelems;
310     case PointerTy: {
311       const Type* thisTy = this->elemTy;
312       const Type* thatTy = that.elemTy;
313       return *thisTy < *thatTy;
314     }
315     case FunctionTy: {
316       const Type* thisTy = this->resultTy;
317       const Type* thatTy = that.resultTy;
318       if (!thisTy->sameOldTyAs(thatTy))
319         return *thisTy < *thatTy;
320       /* FALL THROUGH */
321     }
322     case StructTy:
323     case PackedStructTy: {
324       if (elements->size() != that.elements->size())
325         return elements->size() < that.elements->size();
326       for (unsigned i = 0; i < elements->size(); i++) {
327         const Type* thisTy = (*this->elements)[i];
328         const Type* thatTy = (*that.elements)[i];
329         if (!thisTy->sameOldTyAs(thatTy))
330           return *thisTy < *thatTy;
331       }
332       break;
333     }
334     case UnresolvedTy:
335       return this->newTy < that.newTy;
336     default:
337       break;
338   }
339   return false; 
340 }
341
342 bool Type::sameOldTyAs(const Type* that) const {
343   if (that == 0)
344     return false;
345   if ( this == that ) 
346     return true;
347   if (oldTy != that->oldTy)
348     return false;
349   switch (oldTy) {
350     case PackedTy:
351     case ArrayTy:
352       if (nelems != that->nelems)
353         return false;
354       /* FALL THROUGH */
355     case PointerTy: {
356       const Type* thisTy = this->elemTy;
357       const Type* thatTy = that->elemTy;
358       return thisTy->sameOldTyAs(thatTy);
359     }
360     case FunctionTy: {
361       const Type* thisTy = this->resultTy;
362       const Type* thatTy = that->resultTy;
363       if (!thisTy->sameOldTyAs(thatTy))
364         return false;
365       /* FALL THROUGH */
366     }
367     case StructTy:
368     case PackedStructTy: {
369       if (elements->size() != that->elements->size())
370         return false;
371       for (unsigned i = 0; i < elements->size(); i++) {
372         const Type* thisTy = (*this->elements)[i];
373         const Type* thatTy = (*that->elements)[i];
374         if (!thisTy->sameOldTyAs(thatTy))
375           return false;
376       }
377       return true;
378     }
379     case UnresolvedTy:
380       return this->newTy == that->newTy;
381     default:
382       return true; // for all others oldTy == that->oldTy is sufficient
383   }
384   return true;
385 }
386
387 bool Type::isUnresolvedDeep() const {
388   switch (oldTy) {
389     case UnresolvedTy: 
390       return true;
391     case PackedTy:
392     case ArrayTy:
393     case PointerTy:
394       return elemTy->isUnresolvedDeep();
395     case PackedStructTy:
396     case StructTy:
397       for (unsigned i = 0; i < elements->size(); i++)
398         if ((*elements)[i]->isUnresolvedDeep())
399           return true;
400       return false;
401     default:
402       return false;
403   }
404 }
405
406 unsigned Type::getBitWidth() const {
407   switch (oldTy) {
408     default:
409     case LabelTy:
410     case VoidTy : return 0;
411     case BoolTy : return 1;
412     case SByteTy: case UByteTy : return 8;
413     case ShortTy: case UShortTy : return 16;
414     case IntTy: case UIntTy: case FloatTy: return 32;
415     case LongTy: case ULongTy: case DoubleTy : return 64;
416     case PointerTy: return SizeOfPointer; // global var
417     case PackedTy: 
418     case ArrayTy: 
419       return nelems * elemTy->getBitWidth();
420     case StructTy:
421     case PackedStructTy: {
422       uint64_t size = 0;
423       for (unsigned i = 0; i < elements->size(); i++) {
424         size += (*elements)[i]->getBitWidth();
425       }
426       return size;
427     }
428   }
429 }
430
431 const Type* Type::getIndexedType(const Value*  V) const {
432   if (isStruct()) {
433     if (V->isConstant() && V->type->isInteger()) {
434       size_t pos = V->val->find(' ') + 1;
435       if (pos < V->val->size()) {
436         uint64_t idx = atoi(V->val->substr(pos).c_str());
437         return (*elements)[idx];
438       } else {
439         yyerror("Invalid value for constant integer");
440         return 0;
441       }
442     } else {
443       yyerror("Structure requires constant index");
444       return 0;
445     }
446   }
447   if (isArray() || isPacked() || isPointer())
448     return elemTy;
449   yyerror("Invalid type for getIndexedType");
450   return 0;
451 }
452
453 void Type::getSignedness(unsigned &sNum, unsigned &uNum, 
454                              UpRefStack& stack) const {
455   switch (oldTy) {
456     default:
457     case OpaqueTy: case LabelTy: case VoidTy: case BoolTy: 
458     case FloatTy : case DoubleTy: case UpRefTy:
459       return;
460     case SByteTy: case ShortTy: case LongTy: case IntTy: 
461       sNum++;
462       return;
463     case UByteTy: case UShortTy: case UIntTy: case ULongTy: 
464       uNum++;
465       return;
466     case PointerTy:
467     case PackedTy: 
468     case ArrayTy:
469       stack.push_back(this);
470       elemTy->getSignedness(sNum, uNum, stack);
471       return;
472     case StructTy:
473     case PackedStructTy: {
474       stack.push_back(this);
475       for (unsigned i = 0; i < elements->size(); i++) {
476         (*elements)[i]->getSignedness(sNum, uNum, stack);
477       }
478       return;
479     }
480     case UnresolvedTy: {
481       const Type* Ty = this->resolve();
482       // Let's not recurse.
483       UpRefStack::const_iterator I = stack.begin(), E = stack.end();
484       for ( ; I != E && *I != Ty; ++I) 
485         ;
486       if (I == E)
487         Ty->getSignedness(sNum, uNum, stack);
488       return;
489     }
490   }
491 }
492
493 std::string AddSuffix(const std::string& Name, const std::string& Suffix) {
494   if (Name[Name.size()-1] == '"') {
495     std::string Result = Name;
496     Result.insert(Result.size()-1, Suffix);
497     return Result;
498   }
499   return Name + Suffix;
500 }
501
502 std::string Type::makeUniqueName(const std::string& BaseName) const {
503   if (BaseName == "\"alloca point\"")
504     return BaseName;
505   switch (oldTy) {
506     default:
507       break;
508     case OpaqueTy: case LabelTy: case VoidTy: case BoolTy: case UpRefTy:
509     case FloatTy : case DoubleTy: case UnresolvedTy:
510       return BaseName;
511     case SByteTy: case ShortTy: case LongTy: case IntTy: 
512       return AddSuffix(BaseName, ".s");
513     case UByteTy: case UShortTy: case UIntTy: case ULongTy: 
514       return AddSuffix(BaseName, ".u");
515   }
516
517   unsigned uNum = 0, sNum = 0;
518   std::string Suffix;
519   switch (oldTy) {
520     case PointerTy:
521     case PackedTy: 
522     case ArrayTy: {
523       Type::UpRefStack stack;
524       elemTy->resolve()->getSignedness(sNum, uNum, stack);
525       break;
526     }
527     case StructTy:
528     case PackedStructTy: {
529       for (unsigned i = 0; i < elements->size(); i++) {
530         Type::UpRefStack stack;
531         (*elements)[i]->resolve()->getSignedness(sNum, uNum, stack);
532       }
533       break;
534     }
535     default:
536       assert(0 && "Invalid Type");
537       break;
538   }
539
540   if (sNum == 0 && uNum == 0)
541     return BaseName;
542
543   switch (oldTy) {
544     default:             Suffix += ".nada"; break;
545     case PointerTy:      Suffix += ".pntr"; break;
546     case PackedTy:       Suffix += ".pckd"; break;
547     case ArrayTy:        Suffix += ".arry"; break;
548     case StructTy:       Suffix += ".strc"; break;
549     case PackedStructTy: Suffix += ".pstr"; break;
550   }
551
552   Suffix += ".s" + llvm::utostr(sNum);
553   Suffix += ".u" + llvm::utostr(uNum);
554   return AddSuffix(BaseName, Suffix);
555 }
556
557 Type& Type::operator=(const Type& that) {
558   oldTy = that.oldTy;
559   nelems = that.nelems;
560   newTy = that.newTy;
561   elemTy = that.elemTy;
562   resultTy = that.resultTy;
563   if (that.elements) {
564     elements = new TypeList(that.elements->size());
565     *elements = *that.elements;
566   } else {
567     elements = 0;
568   }
569   return *this;
570 }
571
572 const Type* Type::add_new_type(Type* newTy) {
573   TypeRegMap::iterator I = registry.find(newTy);
574   if (I != registry.end()) {
575     delete newTy;
576     return *I;
577   }
578   registry.insert(newTy);
579   return newTy;
580 }
581
582 class Instruction {
583 };
584
585 /// This type is used to keep track of the signedness of constants.
586 struct Constant {
587   std::string *cnst;
588   const Type *type;
589   ~Constant() { delete cnst; }
590 };
591
592 /// This variable provides a counter for unique names. It is used in various
593 /// productions to ensure a unique name is generated.
594 static uint64_t UniqueNameCounter = 1;
595
596 // This is set when a DECLARE keyword is recognized so that subsequent parsing
597 // of a function prototype can know if its a declaration or definition.
598 static bool isDeclare = false;
599
600 // This bool is used to communicate between the InstVal and Inst rules about
601 // whether or not a cast should be deleted. When the flag is set, InstVal has
602 // determined that the cast is a candidate. However, it can only be deleted if
603 // the value being casted is the same value name as the instruction. The Inst
604 // rule makes that comparison if the flag is set and comments out the
605 // instruction if they match.
606 static bool deleteUselessCastFlag = false;
607 static std::string* deleteUselessCastName = 0;
608
609
610
611 const char* getCastOpcode(std::string& Source, const Type* SrcTy, 
612                           const Type* DstTy) {
613   unsigned SrcBits = SrcTy->getBitWidth();
614   unsigned DstBits = DstTy->getBitWidth();
615   const char* opcode = "bitcast";
616   // Run through the possibilities ...
617   if (DstTy->isIntegral()) {                        // Casting to integral
618     if (SrcTy->isIntegral()) {                      // Casting from integral
619       if (DstBits < SrcBits)
620         opcode = "trunc";
621       else if (DstBits > SrcBits) {                // its an extension
622         if (SrcTy->isSigned())
623           opcode ="sext";                          // signed -> SEXT
624         else
625           opcode = "zext";                         // unsigned -> ZEXT
626       } else {
627         opcode = "bitcast";                        // Same size, No-op cast
628       }
629     } else if (SrcTy->isFloatingPoint()) {          // Casting from floating pt
630       if (DstTy->isSigned()) 
631         opcode = "fptosi";                         // FP -> sint
632       else
633         opcode = "fptoui";                         // FP -> uint 
634     } else if (SrcTy->isPacked()) {
635       assert(DstBits == SrcTy->getBitWidth() &&
636                "Casting packed to integer of different width");
637         opcode = "bitcast";                        // same size, no-op cast
638     } else {
639       assert(SrcTy->isPointer() &&
640              "Casting from a value that is not first-class type");
641       opcode = "ptrtoint";                         // ptr -> int
642     }
643   } else if (DstTy->isFloatingPoint()) {           // Casting to floating pt
644     if (SrcTy->isIntegral()) {                     // Casting from integral
645       if (SrcTy->isSigned())
646         opcode = "sitofp";                         // sint -> FP
647       else
648         opcode = "uitofp";                         // uint -> FP
649     } else if (SrcTy->isFloatingPoint()) {         // Casting from floating pt
650       if (DstBits < SrcBits) {
651         opcode = "fptrunc";                        // FP -> smaller FP
652       } else if (DstBits > SrcBits) {
653         opcode = "fpext";                          // FP -> larger FP
654       } else  {
655         opcode ="bitcast";                         // same size, no-op cast
656       }
657     } else if (SrcTy->isPacked()) {
658       assert(DstBits == SrcTy->getBitWidth() &&
659              "Casting packed to floating point of different width");
660         opcode = "bitcast";                        // same size, no-op cast
661     } else {
662       assert(0 && "Casting pointer or non-first class to float");
663     }
664   } else if (DstTy->isPacked()) {
665     if (SrcTy->isPacked()) {
666       assert(DstTy->getBitWidth() == SrcTy->getBitWidth() &&
667              "Casting packed to packed of different widths");
668       opcode = "bitcast";                          // packed -> packed
669     } else if (DstTy->getBitWidth() == SrcBits) {
670       opcode = "bitcast";                          // float/int -> packed
671     } else {
672       assert(!"Illegal cast to packed (wrong type or size)");
673     }
674   } else if (DstTy->isPointer()) {
675     if (SrcTy->isPointer()) {
676       opcode = "bitcast";                          // ptr -> ptr
677     } else if (SrcTy->isIntegral()) {
678       opcode = "inttoptr";                         // int -> ptr
679     } else {
680       assert(!"Casting invalid type to pointer");
681     }
682   } else {
683     assert(!"Casting to type that is not first-class");
684   }
685   return opcode;
686 }
687
688 std::string getCastUpgrade(const std::string& Src, const Type* SrcTy,
689                            const Type* DstTy, bool isConst) {
690   std::string Result;
691   std::string Source = Src;
692   if (SrcTy->isFloatingPoint() && DstTy->isPointer()) {
693     // fp -> ptr cast is no longer supported but we must upgrade this
694     // by doing a double cast: fp -> int -> ptr
695     if (isConst)
696       Source = "i64 fptoui(" + Source + " to i64)";
697     else {
698       *O << "    %cast_upgrade" << UniqueNameCounter << " = fptoui " 
699          << Source << " to i64\n";
700       Source = "i64 %cast_upgrade" + llvm::utostr(UniqueNameCounter++);
701     }
702     // Update the SrcTy for the getCastOpcode call below
703     SrcTy = Type::get("i64", ULongTy);
704   } else if (DstTy->isBool()) {
705     // cast type %x to bool was previously defined as setne type %x, null
706     // The cast semantic is now to truncate, not compare so we must retain
707     // the original intent by replacing the cast with a setne
708     const char* comparator = SrcTy->isPointer() ? ", null" : 
709       (SrcTy->isFloatingPoint() ? ", 0.0" : 
710        (SrcTy->isBool() ? ", false" : ", 0"));
711     const char* compareOp = SrcTy->isFloatingPoint() ? "fcmp one " : "icmp ne ";
712     if (isConst) { 
713       Result = "(" + Source + comparator + ")";
714       Result = compareOp + Result;
715     } else
716       Result = compareOp + Source + comparator;
717     return Result; // skip cast processing below
718   }
719   SrcTy = SrcTy->resolve();
720   DstTy = DstTy->resolve();
721   std::string Opcode(getCastOpcode(Source, SrcTy, DstTy));
722   if (isConst)
723     Result += Opcode + "( " + Source + " to " + DstTy->getNewTy() + ")";
724   else
725     Result += Opcode + " " + Source + " to " + DstTy->getNewTy();
726   return Result;
727 }
728
729 const char* getDivRemOpcode(const std::string& opcode, const Type* TI) {
730   const char* op = opcode.c_str();
731   const Type* Ty = TI->resolve();
732   if (Ty->isPacked())
733     Ty = Ty->getElementType();
734   if (opcode == "div")
735     if (Ty->isFloatingPoint())
736       op = "fdiv";
737     else if (Ty->isUnsigned())
738       op = "udiv";
739     else if (Ty->isSigned())
740       op = "sdiv";
741     else
742       yyerror("Invalid type for div instruction");
743   else if (opcode == "rem")
744     if (Ty->isFloatingPoint())
745       op = "frem";
746     else if (Ty->isUnsigned())
747       op = "urem";
748     else if (Ty->isSigned())
749       op = "srem";
750     else
751       yyerror("Invalid type for rem instruction");
752   return op;
753 }
754
755 std::string getCompareOp(const std::string& setcc, const Type* TI) {
756   assert(setcc.length() == 5);
757   char cc1 = setcc[3];
758   char cc2 = setcc[4];
759   assert(cc1 == 'e' || cc1 == 'n' || cc1 == 'l' || cc1 == 'g');
760   assert(cc2 == 'q' || cc2 == 'e' || cc2 == 'e' || cc2 == 't');
761   std::string result("xcmp xxx");
762   result[6] = cc1;
763   result[7] = cc2;
764   if (TI->isFloatingPoint()) {
765     result[0] = 'f';
766     result[5] = 'o';
767     if (cc1 == 'n')
768       result[5] = 'u'; // NE maps to unordered
769     else
770       result[5] = 'o'; // everything else maps to ordered
771   } else if (TI->isIntegral() || TI->isPointer()) {
772     result[0] = 'i';
773     if ((cc1 == 'e' && cc2 == 'q') || (cc1 == 'n' && cc2 == 'e'))
774       result.erase(5,1);
775     else if (TI->isSigned())
776       result[5] = 's';
777     else if (TI->isUnsigned() || TI->isPointer() || TI->isBool())
778       result[5] = 'u';
779     else
780       yyerror("Invalid integral type for setcc");
781   }
782   return result;
783 }
784
785 const Type* getFunctionReturnType(const Type* PFTy) {
786   PFTy = PFTy->resolve();
787   if (PFTy->isPointer()) {
788     const Type* ElemTy = PFTy->getElementType();
789     ElemTy = ElemTy->resolve();
790     if (ElemTy->isFunction())
791       return ElemTy->getResultType();
792   } else if (PFTy->isFunction()) {
793     return PFTy->getResultType();
794   }
795   return PFTy;
796 }
797
798 const Type* ResolveUpReference(const Type* Ty, 
799                                    Type::UpRefStack* stack) {
800   assert(Ty->isUpReference() && "Can't resolve a non-upreference");
801   unsigned upref = Ty->getUpRefNum();
802   assert(upref < stack->size() && "Invalid up reference");
803   return (*stack)[upref - stack->size() - 1];
804 }
805
806 const Type* getGEPIndexedType(const Type* PTy, ValueList* idxs) {
807   const Type* Result = PTy = PTy->resolve();
808   assert(PTy->isPointer() && "GEP Operand is not a pointer?");
809   Type::UpRefStack stack;
810   for (unsigned i = 0; i < idxs->size(); ++i) {
811     if (Result->isComposite()) {
812       Result = Result->getIndexedType((*idxs)[i]);
813       Result = Result->resolve();
814       stack.push_back(Result);
815     } else
816       yyerror("Invalid type for index");
817   }
818   // Resolve upreferences so we can return a more natural type
819   if (Result->isPointer()) {
820     if (Result->getElementType()->isUpReference()) {
821       stack.push_back(Result);
822       Result = ResolveUpReference(Result->getElementType(), &stack);
823     }
824   } else if (Result->isUpReference()) {
825     Result = ResolveUpReference(Result->getElementType(), &stack);
826   }
827   return Result->getPointerType();
828 }
829
830 // This function handles appending .u or .s to integer value names that
831 // were previously unsigned or signed, respectively. This avoids name
832 // collisions since the unsigned and signed type planes have collapsed
833 // into a single signless type plane.
834 std::string getUniqueName(const std::string *Name, const Type* Ty,
835                           bool isGlobal = false, bool isDef = false) {
836
837   // If its not a symbolic name, don't modify it, probably a constant val.
838   if ((*Name)[0] != '%' && (*Name)[0] != '"')
839     return *Name;
840
841   // If its a numeric reference, just leave it alone.
842   if (isdigit((*Name)[1]))
843     return *Name;
844
845   // Resolve the type
846   Ty = Ty->resolve(); 
847
848   // If its a global name, get its uniquified name, if any
849   Type::GlobalsTypeMap::iterator GI = Type::Globals.find(*Name);
850   if (GI != Type::Globals.end()) {
851     Type::TypePlaneMap::iterator TPI = GI->second.begin();
852     Type::TypePlaneMap::iterator TPE = GI->second.end();
853     for ( ; TPI != TPE ; ++TPI) {
854       if (TPI->first->sameNewTyAs(Ty)) 
855         return TPI->second;
856     }
857   }
858
859   if (isGlobal) {
860     // We didn't find a global name, but if its supposed to be global then all 
861     // we can do is return the name. This is probably a forward reference of a 
862     // global value that hasn't been defined yet. Since we have no definition
863     // we don't know its linkage class. Just assume its an external and the name
864     // shouldn't change.
865     return *Name;
866   }
867
868   // Default the result to the current name
869   std::string Result = Ty->makeUniqueName(*Name);
870
871   return Result;
872 }
873
874 std::string getGlobalName(const std::string* Name, const std::string Linkage,
875                           const Type* Ty, bool isConstant) {
876   // Default to given name
877   std::string Result = *Name; 
878   // Look up the name in the Globals Map
879   Type::GlobalsTypeMap::iterator GI = Type::Globals.find(*Name);
880   // Did we see this global name before?
881   if (GI != Type::Globals.end()) {
882     if (Ty->isUnresolvedDeep()) {
883       // The Gval's type is unresolved. Consequently, we can't disambiguate it
884       // by type. We'll just change its name and emit a warning.
885       warning("Cannot disambiguate global value '" + *Name + 
886               "' because type '" + Ty->getNewTy() + "'is unresolved.\n");
887       Result = *Name + ".unique";
888       UniqueNameCounter++;
889       Result += llvm::utostr(UniqueNameCounter);
890       return Result;
891     } else {
892       Type::TypePlaneMap::iterator TPI = GI->second.find(Ty);
893       if (TPI != GI->second.end()) {
894         // We found an existing name of the same old type. This isn't allowed 
895         // in LLVM 2.0. Consequently, we must alter the name of the global so it
896         // can at least compile. References to the global will yield the first
897         // definition, which is okay. We also must warn about this.
898         Result = *Name + ".unique";
899         UniqueNameCounter++;
900         Result += llvm::utostr(UniqueNameCounter);
901         warning(std::string("Global variable '") + *Name + "' was renamed to '"+
902                 Result + "'");
903       } else { 
904         // There isn't an existing definition for this name according to the
905         // old types. Now search the TypePlanMap for types with the same new
906         // name. 
907         Type::TypePlaneMap::iterator TPI = GI->second.begin();
908         Type::TypePlaneMap::iterator TPE = GI->second.end();
909         for ( ; TPI != TPE; ++TPI) {
910           if (TPI->first->sameNewTyAs(Ty)) {
911             // The new types are the same but the old types are different so 
912             // this is a global name collision resulting from type planes 
913             // collapsing. 
914             if (Linkage == "external" || Linkage == "dllimport" || 
915                 Linkage == "extern_weak" || Linkage == "") {
916               // The linkage of this gval is external so we can't reliably 
917               // rename it because it could potentially create a linking 
918               // problem.  However, we can't leave the name conflict in the 
919               // output either or it won't assemble with LLVM 2.0.  So, all we 
920               // can do is rename this one to something unique and emit a 
921               // warning about the problem.
922               Result = *Name + ".unique";
923               UniqueNameCounter++;
924               Result += llvm::utostr(UniqueNameCounter);
925               warning("Renaming global value '" + *Name + "' to '" + Result + 
926                       "' may cause linkage errors.");
927               return Result;
928             } else {
929               // Its linkage is internal and its type is known so we can 
930               // disambiguate the name collision successfully based on the type.
931               Result = getUniqueName(Name, Ty);
932               TPI->second = Result;
933               return Result;
934             }
935           }
936         }
937         // We didn't find an entry in the type plane with the same new type and
938         // the old types differ so this is a new type plane for this global 
939         // variable. We just fall through to the logic below which inserts
940         // the global.
941       }
942     }
943   }
944
945   // Its a new global name, if it is external we can't change it
946   if (isConstant || Linkage == "external" || Linkage == "dllimport" || 
947       Linkage == "extern_weak" || Linkage == "") {
948     Type::Globals[Result][Ty] = Result;
949     return Result;
950   }
951
952   // Its a new global name, and it is internal, change the name to make it
953   // unique for its type.
954   // Result = getUniqueName(Name, Ty);
955   Type::Globals[*Name][Ty] = Result;
956   return Result;
957 }
958
959 } // End anonymous namespace
960
961 // This function is used by the Lexer to create a Type. It can't be
962 // in the anonymous namespace.
963 const Type* getType(const std::string& newTy, TypeIDs oldTy) {
964   return Type::get(newTy, oldTy);
965 }
966
967 %}
968
969 // %file-prefix="UpgradeParser"
970
971 %union {
972   std::string*    String;
973   const Type*     Ty;
974   Value*          Val;
975   Constant*       Const;
976   ValueList*      ValList;
977   TypeList*       TypeVec;
978 }
979
980 %token <Ty>     VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
981 %token <Ty>     FLOAT DOUBLE LABEL 
982 %token <String> OPAQUE ESINT64VAL EUINT64VAL SINTVAL UINTVAL FPVAL
983 %token <String> NULL_TOK UNDEF ZEROINITIALIZER TRUETOK FALSETOK
984 %token <String> TYPE VAR_ID LABELSTR STRINGCONSTANT
985 %token <String> IMPLEMENTATION BEGINTOK ENDTOK
986 %token <String> DECLARE GLOBAL CONSTANT SECTION VOLATILE
987 %token <String> TO DOTDOTDOT CONST INTERNAL LINKONCE WEAK 
988 %token <String> DLLIMPORT DLLEXPORT EXTERN_WEAK APPENDING
989 %token <String> EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG
990 %token <String> ALIGN UNINITIALIZED
991 %token <String> DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
992 %token <String> CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
993 %token <String> X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
994 %token <String> DATALAYOUT
995 %token <String> RET BR SWITCH INVOKE EXCEPT UNWIND UNREACHABLE
996 %token <String> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM AND OR XOR
997 %token <String> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comparators
998 %token <String> ICMP FCMP EQ NE SLT SGT SLE SGE OEQ ONE OLT OGT OLE OGE 
999 %token <String> ORD UNO UEQ UNE ULT UGT ULE UGE
1000 %token <String> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1001 %token <String> PHI_TOK SELECT SHL SHR ASHR LSHR VAARG
1002 %token <String> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1003 %token <String> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI UITOFP SITOFP 
1004 %token <String> PTRTOINT INTTOPTR BITCAST
1005
1006 %type <String> OptAssign OptLinkage OptCallingConv OptAlign OptCAlign 
1007 %type <String> SectionString OptSection GlobalVarAttributes GlobalVarAttribute
1008 %type <String> ConstExpr DefinitionList
1009 %type <String> ConstPool TargetDefinition LibrariesDefinition LibList OptName
1010 %type <String> ArgVal ArgListH ArgList FunctionHeaderH BEGIN FunctionHeader END
1011 %type <String> Function FunctionProto BasicBlock 
1012 %type <String> InstructionList BBTerminatorInst JumpTable Inst
1013 %type <String> OptTailCall OptVolatile Unwind
1014 %type <String> SymbolicValueRef OptSideEffect GlobalType
1015 %type <String> FnDeclareLinkage BasicBlockList BigOrLittle AsmBlock
1016 %type <String> Name ConstValueRef ConstVector External
1017 %type <String> ShiftOps SetCondOps LogicalOps ArithmeticOps CastOps
1018 %type <String> IPredicates FPredicates
1019
1020 %type <ValList> ValueRefList ValueRefListE IndexList
1021 %type <TypeVec> TypeListI ArgTypeListI
1022
1023 %type <Ty> IntType SIntType UIntType FPType TypesV Types 
1024 %type <Ty> PrimType UpRTypesV UpRTypes
1025
1026 %type <String> IntVal EInt64Val 
1027 %type <Const>  ConstVal
1028
1029 %type <Val> ValueRef ResolvedVal InstVal PHIList MemoryInst
1030
1031 %start Module
1032
1033 %%
1034
1035 // Handle constant integer size restriction and conversion...
1036 IntVal : SINTVAL | UINTVAL ;
1037 EInt64Val : ESINT64VAL | EUINT64VAL;
1038
1039 // Operations that are notably excluded from this list include:
1040 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1041 ArithmeticOps: ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV 
1042              | REM | UREM | SREM | FREM;
1043 LogicalOps   : AND | OR | XOR;
1044 SetCondOps   : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1045 IPredicates  : EQ | NE | SLT | SGT | SLE | SGE | ULT | UGT | ULE | UGE;
1046 FPredicates  : OEQ | ONE | OLT | OGT | OLE | OGE | ORD | UNO | UEQ | UNE
1047              | ULT | UGT | ULE | UGE | TRUETOK | FALSETOK;
1048 ShiftOps     : SHL | SHR | ASHR | LSHR;
1049 CastOps      : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI | 
1050                UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1051              ;
1052
1053 // These are some types that allow classification if we only want a particular 
1054 // thing... for example, only a signed, unsigned, or integral type.
1055 SIntType :  LONG |  INT |  SHORT | SBYTE;
1056 UIntType : ULONG | UINT | USHORT | UBYTE;
1057 IntType  : SIntType | UIntType;
1058 FPType   : FLOAT | DOUBLE;
1059
1060 // OptAssign - Value producing statements have an optional assignment component
1061 OptAssign : Name '=' {
1062     $$ = $1;
1063   }
1064   | /*empty*/ {
1065     $$ = new std::string(""); 
1066   };
1067
1068 OptLinkage 
1069   : INTERNAL | LINKONCE | WEAK | APPENDING | DLLIMPORT | DLLEXPORT 
1070   | EXTERN_WEAK 
1071   | /*empty*/   { $$ = new std::string(""); } ;
1072
1073 OptCallingConv 
1074   : CCC_TOK | CSRETCC_TOK | FASTCC_TOK | COLDCC_TOK | X86_STDCALLCC_TOK 
1075   | X86_FASTCALLCC_TOK 
1076   | CC_TOK EUINT64VAL { 
1077     *$1 += *$2; 
1078     delete $2;
1079     $$ = $1; 
1080     }
1081   | /*empty*/ { $$ = new std::string(""); } ;
1082
1083 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1084 // a comma before it.
1085 OptAlign 
1086   : /*empty*/        { $$ = new std::string(); }
1087   | ALIGN EUINT64VAL { *$1 += " " + *$2; delete $2; $$ = $1; };
1088
1089 OptCAlign 
1090   : /*empty*/            { $$ = new std::string(); } 
1091   | ',' ALIGN EUINT64VAL { 
1092     $2->insert(0, ", "); 
1093     *$2 += " " + *$3;
1094     delete $3;
1095     $$ = $2;
1096   };
1097
1098 SectionString 
1099   : SECTION STRINGCONSTANT { 
1100     *$1 += " " + *$2;
1101     delete $2;
1102     $$ = $1;
1103   };
1104
1105 OptSection : /*empty*/     { $$ = new std::string(); } 
1106            | SectionString;
1107
1108 GlobalVarAttributes 
1109     : /* empty */ { $$ = new std::string(); } 
1110     | ',' GlobalVarAttribute GlobalVarAttributes  {
1111       $2->insert(0, ", ");
1112       if (!$3->empty())
1113         *$2 += " " + *$3;
1114       delete $3;
1115       $$ = $2;
1116     };
1117
1118 GlobalVarAttribute 
1119     : SectionString 
1120     | ALIGN EUINT64VAL {
1121       *$1 += " " + *$2;
1122       delete $2;
1123       $$ = $1;
1124     };
1125
1126 //===----------------------------------------------------------------------===//
1127 // Types includes all predefined types... except void, because it can only be
1128 // used in specific contexts (function returning void for example).  To have
1129 // access to it, a user must explicitly use TypesV.
1130 //
1131
1132 // TypesV includes all of 'Types', but it also includes the void type.
1133 TypesV    : Types    | VOID ;
1134 UpRTypesV : UpRTypes | VOID ; 
1135 Types     : UpRTypes ;
1136
1137 // Derived types are added later...
1138 //
1139 PrimType : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT ;
1140 PrimType : LONG | ULONG | FLOAT | DOUBLE | LABEL;
1141 UpRTypes 
1142   : OPAQUE { 
1143     $$ = Type::get(*$1, OpaqueTy);
1144   } 
1145   | SymbolicValueRef { 
1146     $$ = Type::get(*$1, UnresolvedTy);
1147   }
1148   | PrimType { 
1149     $$ = $1; 
1150   }
1151   | '\\' EUINT64VAL {                   // Type UpReference
1152     $2->insert(0, "\\");
1153     $$ = Type::get(*$2, UpRefTy);
1154   }
1155   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
1156     std::string newTy( $1->getNewTy() + "(");
1157     for (unsigned i = 0; i < $3->size(); ++i) {
1158       if (i != 0)
1159         newTy +=  ", ";
1160       if ((*$3)[i]->isVoid())
1161         newTy += "...";
1162       else
1163         newTy += (*$3)[i]->getNewTy();
1164     }
1165     newTy += ")";
1166     $$ = Type::get(newTy, $1, $3);
1167   }
1168   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
1169     uint64_t elems = atoi($2->c_str());
1170     $2->insert(0,"[ ");
1171     *$2 += " x " + $4->getNewTy() + " ]";
1172     $$ = Type::get(*$2, ArrayTy, $4, elems);
1173   }
1174   | '<' EUINT64VAL 'x' UpRTypes '>' {          // Packed array type?
1175     uint64_t elems = atoi($2->c_str());
1176     $2->insert(0,"< ");
1177     *$2 += " x " + $4->getNewTy() + " >";
1178     $$ = Type::get(*$2, PackedTy, $4, elems);
1179   }
1180   | '{' TypeListI '}' {                        // Structure type?
1181     std::string newTy("{");
1182     for (unsigned i = 0; i < $2->size(); ++i) {
1183       if (i != 0)
1184         newTy +=  ", ";
1185       newTy += (*$2)[i]->getNewTy();
1186     }
1187     newTy += "}";
1188     $$ = Type::get(newTy, StructTy, $2);
1189   }
1190   | '{' '}' {                                  // Empty structure type?
1191     $$ = Type::get("{}", StructTy, new TypeList());
1192   }
1193   | '<' '{' TypeListI '}' '>' {                // Packed Structure type?
1194     std::string newTy("<{");
1195     for (unsigned i = 0; i < $3->size(); ++i) {
1196       if (i != 0)
1197         newTy +=  ", ";
1198       newTy += (*$3)[i]->getNewTy();
1199     }
1200     newTy += "}>";
1201     $$ = Type::get(newTy, PackedStructTy, $3);
1202   }
1203   | '<' '{' '}' '>' {                          // Empty packed structure type?
1204     $$ = Type::get("<{}>", PackedStructTy, new TypeList());
1205   }
1206   | UpRTypes '*' {                             // Pointer type?
1207     $$ = $1->getPointerType();
1208   };
1209
1210 // TypeList - Used for struct declarations and as a basis for function type 
1211 // declaration type lists
1212 //
1213 TypeListI 
1214   : UpRTypes {
1215     $$ = new TypeList();
1216     $$->push_back($1);
1217   }
1218   | TypeListI ',' UpRTypes {
1219     $$ = $1;
1220     $$->push_back($3);
1221   };
1222
1223 // ArgTypeList - List of types for a function type declaration...
1224 ArgTypeListI 
1225   : TypeListI 
1226   | TypeListI ',' DOTDOTDOT {
1227     $$ = $1;
1228     $$->push_back(Type::get("void",VoidTy));
1229     delete $3;
1230   }
1231   | DOTDOTDOT {
1232     $$ = new TypeList();
1233     $$->push_back(Type::get("void",VoidTy));
1234     delete $1;
1235   }
1236   | /*empty*/ {
1237     $$ = new TypeList();
1238   };
1239
1240 // ConstVal - The various declarations that go into the constant pool.  This
1241 // production is used ONLY to represent constants that show up AFTER a 'const',
1242 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1243 // into other expressions (such as integers and constexprs) are handled by the
1244 // ResolvedVal, ValueRef and ConstValueRef productions.
1245 //
1246 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1247     $$ = new Constant;
1248     $$->type = $1;
1249     $$->cnst = new std::string($1->getNewTy());
1250     *$$->cnst += " [ " + *$3 + " ]";
1251     delete $3;
1252   }
1253   | Types '[' ']' {
1254     $$ = new Constant;
1255     $$->type = $1;
1256     $$->cnst = new std::string($1->getNewTy());
1257     *$$->cnst += "[ ]";
1258   }
1259   | Types 'c' STRINGCONSTANT {
1260     $$ = new Constant;
1261     $$->type = $1;
1262     $$->cnst = new std::string($1->getNewTy());
1263     *$$->cnst += " c" + *$3;
1264     delete $3;
1265   }
1266   | Types '<' ConstVector '>' { // Nonempty unsized arr
1267     $$ = new Constant;
1268     $$->type = $1;
1269     $$->cnst = new std::string($1->getNewTy());
1270     *$$->cnst += " < " + *$3 + " >";
1271     delete $3;
1272   }
1273   | Types '{' ConstVector '}' {
1274     $$ = new Constant;
1275     $$->type = $1;
1276     $$->cnst = new std::string($1->getNewTy());
1277     *$$->cnst += " { " + *$3 + " }";
1278     delete $3;
1279   }
1280   | Types '{' '}' {
1281     $$ = new Constant;
1282     $$->type = $1;
1283     $$->cnst = new std::string($1->getNewTy());
1284     *$$->cnst += " {}";
1285   }
1286   | Types NULL_TOK {
1287     $$ = new Constant;
1288     $$->type = $1;
1289     $$->cnst = new std::string($1->getNewTy());
1290     *$$->cnst +=  " " + *$2;
1291     delete $2;
1292   }
1293   | Types UNDEF {
1294     $$ = new Constant;
1295     $$->type = $1;
1296     $$->cnst = new std::string($1->getNewTy());
1297     *$$->cnst += " " + *$2;
1298     delete $2;
1299   }
1300   | Types SymbolicValueRef {
1301     $$ = new Constant;
1302     std::string Name = getUniqueName($2, $1->resolve(), true);
1303     $$->type = $1;
1304     $$->cnst = new std::string($1->getNewTy());
1305     *$$->cnst += " " + Name;
1306     delete $2;
1307   }
1308   | Types ConstExpr {
1309     $$ = new Constant;
1310     $$->type = $1;
1311     $$->cnst = new std::string($1->getNewTy());
1312     *$$->cnst += " " + *$2;
1313     delete $2;
1314   }
1315   | Types ZEROINITIALIZER {
1316     $$ = new Constant;
1317     $$->type = $1;
1318     $$->cnst = new std::string($1->getNewTy());
1319     *$$->cnst += " " + *$2;
1320     delete $2;
1321   }
1322   | SIntType EInt64Val {      // integral constants
1323     $$ = new Constant;
1324     $$->type = $1;
1325     $$->cnst = new std::string($1->getNewTy());
1326     *$$->cnst += " " + *$2;
1327     delete $2;
1328   }
1329   | UIntType EInt64Val {            // integral constants
1330     $$ = new Constant;
1331     $$->type = $1;
1332     $$->cnst = new std::string($1->getNewTy());
1333     *$$->cnst += " " + *$2;
1334     delete $2;
1335   }
1336   | BOOL TRUETOK {                      // Boolean constants
1337     $$ = new Constant;
1338     $$->type = $1;
1339     $$->cnst = new std::string($1->getNewTy());
1340     *$$->cnst += " " + *$2;
1341     delete $2;
1342   }
1343   | BOOL FALSETOK {                     // Boolean constants
1344     $$ = new Constant;
1345     $$->type = $1;
1346     $$->cnst = new std::string($1->getNewTy());
1347     *$$->cnst += " " + *$2;
1348     delete $2;
1349   }
1350   | FPType FPVAL {                   // Float & Double constants
1351     $$ = new Constant;
1352     $$->type = $1;
1353     $$->cnst = new std::string($1->getNewTy());
1354     *$$->cnst += " " + *$2;
1355     delete $2;
1356   };
1357
1358 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1359     std::string source = *$3->cnst;
1360     const Type* SrcTy = $3->type->resolve();
1361     const Type* DstTy = $5->resolve(); 
1362     if (*$1 == "cast") {
1363       // Call getCastUpgrade to upgrade the old cast
1364       $$ = new std::string(getCastUpgrade(source, SrcTy, DstTy, true));
1365     } else {
1366       // Nothing to upgrade, just create the cast constant expr
1367       $$ = new std::string(*$1);
1368       *$$ += "( " + source + " to " + $5->getNewTy() + ")";
1369     }
1370     delete $1; delete $3; delete $4;
1371   }
1372   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1373     *$1 += "(" + *$3->cnst;
1374     for (unsigned i = 0; i < $4->size(); ++i) {
1375       Value* V = (*$4)[i];
1376       *$1 += ", " + *V->val;
1377       delete V;
1378     }
1379     *$1 += ")";
1380     $$ = $1;
1381     delete $3;
1382     delete $4;
1383   }
1384   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1385     *$1 += "(" + *$3->cnst + "," + *$5->cnst + "," + *$7->cnst + ")";
1386     delete $3; delete $5; delete $7;
1387     $$ = $1;
1388   }
1389   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1390     const char* op = getDivRemOpcode(*$1, $3->type); 
1391     $$ = new std::string(op);
1392     *$$ += "(" + *$3->cnst + "," + *$5->cnst + ")";
1393     delete $1; delete $3; delete $5;
1394   }
1395   | LogicalOps '(' ConstVal ',' ConstVal ')' {
1396     *$1 += "(" + *$3->cnst + "," + *$5->cnst + ")";
1397     delete $3; delete $5;
1398     $$ = $1;
1399   }
1400   | SetCondOps '(' ConstVal ',' ConstVal ')' {
1401     *$1 = getCompareOp(*$1, $3->type);
1402     *$1 += "(" + *$3->cnst + "," + *$5->cnst + ")";
1403     delete $3; delete $5;
1404     $$ = $1;
1405   }
1406   | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1407     *$1 += " " + *$2 + " (" +  *$4->cnst + "," + *$6->cnst + ")";
1408     delete $2; delete $4; delete $6;
1409     $$ = $1;
1410   }
1411   | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1412     *$1 += " " + *$2 + " (" + *$4->cnst + "," + *$6->cnst + ")";
1413     delete $2; delete $4; delete $6;
1414     $$ = $1;
1415   }
1416   | ShiftOps '(' ConstVal ',' ConstVal ')' {
1417     const char* shiftop = $1->c_str();
1418     if (*$1 == "shr")
1419       shiftop = ($3->type->isUnsigned()) ? "lshr" : "ashr";
1420     $$ = new std::string(shiftop);
1421     *$$ += "(" + *$3->cnst + "," + *$5->cnst + ")";
1422     delete $1; delete $3; delete $5;
1423   }
1424   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1425     *$1 += "(" + *$3->cnst + "," + *$5->cnst + ")";
1426     delete $3; delete $5;
1427     $$ = $1;
1428   }
1429   | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1430     *$1 += "(" + *$3->cnst + "," + *$5->cnst + "," + *$7->cnst + ")";
1431     delete $3; delete $5; delete $7;
1432     $$ = $1;
1433   }
1434   | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1435     *$1 += "(" + *$3->cnst + "," + *$5->cnst + "," + *$7->cnst + ")";
1436     delete $3; delete $5; delete $7;
1437     $$ = $1;
1438   };
1439
1440
1441 // ConstVector - A list of comma separated constants.
1442
1443 ConstVector 
1444   : ConstVector ',' ConstVal {
1445     *$1 += ", " + *$3->cnst;
1446     delete $3;
1447     $$ = $1;
1448   }
1449   | ConstVal { $$ = new std::string(*$1->cnst); delete $1; }
1450   ;
1451
1452
1453 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1454 GlobalType : GLOBAL | CONSTANT ;
1455
1456
1457 //===----------------------------------------------------------------------===//
1458 //                             Rules to match Modules
1459 //===----------------------------------------------------------------------===//
1460
1461 // Module rule: Capture the result of parsing the whole file into a result
1462 // variable...
1463 //
1464 Module : DefinitionList {
1465 };
1466
1467 // DefinitionList - Top level definitions
1468 //
1469 DefinitionList : DefinitionList Function {
1470     $$ = 0;
1471   } 
1472   | DefinitionList FunctionProto {
1473     *O << *$2 << '\n';
1474     delete $2;
1475     $$ = 0;
1476   }
1477   | DefinitionList MODULE ASM_TOK AsmBlock {
1478     *O << "module asm " << ' ' << *$4 << '\n';
1479     $$ = 0;
1480   }  
1481   | DefinitionList IMPLEMENTATION {
1482     *O << "implementation\n";
1483     $$ = 0;
1484   }
1485   | ConstPool { $$ = 0; }
1486   ;
1487
1488 External : EXTERNAL | UNINITIALIZED { $$ = $1; *$$ = "external"; } ;
1489
1490 // ConstPool - Constants with optional names assigned to them.
1491 ConstPool : ConstPool OptAssign TYPE TypesV {
1492     Type::EnumeratedTypes.push_back($4);
1493     if (!$2->empty()) {
1494       Type::NamedTypes[*$2] = $4;
1495       *O << *$2 << " = ";
1496     }
1497     *O << "type " << $4->getNewTy() << '\n';
1498     delete $2; delete $3;
1499     $$ = 0;
1500   }
1501   | ConstPool FunctionProto {       // Function prototypes can be in const pool
1502     *O << *$2 << '\n';
1503     delete $2;
1504     $$ = 0;
1505   }
1506   | ConstPool MODULE ASM_TOK AsmBlock {  // Asm blocks can be in the const pool
1507     *O << *$2 << ' ' << *$3 << ' ' << *$4 << '\n';
1508     delete $2; delete $3; delete $4; 
1509     $$ = 0;
1510   }
1511   | ConstPool OptAssign OptLinkage GlobalType ConstVal  GlobalVarAttributes {
1512     if (!$2->empty()) {
1513       std::string Name = getGlobalName($2,*$3, $5->type->getPointerType(),
1514                                        *$4 == "constant");
1515       *O << Name << " = ";
1516     }
1517     *O << *$3 << ' ' << *$4 << ' ' << *$5->cnst << ' ' << *$6 << '\n';
1518     delete $2; delete $3; delete $4; delete $6; 
1519     $$ = 0;
1520   }
1521   | ConstPool OptAssign External GlobalType Types  GlobalVarAttributes {
1522     if (!$2->empty()) {
1523       std::string Name = getGlobalName($2,*$3,$5->getPointerType(),
1524                                        *$4 == "constant");
1525       *O << Name << " = ";
1526     }
1527     *O <<  *$3 << ' ' << *$4 << ' ' << $5->getNewTy() << ' ' << *$6 << '\n';
1528     delete $2; delete $3; delete $4; delete $6;
1529     $$ = 0;
1530   }
1531   | ConstPool OptAssign DLLIMPORT GlobalType Types GlobalVarAttributes {
1532     if (!$2->empty()) {
1533       std::string Name = getGlobalName($2,*$3,$5->getPointerType(),
1534                                        *$4 == "constant");
1535       *O << Name << " = ";
1536     }
1537     *O << *$3 << ' ' << *$4 << ' ' << $5->getNewTy() << ' ' << *$6 << '\n';
1538     delete $2; delete $3; delete $4; delete $6;
1539     $$ = 0;
1540   }
1541   | ConstPool OptAssign EXTERN_WEAK GlobalType Types  GlobalVarAttributes {
1542     if (!$2->empty()) {
1543       std::string Name = getGlobalName($2,*$3,$5->getPointerType(),
1544                                        *$4 == "constant");
1545       *O << Name << " = ";
1546     }
1547     *O << *$3 << ' ' << *$4 << ' ' << $5->getNewTy() << ' ' << *$6 << '\n';
1548     delete $2; delete $3; delete $4; delete $6;
1549     $$ = 0;
1550   }
1551   | ConstPool TARGET TargetDefinition { 
1552     *O << *$2 << ' ' << *$3 << '\n';
1553     delete $2; delete $3;
1554     $$ = 0;
1555   }
1556   | ConstPool DEPLIBS '=' LibrariesDefinition {
1557     *O << *$2 << " = " << *$4 << '\n';
1558     delete $2; delete $4;
1559     $$ = 0;
1560   }
1561   | /* empty: end of list */ { 
1562     $$ = 0;
1563   };
1564
1565
1566 AsmBlock : STRINGCONSTANT ;
1567
1568 BigOrLittle : BIG | LITTLE ;
1569
1570 TargetDefinition 
1571   : ENDIAN '=' BigOrLittle {
1572     *$1 += " = " + *$3;
1573     delete $3;
1574     $$ = $1;
1575   }
1576   | POINTERSIZE '=' EUINT64VAL {
1577     *$1 += " = " + *$3;
1578     if (*$3 == "64")
1579       SizeOfPointer = 64;
1580     delete $3;
1581     $$ = $1;
1582   }
1583   | TRIPLE '=' STRINGCONSTANT {
1584     *$1 += " = " + *$3;
1585     delete $3;
1586     $$ = $1;
1587   }
1588   | DATALAYOUT '=' STRINGCONSTANT {
1589     *$1 += " = " + *$3;
1590     delete $3;
1591     $$ = $1;
1592   };
1593
1594 LibrariesDefinition 
1595   : '[' LibList ']' {
1596     $2->insert(0, "[ ");
1597     *$2 += " ]";
1598     $$ = $2;
1599   };
1600
1601 LibList 
1602   : LibList ',' STRINGCONSTANT {
1603     *$1 += ", " + *$3;
1604     delete $3;
1605     $$ = $1;
1606   }
1607   | STRINGCONSTANT 
1608   | /* empty: end of list */ {
1609     $$ = new std::string();
1610   };
1611
1612 //===----------------------------------------------------------------------===//
1613 //                       Rules to match Function Headers
1614 //===----------------------------------------------------------------------===//
1615
1616 Name : VAR_ID | STRINGCONSTANT;
1617 OptName : Name | /*empty*/ { $$ = new std::string(); };
1618
1619 ArgVal : Types OptName {
1620   $$ = new std::string($1->getNewTy());
1621   if (!$2->empty()) {
1622     std::string Name = getUniqueName($2, $1->resolve());
1623     *$$ += " " + Name;
1624   }
1625   delete $2;
1626 };
1627
1628 ArgListH : ArgListH ',' ArgVal {
1629     *$1 += ", " + *$3;
1630     delete $3;
1631   }
1632   | ArgVal {
1633     $$ = $1;
1634   };
1635
1636 ArgList : ArgListH {
1637     $$ = $1;
1638   }
1639   | ArgListH ',' DOTDOTDOT {
1640     *$1 += ", ...";
1641     $$ = $1;
1642     delete $3;
1643   }
1644   | DOTDOTDOT {
1645     $$ = $1;
1646   }
1647   | /* empty */ { $$ = new std::string(); };
1648
1649 FunctionHeaderH 
1650   : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
1651     if (*$3 == "%llvm.va_start" || *$3 == "%llvm.va_end") {
1652       *$5 = "i8*";
1653     } else if (*$3 == "%llvm.va_copy") {
1654       *$5 = "i8*, i8*";
1655     }
1656     if (!$1->empty()) {
1657       *$1 += " ";
1658     }
1659     *$1 += $2->getNewTy() + " " + *$3 + "(" + *$5 + ")";
1660     if (!$7->empty()) {
1661       *$1 += " " + *$7;
1662     }
1663     if (!$8->empty()) {
1664       *$1 += " " + *$8;
1665     }
1666     delete $3;
1667     delete $5;
1668     delete $7;
1669     delete $8;
1670     $$ = $1;
1671   };
1672
1673 BEGIN : BEGINTOK { $$ = new std::string("{"); delete $1; }
1674   | '{' { $$ = new std::string ("{"); }
1675   ;
1676
1677 FunctionHeader 
1678   : OptLinkage FunctionHeaderH BEGIN {
1679     *O << "define ";
1680     if (!$1->empty()) {
1681       *O << *$1 << ' ';
1682     }
1683     *O << *$2 << ' ' << *$3 << '\n';
1684     delete $1; delete $2; delete $3;
1685     $$ = 0;
1686   }
1687   ;
1688
1689 END : ENDTOK { $$ = new std::string("}"); delete $1; }
1690     | '}' { $$ = new std::string("}"); };
1691
1692 Function : FunctionHeader BasicBlockList END {
1693   if ($2)
1694     *O << *$2;
1695   *O << *$3 << "\n\n";
1696   delete $1; delete $2; delete $3;
1697   $$ = 0;
1698 };
1699
1700 FnDeclareLinkage
1701   : /*default*/ { $$ = new std::string(); }
1702   | DLLIMPORT    
1703   | EXTERN_WEAK 
1704   ;
1705   
1706 FunctionProto 
1707   : DECLARE { isDeclare = true; } FnDeclareLinkage FunctionHeaderH { 
1708     if (!$3->empty())
1709       *$1 += " " + *$3;
1710     *$1 += " " + *$4;
1711     delete $3;
1712     delete $4;
1713     $$ = $1;
1714     isDeclare = false;
1715   };
1716
1717 //===----------------------------------------------------------------------===//
1718 //                        Rules to match Basic Blocks
1719 //===----------------------------------------------------------------------===//
1720
1721 OptSideEffect : /* empty */ { $$ = new std::string(); }
1722   | SIDEEFFECT;
1723
1724 ConstValueRef 
1725   : ESINT64VAL | EUINT64VAL | FPVAL | TRUETOK | FALSETOK | NULL_TOK | UNDEF
1726   | ZEROINITIALIZER 
1727   | '<' ConstVector '>' { 
1728     $2->insert(0, "<");
1729     *$2 += ">";
1730     $$ = $2;
1731   }
1732   | ConstExpr 
1733   | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
1734     if (!$2->empty()) {
1735       *$1 += " " + *$2;
1736     }
1737     *$1 += " " + *$3 + ", " + *$5;
1738     delete $2; delete $3; delete $5;
1739     $$ = $1;
1740   };
1741
1742 SymbolicValueRef : IntVal | Name ;
1743
1744 // ValueRef - A reference to a definition... either constant or symbolic
1745 ValueRef 
1746   : SymbolicValueRef {
1747     $$ = new Value;
1748     $$->val = $1;
1749     $$->constant = false;
1750     $$->type = 0;
1751   }
1752   | ConstValueRef {
1753     $$ = new Value;
1754     $$->val = $1;
1755     $$->constant = true;
1756     $$->type = 0;
1757   }
1758   ;
1759
1760 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
1761 // type immediately preceeds the value reference, and allows complex constant
1762 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1763 ResolvedVal : Types ValueRef {
1764     $1 = $1->resolve();
1765     std::string Name = getUniqueName($2->val, $1);
1766     $$ = $2;
1767     delete $$->val;
1768     $$->val = new std::string($1->getNewTy() + " " + Name);
1769     $$->type = $1;
1770   };
1771
1772 BasicBlockList : BasicBlockList BasicBlock {
1773     $$ = 0;
1774   }
1775   | BasicBlock { // Do not allow functions with 0 basic blocks   
1776     $$ = 0;
1777   };
1778
1779
1780 // Basic blocks are terminated by branching instructions: 
1781 // br, br/cc, switch, ret
1782 //
1783 BasicBlock : InstructionList BBTerminatorInst  {
1784     $$ = 0;
1785   };
1786
1787 InstructionList : InstructionList Inst {
1788     *O << "    " << *$2 << '\n';
1789     delete $2;
1790     $$ = 0;
1791   }
1792   | /* empty */ {
1793     $$ = 0;
1794   }
1795   | LABELSTR {
1796     *O << *$1 << '\n';
1797     delete $1;
1798     $$ = 0;
1799   };
1800
1801 Unwind : UNWIND | EXCEPT { $$ = $1; *$$ = "unwind"; } ;
1802
1803 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
1804     *O << "    " << *$1 << ' ' << *$2->val << '\n';
1805     delete $1; delete $2;
1806     $$ = 0;
1807   }
1808   | RET VOID {                                       // Return with no result...
1809     *O << "    " << *$1 << ' ' << $2->getNewTy() << '\n';
1810     delete $1;
1811     $$ = 0;
1812   }
1813   | BR LABEL ValueRef {                         // Unconditional Branch...
1814     *O << "    " << *$1 << ' ' << $2->getNewTy() << ' ' << *$3->val << '\n';
1815     delete $1; delete $3;
1816     $$ = 0;
1817   }                                                  // Conditional Branch...
1818   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
1819     std::string Name = getUniqueName($3->val, $2);
1820     *O << "    " << *$1 << ' ' << $2->getNewTy() << ' ' << Name << ", " 
1821        << $5->getNewTy() << ' ' << *$6->val << ", " << $8->getNewTy() << ' ' 
1822        << *$9->val << '\n';
1823     delete $1; delete $3; delete $6; delete $9;
1824     $$ = 0;
1825   }
1826   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1827     std::string Name = getUniqueName($3->val, $2);
1828     *O << "    " << *$1 << ' ' << $2->getNewTy() << ' ' << Name << ", " 
1829        << $5->getNewTy() << ' ' << *$6->val << " [" << *$8 << " ]\n";
1830     delete $1; 
1831     delete $3;
1832     delete $6; 
1833     delete $8;
1834     $$ = 0;
1835   }
1836   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1837     std::string Name = getUniqueName($3->val, $2);
1838     *O << "    " << *$1 << ' ' << $2->getNewTy() << ' ' << Name << ", " 
1839        << $5->getNewTy() << ' ' << *$6->val << "[]\n";
1840     delete $1; 
1841     delete $3; 
1842     delete $6;
1843     $$ = 0;
1844   }
1845   | OptAssign INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
1846     TO LABEL ValueRef Unwind LABEL ValueRef {
1847     const Type* ResTy = getFunctionReturnType($4);
1848     *O << "    ";
1849     if (!$1->empty()) {
1850       std::string Name = getUniqueName($1, ResTy);
1851       *O << Name << " = ";
1852     }
1853     *O << *$2 << ' ' << *$3 << ' ' << $4->getNewTy() << ' ' << *$5->val << " (";
1854     for (unsigned i = 0; i < $7->size(); ++i) {
1855       Value* V = (*$7)[i];
1856       *O << *V->val;
1857       if (i+1 < $7->size())
1858         *O << ", ";
1859       delete V;
1860     }
1861     *O << ") " << *$9 << ' ' << $10->getNewTy() << ' ' << *$11->val << ' ' 
1862        << *$12 << ' ' << $13->getNewTy() << ' ' << *$14->val << '\n';
1863     delete $1; delete $2; delete $3; delete $5; delete $7; 
1864     delete $9; delete $11; delete $12; delete $14; 
1865     $$ = 0;
1866   }
1867   | Unwind {
1868     *O << "    " << *$1 << '\n';
1869     delete $1;
1870     $$ = 0;
1871   }
1872   | UNREACHABLE {
1873     *O << "    " << *$1 << '\n';
1874     delete $1;
1875     $$ = 0;
1876   };
1877
1878 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1879     *$1 += " " + $2->getNewTy() + " " + *$3 + ", " + $5->getNewTy() + " " + 
1880            *$6->val;
1881     delete $3; delete $6;
1882     $$ = $1;
1883   }
1884   | IntType ConstValueRef ',' LABEL ValueRef {
1885     $2->insert(0, $1->getNewTy() + " " );
1886     *$2 += ", " + $4->getNewTy() + " " + *$5->val;
1887     delete $5;
1888     $$ = $2;
1889   };
1890
1891 Inst 
1892   : OptAssign InstVal {
1893     if (!$1->empty()) {
1894       // Get a unique name for this value, based on its type.
1895       std::string Name = getUniqueName($1, $2->type);
1896       *$1 = Name + " = ";
1897       if (deleteUselessCastFlag && *deleteUselessCastName == Name) {
1898         // don't actually delete it, just comment it out
1899         $1->insert(0, "; USELSS BITCAST: "); 
1900         delete deleteUselessCastName;
1901       }
1902     }
1903     *$1 += *$2->val;
1904     delete $2;
1905     deleteUselessCastFlag = false;
1906     $$ = $1; 
1907   };
1908
1909 PHIList 
1910   : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
1911     std::string Name = getUniqueName($3->val, $1);
1912     Name.insert(0, $1->getNewTy() + "[");
1913     Name += "," + *$5->val + "]";
1914     $$ = new Value;
1915     $$->val = new std::string(Name);
1916     $$->type = $1;
1917     delete $3; delete $5;
1918   }
1919   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1920     std::string Name = getUniqueName($4->val, $1->type);
1921     *$1->val += ", [" + Name + "," + *$6->val + "]";
1922     delete $4; 
1923     delete $6;
1924     $$ = $1;
1925   };
1926
1927
1928 ValueRefList 
1929   : ResolvedVal {
1930     $$ = new ValueList();
1931     $$->push_back($1);
1932   }
1933   | ValueRefList ',' ResolvedVal {
1934     $$ = $1;
1935     $$->push_back($3);
1936   };
1937
1938 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1939 ValueRefListE 
1940   : ValueRefList  { $$ = $1; }
1941   | /*empty*/ { $$ = new ValueList(); }
1942   ;
1943
1944 OptTailCall 
1945   : TAIL CALL {
1946     *$1 += " " + *$2;
1947     delete $2;
1948     $$ = $1;
1949   }
1950   | CALL 
1951   ;
1952
1953 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1954     const char* op = getDivRemOpcode(*$1, $2); 
1955     std::string Name1 = getUniqueName($3->val, $2);
1956     std::string Name2 = getUniqueName($5->val, $2);
1957     $$ = $3;
1958     delete $$->val;
1959     $$->val = new std::string(op);
1960     *$$->val += " " + $2->getNewTy() + " " + Name1 + ", " + Name2;
1961     $$->type = $2;
1962     delete $1; delete $5;
1963   }
1964   | LogicalOps Types ValueRef ',' ValueRef {
1965     std::string Name1 = getUniqueName($3->val, $2);
1966     std::string Name2 = getUniqueName($5->val, $2);
1967     *$1 += " " + $2->getNewTy() + " " + Name1 + ", " + Name2;
1968     $$ = $3;
1969     delete $$->val;
1970     $$->val = $1;
1971     $$->type = $2;
1972     delete $5;
1973   }
1974   | SetCondOps Types ValueRef ',' ValueRef {
1975     std::string Name1 = getUniqueName($3->val, $2);
1976     std::string Name2 = getUniqueName($5->val, $2);
1977     *$1 = getCompareOp(*$1, $2);
1978     *$1 += " " + $2->getNewTy() + " " + Name1 + ", " + Name2;
1979     $$ = $3;
1980     delete $$->val;
1981     $$->val = $1;
1982     $$->type = Type::get("i1",BoolTy);
1983     delete $5;
1984   }
1985   | ICMP IPredicates Types ValueRef ',' ValueRef {
1986     std::string Name1 = getUniqueName($4->val, $3);
1987     std::string Name2 = getUniqueName($6->val, $3);
1988     *$1 += " " + *$2 + " " + $3->getNewTy() + " " + Name1 + "," + Name2;
1989     $$ = $4;
1990     delete $$->val;
1991     $$->val = $1;
1992     $$->type = Type::get("i1",BoolTy);
1993     delete $2; delete $6;
1994   }
1995   | FCMP FPredicates Types ValueRef ',' ValueRef {
1996     std::string Name1 = getUniqueName($4->val, $3);
1997     std::string Name2 = getUniqueName($6->val, $3);
1998     *$1 += " " + *$2 + " " + $3->getNewTy() + " " + Name1 + "," + Name2;
1999     $$ = $4;
2000     delete $$->val;
2001     $$->val = $1;
2002     $$->type = Type::get("i1",BoolTy);
2003     delete $2; delete $6;
2004   }
2005   | ShiftOps ResolvedVal ',' ResolvedVal {
2006     const char* shiftop = $1->c_str();
2007     if (*$1 == "shr")
2008       shiftop = ($2->type->isUnsigned()) ? "lshr" : "ashr";
2009     std::string *val = new std::string(shiftop);
2010     *val += " " + *$2->val + ", " + *$4->val;
2011     $$ = $2;
2012     delete $$->val;
2013     $$->val = val;
2014     delete $1; delete $4;
2015   }
2016   | CastOps ResolvedVal TO Types {
2017     std::string source = *$2->val;
2018     const Type* SrcTy = $2->type->resolve();
2019     const Type* DstTy = $4->resolve();
2020     $$ = $2;
2021     delete $$->val;
2022     $$->val = new std::string();
2023     $$->type = DstTy;
2024     if (*$1 == "cast") {
2025       *$$->val += getCastUpgrade(source, SrcTy, DstTy, false);
2026     } else {
2027       *$$->val += *$1 + " " + source + " to " + DstTy->getNewTy();
2028     }
2029     // Check to see if this is a useless cast of a value to the same name
2030     // and the same type. Such casts will probably cause redefinition errors
2031     // when assembled and perform no code gen action so just remove them.
2032     if (*$1 == "cast" || *$1 == "bitcast")
2033       if (SrcTy->isInteger() && DstTy->isInteger() &&
2034           SrcTy->getBitWidth() == DstTy->getBitWidth()) {
2035         deleteUselessCastFlag = true; // Flag the "Inst" rule
2036         deleteUselessCastName = new std::string(*$2->val); // save the name
2037         size_t pos = deleteUselessCastName->find_first_of("%\"",0);
2038         if (pos != std::string::npos) {
2039           // remove the type portion before val
2040           deleteUselessCastName->erase(0, pos);
2041         }
2042       }
2043     delete $1; 
2044     delete $3;
2045   }
2046   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2047     *$1 += " " + *$2->val + ", " + *$4->val + ", " + *$6->val;
2048     $$ = $2;
2049     delete $$->val;
2050     $$->val = $1;
2051     $$->type = $4->type;
2052     delete $4;
2053     delete $6;
2054   }
2055   | VAARG ResolvedVal ',' Types {
2056     *$1 += " " + *$2->val + ", " + $4->getNewTy();
2057     $$ = $2;
2058     delete $$->val;
2059     $$->val = $1;
2060     $$->type = $4;
2061   }
2062   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2063     *$1 += " " + *$2->val + ", " + *$4->val;
2064     $$ = $2;
2065     delete $$->val;
2066     $$->val = $1;
2067     $$->type = $$->type->resolve();
2068     $$->type = $$->type->getElementType();
2069     delete $4;
2070   }
2071   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2072     *$1 += " " + *$2->val + ", " + *$4->val + ", " + *$6->val;
2073     $$ = $2;
2074     delete $$->val;
2075     $$->val = $1;
2076     delete $4; delete $6;
2077   }
2078   | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2079     *$1 += " " + *$2->val + ", " + *$4->val + ", " + *$6->val;
2080     $$ = $2;
2081     delete $$->val;
2082     $$->val = $1;
2083     delete $4; delete $6;
2084   }
2085   | PHI_TOK PHIList {
2086     *$1 += " " + *$2->val;
2087     $$ = $2;
2088     delete $2->val;
2089     $$->val = $1;
2090   }
2091   | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')'  {
2092     // map llvm.isunordered to "fcmp uno" 
2093     $$ = new Value;
2094     if (*$4->val == "%llvm.isunordered.f32" ||
2095         *$4->val == "%llvm.isunordered.f64") {
2096       $$->val = new std::string( "fcmp uno " + *(*$6)[0]->val + ", ");
2097       size_t pos = (*$6)[1]->val->find(' ');
2098       assert(pos != std::string::npos && "no space?");
2099       *$$->val += (*$6)[1]->val->substr(pos+1);
2100       $$->type = Type::get("i1", BoolTy);
2101     } else {
2102       static unsigned upgradeCount = 1;
2103       if (*$4->val == "%llvm.va_start" || *$4->val == "%llvm.va_end") {
2104         if (!$6->empty()) {
2105           std::string name("%va_upgrade");
2106           name += llvm::utostr(upgradeCount++);
2107           $1->insert(0, name + " = bitcast " + *(*$6)[0]->val + " to i8*\n    ");
2108           *(*$6)[0]->val = "i8* " + name;
2109           (*$6)[0]->type = Type::get("i8", UByteTy)->getPointerType();
2110         }
2111       } else if (*$4->val == "%llvm.va_copy") {
2112         std::string name0("%va_upgrade");
2113         name0 += llvm::utostr(upgradeCount++);
2114         std::string name1("%va_upgrade");
2115         name1 += llvm::utostr(upgradeCount++);
2116         $1->insert(0, name0 + " = bitcast " + *(*$6)[0]->val + " to i8*\n    " +
2117                       name1 + " = bitcast " + *(*$6)[1]->val + " to i8*\n    ");
2118         *(*$6)[0]->val = "i8* " + name0;
2119         (*$6)[0]->type = Type::get("i8", UByteTy)->getPointerType();
2120         *(*$6)[1]->val = "i8* " + name1;
2121         (*$6)[0]->type = Type::get("i8", UByteTy)->getPointerType();
2122       }
2123       if (!$2->empty())
2124         *$1 += " " + *$2;
2125       if (!$1->empty())
2126         *$1 += " ";
2127       *$1 += $3->getNewTy() + " " + *$4->val + "(";
2128       for (unsigned i = 0; i < $6->size(); ++i) {
2129         Value* V = (*$6)[i];
2130         *$1 += *V->val;
2131         if (i+1 < $6->size())
2132           *$1 += ", ";
2133         delete V;
2134       }
2135       *$1 += ")";
2136       $$ = new Value;
2137       $$->val = $1;
2138       $$->type = getFunctionReturnType($3);
2139     }
2140     delete $2; delete $4; delete $6;
2141   }
2142   | MemoryInst ;
2143
2144
2145 // IndexList - List of indices for GEP based instructions...
2146 IndexList 
2147   : ',' ValueRefList { $$ = $2; }
2148   | /* empty */ {  $$ = new ValueList(); }
2149   ;
2150
2151 OptVolatile 
2152   : VOLATILE 
2153   | /* empty */ { $$ = new std::string(); }
2154   ;
2155
2156 MemoryInst : MALLOC Types OptCAlign {
2157     *$1 += " " + $2->getNewTy();
2158     if (!$3->empty())
2159       *$1 += " " + *$3;
2160     $$ = new Value;
2161     $$->val = $1;
2162     $$->type = $2->getPointerType();
2163     delete $3;
2164   }
2165   | MALLOC Types ',' UINT ValueRef OptCAlign {
2166     std::string Name = getUniqueName($5->val, $4);
2167     *$1 += " " + $2->getNewTy() + ", " + $4->getNewTy() + " " + Name;
2168     if (!$6->empty())
2169       *$1 += " " + *$6;
2170     $$ = new Value;
2171     $$->val = $1;
2172     $$->type = $2->getPointerType();
2173     delete $5; delete $6;
2174   }
2175   | ALLOCA Types OptCAlign {
2176     *$1 += " " + $2->getNewTy();
2177     if (!$3->empty())
2178       *$1 += " " + *$3;
2179     $$ = new Value;
2180     $$->val = $1;
2181     $$->type = $2->getPointerType();
2182     delete $3;
2183   }
2184   | ALLOCA Types ',' UINT ValueRef OptCAlign {
2185     std::string Name = getUniqueName($5->val, $4);
2186     *$1 += " " + $2->getNewTy() + ", " + $4->getNewTy() + " " + Name;
2187     if (!$6->empty())
2188       *$1 += " " + *$6;
2189     $$ = $5;
2190     delete $$->val;
2191     $$->val = $1;
2192     $$->type = $2->getPointerType();
2193     delete $6;
2194   }
2195   | FREE ResolvedVal {
2196     *$1 += " " + *$2->val;
2197     $$ = $2;
2198     delete $2->val;
2199     $$->val = $1;
2200     $$->type = Type::get("void", VoidTy); 
2201   }
2202   | OptVolatile LOAD Types ValueRef {
2203     std::string Name = getUniqueName($4->val, $3);
2204     if (!$1->empty())
2205       *$1 += " ";
2206     *$1 += *$2 + " " + $3->getNewTy() + " " + Name;
2207     $$ = $4;
2208     delete $$->val;
2209     $$->val = $1;
2210     $$->type = $3->getElementType();
2211     delete $2;
2212   }
2213   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2214     std::string Name = getUniqueName($6->val, $5);
2215     if (!$1->empty())
2216       *$1 += " ";
2217     *$1 += *$2 + " " + *$3->val + ", " + $5->getNewTy() + " " + Name;
2218     $$ = $3;
2219     delete $$->val;
2220     $$->val = $1;
2221     $$->type = Type::get("void", VoidTy);
2222     delete $2; delete $6;
2223   }
2224   | GETELEMENTPTR Types ValueRef IndexList {
2225     std::string Name = getUniqueName($3->val, $2);
2226     // Upgrade the indices
2227     for (unsigned i = 0; i < $4->size(); ++i) {
2228       Value* V = (*$4)[i];
2229       if (V->type->isUnsigned() && !V->isConstant() && 
2230           V->type->getBitWidth() < 64) {
2231         *O << "    %gep_upgrade" << UniqueNameCounter << " = zext " << *V->val 
2232            << " to i64\n";
2233         *V->val = "i64 %gep_upgrade" + llvm::utostr(UniqueNameCounter++);
2234         V->type = Type::get("i64",ULongTy);
2235       }
2236     }
2237     *$1 += " " + $2->getNewTy() + " " + Name;
2238     for (unsigned i = 0; i < $4->size(); ++i) {
2239       Value* V = (*$4)[i];
2240       *$1 += ", " + *V->val;
2241     }
2242     $$ = $3;
2243     delete $$->val;
2244     $$->val = $1;
2245     $$->type = getGEPIndexedType($2,$4); 
2246     for (unsigned i = 0; i < $4->size(); ++i)
2247       delete (*$4)[i];
2248     delete $4;
2249   };
2250
2251 %%
2252
2253 int yyerror(const char *ErrorMsg) {
2254   std::string where 
2255     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2256                   + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
2257   std::string errMsg = where + "error: " + std::string(ErrorMsg) + 
2258                        " while reading ";
2259   if (yychar == YYEMPTY || yychar == 0)
2260     errMsg += "end-of-file.";
2261   else
2262     errMsg += "token: '" + std::string(Upgradetext, Upgradeleng) + "'";
2263   std::cerr << "llvm-upgrade: " << errMsg << '\n';
2264   *O << "llvm-upgrade parse failed.\n";
2265   exit(1);
2266 }
2267
2268 void warning(const std::string& ErrorMsg) {
2269   std::string where 
2270     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2271                   + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
2272   std::string errMsg = where + "warning: " + std::string(ErrorMsg) + 
2273                        " while reading ";
2274   if (yychar == YYEMPTY || yychar == 0)
2275     errMsg += "end-of-file.";
2276   else
2277     errMsg += "token: '" + std::string(Upgradetext, Upgradeleng) + "'";
2278   std::cerr << "llvm-upgrade: " << errMsg << '\n';
2279 }