Fix a crash-by-unknown-exception caused by attempting to use a null pointer
[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       // We found an existing global ov the same name. This isn't allowed 
939       // in LLVM 2.0. Consequently, we must alter the name of the global so it
940       // can at least compile. This can happen because of type planes 
941       // There is alread a global of the same name which means there is a
942       // conflict. Let's see what we can do about it.
943       std::string NewName(makeNameUnique(Name));
944       if (Linkage != GlobalValue::InternalLinkage) {
945         // The linkage of this gval is external so we can't reliably rename 
946         // it because it could potentially create a linking problem.  
947         // However, we can't leave the name conflict in the output either or 
948         // it won't assemble with LLVM 2.0.  So, all we can do is rename 
949         // this one to something unique and emit a warning about the problem.
950         warning("Renaming global variable '" + Name + "' to '" + NewName + 
951                   "' may cause linkage errors");
952       }
953
954       // Put the renaming in the global rename map
955       RenameMapKey Key = makeRenameMapKey(Name, PointerType::get(Ty), ID.S);
956       CurModule.RenameMap[Key] = NewName;
957
958       // Rename it
959       Name = NewName;
960     }
961   }
962
963   // Otherwise there is no existing GV to use, create one now.
964   GlobalVariable *GV =
965     new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
966                        CurModule.CurrentModule);
967   InsertValue(GV, CurModule.Values);
968   // Remember the sign of this global.
969   CurModule.NamedValueSigns[Name] = ID.S;
970   return GV;
971 }
972
973 // setTypeName - Set the specified type to the name given.  The name may be
974 // null potentially, in which case this is a noop.  The string passed in is
975 // assumed to be a malloc'd string buffer, and is freed by this function.
976 //
977 // This function returns true if the type has already been defined, but is
978 // allowed to be redefined in the specified context.  If the name is a new name
979 // for the type plane, it is inserted and false is returned.
980 static bool setTypeName(const PATypeInfo& TI, char *NameStr) {
981   assert(!inFunctionScope() && "Can't give types function-local names");
982   if (NameStr == 0) return false;
983  
984   std::string Name(NameStr);      // Copy string
985   free(NameStr);                  // Free old string
986
987   const Type* Ty = TI.PAT->get();
988
989   // We don't allow assigning names to void type
990   if (Ty == Type::VoidTy) {
991     error("Can't assign name '" + Name + "' to the void type");
992     return false;
993   }
994
995   // Set the type name, checking for conflicts as we do so.
996   bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, Ty);
997
998   // Save the sign information for later use 
999   CurModule.NamedTypeSigns[Name] = TI.S;
1000
1001   if (AlreadyExists) {   // Inserting a name that is already defined???
1002     const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
1003     assert(Existing && "Conflict but no matching type?");
1004
1005     // There is only one case where this is allowed: when we are refining an
1006     // opaque type.  In this case, Existing will be an opaque type.
1007     if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
1008       // We ARE replacing an opaque type!
1009       const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(Ty);
1010       return true;
1011     }
1012
1013     // Otherwise, this is an attempt to redefine a type. That's okay if
1014     // the redefinition is identical to the original. This will be so if
1015     // Existing and T point to the same Type object. In this one case we
1016     // allow the equivalent redefinition.
1017     if (Existing == Ty) return true;  // Yes, it's equal.
1018
1019     // Any other kind of (non-equivalent) redefinition is an error.
1020     error("Redefinition of type named '" + Name + "' in the '" +
1021           Ty->getDescription() + "' type plane");
1022   }
1023
1024   return false;
1025 }
1026
1027 //===----------------------------------------------------------------------===//
1028 // Code for handling upreferences in type names...
1029 //
1030
1031 // TypeContains - Returns true if Ty directly contains E in it.
1032 //
1033 static bool TypeContains(const Type *Ty, const Type *E) {
1034   return std::find(Ty->subtype_begin(), Ty->subtype_end(),
1035                    E) != Ty->subtype_end();
1036 }
1037
1038 namespace {
1039   struct UpRefRecord {
1040     // NestingLevel - The number of nesting levels that need to be popped before
1041     // this type is resolved.
1042     unsigned NestingLevel;
1043
1044     // LastContainedTy - This is the type at the current binding level for the
1045     // type.  Every time we reduce the nesting level, this gets updated.
1046     const Type *LastContainedTy;
1047
1048     // UpRefTy - This is the actual opaque type that the upreference is
1049     // represented with.
1050     OpaqueType *UpRefTy;
1051
1052     UpRefRecord(unsigned NL, OpaqueType *URTy)
1053       : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) { }
1054   };
1055 }
1056
1057 // UpRefs - A list of the outstanding upreferences that need to be resolved.
1058 static std::vector<UpRefRecord> UpRefs;
1059
1060 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1061 /// called.  It loops through the UpRefs vector, which is a list of the
1062 /// currently active types.  For each type, if the up reference is contained in
1063 /// the newly completed type, we decrement the level count.  When the level
1064 /// count reaches zero, the upreferenced type is the type that is passed in:
1065 /// thus we can complete the cycle.
1066 ///
1067 static PATypeHolder HandleUpRefs(const Type *ty, const Signedness& Sign) {
1068   // If Ty isn't abstract, or if there are no up-references in it, then there is
1069   // nothing to resolve here.
1070   if (!ty->isAbstract() || UpRefs.empty()) return ty;
1071   
1072   PATypeHolder Ty(ty);
1073   UR_OUT("Type '" << Ty->getDescription() <<
1074          "' newly formed.  Resolving upreferences.\n" <<
1075          UpRefs.size() << " upreferences active!\n");
1076
1077   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1078   // to zero), we resolve them all together before we resolve them to Ty.  At
1079   // the end of the loop, if there is anything to resolve to Ty, it will be in
1080   // this variable.
1081   OpaqueType *TypeToResolve = 0;
1082
1083   unsigned i = 0;
1084   for (; i != UpRefs.size(); ++i) {
1085     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1086            << UpRefs[i].UpRefTy->getDescription() << ") = "
1087            << (TypeContains(Ty, UpRefs[i].UpRefTy) ? "true" : "false") << "\n");
1088     if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
1089       // Decrement level of upreference
1090       unsigned Level = --UpRefs[i].NestingLevel;
1091       UpRefs[i].LastContainedTy = Ty;
1092       UR_OUT("  Uplevel Ref Level = " << Level << "\n");
1093       if (Level == 0) {                     // Upreference should be resolved!
1094         if (!TypeToResolve) {
1095           TypeToResolve = UpRefs[i].UpRefTy;
1096         } else {
1097           UR_OUT("  * Resolving upreference for "
1098                  << UpRefs[i].UpRefTy->getDescription() << "\n";
1099           std::string OldName = UpRefs[i].UpRefTy->getDescription());
1100           ResolveTypeSign(UpRefs[i].UpRefTy, Sign);
1101           UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1102           UR_OUT("  * Type '" << OldName << "' refined upreference to: "
1103                  << (const void*)Ty << ", " << Ty->getDescription() << "\n");
1104         }
1105         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
1106         --i;                                // Do not skip the next element...
1107       }
1108     }
1109   }
1110
1111   if (TypeToResolve) {
1112     UR_OUT("  * Resolving upreference for "
1113            << UpRefs[i].UpRefTy->getDescription() << "\n";
1114            std::string OldName = TypeToResolve->getDescription());
1115     ResolveTypeSign(TypeToResolve, Sign);
1116     TypeToResolve->refineAbstractTypeTo(Ty);
1117   }
1118
1119   return Ty;
1120 }
1121
1122 bool Signedness::operator<(const Signedness &that) const {
1123   if (isNamed()) {
1124     if (that.isNamed()) 
1125       return *(this->name) < *(that.name);
1126     else
1127       return CurModule.NamedTypeSigns[*name] < that;
1128   } else if (that.isNamed()) {
1129     return *this < CurModule.NamedTypeSigns[*that.name];
1130   }
1131
1132   if (isComposite() && that.isComposite()) {
1133     if (sv->size() == that.sv->size()) {
1134       SignVector::const_iterator thisI = sv->begin(), thisE = sv->end();
1135       SignVector::const_iterator thatI = that.sv->begin(), 
1136                                  thatE = that.sv->end();
1137       for (; thisI != thisE; ++thisI, ++thatI) {
1138         if (*thisI < *thatI)
1139           return true;
1140         else if (!(*thisI == *thatI))
1141           return false;
1142       }
1143       return false;
1144     }
1145     return sv->size() < that.sv->size();
1146   }  
1147   return kind < that.kind;
1148 }
1149
1150 bool Signedness::operator==(const Signedness &that) const {
1151   if (isNamed())
1152     if (that.isNamed())
1153       return *(this->name) == *(that.name);
1154     else 
1155       return CurModule.NamedTypeSigns[*(this->name)] == that;
1156   else if (that.isNamed())
1157     return *this == CurModule.NamedTypeSigns[*(that.name)];
1158   if (isComposite() && that.isComposite()) {
1159     if (sv->size() == that.sv->size()) {
1160       SignVector::const_iterator thisI = sv->begin(), thisE = sv->end();
1161       SignVector::const_iterator thatI = that.sv->begin(), 
1162                                  thatE = that.sv->end();
1163       for (; thisI != thisE; ++thisI, ++thatI) {
1164         if (!(*thisI == *thatI))
1165           return false;
1166       }
1167       return true;
1168     }
1169     return false;
1170   }
1171   return kind == that.kind;
1172 }
1173
1174 void Signedness::copy(const Signedness &that) {
1175   if (that.isNamed()) {
1176     kind = Named;
1177     name = new std::string(*that.name);
1178   } else if (that.isComposite()) {
1179     kind = Composite;
1180     sv = new SignVector();
1181     *sv = *that.sv;
1182   } else {
1183     kind = that.kind;
1184     sv = 0;
1185   }
1186 }
1187
1188 void Signedness::destroy() {
1189   if (isNamed()) {
1190     delete name;
1191   } else if (isComposite()) {
1192     delete sv;
1193   } 
1194 }
1195
1196 #ifndef NDEBUG
1197 void Signedness::dump() const {
1198   if (isComposite()) {
1199     if (sv->size() == 1) {
1200       (*sv)[0].dump();
1201       std::cerr << "*";
1202     } else {
1203       std::cerr << "{ " ;
1204       for (unsigned i = 0; i < sv->size(); ++i) {
1205         if (i != 0)
1206           std::cerr << ", ";
1207         (*sv)[i].dump();
1208       }
1209       std::cerr << "} " ;
1210     }
1211   } else if (isNamed()) {
1212     std::cerr << *name;
1213   } else if (isSigned()) {
1214     std::cerr << "S";
1215   } else if (isUnsigned()) {
1216     std::cerr << "U";
1217   } else
1218     std::cerr << ".";
1219 }
1220 #endif
1221
1222 static inline Instruction::TermOps 
1223 getTermOp(TermOps op) {
1224   switch (op) {
1225     default           : assert(0 && "Invalid OldTermOp");
1226     case RetOp        : return Instruction::Ret;
1227     case BrOp         : return Instruction::Br;
1228     case SwitchOp     : return Instruction::Switch;
1229     case InvokeOp     : return Instruction::Invoke;
1230     case UnwindOp     : return Instruction::Unwind;
1231     case UnreachableOp: return Instruction::Unreachable;
1232   }
1233 }
1234
1235 static inline Instruction::BinaryOps 
1236 getBinaryOp(BinaryOps op, const Type *Ty, const Signedness& Sign) {
1237   switch (op) {
1238     default     : assert(0 && "Invalid OldBinaryOps");
1239     case SetEQ  : 
1240     case SetNE  : 
1241     case SetLE  :
1242     case SetGE  :
1243     case SetLT  :
1244     case SetGT  : assert(0 && "Should use getCompareOp");
1245     case AddOp  : return Instruction::Add;
1246     case SubOp  : return Instruction::Sub;
1247     case MulOp  : return Instruction::Mul;
1248     case DivOp  : {
1249       // This is an obsolete instruction so we must upgrade it based on the
1250       // types of its operands.
1251       bool isFP = Ty->isFloatingPoint();
1252       if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1253         // If its a vector type we want to use the element type
1254         isFP = PTy->getElementType()->isFloatingPoint();
1255       if (isFP)
1256         return Instruction::FDiv;
1257       else if (Sign.isSigned())
1258         return Instruction::SDiv;
1259       return Instruction::UDiv;
1260     }
1261     case UDivOp : return Instruction::UDiv;
1262     case SDivOp : return Instruction::SDiv;
1263     case FDivOp : return Instruction::FDiv;
1264     case RemOp  : {
1265       // This is an obsolete instruction so we must upgrade it based on the
1266       // types of its operands.
1267       bool isFP = Ty->isFloatingPoint();
1268       if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1269         // If its a vector type we want to use the element type
1270         isFP = PTy->getElementType()->isFloatingPoint();
1271       // Select correct opcode
1272       if (isFP)
1273         return Instruction::FRem;
1274       else if (Sign.isSigned())
1275         return Instruction::SRem;
1276       return Instruction::URem;
1277     }
1278     case URemOp : return Instruction::URem;
1279     case SRemOp : return Instruction::SRem;
1280     case FRemOp : return Instruction::FRem;
1281     case LShrOp : return Instruction::LShr;
1282     case AShrOp : return Instruction::AShr;
1283     case ShlOp  : return Instruction::Shl;
1284     case ShrOp  : 
1285       if (Sign.isSigned())
1286         return Instruction::AShr;
1287       return Instruction::LShr;
1288     case AndOp  : return Instruction::And;
1289     case OrOp   : return Instruction::Or;
1290     case XorOp  : return Instruction::Xor;
1291   }
1292 }
1293
1294 static inline Instruction::OtherOps 
1295 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1296              const Signedness &Sign) {
1297   bool isSigned = Sign.isSigned();
1298   bool isFP = Ty->isFloatingPoint();
1299   switch (op) {
1300     default     : assert(0 && "Invalid OldSetCC");
1301     case SetEQ  : 
1302       if (isFP) {
1303         predicate = FCmpInst::FCMP_OEQ;
1304         return Instruction::FCmp;
1305       } else {
1306         predicate = ICmpInst::ICMP_EQ;
1307         return Instruction::ICmp;
1308       }
1309     case SetNE  : 
1310       if (isFP) {
1311         predicate = FCmpInst::FCMP_UNE;
1312         return Instruction::FCmp;
1313       } else {
1314         predicate = ICmpInst::ICMP_NE;
1315         return Instruction::ICmp;
1316       }
1317     case SetLE  : 
1318       if (isFP) {
1319         predicate = FCmpInst::FCMP_OLE;
1320         return Instruction::FCmp;
1321       } else {
1322         if (isSigned)
1323           predicate = ICmpInst::ICMP_SLE;
1324         else
1325           predicate = ICmpInst::ICMP_ULE;
1326         return Instruction::ICmp;
1327       }
1328     case SetGE  : 
1329       if (isFP) {
1330         predicate = FCmpInst::FCMP_OGE;
1331         return Instruction::FCmp;
1332       } else {
1333         if (isSigned)
1334           predicate = ICmpInst::ICMP_SGE;
1335         else
1336           predicate = ICmpInst::ICMP_UGE;
1337         return Instruction::ICmp;
1338       }
1339     case SetLT  : 
1340       if (isFP) {
1341         predicate = FCmpInst::FCMP_OLT;
1342         return Instruction::FCmp;
1343       } else {
1344         if (isSigned)
1345           predicate = ICmpInst::ICMP_SLT;
1346         else
1347           predicate = ICmpInst::ICMP_ULT;
1348         return Instruction::ICmp;
1349       }
1350     case SetGT  : 
1351       if (isFP) {
1352         predicate = FCmpInst::FCMP_OGT;
1353         return Instruction::FCmp;
1354       } else {
1355         if (isSigned)
1356           predicate = ICmpInst::ICMP_SGT;
1357         else
1358           predicate = ICmpInst::ICMP_UGT;
1359         return Instruction::ICmp;
1360       }
1361   }
1362 }
1363
1364 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1365   switch (op) {
1366     default              : assert(0 && "Invalid OldMemoryOps");
1367     case MallocOp        : return Instruction::Malloc;
1368     case FreeOp          : return Instruction::Free;
1369     case AllocaOp        : return Instruction::Alloca;
1370     case LoadOp          : return Instruction::Load;
1371     case StoreOp         : return Instruction::Store;
1372     case GetElementPtrOp : return Instruction::GetElementPtr;
1373   }
1374 }
1375
1376 static inline Instruction::OtherOps 
1377 getOtherOp(OtherOps op, const Signedness &Sign) {
1378   switch (op) {
1379     default               : assert(0 && "Invalid OldOtherOps");
1380     case PHIOp            : return Instruction::PHI;
1381     case CallOp           : return Instruction::Call;
1382     case SelectOp         : return Instruction::Select;
1383     case UserOp1          : return Instruction::UserOp1;
1384     case UserOp2          : return Instruction::UserOp2;
1385     case VAArg            : return Instruction::VAArg;
1386     case ExtractElementOp : return Instruction::ExtractElement;
1387     case InsertElementOp  : return Instruction::InsertElement;
1388     case ShuffleVectorOp  : return Instruction::ShuffleVector;
1389     case ICmpOp           : return Instruction::ICmp;
1390     case FCmpOp           : return Instruction::FCmp;
1391   };
1392 }
1393
1394 static inline Value*
1395 getCast(CastOps op, Value *Src, const Signedness &SrcSign, const Type *DstTy, 
1396         const Signedness &DstSign, bool ForceInstruction = false) {
1397   Instruction::CastOps Opcode;
1398   const Type* SrcTy = Src->getType();
1399   if (op == CastOp) {
1400     if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1401       // fp -> ptr cast is no longer supported but we must upgrade this
1402       // by doing a double cast: fp -> int -> ptr
1403       SrcTy = Type::Int64Ty;
1404       Opcode = Instruction::IntToPtr;
1405       if (isa<Constant>(Src)) {
1406         Src = ConstantExpr::getCast(Instruction::FPToUI, 
1407                                      cast<Constant>(Src), SrcTy);
1408       } else {
1409         std::string NewName(makeNameUnique(Src->getName()));
1410         Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1411       }
1412     } else if (isa<IntegerType>(DstTy) &&
1413                cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1414       // cast type %x to bool was previously defined as setne type %x, null
1415       // The cast semantic is now to truncate, not compare so we must retain
1416       // the original intent by replacing the cast with a setne
1417       Constant* Null = Constant::getNullValue(SrcTy);
1418       Instruction::OtherOps Opcode = Instruction::ICmp;
1419       unsigned short predicate = ICmpInst::ICMP_NE;
1420       if (SrcTy->isFloatingPoint()) {
1421         Opcode = Instruction::FCmp;
1422         predicate = FCmpInst::FCMP_ONE;
1423       } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1424         error("Invalid cast to bool");
1425       }
1426       if (isa<Constant>(Src) && !ForceInstruction)
1427         return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1428       else
1429         return CmpInst::create(Opcode, predicate, Src, Null);
1430     }
1431     // Determine the opcode to use by calling CastInst::getCastOpcode
1432     Opcode = 
1433       CastInst::getCastOpcode(Src, SrcSign.isSigned(), DstTy, 
1434                               DstSign.isSigned());
1435
1436   } else switch (op) {
1437     default: assert(0 && "Invalid cast token");
1438     case TruncOp:    Opcode = Instruction::Trunc; break;
1439     case ZExtOp:     Opcode = Instruction::ZExt; break;
1440     case SExtOp:     Opcode = Instruction::SExt; break;
1441     case FPTruncOp:  Opcode = Instruction::FPTrunc; break;
1442     case FPExtOp:    Opcode = Instruction::FPExt; break;
1443     case FPToUIOp:   Opcode = Instruction::FPToUI; break;
1444     case FPToSIOp:   Opcode = Instruction::FPToSI; break;
1445     case UIToFPOp:   Opcode = Instruction::UIToFP; break;
1446     case SIToFPOp:   Opcode = Instruction::SIToFP; break;
1447     case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1448     case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1449     case BitCastOp:  Opcode = Instruction::BitCast; break;
1450   }
1451
1452   if (isa<Constant>(Src) && !ForceInstruction)
1453     return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1454   return CastInst::create(Opcode, Src, DstTy);
1455 }
1456
1457 static Instruction *
1458 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID, 
1459                      std::vector<Value*>& Args) {
1460
1461   std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1462   switch (Name[5]) {
1463     case 'i':
1464       if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1465         if (Args.size() != 2)
1466           error("Invalid prototype for " + Name);
1467         return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1468       }
1469       break;
1470     case 'b':
1471       if (Name.length() == 14 && !memcmp(&Name[5], "bswap.i", 7)) {
1472         const Type* ArgTy = Args[0]->getType();
1473         Name += ".i" + utostr(cast<IntegerType>(ArgTy)->getBitWidth());
1474         Function *F = cast<Function>(
1475           CurModule.CurrentModule->getOrInsertFunction(Name, RetTy, ArgTy, 
1476                                                        (void*)0));
1477         return new CallInst(F, Args[0]);
1478       }
1479       break;
1480     case 'c':
1481       if ((Name.length() <= 14 && !memcmp(&Name[5], "ctpop.i", 7)) ||
1482           (Name.length() <= 13 && !memcmp(&Name[5], "ctlz.i", 6)) ||
1483           (Name.length() <= 13 && !memcmp(&Name[5], "cttz.i", 6))) {
1484         // These intrinsics changed their result type.
1485         const Type* ArgTy = Args[0]->getType();
1486         Function *OldF = CurModule.CurrentModule->getFunction(Name);
1487         if (OldF)
1488           OldF->setName("upgrd.rm." + Name);
1489
1490         Function *NewF = cast<Function>(
1491           CurModule.CurrentModule->getOrInsertFunction(Name, Type::Int32Ty, 
1492                                                        ArgTy, (void*)0));
1493
1494         Instruction *Call = new CallInst(NewF, Args[0], "", CurBB);
1495         return CastInst::createIntegerCast(Call, RetTy, false);
1496       }
1497       break;
1498
1499     case 'v' : {
1500       const Type* PtrTy = PointerType::get(Type::Int8Ty);
1501       std::vector<const Type*> Params;
1502       if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1503         if (Args.size() != 1)
1504           error("Invalid prototype for " + Name + " prototype");
1505         Params.push_back(PtrTy);
1506         const FunctionType *FTy = 
1507           FunctionType::get(Type::VoidTy, Params, false);
1508         const PointerType *PFTy = PointerType::get(FTy);
1509         Value* Func = getVal(PFTy, ID);
1510         Args[0] = new BitCastInst(Args[0], PtrTy, makeNameUnique("va"), CurBB);
1511         return new CallInst(Func, &Args[0], Args.size());
1512       } else if (Name == "llvm.va_copy") {
1513         if (Args.size() != 2)
1514           error("Invalid prototype for " + Name + " prototype");
1515         Params.push_back(PtrTy);
1516         Params.push_back(PtrTy);
1517         const FunctionType *FTy = 
1518           FunctionType::get(Type::VoidTy, Params, false);
1519         const PointerType *PFTy = PointerType::get(FTy);
1520         Value* Func = getVal(PFTy, ID);
1521         std::string InstName0(makeNameUnique("va0"));
1522         std::string InstName1(makeNameUnique("va1"));
1523         Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1524         Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1525         return new CallInst(Func, &Args[0], Args.size());
1526       }
1527     }
1528   }
1529   return 0;
1530 }
1531
1532 const Type* upgradeGEPIndices(const Type* PTy, 
1533                        std::vector<ValueInfo> *Indices, 
1534                        std::vector<Value*>    &VIndices, 
1535                        std::vector<Constant*> *CIndices = 0) {
1536   // Traverse the indices with a gep_type_iterator so we can build the list
1537   // of constant and value indices for use later. Also perform upgrades
1538   VIndices.clear();
1539   if (CIndices) CIndices->clear();
1540   for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1541     VIndices.push_back((*Indices)[i].V);
1542   generic_gep_type_iterator<std::vector<Value*>::iterator>
1543     GTI = gep_type_begin(PTy, VIndices.begin(),  VIndices.end()),
1544     GTE = gep_type_end(PTy,  VIndices.begin(),  VIndices.end());
1545   for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1546     Value *Index = VIndices[i];
1547     if (CIndices && !isa<Constant>(Index))
1548       error("Indices to constant getelementptr must be constants");
1549     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte 
1550     // struct indices to i32 struct indices with ZExt for compatibility.
1551     else if (isa<StructType>(*GTI)) {        // Only change struct indices
1552       if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1553         if (CUI->getType()->getBitWidth() == 8)
1554           Index = 
1555             ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1556     } else {
1557       // Make sure that unsigned SequentialType indices are zext'd to 
1558       // 64-bits if they were smaller than that because LLVM 2.0 will sext 
1559       // all indices for SequentialType elements. We must retain the same 
1560       // semantic (zext) for unsigned types.
1561       if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
1562         if (Ity->getBitWidth() < 64 && (*Indices)[i].S.isUnsigned()) {
1563           if (CIndices)
1564             Index = ConstantExpr::getCast(Instruction::ZExt, 
1565               cast<Constant>(Index), Type::Int64Ty);
1566           else
1567             Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1568               makeNameUnique("gep"), CurBB);
1569           VIndices[i] = Index;
1570         }
1571     }
1572     // Add to the CIndices list, if requested.
1573     if (CIndices)
1574       CIndices->push_back(cast<Constant>(Index));
1575   }
1576
1577   const Type *IdxTy =
1578     GetElementPtrInst::getIndexedType(PTy, &VIndices[0], VIndices.size(), true);
1579     if (!IdxTy)
1580       error("Index list invalid for constant getelementptr");
1581   return IdxTy;
1582 }
1583
1584 unsigned upgradeCallingConv(unsigned CC) {
1585   switch (CC) {
1586     case OldCallingConv::C           : return CallingConv::C;
1587     case OldCallingConv::CSRet       : return CallingConv::C;
1588     case OldCallingConv::Fast        : return CallingConv::Fast;
1589     case OldCallingConv::Cold        : return CallingConv::Cold;
1590     case OldCallingConv::X86_StdCall : return CallingConv::X86_StdCall;
1591     case OldCallingConv::X86_FastCall: return CallingConv::X86_FastCall;
1592     default:
1593       return CC;
1594   }
1595 }
1596
1597 Module* UpgradeAssembly(const std::string &infile, std::istream& in, 
1598                               bool debug, bool addAttrs)
1599 {
1600   Upgradelineno = 1; 
1601   CurFilename = infile;
1602   LexInput = &in;
1603   yydebug = debug;
1604   AddAttributes = addAttrs;
1605   ObsoleteVarArgs = false;
1606   NewVarArgs = false;
1607
1608   CurModule.CurrentModule = new Module(CurFilename);
1609
1610   // Check to make sure the parser succeeded
1611   if (yyparse()) {
1612     if (ParserResult)
1613       delete ParserResult;
1614     std::cerr << "llvm-upgrade: parse failed.\n";
1615     return 0;
1616   }
1617
1618   // Check to make sure that parsing produced a result
1619   if (!ParserResult) {
1620     std::cerr << "llvm-upgrade: no parse result.\n";
1621     return 0;
1622   }
1623
1624   // Reset ParserResult variable while saving its value for the result.
1625   Module *Result = ParserResult;
1626   ParserResult = 0;
1627
1628   //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1629   {
1630     Function* F;
1631     if ((F = Result->getFunction("llvm.va_start"))
1632         && F->getFunctionType()->getNumParams() == 0)
1633       ObsoleteVarArgs = true;
1634     if((F = Result->getFunction("llvm.va_copy"))
1635        && F->getFunctionType()->getNumParams() == 1)
1636       ObsoleteVarArgs = true;
1637   }
1638
1639   if (ObsoleteVarArgs && NewVarArgs) {
1640     error("This file is corrupt: it uses both new and old style varargs");
1641     return 0;
1642   }
1643
1644   if(ObsoleteVarArgs) {
1645     if(Function* F = Result->getFunction("llvm.va_start")) {
1646       if (F->arg_size() != 0) {
1647         error("Obsolete va_start takes 0 argument");
1648         return 0;
1649       }
1650       
1651       //foo = va_start()
1652       // ->
1653       //bar = alloca typeof(foo)
1654       //va_start(bar)
1655       //foo = load bar
1656
1657       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1658       const Type* ArgTy = F->getFunctionType()->getReturnType();
1659       const Type* ArgTyPtr = PointerType::get(ArgTy);
1660       Function* NF = cast<Function>(Result->getOrInsertFunction(
1661         "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1662
1663       while (!F->use_empty()) {
1664         CallInst* CI = cast<CallInst>(F->use_back());
1665         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1666         new CallInst(NF, bar, "", CI);
1667         Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1668         CI->replaceAllUsesWith(foo);
1669         CI->getParent()->getInstList().erase(CI);
1670       }
1671       Result->getFunctionList().erase(F);
1672     }
1673     
1674     if(Function* F = Result->getFunction("llvm.va_end")) {
1675       if(F->arg_size() != 1) {
1676         error("Obsolete va_end takes 1 argument");
1677         return 0;
1678       }
1679
1680       //vaend foo
1681       // ->
1682       //bar = alloca 1 of typeof(foo)
1683       //vaend bar
1684       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1685       const Type* ArgTy = F->getFunctionType()->getParamType(0);
1686       const Type* ArgTyPtr = PointerType::get(ArgTy);
1687       Function* NF = cast<Function>(Result->getOrInsertFunction(
1688         "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1689
1690       while (!F->use_empty()) {
1691         CallInst* CI = cast<CallInst>(F->use_back());
1692         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1693         new StoreInst(CI->getOperand(1), bar, CI);
1694         new CallInst(NF, bar, "", CI);
1695         CI->getParent()->getInstList().erase(CI);
1696       }
1697       Result->getFunctionList().erase(F);
1698     }
1699
1700     if(Function* F = Result->getFunction("llvm.va_copy")) {
1701       if(F->arg_size() != 1) {
1702         error("Obsolete va_copy takes 1 argument");
1703         return 0;
1704       }
1705       //foo = vacopy(bar)
1706       // ->
1707       //a = alloca 1 of typeof(foo)
1708       //b = alloca 1 of typeof(foo)
1709       //store bar -> b
1710       //vacopy(a, b)
1711       //foo = load a
1712       
1713       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1714       const Type* ArgTy = F->getFunctionType()->getReturnType();
1715       const Type* ArgTyPtr = PointerType::get(ArgTy);
1716       Function* NF = cast<Function>(Result->getOrInsertFunction(
1717         "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1718
1719       while (!F->use_empty()) {
1720         CallInst* CI = cast<CallInst>(F->use_back());
1721         AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1722         AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1723         new StoreInst(CI->getOperand(1), b, CI);
1724         new CallInst(NF, a, b, "", CI);
1725         Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1726         CI->replaceAllUsesWith(foo);
1727         CI->getParent()->getInstList().erase(CI);
1728       }
1729       Result->getFunctionList().erase(F);
1730     }
1731   }
1732
1733   return Result;
1734 }
1735
1736 } // end llvm namespace
1737
1738 using namespace llvm;
1739
1740 %}
1741
1742 %union {
1743   llvm::Module                           *ModuleVal;
1744   llvm::Function                         *FunctionVal;
1745   std::pair<llvm::PATypeInfo, char*>     *ArgVal;
1746   llvm::BasicBlock                       *BasicBlockVal;
1747   llvm::TermInstInfo                     TermInstVal;
1748   llvm::InstrInfo                        InstVal;
1749   llvm::ConstInfo                        ConstVal;
1750   llvm::ValueInfo                        ValueVal;
1751   llvm::PATypeInfo                       TypeVal;
1752   llvm::TypeInfo                         PrimType;
1753   llvm::PHIListInfo                      PHIList;
1754   std::list<llvm::PATypeInfo>            *TypeList;
1755   std::vector<llvm::ValueInfo>           *ValueList;
1756   std::vector<llvm::ConstInfo>           *ConstVector;
1757
1758
1759   std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1760   // Represent the RHS of PHI node
1761   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1762
1763   llvm::GlobalValue::LinkageTypes         Linkage;
1764   int64_t                           SInt64Val;
1765   uint64_t                          UInt64Val;
1766   int                               SIntVal;
1767   unsigned                          UIntVal;
1768   double                            FPVal;
1769   bool                              BoolVal;
1770
1771   char                             *StrVal;   // This memory is strdup'd!
1772   llvm::ValID                       ValIDVal; // strdup'd memory maybe!
1773
1774   llvm::BinaryOps                   BinaryOpVal;
1775   llvm::TermOps                     TermOpVal;
1776   llvm::MemoryOps                   MemOpVal;
1777   llvm::OtherOps                    OtherOpVal;
1778   llvm::CastOps                     CastOpVal;
1779   llvm::ICmpInst::Predicate         IPred;
1780   llvm::FCmpInst::Predicate         FPred;
1781   llvm::Module::Endianness          Endianness;
1782 }
1783
1784 %type <ModuleVal>     Module FunctionList
1785 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
1786 %type <BasicBlockVal> BasicBlock InstructionList
1787 %type <TermInstVal>   BBTerminatorInst
1788 %type <InstVal>       Inst InstVal MemoryInst
1789 %type <ConstVal>      ConstVal ConstExpr
1790 %type <ConstVector>   ConstVector
1791 %type <ArgList>       ArgList ArgListH
1792 %type <ArgVal>        ArgVal
1793 %type <PHIList>       PHIList
1794 %type <ValueList>     ValueRefList ValueRefListE  // For call param lists
1795 %type <ValueList>     IndexList                   // For GEP derived indices
1796 %type <TypeList>      TypeListI ArgTypeListI
1797 %type <JumpTable>     JumpTable
1798 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
1799 %type <BoolVal>       OptVolatile                 // 'volatile' or not
1800 %type <BoolVal>       OptTailCall                 // TAIL CALL or plain CALL.
1801 %type <BoolVal>       OptSideEffect               // 'sideeffect' or not.
1802 %type <Linkage>       OptLinkage FnDeclareLinkage
1803 %type <Endianness>    BigOrLittle
1804
1805 // ValueRef - Unresolved reference to a definition or BB
1806 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
1807 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
1808
1809 // Tokens and types for handling constant integer values
1810 //
1811 // ESINT64VAL - A negative number within long long range
1812 %token <SInt64Val> ESINT64VAL
1813
1814 // EUINT64VAL - A positive number within uns. long long range
1815 %token <UInt64Val> EUINT64VAL
1816 %type  <SInt64Val> EINT64VAL
1817
1818 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
1819 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
1820 %type   <SIntVal>   INTVAL
1821 %token  <FPVal>     FPVAL     // Float or Double constant
1822
1823 // Built in types...
1824 %type  <TypeVal> Types TypesV UpRTypes UpRTypesV
1825 %type  <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1826 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1827 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1828
1829 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1830 %type  <StrVal> Name OptName OptAssign
1831 %type  <UIntVal> OptAlign OptCAlign
1832 %type <StrVal> OptSection SectionString
1833
1834 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1835 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1836 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1837 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1838 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1839 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1840 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1841 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1842 %token DATALAYOUT
1843 %type <UIntVal> OptCallingConv
1844
1845 // Basic Block Terminating Operators
1846 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1847 %token UNWIND EXCEPT
1848
1849 // Binary Operators
1850 %type  <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1851 %type  <BinaryOpVal> ShiftOps
1852 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM 
1853 %token <BinaryOpVal> AND OR XOR SHL SHR ASHR LSHR 
1854 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comparators
1855 %token <OtherOpVal> ICMP FCMP
1856
1857 // Memory Instructions
1858 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1859
1860 // Other Operators
1861 %token <OtherOpVal> PHI_TOK SELECT VAARG
1862 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1863 %token VAARG_old VANEXT_old //OBSOLETE
1864
1865 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1866 %type  <IPred> IPredicates
1867 %type  <FPred> FPredicates
1868 %token  EQ NE SLT SGT SLE SGE ULT UGT ULE UGE 
1869 %token  OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1870
1871 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI 
1872 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST 
1873 %type  <CastOpVal> CastOps
1874
1875 %start Module
1876
1877 %%
1878
1879 // Handle constant integer size restriction and conversion...
1880 //
1881 INTVAL 
1882   : SINTVAL
1883   | UINTVAL {
1884     if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
1885       error("Value too large for type");
1886     $$ = (int32_t)$1;
1887   }
1888   ;
1889
1890 EINT64VAL 
1891   : ESINT64VAL       // These have same type and can't cause problems...
1892   | EUINT64VAL {
1893     if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
1894       error("Value too large for type");
1895     $$ = (int64_t)$1;
1896   };
1897
1898 // Operations that are notably excluded from this list include:
1899 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1900 //
1901 ArithmeticOps
1902   : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1903   ;
1904
1905 LogicalOps   
1906   : AND | OR | XOR
1907   ;
1908
1909 SetCondOps   
1910   : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1911   ;
1912
1913 IPredicates  
1914   : EQ   { $$ = ICmpInst::ICMP_EQ; }  | NE   { $$ = ICmpInst::ICMP_NE; }
1915   | SLT  { $$ = ICmpInst::ICMP_SLT; } | SGT  { $$ = ICmpInst::ICMP_SGT; }
1916   | SLE  { $$ = ICmpInst::ICMP_SLE; } | SGE  { $$ = ICmpInst::ICMP_SGE; }
1917   | ULT  { $$ = ICmpInst::ICMP_ULT; } | UGT  { $$ = ICmpInst::ICMP_UGT; }
1918   | ULE  { $$ = ICmpInst::ICMP_ULE; } | UGE  { $$ = ICmpInst::ICMP_UGE; } 
1919   ;
1920
1921 FPredicates  
1922   : OEQ  { $$ = FCmpInst::FCMP_OEQ; } | ONE  { $$ = FCmpInst::FCMP_ONE; }
1923   | OLT  { $$ = FCmpInst::FCMP_OLT; } | OGT  { $$ = FCmpInst::FCMP_OGT; }
1924   | OLE  { $$ = FCmpInst::FCMP_OLE; } | OGE  { $$ = FCmpInst::FCMP_OGE; }
1925   | ORD  { $$ = FCmpInst::FCMP_ORD; } | UNO  { $$ = FCmpInst::FCMP_UNO; }
1926   | UEQ  { $$ = FCmpInst::FCMP_UEQ; } | UNE  { $$ = FCmpInst::FCMP_UNE; }
1927   | ULT  { $$ = FCmpInst::FCMP_ULT; } | UGT  { $$ = FCmpInst::FCMP_UGT; }
1928   | ULE  { $$ = FCmpInst::FCMP_ULE; } | UGE  { $$ = FCmpInst::FCMP_UGE; }
1929   | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1930   | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1931   ;
1932 ShiftOps  
1933   : SHL | SHR | ASHR | LSHR
1934   ;
1935
1936 CastOps      
1937   : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI 
1938   | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1939   ;
1940
1941 // These are some types that allow classification if we only want a particular 
1942 // thing... for example, only a signed, unsigned, or integral type.
1943 SIntType 
1944   :  LONG |  INT |  SHORT | SBYTE
1945   ;
1946
1947 UIntType 
1948   : ULONG | UINT | USHORT | UBYTE
1949   ;
1950
1951 IntType  
1952   : SIntType | UIntType
1953   ;
1954
1955 FPType   
1956   : FLOAT | DOUBLE
1957   ;
1958
1959 // OptAssign - Value producing statements have an optional assignment component
1960 OptAssign 
1961   : Name '=' {
1962     $$ = $1;
1963   }
1964   | /*empty*/ {
1965     $$ = 0;
1966   };
1967
1968 OptLinkage 
1969   : INTERNAL    { $$ = GlobalValue::InternalLinkage; }
1970   | LINKONCE    { $$ = GlobalValue::LinkOnceLinkage; } 
1971   | WEAK        { $$ = GlobalValue::WeakLinkage; } 
1972   | APPENDING   { $$ = GlobalValue::AppendingLinkage; } 
1973   | DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; } 
1974   | DLLEXPORT   { $$ = GlobalValue::DLLExportLinkage; } 
1975   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1976   | /*empty*/   { $$ = GlobalValue::ExternalLinkage; }
1977   ;
1978
1979 OptCallingConv 
1980   : /*empty*/          { $$ = OldCallingConv::C; } 
1981   | CCC_TOK            { $$ = OldCallingConv::C; } 
1982   | CSRETCC_TOK        { $$ = OldCallingConv::CSRet; } 
1983   | FASTCC_TOK         { $$ = OldCallingConv::Fast; } 
1984   | COLDCC_TOK         { $$ = OldCallingConv::Cold; } 
1985   | X86_STDCALLCC_TOK  { $$ = OldCallingConv::X86_StdCall; } 
1986   | X86_FASTCALLCC_TOK { $$ = OldCallingConv::X86_FastCall; } 
1987   | CC_TOK EUINT64VAL  {
1988     if ((unsigned)$2 != $2)
1989       error("Calling conv too large");
1990     $$ = $2;
1991   }
1992   ;
1993
1994 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1995 // a comma before it.
1996 OptAlign 
1997   : /*empty*/        { $$ = 0; } 
1998   | ALIGN EUINT64VAL {
1999     $$ = $2;
2000     if ($$ != 0 && !isPowerOf2_32($$))
2001       error("Alignment must be a power of two");
2002   }
2003   ;
2004
2005 OptCAlign 
2006   : /*empty*/ { $$ = 0; } 
2007   | ',' ALIGN EUINT64VAL {
2008     $$ = $3;
2009     if ($$ != 0 && !isPowerOf2_32($$))
2010       error("Alignment must be a power of two");
2011   }
2012   ;
2013
2014 SectionString 
2015   : SECTION STRINGCONSTANT {
2016     for (unsigned i = 0, e = strlen($2); i != e; ++i)
2017       if ($2[i] == '"' || $2[i] == '\\')
2018         error("Invalid character in section name");
2019     $$ = $2;
2020   }
2021   ;
2022
2023 OptSection 
2024   : /*empty*/ { $$ = 0; } 
2025   | SectionString { $$ = $1; }
2026   ;
2027
2028 // GlobalVarAttributes - Used to pass the attributes string on a global.  CurGV
2029 // is set to be the global we are processing.
2030 //
2031 GlobalVarAttributes 
2032   : /* empty */ {} 
2033   | ',' GlobalVarAttribute GlobalVarAttributes {}
2034   ;
2035
2036 GlobalVarAttribute
2037   : SectionString {
2038     CurGV->setSection($1);
2039     free($1);
2040   } 
2041   | ALIGN EUINT64VAL {
2042     if ($2 != 0 && !isPowerOf2_32($2))
2043       error("Alignment must be a power of two");
2044     CurGV->setAlignment($2);
2045     
2046   }
2047   ;
2048
2049 //===----------------------------------------------------------------------===//
2050 // Types includes all predefined types... except void, because it can only be
2051 // used in specific contexts (function returning void for example).  To have
2052 // access to it, a user must explicitly use TypesV.
2053 //
2054
2055 // TypesV includes all of 'Types', but it also includes the void type.
2056 TypesV    
2057   : Types
2058   | VOID { 
2059     $$.PAT = new PATypeHolder($1.T); 
2060     $$.S.makeSignless();
2061   }
2062   ;
2063
2064 UpRTypesV 
2065   : UpRTypes 
2066   | VOID { 
2067     $$.PAT = new PATypeHolder($1.T); 
2068     $$.S.makeSignless();
2069   }
2070   ;
2071
2072 Types
2073   : UpRTypes {
2074     if (!UpRefs.empty())
2075       error("Invalid upreference in type: " + (*$1.PAT)->getDescription());
2076     $$ = $1;
2077   }
2078   ;
2079
2080 PrimType
2081   : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT 
2082   | LONG | ULONG | FLOAT | DOUBLE | LABEL
2083   ;
2084
2085 // Derived types are added later...
2086 UpRTypes 
2087   : PrimType { 
2088     $$.PAT = new PATypeHolder($1.T);
2089     $$.S.copy($1.S);
2090   }
2091   | OPAQUE {
2092     $$.PAT = new PATypeHolder(OpaqueType::get());
2093     $$.S.makeSignless();
2094   }
2095   | SymbolicValueRef {            // Named types are also simple types...
2096     $$.S.copy(getTypeSign($1));
2097     const Type* tmp = getType($1);
2098     $$.PAT = new PATypeHolder(tmp);
2099   }
2100   | '\\' EUINT64VAL {                   // Type UpReference
2101     if ($2 > (uint64_t)~0U) 
2102       error("Value out of range");
2103     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
2104     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
2105     $$.PAT = new PATypeHolder(OT);
2106     $$.S.makeSignless();
2107     UR_OUT("New Upreference!\n");
2108   }
2109   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
2110     $$.S.makeComposite($1.S);
2111     std::vector<const Type*> Params;
2112     for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
2113            E = $3->end(); I != E; ++I) {
2114       Params.push_back(I->PAT->get());
2115       $$.S.add(I->S);
2116     }
2117     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
2118     if (isVarArg) Params.pop_back();
2119
2120     const FunctionType *FTy =
2121       FunctionType::get($1.PAT->get(), Params, isVarArg, 0);
2122
2123     $$.PAT = new PATypeHolder( HandleUpRefs(FTy, $$.S) );
2124     delete $1.PAT;  // Delete the return type handle
2125     delete $3;      // Delete the argument list
2126   }
2127   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
2128     $$.S.makeComposite($4.S);
2129     $$.PAT = new PATypeHolder(HandleUpRefs(ArrayType::get($4.PAT->get(), 
2130                                            (unsigned)$2), $$.S));
2131     delete $4.PAT;
2132   }
2133   | '<' EUINT64VAL 'x' UpRTypes '>' {          // Vector type?
2134     const llvm::Type* ElemTy = $4.PAT->get();
2135     if ((unsigned)$2 != $2)
2136        error("Unsigned result not equal to signed result");
2137     if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
2138        error("Elements of a VectorType must be integer or floating point");
2139     if (!isPowerOf2_32($2))
2140       error("VectorType length should be a power of 2");
2141     $$.S.makeComposite($4.S);
2142     $$.PAT = new PATypeHolder(HandleUpRefs(VectorType::get(ElemTy, 
2143                                          (unsigned)$2), $$.S));
2144     delete $4.PAT;
2145   }
2146   | '{' TypeListI '}' {                        // Structure type?
2147     std::vector<const Type*> Elements;
2148     $$.S.makeComposite();
2149     for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
2150            E = $2->end(); I != E; ++I) {
2151       Elements.push_back(I->PAT->get());
2152       $$.S.add(I->S);
2153     }
2154     $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements), $$.S));
2155     delete $2;
2156   }
2157   | '{' '}' {                                  // Empty structure type?
2158     $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>()));
2159     $$.S.makeComposite();
2160   }
2161   | '<' '{' TypeListI '}' '>' {                // Packed Structure type?
2162     $$.S.makeComposite();
2163     std::vector<const Type*> Elements;
2164     for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
2165            E = $3->end(); I != E; ++I) {
2166       Elements.push_back(I->PAT->get());
2167       $$.S.add(I->S);
2168       delete I->PAT;
2169     }
2170     $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true), 
2171                                            $$.S));
2172     delete $3;
2173   }
2174   | '<' '{' '}' '>' {                          // Empty packed structure type?
2175     $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
2176     $$.S.makeComposite();
2177   }
2178   | UpRTypes '*' {                             // Pointer type?
2179     if ($1.PAT->get() == Type::LabelTy)
2180       error("Cannot form a pointer to a basic block");
2181     $$.S.makeComposite($1.S);
2182     $$.PAT = new PATypeHolder(HandleUpRefs(PointerType::get($1.PAT->get()),
2183                                            $$.S));
2184     delete $1.PAT;
2185   }
2186   ;
2187
2188 // TypeList - Used for struct declarations and as a basis for function type 
2189 // declaration type lists
2190 //
2191 TypeListI 
2192   : UpRTypes {
2193     $$ = new std::list<PATypeInfo>();
2194     $$->push_back($1); 
2195   }
2196   | TypeListI ',' UpRTypes {
2197     ($$=$1)->push_back($3);
2198   }
2199   ;
2200
2201 // ArgTypeList - List of types for a function type declaration...
2202 ArgTypeListI 
2203   : TypeListI
2204   | TypeListI ',' DOTDOTDOT {
2205     PATypeInfo VoidTI;
2206     VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2207     VoidTI.S.makeSignless();
2208     ($$=$1)->push_back(VoidTI);
2209   }
2210   | DOTDOTDOT {
2211     $$ = new std::list<PATypeInfo>();
2212     PATypeInfo VoidTI;
2213     VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2214     VoidTI.S.makeSignless();
2215     $$->push_back(VoidTI);
2216   }
2217   | /*empty*/ {
2218     $$ = new std::list<PATypeInfo>();
2219   }
2220   ;
2221
2222 // ConstVal - The various declarations that go into the constant pool.  This
2223 // production is used ONLY to represent constants that show up AFTER a 'const',
2224 // 'constant' or 'global' token at global scope.  Constants that can be inlined
2225 // into other expressions (such as integers and constexprs) are handled by the
2226 // ResolvedVal, ValueRef and ConstValueRef productions.
2227 //
2228 ConstVal
2229   : Types '[' ConstVector ']' { // Nonempty unsized arr
2230     const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2231     if (ATy == 0)
2232       error("Cannot make array constant with type: '" + 
2233             $1.PAT->get()->getDescription() + "'");
2234     const Type *ETy = ATy->getElementType();
2235     int NumElements = ATy->getNumElements();
2236
2237     // Verify that we have the correct size...
2238     if (NumElements != -1 && NumElements != (int)$3->size())
2239       error("Type mismatch: constant sized array initialized with " +
2240             utostr($3->size()) +  " arguments, but has size of " + 
2241             itostr(NumElements) + "");
2242
2243     // Verify all elements are correct type!
2244     std::vector<Constant*> Elems;
2245     for (unsigned i = 0; i < $3->size(); i++) {
2246       Constant *C = (*$3)[i].C;
2247       const Type* ValTy = C->getType();
2248       if (ETy != ValTy)
2249         error("Element #" + utostr(i) + " is not of type '" + 
2250               ETy->getDescription() +"' as required!\nIt is of type '"+
2251               ValTy->getDescription() + "'");
2252       Elems.push_back(C);
2253     }
2254     $$.C = ConstantArray::get(ATy, Elems);
2255     $$.S.copy($1.S);
2256     delete $1.PAT; 
2257     delete $3;
2258   }
2259   | Types '[' ']' {
2260     const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2261     if (ATy == 0)
2262       error("Cannot make array constant with type: '" + 
2263             $1.PAT->get()->getDescription() + "'");
2264     int NumElements = ATy->getNumElements();
2265     if (NumElements != -1 && NumElements != 0) 
2266       error("Type mismatch: constant sized array initialized with 0"
2267             " arguments, but has size of " + itostr(NumElements) +"");
2268     $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
2269     $$.S.copy($1.S);
2270     delete $1.PAT;
2271   }
2272   | Types 'c' STRINGCONSTANT {
2273     const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2274     if (ATy == 0)
2275       error("Cannot make array constant with type: '" + 
2276             $1.PAT->get()->getDescription() + "'");
2277     int NumElements = ATy->getNumElements();
2278     const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
2279     if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
2280       error("String arrays require type i8, not '" + ETy->getDescription() + 
2281             "'");
2282     char *EndStr = UnEscapeLexed($3, true);
2283     if (NumElements != -1 && NumElements != (EndStr-$3))
2284       error("Can't build string constant of size " + 
2285             itostr((int)(EndStr-$3)) + " when array has size " + 
2286             itostr(NumElements) + "");
2287     std::vector<Constant*> Vals;
2288     for (char *C = (char *)$3; C != (char *)EndStr; ++C)
2289       Vals.push_back(ConstantInt::get(ETy, *C));
2290     free($3);
2291     $$.C = ConstantArray::get(ATy, Vals);
2292     $$.S.copy($1.S);
2293     delete $1.PAT;
2294   }
2295   | Types '<' ConstVector '>' { // Nonempty unsized arr
2296     const VectorType *PTy = dyn_cast<VectorType>($1.PAT->get());
2297     if (PTy == 0)
2298       error("Cannot make packed constant with type: '" + 
2299             $1.PAT->get()->getDescription() + "'");
2300     const Type *ETy = PTy->getElementType();
2301     int NumElements = PTy->getNumElements();
2302     // Verify that we have the correct size...
2303     if (NumElements != -1 && NumElements != (int)$3->size())
2304       error("Type mismatch: constant sized packed initialized with " +
2305             utostr($3->size()) +  " arguments, but has size of " + 
2306             itostr(NumElements) + "");
2307     // Verify all elements are correct type!
2308     std::vector<Constant*> Elems;
2309     for (unsigned i = 0; i < $3->size(); i++) {
2310       Constant *C = (*$3)[i].C;
2311       const Type* ValTy = C->getType();
2312       if (ETy != ValTy)
2313         error("Element #" + utostr(i) + " is not of type '" + 
2314               ETy->getDescription() +"' as required!\nIt is of type '"+
2315               ValTy->getDescription() + "'");
2316       Elems.push_back(C);
2317     }
2318     $$.C = ConstantVector::get(PTy, Elems);
2319     $$.S.copy($1.S);
2320     delete $1.PAT;
2321     delete $3;
2322   }
2323   | Types '{' ConstVector '}' {
2324     const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2325     if (STy == 0)
2326       error("Cannot make struct constant with type: '" + 
2327             $1.PAT->get()->getDescription() + "'");
2328     if ($3->size() != STy->getNumContainedTypes())
2329       error("Illegal number of initializers for structure type");
2330
2331     // Check to ensure that constants are compatible with the type initializer!
2332     std::vector<Constant*> Fields;
2333     for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2334       Constant *C = (*$3)[i].C;
2335       if (C->getType() != STy->getElementType(i))
2336         error("Expected type '" + STy->getElementType(i)->getDescription() +
2337               "' for element #" + utostr(i) + " of structure initializer");
2338       Fields.push_back(C);
2339     }
2340     $$.C = ConstantStruct::get(STy, Fields);
2341     $$.S.copy($1.S);
2342     delete $1.PAT;
2343     delete $3;
2344   }
2345   | Types '{' '}' {
2346     const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2347     if (STy == 0)
2348       error("Cannot make struct constant with type: '" + 
2349               $1.PAT->get()->getDescription() + "'");
2350     if (STy->getNumContainedTypes() != 0)
2351       error("Illegal number of initializers for structure type");
2352     $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2353     $$.S.copy($1.S);
2354     delete $1.PAT;
2355   }
2356   | Types '<' '{' ConstVector '}' '>' {
2357     const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2358     if (STy == 0)
2359       error("Cannot make packed struct constant with type: '" + 
2360             $1.PAT->get()->getDescription() + "'");
2361     if ($4->size() != STy->getNumContainedTypes())
2362       error("Illegal number of initializers for packed structure type");
2363
2364     // Check to ensure that constants are compatible with the type initializer!
2365     std::vector<Constant*> Fields;
2366     for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2367       Constant *C = (*$4)[i].C;
2368       if (C->getType() != STy->getElementType(i))
2369         error("Expected type '" + STy->getElementType(i)->getDescription() +
2370               "' for element #" + utostr(i) + " of packed struct initializer");
2371       Fields.push_back(C);
2372     }
2373     $$.C = ConstantStruct::get(STy, Fields);
2374     $$.S.copy($1.S);
2375     delete $1.PAT; 
2376     delete $4;
2377   }
2378   | Types '<' '{' '}' '>' {
2379     const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2380     if (STy == 0)
2381       error("Cannot make packed struct constant with type: '" + 
2382               $1.PAT->get()->getDescription() + "'");
2383     if (STy->getNumContainedTypes() != 0)
2384       error("Illegal number of initializers for packed structure type");
2385     $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2386     $$.S.copy($1.S);
2387     delete $1.PAT;
2388   }
2389   | Types NULL_TOK {
2390     const PointerType *PTy = dyn_cast<PointerType>($1.PAT->get());
2391     if (PTy == 0)
2392       error("Cannot make null pointer constant with type: '" + 
2393             $1.PAT->get()->getDescription() + "'");
2394     $$.C = ConstantPointerNull::get(PTy);
2395     $$.S.copy($1.S);
2396     delete $1.PAT;
2397   }
2398   | Types UNDEF {
2399     $$.C = UndefValue::get($1.PAT->get());
2400     $$.S.copy($1.S);
2401     delete $1.PAT;
2402   }
2403   | Types SymbolicValueRef {
2404     const PointerType *Ty = dyn_cast<PointerType>($1.PAT->get());
2405     if (Ty == 0)
2406       error("Global const reference must be a pointer type, not" +
2407             $1.PAT->get()->getDescription());
2408
2409     // ConstExprs can exist in the body of a function, thus creating
2410     // GlobalValues whenever they refer to a variable.  Because we are in
2411     // the context of a function, getExistingValue will search the functions
2412     // symbol table instead of the module symbol table for the global symbol,
2413     // which throws things all off.  To get around this, we just tell
2414     // getExistingValue that we are at global scope here.
2415     //
2416     Function *SavedCurFn = CurFun.CurrentFunction;
2417     CurFun.CurrentFunction = 0;
2418     $2.S.copy($1.S);
2419     Value *V = getExistingValue(Ty, $2);
2420     CurFun.CurrentFunction = SavedCurFn;
2421
2422     // If this is an initializer for a constant pointer, which is referencing a
2423     // (currently) undefined variable, create a stub now that shall be replaced
2424     // in the future with the right type of variable.
2425     //
2426     if (V == 0) {
2427       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2428       const PointerType *PT = cast<PointerType>(Ty);
2429
2430       // First check to see if the forward references value is already created!
2431       PerModuleInfo::GlobalRefsType::iterator I =
2432         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2433     
2434       if (I != CurModule.GlobalRefs.end()) {
2435         V = I->second;             // Placeholder already exists, use it...
2436         $2.destroy();
2437       } else {
2438         std::string Name;
2439         if ($2.Type == ValID::NameVal) Name = $2.Name;
2440
2441         // Create the forward referenced global.
2442         GlobalValue *GV;
2443         if (const FunctionType *FTy = 
2444                  dyn_cast<FunctionType>(PT->getElementType())) {
2445           GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2446                             CurModule.CurrentModule);
2447         } else {
2448           GV = new GlobalVariable(PT->getElementType(), false,
2449                                   GlobalValue::ExternalLinkage, 0,
2450                                   Name, CurModule.CurrentModule);
2451         }
2452
2453         // Keep track of the fact that we have a forward ref to recycle it
2454         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2455         V = GV;
2456       }
2457     }
2458     $$.C = cast<GlobalValue>(V);
2459     $$.S.copy($1.S);
2460     delete $1.PAT;            // Free the type handle
2461   }
2462   | Types ConstExpr {
2463     if ($1.PAT->get() != $2.C->getType())
2464       error("Mismatched types for constant expression");
2465     $$ = $2;
2466     $$.S.copy($1.S);
2467     delete $1.PAT;
2468   }
2469   | Types ZEROINITIALIZER {
2470     const Type *Ty = $1.PAT->get();
2471     if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2472       error("Cannot create a null initialized value of this type");
2473     $$.C = Constant::getNullValue(Ty);
2474     $$.S.copy($1.S);
2475     delete $1.PAT;
2476   }
2477   | SIntType EINT64VAL {      // integral constants
2478     const Type *Ty = $1.T;
2479     if (!ConstantInt::isValueValidForType(Ty, $2))
2480       error("Constant value doesn't fit in type");
2481     $$.C = ConstantInt::get(Ty, $2);
2482     $$.S.makeSigned();
2483   }
2484   | UIntType EUINT64VAL {            // integral constants
2485     const Type *Ty = $1.T;
2486     if (!ConstantInt::isValueValidForType(Ty, $2))
2487       error("Constant value doesn't fit in type");
2488     $$.C = ConstantInt::get(Ty, $2);
2489     $$.S.makeUnsigned();
2490   }
2491   | BOOL TRUETOK {                      // Boolean constants
2492     $$.C = ConstantInt::get(Type::Int1Ty, true);
2493     $$.S.makeUnsigned();
2494   }
2495   | BOOL FALSETOK {                     // Boolean constants
2496     $$.C = ConstantInt::get(Type::Int1Ty, false);
2497     $$.S.makeUnsigned();
2498   }
2499   | FPType FPVAL {                   // Float & Double constants
2500     if (!ConstantFP::isValueValidForType($1.T, $2))
2501       error("Floating point constant invalid for type");
2502     $$.C = ConstantFP::get($1.T, $2);
2503     $$.S.makeSignless();
2504   }
2505   ;
2506
2507 ConstExpr
2508   : CastOps '(' ConstVal TO Types ')' {
2509     const Type* SrcTy = $3.C->getType();
2510     const Type* DstTy = $5.PAT->get();
2511     Signedness SrcSign($3.S);
2512     Signedness DstSign($5.S);
2513     if (!SrcTy->isFirstClassType())
2514       error("cast constant expression from a non-primitive type: '" +
2515             SrcTy->getDescription() + "'");
2516     if (!DstTy->isFirstClassType())
2517       error("cast constant expression to a non-primitive type: '" +
2518             DstTy->getDescription() + "'");
2519     $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2520     $$.S.copy(DstSign);
2521     delete $5.PAT;
2522   }
2523   | GETELEMENTPTR '(' ConstVal IndexList ')' {
2524     const Type *Ty = $3.C->getType();
2525     if (!isa<PointerType>(Ty))
2526       error("GetElementPtr requires a pointer operand");
2527
2528     std::vector<Value*> VIndices;
2529     std::vector<Constant*> CIndices;
2530     upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2531
2532     delete $4;
2533     $$.C = ConstantExpr::getGetElementPtr($3.C, &CIndices[0], CIndices.size());
2534     $$.S.copy(getElementSign($3, CIndices));
2535   }
2536   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2537     if (!$3.C->getType()->isInteger() ||
2538         cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2539       error("Select condition must be bool type");
2540     if ($5.C->getType() != $7.C->getType())
2541       error("Select operand types must match");
2542     $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2543     $$.S.copy($5.S);
2544   }
2545   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2546     const Type *Ty = $3.C->getType();
2547     if (Ty != $5.C->getType())
2548       error("Binary operator types must match");
2549     // First, make sure we're dealing with the right opcode by upgrading from
2550     // obsolete versions.
2551     Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2552
2553     // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2554     // To retain backward compatibility with these early compilers, we emit a
2555     // cast to the appropriate integer type automatically if we are in the
2556     // broken case.  See PR424 for more information.
2557     if (!isa<PointerType>(Ty)) {
2558       $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2559     } else {
2560       const Type *IntPtrTy = 0;
2561       switch (CurModule.CurrentModule->getPointerSize()) {
2562       case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2563       case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2564       default: error("invalid pointer binary constant expr");
2565       }
2566       $$.C = ConstantExpr::get(Opcode, 
2567              ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2568              ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2569       $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2570     }
2571     $$.S.copy($3.S); 
2572   }
2573   | LogicalOps '(' ConstVal ',' ConstVal ')' {
2574     const Type* Ty = $3.C->getType();
2575     if (Ty != $5.C->getType())
2576       error("Logical operator types must match");
2577     if (!Ty->isInteger()) {
2578       if (!isa<VectorType>(Ty) || 
2579           !cast<VectorType>(Ty)->getElementType()->isInteger())
2580         error("Logical operator requires integer operands");
2581     }
2582     Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2583     $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2584     $$.S.copy($3.S);
2585   }
2586   | SetCondOps '(' ConstVal ',' ConstVal ')' {
2587     const Type* Ty = $3.C->getType();
2588     if (Ty != $5.C->getType())
2589       error("setcc operand types must match");
2590     unsigned short pred;
2591     Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2592     $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2593     $$.S.makeUnsigned();
2594   }
2595   | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2596     if ($4.C->getType() != $6.C->getType()) 
2597       error("icmp operand types must match");
2598     $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2599     $$.S.makeUnsigned();
2600   }
2601   | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2602     if ($4.C->getType() != $6.C->getType()) 
2603       error("fcmp operand types must match");
2604     $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2605     $$.S.makeUnsigned();
2606   }
2607   | ShiftOps '(' ConstVal ',' ConstVal ')' {
2608     if (!$5.C->getType()->isInteger() ||
2609         cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2610       error("Shift count for shift constant must be unsigned byte");
2611     const Type* Ty = $3.C->getType();
2612     if (!$3.C->getType()->isInteger())
2613       error("Shift constant expression requires integer operand");
2614     Constant *ShiftAmt = ConstantExpr::getZExt($5.C, Ty);
2615     $$.C = ConstantExpr::get(getBinaryOp($1, Ty, $3.S), $3.C, ShiftAmt);
2616     $$.S.copy($3.S);
2617   }
2618   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2619     if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2620       error("Invalid extractelement operands");
2621     $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2622     $$.S.copy($3.S.get(0));
2623   }
2624   | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2625     if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2626       error("Invalid insertelement operands");
2627     $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2628     $$.S.copy($3.S);
2629   }
2630   | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2631     if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2632       error("Invalid shufflevector operands");
2633     $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2634     $$.S.copy($3.S);
2635   }
2636   ;
2637
2638
2639 // ConstVector - A list of comma separated constants.
2640 ConstVector 
2641   : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2642   | ConstVal {
2643     $$ = new std::vector<ConstInfo>();
2644     $$->push_back($1);
2645   }
2646   ;
2647
2648
2649 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2650 GlobalType 
2651   : GLOBAL { $$ = false; } 
2652   | CONSTANT { $$ = true; }
2653   ;
2654
2655
2656 //===----------------------------------------------------------------------===//
2657 //                             Rules to match Modules
2658 //===----------------------------------------------------------------------===//
2659
2660 // Module rule: Capture the result of parsing the whole file into a result
2661 // variable...
2662 //
2663 Module 
2664   : FunctionList {
2665     $$ = ParserResult = $1;
2666     CurModule.ModuleDone();
2667   }
2668   ;
2669
2670 // FunctionList - A list of functions, preceeded by a constant pool.
2671 //
2672 FunctionList 
2673   : FunctionList Function { $$ = $1; CurFun.FunctionDone(); } 
2674   | FunctionList FunctionProto { $$ = $1; }
2675   | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }  
2676   | FunctionList IMPLEMENTATION { $$ = $1; }
2677   | ConstPool {
2678     $$ = CurModule.CurrentModule;
2679     // Emit an error if there are any unresolved types left.
2680     if (!CurModule.LateResolveTypes.empty()) {
2681       const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2682       if (DID.Type == ValID::NameVal) {
2683         error("Reference to an undefined type: '"+DID.getName() + "'");
2684       } else {
2685         error("Reference to an undefined type: #" + itostr(DID.Num));
2686       }
2687     }
2688   }
2689   ;
2690
2691 // ConstPool - Constants with optional names assigned to them.
2692 ConstPool 
2693   : ConstPool OptAssign TYPE TypesV {
2694     // Eagerly resolve types.  This is not an optimization, this is a
2695     // requirement that is due to the fact that we could have this:
2696     //
2697     // %list = type { %list * }
2698     // %list = type { %list * }    ; repeated type decl
2699     //
2700     // If types are not resolved eagerly, then the two types will not be
2701     // determined to be the same type!
2702     //
2703     ResolveTypeTo($2, $4.PAT->get(), $4.S);
2704
2705     if (!setTypeName($4, $2) && !$2) {
2706       // If this is a numbered type that is not a redefinition, add it to the 
2707       // slot table.
2708       CurModule.Types.push_back($4.PAT->get());
2709       CurModule.TypeSigns.push_back($4.S);
2710     }
2711     delete $4.PAT;
2712   }
2713   | ConstPool FunctionProto {       // Function prototypes can be in const pool
2714   }
2715   | ConstPool MODULE ASM_TOK AsmBlock {  // Asm blocks can be in the const pool
2716   }
2717   | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2718     if ($5.C == 0) 
2719       error("Global value initializer is not a constant");
2720     CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C, $5.S);
2721   } GlobalVarAttributes {
2722     CurGV = 0;
2723   }
2724   | ConstPool OptAssign EXTERNAL GlobalType Types {
2725     const Type *Ty = $5.PAT->get();
2726     CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0,
2727                                 $5.S);
2728     delete $5.PAT;
2729   } GlobalVarAttributes {
2730     CurGV = 0;
2731   }
2732   | ConstPool OptAssign DLLIMPORT GlobalType Types {
2733     const Type *Ty = $5.PAT->get();
2734     CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0,
2735                                 $5.S);
2736     delete $5.PAT;
2737   } GlobalVarAttributes {
2738     CurGV = 0;
2739   }
2740   | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2741     const Type *Ty = $5.PAT->get();
2742     CurGV = 
2743       ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0, 
2744                           $5.S);
2745     delete $5.PAT;
2746   } GlobalVarAttributes {
2747     CurGV = 0;
2748   }
2749   | ConstPool TARGET TargetDefinition { 
2750   }
2751   | ConstPool DEPLIBS '=' LibrariesDefinition {
2752   }
2753   | /* empty: end of list */ { 
2754   }
2755   ;
2756
2757 AsmBlock 
2758   : STRINGCONSTANT {
2759     const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2760     char *EndStr = UnEscapeLexed($1, true);
2761     std::string NewAsm($1, EndStr);
2762     free($1);
2763
2764     if (AsmSoFar.empty())
2765       CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2766     else
2767       CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2768   }
2769   ;
2770
2771 BigOrLittle 
2772   : BIG    { $$ = Module::BigEndian; }
2773   | LITTLE { $$ = Module::LittleEndian; }
2774   ;
2775
2776 TargetDefinition 
2777   : ENDIAN '=' BigOrLittle {
2778     CurModule.setEndianness($3);
2779   }
2780   | POINTERSIZE '=' EUINT64VAL {
2781     if ($3 == 32)
2782       CurModule.setPointerSize(Module::Pointer32);
2783     else if ($3 == 64)
2784       CurModule.setPointerSize(Module::Pointer64);
2785     else
2786       error("Invalid pointer size: '" + utostr($3) + "'");
2787   }
2788   | TRIPLE '=' STRINGCONSTANT {
2789     CurModule.CurrentModule->setTargetTriple($3);
2790     free($3);
2791   }
2792   | DATALAYOUT '=' STRINGCONSTANT {
2793     CurModule.CurrentModule->setDataLayout($3);
2794     free($3);
2795   }
2796   ;
2797
2798 LibrariesDefinition 
2799   : '[' LibList ']'
2800   ;
2801
2802 LibList 
2803   : LibList ',' STRINGCONSTANT {
2804       CurModule.CurrentModule->addLibrary($3);
2805       free($3);
2806   }
2807   | STRINGCONSTANT {
2808     CurModule.CurrentModule->addLibrary($1);
2809     free($1);
2810   }
2811   | /* empty: end of list */ { }
2812   ;
2813
2814 //===----------------------------------------------------------------------===//
2815 //                       Rules to match Function Headers
2816 //===----------------------------------------------------------------------===//
2817
2818 Name 
2819   : VAR_ID | STRINGCONSTANT
2820   ;
2821
2822 OptName 
2823   : Name 
2824   | /*empty*/ { $$ = 0; }
2825   ;
2826
2827 ArgVal 
2828   : Types OptName {
2829     if ($1.PAT->get() == Type::VoidTy)
2830       error("void typed arguments are invalid");
2831     $$ = new std::pair<PATypeInfo, char*>($1, $2);
2832   }
2833   ;
2834
2835 ArgListH 
2836   : ArgListH ',' ArgVal {
2837     $$ = $1;
2838     $$->push_back(*$3);
2839     delete $3;
2840   }
2841   | ArgVal {
2842     $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2843     $$->push_back(*$1);
2844     delete $1;
2845   }
2846   ;
2847
2848 ArgList 
2849   : ArgListH { $$ = $1; }
2850   | ArgListH ',' DOTDOTDOT {
2851     $$ = $1;
2852     PATypeInfo VoidTI;
2853     VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2854     VoidTI.S.makeSignless();
2855     $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2856   }
2857   | DOTDOTDOT {
2858     $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2859     PATypeInfo VoidTI;
2860     VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2861     VoidTI.S.makeSignless();
2862     $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2863   }
2864   | /* empty */ { $$ = 0; }
2865   ;
2866
2867 FunctionHeaderH 
2868   : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2869     UnEscapeLexed($3);
2870     std::string FunctionName($3);
2871     free($3);  // Free strdup'd memory!
2872
2873     const Type* RetTy = $2.PAT->get();
2874     
2875     if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2876       error("LLVM functions cannot return aggregate types");
2877
2878     Signedness FTySign;
2879     FTySign.makeComposite($2.S);
2880     std::vector<const Type*> ParamTyList;
2881
2882     // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2883     // i8*. We check here for those names and override the parameter list
2884     // types to ensure the prototype is correct.
2885     if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2886       ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2887     } else if (FunctionName == "llvm.va_copy") {
2888       ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2889       ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2890     } else if ($5) {   // If there are arguments...
2891       for (std::vector<std::pair<PATypeInfo,char*> >::iterator 
2892            I = $5->begin(), E = $5->end(); I != E; ++I) {
2893         const Type *Ty = I->first.PAT->get();
2894         ParamTyList.push_back(Ty);
2895         FTySign.add(I->first.S);
2896       }
2897     }
2898
2899     bool isVarArg = ParamTyList.size() && ParamTyList.back() == Type::VoidTy;
2900     if (isVarArg) 
2901       ParamTyList.pop_back();
2902
2903     // Convert the CSRet calling convention into the corresponding parameter
2904     // attribute.
2905     ParamAttrsList *ParamAttrs = 0;
2906     if ($1 == OldCallingConv::CSRet) {
2907       ParamAttrs = new ParamAttrsList();
2908       ParamAttrs->addAttributes(0, ParamAttr::None);     // result
2909       ParamAttrs->addAttributes(1, ParamAttr::StructRet); // first arg
2910     }
2911
2912     const FunctionType *FT = 
2913       FunctionType::get(RetTy, ParamTyList, isVarArg, ParamAttrs);
2914     const PointerType *PFT = PointerType::get(FT);
2915     delete $2.PAT;
2916
2917     ValID ID;
2918     if (!FunctionName.empty()) {
2919       ID = ValID::create((char*)FunctionName.c_str());
2920     } else {
2921       ID = ValID::create((int)CurModule.Values[PFT].size());
2922     }
2923     ID.S.makeComposite(FTySign);
2924
2925     Function *Fn = 0;
2926     Module* M = CurModule.CurrentModule;
2927
2928     // See if this function was forward referenced.  If so, recycle the object.
2929     if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2930       // Move the function to the end of the list, from whereever it was 
2931       // previously inserted.
2932       Fn = cast<Function>(FWRef);
2933       M->getFunctionList().remove(Fn);
2934       M->getFunctionList().push_back(Fn);
2935     } else if (!FunctionName.empty()) {
2936       GlobalValue *Conflict = M->getFunction(FunctionName);
2937       if (!Conflict)
2938         Conflict = M->getNamedGlobal(FunctionName);
2939       if (Conflict && PFT == Conflict->getType()) {
2940         if (!CurFun.isDeclare && !Conflict->isDeclaration()) {
2941           // We have two function definitions that conflict, same type, same
2942           // name. We should really check to make sure that this is the result
2943           // of integer type planes collapsing and generate an error if it is
2944           // not, but we'll just rename on the assumption that it is. However,
2945           // let's do it intelligently and rename the internal linkage one
2946           // if there is one.
2947           std::string NewName(makeNameUnique(FunctionName));
2948           if (Conflict->hasInternalLinkage()) {
2949             Conflict->setName(NewName);
2950             RenameMapKey Key = 
2951               makeRenameMapKey(FunctionName, Conflict->getType(), ID.S);
2952             CurModule.RenameMap[Key] = NewName;
2953             Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2954             InsertValue(Fn, CurModule.Values);
2955           } else {
2956             Fn = new Function(FT, CurFun.Linkage, NewName, M);
2957             InsertValue(Fn, CurModule.Values);
2958             RenameMapKey Key = 
2959               makeRenameMapKey(FunctionName, PFT, ID.S);
2960             CurModule.RenameMap[Key] = NewName;
2961           }
2962         } else {
2963           // If they are not both definitions, then just use the function we
2964           // found since the types are the same.
2965           Fn = cast<Function>(Conflict);
2966
2967           // Make sure to strip off any argument names so we can't get 
2968           // conflicts.
2969           if (Fn->isDeclaration())
2970             for (Function::arg_iterator AI = Fn->arg_begin(), 
2971                  AE = Fn->arg_end(); AI != AE; ++AI)
2972               AI->setName("");
2973         }
2974       } else if (Conflict) {
2975         // We have two globals with the same name and  different types. 
2976         // Previously, this was permitted because the symbol table had 
2977         // "type planes" and names only needed to be distinct within a 
2978         // type plane. After PR411 was fixed, this is no loner the case. 
2979         // To resolve this we must rename one of the two. 
2980         if (Conflict->hasInternalLinkage()) {
2981           // We can safely rename the Conflict.
2982           RenameMapKey Key = 
2983             makeRenameMapKey(Conflict->getName(), Conflict->getType(), 
2984               CurModule.NamedValueSigns[Conflict->getName()]);
2985           Conflict->setName(makeNameUnique(Conflict->getName()));
2986           CurModule.RenameMap[Key] = Conflict->getName();
2987           Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2988           InsertValue(Fn, CurModule.Values);
2989         } else { 
2990           // We can't quietly rename either of these things, but we must
2991           // rename one of them. Only if the function's linkage is internal can
2992           // we forgo a warning message about the renamed function. 
2993           std::string NewName = makeNameUnique(FunctionName);
2994           if (CurFun.Linkage != GlobalValue::InternalLinkage) {
2995             warning("Renaming function '" + FunctionName + "' as '" + NewName +
2996                     "' may cause linkage errors");
2997           }
2998           // Elect to rename the thing we're now defining.
2999           Fn = new Function(FT, CurFun.Linkage, NewName, M);
3000           InsertValue(Fn, CurModule.Values);
3001           RenameMapKey Key = makeRenameMapKey(FunctionName, PFT, ID.S);
3002           CurModule.RenameMap[Key] = NewName;
3003         } 
3004       } else {
3005         // There's no conflict, just define the function
3006         Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
3007         InsertValue(Fn, CurModule.Values);
3008       }
3009     }
3010
3011     CurFun.FunctionStart(Fn);
3012
3013     if (CurFun.isDeclare) {
3014       // If we have declaration, always overwrite linkage.  This will allow us 
3015       // to correctly handle cases, when pointer to function is passed as 
3016       // argument to another function.
3017       Fn->setLinkage(CurFun.Linkage);
3018     }
3019     Fn->setCallingConv(upgradeCallingConv($1));
3020     Fn->setAlignment($8);
3021     if ($7) {
3022       Fn->setSection($7);
3023       free($7);
3024     }
3025
3026     // Add all of the arguments we parsed to the function...
3027     if ($5) {                     // Is null if empty...
3028       if (isVarArg) {  // Nuke the last entry
3029         assert($5->back().first.PAT->get() == Type::VoidTy && 
3030                $5->back().second == 0 && "Not a varargs marker");
3031         delete $5->back().first.PAT;
3032         $5->pop_back();  // Delete the last entry
3033       }
3034       Function::arg_iterator ArgIt = Fn->arg_begin();
3035       Function::arg_iterator ArgEnd = Fn->arg_end();
3036       std::vector<std::pair<PATypeInfo,char*> >::iterator I = $5->begin();
3037       std::vector<std::pair<PATypeInfo,char*> >::iterator E = $5->end();
3038       for ( ; I != E && ArgIt != ArgEnd; ++I, ++ArgIt) {
3039         delete I->first.PAT;                      // Delete the typeholder...
3040         ValueInfo VI; VI.V = ArgIt; VI.S.copy(I->first.S); 
3041         setValueName(VI, I->second);           // Insert arg into symtab...
3042         InsertValue(ArgIt);
3043       }
3044       delete $5;                     // We're now done with the argument list
3045     }
3046   }
3047   ;
3048
3049 BEGIN 
3050   : BEGINTOK | '{'                // Allow BEGIN or '{' to start a function
3051   ;
3052
3053 FunctionHeader 
3054   : OptLinkage { CurFun.Linkage = $1; } FunctionHeaderH BEGIN {
3055     $$ = CurFun.CurrentFunction;
3056
3057     // Make sure that we keep track of the linkage type even if there was a
3058     // previous "declare".
3059     $$->setLinkage($1);
3060   }
3061   ;
3062
3063 END 
3064   : ENDTOK | '}'                    // Allow end of '}' to end a function
3065   ;
3066
3067 Function 
3068   : BasicBlockList END {
3069     $$ = $1;
3070   };
3071
3072 FnDeclareLinkage
3073   : /*default*/ { $$ = GlobalValue::ExternalLinkage; }
3074   | DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; } 
3075   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
3076   ;
3077   
3078 FunctionProto 
3079   : DECLARE { CurFun.isDeclare = true; } 
3080      FnDeclareLinkage { CurFun.Linkage = $3; } FunctionHeaderH {
3081     $$ = CurFun.CurrentFunction;
3082     CurFun.FunctionDone();
3083     
3084   }
3085   ;
3086
3087 //===----------------------------------------------------------------------===//
3088 //                        Rules to match Basic Blocks
3089 //===----------------------------------------------------------------------===//
3090
3091 OptSideEffect 
3092   : /* empty */ { $$ = false; }
3093   | SIDEEFFECT { $$ = true; }
3094   ;
3095
3096 ConstValueRef 
3097     // A reference to a direct constant
3098   : ESINT64VAL { $$ = ValID::create($1); }
3099   | EUINT64VAL { $$ = ValID::create($1); }
3100   | FPVAL { $$ = ValID::create($1); } 
3101   | TRUETOK { 
3102     $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true));
3103     $$.S.makeUnsigned();
3104   }
3105   | FALSETOK { 
3106     $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false)); 
3107     $$.S.makeUnsigned();
3108   }
3109   | NULL_TOK { $$ = ValID::createNull(); }
3110   | UNDEF { $$ = ValID::createUndef(); }
3111   | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
3112   | '<' ConstVector '>' { // Nonempty unsized packed vector
3113     const Type *ETy = (*$2)[0].C->getType();
3114     int NumElements = $2->size(); 
3115     VectorType* pt = VectorType::get(ETy, NumElements);
3116     $$.S.makeComposite((*$2)[0].S);
3117     PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt, $$.S));
3118     
3119     // Verify all elements are correct type!
3120     std::vector<Constant*> Elems;
3121     for (unsigned i = 0; i < $2->size(); i++) {
3122       Constant *C = (*$2)[i].C;
3123       const Type *CTy = C->getType();
3124       if (ETy != CTy)
3125         error("Element #" + utostr(i) + " is not of type '" + 
3126               ETy->getDescription() +"' as required!\nIt is of type '" +
3127               CTy->getDescription() + "'");
3128       Elems.push_back(C);
3129     }
3130     $$ = ValID::create(ConstantVector::get(pt, Elems));
3131     delete PTy; delete $2;
3132   }
3133   | ConstExpr {
3134     $$ = ValID::create($1.C);
3135     $$.S.copy($1.S);
3136   }
3137   | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
3138     char *End = UnEscapeLexed($3, true);
3139     std::string AsmStr = std::string($3, End);
3140     End = UnEscapeLexed($5, true);
3141     std::string Constraints = std::string($5, End);
3142     $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
3143     free($3);
3144     free($5);
3145   }
3146   ;
3147
3148 // SymbolicValueRef - Reference to one of two ways of symbolically refering to // another value.
3149 //
3150 SymbolicValueRef 
3151   : INTVAL {  $$ = ValID::create($1); $$.S.makeSignless(); }
3152   | Name   {  $$ = ValID::create($1); $$.S.makeSignless(); }
3153   ;
3154
3155 // ValueRef - A reference to a definition... either constant or symbolic
3156 ValueRef 
3157   : SymbolicValueRef | ConstValueRef
3158   ;
3159
3160
3161 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
3162 // type immediately preceeds the value reference, and allows complex constant
3163 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
3164 ResolvedVal 
3165   : Types ValueRef { 
3166     const Type *Ty = $1.PAT->get();
3167     $2.S.copy($1.S);
3168     $$.V = getVal(Ty, $2); 
3169     $$.S.copy($1.S);
3170     delete $1.PAT;
3171   }
3172   ;
3173
3174 BasicBlockList 
3175   : BasicBlockList BasicBlock {
3176     $$ = $1;
3177   }
3178   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
3179     $$ = $1;
3180   };
3181
3182
3183 // Basic blocks are terminated by branching instructions: 
3184 // br, br/cc, switch, ret
3185 //
3186 BasicBlock 
3187   : InstructionList OptAssign BBTerminatorInst  {
3188     ValueInfo VI; VI.V = $3.TI; VI.S.copy($3.S);
3189     setValueName(VI, $2);
3190     InsertValue($3.TI);
3191     $1->getInstList().push_back($3.TI);
3192     InsertValue($1);
3193     $$ = $1;
3194   }
3195   ;
3196
3197 InstructionList
3198   : InstructionList Inst {
3199     if ($2.I)
3200       $1->getInstList().push_back($2.I);
3201     $$ = $1;
3202   }
3203   | /* empty */ {
3204     $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++),true);
3205     // Make sure to move the basic block to the correct location in the
3206     // function, instead of leaving it inserted wherever it was first
3207     // referenced.
3208     Function::BasicBlockListType &BBL = 
3209       CurFun.CurrentFunction->getBasicBlockList();
3210     BBL.splice(BBL.end(), BBL, $$);
3211   }
3212   | LABELSTR {
3213     $$ = CurBB = getBBVal(ValID::create($1), true);
3214     // Make sure to move the basic block to the correct location in the
3215     // function, instead of leaving it inserted wherever it was first
3216     // referenced.
3217     Function::BasicBlockListType &BBL = 
3218       CurFun.CurrentFunction->getBasicBlockList();
3219     BBL.splice(BBL.end(), BBL, $$);
3220   }
3221   ;
3222
3223 Unwind : UNWIND | EXCEPT;
3224
3225 BBTerminatorInst 
3226   : RET ResolvedVal {              // Return with a result...
3227     $$.TI = new ReturnInst($2.V);
3228     $$.S.makeSignless();
3229   }
3230   | RET VOID {                                       // Return with no result...
3231     $$.TI = new ReturnInst();
3232     $$.S.makeSignless();
3233   }
3234   | BR LABEL ValueRef {                         // Unconditional Branch...
3235     BasicBlock* tmpBB = getBBVal($3);
3236     $$.TI = new BranchInst(tmpBB);
3237     $$.S.makeSignless();
3238   }                                                  // Conditional Branch...
3239   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
3240     $6.S.makeSignless();
3241     $9.S.makeSignless();
3242     BasicBlock* tmpBBA = getBBVal($6);
3243     BasicBlock* tmpBBB = getBBVal($9);
3244     $3.S.makeUnsigned();
3245     Value* tmpVal = getVal(Type::Int1Ty, $3);
3246     $$.TI = new BranchInst(tmpBBA, tmpBBB, tmpVal);
3247     $$.S.makeSignless();
3248   }
3249   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
3250     $3.S.copy($2.S);
3251     Value* tmpVal = getVal($2.T, $3);
3252     $6.S.makeSignless();
3253     BasicBlock* tmpBB = getBBVal($6);
3254     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
3255     $$.TI = S;
3256     $$.S.makeSignless();
3257     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
3258       E = $8->end();
3259     for (; I != E; ++I) {
3260       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
3261           S->addCase(CI, I->second);
3262       else
3263         error("Switch case is constant, but not a simple integer");
3264     }
3265     delete $8;
3266   }
3267   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
3268     $3.S.copy($2.S);
3269     Value* tmpVal = getVal($2.T, $3);
3270     $6.S.makeSignless();
3271     BasicBlock* tmpBB = getBBVal($6);
3272     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
3273     $$.TI = S;
3274     $$.S.makeSignless();
3275   }
3276   | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
3277     TO LABEL ValueRef Unwind LABEL ValueRef {
3278     const PointerType *PFTy;
3279     const FunctionType *Ty;
3280     Signedness FTySign;
3281
3282     if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3283         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3284       // Pull out the types of all of the arguments...
3285       std::vector<const Type*> ParamTypes;
3286       FTySign.makeComposite($3.S);
3287       if ($6) {
3288         for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3289              I != E; ++I) {
3290           ParamTypes.push_back((*I).V->getType());
3291           FTySign.add(I->S);
3292         }
3293       }
3294       ParamAttrsList *ParamAttrs = 0;
3295       if ($2 == OldCallingConv::CSRet) {
3296         ParamAttrs = new ParamAttrsList();
3297         ParamAttrs->addAttributes(0, ParamAttr::None);      // Function result
3298         ParamAttrs->addAttributes(1, ParamAttr::StructRet);  // first param
3299       }
3300       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3301       if (isVarArg) ParamTypes.pop_back();
3302       Ty = FunctionType::get($3.PAT->get(), ParamTypes, isVarArg, ParamAttrs);
3303       PFTy = PointerType::get(Ty);
3304       $$.S.copy($3.S);
3305     } else {
3306       FTySign = $3.S;
3307       // Get the signedness of the result type. $3 is the pointer to the
3308       // function type so we get the 0th element to extract the function type,
3309       // and then the 0th element again to get the result type.
3310       $$.S.copy($3.S.get(0).get(0)); 
3311     }
3312
3313     $4.S.makeComposite(FTySign);
3314     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
3315     BasicBlock *Normal = getBBVal($10);
3316     BasicBlock *Except = getBBVal($13);
3317
3318     // Create the call node...
3319     if (!$6) {                                   // Has no arguments?
3320       $$.TI = new InvokeInst(V, Normal, Except, 0, 0);
3321     } else {                                     // Has arguments?
3322       // Loop through FunctionType's arguments and ensure they are specified
3323       // correctly!
3324       //
3325       FunctionType::param_iterator I = Ty->param_begin();
3326       FunctionType::param_iterator E = Ty->param_end();
3327       std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3328
3329       std::vector<Value*> Args;
3330       for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
3331         if ((*ArgI).V->getType() != *I)
3332           error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3333                 (*I)->getDescription() + "'");
3334         Args.push_back((*ArgI).V);
3335       }
3336
3337       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
3338         error("Invalid number of parameters detected");
3339
3340       $$.TI = new InvokeInst(V, Normal, Except, &Args[0], Args.size());
3341     }
3342     cast<InvokeInst>($$.TI)->setCallingConv(upgradeCallingConv($2));
3343     delete $3.PAT;
3344     delete $6;
3345   }
3346   | Unwind {
3347     $$.TI = new UnwindInst();
3348     $$.S.makeSignless();
3349   }
3350   | UNREACHABLE {
3351     $$.TI = new UnreachableInst();
3352     $$.S.makeSignless();
3353   }
3354   ;
3355
3356 JumpTable 
3357   : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
3358     $$ = $1;
3359     $3.S.copy($2.S);
3360     Constant *V = cast<Constant>(getExistingValue($2.T, $3));
3361     
3362     if (V == 0)
3363       error("May only switch on a constant pool value");
3364
3365     $6.S.makeSignless();
3366     BasicBlock* tmpBB = getBBVal($6);
3367     $$->push_back(std::make_pair(V, tmpBB));
3368   }
3369   | IntType ConstValueRef ',' LABEL ValueRef {
3370     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3371     $2.S.copy($1.S);
3372     Constant *V = cast<Constant>(getExistingValue($1.T, $2));
3373
3374     if (V == 0)
3375       error("May only switch on a constant pool value");
3376
3377     $5.S.makeSignless();
3378     BasicBlock* tmpBB = getBBVal($5);
3379     $$->push_back(std::make_pair(V, tmpBB)); 
3380   }
3381   ;
3382
3383 Inst 
3384   : OptAssign InstVal {
3385     bool omit = false;
3386     if ($1)
3387       if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
3388         if (BCI->getSrcTy() == BCI->getDestTy() && 
3389             BCI->getOperand(0)->getName() == $1)
3390           // This is a useless bit cast causing a name redefinition. It is
3391           // a bit cast from a type to the same type of an operand with the
3392           // same name as the name we would give this instruction. Since this
3393           // instruction results in no code generation, it is safe to omit
3394           // the instruction. This situation can occur because of collapsed
3395           // type planes. For example:
3396           //   %X = add int %Y, %Z
3397           //   %X = cast int %Y to uint
3398           // After upgrade, this looks like:
3399           //   %X = add i32 %Y, %Z
3400           //   %X = bitcast i32 to i32
3401           // The bitcast is clearly useless so we omit it.
3402           omit = true;
3403     if (omit) {
3404       $$.I = 0;
3405       $$.S.makeSignless();
3406     } else {
3407       ValueInfo VI; VI.V = $2.I; VI.S.copy($2.S);
3408       setValueName(VI, $1);
3409       InsertValue($2.I);
3410       $$ = $2;
3411     }
3412   };
3413
3414 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
3415     $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
3416     $$.S.copy($1.S);
3417     $3.S.copy($1.S);
3418     Value* tmpVal = getVal($1.PAT->get(), $3);
3419     $5.S.makeSignless();
3420     BasicBlock* tmpBB = getBBVal($5);
3421     $$.P->push_back(std::make_pair(tmpVal, tmpBB));
3422     delete $1.PAT;
3423   }
3424   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3425     $$ = $1;
3426     $4.S.copy($1.S);
3427     Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3428     $6.S.makeSignless();
3429     BasicBlock* tmpBB = getBBVal($6);
3430     $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3431   }
3432   ;
3433
3434 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
3435     $$ = new std::vector<ValueInfo>();
3436     $$->push_back($1);
3437   }
3438   | ValueRefList ',' ResolvedVal {
3439     $$ = $1;
3440     $1->push_back($3);
3441   };
3442
3443 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
3444 ValueRefListE 
3445   : ValueRefList 
3446   | /*empty*/ { $$ = 0; }
3447   ;
3448
3449 OptTailCall 
3450   : TAIL CALL {
3451     $$ = true;
3452   }
3453   | CALL {
3454     $$ = false;
3455   }
3456   ;
3457
3458 InstVal 
3459   : ArithmeticOps Types ValueRef ',' ValueRef {
3460     $3.S.copy($2.S);
3461     $5.S.copy($2.S);
3462     const Type* Ty = $2.PAT->get();
3463     if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<VectorType>(Ty))
3464       error("Arithmetic operator requires integer, FP, or packed operands");
3465     if (isa<VectorType>(Ty) && 
3466         ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3467       error("Remainder not supported on vector types");
3468     // Upgrade the opcode from obsolete versions before we do anything with it.
3469     Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3470     Value* val1 = getVal(Ty, $3); 
3471     Value* val2 = getVal(Ty, $5);
3472     $$.I = BinaryOperator::create(Opcode, val1, val2);
3473     if ($$.I == 0)
3474       error("binary operator returned null");
3475     $$.S.copy($2.S);
3476     delete $2.PAT;
3477   }
3478   | LogicalOps Types ValueRef ',' ValueRef {
3479     $3.S.copy($2.S);
3480     $5.S.copy($2.S);
3481     const Type *Ty = $2.PAT->get();
3482     if (!Ty->isInteger()) {
3483       if (!isa<VectorType>(Ty) ||
3484           !cast<VectorType>(Ty)->getElementType()->isInteger())
3485         error("Logical operator requires integral operands");
3486     }
3487     Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3488     Value* tmpVal1 = getVal(Ty, $3);
3489     Value* tmpVal2 = getVal(Ty, $5);
3490     $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3491     if ($$.I == 0)
3492       error("binary operator returned null");
3493     $$.S.copy($2.S);
3494     delete $2.PAT;
3495   }
3496   | SetCondOps Types ValueRef ',' ValueRef {
3497     $3.S.copy($2.S);
3498     $5.S.copy($2.S);
3499     const Type* Ty = $2.PAT->get();
3500     if(isa<VectorType>(Ty))
3501       error("VectorTypes currently not supported in setcc instructions");
3502     unsigned short pred;
3503     Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3504     Value* tmpVal1 = getVal(Ty, $3);
3505     Value* tmpVal2 = getVal(Ty, $5);
3506     $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3507     if ($$.I == 0)
3508       error("binary operator returned null");
3509     $$.S.makeUnsigned();
3510     delete $2.PAT;
3511   }
3512   | ICMP IPredicates Types ValueRef ',' ValueRef {
3513     $4.S.copy($3.S);
3514     $6.S.copy($3.S);
3515     const Type *Ty = $3.PAT->get();
3516     if (isa<VectorType>(Ty)) 
3517       error("VectorTypes currently not supported in icmp instructions");
3518     else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3519       error("icmp requires integer or pointer typed operands");
3520     Value* tmpVal1 = getVal(Ty, $4);
3521     Value* tmpVal2 = getVal(Ty, $6);
3522     $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3523     $$.S.makeUnsigned();
3524     delete $3.PAT;
3525   }
3526   | FCMP FPredicates Types ValueRef ',' ValueRef {
3527     $4.S.copy($3.S);
3528     $6.S.copy($3.S);
3529     const Type *Ty = $3.PAT->get();
3530     if (isa<VectorType>(Ty))
3531       error("VectorTypes currently not supported in fcmp instructions");
3532     else if (!Ty->isFloatingPoint())
3533       error("fcmp instruction requires floating point operands");
3534     Value* tmpVal1 = getVal(Ty, $4);
3535     Value* tmpVal2 = getVal(Ty, $6);
3536     $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3537     $$.S.makeUnsigned();
3538     delete $3.PAT;
3539   }
3540   | NOT ResolvedVal {
3541     warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3542     const Type *Ty = $2.V->getType();
3543     Value *Ones = ConstantInt::getAllOnesValue(Ty);
3544     if (Ones == 0)
3545       error("Expected integral type for not instruction");
3546     $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3547     if ($$.I == 0)
3548       error("Could not create a xor instruction");
3549     $$.S.copy($2.S);
3550   }
3551   | ShiftOps ResolvedVal ',' ResolvedVal {
3552     if (!$4.V->getType()->isInteger() ||
3553         cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3554       error("Shift amount must be int8");
3555     const Type* Ty = $2.V->getType();
3556     if (!Ty->isInteger())
3557       error("Shift constant expression requires integer operand");
3558     Value* ShiftAmt = 0;
3559     if (cast<IntegerType>(Ty)->getBitWidth() > Type::Int8Ty->getBitWidth())
3560       if (Constant *C = dyn_cast<Constant>($4.V))
3561         ShiftAmt = ConstantExpr::getZExt(C, Ty);
3562       else
3563         ShiftAmt = new ZExtInst($4.V, Ty, makeNameUnique("shift"), CurBB);
3564     else
3565       ShiftAmt = $4.V;
3566     $$.I = BinaryOperator::create(getBinaryOp($1, Ty, $2.S), $2.V, ShiftAmt);
3567     $$.S.copy($2.S);
3568   }
3569   | CastOps ResolvedVal TO Types {
3570     const Type *DstTy = $4.PAT->get();
3571     if (!DstTy->isFirstClassType())
3572       error("cast instruction to a non-primitive type: '" +
3573             DstTy->getDescription() + "'");
3574     $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3575     $$.S.copy($4.S);
3576     delete $4.PAT;
3577   }
3578   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3579     if (!$2.V->getType()->isInteger() ||
3580         cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3581       error("select condition must be bool");
3582     if ($4.V->getType() != $6.V->getType())
3583       error("select value types should match");
3584     $$.I = new SelectInst($2.V, $4.V, $6.V);
3585     $$.S.copy($4.S);
3586   }
3587   | VAARG ResolvedVal ',' Types {
3588     const Type *Ty = $4.PAT->get();
3589     NewVarArgs = true;
3590     $$.I = new VAArgInst($2.V, Ty);
3591     $$.S.copy($4.S);
3592     delete $4.PAT;
3593   }
3594   | VAARG_old ResolvedVal ',' Types {
3595     const Type* ArgTy = $2.V->getType();
3596     const Type* DstTy = $4.PAT->get();
3597     ObsoleteVarArgs = true;
3598     Function* NF = cast<Function>(CurModule.CurrentModule->
3599       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3600
3601     //b = vaarg a, t -> 
3602     //foo = alloca 1 of t
3603     //bar = vacopy a 
3604     //store bar -> foo
3605     //b = vaarg foo, t
3606     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3607     CurBB->getInstList().push_back(foo);
3608     CallInst* bar = new CallInst(NF, $2.V);
3609     CurBB->getInstList().push_back(bar);
3610     CurBB->getInstList().push_back(new StoreInst(bar, foo));
3611     $$.I = new VAArgInst(foo, DstTy);
3612     $$.S.copy($4.S);
3613     delete $4.PAT;
3614   }
3615   | VANEXT_old ResolvedVal ',' Types {
3616     const Type* ArgTy = $2.V->getType();
3617     const Type* DstTy = $4.PAT->get();
3618     ObsoleteVarArgs = true;
3619     Function* NF = cast<Function>(CurModule.CurrentModule->
3620       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3621
3622     //b = vanext a, t ->
3623     //foo = alloca 1 of t
3624     //bar = vacopy a
3625     //store bar -> foo
3626     //tmp = vaarg foo, t
3627     //b = load foo
3628     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3629     CurBB->getInstList().push_back(foo);
3630     CallInst* bar = new CallInst(NF, $2.V);
3631     CurBB->getInstList().push_back(bar);
3632     CurBB->getInstList().push_back(new StoreInst(bar, foo));
3633     Instruction* tmp = new VAArgInst(foo, DstTy);
3634     CurBB->getInstList().push_back(tmp);
3635     $$.I = new LoadInst(foo);
3636     $$.S.copy($4.S);
3637     delete $4.PAT;
3638   }
3639   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3640     if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3641       error("Invalid extractelement operands");
3642     $$.I = new ExtractElementInst($2.V, $4.V);
3643     $$.S.copy($2.S.get(0));
3644   }
3645   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3646     if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3647       error("Invalid insertelement operands");
3648     $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3649     $$.S.copy($2.S);
3650   }
3651   | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3652     if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3653       error("Invalid shufflevector operands");
3654     $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3655     $$.S.copy($2.S);
3656   }
3657   | PHI_TOK PHIList {
3658     const Type *Ty = $2.P->front().first->getType();
3659     if (!Ty->isFirstClassType())
3660       error("PHI node operands must be of first class type");
3661     PHINode *PHI = new PHINode(Ty);
3662     PHI->reserveOperandSpace($2.P->size());
3663     while ($2.P->begin() != $2.P->end()) {
3664       if ($2.P->front().first->getType() != Ty) 
3665         error("All elements of a PHI node must be of the same type");
3666       PHI->addIncoming($2.P->front().first, $2.P->front().second);
3667       $2.P->pop_front();
3668     }
3669     $$.I = PHI;
3670     $$.S.copy($2.S);
3671     delete $2.P;  // Free the list...
3672   }
3673   | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
3674     // Handle the short call syntax
3675     const PointerType *PFTy;
3676     const FunctionType *FTy;
3677     Signedness FTySign;
3678     if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3679         !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3680       // Pull out the types of all of the arguments...
3681       std::vector<const Type*> ParamTypes;
3682       FTySign.makeComposite($3.S);
3683       if ($6) {
3684         for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3685              I != E; ++I) {
3686           ParamTypes.push_back((*I).V->getType());
3687           FTySign.add(I->S);
3688         }
3689       }
3690
3691       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3692       if (isVarArg) ParamTypes.pop_back();
3693
3694       const Type *RetTy = $3.PAT->get();
3695       if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3696         error("Functions cannot return aggregate types");
3697
3698       // Deal with CSRetCC
3699       ParamAttrsList *ParamAttrs = 0;
3700       if ($2 == OldCallingConv::CSRet) {
3701         ParamAttrs = new ParamAttrsList();
3702         ParamAttrs->addAttributes(0, ParamAttr::None);     // function result
3703         ParamAttrs->addAttributes(1, ParamAttr::StructRet); // first parameter
3704       }
3705
3706       FTy = FunctionType::get(RetTy, ParamTypes, isVarArg, ParamAttrs);
3707       PFTy = PointerType::get(FTy);
3708       $$.S.copy($3.S);
3709     } else {
3710       FTySign = $3.S;
3711       // Get the signedness of the result type. $3 is the pointer to the
3712       // function type so we get the 0th element to extract the function type,
3713       // and then the 0th element again to get the result type.
3714       $$.S.copy($3.S.get(0).get(0)); 
3715     }
3716     $4.S.makeComposite(FTySign);
3717
3718     // First upgrade any intrinsic calls.
3719     std::vector<Value*> Args;
3720     if ($6)
3721       for (unsigned i = 0, e = $6->size(); i < e; ++i) 
3722         Args.push_back((*$6)[i].V);
3723     Instruction *Inst = upgradeIntrinsicCall(FTy->getReturnType(), $4, Args);
3724
3725     // If we got an upgraded intrinsic
3726     if (Inst) {
3727       $$.I = Inst;
3728     } else {
3729       // Get the function we're calling
3730       Value *V = getVal(PFTy, $4);
3731
3732       // Check the argument values match
3733       if (!$6) {                                   // Has no arguments?
3734         // Make sure no arguments is a good thing!
3735         if (FTy->getNumParams() != 0)
3736           error("No arguments passed to a function that expects arguments");
3737       } else {                                     // Has arguments?
3738         // Loop through FunctionType's arguments and ensure they are specified
3739         // correctly!
3740         //
3741         FunctionType::param_iterator I = FTy->param_begin();
3742         FunctionType::param_iterator E = FTy->param_end();
3743         std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3744
3745         for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3746           if ((*ArgI).V->getType() != *I)
3747             error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3748                   (*I)->getDescription() + "'");
3749
3750         if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3751           error("Invalid number of parameters detected");
3752       }
3753
3754       // Create the call instruction
3755       CallInst *CI = new CallInst(V, &Args[0], Args.size());
3756       CI->setTailCall($1);
3757       CI->setCallingConv(upgradeCallingConv($2));
3758       $$.I = CI;
3759     }
3760     delete $3.PAT;
3761     delete $6;
3762   }
3763   | MemoryInst {
3764     $$ = $1;
3765   }
3766   ;
3767
3768
3769 // IndexList - List of indices for GEP based instructions...
3770 IndexList 
3771   : ',' ValueRefList { $$ = $2; } 
3772   | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3773   ;
3774
3775 OptVolatile 
3776   : VOLATILE { $$ = true; }
3777   | /* empty */ { $$ = false; }
3778   ;
3779
3780 MemoryInst 
3781   : MALLOC Types OptCAlign {
3782     const Type *Ty = $2.PAT->get();
3783     $$.S.makeComposite($2.S);
3784     $$.I = new MallocInst(Ty, 0, $3);
3785     delete $2.PAT;
3786   }
3787   | MALLOC Types ',' UINT ValueRef OptCAlign {
3788     const Type *Ty = $2.PAT->get();
3789     $5.S.makeUnsigned();
3790     $$.S.makeComposite($2.S);
3791     $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3792     delete $2.PAT;
3793   }
3794   | ALLOCA Types OptCAlign {
3795     const Type *Ty = $2.PAT->get();
3796     $$.S.makeComposite($2.S);
3797     $$.I = new AllocaInst(Ty, 0, $3);
3798     delete $2.PAT;
3799   }
3800   | ALLOCA Types ',' UINT ValueRef OptCAlign {
3801     const Type *Ty = $2.PAT->get();
3802     $5.S.makeUnsigned();
3803     $$.S.makeComposite($4.S);
3804     $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3805     delete $2.PAT;
3806   }
3807   | FREE ResolvedVal {
3808     const Type *PTy = $2.V->getType();
3809     if (!isa<PointerType>(PTy))
3810       error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3811     $$.I = new FreeInst($2.V);
3812     $$.S.makeSignless();
3813   }
3814   | OptVolatile LOAD Types ValueRef {
3815     const Type* Ty = $3.PAT->get();
3816     $4.S.copy($3.S);
3817     if (!isa<PointerType>(Ty))
3818       error("Can't load from nonpointer type: " + Ty->getDescription());
3819     if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3820       error("Can't load from pointer of non-first-class type: " +
3821                      Ty->getDescription());
3822     Value* tmpVal = getVal(Ty, $4);
3823     $$.I = new LoadInst(tmpVal, "", $1);
3824     $$.S.copy($3.S.get(0));
3825     delete $3.PAT;
3826   }
3827   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3828     $6.S.copy($5.S);
3829     const PointerType *PTy = dyn_cast<PointerType>($5.PAT->get());
3830     if (!PTy)
3831       error("Can't store to a nonpointer type: " + 
3832              $5.PAT->get()->getDescription());
3833     const Type *ElTy = PTy->getElementType();
3834     Value *StoreVal = $3.V;
3835     Value* tmpVal = getVal(PTy, $6);
3836     if (ElTy != $3.V->getType()) {
3837       StoreVal = handleSRetFuncTypeMerge($3.V, ElTy);
3838       if (!StoreVal)
3839         error("Can't store '" + $3.V->getType()->getDescription() +
3840               "' into space of type '" + ElTy->getDescription() + "'");
3841       else {
3842         PTy = PointerType::get(StoreVal->getType());
3843         if (Constant *C = dyn_cast<Constant>(tmpVal))
3844           tmpVal = ConstantExpr::getBitCast(C, PTy);
3845         else
3846           tmpVal = new BitCastInst(tmpVal, PTy, "upgrd.cast", CurBB);
3847       }
3848     }
3849     $$.I = new StoreInst(StoreVal, tmpVal, $1);
3850     $$.S.makeSignless();
3851     delete $5.PAT;
3852   }
3853   | GETELEMENTPTR Types ValueRef IndexList {
3854     $3.S.copy($2.S);
3855     const Type* Ty = $2.PAT->get();
3856     if (!isa<PointerType>(Ty))
3857       error("getelementptr insn requires pointer operand");
3858
3859     std::vector<Value*> VIndices;
3860     upgradeGEPIndices(Ty, $4, VIndices);
3861
3862     Value* tmpVal = getVal(Ty, $3);
3863     $$.I = new GetElementPtrInst(tmpVal, &VIndices[0], VIndices.size());
3864     ValueInfo VI; VI.V = tmpVal; VI.S.copy($2.S);
3865     $$.S.copy(getElementSign(VI, VIndices));
3866     delete $2.PAT;
3867     delete $4;
3868   };
3869
3870
3871 %%
3872
3873 int yyerror(const char *ErrorMsg) {
3874   std::string where 
3875     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3876                   + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3877   std::string errMsg = where + "error: " + std::string(ErrorMsg);
3878   if (yychar != YYEMPTY && yychar != 0)
3879     errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3880               "'.";
3881   std::cerr << "llvm-upgrade: " << errMsg << '\n';
3882   std::cout << "llvm-upgrade: parse failed.\n";
3883   exit(1);
3884 }
3885
3886 void warning(const std::string& ErrorMsg) {
3887   std::string where 
3888     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3889                   + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3890   std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3891   if (yychar != YYEMPTY && yychar != 0)
3892     errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3893               "'.";
3894   std::cerr << "llvm-upgrade: " << errMsg << '\n';
3895 }
3896
3897 void error(const std::string& ErrorMsg, int LineNo) {
3898   if (LineNo == -1) LineNo = Upgradelineno;
3899   Upgradelineno = LineNo;
3900   yyerror(ErrorMsg.c_str());
3901 }
3902