[opaque pointer type] Add textual IR support for explicit type parameter for global...
[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/ADT/STLExtras.h"
17 #include "llvm/AsmParser/SlotMapping.h"
18 #include "llvm/IR/AutoUpgrade.h"
19 #include "llvm/IR/CallingConv.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DebugInfo.h"
22 #include "llvm/IR/DebugInfoMetadata.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/ValueSymbolTable.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/SaveAndRestore.h"
33 #include "llvm/Support/raw_ostream.h"
34 using namespace llvm;
35
36 static std::string getTypeString(Type *T) {
37   std::string Result;
38   raw_string_ostream Tmp(Result);
39   Tmp << *T;
40   return Tmp.str();
41 }
42
43 /// Run: module ::= toplevelentity*
44 bool LLParser::Run() {
45   // Prime the lexer.
46   Lex.Lex();
47
48   return ParseTopLevelEntities() ||
49          ValidateEndOfModule();
50 }
51
52 bool LLParser::parseStandaloneConstantValue(Constant *&C,
53                                             const SlotMapping *Slots) {
54   restoreParsingState(Slots);
55   Lex.Lex();
56
57   Type *Ty = nullptr;
58   if (ParseType(Ty) || parseConstantValue(Ty, C))
59     return true;
60   if (Lex.getKind() != lltok::Eof)
61     return Error(Lex.getLoc(), "expected end of string");
62   return false;
63 }
64
65 void LLParser::restoreParsingState(const SlotMapping *Slots) {
66   if (!Slots)
67     return;
68   NumberedVals = Slots->GlobalValues;
69   NumberedMetadata = Slots->MetadataNodes;
70   for (const auto &I : Slots->NamedTypes)
71     NamedTypes.insert(
72         std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
73   for (const auto &I : Slots->Types)
74     NumberedTypes.insert(
75         std::make_pair(I.first, std::make_pair(I.second, LocTy())));
76 }
77
78 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
79 /// module.
80 bool LLParser::ValidateEndOfModule() {
81   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
82     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
83
84   // Handle any function attribute group forward references.
85   for (std::map<Value*, std::vector<unsigned> >::iterator
86          I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
87          I != E; ++I) {
88     Value *V = I->first;
89     std::vector<unsigned> &Vec = I->second;
90     AttrBuilder B;
91
92     for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
93          VI != VE; ++VI)
94       B.merge(NumberedAttrBuilders[*VI]);
95
96     if (Function *Fn = dyn_cast<Function>(V)) {
97       AttributeSet AS = Fn->getAttributes();
98       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
99       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
100                                AS.getFnAttributes());
101
102       FnAttrs.merge(B);
103
104       // If the alignment was parsed as an attribute, move to the alignment
105       // field.
106       if (FnAttrs.hasAlignmentAttr()) {
107         Fn->setAlignment(FnAttrs.getAlignment());
108         FnAttrs.removeAttribute(Attribute::Alignment);
109       }
110
111       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
112                             AttributeSet::get(Context,
113                                               AttributeSet::FunctionIndex,
114                                               FnAttrs));
115       Fn->setAttributes(AS);
116     } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
117       AttributeSet AS = CI->getAttributes();
118       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
119       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
120                                AS.getFnAttributes());
121       FnAttrs.merge(B);
122       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
123                             AttributeSet::get(Context,
124                                               AttributeSet::FunctionIndex,
125                                               FnAttrs));
126       CI->setAttributes(AS);
127     } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
128       AttributeSet AS = II->getAttributes();
129       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
130       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
131                                AS.getFnAttributes());
132       FnAttrs.merge(B);
133       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
134                             AttributeSet::get(Context,
135                                               AttributeSet::FunctionIndex,
136                                               FnAttrs));
137       II->setAttributes(AS);
138     } else {
139       llvm_unreachable("invalid object with forward attribute group reference");
140     }
141   }
142
143   // If there are entries in ForwardRefBlockAddresses at this point, the
144   // function was never defined.
145   if (!ForwardRefBlockAddresses.empty())
146     return Error(ForwardRefBlockAddresses.begin()->first.Loc,
147                  "expected function name in blockaddress");
148
149   for (const auto &NT : NumberedTypes)
150     if (NT.second.second.isValid())
151       return Error(NT.second.second,
152                    "use of undefined type '%" + Twine(NT.first) + "'");
153
154   for (StringMap<std::pair<Type*, LocTy> >::iterator I =
155        NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
156     if (I->second.second.isValid())
157       return Error(I->second.second,
158                    "use of undefined type named '" + I->getKey() + "'");
159
160   if (!ForwardRefComdats.empty())
161     return Error(ForwardRefComdats.begin()->second,
162                  "use of undefined comdat '$" +
163                      ForwardRefComdats.begin()->first + "'");
164
165   if (!ForwardRefVals.empty())
166     return Error(ForwardRefVals.begin()->second.second,
167                  "use of undefined value '@" + ForwardRefVals.begin()->first +
168                  "'");
169
170   if (!ForwardRefValIDs.empty())
171     return Error(ForwardRefValIDs.begin()->second.second,
172                  "use of undefined value '@" +
173                  Twine(ForwardRefValIDs.begin()->first) + "'");
174
175   if (!ForwardRefMDNodes.empty())
176     return Error(ForwardRefMDNodes.begin()->second.second,
177                  "use of undefined metadata '!" +
178                  Twine(ForwardRefMDNodes.begin()->first) + "'");
179
180   // Resolve metadata cycles.
181   for (auto &N : NumberedMetadata) {
182     if (N.second && !N.second->isResolved())
183       N.second->resolveCycles();
184   }
185
186   // Look for intrinsic functions and CallInst that need to be upgraded
187   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
188     UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
189
190   UpgradeDebugInfo(*M);
191
192   if (!Slots)
193     return false;
194   // Initialize the slot mapping.
195   // Because by this point we've parsed and validated everything, we can "steal"
196   // the mapping from LLParser as it doesn't need it anymore.
197   Slots->GlobalValues = std::move(NumberedVals);
198   Slots->MetadataNodes = std::move(NumberedMetadata);
199   for (const auto &I : NamedTypes)
200     Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
201   for (const auto &I : NumberedTypes)
202     Slots->Types.insert(std::make_pair(I.first, I.second.first));
203
204   return false;
205 }
206
207 //===----------------------------------------------------------------------===//
208 // Top-Level Entities
209 //===----------------------------------------------------------------------===//
210
211 bool LLParser::ParseTopLevelEntities() {
212   while (1) {
213     switch (Lex.getKind()) {
214     default:         return TokError("expected top-level entity");
215     case lltok::Eof: return false;
216     case lltok::kw_declare: if (ParseDeclare()) return true; break;
217     case lltok::kw_define:  if (ParseDefine()) return true; break;
218     case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
219     case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
220     case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
221     case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
222     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
223     case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
224     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
225     case lltok::ComdatVar:  if (parseComdat()) return true; break;
226     case lltok::exclaim:    if (ParseStandaloneMetadata()) return true; break;
227     case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
228
229     // The Global variable production with no name can have many different
230     // optional leading prefixes, the production is:
231     // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
232     //               OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
233     //               ('constant'|'global') ...
234     case lltok::kw_private:             // OptionalLinkage
235     case lltok::kw_internal:            // OptionalLinkage
236     case lltok::kw_weak:                // OptionalLinkage
237     case lltok::kw_weak_odr:            // OptionalLinkage
238     case lltok::kw_linkonce:            // OptionalLinkage
239     case lltok::kw_linkonce_odr:        // OptionalLinkage
240     case lltok::kw_appending:           // OptionalLinkage
241     case lltok::kw_common:              // OptionalLinkage
242     case lltok::kw_extern_weak:         // OptionalLinkage
243     case lltok::kw_external:            // OptionalLinkage
244     case lltok::kw_default:             // OptionalVisibility
245     case lltok::kw_hidden:              // OptionalVisibility
246     case lltok::kw_protected:           // OptionalVisibility
247     case lltok::kw_dllimport:           // OptionalDLLStorageClass
248     case lltok::kw_dllexport:           // OptionalDLLStorageClass
249     case lltok::kw_thread_local:        // OptionalThreadLocal
250     case lltok::kw_addrspace:           // OptionalAddrSpace
251     case lltok::kw_constant:            // GlobalType
252     case lltok::kw_global: {            // GlobalType
253       unsigned Linkage, Visibility, DLLStorageClass;
254       bool UnnamedAddr;
255       GlobalVariable::ThreadLocalMode TLM;
256       bool HasLinkage;
257       if (ParseOptionalLinkage(Linkage, HasLinkage) ||
258           ParseOptionalVisibility(Visibility) ||
259           ParseOptionalDLLStorageClass(DLLStorageClass) ||
260           ParseOptionalThreadLocal(TLM) ||
261           parseOptionalUnnamedAddr(UnnamedAddr) ||
262           ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
263                       DLLStorageClass, TLM, UnnamedAddr))
264         return true;
265       break;
266     }
267
268     case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
269     case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
270     case lltok::kw_uselistorder_bb:
271                                  if (ParseUseListOrderBB()) return true; break;
272     }
273   }
274 }
275
276
277 /// toplevelentity
278 ///   ::= 'module' 'asm' STRINGCONSTANT
279 bool LLParser::ParseModuleAsm() {
280   assert(Lex.getKind() == lltok::kw_module);
281   Lex.Lex();
282
283   std::string AsmStr;
284   if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
285       ParseStringConstant(AsmStr)) return true;
286
287   M->appendModuleInlineAsm(AsmStr);
288   return false;
289 }
290
291 /// toplevelentity
292 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
293 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
294 bool LLParser::ParseTargetDefinition() {
295   assert(Lex.getKind() == lltok::kw_target);
296   std::string Str;
297   switch (Lex.Lex()) {
298   default: return TokError("unknown target property");
299   case lltok::kw_triple:
300     Lex.Lex();
301     if (ParseToken(lltok::equal, "expected '=' after target triple") ||
302         ParseStringConstant(Str))
303       return true;
304     M->setTargetTriple(Str);
305     return false;
306   case lltok::kw_datalayout:
307     Lex.Lex();
308     if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
309         ParseStringConstant(Str))
310       return true;
311     M->setDataLayout(Str);
312     return false;
313   }
314 }
315
316 /// toplevelentity
317 ///   ::= 'deplibs' '=' '[' ']'
318 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
319 /// FIXME: Remove in 4.0. Currently parse, but ignore.
320 bool LLParser::ParseDepLibs() {
321   assert(Lex.getKind() == lltok::kw_deplibs);
322   Lex.Lex();
323   if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
324       ParseToken(lltok::lsquare, "expected '=' after deplibs"))
325     return true;
326
327   if (EatIfPresent(lltok::rsquare))
328     return false;
329
330   do {
331     std::string Str;
332     if (ParseStringConstant(Str)) return true;
333   } while (EatIfPresent(lltok::comma));
334
335   return ParseToken(lltok::rsquare, "expected ']' at end of list");
336 }
337
338 /// ParseUnnamedType:
339 ///   ::= LocalVarID '=' 'type' type
340 bool LLParser::ParseUnnamedType() {
341   LocTy TypeLoc = Lex.getLoc();
342   unsigned TypeID = Lex.getUIntVal();
343   Lex.Lex(); // eat LocalVarID;
344
345   if (ParseToken(lltok::equal, "expected '=' after name") ||
346       ParseToken(lltok::kw_type, "expected 'type' after '='"))
347     return true;
348
349   Type *Result = nullptr;
350   if (ParseStructDefinition(TypeLoc, "",
351                             NumberedTypes[TypeID], Result)) return true;
352
353   if (!isa<StructType>(Result)) {
354     std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
355     if (Entry.first)
356       return Error(TypeLoc, "non-struct types may not be recursive");
357     Entry.first = Result;
358     Entry.second = SMLoc();
359   }
360
361   return false;
362 }
363
364
365 /// toplevelentity
366 ///   ::= LocalVar '=' 'type' type
367 bool LLParser::ParseNamedType() {
368   std::string Name = Lex.getStrVal();
369   LocTy NameLoc = Lex.getLoc();
370   Lex.Lex();  // eat LocalVar.
371
372   if (ParseToken(lltok::equal, "expected '=' after name") ||
373       ParseToken(lltok::kw_type, "expected 'type' after name"))
374     return true;
375
376   Type *Result = nullptr;
377   if (ParseStructDefinition(NameLoc, Name,
378                             NamedTypes[Name], Result)) return true;
379
380   if (!isa<StructType>(Result)) {
381     std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
382     if (Entry.first)
383       return Error(NameLoc, "non-struct types may not be recursive");
384     Entry.first = Result;
385     Entry.second = SMLoc();
386   }
387
388   return false;
389 }
390
391
392 /// toplevelentity
393 ///   ::= 'declare' FunctionHeader
394 bool LLParser::ParseDeclare() {
395   assert(Lex.getKind() == lltok::kw_declare);
396   Lex.Lex();
397
398   Function *F;
399   return ParseFunctionHeader(F, false);
400 }
401
402 /// toplevelentity
403 ///   ::= 'define' FunctionHeader (!dbg !56)* '{' ...
404 bool LLParser::ParseDefine() {
405   assert(Lex.getKind() == lltok::kw_define);
406   Lex.Lex();
407
408   Function *F;
409   return ParseFunctionHeader(F, true) ||
410          ParseOptionalFunctionMetadata(*F) ||
411          ParseFunctionBody(*F);
412 }
413
414 /// ParseGlobalType
415 ///   ::= 'constant'
416 ///   ::= 'global'
417 bool LLParser::ParseGlobalType(bool &IsConstant) {
418   if (Lex.getKind() == lltok::kw_constant)
419     IsConstant = true;
420   else if (Lex.getKind() == lltok::kw_global)
421     IsConstant = false;
422   else {
423     IsConstant = false;
424     return TokError("expected 'global' or 'constant'");
425   }
426   Lex.Lex();
427   return false;
428 }
429
430 /// ParseUnnamedGlobal:
431 ///   OptionalVisibility ALIAS ...
432 ///   OptionalLinkage OptionalVisibility OptionalDLLStorageClass
433 ///                                                     ...   -> global variable
434 ///   GlobalID '=' OptionalVisibility ALIAS ...
435 ///   GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
436 ///                                                     ...   -> global variable
437 bool LLParser::ParseUnnamedGlobal() {
438   unsigned VarID = NumberedVals.size();
439   std::string Name;
440   LocTy NameLoc = Lex.getLoc();
441
442   // Handle the GlobalID form.
443   if (Lex.getKind() == lltok::GlobalID) {
444     if (Lex.getUIntVal() != VarID)
445       return Error(Lex.getLoc(), "variable expected to be numbered '%" +
446                    Twine(VarID) + "'");
447     Lex.Lex(); // eat GlobalID;
448
449     if (ParseToken(lltok::equal, "expected '=' after name"))
450       return true;
451   }
452
453   bool HasLinkage;
454   unsigned Linkage, Visibility, DLLStorageClass;
455   GlobalVariable::ThreadLocalMode TLM;
456   bool UnnamedAddr;
457   if (ParseOptionalLinkage(Linkage, HasLinkage) ||
458       ParseOptionalVisibility(Visibility) ||
459       ParseOptionalDLLStorageClass(DLLStorageClass) ||
460       ParseOptionalThreadLocal(TLM) ||
461       parseOptionalUnnamedAddr(UnnamedAddr))
462     return true;
463
464   if (Lex.getKind() != lltok::kw_alias)
465     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
466                        DLLStorageClass, TLM, UnnamedAddr);
467   return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
468                     UnnamedAddr);
469 }
470
471 /// ParseNamedGlobal:
472 ///   GlobalVar '=' OptionalVisibility ALIAS ...
473 ///   GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
474 ///                                                     ...   -> global variable
475 bool LLParser::ParseNamedGlobal() {
476   assert(Lex.getKind() == lltok::GlobalVar);
477   LocTy NameLoc = Lex.getLoc();
478   std::string Name = Lex.getStrVal();
479   Lex.Lex();
480
481   bool HasLinkage;
482   unsigned Linkage, Visibility, DLLStorageClass;
483   GlobalVariable::ThreadLocalMode TLM;
484   bool UnnamedAddr;
485   if (ParseToken(lltok::equal, "expected '=' in global variable") ||
486       ParseOptionalLinkage(Linkage, HasLinkage) ||
487       ParseOptionalVisibility(Visibility) ||
488       ParseOptionalDLLStorageClass(DLLStorageClass) ||
489       ParseOptionalThreadLocal(TLM) ||
490       parseOptionalUnnamedAddr(UnnamedAddr))
491     return true;
492
493   if (Lex.getKind() != lltok::kw_alias)
494     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
495                        DLLStorageClass, TLM, UnnamedAddr);
496
497   return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
498                     UnnamedAddr);
499 }
500
501 bool LLParser::parseComdat() {
502   assert(Lex.getKind() == lltok::ComdatVar);
503   std::string Name = Lex.getStrVal();
504   LocTy NameLoc = Lex.getLoc();
505   Lex.Lex();
506
507   if (ParseToken(lltok::equal, "expected '=' here"))
508     return true;
509
510   if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
511     return TokError("expected comdat type");
512
513   Comdat::SelectionKind SK;
514   switch (Lex.getKind()) {
515   default:
516     return TokError("unknown selection kind");
517   case lltok::kw_any:
518     SK = Comdat::Any;
519     break;
520   case lltok::kw_exactmatch:
521     SK = Comdat::ExactMatch;
522     break;
523   case lltok::kw_largest:
524     SK = Comdat::Largest;
525     break;
526   case lltok::kw_noduplicates:
527     SK = Comdat::NoDuplicates;
528     break;
529   case lltok::kw_samesize:
530     SK = Comdat::SameSize;
531     break;
532   }
533   Lex.Lex();
534
535   // See if the comdat was forward referenced, if so, use the comdat.
536   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
537   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
538   if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
539     return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
540
541   Comdat *C;
542   if (I != ComdatSymTab.end())
543     C = &I->second;
544   else
545     C = M->getOrInsertComdat(Name);
546   C->setSelectionKind(SK);
547
548   return false;
549 }
550
551 // MDString:
552 //   ::= '!' STRINGCONSTANT
553 bool LLParser::ParseMDString(MDString *&Result) {
554   std::string Str;
555   if (ParseStringConstant(Str)) return true;
556   llvm::UpgradeMDStringConstant(Str);
557   Result = MDString::get(Context, Str);
558   return false;
559 }
560
561 // MDNode:
562 //   ::= '!' MDNodeNumber
563 bool LLParser::ParseMDNodeID(MDNode *&Result) {
564   // !{ ..., !42, ... }
565   unsigned MID = 0;
566   if (ParseUInt32(MID))
567     return true;
568
569   // If not a forward reference, just return it now.
570   if (NumberedMetadata.count(MID)) {
571     Result = NumberedMetadata[MID];
572     return false;
573   }
574
575   // Otherwise, create MDNode forward reference.
576   auto &FwdRef = ForwardRefMDNodes[MID];
577   FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
578
579   Result = FwdRef.first.get();
580   NumberedMetadata[MID].reset(Result);
581   return false;
582 }
583
584 /// ParseNamedMetadata:
585 ///   !foo = !{ !1, !2 }
586 bool LLParser::ParseNamedMetadata() {
587   assert(Lex.getKind() == lltok::MetadataVar);
588   std::string Name = Lex.getStrVal();
589   Lex.Lex();
590
591   if (ParseToken(lltok::equal, "expected '=' here") ||
592       ParseToken(lltok::exclaim, "Expected '!' here") ||
593       ParseToken(lltok::lbrace, "Expected '{' here"))
594     return true;
595
596   NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
597   if (Lex.getKind() != lltok::rbrace)
598     do {
599       if (ParseToken(lltok::exclaim, "Expected '!' here"))
600         return true;
601
602       MDNode *N = nullptr;
603       if (ParseMDNodeID(N)) return true;
604       NMD->addOperand(N);
605     } while (EatIfPresent(lltok::comma));
606
607   return ParseToken(lltok::rbrace, "expected end of metadata node");
608 }
609
610 /// ParseStandaloneMetadata:
611 ///   !42 = !{...}
612 bool LLParser::ParseStandaloneMetadata() {
613   assert(Lex.getKind() == lltok::exclaim);
614   Lex.Lex();
615   unsigned MetadataID = 0;
616
617   MDNode *Init;
618   if (ParseUInt32(MetadataID) ||
619       ParseToken(lltok::equal, "expected '=' here"))
620     return true;
621
622   // Detect common error, from old metadata syntax.
623   if (Lex.getKind() == lltok::Type)
624     return TokError("unexpected type in metadata definition");
625
626   bool IsDistinct = EatIfPresent(lltok::kw_distinct);
627   if (Lex.getKind() == lltok::MetadataVar) {
628     if (ParseSpecializedMDNode(Init, IsDistinct))
629       return true;
630   } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
631              ParseMDTuple(Init, IsDistinct))
632     return true;
633
634   // See if this was forward referenced, if so, handle it.
635   auto FI = ForwardRefMDNodes.find(MetadataID);
636   if (FI != ForwardRefMDNodes.end()) {
637     FI->second.first->replaceAllUsesWith(Init);
638     ForwardRefMDNodes.erase(FI);
639
640     assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
641   } else {
642     if (NumberedMetadata.count(MetadataID))
643       return TokError("Metadata id is already used");
644     NumberedMetadata[MetadataID].reset(Init);
645   }
646
647   return false;
648 }
649
650 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
651   return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
652          (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
653 }
654
655 /// ParseAlias:
656 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility
657 ///                     OptionalDLLStorageClass OptionalThreadLocal
658 ///                     OptionalUnnamedAddr 'alias' Aliasee
659 ///
660 /// Aliasee
661 ///   ::= TypeAndValue
662 ///
663 /// Everything through OptionalUnnamedAddr has already been parsed.
664 ///
665 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
666                           unsigned Visibility, unsigned DLLStorageClass,
667                           GlobalVariable::ThreadLocalMode TLM,
668                           bool UnnamedAddr) {
669   assert(Lex.getKind() == lltok::kw_alias);
670   Lex.Lex();
671
672   GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
673
674   if(!GlobalAlias::isValidLinkage(Linkage))
675     return Error(NameLoc, "invalid linkage type for alias");
676
677   if (!isValidVisibilityForLinkage(Visibility, L))
678     return Error(NameLoc,
679                  "symbol with local linkage must have default visibility");
680
681   Type *Ty;
682   LocTy ExplicitTypeLoc = Lex.getLoc();
683   if (ParseType(Ty) ||
684       ParseToken(lltok::comma, "expected comma after alias's type"))
685     return true;
686
687   Constant *Aliasee;
688   LocTy AliaseeLoc = Lex.getLoc();
689   if (Lex.getKind() != lltok::kw_bitcast &&
690       Lex.getKind() != lltok::kw_getelementptr &&
691       Lex.getKind() != lltok::kw_addrspacecast &&
692       Lex.getKind() != lltok::kw_inttoptr) {
693     if (ParseGlobalTypeAndValue(Aliasee))
694       return true;
695   } else {
696     // The bitcast dest type is not present, it is implied by the dest type.
697     ValID ID;
698     if (ParseValID(ID))
699       return true;
700     if (ID.Kind != ValID::t_Constant)
701       return Error(AliaseeLoc, "invalid aliasee");
702     Aliasee = ID.ConstantVal;
703   }
704
705   Type *AliaseeType = Aliasee->getType();
706   auto *PTy = dyn_cast<PointerType>(AliaseeType);
707   if (!PTy)
708     return Error(AliaseeLoc, "An alias must have pointer type");
709
710   if (Ty != PTy->getElementType())
711     return Error(
712         ExplicitTypeLoc,
713         "explicit pointee type doesn't match operand's pointee type");
714
715   // Okay, create the alias but do not insert it into the module yet.
716   std::unique_ptr<GlobalAlias> GA(
717       GlobalAlias::create(PTy, (GlobalValue::LinkageTypes)Linkage, Name,
718                           Aliasee, /*Parent*/ nullptr));
719   GA->setThreadLocalMode(TLM);
720   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
721   GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
722   GA->setUnnamedAddr(UnnamedAddr);
723
724   if (Name.empty())
725     NumberedVals.push_back(GA.get());
726
727   // See if this value already exists in the symbol table.  If so, it is either
728   // a redefinition or a definition of a forward reference.
729   if (GlobalValue *Val = M->getNamedValue(Name)) {
730     // See if this was a redefinition.  If so, there is no entry in
731     // ForwardRefVals.
732     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
733       I = ForwardRefVals.find(Name);
734     if (I == ForwardRefVals.end())
735       return Error(NameLoc, "redefinition of global named '@" + Name + "'");
736
737     // Otherwise, this was a definition of forward ref.  Verify that types
738     // agree.
739     if (Val->getType() != GA->getType())
740       return Error(NameLoc,
741               "forward reference and definition of alias have different types");
742
743     // If they agree, just RAUW the old value with the alias and remove the
744     // forward ref info.
745     Val->replaceAllUsesWith(GA.get());
746     Val->eraseFromParent();
747     ForwardRefVals.erase(I);
748   }
749
750   // Insert into the module, we know its name won't collide now.
751   M->getAliasList().push_back(GA.get());
752   assert(GA->getName() == Name && "Should not be a name conflict!");
753
754   // The module owns this now
755   GA.release();
756
757   return false;
758 }
759
760 /// ParseGlobal
761 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
762 ///       OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
763 ///       OptionalExternallyInitialized GlobalType Type Const
764 ///   ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
765 ///       OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
766 ///       OptionalExternallyInitialized GlobalType Type Const
767 ///
768 /// Everything up to and including OptionalUnnamedAddr has been parsed
769 /// already.
770 ///
771 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
772                            unsigned Linkage, bool HasLinkage,
773                            unsigned Visibility, unsigned DLLStorageClass,
774                            GlobalVariable::ThreadLocalMode TLM,
775                            bool UnnamedAddr) {
776   if (!isValidVisibilityForLinkage(Visibility, Linkage))
777     return Error(NameLoc,
778                  "symbol with local linkage must have default visibility");
779
780   unsigned AddrSpace;
781   bool IsConstant, IsExternallyInitialized;
782   LocTy IsExternallyInitializedLoc;
783   LocTy TyLoc;
784
785   Type *Ty = nullptr;
786   if (ParseOptionalAddrSpace(AddrSpace) ||
787       ParseOptionalToken(lltok::kw_externally_initialized,
788                          IsExternallyInitialized,
789                          &IsExternallyInitializedLoc) ||
790       ParseGlobalType(IsConstant) ||
791       ParseType(Ty, TyLoc))
792     return true;
793
794   // If the linkage is specified and is external, then no initializer is
795   // present.
796   Constant *Init = nullptr;
797   if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
798                       Linkage != GlobalValue::ExternalLinkage)) {
799     if (ParseGlobalValue(Ty, Init))
800       return true;
801   }
802
803   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
804     return Error(TyLoc, "invalid type for global variable");
805
806   GlobalValue *GVal = nullptr;
807
808   // See if the global was forward referenced, if so, use the global.
809   if (!Name.empty()) {
810     GVal = M->getNamedValue(Name);
811     if (GVal) {
812       if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
813         return Error(NameLoc, "redefinition of global '@" + Name + "'");
814     }
815   } else {
816     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
817       I = ForwardRefValIDs.find(NumberedVals.size());
818     if (I != ForwardRefValIDs.end()) {
819       GVal = I->second.first;
820       ForwardRefValIDs.erase(I);
821     }
822   }
823
824   GlobalVariable *GV;
825   if (!GVal) {
826     GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
827                             Name, nullptr, GlobalVariable::NotThreadLocal,
828                             AddrSpace);
829   } else {
830     if (GVal->getValueType() != Ty)
831       return Error(TyLoc,
832             "forward reference and definition of global have different types");
833
834     GV = cast<GlobalVariable>(GVal);
835
836     // Move the forward-reference to the correct spot in the module.
837     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
838   }
839
840   if (Name.empty())
841     NumberedVals.push_back(GV);
842
843   // Set the parsed properties on the global.
844   if (Init)
845     GV->setInitializer(Init);
846   GV->setConstant(IsConstant);
847   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
848   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
849   GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
850   GV->setExternallyInitialized(IsExternallyInitialized);
851   GV->setThreadLocalMode(TLM);
852   GV->setUnnamedAddr(UnnamedAddr);
853
854   // Parse attributes on the global.
855   while (Lex.getKind() == lltok::comma) {
856     Lex.Lex();
857
858     if (Lex.getKind() == lltok::kw_section) {
859       Lex.Lex();
860       GV->setSection(Lex.getStrVal());
861       if (ParseToken(lltok::StringConstant, "expected global section string"))
862         return true;
863     } else if (Lex.getKind() == lltok::kw_align) {
864       unsigned Alignment;
865       if (ParseOptionalAlignment(Alignment)) return true;
866       GV->setAlignment(Alignment);
867     } else {
868       Comdat *C;
869       if (parseOptionalComdat(Name, C))
870         return true;
871       if (C)
872         GV->setComdat(C);
873       else
874         return TokError("unknown global variable property!");
875     }
876   }
877
878   return false;
879 }
880
881 /// ParseUnnamedAttrGrp
882 ///   ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
883 bool LLParser::ParseUnnamedAttrGrp() {
884   assert(Lex.getKind() == lltok::kw_attributes);
885   LocTy AttrGrpLoc = Lex.getLoc();
886   Lex.Lex();
887
888   if (Lex.getKind() != lltok::AttrGrpID)
889     return TokError("expected attribute group id");
890
891   unsigned VarID = Lex.getUIntVal();
892   std::vector<unsigned> unused;
893   LocTy BuiltinLoc;
894   Lex.Lex();
895
896   if (ParseToken(lltok::equal, "expected '=' here") ||
897       ParseToken(lltok::lbrace, "expected '{' here") ||
898       ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
899                                  BuiltinLoc) ||
900       ParseToken(lltok::rbrace, "expected end of attribute group"))
901     return true;
902
903   if (!NumberedAttrBuilders[VarID].hasAttributes())
904     return Error(AttrGrpLoc, "attribute group has no attributes");
905
906   return false;
907 }
908
909 /// ParseFnAttributeValuePairs
910 ///   ::= <attr> | <attr> '=' <value>
911 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
912                                           std::vector<unsigned> &FwdRefAttrGrps,
913                                           bool inAttrGrp, LocTy &BuiltinLoc) {
914   bool HaveError = false;
915
916   B.clear();
917
918   while (true) {
919     lltok::Kind Token = Lex.getKind();
920     if (Token == lltok::kw_builtin)
921       BuiltinLoc = Lex.getLoc();
922     switch (Token) {
923     default:
924       if (!inAttrGrp) return HaveError;
925       return Error(Lex.getLoc(), "unterminated attribute group");
926     case lltok::rbrace:
927       // Finished.
928       return false;
929
930     case lltok::AttrGrpID: {
931       // Allow a function to reference an attribute group:
932       //
933       //   define void @foo() #1 { ... }
934       if (inAttrGrp)
935         HaveError |=
936           Error(Lex.getLoc(),
937               "cannot have an attribute group reference in an attribute group");
938
939       unsigned AttrGrpNum = Lex.getUIntVal();
940       if (inAttrGrp) break;
941
942       // Save the reference to the attribute group. We'll fill it in later.
943       FwdRefAttrGrps.push_back(AttrGrpNum);
944       break;
945     }
946     // Target-dependent attributes:
947     case lltok::StringConstant: {
948       if (ParseStringAttribute(B))
949         return true;
950       continue;
951     }
952
953     // Target-independent attributes:
954     case lltok::kw_align: {
955       // As a hack, we allow function alignment to be initially parsed as an
956       // attribute on a function declaration/definition or added to an attribute
957       // group and later moved to the alignment field.
958       unsigned Alignment;
959       if (inAttrGrp) {
960         Lex.Lex();
961         if (ParseToken(lltok::equal, "expected '=' here") ||
962             ParseUInt32(Alignment))
963           return true;
964       } else {
965         if (ParseOptionalAlignment(Alignment))
966           return true;
967       }
968       B.addAlignmentAttr(Alignment);
969       continue;
970     }
971     case lltok::kw_alignstack: {
972       unsigned Alignment;
973       if (inAttrGrp) {
974         Lex.Lex();
975         if (ParseToken(lltok::equal, "expected '=' here") ||
976             ParseUInt32(Alignment))
977           return true;
978       } else {
979         if (ParseOptionalStackAlignment(Alignment))
980           return true;
981       }
982       B.addStackAlignmentAttr(Alignment);
983       continue;
984     }
985     case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
986     case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
987     case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
988     case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
989     case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
990     case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
991     case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
992     case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
993     case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
994     case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
995     case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
996     case lltok::kw_noimplicitfloat:
997       B.addAttribute(Attribute::NoImplicitFloat); break;
998     case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
999     case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1000     case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1001     case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1002     case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1003     case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1004     case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1005     case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1006     case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1007     case lltok::kw_returns_twice:
1008       B.addAttribute(Attribute::ReturnsTwice); break;
1009     case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1010     case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1011     case lltok::kw_sspstrong:
1012       B.addAttribute(Attribute::StackProtectStrong); break;
1013     case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1014     case lltok::kw_sanitize_address:
1015       B.addAttribute(Attribute::SanitizeAddress); break;
1016     case lltok::kw_sanitize_thread:
1017       B.addAttribute(Attribute::SanitizeThread); break;
1018     case lltok::kw_sanitize_memory:
1019       B.addAttribute(Attribute::SanitizeMemory); break;
1020     case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1021
1022     // Error handling.
1023     case lltok::kw_inreg:
1024     case lltok::kw_signext:
1025     case lltok::kw_zeroext:
1026       HaveError |=
1027         Error(Lex.getLoc(),
1028               "invalid use of attribute on a function");
1029       break;
1030     case lltok::kw_byval:
1031     case lltok::kw_dereferenceable:
1032     case lltok::kw_dereferenceable_or_null:
1033     case lltok::kw_inalloca:
1034     case lltok::kw_nest:
1035     case lltok::kw_noalias:
1036     case lltok::kw_nocapture:
1037     case lltok::kw_nonnull:
1038     case lltok::kw_returned:
1039     case lltok::kw_sret:
1040       HaveError |=
1041         Error(Lex.getLoc(),
1042               "invalid use of parameter-only attribute on a function");
1043       break;
1044     }
1045
1046     Lex.Lex();
1047   }
1048 }
1049
1050 //===----------------------------------------------------------------------===//
1051 // GlobalValue Reference/Resolution Routines.
1052 //===----------------------------------------------------------------------===//
1053
1054 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1055                                               const std::string &Name) {
1056   if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1057     return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1058   else
1059     return new GlobalVariable(*M, PTy->getElementType(), false,
1060                               GlobalValue::ExternalWeakLinkage, nullptr, Name,
1061                               nullptr, GlobalVariable::NotThreadLocal,
1062                               PTy->getAddressSpace());
1063 }
1064
1065 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1066 /// forward reference record if needed.  This can return null if the value
1067 /// exists but does not have the right type.
1068 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1069                                     LocTy Loc) {
1070   PointerType *PTy = dyn_cast<PointerType>(Ty);
1071   if (!PTy) {
1072     Error(Loc, "global variable reference must have pointer type");
1073     return nullptr;
1074   }
1075
1076   // Look this name up in the normal function symbol table.
1077   GlobalValue *Val =
1078     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1079
1080   // If this is a forward reference for the value, see if we already created a
1081   // forward ref record.
1082   if (!Val) {
1083     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1084       I = ForwardRefVals.find(Name);
1085     if (I != ForwardRefVals.end())
1086       Val = I->second.first;
1087   }
1088
1089   // If we have the value in the symbol table or fwd-ref table, return it.
1090   if (Val) {
1091     if (Val->getType() == Ty) return Val;
1092     Error(Loc, "'@" + Name + "' defined with type '" +
1093           getTypeString(Val->getType()) + "'");
1094     return nullptr;
1095   }
1096
1097   // Otherwise, create a new forward reference for this value and remember it.
1098   GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1099   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1100   return FwdVal;
1101 }
1102
1103 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1104   PointerType *PTy = dyn_cast<PointerType>(Ty);
1105   if (!PTy) {
1106     Error(Loc, "global variable reference must have pointer type");
1107     return nullptr;
1108   }
1109
1110   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1111
1112   // If this is a forward reference for the value, see if we already created a
1113   // forward ref record.
1114   if (!Val) {
1115     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1116       I = ForwardRefValIDs.find(ID);
1117     if (I != ForwardRefValIDs.end())
1118       Val = I->second.first;
1119   }
1120
1121   // If we have the value in the symbol table or fwd-ref table, return it.
1122   if (Val) {
1123     if (Val->getType() == Ty) return Val;
1124     Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1125           getTypeString(Val->getType()) + "'");
1126     return nullptr;
1127   }
1128
1129   // Otherwise, create a new forward reference for this value and remember it.
1130   GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1131   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1132   return FwdVal;
1133 }
1134
1135
1136 //===----------------------------------------------------------------------===//
1137 // Comdat Reference/Resolution Routines.
1138 //===----------------------------------------------------------------------===//
1139
1140 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1141   // Look this name up in the comdat symbol table.
1142   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1143   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1144   if (I != ComdatSymTab.end())
1145     return &I->second;
1146
1147   // Otherwise, create a new forward reference for this value and remember it.
1148   Comdat *C = M->getOrInsertComdat(Name);
1149   ForwardRefComdats[Name] = Loc;
1150   return C;
1151 }
1152
1153
1154 //===----------------------------------------------------------------------===//
1155 // Helper Routines.
1156 //===----------------------------------------------------------------------===//
1157
1158 /// ParseToken - If the current token has the specified kind, eat it and return
1159 /// success.  Otherwise, emit the specified error and return failure.
1160 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1161   if (Lex.getKind() != T)
1162     return TokError(ErrMsg);
1163   Lex.Lex();
1164   return false;
1165 }
1166
1167 /// ParseStringConstant
1168 ///   ::= StringConstant
1169 bool LLParser::ParseStringConstant(std::string &Result) {
1170   if (Lex.getKind() != lltok::StringConstant)
1171     return TokError("expected string constant");
1172   Result = Lex.getStrVal();
1173   Lex.Lex();
1174   return false;
1175 }
1176
1177 /// ParseUInt32
1178 ///   ::= uint32
1179 bool LLParser::ParseUInt32(unsigned &Val) {
1180   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1181     return TokError("expected integer");
1182   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1183   if (Val64 != unsigned(Val64))
1184     return TokError("expected 32-bit integer (too large)");
1185   Val = Val64;
1186   Lex.Lex();
1187   return false;
1188 }
1189
1190 /// ParseUInt64
1191 ///   ::= uint64
1192 bool LLParser::ParseUInt64(uint64_t &Val) {
1193   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1194     return TokError("expected integer");
1195   Val = Lex.getAPSIntVal().getLimitedValue();
1196   Lex.Lex();
1197   return false;
1198 }
1199
1200 /// ParseTLSModel
1201 ///   := 'localdynamic'
1202 ///   := 'initialexec'
1203 ///   := 'localexec'
1204 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1205   switch (Lex.getKind()) {
1206     default:
1207       return TokError("expected localdynamic, initialexec or localexec");
1208     case lltok::kw_localdynamic:
1209       TLM = GlobalVariable::LocalDynamicTLSModel;
1210       break;
1211     case lltok::kw_initialexec:
1212       TLM = GlobalVariable::InitialExecTLSModel;
1213       break;
1214     case lltok::kw_localexec:
1215       TLM = GlobalVariable::LocalExecTLSModel;
1216       break;
1217   }
1218
1219   Lex.Lex();
1220   return false;
1221 }
1222
1223 /// ParseOptionalThreadLocal
1224 ///   := /*empty*/
1225 ///   := 'thread_local'
1226 ///   := 'thread_local' '(' tlsmodel ')'
1227 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1228   TLM = GlobalVariable::NotThreadLocal;
1229   if (!EatIfPresent(lltok::kw_thread_local))
1230     return false;
1231
1232   TLM = GlobalVariable::GeneralDynamicTLSModel;
1233   if (Lex.getKind() == lltok::lparen) {
1234     Lex.Lex();
1235     return ParseTLSModel(TLM) ||
1236       ParseToken(lltok::rparen, "expected ')' after thread local model");
1237   }
1238   return false;
1239 }
1240
1241 /// ParseOptionalAddrSpace
1242 ///   := /*empty*/
1243 ///   := 'addrspace' '(' uint32 ')'
1244 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1245   AddrSpace = 0;
1246   if (!EatIfPresent(lltok::kw_addrspace))
1247     return false;
1248   return ParseToken(lltok::lparen, "expected '(' in address space") ||
1249          ParseUInt32(AddrSpace) ||
1250          ParseToken(lltok::rparen, "expected ')' in address space");
1251 }
1252
1253 /// ParseStringAttribute
1254 ///   := StringConstant
1255 ///   := StringConstant '=' StringConstant
1256 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1257   std::string Attr = Lex.getStrVal();
1258   Lex.Lex();
1259   std::string Val;
1260   if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1261     return true;
1262   B.addAttribute(Attr, Val);
1263   return false;
1264 }
1265
1266 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1267 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1268   bool HaveError = false;
1269
1270   B.clear();
1271
1272   while (1) {
1273     lltok::Kind Token = Lex.getKind();
1274     switch (Token) {
1275     default:  // End of attributes.
1276       return HaveError;
1277     case lltok::StringConstant: {
1278       if (ParseStringAttribute(B))
1279         return true;
1280       continue;
1281     }
1282     case lltok::kw_align: {
1283       unsigned Alignment;
1284       if (ParseOptionalAlignment(Alignment))
1285         return true;
1286       B.addAlignmentAttr(Alignment);
1287       continue;
1288     }
1289     case lltok::kw_byval:           B.addAttribute(Attribute::ByVal); break;
1290     case lltok::kw_dereferenceable: {
1291       uint64_t Bytes;
1292       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1293         return true;
1294       B.addDereferenceableAttr(Bytes);
1295       continue;
1296     }
1297     case lltok::kw_dereferenceable_or_null: {
1298       uint64_t Bytes;
1299       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1300         return true;
1301       B.addDereferenceableOrNullAttr(Bytes);
1302       continue;
1303     }
1304     case lltok::kw_inalloca:        B.addAttribute(Attribute::InAlloca); break;
1305     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1306     case lltok::kw_nest:            B.addAttribute(Attribute::Nest); break;
1307     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1308     case lltok::kw_nocapture:       B.addAttribute(Attribute::NoCapture); break;
1309     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1310     case lltok::kw_readnone:        B.addAttribute(Attribute::ReadNone); break;
1311     case lltok::kw_readonly:        B.addAttribute(Attribute::ReadOnly); break;
1312     case lltok::kw_returned:        B.addAttribute(Attribute::Returned); break;
1313     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1314     case lltok::kw_sret:            B.addAttribute(Attribute::StructRet); break;
1315     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1316
1317     case lltok::kw_alignstack:
1318     case lltok::kw_alwaysinline:
1319     case lltok::kw_argmemonly:
1320     case lltok::kw_builtin:
1321     case lltok::kw_inlinehint:
1322     case lltok::kw_jumptable:
1323     case lltok::kw_minsize:
1324     case lltok::kw_naked:
1325     case lltok::kw_nobuiltin:
1326     case lltok::kw_noduplicate:
1327     case lltok::kw_noimplicitfloat:
1328     case lltok::kw_noinline:
1329     case lltok::kw_nonlazybind:
1330     case lltok::kw_noredzone:
1331     case lltok::kw_noreturn:
1332     case lltok::kw_nounwind:
1333     case lltok::kw_optnone:
1334     case lltok::kw_optsize:
1335     case lltok::kw_returns_twice:
1336     case lltok::kw_sanitize_address:
1337     case lltok::kw_sanitize_memory:
1338     case lltok::kw_sanitize_thread:
1339     case lltok::kw_ssp:
1340     case lltok::kw_sspreq:
1341     case lltok::kw_sspstrong:
1342     case lltok::kw_safestack:
1343     case lltok::kw_uwtable:
1344       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1345       break;
1346     }
1347
1348     Lex.Lex();
1349   }
1350 }
1351
1352 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1353 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1354   bool HaveError = false;
1355
1356   B.clear();
1357
1358   while (1) {
1359     lltok::Kind Token = Lex.getKind();
1360     switch (Token) {
1361     default:  // End of attributes.
1362       return HaveError;
1363     case lltok::StringConstant: {
1364       if (ParseStringAttribute(B))
1365         return true;
1366       continue;
1367     }
1368     case lltok::kw_dereferenceable: {
1369       uint64_t Bytes;
1370       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1371         return true;
1372       B.addDereferenceableAttr(Bytes);
1373       continue;
1374     }
1375     case lltok::kw_dereferenceable_or_null: {
1376       uint64_t Bytes;
1377       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1378         return true;
1379       B.addDereferenceableOrNullAttr(Bytes);
1380       continue;
1381     }
1382     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1383     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1384     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1385     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1386     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1387
1388     // Error handling.
1389     case lltok::kw_align:
1390     case lltok::kw_byval:
1391     case lltok::kw_inalloca:
1392     case lltok::kw_nest:
1393     case lltok::kw_nocapture:
1394     case lltok::kw_returned:
1395     case lltok::kw_sret:
1396       HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1397       break;
1398
1399     case lltok::kw_alignstack:
1400     case lltok::kw_alwaysinline:
1401     case lltok::kw_argmemonly:
1402     case lltok::kw_builtin:
1403     case lltok::kw_cold:
1404     case lltok::kw_inlinehint:
1405     case lltok::kw_jumptable:
1406     case lltok::kw_minsize:
1407     case lltok::kw_naked:
1408     case lltok::kw_nobuiltin:
1409     case lltok::kw_noduplicate:
1410     case lltok::kw_noimplicitfloat:
1411     case lltok::kw_noinline:
1412     case lltok::kw_nonlazybind:
1413     case lltok::kw_noredzone:
1414     case lltok::kw_noreturn:
1415     case lltok::kw_nounwind:
1416     case lltok::kw_optnone:
1417     case lltok::kw_optsize:
1418     case lltok::kw_returns_twice:
1419     case lltok::kw_sanitize_address:
1420     case lltok::kw_sanitize_memory:
1421     case lltok::kw_sanitize_thread:
1422     case lltok::kw_ssp:
1423     case lltok::kw_sspreq:
1424     case lltok::kw_sspstrong:
1425     case lltok::kw_safestack:
1426     case lltok::kw_uwtable:
1427       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1428       break;
1429
1430     case lltok::kw_readnone:
1431     case lltok::kw_readonly:
1432       HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1433     }
1434
1435     Lex.Lex();
1436   }
1437 }
1438
1439 /// ParseOptionalLinkage
1440 ///   ::= /*empty*/
1441 ///   ::= 'private'
1442 ///   ::= 'internal'
1443 ///   ::= 'weak'
1444 ///   ::= 'weak_odr'
1445 ///   ::= 'linkonce'
1446 ///   ::= 'linkonce_odr'
1447 ///   ::= 'available_externally'
1448 ///   ::= 'appending'
1449 ///   ::= 'common'
1450 ///   ::= 'extern_weak'
1451 ///   ::= 'external'
1452 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1453   HasLinkage = false;
1454   switch (Lex.getKind()) {
1455   default:                       Res=GlobalValue::ExternalLinkage; return false;
1456   case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
1457   case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
1458   case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
1459   case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
1460   case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
1461   case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
1462   case lltok::kw_available_externally:
1463     Res = GlobalValue::AvailableExternallyLinkage;
1464     break;
1465   case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
1466   case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
1467   case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
1468   case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
1469   }
1470   Lex.Lex();
1471   HasLinkage = true;
1472   return false;
1473 }
1474
1475 /// ParseOptionalVisibility
1476 ///   ::= /*empty*/
1477 ///   ::= 'default'
1478 ///   ::= 'hidden'
1479 ///   ::= 'protected'
1480 ///
1481 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1482   switch (Lex.getKind()) {
1483   default:                  Res = GlobalValue::DefaultVisibility; return false;
1484   case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
1485   case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
1486   case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1487   }
1488   Lex.Lex();
1489   return false;
1490 }
1491
1492 /// ParseOptionalDLLStorageClass
1493 ///   ::= /*empty*/
1494 ///   ::= 'dllimport'
1495 ///   ::= 'dllexport'
1496 ///
1497 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1498   switch (Lex.getKind()) {
1499   default:                  Res = GlobalValue::DefaultStorageClass; return false;
1500   case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1501   case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1502   }
1503   Lex.Lex();
1504   return false;
1505 }
1506
1507 /// ParseOptionalCallingConv
1508 ///   ::= /*empty*/
1509 ///   ::= 'ccc'
1510 ///   ::= 'fastcc'
1511 ///   ::= 'intel_ocl_bicc'
1512 ///   ::= 'coldcc'
1513 ///   ::= 'x86_stdcallcc'
1514 ///   ::= 'x86_fastcallcc'
1515 ///   ::= 'x86_thiscallcc'
1516 ///   ::= 'x86_vectorcallcc'
1517 ///   ::= 'arm_apcscc'
1518 ///   ::= 'arm_aapcscc'
1519 ///   ::= 'arm_aapcs_vfpcc'
1520 ///   ::= 'msp430_intrcc'
1521 ///   ::= 'ptx_kernel'
1522 ///   ::= 'ptx_device'
1523 ///   ::= 'spir_func'
1524 ///   ::= 'spir_kernel'
1525 ///   ::= 'x86_64_sysvcc'
1526 ///   ::= 'x86_64_win64cc'
1527 ///   ::= 'webkit_jscc'
1528 ///   ::= 'anyregcc'
1529 ///   ::= 'preserve_mostcc'
1530 ///   ::= 'preserve_allcc'
1531 ///   ::= 'ghccc'
1532 ///   ::= 'cc' UINT
1533 ///
1534 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1535   switch (Lex.getKind()) {
1536   default:                       CC = CallingConv::C; return false;
1537   case lltok::kw_ccc:            CC = CallingConv::C; break;
1538   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1539   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1540   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1541   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1542   case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1543   case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1544   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1545   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1546   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1547   case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
1548   case lltok::kw_ptx_kernel:     CC = CallingConv::PTX_Kernel; break;
1549   case lltok::kw_ptx_device:     CC = CallingConv::PTX_Device; break;
1550   case lltok::kw_spir_kernel:    CC = CallingConv::SPIR_KERNEL; break;
1551   case lltok::kw_spir_func:      CC = CallingConv::SPIR_FUNC; break;
1552   case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1553   case lltok::kw_x86_64_sysvcc:  CC = CallingConv::X86_64_SysV; break;
1554   case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1555   case lltok::kw_webkit_jscc:    CC = CallingConv::WebKit_JS; break;
1556   case lltok::kw_anyregcc:       CC = CallingConv::AnyReg; break;
1557   case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1558   case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1559   case lltok::kw_ghccc:          CC = CallingConv::GHC; break;
1560   case lltok::kw_cc: {
1561       Lex.Lex();
1562       return ParseUInt32(CC);
1563     }
1564   }
1565
1566   Lex.Lex();
1567   return false;
1568 }
1569
1570 /// ParseMetadataAttachment
1571 ///   ::= !dbg !42
1572 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1573   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1574
1575   std::string Name = Lex.getStrVal();
1576   Kind = M->getMDKindID(Name);
1577   Lex.Lex();
1578
1579   return ParseMDNode(MD);
1580 }
1581
1582 /// ParseInstructionMetadata
1583 ///   ::= !dbg !42 (',' !dbg !57)*
1584 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1585   do {
1586     if (Lex.getKind() != lltok::MetadataVar)
1587       return TokError("expected metadata after comma");
1588
1589     unsigned MDK;
1590     MDNode *N;
1591     if (ParseMetadataAttachment(MDK, N))
1592       return true;
1593
1594     Inst.setMetadata(MDK, N);
1595     if (MDK == LLVMContext::MD_tbaa)
1596       InstsWithTBAATag.push_back(&Inst);
1597
1598     // If this is the end of the list, we're done.
1599   } while (EatIfPresent(lltok::comma));
1600   return false;
1601 }
1602
1603 /// ParseOptionalFunctionMetadata
1604 ///   ::= (!dbg !57)*
1605 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1606   while (Lex.getKind() == lltok::MetadataVar) {
1607     unsigned MDK;
1608     MDNode *N;
1609     if (ParseMetadataAttachment(MDK, N))
1610       return true;
1611
1612     F.setMetadata(MDK, N);
1613   }
1614   return false;
1615 }
1616
1617 /// ParseOptionalAlignment
1618 ///   ::= /* empty */
1619 ///   ::= 'align' 4
1620 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1621   Alignment = 0;
1622   if (!EatIfPresent(lltok::kw_align))
1623     return false;
1624   LocTy AlignLoc = Lex.getLoc();
1625   if (ParseUInt32(Alignment)) return true;
1626   if (!isPowerOf2_32(Alignment))
1627     return Error(AlignLoc, "alignment is not a power of two");
1628   if (Alignment > Value::MaximumAlignment)
1629     return Error(AlignLoc, "huge alignments are not supported yet");
1630   return false;
1631 }
1632
1633 /// ParseOptionalDerefAttrBytes
1634 ///   ::= /* empty */
1635 ///   ::= AttrKind '(' 4 ')'
1636 ///
1637 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1638 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1639                                            uint64_t &Bytes) {
1640   assert((AttrKind == lltok::kw_dereferenceable ||
1641           AttrKind == lltok::kw_dereferenceable_or_null) &&
1642          "contract!");
1643
1644   Bytes = 0;
1645   if (!EatIfPresent(AttrKind))
1646     return false;
1647   LocTy ParenLoc = Lex.getLoc();
1648   if (!EatIfPresent(lltok::lparen))
1649     return Error(ParenLoc, "expected '('");
1650   LocTy DerefLoc = Lex.getLoc();
1651   if (ParseUInt64(Bytes)) return true;
1652   ParenLoc = Lex.getLoc();
1653   if (!EatIfPresent(lltok::rparen))
1654     return Error(ParenLoc, "expected ')'");
1655   if (!Bytes)
1656     return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1657   return false;
1658 }
1659
1660 /// ParseOptionalCommaAlign
1661 ///   ::=
1662 ///   ::= ',' align 4
1663 ///
1664 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1665 /// end.
1666 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1667                                        bool &AteExtraComma) {
1668   AteExtraComma = false;
1669   while (EatIfPresent(lltok::comma)) {
1670     // Metadata at the end is an early exit.
1671     if (Lex.getKind() == lltok::MetadataVar) {
1672       AteExtraComma = true;
1673       return false;
1674     }
1675
1676     if (Lex.getKind() != lltok::kw_align)
1677       return Error(Lex.getLoc(), "expected metadata or 'align'");
1678
1679     if (ParseOptionalAlignment(Alignment)) return true;
1680   }
1681
1682   return false;
1683 }
1684
1685 /// ParseScopeAndOrdering
1686 ///   if isAtomic: ::= 'singlethread'? AtomicOrdering
1687 ///   else: ::=
1688 ///
1689 /// This sets Scope and Ordering to the parsed values.
1690 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1691                                      AtomicOrdering &Ordering) {
1692   if (!isAtomic)
1693     return false;
1694
1695   Scope = CrossThread;
1696   if (EatIfPresent(lltok::kw_singlethread))
1697     Scope = SingleThread;
1698
1699   return ParseOrdering(Ordering);
1700 }
1701
1702 /// ParseOrdering
1703 ///   ::= AtomicOrdering
1704 ///
1705 /// This sets Ordering to the parsed value.
1706 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1707   switch (Lex.getKind()) {
1708   default: return TokError("Expected ordering on atomic instruction");
1709   case lltok::kw_unordered: Ordering = Unordered; break;
1710   case lltok::kw_monotonic: Ordering = Monotonic; break;
1711   case lltok::kw_acquire: Ordering = Acquire; break;
1712   case lltok::kw_release: Ordering = Release; break;
1713   case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1714   case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1715   }
1716   Lex.Lex();
1717   return false;
1718 }
1719
1720 /// ParseOptionalStackAlignment
1721 ///   ::= /* empty */
1722 ///   ::= 'alignstack' '(' 4 ')'
1723 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1724   Alignment = 0;
1725   if (!EatIfPresent(lltok::kw_alignstack))
1726     return false;
1727   LocTy ParenLoc = Lex.getLoc();
1728   if (!EatIfPresent(lltok::lparen))
1729     return Error(ParenLoc, "expected '('");
1730   LocTy AlignLoc = Lex.getLoc();
1731   if (ParseUInt32(Alignment)) return true;
1732   ParenLoc = Lex.getLoc();
1733   if (!EatIfPresent(lltok::rparen))
1734     return Error(ParenLoc, "expected ')'");
1735   if (!isPowerOf2_32(Alignment))
1736     return Error(AlignLoc, "stack alignment is not a power of two");
1737   return false;
1738 }
1739
1740 /// ParseIndexList - This parses the index list for an insert/extractvalue
1741 /// instruction.  This sets AteExtraComma in the case where we eat an extra
1742 /// comma at the end of the line and find that it is followed by metadata.
1743 /// Clients that don't allow metadata can call the version of this function that
1744 /// only takes one argument.
1745 ///
1746 /// ParseIndexList
1747 ///    ::=  (',' uint32)+
1748 ///
1749 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1750                               bool &AteExtraComma) {
1751   AteExtraComma = false;
1752
1753   if (Lex.getKind() != lltok::comma)
1754     return TokError("expected ',' as start of index list");
1755
1756   while (EatIfPresent(lltok::comma)) {
1757     if (Lex.getKind() == lltok::MetadataVar) {
1758       if (Indices.empty()) return TokError("expected index");
1759       AteExtraComma = true;
1760       return false;
1761     }
1762     unsigned Idx = 0;
1763     if (ParseUInt32(Idx)) return true;
1764     Indices.push_back(Idx);
1765   }
1766
1767   return false;
1768 }
1769
1770 //===----------------------------------------------------------------------===//
1771 // Type Parsing.
1772 //===----------------------------------------------------------------------===//
1773
1774 /// ParseType - Parse a type.
1775 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1776   SMLoc TypeLoc = Lex.getLoc();
1777   switch (Lex.getKind()) {
1778   default:
1779     return TokError(Msg);
1780   case lltok::Type:
1781     // Type ::= 'float' | 'void' (etc)
1782     Result = Lex.getTyVal();
1783     Lex.Lex();
1784     break;
1785   case lltok::lbrace:
1786     // Type ::= StructType
1787     if (ParseAnonStructType(Result, false))
1788       return true;
1789     break;
1790   case lltok::lsquare:
1791     // Type ::= '[' ... ']'
1792     Lex.Lex(); // eat the lsquare.
1793     if (ParseArrayVectorType(Result, false))
1794       return true;
1795     break;
1796   case lltok::less: // Either vector or packed struct.
1797     // Type ::= '<' ... '>'
1798     Lex.Lex();
1799     if (Lex.getKind() == lltok::lbrace) {
1800       if (ParseAnonStructType(Result, true) ||
1801           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1802         return true;
1803     } else if (ParseArrayVectorType(Result, true))
1804       return true;
1805     break;
1806   case lltok::LocalVar: {
1807     // Type ::= %foo
1808     std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1809
1810     // If the type hasn't been defined yet, create a forward definition and
1811     // remember where that forward def'n was seen (in case it never is defined).
1812     if (!Entry.first) {
1813       Entry.first = StructType::create(Context, Lex.getStrVal());
1814       Entry.second = Lex.getLoc();
1815     }
1816     Result = Entry.first;
1817     Lex.Lex();
1818     break;
1819   }
1820
1821   case lltok::LocalVarID: {
1822     // Type ::= %4
1823     std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1824
1825     // If the type hasn't been defined yet, create a forward definition and
1826     // remember where that forward def'n was seen (in case it never is defined).
1827     if (!Entry.first) {
1828       Entry.first = StructType::create(Context);
1829       Entry.second = Lex.getLoc();
1830     }
1831     Result = Entry.first;
1832     Lex.Lex();
1833     break;
1834   }
1835   }
1836
1837   // Parse the type suffixes.
1838   while (1) {
1839     switch (Lex.getKind()) {
1840     // End of type.
1841     default:
1842       if (!AllowVoid && Result->isVoidTy())
1843         return Error(TypeLoc, "void type only allowed for function results");
1844       return false;
1845
1846     // Type ::= Type '*'
1847     case lltok::star:
1848       if (Result->isLabelTy())
1849         return TokError("basic block pointers are invalid");
1850       if (Result->isVoidTy())
1851         return TokError("pointers to void are invalid - use i8* instead");
1852       if (!PointerType::isValidElementType(Result))
1853         return TokError("pointer to this type is invalid");
1854       Result = PointerType::getUnqual(Result);
1855       Lex.Lex();
1856       break;
1857
1858     // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1859     case lltok::kw_addrspace: {
1860       if (Result->isLabelTy())
1861         return TokError("basic block pointers are invalid");
1862       if (Result->isVoidTy())
1863         return TokError("pointers to void are invalid; use i8* instead");
1864       if (!PointerType::isValidElementType(Result))
1865         return TokError("pointer to this type is invalid");
1866       unsigned AddrSpace;
1867       if (ParseOptionalAddrSpace(AddrSpace) ||
1868           ParseToken(lltok::star, "expected '*' in address space"))
1869         return true;
1870
1871       Result = PointerType::get(Result, AddrSpace);
1872       break;
1873     }
1874
1875     /// Types '(' ArgTypeListI ')' OptFuncAttrs
1876     case lltok::lparen:
1877       if (ParseFunctionType(Result))
1878         return true;
1879       break;
1880     }
1881   }
1882 }
1883
1884 /// ParseParameterList
1885 ///    ::= '(' ')'
1886 ///    ::= '(' Arg (',' Arg)* ')'
1887 ///  Arg
1888 ///    ::= Type OptionalAttributes Value OptionalAttributes
1889 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1890                                   PerFunctionState &PFS, bool IsMustTailCall,
1891                                   bool InVarArgsFunc) {
1892   if (ParseToken(lltok::lparen, "expected '(' in call"))
1893     return true;
1894
1895   unsigned AttrIndex = 1;
1896   while (Lex.getKind() != lltok::rparen) {
1897     // If this isn't the first argument, we need a comma.
1898     if (!ArgList.empty() &&
1899         ParseToken(lltok::comma, "expected ',' in argument list"))
1900       return true;
1901
1902     // Parse an ellipsis if this is a musttail call in a variadic function.
1903     if (Lex.getKind() == lltok::dotdotdot) {
1904       const char *Msg = "unexpected ellipsis in argument list for ";
1905       if (!IsMustTailCall)
1906         return TokError(Twine(Msg) + "non-musttail call");
1907       if (!InVarArgsFunc)
1908         return TokError(Twine(Msg) + "musttail call in non-varargs function");
1909       Lex.Lex();  // Lex the '...', it is purely for readability.
1910       return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1911     }
1912
1913     // Parse the argument.
1914     LocTy ArgLoc;
1915     Type *ArgTy = nullptr;
1916     AttrBuilder ArgAttrs;
1917     Value *V;
1918     if (ParseType(ArgTy, ArgLoc))
1919       return true;
1920
1921     if (ArgTy->isMetadataTy()) {
1922       if (ParseMetadataAsValue(V, PFS))
1923         return true;
1924     } else {
1925       // Otherwise, handle normal operands.
1926       if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1927         return true;
1928     }
1929     ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1930                                                              AttrIndex++,
1931                                                              ArgAttrs)));
1932   }
1933
1934   if (IsMustTailCall && InVarArgsFunc)
1935     return TokError("expected '...' at end of argument list for musttail call "
1936                     "in varargs function");
1937
1938   Lex.Lex();  // Lex the ')'.
1939   return false;
1940 }
1941
1942
1943
1944 /// ParseArgumentList - Parse the argument list for a function type or function
1945 /// prototype.
1946 ///   ::= '(' ArgTypeListI ')'
1947 /// ArgTypeListI
1948 ///   ::= /*empty*/
1949 ///   ::= '...'
1950 ///   ::= ArgTypeList ',' '...'
1951 ///   ::= ArgType (',' ArgType)*
1952 ///
1953 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1954                                  bool &isVarArg){
1955   isVarArg = false;
1956   assert(Lex.getKind() == lltok::lparen);
1957   Lex.Lex(); // eat the (.
1958
1959   if (Lex.getKind() == lltok::rparen) {
1960     // empty
1961   } else if (Lex.getKind() == lltok::dotdotdot) {
1962     isVarArg = true;
1963     Lex.Lex();
1964   } else {
1965     LocTy TypeLoc = Lex.getLoc();
1966     Type *ArgTy = nullptr;
1967     AttrBuilder Attrs;
1968     std::string Name;
1969
1970     if (ParseType(ArgTy) ||
1971         ParseOptionalParamAttrs(Attrs)) return true;
1972
1973     if (ArgTy->isVoidTy())
1974       return Error(TypeLoc, "argument can not have void type");
1975
1976     if (Lex.getKind() == lltok::LocalVar) {
1977       Name = Lex.getStrVal();
1978       Lex.Lex();
1979     }
1980
1981     if (!FunctionType::isValidArgumentType(ArgTy))
1982       return Error(TypeLoc, "invalid type for function argument");
1983
1984     unsigned AttrIndex = 1;
1985     ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
1986                                                            AttrIndex++, Attrs),
1987                          std::move(Name));
1988
1989     while (EatIfPresent(lltok::comma)) {
1990       // Handle ... at end of arg list.
1991       if (EatIfPresent(lltok::dotdotdot)) {
1992         isVarArg = true;
1993         break;
1994       }
1995
1996       // Otherwise must be an argument type.
1997       TypeLoc = Lex.getLoc();
1998       if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1999
2000       if (ArgTy->isVoidTy())
2001         return Error(TypeLoc, "argument can not have void type");
2002
2003       if (Lex.getKind() == lltok::LocalVar) {
2004         Name = Lex.getStrVal();
2005         Lex.Lex();
2006       } else {
2007         Name = "";
2008       }
2009
2010       if (!ArgTy->isFirstClassType())
2011         return Error(TypeLoc, "invalid type for function argument");
2012
2013       ArgList.emplace_back(
2014           TypeLoc, ArgTy,
2015           AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2016           std::move(Name));
2017     }
2018   }
2019
2020   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2021 }
2022
2023 /// ParseFunctionType
2024 ///  ::= Type ArgumentList OptionalAttrs
2025 bool LLParser::ParseFunctionType(Type *&Result) {
2026   assert(Lex.getKind() == lltok::lparen);
2027
2028   if (!FunctionType::isValidReturnType(Result))
2029     return TokError("invalid function return type");
2030
2031   SmallVector<ArgInfo, 8> ArgList;
2032   bool isVarArg;
2033   if (ParseArgumentList(ArgList, isVarArg))
2034     return true;
2035
2036   // Reject names on the arguments lists.
2037   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2038     if (!ArgList[i].Name.empty())
2039       return Error(ArgList[i].Loc, "argument name invalid in function type");
2040     if (ArgList[i].Attrs.hasAttributes(i + 1))
2041       return Error(ArgList[i].Loc,
2042                    "argument attributes invalid in function type");
2043   }
2044
2045   SmallVector<Type*, 16> ArgListTy;
2046   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2047     ArgListTy.push_back(ArgList[i].Ty);
2048
2049   Result = FunctionType::get(Result, ArgListTy, isVarArg);
2050   return false;
2051 }
2052
2053 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2054 /// other structs.
2055 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2056   SmallVector<Type*, 8> Elts;
2057   if (ParseStructBody(Elts)) return true;
2058
2059   Result = StructType::get(Context, Elts, Packed);
2060   return false;
2061 }
2062
2063 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2064 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2065                                      std::pair<Type*, LocTy> &Entry,
2066                                      Type *&ResultTy) {
2067   // If the type was already defined, diagnose the redefinition.
2068   if (Entry.first && !Entry.second.isValid())
2069     return Error(TypeLoc, "redefinition of type");
2070
2071   // If we have opaque, just return without filling in the definition for the
2072   // struct.  This counts as a definition as far as the .ll file goes.
2073   if (EatIfPresent(lltok::kw_opaque)) {
2074     // This type is being defined, so clear the location to indicate this.
2075     Entry.second = SMLoc();
2076
2077     // If this type number has never been uttered, create it.
2078     if (!Entry.first)
2079       Entry.first = StructType::create(Context, Name);
2080     ResultTy = Entry.first;
2081     return false;
2082   }
2083
2084   // If the type starts with '<', then it is either a packed struct or a vector.
2085   bool isPacked = EatIfPresent(lltok::less);
2086
2087   // If we don't have a struct, then we have a random type alias, which we
2088   // accept for compatibility with old files.  These types are not allowed to be
2089   // forward referenced and not allowed to be recursive.
2090   if (Lex.getKind() != lltok::lbrace) {
2091     if (Entry.first)
2092       return Error(TypeLoc, "forward references to non-struct type");
2093
2094     ResultTy = nullptr;
2095     if (isPacked)
2096       return ParseArrayVectorType(ResultTy, true);
2097     return ParseType(ResultTy);
2098   }
2099
2100   // This type is being defined, so clear the location to indicate this.
2101   Entry.second = SMLoc();
2102
2103   // If this type number has never been uttered, create it.
2104   if (!Entry.first)
2105     Entry.first = StructType::create(Context, Name);
2106
2107   StructType *STy = cast<StructType>(Entry.first);
2108
2109   SmallVector<Type*, 8> Body;
2110   if (ParseStructBody(Body) ||
2111       (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2112     return true;
2113
2114   STy->setBody(Body, isPacked);
2115   ResultTy = STy;
2116   return false;
2117 }
2118
2119
2120 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
2121 ///   StructType
2122 ///     ::= '{' '}'
2123 ///     ::= '{' Type (',' Type)* '}'
2124 ///     ::= '<' '{' '}' '>'
2125 ///     ::= '<' '{' Type (',' Type)* '}' '>'
2126 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2127   assert(Lex.getKind() == lltok::lbrace);
2128   Lex.Lex(); // Consume the '{'
2129
2130   // Handle the empty struct.
2131   if (EatIfPresent(lltok::rbrace))
2132     return false;
2133
2134   LocTy EltTyLoc = Lex.getLoc();
2135   Type *Ty = nullptr;
2136   if (ParseType(Ty)) return true;
2137   Body.push_back(Ty);
2138
2139   if (!StructType::isValidElementType(Ty))
2140     return Error(EltTyLoc, "invalid element type for struct");
2141
2142   while (EatIfPresent(lltok::comma)) {
2143     EltTyLoc = Lex.getLoc();
2144     if (ParseType(Ty)) return true;
2145
2146     if (!StructType::isValidElementType(Ty))
2147       return Error(EltTyLoc, "invalid element type for struct");
2148
2149     Body.push_back(Ty);
2150   }
2151
2152   return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2153 }
2154
2155 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2156 /// token has already been consumed.
2157 ///   Type
2158 ///     ::= '[' APSINTVAL 'x' Types ']'
2159 ///     ::= '<' APSINTVAL 'x' Types '>'
2160 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2161   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2162       Lex.getAPSIntVal().getBitWidth() > 64)
2163     return TokError("expected number in address space");
2164
2165   LocTy SizeLoc = Lex.getLoc();
2166   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2167   Lex.Lex();
2168
2169   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2170       return true;
2171
2172   LocTy TypeLoc = Lex.getLoc();
2173   Type *EltTy = nullptr;
2174   if (ParseType(EltTy)) return true;
2175
2176   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2177                  "expected end of sequential type"))
2178     return true;
2179
2180   if (isVector) {
2181     if (Size == 0)
2182       return Error(SizeLoc, "zero element vector is illegal");
2183     if ((unsigned)Size != Size)
2184       return Error(SizeLoc, "size too large for vector");
2185     if (!VectorType::isValidElementType(EltTy))
2186       return Error(TypeLoc, "invalid vector element type");
2187     Result = VectorType::get(EltTy, unsigned(Size));
2188   } else {
2189     if (!ArrayType::isValidElementType(EltTy))
2190       return Error(TypeLoc, "invalid array element type");
2191     Result = ArrayType::get(EltTy, Size);
2192   }
2193   return false;
2194 }
2195
2196 //===----------------------------------------------------------------------===//
2197 // Function Semantic Analysis.
2198 //===----------------------------------------------------------------------===//
2199
2200 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2201                                              int functionNumber)
2202   : P(p), F(f), FunctionNumber(functionNumber) {
2203
2204   // Insert unnamed arguments into the NumberedVals list.
2205   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2206        AI != E; ++AI)
2207     if (!AI->hasName())
2208       NumberedVals.push_back(AI);
2209 }
2210
2211 LLParser::PerFunctionState::~PerFunctionState() {
2212   // If there were any forward referenced non-basicblock values, delete them.
2213   for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2214        I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2215     if (!isa<BasicBlock>(I->second.first)) {
2216       I->second.first->replaceAllUsesWith(
2217                            UndefValue::get(I->second.first->getType()));
2218       delete I->second.first;
2219       I->second.first = nullptr;
2220     }
2221
2222   for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2223        I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2224     if (!isa<BasicBlock>(I->second.first)) {
2225       I->second.first->replaceAllUsesWith(
2226                            UndefValue::get(I->second.first->getType()));
2227       delete I->second.first;
2228       I->second.first = nullptr;
2229     }
2230 }
2231
2232 bool LLParser::PerFunctionState::FinishFunction() {
2233   if (!ForwardRefVals.empty())
2234     return P.Error(ForwardRefVals.begin()->second.second,
2235                    "use of undefined value '%" + ForwardRefVals.begin()->first +
2236                    "'");
2237   if (!ForwardRefValIDs.empty())
2238     return P.Error(ForwardRefValIDs.begin()->second.second,
2239                    "use of undefined value '%" +
2240                    Twine(ForwardRefValIDs.begin()->first) + "'");
2241   return false;
2242 }
2243
2244
2245 /// GetVal - Get a value with the specified name or ID, creating a
2246 /// forward reference record if needed.  This can return null if the value
2247 /// exists but does not have the right type.
2248 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2249                                           LocTy Loc, OperatorConstraint OC) {
2250   // Look this name up in the normal function symbol table.
2251   Value *Val = F.getValueSymbolTable().lookup(Name);
2252
2253   // If this is a forward reference for the value, see if we already created a
2254   // forward ref record.
2255   if (!Val) {
2256     std::map<std::string, std::pair<Value*, LocTy> >::iterator
2257       I = ForwardRefVals.find(Name);
2258     if (I != ForwardRefVals.end())
2259       Val = I->second.first;
2260   }
2261
2262   // If we have the value in the symbol table or fwd-ref table, return it.
2263   if (Val) {
2264     // Check operator constraints.
2265     switch (OC) {
2266     case OC_None:
2267       // no constraint
2268       break;
2269     case OC_CatchPad:
2270       if (!isa<CatchPadInst>(Val)) {
2271         P.Error(Loc, "'%" + Name + "' is not a catchpad");
2272         return nullptr;
2273       }
2274       break;
2275     case OC_CleanupPad:
2276       if (!isa<CleanupPadInst>(Val)) {
2277         P.Error(Loc, "'%" + Name + "' is not a cleanuppad");
2278         return nullptr;
2279       }
2280       break;
2281     }
2282     if (Val->getType() == Ty) return Val;
2283     if (Ty->isLabelTy())
2284       P.Error(Loc, "'%" + Name + "' is not a basic block");
2285     else
2286       P.Error(Loc, "'%" + Name + "' defined with type '" +
2287               getTypeString(Val->getType()) + "'");
2288     return nullptr;
2289   }
2290
2291   // Don't make placeholders with invalid type.
2292   if (!Ty->isFirstClassType()) {
2293     P.Error(Loc, "invalid use of a non-first-class type");
2294     return nullptr;
2295   }
2296
2297   // Otherwise, create a new forward reference for this value and remember it.
2298   Value *FwdVal;
2299   if (Ty->isLabelTy()) {
2300     assert(!OC);
2301     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2302   } else if (!OC) {
2303     FwdVal = new Argument(Ty, Name);
2304   } else {
2305     switch (OC) {
2306     case OC_CatchPad:
2307       FwdVal = CatchPadInst::Create(&F.getEntryBlock(), &F.getEntryBlock(), {},
2308                                     Name);
2309       break;
2310     case OC_CleanupPad:
2311       FwdVal = CleanupPadInst::Create(F.getContext(), {}, Name);
2312       break;
2313     default:
2314       llvm_unreachable("unexpected constraint");
2315     }
2316   }
2317
2318   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2319   return FwdVal;
2320 }
2321
2322 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2323                                           OperatorConstraint OC) {
2324   // Look this name up in the normal function symbol table.
2325   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2326
2327   // If this is a forward reference for the value, see if we already created a
2328   // forward ref record.
2329   if (!Val) {
2330     std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2331       I = ForwardRefValIDs.find(ID);
2332     if (I != ForwardRefValIDs.end())
2333       Val = I->second.first;
2334   }
2335
2336   // If we have the value in the symbol table or fwd-ref table, return it.
2337   if (Val) {
2338     // Check operator constraint.
2339     switch (OC) {
2340     case OC_None:
2341       // no constraint
2342       break;
2343     case OC_CatchPad:
2344       if (!isa<CatchPadInst>(Val)) {
2345         P.Error(Loc, "'%" + Twine(ID) + "' is not a catchpad");
2346         return nullptr;
2347       }
2348       break;
2349     case OC_CleanupPad:
2350       if (!isa<CleanupPadInst>(Val)) {
2351         P.Error(Loc, "'%" + Twine(ID) + "' is not a cleanuppad");
2352         return nullptr;
2353       }
2354       break;
2355     }
2356     if (Val->getType() == Ty) return Val;
2357     if (Ty->isLabelTy())
2358       P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2359     else
2360       P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2361               getTypeString(Val->getType()) + "'");
2362     return nullptr;
2363   }
2364
2365   if (!Ty->isFirstClassType()) {
2366     P.Error(Loc, "invalid use of a non-first-class type");
2367     return nullptr;
2368   }
2369
2370   // Otherwise, create a new forward reference for this value and remember it.
2371   Value *FwdVal;
2372   if (Ty->isLabelTy()) {
2373     assert(!OC);
2374     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2375   } else if (!OC) {
2376     FwdVal = new Argument(Ty);
2377   } else {
2378     switch (OC) {
2379     case OC_CatchPad:
2380       FwdVal = CatchPadInst::Create(&F.getEntryBlock(), &F.getEntryBlock(), {});
2381       break;
2382     case OC_CleanupPad:
2383       FwdVal = CleanupPadInst::Create(F.getContext(), {});
2384       break;
2385     default:
2386       llvm_unreachable("unexpected constraint");
2387     }
2388   }
2389
2390   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2391   return FwdVal;
2392 }
2393
2394 /// SetInstName - After an instruction is parsed and inserted into its
2395 /// basic block, this installs its name.
2396 bool LLParser::PerFunctionState::SetInstName(int NameID,
2397                                              const std::string &NameStr,
2398                                              LocTy NameLoc, Instruction *Inst) {
2399   // If this instruction has void type, it cannot have a name or ID specified.
2400   if (Inst->getType()->isVoidTy()) {
2401     if (NameID != -1 || !NameStr.empty())
2402       return P.Error(NameLoc, "instructions returning void cannot have a name");
2403     return false;
2404   }
2405
2406   // If this was a numbered instruction, verify that the instruction is the
2407   // expected value and resolve any forward references.
2408   if (NameStr.empty()) {
2409     // If neither a name nor an ID was specified, just use the next ID.
2410     if (NameID == -1)
2411       NameID = NumberedVals.size();
2412
2413     if (unsigned(NameID) != NumberedVals.size())
2414       return P.Error(NameLoc, "instruction expected to be numbered '%" +
2415                      Twine(NumberedVals.size()) + "'");
2416
2417     std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2418       ForwardRefValIDs.find(NameID);
2419     if (FI != ForwardRefValIDs.end()) {
2420       Value *Sentinel = FI->second.first;
2421       if (Sentinel->getType() != Inst->getType())
2422         return P.Error(NameLoc, "instruction forward referenced with type '" +
2423                        getTypeString(FI->second.first->getType()) + "'");
2424       // Check operator constraints.  We only put cleanuppads or catchpads in
2425       // the forward value map if the value is constrained to match.
2426       if (isa<CatchPadInst>(Sentinel)) {
2427         if (!isa<CatchPadInst>(Inst))
2428           return P.Error(FI->second.second,
2429                          "'%" + Twine(NameID) + "' is not a catchpad");
2430       } else if (isa<CleanupPadInst>(Sentinel)) {
2431         if (!isa<CleanupPadInst>(Inst))
2432           return P.Error(FI->second.second,
2433                          "'%" + Twine(NameID) + "' is not a cleanuppad");
2434       }
2435
2436       Sentinel->replaceAllUsesWith(Inst);
2437       delete Sentinel;
2438       ForwardRefValIDs.erase(FI);
2439     }
2440
2441     NumberedVals.push_back(Inst);
2442     return false;
2443   }
2444
2445   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
2446   std::map<std::string, std::pair<Value*, LocTy> >::iterator
2447     FI = ForwardRefVals.find(NameStr);
2448   if (FI != ForwardRefVals.end()) {
2449     Value *Sentinel = FI->second.first;
2450     if (Sentinel->getType() != Inst->getType())
2451       return P.Error(NameLoc, "instruction forward referenced with type '" +
2452                      getTypeString(FI->second.first->getType()) + "'");
2453     // Check operator constraints.  We only put cleanuppads or catchpads in
2454     // the forward value map if the value is constrained to match.
2455     if (isa<CatchPadInst>(Sentinel)) {
2456       if (!isa<CatchPadInst>(Inst))
2457         return P.Error(FI->second.second,
2458                        "'%" + NameStr + "' is not a catchpad");
2459     } else if (isa<CleanupPadInst>(Sentinel)) {
2460       if (!isa<CleanupPadInst>(Inst))
2461         return P.Error(FI->second.second,
2462                        "'%" + NameStr + "' is not a cleanuppad");
2463     }
2464
2465     Sentinel->replaceAllUsesWith(Inst);
2466     delete Sentinel;
2467     ForwardRefVals.erase(FI);
2468   }
2469
2470   // Set the name on the instruction.
2471   Inst->setName(NameStr);
2472
2473   if (Inst->getName() != NameStr)
2474     return P.Error(NameLoc, "multiple definition of local value named '" +
2475                    NameStr + "'");
2476   return false;
2477 }
2478
2479 /// GetBB - Get a basic block with the specified name or ID, creating a
2480 /// forward reference record if needed.
2481 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2482                                               LocTy Loc) {
2483   return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2484                                       Type::getLabelTy(F.getContext()), Loc));
2485 }
2486
2487 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2488   return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2489                                       Type::getLabelTy(F.getContext()), Loc));
2490 }
2491
2492 /// DefineBB - Define the specified basic block, which is either named or
2493 /// unnamed.  If there is an error, this returns null otherwise it returns
2494 /// the block being defined.
2495 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2496                                                  LocTy Loc) {
2497   BasicBlock *BB;
2498   if (Name.empty())
2499     BB = GetBB(NumberedVals.size(), Loc);
2500   else
2501     BB = GetBB(Name, Loc);
2502   if (!BB) return nullptr; // Already diagnosed error.
2503
2504   // Move the block to the end of the function.  Forward ref'd blocks are
2505   // inserted wherever they happen to be referenced.
2506   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2507
2508   // Remove the block from forward ref sets.
2509   if (Name.empty()) {
2510     ForwardRefValIDs.erase(NumberedVals.size());
2511     NumberedVals.push_back(BB);
2512   } else {
2513     // BB forward references are already in the function symbol table.
2514     ForwardRefVals.erase(Name);
2515   }
2516
2517   return BB;
2518 }
2519
2520 //===----------------------------------------------------------------------===//
2521 // Constants.
2522 //===----------------------------------------------------------------------===//
2523
2524 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2525 /// type implied.  For example, if we parse "4" we don't know what integer type
2526 /// it has.  The value will later be combined with its type and checked for
2527 /// sanity.  PFS is used to convert function-local operands of metadata (since
2528 /// metadata operands are not just parsed here but also converted to values).
2529 /// PFS can be null when we are not parsing metadata values inside a function.
2530 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2531   ID.Loc = Lex.getLoc();
2532   switch (Lex.getKind()) {
2533   default: return TokError("expected value token");
2534   case lltok::GlobalID:  // @42
2535     ID.UIntVal = Lex.getUIntVal();
2536     ID.Kind = ValID::t_GlobalID;
2537     break;
2538   case lltok::GlobalVar:  // @foo
2539     ID.StrVal = Lex.getStrVal();
2540     ID.Kind = ValID::t_GlobalName;
2541     break;
2542   case lltok::LocalVarID:  // %42
2543     ID.UIntVal = Lex.getUIntVal();
2544     ID.Kind = ValID::t_LocalID;
2545     break;
2546   case lltok::LocalVar:  // %foo
2547     ID.StrVal = Lex.getStrVal();
2548     ID.Kind = ValID::t_LocalName;
2549     break;
2550   case lltok::APSInt:
2551     ID.APSIntVal = Lex.getAPSIntVal();
2552     ID.Kind = ValID::t_APSInt;
2553     break;
2554   case lltok::APFloat:
2555     ID.APFloatVal = Lex.getAPFloatVal();
2556     ID.Kind = ValID::t_APFloat;
2557     break;
2558   case lltok::kw_true:
2559     ID.ConstantVal = ConstantInt::getTrue(Context);
2560     ID.Kind = ValID::t_Constant;
2561     break;
2562   case lltok::kw_false:
2563     ID.ConstantVal = ConstantInt::getFalse(Context);
2564     ID.Kind = ValID::t_Constant;
2565     break;
2566   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2567   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2568   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2569
2570   case lltok::lbrace: {
2571     // ValID ::= '{' ConstVector '}'
2572     Lex.Lex();
2573     SmallVector<Constant*, 16> Elts;
2574     if (ParseGlobalValueVector(Elts) ||
2575         ParseToken(lltok::rbrace, "expected end of struct constant"))
2576       return true;
2577
2578     ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2579     ID.UIntVal = Elts.size();
2580     memcpy(ID.ConstantStructElts.get(), Elts.data(),
2581            Elts.size() * sizeof(Elts[0]));
2582     ID.Kind = ValID::t_ConstantStruct;
2583     return false;
2584   }
2585   case lltok::less: {
2586     // ValID ::= '<' ConstVector '>'         --> Vector.
2587     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2588     Lex.Lex();
2589     bool isPackedStruct = EatIfPresent(lltok::lbrace);
2590
2591     SmallVector<Constant*, 16> Elts;
2592     LocTy FirstEltLoc = Lex.getLoc();
2593     if (ParseGlobalValueVector(Elts) ||
2594         (isPackedStruct &&
2595          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2596         ParseToken(lltok::greater, "expected end of constant"))
2597       return true;
2598
2599     if (isPackedStruct) {
2600       ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2601       memcpy(ID.ConstantStructElts.get(), Elts.data(),
2602              Elts.size() * sizeof(Elts[0]));
2603       ID.UIntVal = Elts.size();
2604       ID.Kind = ValID::t_PackedConstantStruct;
2605       return false;
2606     }
2607
2608     if (Elts.empty())
2609       return Error(ID.Loc, "constant vector must not be empty");
2610
2611     if (!Elts[0]->getType()->isIntegerTy() &&
2612         !Elts[0]->getType()->isFloatingPointTy() &&
2613         !Elts[0]->getType()->isPointerTy())
2614       return Error(FirstEltLoc,
2615             "vector elements must have integer, pointer or floating point type");
2616
2617     // Verify that all the vector elements have the same type.
2618     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2619       if (Elts[i]->getType() != Elts[0]->getType())
2620         return Error(FirstEltLoc,
2621                      "vector element #" + Twine(i) +
2622                     " is not of type '" + getTypeString(Elts[0]->getType()));
2623
2624     ID.ConstantVal = ConstantVector::get(Elts);
2625     ID.Kind = ValID::t_Constant;
2626     return false;
2627   }
2628   case lltok::lsquare: {   // Array Constant
2629     Lex.Lex();
2630     SmallVector<Constant*, 16> Elts;
2631     LocTy FirstEltLoc = Lex.getLoc();
2632     if (ParseGlobalValueVector(Elts) ||
2633         ParseToken(lltok::rsquare, "expected end of array constant"))
2634       return true;
2635
2636     // Handle empty element.
2637     if (Elts.empty()) {
2638       // Use undef instead of an array because it's inconvenient to determine
2639       // the element type at this point, there being no elements to examine.
2640       ID.Kind = ValID::t_EmptyArray;
2641       return false;
2642     }
2643
2644     if (!Elts[0]->getType()->isFirstClassType())
2645       return Error(FirstEltLoc, "invalid array element type: " +
2646                    getTypeString(Elts[0]->getType()));
2647
2648     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2649
2650     // Verify all elements are correct type!
2651     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2652       if (Elts[i]->getType() != Elts[0]->getType())
2653         return Error(FirstEltLoc,
2654                      "array element #" + Twine(i) +
2655                      " is not of type '" + getTypeString(Elts[0]->getType()));
2656     }
2657
2658     ID.ConstantVal = ConstantArray::get(ATy, Elts);
2659     ID.Kind = ValID::t_Constant;
2660     return false;
2661   }
2662   case lltok::kw_c:  // c "foo"
2663     Lex.Lex();
2664     ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2665                                                   false);
2666     if (ParseToken(lltok::StringConstant, "expected string")) return true;
2667     ID.Kind = ValID::t_Constant;
2668     return false;
2669
2670   case lltok::kw_asm: {
2671     // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2672     //             STRINGCONSTANT
2673     bool HasSideEffect, AlignStack, AsmDialect;
2674     Lex.Lex();
2675     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2676         ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2677         ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2678         ParseStringConstant(ID.StrVal) ||
2679         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2680         ParseToken(lltok::StringConstant, "expected constraint string"))
2681       return true;
2682     ID.StrVal2 = Lex.getStrVal();
2683     ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2684       (unsigned(AsmDialect)<<2);
2685     ID.Kind = ValID::t_InlineAsm;
2686     return false;
2687   }
2688
2689   case lltok::kw_blockaddress: {
2690     // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2691     Lex.Lex();
2692
2693     ValID Fn, Label;
2694
2695     if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2696         ParseValID(Fn) ||
2697         ParseToken(lltok::comma, "expected comma in block address expression")||
2698         ParseValID(Label) ||
2699         ParseToken(lltok::rparen, "expected ')' in block address expression"))
2700       return true;
2701
2702     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2703       return Error(Fn.Loc, "expected function name in blockaddress");
2704     if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2705       return Error(Label.Loc, "expected basic block name in blockaddress");
2706
2707     // Try to find the function (but skip it if it's forward-referenced).
2708     GlobalValue *GV = nullptr;
2709     if (Fn.Kind == ValID::t_GlobalID) {
2710       if (Fn.UIntVal < NumberedVals.size())
2711         GV = NumberedVals[Fn.UIntVal];
2712     } else if (!ForwardRefVals.count(Fn.StrVal)) {
2713       GV = M->getNamedValue(Fn.StrVal);
2714     }
2715     Function *F = nullptr;
2716     if (GV) {
2717       // Confirm that it's actually a function with a definition.
2718       if (!isa<Function>(GV))
2719         return Error(Fn.Loc, "expected function name in blockaddress");
2720       F = cast<Function>(GV);
2721       if (F->isDeclaration())
2722         return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2723     }
2724
2725     if (!F) {
2726       // Make a global variable as a placeholder for this reference.
2727       GlobalValue *&FwdRef =
2728           ForwardRefBlockAddresses.insert(std::make_pair(
2729                                               std::move(Fn),
2730                                               std::map<ValID, GlobalValue *>()))
2731               .first->second.insert(std::make_pair(std::move(Label), nullptr))
2732               .first->second;
2733       if (!FwdRef)
2734         FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2735                                     GlobalValue::InternalLinkage, nullptr, "");
2736       ID.ConstantVal = FwdRef;
2737       ID.Kind = ValID::t_Constant;
2738       return false;
2739     }
2740
2741     // We found the function; now find the basic block.  Don't use PFS, since we
2742     // might be inside a constant expression.
2743     BasicBlock *BB;
2744     if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2745       if (Label.Kind == ValID::t_LocalID)
2746         BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2747       else
2748         BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2749       if (!BB)
2750         return Error(Label.Loc, "referenced value is not a basic block");
2751     } else {
2752       if (Label.Kind == ValID::t_LocalID)
2753         return Error(Label.Loc, "cannot take address of numeric label after "
2754                                 "the function is defined");
2755       BB = dyn_cast_or_null<BasicBlock>(
2756           F->getValueSymbolTable().lookup(Label.StrVal));
2757       if (!BB)
2758         return Error(Label.Loc, "referenced value is not a basic block");
2759     }
2760
2761     ID.ConstantVal = BlockAddress::get(F, BB);
2762     ID.Kind = ValID::t_Constant;
2763     return false;
2764   }
2765
2766   case lltok::kw_trunc:
2767   case lltok::kw_zext:
2768   case lltok::kw_sext:
2769   case lltok::kw_fptrunc:
2770   case lltok::kw_fpext:
2771   case lltok::kw_bitcast:
2772   case lltok::kw_addrspacecast:
2773   case lltok::kw_uitofp:
2774   case lltok::kw_sitofp:
2775   case lltok::kw_fptoui:
2776   case lltok::kw_fptosi:
2777   case lltok::kw_inttoptr:
2778   case lltok::kw_ptrtoint: {
2779     unsigned Opc = Lex.getUIntVal();
2780     Type *DestTy = nullptr;
2781     Constant *SrcVal;
2782     Lex.Lex();
2783     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2784         ParseGlobalTypeAndValue(SrcVal) ||
2785         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2786         ParseType(DestTy) ||
2787         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2788       return true;
2789     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2790       return Error(ID.Loc, "invalid cast opcode for cast from '" +
2791                    getTypeString(SrcVal->getType()) + "' to '" +
2792                    getTypeString(DestTy) + "'");
2793     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2794                                                  SrcVal, DestTy);
2795     ID.Kind = ValID::t_Constant;
2796     return false;
2797   }
2798   case lltok::kw_extractvalue: {
2799     Lex.Lex();
2800     Constant *Val;
2801     SmallVector<unsigned, 4> Indices;
2802     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2803         ParseGlobalTypeAndValue(Val) ||
2804         ParseIndexList(Indices) ||
2805         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2806       return true;
2807
2808     if (!Val->getType()->isAggregateType())
2809       return Error(ID.Loc, "extractvalue operand must be aggregate type");
2810     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2811       return Error(ID.Loc, "invalid indices for extractvalue");
2812     ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2813     ID.Kind = ValID::t_Constant;
2814     return false;
2815   }
2816   case lltok::kw_insertvalue: {
2817     Lex.Lex();
2818     Constant *Val0, *Val1;
2819     SmallVector<unsigned, 4> Indices;
2820     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2821         ParseGlobalTypeAndValue(Val0) ||
2822         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2823         ParseGlobalTypeAndValue(Val1) ||
2824         ParseIndexList(Indices) ||
2825         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2826       return true;
2827     if (!Val0->getType()->isAggregateType())
2828       return Error(ID.Loc, "insertvalue operand must be aggregate type");
2829     Type *IndexedType =
2830         ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2831     if (!IndexedType)
2832       return Error(ID.Loc, "invalid indices for insertvalue");
2833     if (IndexedType != Val1->getType())
2834       return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2835                                getTypeString(Val1->getType()) +
2836                                "' instead of '" + getTypeString(IndexedType) +
2837                                "'");
2838     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2839     ID.Kind = ValID::t_Constant;
2840     return false;
2841   }
2842   case lltok::kw_icmp:
2843   case lltok::kw_fcmp: {
2844     unsigned PredVal, Opc = Lex.getUIntVal();
2845     Constant *Val0, *Val1;
2846     Lex.Lex();
2847     if (ParseCmpPredicate(PredVal, Opc) ||
2848         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2849         ParseGlobalTypeAndValue(Val0) ||
2850         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2851         ParseGlobalTypeAndValue(Val1) ||
2852         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2853       return true;
2854
2855     if (Val0->getType() != Val1->getType())
2856       return Error(ID.Loc, "compare operands must have the same type");
2857
2858     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2859
2860     if (Opc == Instruction::FCmp) {
2861       if (!Val0->getType()->isFPOrFPVectorTy())
2862         return Error(ID.Loc, "fcmp requires floating point operands");
2863       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2864     } else {
2865       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2866       if (!Val0->getType()->isIntOrIntVectorTy() &&
2867           !Val0->getType()->getScalarType()->isPointerTy())
2868         return Error(ID.Loc, "icmp requires pointer or integer operands");
2869       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2870     }
2871     ID.Kind = ValID::t_Constant;
2872     return false;
2873   }
2874
2875   // Binary Operators.
2876   case lltok::kw_add:
2877   case lltok::kw_fadd:
2878   case lltok::kw_sub:
2879   case lltok::kw_fsub:
2880   case lltok::kw_mul:
2881   case lltok::kw_fmul:
2882   case lltok::kw_udiv:
2883   case lltok::kw_sdiv:
2884   case lltok::kw_fdiv:
2885   case lltok::kw_urem:
2886   case lltok::kw_srem:
2887   case lltok::kw_frem:
2888   case lltok::kw_shl:
2889   case lltok::kw_lshr:
2890   case lltok::kw_ashr: {
2891     bool NUW = false;
2892     bool NSW = false;
2893     bool Exact = false;
2894     unsigned Opc = Lex.getUIntVal();
2895     Constant *Val0, *Val1;
2896     Lex.Lex();
2897     LocTy ModifierLoc = Lex.getLoc();
2898     if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2899         Opc == Instruction::Mul || Opc == Instruction::Shl) {
2900       if (EatIfPresent(lltok::kw_nuw))
2901         NUW = true;
2902       if (EatIfPresent(lltok::kw_nsw)) {
2903         NSW = true;
2904         if (EatIfPresent(lltok::kw_nuw))
2905           NUW = true;
2906       }
2907     } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2908                Opc == Instruction::LShr || Opc == Instruction::AShr) {
2909       if (EatIfPresent(lltok::kw_exact))
2910         Exact = true;
2911     }
2912     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2913         ParseGlobalTypeAndValue(Val0) ||
2914         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2915         ParseGlobalTypeAndValue(Val1) ||
2916         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2917       return true;
2918     if (Val0->getType() != Val1->getType())
2919       return Error(ID.Loc, "operands of constexpr must have same type");
2920     if (!Val0->getType()->isIntOrIntVectorTy()) {
2921       if (NUW)
2922         return Error(ModifierLoc, "nuw only applies to integer operations");
2923       if (NSW)
2924         return Error(ModifierLoc, "nsw only applies to integer operations");
2925     }
2926     // Check that the type is valid for the operator.
2927     switch (Opc) {
2928     case Instruction::Add:
2929     case Instruction::Sub:
2930     case Instruction::Mul:
2931     case Instruction::UDiv:
2932     case Instruction::SDiv:
2933     case Instruction::URem:
2934     case Instruction::SRem:
2935     case Instruction::Shl:
2936     case Instruction::AShr:
2937     case Instruction::LShr:
2938       if (!Val0->getType()->isIntOrIntVectorTy())
2939         return Error(ID.Loc, "constexpr requires integer operands");
2940       break;
2941     case Instruction::FAdd:
2942     case Instruction::FSub:
2943     case Instruction::FMul:
2944     case Instruction::FDiv:
2945     case Instruction::FRem:
2946       if (!Val0->getType()->isFPOrFPVectorTy())
2947         return Error(ID.Loc, "constexpr requires fp operands");
2948       break;
2949     default: llvm_unreachable("Unknown binary operator!");
2950     }
2951     unsigned Flags = 0;
2952     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2953     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
2954     if (Exact) Flags |= PossiblyExactOperator::IsExact;
2955     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2956     ID.ConstantVal = C;
2957     ID.Kind = ValID::t_Constant;
2958     return false;
2959   }
2960
2961   // Logical Operations
2962   case lltok::kw_and:
2963   case lltok::kw_or:
2964   case lltok::kw_xor: {
2965     unsigned Opc = Lex.getUIntVal();
2966     Constant *Val0, *Val1;
2967     Lex.Lex();
2968     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2969         ParseGlobalTypeAndValue(Val0) ||
2970         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2971         ParseGlobalTypeAndValue(Val1) ||
2972         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2973       return true;
2974     if (Val0->getType() != Val1->getType())
2975       return Error(ID.Loc, "operands of constexpr must have same type");
2976     if (!Val0->getType()->isIntOrIntVectorTy())
2977       return Error(ID.Loc,
2978                    "constexpr requires integer or integer vector operands");
2979     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2980     ID.Kind = ValID::t_Constant;
2981     return false;
2982   }
2983
2984   case lltok::kw_getelementptr:
2985   case lltok::kw_shufflevector:
2986   case lltok::kw_insertelement:
2987   case lltok::kw_extractelement:
2988   case lltok::kw_select: {
2989     unsigned Opc = Lex.getUIntVal();
2990     SmallVector<Constant*, 16> Elts;
2991     bool InBounds = false;
2992     Type *Ty;
2993     Lex.Lex();
2994
2995     if (Opc == Instruction::GetElementPtr)
2996       InBounds = EatIfPresent(lltok::kw_inbounds);
2997
2998     if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2999       return true;
3000
3001     LocTy ExplicitTypeLoc = Lex.getLoc();
3002     if (Opc == Instruction::GetElementPtr) {
3003       if (ParseType(Ty) ||
3004           ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3005         return true;
3006     }
3007
3008     if (ParseGlobalValueVector(Elts) ||
3009         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3010       return true;
3011
3012     if (Opc == Instruction::GetElementPtr) {
3013       if (Elts.size() == 0 ||
3014           !Elts[0]->getType()->getScalarType()->isPointerTy())
3015         return Error(ID.Loc, "base of getelementptr must be a pointer");
3016
3017       Type *BaseType = Elts[0]->getType();
3018       auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3019       if (Ty != BasePointerType->getElementType())
3020         return Error(
3021             ExplicitTypeLoc,
3022             "explicit pointee type doesn't match operand's pointee type");
3023
3024       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3025       for (Constant *Val : Indices) {
3026         Type *ValTy = Val->getType();
3027         if (!ValTy->getScalarType()->isIntegerTy())
3028           return Error(ID.Loc, "getelementptr index must be an integer");
3029         if (ValTy->isVectorTy() != BaseType->isVectorTy())
3030           return Error(ID.Loc, "getelementptr index type missmatch");
3031         if (ValTy->isVectorTy()) {
3032           unsigned ValNumEl = ValTy->getVectorNumElements();
3033           unsigned PtrNumEl = BaseType->getVectorNumElements();
3034           if (ValNumEl != PtrNumEl)
3035             return Error(
3036                 ID.Loc,
3037                 "getelementptr vector index has a wrong number of elements");
3038         }
3039       }
3040
3041       SmallPtrSet<Type*, 4> Visited;
3042       if (!Indices.empty() && !Ty->isSized(&Visited))
3043         return Error(ID.Loc, "base element of getelementptr must be sized");
3044
3045       if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3046         return Error(ID.Loc, "invalid getelementptr indices");
3047       ID.ConstantVal =
3048           ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
3049     } else if (Opc == Instruction::Select) {
3050       if (Elts.size() != 3)
3051         return Error(ID.Loc, "expected three operands to select");
3052       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3053                                                               Elts[2]))
3054         return Error(ID.Loc, Reason);
3055       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3056     } else if (Opc == Instruction::ShuffleVector) {
3057       if (Elts.size() != 3)
3058         return Error(ID.Loc, "expected three operands to shufflevector");
3059       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3060         return Error(ID.Loc, "invalid operands to shufflevector");
3061       ID.ConstantVal =
3062                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3063     } else if (Opc == Instruction::ExtractElement) {
3064       if (Elts.size() != 2)
3065         return Error(ID.Loc, "expected two operands to extractelement");
3066       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3067         return Error(ID.Loc, "invalid extractelement operands");
3068       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3069     } else {
3070       assert(Opc == Instruction::InsertElement && "Unknown opcode");
3071       if (Elts.size() != 3)
3072       return Error(ID.Loc, "expected three operands to insertelement");
3073       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3074         return Error(ID.Loc, "invalid insertelement operands");
3075       ID.ConstantVal =
3076                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3077     }
3078
3079     ID.Kind = ValID::t_Constant;
3080     return false;
3081   }
3082   }
3083
3084   Lex.Lex();
3085   return false;
3086 }
3087
3088 /// ParseGlobalValue - Parse a global value with the specified type.
3089 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3090   C = nullptr;
3091   ValID ID;
3092   Value *V = nullptr;
3093   bool Parsed = ParseValID(ID) ||
3094                 ConvertValIDToValue(Ty, ID, V, nullptr);
3095   if (V && !(C = dyn_cast<Constant>(V)))
3096     return Error(ID.Loc, "global values must be constants");
3097   return Parsed;
3098 }
3099
3100 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3101   Type *Ty = nullptr;
3102   return ParseType(Ty) ||
3103          ParseGlobalValue(Ty, V);
3104 }
3105
3106 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3107   C = nullptr;
3108
3109   LocTy KwLoc = Lex.getLoc();
3110   if (!EatIfPresent(lltok::kw_comdat))
3111     return false;
3112
3113   if (EatIfPresent(lltok::lparen)) {
3114     if (Lex.getKind() != lltok::ComdatVar)
3115       return TokError("expected comdat variable");
3116     C = getComdat(Lex.getStrVal(), Lex.getLoc());
3117     Lex.Lex();
3118     if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3119       return true;
3120   } else {
3121     if (GlobalName.empty())
3122       return TokError("comdat cannot be unnamed");
3123     C = getComdat(GlobalName, KwLoc);
3124   }
3125
3126   return false;
3127 }
3128
3129 /// ParseGlobalValueVector
3130 ///   ::= /*empty*/
3131 ///   ::= TypeAndValue (',' TypeAndValue)*
3132 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
3133   // Empty list.
3134   if (Lex.getKind() == lltok::rbrace ||
3135       Lex.getKind() == lltok::rsquare ||
3136       Lex.getKind() == lltok::greater ||
3137       Lex.getKind() == lltok::rparen)
3138     return false;
3139
3140   Constant *C;
3141   if (ParseGlobalTypeAndValue(C)) return true;
3142   Elts.push_back(C);
3143
3144   while (EatIfPresent(lltok::comma)) {
3145     if (ParseGlobalTypeAndValue(C)) return true;
3146     Elts.push_back(C);
3147   }
3148
3149   return false;
3150 }
3151
3152 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3153   SmallVector<Metadata *, 16> Elts;
3154   if (ParseMDNodeVector(Elts))
3155     return true;
3156
3157   MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3158   return false;
3159 }
3160
3161 /// MDNode:
3162 ///  ::= !{ ... }
3163 ///  ::= !7
3164 ///  ::= !DILocation(...)
3165 bool LLParser::ParseMDNode(MDNode *&N) {
3166   if (Lex.getKind() == lltok::MetadataVar)
3167     return ParseSpecializedMDNode(N);
3168
3169   return ParseToken(lltok::exclaim, "expected '!' here") ||
3170          ParseMDNodeTail(N);
3171 }
3172
3173 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3174   // !{ ... }
3175   if (Lex.getKind() == lltok::lbrace)
3176     return ParseMDTuple(N);
3177
3178   // !42
3179   return ParseMDNodeID(N);
3180 }
3181
3182 namespace {
3183
3184 /// Structure to represent an optional metadata field.
3185 template <class FieldTy> struct MDFieldImpl {
3186   typedef MDFieldImpl ImplTy;
3187   FieldTy Val;
3188   bool Seen;
3189
3190   void assign(FieldTy Val) {
3191     Seen = true;
3192     this->Val = std::move(Val);
3193   }
3194
3195   explicit MDFieldImpl(FieldTy Default)
3196       : Val(std::move(Default)), Seen(false) {}
3197 };
3198
3199 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3200   uint64_t Max;
3201
3202   MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3203       : ImplTy(Default), Max(Max) {}
3204 };
3205 struct LineField : public MDUnsignedField {
3206   LineField() : MDUnsignedField(0, UINT32_MAX) {}
3207 };
3208 struct ColumnField : public MDUnsignedField {
3209   ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3210 };
3211 struct DwarfTagField : public MDUnsignedField {
3212   DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3213   DwarfTagField(dwarf::Tag DefaultTag)
3214       : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3215 };
3216 struct DwarfAttEncodingField : public MDUnsignedField {
3217   DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3218 };
3219 struct DwarfVirtualityField : public MDUnsignedField {
3220   DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3221 };
3222 struct DwarfLangField : public MDUnsignedField {
3223   DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3224 };
3225
3226 struct DIFlagField : public MDUnsignedField {
3227   DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3228 };
3229
3230 struct MDSignedField : public MDFieldImpl<int64_t> {
3231   int64_t Min;
3232   int64_t Max;
3233
3234   MDSignedField(int64_t Default = 0)
3235       : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3236   MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3237       : ImplTy(Default), Min(Min), Max(Max) {}
3238 };
3239
3240 struct MDBoolField : public MDFieldImpl<bool> {
3241   MDBoolField(bool Default = false) : ImplTy(Default) {}
3242 };
3243 struct MDField : public MDFieldImpl<Metadata *> {
3244   bool AllowNull;
3245
3246   MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3247 };
3248 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3249   MDConstant() : ImplTy(nullptr) {}
3250 };
3251 struct MDStringField : public MDFieldImpl<MDString *> {
3252   bool AllowEmpty;
3253   MDStringField(bool AllowEmpty = true)
3254       : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3255 };
3256 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3257   MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3258 };
3259
3260 } // end namespace
3261
3262 namespace llvm {
3263
3264 template <>
3265 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3266                             MDUnsignedField &Result) {
3267   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3268     return TokError("expected unsigned integer");
3269
3270   auto &U = Lex.getAPSIntVal();
3271   if (U.ugt(Result.Max))
3272     return TokError("value for '" + Name + "' too large, limit is " +
3273                     Twine(Result.Max));
3274   Result.assign(U.getZExtValue());
3275   assert(Result.Val <= Result.Max && "Expected value in range");
3276   Lex.Lex();
3277   return false;
3278 }
3279
3280 template <>
3281 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3282   return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3283 }
3284 template <>
3285 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3286   return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3287 }
3288
3289 template <>
3290 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3291   if (Lex.getKind() == lltok::APSInt)
3292     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3293
3294   if (Lex.getKind() != lltok::DwarfTag)
3295     return TokError("expected DWARF tag");
3296
3297   unsigned Tag = dwarf::getTag(Lex.getStrVal());
3298   if (Tag == dwarf::DW_TAG_invalid)
3299     return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3300   assert(Tag <= Result.Max && "Expected valid DWARF tag");
3301
3302   Result.assign(Tag);
3303   Lex.Lex();
3304   return false;
3305 }
3306
3307 template <>
3308 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3309                             DwarfVirtualityField &Result) {
3310   if (Lex.getKind() == lltok::APSInt)
3311     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3312
3313   if (Lex.getKind() != lltok::DwarfVirtuality)
3314     return TokError("expected DWARF virtuality code");
3315
3316   unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3317   if (!Virtuality)
3318     return TokError("invalid DWARF virtuality code" + Twine(" '") +
3319                     Lex.getStrVal() + "'");
3320   assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3321   Result.assign(Virtuality);
3322   Lex.Lex();
3323   return false;
3324 }
3325
3326 template <>
3327 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3328   if (Lex.getKind() == lltok::APSInt)
3329     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3330
3331   if (Lex.getKind() != lltok::DwarfLang)
3332     return TokError("expected DWARF language");
3333
3334   unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3335   if (!Lang)
3336     return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3337                     "'");
3338   assert(Lang <= Result.Max && "Expected valid DWARF language");
3339   Result.assign(Lang);
3340   Lex.Lex();
3341   return false;
3342 }
3343
3344 template <>
3345 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3346                             DwarfAttEncodingField &Result) {
3347   if (Lex.getKind() == lltok::APSInt)
3348     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3349
3350   if (Lex.getKind() != lltok::DwarfAttEncoding)
3351     return TokError("expected DWARF type attribute encoding");
3352
3353   unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3354   if (!Encoding)
3355     return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3356                     Lex.getStrVal() + "'");
3357   assert(Encoding <= Result.Max && "Expected valid DWARF language");
3358   Result.assign(Encoding);
3359   Lex.Lex();
3360   return false;
3361 }
3362
3363 /// DIFlagField
3364 ///  ::= uint32
3365 ///  ::= DIFlagVector
3366 ///  ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3367 template <>
3368 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3369   assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3370
3371   // Parser for a single flag.
3372   auto parseFlag = [&](unsigned &Val) {
3373     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3374       return ParseUInt32(Val);
3375
3376     if (Lex.getKind() != lltok::DIFlag)
3377       return TokError("expected debug info flag");
3378
3379     Val = DINode::getFlag(Lex.getStrVal());
3380     if (!Val)
3381       return TokError(Twine("invalid debug info flag flag '") +
3382                       Lex.getStrVal() + "'");
3383     Lex.Lex();
3384     return false;
3385   };
3386
3387   // Parse the flags and combine them together.
3388   unsigned Combined = 0;
3389   do {
3390     unsigned Val;
3391     if (parseFlag(Val))
3392       return true;
3393     Combined |= Val;
3394   } while (EatIfPresent(lltok::bar));
3395
3396   Result.assign(Combined);
3397   return false;
3398 }
3399
3400 template <>
3401 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3402                             MDSignedField &Result) {
3403   if (Lex.getKind() != lltok::APSInt)
3404     return TokError("expected signed integer");
3405
3406   auto &S = Lex.getAPSIntVal();
3407   if (S < Result.Min)
3408     return TokError("value for '" + Name + "' too small, limit is " +
3409                     Twine(Result.Min));
3410   if (S > Result.Max)
3411     return TokError("value for '" + Name + "' too large, limit is " +
3412                     Twine(Result.Max));
3413   Result.assign(S.getExtValue());
3414   assert(Result.Val >= Result.Min && "Expected value in range");
3415   assert(Result.Val <= Result.Max && "Expected value in range");
3416   Lex.Lex();
3417   return false;
3418 }
3419
3420 template <>
3421 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3422   switch (Lex.getKind()) {
3423   default:
3424     return TokError("expected 'true' or 'false'");
3425   case lltok::kw_true:
3426     Result.assign(true);
3427     break;
3428   case lltok::kw_false:
3429     Result.assign(false);
3430     break;
3431   }
3432   Lex.Lex();
3433   return false;
3434 }
3435
3436 template <>
3437 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3438   if (Lex.getKind() == lltok::kw_null) {
3439     if (!Result.AllowNull)
3440       return TokError("'" + Name + "' cannot be null");
3441     Lex.Lex();
3442     Result.assign(nullptr);
3443     return false;
3444   }
3445
3446   Metadata *MD;
3447   if (ParseMetadata(MD, nullptr))
3448     return true;
3449
3450   Result.assign(MD);
3451   return false;
3452 }
3453
3454 template <>
3455 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3456   Metadata *MD;
3457   if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3458     return true;
3459
3460   Result.assign(cast<ConstantAsMetadata>(MD));
3461   return false;
3462 }
3463
3464 template <>
3465 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3466   LocTy ValueLoc = Lex.getLoc();
3467   std::string S;
3468   if (ParseStringConstant(S))
3469     return true;
3470
3471   if (!Result.AllowEmpty && S.empty())
3472     return Error(ValueLoc, "'" + Name + "' cannot be empty");
3473
3474   Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3475   return false;
3476 }
3477
3478 template <>
3479 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3480   SmallVector<Metadata *, 4> MDs;
3481   if (ParseMDNodeVector(MDs))
3482     return true;
3483
3484   Result.assign(std::move(MDs));
3485   return false;
3486 }
3487
3488 } // end namespace llvm
3489
3490 template <class ParserTy>
3491 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3492   do {
3493     if (Lex.getKind() != lltok::LabelStr)
3494       return TokError("expected field label here");
3495
3496     if (parseField())
3497       return true;
3498   } while (EatIfPresent(lltok::comma));
3499
3500   return false;
3501 }
3502
3503 template <class ParserTy>
3504 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3505   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3506   Lex.Lex();
3507
3508   if (ParseToken(lltok::lparen, "expected '(' here"))
3509     return true;
3510   if (Lex.getKind() != lltok::rparen)
3511     if (ParseMDFieldsImplBody(parseField))
3512       return true;
3513
3514   ClosingLoc = Lex.getLoc();
3515   return ParseToken(lltok::rparen, "expected ')' here");
3516 }
3517
3518 template <class FieldTy>
3519 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3520   if (Result.Seen)
3521     return TokError("field '" + Name + "' cannot be specified more than once");
3522
3523   LocTy Loc = Lex.getLoc();
3524   Lex.Lex();
3525   return ParseMDField(Loc, Name, Result);
3526 }
3527
3528 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3529   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3530
3531 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
3532   if (Lex.getStrVal() == #CLASS)                                               \
3533     return Parse##CLASS(N, IsDistinct);
3534 #include "llvm/IR/Metadata.def"
3535
3536   return TokError("expected metadata type");
3537 }
3538
3539 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3540 #define NOP_FIELD(NAME, TYPE, INIT)
3541 #define REQUIRE_FIELD(NAME, TYPE, INIT)                                        \
3542   if (!NAME.Seen)                                                              \
3543     return Error(ClosingLoc, "missing required field '" #NAME "'");
3544 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT)                                    \
3545   if (Lex.getStrVal() == #NAME)                                                \
3546     return ParseMDField(#NAME, NAME);
3547 #define PARSE_MD_FIELDS()                                                      \
3548   VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD)                                \
3549   do {                                                                         \
3550     LocTy ClosingLoc;                                                          \
3551     if (ParseMDFieldsImpl([&]() -> bool {                                      \
3552       VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD)                          \
3553       return TokError(Twine("invalid field '") + Lex.getStrVal() + "'");       \
3554     }, ClosingLoc))                                                            \
3555       return true;                                                             \
3556     VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD)                                  \
3557   } while (false)
3558 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
3559   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3560
3561 /// ParseDILocationFields:
3562 ///   ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3563 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3564 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3565   OPTIONAL(line, LineField, );                                                 \
3566   OPTIONAL(column, ColumnField, );                                             \
3567   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3568   OPTIONAL(inlinedAt, MDField, );
3569   PARSE_MD_FIELDS();
3570 #undef VISIT_MD_FIELDS
3571
3572   Result = GET_OR_DISTINCT(
3573       DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3574   return false;
3575 }
3576
3577 /// ParseGenericDINode:
3578 ///   ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3579 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3580 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3581   REQUIRED(tag, DwarfTagField, );                                              \
3582   OPTIONAL(header, MDStringField, );                                           \
3583   OPTIONAL(operands, MDFieldList, );
3584   PARSE_MD_FIELDS();
3585 #undef VISIT_MD_FIELDS
3586
3587   Result = GET_OR_DISTINCT(GenericDINode,
3588                            (Context, tag.Val, header.Val, operands.Val));
3589   return false;
3590 }
3591
3592 /// ParseDISubrange:
3593 ///   ::= !DISubrange(count: 30, lowerBound: 2)
3594 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3595 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3596   REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX));                         \
3597   OPTIONAL(lowerBound, MDSignedField, );
3598   PARSE_MD_FIELDS();
3599 #undef VISIT_MD_FIELDS
3600
3601   Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3602   return false;
3603 }
3604
3605 /// ParseDIEnumerator:
3606 ///   ::= !DIEnumerator(value: 30, name: "SomeKind")
3607 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3608 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3609   REQUIRED(name, MDStringField, );                                             \
3610   REQUIRED(value, MDSignedField, );
3611   PARSE_MD_FIELDS();
3612 #undef VISIT_MD_FIELDS
3613
3614   Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3615   return false;
3616 }
3617
3618 /// ParseDIBasicType:
3619 ///   ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3620 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3621 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3622   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type));                     \
3623   OPTIONAL(name, MDStringField, );                                             \
3624   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3625   OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX));                           \
3626   OPTIONAL(encoding, DwarfAttEncodingField, );
3627   PARSE_MD_FIELDS();
3628 #undef VISIT_MD_FIELDS
3629
3630   Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3631                                          align.Val, encoding.Val));
3632   return false;
3633 }
3634
3635 /// ParseDIDerivedType:
3636 ///   ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3637 ///                      line: 7, scope: !1, baseType: !2, size: 32,
3638 ///                      align: 32, offset: 0, flags: 0, extraData: !3)
3639 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3640 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3641   REQUIRED(tag, DwarfTagField, );                                              \
3642   OPTIONAL(name, MDStringField, );                                             \
3643   OPTIONAL(file, MDField, );                                                   \
3644   OPTIONAL(line, LineField, );                                                 \
3645   OPTIONAL(scope, MDField, );                                                  \
3646   REQUIRED(baseType, MDField, );                                               \
3647   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3648   OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX));                           \
3649   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
3650   OPTIONAL(flags, DIFlagField, );                                              \
3651   OPTIONAL(extraData, MDField, );
3652   PARSE_MD_FIELDS();
3653 #undef VISIT_MD_FIELDS
3654
3655   Result = GET_OR_DISTINCT(DIDerivedType,
3656                            (Context, tag.Val, name.Val, file.Val, line.Val,
3657                             scope.Val, baseType.Val, size.Val, align.Val,
3658                             offset.Val, flags.Val, extraData.Val));
3659   return false;
3660 }
3661
3662 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3663 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3664   REQUIRED(tag, DwarfTagField, );                                              \
3665   OPTIONAL(name, MDStringField, );                                             \
3666   OPTIONAL(file, MDField, );                                                   \
3667   OPTIONAL(line, LineField, );                                                 \
3668   OPTIONAL(scope, MDField, );                                                  \
3669   OPTIONAL(baseType, MDField, );                                               \
3670   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3671   OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX));                           \
3672   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
3673   OPTIONAL(flags, DIFlagField, );                                              \
3674   OPTIONAL(elements, MDField, );                                               \
3675   OPTIONAL(runtimeLang, DwarfLangField, );                                     \
3676   OPTIONAL(vtableHolder, MDField, );                                           \
3677   OPTIONAL(templateParams, MDField, );                                         \
3678   OPTIONAL(identifier, MDStringField, );
3679   PARSE_MD_FIELDS();
3680 #undef VISIT_MD_FIELDS
3681
3682   Result = GET_OR_DISTINCT(
3683       DICompositeType,
3684       (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3685        size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3686        runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3687   return false;
3688 }
3689
3690 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
3691 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3692   OPTIONAL(flags, DIFlagField, );                                              \
3693   REQUIRED(types, MDField, );
3694   PARSE_MD_FIELDS();
3695 #undef VISIT_MD_FIELDS
3696
3697   Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
3698   return false;
3699 }
3700
3701 /// ParseDIFileType:
3702 ///   ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3703 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
3704 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3705   REQUIRED(filename, MDStringField, );                                         \
3706   REQUIRED(directory, MDStringField, );
3707   PARSE_MD_FIELDS();
3708 #undef VISIT_MD_FIELDS
3709
3710   Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
3711   return false;
3712 }
3713
3714 /// ParseDICompileUnit:
3715 ///   ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3716 ///                      isOptimized: true, flags: "-O2", runtimeVersion: 1,
3717 ///                      splitDebugFilename: "abc.debug", emissionKind: 1,
3718 ///                      enums: !1, retainedTypes: !2, subprograms: !3,
3719 ///                      globals: !4, imports: !5, dwoId: 0x0abcd)
3720 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
3721   if (!IsDistinct)
3722     return Lex.Error("missing 'distinct', required for !DICompileUnit");
3723
3724 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3725   REQUIRED(language, DwarfLangField, );                                        \
3726   REQUIRED(file, MDField, (/* AllowNull */ false));                            \
3727   OPTIONAL(producer, MDStringField, );                                         \
3728   OPTIONAL(isOptimized, MDBoolField, );                                        \
3729   OPTIONAL(flags, MDStringField, );                                            \
3730   OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX));                  \
3731   OPTIONAL(splitDebugFilename, MDStringField, );                               \
3732   OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX));                    \
3733   OPTIONAL(enums, MDField, );                                                  \
3734   OPTIONAL(retainedTypes, MDField, );                                          \
3735   OPTIONAL(subprograms, MDField, );                                            \
3736   OPTIONAL(globals, MDField, );                                                \
3737   OPTIONAL(imports, MDField, );                                                \
3738   OPTIONAL(dwoId, MDUnsignedField, );
3739   PARSE_MD_FIELDS();
3740 #undef VISIT_MD_FIELDS
3741
3742   Result = DICompileUnit::getDistinct(
3743       Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3744       runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
3745       retainedTypes.Val, subprograms.Val, globals.Val, imports.Val, dwoId.Val);
3746   return false;
3747 }
3748
3749 /// ParseDISubprogram:
3750 ///   ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3751 ///                     file: !1, line: 7, type: !2, isLocal: false,
3752 ///                     isDefinition: true, scopeLine: 8, containingType: !3,
3753 ///                     virtuality: DW_VIRTUALTIY_pure_virtual,
3754 ///                     virtualIndex: 10, flags: 11,
3755 ///                     isOptimized: false, function: void ()* @_Z3foov,
3756 ///                     templateParams: !4, declaration: !5, variables: !6)
3757 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
3758   auto Loc = Lex.getLoc();
3759 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3760   OPTIONAL(scope, MDField, );                                                  \
3761   OPTIONAL(name, MDStringField, );                                             \
3762   OPTIONAL(linkageName, MDStringField, );                                      \
3763   OPTIONAL(file, MDField, );                                                   \
3764   OPTIONAL(line, LineField, );                                                 \
3765   OPTIONAL(type, MDField, );                                                   \
3766   OPTIONAL(isLocal, MDBoolField, );                                            \
3767   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
3768   OPTIONAL(scopeLine, LineField, );                                            \
3769   OPTIONAL(containingType, MDField, );                                         \
3770   OPTIONAL(virtuality, DwarfVirtualityField, );                                \
3771   OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX));                    \
3772   OPTIONAL(flags, DIFlagField, );                                              \
3773   OPTIONAL(isOptimized, MDBoolField, );                                        \
3774   OPTIONAL(function, MDConstant, );                                            \
3775   OPTIONAL(templateParams, MDField, );                                         \
3776   OPTIONAL(declaration, MDField, );                                            \
3777   OPTIONAL(variables, MDField, );
3778   PARSE_MD_FIELDS();
3779 #undef VISIT_MD_FIELDS
3780
3781   if (isDefinition.Val && !IsDistinct)
3782     return Lex.Error(
3783         Loc,
3784         "missing 'distinct', required for !DISubprogram when 'isDefinition'");
3785
3786   Result = GET_OR_DISTINCT(
3787       DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3788                      line.Val, type.Val, isLocal.Val, isDefinition.Val,
3789                      scopeLine.Val, containingType.Val, virtuality.Val,
3790                      virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3791                      templateParams.Val, declaration.Val, variables.Val));
3792   return false;
3793 }
3794
3795 /// ParseDILexicalBlock:
3796 ///   ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3797 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
3798 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3799   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3800   OPTIONAL(file, MDField, );                                                   \
3801   OPTIONAL(line, LineField, );                                                 \
3802   OPTIONAL(column, ColumnField, );
3803   PARSE_MD_FIELDS();
3804 #undef VISIT_MD_FIELDS
3805
3806   Result = GET_OR_DISTINCT(
3807       DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3808   return false;
3809 }
3810
3811 /// ParseDILexicalBlockFile:
3812 ///   ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3813 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
3814 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3815   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3816   OPTIONAL(file, MDField, );                                                   \
3817   REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3818   PARSE_MD_FIELDS();
3819 #undef VISIT_MD_FIELDS
3820
3821   Result = GET_OR_DISTINCT(DILexicalBlockFile,
3822                            (Context, scope.Val, file.Val, discriminator.Val));
3823   return false;
3824 }
3825
3826 /// ParseDINamespace:
3827 ///   ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3828 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
3829 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3830   REQUIRED(scope, MDField, );                                                  \
3831   OPTIONAL(file, MDField, );                                                   \
3832   OPTIONAL(name, MDStringField, );                                             \
3833   OPTIONAL(line, LineField, );
3834   PARSE_MD_FIELDS();
3835 #undef VISIT_MD_FIELDS
3836
3837   Result = GET_OR_DISTINCT(DINamespace,
3838                            (Context, scope.Val, file.Val, name.Val, line.Val));
3839   return false;
3840 }
3841
3842 /// ParseDIModule:
3843 ///   ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
3844 ///                 includePath: "/usr/include", isysroot: "/")
3845 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
3846 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3847   REQUIRED(scope, MDField, );                                                  \
3848   REQUIRED(name, MDStringField, );                                             \
3849   OPTIONAL(configMacros, MDStringField, );                                     \
3850   OPTIONAL(includePath, MDStringField, );                                      \
3851   OPTIONAL(isysroot, MDStringField, );
3852   PARSE_MD_FIELDS();
3853 #undef VISIT_MD_FIELDS
3854
3855   Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
3856                            configMacros.Val, includePath.Val, isysroot.Val));
3857   return false;
3858 }
3859
3860 /// ParseDITemplateTypeParameter:
3861 ///   ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3862 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
3863 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3864   OPTIONAL(name, MDStringField, );                                             \
3865   REQUIRED(type, MDField, );
3866   PARSE_MD_FIELDS();
3867 #undef VISIT_MD_FIELDS
3868
3869   Result =
3870       GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
3871   return false;
3872 }
3873
3874 /// ParseDITemplateValueParameter:
3875 ///   ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
3876 ///                                 name: "V", type: !1, value: i32 7)
3877 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
3878 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3879   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter));      \
3880   OPTIONAL(name, MDStringField, );                                             \
3881   OPTIONAL(type, MDField, );                                                   \
3882   REQUIRED(value, MDField, );
3883   PARSE_MD_FIELDS();
3884 #undef VISIT_MD_FIELDS
3885
3886   Result = GET_OR_DISTINCT(DITemplateValueParameter,
3887                            (Context, tag.Val, name.Val, type.Val, value.Val));
3888   return false;
3889 }
3890
3891 /// ParseDIGlobalVariable:
3892 ///   ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3893 ///                         file: !1, line: 7, type: !2, isLocal: false,
3894 ///                         isDefinition: true, variable: i32* @foo,
3895 ///                         declaration: !3)
3896 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
3897 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3898   REQUIRED(name, MDStringField, (/* AllowEmpty */ false));                     \
3899   OPTIONAL(scope, MDField, );                                                  \
3900   OPTIONAL(linkageName, MDStringField, );                                      \
3901   OPTIONAL(file, MDField, );                                                   \
3902   OPTIONAL(line, LineField, );                                                 \
3903   OPTIONAL(type, MDField, );                                                   \
3904   OPTIONAL(isLocal, MDBoolField, );                                            \
3905   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
3906   OPTIONAL(variable, MDConstant, );                                            \
3907   OPTIONAL(declaration, MDField, );
3908   PARSE_MD_FIELDS();
3909 #undef VISIT_MD_FIELDS
3910
3911   Result = GET_OR_DISTINCT(DIGlobalVariable,
3912                            (Context, scope.Val, name.Val, linkageName.Val,
3913                             file.Val, line.Val, type.Val, isLocal.Val,
3914                             isDefinition.Val, variable.Val, declaration.Val));
3915   return false;
3916 }
3917
3918 /// ParseDILocalVariable:
3919 ///   ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
3920 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7)
3921 ///   ::= !DILocalVariable(scope: !0, name: "foo",
3922 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7)
3923 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
3924 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3925   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3926   OPTIONAL(name, MDStringField, );                                             \
3927   OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX));                             \
3928   OPTIONAL(file, MDField, );                                                   \
3929   OPTIONAL(line, LineField, );                                                 \
3930   OPTIONAL(type, MDField, );                                                   \
3931   OPTIONAL(flags, DIFlagField, );
3932   PARSE_MD_FIELDS();
3933 #undef VISIT_MD_FIELDS
3934
3935   Result = GET_OR_DISTINCT(DILocalVariable,
3936                            (Context, scope.Val, name.Val, file.Val, line.Val,
3937                             type.Val, arg.Val, flags.Val));
3938   return false;
3939 }
3940
3941 /// ParseDIExpression:
3942 ///   ::= !DIExpression(0, 7, -1)
3943 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
3944   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3945   Lex.Lex();
3946
3947   if (ParseToken(lltok::lparen, "expected '(' here"))
3948     return true;
3949
3950   SmallVector<uint64_t, 8> Elements;
3951   if (Lex.getKind() != lltok::rparen)
3952     do {
3953       if (Lex.getKind() == lltok::DwarfOp) {
3954         if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3955           Lex.Lex();
3956           Elements.push_back(Op);
3957           continue;
3958         }
3959         return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3960       }
3961
3962       if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3963         return TokError("expected unsigned integer");
3964
3965       auto &U = Lex.getAPSIntVal();
3966       if (U.ugt(UINT64_MAX))
3967         return TokError("element too large, limit is " + Twine(UINT64_MAX));
3968       Elements.push_back(U.getZExtValue());
3969       Lex.Lex();
3970     } while (EatIfPresent(lltok::comma));
3971
3972   if (ParseToken(lltok::rparen, "expected ')' here"))
3973     return true;
3974
3975   Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
3976   return false;
3977 }
3978
3979 /// ParseDIObjCProperty:
3980 ///   ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3981 ///                       getter: "getFoo", attributes: 7, type: !2)
3982 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
3983 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3984   OPTIONAL(name, MDStringField, );                                             \
3985   OPTIONAL(file, MDField, );                                                   \
3986   OPTIONAL(line, LineField, );                                                 \
3987   OPTIONAL(setter, MDStringField, );                                           \
3988   OPTIONAL(getter, MDStringField, );                                           \
3989   OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX));                      \
3990   OPTIONAL(type, MDField, );
3991   PARSE_MD_FIELDS();
3992 #undef VISIT_MD_FIELDS
3993
3994   Result = GET_OR_DISTINCT(DIObjCProperty,
3995                            (Context, name.Val, file.Val, line.Val, setter.Val,
3996                             getter.Val, attributes.Val, type.Val));
3997   return false;
3998 }
3999
4000 /// ParseDIImportedEntity:
4001 ///   ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4002 ///                         line: 7, name: "foo")
4003 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
4004 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4005   REQUIRED(tag, DwarfTagField, );                                              \
4006   REQUIRED(scope, MDField, );                                                  \
4007   OPTIONAL(entity, MDField, );                                                 \
4008   OPTIONAL(line, LineField, );                                                 \
4009   OPTIONAL(name, MDStringField, );
4010   PARSE_MD_FIELDS();
4011 #undef VISIT_MD_FIELDS
4012
4013   Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
4014                                               entity.Val, line.Val, name.Val));
4015   return false;
4016 }
4017
4018 #undef PARSE_MD_FIELD
4019 #undef NOP_FIELD
4020 #undef REQUIRE_FIELD
4021 #undef DECLARE_FIELD
4022
4023 /// ParseMetadataAsValue
4024 ///  ::= metadata i32 %local
4025 ///  ::= metadata i32 @global
4026 ///  ::= metadata i32 7
4027 ///  ::= metadata !0
4028 ///  ::= metadata !{...}
4029 ///  ::= metadata !"string"
4030 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4031   // Note: the type 'metadata' has already been parsed.
4032   Metadata *MD;
4033   if (ParseMetadata(MD, &PFS))
4034     return true;
4035
4036   V = MetadataAsValue::get(Context, MD);
4037   return false;
4038 }
4039
4040 /// ParseValueAsMetadata
4041 ///  ::= i32 %local
4042 ///  ::= i32 @global
4043 ///  ::= i32 7
4044 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4045                                     PerFunctionState *PFS) {
4046   Type *Ty;
4047   LocTy Loc;
4048   if (ParseType(Ty, TypeMsg, Loc))
4049     return true;
4050   if (Ty->isMetadataTy())
4051     return Error(Loc, "invalid metadata-value-metadata roundtrip");
4052
4053   Value *V;
4054   if (ParseValue(Ty, V, PFS))
4055     return true;
4056
4057   MD = ValueAsMetadata::get(V);
4058   return false;
4059 }
4060
4061 /// ParseMetadata
4062 ///  ::= i32 %local
4063 ///  ::= i32 @global
4064 ///  ::= i32 7
4065 ///  ::= !42
4066 ///  ::= !{...}
4067 ///  ::= !"string"
4068 ///  ::= !DILocation(...)
4069 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
4070   if (Lex.getKind() == lltok::MetadataVar) {
4071     MDNode *N;
4072     if (ParseSpecializedMDNode(N))
4073       return true;
4074     MD = N;
4075     return false;
4076   }
4077
4078   // ValueAsMetadata:
4079   // <type> <value>
4080   if (Lex.getKind() != lltok::exclaim)
4081     return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
4082
4083   // '!'.
4084   assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4085   Lex.Lex();
4086
4087   // MDString:
4088   //   ::= '!' STRINGCONSTANT
4089   if (Lex.getKind() == lltok::StringConstant) {
4090     MDString *S;
4091     if (ParseMDString(S))
4092       return true;
4093     MD = S;
4094     return false;
4095   }
4096
4097   // MDNode:
4098   // !{ ... }
4099   // !7
4100   MDNode *N;
4101   if (ParseMDNodeTail(N))
4102     return true;
4103   MD = N;
4104   return false;
4105 }
4106
4107
4108 //===----------------------------------------------------------------------===//
4109 // Function Parsing.
4110 //===----------------------------------------------------------------------===//
4111
4112 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
4113                                    PerFunctionState *PFS,
4114                                    OperatorConstraint OC) {
4115   if (Ty->isFunctionTy())
4116     return Error(ID.Loc, "functions are not values, refer to them as pointers");
4117
4118   if (OC && ID.Kind != ValID::t_LocalID && ID.Kind != ValID::t_LocalName) {
4119     switch (OC) {
4120     case OC_CatchPad:
4121       return Error(ID.Loc, "Catchpad value required in this position");
4122     case OC_CleanupPad:
4123       return Error(ID.Loc, "Cleanuppad value required in this position");
4124     default:
4125       llvm_unreachable("Unexpected constraint kind");
4126     }
4127   }
4128
4129   switch (ID.Kind) {
4130   case ValID::t_LocalID:
4131     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4132     V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, OC);
4133     return V == nullptr;
4134   case ValID::t_LocalName:
4135     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4136     V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, OC);
4137     return V == nullptr;
4138   case ValID::t_InlineAsm: {
4139     if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
4140       return Error(ID.Loc, "invalid type for inline asm constraint string");
4141     V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4142                        (ID.UIntVal >> 1) & 1,
4143                        (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
4144     return false;
4145   }
4146   case ValID::t_GlobalName:
4147     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
4148     return V == nullptr;
4149   case ValID::t_GlobalID:
4150     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
4151     return V == nullptr;
4152   case ValID::t_APSInt:
4153     if (!Ty->isIntegerTy())
4154       return Error(ID.Loc, "integer constant must have integer type");
4155     ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
4156     V = ConstantInt::get(Context, ID.APSIntVal);
4157     return false;
4158   case ValID::t_APFloat:
4159     if (!Ty->isFloatingPointTy() ||
4160         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4161       return Error(ID.Loc, "floating point constant invalid for type");
4162
4163     // The lexer has no type info, so builds all half, float, and double FP
4164     // constants as double.  Fix this here.  Long double does not need this.
4165     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
4166       bool Ignored;
4167       if (Ty->isHalfTy())
4168         ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4169                               &Ignored);
4170       else if (Ty->isFloatTy())
4171         ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4172                               &Ignored);
4173     }
4174     V = ConstantFP::get(Context, ID.APFloatVal);
4175
4176     if (V->getType() != Ty)
4177       return Error(ID.Loc, "floating point constant does not have type '" +
4178                    getTypeString(Ty) + "'");
4179
4180     return false;
4181   case ValID::t_Null:
4182     if (!Ty->isPointerTy())
4183       return Error(ID.Loc, "null must be a pointer type");
4184     V = ConstantPointerNull::get(cast<PointerType>(Ty));
4185     return false;
4186   case ValID::t_Undef:
4187     // FIXME: LabelTy should not be a first-class type.
4188     if (!Ty->isFirstClassType() || Ty->isLabelTy())
4189       return Error(ID.Loc, "invalid type for undef constant");
4190     V = UndefValue::get(Ty);
4191     return false;
4192   case ValID::t_EmptyArray:
4193     if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4194       return Error(ID.Loc, "invalid empty array initializer");
4195     V = UndefValue::get(Ty);
4196     return false;
4197   case ValID::t_Zero:
4198     // FIXME: LabelTy should not be a first-class type.
4199     if (!Ty->isFirstClassType() || Ty->isLabelTy())
4200       return Error(ID.Loc, "invalid type for null constant");
4201     V = Constant::getNullValue(Ty);
4202     return false;
4203   case ValID::t_Constant:
4204     if (ID.ConstantVal->getType() != Ty)
4205       return Error(ID.Loc, "constant expression type mismatch");
4206
4207     V = ID.ConstantVal;
4208     return false;
4209   case ValID::t_ConstantStruct:
4210   case ValID::t_PackedConstantStruct:
4211     if (StructType *ST = dyn_cast<StructType>(Ty)) {
4212       if (ST->getNumElements() != ID.UIntVal)
4213         return Error(ID.Loc,
4214                      "initializer with struct type has wrong # elements");
4215       if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4216         return Error(ID.Loc, "packed'ness of initializer and type don't match");
4217
4218       // Verify that the elements are compatible with the structtype.
4219       for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4220         if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4221           return Error(ID.Loc, "element " + Twine(i) +
4222                     " of struct initializer doesn't match struct element type");
4223
4224       V = ConstantStruct::get(
4225           ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
4226     } else
4227       return Error(ID.Loc, "constant expression type mismatch");
4228     return false;
4229   }
4230   llvm_unreachable("Invalid ValID");
4231 }
4232
4233 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4234   C = nullptr;
4235   ValID ID;
4236   auto Loc = Lex.getLoc();
4237   if (ParseValID(ID, /*PFS=*/nullptr))
4238     return true;
4239   switch (ID.Kind) {
4240   case ValID::t_APSInt:
4241   case ValID::t_APFloat:
4242   case ValID::t_Undef:
4243   case ValID::t_Constant:
4244   case ValID::t_ConstantStruct:
4245   case ValID::t_PackedConstantStruct: {
4246     Value *V;
4247     if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4248       return true;
4249     assert(isa<Constant>(V) && "Expected a constant value");
4250     C = cast<Constant>(V);
4251     return false;
4252   }
4253   default:
4254     return Error(Loc, "expected a constant value");
4255   }
4256 }
4257
4258 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS,
4259                           OperatorConstraint OC) {
4260   V = nullptr;
4261   ValID ID;
4262   return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS, OC);
4263 }
4264
4265 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4266   Type *Ty = nullptr;
4267   return ParseType(Ty) ||
4268          ParseValue(Ty, V, PFS);
4269 }
4270
4271 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4272                                       PerFunctionState &PFS) {
4273   Value *V;
4274   Loc = Lex.getLoc();
4275   if (ParseTypeAndValue(V, PFS)) return true;
4276   if (!isa<BasicBlock>(V))
4277     return Error(Loc, "expected a basic block");
4278   BB = cast<BasicBlock>(V);
4279   return false;
4280 }
4281
4282
4283 /// FunctionHeader
4284 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4285 ///       OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4286 ///       OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
4287 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4288   // Parse the linkage.
4289   LocTy LinkageLoc = Lex.getLoc();
4290   unsigned Linkage;
4291
4292   unsigned Visibility;
4293   unsigned DLLStorageClass;
4294   AttrBuilder RetAttrs;
4295   unsigned CC;
4296   Type *RetType = nullptr;
4297   LocTy RetTypeLoc = Lex.getLoc();
4298   if (ParseOptionalLinkage(Linkage) ||
4299       ParseOptionalVisibility(Visibility) ||
4300       ParseOptionalDLLStorageClass(DLLStorageClass) ||
4301       ParseOptionalCallingConv(CC) ||
4302       ParseOptionalReturnAttrs(RetAttrs) ||
4303       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4304     return true;
4305
4306   // Verify that the linkage is ok.
4307   switch ((GlobalValue::LinkageTypes)Linkage) {
4308   case GlobalValue::ExternalLinkage:
4309     break; // always ok.
4310   case GlobalValue::ExternalWeakLinkage:
4311     if (isDefine)
4312       return Error(LinkageLoc, "invalid linkage for function definition");
4313     break;
4314   case GlobalValue::PrivateLinkage:
4315   case GlobalValue::InternalLinkage:
4316   case GlobalValue::AvailableExternallyLinkage:
4317   case GlobalValue::LinkOnceAnyLinkage:
4318   case GlobalValue::LinkOnceODRLinkage:
4319   case GlobalValue::WeakAnyLinkage:
4320   case GlobalValue::WeakODRLinkage:
4321     if (!isDefine)
4322       return Error(LinkageLoc, "invalid linkage for function declaration");
4323     break;
4324   case GlobalValue::AppendingLinkage:
4325   case GlobalValue::CommonLinkage:
4326     return Error(LinkageLoc, "invalid function linkage type");
4327   }
4328
4329   if (!isValidVisibilityForLinkage(Visibility, Linkage))
4330     return Error(LinkageLoc,
4331                  "symbol with local linkage must have default visibility");
4332
4333   if (!FunctionType::isValidReturnType(RetType))
4334     return Error(RetTypeLoc, "invalid function return type");
4335
4336   LocTy NameLoc = Lex.getLoc();
4337
4338   std::string FunctionName;
4339   if (Lex.getKind() == lltok::GlobalVar) {
4340     FunctionName = Lex.getStrVal();
4341   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
4342     unsigned NameID = Lex.getUIntVal();
4343
4344     if (NameID != NumberedVals.size())
4345       return TokError("function expected to be numbered '%" +
4346                       Twine(NumberedVals.size()) + "'");
4347   } else {
4348     return TokError("expected function name");
4349   }
4350
4351   Lex.Lex();
4352
4353   if (Lex.getKind() != lltok::lparen)
4354     return TokError("expected '(' in function argument list");
4355
4356   SmallVector<ArgInfo, 8> ArgList;
4357   bool isVarArg;
4358   AttrBuilder FuncAttrs;
4359   std::vector<unsigned> FwdRefAttrGrps;
4360   LocTy BuiltinLoc;
4361   std::string Section;
4362   unsigned Alignment;
4363   std::string GC;
4364   bool UnnamedAddr;
4365   LocTy UnnamedAddrLoc;
4366   Constant *Prefix = nullptr;
4367   Constant *Prologue = nullptr;
4368   Constant *PersonalityFn = nullptr;
4369   Comdat *C;
4370
4371   if (ParseArgumentList(ArgList, isVarArg) ||
4372       ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4373                          &UnnamedAddrLoc) ||
4374       ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4375                                  BuiltinLoc) ||
4376       (EatIfPresent(lltok::kw_section) &&
4377        ParseStringConstant(Section)) ||
4378       parseOptionalComdat(FunctionName, C) ||
4379       ParseOptionalAlignment(Alignment) ||
4380       (EatIfPresent(lltok::kw_gc) &&
4381        ParseStringConstant(GC)) ||
4382       (EatIfPresent(lltok::kw_prefix) &&
4383        ParseGlobalTypeAndValue(Prefix)) ||
4384       (EatIfPresent(lltok::kw_prologue) &&
4385        ParseGlobalTypeAndValue(Prologue)) ||
4386       (EatIfPresent(lltok::kw_personality) &&
4387        ParseGlobalTypeAndValue(PersonalityFn)))
4388     return true;
4389
4390   if (FuncAttrs.contains(Attribute::Builtin))
4391     return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4392
4393   // If the alignment was parsed as an attribute, move to the alignment field.
4394   if (FuncAttrs.hasAlignmentAttr()) {
4395     Alignment = FuncAttrs.getAlignment();
4396     FuncAttrs.removeAttribute(Attribute::Alignment);
4397   }
4398
4399   // Okay, if we got here, the function is syntactically valid.  Convert types
4400   // and do semantic checks.
4401   std::vector<Type*> ParamTypeList;
4402   SmallVector<AttributeSet, 8> Attrs;
4403
4404   if (RetAttrs.hasAttributes())
4405     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4406                                       AttributeSet::ReturnIndex,
4407                                       RetAttrs));
4408
4409   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4410     ParamTypeList.push_back(ArgList[i].Ty);
4411     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4412       AttrBuilder B(ArgList[i].Attrs, i + 1);
4413       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4414     }
4415   }
4416
4417   if (FuncAttrs.hasAttributes())
4418     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4419                                       AttributeSet::FunctionIndex,
4420                                       FuncAttrs));
4421
4422   AttributeSet PAL = AttributeSet::get(Context, Attrs);
4423
4424   if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4425     return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4426
4427   FunctionType *FT =
4428     FunctionType::get(RetType, ParamTypeList, isVarArg);
4429   PointerType *PFT = PointerType::getUnqual(FT);
4430
4431   Fn = nullptr;
4432   if (!FunctionName.empty()) {
4433     // If this was a definition of a forward reference, remove the definition
4434     // from the forward reference table and fill in the forward ref.
4435     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4436       ForwardRefVals.find(FunctionName);
4437     if (FRVI != ForwardRefVals.end()) {
4438       Fn = M->getFunction(FunctionName);
4439       if (!Fn)
4440         return Error(FRVI->second.second, "invalid forward reference to "
4441                      "function as global value!");
4442       if (Fn->getType() != PFT)
4443         return Error(FRVI->second.second, "invalid forward reference to "
4444                      "function '" + FunctionName + "' with wrong type!");
4445
4446       ForwardRefVals.erase(FRVI);
4447     } else if ((Fn = M->getFunction(FunctionName))) {
4448       // Reject redefinitions.
4449       return Error(NameLoc, "invalid redefinition of function '" +
4450                    FunctionName + "'");
4451     } else if (M->getNamedValue(FunctionName)) {
4452       return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4453     }
4454
4455   } else {
4456     // If this is a definition of a forward referenced function, make sure the
4457     // types agree.
4458     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4459       = ForwardRefValIDs.find(NumberedVals.size());
4460     if (I != ForwardRefValIDs.end()) {
4461       Fn = cast<Function>(I->second.first);
4462       if (Fn->getType() != PFT)
4463         return Error(NameLoc, "type of definition and forward reference of '@" +
4464                      Twine(NumberedVals.size()) + "' disagree");
4465       ForwardRefValIDs.erase(I);
4466     }
4467   }
4468
4469   if (!Fn)
4470     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4471   else // Move the forward-reference to the correct spot in the module.
4472     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4473
4474   if (FunctionName.empty())
4475     NumberedVals.push_back(Fn);
4476
4477   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4478   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4479   Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4480   Fn->setCallingConv(CC);
4481   Fn->setAttributes(PAL);
4482   Fn->setUnnamedAddr(UnnamedAddr);
4483   Fn->setAlignment(Alignment);
4484   Fn->setSection(Section);
4485   Fn->setComdat(C);
4486   Fn->setPersonalityFn(PersonalityFn);
4487   if (!GC.empty()) Fn->setGC(GC.c_str());
4488   Fn->setPrefixData(Prefix);
4489   Fn->setPrologueData(Prologue);
4490   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4491
4492   // Add all of the arguments we parsed to the function.
4493   Function::arg_iterator ArgIt = Fn->arg_begin();
4494   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4495     // If the argument has a name, insert it into the argument symbol table.
4496     if (ArgList[i].Name.empty()) continue;
4497
4498     // Set the name, if it conflicted, it will be auto-renamed.
4499     ArgIt->setName(ArgList[i].Name);
4500
4501     if (ArgIt->getName() != ArgList[i].Name)
4502       return Error(ArgList[i].Loc, "redefinition of argument '%" +
4503                    ArgList[i].Name + "'");
4504   }
4505
4506   if (isDefine)
4507     return false;
4508
4509   // Check the declaration has no block address forward references.
4510   ValID ID;
4511   if (FunctionName.empty()) {
4512     ID.Kind = ValID::t_GlobalID;
4513     ID.UIntVal = NumberedVals.size() - 1;
4514   } else {
4515     ID.Kind = ValID::t_GlobalName;
4516     ID.StrVal = FunctionName;
4517   }
4518   auto Blocks = ForwardRefBlockAddresses.find(ID);
4519   if (Blocks != ForwardRefBlockAddresses.end())
4520     return Error(Blocks->first.Loc,
4521                  "cannot take blockaddress inside a declaration");
4522   return false;
4523 }
4524
4525 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4526   ValID ID;
4527   if (FunctionNumber == -1) {
4528     ID.Kind = ValID::t_GlobalName;
4529     ID.StrVal = F.getName();
4530   } else {
4531     ID.Kind = ValID::t_GlobalID;
4532     ID.UIntVal = FunctionNumber;
4533   }
4534
4535   auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4536   if (Blocks == P.ForwardRefBlockAddresses.end())
4537     return false;
4538
4539   for (const auto &I : Blocks->second) {
4540     const ValID &BBID = I.first;
4541     GlobalValue *GV = I.second;
4542
4543     assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4544            "Expected local id or name");
4545     BasicBlock *BB;
4546     if (BBID.Kind == ValID::t_LocalName)
4547       BB = GetBB(BBID.StrVal, BBID.Loc);
4548     else
4549       BB = GetBB(BBID.UIntVal, BBID.Loc);
4550     if (!BB)
4551       return P.Error(BBID.Loc, "referenced value is not a basic block");
4552
4553     GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4554     GV->eraseFromParent();
4555   }
4556
4557   P.ForwardRefBlockAddresses.erase(Blocks);
4558   return false;
4559 }
4560
4561 /// ParseFunctionBody
4562 ///   ::= '{' BasicBlock+ UseListOrderDirective* '}'
4563 bool LLParser::ParseFunctionBody(Function &Fn) {
4564   if (Lex.getKind() != lltok::lbrace)
4565     return TokError("expected '{' in function body");
4566   Lex.Lex();  // eat the {.
4567
4568   int FunctionNumber = -1;
4569   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4570
4571   PerFunctionState PFS(*this, Fn, FunctionNumber);
4572
4573   // Resolve block addresses and allow basic blocks to be forward-declared
4574   // within this function.
4575   if (PFS.resolveForwardRefBlockAddresses())
4576     return true;
4577   SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4578
4579   // We need at least one basic block.
4580   if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4581     return TokError("function body requires at least one basic block");
4582
4583   while (Lex.getKind() != lltok::rbrace &&
4584          Lex.getKind() != lltok::kw_uselistorder)
4585     if (ParseBasicBlock(PFS)) return true;
4586
4587   while (Lex.getKind() != lltok::rbrace)
4588     if (ParseUseListOrder(&PFS))
4589       return true;
4590
4591   // Eat the }.
4592   Lex.Lex();
4593
4594   // Verify function is ok.
4595   return PFS.FinishFunction();
4596 }
4597
4598 /// ParseBasicBlock
4599 ///   ::= LabelStr? Instruction*
4600 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4601   // If this basic block starts out with a name, remember it.
4602   std::string Name;
4603   LocTy NameLoc = Lex.getLoc();
4604   if (Lex.getKind() == lltok::LabelStr) {
4605     Name = Lex.getStrVal();
4606     Lex.Lex();
4607   }
4608
4609   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4610   if (!BB)
4611     return Error(NameLoc,
4612                  "unable to create block named '" + Name + "'");
4613
4614   std::string NameStr;
4615
4616   // Parse the instructions in this block until we get a terminator.
4617   Instruction *Inst;
4618   do {
4619     // This instruction may have three possibilities for a name: a) none
4620     // specified, b) name specified "%foo =", c) number specified: "%4 =".
4621     LocTy NameLoc = Lex.getLoc();
4622     int NameID = -1;
4623     NameStr = "";
4624
4625     if (Lex.getKind() == lltok::LocalVarID) {
4626       NameID = Lex.getUIntVal();
4627       Lex.Lex();
4628       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4629         return true;
4630     } else if (Lex.getKind() == lltok::LocalVar) {
4631       NameStr = Lex.getStrVal();
4632       Lex.Lex();
4633       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4634         return true;
4635     }
4636
4637     switch (ParseInstruction(Inst, BB, PFS)) {
4638     default: llvm_unreachable("Unknown ParseInstruction result!");
4639     case InstError: return true;
4640     case InstNormal:
4641       BB->getInstList().push_back(Inst);
4642
4643       // With a normal result, we check to see if the instruction is followed by
4644       // a comma and metadata.
4645       if (EatIfPresent(lltok::comma))
4646         if (ParseInstructionMetadata(*Inst))
4647           return true;
4648       break;
4649     case InstExtraComma:
4650       BB->getInstList().push_back(Inst);
4651
4652       // If the instruction parser ate an extra comma at the end of it, it
4653       // *must* be followed by metadata.
4654       if (ParseInstructionMetadata(*Inst))
4655         return true;
4656       break;
4657     }
4658
4659     // Set the name on the instruction.
4660     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4661   } while (!isa<TerminatorInst>(Inst));
4662
4663   return false;
4664 }
4665
4666 //===----------------------------------------------------------------------===//
4667 // Instruction Parsing.
4668 //===----------------------------------------------------------------------===//
4669
4670 /// ParseInstruction - Parse one of the many different instructions.
4671 ///
4672 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4673                                PerFunctionState &PFS) {
4674   lltok::Kind Token = Lex.getKind();
4675   if (Token == lltok::Eof)
4676     return TokError("found end of file when expecting more instructions");
4677   LocTy Loc = Lex.getLoc();
4678   unsigned KeywordVal = Lex.getUIntVal();
4679   Lex.Lex();  // Eat the keyword.
4680
4681   switch (Token) {
4682   default:                    return Error(Loc, "expected instruction opcode");
4683   // Terminator Instructions.
4684   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4685   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
4686   case lltok::kw_br:          return ParseBr(Inst, PFS);
4687   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
4688   case lltok::kw_indirectbr:  return ParseIndirectBr(Inst, PFS);
4689   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
4690   case lltok::kw_resume:      return ParseResume(Inst, PFS);
4691   case lltok::kw_cleanupret:  return ParseCleanupRet(Inst, PFS);
4692   case lltok::kw_catchret:    return ParseCatchRet(Inst, PFS);
4693   case lltok::kw_catchpad:  return ParseCatchPad(Inst, PFS);
4694   case lltok::kw_terminatepad: return ParseTerminatePad(Inst, PFS);
4695   case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
4696   case lltok::kw_catchendpad: return ParseCatchEndPad(Inst, PFS);
4697   case lltok::kw_cleanupendpad: return ParseCleanupEndPad(Inst, PFS);
4698   // Binary Operators.
4699   case lltok::kw_add:
4700   case lltok::kw_sub:
4701   case lltok::kw_mul:
4702   case lltok::kw_shl: {
4703     bool NUW = EatIfPresent(lltok::kw_nuw);
4704     bool NSW = EatIfPresent(lltok::kw_nsw);
4705     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4706
4707     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4708
4709     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4710     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4711     return false;
4712   }
4713   case lltok::kw_fadd:
4714   case lltok::kw_fsub:
4715   case lltok::kw_fmul:
4716   case lltok::kw_fdiv:
4717   case lltok::kw_frem: {
4718     FastMathFlags FMF = EatFastMathFlagsIfPresent();
4719     int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4720     if (Res != 0)
4721       return Res;
4722     if (FMF.any())
4723       Inst->setFastMathFlags(FMF);
4724     return 0;
4725   }
4726
4727   case lltok::kw_sdiv:
4728   case lltok::kw_udiv:
4729   case lltok::kw_lshr:
4730   case lltok::kw_ashr: {
4731     bool Exact = EatIfPresent(lltok::kw_exact);
4732
4733     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4734     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4735     return false;
4736   }
4737
4738   case lltok::kw_urem:
4739   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4740   case lltok::kw_and:
4741   case lltok::kw_or:
4742   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
4743   case lltok::kw_icmp:   return ParseCompare(Inst, PFS, KeywordVal);
4744   case lltok::kw_fcmp: {
4745     FastMathFlags FMF = EatFastMathFlagsIfPresent();
4746     int Res = ParseCompare(Inst, PFS, KeywordVal);
4747     if (Res != 0)
4748       return Res;
4749     if (FMF.any())
4750       Inst->setFastMathFlags(FMF);
4751     return 0;
4752   }
4753
4754   // Casts.
4755   case lltok::kw_trunc:
4756   case lltok::kw_zext:
4757   case lltok::kw_sext:
4758   case lltok::kw_fptrunc:
4759   case lltok::kw_fpext:
4760   case lltok::kw_bitcast:
4761   case lltok::kw_addrspacecast:
4762   case lltok::kw_uitofp:
4763   case lltok::kw_sitofp:
4764   case lltok::kw_fptoui:
4765   case lltok::kw_fptosi:
4766   case lltok::kw_inttoptr:
4767   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
4768   // Other.
4769   case lltok::kw_select:         return ParseSelect(Inst, PFS);
4770   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
4771   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4772   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
4773   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
4774   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
4775   case lltok::kw_landingpad:     return ParseLandingPad(Inst, PFS);
4776   // Call.
4777   case lltok::kw_call:     return ParseCall(Inst, PFS, CallInst::TCK_None);
4778   case lltok::kw_tail:     return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4779   case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
4780   // Memory.
4781   case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
4782   case lltok::kw_load:           return ParseLoad(Inst, PFS);
4783   case lltok::kw_store:          return ParseStore(Inst, PFS);
4784   case lltok::kw_cmpxchg:        return ParseCmpXchg(Inst, PFS);
4785   case lltok::kw_atomicrmw:      return ParseAtomicRMW(Inst, PFS);
4786   case lltok::kw_fence:          return ParseFence(Inst, PFS);
4787   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4788   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
4789   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
4790   }
4791 }
4792
4793 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4794 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
4795   if (Opc == Instruction::FCmp) {
4796     switch (Lex.getKind()) {
4797     default: return TokError("expected fcmp predicate (e.g. 'oeq')");
4798     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4799     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4800     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4801     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4802     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4803     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4804     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4805     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4806     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4807     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4808     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4809     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4810     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4811     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4812     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4813     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4814     }
4815   } else {
4816     switch (Lex.getKind()) {
4817     default: return TokError("expected icmp predicate (e.g. 'eq')");
4818     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
4819     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
4820     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4821     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4822     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4823     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4824     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4825     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4826     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4827     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4828     }
4829   }
4830   Lex.Lex();
4831   return false;
4832 }
4833
4834 //===----------------------------------------------------------------------===//
4835 // Terminator Instructions.
4836 //===----------------------------------------------------------------------===//
4837
4838 /// ParseRet - Parse a return instruction.
4839 ///   ::= 'ret' void (',' !dbg, !1)*
4840 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
4841 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
4842                         PerFunctionState &PFS) {
4843   SMLoc TypeLoc = Lex.getLoc();
4844   Type *Ty = nullptr;
4845   if (ParseType(Ty, true /*void allowed*/)) return true;
4846
4847   Type *ResType = PFS.getFunction().getReturnType();
4848
4849   if (Ty->isVoidTy()) {
4850     if (!ResType->isVoidTy())
4851       return Error(TypeLoc, "value doesn't match function result type '" +
4852                    getTypeString(ResType) + "'");
4853
4854     Inst = ReturnInst::Create(Context);
4855     return false;
4856   }
4857
4858   Value *RV;
4859   if (ParseValue(Ty, RV, PFS)) return true;
4860
4861   if (ResType != RV->getType())
4862     return Error(TypeLoc, "value doesn't match function result type '" +
4863                  getTypeString(ResType) + "'");
4864
4865   Inst = ReturnInst::Create(Context, RV);
4866   return false;
4867 }
4868
4869
4870 /// ParseBr
4871 ///   ::= 'br' TypeAndValue
4872 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4873 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4874   LocTy Loc, Loc2;
4875   Value *Op0;
4876   BasicBlock *Op1, *Op2;
4877   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
4878
4879   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4880     Inst = BranchInst::Create(BB);
4881     return false;
4882   }
4883
4884   if (Op0->getType() != Type::getInt1Ty(Context))
4885     return Error(Loc, "branch condition must have 'i1' type");
4886
4887   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
4888       ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
4889       ParseToken(lltok::comma, "expected ',' after true destination") ||
4890       ParseTypeAndBasicBlock(Op2, Loc2, PFS))
4891     return true;
4892
4893   Inst = BranchInst::Create(Op1, Op2, Op0);
4894   return false;
4895 }
4896
4897 /// ParseSwitch
4898 ///  Instruction
4899 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4900 ///  JumpTable
4901 ///    ::= (TypeAndValue ',' TypeAndValue)*
4902 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4903   LocTy CondLoc, BBLoc;
4904   Value *Cond;
4905   BasicBlock *DefaultBB;
4906   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4907       ParseToken(lltok::comma, "expected ',' after switch condition") ||
4908       ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
4909       ParseToken(lltok::lsquare, "expected '[' with switch table"))
4910     return true;
4911
4912   if (!Cond->getType()->isIntegerTy())
4913     return Error(CondLoc, "switch condition must have integer type");
4914
4915   // Parse the jump table pairs.
4916   SmallPtrSet<Value*, 32> SeenCases;
4917   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4918   while (Lex.getKind() != lltok::rsquare) {
4919     Value *Constant;
4920     BasicBlock *DestBB;
4921
4922     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4923         ParseToken(lltok::comma, "expected ',' after case value") ||
4924         ParseTypeAndBasicBlock(DestBB, PFS))
4925       return true;
4926
4927     if (!SeenCases.insert(Constant).second)
4928       return Error(CondLoc, "duplicate case value in switch");
4929     if (!isa<ConstantInt>(Constant))
4930       return Error(CondLoc, "case value is not a constant integer");
4931
4932     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
4933   }
4934
4935   Lex.Lex();  // Eat the ']'.
4936
4937   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
4938   for (unsigned i = 0, e = Table.size(); i != e; ++i)
4939     SI->addCase(Table[i].first, Table[i].second);
4940   Inst = SI;
4941   return false;
4942 }
4943
4944 /// ParseIndirectBr
4945 ///  Instruction
4946 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4947 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
4948   LocTy AddrLoc;
4949   Value *Address;
4950   if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
4951       ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4952       ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
4953     return true;
4954
4955   if (!Address->getType()->isPointerTy())
4956     return Error(AddrLoc, "indirectbr address must have pointer type");
4957
4958   // Parse the destination list.
4959   SmallVector<BasicBlock*, 16> DestList;
4960
4961   if (Lex.getKind() != lltok::rsquare) {
4962     BasicBlock *DestBB;
4963     if (ParseTypeAndBasicBlock(DestBB, PFS))
4964       return true;
4965     DestList.push_back(DestBB);
4966
4967     while (EatIfPresent(lltok::comma)) {
4968       if (ParseTypeAndBasicBlock(DestBB, PFS))
4969         return true;
4970       DestList.push_back(DestBB);
4971     }
4972   }
4973
4974   if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4975     return true;
4976
4977   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
4978   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4979     IBI->addDestination(DestList[i]);
4980   Inst = IBI;
4981   return false;
4982 }
4983
4984
4985 /// ParseInvoke
4986 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4987 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4988 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4989   LocTy CallLoc = Lex.getLoc();
4990   AttrBuilder RetAttrs, FnAttrs;
4991   std::vector<unsigned> FwdRefAttrGrps;
4992   LocTy NoBuiltinLoc;
4993   unsigned CC;
4994   Type *RetType = nullptr;
4995   LocTy RetTypeLoc;
4996   ValID CalleeID;
4997   SmallVector<ParamInfo, 16> ArgList;
4998
4999   BasicBlock *NormalBB, *UnwindBB;
5000   if (ParseOptionalCallingConv(CC) ||
5001       ParseOptionalReturnAttrs(RetAttrs) ||
5002       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5003       ParseValID(CalleeID) ||
5004       ParseParameterList(ArgList, PFS) ||
5005       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5006                                  NoBuiltinLoc) ||
5007       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
5008       ParseTypeAndBasicBlock(NormalBB, PFS) ||
5009       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
5010       ParseTypeAndBasicBlock(UnwindBB, PFS))
5011     return true;
5012
5013   // If RetType is a non-function pointer type, then this is the short syntax
5014   // for the call, which means that RetType is just the return type.  Infer the
5015   // rest of the function argument types from the arguments that are present.
5016   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5017   if (!Ty) {
5018     // Pull out the types of all of the arguments...
5019     std::vector<Type*> ParamTypes;
5020     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5021       ParamTypes.push_back(ArgList[i].V->getType());
5022
5023     if (!FunctionType::isValidReturnType(RetType))
5024       return Error(RetTypeLoc, "Invalid result type for LLVM function");
5025
5026     Ty = FunctionType::get(RetType, ParamTypes, false);
5027   }
5028
5029   CalleeID.FTy = Ty;
5030
5031   // Look up the callee.
5032   Value *Callee;
5033   if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5034     return true;
5035
5036   // Set up the Attribute for the function.
5037   SmallVector<AttributeSet, 8> Attrs;
5038   if (RetAttrs.hasAttributes())
5039     Attrs.push_back(AttributeSet::get(RetType->getContext(),
5040                                       AttributeSet::ReturnIndex,
5041                                       RetAttrs));
5042
5043   SmallVector<Value*, 8> Args;
5044
5045   // Loop through FunctionType's arguments and ensure they are specified
5046   // correctly.  Also, gather any parameter attributes.
5047   FunctionType::param_iterator I = Ty->param_begin();
5048   FunctionType::param_iterator E = Ty->param_end();
5049   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5050     Type *ExpectedTy = nullptr;
5051     if (I != E) {
5052       ExpectedTy = *I++;
5053     } else if (!Ty->isVarArg()) {
5054       return Error(ArgList[i].Loc, "too many arguments specified");
5055     }
5056
5057     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5058       return Error(ArgList[i].Loc, "argument is not of expected type '" +
5059                    getTypeString(ExpectedTy) + "'");
5060     Args.push_back(ArgList[i].V);
5061     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5062       AttrBuilder B(ArgList[i].Attrs, i + 1);
5063       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5064     }
5065   }
5066
5067   if (I != E)
5068     return Error(CallLoc, "not enough parameters specified for call");
5069
5070   if (FnAttrs.hasAttributes()) {
5071     if (FnAttrs.hasAlignmentAttr())
5072       return Error(CallLoc, "invoke instructions may not have an alignment");
5073
5074     Attrs.push_back(AttributeSet::get(RetType->getContext(),
5075                                       AttributeSet::FunctionIndex,
5076                                       FnAttrs));
5077   }
5078
5079   // Finish off the Attribute and check them
5080   AttributeSet PAL = AttributeSet::get(Context, Attrs);
5081
5082   InvokeInst *II = InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args);
5083   II->setCallingConv(CC);
5084   II->setAttributes(PAL);
5085   ForwardRefAttrGroups[II] = FwdRefAttrGrps;
5086   Inst = II;
5087   return false;
5088 }
5089
5090 /// ParseResume
5091 ///   ::= 'resume' TypeAndValue
5092 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5093   Value *Exn; LocTy ExnLoc;
5094   if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5095     return true;
5096
5097   ResumeInst *RI = ResumeInst::Create(Exn);
5098   Inst = RI;
5099   return false;
5100 }
5101
5102 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5103                                   PerFunctionState &PFS) {
5104   if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
5105     return true;
5106
5107   while (Lex.getKind() != lltok::rsquare) {
5108     // If this isn't the first argument, we need a comma.
5109     if (!Args.empty() &&
5110         ParseToken(lltok::comma, "expected ',' in argument list"))
5111       return true;
5112
5113     // Parse the argument.
5114     LocTy ArgLoc;
5115     Type *ArgTy = nullptr;
5116     if (ParseType(ArgTy, ArgLoc))
5117       return true;
5118
5119     Value *V;
5120     if (ArgTy->isMetadataTy()) {
5121       if (ParseMetadataAsValue(V, PFS))
5122         return true;
5123     } else {
5124       if (ParseValue(ArgTy, V, PFS))
5125         return true;
5126     }
5127     Args.push_back(V);
5128   }
5129
5130   Lex.Lex();  // Lex the ']'.
5131   return false;
5132 }
5133
5134 /// ParseCleanupRet
5135 ///   ::= 'cleanupret' Value unwind ('to' 'caller' | TypeAndValue)
5136 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
5137   Value *CleanupPad = nullptr;
5138
5139   if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS, OC_CleanupPad))
5140     return true;
5141
5142   if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5143     return true;
5144
5145   BasicBlock *UnwindBB = nullptr;
5146   if (Lex.getKind() == lltok::kw_to) {
5147     Lex.Lex();
5148     if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5149       return true;
5150   } else {
5151     if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5152       return true;
5153     }
5154   }
5155
5156   Inst = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad), UnwindBB);
5157   return false;
5158 }
5159
5160 /// ParseCatchRet
5161 ///   ::= 'catchret' Value 'to' TypeAndValue
5162 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
5163   Value *CatchPad = nullptr;
5164
5165   if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS, OC_CatchPad))
5166     return true;
5167
5168   BasicBlock *BB;
5169   if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5170       ParseTypeAndBasicBlock(BB, PFS))
5171       return true;
5172
5173   Inst = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
5174   return false;
5175 }
5176
5177 /// ParseCatchPad
5178 ///   ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
5179 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
5180   SmallVector<Value *, 8> Args;
5181   if (ParseExceptionArgs(Args, PFS))
5182     return true;
5183
5184   BasicBlock *NormalBB, *UnwindBB;
5185   if (ParseToken(lltok::kw_to, "expected 'to' in catchpad") ||
5186       ParseTypeAndBasicBlock(NormalBB, PFS) ||
5187       ParseToken(lltok::kw_unwind, "expected 'unwind' in catchpad") ||
5188       ParseTypeAndBasicBlock(UnwindBB, PFS))
5189     return true;
5190
5191   Inst = CatchPadInst::Create(NormalBB, UnwindBB, Args);
5192   return false;
5193 }
5194
5195 /// ParseTerminatePad
5196 ///   ::= 'terminatepad' ParamList 'to' TypeAndValue
5197 bool LLParser::ParseTerminatePad(Instruction *&Inst, PerFunctionState &PFS) {
5198   SmallVector<Value *, 8> Args;
5199   if (ParseExceptionArgs(Args, PFS))
5200     return true;
5201
5202   if (ParseToken(lltok::kw_unwind, "expected 'unwind' in terminatepad"))
5203     return true;
5204
5205   BasicBlock *UnwindBB = nullptr;
5206   if (Lex.getKind() == lltok::kw_to) {
5207     Lex.Lex();
5208     if (ParseToken(lltok::kw_caller, "expected 'caller' in terminatepad"))
5209       return true;
5210   } else {
5211     if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5212       return true;
5213     }
5214   }
5215
5216   Inst = TerminatePadInst::Create(Context, UnwindBB, Args);
5217   return false;
5218 }
5219
5220 /// ParseCleanupPad
5221 ///   ::= 'cleanuppad' ParamList
5222 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
5223   SmallVector<Value *, 8> Args;
5224   if (ParseExceptionArgs(Args, PFS))
5225     return true;
5226
5227   Inst = CleanupPadInst::Create(Context, Args);
5228   return false;
5229 }
5230
5231 /// ParseCatchEndPad
5232 ///   ::= 'catchendpad' unwind ('to' 'caller' | TypeAndValue)
5233 bool LLParser::ParseCatchEndPad(Instruction *&Inst, PerFunctionState &PFS) {
5234   if (ParseToken(lltok::kw_unwind, "expected 'unwind' in catchendpad"))
5235     return true;
5236
5237   BasicBlock *UnwindBB = nullptr;
5238   if (Lex.getKind() == lltok::kw_to) {
5239     Lex.Lex();
5240     if (Lex.getKind() == lltok::kw_caller) {
5241       Lex.Lex();
5242     } else {
5243       return true;
5244     }
5245   } else {
5246     if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5247       return true;
5248     }
5249   }
5250
5251   Inst = CatchEndPadInst::Create(Context, UnwindBB);
5252   return false;
5253 }
5254
5255 /// ParseCatchEndPad
5256 ///   ::= 'cleanupendpad' Value unwind ('to' 'caller' | TypeAndValue)
5257 bool LLParser::ParseCleanupEndPad(Instruction *&Inst, PerFunctionState &PFS) {
5258   Value *CleanupPad = nullptr;
5259
5260   if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS, OC_CleanupPad))
5261     return true;
5262
5263   if (ParseToken(lltok::kw_unwind, "expected 'unwind' in catchendpad"))
5264     return true;
5265
5266   BasicBlock *UnwindBB = nullptr;
5267   if (Lex.getKind() == lltok::kw_to) {
5268     Lex.Lex();
5269     if (Lex.getKind() == lltok::kw_caller) {
5270       Lex.Lex();
5271     } else {
5272       return true;
5273     }
5274   } else {
5275     if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5276       return true;
5277     }
5278   }
5279
5280   Inst = CleanupEndPadInst::Create(cast<CleanupPadInst>(CleanupPad), UnwindBB);
5281   return false;
5282 }
5283
5284 //===----------------------------------------------------------------------===//
5285 // Binary Operators.
5286 //===----------------------------------------------------------------------===//
5287
5288 /// ParseArithmetic
5289 ///  ::= ArithmeticOps TypeAndValue ',' Value
5290 ///
5291 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
5292 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
5293 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
5294                                unsigned Opc, unsigned OperandType) {
5295   LocTy Loc; Value *LHS, *RHS;
5296   if (ParseTypeAndValue(LHS, Loc, PFS) ||
5297       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5298       ParseValue(LHS->getType(), RHS, PFS))
5299     return true;
5300
5301   bool Valid;
5302   switch (OperandType) {
5303   default: llvm_unreachable("Unknown operand type!");
5304   case 0: // int or FP.
5305     Valid = LHS->getType()->isIntOrIntVectorTy() ||
5306             LHS->getType()->isFPOrFPVectorTy();
5307     break;
5308   case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5309   case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
5310   }
5311
5312   if (!Valid)
5313     return Error(Loc, "invalid operand type for instruction");
5314
5315   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5316   return false;
5317 }
5318
5319 /// ParseLogical
5320 ///  ::= ArithmeticOps TypeAndValue ',' Value {
5321 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5322                             unsigned Opc) {
5323   LocTy Loc; Value *LHS, *RHS;
5324   if (ParseTypeAndValue(LHS, Loc, PFS) ||
5325       ParseToken(lltok::comma, "expected ',' in logical operation") ||
5326       ParseValue(LHS->getType(), RHS, PFS))
5327     return true;
5328
5329   if (!LHS->getType()->isIntOrIntVectorTy())
5330     return Error(Loc,"instruction requires integer or integer vector operands");
5331
5332   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5333   return false;
5334 }
5335
5336
5337 /// ParseCompare
5338 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
5339 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
5340 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5341                             unsigned Opc) {
5342   // Parse the integer/fp comparison predicate.
5343   LocTy Loc;
5344   unsigned Pred;
5345   Value *LHS, *RHS;
5346   if (ParseCmpPredicate(Pred, Opc) ||
5347       ParseTypeAndValue(LHS, Loc, PFS) ||
5348       ParseToken(lltok::comma, "expected ',' after compare value") ||
5349       ParseValue(LHS->getType(), RHS, PFS))
5350     return true;
5351
5352   if (Opc == Instruction::FCmp) {
5353     if (!LHS->getType()->isFPOrFPVectorTy())
5354       return Error(Loc, "fcmp requires floating point operands");
5355     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5356   } else {
5357     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
5358     if (!LHS->getType()->isIntOrIntVectorTy() &&
5359         !LHS->getType()->getScalarType()->isPointerTy())
5360       return Error(Loc, "icmp requires integer operands");
5361     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5362   }
5363   return false;
5364 }
5365
5366 //===----------------------------------------------------------------------===//
5367 // Other Instructions.
5368 //===----------------------------------------------------------------------===//
5369
5370
5371 /// ParseCast
5372 ///   ::= CastOpc TypeAndValue 'to' Type
5373 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5374                          unsigned Opc) {
5375   LocTy Loc;
5376   Value *Op;
5377   Type *DestTy = nullptr;
5378   if (ParseTypeAndValue(Op, Loc, PFS) ||
5379       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5380       ParseType(DestTy))
5381     return true;
5382
5383   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5384     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
5385     return Error(Loc, "invalid cast opcode for cast from '" +
5386                  getTypeString(Op->getType()) + "' to '" +
5387                  getTypeString(DestTy) + "'");
5388   }
5389   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5390   return false;
5391 }
5392
5393 /// ParseSelect
5394 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5395 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5396   LocTy Loc;
5397   Value *Op0, *Op1, *Op2;
5398   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5399       ParseToken(lltok::comma, "expected ',' after select condition") ||
5400       ParseTypeAndValue(Op1, PFS) ||
5401       ParseToken(lltok::comma, "expected ',' after select value") ||
5402       ParseTypeAndValue(Op2, PFS))
5403     return true;
5404
5405   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5406     return Error(Loc, Reason);
5407
5408   Inst = SelectInst::Create(Op0, Op1, Op2);
5409   return false;
5410 }
5411
5412 /// ParseVA_Arg
5413 ///   ::= 'va_arg' TypeAndValue ',' Type
5414 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5415   Value *Op;
5416   Type *EltTy = nullptr;
5417   LocTy TypeLoc;
5418   if (ParseTypeAndValue(Op, PFS) ||
5419       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5420       ParseType(EltTy, TypeLoc))
5421     return true;
5422
5423   if (!EltTy->isFirstClassType())
5424     return Error(TypeLoc, "va_arg requires operand with first class type");
5425
5426   Inst = new VAArgInst(Op, EltTy);
5427   return false;
5428 }
5429
5430 /// ParseExtractElement
5431 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
5432 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5433   LocTy Loc;
5434   Value *Op0, *Op1;
5435   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5436       ParseToken(lltok::comma, "expected ',' after extract value") ||
5437       ParseTypeAndValue(Op1, PFS))
5438     return true;
5439
5440   if (!ExtractElementInst::isValidOperands(Op0, Op1))
5441     return Error(Loc, "invalid extractelement operands");
5442
5443   Inst = ExtractElementInst::Create(Op0, Op1);
5444   return false;
5445 }
5446
5447 /// ParseInsertElement
5448 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5449 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5450   LocTy Loc;
5451   Value *Op0, *Op1, *Op2;
5452   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5453       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5454       ParseTypeAndValue(Op1, PFS) ||
5455       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5456       ParseTypeAndValue(Op2, PFS))
5457     return true;
5458
5459   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5460     return Error(Loc, "invalid insertelement operands");
5461
5462   Inst = InsertElementInst::Create(Op0, Op1, Op2);
5463   return false;
5464 }
5465
5466 /// ParseShuffleVector
5467 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5468 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5469   LocTy Loc;
5470   Value *Op0, *Op1, *Op2;
5471   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5472       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5473       ParseTypeAndValue(Op1, PFS) ||
5474       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5475       ParseTypeAndValue(Op2, PFS))
5476     return true;
5477
5478   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5479     return Error(Loc, "invalid shufflevector operands");
5480
5481   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5482   return false;
5483 }
5484
5485 /// ParsePHI
5486 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5487 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5488   Type *Ty = nullptr;  LocTy TypeLoc;
5489   Value *Op0, *Op1;
5490
5491   if (ParseType(Ty, TypeLoc) ||
5492       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5493       ParseValue(Ty, Op0, PFS) ||
5494       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5495       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5496       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5497     return true;
5498
5499   bool AteExtraComma = false;
5500   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5501   while (1) {
5502     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5503
5504     if (!EatIfPresent(lltok::comma))
5505       break;
5506
5507     if (Lex.getKind() == lltok::MetadataVar) {
5508       AteExtraComma = true;
5509       break;
5510     }
5511
5512     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5513         ParseValue(Ty, Op0, PFS) ||
5514         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5515         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5516         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5517       return true;
5518   }
5519
5520   if (!Ty->isFirstClassType())
5521     return Error(TypeLoc, "phi node must have first class type");
5522
5523   PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5524   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5525     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5526   Inst = PN;
5527   return AteExtraComma ? InstExtraComma : InstNormal;
5528 }
5529
5530 /// ParseLandingPad
5531 ///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5532 /// Clause
5533 ///   ::= 'catch' TypeAndValue
5534 ///   ::= 'filter'
5535 ///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5536 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5537   Type *Ty = nullptr; LocTy TyLoc;
5538
5539   if (ParseType(Ty, TyLoc))
5540     return true;
5541
5542   std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
5543   LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5544
5545   while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5546     LandingPadInst::ClauseType CT;
5547     if (EatIfPresent(lltok::kw_catch))
5548       CT = LandingPadInst::Catch;
5549     else if (EatIfPresent(lltok::kw_filter))
5550       CT = LandingPadInst::Filter;
5551     else
5552       return TokError("expected 'catch' or 'filter' clause type");
5553
5554     Value *V;
5555     LocTy VLoc;
5556     if (ParseTypeAndValue(V, VLoc, PFS))
5557       return true;
5558
5559     // A 'catch' type expects a non-array constant. A filter clause expects an
5560     // array constant.
5561     if (CT == LandingPadInst::Catch) {
5562       if (isa<ArrayType>(V->getType()))
5563         Error(VLoc, "'catch' clause has an invalid type");
5564     } else {
5565       if (!isa<ArrayType>(V->getType()))
5566         Error(VLoc, "'filter' clause has an invalid type");
5567     }
5568
5569     Constant *CV = dyn_cast<Constant>(V);
5570     if (!CV)
5571       return Error(VLoc, "clause argument must be a constant");
5572     LP->addClause(CV);
5573   }
5574
5575   Inst = LP.release();
5576   return false;
5577 }
5578
5579 /// ParseCall
5580 ///   ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5581 ///       ParameterList OptionalAttrs
5582 ///   ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5583 ///       ParameterList OptionalAttrs
5584 ///   ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
5585 ///       ParameterList OptionalAttrs
5586 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5587                          CallInst::TailCallKind TCK) {
5588   AttrBuilder RetAttrs, FnAttrs;
5589   std::vector<unsigned> FwdRefAttrGrps;
5590   LocTy BuiltinLoc;
5591   unsigned CC;
5592   Type *RetType = nullptr;
5593   LocTy RetTypeLoc;
5594   ValID CalleeID;
5595   SmallVector<ParamInfo, 16> ArgList;
5596   LocTy CallLoc = Lex.getLoc();
5597
5598   if ((TCK != CallInst::TCK_None &&
5599        ParseToken(lltok::kw_call, "expected 'tail call'")) ||
5600       ParseOptionalCallingConv(CC) ||
5601       ParseOptionalReturnAttrs(RetAttrs) ||
5602       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5603       ParseValID(CalleeID) ||
5604       ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5605                          PFS.getFunction().isVarArg()) ||
5606       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5607                                  BuiltinLoc))
5608     return true;
5609
5610   // If RetType is a non-function pointer type, then this is the short syntax
5611   // for the call, which means that RetType is just the return type.  Infer the
5612   // rest of the function argument types from the arguments that are present.
5613   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5614   if (!Ty) {
5615     // Pull out the types of all of the arguments...
5616     std::vector<Type*> ParamTypes;
5617     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5618       ParamTypes.push_back(ArgList[i].V->getType());
5619
5620     if (!FunctionType::isValidReturnType(RetType))
5621       return Error(RetTypeLoc, "Invalid result type for LLVM function");
5622
5623     Ty = FunctionType::get(RetType, ParamTypes, false);
5624   }
5625
5626   CalleeID.FTy = Ty;
5627
5628   // Look up the callee.
5629   Value *Callee;
5630   if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5631     return true;
5632
5633   // Set up the Attribute for the function.
5634   SmallVector<AttributeSet, 8> Attrs;
5635   if (RetAttrs.hasAttributes())
5636     Attrs.push_back(AttributeSet::get(RetType->getContext(),
5637                                       AttributeSet::ReturnIndex,
5638                                       RetAttrs));
5639
5640   SmallVector<Value*, 8> Args;
5641
5642   // Loop through FunctionType's arguments and ensure they are specified
5643   // correctly.  Also, gather any parameter attributes.
5644   FunctionType::param_iterator I = Ty->param_begin();
5645   FunctionType::param_iterator E = Ty->param_end();
5646   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5647     Type *ExpectedTy = nullptr;
5648     if (I != E) {
5649       ExpectedTy = *I++;
5650     } else if (!Ty->isVarArg()) {
5651       return Error(ArgList[i].Loc, "too many arguments specified");
5652     }
5653
5654     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5655       return Error(ArgList[i].Loc, "argument is not of expected type '" +
5656                    getTypeString(ExpectedTy) + "'");
5657     Args.push_back(ArgList[i].V);
5658     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5659       AttrBuilder B(ArgList[i].Attrs, i + 1);
5660       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5661     }
5662   }
5663
5664   if (I != E)
5665     return Error(CallLoc, "not enough parameters specified for call");
5666
5667   if (FnAttrs.hasAttributes()) {
5668     if (FnAttrs.hasAlignmentAttr())
5669       return Error(CallLoc, "call instructions may not have an alignment");
5670
5671     Attrs.push_back(AttributeSet::get(RetType->getContext(),
5672                                       AttributeSet::FunctionIndex,
5673                                       FnAttrs));
5674   }
5675
5676   // Finish off the Attribute and check them
5677   AttributeSet PAL = AttributeSet::get(Context, Attrs);
5678
5679   CallInst *CI = CallInst::Create(Ty, Callee, Args);
5680   CI->setTailCallKind(TCK);
5681   CI->setCallingConv(CC);
5682   CI->setAttributes(PAL);
5683   ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5684   Inst = CI;
5685   return false;
5686 }
5687
5688 //===----------------------------------------------------------------------===//
5689 // Memory Instructions.
5690 //===----------------------------------------------------------------------===//
5691
5692 /// ParseAlloc
5693 ///   ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
5694 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5695   Value *Size = nullptr;
5696   LocTy SizeLoc, TyLoc;
5697   unsigned Alignment = 0;
5698   Type *Ty = nullptr;
5699
5700   bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5701
5702   if (ParseType(Ty, TyLoc)) return true;
5703
5704   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5705     return Error(TyLoc, "invalid type for alloca");
5706
5707   bool AteExtraComma = false;
5708   if (EatIfPresent(lltok::comma)) {
5709     if (Lex.getKind() == lltok::kw_align) {
5710       if (ParseOptionalAlignment(Alignment)) return true;
5711     } else if (Lex.getKind() == lltok::MetadataVar) {
5712       AteExtraComma = true;
5713     } else {
5714       if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5715           ParseOptionalCommaAlign(Alignment, AteExtraComma))
5716         return true;
5717     }
5718   }
5719
5720   if (Size && !Size->getType()->isIntegerTy())
5721     return Error(SizeLoc, "element count must have integer type");
5722
5723   AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5724   AI->setUsedWithInAlloca(IsInAlloca);
5725   Inst = AI;
5726   return AteExtraComma ? InstExtraComma : InstNormal;
5727 }
5728
5729 /// ParseLoad
5730 ///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5731 ///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
5732 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
5733 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
5734   Value *Val; LocTy Loc;
5735   unsigned Alignment = 0;
5736   bool AteExtraComma = false;
5737   bool isAtomic = false;
5738   AtomicOrdering Ordering = NotAtomic;
5739   SynchronizationScope Scope = CrossThread;
5740
5741   if (Lex.getKind() == lltok::kw_atomic) {
5742     isAtomic = true;
5743     Lex.Lex();
5744   }
5745
5746   bool isVolatile = false;
5747   if (Lex.getKind() == lltok::kw_volatile) {
5748     isVolatile = true;
5749     Lex.Lex();
5750   }
5751
5752   Type *Ty;
5753   LocTy ExplicitTypeLoc = Lex.getLoc();
5754   if (ParseType(Ty) ||
5755       ParseToken(lltok::comma, "expected comma after load's type") ||
5756       ParseTypeAndValue(Val, Loc, PFS) ||
5757       ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5758       ParseOptionalCommaAlign(Alignment, AteExtraComma))
5759     return true;
5760
5761   if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
5762     return Error(Loc, "load operand must be a pointer to a first class type");
5763   if (isAtomic && !Alignment)
5764     return Error(Loc, "atomic load must have explicit non-zero alignment");
5765   if (Ordering == Release || Ordering == AcquireRelease)
5766     return Error(Loc, "atomic load cannot use Release ordering");
5767
5768   if (Ty != cast<PointerType>(Val->getType())->getElementType())
5769     return Error(ExplicitTypeLoc,
5770                  "explicit pointee type doesn't match operand's pointee type");
5771
5772   Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
5773   return AteExtraComma ? InstExtraComma : InstNormal;
5774 }
5775
5776 /// ParseStore
5777
5778 ///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5779 ///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
5780 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
5781 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
5782   Value *Val, *Ptr; LocTy Loc, PtrLoc;
5783   unsigned Alignment = 0;
5784   bool AteExtraComma = false;
5785   bool isAtomic = false;
5786   AtomicOrdering Ordering = NotAtomic;
5787   SynchronizationScope Scope = CrossThread;
5788
5789   if (Lex.getKind() == lltok::kw_atomic) {
5790     isAtomic = true;
5791     Lex.Lex();
5792   }
5793
5794   bool isVolatile = false;
5795   if (Lex.getKind() == lltok::kw_volatile) {
5796     isVolatile = true;
5797     Lex.Lex();
5798   }
5799
5800   if (ParseTypeAndValue(Val, Loc, PFS) ||
5801       ParseToken(lltok::comma, "expected ',' after store operand") ||
5802       ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5803       ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5804       ParseOptionalCommaAlign(Alignment, AteExtraComma))
5805     return true;
5806
5807   if (!Ptr->getType()->isPointerTy())
5808     return Error(PtrLoc, "store operand must be a pointer");
5809   if (!Val->getType()->isFirstClassType())
5810     return Error(Loc, "store operand must be a first class value");
5811   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5812     return Error(Loc, "stored value and pointer type do not match");
5813   if (isAtomic && !Alignment)
5814     return Error(Loc, "atomic store must have explicit non-zero alignment");
5815   if (Ordering == Acquire || Ordering == AcquireRelease)
5816     return Error(Loc, "atomic store cannot use Acquire ordering");
5817
5818   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
5819   return AteExtraComma ? InstExtraComma : InstNormal;
5820 }
5821
5822 /// ParseCmpXchg
5823 ///   ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5824 ///       TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
5825 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
5826   Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5827   bool AteExtraComma = false;
5828   AtomicOrdering SuccessOrdering = NotAtomic;
5829   AtomicOrdering FailureOrdering = NotAtomic;
5830   SynchronizationScope Scope = CrossThread;
5831   bool isVolatile = false;
5832   bool isWeak = false;
5833
5834   if (EatIfPresent(lltok::kw_weak))
5835     isWeak = true;
5836
5837   if (EatIfPresent(lltok::kw_volatile))
5838     isVolatile = true;
5839
5840   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5841       ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5842       ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5843       ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5844       ParseTypeAndValue(New, NewLoc, PFS) ||
5845       ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5846       ParseOrdering(FailureOrdering))
5847     return true;
5848
5849   if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
5850     return TokError("cmpxchg cannot be unordered");
5851   if (SuccessOrdering < FailureOrdering)
5852     return TokError("cmpxchg must be at least as ordered on success as failure");
5853   if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5854     return TokError("cmpxchg failure ordering cannot include release semantics");
5855   if (!Ptr->getType()->isPointerTy())
5856     return Error(PtrLoc, "cmpxchg operand must be a pointer");
5857   if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5858     return Error(CmpLoc, "compare value and pointer type do not match");
5859   if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5860     return Error(NewLoc, "new value and pointer type do not match");
5861   if (!New->getType()->isIntegerTy())
5862     return Error(NewLoc, "cmpxchg operand must be an integer");
5863   unsigned Size = New->getType()->getPrimitiveSizeInBits();
5864   if (Size < 8 || (Size & (Size - 1)))
5865     return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5866                          " integer");
5867
5868   AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5869       Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
5870   CXI->setVolatile(isVolatile);
5871   CXI->setWeak(isWeak);
5872   Inst = CXI;
5873   return AteExtraComma ? InstExtraComma : InstNormal;
5874 }
5875
5876 /// ParseAtomicRMW
5877 ///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5878 ///       'singlethread'? AtomicOrdering
5879 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
5880   Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5881   bool AteExtraComma = false;
5882   AtomicOrdering Ordering = NotAtomic;
5883   SynchronizationScope Scope = CrossThread;
5884   bool isVolatile = false;
5885   AtomicRMWInst::BinOp Operation;
5886
5887   if (EatIfPresent(lltok::kw_volatile))
5888     isVolatile = true;
5889
5890   switch (Lex.getKind()) {
5891   default: return TokError("expected binary operation in atomicrmw");
5892   case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5893   case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5894   case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5895   case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5896   case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5897   case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5898   case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5899   case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5900   case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5901   case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5902   case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5903   }
5904   Lex.Lex();  // Eat the operation.
5905
5906   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5907       ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5908       ParseTypeAndValue(Val, ValLoc, PFS) ||
5909       ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5910     return true;
5911
5912   if (Ordering == Unordered)
5913     return TokError("atomicrmw cannot be unordered");
5914   if (!Ptr->getType()->isPointerTy())
5915     return Error(PtrLoc, "atomicrmw operand must be a pointer");
5916   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5917     return Error(ValLoc, "atomicrmw value and pointer type do not match");
5918   if (!Val->getType()->isIntegerTy())
5919     return Error(ValLoc, "atomicrmw operand must be an integer");
5920   unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5921   if (Size < 8 || (Size & (Size - 1)))
5922     return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5923                          " integer");
5924
5925   AtomicRMWInst *RMWI =
5926     new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5927   RMWI->setVolatile(isVolatile);
5928   Inst = RMWI;
5929   return AteExtraComma ? InstExtraComma : InstNormal;
5930 }
5931
5932 /// ParseFence
5933 ///   ::= 'fence' 'singlethread'? AtomicOrdering
5934 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5935   AtomicOrdering Ordering = NotAtomic;
5936   SynchronizationScope Scope = CrossThread;
5937   if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5938     return true;
5939
5940   if (Ordering == Unordered)
5941     return TokError("fence cannot be unordered");
5942   if (Ordering == Monotonic)
5943     return TokError("fence cannot be monotonic");
5944
5945   Inst = new FenceInst(Context, Ordering, Scope);
5946   return InstNormal;
5947 }
5948
5949 /// ParseGetElementPtr
5950 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
5951 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
5952   Value *Ptr = nullptr;
5953   Value *Val = nullptr;
5954   LocTy Loc, EltLoc;
5955
5956   bool InBounds = EatIfPresent(lltok::kw_inbounds);
5957
5958   Type *Ty = nullptr;
5959   LocTy ExplicitTypeLoc = Lex.getLoc();
5960   if (ParseType(Ty) ||
5961       ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5962       ParseTypeAndValue(Ptr, Loc, PFS))
5963     return true;
5964
5965   Type *BaseType = Ptr->getType();
5966   PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5967   if (!BasePointerType)
5968     return Error(Loc, "base of getelementptr must be a pointer");
5969
5970   if (Ty != BasePointerType->getElementType())
5971     return Error(ExplicitTypeLoc,
5972                  "explicit pointee type doesn't match operand's pointee type");
5973
5974   SmallVector<Value*, 16> Indices;
5975   bool AteExtraComma = false;
5976   // GEP returns a vector of pointers if at least one of parameters is a vector.
5977   // All vector parameters should have the same vector width.
5978   unsigned GEPWidth = BaseType->isVectorTy() ?
5979     BaseType->getVectorNumElements() : 0;
5980
5981   while (EatIfPresent(lltok::comma)) {
5982     if (Lex.getKind() == lltok::MetadataVar) {
5983       AteExtraComma = true;
5984       break;
5985     }
5986     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
5987     if (!Val->getType()->getScalarType()->isIntegerTy())
5988       return Error(EltLoc, "getelementptr index must be an integer");
5989
5990     if (Val->getType()->isVectorTy()) {
5991       unsigned ValNumEl = Val->getType()->getVectorNumElements();
5992       if (GEPWidth && GEPWidth != ValNumEl)
5993         return Error(EltLoc,
5994           "getelementptr vector index has a wrong number of elements");
5995       GEPWidth = ValNumEl;
5996     }
5997     Indices.push_back(Val);
5998   }
5999
6000   SmallPtrSet<Type*, 4> Visited;
6001   if (!Indices.empty() && !Ty->isSized(&Visited))
6002     return Error(Loc, "base element of getelementptr must be sized");
6003
6004   if (!GetElementPtrInst::getIndexedType(Ty, Indices))
6005     return Error(Loc, "invalid getelementptr indices");
6006   Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
6007   if (InBounds)
6008     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
6009   return AteExtraComma ? InstExtraComma : InstNormal;
6010 }
6011
6012 /// ParseExtractValue
6013 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
6014 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
6015   Value *Val; LocTy Loc;
6016   SmallVector<unsigned, 4> Indices;
6017   bool AteExtraComma;
6018   if (ParseTypeAndValue(Val, Loc, PFS) ||
6019       ParseIndexList(Indices, AteExtraComma))
6020     return true;
6021
6022   if (!Val->getType()->isAggregateType())
6023     return Error(Loc, "extractvalue operand must be aggregate type");
6024
6025   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
6026     return Error(Loc, "invalid indices for extractvalue");
6027   Inst = ExtractValueInst::Create(Val, Indices);
6028   return AteExtraComma ? InstExtraComma : InstNormal;
6029 }
6030
6031 /// ParseInsertValue
6032 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
6033 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
6034   Value *Val0, *Val1; LocTy Loc0, Loc1;
6035   SmallVector<unsigned, 4> Indices;
6036   bool AteExtraComma;
6037   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6038       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6039       ParseTypeAndValue(Val1, Loc1, PFS) ||
6040       ParseIndexList(Indices, AteExtraComma))
6041     return true;
6042
6043   if (!Val0->getType()->isAggregateType())
6044     return Error(Loc0, "insertvalue operand must be aggregate type");
6045
6046   Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6047   if (!IndexedType)
6048     return Error(Loc0, "invalid indices for insertvalue");
6049   if (IndexedType != Val1->getType())
6050     return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6051                            getTypeString(Val1->getType()) + "' instead of '" +
6052                            getTypeString(IndexedType) + "'");
6053   Inst = InsertValueInst::Create(Val0, Val1, Indices);
6054   return AteExtraComma ? InstExtraComma : InstNormal;
6055 }
6056
6057 //===----------------------------------------------------------------------===//
6058 // Embedded metadata.
6059 //===----------------------------------------------------------------------===//
6060
6061 /// ParseMDNodeVector
6062 ///   ::= { Element (',' Element)* }
6063 /// Element
6064 ///   ::= 'null' | TypeAndValue
6065 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
6066   if (ParseToken(lltok::lbrace, "expected '{' here"))
6067     return true;
6068
6069   // Check for an empty list.
6070   if (EatIfPresent(lltok::rbrace))
6071     return false;
6072
6073   do {
6074     // Null is a special case since it is typeless.
6075     if (EatIfPresent(lltok::kw_null)) {
6076       Elts.push_back(nullptr);
6077       continue;
6078     }
6079
6080     Metadata *MD;
6081     if (ParseMetadata(MD, nullptr))
6082       return true;
6083     Elts.push_back(MD);
6084   } while (EatIfPresent(lltok::comma));
6085
6086   return ParseToken(lltok::rbrace, "expected end of metadata node");
6087 }
6088
6089 //===----------------------------------------------------------------------===//
6090 // Use-list order directives.
6091 //===----------------------------------------------------------------------===//
6092 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6093                                 SMLoc Loc) {
6094   if (V->use_empty())
6095     return Error(Loc, "value has no uses");
6096
6097   unsigned NumUses = 0;
6098   SmallDenseMap<const Use *, unsigned, 16> Order;
6099   for (const Use &U : V->uses()) {
6100     if (++NumUses > Indexes.size())
6101       break;
6102     Order[&U] = Indexes[NumUses - 1];
6103   }
6104   if (NumUses < 2)
6105     return Error(Loc, "value only has one use");
6106   if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6107     return Error(Loc, "wrong number of indexes, expected " +
6108                           Twine(std::distance(V->use_begin(), V->use_end())));
6109
6110   V->sortUseList([&](const Use &L, const Use &R) {
6111     return Order.lookup(&L) < Order.lookup(&R);
6112   });
6113   return false;
6114 }
6115
6116 /// ParseUseListOrderIndexes
6117 ///   ::= '{' uint32 (',' uint32)+ '}'
6118 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6119   SMLoc Loc = Lex.getLoc();
6120   if (ParseToken(lltok::lbrace, "expected '{' here"))
6121     return true;
6122   if (Lex.getKind() == lltok::rbrace)
6123     return Lex.Error("expected non-empty list of uselistorder indexes");
6124
6125   // Use Offset, Max, and IsOrdered to check consistency of indexes.  The
6126   // indexes should be distinct numbers in the range [0, size-1], and should
6127   // not be in order.
6128   unsigned Offset = 0;
6129   unsigned Max = 0;
6130   bool IsOrdered = true;
6131   assert(Indexes.empty() && "Expected empty order vector");
6132   do {
6133     unsigned Index;
6134     if (ParseUInt32(Index))
6135       return true;
6136
6137     // Update consistency checks.
6138     Offset += Index - Indexes.size();
6139     Max = std::max(Max, Index);
6140     IsOrdered &= Index == Indexes.size();
6141
6142     Indexes.push_back(Index);
6143   } while (EatIfPresent(lltok::comma));
6144
6145   if (ParseToken(lltok::rbrace, "expected '}' here"))
6146     return true;
6147
6148   if (Indexes.size() < 2)
6149     return Error(Loc, "expected >= 2 uselistorder indexes");
6150   if (Offset != 0 || Max >= Indexes.size())
6151     return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6152   if (IsOrdered)
6153     return Error(Loc, "expected uselistorder indexes to change the order");
6154
6155   return false;
6156 }
6157
6158 /// ParseUseListOrder
6159 ///   ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6160 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6161   SMLoc Loc = Lex.getLoc();
6162   if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6163     return true;
6164
6165   Value *V;
6166   SmallVector<unsigned, 16> Indexes;
6167   if (ParseTypeAndValue(V, PFS) ||
6168       ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6169       ParseUseListOrderIndexes(Indexes))
6170     return true;
6171
6172   return sortUseListOrder(V, Indexes, Loc);
6173 }
6174
6175 /// ParseUseListOrderBB
6176 ///   ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6177 bool LLParser::ParseUseListOrderBB() {
6178   assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6179   SMLoc Loc = Lex.getLoc();
6180   Lex.Lex();
6181
6182   ValID Fn, Label;
6183   SmallVector<unsigned, 16> Indexes;
6184   if (ParseValID(Fn) ||
6185       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6186       ParseValID(Label) ||
6187       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6188       ParseUseListOrderIndexes(Indexes))
6189     return true;
6190
6191   // Check the function.
6192   GlobalValue *GV;
6193   if (Fn.Kind == ValID::t_GlobalName)
6194     GV = M->getNamedValue(Fn.StrVal);
6195   else if (Fn.Kind == ValID::t_GlobalID)
6196     GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6197   else
6198     return Error(Fn.Loc, "expected function name in uselistorder_bb");
6199   if (!GV)
6200     return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6201   auto *F = dyn_cast<Function>(GV);
6202   if (!F)
6203     return Error(Fn.Loc, "expected function name in uselistorder_bb");
6204   if (F->isDeclaration())
6205     return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6206
6207   // Check the basic block.
6208   if (Label.Kind == ValID::t_LocalID)
6209     return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6210   if (Label.Kind != ValID::t_LocalName)
6211     return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6212   Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6213   if (!V)
6214     return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6215   if (!isa<BasicBlock>(V))
6216     return Error(Label.Loc, "expected basic block in uselistorder_bb");
6217
6218   return sortUseListOrder(V, Indexes, Loc);
6219 }