Minor logic simplification.
[oota-llvm.git] / lib / AsmParser / LLParser.cpp
1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the parser class for .ll files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LLParser.h"
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Metadata.h"
23 #include "llvm/Module.h"
24 #include "llvm/Operator.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 using namespace llvm;
31
32 namespace llvm {
33   /// ValID - Represents a reference of a definition of some sort with no type.
34   /// There are several cases where we have to parse the value but where the
35   /// type can depend on later context.  This may either be a numeric reference
36   /// or a symbolic (%var) reference.  This is just a discriminated union.
37   struct ValID {
38     enum {
39       t_LocalID, t_GlobalID,      // ID in UIntVal.
40       t_LocalName, t_GlobalName,  // Name in StrVal.
41       t_APSInt, t_APFloat,        // Value in APSIntVal/APFloatVal.
42       t_Null, t_Undef, t_Zero,    // No value.
43       t_EmptyArray,               // No value:  []
44       t_Constant,                 // Value in ConstantVal.
45       t_InlineAsm,                // Value in StrVal/StrVal2/UIntVal.
46       t_Metadata                  // Value in MetadataVal.
47     } Kind;
48     
49     LLParser::LocTy Loc;
50     unsigned UIntVal;
51     std::string StrVal, StrVal2;
52     APSInt APSIntVal;
53     APFloat APFloatVal;
54     Constant *ConstantVal;
55     MetadataBase *MetadataVal;
56     ValID() : APFloatVal(0.0) {}
57   };
58 }
59
60 /// Run: module ::= toplevelentity*
61 bool LLParser::Run() {
62   // Prime the lexer.
63   Lex.Lex();
64
65   return ParseTopLevelEntities() ||
66          ValidateEndOfModule();
67 }
68
69 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
70 /// module.
71 bool LLParser::ValidateEndOfModule() {
72   if (!ForwardRefTypes.empty())
73     return Error(ForwardRefTypes.begin()->second.second,
74                  "use of undefined type named '" +
75                  ForwardRefTypes.begin()->first + "'");
76   if (!ForwardRefTypeIDs.empty())
77     return Error(ForwardRefTypeIDs.begin()->second.second,
78                  "use of undefined type '%" +
79                  utostr(ForwardRefTypeIDs.begin()->first) + "'");
80   
81   if (!ForwardRefVals.empty())
82     return Error(ForwardRefVals.begin()->second.second,
83                  "use of undefined value '@" + ForwardRefVals.begin()->first +
84                  "'");
85   
86   if (!ForwardRefValIDs.empty())
87     return Error(ForwardRefValIDs.begin()->second.second,
88                  "use of undefined value '@" +
89                  utostr(ForwardRefValIDs.begin()->first) + "'");
90   
91   if (!ForwardRefMDNodes.empty())
92     return Error(ForwardRefMDNodes.begin()->second.second,
93                  "use of undefined metadata '!" +
94                  utostr(ForwardRefMDNodes.begin()->first) + "'");
95   
96
97   // Look for intrinsic functions and CallInst that need to be upgraded
98   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
99     UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
100   
101   // Check debug info intrinsics.
102   CheckDebugInfoIntrinsics(M);
103   return false;
104 }
105
106 //===----------------------------------------------------------------------===//
107 // Top-Level Entities
108 //===----------------------------------------------------------------------===//
109
110 bool LLParser::ParseTopLevelEntities() {
111   while (1) {
112     switch (Lex.getKind()) {
113     default:         return TokError("expected top-level entity");
114     case lltok::Eof: return false;
115     //case lltok::kw_define:
116     case lltok::kw_declare: if (ParseDeclare()) return true; break;
117     case lltok::kw_define:  if (ParseDefine()) return true; break;
118     case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
119     case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
120     case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
121     case lltok::kw_type:    if (ParseUnnamedType()) return true; break;
122     case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
123     case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
124     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
125     case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
126     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
127     case lltok::Metadata:   if (ParseStandaloneMetadata()) return true; break;
128     case lltok::NamedMD:    if (ParseNamedMetadata()) return true; break;
129
130     // The Global variable production with no name can have many different
131     // optional leading prefixes, the production is:
132     // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
133     //               OptionalAddrSpace ('constant'|'global') ...
134     case lltok::kw_private :       // OptionalLinkage
135     case lltok::kw_linker_private: // OptionalLinkage
136     case lltok::kw_internal:       // OptionalLinkage
137     case lltok::kw_weak:           // OptionalLinkage
138     case lltok::kw_weak_odr:       // OptionalLinkage
139     case lltok::kw_linkonce:       // OptionalLinkage
140     case lltok::kw_linkonce_odr:   // OptionalLinkage
141     case lltok::kw_appending:      // OptionalLinkage
142     case lltok::kw_dllexport:      // OptionalLinkage
143     case lltok::kw_common:         // OptionalLinkage
144     case lltok::kw_dllimport:      // OptionalLinkage
145     case lltok::kw_extern_weak:    // OptionalLinkage
146     case lltok::kw_external: {     // OptionalLinkage
147       unsigned Linkage, Visibility;
148       if (ParseOptionalLinkage(Linkage) ||
149           ParseOptionalVisibility(Visibility) ||
150           ParseGlobal("", SMLoc(), Linkage, true, Visibility))
151         return true;
152       break;
153     }
154     case lltok::kw_default:       // OptionalVisibility
155     case lltok::kw_hidden:        // OptionalVisibility
156     case lltok::kw_protected: {   // OptionalVisibility
157       unsigned Visibility;
158       if (ParseOptionalVisibility(Visibility) ||
159           ParseGlobal("", SMLoc(), 0, false, Visibility))
160         return true;
161       break;
162     }
163         
164     case lltok::kw_thread_local:  // OptionalThreadLocal
165     case lltok::kw_addrspace:     // OptionalAddrSpace
166     case lltok::kw_constant:      // GlobalType
167     case lltok::kw_global:        // GlobalType
168       if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
169       break;
170     }
171   }
172 }
173
174
175 /// toplevelentity
176 ///   ::= 'module' 'asm' STRINGCONSTANT
177 bool LLParser::ParseModuleAsm() {
178   assert(Lex.getKind() == lltok::kw_module);
179   Lex.Lex();
180   
181   std::string AsmStr; 
182   if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
183       ParseStringConstant(AsmStr)) return true;
184   
185   const std::string &AsmSoFar = M->getModuleInlineAsm();
186   if (AsmSoFar.empty())
187     M->setModuleInlineAsm(AsmStr);
188   else
189     M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
190   return false;
191 }
192
193 /// toplevelentity
194 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
195 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
196 bool LLParser::ParseTargetDefinition() {
197   assert(Lex.getKind() == lltok::kw_target);
198   std::string Str;
199   switch (Lex.Lex()) {
200   default: return TokError("unknown target property");
201   case lltok::kw_triple:
202     Lex.Lex();
203     if (ParseToken(lltok::equal, "expected '=' after target triple") ||
204         ParseStringConstant(Str))
205       return true;
206     M->setTargetTriple(Str);
207     return false;
208   case lltok::kw_datalayout:
209     Lex.Lex();
210     if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
211         ParseStringConstant(Str))
212       return true;
213     M->setDataLayout(Str);
214     return false;
215   }
216 }
217
218 /// toplevelentity
219 ///   ::= 'deplibs' '=' '[' ']'
220 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
221 bool LLParser::ParseDepLibs() {
222   assert(Lex.getKind() == lltok::kw_deplibs);
223   Lex.Lex();
224   if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
225       ParseToken(lltok::lsquare, "expected '=' after deplibs"))
226     return true;
227
228   if (EatIfPresent(lltok::rsquare))
229     return false;
230   
231   std::string Str;
232   if (ParseStringConstant(Str)) return true;
233   M->addLibrary(Str);
234
235   while (EatIfPresent(lltok::comma)) {
236     if (ParseStringConstant(Str)) return true;
237     M->addLibrary(Str);
238   }
239
240   return ParseToken(lltok::rsquare, "expected ']' at end of list");
241 }
242
243 /// ParseUnnamedType:
244 ///   ::= 'type' type
245 ///   ::= LocalVarID '=' 'type' type
246 bool LLParser::ParseUnnamedType() {
247   unsigned TypeID = NumberedTypes.size();
248
249   // Handle the LocalVarID form.
250   if (Lex.getKind() == lltok::LocalVarID) {
251     if (Lex.getUIntVal() != TypeID)
252       return Error(Lex.getLoc(), "type expected to be numbered '%" +
253                    utostr(TypeID) + "'");
254     Lex.Lex(); // eat LocalVarID;
255
256     if (ParseToken(lltok::equal, "expected '=' after name"))
257       return true;
258   }
259
260   assert(Lex.getKind() == lltok::kw_type);
261   LocTy TypeLoc = Lex.getLoc();
262   Lex.Lex(); // eat kw_type
263
264   PATypeHolder Ty(Type::getVoidTy(Context));
265   if (ParseType(Ty)) return true;
266  
267   // See if this type was previously referenced.
268   std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
269     FI = ForwardRefTypeIDs.find(TypeID);
270   if (FI != ForwardRefTypeIDs.end()) {
271     if (FI->second.first.get() == Ty)
272       return Error(TypeLoc, "self referential type is invalid");
273     
274     cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
275     Ty = FI->second.first.get();
276     ForwardRefTypeIDs.erase(FI);
277   }
278   
279   NumberedTypes.push_back(Ty);
280   
281   return false;
282 }
283
284 /// toplevelentity
285 ///   ::= LocalVar '=' 'type' type
286 bool LLParser::ParseNamedType() {
287   std::string Name = Lex.getStrVal();
288   LocTy NameLoc = Lex.getLoc();
289   Lex.Lex();  // eat LocalVar.
290   
291   PATypeHolder Ty(Type::getVoidTy(Context));
292   
293   if (ParseToken(lltok::equal, "expected '=' after name") ||
294       ParseToken(lltok::kw_type, "expected 'type' after name") ||
295       ParseType(Ty))
296     return true;
297   
298   // Set the type name, checking for conflicts as we do so.
299   bool AlreadyExists = M->addTypeName(Name, Ty);
300   if (!AlreadyExists) return false;
301
302   // See if this type is a forward reference.  We need to eagerly resolve
303   // types to allow recursive type redefinitions below.
304   std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
305   FI = ForwardRefTypes.find(Name);
306   if (FI != ForwardRefTypes.end()) {
307     if (FI->second.first.get() == Ty)
308       return Error(NameLoc, "self referential type is invalid");
309
310     cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
311     Ty = FI->second.first.get();
312     ForwardRefTypes.erase(FI);
313   }
314   
315   // Inserting a name that is already defined, get the existing name.
316   const Type *Existing = M->getTypeByName(Name);
317   assert(Existing && "Conflict but no matching type?!");
318     
319   // Otherwise, this is an attempt to redefine a type. That's okay if
320   // the redefinition is identical to the original.
321   // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
322   if (Existing == Ty) return false;
323   
324   // Any other kind of (non-equivalent) redefinition is an error.
325   return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
326                Ty->getDescription() + "'");
327 }
328
329
330 /// toplevelentity
331 ///   ::= 'declare' FunctionHeader
332 bool LLParser::ParseDeclare() {
333   assert(Lex.getKind() == lltok::kw_declare);
334   Lex.Lex();
335   
336   Function *F;
337   return ParseFunctionHeader(F, false);
338 }
339
340 /// toplevelentity
341 ///   ::= 'define' FunctionHeader '{' ...
342 bool LLParser::ParseDefine() {
343   assert(Lex.getKind() == lltok::kw_define);
344   Lex.Lex();
345   
346   Function *F;
347   return ParseFunctionHeader(F, true) ||
348          ParseFunctionBody(*F);
349 }
350
351 /// ParseGlobalType
352 ///   ::= 'constant'
353 ///   ::= 'global'
354 bool LLParser::ParseGlobalType(bool &IsConstant) {
355   if (Lex.getKind() == lltok::kw_constant)
356     IsConstant = true;
357   else if (Lex.getKind() == lltok::kw_global)
358     IsConstant = false;
359   else {
360     IsConstant = false;
361     return TokError("expected 'global' or 'constant'");
362   }
363   Lex.Lex();
364   return false;
365 }
366
367 /// ParseUnnamedGlobal:
368 ///   OptionalVisibility ALIAS ...
369 ///   OptionalLinkage OptionalVisibility ...   -> global variable
370 ///   GlobalID '=' OptionalVisibility ALIAS ...
371 ///   GlobalID '=' OptionalLinkage OptionalVisibility ...   -> global variable
372 bool LLParser::ParseUnnamedGlobal() {
373   unsigned VarID = NumberedVals.size();
374   std::string Name;
375   LocTy NameLoc = Lex.getLoc();
376
377   // Handle the GlobalID form.
378   if (Lex.getKind() == lltok::GlobalID) {
379     if (Lex.getUIntVal() != VarID)
380       return Error(Lex.getLoc(), "variable expected to be numbered '%" +
381                    utostr(VarID) + "'");
382     Lex.Lex(); // eat GlobalID;
383
384     if (ParseToken(lltok::equal, "expected '=' after name"))
385       return true;
386   }
387
388   bool HasLinkage;
389   unsigned Linkage, Visibility;
390   if (ParseOptionalLinkage(Linkage, HasLinkage) ||
391       ParseOptionalVisibility(Visibility))
392     return true;
393   
394   if (HasLinkage || Lex.getKind() != lltok::kw_alias)
395     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
396   return ParseAlias(Name, NameLoc, Visibility);
397 }
398
399 /// ParseNamedGlobal:
400 ///   GlobalVar '=' OptionalVisibility ALIAS ...
401 ///   GlobalVar '=' OptionalLinkage OptionalVisibility ...   -> global variable
402 bool LLParser::ParseNamedGlobal() {
403   assert(Lex.getKind() == lltok::GlobalVar);
404   LocTy NameLoc = Lex.getLoc();
405   std::string Name = Lex.getStrVal();
406   Lex.Lex();
407   
408   bool HasLinkage;
409   unsigned Linkage, Visibility;
410   if (ParseToken(lltok::equal, "expected '=' in global variable") ||
411       ParseOptionalLinkage(Linkage, HasLinkage) ||
412       ParseOptionalVisibility(Visibility))
413     return true;
414   
415   if (HasLinkage || Lex.getKind() != lltok::kw_alias)
416     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
417   return ParseAlias(Name, NameLoc, Visibility);
418 }
419
420 // MDString:
421 //   ::= '!' STRINGCONSTANT
422 bool LLParser::ParseMDString(MetadataBase *&MDS) {
423   std::string Str;
424   if (ParseStringConstant(Str)) return true;
425   MDS = MDString::get(Context, Str);
426   return false;
427 }
428
429 // MDNode:
430 //   ::= '!' MDNodeNumber
431 bool LLParser::ParseMDNode(MetadataBase *&Node) {
432   // !{ ..., !42, ... }
433   unsigned MID = 0;
434   if (ParseUInt32(MID))  return true;
435   
436   // Check existing MDNode.
437   std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
438   if (I != MetadataCache.end()) {
439     Node = I->second;
440     return false;
441   }
442
443   // Check known forward references.
444   std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
445     FI = ForwardRefMDNodes.find(MID);
446   if (FI != ForwardRefMDNodes.end()) {
447     Node = FI->second.first;
448     return false;
449   }
450
451   // Create MDNode forward reference
452   SmallVector<Value *, 1> Elts;
453   std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
454   Elts.push_back(MDString::get(Context, FwdRefName));
455   MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
456   ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
457   Node = FwdNode;
458   return false;
459 }    
460
461 ///ParseNamedMetadata:
462 ///   !foo = !{ !1, !2 }
463 bool LLParser::ParseNamedMetadata() {
464   assert(Lex.getKind() == lltok::NamedMD);
465   Lex.Lex();
466   std::string Name = Lex.getStrVal();
467
468   if (ParseToken(lltok::equal, "expected '=' here"))
469     return true;
470
471   if (Lex.getKind() != lltok::Metadata)
472     return TokError("Expected '!' here");
473   Lex.Lex();
474
475   if (Lex.getKind() != lltok::lbrace)
476     return TokError("Expected '{' here");
477   Lex.Lex();
478   SmallVector<MetadataBase *, 8> Elts;
479   do {
480     if (Lex.getKind() != lltok::Metadata)
481       return TokError("Expected '!' here");
482     Lex.Lex();
483     MetadataBase *N = 0;
484     if (ParseMDNode(N)) return true;
485     Elts.push_back(N);
486   } while (EatIfPresent(lltok::comma));
487
488   if (ParseToken(lltok::rbrace, "expected end of metadata node"))
489     return true;
490
491   NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
492   return false;
493 }
494
495 /// ParseStandaloneMetadata:
496 ///   !42 = !{...} 
497 bool LLParser::ParseStandaloneMetadata() {
498   assert(Lex.getKind() == lltok::Metadata);
499   Lex.Lex();
500   unsigned MetadataID = 0;
501   if (ParseUInt32(MetadataID))
502     return true;
503   if (MetadataCache.find(MetadataID) != MetadataCache.end())
504     return TokError("Metadata id is already used");
505   if (ParseToken(lltok::equal, "expected '=' here"))
506     return true;
507
508   LocTy TyLoc;
509   PATypeHolder Ty(Type::getVoidTy(Context));
510   if (ParseType(Ty, TyLoc))
511     return true;
512   
513   if (Lex.getKind() != lltok::Metadata)
514     return TokError("Expected metadata here");
515
516   Lex.Lex();
517   if (Lex.getKind() != lltok::lbrace)
518     return TokError("Expected '{' here");
519
520   SmallVector<Value *, 16> Elts;
521   if (ParseMDNodeVector(Elts) 
522       || ParseToken(lltok::rbrace, "expected end of metadata node"))
523     return true;
524
525   MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
526   MetadataCache[MetadataID] = Init;
527   std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
528     FI = ForwardRefMDNodes.find(MetadataID);
529   if (FI != ForwardRefMDNodes.end()) {
530     MDNode *FwdNode = cast<MDNode>(FI->second.first);
531     FwdNode->replaceAllUsesWith(Init);
532     ForwardRefMDNodes.erase(FI);
533   }
534
535   return false;
536 }
537
538 /// ParseAlias:
539 ///   ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
540 /// Aliasee
541 ///   ::= TypeAndValue
542 ///   ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
543 ///   ::= 'getelementptr' 'inbounds'? '(' ... ')'
544 ///
545 /// Everything through visibility has already been parsed.
546 ///
547 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
548                           unsigned Visibility) {
549   assert(Lex.getKind() == lltok::kw_alias);
550   Lex.Lex();
551   unsigned Linkage;
552   LocTy LinkageLoc = Lex.getLoc();
553   if (ParseOptionalLinkage(Linkage))
554     return true;
555
556   if (Linkage != GlobalValue::ExternalLinkage &&
557       Linkage != GlobalValue::WeakAnyLinkage &&
558       Linkage != GlobalValue::WeakODRLinkage &&
559       Linkage != GlobalValue::InternalLinkage &&
560       Linkage != GlobalValue::PrivateLinkage &&
561       Linkage != GlobalValue::LinkerPrivateLinkage)
562     return Error(LinkageLoc, "invalid linkage type for alias");
563   
564   Constant *Aliasee;
565   LocTy AliaseeLoc = Lex.getLoc();
566   if (Lex.getKind() != lltok::kw_bitcast &&
567       Lex.getKind() != lltok::kw_getelementptr) {
568     if (ParseGlobalTypeAndValue(Aliasee)) return true;
569   } else {
570     // The bitcast dest type is not present, it is implied by the dest type.
571     ValID ID;
572     if (ParseValID(ID)) return true;
573     if (ID.Kind != ValID::t_Constant)
574       return Error(AliaseeLoc, "invalid aliasee");
575     Aliasee = ID.ConstantVal;
576   }
577   
578   if (!isa<PointerType>(Aliasee->getType()))
579     return Error(AliaseeLoc, "alias must have pointer type");
580
581   // Okay, create the alias but do not insert it into the module yet.
582   GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
583                                     (GlobalValue::LinkageTypes)Linkage, Name,
584                                     Aliasee);
585   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
586   
587   // See if this value already exists in the symbol table.  If so, it is either
588   // a redefinition or a definition of a forward reference.
589   if (GlobalValue *Val =
590         cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
591     // See if this was a redefinition.  If so, there is no entry in
592     // ForwardRefVals.
593     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
594       I = ForwardRefVals.find(Name);
595     if (I == ForwardRefVals.end())
596       return Error(NameLoc, "redefinition of global named '@" + Name + "'");
597
598     // Otherwise, this was a definition of forward ref.  Verify that types
599     // agree.
600     if (Val->getType() != GA->getType())
601       return Error(NameLoc,
602               "forward reference and definition of alias have different types");
603     
604     // If they agree, just RAUW the old value with the alias and remove the
605     // forward ref info.
606     Val->replaceAllUsesWith(GA);
607     Val->eraseFromParent();
608     ForwardRefVals.erase(I);
609   }
610   
611   // Insert into the module, we know its name won't collide now.
612   M->getAliasList().push_back(GA);
613   assert(GA->getNameStr() == Name && "Should not be a name conflict!");
614   
615   return false;
616 }
617
618 /// ParseGlobal
619 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
620 ///       OptionalAddrSpace GlobalType Type Const
621 ///   ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
622 ///       OptionalAddrSpace GlobalType Type Const
623 ///
624 /// Everything through visibility has been parsed already.
625 ///
626 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
627                            unsigned Linkage, bool HasLinkage,
628                            unsigned Visibility) {
629   unsigned AddrSpace;
630   bool ThreadLocal, IsConstant;
631   LocTy TyLoc;
632     
633   PATypeHolder Ty(Type::getVoidTy(Context));
634   if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
635       ParseOptionalAddrSpace(AddrSpace) ||
636       ParseGlobalType(IsConstant) ||
637       ParseType(Ty, TyLoc))
638     return true;
639   
640   // If the linkage is specified and is external, then no initializer is
641   // present.
642   Constant *Init = 0;
643   if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
644                       Linkage != GlobalValue::ExternalWeakLinkage &&
645                       Linkage != GlobalValue::ExternalLinkage)) {
646     if (ParseGlobalValue(Ty, Init))
647       return true;
648   }
649
650   if (isa<FunctionType>(Ty) || Ty == Type::getLabelTy(Context))
651     return Error(TyLoc, "invalid type for global variable");
652   
653   GlobalVariable *GV = 0;
654
655   // See if the global was forward referenced, if so, use the global.
656   if (!Name.empty()) {
657     if ((GV = M->getGlobalVariable(Name, true)) &&
658         !ForwardRefVals.erase(Name))
659       return Error(NameLoc, "redefinition of global '@" + Name + "'");
660   } else {
661     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
662       I = ForwardRefValIDs.find(NumberedVals.size());
663     if (I != ForwardRefValIDs.end()) {
664       GV = cast<GlobalVariable>(I->second.first);
665       ForwardRefValIDs.erase(I);
666     }
667   }
668
669   if (GV == 0) {
670     GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0, 
671                             Name, 0, false, AddrSpace);
672   } else {
673     if (GV->getType()->getElementType() != Ty)
674       return Error(TyLoc,
675             "forward reference and definition of global have different types");
676     
677     // Move the forward-reference to the correct spot in the module.
678     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
679   }
680
681   if (Name.empty())
682     NumberedVals.push_back(GV);
683   
684   // Set the parsed properties on the global.
685   if (Init)
686     GV->setInitializer(Init);
687   GV->setConstant(IsConstant);
688   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
689   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
690   GV->setThreadLocal(ThreadLocal);
691   
692   // Parse attributes on the global.
693   while (Lex.getKind() == lltok::comma) {
694     Lex.Lex();
695     
696     if (Lex.getKind() == lltok::kw_section) {
697       Lex.Lex();
698       GV->setSection(Lex.getStrVal());
699       if (ParseToken(lltok::StringConstant, "expected global section string"))
700         return true;
701     } else if (Lex.getKind() == lltok::kw_align) {
702       unsigned Alignment;
703       if (ParseOptionalAlignment(Alignment)) return true;
704       GV->setAlignment(Alignment);
705     } else {
706       TokError("unknown global variable property!");
707     }
708   }
709   
710   return false;
711 }
712
713
714 //===----------------------------------------------------------------------===//
715 // GlobalValue Reference/Resolution Routines.
716 //===----------------------------------------------------------------------===//
717
718 /// GetGlobalVal - Get a value with the specified name or ID, creating a
719 /// forward reference record if needed.  This can return null if the value
720 /// exists but does not have the right type.
721 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
722                                     LocTy Loc) {
723   const PointerType *PTy = dyn_cast<PointerType>(Ty);
724   if (PTy == 0) {
725     Error(Loc, "global variable reference must have pointer type");
726     return 0;
727   }
728   
729   // Look this name up in the normal function symbol table.
730   GlobalValue *Val =
731     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
732   
733   // If this is a forward reference for the value, see if we already created a
734   // forward ref record.
735   if (Val == 0) {
736     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
737       I = ForwardRefVals.find(Name);
738     if (I != ForwardRefVals.end())
739       Val = I->second.first;
740   }
741   
742   // If we have the value in the symbol table or fwd-ref table, return it.
743   if (Val) {
744     if (Val->getType() == Ty) return Val;
745     Error(Loc, "'@" + Name + "' defined with type '" +
746           Val->getType()->getDescription() + "'");
747     return 0;
748   }
749   
750   // Otherwise, create a new forward reference for this value and remember it.
751   GlobalValue *FwdVal;
752   if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
753     // Function types can return opaque but functions can't.
754     if (isa<OpaqueType>(FT->getReturnType())) {
755       Error(Loc, "function may not return opaque type");
756       return 0;
757     }
758     
759     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
760   } else {
761     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
762                                 GlobalValue::ExternalWeakLinkage, 0, Name);
763   }
764   
765   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
766   return FwdVal;
767 }
768
769 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
770   const PointerType *PTy = dyn_cast<PointerType>(Ty);
771   if (PTy == 0) {
772     Error(Loc, "global variable reference must have pointer type");
773     return 0;
774   }
775   
776   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
777   
778   // If this is a forward reference for the value, see if we already created a
779   // forward ref record.
780   if (Val == 0) {
781     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
782       I = ForwardRefValIDs.find(ID);
783     if (I != ForwardRefValIDs.end())
784       Val = I->second.first;
785   }
786   
787   // If we have the value in the symbol table or fwd-ref table, return it.
788   if (Val) {
789     if (Val->getType() == Ty) return Val;
790     Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
791           Val->getType()->getDescription() + "'");
792     return 0;
793   }
794   
795   // Otherwise, create a new forward reference for this value and remember it.
796   GlobalValue *FwdVal;
797   if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
798     // Function types can return opaque but functions can't.
799     if (isa<OpaqueType>(FT->getReturnType())) {
800       Error(Loc, "function may not return opaque type");
801       return 0;
802     }
803     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
804   } else {
805     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
806                                 GlobalValue::ExternalWeakLinkage, 0, "");
807   }
808   
809   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
810   return FwdVal;
811 }
812
813
814 //===----------------------------------------------------------------------===//
815 // Helper Routines.
816 //===----------------------------------------------------------------------===//
817
818 /// ParseToken - If the current token has the specified kind, eat it and return
819 /// success.  Otherwise, emit the specified error and return failure.
820 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
821   if (Lex.getKind() != T)
822     return TokError(ErrMsg);
823   Lex.Lex();
824   return false;
825 }
826
827 /// ParseStringConstant
828 ///   ::= StringConstant
829 bool LLParser::ParseStringConstant(std::string &Result) {
830   if (Lex.getKind() != lltok::StringConstant)
831     return TokError("expected string constant");
832   Result = Lex.getStrVal();
833   Lex.Lex();
834   return false;
835 }
836
837 /// ParseUInt32
838 ///   ::= uint32
839 bool LLParser::ParseUInt32(unsigned &Val) {
840   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
841     return TokError("expected integer");
842   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
843   if (Val64 != unsigned(Val64))
844     return TokError("expected 32-bit integer (too large)");
845   Val = Val64;
846   Lex.Lex();
847   return false;
848 }
849
850
851 /// ParseOptionalAddrSpace
852 ///   := /*empty*/
853 ///   := 'addrspace' '(' uint32 ')'
854 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
855   AddrSpace = 0;
856   if (!EatIfPresent(lltok::kw_addrspace))
857     return false;
858   return ParseToken(lltok::lparen, "expected '(' in address space") ||
859          ParseUInt32(AddrSpace) ||
860          ParseToken(lltok::rparen, "expected ')' in address space");
861 }  
862
863 /// ParseOptionalAttrs - Parse a potentially empty attribute list.  AttrKind
864 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
865 /// 2: function attr.
866 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
867 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
868   Attrs = Attribute::None;
869   LocTy AttrLoc = Lex.getLoc();
870   
871   while (1) {
872     switch (Lex.getKind()) {
873     case lltok::kw_sext:
874     case lltok::kw_zext:
875       // Treat these as signext/zeroext if they occur in the argument list after
876       // the value, as in "call i8 @foo(i8 10 sext)".  If they occur before the
877       // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
878       // expr.
879       // FIXME: REMOVE THIS IN LLVM 3.0
880       if (AttrKind == 3) {
881         if (Lex.getKind() == lltok::kw_sext)
882           Attrs |= Attribute::SExt;
883         else
884           Attrs |= Attribute::ZExt;
885         break;
886       }
887       // FALL THROUGH.
888     default:  // End of attributes.
889       if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
890         return Error(AttrLoc, "invalid use of function-only attribute");
891         
892       if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
893         return Error(AttrLoc, "invalid use of parameter-only attribute");
894         
895       return false;
896     case lltok::kw_zeroext:         Attrs |= Attribute::ZExt; break;
897     case lltok::kw_signext:         Attrs |= Attribute::SExt; break;
898     case lltok::kw_inreg:           Attrs |= Attribute::InReg; break;
899     case lltok::kw_sret:            Attrs |= Attribute::StructRet; break;
900     case lltok::kw_noalias:         Attrs |= Attribute::NoAlias; break;
901     case lltok::kw_nocapture:       Attrs |= Attribute::NoCapture; break;
902     case lltok::kw_byval:           Attrs |= Attribute::ByVal; break;
903     case lltok::kw_nest:            Attrs |= Attribute::Nest; break;
904
905     case lltok::kw_noreturn:        Attrs |= Attribute::NoReturn; break;
906     case lltok::kw_nounwind:        Attrs |= Attribute::NoUnwind; break;
907     case lltok::kw_noinline:        Attrs |= Attribute::NoInline; break;
908     case lltok::kw_readnone:        Attrs |= Attribute::ReadNone; break;
909     case lltok::kw_readonly:        Attrs |= Attribute::ReadOnly; break;
910     case lltok::kw_inlinehint:      Attrs |= Attribute::InlineHint; break;
911     case lltok::kw_alwaysinline:    Attrs |= Attribute::AlwaysInline; break;
912     case lltok::kw_optsize:         Attrs |= Attribute::OptimizeForSize; break;
913     case lltok::kw_ssp:             Attrs |= Attribute::StackProtect; break;
914     case lltok::kw_sspreq:          Attrs |= Attribute::StackProtectReq; break;
915     case lltok::kw_noredzone:       Attrs |= Attribute::NoRedZone; break;
916     case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
917     case lltok::kw_naked:           Attrs |= Attribute::Naked; break;
918         
919     case lltok::kw_align: {
920       unsigned Alignment;
921       if (ParseOptionalAlignment(Alignment))
922         return true;
923       Attrs |= Attribute::constructAlignmentFromInt(Alignment);
924       continue;
925     }
926     }
927     Lex.Lex();
928   }
929 }
930
931 /// ParseOptionalLinkage
932 ///   ::= /*empty*/
933 ///   ::= 'private'
934 ///   ::= 'linker_private'
935 ///   ::= 'internal'
936 ///   ::= 'weak'
937 ///   ::= 'weak_odr'
938 ///   ::= 'linkonce'
939 ///   ::= 'linkonce_odr'
940 ///   ::= 'appending'
941 ///   ::= 'dllexport'
942 ///   ::= 'common'
943 ///   ::= 'dllimport'
944 ///   ::= 'extern_weak'
945 ///   ::= 'external'
946 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
947   HasLinkage = false;
948   switch (Lex.getKind()) {
949   default:                       Res=GlobalValue::ExternalLinkage; return false;
950   case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
951   case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
952   case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
953   case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
954   case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
955   case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
956   case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
957   case lltok::kw_available_externally:
958     Res = GlobalValue::AvailableExternallyLinkage;
959     break;
960   case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
961   case lltok::kw_dllexport:      Res = GlobalValue::DLLExportLinkage;     break;
962   case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
963   case lltok::kw_dllimport:      Res = GlobalValue::DLLImportLinkage;     break;
964   case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
965   case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
966   }
967   Lex.Lex();
968   HasLinkage = true;
969   return false;
970 }
971
972 /// ParseOptionalVisibility
973 ///   ::= /*empty*/
974 ///   ::= 'default'
975 ///   ::= 'hidden'
976 ///   ::= 'protected'
977 /// 
978 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
979   switch (Lex.getKind()) {
980   default:                  Res = GlobalValue::DefaultVisibility; return false;
981   case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
982   case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
983   case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
984   }
985   Lex.Lex();
986   return false;
987 }
988
989 /// ParseOptionalCallingConv
990 ///   ::= /*empty*/
991 ///   ::= 'ccc'
992 ///   ::= 'fastcc'
993 ///   ::= 'coldcc'
994 ///   ::= 'x86_stdcallcc'
995 ///   ::= 'x86_fastcallcc'
996 ///   ::= 'arm_apcscc'
997 ///   ::= 'arm_aapcscc'
998 ///   ::= 'arm_aapcs_vfpcc'
999 ///   ::= 'cc' UINT
1000 ///
1001 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1002   switch (Lex.getKind()) {
1003   default:                       CC = CallingConv::C; return false;
1004   case lltok::kw_ccc:            CC = CallingConv::C; break;
1005   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1006   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1007   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1008   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1009   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1010   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1011   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1012   case lltok::kw_cc:             Lex.Lex(); return ParseUInt32(CC);
1013   }
1014   Lex.Lex();
1015   return false;
1016 }
1017
1018 /// ParseOptionalAlignment
1019 ///   ::= /* empty */
1020 ///   ::= 'align' 4
1021 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1022   Alignment = 0;
1023   if (!EatIfPresent(lltok::kw_align))
1024     return false;
1025   LocTy AlignLoc = Lex.getLoc();
1026   if (ParseUInt32(Alignment)) return true;
1027   if (!isPowerOf2_32(Alignment))
1028     return Error(AlignLoc, "alignment is not a power of two");
1029   return false;
1030 }
1031
1032 /// ParseOptionalCommaAlignment
1033 ///   ::= /* empty */
1034 ///   ::= ',' 'align' 4
1035 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
1036   Alignment = 0;
1037   if (!EatIfPresent(lltok::comma))
1038     return false;
1039   return ParseToken(lltok::kw_align, "expected 'align'") ||
1040          ParseUInt32(Alignment);
1041 }
1042
1043 /// ParseIndexList
1044 ///    ::=  (',' uint32)+
1045 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1046   if (Lex.getKind() != lltok::comma)
1047     return TokError("expected ',' as start of index list");
1048   
1049   while (EatIfPresent(lltok::comma)) {
1050     unsigned Idx;
1051     if (ParseUInt32(Idx)) return true;
1052     Indices.push_back(Idx);
1053   }
1054   
1055   return false;
1056 }
1057
1058 //===----------------------------------------------------------------------===//
1059 // Type Parsing.
1060 //===----------------------------------------------------------------------===//
1061
1062 /// ParseType - Parse and resolve a full type.
1063 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1064   LocTy TypeLoc = Lex.getLoc();
1065   if (ParseTypeRec(Result)) return true;
1066   
1067   // Verify no unresolved uprefs.
1068   if (!UpRefs.empty())
1069     return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1070   
1071   if (!AllowVoid && Result.get() == Type::getVoidTy(Context))
1072     return Error(TypeLoc, "void type only allowed for function results");
1073   
1074   return false;
1075 }
1076
1077 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1078 /// called.  It loops through the UpRefs vector, which is a list of the
1079 /// currently active types.  For each type, if the up-reference is contained in
1080 /// the newly completed type, we decrement the level count.  When the level
1081 /// count reaches zero, the up-referenced type is the type that is passed in:
1082 /// thus we can complete the cycle.
1083 ///
1084 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1085   // If Ty isn't abstract, or if there are no up-references in it, then there is
1086   // nothing to resolve here.
1087   if (!ty->isAbstract() || UpRefs.empty()) return ty;
1088   
1089   PATypeHolder Ty(ty);
1090 #if 0
1091   errs() << "Type '" << Ty->getDescription()
1092          << "' newly formed.  Resolving upreferences.\n"
1093          << UpRefs.size() << " upreferences active!\n";
1094 #endif
1095   
1096   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1097   // to zero), we resolve them all together before we resolve them to Ty.  At
1098   // the end of the loop, if there is anything to resolve to Ty, it will be in
1099   // this variable.
1100   OpaqueType *TypeToResolve = 0;
1101   
1102   for (unsigned i = 0; i != UpRefs.size(); ++i) {
1103     // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1104     bool ContainsType =
1105       std::find(Ty->subtype_begin(), Ty->subtype_end(),
1106                 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1107     
1108 #if 0
1109     errs() << "  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1110            << UpRefs[i].LastContainedTy->getDescription() << ") = "
1111            << (ContainsType ? "true" : "false")
1112            << " level=" << UpRefs[i].NestingLevel << "\n";
1113 #endif
1114     if (!ContainsType)
1115       continue;
1116     
1117     // Decrement level of upreference
1118     unsigned Level = --UpRefs[i].NestingLevel;
1119     UpRefs[i].LastContainedTy = Ty;
1120     
1121     // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1122     if (Level != 0)
1123       continue;
1124     
1125 #if 0
1126     errs() << "  * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1127 #endif
1128     if (!TypeToResolve)
1129       TypeToResolve = UpRefs[i].UpRefTy;
1130     else
1131       UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1132     UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list.
1133     --i;                                // Do not skip the next element.
1134   }
1135   
1136   if (TypeToResolve)
1137     TypeToResolve->refineAbstractTypeTo(Ty);
1138   
1139   return Ty;
1140 }
1141
1142
1143 /// ParseTypeRec - The recursive function used to process the internal
1144 /// implementation details of types.
1145 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1146   switch (Lex.getKind()) {
1147   default:
1148     return TokError("expected type");
1149   case lltok::Type:
1150     // TypeRec ::= 'float' | 'void' (etc)
1151     Result = Lex.getTyVal();
1152     Lex.Lex(); 
1153     break;
1154   case lltok::kw_opaque:
1155     // TypeRec ::= 'opaque'
1156     Result = OpaqueType::get(Context);
1157     Lex.Lex();
1158     break;
1159   case lltok::lbrace:
1160     // TypeRec ::= '{' ... '}'
1161     if (ParseStructType(Result, false))
1162       return true;
1163     break;
1164   case lltok::lsquare:
1165     // TypeRec ::= '[' ... ']'
1166     Lex.Lex(); // eat the lsquare.
1167     if (ParseArrayVectorType(Result, false))
1168       return true;
1169     break;
1170   case lltok::less: // Either vector or packed struct.
1171     // TypeRec ::= '<' ... '>'
1172     Lex.Lex();
1173     if (Lex.getKind() == lltok::lbrace) {
1174       if (ParseStructType(Result, true) ||
1175           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1176         return true;
1177     } else if (ParseArrayVectorType(Result, true))
1178       return true;
1179     break;
1180   case lltok::LocalVar:
1181   case lltok::StringConstant:  // FIXME: REMOVE IN LLVM 3.0
1182     // TypeRec ::= %foo
1183     if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1184       Result = T;
1185     } else {
1186       Result = OpaqueType::get(Context);
1187       ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1188                                             std::make_pair(Result,
1189                                                            Lex.getLoc())));
1190       M->addTypeName(Lex.getStrVal(), Result.get());
1191     }
1192     Lex.Lex();
1193     break;
1194       
1195   case lltok::LocalVarID:
1196     // TypeRec ::= %4
1197     if (Lex.getUIntVal() < NumberedTypes.size())
1198       Result = NumberedTypes[Lex.getUIntVal()];
1199     else {
1200       std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1201         I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1202       if (I != ForwardRefTypeIDs.end())
1203         Result = I->second.first;
1204       else {
1205         Result = OpaqueType::get(Context);
1206         ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1207                                                 std::make_pair(Result,
1208                                                                Lex.getLoc())));
1209       }
1210     }
1211     Lex.Lex();
1212     break;
1213   case lltok::backslash: {
1214     // TypeRec ::= '\' 4
1215     Lex.Lex();
1216     unsigned Val;
1217     if (ParseUInt32(Val)) return true;
1218     OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1219     UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1220     Result = OT;
1221     break;
1222   }
1223   }
1224   
1225   // Parse the type suffixes. 
1226   while (1) {
1227     switch (Lex.getKind()) {
1228     // End of type.
1229     default: return false;    
1230
1231     // TypeRec ::= TypeRec '*'
1232     case lltok::star:
1233       if (Result.get() == Type::getLabelTy(Context))
1234         return TokError("basic block pointers are invalid");
1235       if (Result.get() == Type::getVoidTy(Context))
1236         return TokError("pointers to void are invalid; use i8* instead");
1237       if (!PointerType::isValidElementType(Result.get()))
1238         return TokError("pointer to this type is invalid");
1239       Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1240       Lex.Lex();
1241       break;
1242
1243     // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1244     case lltok::kw_addrspace: {
1245       if (Result.get() == Type::getLabelTy(Context))
1246         return TokError("basic block pointers are invalid");
1247       if (Result.get() == Type::getVoidTy(Context))
1248         return TokError("pointers to void are invalid; use i8* instead");
1249       if (!PointerType::isValidElementType(Result.get()))
1250         return TokError("pointer to this type is invalid");
1251       unsigned AddrSpace;
1252       if (ParseOptionalAddrSpace(AddrSpace) ||
1253           ParseToken(lltok::star, "expected '*' in address space"))
1254         return true;
1255
1256       Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1257       break;
1258     }
1259         
1260     /// Types '(' ArgTypeListI ')' OptFuncAttrs
1261     case lltok::lparen:
1262       if (ParseFunctionType(Result))
1263         return true;
1264       break;
1265     }
1266   }
1267 }
1268
1269 /// ParseParameterList
1270 ///    ::= '(' ')'
1271 ///    ::= '(' Arg (',' Arg)* ')'
1272 ///  Arg
1273 ///    ::= Type OptionalAttributes Value OptionalAttributes
1274 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1275                                   PerFunctionState &PFS) {
1276   if (ParseToken(lltok::lparen, "expected '(' in call"))
1277     return true;
1278   
1279   while (Lex.getKind() != lltok::rparen) {
1280     // If this isn't the first argument, we need a comma.
1281     if (!ArgList.empty() &&
1282         ParseToken(lltok::comma, "expected ',' in argument list"))
1283       return true;
1284     
1285     // Parse the argument.
1286     LocTy ArgLoc;
1287     PATypeHolder ArgTy(Type::getVoidTy(Context));
1288     unsigned ArgAttrs1, ArgAttrs2;
1289     Value *V;
1290     if (ParseType(ArgTy, ArgLoc) ||
1291         ParseOptionalAttrs(ArgAttrs1, 0) ||
1292         ParseValue(ArgTy, V, PFS) ||
1293         // FIXME: Should not allow attributes after the argument, remove this in
1294         // LLVM 3.0.
1295         ParseOptionalAttrs(ArgAttrs2, 3))
1296       return true;
1297     ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1298   }
1299
1300   Lex.Lex();  // Lex the ')'.
1301   return false;
1302 }
1303
1304
1305
1306 /// ParseArgumentList - Parse the argument list for a function type or function
1307 /// prototype.  If 'inType' is true then we are parsing a FunctionType.
1308 ///   ::= '(' ArgTypeListI ')'
1309 /// ArgTypeListI
1310 ///   ::= /*empty*/
1311 ///   ::= '...'
1312 ///   ::= ArgTypeList ',' '...'
1313 ///   ::= ArgType (',' ArgType)*
1314 ///
1315 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1316                                  bool &isVarArg, bool inType) {
1317   isVarArg = false;
1318   assert(Lex.getKind() == lltok::lparen);
1319   Lex.Lex(); // eat the (.
1320   
1321   if (Lex.getKind() == lltok::rparen) {
1322     // empty
1323   } else if (Lex.getKind() == lltok::dotdotdot) {
1324     isVarArg = true;
1325     Lex.Lex();
1326   } else {
1327     LocTy TypeLoc = Lex.getLoc();
1328     PATypeHolder ArgTy(Type::getVoidTy(Context));
1329     unsigned Attrs;
1330     std::string Name;
1331     
1332     // If we're parsing a type, use ParseTypeRec, because we allow recursive
1333     // types (such as a function returning a pointer to itself).  If parsing a
1334     // function prototype, we require fully resolved types.
1335     if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1336         ParseOptionalAttrs(Attrs, 0)) return true;
1337     
1338     if (ArgTy == Type::getVoidTy(Context))
1339       return Error(TypeLoc, "argument can not have void type");
1340     
1341     if (Lex.getKind() == lltok::LocalVar ||
1342         Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1343       Name = Lex.getStrVal();
1344       Lex.Lex();
1345     }
1346
1347     if (!FunctionType::isValidArgumentType(ArgTy))
1348       return Error(TypeLoc, "invalid type for function argument");
1349     
1350     ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1351     
1352     while (EatIfPresent(lltok::comma)) {
1353       // Handle ... at end of arg list.
1354       if (EatIfPresent(lltok::dotdotdot)) {
1355         isVarArg = true;
1356         break;
1357       }
1358       
1359       // Otherwise must be an argument type.
1360       TypeLoc = Lex.getLoc();
1361       if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1362           ParseOptionalAttrs(Attrs, 0)) return true;
1363
1364       if (ArgTy == Type::getVoidTy(Context))
1365         return Error(TypeLoc, "argument can not have void type");
1366
1367       if (Lex.getKind() == lltok::LocalVar ||
1368           Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1369         Name = Lex.getStrVal();
1370         Lex.Lex();
1371       } else {
1372         Name = "";
1373       }
1374
1375       if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1376         return Error(TypeLoc, "invalid type for function argument");
1377       
1378       ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1379     }
1380   }
1381   
1382   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1383 }
1384   
1385 /// ParseFunctionType
1386 ///  ::= Type ArgumentList OptionalAttrs
1387 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1388   assert(Lex.getKind() == lltok::lparen);
1389
1390   if (!FunctionType::isValidReturnType(Result))
1391     return TokError("invalid function return type");
1392   
1393   std::vector<ArgInfo> ArgList;
1394   bool isVarArg;
1395   unsigned Attrs;
1396   if (ParseArgumentList(ArgList, isVarArg, true) ||
1397       // FIXME: Allow, but ignore attributes on function types!
1398       // FIXME: Remove in LLVM 3.0
1399       ParseOptionalAttrs(Attrs, 2))
1400     return true;
1401   
1402   // Reject names on the arguments lists.
1403   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1404     if (!ArgList[i].Name.empty())
1405       return Error(ArgList[i].Loc, "argument name invalid in function type");
1406     if (!ArgList[i].Attrs != 0) {
1407       // Allow but ignore attributes on function types; this permits
1408       // auto-upgrade.
1409       // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1410     }
1411   }
1412   
1413   std::vector<const Type*> ArgListTy;
1414   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1415     ArgListTy.push_back(ArgList[i].Type);
1416     
1417   Result = HandleUpRefs(FunctionType::get(Result.get(),
1418                                                 ArgListTy, isVarArg));
1419   return false;
1420 }
1421
1422 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
1423 ///   TypeRec
1424 ///     ::= '{' '}'
1425 ///     ::= '{' TypeRec (',' TypeRec)* '}'
1426 ///     ::= '<' '{' '}' '>'
1427 ///     ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1428 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1429   assert(Lex.getKind() == lltok::lbrace);
1430   Lex.Lex(); // Consume the '{'
1431   
1432   if (EatIfPresent(lltok::rbrace)) {
1433     Result = StructType::get(Context, Packed);
1434     return false;
1435   }
1436
1437   std::vector<PATypeHolder> ParamsList;
1438   LocTy EltTyLoc = Lex.getLoc();
1439   if (ParseTypeRec(Result)) return true;
1440   ParamsList.push_back(Result);
1441   
1442   if (Result == Type::getVoidTy(Context))
1443     return Error(EltTyLoc, "struct element can not have void type");
1444   if (!StructType::isValidElementType(Result))
1445     return Error(EltTyLoc, "invalid element type for struct");
1446   
1447   while (EatIfPresent(lltok::comma)) {
1448     EltTyLoc = Lex.getLoc();
1449     if (ParseTypeRec(Result)) return true;
1450     
1451     if (Result == Type::getVoidTy(Context))
1452       return Error(EltTyLoc, "struct element can not have void type");
1453     if (!StructType::isValidElementType(Result))
1454       return Error(EltTyLoc, "invalid element type for struct");
1455     
1456     ParamsList.push_back(Result);
1457   }
1458   
1459   if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1460     return true;
1461   
1462   std::vector<const Type*> ParamsListTy;
1463   for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1464     ParamsListTy.push_back(ParamsList[i].get());
1465   Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1466   return false;
1467 }
1468
1469 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1470 /// token has already been consumed.
1471 ///   TypeRec 
1472 ///     ::= '[' APSINTVAL 'x' Types ']'
1473 ///     ::= '<' APSINTVAL 'x' Types '>'
1474 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1475   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1476       Lex.getAPSIntVal().getBitWidth() > 64)
1477     return TokError("expected number in address space");
1478   
1479   LocTy SizeLoc = Lex.getLoc();
1480   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1481   Lex.Lex();
1482       
1483   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1484       return true;
1485
1486   LocTy TypeLoc = Lex.getLoc();
1487   PATypeHolder EltTy(Type::getVoidTy(Context));
1488   if (ParseTypeRec(EltTy)) return true;
1489   
1490   if (EltTy == Type::getVoidTy(Context))
1491     return Error(TypeLoc, "array and vector element type cannot be void");
1492
1493   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1494                  "expected end of sequential type"))
1495     return true;
1496   
1497   if (isVector) {
1498     if (Size == 0)
1499       return Error(SizeLoc, "zero element vector is illegal");
1500     if ((unsigned)Size != Size)
1501       return Error(SizeLoc, "size too large for vector");
1502     if (!VectorType::isValidElementType(EltTy))
1503       return Error(TypeLoc, "vector element type must be fp or integer");
1504     Result = VectorType::get(EltTy, unsigned(Size));
1505   } else {
1506     if (!ArrayType::isValidElementType(EltTy))
1507       return Error(TypeLoc, "invalid array element type");
1508     Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1509   }
1510   return false;
1511 }
1512
1513 //===----------------------------------------------------------------------===//
1514 // Function Semantic Analysis.
1515 //===----------------------------------------------------------------------===//
1516
1517 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1518   : P(p), F(f) {
1519
1520   // Insert unnamed arguments into the NumberedVals list.
1521   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1522        AI != E; ++AI)
1523     if (!AI->hasName())
1524       NumberedVals.push_back(AI);
1525 }
1526
1527 LLParser::PerFunctionState::~PerFunctionState() {
1528   // If there were any forward referenced non-basicblock values, delete them.
1529   for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1530        I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1531     if (!isa<BasicBlock>(I->second.first)) {
1532       I->second.first->replaceAllUsesWith(
1533                            UndefValue::get(I->second.first->getType()));
1534       delete I->second.first;
1535       I->second.first = 0;
1536     }
1537   
1538   for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1539        I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1540     if (!isa<BasicBlock>(I->second.first)) {
1541       I->second.first->replaceAllUsesWith(
1542                            UndefValue::get(I->second.first->getType()));
1543       delete I->second.first;
1544       I->second.first = 0;
1545     }
1546 }
1547
1548 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1549   if (!ForwardRefVals.empty())
1550     return P.Error(ForwardRefVals.begin()->second.second,
1551                    "use of undefined value '%" + ForwardRefVals.begin()->first +
1552                    "'");
1553   if (!ForwardRefValIDs.empty())
1554     return P.Error(ForwardRefValIDs.begin()->second.second,
1555                    "use of undefined value '%" +
1556                    utostr(ForwardRefValIDs.begin()->first) + "'");
1557   return false;
1558 }
1559
1560
1561 /// GetVal - Get a value with the specified name or ID, creating a
1562 /// forward reference record if needed.  This can return null if the value
1563 /// exists but does not have the right type.
1564 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1565                                           const Type *Ty, LocTy Loc) {
1566   // Look this name up in the normal function symbol table.
1567   Value *Val = F.getValueSymbolTable().lookup(Name);
1568   
1569   // If this is a forward reference for the value, see if we already created a
1570   // forward ref record.
1571   if (Val == 0) {
1572     std::map<std::string, std::pair<Value*, LocTy> >::iterator
1573       I = ForwardRefVals.find(Name);
1574     if (I != ForwardRefVals.end())
1575       Val = I->second.first;
1576   }
1577     
1578   // If we have the value in the symbol table or fwd-ref table, return it.
1579   if (Val) {
1580     if (Val->getType() == Ty) return Val;
1581     if (Ty == Type::getLabelTy(F.getContext()))
1582       P.Error(Loc, "'%" + Name + "' is not a basic block");
1583     else
1584       P.Error(Loc, "'%" + Name + "' defined with type '" +
1585               Val->getType()->getDescription() + "'");
1586     return 0;
1587   }
1588   
1589   // Don't make placeholders with invalid type.
1590   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1591       Ty != Type::getLabelTy(F.getContext())) {
1592     P.Error(Loc, "invalid use of a non-first-class type");
1593     return 0;
1594   }
1595   
1596   // Otherwise, create a new forward reference for this value and remember it.
1597   Value *FwdVal;
1598   if (Ty == Type::getLabelTy(F.getContext())) 
1599     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1600   else
1601     FwdVal = new Argument(Ty, Name);
1602   
1603   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1604   return FwdVal;
1605 }
1606
1607 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1608                                           LocTy Loc) {
1609   // Look this name up in the normal function symbol table.
1610   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1611   
1612   // If this is a forward reference for the value, see if we already created a
1613   // forward ref record.
1614   if (Val == 0) {
1615     std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1616       I = ForwardRefValIDs.find(ID);
1617     if (I != ForwardRefValIDs.end())
1618       Val = I->second.first;
1619   }
1620   
1621   // If we have the value in the symbol table or fwd-ref table, return it.
1622   if (Val) {
1623     if (Val->getType() == Ty) return Val;
1624     if (Ty == Type::getLabelTy(F.getContext()))
1625       P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1626     else
1627       P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1628               Val->getType()->getDescription() + "'");
1629     return 0;
1630   }
1631   
1632   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1633       Ty != Type::getLabelTy(F.getContext())) {
1634     P.Error(Loc, "invalid use of a non-first-class type");
1635     return 0;
1636   }
1637   
1638   // Otherwise, create a new forward reference for this value and remember it.
1639   Value *FwdVal;
1640   if (Ty == Type::getLabelTy(F.getContext())) 
1641     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1642   else
1643     FwdVal = new Argument(Ty);
1644   
1645   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1646   return FwdVal;
1647 }
1648
1649 /// SetInstName - After an instruction is parsed and inserted into its
1650 /// basic block, this installs its name.
1651 bool LLParser::PerFunctionState::SetInstName(int NameID,
1652                                              const std::string &NameStr,
1653                                              LocTy NameLoc, Instruction *Inst) {
1654   // If this instruction has void type, it cannot have a name or ID specified.
1655   if (Inst->getType() == Type::getVoidTy(F.getContext())) {
1656     if (NameID != -1 || !NameStr.empty())
1657       return P.Error(NameLoc, "instructions returning void cannot have a name");
1658     return false;
1659   }
1660   
1661   // If this was a numbered instruction, verify that the instruction is the
1662   // expected value and resolve any forward references.
1663   if (NameStr.empty()) {
1664     // If neither a name nor an ID was specified, just use the next ID.
1665     if (NameID == -1)
1666       NameID = NumberedVals.size();
1667     
1668     if (unsigned(NameID) != NumberedVals.size())
1669       return P.Error(NameLoc, "instruction expected to be numbered '%" +
1670                      utostr(NumberedVals.size()) + "'");
1671     
1672     std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1673       ForwardRefValIDs.find(NameID);
1674     if (FI != ForwardRefValIDs.end()) {
1675       if (FI->second.first->getType() != Inst->getType())
1676         return P.Error(NameLoc, "instruction forward referenced with type '" + 
1677                        FI->second.first->getType()->getDescription() + "'");
1678       FI->second.first->replaceAllUsesWith(Inst);
1679       ForwardRefValIDs.erase(FI);
1680     }
1681
1682     NumberedVals.push_back(Inst);
1683     return false;
1684   }
1685
1686   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
1687   std::map<std::string, std::pair<Value*, LocTy> >::iterator
1688     FI = ForwardRefVals.find(NameStr);
1689   if (FI != ForwardRefVals.end()) {
1690     if (FI->second.first->getType() != Inst->getType())
1691       return P.Error(NameLoc, "instruction forward referenced with type '" + 
1692                      FI->second.first->getType()->getDescription() + "'");
1693     FI->second.first->replaceAllUsesWith(Inst);
1694     ForwardRefVals.erase(FI);
1695   }
1696   
1697   // Set the name on the instruction.
1698   Inst->setName(NameStr);
1699   
1700   if (Inst->getNameStr() != NameStr)
1701     return P.Error(NameLoc, "multiple definition of local value named '" + 
1702                    NameStr + "'");
1703   return false;
1704 }
1705
1706 /// GetBB - Get a basic block with the specified name or ID, creating a
1707 /// forward reference record if needed.
1708 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1709                                               LocTy Loc) {
1710   return cast_or_null<BasicBlock>(GetVal(Name,
1711                                         Type::getLabelTy(F.getContext()), Loc));
1712 }
1713
1714 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1715   return cast_or_null<BasicBlock>(GetVal(ID,
1716                                         Type::getLabelTy(F.getContext()), Loc));
1717 }
1718
1719 /// DefineBB - Define the specified basic block, which is either named or
1720 /// unnamed.  If there is an error, this returns null otherwise it returns
1721 /// the block being defined.
1722 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1723                                                  LocTy Loc) {
1724   BasicBlock *BB;
1725   if (Name.empty())
1726     BB = GetBB(NumberedVals.size(), Loc);
1727   else
1728     BB = GetBB(Name, Loc);
1729   if (BB == 0) return 0; // Already diagnosed error.
1730   
1731   // Move the block to the end of the function.  Forward ref'd blocks are
1732   // inserted wherever they happen to be referenced.
1733   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1734   
1735   // Remove the block from forward ref sets.
1736   if (Name.empty()) {
1737     ForwardRefValIDs.erase(NumberedVals.size());
1738     NumberedVals.push_back(BB);
1739   } else {
1740     // BB forward references are already in the function symbol table.
1741     ForwardRefVals.erase(Name);
1742   }
1743   
1744   return BB;
1745 }
1746
1747 //===----------------------------------------------------------------------===//
1748 // Constants.
1749 //===----------------------------------------------------------------------===//
1750
1751 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1752 /// type implied.  For example, if we parse "4" we don't know what integer type
1753 /// it has.  The value will later be combined with its type and checked for
1754 /// sanity.
1755 bool LLParser::ParseValID(ValID &ID) {
1756   ID.Loc = Lex.getLoc();
1757   switch (Lex.getKind()) {
1758   default: return TokError("expected value token");
1759   case lltok::GlobalID:  // @42
1760     ID.UIntVal = Lex.getUIntVal();
1761     ID.Kind = ValID::t_GlobalID;
1762     break;
1763   case lltok::GlobalVar:  // @foo
1764     ID.StrVal = Lex.getStrVal();
1765     ID.Kind = ValID::t_GlobalName;
1766     break;
1767   case lltok::LocalVarID:  // %42
1768     ID.UIntVal = Lex.getUIntVal();
1769     ID.Kind = ValID::t_LocalID;
1770     break;
1771   case lltok::LocalVar:  // %foo
1772   case lltok::StringConstant:  // "foo" - FIXME: REMOVE IN LLVM 3.0
1773     ID.StrVal = Lex.getStrVal();
1774     ID.Kind = ValID::t_LocalName;
1775     break;
1776   case lltok::Metadata: {  // !{...} MDNode, !"foo" MDString
1777     ID.Kind = ValID::t_Metadata;
1778     Lex.Lex();
1779     if (Lex.getKind() == lltok::lbrace) {
1780       SmallVector<Value*, 16> Elts;
1781       if (ParseMDNodeVector(Elts) ||
1782           ParseToken(lltok::rbrace, "expected end of metadata node"))
1783         return true;
1784
1785       ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
1786       return false;
1787     }
1788
1789     // Standalone metadata reference
1790     // !{ ..., !42, ... }
1791     if (!ParseMDNode(ID.MetadataVal))
1792       return false;
1793
1794     // MDString:
1795     //   ::= '!' STRINGCONSTANT
1796     if (ParseMDString(ID.MetadataVal)) return true;
1797     ID.Kind = ValID::t_Metadata;
1798     return false;
1799   }
1800   case lltok::APSInt:
1801     ID.APSIntVal = Lex.getAPSIntVal(); 
1802     ID.Kind = ValID::t_APSInt;
1803     break;
1804   case lltok::APFloat:
1805     ID.APFloatVal = Lex.getAPFloatVal();
1806     ID.Kind = ValID::t_APFloat;
1807     break;
1808   case lltok::kw_true:
1809     ID.ConstantVal = ConstantInt::getTrue(Context);
1810     ID.Kind = ValID::t_Constant;
1811     break;
1812   case lltok::kw_false:
1813     ID.ConstantVal = ConstantInt::getFalse(Context);
1814     ID.Kind = ValID::t_Constant;
1815     break;
1816   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1817   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1818   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1819       
1820   case lltok::lbrace: {
1821     // ValID ::= '{' ConstVector '}'
1822     Lex.Lex();
1823     SmallVector<Constant*, 16> Elts;
1824     if (ParseGlobalValueVector(Elts) ||
1825         ParseToken(lltok::rbrace, "expected end of struct constant"))
1826       return true;
1827     
1828     ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1829                                          Elts.size(), false);
1830     ID.Kind = ValID::t_Constant;
1831     return false;
1832   }
1833   case lltok::less: {
1834     // ValID ::= '<' ConstVector '>'         --> Vector.
1835     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1836     Lex.Lex();
1837     bool isPackedStruct = EatIfPresent(lltok::lbrace);
1838     
1839     SmallVector<Constant*, 16> Elts;
1840     LocTy FirstEltLoc = Lex.getLoc();
1841     if (ParseGlobalValueVector(Elts) ||
1842         (isPackedStruct &&
1843          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1844         ParseToken(lltok::greater, "expected end of constant"))
1845       return true;
1846     
1847     if (isPackedStruct) {
1848       ID.ConstantVal =
1849         ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
1850       ID.Kind = ValID::t_Constant;
1851       return false;
1852     }
1853     
1854     if (Elts.empty())
1855       return Error(ID.Loc, "constant vector must not be empty");
1856
1857     if (!Elts[0]->getType()->isInteger() &&
1858         !Elts[0]->getType()->isFloatingPoint())
1859       return Error(FirstEltLoc,
1860                    "vector elements must have integer or floating point type");
1861     
1862     // Verify that all the vector elements have the same type.
1863     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1864       if (Elts[i]->getType() != Elts[0]->getType())
1865         return Error(FirstEltLoc,
1866                      "vector element #" + utostr(i) +
1867                     " is not of type '" + Elts[0]->getType()->getDescription());
1868     
1869     ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
1870     ID.Kind = ValID::t_Constant;
1871     return false;
1872   }
1873   case lltok::lsquare: {   // Array Constant
1874     Lex.Lex();
1875     SmallVector<Constant*, 16> Elts;
1876     LocTy FirstEltLoc = Lex.getLoc();
1877     if (ParseGlobalValueVector(Elts) ||
1878         ParseToken(lltok::rsquare, "expected end of array constant"))
1879       return true;
1880
1881     // Handle empty element.
1882     if (Elts.empty()) {
1883       // Use undef instead of an array because it's inconvenient to determine
1884       // the element type at this point, there being no elements to examine.
1885       ID.Kind = ValID::t_EmptyArray;
1886       return false;
1887     }
1888     
1889     if (!Elts[0]->getType()->isFirstClassType())
1890       return Error(FirstEltLoc, "invalid array element type: " + 
1891                    Elts[0]->getType()->getDescription());
1892           
1893     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1894     
1895     // Verify all elements are correct type!
1896     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1897       if (Elts[i]->getType() != Elts[0]->getType())
1898         return Error(FirstEltLoc,
1899                      "array element #" + utostr(i) +
1900                      " is not of type '" +Elts[0]->getType()->getDescription());
1901     }
1902     
1903     ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
1904     ID.Kind = ValID::t_Constant;
1905     return false;
1906   }
1907   case lltok::kw_c:  // c "foo"
1908     Lex.Lex();
1909     ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
1910     if (ParseToken(lltok::StringConstant, "expected string")) return true;
1911     ID.Kind = ValID::t_Constant;
1912     return false;
1913
1914   case lltok::kw_asm: {
1915     // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1916     bool HasSideEffect;
1917     Lex.Lex();
1918     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1919         ParseStringConstant(ID.StrVal) ||
1920         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1921         ParseToken(lltok::StringConstant, "expected constraint string"))
1922       return true;
1923     ID.StrVal2 = Lex.getStrVal();
1924     ID.UIntVal = HasSideEffect;
1925     ID.Kind = ValID::t_InlineAsm;
1926     return false;
1927   }
1928       
1929   case lltok::kw_trunc:
1930   case lltok::kw_zext:
1931   case lltok::kw_sext:
1932   case lltok::kw_fptrunc:
1933   case lltok::kw_fpext:
1934   case lltok::kw_bitcast:
1935   case lltok::kw_uitofp:
1936   case lltok::kw_sitofp:
1937   case lltok::kw_fptoui:
1938   case lltok::kw_fptosi: 
1939   case lltok::kw_inttoptr:
1940   case lltok::kw_ptrtoint: { 
1941     unsigned Opc = Lex.getUIntVal();
1942     PATypeHolder DestTy(Type::getVoidTy(Context));
1943     Constant *SrcVal;
1944     Lex.Lex();
1945     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1946         ParseGlobalTypeAndValue(SrcVal) ||
1947         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1948         ParseType(DestTy) ||
1949         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1950       return true;
1951     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1952       return Error(ID.Loc, "invalid cast opcode for cast from '" +
1953                    SrcVal->getType()->getDescription() + "' to '" +
1954                    DestTy->getDescription() + "'");
1955     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, 
1956                                                  SrcVal, DestTy);
1957     ID.Kind = ValID::t_Constant;
1958     return false;
1959   }
1960   case lltok::kw_extractvalue: {
1961     Lex.Lex();
1962     Constant *Val;
1963     SmallVector<unsigned, 4> Indices;
1964     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1965         ParseGlobalTypeAndValue(Val) ||
1966         ParseIndexList(Indices) ||
1967         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1968       return true;
1969     if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1970       return Error(ID.Loc, "extractvalue operand must be array or struct");
1971     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1972                                           Indices.end()))
1973       return Error(ID.Loc, "invalid indices for extractvalue");
1974     ID.ConstantVal =
1975       ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
1976     ID.Kind = ValID::t_Constant;
1977     return false;
1978   }
1979   case lltok::kw_insertvalue: {
1980     Lex.Lex();
1981     Constant *Val0, *Val1;
1982     SmallVector<unsigned, 4> Indices;
1983     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1984         ParseGlobalTypeAndValue(Val0) ||
1985         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1986         ParseGlobalTypeAndValue(Val1) ||
1987         ParseIndexList(Indices) ||
1988         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1989       return true;
1990     if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1991       return Error(ID.Loc, "extractvalue operand must be array or struct");
1992     if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1993                                           Indices.end()))
1994       return Error(ID.Loc, "invalid indices for insertvalue");
1995     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1996                        Indices.data(), Indices.size());
1997     ID.Kind = ValID::t_Constant;
1998     return false;
1999   }
2000   case lltok::kw_icmp:
2001   case lltok::kw_fcmp: {
2002     unsigned PredVal, Opc = Lex.getUIntVal();
2003     Constant *Val0, *Val1;
2004     Lex.Lex();
2005     if (ParseCmpPredicate(PredVal, Opc) ||
2006         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2007         ParseGlobalTypeAndValue(Val0) ||
2008         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2009         ParseGlobalTypeAndValue(Val1) ||
2010         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2011       return true;
2012     
2013     if (Val0->getType() != Val1->getType())
2014       return Error(ID.Loc, "compare operands must have the same type");
2015     
2016     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2017     
2018     if (Opc == Instruction::FCmp) {
2019       if (!Val0->getType()->isFPOrFPVector())
2020         return Error(ID.Loc, "fcmp requires floating point operands");
2021       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2022     } else {
2023       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2024       if (!Val0->getType()->isIntOrIntVector() &&
2025           !isa<PointerType>(Val0->getType()))
2026         return Error(ID.Loc, "icmp requires pointer or integer operands");
2027       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2028     }
2029     ID.Kind = ValID::t_Constant;
2030     return false;
2031   }
2032       
2033   // Binary Operators.
2034   case lltok::kw_add:
2035   case lltok::kw_fadd:
2036   case lltok::kw_sub:
2037   case lltok::kw_fsub:
2038   case lltok::kw_mul:
2039   case lltok::kw_fmul:
2040   case lltok::kw_udiv:
2041   case lltok::kw_sdiv:
2042   case lltok::kw_fdiv:
2043   case lltok::kw_urem:
2044   case lltok::kw_srem:
2045   case lltok::kw_frem: {
2046     bool NUW = false;
2047     bool NSW = false;
2048     bool Exact = false;
2049     unsigned Opc = Lex.getUIntVal();
2050     Constant *Val0, *Val1;
2051     Lex.Lex();
2052     LocTy ModifierLoc = Lex.getLoc();
2053     if (Opc == Instruction::Add ||
2054         Opc == Instruction::Sub ||
2055         Opc == Instruction::Mul) {
2056       if (EatIfPresent(lltok::kw_nuw))
2057         NUW = true;
2058       if (EatIfPresent(lltok::kw_nsw)) {
2059         NSW = true;
2060         if (EatIfPresent(lltok::kw_nuw))
2061           NUW = true;
2062       }
2063     } else if (Opc == Instruction::SDiv) {
2064       if (EatIfPresent(lltok::kw_exact))
2065         Exact = true;
2066     }
2067     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2068         ParseGlobalTypeAndValue(Val0) ||
2069         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2070         ParseGlobalTypeAndValue(Val1) ||
2071         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2072       return true;
2073     if (Val0->getType() != Val1->getType())
2074       return Error(ID.Loc, "operands of constexpr must have same type");
2075     if (!Val0->getType()->isIntOrIntVector()) {
2076       if (NUW)
2077         return Error(ModifierLoc, "nuw only applies to integer operations");
2078       if (NSW)
2079         return Error(ModifierLoc, "nsw only applies to integer operations");
2080     }
2081     // API compatibility: Accept either integer or floating-point types with
2082     // add, sub, and mul.
2083     if (!Val0->getType()->isIntOrIntVector() &&
2084         !Val0->getType()->isFPOrFPVector())
2085       return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
2086     Constant *C = ConstantExpr::get(Opc, Val0, Val1);
2087     if (NUW)
2088       cast<OverflowingBinaryOperator>(C)->setHasNoUnsignedWrap(true);
2089     if (NSW)
2090       cast<OverflowingBinaryOperator>(C)->setHasNoSignedWrap(true);
2091     if (Exact)
2092       cast<SDivOperator>(C)->setIsExact(true);
2093     ID.ConstantVal = C;
2094     ID.Kind = ValID::t_Constant;
2095     return false;
2096   }
2097       
2098   // Logical Operations
2099   case lltok::kw_shl:
2100   case lltok::kw_lshr:
2101   case lltok::kw_ashr:
2102   case lltok::kw_and:
2103   case lltok::kw_or:
2104   case lltok::kw_xor: {
2105     unsigned Opc = Lex.getUIntVal();
2106     Constant *Val0, *Val1;
2107     Lex.Lex();
2108     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2109         ParseGlobalTypeAndValue(Val0) ||
2110         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2111         ParseGlobalTypeAndValue(Val1) ||
2112         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2113       return true;
2114     if (Val0->getType() != Val1->getType())
2115       return Error(ID.Loc, "operands of constexpr must have same type");
2116     if (!Val0->getType()->isIntOrIntVector())
2117       return Error(ID.Loc,
2118                    "constexpr requires integer or integer vector operands");
2119     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2120     ID.Kind = ValID::t_Constant;
2121     return false;
2122   }  
2123       
2124   case lltok::kw_getelementptr:
2125   case lltok::kw_shufflevector:
2126   case lltok::kw_insertelement:
2127   case lltok::kw_extractelement:
2128   case lltok::kw_select: {
2129     unsigned Opc = Lex.getUIntVal();
2130     SmallVector<Constant*, 16> Elts;
2131     bool InBounds = false;
2132     Lex.Lex();
2133     if (Opc == Instruction::GetElementPtr)
2134       InBounds = EatIfPresent(lltok::kw_inbounds);
2135     if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2136         ParseGlobalValueVector(Elts) ||
2137         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2138       return true;
2139     
2140     if (Opc == Instruction::GetElementPtr) {
2141       if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2142         return Error(ID.Loc, "getelementptr requires pointer operand");
2143       
2144       if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2145                                              (Value**)(Elts.data() + 1),
2146                                              Elts.size() - 1))
2147         return Error(ID.Loc, "invalid indices for getelementptr");
2148       ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
2149                                               Elts.data() + 1, Elts.size() - 1);
2150       if (InBounds)
2151         cast<GEPOperator>(ID.ConstantVal)->setIsInBounds(true);
2152     } else if (Opc == Instruction::Select) {
2153       if (Elts.size() != 3)
2154         return Error(ID.Loc, "expected three operands to select");
2155       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2156                                                               Elts[2]))
2157         return Error(ID.Loc, Reason);
2158       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2159     } else if (Opc == Instruction::ShuffleVector) {
2160       if (Elts.size() != 3)
2161         return Error(ID.Loc, "expected three operands to shufflevector");
2162       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2163         return Error(ID.Loc, "invalid operands to shufflevector");
2164       ID.ConstantVal =
2165                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2166     } else if (Opc == Instruction::ExtractElement) {
2167       if (Elts.size() != 2)
2168         return Error(ID.Loc, "expected two operands to extractelement");
2169       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2170         return Error(ID.Loc, "invalid extractelement operands");
2171       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2172     } else {
2173       assert(Opc == Instruction::InsertElement && "Unknown opcode");
2174       if (Elts.size() != 3)
2175       return Error(ID.Loc, "expected three operands to insertelement");
2176       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2177         return Error(ID.Loc, "invalid insertelement operands");
2178       ID.ConstantVal =
2179                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2180     }
2181     
2182     ID.Kind = ValID::t_Constant;
2183     return false;
2184   }
2185   }
2186   
2187   Lex.Lex();
2188   return false;
2189 }
2190
2191 /// ParseGlobalValue - Parse a global value with the specified type.
2192 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2193   V = 0;
2194   ValID ID;
2195   return ParseValID(ID) ||
2196          ConvertGlobalValIDToValue(Ty, ID, V);
2197 }
2198
2199 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2200 /// constant.
2201 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2202                                          Constant *&V) {
2203   if (isa<FunctionType>(Ty))
2204     return Error(ID.Loc, "functions are not values, refer to them as pointers");
2205   
2206   switch (ID.Kind) {
2207   default: llvm_unreachable("Unknown ValID!");    
2208   case ValID::t_Metadata:
2209     return Error(ID.Loc, "invalid use of metadata");
2210   case ValID::t_LocalID:
2211   case ValID::t_LocalName:
2212     return Error(ID.Loc, "invalid use of function-local name");
2213   case ValID::t_InlineAsm:
2214     return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2215   case ValID::t_GlobalName:
2216     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2217     return V == 0;
2218   case ValID::t_GlobalID:
2219     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2220     return V == 0;
2221   case ValID::t_APSInt:
2222     if (!isa<IntegerType>(Ty))
2223       return Error(ID.Loc, "integer constant must have integer type");
2224     ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2225     V = ConstantInt::get(Context, ID.APSIntVal);
2226     return false;
2227   case ValID::t_APFloat:
2228     if (!Ty->isFloatingPoint() ||
2229         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2230       return Error(ID.Loc, "floating point constant invalid for type");
2231       
2232     // The lexer has no type info, so builds all float and double FP constants
2233     // as double.  Fix this here.  Long double does not need this.
2234     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2235         Ty == Type::getFloatTy(Context)) {
2236       bool Ignored;
2237       ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2238                             &Ignored);
2239     }
2240     V = ConstantFP::get(Context, ID.APFloatVal);
2241       
2242     if (V->getType() != Ty)
2243       return Error(ID.Loc, "floating point constant does not have type '" +
2244                    Ty->getDescription() + "'");
2245       
2246     return false;
2247   case ValID::t_Null:
2248     if (!isa<PointerType>(Ty))
2249       return Error(ID.Loc, "null must be a pointer type");
2250     V = ConstantPointerNull::get(cast<PointerType>(Ty));
2251     return false;
2252   case ValID::t_Undef:
2253     // FIXME: LabelTy should not be a first-class type.
2254     if ((!Ty->isFirstClassType() || Ty == Type::getLabelTy(Context)) &&
2255         !isa<OpaqueType>(Ty))
2256       return Error(ID.Loc, "invalid type for undef constant");
2257     V = UndefValue::get(Ty);
2258     return false;
2259   case ValID::t_EmptyArray:
2260     if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2261       return Error(ID.Loc, "invalid empty array initializer");
2262     V = UndefValue::get(Ty);
2263     return false;
2264   case ValID::t_Zero:
2265     // FIXME: LabelTy should not be a first-class type.
2266     if (!Ty->isFirstClassType() || Ty == Type::getLabelTy(Context))
2267       return Error(ID.Loc, "invalid type for null constant");
2268     V = Constant::getNullValue(Ty);
2269     return false;
2270   case ValID::t_Constant:
2271     if (ID.ConstantVal->getType() != Ty)
2272       return Error(ID.Loc, "constant expression type mismatch");
2273     V = ID.ConstantVal;
2274     return false;
2275   }
2276 }
2277   
2278 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2279   PATypeHolder Type(Type::getVoidTy(Context));
2280   return ParseType(Type) ||
2281          ParseGlobalValue(Type, V);
2282 }    
2283
2284 /// ParseGlobalValueVector
2285 ///   ::= /*empty*/
2286 ///   ::= TypeAndValue (',' TypeAndValue)*
2287 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2288   // Empty list.
2289   if (Lex.getKind() == lltok::rbrace ||
2290       Lex.getKind() == lltok::rsquare ||
2291       Lex.getKind() == lltok::greater ||
2292       Lex.getKind() == lltok::rparen)
2293     return false;
2294   
2295   Constant *C;
2296   if (ParseGlobalTypeAndValue(C)) return true;
2297   Elts.push_back(C);
2298   
2299   while (EatIfPresent(lltok::comma)) {
2300     if (ParseGlobalTypeAndValue(C)) return true;
2301     Elts.push_back(C);
2302   }
2303   
2304   return false;
2305 }
2306
2307
2308 //===----------------------------------------------------------------------===//
2309 // Function Parsing.
2310 //===----------------------------------------------------------------------===//
2311
2312 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2313                                    PerFunctionState &PFS) {
2314   if (ID.Kind == ValID::t_LocalID)
2315     V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2316   else if (ID.Kind == ValID::t_LocalName)
2317     V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2318   else if (ID.Kind == ValID::t_InlineAsm) {
2319     const PointerType *PTy = dyn_cast<PointerType>(Ty);
2320     const FunctionType *FTy =
2321       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2322     if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2323       return Error(ID.Loc, "invalid type for inline asm constraint string");
2324     V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2325     return false;
2326   } else if (ID.Kind == ValID::t_Metadata) {
2327     V = ID.MetadataVal;
2328   } else {
2329     Constant *C;
2330     if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2331     V = C;
2332     return false;
2333   }
2334
2335   return V == 0;
2336 }
2337
2338 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2339   V = 0;
2340   ValID ID;
2341   return ParseValID(ID) ||
2342          ConvertValIDToValue(Ty, ID, V, PFS);
2343 }
2344
2345 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2346   PATypeHolder T(Type::getVoidTy(Context));
2347   return ParseType(T) ||
2348          ParseValue(T, V, PFS);
2349 }
2350
2351 /// FunctionHeader
2352 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2353 ///       Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2354 ///       OptionalAlign OptGC
2355 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2356   // Parse the linkage.
2357   LocTy LinkageLoc = Lex.getLoc();
2358   unsigned Linkage;
2359   
2360   unsigned Visibility, CC, RetAttrs;
2361   PATypeHolder RetType(Type::getVoidTy(Context));
2362   LocTy RetTypeLoc = Lex.getLoc();
2363   if (ParseOptionalLinkage(Linkage) ||
2364       ParseOptionalVisibility(Visibility) ||
2365       ParseOptionalCallingConv(CC) ||
2366       ParseOptionalAttrs(RetAttrs, 1) ||
2367       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2368     return true;
2369
2370   // Verify that the linkage is ok.
2371   switch ((GlobalValue::LinkageTypes)Linkage) {
2372   case GlobalValue::ExternalLinkage:
2373     break; // always ok.
2374   case GlobalValue::DLLImportLinkage:
2375   case GlobalValue::ExternalWeakLinkage:
2376     if (isDefine)
2377       return Error(LinkageLoc, "invalid linkage for function definition");
2378     break;
2379   case GlobalValue::PrivateLinkage:
2380   case GlobalValue::LinkerPrivateLinkage:
2381   case GlobalValue::InternalLinkage:
2382   case GlobalValue::AvailableExternallyLinkage:
2383   case GlobalValue::LinkOnceAnyLinkage:
2384   case GlobalValue::LinkOnceODRLinkage:
2385   case GlobalValue::WeakAnyLinkage:
2386   case GlobalValue::WeakODRLinkage:
2387   case GlobalValue::DLLExportLinkage:
2388     if (!isDefine)
2389       return Error(LinkageLoc, "invalid linkage for function declaration");
2390     break;
2391   case GlobalValue::AppendingLinkage:
2392   case GlobalValue::GhostLinkage:
2393   case GlobalValue::CommonLinkage:
2394     return Error(LinkageLoc, "invalid function linkage type");
2395   }
2396   
2397   if (!FunctionType::isValidReturnType(RetType) ||
2398       isa<OpaqueType>(RetType))
2399     return Error(RetTypeLoc, "invalid function return type");
2400   
2401   LocTy NameLoc = Lex.getLoc();
2402
2403   std::string FunctionName;
2404   if (Lex.getKind() == lltok::GlobalVar) {
2405     FunctionName = Lex.getStrVal();
2406   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
2407     unsigned NameID = Lex.getUIntVal();
2408
2409     if (NameID != NumberedVals.size())
2410       return TokError("function expected to be numbered '%" +
2411                       utostr(NumberedVals.size()) + "'");
2412   } else {
2413     return TokError("expected function name");
2414   }
2415   
2416   Lex.Lex();
2417   
2418   if (Lex.getKind() != lltok::lparen)
2419     return TokError("expected '(' in function argument list");
2420   
2421   std::vector<ArgInfo> ArgList;
2422   bool isVarArg;
2423   unsigned FuncAttrs;
2424   std::string Section;
2425   unsigned Alignment;
2426   std::string GC;
2427
2428   if (ParseArgumentList(ArgList, isVarArg, false) ||
2429       ParseOptionalAttrs(FuncAttrs, 2) ||
2430       (EatIfPresent(lltok::kw_section) &&
2431        ParseStringConstant(Section)) ||
2432       ParseOptionalAlignment(Alignment) ||
2433       (EatIfPresent(lltok::kw_gc) &&
2434        ParseStringConstant(GC)))
2435     return true;
2436
2437   // If the alignment was parsed as an attribute, move to the alignment field.
2438   if (FuncAttrs & Attribute::Alignment) {
2439     Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2440     FuncAttrs &= ~Attribute::Alignment;
2441   }
2442   
2443   // Okay, if we got here, the function is syntactically valid.  Convert types
2444   // and do semantic checks.
2445   std::vector<const Type*> ParamTypeList;
2446   SmallVector<AttributeWithIndex, 8> Attrs;
2447   // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function 
2448   // attributes.
2449   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2450   if (FuncAttrs & ObsoleteFuncAttrs) {
2451     RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2452     FuncAttrs &= ~ObsoleteFuncAttrs;
2453   }
2454   
2455   if (RetAttrs != Attribute::None)
2456     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2457   
2458   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2459     ParamTypeList.push_back(ArgList[i].Type);
2460     if (ArgList[i].Attrs != Attribute::None)
2461       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2462   }
2463
2464   if (FuncAttrs != Attribute::None)
2465     Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2466
2467   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2468   
2469   if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2470       RetType != Type::getVoidTy(Context))
2471     return Error(RetTypeLoc, "functions with 'sret' argument must return void"); 
2472   
2473   const FunctionType *FT =
2474     FunctionType::get(RetType, ParamTypeList, isVarArg);
2475   const PointerType *PFT = PointerType::getUnqual(FT);
2476
2477   Fn = 0;
2478   if (!FunctionName.empty()) {
2479     // If this was a definition of a forward reference, remove the definition
2480     // from the forward reference table and fill in the forward ref.
2481     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2482       ForwardRefVals.find(FunctionName);
2483     if (FRVI != ForwardRefVals.end()) {
2484       Fn = M->getFunction(FunctionName);
2485       ForwardRefVals.erase(FRVI);
2486     } else if ((Fn = M->getFunction(FunctionName))) {
2487       // If this function already exists in the symbol table, then it is
2488       // multiply defined.  We accept a few cases for old backwards compat.
2489       // FIXME: Remove this stuff for LLVM 3.0.
2490       if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2491           (!Fn->isDeclaration() && isDefine)) {
2492         // If the redefinition has different type or different attributes,
2493         // reject it.  If both have bodies, reject it.
2494         return Error(NameLoc, "invalid redefinition of function '" +
2495                      FunctionName + "'");
2496       } else if (Fn->isDeclaration()) {
2497         // Make sure to strip off any argument names so we can't get conflicts.
2498         for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2499              AI != AE; ++AI)
2500           AI->setName("");
2501       }
2502     }
2503     
2504   } else {
2505     // If this is a definition of a forward referenced function, make sure the
2506     // types agree.
2507     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2508       = ForwardRefValIDs.find(NumberedVals.size());
2509     if (I != ForwardRefValIDs.end()) {
2510       Fn = cast<Function>(I->second.first);
2511       if (Fn->getType() != PFT)
2512         return Error(NameLoc, "type of definition and forward reference of '@" +
2513                      utostr(NumberedVals.size()) +"' disagree");
2514       ForwardRefValIDs.erase(I);
2515     }
2516   }
2517
2518   if (Fn == 0)
2519     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2520   else // Move the forward-reference to the correct spot in the module.
2521     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2522
2523   if (FunctionName.empty())
2524     NumberedVals.push_back(Fn);
2525   
2526   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2527   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2528   Fn->setCallingConv(CC);
2529   Fn->setAttributes(PAL);
2530   Fn->setAlignment(Alignment);
2531   Fn->setSection(Section);
2532   if (!GC.empty()) Fn->setGC(GC.c_str());
2533     
2534   // Add all of the arguments we parsed to the function.
2535   Function::arg_iterator ArgIt = Fn->arg_begin();
2536   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2537     // If the argument has a name, insert it into the argument symbol table.
2538     if (ArgList[i].Name.empty()) continue;
2539     
2540     // Set the name, if it conflicted, it will be auto-renamed.
2541     ArgIt->setName(ArgList[i].Name);
2542     
2543     if (ArgIt->getNameStr() != ArgList[i].Name)
2544       return Error(ArgList[i].Loc, "redefinition of argument '%" +
2545                    ArgList[i].Name + "'");
2546   }
2547   
2548   return false;
2549 }
2550
2551
2552 /// ParseFunctionBody
2553 ///   ::= '{' BasicBlock+ '}'
2554 ///   ::= 'begin' BasicBlock+ 'end'  // FIXME: remove in LLVM 3.0
2555 ///
2556 bool LLParser::ParseFunctionBody(Function &Fn) {
2557   if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2558     return TokError("expected '{' in function body");
2559   Lex.Lex();  // eat the {.
2560   
2561   PerFunctionState PFS(*this, Fn);
2562   
2563   while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2564     if (ParseBasicBlock(PFS)) return true;
2565   
2566   // Eat the }.
2567   Lex.Lex();
2568   
2569   // Verify function is ok.
2570   return PFS.VerifyFunctionComplete();
2571 }
2572
2573 /// ParseBasicBlock
2574 ///   ::= LabelStr? Instruction*
2575 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2576   // If this basic block starts out with a name, remember it.
2577   std::string Name;
2578   LocTy NameLoc = Lex.getLoc();
2579   if (Lex.getKind() == lltok::LabelStr) {
2580     Name = Lex.getStrVal();
2581     Lex.Lex();
2582   }
2583   
2584   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2585   if (BB == 0) return true;
2586   
2587   std::string NameStr;
2588   
2589   // Parse the instructions in this block until we get a terminator.
2590   Instruction *Inst;
2591   do {
2592     // This instruction may have three possibilities for a name: a) none
2593     // specified, b) name specified "%foo =", c) number specified: "%4 =".
2594     LocTy NameLoc = Lex.getLoc();
2595     int NameID = -1;
2596     NameStr = "";
2597     
2598     if (Lex.getKind() == lltok::LocalVarID) {
2599       NameID = Lex.getUIntVal();
2600       Lex.Lex();
2601       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2602         return true;
2603     } else if (Lex.getKind() == lltok::LocalVar ||
2604                // FIXME: REMOVE IN LLVM 3.0
2605                Lex.getKind() == lltok::StringConstant) {
2606       NameStr = Lex.getStrVal();
2607       Lex.Lex();
2608       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2609         return true;
2610     }
2611     
2612     if (ParseInstruction(Inst, BB, PFS)) return true;
2613     
2614     BB->getInstList().push_back(Inst);
2615
2616     // Set the name on the instruction.
2617     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2618   } while (!isa<TerminatorInst>(Inst));
2619   
2620   return false;
2621 }
2622
2623 //===----------------------------------------------------------------------===//
2624 // Instruction Parsing.
2625 //===----------------------------------------------------------------------===//
2626
2627 /// ParseInstruction - Parse one of the many different instructions.
2628 ///
2629 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2630                                 PerFunctionState &PFS) {
2631   lltok::Kind Token = Lex.getKind();
2632   if (Token == lltok::Eof)
2633     return TokError("found end of file when expecting more instructions");
2634   LocTy Loc = Lex.getLoc();
2635   unsigned KeywordVal = Lex.getUIntVal();
2636   Lex.Lex();  // Eat the keyword.
2637   
2638   switch (Token) {
2639   default:                    return Error(Loc, "expected instruction opcode");
2640   // Terminator Instructions.
2641   case lltok::kw_unwind:      Inst = new UnwindInst(Context); return false;
2642   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2643   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
2644   case lltok::kw_br:          return ParseBr(Inst, PFS);
2645   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
2646   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
2647   // Binary Operators.
2648   case lltok::kw_add:
2649   case lltok::kw_sub:
2650   case lltok::kw_mul: {
2651     bool NUW = false;
2652     bool NSW = false;
2653     LocTy ModifierLoc = Lex.getLoc();
2654     if (EatIfPresent(lltok::kw_nuw))
2655       NUW = true;
2656     if (EatIfPresent(lltok::kw_nsw)) {
2657       NSW = true;
2658       if (EatIfPresent(lltok::kw_nuw))
2659         NUW = true;
2660     }
2661     // API compatibility: Accept either integer or floating-point types.
2662     bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2663     if (!Result) {
2664       if (!Inst->getType()->isIntOrIntVector()) {
2665         if (NUW)
2666           return Error(ModifierLoc, "nuw only applies to integer operations");
2667         if (NSW)
2668           return Error(ModifierLoc, "nsw only applies to integer operations");
2669       }
2670       if (NUW)
2671         cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2672       if (NSW)
2673         cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedWrap(true);
2674     }
2675     return Result;
2676   }
2677   case lltok::kw_fadd:
2678   case lltok::kw_fsub:
2679   case lltok::kw_fmul:    return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2680
2681   case lltok::kw_sdiv: {
2682     bool Exact = false;
2683     if (EatIfPresent(lltok::kw_exact))
2684       Exact = true;
2685     bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2686     if (!Result)
2687       if (Exact)
2688         cast<SDivOperator>(Inst)->setIsExact(true);
2689     return Result;
2690   }
2691
2692   case lltok::kw_udiv:
2693   case lltok::kw_urem:
2694   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2695   case lltok::kw_fdiv:
2696   case lltok::kw_frem:   return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2697   case lltok::kw_shl:
2698   case lltok::kw_lshr:
2699   case lltok::kw_ashr:
2700   case lltok::kw_and:
2701   case lltok::kw_or:
2702   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
2703   case lltok::kw_icmp:
2704   case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
2705   // Casts.
2706   case lltok::kw_trunc:
2707   case lltok::kw_zext:
2708   case lltok::kw_sext:
2709   case lltok::kw_fptrunc:
2710   case lltok::kw_fpext:
2711   case lltok::kw_bitcast:
2712   case lltok::kw_uitofp:
2713   case lltok::kw_sitofp:
2714   case lltok::kw_fptoui:
2715   case lltok::kw_fptosi: 
2716   case lltok::kw_inttoptr:
2717   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
2718   // Other.
2719   case lltok::kw_select:         return ParseSelect(Inst, PFS);
2720   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
2721   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2722   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
2723   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
2724   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
2725   case lltok::kw_call:           return ParseCall(Inst, PFS, false);
2726   case lltok::kw_tail:           return ParseCall(Inst, PFS, true);
2727   // Memory.
2728   case lltok::kw_alloca:
2729   case lltok::kw_malloc:         return ParseAlloc(Inst, PFS, KeywordVal);
2730   case lltok::kw_free:           return ParseFree(Inst, PFS);
2731   case lltok::kw_load:           return ParseLoad(Inst, PFS, false);
2732   case lltok::kw_store:          return ParseStore(Inst, PFS, false);
2733   case lltok::kw_volatile:
2734     if (EatIfPresent(lltok::kw_load))
2735       return ParseLoad(Inst, PFS, true);
2736     else if (EatIfPresent(lltok::kw_store))
2737       return ParseStore(Inst, PFS, true);
2738     else
2739       return TokError("expected 'load' or 'store'");
2740   case lltok::kw_getresult:     return ParseGetResult(Inst, PFS);
2741   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2742   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
2743   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
2744   }
2745 }
2746
2747 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2748 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2749   if (Opc == Instruction::FCmp) {
2750     switch (Lex.getKind()) {
2751     default: TokError("expected fcmp predicate (e.g. 'oeq')");
2752     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2753     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2754     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2755     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2756     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2757     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2758     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2759     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2760     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2761     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2762     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2763     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2764     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2765     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2766     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2767     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2768     }
2769   } else {
2770     switch (Lex.getKind()) {
2771     default: TokError("expected icmp predicate (e.g. 'eq')");
2772     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
2773     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
2774     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2775     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2776     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2777     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2778     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2779     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2780     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2781     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2782     }
2783   }
2784   Lex.Lex();
2785   return false;
2786 }
2787
2788 //===----------------------------------------------------------------------===//
2789 // Terminator Instructions.
2790 //===----------------------------------------------------------------------===//
2791
2792 /// ParseRet - Parse a return instruction.
2793 ///   ::= 'ret' void
2794 ///   ::= 'ret' TypeAndValue
2795 ///   ::= 'ret' TypeAndValue (',' TypeAndValue)+  [[obsolete: LLVM 3.0]]
2796 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2797                         PerFunctionState &PFS) {
2798   PATypeHolder Ty(Type::getVoidTy(Context));
2799   if (ParseType(Ty, true /*void allowed*/)) return true;
2800   
2801   if (Ty == Type::getVoidTy(Context)) {
2802     Inst = ReturnInst::Create(Context);
2803     return false;
2804   }
2805   
2806   Value *RV;
2807   if (ParseValue(Ty, RV, PFS)) return true;
2808   
2809   // The normal case is one return value.
2810   if (Lex.getKind() == lltok::comma) {
2811     // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2812     // of 'ret {i32,i32} {i32 1, i32 2}'
2813     SmallVector<Value*, 8> RVs;
2814     RVs.push_back(RV);
2815     
2816     while (EatIfPresent(lltok::comma)) {
2817       if (ParseTypeAndValue(RV, PFS)) return true;
2818       RVs.push_back(RV);
2819     }
2820
2821     RV = UndefValue::get(PFS.getFunction().getReturnType());
2822     for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2823       Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2824       BB->getInstList().push_back(I);
2825       RV = I;
2826     }
2827   }
2828   Inst = ReturnInst::Create(Context, RV);
2829   return false;
2830 }
2831
2832
2833 /// ParseBr
2834 ///   ::= 'br' TypeAndValue
2835 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2836 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2837   LocTy Loc, Loc2;
2838   Value *Op0, *Op1, *Op2;
2839   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2840   
2841   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2842     Inst = BranchInst::Create(BB);
2843     return false;
2844   }
2845   
2846   if (Op0->getType() != Type::getInt1Ty(Context))
2847     return Error(Loc, "branch condition must have 'i1' type");
2848     
2849   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2850       ParseTypeAndValue(Op1, Loc, PFS) ||
2851       ParseToken(lltok::comma, "expected ',' after true destination") ||
2852       ParseTypeAndValue(Op2, Loc2, PFS))
2853     return true;
2854   
2855   if (!isa<BasicBlock>(Op1))
2856     return Error(Loc, "true destination of branch must be a basic block");
2857   if (!isa<BasicBlock>(Op2))
2858     return Error(Loc2, "true destination of branch must be a basic block");
2859     
2860   Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2861   return false;
2862 }
2863
2864 /// ParseSwitch
2865 ///  Instruction
2866 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2867 ///  JumpTable
2868 ///    ::= (TypeAndValue ',' TypeAndValue)*
2869 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2870   LocTy CondLoc, BBLoc;
2871   Value *Cond, *DefaultBB;
2872   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2873       ParseToken(lltok::comma, "expected ',' after switch condition") ||
2874       ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2875       ParseToken(lltok::lsquare, "expected '[' with switch table"))
2876     return true;
2877
2878   if (!isa<IntegerType>(Cond->getType()))
2879     return Error(CondLoc, "switch condition must have integer type");
2880   if (!isa<BasicBlock>(DefaultBB))
2881     return Error(BBLoc, "default destination must be a basic block");
2882   
2883   // Parse the jump table pairs.
2884   SmallPtrSet<Value*, 32> SeenCases;
2885   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2886   while (Lex.getKind() != lltok::rsquare) {
2887     Value *Constant, *DestBB;
2888     
2889     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2890         ParseToken(lltok::comma, "expected ',' after case value") ||
2891         ParseTypeAndValue(DestBB, BBLoc, PFS))
2892       return true;
2893
2894     if (!SeenCases.insert(Constant))
2895       return Error(CondLoc, "duplicate case value in switch");
2896     if (!isa<ConstantInt>(Constant))
2897       return Error(CondLoc, "case value is not a constant integer");
2898     if (!isa<BasicBlock>(DestBB))
2899       return Error(BBLoc, "case destination is not a basic block");
2900     
2901     Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2902                                    cast<BasicBlock>(DestBB)));
2903   }
2904   
2905   Lex.Lex();  // Eat the ']'.
2906   
2907   SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2908                                       Table.size());
2909   for (unsigned i = 0, e = Table.size(); i != e; ++i)
2910     SI->addCase(Table[i].first, Table[i].second);
2911   Inst = SI;
2912   return false;
2913 }
2914
2915 /// ParseInvoke
2916 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2917 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2918 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2919   LocTy CallLoc = Lex.getLoc();
2920   unsigned CC, RetAttrs, FnAttrs;
2921   PATypeHolder RetType(Type::getVoidTy(Context));
2922   LocTy RetTypeLoc;
2923   ValID CalleeID;
2924   SmallVector<ParamInfo, 16> ArgList;
2925
2926   Value *NormalBB, *UnwindBB;
2927   if (ParseOptionalCallingConv(CC) ||
2928       ParseOptionalAttrs(RetAttrs, 1) ||
2929       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2930       ParseValID(CalleeID) ||
2931       ParseParameterList(ArgList, PFS) ||
2932       ParseOptionalAttrs(FnAttrs, 2) ||
2933       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2934       ParseTypeAndValue(NormalBB, PFS) ||
2935       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2936       ParseTypeAndValue(UnwindBB, PFS))
2937     return true;
2938   
2939   if (!isa<BasicBlock>(NormalBB))
2940     return Error(CallLoc, "normal destination is not a basic block");
2941   if (!isa<BasicBlock>(UnwindBB))
2942     return Error(CallLoc, "unwind destination is not a basic block");
2943   
2944   // If RetType is a non-function pointer type, then this is the short syntax
2945   // for the call, which means that RetType is just the return type.  Infer the
2946   // rest of the function argument types from the arguments that are present.
2947   const PointerType *PFTy = 0;
2948   const FunctionType *Ty = 0;
2949   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2950       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2951     // Pull out the types of all of the arguments...
2952     std::vector<const Type*> ParamTypes;
2953     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2954       ParamTypes.push_back(ArgList[i].V->getType());
2955     
2956     if (!FunctionType::isValidReturnType(RetType))
2957       return Error(RetTypeLoc, "Invalid result type for LLVM function");
2958     
2959     Ty = FunctionType::get(RetType, ParamTypes, false);
2960     PFTy = PointerType::getUnqual(Ty);
2961   }
2962   
2963   // Look up the callee.
2964   Value *Callee;
2965   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2966   
2967   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2968   // function attributes.
2969   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2970   if (FnAttrs & ObsoleteFuncAttrs) {
2971     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2972     FnAttrs &= ~ObsoleteFuncAttrs;
2973   }
2974   
2975   // Set up the Attributes for the function.
2976   SmallVector<AttributeWithIndex, 8> Attrs;
2977   if (RetAttrs != Attribute::None)
2978     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2979   
2980   SmallVector<Value*, 8> Args;
2981   
2982   // Loop through FunctionType's arguments and ensure they are specified
2983   // correctly.  Also, gather any parameter attributes.
2984   FunctionType::param_iterator I = Ty->param_begin();
2985   FunctionType::param_iterator E = Ty->param_end();
2986   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2987     const Type *ExpectedTy = 0;
2988     if (I != E) {
2989       ExpectedTy = *I++;
2990     } else if (!Ty->isVarArg()) {
2991       return Error(ArgList[i].Loc, "too many arguments specified");
2992     }
2993     
2994     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2995       return Error(ArgList[i].Loc, "argument is not of expected type '" +
2996                    ExpectedTy->getDescription() + "'");
2997     Args.push_back(ArgList[i].V);
2998     if (ArgList[i].Attrs != Attribute::None)
2999       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3000   }
3001   
3002   if (I != E)
3003     return Error(CallLoc, "not enough parameters specified for call");
3004   
3005   if (FnAttrs != Attribute::None)
3006     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3007   
3008   // Finish off the Attributes and check them
3009   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3010   
3011   InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
3012                                       cast<BasicBlock>(UnwindBB),
3013                                       Args.begin(), Args.end());
3014   II->setCallingConv(CC);
3015   II->setAttributes(PAL);
3016   Inst = II;
3017   return false;
3018 }
3019
3020
3021
3022 //===----------------------------------------------------------------------===//
3023 // Binary Operators.
3024 //===----------------------------------------------------------------------===//
3025
3026 /// ParseArithmetic
3027 ///  ::= ArithmeticOps TypeAndValue ',' Value
3028 ///
3029 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
3030 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3031 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3032                                unsigned Opc, unsigned OperandType) {
3033   LocTy Loc; Value *LHS, *RHS;
3034   if (ParseTypeAndValue(LHS, Loc, PFS) ||
3035       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3036       ParseValue(LHS->getType(), RHS, PFS))
3037     return true;
3038
3039   bool Valid;
3040   switch (OperandType) {
3041   default: llvm_unreachable("Unknown operand type!");
3042   case 0: // int or FP.
3043     Valid = LHS->getType()->isIntOrIntVector() ||
3044             LHS->getType()->isFPOrFPVector();
3045     break;
3046   case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3047   case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3048   }
3049   
3050   if (!Valid)
3051     return Error(Loc, "invalid operand type for instruction");
3052   
3053   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3054   return false;
3055 }
3056
3057 /// ParseLogical
3058 ///  ::= ArithmeticOps TypeAndValue ',' Value {
3059 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3060                             unsigned Opc) {
3061   LocTy Loc; Value *LHS, *RHS;
3062   if (ParseTypeAndValue(LHS, Loc, PFS) ||
3063       ParseToken(lltok::comma, "expected ',' in logical operation") ||
3064       ParseValue(LHS->getType(), RHS, PFS))
3065     return true;
3066
3067   if (!LHS->getType()->isIntOrIntVector())
3068     return Error(Loc,"instruction requires integer or integer vector operands");
3069
3070   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3071   return false;
3072 }
3073
3074
3075 /// ParseCompare
3076 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
3077 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
3078 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3079                             unsigned Opc) {
3080   // Parse the integer/fp comparison predicate.
3081   LocTy Loc;
3082   unsigned Pred;
3083   Value *LHS, *RHS;
3084   if (ParseCmpPredicate(Pred, Opc) ||
3085       ParseTypeAndValue(LHS, Loc, PFS) ||
3086       ParseToken(lltok::comma, "expected ',' after compare value") ||
3087       ParseValue(LHS->getType(), RHS, PFS))
3088     return true;
3089   
3090   if (Opc == Instruction::FCmp) {
3091     if (!LHS->getType()->isFPOrFPVector())
3092       return Error(Loc, "fcmp requires floating point operands");
3093     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3094   } else {
3095     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3096     if (!LHS->getType()->isIntOrIntVector() &&
3097         !isa<PointerType>(LHS->getType()))
3098       return Error(Loc, "icmp requires integer operands");
3099     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3100   }
3101   return false;
3102 }
3103
3104 //===----------------------------------------------------------------------===//
3105 // Other Instructions.
3106 //===----------------------------------------------------------------------===//
3107
3108
3109 /// ParseCast
3110 ///   ::= CastOpc TypeAndValue 'to' Type
3111 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3112                          unsigned Opc) {
3113   LocTy Loc;  Value *Op;
3114   PATypeHolder DestTy(Type::getVoidTy(Context));
3115   if (ParseTypeAndValue(Op, Loc, PFS) ||
3116       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3117       ParseType(DestTy))
3118     return true;
3119   
3120   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3121     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3122     return Error(Loc, "invalid cast opcode for cast from '" +
3123                  Op->getType()->getDescription() + "' to '" +
3124                  DestTy->getDescription() + "'");
3125   }
3126   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3127   return false;
3128 }
3129
3130 /// ParseSelect
3131 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3132 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3133   LocTy Loc;
3134   Value *Op0, *Op1, *Op2;
3135   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3136       ParseToken(lltok::comma, "expected ',' after select condition") ||
3137       ParseTypeAndValue(Op1, PFS) ||
3138       ParseToken(lltok::comma, "expected ',' after select value") ||
3139       ParseTypeAndValue(Op2, PFS))
3140     return true;
3141   
3142   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3143     return Error(Loc, Reason);
3144   
3145   Inst = SelectInst::Create(Op0, Op1, Op2);
3146   return false;
3147 }
3148
3149 /// ParseVA_Arg
3150 ///   ::= 'va_arg' TypeAndValue ',' Type
3151 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3152   Value *Op;
3153   PATypeHolder EltTy(Type::getVoidTy(Context));
3154   LocTy TypeLoc;
3155   if (ParseTypeAndValue(Op, PFS) ||
3156       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3157       ParseType(EltTy, TypeLoc))
3158     return true;
3159   
3160   if (!EltTy->isFirstClassType())
3161     return Error(TypeLoc, "va_arg requires operand with first class type");
3162
3163   Inst = new VAArgInst(Op, EltTy);
3164   return false;
3165 }
3166
3167 /// ParseExtractElement
3168 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
3169 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3170   LocTy Loc;
3171   Value *Op0, *Op1;
3172   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3173       ParseToken(lltok::comma, "expected ',' after extract value") ||
3174       ParseTypeAndValue(Op1, PFS))
3175     return true;
3176   
3177   if (!ExtractElementInst::isValidOperands(Op0, Op1))
3178     return Error(Loc, "invalid extractelement operands");
3179   
3180   Inst = ExtractElementInst::Create(Op0, Op1);
3181   return false;
3182 }
3183
3184 /// ParseInsertElement
3185 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3186 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3187   LocTy Loc;
3188   Value *Op0, *Op1, *Op2;
3189   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3190       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3191       ParseTypeAndValue(Op1, PFS) ||
3192       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3193       ParseTypeAndValue(Op2, PFS))
3194     return true;
3195   
3196   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3197     return Error(Loc, "invalid insertelement operands");
3198   
3199   Inst = InsertElementInst::Create(Op0, Op1, Op2);
3200   return false;
3201 }
3202
3203 /// ParseShuffleVector
3204 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3205 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3206   LocTy Loc;
3207   Value *Op0, *Op1, *Op2;
3208   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3209       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3210       ParseTypeAndValue(Op1, PFS) ||
3211       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3212       ParseTypeAndValue(Op2, PFS))
3213     return true;
3214   
3215   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3216     return Error(Loc, "invalid extractelement operands");
3217   
3218   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3219   return false;
3220 }
3221
3222 /// ParsePHI
3223 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3224 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3225   PATypeHolder Ty(Type::getVoidTy(Context));
3226   Value *Op0, *Op1;
3227   LocTy TypeLoc = Lex.getLoc();
3228   
3229   if (ParseType(Ty) ||
3230       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3231       ParseValue(Ty, Op0, PFS) ||
3232       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3233       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3234       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3235     return true;
3236  
3237   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3238   while (1) {
3239     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3240     
3241     if (!EatIfPresent(lltok::comma))
3242       break;
3243
3244     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3245         ParseValue(Ty, Op0, PFS) ||
3246         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3247         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3248         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3249       return true;
3250   }
3251   
3252   if (!Ty->isFirstClassType())
3253     return Error(TypeLoc, "phi node must have first class type");
3254
3255   PHINode *PN = PHINode::Create(Ty);
3256   PN->reserveOperandSpace(PHIVals.size());
3257   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3258     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3259   Inst = PN;
3260   return false;
3261 }
3262
3263 /// ParseCall
3264 ///   ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3265 ///       ParameterList OptionalAttrs
3266 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3267                          bool isTail) {
3268   unsigned CC, RetAttrs, FnAttrs;
3269   PATypeHolder RetType(Type::getVoidTy(Context));
3270   LocTy RetTypeLoc;
3271   ValID CalleeID;
3272   SmallVector<ParamInfo, 16> ArgList;
3273   LocTy CallLoc = Lex.getLoc();
3274   
3275   if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3276       ParseOptionalCallingConv(CC) ||
3277       ParseOptionalAttrs(RetAttrs, 1) ||
3278       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3279       ParseValID(CalleeID) ||
3280       ParseParameterList(ArgList, PFS) ||
3281       ParseOptionalAttrs(FnAttrs, 2))
3282     return true;
3283   
3284   // If RetType is a non-function pointer type, then this is the short syntax
3285   // for the call, which means that RetType is just the return type.  Infer the
3286   // rest of the function argument types from the arguments that are present.
3287   const PointerType *PFTy = 0;
3288   const FunctionType *Ty = 0;
3289   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3290       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3291     // Pull out the types of all of the arguments...
3292     std::vector<const Type*> ParamTypes;
3293     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3294       ParamTypes.push_back(ArgList[i].V->getType());
3295     
3296     if (!FunctionType::isValidReturnType(RetType))
3297       return Error(RetTypeLoc, "Invalid result type for LLVM function");
3298     
3299     Ty = FunctionType::get(RetType, ParamTypes, false);
3300     PFTy = PointerType::getUnqual(Ty);
3301   }
3302   
3303   // Look up the callee.
3304   Value *Callee;
3305   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3306   
3307   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3308   // function attributes.
3309   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3310   if (FnAttrs & ObsoleteFuncAttrs) {
3311     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3312     FnAttrs &= ~ObsoleteFuncAttrs;
3313   }
3314
3315   // Set up the Attributes for the function.
3316   SmallVector<AttributeWithIndex, 8> Attrs;
3317   if (RetAttrs != Attribute::None)
3318     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3319   
3320   SmallVector<Value*, 8> Args;
3321   
3322   // Loop through FunctionType's arguments and ensure they are specified
3323   // correctly.  Also, gather any parameter attributes.
3324   FunctionType::param_iterator I = Ty->param_begin();
3325   FunctionType::param_iterator E = Ty->param_end();
3326   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3327     const Type *ExpectedTy = 0;
3328     if (I != E) {
3329       ExpectedTy = *I++;
3330     } else if (!Ty->isVarArg()) {
3331       return Error(ArgList[i].Loc, "too many arguments specified");
3332     }
3333     
3334     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3335       return Error(ArgList[i].Loc, "argument is not of expected type '" +
3336                    ExpectedTy->getDescription() + "'");
3337     Args.push_back(ArgList[i].V);
3338     if (ArgList[i].Attrs != Attribute::None)
3339       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3340   }
3341   
3342   if (I != E)
3343     return Error(CallLoc, "not enough parameters specified for call");
3344
3345   if (FnAttrs != Attribute::None)
3346     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3347
3348   // Finish off the Attributes and check them
3349   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3350   
3351   CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3352   CI->setTailCall(isTail);
3353   CI->setCallingConv(CC);
3354   CI->setAttributes(PAL);
3355   Inst = CI;
3356   return false;
3357 }
3358
3359 //===----------------------------------------------------------------------===//
3360 // Memory Instructions.
3361 //===----------------------------------------------------------------------===//
3362
3363 /// ParseAlloc
3364 ///   ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3365 ///   ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3366 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3367                           unsigned Opc) {
3368   PATypeHolder Ty(Type::getVoidTy(Context));
3369   Value *Size = 0;
3370   LocTy SizeLoc;
3371   unsigned Alignment = 0;
3372   if (ParseType(Ty)) return true;
3373
3374   if (EatIfPresent(lltok::comma)) {
3375     if (Lex.getKind() == lltok::kw_align) {
3376       if (ParseOptionalAlignment(Alignment)) return true;
3377     } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3378                ParseOptionalCommaAlignment(Alignment)) {
3379       return true;
3380     }
3381   }
3382
3383   if (Size && Size->getType() != Type::getInt32Ty(Context))
3384     return Error(SizeLoc, "element count must be i32");
3385
3386   if (Opc == Instruction::Malloc)
3387     Inst = new MallocInst(Ty, Size, Alignment);
3388   else
3389     Inst = new AllocaInst(Ty, Size, Alignment);
3390   return false;
3391 }
3392
3393 /// ParseFree
3394 ///   ::= 'free' TypeAndValue
3395 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3396   Value *Val; LocTy Loc;
3397   if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3398   if (!isa<PointerType>(Val->getType()))
3399     return Error(Loc, "operand to free must be a pointer");
3400   Inst = new FreeInst(Val);
3401   return false;
3402 }
3403
3404 /// ParseLoad
3405 ///   ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3406 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3407                          bool isVolatile) {
3408   Value *Val; LocTy Loc;
3409   unsigned Alignment;
3410   if (ParseTypeAndValue(Val, Loc, PFS) ||
3411       ParseOptionalCommaAlignment(Alignment))
3412     return true;
3413
3414   if (!isa<PointerType>(Val->getType()) ||
3415       !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3416     return Error(Loc, "load operand must be a pointer to a first class type");
3417   
3418   Inst = new LoadInst(Val, "", isVolatile, Alignment);
3419   return false;
3420 }
3421
3422 /// ParseStore
3423 ///   ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3424 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3425                           bool isVolatile) {
3426   Value *Val, *Ptr; LocTy Loc, PtrLoc;
3427   unsigned Alignment;
3428   if (ParseTypeAndValue(Val, Loc, PFS) ||
3429       ParseToken(lltok::comma, "expected ',' after store operand") ||
3430       ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3431       ParseOptionalCommaAlignment(Alignment))
3432     return true;
3433   
3434   if (!isa<PointerType>(Ptr->getType()))
3435     return Error(PtrLoc, "store operand must be a pointer");
3436   if (!Val->getType()->isFirstClassType())
3437     return Error(Loc, "store operand must be a first class value");
3438   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3439     return Error(Loc, "stored value and pointer type do not match");
3440   
3441   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3442   return false;
3443 }
3444
3445 /// ParseGetResult
3446 ///   ::= 'getresult' TypeAndValue ',' i32
3447 /// FIXME: Remove support for getresult in LLVM 3.0
3448 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3449   Value *Val; LocTy ValLoc, EltLoc;
3450   unsigned Element;
3451   if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3452       ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3453       ParseUInt32(Element, EltLoc))
3454     return true;
3455   
3456   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3457     return Error(ValLoc, "getresult inst requires an aggregate operand");
3458   if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3459     return Error(EltLoc, "invalid getresult index for value");
3460   Inst = ExtractValueInst::Create(Val, Element);
3461   return false;
3462 }
3463
3464 /// ParseGetElementPtr
3465 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3466 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3467   Value *Ptr, *Val; LocTy Loc, EltLoc;
3468
3469   bool InBounds = EatIfPresent(lltok::kw_inbounds);
3470
3471   if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3472   
3473   if (!isa<PointerType>(Ptr->getType()))
3474     return Error(Loc, "base of getelementptr must be a pointer");
3475   
3476   SmallVector<Value*, 16> Indices;
3477   while (EatIfPresent(lltok::comma)) {
3478     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3479     if (!isa<IntegerType>(Val->getType()))
3480       return Error(EltLoc, "getelementptr index must be an integer");
3481     Indices.push_back(Val);
3482   }
3483   
3484   if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3485                                          Indices.begin(), Indices.end()))
3486     return Error(Loc, "invalid getelementptr indices");
3487   Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3488   if (InBounds)
3489     cast<GEPOperator>(Inst)->setIsInBounds(true);
3490   return false;
3491 }
3492
3493 /// ParseExtractValue
3494 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
3495 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3496   Value *Val; LocTy Loc;
3497   SmallVector<unsigned, 4> Indices;
3498   if (ParseTypeAndValue(Val, Loc, PFS) ||
3499       ParseIndexList(Indices))
3500     return true;
3501
3502   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3503     return Error(Loc, "extractvalue operand must be array or struct");
3504
3505   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3506                                         Indices.end()))
3507     return Error(Loc, "invalid indices for extractvalue");
3508   Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3509   return false;
3510 }
3511
3512 /// ParseInsertValue
3513 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3514 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3515   Value *Val0, *Val1; LocTy Loc0, Loc1;
3516   SmallVector<unsigned, 4> Indices;
3517   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3518       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3519       ParseTypeAndValue(Val1, Loc1, PFS) ||
3520       ParseIndexList(Indices))
3521     return true;
3522   
3523   if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3524     return Error(Loc0, "extractvalue operand must be array or struct");
3525   
3526   if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3527                                         Indices.end()))
3528     return Error(Loc0, "invalid indices for insertvalue");
3529   Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3530   return false;
3531 }
3532
3533 //===----------------------------------------------------------------------===//
3534 // Embedded metadata.
3535 //===----------------------------------------------------------------------===//
3536
3537 /// ParseMDNodeVector
3538 ///   ::= Element (',' Element)*
3539 /// Element
3540 ///   ::= 'null' | TypeAndValue
3541 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3542   assert(Lex.getKind() == lltok::lbrace);
3543   Lex.Lex();
3544   do {
3545     Value *V = 0;
3546     if (Lex.getKind() == lltok::kw_null) {
3547       Lex.Lex();
3548       V = 0;
3549     } else {
3550       PATypeHolder Ty(Type::getVoidTy(Context));
3551       if (ParseType(Ty)) return true;
3552       if (Lex.getKind() == lltok::Metadata) {
3553         Lex.Lex();
3554         MetadataBase *Node = 0;
3555         if (!ParseMDNode(Node))
3556           V = Node;
3557         else {
3558           MetadataBase *MDS = 0;
3559           if (ParseMDString(MDS)) return true;
3560           V = MDS;
3561         }
3562       } else {
3563         Constant *C;
3564         if (ParseGlobalValue(Ty, C)) return true;
3565         V = C;
3566       }
3567     }
3568     Elts.push_back(V);
3569   } while (EatIfPresent(lltok::comma));
3570
3571   return false;
3572 }