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