[AArch64] Add support for NEON scalar three register different instruction
[oota-llvm.git] / lib / AsmParser / LLParser.cpp
1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the parser class for .ll files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LLParser.h"
15 #include "llvm/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   return false;
186 }
187
188 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
189                              std::vector<std::pair<ValID, GlobalValue*> > &Refs,
190                                                PerFunctionState *PFS) {
191   // Loop over all the references, resolving them.
192   for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
193     BasicBlock *Res;
194     if (PFS) {
195       if (Refs[i].first.Kind == ValID::t_LocalName)
196         Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
197       else
198         Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
199     } else if (Refs[i].first.Kind == ValID::t_LocalID) {
200       return Error(Refs[i].first.Loc,
201        "cannot take address of numeric label after the function is defined");
202     } else {
203       Res = dyn_cast_or_null<BasicBlock>(
204                      TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
205     }
206
207     if (Res == 0)
208       return Error(Refs[i].first.Loc,
209                    "referenced value is not a basic block");
210
211     // Get the BlockAddress for this and update references to use it.
212     BlockAddress *BA = BlockAddress::get(TheFn, Res);
213     Refs[i].second->replaceAllUsesWith(BA);
214     Refs[i].second->eraseFromParent();
215   }
216   return false;
217 }
218
219
220 //===----------------------------------------------------------------------===//
221 // Top-Level Entities
222 //===----------------------------------------------------------------------===//
223
224 bool LLParser::ParseTopLevelEntities() {
225   while (1) {
226     switch (Lex.getKind()) {
227     default:         return TokError("expected top-level entity");
228     case lltok::Eof: return false;
229     case lltok::kw_declare: if (ParseDeclare()) return true; break;
230     case lltok::kw_define:  if (ParseDefine()) return true; break;
231     case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
232     case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
233     case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
234     case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
235     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
236     case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
237     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
238     case lltok::exclaim:    if (ParseStandaloneMetadata()) return true; break;
239     case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
240
241     // The Global variable production with no name can have many different
242     // optional leading prefixes, the production is:
243     // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
244     //               OptionalAddrSpace OptionalUnNammedAddr
245     //               ('constant'|'global') ...
246     case lltok::kw_private:             // OptionalLinkage
247     case lltok::kw_linker_private:      // OptionalLinkage
248     case lltok::kw_linker_private_weak: // OptionalLinkage
249     case lltok::kw_linker_private_weak_def_auto: // FIXME: backwards compat.
250     case lltok::kw_internal:            // OptionalLinkage
251     case lltok::kw_weak:                // OptionalLinkage
252     case lltok::kw_weak_odr:            // OptionalLinkage
253     case lltok::kw_linkonce:            // OptionalLinkage
254     case lltok::kw_linkonce_odr:        // OptionalLinkage
255     case lltok::kw_linkonce_odr_auto_hide: // 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 ///   ::= 'linkonce_odr_auto_hide'
1276 ///   ::= 'available_externally'
1277 ///   ::= 'appending'
1278 ///   ::= 'dllexport'
1279 ///   ::= 'common'
1280 ///   ::= 'dllimport'
1281 ///   ::= 'extern_weak'
1282 ///   ::= 'external'
1283 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1284   HasLinkage = false;
1285   switch (Lex.getKind()) {
1286   default:                       Res=GlobalValue::ExternalLinkage; return false;
1287   case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
1288   case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1289   case lltok::kw_linker_private_weak:
1290     Res = GlobalValue::LinkerPrivateWeakLinkage;
1291     break;
1292   case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
1293   case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
1294   case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
1295   case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
1296   case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
1297   case lltok::kw_linkonce_odr_auto_hide:
1298   case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1299     Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1300     break;
1301   case lltok::kw_available_externally:
1302     Res = GlobalValue::AvailableExternallyLinkage;
1303     break;
1304   case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
1305   case lltok::kw_dllexport:      Res = GlobalValue::DLLExportLinkage;     break;
1306   case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
1307   case lltok::kw_dllimport:      Res = GlobalValue::DLLImportLinkage;     break;
1308   case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
1309   case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
1310   }
1311   Lex.Lex();
1312   HasLinkage = true;
1313   return false;
1314 }
1315
1316 /// ParseOptionalVisibility
1317 ///   ::= /*empty*/
1318 ///   ::= 'default'
1319 ///   ::= 'hidden'
1320 ///   ::= 'protected'
1321 ///
1322 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1323   switch (Lex.getKind()) {
1324   default:                  Res = GlobalValue::DefaultVisibility; return false;
1325   case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
1326   case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
1327   case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1328   }
1329   Lex.Lex();
1330   return false;
1331 }
1332
1333 /// ParseOptionalCallingConv
1334 ///   ::= /*empty*/
1335 ///   ::= 'ccc'
1336 ///   ::= 'fastcc'
1337 ///   ::= 'kw_intel_ocl_bicc'
1338 ///   ::= 'coldcc'
1339 ///   ::= 'x86_stdcallcc'
1340 ///   ::= 'x86_fastcallcc'
1341 ///   ::= 'x86_thiscallcc'
1342 ///   ::= 'arm_apcscc'
1343 ///   ::= 'arm_aapcscc'
1344 ///   ::= 'arm_aapcs_vfpcc'
1345 ///   ::= 'msp430_intrcc'
1346 ///   ::= 'ptx_kernel'
1347 ///   ::= 'ptx_device'
1348 ///   ::= 'spir_func'
1349 ///   ::= 'spir_kernel'
1350 ///   ::= 'x86_64_sysvcc'
1351 ///   ::= 'x86_64_win64cc'
1352 ///   ::= 'cc' UINT
1353 ///
1354 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1355   switch (Lex.getKind()) {
1356   default:                       CC = CallingConv::C; return false;
1357   case lltok::kw_ccc:            CC = CallingConv::C; break;
1358   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1359   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1360   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1361   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1362   case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1363   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1364   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1365   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1366   case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
1367   case lltok::kw_ptx_kernel:     CC = CallingConv::PTX_Kernel; break;
1368   case lltok::kw_ptx_device:     CC = CallingConv::PTX_Device; break;
1369   case lltok::kw_spir_kernel:    CC = CallingConv::SPIR_KERNEL; break;
1370   case lltok::kw_spir_func:      CC = CallingConv::SPIR_FUNC; break;
1371   case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1372   case lltok::kw_x86_64_sysvcc:  CC = CallingConv::X86_64_SysV; break;
1373   case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1374   case lltok::kw_cc: {
1375       unsigned ArbitraryCC;
1376       Lex.Lex();
1377       if (ParseUInt32(ArbitraryCC))
1378         return true;
1379       CC = static_cast<CallingConv::ID>(ArbitraryCC);
1380       return false;
1381     }
1382   }
1383
1384   Lex.Lex();
1385   return false;
1386 }
1387
1388 /// ParseInstructionMetadata
1389 ///   ::= !dbg !42 (',' !dbg !57)*
1390 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1391                                         PerFunctionState *PFS) {
1392   do {
1393     if (Lex.getKind() != lltok::MetadataVar)
1394       return TokError("expected metadata after comma");
1395
1396     std::string Name = Lex.getStrVal();
1397     unsigned MDK = M->getMDKindID(Name);
1398     Lex.Lex();
1399
1400     MDNode *Node;
1401     SMLoc Loc = Lex.getLoc();
1402
1403     if (ParseToken(lltok::exclaim, "expected '!' here"))
1404       return true;
1405
1406     // This code is similar to that of ParseMetadataValue, however it needs to
1407     // have special-case code for a forward reference; see the comments on
1408     // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1409     // at the top level here.
1410     if (Lex.getKind() == lltok::lbrace) {
1411       ValID ID;
1412       if (ParseMetadataListValue(ID, PFS))
1413         return true;
1414       assert(ID.Kind == ValID::t_MDNode);
1415       Inst->setMetadata(MDK, ID.MDNodeVal);
1416     } else {
1417       unsigned NodeID = 0;
1418       if (ParseMDNodeID(Node, NodeID))
1419         return true;
1420       if (Node) {
1421         // If we got the node, add it to the instruction.
1422         Inst->setMetadata(MDK, Node);
1423       } else {
1424         MDRef R = { Loc, MDK, NodeID };
1425         // Otherwise, remember that this should be resolved later.
1426         ForwardRefInstMetadata[Inst].push_back(R);
1427       }
1428     }
1429
1430     if (MDK == LLVMContext::MD_tbaa)
1431       InstsWithTBAATag.push_back(Inst);
1432
1433     // If this is the end of the list, we're done.
1434   } while (EatIfPresent(lltok::comma));
1435   return false;
1436 }
1437
1438 /// ParseOptionalAlignment
1439 ///   ::= /* empty */
1440 ///   ::= 'align' 4
1441 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1442   Alignment = 0;
1443   if (!EatIfPresent(lltok::kw_align))
1444     return false;
1445   LocTy AlignLoc = Lex.getLoc();
1446   if (ParseUInt32(Alignment)) return true;
1447   if (!isPowerOf2_32(Alignment))
1448     return Error(AlignLoc, "alignment is not a power of two");
1449   if (Alignment > Value::MaximumAlignment)
1450     return Error(AlignLoc, "huge alignments are not supported yet");
1451   return false;
1452 }
1453
1454 /// ParseOptionalCommaAlign
1455 ///   ::=
1456 ///   ::= ',' align 4
1457 ///
1458 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1459 /// end.
1460 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1461                                        bool &AteExtraComma) {
1462   AteExtraComma = false;
1463   while (EatIfPresent(lltok::comma)) {
1464     // Metadata at the end is an early exit.
1465     if (Lex.getKind() == lltok::MetadataVar) {
1466       AteExtraComma = true;
1467       return false;
1468     }
1469
1470     if (Lex.getKind() != lltok::kw_align)
1471       return Error(Lex.getLoc(), "expected metadata or 'align'");
1472
1473     if (ParseOptionalAlignment(Alignment)) return true;
1474   }
1475
1476   return false;
1477 }
1478
1479 /// ParseScopeAndOrdering
1480 ///   if isAtomic: ::= 'singlethread'? AtomicOrdering
1481 ///   else: ::=
1482 ///
1483 /// This sets Scope and Ordering to the parsed values.
1484 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1485                                      AtomicOrdering &Ordering) {
1486   if (!isAtomic)
1487     return false;
1488
1489   Scope = CrossThread;
1490   if (EatIfPresent(lltok::kw_singlethread))
1491     Scope = SingleThread;
1492   switch (Lex.getKind()) {
1493   default: return TokError("Expected ordering on atomic instruction");
1494   case lltok::kw_unordered: Ordering = Unordered; break;
1495   case lltok::kw_monotonic: Ordering = Monotonic; break;
1496   case lltok::kw_acquire: Ordering = Acquire; break;
1497   case lltok::kw_release: Ordering = Release; break;
1498   case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1499   case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1500   }
1501   Lex.Lex();
1502   return false;
1503 }
1504
1505 /// ParseOptionalStackAlignment
1506 ///   ::= /* empty */
1507 ///   ::= 'alignstack' '(' 4 ')'
1508 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1509   Alignment = 0;
1510   if (!EatIfPresent(lltok::kw_alignstack))
1511     return false;
1512   LocTy ParenLoc = Lex.getLoc();
1513   if (!EatIfPresent(lltok::lparen))
1514     return Error(ParenLoc, "expected '('");
1515   LocTy AlignLoc = Lex.getLoc();
1516   if (ParseUInt32(Alignment)) return true;
1517   ParenLoc = Lex.getLoc();
1518   if (!EatIfPresent(lltok::rparen))
1519     return Error(ParenLoc, "expected ')'");
1520   if (!isPowerOf2_32(Alignment))
1521     return Error(AlignLoc, "stack alignment is not a power of two");
1522   return false;
1523 }
1524
1525 /// ParseIndexList - This parses the index list for an insert/extractvalue
1526 /// instruction.  This sets AteExtraComma in the case where we eat an extra
1527 /// comma at the end of the line and find that it is followed by metadata.
1528 /// Clients that don't allow metadata can call the version of this function that
1529 /// only takes one argument.
1530 ///
1531 /// ParseIndexList
1532 ///    ::=  (',' uint32)+
1533 ///
1534 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1535                               bool &AteExtraComma) {
1536   AteExtraComma = false;
1537
1538   if (Lex.getKind() != lltok::comma)
1539     return TokError("expected ',' as start of index list");
1540
1541   while (EatIfPresent(lltok::comma)) {
1542     if (Lex.getKind() == lltok::MetadataVar) {
1543       AteExtraComma = true;
1544       return false;
1545     }
1546     unsigned Idx = 0;
1547     if (ParseUInt32(Idx)) return true;
1548     Indices.push_back(Idx);
1549   }
1550
1551   return false;
1552 }
1553
1554 //===----------------------------------------------------------------------===//
1555 // Type Parsing.
1556 //===----------------------------------------------------------------------===//
1557
1558 /// ParseType - Parse a type.
1559 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1560   SMLoc TypeLoc = Lex.getLoc();
1561   switch (Lex.getKind()) {
1562   default:
1563     return TokError("expected type");
1564   case lltok::Type:
1565     // Type ::= 'float' | 'void' (etc)
1566     Result = Lex.getTyVal();
1567     Lex.Lex();
1568     break;
1569   case lltok::lbrace:
1570     // Type ::= StructType
1571     if (ParseAnonStructType(Result, false))
1572       return true;
1573     break;
1574   case lltok::lsquare:
1575     // Type ::= '[' ... ']'
1576     Lex.Lex(); // eat the lsquare.
1577     if (ParseArrayVectorType(Result, false))
1578       return true;
1579     break;
1580   case lltok::less: // Either vector or packed struct.
1581     // Type ::= '<' ... '>'
1582     Lex.Lex();
1583     if (Lex.getKind() == lltok::lbrace) {
1584       if (ParseAnonStructType(Result, true) ||
1585           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1586         return true;
1587     } else if (ParseArrayVectorType(Result, true))
1588       return true;
1589     break;
1590   case lltok::LocalVar: {
1591     // Type ::= %foo
1592     std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1593
1594     // If the type hasn't been defined yet, create a forward definition and
1595     // remember where that forward def'n was seen (in case it never is defined).
1596     if (Entry.first == 0) {
1597       Entry.first = StructType::create(Context, Lex.getStrVal());
1598       Entry.second = Lex.getLoc();
1599     }
1600     Result = Entry.first;
1601     Lex.Lex();
1602     break;
1603   }
1604
1605   case lltok::LocalVarID: {
1606     // Type ::= %4
1607     if (Lex.getUIntVal() >= NumberedTypes.size())
1608       NumberedTypes.resize(Lex.getUIntVal()+1);
1609     std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1610
1611     // If the type hasn't been defined yet, create a forward definition and
1612     // remember where that forward def'n was seen (in case it never is defined).
1613     if (Entry.first == 0) {
1614       Entry.first = StructType::create(Context);
1615       Entry.second = Lex.getLoc();
1616     }
1617     Result = Entry.first;
1618     Lex.Lex();
1619     break;
1620   }
1621   }
1622
1623   // Parse the type suffixes.
1624   while (1) {
1625     switch (Lex.getKind()) {
1626     // End of type.
1627     default:
1628       if (!AllowVoid && Result->isVoidTy())
1629         return Error(TypeLoc, "void type only allowed for function results");
1630       return false;
1631
1632     // Type ::= Type '*'
1633     case lltok::star:
1634       if (Result->isLabelTy())
1635         return TokError("basic block pointers are invalid");
1636       if (Result->isVoidTy())
1637         return TokError("pointers to void are invalid - use i8* instead");
1638       if (!PointerType::isValidElementType(Result))
1639         return TokError("pointer to this type is invalid");
1640       Result = PointerType::getUnqual(Result);
1641       Lex.Lex();
1642       break;
1643
1644     // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1645     case lltok::kw_addrspace: {
1646       if (Result->isLabelTy())
1647         return TokError("basic block pointers are invalid");
1648       if (Result->isVoidTy())
1649         return TokError("pointers to void are invalid; use i8* instead");
1650       if (!PointerType::isValidElementType(Result))
1651         return TokError("pointer to this type is invalid");
1652       unsigned AddrSpace;
1653       if (ParseOptionalAddrSpace(AddrSpace) ||
1654           ParseToken(lltok::star, "expected '*' in address space"))
1655         return true;
1656
1657       Result = PointerType::get(Result, AddrSpace);
1658       break;
1659     }
1660
1661     /// Types '(' ArgTypeListI ')' OptFuncAttrs
1662     case lltok::lparen:
1663       if (ParseFunctionType(Result))
1664         return true;
1665       break;
1666     }
1667   }
1668 }
1669
1670 /// ParseParameterList
1671 ///    ::= '(' ')'
1672 ///    ::= '(' Arg (',' Arg)* ')'
1673 ///  Arg
1674 ///    ::= Type OptionalAttributes Value OptionalAttributes
1675 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1676                                   PerFunctionState &PFS) {
1677   if (ParseToken(lltok::lparen, "expected '(' in call"))
1678     return true;
1679
1680   unsigned AttrIndex = 1;
1681   while (Lex.getKind() != lltok::rparen) {
1682     // If this isn't the first argument, we need a comma.
1683     if (!ArgList.empty() &&
1684         ParseToken(lltok::comma, "expected ',' in argument list"))
1685       return true;
1686
1687     // Parse the argument.
1688     LocTy ArgLoc;
1689     Type *ArgTy = 0;
1690     AttrBuilder ArgAttrs;
1691     Value *V;
1692     if (ParseType(ArgTy, ArgLoc))
1693       return true;
1694
1695     // Otherwise, handle normal operands.
1696     if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1697       return true;
1698     ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1699                                                              AttrIndex++,
1700                                                              ArgAttrs)));
1701   }
1702
1703   Lex.Lex();  // Lex the ')'.
1704   return false;
1705 }
1706
1707
1708
1709 /// ParseArgumentList - Parse the argument list for a function type or function
1710 /// prototype.
1711 ///   ::= '(' ArgTypeListI ')'
1712 /// ArgTypeListI
1713 ///   ::= /*empty*/
1714 ///   ::= '...'
1715 ///   ::= ArgTypeList ',' '...'
1716 ///   ::= ArgType (',' ArgType)*
1717 ///
1718 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1719                                  bool &isVarArg){
1720   isVarArg = false;
1721   assert(Lex.getKind() == lltok::lparen);
1722   Lex.Lex(); // eat the (.
1723
1724   if (Lex.getKind() == lltok::rparen) {
1725     // empty
1726   } else if (Lex.getKind() == lltok::dotdotdot) {
1727     isVarArg = true;
1728     Lex.Lex();
1729   } else {
1730     LocTy TypeLoc = Lex.getLoc();
1731     Type *ArgTy = 0;
1732     AttrBuilder Attrs;
1733     std::string Name;
1734
1735     if (ParseType(ArgTy) ||
1736         ParseOptionalParamAttrs(Attrs)) return true;
1737
1738     if (ArgTy->isVoidTy())
1739       return Error(TypeLoc, "argument can not have void type");
1740
1741     if (Lex.getKind() == lltok::LocalVar) {
1742       Name = Lex.getStrVal();
1743       Lex.Lex();
1744     }
1745
1746     if (!FunctionType::isValidArgumentType(ArgTy))
1747       return Error(TypeLoc, "invalid type for function argument");
1748
1749     unsigned AttrIndex = 1;
1750     ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1751                               AttributeSet::get(ArgTy->getContext(),
1752                                                 AttrIndex++, Attrs), Name));
1753
1754     while (EatIfPresent(lltok::comma)) {
1755       // Handle ... at end of arg list.
1756       if (EatIfPresent(lltok::dotdotdot)) {
1757         isVarArg = true;
1758         break;
1759       }
1760
1761       // Otherwise must be an argument type.
1762       TypeLoc = Lex.getLoc();
1763       if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1764
1765       if (ArgTy->isVoidTy())
1766         return Error(TypeLoc, "argument can not have void type");
1767
1768       if (Lex.getKind() == lltok::LocalVar) {
1769         Name = Lex.getStrVal();
1770         Lex.Lex();
1771       } else {
1772         Name = "";
1773       }
1774
1775       if (!ArgTy->isFirstClassType())
1776         return Error(TypeLoc, "invalid type for function argument");
1777
1778       ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1779                                 AttributeSet::get(ArgTy->getContext(),
1780                                                   AttrIndex++, Attrs),
1781                                 Name));
1782     }
1783   }
1784
1785   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1786 }
1787
1788 /// ParseFunctionType
1789 ///  ::= Type ArgumentList OptionalAttrs
1790 bool LLParser::ParseFunctionType(Type *&Result) {
1791   assert(Lex.getKind() == lltok::lparen);
1792
1793   if (!FunctionType::isValidReturnType(Result))
1794     return TokError("invalid function return type");
1795
1796   SmallVector<ArgInfo, 8> ArgList;
1797   bool isVarArg;
1798   if (ParseArgumentList(ArgList, isVarArg))
1799     return true;
1800
1801   // Reject names on the arguments lists.
1802   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1803     if (!ArgList[i].Name.empty())
1804       return Error(ArgList[i].Loc, "argument name invalid in function type");
1805     if (ArgList[i].Attrs.hasAttributes(i + 1))
1806       return Error(ArgList[i].Loc,
1807                    "argument attributes invalid in function type");
1808   }
1809
1810   SmallVector<Type*, 16> ArgListTy;
1811   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1812     ArgListTy.push_back(ArgList[i].Ty);
1813
1814   Result = FunctionType::get(Result, ArgListTy, isVarArg);
1815   return false;
1816 }
1817
1818 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1819 /// other structs.
1820 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1821   SmallVector<Type*, 8> Elts;
1822   if (ParseStructBody(Elts)) return true;
1823
1824   Result = StructType::get(Context, Elts, Packed);
1825   return false;
1826 }
1827
1828 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1829 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1830                                      std::pair<Type*, LocTy> &Entry,
1831                                      Type *&ResultTy) {
1832   // If the type was already defined, diagnose the redefinition.
1833   if (Entry.first && !Entry.second.isValid())
1834     return Error(TypeLoc, "redefinition of type");
1835
1836   // If we have opaque, just return without filling in the definition for the
1837   // struct.  This counts as a definition as far as the .ll file goes.
1838   if (EatIfPresent(lltok::kw_opaque)) {
1839     // This type is being defined, so clear the location to indicate this.
1840     Entry.second = SMLoc();
1841
1842     // If this type number has never been uttered, create it.
1843     if (Entry.first == 0)
1844       Entry.first = StructType::create(Context, Name);
1845     ResultTy = Entry.first;
1846     return false;
1847   }
1848
1849   // If the type starts with '<', then it is either a packed struct or a vector.
1850   bool isPacked = EatIfPresent(lltok::less);
1851
1852   // If we don't have a struct, then we have a random type alias, which we
1853   // accept for compatibility with old files.  These types are not allowed to be
1854   // forward referenced and not allowed to be recursive.
1855   if (Lex.getKind() != lltok::lbrace) {
1856     if (Entry.first)
1857       return Error(TypeLoc, "forward references to non-struct type");
1858
1859     ResultTy = 0;
1860     if (isPacked)
1861       return ParseArrayVectorType(ResultTy, true);
1862     return ParseType(ResultTy);
1863   }
1864
1865   // This type is being defined, so clear the location to indicate this.
1866   Entry.second = SMLoc();
1867
1868   // If this type number has never been uttered, create it.
1869   if (Entry.first == 0)
1870     Entry.first = StructType::create(Context, Name);
1871
1872   StructType *STy = cast<StructType>(Entry.first);
1873
1874   SmallVector<Type*, 8> Body;
1875   if (ParseStructBody(Body) ||
1876       (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1877     return true;
1878
1879   STy->setBody(Body, isPacked);
1880   ResultTy = STy;
1881   return false;
1882 }
1883
1884
1885 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
1886 ///   StructType
1887 ///     ::= '{' '}'
1888 ///     ::= '{' Type (',' Type)* '}'
1889 ///     ::= '<' '{' '}' '>'
1890 ///     ::= '<' '{' Type (',' Type)* '}' '>'
1891 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1892   assert(Lex.getKind() == lltok::lbrace);
1893   Lex.Lex(); // Consume the '{'
1894
1895   // Handle the empty struct.
1896   if (EatIfPresent(lltok::rbrace))
1897     return false;
1898
1899   LocTy EltTyLoc = Lex.getLoc();
1900   Type *Ty = 0;
1901   if (ParseType(Ty)) return true;
1902   Body.push_back(Ty);
1903
1904   if (!StructType::isValidElementType(Ty))
1905     return Error(EltTyLoc, "invalid element type for struct");
1906
1907   while (EatIfPresent(lltok::comma)) {
1908     EltTyLoc = Lex.getLoc();
1909     if (ParseType(Ty)) return true;
1910
1911     if (!StructType::isValidElementType(Ty))
1912       return Error(EltTyLoc, "invalid element type for struct");
1913
1914     Body.push_back(Ty);
1915   }
1916
1917   return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1918 }
1919
1920 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1921 /// token has already been consumed.
1922 ///   Type
1923 ///     ::= '[' APSINTVAL 'x' Types ']'
1924 ///     ::= '<' APSINTVAL 'x' Types '>'
1925 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1926   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1927       Lex.getAPSIntVal().getBitWidth() > 64)
1928     return TokError("expected number in address space");
1929
1930   LocTy SizeLoc = Lex.getLoc();
1931   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1932   Lex.Lex();
1933
1934   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1935       return true;
1936
1937   LocTy TypeLoc = Lex.getLoc();
1938   Type *EltTy = 0;
1939   if (ParseType(EltTy)) return true;
1940
1941   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1942                  "expected end of sequential type"))
1943     return true;
1944
1945   if (isVector) {
1946     if (Size == 0)
1947       return Error(SizeLoc, "zero element vector is illegal");
1948     if ((unsigned)Size != Size)
1949       return Error(SizeLoc, "size too large for vector");
1950     if (!VectorType::isValidElementType(EltTy))
1951       return Error(TypeLoc, "invalid vector element type");
1952     Result = VectorType::get(EltTy, unsigned(Size));
1953   } else {
1954     if (!ArrayType::isValidElementType(EltTy))
1955       return Error(TypeLoc, "invalid array element type");
1956     Result = ArrayType::get(EltTy, Size);
1957   }
1958   return false;
1959 }
1960
1961 //===----------------------------------------------------------------------===//
1962 // Function Semantic Analysis.
1963 //===----------------------------------------------------------------------===//
1964
1965 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1966                                              int functionNumber)
1967   : P(p), F(f), FunctionNumber(functionNumber) {
1968
1969   // Insert unnamed arguments into the NumberedVals list.
1970   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1971        AI != E; ++AI)
1972     if (!AI->hasName())
1973       NumberedVals.push_back(AI);
1974 }
1975
1976 LLParser::PerFunctionState::~PerFunctionState() {
1977   // If there were any forward referenced non-basicblock values, delete them.
1978   for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1979        I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1980     if (!isa<BasicBlock>(I->second.first)) {
1981       I->second.first->replaceAllUsesWith(
1982                            UndefValue::get(I->second.first->getType()));
1983       delete I->second.first;
1984       I->second.first = 0;
1985     }
1986
1987   for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1988        I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1989     if (!isa<BasicBlock>(I->second.first)) {
1990       I->second.first->replaceAllUsesWith(
1991                            UndefValue::get(I->second.first->getType()));
1992       delete I->second.first;
1993       I->second.first = 0;
1994     }
1995 }
1996
1997 bool LLParser::PerFunctionState::FinishFunction() {
1998   // Check to see if someone took the address of labels in this block.
1999   if (!P.ForwardRefBlockAddresses.empty()) {
2000     ValID FunctionID;
2001     if (!F.getName().empty()) {
2002       FunctionID.Kind = ValID::t_GlobalName;
2003       FunctionID.StrVal = F.getName();
2004     } else {
2005       FunctionID.Kind = ValID::t_GlobalID;
2006       FunctionID.UIntVal = FunctionNumber;
2007     }
2008
2009     std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2010       FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2011     if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2012       // Resolve all these references.
2013       if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2014         return true;
2015
2016       P.ForwardRefBlockAddresses.erase(FRBAI);
2017     }
2018   }
2019
2020   if (!ForwardRefVals.empty())
2021     return P.Error(ForwardRefVals.begin()->second.second,
2022                    "use of undefined value '%" + ForwardRefVals.begin()->first +
2023                    "'");
2024   if (!ForwardRefValIDs.empty())
2025     return P.Error(ForwardRefValIDs.begin()->second.second,
2026                    "use of undefined value '%" +
2027                    Twine(ForwardRefValIDs.begin()->first) + "'");
2028   return false;
2029 }
2030
2031
2032 /// GetVal - Get a value with the specified name or ID, creating a
2033 /// forward reference record if needed.  This can return null if the value
2034 /// exists but does not have the right type.
2035 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2036                                           Type *Ty, LocTy Loc) {
2037   // Look this name up in the normal function symbol table.
2038   Value *Val = F.getValueSymbolTable().lookup(Name);
2039
2040   // If this is a forward reference for the value, see if we already created a
2041   // forward ref record.
2042   if (Val == 0) {
2043     std::map<std::string, std::pair<Value*, LocTy> >::iterator
2044       I = ForwardRefVals.find(Name);
2045     if (I != ForwardRefVals.end())
2046       Val = I->second.first;
2047   }
2048
2049   // If we have the value in the symbol table or fwd-ref table, return it.
2050   if (Val) {
2051     if (Val->getType() == Ty) return Val;
2052     if (Ty->isLabelTy())
2053       P.Error(Loc, "'%" + Name + "' is not a basic block");
2054     else
2055       P.Error(Loc, "'%" + Name + "' defined with type '" +
2056               getTypeString(Val->getType()) + "'");
2057     return 0;
2058   }
2059
2060   // Don't make placeholders with invalid type.
2061   if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2062     P.Error(Loc, "invalid use of a non-first-class type");
2063     return 0;
2064   }
2065
2066   // Otherwise, create a new forward reference for this value and remember it.
2067   Value *FwdVal;
2068   if (Ty->isLabelTy())
2069     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2070   else
2071     FwdVal = new Argument(Ty, Name);
2072
2073   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2074   return FwdVal;
2075 }
2076
2077 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2078                                           LocTy Loc) {
2079   // Look this name up in the normal function symbol table.
2080   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
2081
2082   // If this is a forward reference for the value, see if we already created a
2083   // forward ref record.
2084   if (Val == 0) {
2085     std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2086       I = ForwardRefValIDs.find(ID);
2087     if (I != ForwardRefValIDs.end())
2088       Val = I->second.first;
2089   }
2090
2091   // If we have the value in the symbol table or fwd-ref table, return it.
2092   if (Val) {
2093     if (Val->getType() == Ty) return Val;
2094     if (Ty->isLabelTy())
2095       P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2096     else
2097       P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2098               getTypeString(Val->getType()) + "'");
2099     return 0;
2100   }
2101
2102   if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2103     P.Error(Loc, "invalid use of a non-first-class type");
2104     return 0;
2105   }
2106
2107   // Otherwise, create a new forward reference for this value and remember it.
2108   Value *FwdVal;
2109   if (Ty->isLabelTy())
2110     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2111   else
2112     FwdVal = new Argument(Ty);
2113
2114   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2115   return FwdVal;
2116 }
2117
2118 /// SetInstName - After an instruction is parsed and inserted into its
2119 /// basic block, this installs its name.
2120 bool LLParser::PerFunctionState::SetInstName(int NameID,
2121                                              const std::string &NameStr,
2122                                              LocTy NameLoc, Instruction *Inst) {
2123   // If this instruction has void type, it cannot have a name or ID specified.
2124   if (Inst->getType()->isVoidTy()) {
2125     if (NameID != -1 || !NameStr.empty())
2126       return P.Error(NameLoc, "instructions returning void cannot have a name");
2127     return false;
2128   }
2129
2130   // If this was a numbered instruction, verify that the instruction is the
2131   // expected value and resolve any forward references.
2132   if (NameStr.empty()) {
2133     // If neither a name nor an ID was specified, just use the next ID.
2134     if (NameID == -1)
2135       NameID = NumberedVals.size();
2136
2137     if (unsigned(NameID) != NumberedVals.size())
2138       return P.Error(NameLoc, "instruction expected to be numbered '%" +
2139                      Twine(NumberedVals.size()) + "'");
2140
2141     std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2142       ForwardRefValIDs.find(NameID);
2143     if (FI != ForwardRefValIDs.end()) {
2144       if (FI->second.first->getType() != Inst->getType())
2145         return P.Error(NameLoc, "instruction forward referenced with type '" +
2146                        getTypeString(FI->second.first->getType()) + "'");
2147       FI->second.first->replaceAllUsesWith(Inst);
2148       delete FI->second.first;
2149       ForwardRefValIDs.erase(FI);
2150     }
2151
2152     NumberedVals.push_back(Inst);
2153     return false;
2154   }
2155
2156   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
2157   std::map<std::string, std::pair<Value*, LocTy> >::iterator
2158     FI = ForwardRefVals.find(NameStr);
2159   if (FI != ForwardRefVals.end()) {
2160     if (FI->second.first->getType() != Inst->getType())
2161       return P.Error(NameLoc, "instruction forward referenced with type '" +
2162                      getTypeString(FI->second.first->getType()) + "'");
2163     FI->second.first->replaceAllUsesWith(Inst);
2164     delete FI->second.first;
2165     ForwardRefVals.erase(FI);
2166   }
2167
2168   // Set the name on the instruction.
2169   Inst->setName(NameStr);
2170
2171   if (Inst->getName() != NameStr)
2172     return P.Error(NameLoc, "multiple definition of local value named '" +
2173                    NameStr + "'");
2174   return false;
2175 }
2176
2177 /// GetBB - Get a basic block with the specified name or ID, creating a
2178 /// forward reference record if needed.
2179 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2180                                               LocTy Loc) {
2181   return cast_or_null<BasicBlock>(GetVal(Name,
2182                                         Type::getLabelTy(F.getContext()), Loc));
2183 }
2184
2185 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2186   return cast_or_null<BasicBlock>(GetVal(ID,
2187                                         Type::getLabelTy(F.getContext()), Loc));
2188 }
2189
2190 /// DefineBB - Define the specified basic block, which is either named or
2191 /// unnamed.  If there is an error, this returns null otherwise it returns
2192 /// the block being defined.
2193 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2194                                                  LocTy Loc) {
2195   BasicBlock *BB;
2196   if (Name.empty())
2197     BB = GetBB(NumberedVals.size(), Loc);
2198   else
2199     BB = GetBB(Name, Loc);
2200   if (BB == 0) return 0; // Already diagnosed error.
2201
2202   // Move the block to the end of the function.  Forward ref'd blocks are
2203   // inserted wherever they happen to be referenced.
2204   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2205
2206   // Remove the block from forward ref sets.
2207   if (Name.empty()) {
2208     ForwardRefValIDs.erase(NumberedVals.size());
2209     NumberedVals.push_back(BB);
2210   } else {
2211     // BB forward references are already in the function symbol table.
2212     ForwardRefVals.erase(Name);
2213   }
2214
2215   return BB;
2216 }
2217
2218 //===----------------------------------------------------------------------===//
2219 // Constants.
2220 //===----------------------------------------------------------------------===//
2221
2222 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2223 /// type implied.  For example, if we parse "4" we don't know what integer type
2224 /// it has.  The value will later be combined with its type and checked for
2225 /// sanity.  PFS is used to convert function-local operands of metadata (since
2226 /// metadata operands are not just parsed here but also converted to values).
2227 /// PFS can be null when we are not parsing metadata values inside a function.
2228 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2229   ID.Loc = Lex.getLoc();
2230   switch (Lex.getKind()) {
2231   default: return TokError("expected value token");
2232   case lltok::GlobalID:  // @42
2233     ID.UIntVal = Lex.getUIntVal();
2234     ID.Kind = ValID::t_GlobalID;
2235     break;
2236   case lltok::GlobalVar:  // @foo
2237     ID.StrVal = Lex.getStrVal();
2238     ID.Kind = ValID::t_GlobalName;
2239     break;
2240   case lltok::LocalVarID:  // %42
2241     ID.UIntVal = Lex.getUIntVal();
2242     ID.Kind = ValID::t_LocalID;
2243     break;
2244   case lltok::LocalVar:  // %foo
2245     ID.StrVal = Lex.getStrVal();
2246     ID.Kind = ValID::t_LocalName;
2247     break;
2248   case lltok::exclaim:   // !42, !{...}, or !"foo"
2249     return ParseMetadataValue(ID, PFS);
2250   case lltok::APSInt:
2251     ID.APSIntVal = Lex.getAPSIntVal();
2252     ID.Kind = ValID::t_APSInt;
2253     break;
2254   case lltok::APFloat:
2255     ID.APFloatVal = Lex.getAPFloatVal();
2256     ID.Kind = ValID::t_APFloat;
2257     break;
2258   case lltok::kw_true:
2259     ID.ConstantVal = ConstantInt::getTrue(Context);
2260     ID.Kind = ValID::t_Constant;
2261     break;
2262   case lltok::kw_false:
2263     ID.ConstantVal = ConstantInt::getFalse(Context);
2264     ID.Kind = ValID::t_Constant;
2265     break;
2266   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2267   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2268   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2269
2270   case lltok::lbrace: {
2271     // ValID ::= '{' ConstVector '}'
2272     Lex.Lex();
2273     SmallVector<Constant*, 16> Elts;
2274     if (ParseGlobalValueVector(Elts) ||
2275         ParseToken(lltok::rbrace, "expected end of struct constant"))
2276       return true;
2277
2278     ID.ConstantStructElts = new Constant*[Elts.size()];
2279     ID.UIntVal = Elts.size();
2280     memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2281     ID.Kind = ValID::t_ConstantStruct;
2282     return false;
2283   }
2284   case lltok::less: {
2285     // ValID ::= '<' ConstVector '>'         --> Vector.
2286     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2287     Lex.Lex();
2288     bool isPackedStruct = EatIfPresent(lltok::lbrace);
2289
2290     SmallVector<Constant*, 16> Elts;
2291     LocTy FirstEltLoc = Lex.getLoc();
2292     if (ParseGlobalValueVector(Elts) ||
2293         (isPackedStruct &&
2294          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2295         ParseToken(lltok::greater, "expected end of constant"))
2296       return true;
2297
2298     if (isPackedStruct) {
2299       ID.ConstantStructElts = new Constant*[Elts.size()];
2300       memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2301       ID.UIntVal = Elts.size();
2302       ID.Kind = ValID::t_PackedConstantStruct;
2303       return false;
2304     }
2305
2306     if (Elts.empty())
2307       return Error(ID.Loc, "constant vector must not be empty");
2308
2309     if (!Elts[0]->getType()->isIntegerTy() &&
2310         !Elts[0]->getType()->isFloatingPointTy() &&
2311         !Elts[0]->getType()->isPointerTy())
2312       return Error(FirstEltLoc,
2313             "vector elements must have integer, pointer or floating point type");
2314
2315     // Verify that all the vector elements have the same type.
2316     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2317       if (Elts[i]->getType() != Elts[0]->getType())
2318         return Error(FirstEltLoc,
2319                      "vector element #" + Twine(i) +
2320                     " is not of type '" + getTypeString(Elts[0]->getType()));
2321
2322     ID.ConstantVal = ConstantVector::get(Elts);
2323     ID.Kind = ValID::t_Constant;
2324     return false;
2325   }
2326   case lltok::lsquare: {   // Array Constant
2327     Lex.Lex();
2328     SmallVector<Constant*, 16> Elts;
2329     LocTy FirstEltLoc = Lex.getLoc();
2330     if (ParseGlobalValueVector(Elts) ||
2331         ParseToken(lltok::rsquare, "expected end of array constant"))
2332       return true;
2333
2334     // Handle empty element.
2335     if (Elts.empty()) {
2336       // Use undef instead of an array because it's inconvenient to determine
2337       // the element type at this point, there being no elements to examine.
2338       ID.Kind = ValID::t_EmptyArray;
2339       return false;
2340     }
2341
2342     if (!Elts[0]->getType()->isFirstClassType())
2343       return Error(FirstEltLoc, "invalid array element type: " +
2344                    getTypeString(Elts[0]->getType()));
2345
2346     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2347
2348     // Verify all elements are correct type!
2349     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2350       if (Elts[i]->getType() != Elts[0]->getType())
2351         return Error(FirstEltLoc,
2352                      "array element #" + Twine(i) +
2353                      " is not of type '" + getTypeString(Elts[0]->getType()));
2354     }
2355
2356     ID.ConstantVal = ConstantArray::get(ATy, Elts);
2357     ID.Kind = ValID::t_Constant;
2358     return false;
2359   }
2360   case lltok::kw_c:  // c "foo"
2361     Lex.Lex();
2362     ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2363                                                   false);
2364     if (ParseToken(lltok::StringConstant, "expected string")) return true;
2365     ID.Kind = ValID::t_Constant;
2366     return false;
2367
2368   case lltok::kw_asm: {
2369     // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2370     //             STRINGCONSTANT
2371     bool HasSideEffect, AlignStack, AsmDialect;
2372     Lex.Lex();
2373     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2374         ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2375         ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2376         ParseStringConstant(ID.StrVal) ||
2377         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2378         ParseToken(lltok::StringConstant, "expected constraint string"))
2379       return true;
2380     ID.StrVal2 = Lex.getStrVal();
2381     ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2382       (unsigned(AsmDialect)<<2);
2383     ID.Kind = ValID::t_InlineAsm;
2384     return false;
2385   }
2386
2387   case lltok::kw_blockaddress: {
2388     // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2389     Lex.Lex();
2390
2391     ValID Fn, Label;
2392
2393     if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2394         ParseValID(Fn) ||
2395         ParseToken(lltok::comma, "expected comma in block address expression")||
2396         ParseValID(Label) ||
2397         ParseToken(lltok::rparen, "expected ')' in block address expression"))
2398       return true;
2399
2400     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2401       return Error(Fn.Loc, "expected function name in blockaddress");
2402     if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2403       return Error(Label.Loc, "expected basic block name in blockaddress");
2404
2405     // Make a global variable as a placeholder for this reference.
2406     GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2407                                            false, GlobalValue::InternalLinkage,
2408                                                 0, "");
2409     ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2410     ID.ConstantVal = FwdRef;
2411     ID.Kind = ValID::t_Constant;
2412     return false;
2413   }
2414
2415   case lltok::kw_trunc:
2416   case lltok::kw_zext:
2417   case lltok::kw_sext:
2418   case lltok::kw_fptrunc:
2419   case lltok::kw_fpext:
2420   case lltok::kw_bitcast:
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::LinkOnceODRAutoHideLinkage:
2962   case GlobalValue::WeakAnyLinkage:
2963   case GlobalValue::WeakODRLinkage:
2964   case GlobalValue::DLLExportLinkage:
2965     if (!isDefine)
2966       return Error(LinkageLoc, "invalid linkage for function declaration");
2967     break;
2968   case GlobalValue::AppendingLinkage:
2969   case GlobalValue::CommonLinkage:
2970     return Error(LinkageLoc, "invalid function linkage type");
2971   }
2972
2973   if (!FunctionType::isValidReturnType(RetType))
2974     return Error(RetTypeLoc, "invalid function return type");
2975
2976   LocTy NameLoc = Lex.getLoc();
2977
2978   std::string FunctionName;
2979   if (Lex.getKind() == lltok::GlobalVar) {
2980     FunctionName = Lex.getStrVal();
2981   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
2982     unsigned NameID = Lex.getUIntVal();
2983
2984     if (NameID != NumberedVals.size())
2985       return TokError("function expected to be numbered '%" +
2986                       Twine(NumberedVals.size()) + "'");
2987   } else {
2988     return TokError("expected function name");
2989   }
2990
2991   Lex.Lex();
2992
2993   if (Lex.getKind() != lltok::lparen)
2994     return TokError("expected '(' in function argument list");
2995
2996   SmallVector<ArgInfo, 8> ArgList;
2997   bool isVarArg;
2998   AttrBuilder FuncAttrs;
2999   std::vector<unsigned> FwdRefAttrGrps;
3000   LocTy BuiltinLoc;
3001   std::string Section;
3002   unsigned Alignment;
3003   std::string GC;
3004   bool UnnamedAddr;
3005   LocTy UnnamedAddrLoc;
3006   Constant *Prefix = 0;
3007
3008   if (ParseArgumentList(ArgList, isVarArg) ||
3009       ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3010                          &UnnamedAddrLoc) ||
3011       ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3012                                  BuiltinLoc) ||
3013       (EatIfPresent(lltok::kw_section) &&
3014        ParseStringConstant(Section)) ||
3015       ParseOptionalAlignment(Alignment) ||
3016       (EatIfPresent(lltok::kw_gc) &&
3017        ParseStringConstant(GC)) ||
3018       (EatIfPresent(lltok::kw_prefix) &&
3019        ParseGlobalTypeAndValue(Prefix)))
3020     return true;
3021
3022   if (FuncAttrs.contains(Attribute::Builtin))
3023     return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3024
3025   // If the alignment was parsed as an attribute, move to the alignment field.
3026   if (FuncAttrs.hasAlignmentAttr()) {
3027     Alignment = FuncAttrs.getAlignment();
3028     FuncAttrs.removeAttribute(Attribute::Alignment);
3029   }
3030
3031   // Okay, if we got here, the function is syntactically valid.  Convert types
3032   // and do semantic checks.
3033   std::vector<Type*> ParamTypeList;
3034   SmallVector<AttributeSet, 8> Attrs;
3035
3036   if (RetAttrs.hasAttributes())
3037     Attrs.push_back(AttributeSet::get(RetType->getContext(),
3038                                       AttributeSet::ReturnIndex,
3039                                       RetAttrs));
3040
3041   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3042     ParamTypeList.push_back(ArgList[i].Ty);
3043     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3044       AttrBuilder B(ArgList[i].Attrs, i + 1);
3045       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3046     }
3047   }
3048
3049   if (FuncAttrs.hasAttributes())
3050     Attrs.push_back(AttributeSet::get(RetType->getContext(),
3051                                       AttributeSet::FunctionIndex,
3052                                       FuncAttrs));
3053
3054   AttributeSet PAL = AttributeSet::get(Context, Attrs);
3055
3056   if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3057     return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3058
3059   FunctionType *FT =
3060     FunctionType::get(RetType, ParamTypeList, isVarArg);
3061   PointerType *PFT = PointerType::getUnqual(FT);
3062
3063   Fn = 0;
3064   if (!FunctionName.empty()) {
3065     // If this was a definition of a forward reference, remove the definition
3066     // from the forward reference table and fill in the forward ref.
3067     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3068       ForwardRefVals.find(FunctionName);
3069     if (FRVI != ForwardRefVals.end()) {
3070       Fn = M->getFunction(FunctionName);
3071       if (!Fn)
3072         return Error(FRVI->second.second, "invalid forward reference to "
3073                      "function as global value!");
3074       if (Fn->getType() != PFT)
3075         return Error(FRVI->second.second, "invalid forward reference to "
3076                      "function '" + FunctionName + "' with wrong type!");
3077
3078       ForwardRefVals.erase(FRVI);
3079     } else if ((Fn = M->getFunction(FunctionName))) {
3080       // Reject redefinitions.
3081       return Error(NameLoc, "invalid redefinition of function '" +
3082                    FunctionName + "'");
3083     } else if (M->getNamedValue(FunctionName)) {
3084       return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3085     }
3086
3087   } else {
3088     // If this is a definition of a forward referenced function, make sure the
3089     // types agree.
3090     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3091       = ForwardRefValIDs.find(NumberedVals.size());
3092     if (I != ForwardRefValIDs.end()) {
3093       Fn = cast<Function>(I->second.first);
3094       if (Fn->getType() != PFT)
3095         return Error(NameLoc, "type of definition and forward reference of '@" +
3096                      Twine(NumberedVals.size()) + "' disagree");
3097       ForwardRefValIDs.erase(I);
3098     }
3099   }
3100
3101   if (Fn == 0)
3102     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3103   else // Move the forward-reference to the correct spot in the module.
3104     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3105
3106   if (FunctionName.empty())
3107     NumberedVals.push_back(Fn);
3108
3109   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3110   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3111   Fn->setCallingConv(CC);
3112   Fn->setAttributes(PAL);
3113   Fn->setUnnamedAddr(UnnamedAddr);
3114   Fn->setAlignment(Alignment);
3115   Fn->setSection(Section);
3116   if (!GC.empty()) Fn->setGC(GC.c_str());
3117   Fn->setPrefixData(Prefix);
3118   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3119
3120   // Add all of the arguments we parsed to the function.
3121   Function::arg_iterator ArgIt = Fn->arg_begin();
3122   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3123     // If the argument has a name, insert it into the argument symbol table.
3124     if (ArgList[i].Name.empty()) continue;
3125
3126     // Set the name, if it conflicted, it will be auto-renamed.
3127     ArgIt->setName(ArgList[i].Name);
3128
3129     if (ArgIt->getName() != ArgList[i].Name)
3130       return Error(ArgList[i].Loc, "redefinition of argument '%" +
3131                    ArgList[i].Name + "'");
3132   }
3133
3134   return false;
3135 }
3136
3137
3138 /// ParseFunctionBody
3139 ///   ::= '{' BasicBlock+ '}'
3140 ///
3141 bool LLParser::ParseFunctionBody(Function &Fn) {
3142   if (Lex.getKind() != lltok::lbrace)
3143     return TokError("expected '{' in function body");
3144   Lex.Lex();  // eat the {.
3145
3146   int FunctionNumber = -1;
3147   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3148
3149   PerFunctionState PFS(*this, Fn, FunctionNumber);
3150
3151   // We need at least one basic block.
3152   if (Lex.getKind() == lltok::rbrace)
3153     return TokError("function body requires at least one basic block");
3154
3155   while (Lex.getKind() != lltok::rbrace)
3156     if (ParseBasicBlock(PFS)) return true;
3157
3158   // Eat the }.
3159   Lex.Lex();
3160
3161   // Verify function is ok.
3162   return PFS.FinishFunction();
3163 }
3164
3165 /// ParseBasicBlock
3166 ///   ::= LabelStr? Instruction*
3167 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3168   // If this basic block starts out with a name, remember it.
3169   std::string Name;
3170   LocTy NameLoc = Lex.getLoc();
3171   if (Lex.getKind() == lltok::LabelStr) {
3172     Name = Lex.getStrVal();
3173     Lex.Lex();
3174   }
3175
3176   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3177   if (BB == 0) return true;
3178
3179   std::string NameStr;
3180
3181   // Parse the instructions in this block until we get a terminator.
3182   Instruction *Inst;
3183   do {
3184     // This instruction may have three possibilities for a name: a) none
3185     // specified, b) name specified "%foo =", c) number specified: "%4 =".
3186     LocTy NameLoc = Lex.getLoc();
3187     int NameID = -1;
3188     NameStr = "";
3189
3190     if (Lex.getKind() == lltok::LocalVarID) {
3191       NameID = Lex.getUIntVal();
3192       Lex.Lex();
3193       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3194         return true;
3195     } else if (Lex.getKind() == lltok::LocalVar) {
3196       NameStr = Lex.getStrVal();
3197       Lex.Lex();
3198       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3199         return true;
3200     }
3201
3202     switch (ParseInstruction(Inst, BB, PFS)) {
3203     default: llvm_unreachable("Unknown ParseInstruction result!");
3204     case InstError: return true;
3205     case InstNormal:
3206       BB->getInstList().push_back(Inst);
3207
3208       // With a normal result, we check to see if the instruction is followed by
3209       // a comma and metadata.
3210       if (EatIfPresent(lltok::comma))
3211         if (ParseInstructionMetadata(Inst, &PFS))
3212           return true;
3213       break;
3214     case InstExtraComma:
3215       BB->getInstList().push_back(Inst);
3216
3217       // If the instruction parser ate an extra comma at the end of it, it
3218       // *must* be followed by metadata.
3219       if (ParseInstructionMetadata(Inst, &PFS))
3220         return true;
3221       break;
3222     }
3223
3224     // Set the name on the instruction.
3225     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3226   } while (!isa<TerminatorInst>(Inst));
3227
3228   return false;
3229 }
3230
3231 //===----------------------------------------------------------------------===//
3232 // Instruction Parsing.
3233 //===----------------------------------------------------------------------===//
3234
3235 /// ParseInstruction - Parse one of the many different instructions.
3236 ///
3237 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3238                                PerFunctionState &PFS) {
3239   lltok::Kind Token = Lex.getKind();
3240   if (Token == lltok::Eof)
3241     return TokError("found end of file when expecting more instructions");
3242   LocTy Loc = Lex.getLoc();
3243   unsigned KeywordVal = Lex.getUIntVal();
3244   Lex.Lex();  // Eat the keyword.
3245
3246   switch (Token) {
3247   default:                    return Error(Loc, "expected instruction opcode");
3248   // Terminator Instructions.
3249   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3250   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
3251   case lltok::kw_br:          return ParseBr(Inst, PFS);
3252   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
3253   case lltok::kw_indirectbr:  return ParseIndirectBr(Inst, PFS);
3254   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
3255   case lltok::kw_resume:      return ParseResume(Inst, PFS);
3256   // Binary Operators.
3257   case lltok::kw_add:
3258   case lltok::kw_sub:
3259   case lltok::kw_mul:
3260   case lltok::kw_shl: {
3261     bool NUW = EatIfPresent(lltok::kw_nuw);
3262     bool NSW = EatIfPresent(lltok::kw_nsw);
3263     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3264
3265     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3266
3267     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3268     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3269     return false;
3270   }
3271   case lltok::kw_fadd:
3272   case lltok::kw_fsub:
3273   case lltok::kw_fmul:
3274   case lltok::kw_fdiv:
3275   case lltok::kw_frem: {
3276     FastMathFlags FMF = EatFastMathFlagsIfPresent();
3277     int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3278     if (Res != 0)
3279       return Res;
3280     if (FMF.any())
3281       Inst->setFastMathFlags(FMF);
3282     return 0;
3283   }
3284
3285   case lltok::kw_sdiv:
3286   case lltok::kw_udiv:
3287   case lltok::kw_lshr:
3288   case lltok::kw_ashr: {
3289     bool Exact = EatIfPresent(lltok::kw_exact);
3290
3291     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3292     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3293     return false;
3294   }
3295
3296   case lltok::kw_urem:
3297   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3298   case lltok::kw_and:
3299   case lltok::kw_or:
3300   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
3301   case lltok::kw_icmp:
3302   case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
3303   // Casts.
3304   case lltok::kw_trunc:
3305   case lltok::kw_zext:
3306   case lltok::kw_sext:
3307   case lltok::kw_fptrunc:
3308   case lltok::kw_fpext:
3309   case lltok::kw_bitcast:
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 }