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