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