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