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