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