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