Finish implementation of variable renaming to handle collapsed type planes
[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 "ParserInternals.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 static uint64_t unique = 1;
34
35 // This bool controls whether attributes are ever added to function declarations
36 // definitions and calls.
37 static bool AddAttributes = false;
38
39 // This bool is used to communicate between the InstVal and Inst rules about
40 // whether or not a cast should be deleted. When the flag is set, InstVal has
41 // determined that the cast is a candidate. However, it can only be deleted if
42 // the value being casted is the same value name as the instruction. The Inst
43 // rule makes that comparison if the flag is set and comments out the
44 // instruction if they match.
45 static bool deleteUselessCastFlag = false;
46 static std::string* deleteUselessCastName = 0;
47
48 typedef std::vector<TypeInfo> TypeVector;
49 static TypeVector EnumeratedTypes;
50 typedef std::map<std::string,TypeInfo> TypeMap;
51 static TypeMap NamedTypes;
52 static TypeMap Globals;
53
54 void destroy(ValueList* VL) {
55   while (!VL->empty()) {
56     ValueInfo& VI = VL->back();
57     VI.destroy();
58     VL->pop_back();
59   }
60   delete VL;
61 }
62
63 void UpgradeAssembly(const std::string &infile, std::istream& in, 
64                      std::ostream &out, bool debug, bool addAttrs)
65 {
66   Upgradelineno = 1; 
67   CurFilename = infile;
68   LexInput = &in;
69   yydebug = debug;
70   AddAttributes = addAttrs;
71   O = &out;
72
73   if (yyparse()) {
74     std::cerr << "Parse failed.\n";
75     exit(1);
76   }
77 }
78
79 TypeInfo* ResolveType(TypeInfo*& Ty) {
80   if (Ty->isUnresolved()) {
81     if (Ty->getNewTy()[0] == '%' && isdigit(Ty->getNewTy()[1])) {
82       unsigned ref = atoi(&((Ty->getNewTy().c_str())[1])); // skip the %
83       if (ref < EnumeratedTypes.size()) {
84         Ty = &EnumeratedTypes[ref];
85         return Ty;
86       } else {
87         std::string msg("Can't resolve numbered type: ");
88         msg += Ty->getNewTy();
89         yyerror(msg.c_str());
90       }
91     } else {
92       TypeMap::iterator I = NamedTypes.find(Ty->getNewTy());
93       if (I != NamedTypes.end()) {
94         Ty = &I->second;
95         return Ty;
96       } else {
97         std::string msg("Cannot resolve type: ");
98         msg += Ty->getNewTy();
99         yyerror(msg.c_str());
100       }
101     }
102   }
103   // otherwise its already resolved.
104   return Ty;
105 }
106
107 static const char* getCastOpcode(
108   std::string& Source, const TypeInfo* SrcTy, const TypeInfo* DstTy) 
109 {
110   unsigned SrcBits = SrcTy->getBitWidth();
111   unsigned DstBits = DstTy->getBitWidth();
112   const char* opcode = "bitcast";
113   // Run through the possibilities ...
114   if (DstTy->isIntegral()) {                        // Casting to integral
115     if (SrcTy->isIntegral()) {                      // Casting from integral
116       if (DstBits < SrcBits)
117         opcode = "trunc";
118       else if (DstBits > SrcBits) {                // its an extension
119         if (SrcTy->isSigned())
120           opcode ="sext";                          // signed -> SEXT
121         else
122           opcode = "zext";                         // unsigned -> ZEXT
123       } else {
124         opcode = "bitcast";                        // Same size, No-op cast
125       }
126     } else if (SrcTy->isFloatingPoint()) {          // Casting from floating pt
127       if (DstTy->isSigned()) 
128         opcode = "fptosi";                         // FP -> sint
129       else
130         opcode = "fptoui";                         // FP -> uint 
131     } else if (SrcTy->isPacked()) {
132       assert(DstBits == SrcTy->getBitWidth() &&
133                "Casting packed to integer of different width");
134         opcode = "bitcast";                        // same size, no-op cast
135     } else {
136       assert(SrcTy->isPointer() &&
137              "Casting from a value that is not first-class type");
138       opcode = "ptrtoint";                         // ptr -> int
139     }
140   } else if (DstTy->isFloatingPoint()) {           // Casting to floating pt
141     if (SrcTy->isIntegral()) {                     // Casting from integral
142       if (SrcTy->isSigned())
143         opcode = "sitofp";                         // sint -> FP
144       else
145         opcode = "uitofp";                         // uint -> FP
146     } else if (SrcTy->isFloatingPoint()) {         // Casting from floating pt
147       if (DstBits < SrcBits) {
148         opcode = "fptrunc";                        // FP -> smaller FP
149       } else if (DstBits > SrcBits) {
150         opcode = "fpext";                          // FP -> larger FP
151       } else  {
152         opcode ="bitcast";                         // same size, no-op cast
153       }
154     } else if (SrcTy->isPacked()) {
155       assert(DstBits == SrcTy->getBitWidth() &&
156              "Casting packed to floating point of different width");
157         opcode = "bitcast";                        // same size, no-op cast
158     } else {
159       assert(0 && "Casting pointer or non-first class to float");
160     }
161   } else if (DstTy->isPacked()) {
162     if (SrcTy->isPacked()) {
163       assert(DstTy->getBitWidth() == SrcTy->getBitWidth() &&
164              "Casting packed to packed of different widths");
165       opcode = "bitcast";                          // packed -> packed
166     } else if (DstTy->getBitWidth() == SrcBits) {
167       opcode = "bitcast";                          // float/int -> packed
168     } else {
169       assert(!"Illegal cast to packed (wrong type or size)");
170     }
171   } else if (DstTy->isPointer()) {
172     if (SrcTy->isPointer()) {
173       opcode = "bitcast";                          // ptr -> ptr
174     } else if (SrcTy->isIntegral()) {
175       opcode = "inttoptr";                         // int -> ptr
176     } else {
177       assert(!"Casting invalid type to pointer");
178     }
179   } else {
180     assert(!"Casting to type that is not first-class");
181   }
182   return opcode;
183 }
184
185 static std::string getCastUpgrade(const std::string& Src, TypeInfo* SrcTy,
186                                   TypeInfo* DstTy, bool isConst)
187 {
188   std::string Result;
189   std::string Source = Src;
190   if (SrcTy->isFloatingPoint() && DstTy->isPointer()) {
191     // fp -> ptr cast is no longer supported but we must upgrade this
192     // by doing a double cast: fp -> int -> ptr
193     if (isConst)
194       Source = "i64 fptoui(" + Source + " to i64)";
195     else {
196       *O << "    %cast_upgrade" << unique << " = fptoui " << Source 
197          << " to i64\n";
198       Source = "i64 %cast_upgrade" + llvm::utostr(unique);
199     }
200     // Update the SrcTy for the getCastOpcode call below
201     delete SrcTy;
202     SrcTy = new TypeInfo("i64", ULongTy);
203   } else if (DstTy->isBool()) {
204     // cast type %x to bool was previously defined as setne type %x, null
205     // The cast semantic is now to truncate, not compare so we must retain
206     // the original intent by replacing the cast with a setne
207     const char* comparator = SrcTy->isPointer() ? ", null" : 
208       (SrcTy->isFloatingPoint() ? ", 0.0" : 
209        (SrcTy->isBool() ? ", false" : ", 0"));
210     const char* compareOp = SrcTy->isFloatingPoint() ? "fcmp one " : "icmp ne ";
211     if (isConst) { 
212       Result = "(" + Source + comparator + ")";
213       Result = compareOp + Result;
214     } else
215       Result = compareOp + Source + comparator;
216     return Result; // skip cast processing below
217   }
218   ResolveType(SrcTy);
219   ResolveType(DstTy);
220   std::string Opcode(getCastOpcode(Source, SrcTy, DstTy));
221   if (isConst)
222     Result += Opcode + "( " + Source + " to " + DstTy->getNewTy() + ")";
223   else
224     Result += Opcode + " " + Source + " to " + DstTy->getNewTy();
225   return Result;
226 }
227
228 const char* getDivRemOpcode(const std::string& opcode, TypeInfo* TI) {
229   const char* op = opcode.c_str();
230   const TypeInfo* Ty = ResolveType(TI);
231   if (Ty->isPacked())
232     Ty = Ty->getElementType();
233   if (opcode == "div")
234     if (Ty->isFloatingPoint())
235       op = "fdiv";
236     else if (Ty->isUnsigned())
237       op = "udiv";
238     else if (Ty->isSigned())
239       op = "sdiv";
240     else
241       yyerror("Invalid type for div instruction");
242   else if (opcode == "rem")
243     if (Ty->isFloatingPoint())
244       op = "frem";
245     else if (Ty->isUnsigned())
246       op = "urem";
247     else if (Ty->isSigned())
248       op = "srem";
249     else
250       yyerror("Invalid type for rem instruction");
251   return op;
252 }
253
254 std::string 
255 getCompareOp(const std::string& setcc, const TypeInfo* TI) {
256   assert(setcc.length() == 5);
257   char cc1 = setcc[3];
258   char cc2 = setcc[4];
259   assert(cc1 == 'e' || cc1 == 'n' || cc1 == 'l' || cc1 == 'g');
260   assert(cc2 == 'q' || cc2 == 'e' || cc2 == 'e' || cc2 == 't');
261   std::string result("xcmp xxx");
262   result[6] = cc1;
263   result[7] = cc2;
264   if (TI->isFloatingPoint()) {
265     result[0] = 'f';
266     result[5] = 'o';
267     if (cc1 == 'n')
268       result[5] = 'u'; // NE maps to unordered
269     else
270       result[5] = 'o'; // everything else maps to ordered
271   } else if (TI->isIntegral() || TI->isPointer()) {
272     result[0] = 'i';
273     if ((cc1 == 'e' && cc2 == 'q') || (cc1 == 'n' && cc2 == 'e'))
274       result.erase(5,1);
275     else if (TI->isSigned())
276       result[5] = 's';
277     else if (TI->isUnsigned() || TI->isPointer() || TI->isBool())
278       result[5] = 'u';
279     else
280       yyerror("Invalid integral type for setcc");
281   }
282   return result;
283 }
284
285 static TypeInfo* getFunctionReturnType(TypeInfo* PFTy) {
286   ResolveType(PFTy);
287   if (PFTy->isPointer()) {
288     TypeInfo* ElemTy = PFTy->getElementType();
289     ResolveType(ElemTy);
290     if (ElemTy->isFunction())
291       return ElemTy->getResultType()->clone();
292   } else if (PFTy->isFunction()) {
293     return PFTy->getResultType()->clone();
294   }
295   return PFTy->clone();
296 }
297
298 typedef std::vector<TypeInfo*> UpRefStack;
299 static TypeInfo* ResolveUpReference(TypeInfo* Ty, UpRefStack* stack) {
300   assert(Ty->isUpReference() && "Can't resolve a non-upreference");
301   unsigned upref = atoi(&((Ty->getNewTy().c_str())[1])); // skip the slash
302   assert(upref < stack->size() && "Invalid up reference");
303   return (*stack)[upref - stack->size() - 1];
304 }
305
306 static TypeInfo* getGEPIndexedType(TypeInfo* PTy, ValueList* idxs) {
307   TypeInfo* Result = ResolveType(PTy);
308   assert(PTy->isPointer() && "GEP Operand is not a pointer?");
309   UpRefStack stack;
310   for (unsigned i = 0; i < idxs->size(); ++i) {
311     if (Result->isComposite()) {
312       Result = Result->getIndexedType((*idxs)[i]);
313       ResolveType(Result);
314       stack.push_back(Result);
315     } else
316       yyerror("Invalid type for index");
317   }
318   // Resolve upreferences so we can return a more natural type
319   if (Result->isPointer()) {
320     if (Result->getElementType()->isUpReference()) {
321       stack.push_back(Result);
322       Result = ResolveUpReference(Result->getElementType(), &stack);
323     }
324   } else if (Result->isUpReference()) {
325     Result = ResolveUpReference(Result->getElementType(), &stack);
326   }
327   return Result->getPointerType();
328 }
329
330 static std::string makeUniqueName(const std::string *Name, bool isSigned) {
331   const char *suffix = ".u";
332   if (isSigned)
333     suffix = ".s";
334   if ((*Name)[Name->size()-1] == '"') {
335     std::string Result(*Name);
336     Result.insert(Name->size()-1, suffix);
337     return Result;
338   }
339   return *Name + suffix;
340 }
341
342 // This function handles appending .u or .s to integer value names that
343 // were previously unsigned or signed, respectively. This avoids name
344 // collisions since the unsigned and signed type planes have collapsed
345 // into a single signless type plane.
346 static std::string getUniqueName(const std::string *Name, TypeInfo* Ty) {
347   // If its not a symbolic name, don't modify it, probably a constant val.
348   if ((*Name)[0] != '%' && (*Name)[0] != '"')
349     return *Name;
350   // If its a numeric reference, just leave it alone.
351   if (isdigit((*Name)[1]))
352     return *Name;
353
354   // Resolve the type
355   ResolveType(Ty);
356
357   // Remove as many levels of pointer nesting that we have.
358   if (Ty->isPointer()) {
359     // Avoid infinite loops in recursive types
360     TypeInfo* Last = 0;
361     while (Ty->isPointer() && Last != Ty) {
362       Last = Ty;
363       Ty = Ty->getElementType();
364       ResolveType(Ty);
365     }
366   }
367
368   // Default the result to the current name
369   std::string Result = *Name; 
370
371   // Now deal with the underlying type
372   if (Ty->isInteger()) {
373     // If its an integer type, make the name unique
374     Result = makeUniqueName(Name, Ty->isSigned());
375   } else if (Ty->isArray() || Ty->isPacked()) {
376     Ty = Ty->getElementType();
377     if (Ty->isInteger())
378       Result = makeUniqueName(Name, Ty->isSigned());
379   } else if (Ty->isStruct()) {
380     // Scan the fields and count the signed and unsigned fields
381     int isSigned = 0;
382     for (unsigned i = 0; i < Ty->getNumStructElements(); ++i) {
383       TypeInfo* Tmp = Ty->getElement(i);
384       if (Tmp->isInteger())
385         if (Tmp->isSigned())
386           isSigned++;
387         else
388           isSigned--;
389     }
390     if (isSigned != 0)
391       Result = makeUniqueName(Name, isSigned > 0);
392   }
393   return Result;
394 }
395
396 %}
397
398 // %file-prefix="UpgradeParser"
399
400 %union {
401   std::string*    String;
402   TypeInfo*       Type;
403   ValueInfo       Value;
404   ConstInfo       Const;
405   ValueList*      ValList;
406   TypeList*       TypeVec;
407 }
408
409 %token <Type>   VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
410 %token <Type>   FLOAT DOUBLE LABEL 
411 %token <String> OPAQUE ESINT64VAL EUINT64VAL SINTVAL UINTVAL FPVAL
412 %token <String> NULL_TOK UNDEF ZEROINITIALIZER TRUETOK FALSETOK
413 %token <String> TYPE VAR_ID LABELSTR STRINGCONSTANT
414 %token <String> IMPLEMENTATION BEGINTOK ENDTOK
415 %token <String> DECLARE GLOBAL CONSTANT SECTION VOLATILE
416 %token <String> TO DOTDOTDOT CONST INTERNAL LINKONCE WEAK 
417 %token <String> DLLIMPORT DLLEXPORT EXTERN_WEAK APPENDING
418 %token <String> NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG
419 %token <String> ALIGN UNINITIALIZED
420 %token <String> DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
421 %token <String> CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
422 %token <String> X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
423 %token <String> DATALAYOUT
424 %token <String> RET BR SWITCH INVOKE EXCEPT UNWIND UNREACHABLE
425 %token <String> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM AND OR XOR
426 %token <String> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comparators
427 %token <String> ICMP FCMP EQ NE SLT SGT SLE SGE OEQ ONE OLT OGT OLE OGE 
428 %token <String> ORD UNO UEQ UNE ULT UGT ULE UGE
429 %token <String> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
430 %token <String> PHI_TOK SELECT SHL SHR ASHR LSHR VAARG
431 %token <String> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
432 %token <String> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI UITOFP SITOFP 
433 %token <String> PTRTOINT INTTOPTR BITCAST
434
435 %type <String> OptAssign OptLinkage OptCallingConv OptAlign OptCAlign 
436 %type <String> SectionString OptSection GlobalVarAttributes GlobalVarAttribute
437 %type <String> ConstExpr DefinitionList
438 %type <String> ConstPool TargetDefinition LibrariesDefinition LibList OptName
439 %type <String> ArgVal ArgListH ArgList FunctionHeaderH BEGIN FunctionHeader END
440 %type <String> Function FunctionProto BasicBlock 
441 %type <String> InstructionList BBTerminatorInst JumpTable Inst
442 %type <String> OptTailCall OptVolatile Unwind
443 %type <String> SymbolicValueRef OptSideEffect GlobalType
444 %type <String> FnDeclareLinkage BasicBlockList BigOrLittle AsmBlock
445 %type <String> Name ConstValueRef ConstVector External
446 %type <String> ShiftOps SetCondOps LogicalOps ArithmeticOps CastOps
447 %type <String> IPredicates FPredicates
448
449 %type <ValList> ValueRefList ValueRefListE IndexList
450 %type <TypeVec> TypeListI ArgTypeListI
451
452 %type <Type> IntType SIntType UIntType FPType TypesV Types 
453 %type <Type> PrimType UpRTypesV UpRTypes
454
455 %type <String> IntVal EInt64Val 
456 %type <Const>  ConstVal
457
458 %type <Value> ValueRef ResolvedVal InstVal PHIList MemoryInst
459
460 %start Module
461
462 %%
463
464 // Handle constant integer size restriction and conversion...
465 IntVal : SINTVAL | UINTVAL ;
466 EInt64Val : ESINT64VAL | EUINT64VAL;
467
468 // Operations that are notably excluded from this list include:
469 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
470 ArithmeticOps: ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV 
471              | REM | UREM | SREM | FREM;
472 LogicalOps   : AND | OR | XOR;
473 SetCondOps   : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
474 IPredicates  : EQ | NE | SLT | SGT | SLE | SGE | ULT | UGT | ULE | UGE;
475 FPredicates  : OEQ | ONE | OLT | OGT | OLE | OGE | ORD | UNO | UEQ | UNE
476              | ULT | UGT | ULE | UGE | TRUETOK | FALSETOK;
477 ShiftOps     : SHL | SHR | ASHR | LSHR;
478 CastOps      : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI | 
479                UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
480              ;
481
482 // These are some types that allow classification if we only want a particular 
483 // thing... for example, only a signed, unsigned, or integral type.
484 SIntType :  LONG |  INT |  SHORT | SBYTE;
485 UIntType : ULONG | UINT | USHORT | UBYTE;
486 IntType  : SIntType | UIntType;
487 FPType   : FLOAT | DOUBLE;
488
489 // OptAssign - Value producing statements have an optional assignment component
490 OptAssign : Name '=' {
491     $$ = $1;
492   }
493   | /*empty*/ {
494     $$ = new std::string(""); 
495   };
496
497 OptLinkage 
498   : INTERNAL | LINKONCE | WEAK | APPENDING | DLLIMPORT | DLLEXPORT 
499   | EXTERN_WEAK 
500   | /*empty*/   { $$ = new std::string(""); } ;
501
502 OptCallingConv 
503   : CCC_TOK | CSRETCC_TOK | FASTCC_TOK | COLDCC_TOK | X86_STDCALLCC_TOK 
504   | X86_FASTCALLCC_TOK 
505   | CC_TOK EUINT64VAL { 
506     *$1 += *$2; 
507     delete $2;
508     $$ = $1; 
509     }
510   | /*empty*/ { $$ = new std::string(""); } ;
511
512 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
513 // a comma before it.
514 OptAlign 
515   : /*empty*/        { $$ = new std::string(); }
516   | ALIGN EUINT64VAL { *$1 += " " + *$2; delete $2; $$ = $1; };
517
518 OptCAlign 
519   : /*empty*/            { $$ = new std::string(); } 
520   | ',' ALIGN EUINT64VAL { 
521     $2->insert(0, ", "); 
522     *$2 += " " + *$3;
523     delete $3;
524     $$ = $2;
525   };
526
527 SectionString 
528   : SECTION STRINGCONSTANT { 
529     *$1 += " " + *$2;
530     delete $2;
531     $$ = $1;
532   };
533
534 OptSection : /*empty*/     { $$ = new std::string(); } 
535            | SectionString;
536
537 GlobalVarAttributes 
538     : /* empty */ { $$ = new std::string(); } 
539     | ',' GlobalVarAttribute GlobalVarAttributes  {
540       $2->insert(0, ", ");
541       if (!$3->empty())
542         *$2 += " " + *$3;
543       delete $3;
544       $$ = $2;
545     };
546
547 GlobalVarAttribute 
548     : SectionString 
549     | ALIGN EUINT64VAL {
550       *$1 += " " + *$2;
551       delete $2;
552       $$ = $1;
553     };
554
555 //===----------------------------------------------------------------------===//
556 // Types includes all predefined types... except void, because it can only be
557 // used in specific contexts (function returning void for example).  To have
558 // access to it, a user must explicitly use TypesV.
559 //
560
561 // TypesV includes all of 'Types', but it also includes the void type.
562 TypesV    : Types    | VOID ;
563 UpRTypesV : UpRTypes | VOID ; 
564 Types     : UpRTypes ;
565
566 // Derived types are added later...
567 //
568 PrimType : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT ;
569 PrimType : LONG | ULONG | FLOAT | DOUBLE | LABEL;
570 UpRTypes 
571   : OPAQUE { 
572     $$ = new TypeInfo($1, OpaqueTy);
573   } 
574   | SymbolicValueRef { 
575     $$ = new TypeInfo($1, UnresolvedTy);
576   }
577   | PrimType { 
578     $$ = $1; 
579   }
580   | '\\' EUINT64VAL {                   // Type UpReference
581     $2->insert(0, "\\");
582     $$ = new TypeInfo($2, UpRefTy);
583   }
584   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
585     std::string newTy( $1->getNewTy() + "(");
586     for (unsigned i = 0; i < $3->size(); ++i) {
587       if (i != 0)
588         newTy +=  ", ";
589       if ((*$3)[i]->isVoid())
590         newTy += "...";
591       else
592         newTy += (*$3)[i]->getNewTy();
593     }
594     newTy += ")";
595     $$ = new TypeInfo(new std::string(newTy), $1, $3);
596   }
597   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
598     $2->insert(0,"[ ");
599     *$2 += " x " + $4->getNewTy() + " ]";
600     uint64_t elems = atoi($2->c_str());
601     $$ = new TypeInfo($2, ArrayTy, $4, elems);
602   }
603   | '<' EUINT64VAL 'x' UpRTypes '>' {          // Packed array type?
604     $2->insert(0,"< ");
605     *$2 += " x " + $4->getNewTy() + " >";
606     uint64_t elems = atoi($2->c_str());
607     $$ = new TypeInfo($2, PackedTy, $4, elems);
608   }
609   | '{' TypeListI '}' {                        // Structure type?
610     std::string newTy("{");
611     for (unsigned i = 0; i < $2->size(); ++i) {
612       if (i != 0)
613         newTy +=  ", ";
614       newTy += (*$2)[i]->getNewTy();
615     }
616     newTy += "}";
617     $$ = new TypeInfo(new std::string(newTy), StructTy, $2);
618   }
619   | '{' '}' {                                  // Empty structure type?
620     $$ = new TypeInfo(new std::string("{}"), StructTy, new TypeList());
621   }
622   | '<' '{' TypeListI '}' '>' {                // Packed Structure type?
623     std::string newTy("<{");
624     for (unsigned i = 0; i < $3->size(); ++i) {
625       if (i != 0)
626         newTy +=  ", ";
627       newTy += (*$3)[i]->getNewTy();
628     }
629     newTy += "}>";
630     $$ = new TypeInfo(new std::string(newTy), PackedStructTy, $3);
631   }
632   | '<' '{' '}' '>' {                          // Empty packed structure type?
633     $$ = new TypeInfo(new std::string("<{}>"), PackedStructTy, new TypeList());
634   }
635   | UpRTypes '*' {                             // Pointer type?
636     $$ = $1->getPointerType();
637   };
638
639 // TypeList - Used for struct declarations and as a basis for function type 
640 // declaration type lists
641 //
642 TypeListI 
643   : UpRTypes {
644     $$ = new TypeList();
645     $$->push_back($1);
646   }
647   | TypeListI ',' UpRTypes {
648     $$ = $1;
649     $$->push_back($3);
650   };
651
652 // ArgTypeList - List of types for a function type declaration...
653 ArgTypeListI 
654   : TypeListI 
655   | TypeListI ',' DOTDOTDOT {
656     $$ = $1;
657     $$->push_back(new TypeInfo("void",VoidTy));
658     delete $3;
659   }
660   | DOTDOTDOT {
661     $$ = new TypeList();
662     $$->push_back(new TypeInfo("void",VoidTy));
663     delete $1;
664   }
665   | /*empty*/ {
666     $$ = new TypeList();
667   };
668
669 // ConstVal - The various declarations that go into the constant pool.  This
670 // production is used ONLY to represent constants that show up AFTER a 'const',
671 // 'constant' or 'global' token at global scope.  Constants that can be inlined
672 // into other expressions (such as integers and constexprs) are handled by the
673 // ResolvedVal, ValueRef and ConstValueRef productions.
674 //
675 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
676     $$.type = $1;
677     $$.cnst = new std::string($1->getNewTy());
678     *$$.cnst += " [ " + *$3 + " ]";
679     delete $3;
680   }
681   | Types '[' ']' {
682     $$.type = $1;
683     $$.cnst = new std::string($1->getNewTy());
684     *$$.cnst += "[ ]";
685   }
686   | Types 'c' STRINGCONSTANT {
687     $$.type = $1;
688     $$.cnst = new std::string($1->getNewTy());
689     *$$.cnst += " c" + *$3;
690     delete $3;
691   }
692   | Types '<' ConstVector '>' { // Nonempty unsized arr
693     $$.type = $1;
694     $$.cnst = new std::string($1->getNewTy());
695     *$$.cnst += " < " + *$3 + " >";
696     delete $3;
697   }
698   | Types '{' ConstVector '}' {
699     $$.type = $1;
700     $$.cnst = new std::string($1->getNewTy());
701     *$$.cnst += " { " + *$3 + " }";
702     delete $3;
703   }
704   | Types '{' '}' {
705     $$.type = $1;
706     $$.cnst = new std::string($1->getNewTy());
707     *$$.cnst += " {}";
708   }
709   | Types NULL_TOK {
710     $$.type = $1;
711     $$.cnst = new std::string($1->getNewTy());
712     *$$.cnst +=  " " + *$2;
713     delete $2;
714   }
715   | Types UNDEF {
716     $$.type = $1;
717     $$.cnst = new std::string($1->getNewTy());
718     *$$.cnst += " " + *$2;
719     delete $2;
720   }
721   | Types SymbolicValueRef {
722     std::string Name = getUniqueName($2,$1);
723     $$.type = $1;
724     $$.cnst = new std::string($1->getNewTy());
725     *$$.cnst += " " + Name;
726     delete $2;
727   }
728   | Types ConstExpr {
729     $$.type = $1;
730     $$.cnst = new std::string($1->getNewTy());
731     *$$.cnst += " " + *$2;
732     delete $2;
733   }
734   | Types ZEROINITIALIZER {
735     $$.type = $1;
736     $$.cnst = new std::string($1->getNewTy());
737     *$$.cnst += " " + *$2;
738     delete $2;
739   }
740   | SIntType EInt64Val {      // integral constants
741     $$.type = $1;
742     $$.cnst = new std::string($1->getNewTy());
743     *$$.cnst += " " + *$2;
744     delete $2;
745   }
746   | UIntType EInt64Val {            // integral constants
747     $$.type = $1;
748     $$.cnst = new std::string($1->getNewTy());
749     *$$.cnst += " " + *$2;
750     delete $2;
751   }
752   | BOOL TRUETOK {                      // Boolean constants
753     $$.type = $1;
754     $$.cnst = new std::string($1->getNewTy());
755     *$$.cnst += " " + *$2;
756     delete $2;
757   }
758   | BOOL FALSETOK {                     // Boolean constants
759     $$.type = $1;
760     $$.cnst = new std::string($1->getNewTy());
761     *$$.cnst += " " + *$2;
762     delete $2;
763   }
764   | FPType FPVAL {                   // Float & Double constants
765     $$.type = $1;
766     $$.cnst = new std::string($1->getNewTy());
767     *$$.cnst += " " + *$2;
768     delete $2;
769   };
770
771
772 ConstExpr: CastOps '(' ConstVal TO Types ')' {
773     std::string source = *$3.cnst;
774     TypeInfo* DstTy = ResolveType($5);
775     if (*$1 == "cast") {
776       // Call getCastUpgrade to upgrade the old cast
777       $$ = new std::string(getCastUpgrade(source, $3.type, DstTy, true));
778     } else {
779       // Nothing to upgrade, just create the cast constant expr
780       $$ = new std::string(*$1);
781       *$$ += "( " + source + " to " + $5->getNewTy() + ")";
782     }
783     delete $1; $3.destroy(); delete $4;
784   }
785   | GETELEMENTPTR '(' ConstVal IndexList ')' {
786     *$1 += "(" + *$3.cnst;
787     for (unsigned i = 0; i < $4->size(); ++i) {
788       ValueInfo& VI = (*$4)[i];
789       *$1 += ", " + *VI.val;
790       VI.destroy();
791     }
792     *$1 += ")";
793     $$ = $1;
794     $3.destroy();
795     delete $4;
796   }
797   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
798     *$1 += "(" + *$3.cnst + "," + *$5.cnst + "," + *$7.cnst + ")";
799     $3.destroy(); $5.destroy(); $7.destroy();
800     $$ = $1;
801   }
802   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
803     const char* op = getDivRemOpcode(*$1, $3.type); 
804     $$ = new std::string(op);
805     *$$ += "(" + *$3.cnst + "," + *$5.cnst + ")";
806     delete $1; $3.destroy(); $5.destroy();
807   }
808   | LogicalOps '(' ConstVal ',' ConstVal ')' {
809     *$1 += "(" + *$3.cnst + "," + *$5.cnst + ")";
810     $3.destroy(); $5.destroy();
811     $$ = $1;
812   }
813   | SetCondOps '(' ConstVal ',' ConstVal ')' {
814     *$1 = getCompareOp(*$1, $3.type);
815     *$1 += "(" + *$3.cnst + "," + *$5.cnst + ")";
816     $3.destroy(); $5.destroy();
817     $$ = $1;
818   }
819   | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
820     *$1 += "(" + *$2 + "," + *$4.cnst + "," + *$6.cnst + ")";
821     delete $2; $4.destroy(); $6.destroy();
822     $$ = $1;
823   }
824   | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
825     *$1 += "(" + *$2 + "," + *$4.cnst + "," + *$6.cnst + ")";
826     delete $2; $4.destroy(); $6.destroy();
827     $$ = $1;
828   }
829   | ShiftOps '(' ConstVal ',' ConstVal ')' {
830     const char* shiftop = $1->c_str();
831     if (*$1 == "shr")
832       shiftop = ($3.type->isUnsigned()) ? "lshr" : "ashr";
833     $$ = new std::string(shiftop);
834     *$$ += "(" + *$3.cnst + "," + *$5.cnst + ")";
835     delete $1; $3.destroy(); $5.destroy();
836   }
837   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
838     *$1 += "(" + *$3.cnst + "," + *$5.cnst + ")";
839     $3.destroy(); $5.destroy();
840     $$ = $1;
841   }
842   | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
843     *$1 += "(" + *$3.cnst + "," + *$5.cnst + "," + *$7.cnst + ")";
844     $3.destroy(); $5.destroy(); $7.destroy();
845     $$ = $1;
846   }
847   | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
848     *$1 += "(" + *$3.cnst + "," + *$5.cnst + "," + *$7.cnst + ")";
849     $3.destroy(); $5.destroy(); $7.destroy();
850     $$ = $1;
851   };
852
853
854 // ConstVector - A list of comma separated constants.
855
856 ConstVector 
857   : ConstVector ',' ConstVal {
858     *$1 += ", " + *$3.cnst;
859     $3.destroy();
860     $$ = $1;
861   }
862   | ConstVal { $$ = new std::string(*$1.cnst); $1.destroy(); }
863   ;
864
865
866 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
867 GlobalType : GLOBAL | CONSTANT ;
868
869
870 //===----------------------------------------------------------------------===//
871 //                             Rules to match Modules
872 //===----------------------------------------------------------------------===//
873
874 // Module rule: Capture the result of parsing the whole file into a result
875 // variable...
876 //
877 Module : DefinitionList {
878 };
879
880 // DefinitionList - Top level definitions
881 //
882 DefinitionList : DefinitionList Function {
883     $$ = 0;
884   } 
885   | DefinitionList FunctionProto {
886     *O << *$2 << '\n';
887     delete $2;
888     $$ = 0;
889   }
890   | DefinitionList MODULE ASM_TOK AsmBlock {
891     *O << "module asm " << ' ' << *$4 << '\n';
892     $$ = 0;
893   }  
894   | DefinitionList IMPLEMENTATION {
895     *O << "implementation\n";
896     $$ = 0;
897   }
898   | ConstPool { $$ = 0; }
899
900 External : EXTERNAL | UNINITIALIZED { $$ = $1; *$$ = "external"; }
901
902 // ConstPool - Constants with optional names assigned to them.
903 ConstPool : ConstPool OptAssign TYPE TypesV {
904     EnumeratedTypes.push_back(*$4);
905     if (!$2->empty()) {
906       NamedTypes[*$2] = *$4;
907       *O << *$2 << " = ";
908     }
909     *O << "type " << $4->getNewTy() << '\n';
910     delete $2; delete $3;
911     $$ = 0;
912   }
913   | ConstPool FunctionProto {       // Function prototypes can be in const pool
914     *O << *$2 << '\n';
915     delete $2;
916     $$ = 0;
917   }
918   | ConstPool MODULE ASM_TOK AsmBlock {  // Asm blocks can be in the const pool
919     *O << *$2 << ' ' << *$3 << ' ' << *$4 << '\n';
920     delete $2; delete $3; delete $4; 
921     $$ = 0;
922   }
923   | ConstPool OptAssign OptLinkage GlobalType ConstVal  GlobalVarAttributes {
924     if (!$2->empty()) {
925       std::string Name = getUniqueName($2,$5.type);
926       *O << Name << " = ";
927       Globals[Name] = *$5.type;
928     }
929     *O << *$3 << ' ' << *$4 << ' ' << *$5.cnst << ' ' << *$6 << '\n';
930     delete $2; delete $3; delete $4; delete $6; 
931     $$ = 0;
932   }
933   | ConstPool OptAssign External GlobalType Types  GlobalVarAttributes {
934     if (!$2->empty()) {
935       std::string Name = getUniqueName($2,$5);
936       *O << Name << " = ";
937       Globals[Name] = *$5;
938     }
939     *O <<  *$3 << ' ' << *$4 << ' ' << $5->getNewTy() << ' ' << *$6 << '\n';
940     delete $2; delete $3; delete $4; delete $6;
941     $$ = 0;
942   }
943   | ConstPool OptAssign DLLIMPORT GlobalType Types  GlobalVarAttributes {
944     if (!$2->empty()) {
945       std::string Name = getUniqueName($2,$5);
946       *O << Name << " = ";
947       Globals[Name] = *$5;
948     }
949     *O << *$3 << ' ' << *$4 << ' ' << $5->getNewTy() << ' ' << *$6 << '\n';
950     delete $2; delete $3; delete $4; delete $6;
951     $$ = 0;
952   }
953   | ConstPool OptAssign EXTERN_WEAK GlobalType Types  GlobalVarAttributes {
954     if (!$2->empty()) {
955       std::string Name = getUniqueName($2,$5);
956       *O << Name << " = ";
957       Globals[Name] = *$5;
958     }
959     *O << *$3 << ' ' << *$4 << ' ' << $5->getNewTy() << ' ' << *$6 << '\n';
960     delete $2; delete $3; delete $4; delete $6;
961     $$ = 0;
962   }
963   | ConstPool TARGET TargetDefinition { 
964     *O << *$2 << ' ' << *$3 << '\n';
965     delete $2; delete $3;
966     $$ = 0;
967   }
968   | ConstPool DEPLIBS '=' LibrariesDefinition {
969     *O << *$2 << " = " << *$4 << '\n';
970     delete $2; delete $4;
971     $$ = 0;
972   }
973   | /* empty: end of list */ { 
974     $$ = 0;
975   };
976
977
978 AsmBlock : STRINGCONSTANT ;
979
980 BigOrLittle : BIG | LITTLE 
981
982 TargetDefinition 
983   : ENDIAN '=' BigOrLittle {
984     *$1 += " = " + *$3;
985     delete $3;
986     $$ = $1;
987   }
988   | POINTERSIZE '=' EUINT64VAL {
989     *$1 += " = " + *$3;
990     if (*$3 == "64")
991       SizeOfPointer = 64;
992     delete $3;
993     $$ = $1;
994   }
995   | TRIPLE '=' STRINGCONSTANT {
996     *$1 += " = " + *$3;
997     delete $3;
998     $$ = $1;
999   }
1000   | DATALAYOUT '=' STRINGCONSTANT {
1001     *$1 += " = " + *$3;
1002     delete $3;
1003     $$ = $1;
1004   };
1005
1006 LibrariesDefinition 
1007   : '[' LibList ']' {
1008     $2->insert(0, "[ ");
1009     *$2 += " ]";
1010     $$ = $2;
1011   };
1012
1013 LibList 
1014   : LibList ',' STRINGCONSTANT {
1015     *$1 += ", " + *$3;
1016     delete $3;
1017     $$ = $1;
1018   }
1019   | STRINGCONSTANT 
1020   | /* empty: end of list */ {
1021     $$ = new std::string();
1022   };
1023
1024 //===----------------------------------------------------------------------===//
1025 //                       Rules to match Function Headers
1026 //===----------------------------------------------------------------------===//
1027
1028 Name : VAR_ID | STRINGCONSTANT;
1029 OptName : Name | /*empty*/ { $$ = new std::string(); };
1030
1031 ArgVal : Types OptName {
1032   $$ = new std::string($1->getNewTy());
1033   if (!$2->empty()) {
1034     std::string Name = getUniqueName($2, $1);
1035     *$$ += " " + Name;
1036   }
1037   delete $2;
1038 };
1039
1040 ArgListH : ArgListH ',' ArgVal {
1041     *$1 += ", " + *$3;
1042     delete $3;
1043   }
1044   | ArgVal {
1045     $$ = $1;
1046   };
1047
1048 ArgList : ArgListH {
1049     $$ = $1;
1050   }
1051   | ArgListH ',' DOTDOTDOT {
1052     *$1 += ", ...";
1053     $$ = $1;
1054     delete $3;
1055   }
1056   | DOTDOTDOT {
1057     $$ = $1;
1058   }
1059   | /* empty */ { $$ = new std::string(); };
1060
1061 FunctionHeaderH 
1062   : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
1063     if (!$1->empty()) {
1064       *$1 += " ";
1065     }
1066     *$1 += $2->getNewTy() + " " + *$3 + "(" + *$5 + ")";
1067     if (!$7->empty()) {
1068       *$1 += " " + *$7;
1069     }
1070     if (!$8->empty()) {
1071       *$1 += " " + *$8;
1072     }
1073     delete $3;
1074     delete $5;
1075     delete $7;
1076     delete $8;
1077     $$ = $1;
1078   };
1079
1080 BEGIN : BEGINTOK { $$ = new std::string("{"); delete $1; }
1081   | '{' { $$ = new std::string ("{"); }
1082
1083 FunctionHeader 
1084   : OptLinkage FunctionHeaderH BEGIN {
1085     *O << "define ";
1086     if (!$1->empty()) {
1087       *O << *$1 << ' ';
1088     }
1089     *O << *$2 << ' ' << *$3 << '\n';
1090     delete $1; delete $2; delete $3;
1091     $$ = 0;
1092   }
1093   ;
1094
1095 END : ENDTOK { $$ = new std::string("}"); delete $1; }
1096     | '}' { $$ = new std::string("}"); };
1097
1098 Function : FunctionHeader BasicBlockList END {
1099   if ($2)
1100     *O << *$2;
1101   *O << *$3 << "\n\n";
1102   delete $1; delete $2; delete $3;
1103   $$ = 0;
1104 };
1105
1106 FnDeclareLinkage
1107   : /*default*/ { $$ = new std::string(); }
1108   | DLLIMPORT    
1109   | EXTERN_WEAK 
1110   ;
1111   
1112 FunctionProto 
1113   : DECLARE FnDeclareLinkage FunctionHeaderH { 
1114     if (!$2->empty())
1115       *$1 += " " + *$2;
1116     *$1 += " " + *$3;
1117     delete $2;
1118     delete $3;
1119     $$ = $1;
1120   };
1121
1122 //===----------------------------------------------------------------------===//
1123 //                        Rules to match Basic Blocks
1124 //===----------------------------------------------------------------------===//
1125
1126 OptSideEffect : /* empty */ { $$ = new std::string(); }
1127   | SIDEEFFECT;
1128
1129 ConstValueRef 
1130   : ESINT64VAL | EUINT64VAL | FPVAL | TRUETOK | FALSETOK | NULL_TOK | UNDEF
1131   | ZEROINITIALIZER 
1132   | '<' ConstVector '>' { 
1133     $2->insert(0, "<");
1134     *$2 += ">";
1135     $$ = $2;
1136   }
1137   | ConstExpr 
1138   | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
1139     if (!$2->empty()) {
1140       *$1 += " " + *$2;
1141     }
1142     *$1 += " " + *$3 + ", " + *$5;
1143     delete $2; delete $3; delete $5;
1144     $$ = $1;
1145   };
1146
1147 SymbolicValueRef : IntVal | Name ;
1148
1149 // ValueRef - A reference to a definition... either constant or symbolic
1150 ValueRef 
1151   : SymbolicValueRef {
1152     $$.val = $1;
1153     $$.constant = false;
1154     $$.type = new TypeInfo();
1155   }
1156   | ConstValueRef {
1157     $$.val = $1;
1158     $$.constant = true;
1159     $$.type = new TypeInfo();
1160   }
1161   ;
1162
1163 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
1164 // type immediately preceeds the value reference, and allows complex constant
1165 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1166 ResolvedVal : Types ValueRef {
1167     ResolveType($1);
1168     std::string Name = getUniqueName($2.val, $1);
1169     $$ = $2;
1170     delete $$.val;
1171     delete $$.type;
1172     $$.val = new std::string($1->getNewTy() + " " + Name);
1173     $$.type = $1;
1174   };
1175
1176 BasicBlockList : BasicBlockList BasicBlock {
1177     $$ = 0;
1178   }
1179   | BasicBlock { // Do not allow functions with 0 basic blocks   
1180     $$ = 0;
1181   };
1182
1183
1184 // Basic blocks are terminated by branching instructions: 
1185 // br, br/cc, switch, ret
1186 //
1187 BasicBlock : InstructionList BBTerminatorInst  {
1188     $$ = 0;
1189   };
1190
1191 InstructionList : InstructionList Inst {
1192     *O << "    " << *$2 << '\n';
1193     delete $2;
1194     $$ = 0;
1195   }
1196   | /* empty */ {
1197     $$ = 0;
1198   }
1199   | LABELSTR {
1200     *O << *$1 << '\n';
1201     delete $1;
1202     $$ = 0;
1203   };
1204
1205 Unwind : UNWIND | EXCEPT { $$ = $1; *$$ = "unwind"; }
1206
1207 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
1208     *O << "    " << *$1 << ' ' << *$2.val << '\n';
1209     delete $1; $2.destroy();
1210     $$ = 0;
1211   }
1212   | RET VOID {                                       // Return with no result...
1213     *O << "    " << *$1 << ' ' << $2->getNewTy() << '\n';
1214     delete $1; delete $2;
1215     $$ = 0;
1216   }
1217   | BR LABEL ValueRef {                         // Unconditional Branch...
1218     *O << "    " << *$1 << ' ' << $2->getNewTy() << ' ' << *$3.val << '\n';
1219     delete $1; delete $2; $3.destroy();
1220     $$ = 0;
1221   }                                                  // Conditional Branch...
1222   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
1223     std::string Name = getUniqueName($3.val, $2);
1224     *O << "    " << *$1 << ' ' << $2->getNewTy() << ' ' << Name << ", " 
1225        << $5->getNewTy() << ' ' << *$6.val << ", " << $8->getNewTy() << ' ' 
1226        << *$9.val << '\n';
1227     delete $1; delete $2; $3.destroy(); delete $5; $6.destroy(); 
1228     delete $8; $9.destroy();
1229     $$ = 0;
1230   }
1231   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1232     std::string Name = getUniqueName($3.val, $2);
1233     *O << "    " << *$1 << ' ' << $2->getNewTy() << ' ' << Name << ", " 
1234        << $5->getNewTy() << ' ' << *$6.val << " [" << *$8 << " ]\n";
1235     delete $1; delete $2; $3.destroy(); delete $5; $6.destroy(); 
1236     delete $8;
1237     $$ = 0;
1238   }
1239   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1240     std::string Name = getUniqueName($3.val, $2);
1241     *O << "    " << *$1 << ' ' << $2->getNewTy() << ' ' << Name << ", " 
1242        << $5->getNewTy() << ' ' << *$6.val << "[]\n";
1243     delete $1; delete $2; $3.destroy(); delete $5; $6.destroy();
1244     $$ = 0;
1245   }
1246   | OptAssign INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
1247     TO LABEL ValueRef Unwind LABEL ValueRef {
1248     TypeInfo* ResTy = getFunctionReturnType($4);
1249     *O << "    ";
1250     if (!$1->empty()) {
1251       std::string Name = getUniqueName($1, ResTy);
1252       *O << Name << " = ";
1253     }
1254     *O << *$2 << ' ' << *$3 << ' ' << $4->getNewTy() << ' ' << *$5.val << " (";
1255     for (unsigned i = 0; i < $7->size(); ++i) {
1256       ValueInfo& VI = (*$7)[i];
1257       *O << *VI.val;
1258       if (i+1 < $7->size())
1259         *O << ", ";
1260       VI.destroy();
1261     }
1262     *O << ") " << *$9 << ' ' << $10->getNewTy() << ' ' << *$11.val << ' ' 
1263        << *$12 << ' ' << $13->getNewTy() << ' ' << *$14.val << '\n';
1264     delete $1; delete $2; delete $3; delete $4; $5.destroy(); delete $7; 
1265     delete $9; delete $10; $11.destroy(); delete $12; delete $13; 
1266     $14.destroy(); 
1267     $$ = 0;
1268   }
1269   | Unwind {
1270     *O << "    " << *$1 << '\n';
1271     delete $1;
1272     $$ = 0;
1273   }
1274   | UNREACHABLE {
1275     *O << "    " << *$1 << '\n';
1276     delete $1;
1277     $$ = 0;
1278   };
1279
1280 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1281     *$1 += " " + $2->getNewTy() + " " + *$3 + ", " + $5->getNewTy() + " " + 
1282            *$6.val;
1283     delete $2; delete $3; delete $5; $6.destroy();
1284     $$ = $1;
1285   }
1286   | IntType ConstValueRef ',' LABEL ValueRef {
1287     $2->insert(0, $1->getNewTy() + " " );
1288     *$2 += ", " + $4->getNewTy() + " " + *$5.val;
1289     delete $1; delete $4; $5.destroy();
1290     $$ = $2;
1291   };
1292
1293 Inst 
1294   : OptAssign InstVal {
1295     if (!$1->empty()) {
1296       if (deleteUselessCastFlag && *deleteUselessCastName == *$1) {
1297         *$1 += " = ";
1298         $1->insert(0, "; "); // don't actually delete it, just comment it out
1299         delete deleteUselessCastName;
1300       } else {
1301         // Get a unique name for the name of this value, based on its type.
1302         *$1 = getUniqueName($1, $2.type) + " = ";
1303       }
1304     }
1305     *$1 += *$2.val;
1306     $2.destroy();
1307     deleteUselessCastFlag = false;
1308     $$ = $1; 
1309   };
1310
1311 PHIList 
1312   : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
1313     std::string Name = getUniqueName($3.val, $1);
1314     Name.insert(0, $1->getNewTy() + "[");
1315     Name += "," + *$5.val + "]";
1316     $$.val = new std::string(Name);
1317     $$.type = $1;
1318     $3.destroy(); $5.destroy();
1319   }
1320   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1321     std::string Name = getUniqueName($4.val, $1.type);
1322     *$1.val += ", [" + Name + "," + *$6.val + "]";
1323     $4.destroy(); $6.destroy();
1324     $$ = $1;
1325   };
1326
1327
1328 ValueRefList 
1329   : ResolvedVal {
1330     $$ = new ValueList();
1331     $$->push_back($1);
1332   }
1333   | ValueRefList ',' ResolvedVal {
1334     $$ = $1;
1335     $$->push_back($3);
1336   };
1337
1338 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1339 ValueRefListE 
1340   : ValueRefList  { $$ = $1; }
1341   | /*empty*/ { $$ = new ValueList(); }
1342   ;
1343
1344 OptTailCall 
1345   : TAIL CALL {
1346     *$1 += " " + *$2;
1347     delete $2;
1348     $$ = $1;
1349   }
1350   | CALL 
1351   ;
1352
1353 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1354     const char* op = getDivRemOpcode(*$1, $2); 
1355     std::string Name1 = getUniqueName($3.val, $2);
1356     std::string Name2 = getUniqueName($5.val, $2);
1357     $$.val = new std::string(op);
1358     *$$.val += " " + $2->getNewTy() + " " + Name1 + ", " + Name2;
1359     $$.type = $2;
1360     delete $1; $3.destroy(); $5.destroy();
1361   }
1362   | LogicalOps Types ValueRef ',' ValueRef {
1363     std::string Name1 = getUniqueName($3.val, $2);
1364     std::string Name2 = getUniqueName($5.val, $2);
1365     *$1 += " " + $2->getNewTy() + " " + Name1 + ", " + Name2;
1366     $$.val = $1;
1367     $$.type = $2;
1368     $3.destroy(); $5.destroy();
1369   }
1370   | SetCondOps Types ValueRef ',' ValueRef {
1371     std::string Name1 = getUniqueName($3.val, $2);
1372     std::string Name2 = getUniqueName($5.val, $2);
1373     *$1 = getCompareOp(*$1, $2);
1374     *$1 += " " + $2->getNewTy() + " " + Name1 + ", " + Name2;
1375     $$.val = $1;
1376     $$.type = new TypeInfo("bool",BoolTy);
1377     $3.destroy(); $5.destroy();
1378   }
1379   | ICMP IPredicates Types ValueRef ',' ValueRef {
1380     std::string Name1 = getUniqueName($4.val, $3);
1381     std::string Name2 = getUniqueName($6.val, $3);
1382     *$1 += " " + *$2 + " " + $3->getNewTy() + " " + Name1 + "," + Name2;
1383     $$.val = $1;
1384     $$.type = new TypeInfo("bool",BoolTy);
1385     delete $2; $4.destroy(); $6.destroy();
1386   }
1387   | FCMP FPredicates Types ValueRef ',' ValueRef {
1388     std::string Name1 = getUniqueName($4.val, $3);
1389     std::string Name2 = getUniqueName($6.val, $3);
1390     *$1 += " " + *$2 + " " + $3->getNewTy() + " " + Name1 + "," + Name2;
1391     $$.val = $1;
1392     $$.type = new TypeInfo("bool",BoolTy);
1393     delete $2; $4.destroy(); $6.destroy();
1394   }
1395   | NOT ResolvedVal {
1396     $$ = $2;
1397     $$.val->insert(0, *$1 + " ");
1398     delete $1;
1399   }
1400   | ShiftOps ResolvedVal ',' ResolvedVal {
1401     const char* shiftop = $1->c_str();
1402     if (*$1 == "shr")
1403       shiftop = ($2.type->isUnsigned()) ? "lshr" : "ashr";
1404     $$.val = new std::string(shiftop);
1405     *$$.val += " " + *$2.val + ", " + *$4.val;
1406     $$.type = $2.type;
1407     delete $1; delete $2.val; $4.destroy();
1408   }
1409   | CastOps ResolvedVal TO Types {
1410     std::string source = *$2.val;
1411     TypeInfo* SrcTy = $2.type;
1412     TypeInfo* DstTy = ResolveType($4);
1413     $$.val = new std::string();
1414     if (*$1 == "cast") {
1415       *$$.val +=  getCastUpgrade(source, SrcTy, DstTy, false);
1416     } else {
1417       *$$.val += *$1 + " " + source + " to " + DstTy->getNewTy();
1418     }
1419     $$.type = $4;
1420     // Check to see if this is a useless cast of a value to the same name
1421     // and the same type. Such casts will probably cause redefinition errors
1422     // when assembled and perform no code gen action so just remove them.
1423     if (*$1 == "cast" || *$1 == "bitcast")
1424       if ($2.type->isInteger() && DstTy->isInteger() &&
1425           $2.type->getBitWidth() == DstTy->getBitWidth()) {
1426         deleteUselessCastFlag = true; // Flag the "Inst" rule
1427         deleteUselessCastName = new std::string(*$2.val); // save the name
1428         size_t pos = deleteUselessCastName->find_first_of("%\"",0);
1429         if (pos != std::string::npos) {
1430           // remove the type portion before val
1431           deleteUselessCastName->erase(0, pos);
1432         }
1433       }
1434     delete $1; $2.destroy();
1435     delete $3;
1436   }
1437   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1438     *$1 += " " + *$2.val + ", " + *$4.val + ", " + *$6.val;
1439     $$.val = $1;
1440     $$.type = $4.type;
1441     $2.destroy(); delete $4.val; $6.destroy();
1442   }
1443   | VAARG ResolvedVal ',' Types {
1444     *$1 += " " + *$2.val + ", " + $4->getNewTy();
1445     $$.val = $1;
1446     $$.type = $4;
1447     $2.destroy();
1448   }
1449   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
1450     *$1 += " " + *$2.val + ", " + *$4.val;
1451     $$.val = $1;
1452     ResolveType($2.type);
1453     $$.type = $2.type->getElementType();
1454     delete $2.val; $4.destroy();
1455   }
1456   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1457     *$1 += " " + *$2.val + ", " + *$4.val + ", " + *$6.val;
1458     $$.val = $1;
1459     $$.type = $2.type;
1460     delete $2.val; $4.destroy(); $6.destroy();
1461   }
1462   | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1463     *$1 += " " + *$2.val + ", " + *$4.val + ", " + *$6.val;
1464     $$.val = $1;
1465     $$.type = $2.type;
1466     delete $2.val; $4.destroy(); $6.destroy();
1467   }
1468   | PHI_TOK PHIList {
1469     *$1 += " " + *$2.val;
1470     $$.val = $1;
1471     $$.type = $2.type;
1472     delete $2.val;
1473   }
1474   | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')'  {
1475     if (!$2->empty())
1476       *$1 += " " + *$2;
1477     if (!$1->empty())
1478       *$1 += " ";
1479     *$1 += $3->getNewTy() + " " + *$4.val + "(";
1480     for (unsigned i = 0; i < $6->size(); ++i) {
1481       ValueInfo& VI = (*$6)[i];
1482       *$1 += *VI.val;
1483       if (i+1 < $6->size())
1484         *$1 += ", ";
1485       VI.destroy();
1486     }
1487     *$1 += ")";
1488     $$.val = $1;
1489     $$.type = getFunctionReturnType($3);
1490     delete $2; delete $3; $4.destroy(); delete $6;
1491   }
1492   | MemoryInst ;
1493
1494
1495 // IndexList - List of indices for GEP based instructions...
1496 IndexList 
1497   : ',' ValueRefList { $$ = $2; }
1498   | /* empty */ {  $$ = new ValueList(); }
1499   ;
1500
1501 OptVolatile 
1502   : VOLATILE 
1503   | /* empty */ { $$ = new std::string(); }
1504   ;
1505
1506 MemoryInst : MALLOC Types OptCAlign {
1507     *$1 += " " + $2->getNewTy();
1508     if (!$3->empty())
1509       *$1 += " " + *$3;
1510     $$.val = $1;
1511     $$.type = $2->getPointerType();
1512     delete $2; delete $3;
1513   }
1514   | MALLOC Types ',' UINT ValueRef OptCAlign {
1515     std::string Name = getUniqueName($5.val, $4);
1516     *$1 += " " + $2->getNewTy() + ", " + $4->getNewTy() + " " + Name;
1517     if (!$6->empty())
1518       *$1 += " " + *$6;
1519     $$.val = $1;
1520     $$.type = $2->getPointerType();
1521     delete $2; delete $4; $5.destroy(); delete $6;
1522   }
1523   | ALLOCA Types OptCAlign {
1524     *$1 += " " + $2->getNewTy();
1525     if (!$3->empty())
1526       *$1 += " " + *$3;
1527     $$.val = $1;
1528     $$.type = $2->getPointerType();
1529     delete $2; delete $3;
1530   }
1531   | ALLOCA Types ',' UINT ValueRef OptCAlign {
1532     std::string Name = getUniqueName($5.val, $4);
1533     *$1 += " " + $2->getNewTy() + ", " + $4->getNewTy() + " " + Name;
1534     if (!$6->empty())
1535       *$1 += " " + *$6;
1536     $$.val = $1;
1537     $$.type = $2->getPointerType();
1538     delete $2; delete $4; $5.destroy(); delete $6;
1539   }
1540   | FREE ResolvedVal {
1541     *$1 += " " + *$2.val;
1542     $$.val = $1;
1543     $$.type = new TypeInfo("void", VoidTy); 
1544     $2.destroy();
1545   }
1546   | OptVolatile LOAD Types ValueRef {
1547     std::string Name = getUniqueName($4.val, $3);
1548     if (!$1->empty())
1549       *$1 += " ";
1550     *$1 += *$2 + " " + $3->getNewTy() + " " + Name;
1551     $$.val = $1;
1552     $$.type = $3->getElementType()->clone();
1553     delete $2; delete $3; $4.destroy();
1554   }
1555   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
1556     std::string Name = getUniqueName($6.val, $5);
1557     if (!$1->empty())
1558       *$1 += " ";
1559     *$1 += *$2 + " " + *$3.val + ", " + $5->getNewTy() + " " + Name;
1560     $$.val = $1;
1561     $$.type = new TypeInfo("void", VoidTy);
1562     delete $2; $3.destroy(); delete $5; $6.destroy();
1563   }
1564   | GETELEMENTPTR Types ValueRef IndexList {
1565     std::string Name = getUniqueName($3.val, $2);
1566     // Upgrade the indices
1567     for (unsigned i = 0; i < $4->size(); ++i) {
1568       ValueInfo& VI = (*$4)[i];
1569       if (VI.type->isUnsigned() && !VI.isConstant() && 
1570           VI.type->getBitWidth() < 64) {
1571         std::string* old = VI.val;
1572         *O << "    %gep_upgrade" << unique << " = zext " << *old 
1573            << " to i64\n";
1574         VI.val = new std::string("i64 %gep_upgrade" + llvm::utostr(unique++));
1575         VI.type->setOldTy(ULongTy);
1576       }
1577     }
1578     *$1 += " " + $2->getNewTy() + " " + Name;
1579     for (unsigned i = 0; i < $4->size(); ++i) {
1580       ValueInfo& VI = (*$4)[i];
1581       *$1 += ", " + *VI.val;
1582     }
1583     $$.val = $1;
1584     $$.type = getGEPIndexedType($2,$4); 
1585     $3.destroy(); delete $4;
1586   };
1587
1588 %%
1589
1590 int yyerror(const char *ErrorMsg) {
1591   std::string where 
1592     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
1593                   + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
1594   std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
1595   if (yychar == YYEMPTY || yychar == 0)
1596     errMsg += "end-of-file.";
1597   else
1598     errMsg += "token: '" + std::string(Upgradetext, Upgradeleng) + "'";
1599   std::cerr << "llvm-upgrade: " << errMsg << '\n';
1600   exit(1);
1601 }