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