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