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