1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines the parser class for .ll files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "LLParser.h"
14 #include "LLToken.h"
15 #include "llvm/ADT/APSInt.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/AsmParser/SlotMapping.h"
21 #include "llvm/BinaryFormat/Dwarf.h"
22 #include "llvm/IR/Argument.h"
23 #include "llvm/IR/AutoUpgrade.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/CallingConv.h"
26 #include "llvm/IR/Comdat.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DebugInfoMetadata.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalIFunc.h"
33 #include "llvm/IR/GlobalObject.h"
34 #include "llvm/IR/InlineAsm.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/Value.h"
40 #include "llvm/IR/ValueSymbolTable.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/SaveAndRestore.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include <algorithm>
47 #include <cassert>
48 #include <cstring>
49 #include <iterator>
50 #include <vector>
51 
52 using namespace llvm;
53 
getTypeString(Type * T)54 static std::string getTypeString(Type *T) {
55   std::string Result;
56   raw_string_ostream Tmp(Result);
57   Tmp << *T;
58   return Tmp.str();
59 }
60 
61 /// Run: module ::= toplevelentity*
Run(bool UpgradeDebugInfo,DataLayoutCallbackTy DataLayoutCallback)62 bool LLParser::Run(bool UpgradeDebugInfo,
63                    DataLayoutCallbackTy DataLayoutCallback) {
64   // Prime the lexer.
65   Lex.Lex();
66 
67   if (Context.shouldDiscardValueNames())
68     return error(
69         Lex.getLoc(),
70         "Can't read textual IR with a Context that discards named Values");
71 
72   if (M) {
73     if (parseTargetDefinitions())
74       return true;
75 
76     if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple()))
77       M->setDataLayout(*LayoutOverride);
78   }
79 
80   return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
81          validateEndOfIndex();
82 }
83 
parseStandaloneConstantValue(Constant * & C,const SlotMapping * Slots)84 bool LLParser::parseStandaloneConstantValue(Constant *&C,
85                                             const SlotMapping *Slots) {
86   restoreParsingState(Slots);
87   Lex.Lex();
88 
89   Type *Ty = nullptr;
90   if (parseType(Ty) || parseConstantValue(Ty, C))
91     return true;
92   if (Lex.getKind() != lltok::Eof)
93     return error(Lex.getLoc(), "expected end of string");
94   return false;
95 }
96 
parseTypeAtBeginning(Type * & Ty,unsigned & Read,const SlotMapping * Slots)97 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
98                                     const SlotMapping *Slots) {
99   restoreParsingState(Slots);
100   Lex.Lex();
101 
102   Read = 0;
103   SMLoc Start = Lex.getLoc();
104   Ty = nullptr;
105   if (parseType(Ty))
106     return true;
107   SMLoc End = Lex.getLoc();
108   Read = End.getPointer() - Start.getPointer();
109 
110   return false;
111 }
112 
restoreParsingState(const SlotMapping * Slots)113 void LLParser::restoreParsingState(const SlotMapping *Slots) {
114   if (!Slots)
115     return;
116   NumberedVals = Slots->GlobalValues;
117   NumberedMetadata = Slots->MetadataNodes;
118   for (const auto &I : Slots->NamedTypes)
119     NamedTypes.insert(
120         std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
121   for (const auto &I : Slots->Types)
122     NumberedTypes.insert(
123         std::make_pair(I.first, std::make_pair(I.second, LocTy())));
124 }
125 
126 /// validateEndOfModule - Do final validity and sanity checks at the end of the
127 /// module.
validateEndOfModule(bool UpgradeDebugInfo)128 bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
129   if (!M)
130     return false;
131   // Handle any function attribute group forward references.
132   for (const auto &RAG : ForwardRefAttrGroups) {
133     Value *V = RAG.first;
134     const std::vector<unsigned> &Attrs = RAG.second;
135     AttrBuilder B;
136 
137     for (const auto &Attr : Attrs)
138       B.merge(NumberedAttrBuilders[Attr]);
139 
140     if (Function *Fn = dyn_cast<Function>(V)) {
141       AttributeList AS = Fn->getAttributes();
142       AttrBuilder FnAttrs(AS.getFnAttributes());
143       AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
144 
145       FnAttrs.merge(B);
146 
147       // If the alignment was parsed as an attribute, move to the alignment
148       // field.
149       if (FnAttrs.hasAlignmentAttr()) {
150         Fn->setAlignment(FnAttrs.getAlignment());
151         FnAttrs.removeAttribute(Attribute::Alignment);
152       }
153 
154       AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
155                             AttributeSet::get(Context, FnAttrs));
156       Fn->setAttributes(AS);
157     } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
158       AttributeList AS = CI->getAttributes();
159       AttrBuilder FnAttrs(AS.getFnAttributes());
160       AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
161       FnAttrs.merge(B);
162       AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
163                             AttributeSet::get(Context, FnAttrs));
164       CI->setAttributes(AS);
165     } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
166       AttributeList AS = II->getAttributes();
167       AttrBuilder FnAttrs(AS.getFnAttributes());
168       AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
169       FnAttrs.merge(B);
170       AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
171                             AttributeSet::get(Context, FnAttrs));
172       II->setAttributes(AS);
173     } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
174       AttributeList AS = CBI->getAttributes();
175       AttrBuilder FnAttrs(AS.getFnAttributes());
176       AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
177       FnAttrs.merge(B);
178       AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
179                             AttributeSet::get(Context, FnAttrs));
180       CBI->setAttributes(AS);
181     } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
182       AttrBuilder Attrs(GV->getAttributes());
183       Attrs.merge(B);
184       GV->setAttributes(AttributeSet::get(Context,Attrs));
185     } else {
186       llvm_unreachable("invalid object with forward attribute group reference");
187     }
188   }
189 
190   // If there are entries in ForwardRefBlockAddresses at this point, the
191   // function was never defined.
192   if (!ForwardRefBlockAddresses.empty())
193     return error(ForwardRefBlockAddresses.begin()->first.Loc,
194                  "expected function name in blockaddress");
195 
196   for (const auto &NT : NumberedTypes)
197     if (NT.second.second.isValid())
198       return error(NT.second.second,
199                    "use of undefined type '%" + Twine(NT.first) + "'");
200 
201   for (StringMap<std::pair<Type*, LocTy> >::iterator I =
202        NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
203     if (I->second.second.isValid())
204       return error(I->second.second,
205                    "use of undefined type named '" + I->getKey() + "'");
206 
207   if (!ForwardRefComdats.empty())
208     return error(ForwardRefComdats.begin()->second,
209                  "use of undefined comdat '$" +
210                      ForwardRefComdats.begin()->first + "'");
211 
212   if (!ForwardRefVals.empty())
213     return error(ForwardRefVals.begin()->second.second,
214                  "use of undefined value '@" + ForwardRefVals.begin()->first +
215                      "'");
216 
217   if (!ForwardRefValIDs.empty())
218     return error(ForwardRefValIDs.begin()->second.second,
219                  "use of undefined value '@" +
220                      Twine(ForwardRefValIDs.begin()->first) + "'");
221 
222   if (!ForwardRefMDNodes.empty())
223     return error(ForwardRefMDNodes.begin()->second.second,
224                  "use of undefined metadata '!" +
225                      Twine(ForwardRefMDNodes.begin()->first) + "'");
226 
227   // Resolve metadata cycles.
228   for (auto &N : NumberedMetadata) {
229     if (N.second && !N.second->isResolved())
230       N.second->resolveCycles();
231   }
232 
233   for (auto *Inst : InstsWithTBAATag) {
234     MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
235     assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
236     auto *UpgradedMD = UpgradeTBAANode(*MD);
237     if (MD != UpgradedMD)
238       Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
239   }
240 
241   // Look for intrinsic functions and CallInst that need to be upgraded
242   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
243     UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
244 
245   // Some types could be renamed during loading if several modules are
246   // loaded in the same LLVMContext (LTO scenario). In this case we should
247   // remangle intrinsics names as well.
248   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
249     Function *F = &*FI++;
250     if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
251       F->replaceAllUsesWith(Remangled.getValue());
252       F->eraseFromParent();
253     }
254   }
255 
256   if (UpgradeDebugInfo)
257     llvm::UpgradeDebugInfo(*M);
258 
259   UpgradeModuleFlags(*M);
260   UpgradeSectionAttributes(*M);
261 
262   if (!Slots)
263     return false;
264   // Initialize the slot mapping.
265   // Because by this point we've parsed and validated everything, we can "steal"
266   // the mapping from LLParser as it doesn't need it anymore.
267   Slots->GlobalValues = std::move(NumberedVals);
268   Slots->MetadataNodes = std::move(NumberedMetadata);
269   for (const auto &I : NamedTypes)
270     Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
271   for (const auto &I : NumberedTypes)
272     Slots->Types.insert(std::make_pair(I.first, I.second.first));
273 
274   return false;
275 }
276 
277 /// Do final validity and sanity checks at the end of the index.
validateEndOfIndex()278 bool LLParser::validateEndOfIndex() {
279   if (!Index)
280     return false;
281 
282   if (!ForwardRefValueInfos.empty())
283     return error(ForwardRefValueInfos.begin()->second.front().second,
284                  "use of undefined summary '^" +
285                      Twine(ForwardRefValueInfos.begin()->first) + "'");
286 
287   if (!ForwardRefAliasees.empty())
288     return error(ForwardRefAliasees.begin()->second.front().second,
289                  "use of undefined summary '^" +
290                      Twine(ForwardRefAliasees.begin()->first) + "'");
291 
292   if (!ForwardRefTypeIds.empty())
293     return error(ForwardRefTypeIds.begin()->second.front().second,
294                  "use of undefined type id summary '^" +
295                      Twine(ForwardRefTypeIds.begin()->first) + "'");
296 
297   return false;
298 }
299 
300 //===----------------------------------------------------------------------===//
301 // Top-Level Entities
302 //===----------------------------------------------------------------------===//
303 
parseTargetDefinitions()304 bool LLParser::parseTargetDefinitions() {
305   while (true) {
306     switch (Lex.getKind()) {
307     case lltok::kw_target:
308       if (parseTargetDefinition())
309         return true;
310       break;
311     case lltok::kw_source_filename:
312       if (parseSourceFileName())
313         return true;
314       break;
315     default:
316       return false;
317     }
318   }
319 }
320 
parseTopLevelEntities()321 bool LLParser::parseTopLevelEntities() {
322   // If there is no Module, then parse just the summary index entries.
323   if (!M) {
324     while (true) {
325       switch (Lex.getKind()) {
326       case lltok::Eof:
327         return false;
328       case lltok::SummaryID:
329         if (parseSummaryEntry())
330           return true;
331         break;
332       case lltok::kw_source_filename:
333         if (parseSourceFileName())
334           return true;
335         break;
336       default:
337         // Skip everything else
338         Lex.Lex();
339       }
340     }
341   }
342   while (true) {
343     switch (Lex.getKind()) {
344     default:
345       return tokError("expected top-level entity");
346     case lltok::Eof: return false;
347     case lltok::kw_declare:
348       if (parseDeclare())
349         return true;
350       break;
351     case lltok::kw_define:
352       if (parseDefine())
353         return true;
354       break;
355     case lltok::kw_module:
356       if (parseModuleAsm())
357         return true;
358       break;
359     case lltok::kw_deplibs:
360       if (parseDepLibs())
361         return true;
362       break;
363     case lltok::LocalVarID:
364       if (parseUnnamedType())
365         return true;
366       break;
367     case lltok::LocalVar:
368       if (parseNamedType())
369         return true;
370       break;
371     case lltok::GlobalID:
372       if (parseUnnamedGlobal())
373         return true;
374       break;
375     case lltok::GlobalVar:
376       if (parseNamedGlobal())
377         return true;
378       break;
379     case lltok::ComdatVar:  if (parseComdat()) return true; break;
380     case lltok::exclaim:
381       if (parseStandaloneMetadata())
382         return true;
383       break;
384     case lltok::SummaryID:
385       if (parseSummaryEntry())
386         return true;
387       break;
388     case lltok::MetadataVar:
389       if (parseNamedMetadata())
390         return true;
391       break;
392     case lltok::kw_attributes:
393       if (parseUnnamedAttrGrp())
394         return true;
395       break;
396     case lltok::kw_uselistorder:
397       if (parseUseListOrder())
398         return true;
399       break;
400     case lltok::kw_uselistorder_bb:
401       if (parseUseListOrderBB())
402         return true;
403       break;
404     }
405   }
406 }
407 
408 /// toplevelentity
409 ///   ::= 'module' 'asm' STRINGCONSTANT
parseModuleAsm()410 bool LLParser::parseModuleAsm() {
411   assert(Lex.getKind() == lltok::kw_module);
412   Lex.Lex();
413 
414   std::string AsmStr;
415   if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
416       parseStringConstant(AsmStr))
417     return true;
418 
419   M->appendModuleInlineAsm(AsmStr);
420   return false;
421 }
422 
423 /// toplevelentity
424 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
425 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
parseTargetDefinition()426 bool LLParser::parseTargetDefinition() {
427   assert(Lex.getKind() == lltok::kw_target);
428   std::string Str;
429   switch (Lex.Lex()) {
430   default:
431     return tokError("unknown target property");
432   case lltok::kw_triple:
433     Lex.Lex();
434     if (parseToken(lltok::equal, "expected '=' after target triple") ||
435         parseStringConstant(Str))
436       return true;
437     M->setTargetTriple(Str);
438     return false;
439   case lltok::kw_datalayout:
440     Lex.Lex();
441     if (parseToken(lltok::equal, "expected '=' after target datalayout") ||
442         parseStringConstant(Str))
443       return true;
444     M->setDataLayout(Str);
445     return false;
446   }
447 }
448 
449 /// toplevelentity
450 ///   ::= 'source_filename' '=' STRINGCONSTANT
parseSourceFileName()451 bool LLParser::parseSourceFileName() {
452   assert(Lex.getKind() == lltok::kw_source_filename);
453   Lex.Lex();
454   if (parseToken(lltok::equal, "expected '=' after source_filename") ||
455       parseStringConstant(SourceFileName))
456     return true;
457   if (M)
458     M->setSourceFileName(SourceFileName);
459   return false;
460 }
461 
462 /// toplevelentity
463 ///   ::= 'deplibs' '=' '[' ']'
464 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
465 /// FIXME: Remove in 4.0. Currently parse, but ignore.
parseDepLibs()466 bool LLParser::parseDepLibs() {
467   assert(Lex.getKind() == lltok::kw_deplibs);
468   Lex.Lex();
469   if (parseToken(lltok::equal, "expected '=' after deplibs") ||
470       parseToken(lltok::lsquare, "expected '=' after deplibs"))
471     return true;
472 
473   if (EatIfPresent(lltok::rsquare))
474     return false;
475 
476   do {
477     std::string Str;
478     if (parseStringConstant(Str))
479       return true;
480   } while (EatIfPresent(lltok::comma));
481 
482   return parseToken(lltok::rsquare, "expected ']' at end of list");
483 }
484 
485 /// parseUnnamedType:
486 ///   ::= LocalVarID '=' 'type' type
parseUnnamedType()487 bool LLParser::parseUnnamedType() {
488   LocTy TypeLoc = Lex.getLoc();
489   unsigned TypeID = Lex.getUIntVal();
490   Lex.Lex(); // eat LocalVarID;
491 
492   if (parseToken(lltok::equal, "expected '=' after name") ||
493       parseToken(lltok::kw_type, "expected 'type' after '='"))
494     return true;
495 
496   Type *Result = nullptr;
497   if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
498     return true;
499 
500   if (!isa<StructType>(Result)) {
501     std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
502     if (Entry.first)
503       return error(TypeLoc, "non-struct types may not be recursive");
504     Entry.first = Result;
505     Entry.second = SMLoc();
506   }
507 
508   return false;
509 }
510 
511 /// toplevelentity
512 ///   ::= LocalVar '=' 'type' type
parseNamedType()513 bool LLParser::parseNamedType() {
514   std::string Name = Lex.getStrVal();
515   LocTy NameLoc = Lex.getLoc();
516   Lex.Lex();  // eat LocalVar.
517 
518   if (parseToken(lltok::equal, "expected '=' after name") ||
519       parseToken(lltok::kw_type, "expected 'type' after name"))
520     return true;
521 
522   Type *Result = nullptr;
523   if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
524     return true;
525 
526   if (!isa<StructType>(Result)) {
527     std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
528     if (Entry.first)
529       return error(NameLoc, "non-struct types may not be recursive");
530     Entry.first = Result;
531     Entry.second = SMLoc();
532   }
533 
534   return false;
535 }
536 
537 /// toplevelentity
538 ///   ::= 'declare' FunctionHeader
parseDeclare()539 bool LLParser::parseDeclare() {
540   assert(Lex.getKind() == lltok::kw_declare);
541   Lex.Lex();
542 
543   std::vector<std::pair<unsigned, MDNode *>> MDs;
544   while (Lex.getKind() == lltok::MetadataVar) {
545     unsigned MDK;
546     MDNode *N;
547     if (parseMetadataAttachment(MDK, N))
548       return true;
549     MDs.push_back({MDK, N});
550   }
551 
552   Function *F;
553   if (parseFunctionHeader(F, false))
554     return true;
555   for (auto &MD : MDs)
556     F->addMetadata(MD.first, *MD.second);
557   return false;
558 }
559 
560 /// toplevelentity
561 ///   ::= 'define' FunctionHeader (!dbg !56)* '{' ...
parseDefine()562 bool LLParser::parseDefine() {
563   assert(Lex.getKind() == lltok::kw_define);
564   Lex.Lex();
565 
566   Function *F;
567   return parseFunctionHeader(F, true) || parseOptionalFunctionMetadata(*F) ||
568          parseFunctionBody(*F);
569 }
570 
571 /// parseGlobalType
572 ///   ::= 'constant'
573 ///   ::= 'global'
parseGlobalType(bool & IsConstant)574 bool LLParser::parseGlobalType(bool &IsConstant) {
575   if (Lex.getKind() == lltok::kw_constant)
576     IsConstant = true;
577   else if (Lex.getKind() == lltok::kw_global)
578     IsConstant = false;
579   else {
580     IsConstant = false;
581     return tokError("expected 'global' or 'constant'");
582   }
583   Lex.Lex();
584   return false;
585 }
586 
parseOptionalUnnamedAddr(GlobalVariable::UnnamedAddr & UnnamedAddr)587 bool LLParser::parseOptionalUnnamedAddr(
588     GlobalVariable::UnnamedAddr &UnnamedAddr) {
589   if (EatIfPresent(lltok::kw_unnamed_addr))
590     UnnamedAddr = GlobalValue::UnnamedAddr::Global;
591   else if (EatIfPresent(lltok::kw_local_unnamed_addr))
592     UnnamedAddr = GlobalValue::UnnamedAddr::Local;
593   else
594     UnnamedAddr = GlobalValue::UnnamedAddr::None;
595   return false;
596 }
597 
598 /// parseUnnamedGlobal:
599 ///   OptionalVisibility (ALIAS | IFUNC) ...
600 ///   OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
601 ///   OptionalDLLStorageClass
602 ///                                                     ...   -> global variable
603 ///   GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
604 ///   GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
605 ///   OptionalVisibility
606 ///                OptionalDLLStorageClass
607 ///                                                     ...   -> global variable
parseUnnamedGlobal()608 bool LLParser::parseUnnamedGlobal() {
609   unsigned VarID = NumberedVals.size();
610   std::string Name;
611   LocTy NameLoc = Lex.getLoc();
612 
613   // Handle the GlobalID form.
614   if (Lex.getKind() == lltok::GlobalID) {
615     if (Lex.getUIntVal() != VarID)
616       return error(Lex.getLoc(),
617                    "variable expected to be numbered '%" + Twine(VarID) + "'");
618     Lex.Lex(); // eat GlobalID;
619 
620     if (parseToken(lltok::equal, "expected '=' after name"))
621       return true;
622   }
623 
624   bool HasLinkage;
625   unsigned Linkage, Visibility, DLLStorageClass;
626   bool DSOLocal;
627   GlobalVariable::ThreadLocalMode TLM;
628   GlobalVariable::UnnamedAddr UnnamedAddr;
629   if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
630                            DSOLocal) ||
631       parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
632     return true;
633 
634   if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
635     return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
636                        DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
637 
638   return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
639                              DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
640 }
641 
642 /// parseNamedGlobal:
643 ///   GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
644 ///   GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
645 ///                 OptionalVisibility OptionalDLLStorageClass
646 ///                                                     ...   -> global variable
parseNamedGlobal()647 bool LLParser::parseNamedGlobal() {
648   assert(Lex.getKind() == lltok::GlobalVar);
649   LocTy NameLoc = Lex.getLoc();
650   std::string Name = Lex.getStrVal();
651   Lex.Lex();
652 
653   bool HasLinkage;
654   unsigned Linkage, Visibility, DLLStorageClass;
655   bool DSOLocal;
656   GlobalVariable::ThreadLocalMode TLM;
657   GlobalVariable::UnnamedAddr UnnamedAddr;
658   if (parseToken(lltok::equal, "expected '=' in global variable") ||
659       parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
660                            DSOLocal) ||
661       parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
662     return true;
663 
664   if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
665     return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
666                        DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
667 
668   return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
669                              DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
670 }
671 
parseComdat()672 bool LLParser::parseComdat() {
673   assert(Lex.getKind() == lltok::ComdatVar);
674   std::string Name = Lex.getStrVal();
675   LocTy NameLoc = Lex.getLoc();
676   Lex.Lex();
677 
678   if (parseToken(lltok::equal, "expected '=' here"))
679     return true;
680 
681   if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
682     return tokError("expected comdat type");
683 
684   Comdat::SelectionKind SK;
685   switch (Lex.getKind()) {
686   default:
687     return tokError("unknown selection kind");
688   case lltok::kw_any:
689     SK = Comdat::Any;
690     break;
691   case lltok::kw_exactmatch:
692     SK = Comdat::ExactMatch;
693     break;
694   case lltok::kw_largest:
695     SK = Comdat::Largest;
696     break;
697   case lltok::kw_noduplicates:
698     SK = Comdat::NoDuplicates;
699     break;
700   case lltok::kw_samesize:
701     SK = Comdat::SameSize;
702     break;
703   }
704   Lex.Lex();
705 
706   // See if the comdat was forward referenced, if so, use the comdat.
707   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
708   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
709   if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
710     return error(NameLoc, "redefinition of comdat '$" + Name + "'");
711 
712   Comdat *C;
713   if (I != ComdatSymTab.end())
714     C = &I->second;
715   else
716     C = M->getOrInsertComdat(Name);
717   C->setSelectionKind(SK);
718 
719   return false;
720 }
721 
722 // MDString:
723 //   ::= '!' STRINGCONSTANT
parseMDString(MDString * & Result)724 bool LLParser::parseMDString(MDString *&Result) {
725   std::string Str;
726   if (parseStringConstant(Str))
727     return true;
728   Result = MDString::get(Context, Str);
729   return false;
730 }
731 
732 // MDNode:
733 //   ::= '!' MDNodeNumber
parseMDNodeID(MDNode * & Result)734 bool LLParser::parseMDNodeID(MDNode *&Result) {
735   // !{ ..., !42, ... }
736   LocTy IDLoc = Lex.getLoc();
737   unsigned MID = 0;
738   if (parseUInt32(MID))
739     return true;
740 
741   // If not a forward reference, just return it now.
742   if (NumberedMetadata.count(MID)) {
743     Result = NumberedMetadata[MID];
744     return false;
745   }
746 
747   // Otherwise, create MDNode forward reference.
748   auto &FwdRef = ForwardRefMDNodes[MID];
749   FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
750 
751   Result = FwdRef.first.get();
752   NumberedMetadata[MID].reset(Result);
753   return false;
754 }
755 
756 /// parseNamedMetadata:
757 ///   !foo = !{ !1, !2 }
parseNamedMetadata()758 bool LLParser::parseNamedMetadata() {
759   assert(Lex.getKind() == lltok::MetadataVar);
760   std::string Name = Lex.getStrVal();
761   Lex.Lex();
762 
763   if (parseToken(lltok::equal, "expected '=' here") ||
764       parseToken(lltok::exclaim, "Expected '!' here") ||
765       parseToken(lltok::lbrace, "Expected '{' here"))
766     return true;
767 
768   NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
769   if (Lex.getKind() != lltok::rbrace)
770     do {
771       MDNode *N = nullptr;
772       // parse DIExpressions inline as a special case. They are still MDNodes,
773       // so they can still appear in named metadata. Remove this logic if they
774       // become plain Metadata.
775       if (Lex.getKind() == lltok::MetadataVar &&
776           Lex.getStrVal() == "DIExpression") {
777         if (parseDIExpression(N, /*IsDistinct=*/false))
778           return true;
779       } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
780                  parseMDNodeID(N)) {
781         return true;
782       }
783       NMD->addOperand(N);
784     } while (EatIfPresent(lltok::comma));
785 
786   return parseToken(lltok::rbrace, "expected end of metadata node");
787 }
788 
789 /// parseStandaloneMetadata:
790 ///   !42 = !{...}
parseStandaloneMetadata()791 bool LLParser::parseStandaloneMetadata() {
792   assert(Lex.getKind() == lltok::exclaim);
793   Lex.Lex();
794   unsigned MetadataID = 0;
795 
796   MDNode *Init;
797   if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
798     return true;
799 
800   // Detect common error, from old metadata syntax.
801   if (Lex.getKind() == lltok::Type)
802     return tokError("unexpected type in metadata definition");
803 
804   bool IsDistinct = EatIfPresent(lltok::kw_distinct);
805   if (Lex.getKind() == lltok::MetadataVar) {
806     if (parseSpecializedMDNode(Init, IsDistinct))
807       return true;
808   } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
809              parseMDTuple(Init, IsDistinct))
810     return true;
811 
812   // See if this was forward referenced, if so, handle it.
813   auto FI = ForwardRefMDNodes.find(MetadataID);
814   if (FI != ForwardRefMDNodes.end()) {
815     FI->second.first->replaceAllUsesWith(Init);
816     ForwardRefMDNodes.erase(FI);
817 
818     assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
819   } else {
820     if (NumberedMetadata.count(MetadataID))
821       return tokError("Metadata id is already used");
822     NumberedMetadata[MetadataID].reset(Init);
823   }
824 
825   return false;
826 }
827 
828 // Skips a single module summary entry.
skipModuleSummaryEntry()829 bool LLParser::skipModuleSummaryEntry() {
830   // Each module summary entry consists of a tag for the entry
831   // type, followed by a colon, then the fields which may be surrounded by
832   // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
833   // support is in place we will look for the tokens corresponding to the
834   // expected tags.
835   if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
836       Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
837       Lex.getKind() != lltok::kw_blockcount)
838     return tokError(
839         "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
840         "start of summary entry");
841   if (Lex.getKind() == lltok::kw_flags)
842     return parseSummaryIndexFlags();
843   if (Lex.getKind() == lltok::kw_blockcount)
844     return parseBlockCount();
845   Lex.Lex();
846   if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
847       parseToken(lltok::lparen, "expected '(' at start of summary entry"))
848     return true;
849   // Now walk through the parenthesized entry, until the number of open
850   // parentheses goes back down to 0 (the first '(' was parsed above).
851   unsigned NumOpenParen = 1;
852   do {
853     switch (Lex.getKind()) {
854     case lltok::lparen:
855       NumOpenParen++;
856       break;
857     case lltok::rparen:
858       NumOpenParen--;
859       break;
860     case lltok::Eof:
861       return tokError("found end of file while parsing summary entry");
862     default:
863       // Skip everything in between parentheses.
864       break;
865     }
866     Lex.Lex();
867   } while (NumOpenParen > 0);
868   return false;
869 }
870 
871 /// SummaryEntry
872 ///   ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
parseSummaryEntry()873 bool LLParser::parseSummaryEntry() {
874   assert(Lex.getKind() == lltok::SummaryID);
875   unsigned SummaryID = Lex.getUIntVal();
876 
877   // For summary entries, colons should be treated as distinct tokens,
878   // not an indication of the end of a label token.
879   Lex.setIgnoreColonInIdentifiers(true);
880 
881   Lex.Lex();
882   if (parseToken(lltok::equal, "expected '=' here"))
883     return true;
884 
885   // If we don't have an index object, skip the summary entry.
886   if (!Index)
887     return skipModuleSummaryEntry();
888 
889   bool result = false;
890   switch (Lex.getKind()) {
891   case lltok::kw_gv:
892     result = parseGVEntry(SummaryID);
893     break;
894   case lltok::kw_module:
895     result = parseModuleEntry(SummaryID);
896     break;
897   case lltok::kw_typeid:
898     result = parseTypeIdEntry(SummaryID);
899     break;
900   case lltok::kw_typeidCompatibleVTable:
901     result = parseTypeIdCompatibleVtableEntry(SummaryID);
902     break;
903   case lltok::kw_flags:
904     result = parseSummaryIndexFlags();
905     break;
906   case lltok::kw_blockcount:
907     result = parseBlockCount();
908     break;
909   default:
910     result = error(Lex.getLoc(), "unexpected summary kind");
911     break;
912   }
913   Lex.setIgnoreColonInIdentifiers(false);
914   return result;
915 }
916 
isValidVisibilityForLinkage(unsigned V,unsigned L)917 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
918   return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
919          (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
920 }
921 
922 // If there was an explicit dso_local, update GV. In the absence of an explicit
923 // dso_local we keep the default value.
maybeSetDSOLocal(bool DSOLocal,GlobalValue & GV)924 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
925   if (DSOLocal)
926     GV.setDSOLocal(true);
927 }
928 
929 /// parseIndirectSymbol:
930 ///   ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
931 ///                     OptionalVisibility OptionalDLLStorageClass
932 ///                     OptionalThreadLocal OptionalUnnamedAddr
933 ///                     'alias|ifunc' IndirectSymbol IndirectSymbolAttr*
934 ///
935 /// IndirectSymbol
936 ///   ::= TypeAndValue
937 ///
938 /// IndirectSymbolAttr
939 ///   ::= ',' 'partition' StringConstant
940 ///
941 /// Everything through OptionalUnnamedAddr has already been parsed.
942 ///
parseIndirectSymbol(const std::string & Name,LocTy NameLoc,unsigned L,unsigned Visibility,unsigned DLLStorageClass,bool DSOLocal,GlobalVariable::ThreadLocalMode TLM,GlobalVariable::UnnamedAddr UnnamedAddr)943 bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
944                                    unsigned L, unsigned Visibility,
945                                    unsigned DLLStorageClass, bool DSOLocal,
946                                    GlobalVariable::ThreadLocalMode TLM,
947                                    GlobalVariable::UnnamedAddr UnnamedAddr) {
948   bool IsAlias;
949   if (Lex.getKind() == lltok::kw_alias)
950     IsAlias = true;
951   else if (Lex.getKind() == lltok::kw_ifunc)
952     IsAlias = false;
953   else
954     llvm_unreachable("Not an alias or ifunc!");
955   Lex.Lex();
956 
957   GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
958 
959   if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
960     return error(NameLoc, "invalid linkage type for alias");
961 
962   if (!isValidVisibilityForLinkage(Visibility, L))
963     return error(NameLoc,
964                  "symbol with local linkage must have default visibility");
965 
966   Type *Ty;
967   LocTy ExplicitTypeLoc = Lex.getLoc();
968   if (parseType(Ty) ||
969       parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
970     return true;
971 
972   Constant *Aliasee;
973   LocTy AliaseeLoc = Lex.getLoc();
974   if (Lex.getKind() != lltok::kw_bitcast &&
975       Lex.getKind() != lltok::kw_getelementptr &&
976       Lex.getKind() != lltok::kw_addrspacecast &&
977       Lex.getKind() != lltok::kw_inttoptr) {
978     if (parseGlobalTypeAndValue(Aliasee))
979       return true;
980   } else {
981     // The bitcast dest type is not present, it is implied by the dest type.
982     ValID ID;
983     if (parseValID(ID))
984       return true;
985     if (ID.Kind != ValID::t_Constant)
986       return error(AliaseeLoc, "invalid aliasee");
987     Aliasee = ID.ConstantVal;
988   }
989 
990   Type *AliaseeType = Aliasee->getType();
991   auto *PTy = dyn_cast<PointerType>(AliaseeType);
992   if (!PTy)
993     return error(AliaseeLoc, "An alias or ifunc must have pointer type");
994   unsigned AddrSpace = PTy->getAddressSpace();
995 
996   if (IsAlias && Ty != PTy->getElementType())
997     return error(ExplicitTypeLoc,
998                  "explicit pointee type doesn't match operand's pointee type");
999 
1000   if (!IsAlias && !PTy->getElementType()->isFunctionTy())
1001     return error(ExplicitTypeLoc,
1002                  "explicit pointee type should be a function type");
1003 
1004   GlobalValue *GVal = nullptr;
1005 
1006   // See if the alias was forward referenced, if so, prepare to replace the
1007   // forward reference.
1008   if (!Name.empty()) {
1009     GVal = M->getNamedValue(Name);
1010     if (GVal) {
1011       if (!ForwardRefVals.erase(Name))
1012         return error(NameLoc, "redefinition of global '@" + Name + "'");
1013     }
1014   } else {
1015     auto I = ForwardRefValIDs.find(NumberedVals.size());
1016     if (I != ForwardRefValIDs.end()) {
1017       GVal = I->second.first;
1018       ForwardRefValIDs.erase(I);
1019     }
1020   }
1021 
1022   // Okay, create the alias but do not insert it into the module yet.
1023   std::unique_ptr<GlobalIndirectSymbol> GA;
1024   if (IsAlias)
1025     GA.reset(GlobalAlias::create(Ty, AddrSpace,
1026                                  (GlobalValue::LinkageTypes)Linkage, Name,
1027                                  Aliasee, /*Parent*/ nullptr));
1028   else
1029     GA.reset(GlobalIFunc::create(Ty, AddrSpace,
1030                                  (GlobalValue::LinkageTypes)Linkage, Name,
1031                                  Aliasee, /*Parent*/ nullptr));
1032   GA->setThreadLocalMode(TLM);
1033   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1034   GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1035   GA->setUnnamedAddr(UnnamedAddr);
1036   maybeSetDSOLocal(DSOLocal, *GA);
1037 
1038   // At this point we've parsed everything except for the IndirectSymbolAttrs.
1039   // Now parse them if there are any.
1040   while (Lex.getKind() == lltok::comma) {
1041     Lex.Lex();
1042 
1043     if (Lex.getKind() == lltok::kw_partition) {
1044       Lex.Lex();
1045       GA->setPartition(Lex.getStrVal());
1046       if (parseToken(lltok::StringConstant, "expected partition string"))
1047         return true;
1048     } else {
1049       return tokError("unknown alias or ifunc property!");
1050     }
1051   }
1052 
1053   if (Name.empty())
1054     NumberedVals.push_back(GA.get());
1055 
1056   if (GVal) {
1057     // Verify that types agree.
1058     if (GVal->getType() != GA->getType())
1059       return error(
1060           ExplicitTypeLoc,
1061           "forward reference and definition of alias have different types");
1062 
1063     // If they agree, just RAUW the old value with the alias and remove the
1064     // forward ref info.
1065     GVal->replaceAllUsesWith(GA.get());
1066     GVal->eraseFromParent();
1067   }
1068 
1069   // Insert into the module, we know its name won't collide now.
1070   if (IsAlias)
1071     M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
1072   else
1073     M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
1074   assert(GA->getName() == Name && "Should not be a name conflict!");
1075 
1076   // The module owns this now
1077   GA.release();
1078 
1079   return false;
1080 }
1081 
1082 /// parseGlobal
1083 ///   ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1084 ///       OptionalVisibility OptionalDLLStorageClass
1085 ///       OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1086 ///       OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1087 ///   ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1088 ///       OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1089 ///       OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1090 ///       Const OptionalAttrs
1091 ///
1092 /// Everything up to and including OptionalUnnamedAddr has been parsed
1093 /// already.
1094 ///
parseGlobal(const std::string & Name,LocTy NameLoc,unsigned Linkage,bool HasLinkage,unsigned Visibility,unsigned DLLStorageClass,bool DSOLocal,GlobalVariable::ThreadLocalMode TLM,GlobalVariable::UnnamedAddr UnnamedAddr)1095 bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc,
1096                            unsigned Linkage, bool HasLinkage,
1097                            unsigned Visibility, unsigned DLLStorageClass,
1098                            bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1099                            GlobalVariable::UnnamedAddr UnnamedAddr) {
1100   if (!isValidVisibilityForLinkage(Visibility, Linkage))
1101     return error(NameLoc,
1102                  "symbol with local linkage must have default visibility");
1103 
1104   unsigned AddrSpace;
1105   bool IsConstant, IsExternallyInitialized;
1106   LocTy IsExternallyInitializedLoc;
1107   LocTy TyLoc;
1108 
1109   Type *Ty = nullptr;
1110   if (parseOptionalAddrSpace(AddrSpace) ||
1111       parseOptionalToken(lltok::kw_externally_initialized,
1112                          IsExternallyInitialized,
1113                          &IsExternallyInitializedLoc) ||
1114       parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1115     return true;
1116 
1117   // If the linkage is specified and is external, then no initializer is
1118   // present.
1119   Constant *Init = nullptr;
1120   if (!HasLinkage ||
1121       !GlobalValue::isValidDeclarationLinkage(
1122           (GlobalValue::LinkageTypes)Linkage)) {
1123     if (parseGlobalValue(Ty, Init))
1124       return true;
1125   }
1126 
1127   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
1128     return error(TyLoc, "invalid type for global variable");
1129 
1130   GlobalValue *GVal = nullptr;
1131 
1132   // See if the global was forward referenced, if so, use the global.
1133   if (!Name.empty()) {
1134     GVal = M->getNamedValue(Name);
1135     if (GVal) {
1136       if (!ForwardRefVals.erase(Name))
1137         return error(NameLoc, "redefinition of global '@" + Name + "'");
1138     }
1139   } else {
1140     auto I = ForwardRefValIDs.find(NumberedVals.size());
1141     if (I != ForwardRefValIDs.end()) {
1142       GVal = I->second.first;
1143       ForwardRefValIDs.erase(I);
1144     }
1145   }
1146 
1147   GlobalVariable *GV;
1148   if (!GVal) {
1149     GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1150                             Name, nullptr, GlobalVariable::NotThreadLocal,
1151                             AddrSpace);
1152   } else {
1153     if (GVal->getValueType() != Ty)
1154       return error(
1155           TyLoc,
1156           "forward reference and definition of global have different types");
1157 
1158     GV = cast<GlobalVariable>(GVal);
1159 
1160     // Move the forward-reference to the correct spot in the module.
1161     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1162   }
1163 
1164   if (Name.empty())
1165     NumberedVals.push_back(GV);
1166 
1167   // Set the parsed properties on the global.
1168   if (Init)
1169     GV->setInitializer(Init);
1170   GV->setConstant(IsConstant);
1171   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1172   maybeSetDSOLocal(DSOLocal, *GV);
1173   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1174   GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1175   GV->setExternallyInitialized(IsExternallyInitialized);
1176   GV->setThreadLocalMode(TLM);
1177   GV->setUnnamedAddr(UnnamedAddr);
1178 
1179   // parse attributes on the global.
1180   while (Lex.getKind() == lltok::comma) {
1181     Lex.Lex();
1182 
1183     if (Lex.getKind() == lltok::kw_section) {
1184       Lex.Lex();
1185       GV->setSection(Lex.getStrVal());
1186       if (parseToken(lltok::StringConstant, "expected global section string"))
1187         return true;
1188     } else if (Lex.getKind() == lltok::kw_partition) {
1189       Lex.Lex();
1190       GV->setPartition(Lex.getStrVal());
1191       if (parseToken(lltok::StringConstant, "expected partition string"))
1192         return true;
1193     } else if (Lex.getKind() == lltok::kw_align) {
1194       MaybeAlign Alignment;
1195       if (parseOptionalAlignment(Alignment))
1196         return true;
1197       GV->setAlignment(Alignment);
1198     } else if (Lex.getKind() == lltok::MetadataVar) {
1199       if (parseGlobalObjectMetadataAttachment(*GV))
1200         return true;
1201     } else {
1202       Comdat *C;
1203       if (parseOptionalComdat(Name, C))
1204         return true;
1205       if (C)
1206         GV->setComdat(C);
1207       else
1208         return tokError("unknown global variable property!");
1209     }
1210   }
1211 
1212   AttrBuilder Attrs;
1213   LocTy BuiltinLoc;
1214   std::vector<unsigned> FwdRefAttrGrps;
1215   if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1216     return true;
1217   if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1218     GV->setAttributes(AttributeSet::get(Context, Attrs));
1219     ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1220   }
1221 
1222   return false;
1223 }
1224 
1225 /// parseUnnamedAttrGrp
1226 ///   ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
parseUnnamedAttrGrp()1227 bool LLParser::parseUnnamedAttrGrp() {
1228   assert(Lex.getKind() == lltok::kw_attributes);
1229   LocTy AttrGrpLoc = Lex.getLoc();
1230   Lex.Lex();
1231 
1232   if (Lex.getKind() != lltok::AttrGrpID)
1233     return tokError("expected attribute group id");
1234 
1235   unsigned VarID = Lex.getUIntVal();
1236   std::vector<unsigned> unused;
1237   LocTy BuiltinLoc;
1238   Lex.Lex();
1239 
1240   if (parseToken(lltok::equal, "expected '=' here") ||
1241       parseToken(lltok::lbrace, "expected '{' here") ||
1242       parseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
1243                                  BuiltinLoc) ||
1244       parseToken(lltok::rbrace, "expected end of attribute group"))
1245     return true;
1246 
1247   if (!NumberedAttrBuilders[VarID].hasAttributes())
1248     return error(AttrGrpLoc, "attribute group has no attributes");
1249 
1250   return false;
1251 }
1252 
1253 /// parseFnAttributeValuePairs
1254 ///   ::= <attr> | <attr> '=' <value>
parseFnAttributeValuePairs(AttrBuilder & B,std::vector<unsigned> & FwdRefAttrGrps,bool inAttrGrp,LocTy & BuiltinLoc)1255 bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1256                                           std::vector<unsigned> &FwdRefAttrGrps,
1257                                           bool inAttrGrp, LocTy &BuiltinLoc) {
1258   bool HaveError = false;
1259 
1260   B.clear();
1261 
1262   while (true) {
1263     lltok::Kind Token = Lex.getKind();
1264     if (Token == lltok::kw_builtin)
1265       BuiltinLoc = Lex.getLoc();
1266     switch (Token) {
1267     default:
1268       if (!inAttrGrp) return HaveError;
1269       return error(Lex.getLoc(), "unterminated attribute group");
1270     case lltok::rbrace:
1271       // Finished.
1272       return false;
1273 
1274     case lltok::AttrGrpID: {
1275       // Allow a function to reference an attribute group:
1276       //
1277       //   define void @foo() #1 { ... }
1278       if (inAttrGrp)
1279         HaveError |= error(
1280             Lex.getLoc(),
1281             "cannot have an attribute group reference in an attribute group");
1282 
1283       unsigned AttrGrpNum = Lex.getUIntVal();
1284       if (inAttrGrp) break;
1285 
1286       // Save the reference to the attribute group. We'll fill it in later.
1287       FwdRefAttrGrps.push_back(AttrGrpNum);
1288       break;
1289     }
1290     // Target-dependent attributes:
1291     case lltok::StringConstant: {
1292       if (parseStringAttribute(B))
1293         return true;
1294       continue;
1295     }
1296 
1297     // Target-independent attributes:
1298     case lltok::kw_align: {
1299       // As a hack, we allow function alignment to be initially parsed as an
1300       // attribute on a function declaration/definition or added to an attribute
1301       // group and later moved to the alignment field.
1302       MaybeAlign Alignment;
1303       if (inAttrGrp) {
1304         Lex.Lex();
1305         uint32_t Value = 0;
1306         if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1307           return true;
1308         Alignment = Align(Value);
1309       } else {
1310         if (parseOptionalAlignment(Alignment))
1311           return true;
1312       }
1313       B.addAlignmentAttr(Alignment);
1314       continue;
1315     }
1316     case lltok::kw_alignstack: {
1317       unsigned Alignment;
1318       if (inAttrGrp) {
1319         Lex.Lex();
1320         if (parseToken(lltok::equal, "expected '=' here") ||
1321             parseUInt32(Alignment))
1322           return true;
1323       } else {
1324         if (parseOptionalStackAlignment(Alignment))
1325           return true;
1326       }
1327       B.addStackAlignmentAttr(Alignment);
1328       continue;
1329     }
1330     case lltok::kw_allocsize: {
1331       unsigned ElemSizeArg;
1332       Optional<unsigned> NumElemsArg;
1333       // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1334       if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1335         return true;
1336       B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1337       continue;
1338     }
1339     case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1340     case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1341     case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1342     case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1343     case lltok::kw_hot: B.addAttribute(Attribute::Hot); break;
1344     case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1345     case lltok::kw_inaccessiblememonly:
1346       B.addAttribute(Attribute::InaccessibleMemOnly); break;
1347     case lltok::kw_inaccessiblemem_or_argmemonly:
1348       B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1349     case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1350     case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1351     case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1352     case lltok::kw_mustprogress:
1353       B.addAttribute(Attribute::MustProgress);
1354       break;
1355     case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1356     case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1357     case lltok::kw_nocallback:
1358       B.addAttribute(Attribute::NoCallback);
1359       break;
1360     case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1361     case lltok::kw_nofree: B.addAttribute(Attribute::NoFree); break;
1362     case lltok::kw_noimplicitfloat:
1363       B.addAttribute(Attribute::NoImplicitFloat); break;
1364     case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1365     case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1366     case lltok::kw_nomerge: B.addAttribute(Attribute::NoMerge); break;
1367     case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1368     case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1369     case lltok::kw_nosync: B.addAttribute(Attribute::NoSync); break;
1370     case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
1371     case lltok::kw_noprofile: B.addAttribute(Attribute::NoProfile); break;
1372     case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1373     case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1374     case lltok::kw_null_pointer_is_valid:
1375       B.addAttribute(Attribute::NullPointerIsValid); break;
1376     case lltok::kw_optforfuzzing:
1377       B.addAttribute(Attribute::OptForFuzzing); break;
1378     case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1379     case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1380     case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1381     case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1382     case lltok::kw_returns_twice:
1383       B.addAttribute(Attribute::ReturnsTwice); break;
1384     case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
1385     case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1386     case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1387     case lltok::kw_sspstrong:
1388       B.addAttribute(Attribute::StackProtectStrong); break;
1389     case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1390     case lltok::kw_shadowcallstack:
1391       B.addAttribute(Attribute::ShadowCallStack); break;
1392     case lltok::kw_sanitize_address:
1393       B.addAttribute(Attribute::SanitizeAddress); break;
1394     case lltok::kw_sanitize_hwaddress:
1395       B.addAttribute(Attribute::SanitizeHWAddress); break;
1396     case lltok::kw_sanitize_memtag:
1397       B.addAttribute(Attribute::SanitizeMemTag); break;
1398     case lltok::kw_sanitize_thread:
1399       B.addAttribute(Attribute::SanitizeThread); break;
1400     case lltok::kw_sanitize_memory:
1401       B.addAttribute(Attribute::SanitizeMemory); break;
1402     case lltok::kw_speculative_load_hardening:
1403       B.addAttribute(Attribute::SpeculativeLoadHardening);
1404       break;
1405     case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
1406     case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1407     case lltok::kw_willreturn: B.addAttribute(Attribute::WillReturn); break;
1408     case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1409     case lltok::kw_preallocated: {
1410       Type *Ty;
1411       if (parsePreallocated(Ty))
1412         return true;
1413       B.addPreallocatedAttr(Ty);
1414       break;
1415     }
1416 
1417     // error handling.
1418     case lltok::kw_inreg:
1419     case lltok::kw_signext:
1420     case lltok::kw_zeroext:
1421       HaveError |=
1422           error(Lex.getLoc(), "invalid use of attribute on a function");
1423       break;
1424     case lltok::kw_byval:
1425     case lltok::kw_dereferenceable:
1426     case lltok::kw_dereferenceable_or_null:
1427     case lltok::kw_inalloca:
1428     case lltok::kw_nest:
1429     case lltok::kw_noalias:
1430     case lltok::kw_noundef:
1431     case lltok::kw_nocapture:
1432     case lltok::kw_nonnull:
1433     case lltok::kw_returned:
1434     case lltok::kw_sret:
1435     case lltok::kw_swifterror:
1436     case lltok::kw_swiftself:
1437     case lltok::kw_immarg:
1438     case lltok::kw_byref:
1439       HaveError |=
1440           error(Lex.getLoc(),
1441                 "invalid use of parameter-only attribute on a function");
1442       break;
1443     }
1444 
1445     // parsePreallocated() consumes token
1446     if (Token != lltok::kw_preallocated)
1447       Lex.Lex();
1448   }
1449 }
1450 
1451 //===----------------------------------------------------------------------===//
1452 // GlobalValue Reference/Resolution Routines.
1453 //===----------------------------------------------------------------------===//
1454 
createGlobalFwdRef(Module * M,PointerType * PTy,const std::string & Name)1455 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1456                                               const std::string &Name) {
1457   if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1458     return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1459                             PTy->getAddressSpace(), Name, M);
1460   else
1461     return new GlobalVariable(*M, PTy->getElementType(), false,
1462                               GlobalValue::ExternalWeakLinkage, nullptr, Name,
1463                               nullptr, GlobalVariable::NotThreadLocal,
1464                               PTy->getAddressSpace());
1465 }
1466 
checkValidVariableType(LocTy Loc,const Twine & Name,Type * Ty,Value * Val,bool IsCall)1467 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1468                                         Value *Val, bool IsCall) {
1469   if (Val->getType() == Ty)
1470     return Val;
1471   // For calls we also accept variables in the program address space.
1472   Type *SuggestedTy = Ty;
1473   if (IsCall && isa<PointerType>(Ty)) {
1474     Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1475         M->getDataLayout().getProgramAddressSpace());
1476     SuggestedTy = TyInProgAS;
1477     if (Val->getType() == TyInProgAS)
1478       return Val;
1479   }
1480   if (Ty->isLabelTy())
1481     error(Loc, "'" + Name + "' is not a basic block");
1482   else
1483     error(Loc, "'" + Name + "' defined with type '" +
1484                    getTypeString(Val->getType()) + "' but expected '" +
1485                    getTypeString(SuggestedTy) + "'");
1486   return nullptr;
1487 }
1488 
1489 /// getGlobalVal - Get a value with the specified name or ID, creating a
1490 /// forward reference record if needed.  This can return null if the value
1491 /// exists but does not have the right type.
getGlobalVal(const std::string & Name,Type * Ty,LocTy Loc,bool IsCall)1492 GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1493                                     LocTy Loc, bool IsCall) {
1494   PointerType *PTy = dyn_cast<PointerType>(Ty);
1495   if (!PTy) {
1496     error(Loc, "global variable reference must have pointer type");
1497     return nullptr;
1498   }
1499 
1500   // Look this name up in the normal function symbol table.
1501   GlobalValue *Val =
1502     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1503 
1504   // If this is a forward reference for the value, see if we already created a
1505   // forward ref record.
1506   if (!Val) {
1507     auto I = ForwardRefVals.find(Name);
1508     if (I != ForwardRefVals.end())
1509       Val = I->second.first;
1510   }
1511 
1512   // If we have the value in the symbol table or fwd-ref table, return it.
1513   if (Val)
1514     return cast_or_null<GlobalValue>(
1515         checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
1516 
1517   // Otherwise, create a new forward reference for this value and remember it.
1518   GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1519   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1520   return FwdVal;
1521 }
1522 
getGlobalVal(unsigned ID,Type * Ty,LocTy Loc,bool IsCall)1523 GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1524                                     bool IsCall) {
1525   PointerType *PTy = dyn_cast<PointerType>(Ty);
1526   if (!PTy) {
1527     error(Loc, "global variable reference must have pointer type");
1528     return nullptr;
1529   }
1530 
1531   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1532 
1533   // If this is a forward reference for the value, see if we already created a
1534   // forward ref record.
1535   if (!Val) {
1536     auto I = ForwardRefValIDs.find(ID);
1537     if (I != ForwardRefValIDs.end())
1538       Val = I->second.first;
1539   }
1540 
1541   // If we have the value in the symbol table or fwd-ref table, return it.
1542   if (Val)
1543     return cast_or_null<GlobalValue>(
1544         checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
1545 
1546   // Otherwise, create a new forward reference for this value and remember it.
1547   GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1548   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1549   return FwdVal;
1550 }
1551 
1552 //===----------------------------------------------------------------------===//
1553 // Comdat Reference/Resolution Routines.
1554 //===----------------------------------------------------------------------===//
1555 
getComdat(const std::string & Name,LocTy Loc)1556 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1557   // Look this name up in the comdat symbol table.
1558   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1559   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1560   if (I != ComdatSymTab.end())
1561     return &I->second;
1562 
1563   // Otherwise, create a new forward reference for this value and remember it.
1564   Comdat *C = M->getOrInsertComdat(Name);
1565   ForwardRefComdats[Name] = Loc;
1566   return C;
1567 }
1568 
1569 //===----------------------------------------------------------------------===//
1570 // Helper Routines.
1571 //===----------------------------------------------------------------------===//
1572 
1573 /// parseToken - If the current token has the specified kind, eat it and return
1574 /// success.  Otherwise, emit the specified error and return failure.
parseToken(lltok::Kind T,const char * ErrMsg)1575 bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1576   if (Lex.getKind() != T)
1577     return tokError(ErrMsg);
1578   Lex.Lex();
1579   return false;
1580 }
1581 
1582 /// parseStringConstant
1583 ///   ::= StringConstant
parseStringConstant(std::string & Result)1584 bool LLParser::parseStringConstant(std::string &Result) {
1585   if (Lex.getKind() != lltok::StringConstant)
1586     return tokError("expected string constant");
1587   Result = Lex.getStrVal();
1588   Lex.Lex();
1589   return false;
1590 }
1591 
1592 /// parseUInt32
1593 ///   ::= uint32
parseUInt32(uint32_t & Val)1594 bool LLParser::parseUInt32(uint32_t &Val) {
1595   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1596     return tokError("expected integer");
1597   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1598   if (Val64 != unsigned(Val64))
1599     return tokError("expected 32-bit integer (too large)");
1600   Val = Val64;
1601   Lex.Lex();
1602   return false;
1603 }
1604 
1605 /// parseUInt64
1606 ///   ::= uint64
parseUInt64(uint64_t & Val)1607 bool LLParser::parseUInt64(uint64_t &Val) {
1608   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1609     return tokError("expected integer");
1610   Val = Lex.getAPSIntVal().getLimitedValue();
1611   Lex.Lex();
1612   return false;
1613 }
1614 
1615 /// parseTLSModel
1616 ///   := 'localdynamic'
1617 ///   := 'initialexec'
1618 ///   := 'localexec'
parseTLSModel(GlobalVariable::ThreadLocalMode & TLM)1619 bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1620   switch (Lex.getKind()) {
1621     default:
1622       return tokError("expected localdynamic, initialexec or localexec");
1623     case lltok::kw_localdynamic:
1624       TLM = GlobalVariable::LocalDynamicTLSModel;
1625       break;
1626     case lltok::kw_initialexec:
1627       TLM = GlobalVariable::InitialExecTLSModel;
1628       break;
1629     case lltok::kw_localexec:
1630       TLM = GlobalVariable::LocalExecTLSModel;
1631       break;
1632   }
1633 
1634   Lex.Lex();
1635   return false;
1636 }
1637 
1638 /// parseOptionalThreadLocal
1639 ///   := /*empty*/
1640 ///   := 'thread_local'
1641 ///   := 'thread_local' '(' tlsmodel ')'
parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode & TLM)1642 bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1643   TLM = GlobalVariable::NotThreadLocal;
1644   if (!EatIfPresent(lltok::kw_thread_local))
1645     return false;
1646 
1647   TLM = GlobalVariable::GeneralDynamicTLSModel;
1648   if (Lex.getKind() == lltok::lparen) {
1649     Lex.Lex();
1650     return parseTLSModel(TLM) ||
1651            parseToken(lltok::rparen, "expected ')' after thread local model");
1652   }
1653   return false;
1654 }
1655 
1656 /// parseOptionalAddrSpace
1657 ///   := /*empty*/
1658 ///   := 'addrspace' '(' uint32 ')'
parseOptionalAddrSpace(unsigned & AddrSpace,unsigned DefaultAS)1659 bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1660   AddrSpace = DefaultAS;
1661   if (!EatIfPresent(lltok::kw_addrspace))
1662     return false;
1663   return parseToken(lltok::lparen, "expected '(' in address space") ||
1664          parseUInt32(AddrSpace) ||
1665          parseToken(lltok::rparen, "expected ')' in address space");
1666 }
1667 
1668 /// parseStringAttribute
1669 ///   := StringConstant
1670 ///   := StringConstant '=' StringConstant
parseStringAttribute(AttrBuilder & B)1671 bool LLParser::parseStringAttribute(AttrBuilder &B) {
1672   std::string Attr = Lex.getStrVal();
1673   Lex.Lex();
1674   std::string Val;
1675   if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1676     return true;
1677   B.addAttribute(Attr, Val);
1678   return false;
1679 }
1680 
1681 /// parseOptionalParamAttrs - parse a potentially empty list of parameter
1682 /// attributes.
parseOptionalParamAttrs(AttrBuilder & B)1683 bool LLParser::parseOptionalParamAttrs(AttrBuilder &B) {
1684   bool HaveError = false;
1685 
1686   B.clear();
1687 
1688   while (true) {
1689     lltok::Kind Token = Lex.getKind();
1690     switch (Token) {
1691     default:  // End of attributes.
1692       return HaveError;
1693     case lltok::StringConstant: {
1694       if (parseStringAttribute(B))
1695         return true;
1696       continue;
1697     }
1698     case lltok::kw_align: {
1699       MaybeAlign Alignment;
1700       if (parseOptionalAlignment(Alignment, true))
1701         return true;
1702       B.addAlignmentAttr(Alignment);
1703       continue;
1704     }
1705     case lltok::kw_byval: {
1706       Type *Ty;
1707       if (parseRequiredTypeAttr(Ty, lltok::kw_byval))
1708         return true;
1709       B.addByValAttr(Ty);
1710       continue;
1711     }
1712     case lltok::kw_sret: {
1713       Type *Ty;
1714       if (parseRequiredTypeAttr(Ty, lltok::kw_sret))
1715         return true;
1716       B.addStructRetAttr(Ty);
1717       continue;
1718     }
1719     case lltok::kw_preallocated: {
1720       Type *Ty;
1721       if (parsePreallocated(Ty))
1722         return true;
1723       B.addPreallocatedAttr(Ty);
1724       continue;
1725     }
1726     case lltok::kw_dereferenceable: {
1727       uint64_t Bytes;
1728       if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1729         return true;
1730       B.addDereferenceableAttr(Bytes);
1731       continue;
1732     }
1733     case lltok::kw_dereferenceable_or_null: {
1734       uint64_t Bytes;
1735       if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1736         return true;
1737       B.addDereferenceableOrNullAttr(Bytes);
1738       continue;
1739     }
1740     case lltok::kw_byref: {
1741       Type *Ty;
1742       if (parseByRef(Ty))
1743         return true;
1744       B.addByRefAttr(Ty);
1745       continue;
1746     }
1747     case lltok::kw_inalloca:        B.addAttribute(Attribute::InAlloca); break;
1748     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1749     case lltok::kw_nest:            B.addAttribute(Attribute::Nest); break;
1750     case lltok::kw_noundef:
1751       B.addAttribute(Attribute::NoUndef);
1752       break;
1753     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1754     case lltok::kw_nocapture:       B.addAttribute(Attribute::NoCapture); break;
1755     case lltok::kw_nofree:          B.addAttribute(Attribute::NoFree); break;
1756     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1757     case lltok::kw_readnone:        B.addAttribute(Attribute::ReadNone); break;
1758     case lltok::kw_readonly:        B.addAttribute(Attribute::ReadOnly); break;
1759     case lltok::kw_returned:        B.addAttribute(Attribute::Returned); break;
1760     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1761     case lltok::kw_swifterror:      B.addAttribute(Attribute::SwiftError); break;
1762     case lltok::kw_swiftself:       B.addAttribute(Attribute::SwiftSelf); break;
1763     case lltok::kw_writeonly:       B.addAttribute(Attribute::WriteOnly); break;
1764     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1765     case lltok::kw_immarg:          B.addAttribute(Attribute::ImmArg); break;
1766 
1767     case lltok::kw_alignstack:
1768     case lltok::kw_alwaysinline:
1769     case lltok::kw_argmemonly:
1770     case lltok::kw_builtin:
1771     case lltok::kw_inlinehint:
1772     case lltok::kw_jumptable:
1773     case lltok::kw_minsize:
1774     case lltok::kw_mustprogress:
1775     case lltok::kw_naked:
1776     case lltok::kw_nobuiltin:
1777     case lltok::kw_noduplicate:
1778     case lltok::kw_noimplicitfloat:
1779     case lltok::kw_noinline:
1780     case lltok::kw_nonlazybind:
1781     case lltok::kw_nomerge:
1782     case lltok::kw_noprofile:
1783     case lltok::kw_noredzone:
1784     case lltok::kw_noreturn:
1785     case lltok::kw_nocf_check:
1786     case lltok::kw_nounwind:
1787     case lltok::kw_optforfuzzing:
1788     case lltok::kw_optnone:
1789     case lltok::kw_optsize:
1790     case lltok::kw_returns_twice:
1791     case lltok::kw_sanitize_address:
1792     case lltok::kw_sanitize_hwaddress:
1793     case lltok::kw_sanitize_memtag:
1794     case lltok::kw_sanitize_memory:
1795     case lltok::kw_sanitize_thread:
1796     case lltok::kw_speculative_load_hardening:
1797     case lltok::kw_ssp:
1798     case lltok::kw_sspreq:
1799     case lltok::kw_sspstrong:
1800     case lltok::kw_safestack:
1801     case lltok::kw_shadowcallstack:
1802     case lltok::kw_strictfp:
1803     case lltok::kw_uwtable:
1804       HaveError |=
1805           error(Lex.getLoc(), "invalid use of function-only attribute");
1806       break;
1807     }
1808 
1809     Lex.Lex();
1810   }
1811 }
1812 
1813 /// parseOptionalReturnAttrs - parse a potentially empty list of return
1814 /// attributes.
parseOptionalReturnAttrs(AttrBuilder & B)1815 bool LLParser::parseOptionalReturnAttrs(AttrBuilder &B) {
1816   bool HaveError = false;
1817 
1818   B.clear();
1819 
1820   while (true) {
1821     lltok::Kind Token = Lex.getKind();
1822     switch (Token) {
1823     default:  // End of attributes.
1824       return HaveError;
1825     case lltok::StringConstant: {
1826       if (parseStringAttribute(B))
1827         return true;
1828       continue;
1829     }
1830     case lltok::kw_dereferenceable: {
1831       uint64_t Bytes;
1832       if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1833         return true;
1834       B.addDereferenceableAttr(Bytes);
1835       continue;
1836     }
1837     case lltok::kw_dereferenceable_or_null: {
1838       uint64_t Bytes;
1839       if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1840         return true;
1841       B.addDereferenceableOrNullAttr(Bytes);
1842       continue;
1843     }
1844     case lltok::kw_align: {
1845       MaybeAlign Alignment;
1846       if (parseOptionalAlignment(Alignment))
1847         return true;
1848       B.addAlignmentAttr(Alignment);
1849       continue;
1850     }
1851     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1852     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1853     case lltok::kw_noundef:
1854       B.addAttribute(Attribute::NoUndef);
1855       break;
1856     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1857     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1858     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1859 
1860     // error handling.
1861     case lltok::kw_byval:
1862     case lltok::kw_inalloca:
1863     case lltok::kw_nest:
1864     case lltok::kw_nocapture:
1865     case lltok::kw_returned:
1866     case lltok::kw_sret:
1867     case lltok::kw_swifterror:
1868     case lltok::kw_swiftself:
1869     case lltok::kw_immarg:
1870     case lltok::kw_byref:
1871       HaveError |=
1872           error(Lex.getLoc(), "invalid use of parameter-only attribute");
1873       break;
1874 
1875     case lltok::kw_alignstack:
1876     case lltok::kw_alwaysinline:
1877     case lltok::kw_argmemonly:
1878     case lltok::kw_builtin:
1879     case lltok::kw_cold:
1880     case lltok::kw_inlinehint:
1881     case lltok::kw_jumptable:
1882     case lltok::kw_minsize:
1883     case lltok::kw_mustprogress:
1884     case lltok::kw_naked:
1885     case lltok::kw_nobuiltin:
1886     case lltok::kw_noduplicate:
1887     case lltok::kw_noimplicitfloat:
1888     case lltok::kw_noinline:
1889     case lltok::kw_nonlazybind:
1890     case lltok::kw_nomerge:
1891     case lltok::kw_noprofile:
1892     case lltok::kw_noredzone:
1893     case lltok::kw_noreturn:
1894     case lltok::kw_nocf_check:
1895     case lltok::kw_nounwind:
1896     case lltok::kw_optforfuzzing:
1897     case lltok::kw_optnone:
1898     case lltok::kw_optsize:
1899     case lltok::kw_returns_twice:
1900     case lltok::kw_sanitize_address:
1901     case lltok::kw_sanitize_hwaddress:
1902     case lltok::kw_sanitize_memtag:
1903     case lltok::kw_sanitize_memory:
1904     case lltok::kw_sanitize_thread:
1905     case lltok::kw_speculative_load_hardening:
1906     case lltok::kw_ssp:
1907     case lltok::kw_sspreq:
1908     case lltok::kw_sspstrong:
1909     case lltok::kw_safestack:
1910     case lltok::kw_shadowcallstack:
1911     case lltok::kw_strictfp:
1912     case lltok::kw_uwtable:
1913       HaveError |=
1914           error(Lex.getLoc(), "invalid use of function-only attribute");
1915       break;
1916     case lltok::kw_readnone:
1917     case lltok::kw_readonly:
1918       HaveError |=
1919           error(Lex.getLoc(), "invalid use of attribute on return type");
1920       break;
1921     case lltok::kw_preallocated:
1922       HaveError |=
1923           error(Lex.getLoc(),
1924                 "invalid use of parameter-only/call site-only attribute");
1925       break;
1926     }
1927 
1928     Lex.Lex();
1929   }
1930 }
1931 
parseOptionalLinkageAux(lltok::Kind Kind,bool & HasLinkage)1932 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1933   HasLinkage = true;
1934   switch (Kind) {
1935   default:
1936     HasLinkage = false;
1937     return GlobalValue::ExternalLinkage;
1938   case lltok::kw_private:
1939     return GlobalValue::PrivateLinkage;
1940   case lltok::kw_internal:
1941     return GlobalValue::InternalLinkage;
1942   case lltok::kw_weak:
1943     return GlobalValue::WeakAnyLinkage;
1944   case lltok::kw_weak_odr:
1945     return GlobalValue::WeakODRLinkage;
1946   case lltok::kw_linkonce:
1947     return GlobalValue::LinkOnceAnyLinkage;
1948   case lltok::kw_linkonce_odr:
1949     return GlobalValue::LinkOnceODRLinkage;
1950   case lltok::kw_available_externally:
1951     return GlobalValue::AvailableExternallyLinkage;
1952   case lltok::kw_appending:
1953     return GlobalValue::AppendingLinkage;
1954   case lltok::kw_common:
1955     return GlobalValue::CommonLinkage;
1956   case lltok::kw_extern_weak:
1957     return GlobalValue::ExternalWeakLinkage;
1958   case lltok::kw_external:
1959     return GlobalValue::ExternalLinkage;
1960   }
1961 }
1962 
1963 /// parseOptionalLinkage
1964 ///   ::= /*empty*/
1965 ///   ::= 'private'
1966 ///   ::= 'internal'
1967 ///   ::= 'weak'
1968 ///   ::= 'weak_odr'
1969 ///   ::= 'linkonce'
1970 ///   ::= 'linkonce_odr'
1971 ///   ::= 'available_externally'
1972 ///   ::= 'appending'
1973 ///   ::= 'common'
1974 ///   ::= 'extern_weak'
1975 ///   ::= 'external'
parseOptionalLinkage(unsigned & Res,bool & HasLinkage,unsigned & Visibility,unsigned & DLLStorageClass,bool & DSOLocal)1976 bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1977                                     unsigned &Visibility,
1978                                     unsigned &DLLStorageClass, bool &DSOLocal) {
1979   Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1980   if (HasLinkage)
1981     Lex.Lex();
1982   parseOptionalDSOLocal(DSOLocal);
1983   parseOptionalVisibility(Visibility);
1984   parseOptionalDLLStorageClass(DLLStorageClass);
1985 
1986   if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1987     return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1988   }
1989 
1990   return false;
1991 }
1992 
parseOptionalDSOLocal(bool & DSOLocal)1993 void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
1994   switch (Lex.getKind()) {
1995   default:
1996     DSOLocal = false;
1997     break;
1998   case lltok::kw_dso_local:
1999     DSOLocal = true;
2000     Lex.Lex();
2001     break;
2002   case lltok::kw_dso_preemptable:
2003     DSOLocal = false;
2004     Lex.Lex();
2005     break;
2006   }
2007 }
2008 
2009 /// parseOptionalVisibility
2010 ///   ::= /*empty*/
2011 ///   ::= 'default'
2012 ///   ::= 'hidden'
2013 ///   ::= 'protected'
2014 ///
parseOptionalVisibility(unsigned & Res)2015 void LLParser::parseOptionalVisibility(unsigned &Res) {
2016   switch (Lex.getKind()) {
2017   default:
2018     Res = GlobalValue::DefaultVisibility;
2019     return;
2020   case lltok::kw_default:
2021     Res = GlobalValue::DefaultVisibility;
2022     break;
2023   case lltok::kw_hidden:
2024     Res = GlobalValue::HiddenVisibility;
2025     break;
2026   case lltok::kw_protected:
2027     Res = GlobalValue::ProtectedVisibility;
2028     break;
2029   }
2030   Lex.Lex();
2031 }
2032 
2033 /// parseOptionalDLLStorageClass
2034 ///   ::= /*empty*/
2035 ///   ::= 'dllimport'
2036 ///   ::= 'dllexport'
2037 ///
parseOptionalDLLStorageClass(unsigned & Res)2038 void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2039   switch (Lex.getKind()) {
2040   default:
2041     Res = GlobalValue::DefaultStorageClass;
2042     return;
2043   case lltok::kw_dllimport:
2044     Res = GlobalValue::DLLImportStorageClass;
2045     break;
2046   case lltok::kw_dllexport:
2047     Res = GlobalValue::DLLExportStorageClass;
2048     break;
2049   }
2050   Lex.Lex();
2051 }
2052 
2053 /// parseOptionalCallingConv
2054 ///   ::= /*empty*/
2055 ///   ::= 'ccc'
2056 ///   ::= 'fastcc'
2057 ///   ::= 'intel_ocl_bicc'
2058 ///   ::= 'coldcc'
2059 ///   ::= 'cfguard_checkcc'
2060 ///   ::= 'x86_stdcallcc'
2061 ///   ::= 'x86_fastcallcc'
2062 ///   ::= 'x86_thiscallcc'
2063 ///   ::= 'x86_vectorcallcc'
2064 ///   ::= 'arm_apcscc'
2065 ///   ::= 'arm_aapcscc'
2066 ///   ::= 'arm_aapcs_vfpcc'
2067 ///   ::= 'aarch64_vector_pcs'
2068 ///   ::= 'aarch64_sve_vector_pcs'
2069 ///   ::= 'msp430_intrcc'
2070 ///   ::= 'avr_intrcc'
2071 ///   ::= 'avr_signalcc'
2072 ///   ::= 'ptx_kernel'
2073 ///   ::= 'ptx_device'
2074 ///   ::= 'spir_func'
2075 ///   ::= 'spir_kernel'
2076 ///   ::= 'x86_64_sysvcc'
2077 ///   ::= 'win64cc'
2078 ///   ::= 'webkit_jscc'
2079 ///   ::= 'anyregcc'
2080 ///   ::= 'preserve_mostcc'
2081 ///   ::= 'preserve_allcc'
2082 ///   ::= 'ghccc'
2083 ///   ::= 'swiftcc'
2084 ///   ::= 'x86_intrcc'
2085 ///   ::= 'hhvmcc'
2086 ///   ::= 'hhvm_ccc'
2087 ///   ::= 'cxx_fast_tlscc'
2088 ///   ::= 'amdgpu_vs'
2089 ///   ::= 'amdgpu_ls'
2090 ///   ::= 'amdgpu_hs'
2091 ///   ::= 'amdgpu_es'
2092 ///   ::= 'amdgpu_gs'
2093 ///   ::= 'amdgpu_ps'
2094 ///   ::= 'amdgpu_cs'
2095 ///   ::= 'amdgpu_kernel'
2096 ///   ::= 'tailcc'
2097 ///   ::= 'cc' UINT
2098 ///
parseOptionalCallingConv(unsigned & CC)2099 bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2100   switch (Lex.getKind()) {
2101   default:                       CC = CallingConv::C; return false;
2102   case lltok::kw_ccc:            CC = CallingConv::C; break;
2103   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
2104   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
2105   case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break;
2106   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
2107   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
2108   case lltok::kw_x86_regcallcc:  CC = CallingConv::X86_RegCall; break;
2109   case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
2110   case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
2111   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
2112   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
2113   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
2114   case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
2115   case lltok::kw_aarch64_sve_vector_pcs:
2116     CC = CallingConv::AArch64_SVE_VectorCall;
2117     break;
2118   case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
2119   case lltok::kw_avr_intrcc:     CC = CallingConv::AVR_INTR; break;
2120   case lltok::kw_avr_signalcc:   CC = CallingConv::AVR_SIGNAL; break;
2121   case lltok::kw_ptx_kernel:     CC = CallingConv::PTX_Kernel; break;
2122   case lltok::kw_ptx_device:     CC = CallingConv::PTX_Device; break;
2123   case lltok::kw_spir_kernel:    CC = CallingConv::SPIR_KERNEL; break;
2124   case lltok::kw_spir_func:      CC = CallingConv::SPIR_FUNC; break;
2125   case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
2126   case lltok::kw_x86_64_sysvcc:  CC = CallingConv::X86_64_SysV; break;
2127   case lltok::kw_win64cc:        CC = CallingConv::Win64; break;
2128   case lltok::kw_webkit_jscc:    CC = CallingConv::WebKit_JS; break;
2129   case lltok::kw_anyregcc:       CC = CallingConv::AnyReg; break;
2130   case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
2131   case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
2132   case lltok::kw_ghccc:          CC = CallingConv::GHC; break;
2133   case lltok::kw_swiftcc:        CC = CallingConv::Swift; break;
2134   case lltok::kw_x86_intrcc:     CC = CallingConv::X86_INTR; break;
2135   case lltok::kw_hhvmcc:         CC = CallingConv::HHVM; break;
2136   case lltok::kw_hhvm_ccc:       CC = CallingConv::HHVM_C; break;
2137   case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
2138   case lltok::kw_amdgpu_vs:      CC = CallingConv::AMDGPU_VS; break;
2139   case lltok::kw_amdgpu_gfx:     CC = CallingConv::AMDGPU_Gfx; break;
2140   case lltok::kw_amdgpu_ls:      CC = CallingConv::AMDGPU_LS; break;
2141   case lltok::kw_amdgpu_hs:      CC = CallingConv::AMDGPU_HS; break;
2142   case lltok::kw_amdgpu_es:      CC = CallingConv::AMDGPU_ES; break;
2143   case lltok::kw_amdgpu_gs:      CC = CallingConv::AMDGPU_GS; break;
2144   case lltok::kw_amdgpu_ps:      CC = CallingConv::AMDGPU_PS; break;
2145   case lltok::kw_amdgpu_cs:      CC = CallingConv::AMDGPU_CS; break;
2146   case lltok::kw_amdgpu_kernel:  CC = CallingConv::AMDGPU_KERNEL; break;
2147   case lltok::kw_tailcc:         CC = CallingConv::Tail; break;
2148   case lltok::kw_cc: {
2149       Lex.Lex();
2150       return parseUInt32(CC);
2151     }
2152   }
2153 
2154   Lex.Lex();
2155   return false;
2156 }
2157 
2158 /// parseMetadataAttachment
2159 ///   ::= !dbg !42
parseMetadataAttachment(unsigned & Kind,MDNode * & MD)2160 bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2161   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2162 
2163   std::string Name = Lex.getStrVal();
2164   Kind = M->getMDKindID(Name);
2165   Lex.Lex();
2166 
2167   return parseMDNode(MD);
2168 }
2169 
2170 /// parseInstructionMetadata
2171 ///   ::= !dbg !42 (',' !dbg !57)*
parseInstructionMetadata(Instruction & Inst)2172 bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2173   do {
2174     if (Lex.getKind() != lltok::MetadataVar)
2175       return tokError("expected metadata after comma");
2176 
2177     unsigned MDK;
2178     MDNode *N;
2179     if (parseMetadataAttachment(MDK, N))
2180       return true;
2181 
2182     Inst.setMetadata(MDK, N);
2183     if (MDK == LLVMContext::MD_tbaa)
2184       InstsWithTBAATag.push_back(&Inst);
2185 
2186     // If this is the end of the list, we're done.
2187   } while (EatIfPresent(lltok::comma));
2188   return false;
2189 }
2190 
2191 /// parseGlobalObjectMetadataAttachment
2192 ///   ::= !dbg !57
parseGlobalObjectMetadataAttachment(GlobalObject & GO)2193 bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2194   unsigned MDK;
2195   MDNode *N;
2196   if (parseMetadataAttachment(MDK, N))
2197     return true;
2198 
2199   GO.addMetadata(MDK, *N);
2200   return false;
2201 }
2202 
2203 /// parseOptionalFunctionMetadata
2204 ///   ::= (!dbg !57)*
parseOptionalFunctionMetadata(Function & F)2205 bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2206   while (Lex.getKind() == lltok::MetadataVar)
2207     if (parseGlobalObjectMetadataAttachment(F))
2208       return true;
2209   return false;
2210 }
2211 
2212 /// parseOptionalAlignment
2213 ///   ::= /* empty */
2214 ///   ::= 'align' 4
parseOptionalAlignment(MaybeAlign & Alignment,bool AllowParens)2215 bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2216   Alignment = None;
2217   if (!EatIfPresent(lltok::kw_align))
2218     return false;
2219   LocTy AlignLoc = Lex.getLoc();
2220   uint32_t Value = 0;
2221 
2222   LocTy ParenLoc = Lex.getLoc();
2223   bool HaveParens = false;
2224   if (AllowParens) {
2225     if (EatIfPresent(lltok::lparen))
2226       HaveParens = true;
2227   }
2228 
2229   if (parseUInt32(Value))
2230     return true;
2231 
2232   if (HaveParens && !EatIfPresent(lltok::rparen))
2233     return error(ParenLoc, "expected ')'");
2234 
2235   if (!isPowerOf2_32(Value))
2236     return error(AlignLoc, "alignment is not a power of two");
2237   if (Value > Value::MaximumAlignment)
2238     return error(AlignLoc, "huge alignments are not supported yet");
2239   Alignment = Align(Value);
2240   return false;
2241 }
2242 
2243 /// parseOptionalDerefAttrBytes
2244 ///   ::= /* empty */
2245 ///   ::= AttrKind '(' 4 ')'
2246 ///
2247 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
parseOptionalDerefAttrBytes(lltok::Kind AttrKind,uint64_t & Bytes)2248 bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2249                                            uint64_t &Bytes) {
2250   assert((AttrKind == lltok::kw_dereferenceable ||
2251           AttrKind == lltok::kw_dereferenceable_or_null) &&
2252          "contract!");
2253 
2254   Bytes = 0;
2255   if (!EatIfPresent(AttrKind))
2256     return false;
2257   LocTy ParenLoc = Lex.getLoc();
2258   if (!EatIfPresent(lltok::lparen))
2259     return error(ParenLoc, "expected '('");
2260   LocTy DerefLoc = Lex.getLoc();
2261   if (parseUInt64(Bytes))
2262     return true;
2263   ParenLoc = Lex.getLoc();
2264   if (!EatIfPresent(lltok::rparen))
2265     return error(ParenLoc, "expected ')'");
2266   if (!Bytes)
2267     return error(DerefLoc, "dereferenceable bytes must be non-zero");
2268   return false;
2269 }
2270 
2271 /// parseOptionalCommaAlign
2272 ///   ::=
2273 ///   ::= ',' align 4
2274 ///
2275 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2276 /// end.
parseOptionalCommaAlign(MaybeAlign & Alignment,bool & AteExtraComma)2277 bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2278                                        bool &AteExtraComma) {
2279   AteExtraComma = false;
2280   while (EatIfPresent(lltok::comma)) {
2281     // Metadata at the end is an early exit.
2282     if (Lex.getKind() == lltok::MetadataVar) {
2283       AteExtraComma = true;
2284       return false;
2285     }
2286 
2287     if (Lex.getKind() != lltok::kw_align)
2288       return error(Lex.getLoc(), "expected metadata or 'align'");
2289 
2290     if (parseOptionalAlignment(Alignment))
2291       return true;
2292   }
2293 
2294   return false;
2295 }
2296 
2297 /// parseOptionalCommaAddrSpace
2298 ///   ::=
2299 ///   ::= ',' addrspace(1)
2300 ///
2301 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2302 /// end.
parseOptionalCommaAddrSpace(unsigned & AddrSpace,LocTy & Loc,bool & AteExtraComma)2303 bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2304                                            bool &AteExtraComma) {
2305   AteExtraComma = false;
2306   while (EatIfPresent(lltok::comma)) {
2307     // Metadata at the end is an early exit.
2308     if (Lex.getKind() == lltok::MetadataVar) {
2309       AteExtraComma = true;
2310       return false;
2311     }
2312 
2313     Loc = Lex.getLoc();
2314     if (Lex.getKind() != lltok::kw_addrspace)
2315       return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2316 
2317     if (parseOptionalAddrSpace(AddrSpace))
2318       return true;
2319   }
2320 
2321   return false;
2322 }
2323 
parseAllocSizeArguments(unsigned & BaseSizeArg,Optional<unsigned> & HowManyArg)2324 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2325                                        Optional<unsigned> &HowManyArg) {
2326   Lex.Lex();
2327 
2328   auto StartParen = Lex.getLoc();
2329   if (!EatIfPresent(lltok::lparen))
2330     return error(StartParen, "expected '('");
2331 
2332   if (parseUInt32(BaseSizeArg))
2333     return true;
2334 
2335   if (EatIfPresent(lltok::comma)) {
2336     auto HowManyAt = Lex.getLoc();
2337     unsigned HowMany;
2338     if (parseUInt32(HowMany))
2339       return true;
2340     if (HowMany == BaseSizeArg)
2341       return error(HowManyAt,
2342                    "'allocsize' indices can't refer to the same parameter");
2343     HowManyArg = HowMany;
2344   } else
2345     HowManyArg = None;
2346 
2347   auto EndParen = Lex.getLoc();
2348   if (!EatIfPresent(lltok::rparen))
2349     return error(EndParen, "expected ')'");
2350   return false;
2351 }
2352 
2353 /// parseScopeAndOrdering
2354 ///   if isAtomic: ::= SyncScope? AtomicOrdering
2355 ///   else: ::=
2356 ///
2357 /// This sets Scope and Ordering to the parsed values.
parseScopeAndOrdering(bool IsAtomic,SyncScope::ID & SSID,AtomicOrdering & Ordering)2358 bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2359                                      AtomicOrdering &Ordering) {
2360   if (!IsAtomic)
2361     return false;
2362 
2363   return parseScope(SSID) || parseOrdering(Ordering);
2364 }
2365 
2366 /// parseScope
2367 ///   ::= syncscope("singlethread" | "<target scope>")?
2368 ///
2369 /// This sets synchronization scope ID to the ID of the parsed value.
parseScope(SyncScope::ID & SSID)2370 bool LLParser::parseScope(SyncScope::ID &SSID) {
2371   SSID = SyncScope::System;
2372   if (EatIfPresent(lltok::kw_syncscope)) {
2373     auto StartParenAt = Lex.getLoc();
2374     if (!EatIfPresent(lltok::lparen))
2375       return error(StartParenAt, "Expected '(' in syncscope");
2376 
2377     std::string SSN;
2378     auto SSNAt = Lex.getLoc();
2379     if (parseStringConstant(SSN))
2380       return error(SSNAt, "Expected synchronization scope name");
2381 
2382     auto EndParenAt = Lex.getLoc();
2383     if (!EatIfPresent(lltok::rparen))
2384       return error(EndParenAt, "Expected ')' in syncscope");
2385 
2386     SSID = Context.getOrInsertSyncScopeID(SSN);
2387   }
2388 
2389   return false;
2390 }
2391 
2392 /// parseOrdering
2393 ///   ::= AtomicOrdering
2394 ///
2395 /// This sets Ordering to the parsed value.
parseOrdering(AtomicOrdering & Ordering)2396 bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2397   switch (Lex.getKind()) {
2398   default:
2399     return tokError("Expected ordering on atomic instruction");
2400   case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2401   case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2402   // Not specified yet:
2403   // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2404   case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2405   case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2406   case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2407   case lltok::kw_seq_cst:
2408     Ordering = AtomicOrdering::SequentiallyConsistent;
2409     break;
2410   }
2411   Lex.Lex();
2412   return false;
2413 }
2414 
2415 /// parseOptionalStackAlignment
2416 ///   ::= /* empty */
2417 ///   ::= 'alignstack' '(' 4 ')'
parseOptionalStackAlignment(unsigned & Alignment)2418 bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2419   Alignment = 0;
2420   if (!EatIfPresent(lltok::kw_alignstack))
2421     return false;
2422   LocTy ParenLoc = Lex.getLoc();
2423   if (!EatIfPresent(lltok::lparen))
2424     return error(ParenLoc, "expected '('");
2425   LocTy AlignLoc = Lex.getLoc();
2426   if (parseUInt32(Alignment))
2427     return true;
2428   ParenLoc = Lex.getLoc();
2429   if (!EatIfPresent(lltok::rparen))
2430     return error(ParenLoc, "expected ')'");
2431   if (!isPowerOf2_32(Alignment))
2432     return error(AlignLoc, "stack alignment is not a power of two");
2433   return false;
2434 }
2435 
2436 /// parseIndexList - This parses the index list for an insert/extractvalue
2437 /// instruction.  This sets AteExtraComma in the case where we eat an extra
2438 /// comma at the end of the line and find that it is followed by metadata.
2439 /// Clients that don't allow metadata can call the version of this function that
2440 /// only takes one argument.
2441 ///
2442 /// parseIndexList
2443 ///    ::=  (',' uint32)+
2444 ///
parseIndexList(SmallVectorImpl<unsigned> & Indices,bool & AteExtraComma)2445 bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2446                               bool &AteExtraComma) {
2447   AteExtraComma = false;
2448 
2449   if (Lex.getKind() != lltok::comma)
2450     return tokError("expected ',' as start of index list");
2451 
2452   while (EatIfPresent(lltok::comma)) {
2453     if (Lex.getKind() == lltok::MetadataVar) {
2454       if (Indices.empty())
2455         return tokError("expected index");
2456       AteExtraComma = true;
2457       return false;
2458     }
2459     unsigned Idx = 0;
2460     if (parseUInt32(Idx))
2461       return true;
2462     Indices.push_back(Idx);
2463   }
2464 
2465   return false;
2466 }
2467 
2468 //===----------------------------------------------------------------------===//
2469 // Type Parsing.
2470 //===----------------------------------------------------------------------===//
2471 
2472 /// parseType - parse a type.
parseType(Type * & Result,const Twine & Msg,bool AllowVoid)2473 bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2474   SMLoc TypeLoc = Lex.getLoc();
2475   switch (Lex.getKind()) {
2476   default:
2477     return tokError(Msg);
2478   case lltok::Type:
2479     // Type ::= 'float' | 'void' (etc)
2480     Result = Lex.getTyVal();
2481     Lex.Lex();
2482     break;
2483   case lltok::lbrace:
2484     // Type ::= StructType
2485     if (parseAnonStructType(Result, false))
2486       return true;
2487     break;
2488   case lltok::lsquare:
2489     // Type ::= '[' ... ']'
2490     Lex.Lex(); // eat the lsquare.
2491     if (parseArrayVectorType(Result, false))
2492       return true;
2493     break;
2494   case lltok::less: // Either vector or packed struct.
2495     // Type ::= '<' ... '>'
2496     Lex.Lex();
2497     if (Lex.getKind() == lltok::lbrace) {
2498       if (parseAnonStructType(Result, true) ||
2499           parseToken(lltok::greater, "expected '>' at end of packed struct"))
2500         return true;
2501     } else if (parseArrayVectorType(Result, true))
2502       return true;
2503     break;
2504   case lltok::LocalVar: {
2505     // Type ::= %foo
2506     std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2507 
2508     // If the type hasn't been defined yet, create a forward definition and
2509     // remember where that forward def'n was seen (in case it never is defined).
2510     if (!Entry.first) {
2511       Entry.first = StructType::create(Context, Lex.getStrVal());
2512       Entry.second = Lex.getLoc();
2513     }
2514     Result = Entry.first;
2515     Lex.Lex();
2516     break;
2517   }
2518 
2519   case lltok::LocalVarID: {
2520     // Type ::= %4
2521     std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2522 
2523     // If the type hasn't been defined yet, create a forward definition and
2524     // remember where that forward def'n was seen (in case it never is defined).
2525     if (!Entry.first) {
2526       Entry.first = StructType::create(Context);
2527       Entry.second = Lex.getLoc();
2528     }
2529     Result = Entry.first;
2530     Lex.Lex();
2531     break;
2532   }
2533   }
2534 
2535   // parse the type suffixes.
2536   while (true) {
2537     switch (Lex.getKind()) {
2538     // End of type.
2539     default:
2540       if (!AllowVoid && Result->isVoidTy())
2541         return error(TypeLoc, "void type only allowed for function results");
2542       return false;
2543 
2544     // Type ::= Type '*'
2545     case lltok::star:
2546       if (Result->isLabelTy())
2547         return tokError("basic block pointers are invalid");
2548       if (Result->isVoidTy())
2549         return tokError("pointers to void are invalid - use i8* instead");
2550       if (!PointerType::isValidElementType(Result))
2551         return tokError("pointer to this type is invalid");
2552       Result = PointerType::getUnqual(Result);
2553       Lex.Lex();
2554       break;
2555 
2556     // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2557     case lltok::kw_addrspace: {
2558       if (Result->isLabelTy())
2559         return tokError("basic block pointers are invalid");
2560       if (Result->isVoidTy())
2561         return tokError("pointers to void are invalid; use i8* instead");
2562       if (!PointerType::isValidElementType(Result))
2563         return tokError("pointer to this type is invalid");
2564       unsigned AddrSpace;
2565       if (parseOptionalAddrSpace(AddrSpace) ||
2566           parseToken(lltok::star, "expected '*' in address space"))
2567         return true;
2568 
2569       Result = PointerType::get(Result, AddrSpace);
2570       break;
2571     }
2572 
2573     /// Types '(' ArgTypeListI ')' OptFuncAttrs
2574     case lltok::lparen:
2575       if (parseFunctionType(Result))
2576         return true;
2577       break;
2578     }
2579   }
2580 }
2581 
2582 /// parseParameterList
2583 ///    ::= '(' ')'
2584 ///    ::= '(' Arg (',' Arg)* ')'
2585 ///  Arg
2586 ///    ::= Type OptionalAttributes Value OptionalAttributes
parseParameterList(SmallVectorImpl<ParamInfo> & ArgList,PerFunctionState & PFS,bool IsMustTailCall,bool InVarArgsFunc)2587 bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2588                                   PerFunctionState &PFS, bool IsMustTailCall,
2589                                   bool InVarArgsFunc) {
2590   if (parseToken(lltok::lparen, "expected '(' in call"))
2591     return true;
2592 
2593   while (Lex.getKind() != lltok::rparen) {
2594     // If this isn't the first argument, we need a comma.
2595     if (!ArgList.empty() &&
2596         parseToken(lltok::comma, "expected ',' in argument list"))
2597       return true;
2598 
2599     // parse an ellipsis if this is a musttail call in a variadic function.
2600     if (Lex.getKind() == lltok::dotdotdot) {
2601       const char *Msg = "unexpected ellipsis in argument list for ";
2602       if (!IsMustTailCall)
2603         return tokError(Twine(Msg) + "non-musttail call");
2604       if (!InVarArgsFunc)
2605         return tokError(Twine(Msg) + "musttail call in non-varargs function");
2606       Lex.Lex();  // Lex the '...', it is purely for readability.
2607       return parseToken(lltok::rparen, "expected ')' at end of argument list");
2608     }
2609 
2610     // parse the argument.
2611     LocTy ArgLoc;
2612     Type *ArgTy = nullptr;
2613     AttrBuilder ArgAttrs;
2614     Value *V;
2615     if (parseType(ArgTy, ArgLoc))
2616       return true;
2617 
2618     if (ArgTy->isMetadataTy()) {
2619       if (parseMetadataAsValue(V, PFS))
2620         return true;
2621     } else {
2622       // Otherwise, handle normal operands.
2623       if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
2624         return true;
2625     }
2626     ArgList.push_back(ParamInfo(
2627         ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2628   }
2629 
2630   if (IsMustTailCall && InVarArgsFunc)
2631     return tokError("expected '...' at end of argument list for musttail call "
2632                     "in varargs function");
2633 
2634   Lex.Lex();  // Lex the ')'.
2635   return false;
2636 }
2637 
2638 /// parseRequiredTypeAttr
2639 ///   ::= attrname(<ty>)
parseRequiredTypeAttr(Type * & Result,lltok::Kind AttrName)2640 bool LLParser::parseRequiredTypeAttr(Type *&Result, lltok::Kind AttrName) {
2641   Result = nullptr;
2642   if (!EatIfPresent(AttrName))
2643     return true;
2644   if (!EatIfPresent(lltok::lparen))
2645     return error(Lex.getLoc(), "expected '('");
2646   if (parseType(Result))
2647     return true;
2648   if (!EatIfPresent(lltok::rparen))
2649     return error(Lex.getLoc(), "expected ')'");
2650   return false;
2651 }
2652 
2653 /// parsePreallocated
2654 ///   ::= preallocated(<ty>)
parsePreallocated(Type * & Result)2655 bool LLParser::parsePreallocated(Type *&Result) {
2656   return parseRequiredTypeAttr(Result, lltok::kw_preallocated);
2657 }
2658 
2659 /// parseByRef
2660 ///   ::= byref(<type>)
parseByRef(Type * & Result)2661 bool LLParser::parseByRef(Type *&Result) {
2662   return parseRequiredTypeAttr(Result, lltok::kw_byref);
2663 }
2664 
2665 /// parseOptionalOperandBundles
2666 ///    ::= /*empty*/
2667 ///    ::= '[' OperandBundle [, OperandBundle ]* ']'
2668 ///
2669 /// OperandBundle
2670 ///    ::= bundle-tag '(' ')'
2671 ///    ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2672 ///
2673 /// bundle-tag ::= String Constant
parseOptionalOperandBundles(SmallVectorImpl<OperandBundleDef> & BundleList,PerFunctionState & PFS)2674 bool LLParser::parseOptionalOperandBundles(
2675     SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2676   LocTy BeginLoc = Lex.getLoc();
2677   if (!EatIfPresent(lltok::lsquare))
2678     return false;
2679 
2680   while (Lex.getKind() != lltok::rsquare) {
2681     // If this isn't the first operand bundle, we need a comma.
2682     if (!BundleList.empty() &&
2683         parseToken(lltok::comma, "expected ',' in input list"))
2684       return true;
2685 
2686     std::string Tag;
2687     if (parseStringConstant(Tag))
2688       return true;
2689 
2690     if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
2691       return true;
2692 
2693     std::vector<Value *> Inputs;
2694     while (Lex.getKind() != lltok::rparen) {
2695       // If this isn't the first input, we need a comma.
2696       if (!Inputs.empty() &&
2697           parseToken(lltok::comma, "expected ',' in input list"))
2698         return true;
2699 
2700       Type *Ty = nullptr;
2701       Value *Input = nullptr;
2702       if (parseType(Ty) || parseValue(Ty, Input, PFS))
2703         return true;
2704       Inputs.push_back(Input);
2705     }
2706 
2707     BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2708 
2709     Lex.Lex(); // Lex the ')'.
2710   }
2711 
2712   if (BundleList.empty())
2713     return error(BeginLoc, "operand bundle set must not be empty");
2714 
2715   Lex.Lex(); // Lex the ']'.
2716   return false;
2717 }
2718 
2719 /// parseArgumentList - parse the argument list for a function type or function
2720 /// prototype.
2721 ///   ::= '(' ArgTypeListI ')'
2722 /// ArgTypeListI
2723 ///   ::= /*empty*/
2724 ///   ::= '...'
2725 ///   ::= ArgTypeList ',' '...'
2726 ///   ::= ArgType (',' ArgType)*
2727 ///
parseArgumentList(SmallVectorImpl<ArgInfo> & ArgList,bool & IsVarArg)2728 bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2729                                  bool &IsVarArg) {
2730   unsigned CurValID = 0;
2731   IsVarArg = false;
2732   assert(Lex.getKind() == lltok::lparen);
2733   Lex.Lex(); // eat the (.
2734 
2735   if (Lex.getKind() == lltok::rparen) {
2736     // empty
2737   } else if (Lex.getKind() == lltok::dotdotdot) {
2738     IsVarArg = true;
2739     Lex.Lex();
2740   } else {
2741     LocTy TypeLoc = Lex.getLoc();
2742     Type *ArgTy = nullptr;
2743     AttrBuilder Attrs;
2744     std::string Name;
2745 
2746     if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2747       return true;
2748 
2749     if (ArgTy->isVoidTy())
2750       return error(TypeLoc, "argument can not have void type");
2751 
2752     if (Lex.getKind() == lltok::LocalVar) {
2753       Name = Lex.getStrVal();
2754       Lex.Lex();
2755     } else if (Lex.getKind() == lltok::LocalVarID) {
2756       if (Lex.getUIntVal() != CurValID)
2757         return error(TypeLoc, "argument expected to be numbered '%" +
2758                                   Twine(CurValID) + "'");
2759       ++CurValID;
2760       Lex.Lex();
2761     }
2762 
2763     if (!FunctionType::isValidArgumentType(ArgTy))
2764       return error(TypeLoc, "invalid type for function argument");
2765 
2766     ArgList.emplace_back(TypeLoc, ArgTy,
2767                          AttributeSet::get(ArgTy->getContext(), Attrs),
2768                          std::move(Name));
2769 
2770     while (EatIfPresent(lltok::comma)) {
2771       // Handle ... at end of arg list.
2772       if (EatIfPresent(lltok::dotdotdot)) {
2773         IsVarArg = true;
2774         break;
2775       }
2776 
2777       // Otherwise must be an argument type.
2778       TypeLoc = Lex.getLoc();
2779       if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2780         return true;
2781 
2782       if (ArgTy->isVoidTy())
2783         return error(TypeLoc, "argument can not have void type");
2784 
2785       if (Lex.getKind() == lltok::LocalVar) {
2786         Name = Lex.getStrVal();
2787         Lex.Lex();
2788       } else {
2789         if (Lex.getKind() == lltok::LocalVarID) {
2790           if (Lex.getUIntVal() != CurValID)
2791             return error(TypeLoc, "argument expected to be numbered '%" +
2792                                       Twine(CurValID) + "'");
2793           Lex.Lex();
2794         }
2795         ++CurValID;
2796         Name = "";
2797       }
2798 
2799       if (!ArgTy->isFirstClassType())
2800         return error(TypeLoc, "invalid type for function argument");
2801 
2802       ArgList.emplace_back(TypeLoc, ArgTy,
2803                            AttributeSet::get(ArgTy->getContext(), Attrs),
2804                            std::move(Name));
2805     }
2806   }
2807 
2808   return parseToken(lltok::rparen, "expected ')' at end of argument list");
2809 }
2810 
2811 /// parseFunctionType
2812 ///  ::= Type ArgumentList OptionalAttrs
parseFunctionType(Type * & Result)2813 bool LLParser::parseFunctionType(Type *&Result) {
2814   assert(Lex.getKind() == lltok::lparen);
2815 
2816   if (!FunctionType::isValidReturnType(Result))
2817     return tokError("invalid function return type");
2818 
2819   SmallVector<ArgInfo, 8> ArgList;
2820   bool IsVarArg;
2821   if (parseArgumentList(ArgList, IsVarArg))
2822     return true;
2823 
2824   // Reject names on the arguments lists.
2825   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2826     if (!ArgList[i].Name.empty())
2827       return error(ArgList[i].Loc, "argument name invalid in function type");
2828     if (ArgList[i].Attrs.hasAttributes())
2829       return error(ArgList[i].Loc,
2830                    "argument attributes invalid in function type");
2831   }
2832 
2833   SmallVector<Type*, 16> ArgListTy;
2834   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2835     ArgListTy.push_back(ArgList[i].Ty);
2836 
2837   Result = FunctionType::get(Result, ArgListTy, IsVarArg);
2838   return false;
2839 }
2840 
2841 /// parseAnonStructType - parse an anonymous struct type, which is inlined into
2842 /// other structs.
parseAnonStructType(Type * & Result,bool Packed)2843 bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
2844   SmallVector<Type*, 8> Elts;
2845   if (parseStructBody(Elts))
2846     return true;
2847 
2848   Result = StructType::get(Context, Elts, Packed);
2849   return false;
2850 }
2851 
2852 /// parseStructDefinition - parse a struct in a 'type' definition.
parseStructDefinition(SMLoc TypeLoc,StringRef Name,std::pair<Type *,LocTy> & Entry,Type * & ResultTy)2853 bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
2854                                      std::pair<Type *, LocTy> &Entry,
2855                                      Type *&ResultTy) {
2856   // If the type was already defined, diagnose the redefinition.
2857   if (Entry.first && !Entry.second.isValid())
2858     return error(TypeLoc, "redefinition of type");
2859 
2860   // If we have opaque, just return without filling in the definition for the
2861   // struct.  This counts as a definition as far as the .ll file goes.
2862   if (EatIfPresent(lltok::kw_opaque)) {
2863     // This type is being defined, so clear the location to indicate this.
2864     Entry.second = SMLoc();
2865 
2866     // If this type number has never been uttered, create it.
2867     if (!Entry.first)
2868       Entry.first = StructType::create(Context, Name);
2869     ResultTy = Entry.first;
2870     return false;
2871   }
2872 
2873   // If the type starts with '<', then it is either a packed struct or a vector.
2874   bool isPacked = EatIfPresent(lltok::less);
2875 
2876   // If we don't have a struct, then we have a random type alias, which we
2877   // accept for compatibility with old files.  These types are not allowed to be
2878   // forward referenced and not allowed to be recursive.
2879   if (Lex.getKind() != lltok::lbrace) {
2880     if (Entry.first)
2881       return error(TypeLoc, "forward references to non-struct type");
2882 
2883     ResultTy = nullptr;
2884     if (isPacked)
2885       return parseArrayVectorType(ResultTy, true);
2886     return parseType(ResultTy);
2887   }
2888 
2889   // This type is being defined, so clear the location to indicate this.
2890   Entry.second = SMLoc();
2891 
2892   // If this type number has never been uttered, create it.
2893   if (!Entry.first)
2894     Entry.first = StructType::create(Context, Name);
2895 
2896   StructType *STy = cast<StructType>(Entry.first);
2897 
2898   SmallVector<Type*, 8> Body;
2899   if (parseStructBody(Body) ||
2900       (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
2901     return true;
2902 
2903   STy->setBody(Body, isPacked);
2904   ResultTy = STy;
2905   return false;
2906 }
2907 
2908 /// parseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
2909 ///   StructType
2910 ///     ::= '{' '}'
2911 ///     ::= '{' Type (',' Type)* '}'
2912 ///     ::= '<' '{' '}' '>'
2913 ///     ::= '<' '{' Type (',' Type)* '}' '>'
parseStructBody(SmallVectorImpl<Type * > & Body)2914 bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
2915   assert(Lex.getKind() == lltok::lbrace);
2916   Lex.Lex(); // Consume the '{'
2917 
2918   // Handle the empty struct.
2919   if (EatIfPresent(lltok::rbrace))
2920     return false;
2921 
2922   LocTy EltTyLoc = Lex.getLoc();
2923   Type *Ty = nullptr;
2924   if (parseType(Ty))
2925     return true;
2926   Body.push_back(Ty);
2927 
2928   if (!StructType::isValidElementType(Ty))
2929     return error(EltTyLoc, "invalid element type for struct");
2930 
2931   while (EatIfPresent(lltok::comma)) {
2932     EltTyLoc = Lex.getLoc();
2933     if (parseType(Ty))
2934       return true;
2935 
2936     if (!StructType::isValidElementType(Ty))
2937       return error(EltTyLoc, "invalid element type for struct");
2938 
2939     Body.push_back(Ty);
2940   }
2941 
2942   return parseToken(lltok::rbrace, "expected '}' at end of struct");
2943 }
2944 
2945 /// parseArrayVectorType - parse an array or vector type, assuming the first
2946 /// token has already been consumed.
2947 ///   Type
2948 ///     ::= '[' APSINTVAL 'x' Types ']'
2949 ///     ::= '<' APSINTVAL 'x' Types '>'
2950 ///     ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
parseArrayVectorType(Type * & Result,bool IsVector)2951 bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
2952   bool Scalable = false;
2953 
2954   if (IsVector && Lex.getKind() == lltok::kw_vscale) {
2955     Lex.Lex(); // consume the 'vscale'
2956     if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
2957       return true;
2958 
2959     Scalable = true;
2960   }
2961 
2962   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2963       Lex.getAPSIntVal().getBitWidth() > 64)
2964     return tokError("expected number in address space");
2965 
2966   LocTy SizeLoc = Lex.getLoc();
2967   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2968   Lex.Lex();
2969 
2970   if (parseToken(lltok::kw_x, "expected 'x' after element count"))
2971     return true;
2972 
2973   LocTy TypeLoc = Lex.getLoc();
2974   Type *EltTy = nullptr;
2975   if (parseType(EltTy))
2976     return true;
2977 
2978   if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
2979                  "expected end of sequential type"))
2980     return true;
2981 
2982   if (IsVector) {
2983     if (Size == 0)
2984       return error(SizeLoc, "zero element vector is illegal");
2985     if ((unsigned)Size != Size)
2986       return error(SizeLoc, "size too large for vector");
2987     if (!VectorType::isValidElementType(EltTy))
2988       return error(TypeLoc, "invalid vector element type");
2989     Result = VectorType::get(EltTy, unsigned(Size), Scalable);
2990   } else {
2991     if (!ArrayType::isValidElementType(EltTy))
2992       return error(TypeLoc, "invalid array element type");
2993     Result = ArrayType::get(EltTy, Size);
2994   }
2995   return false;
2996 }
2997 
2998 //===----------------------------------------------------------------------===//
2999 // Function Semantic Analysis.
3000 //===----------------------------------------------------------------------===//
3001 
PerFunctionState(LLParser & p,Function & f,int functionNumber)3002 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3003                                              int functionNumber)
3004   : P(p), F(f), FunctionNumber(functionNumber) {
3005 
3006   // Insert unnamed arguments into the NumberedVals list.
3007   for (Argument &A : F.args())
3008     if (!A.hasName())
3009       NumberedVals.push_back(&A);
3010 }
3011 
~PerFunctionState()3012 LLParser::PerFunctionState::~PerFunctionState() {
3013   // If there were any forward referenced non-basicblock values, delete them.
3014 
3015   for (const auto &P : ForwardRefVals) {
3016     if (isa<BasicBlock>(P.second.first))
3017       continue;
3018     P.second.first->replaceAllUsesWith(
3019         UndefValue::get(P.second.first->getType()));
3020     P.second.first->deleteValue();
3021   }
3022 
3023   for (const auto &P : ForwardRefValIDs) {
3024     if (isa<BasicBlock>(P.second.first))
3025       continue;
3026     P.second.first->replaceAllUsesWith(
3027         UndefValue::get(P.second.first->getType()));
3028     P.second.first->deleteValue();
3029   }
3030 }
3031 
finishFunction()3032 bool LLParser::PerFunctionState::finishFunction() {
3033   if (!ForwardRefVals.empty())
3034     return P.error(ForwardRefVals.begin()->second.second,
3035                    "use of undefined value '%" + ForwardRefVals.begin()->first +
3036                        "'");
3037   if (!ForwardRefValIDs.empty())
3038     return P.error(ForwardRefValIDs.begin()->second.second,
3039                    "use of undefined value '%" +
3040                        Twine(ForwardRefValIDs.begin()->first) + "'");
3041   return false;
3042 }
3043 
3044 /// getVal - Get a value with the specified name or ID, creating a
3045 /// forward reference record if needed.  This can return null if the value
3046 /// exists but does not have the right type.
getVal(const std::string & Name,Type * Ty,LocTy Loc,bool IsCall)3047 Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3048                                           LocTy Loc, bool IsCall) {
3049   // Look this name up in the normal function symbol table.
3050   Value *Val = F.getValueSymbolTable()->lookup(Name);
3051 
3052   // If this is a forward reference for the value, see if we already created a
3053   // forward ref record.
3054   if (!Val) {
3055     auto I = ForwardRefVals.find(Name);
3056     if (I != ForwardRefVals.end())
3057       Val = I->second.first;
3058   }
3059 
3060   // If we have the value in the symbol table or fwd-ref table, return it.
3061   if (Val)
3062     return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
3063 
3064   // Don't make placeholders with invalid type.
3065   if (!Ty->isFirstClassType()) {
3066     P.error(Loc, "invalid use of a non-first-class type");
3067     return nullptr;
3068   }
3069 
3070   // Otherwise, create a new forward reference for this value and remember it.
3071   Value *FwdVal;
3072   if (Ty->isLabelTy()) {
3073     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3074   } else {
3075     FwdVal = new Argument(Ty, Name);
3076   }
3077 
3078   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3079   return FwdVal;
3080 }
3081 
getVal(unsigned ID,Type * Ty,LocTy Loc,bool IsCall)3082 Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc,
3083                                           bool IsCall) {
3084   // Look this name up in the normal function symbol table.
3085   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
3086 
3087   // If this is a forward reference for the value, see if we already created a
3088   // forward ref record.
3089   if (!Val) {
3090     auto I = ForwardRefValIDs.find(ID);
3091     if (I != ForwardRefValIDs.end())
3092       Val = I->second.first;
3093   }
3094 
3095   // If we have the value in the symbol table or fwd-ref table, return it.
3096   if (Val)
3097     return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
3098 
3099   if (!Ty->isFirstClassType()) {
3100     P.error(Loc, "invalid use of a non-first-class type");
3101     return nullptr;
3102   }
3103 
3104   // Otherwise, create a new forward reference for this value and remember it.
3105   Value *FwdVal;
3106   if (Ty->isLabelTy()) {
3107     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3108   } else {
3109     FwdVal = new Argument(Ty);
3110   }
3111 
3112   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3113   return FwdVal;
3114 }
3115 
3116 /// setInstName - After an instruction is parsed and inserted into its
3117 /// basic block, this installs its name.
setInstName(int NameID,const std::string & NameStr,LocTy NameLoc,Instruction * Inst)3118 bool LLParser::PerFunctionState::setInstName(int NameID,
3119                                              const std::string &NameStr,
3120                                              LocTy NameLoc, Instruction *Inst) {
3121   // If this instruction has void type, it cannot have a name or ID specified.
3122   if (Inst->getType()->isVoidTy()) {
3123     if (NameID != -1 || !NameStr.empty())
3124       return P.error(NameLoc, "instructions returning void cannot have a name");
3125     return false;
3126   }
3127 
3128   // If this was a numbered instruction, verify that the instruction is the
3129   // expected value and resolve any forward references.
3130   if (NameStr.empty()) {
3131     // If neither a name nor an ID was specified, just use the next ID.
3132     if (NameID == -1)
3133       NameID = NumberedVals.size();
3134 
3135     if (unsigned(NameID) != NumberedVals.size())
3136       return P.error(NameLoc, "instruction expected to be numbered '%" +
3137                                   Twine(NumberedVals.size()) + "'");
3138 
3139     auto FI = ForwardRefValIDs.find(NameID);
3140     if (FI != ForwardRefValIDs.end()) {
3141       Value *Sentinel = FI->second.first;
3142       if (Sentinel->getType() != Inst->getType())
3143         return P.error(NameLoc, "instruction forward referenced with type '" +
3144                                     getTypeString(FI->second.first->getType()) +
3145                                     "'");
3146 
3147       Sentinel->replaceAllUsesWith(Inst);
3148       Sentinel->deleteValue();
3149       ForwardRefValIDs.erase(FI);
3150     }
3151 
3152     NumberedVals.push_back(Inst);
3153     return false;
3154   }
3155 
3156   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
3157   auto FI = ForwardRefVals.find(NameStr);
3158   if (FI != ForwardRefVals.end()) {
3159     Value *Sentinel = FI->second.first;
3160     if (Sentinel->getType() != Inst->getType())
3161       return P.error(NameLoc, "instruction forward referenced with type '" +
3162                                   getTypeString(FI->second.first->getType()) +
3163                                   "'");
3164 
3165     Sentinel->replaceAllUsesWith(Inst);
3166     Sentinel->deleteValue();
3167     ForwardRefVals.erase(FI);
3168   }
3169 
3170   // Set the name on the instruction.
3171   Inst->setName(NameStr);
3172 
3173   if (Inst->getName() != NameStr)
3174     return P.error(NameLoc, "multiple definition of local value named '" +
3175                                 NameStr + "'");
3176   return false;
3177 }
3178 
3179 /// getBB - Get a basic block with the specified name or ID, creating a
3180 /// forward reference record if needed.
getBB(const std::string & Name,LocTy Loc)3181 BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3182                                               LocTy Loc) {
3183   return dyn_cast_or_null<BasicBlock>(
3184       getVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
3185 }
3186 
getBB(unsigned ID,LocTy Loc)3187 BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3188   return dyn_cast_or_null<BasicBlock>(
3189       getVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
3190 }
3191 
3192 /// defineBB - Define the specified basic block, which is either named or
3193 /// unnamed.  If there is an error, this returns null otherwise it returns
3194 /// the block being defined.
defineBB(const std::string & Name,int NameID,LocTy Loc)3195 BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3196                                                  int NameID, LocTy Loc) {
3197   BasicBlock *BB;
3198   if (Name.empty()) {
3199     if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
3200       P.error(Loc, "label expected to be numbered '" +
3201                        Twine(NumberedVals.size()) + "'");
3202       return nullptr;
3203     }
3204     BB = getBB(NumberedVals.size(), Loc);
3205     if (!BB) {
3206       P.error(Loc, "unable to create block numbered '" +
3207                        Twine(NumberedVals.size()) + "'");
3208       return nullptr;
3209     }
3210   } else {
3211     BB = getBB(Name, Loc);
3212     if (!BB) {
3213       P.error(Loc, "unable to create block named '" + Name + "'");
3214       return nullptr;
3215     }
3216   }
3217 
3218   // Move the block to the end of the function.  Forward ref'd blocks are
3219   // inserted wherever they happen to be referenced.
3220   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
3221 
3222   // Remove the block from forward ref sets.
3223   if (Name.empty()) {
3224     ForwardRefValIDs.erase(NumberedVals.size());
3225     NumberedVals.push_back(BB);
3226   } else {
3227     // BB forward references are already in the function symbol table.
3228     ForwardRefVals.erase(Name);
3229   }
3230 
3231   return BB;
3232 }
3233 
3234 //===----------------------------------------------------------------------===//
3235 // Constants.
3236 //===----------------------------------------------------------------------===//
3237 
3238 /// parseValID - parse an abstract value that doesn't necessarily have a
3239 /// type implied.  For example, if we parse "4" we don't know what integer type
3240 /// it has.  The value will later be combined with its type and checked for
3241 /// sanity.  PFS is used to convert function-local operands of metadata (since
3242 /// metadata operands are not just parsed here but also converted to values).
3243 /// PFS can be null when we are not parsing metadata values inside a function.
parseValID(ValID & ID,PerFunctionState * PFS)3244 bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS) {
3245   ID.Loc = Lex.getLoc();
3246   switch (Lex.getKind()) {
3247   default:
3248     return tokError("expected value token");
3249   case lltok::GlobalID:  // @42
3250     ID.UIntVal = Lex.getUIntVal();
3251     ID.Kind = ValID::t_GlobalID;
3252     break;
3253   case lltok::GlobalVar:  // @foo
3254     ID.StrVal = Lex.getStrVal();
3255     ID.Kind = ValID::t_GlobalName;
3256     break;
3257   case lltok::LocalVarID:  // %42
3258     ID.UIntVal = Lex.getUIntVal();
3259     ID.Kind = ValID::t_LocalID;
3260     break;
3261   case lltok::LocalVar:  // %foo
3262     ID.StrVal = Lex.getStrVal();
3263     ID.Kind = ValID::t_LocalName;
3264     break;
3265   case lltok::APSInt:
3266     ID.APSIntVal = Lex.getAPSIntVal();
3267     ID.Kind = ValID::t_APSInt;
3268     break;
3269   case lltok::APFloat:
3270     ID.APFloatVal = Lex.getAPFloatVal();
3271     ID.Kind = ValID::t_APFloat;
3272     break;
3273   case lltok::kw_true:
3274     ID.ConstantVal = ConstantInt::getTrue(Context);
3275     ID.Kind = ValID::t_Constant;
3276     break;
3277   case lltok::kw_false:
3278     ID.ConstantVal = ConstantInt::getFalse(Context);
3279     ID.Kind = ValID::t_Constant;
3280     break;
3281   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3282   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3283   case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3284   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3285   case lltok::kw_none: ID.Kind = ValID::t_None; break;
3286 
3287   case lltok::lbrace: {
3288     // ValID ::= '{' ConstVector '}'
3289     Lex.Lex();
3290     SmallVector<Constant*, 16> Elts;
3291     if (parseGlobalValueVector(Elts) ||
3292         parseToken(lltok::rbrace, "expected end of struct constant"))
3293       return true;
3294 
3295     ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3296     ID.UIntVal = Elts.size();
3297     memcpy(ID.ConstantStructElts.get(), Elts.data(),
3298            Elts.size() * sizeof(Elts[0]));
3299     ID.Kind = ValID::t_ConstantStruct;
3300     return false;
3301   }
3302   case lltok::less: {
3303     // ValID ::= '<' ConstVector '>'         --> Vector.
3304     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3305     Lex.Lex();
3306     bool isPackedStruct = EatIfPresent(lltok::lbrace);
3307 
3308     SmallVector<Constant*, 16> Elts;
3309     LocTy FirstEltLoc = Lex.getLoc();
3310     if (parseGlobalValueVector(Elts) ||
3311         (isPackedStruct &&
3312          parseToken(lltok::rbrace, "expected end of packed struct")) ||
3313         parseToken(lltok::greater, "expected end of constant"))
3314       return true;
3315 
3316     if (isPackedStruct) {
3317       ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3318       memcpy(ID.ConstantStructElts.get(), Elts.data(),
3319              Elts.size() * sizeof(Elts[0]));
3320       ID.UIntVal = Elts.size();
3321       ID.Kind = ValID::t_PackedConstantStruct;
3322       return false;
3323     }
3324 
3325     if (Elts.empty())
3326       return error(ID.Loc, "constant vector must not be empty");
3327 
3328     if (!Elts[0]->getType()->isIntegerTy() &&
3329         !Elts[0]->getType()->isFloatingPointTy() &&
3330         !Elts[0]->getType()->isPointerTy())
3331       return error(
3332           FirstEltLoc,
3333           "vector elements must have integer, pointer or floating point type");
3334 
3335     // Verify that all the vector elements have the same type.
3336     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3337       if (Elts[i]->getType() != Elts[0]->getType())
3338         return error(FirstEltLoc, "vector element #" + Twine(i) +
3339                                       " is not of type '" +
3340                                       getTypeString(Elts[0]->getType()));
3341 
3342     ID.ConstantVal = ConstantVector::get(Elts);
3343     ID.Kind = ValID::t_Constant;
3344     return false;
3345   }
3346   case lltok::lsquare: {   // Array Constant
3347     Lex.Lex();
3348     SmallVector<Constant*, 16> Elts;
3349     LocTy FirstEltLoc = Lex.getLoc();
3350     if (parseGlobalValueVector(Elts) ||
3351         parseToken(lltok::rsquare, "expected end of array constant"))
3352       return true;
3353 
3354     // Handle empty element.
3355     if (Elts.empty()) {
3356       // Use undef instead of an array because it's inconvenient to determine
3357       // the element type at this point, there being no elements to examine.
3358       ID.Kind = ValID::t_EmptyArray;
3359       return false;
3360     }
3361 
3362     if (!Elts[0]->getType()->isFirstClassType())
3363       return error(FirstEltLoc, "invalid array element type: " +
3364                                     getTypeString(Elts[0]->getType()));
3365 
3366     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3367 
3368     // Verify all elements are correct type!
3369     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3370       if (Elts[i]->getType() != Elts[0]->getType())
3371         return error(FirstEltLoc, "array element #" + Twine(i) +
3372                                       " is not of type '" +
3373                                       getTypeString(Elts[0]->getType()));
3374     }
3375 
3376     ID.ConstantVal = ConstantArray::get(ATy, Elts);
3377     ID.Kind = ValID::t_Constant;
3378     return false;
3379   }
3380   case lltok::kw_c:  // c "foo"
3381     Lex.Lex();
3382     ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3383                                                   false);
3384     if (parseToken(lltok::StringConstant, "expected string"))
3385       return true;
3386     ID.Kind = ValID::t_Constant;
3387     return false;
3388 
3389   case lltok::kw_asm: {
3390     // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3391     //             STRINGCONSTANT
3392     bool HasSideEffect, AlignStack, AsmDialect;
3393     Lex.Lex();
3394     if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3395         parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3396         parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3397         parseStringConstant(ID.StrVal) ||
3398         parseToken(lltok::comma, "expected comma in inline asm expression") ||
3399         parseToken(lltok::StringConstant, "expected constraint string"))
3400       return true;
3401     ID.StrVal2 = Lex.getStrVal();
3402     ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
3403       (unsigned(AsmDialect)<<2);
3404     ID.Kind = ValID::t_InlineAsm;
3405     return false;
3406   }
3407 
3408   case lltok::kw_blockaddress: {
3409     // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3410     Lex.Lex();
3411 
3412     ValID Fn, Label;
3413 
3414     if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
3415         parseValID(Fn) ||
3416         parseToken(lltok::comma,
3417                    "expected comma in block address expression") ||
3418         parseValID(Label) ||
3419         parseToken(lltok::rparen, "expected ')' in block address expression"))
3420       return true;
3421 
3422     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3423       return error(Fn.Loc, "expected function name in blockaddress");
3424     if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3425       return error(Label.Loc, "expected basic block name in blockaddress");
3426 
3427     // Try to find the function (but skip it if it's forward-referenced).
3428     GlobalValue *GV = nullptr;
3429     if (Fn.Kind == ValID::t_GlobalID) {
3430       if (Fn.UIntVal < NumberedVals.size())
3431         GV = NumberedVals[Fn.UIntVal];
3432     } else if (!ForwardRefVals.count(Fn.StrVal)) {
3433       GV = M->getNamedValue(Fn.StrVal);
3434     }
3435     Function *F = nullptr;
3436     if (GV) {
3437       // Confirm that it's actually a function with a definition.
3438       if (!isa<Function>(GV))
3439         return error(Fn.Loc, "expected function name in blockaddress");
3440       F = cast<Function>(GV);
3441       if (F->isDeclaration())
3442         return error(Fn.Loc, "cannot take blockaddress inside a declaration");
3443     }
3444 
3445     if (!F) {
3446       // Make a global variable as a placeholder for this reference.
3447       GlobalValue *&FwdRef =
3448           ForwardRefBlockAddresses.insert(std::make_pair(
3449                                               std::move(Fn),
3450                                               std::map<ValID, GlobalValue *>()))
3451               .first->second.insert(std::make_pair(std::move(Label), nullptr))
3452               .first->second;
3453       if (!FwdRef)
3454         FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3455                                     GlobalValue::InternalLinkage, nullptr, "");
3456       ID.ConstantVal = FwdRef;
3457       ID.Kind = ValID::t_Constant;
3458       return false;
3459     }
3460 
3461     // We found the function; now find the basic block.  Don't use PFS, since we
3462     // might be inside a constant expression.
3463     BasicBlock *BB;
3464     if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3465       if (Label.Kind == ValID::t_LocalID)
3466         BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
3467       else
3468         BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
3469       if (!BB)
3470         return error(Label.Loc, "referenced value is not a basic block");
3471     } else {
3472       if (Label.Kind == ValID::t_LocalID)
3473         return error(Label.Loc, "cannot take address of numeric label after "
3474                                 "the function is defined");
3475       BB = dyn_cast_or_null<BasicBlock>(
3476           F->getValueSymbolTable()->lookup(Label.StrVal));
3477       if (!BB)
3478         return error(Label.Loc, "referenced value is not a basic block");
3479     }
3480 
3481     ID.ConstantVal = BlockAddress::get(F, BB);
3482     ID.Kind = ValID::t_Constant;
3483     return false;
3484   }
3485 
3486   case lltok::kw_dso_local_equivalent: {
3487     // ValID ::= 'dso_local_equivalent' @foo
3488     Lex.Lex();
3489 
3490     ValID Fn;
3491 
3492     if (parseValID(Fn))
3493       return true;
3494 
3495     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3496       return error(Fn.Loc,
3497                    "expected global value name in dso_local_equivalent");
3498 
3499     // Try to find the function (but skip it if it's forward-referenced).
3500     GlobalValue *GV = nullptr;
3501     if (Fn.Kind == ValID::t_GlobalID) {
3502       if (Fn.UIntVal < NumberedVals.size())
3503         GV = NumberedVals[Fn.UIntVal];
3504     } else if (!ForwardRefVals.count(Fn.StrVal)) {
3505       GV = M->getNamedValue(Fn.StrVal);
3506     }
3507 
3508     assert(GV && "Could not find a corresponding global variable");
3509 
3510     if (!GV->getValueType()->isFunctionTy())
3511       return error(Fn.Loc, "expected a function, alias to function, or ifunc "
3512                            "in dso_local_equivalent");
3513 
3514     ID.ConstantVal = DSOLocalEquivalent::get(GV);
3515     ID.Kind = ValID::t_Constant;
3516     return false;
3517   }
3518 
3519   case lltok::kw_trunc:
3520   case lltok::kw_zext:
3521   case lltok::kw_sext:
3522   case lltok::kw_fptrunc:
3523   case lltok::kw_fpext:
3524   case lltok::kw_bitcast:
3525   case lltok::kw_addrspacecast:
3526   case lltok::kw_uitofp:
3527   case lltok::kw_sitofp:
3528   case lltok::kw_fptoui:
3529   case lltok::kw_fptosi:
3530   case lltok::kw_inttoptr:
3531   case lltok::kw_ptrtoint: {
3532     unsigned Opc = Lex.getUIntVal();
3533     Type *DestTy = nullptr;
3534     Constant *SrcVal;
3535     Lex.Lex();
3536     if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3537         parseGlobalTypeAndValue(SrcVal) ||
3538         parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3539         parseType(DestTy) ||
3540         parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3541       return true;
3542     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3543       return error(ID.Loc, "invalid cast opcode for cast from '" +
3544                                getTypeString(SrcVal->getType()) + "' to '" +
3545                                getTypeString(DestTy) + "'");
3546     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3547                                                  SrcVal, DestTy);
3548     ID.Kind = ValID::t_Constant;
3549     return false;
3550   }
3551   case lltok::kw_extractvalue: {
3552     Lex.Lex();
3553     Constant *Val;
3554     SmallVector<unsigned, 4> Indices;
3555     if (parseToken(lltok::lparen,
3556                    "expected '(' in extractvalue constantexpr") ||
3557         parseGlobalTypeAndValue(Val) || parseIndexList(Indices) ||
3558         parseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3559       return true;
3560 
3561     if (!Val->getType()->isAggregateType())
3562       return error(ID.Loc, "extractvalue operand must be aggregate type");
3563     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3564       return error(ID.Loc, "invalid indices for extractvalue");
3565     ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3566     ID.Kind = ValID::t_Constant;
3567     return false;
3568   }
3569   case lltok::kw_insertvalue: {
3570     Lex.Lex();
3571     Constant *Val0, *Val1;
3572     SmallVector<unsigned, 4> Indices;
3573     if (parseToken(lltok::lparen, "expected '(' in insertvalue constantexpr") ||
3574         parseGlobalTypeAndValue(Val0) ||
3575         parseToken(lltok::comma,
3576                    "expected comma in insertvalue constantexpr") ||
3577         parseGlobalTypeAndValue(Val1) || parseIndexList(Indices) ||
3578         parseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3579       return true;
3580     if (!Val0->getType()->isAggregateType())
3581       return error(ID.Loc, "insertvalue operand must be aggregate type");
3582     Type *IndexedType =
3583         ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3584     if (!IndexedType)
3585       return error(ID.Loc, "invalid indices for insertvalue");
3586     if (IndexedType != Val1->getType())
3587       return error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3588                                getTypeString(Val1->getType()) +
3589                                "' instead of '" + getTypeString(IndexedType) +
3590                                "'");
3591     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3592     ID.Kind = ValID::t_Constant;
3593     return false;
3594   }
3595   case lltok::kw_icmp:
3596   case lltok::kw_fcmp: {
3597     unsigned PredVal, Opc = Lex.getUIntVal();
3598     Constant *Val0, *Val1;
3599     Lex.Lex();
3600     if (parseCmpPredicate(PredVal, Opc) ||
3601         parseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3602         parseGlobalTypeAndValue(Val0) ||
3603         parseToken(lltok::comma, "expected comma in compare constantexpr") ||
3604         parseGlobalTypeAndValue(Val1) ||
3605         parseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3606       return true;
3607 
3608     if (Val0->getType() != Val1->getType())
3609       return error(ID.Loc, "compare operands must have the same type");
3610 
3611     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3612 
3613     if (Opc == Instruction::FCmp) {
3614       if (!Val0->getType()->isFPOrFPVectorTy())
3615         return error(ID.Loc, "fcmp requires floating point operands");
3616       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3617     } else {
3618       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3619       if (!Val0->getType()->isIntOrIntVectorTy() &&
3620           !Val0->getType()->isPtrOrPtrVectorTy())
3621         return error(ID.Loc, "icmp requires pointer or integer operands");
3622       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3623     }
3624     ID.Kind = ValID::t_Constant;
3625     return false;
3626   }
3627 
3628   // Unary Operators.
3629   case lltok::kw_fneg: {
3630     unsigned Opc = Lex.getUIntVal();
3631     Constant *Val;
3632     Lex.Lex();
3633     if (parseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3634         parseGlobalTypeAndValue(Val) ||
3635         parseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3636       return true;
3637 
3638     // Check that the type is valid for the operator.
3639     switch (Opc) {
3640     case Instruction::FNeg:
3641       if (!Val->getType()->isFPOrFPVectorTy())
3642         return error(ID.Loc, "constexpr requires fp operands");
3643       break;
3644     default: llvm_unreachable("Unknown unary operator!");
3645     }
3646     unsigned Flags = 0;
3647     Constant *C = ConstantExpr::get(Opc, Val, Flags);
3648     ID.ConstantVal = C;
3649     ID.Kind = ValID::t_Constant;
3650     return false;
3651   }
3652   // Binary Operators.
3653   case lltok::kw_add:
3654   case lltok::kw_fadd:
3655   case lltok::kw_sub:
3656   case lltok::kw_fsub:
3657   case lltok::kw_mul:
3658   case lltok::kw_fmul:
3659   case lltok::kw_udiv:
3660   case lltok::kw_sdiv:
3661   case lltok::kw_fdiv:
3662   case lltok::kw_urem:
3663   case lltok::kw_srem:
3664   case lltok::kw_frem:
3665   case lltok::kw_shl:
3666   case lltok::kw_lshr:
3667   case lltok::kw_ashr: {
3668     bool NUW = false;
3669     bool NSW = false;
3670     bool Exact = false;
3671     unsigned Opc = Lex.getUIntVal();
3672     Constant *Val0, *Val1;
3673     Lex.Lex();
3674     if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3675         Opc == Instruction::Mul || Opc == Instruction::Shl) {
3676       if (EatIfPresent(lltok::kw_nuw))
3677         NUW = true;
3678       if (EatIfPresent(lltok::kw_nsw)) {
3679         NSW = true;
3680         if (EatIfPresent(lltok::kw_nuw))
3681           NUW = true;
3682       }
3683     } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3684                Opc == Instruction::LShr || Opc == Instruction::AShr) {
3685       if (EatIfPresent(lltok::kw_exact))
3686         Exact = true;
3687     }
3688     if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3689         parseGlobalTypeAndValue(Val0) ||
3690         parseToken(lltok::comma, "expected comma in binary constantexpr") ||
3691         parseGlobalTypeAndValue(Val1) ||
3692         parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3693       return true;
3694     if (Val0->getType() != Val1->getType())
3695       return error(ID.Loc, "operands of constexpr must have same type");
3696     // Check that the type is valid for the operator.
3697     switch (Opc) {
3698     case Instruction::Add:
3699     case Instruction::Sub:
3700     case Instruction::Mul:
3701     case Instruction::UDiv:
3702     case Instruction::SDiv:
3703     case Instruction::URem:
3704     case Instruction::SRem:
3705     case Instruction::Shl:
3706     case Instruction::AShr:
3707     case Instruction::LShr:
3708       if (!Val0->getType()->isIntOrIntVectorTy())
3709         return error(ID.Loc, "constexpr requires integer operands");
3710       break;
3711     case Instruction::FAdd:
3712     case Instruction::FSub:
3713     case Instruction::FMul:
3714     case Instruction::FDiv:
3715     case Instruction::FRem:
3716       if (!Val0->getType()->isFPOrFPVectorTy())
3717         return error(ID.Loc, "constexpr requires fp operands");
3718       break;
3719     default: llvm_unreachable("Unknown binary operator!");
3720     }
3721     unsigned Flags = 0;
3722     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3723     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
3724     if (Exact) Flags |= PossiblyExactOperator::IsExact;
3725     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3726     ID.ConstantVal = C;
3727     ID.Kind = ValID::t_Constant;
3728     return false;
3729   }
3730 
3731   // Logical Operations
3732   case lltok::kw_and:
3733   case lltok::kw_or:
3734   case lltok::kw_xor: {
3735     unsigned Opc = Lex.getUIntVal();
3736     Constant *Val0, *Val1;
3737     Lex.Lex();
3738     if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3739         parseGlobalTypeAndValue(Val0) ||
3740         parseToken(lltok::comma, "expected comma in logical constantexpr") ||
3741         parseGlobalTypeAndValue(Val1) ||
3742         parseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3743       return true;
3744     if (Val0->getType() != Val1->getType())
3745       return error(ID.Loc, "operands of constexpr must have same type");
3746     if (!Val0->getType()->isIntOrIntVectorTy())
3747       return error(ID.Loc,
3748                    "constexpr requires integer or integer vector operands");
3749     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3750     ID.Kind = ValID::t_Constant;
3751     return false;
3752   }
3753 
3754   case lltok::kw_getelementptr:
3755   case lltok::kw_shufflevector:
3756   case lltok::kw_insertelement:
3757   case lltok::kw_extractelement:
3758   case lltok::kw_select: {
3759     unsigned Opc = Lex.getUIntVal();
3760     SmallVector<Constant*, 16> Elts;
3761     bool InBounds = false;
3762     Type *Ty;
3763     Lex.Lex();
3764 
3765     if (Opc == Instruction::GetElementPtr)
3766       InBounds = EatIfPresent(lltok::kw_inbounds);
3767 
3768     if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
3769       return true;
3770 
3771     LocTy ExplicitTypeLoc = Lex.getLoc();
3772     if (Opc == Instruction::GetElementPtr) {
3773       if (parseType(Ty) ||
3774           parseToken(lltok::comma, "expected comma after getelementptr's type"))
3775         return true;
3776     }
3777 
3778     Optional<unsigned> InRangeOp;
3779     if (parseGlobalValueVector(
3780             Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3781         parseToken(lltok::rparen, "expected ')' in constantexpr"))
3782       return true;
3783 
3784     if (Opc == Instruction::GetElementPtr) {
3785       if (Elts.size() == 0 ||
3786           !Elts[0]->getType()->isPtrOrPtrVectorTy())
3787         return error(ID.Loc, "base of getelementptr must be a pointer");
3788 
3789       Type *BaseType = Elts[0]->getType();
3790       auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3791       if (Ty != BasePointerType->getElementType())
3792         return error(
3793             ExplicitTypeLoc,
3794             "explicit pointee type doesn't match operand's pointee type");
3795 
3796       unsigned GEPWidth =
3797           BaseType->isVectorTy()
3798               ? cast<FixedVectorType>(BaseType)->getNumElements()
3799               : 0;
3800 
3801       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3802       for (Constant *Val : Indices) {
3803         Type *ValTy = Val->getType();
3804         if (!ValTy->isIntOrIntVectorTy())
3805           return error(ID.Loc, "getelementptr index must be an integer");
3806         if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
3807           unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
3808           if (GEPWidth && (ValNumEl != GEPWidth))
3809             return error(
3810                 ID.Loc,
3811                 "getelementptr vector index has a wrong number of elements");
3812           // GEPWidth may have been unknown because the base is a scalar,
3813           // but it is known now.
3814           GEPWidth = ValNumEl;
3815         }
3816       }
3817 
3818       SmallPtrSet<Type*, 4> Visited;
3819       if (!Indices.empty() && !Ty->isSized(&Visited))
3820         return error(ID.Loc, "base element of getelementptr must be sized");
3821 
3822       if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3823         return error(ID.Loc, "invalid getelementptr indices");
3824 
3825       if (InRangeOp) {
3826         if (*InRangeOp == 0)
3827           return error(ID.Loc,
3828                        "inrange keyword may not appear on pointer operand");
3829         --*InRangeOp;
3830       }
3831 
3832       ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3833                                                       InBounds, InRangeOp);
3834     } else if (Opc == Instruction::Select) {
3835       if (Elts.size() != 3)
3836         return error(ID.Loc, "expected three operands to select");
3837       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3838                                                               Elts[2]))
3839         return error(ID.Loc, Reason);
3840       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3841     } else if (Opc == Instruction::ShuffleVector) {
3842       if (Elts.size() != 3)
3843         return error(ID.Loc, "expected three operands to shufflevector");
3844       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3845         return error(ID.Loc, "invalid operands to shufflevector");
3846       SmallVector<int, 16> Mask;
3847       ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
3848       ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
3849     } else if (Opc == Instruction::ExtractElement) {
3850       if (Elts.size() != 2)
3851         return error(ID.Loc, "expected two operands to extractelement");
3852       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3853         return error(ID.Loc, "invalid extractelement operands");
3854       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3855     } else {
3856       assert(Opc == Instruction::InsertElement && "Unknown opcode");
3857       if (Elts.size() != 3)
3858         return error(ID.Loc, "expected three operands to insertelement");
3859       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3860         return error(ID.Loc, "invalid insertelement operands");
3861       ID.ConstantVal =
3862                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3863     }
3864 
3865     ID.Kind = ValID::t_Constant;
3866     return false;
3867   }
3868   }
3869 
3870   Lex.Lex();
3871   return false;
3872 }
3873 
3874 /// parseGlobalValue - parse a global value with the specified type.
parseGlobalValue(Type * Ty,Constant * & C)3875 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
3876   C = nullptr;
3877   ValID ID;
3878   Value *V = nullptr;
3879   bool Parsed = parseValID(ID) ||
3880                 convertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
3881   if (V && !(C = dyn_cast<Constant>(V)))
3882     return error(ID.Loc, "global values must be constants");
3883   return Parsed;
3884 }
3885 
parseGlobalTypeAndValue(Constant * & V)3886 bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
3887   Type *Ty = nullptr;
3888   return parseType(Ty) || parseGlobalValue(Ty, V);
3889 }
3890 
parseOptionalComdat(StringRef GlobalName,Comdat * & C)3891 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3892   C = nullptr;
3893 
3894   LocTy KwLoc = Lex.getLoc();
3895   if (!EatIfPresent(lltok::kw_comdat))
3896     return false;
3897 
3898   if (EatIfPresent(lltok::lparen)) {
3899     if (Lex.getKind() != lltok::ComdatVar)
3900       return tokError("expected comdat variable");
3901     C = getComdat(Lex.getStrVal(), Lex.getLoc());
3902     Lex.Lex();
3903     if (parseToken(lltok::rparen, "expected ')' after comdat var"))
3904       return true;
3905   } else {
3906     if (GlobalName.empty())
3907       return tokError("comdat cannot be unnamed");
3908     C = getComdat(std::string(GlobalName), KwLoc);
3909   }
3910 
3911   return false;
3912 }
3913 
3914 /// parseGlobalValueVector
3915 ///   ::= /*empty*/
3916 ///   ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
parseGlobalValueVector(SmallVectorImpl<Constant * > & Elts,Optional<unsigned> * InRangeOp)3917 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3918                                       Optional<unsigned> *InRangeOp) {
3919   // Empty list.
3920   if (Lex.getKind() == lltok::rbrace ||
3921       Lex.getKind() == lltok::rsquare ||
3922       Lex.getKind() == lltok::greater ||
3923       Lex.getKind() == lltok::rparen)
3924     return false;
3925 
3926   do {
3927     if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3928       *InRangeOp = Elts.size();
3929 
3930     Constant *C;
3931     if (parseGlobalTypeAndValue(C))
3932       return true;
3933     Elts.push_back(C);
3934   } while (EatIfPresent(lltok::comma));
3935 
3936   return false;
3937 }
3938 
parseMDTuple(MDNode * & MD,bool IsDistinct)3939 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
3940   SmallVector<Metadata *, 16> Elts;
3941   if (parseMDNodeVector(Elts))
3942     return true;
3943 
3944   MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3945   return false;
3946 }
3947 
3948 /// MDNode:
3949 ///  ::= !{ ... }
3950 ///  ::= !7
3951 ///  ::= !DILocation(...)
parseMDNode(MDNode * & N)3952 bool LLParser::parseMDNode(MDNode *&N) {
3953   if (Lex.getKind() == lltok::MetadataVar)
3954     return parseSpecializedMDNode(N);
3955 
3956   return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
3957 }
3958 
parseMDNodeTail(MDNode * & N)3959 bool LLParser::parseMDNodeTail(MDNode *&N) {
3960   // !{ ... }
3961   if (Lex.getKind() == lltok::lbrace)
3962     return parseMDTuple(N);
3963 
3964   // !42
3965   return parseMDNodeID(N);
3966 }
3967 
3968 namespace {
3969 
3970 /// Structure to represent an optional metadata field.
3971 template <class FieldTy> struct MDFieldImpl {
3972   typedef MDFieldImpl ImplTy;
3973   FieldTy Val;
3974   bool Seen;
3975 
assign__anonec6e76de0111::MDFieldImpl3976   void assign(FieldTy Val) {
3977     Seen = true;
3978     this->Val = std::move(Val);
3979   }
3980 
MDFieldImpl__anonec6e76de0111::MDFieldImpl3981   explicit MDFieldImpl(FieldTy Default)
3982       : Val(std::move(Default)), Seen(false) {}
3983 };
3984 
3985 /// Structure to represent an optional metadata field that
3986 /// can be of either type (A or B) and encapsulates the
3987 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
3988 /// to reimplement the specifics for representing each Field.
3989 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3990   typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3991   FieldTypeA A;
3992   FieldTypeB B;
3993   bool Seen;
3994 
3995   enum {
3996     IsInvalid = 0,
3997     IsTypeA = 1,
3998     IsTypeB = 2
3999   } WhatIs;
4000 
assign__anonec6e76de0111::MDEitherFieldImpl4001   void assign(FieldTypeA A) {
4002     Seen = true;
4003     this->A = std::move(A);
4004     WhatIs = IsTypeA;
4005   }
4006 
assign__anonec6e76de0111::MDEitherFieldImpl4007   void assign(FieldTypeB B) {
4008     Seen = true;
4009     this->B = std::move(B);
4010     WhatIs = IsTypeB;
4011   }
4012 
MDEitherFieldImpl__anonec6e76de0111::MDEitherFieldImpl4013   explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4014       : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4015         WhatIs(IsInvalid) {}
4016 };
4017 
4018 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4019   uint64_t Max;
4020 
MDUnsignedField__anonec6e76de0111::MDUnsignedField4021   MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4022       : ImplTy(Default), Max(Max) {}
4023 };
4024 
4025 struct LineField : public MDUnsignedField {
LineField__anonec6e76de0111::LineField4026   LineField() : MDUnsignedField(0, UINT32_MAX) {}
4027 };
4028 
4029 struct ColumnField : public MDUnsignedField {
ColumnField__anonec6e76de0111::ColumnField4030   ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4031 };
4032 
4033 struct DwarfTagField : public MDUnsignedField {
DwarfTagField__anonec6e76de0111::DwarfTagField4034   DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
DwarfTagField__anonec6e76de0111::DwarfTagField4035   DwarfTagField(dwarf::Tag DefaultTag)
4036       : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4037 };
4038 
4039 struct DwarfMacinfoTypeField : public MDUnsignedField {
DwarfMacinfoTypeField__anonec6e76de0111::DwarfMacinfoTypeField4040   DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
DwarfMacinfoTypeField__anonec6e76de0111::DwarfMacinfoTypeField4041   DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4042     : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4043 };
4044 
4045 struct DwarfAttEncodingField : public MDUnsignedField {
DwarfAttEncodingField__anonec6e76de0111::DwarfAttEncodingField4046   DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4047 };
4048 
4049 struct DwarfVirtualityField : public MDUnsignedField {
DwarfVirtualityField__anonec6e76de0111::DwarfVirtualityField4050   DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4051 };
4052 
4053 struct DwarfLangField : public MDUnsignedField {
DwarfLangField__anonec6e76de0111::DwarfLangField4054   DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4055 };
4056 
4057 struct DwarfCCField : public MDUnsignedField {
DwarfCCField__anonec6e76de0111::DwarfCCField4058   DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4059 };
4060 
4061 struct EmissionKindField : public MDUnsignedField {
EmissionKindField__anonec6e76de0111::EmissionKindField4062   EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4063 };
4064 
4065 struct NameTableKindField : public MDUnsignedField {
NameTableKindField__anonec6e76de0111::NameTableKindField4066   NameTableKindField()
4067       : MDUnsignedField(
4068             0, (unsigned)
4069                    DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4070 };
4071 
4072 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
DIFlagField__anonec6e76de0111::DIFlagField4073   DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4074 };
4075 
4076 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
DISPFlagField__anonec6e76de0111::DISPFlagField4077   DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4078 };
4079 
4080 struct MDAPSIntField : public MDFieldImpl<APSInt> {
MDAPSIntField__anonec6e76de0111::MDAPSIntField4081   MDAPSIntField() : ImplTy(APSInt()) {}
4082 };
4083 
4084 struct MDSignedField : public MDFieldImpl<int64_t> {
4085   int64_t Min;
4086   int64_t Max;
4087 
MDSignedField__anonec6e76de0111::MDSignedField4088   MDSignedField(int64_t Default = 0)
4089       : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
MDSignedField__anonec6e76de0111::MDSignedField4090   MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4091       : ImplTy(Default), Min(Min), Max(Max) {}
4092 };
4093 
4094 struct MDBoolField : public MDFieldImpl<bool> {
MDBoolField__anonec6e76de0111::MDBoolField4095   MDBoolField(bool Default = false) : ImplTy(Default) {}
4096 };
4097 
4098 struct MDField : public MDFieldImpl<Metadata *> {
4099   bool AllowNull;
4100 
MDField__anonec6e76de0111::MDField4101   MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4102 };
4103 
4104 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
MDConstant__anonec6e76de0111::MDConstant4105   MDConstant() : ImplTy(nullptr) {}
4106 };
4107 
4108 struct MDStringField : public MDFieldImpl<MDString *> {
4109   bool AllowEmpty;
MDStringField__anonec6e76de0111::MDStringField4110   MDStringField(bool AllowEmpty = true)
4111       : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4112 };
4113 
4114 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
MDFieldList__anonec6e76de0111::MDFieldList4115   MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4116 };
4117 
4118 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
ChecksumKindField__anonec6e76de0111::ChecksumKindField4119   ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4120 };
4121 
4122 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
MDSignedOrMDField__anonec6e76de0111::MDSignedOrMDField4123   MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4124       : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4125 
MDSignedOrMDField__anonec6e76de0111::MDSignedOrMDField4126   MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4127                     bool AllowNull = true)
4128       : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4129 
isMDSignedField__anonec6e76de0111::MDSignedOrMDField4130   bool isMDSignedField() const { return WhatIs == IsTypeA; }
isMDField__anonec6e76de0111::MDSignedOrMDField4131   bool isMDField() const { return WhatIs == IsTypeB; }
getMDSignedValue__anonec6e76de0111::MDSignedOrMDField4132   int64_t getMDSignedValue() const {
4133     assert(isMDSignedField() && "Wrong field type");
4134     return A.Val;
4135   }
getMDFieldValue__anonec6e76de0111::MDSignedOrMDField4136   Metadata *getMDFieldValue() const {
4137     assert(isMDField() && "Wrong field type");
4138     return B.Val;
4139   }
4140 };
4141 
4142 struct MDSignedOrUnsignedField
4143     : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
MDSignedOrUnsignedField__anonec6e76de0111::MDSignedOrUnsignedField4144   MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
4145 
isMDSignedField__anonec6e76de0111::MDSignedOrUnsignedField4146   bool isMDSignedField() const { return WhatIs == IsTypeA; }
isMDUnsignedField__anonec6e76de0111::MDSignedOrUnsignedField4147   bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
getMDSignedValue__anonec6e76de0111::MDSignedOrUnsignedField4148   int64_t getMDSignedValue() const {
4149     assert(isMDSignedField() && "Wrong field type");
4150     return A.Val;
4151   }
getMDUnsignedValue__anonec6e76de0111::MDSignedOrUnsignedField4152   uint64_t getMDUnsignedValue() const {
4153     assert(isMDUnsignedField() && "Wrong field type");
4154     return B.Val;
4155   }
4156 };
4157 
4158 } // end anonymous namespace
4159 
4160 namespace llvm {
4161 
4162 template <>
parseMDField(LocTy Loc,StringRef Name,MDAPSIntField & Result)4163 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4164   if (Lex.getKind() != lltok::APSInt)
4165     return tokError("expected integer");
4166 
4167   Result.assign(Lex.getAPSIntVal());
4168   Lex.Lex();
4169   return false;
4170 }
4171 
4172 template <>
parseMDField(LocTy Loc,StringRef Name,MDUnsignedField & Result)4173 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4174                             MDUnsignedField &Result) {
4175   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4176     return tokError("expected unsigned integer");
4177 
4178   auto &U = Lex.getAPSIntVal();
4179   if (U.ugt(Result.Max))
4180     return tokError("value for '" + Name + "' too large, limit is " +
4181                     Twine(Result.Max));
4182   Result.assign(U.getZExtValue());
4183   assert(Result.Val <= Result.Max && "Expected value in range");
4184   Lex.Lex();
4185   return false;
4186 }
4187 
4188 template <>
parseMDField(LocTy Loc,StringRef Name,LineField & Result)4189 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4190   return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4191 }
4192 template <>
parseMDField(LocTy Loc,StringRef Name,ColumnField & Result)4193 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4194   return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4195 }
4196 
4197 template <>
parseMDField(LocTy Loc,StringRef Name,DwarfTagField & Result)4198 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4199   if (Lex.getKind() == lltok::APSInt)
4200     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4201 
4202   if (Lex.getKind() != lltok::DwarfTag)
4203     return tokError("expected DWARF tag");
4204 
4205   unsigned Tag = dwarf::getTag(Lex.getStrVal());
4206   if (Tag == dwarf::DW_TAG_invalid)
4207     return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4208   assert(Tag <= Result.Max && "Expected valid DWARF tag");
4209 
4210   Result.assign(Tag);
4211   Lex.Lex();
4212   return false;
4213 }
4214 
4215 template <>
parseMDField(LocTy Loc,StringRef Name,DwarfMacinfoTypeField & Result)4216 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4217                             DwarfMacinfoTypeField &Result) {
4218   if (Lex.getKind() == lltok::APSInt)
4219     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4220 
4221   if (Lex.getKind() != lltok::DwarfMacinfo)
4222     return tokError("expected DWARF macinfo type");
4223 
4224   unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4225   if (Macinfo == dwarf::DW_MACINFO_invalid)
4226     return tokError("invalid DWARF macinfo type" + Twine(" '") +
4227                     Lex.getStrVal() + "'");
4228   assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4229 
4230   Result.assign(Macinfo);
4231   Lex.Lex();
4232   return false;
4233 }
4234 
4235 template <>
parseMDField(LocTy Loc,StringRef Name,DwarfVirtualityField & Result)4236 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4237                             DwarfVirtualityField &Result) {
4238   if (Lex.getKind() == lltok::APSInt)
4239     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4240 
4241   if (Lex.getKind() != lltok::DwarfVirtuality)
4242     return tokError("expected DWARF virtuality code");
4243 
4244   unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4245   if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4246     return tokError("invalid DWARF virtuality code" + Twine(" '") +
4247                     Lex.getStrVal() + "'");
4248   assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4249   Result.assign(Virtuality);
4250   Lex.Lex();
4251   return false;
4252 }
4253 
4254 template <>
parseMDField(LocTy Loc,StringRef Name,DwarfLangField & Result)4255 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4256   if (Lex.getKind() == lltok::APSInt)
4257     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4258 
4259   if (Lex.getKind() != lltok::DwarfLang)
4260     return tokError("expected DWARF language");
4261 
4262   unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4263   if (!Lang)
4264     return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4265                     "'");
4266   assert(Lang <= Result.Max && "Expected valid DWARF language");
4267   Result.assign(Lang);
4268   Lex.Lex();
4269   return false;
4270 }
4271 
4272 template <>
parseMDField(LocTy Loc,StringRef Name,DwarfCCField & Result)4273 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4274   if (Lex.getKind() == lltok::APSInt)
4275     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4276 
4277   if (Lex.getKind() != lltok::DwarfCC)
4278     return tokError("expected DWARF calling convention");
4279 
4280   unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4281   if (!CC)
4282     return tokError("invalid DWARF calling convention" + Twine(" '") +
4283                     Lex.getStrVal() + "'");
4284   assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4285   Result.assign(CC);
4286   Lex.Lex();
4287   return false;
4288 }
4289 
4290 template <>
parseMDField(LocTy Loc,StringRef Name,EmissionKindField & Result)4291 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4292                             EmissionKindField &Result) {
4293   if (Lex.getKind() == lltok::APSInt)
4294     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4295 
4296   if (Lex.getKind() != lltok::EmissionKind)
4297     return tokError("expected emission kind");
4298 
4299   auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4300   if (!Kind)
4301     return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4302                     "'");
4303   assert(*Kind <= Result.Max && "Expected valid emission kind");
4304   Result.assign(*Kind);
4305   Lex.Lex();
4306   return false;
4307 }
4308 
4309 template <>
parseMDField(LocTy Loc,StringRef Name,NameTableKindField & Result)4310 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4311                             NameTableKindField &Result) {
4312   if (Lex.getKind() == lltok::APSInt)
4313     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4314 
4315   if (Lex.getKind() != lltok::NameTableKind)
4316     return tokError("expected nameTable kind");
4317 
4318   auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4319   if (!Kind)
4320     return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4321                     "'");
4322   assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4323   Result.assign((unsigned)*Kind);
4324   Lex.Lex();
4325   return false;
4326 }
4327 
4328 template <>
parseMDField(LocTy Loc,StringRef Name,DwarfAttEncodingField & Result)4329 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4330                             DwarfAttEncodingField &Result) {
4331   if (Lex.getKind() == lltok::APSInt)
4332     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4333 
4334   if (Lex.getKind() != lltok::DwarfAttEncoding)
4335     return tokError("expected DWARF type attribute encoding");
4336 
4337   unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4338   if (!Encoding)
4339     return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4340                     Lex.getStrVal() + "'");
4341   assert(Encoding <= Result.Max && "Expected valid DWARF language");
4342   Result.assign(Encoding);
4343   Lex.Lex();
4344   return false;
4345 }
4346 
4347 /// DIFlagField
4348 ///  ::= uint32
4349 ///  ::= DIFlagVector
4350 ///  ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4351 template <>
parseMDField(LocTy Loc,StringRef Name,DIFlagField & Result)4352 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4353 
4354   // parser for a single flag.
4355   auto parseFlag = [&](DINode::DIFlags &Val) {
4356     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4357       uint32_t TempVal = static_cast<uint32_t>(Val);
4358       bool Res = parseUInt32(TempVal);
4359       Val = static_cast<DINode::DIFlags>(TempVal);
4360       return Res;
4361     }
4362 
4363     if (Lex.getKind() != lltok::DIFlag)
4364       return tokError("expected debug info flag");
4365 
4366     Val = DINode::getFlag(Lex.getStrVal());
4367     if (!Val)
4368       return tokError(Twine("invalid debug info flag flag '") +
4369                       Lex.getStrVal() + "'");
4370     Lex.Lex();
4371     return false;
4372   };
4373 
4374   // parse the flags and combine them together.
4375   DINode::DIFlags Combined = DINode::FlagZero;
4376   do {
4377     DINode::DIFlags Val;
4378     if (parseFlag(Val))
4379       return true;
4380     Combined |= Val;
4381   } while (EatIfPresent(lltok::bar));
4382 
4383   Result.assign(Combined);
4384   return false;
4385 }
4386 
4387 /// DISPFlagField
4388 ///  ::= uint32
4389 ///  ::= DISPFlagVector
4390 ///  ::= DISPFlagVector '|' DISPFlag* '|' uint32
4391 template <>
parseMDField(LocTy Loc,StringRef Name,DISPFlagField & Result)4392 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4393 
4394   // parser for a single flag.
4395   auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4396     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4397       uint32_t TempVal = static_cast<uint32_t>(Val);
4398       bool Res = parseUInt32(TempVal);
4399       Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4400       return Res;
4401     }
4402 
4403     if (Lex.getKind() != lltok::DISPFlag)
4404       return tokError("expected debug info flag");
4405 
4406     Val = DISubprogram::getFlag(Lex.getStrVal());
4407     if (!Val)
4408       return tokError(Twine("invalid subprogram debug info flag '") +
4409                       Lex.getStrVal() + "'");
4410     Lex.Lex();
4411     return false;
4412   };
4413 
4414   // parse the flags and combine them together.
4415   DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4416   do {
4417     DISubprogram::DISPFlags Val;
4418     if (parseFlag(Val))
4419       return true;
4420     Combined |= Val;
4421   } while (EatIfPresent(lltok::bar));
4422 
4423   Result.assign(Combined);
4424   return false;
4425 }
4426 
4427 template <>
parseMDField(LocTy Loc,StringRef Name,MDSignedField & Result)4428 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4429   if (Lex.getKind() != lltok::APSInt)
4430     return tokError("expected signed integer");
4431 
4432   auto &S = Lex.getAPSIntVal();
4433   if (S < Result.Min)
4434     return tokError("value for '" + Name + "' too small, limit is " +
4435                     Twine(Result.Min));
4436   if (S > Result.Max)
4437     return tokError("value for '" + Name + "' too large, limit is " +
4438                     Twine(Result.Max));
4439   Result.assign(S.getExtValue());
4440   assert(Result.Val >= Result.Min && "Expected value in range");
4441   assert(Result.Val <= Result.Max && "Expected value in range");
4442   Lex.Lex();
4443   return false;
4444 }
4445 
4446 template <>
parseMDField(LocTy Loc,StringRef Name,MDBoolField & Result)4447 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4448   switch (Lex.getKind()) {
4449   default:
4450     return tokError("expected 'true' or 'false'");
4451   case lltok::kw_true:
4452     Result.assign(true);
4453     break;
4454   case lltok::kw_false:
4455     Result.assign(false);
4456     break;
4457   }
4458   Lex.Lex();
4459   return false;
4460 }
4461 
4462 template <>
parseMDField(LocTy Loc,StringRef Name,MDField & Result)4463 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4464   if (Lex.getKind() == lltok::kw_null) {
4465     if (!Result.AllowNull)
4466       return tokError("'" + Name + "' cannot be null");
4467     Lex.Lex();
4468     Result.assign(nullptr);
4469     return false;
4470   }
4471 
4472   Metadata *MD;
4473   if (parseMetadata(MD, nullptr))
4474     return true;
4475 
4476   Result.assign(MD);
4477   return false;
4478 }
4479 
4480 template <>
parseMDField(LocTy Loc,StringRef Name,MDSignedOrMDField & Result)4481 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4482                             MDSignedOrMDField &Result) {
4483   // Try to parse a signed int.
4484   if (Lex.getKind() == lltok::APSInt) {
4485     MDSignedField Res = Result.A;
4486     if (!parseMDField(Loc, Name, Res)) {
4487       Result.assign(Res);
4488       return false;
4489     }
4490     return true;
4491   }
4492 
4493   // Otherwise, try to parse as an MDField.
4494   MDField Res = Result.B;
4495   if (!parseMDField(Loc, Name, Res)) {
4496     Result.assign(Res);
4497     return false;
4498   }
4499 
4500   return true;
4501 }
4502 
4503 template <>
parseMDField(LocTy Loc,StringRef Name,MDStringField & Result)4504 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4505   LocTy ValueLoc = Lex.getLoc();
4506   std::string S;
4507   if (parseStringConstant(S))
4508     return true;
4509 
4510   if (!Result.AllowEmpty && S.empty())
4511     return error(ValueLoc, "'" + Name + "' cannot be empty");
4512 
4513   Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4514   return false;
4515 }
4516 
4517 template <>
parseMDField(LocTy Loc,StringRef Name,MDFieldList & Result)4518 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4519   SmallVector<Metadata *, 4> MDs;
4520   if (parseMDNodeVector(MDs))
4521     return true;
4522 
4523   Result.assign(std::move(MDs));
4524   return false;
4525 }
4526 
4527 template <>
parseMDField(LocTy Loc,StringRef Name,ChecksumKindField & Result)4528 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4529                             ChecksumKindField &Result) {
4530   Optional<DIFile::ChecksumKind> CSKind =
4531       DIFile::getChecksumKind(Lex.getStrVal());
4532 
4533   if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4534     return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
4535                     "'");
4536 
4537   Result.assign(*CSKind);
4538   Lex.Lex();
4539   return false;
4540 }
4541 
4542 } // end namespace llvm
4543 
4544 template <class ParserTy>
parseMDFieldsImplBody(ParserTy ParseField)4545 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4546   do {
4547     if (Lex.getKind() != lltok::LabelStr)
4548       return tokError("expected field label here");
4549 
4550     if (ParseField())
4551       return true;
4552   } while (EatIfPresent(lltok::comma));
4553 
4554   return false;
4555 }
4556 
4557 template <class ParserTy>
parseMDFieldsImpl(ParserTy ParseField,LocTy & ClosingLoc)4558 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4559   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4560   Lex.Lex();
4561 
4562   if (parseToken(lltok::lparen, "expected '(' here"))
4563     return true;
4564   if (Lex.getKind() != lltok::rparen)
4565     if (parseMDFieldsImplBody(ParseField))
4566       return true;
4567 
4568   ClosingLoc = Lex.getLoc();
4569   return parseToken(lltok::rparen, "expected ')' here");
4570 }
4571 
4572 template <class FieldTy>
parseMDField(StringRef Name,FieldTy & Result)4573 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
4574   if (Result.Seen)
4575     return tokError("field '" + Name + "' cannot be specified more than once");
4576 
4577   LocTy Loc = Lex.getLoc();
4578   Lex.Lex();
4579   return parseMDField(Loc, Name, Result);
4580 }
4581 
parseSpecializedMDNode(MDNode * & N,bool IsDistinct)4582 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4583   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4584 
4585 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
4586   if (Lex.getStrVal() == #CLASS)                                               \
4587     return parse##CLASS(N, IsDistinct);
4588 #include "llvm/IR/Metadata.def"
4589 
4590   return tokError("expected metadata type");
4591 }
4592 
4593 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4594 #define NOP_FIELD(NAME, TYPE, INIT)
4595 #define REQUIRE_FIELD(NAME, TYPE, INIT)                                        \
4596   if (!NAME.Seen)                                                              \
4597     return error(ClosingLoc, "missing required field '" #NAME "'");
4598 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT)                                    \
4599   if (Lex.getStrVal() == #NAME)                                                \
4600     return parseMDField(#NAME, NAME);
4601 #define PARSE_MD_FIELDS()                                                      \
4602   VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD)                                \
4603   do {                                                                         \
4604     LocTy ClosingLoc;                                                          \
4605     if (parseMDFieldsImpl(                                                     \
4606             [&]() -> bool {                                                    \
4607               VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD)                  \
4608               return tokError(Twine("invalid field '") + Lex.getStrVal() +     \
4609                               "'");                                            \
4610             },                                                                 \
4611             ClosingLoc))                                                       \
4612       return true;                                                             \
4613     VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD)                                  \
4614   } while (false)
4615 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
4616   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4617 
4618 /// parseDILocationFields:
4619 ///   ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4620 ///   isImplicitCode: true)
parseDILocation(MDNode * & Result,bool IsDistinct)4621 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
4622 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4623   OPTIONAL(line, LineField, );                                                 \
4624   OPTIONAL(column, ColumnField, );                                             \
4625   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4626   OPTIONAL(inlinedAt, MDField, );                                              \
4627   OPTIONAL(isImplicitCode, MDBoolField, (false));
4628   PARSE_MD_FIELDS();
4629 #undef VISIT_MD_FIELDS
4630 
4631   Result =
4632       GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4633                                    inlinedAt.Val, isImplicitCode.Val));
4634   return false;
4635 }
4636 
4637 /// parseGenericDINode:
4638 ///   ::= !GenericDINode(tag: 15, header: "...", operands: {...})
parseGenericDINode(MDNode * & Result,bool IsDistinct)4639 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
4640 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4641   REQUIRED(tag, DwarfTagField, );                                              \
4642   OPTIONAL(header, MDStringField, );                                           \
4643   OPTIONAL(operands, MDFieldList, );
4644   PARSE_MD_FIELDS();
4645 #undef VISIT_MD_FIELDS
4646 
4647   Result = GET_OR_DISTINCT(GenericDINode,
4648                            (Context, tag.Val, header.Val, operands.Val));
4649   return false;
4650 }
4651 
4652 /// parseDISubrange:
4653 ///   ::= !DISubrange(count: 30, lowerBound: 2)
4654 ///   ::= !DISubrange(count: !node, lowerBound: 2)
4655 ///   ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
parseDISubrange(MDNode * & Result,bool IsDistinct)4656 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
4657 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4658   OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false));              \
4659   OPTIONAL(lowerBound, MDSignedOrMDField, );                                   \
4660   OPTIONAL(upperBound, MDSignedOrMDField, );                                   \
4661   OPTIONAL(stride, MDSignedOrMDField, );
4662   PARSE_MD_FIELDS();
4663 #undef VISIT_MD_FIELDS
4664 
4665   Metadata *Count = nullptr;
4666   Metadata *LowerBound = nullptr;
4667   Metadata *UpperBound = nullptr;
4668   Metadata *Stride = nullptr;
4669   if (count.isMDSignedField())
4670     Count = ConstantAsMetadata::get(ConstantInt::getSigned(
4671         Type::getInt64Ty(Context), count.getMDSignedValue()));
4672   else if (count.isMDField())
4673     Count = count.getMDFieldValue();
4674 
4675   auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4676     if (Bound.isMDSignedField())
4677       return ConstantAsMetadata::get(ConstantInt::getSigned(
4678           Type::getInt64Ty(Context), Bound.getMDSignedValue()));
4679     if (Bound.isMDField())
4680       return Bound.getMDFieldValue();
4681     return nullptr;
4682   };
4683 
4684   LowerBound = convToMetadata(lowerBound);
4685   UpperBound = convToMetadata(upperBound);
4686   Stride = convToMetadata(stride);
4687 
4688   Result = GET_OR_DISTINCT(DISubrange,
4689                            (Context, Count, LowerBound, UpperBound, Stride));
4690 
4691   return false;
4692 }
4693 
4694 /// parseDIGenericSubrange:
4695 ///   ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
4696 ///   !node3)
parseDIGenericSubrange(MDNode * & Result,bool IsDistinct)4697 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
4698 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4699   OPTIONAL(count, MDSignedOrMDField, );                                        \
4700   OPTIONAL(lowerBound, MDSignedOrMDField, );                                   \
4701   OPTIONAL(upperBound, MDSignedOrMDField, );                                   \
4702   OPTIONAL(stride, MDSignedOrMDField, );
4703   PARSE_MD_FIELDS();
4704 #undef VISIT_MD_FIELDS
4705 
4706   auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4707     if (Bound.isMDSignedField())
4708       return DIExpression::get(
4709           Context, {dwarf::DW_OP_consts,
4710                     static_cast<uint64_t>(Bound.getMDSignedValue())});
4711     if (Bound.isMDField())
4712       return Bound.getMDFieldValue();
4713     return nullptr;
4714   };
4715 
4716   Metadata *Count = ConvToMetadata(count);
4717   Metadata *LowerBound = ConvToMetadata(lowerBound);
4718   Metadata *UpperBound = ConvToMetadata(upperBound);
4719   Metadata *Stride = ConvToMetadata(stride);
4720 
4721   Result = GET_OR_DISTINCT(DIGenericSubrange,
4722                            (Context, Count, LowerBound, UpperBound, Stride));
4723 
4724   return false;
4725 }
4726 
4727 /// parseDIEnumerator:
4728 ///   ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
parseDIEnumerator(MDNode * & Result,bool IsDistinct)4729 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4730 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4731   REQUIRED(name, MDStringField, );                                             \
4732   REQUIRED(value, MDAPSIntField, );                                            \
4733   OPTIONAL(isUnsigned, MDBoolField, (false));
4734   PARSE_MD_FIELDS();
4735 #undef VISIT_MD_FIELDS
4736 
4737   if (isUnsigned.Val && value.Val.isNegative())
4738     return tokError("unsigned enumerator with negative value");
4739 
4740   APSInt Value(value.Val);
4741   // Add a leading zero so that unsigned values with the msb set are not
4742   // mistaken for negative values when used for signed enumerators.
4743   if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
4744     Value = Value.zext(Value.getBitWidth() + 1);
4745 
4746   Result =
4747       GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4748 
4749   return false;
4750 }
4751 
4752 /// parseDIBasicType:
4753 ///   ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4754 ///                    encoding: DW_ATE_encoding, flags: 0)
parseDIBasicType(MDNode * & Result,bool IsDistinct)4755 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
4756 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4757   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type));                     \
4758   OPTIONAL(name, MDStringField, );                                             \
4759   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4760   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4761   OPTIONAL(encoding, DwarfAttEncodingField, );                                 \
4762   OPTIONAL(flags, DIFlagField, );
4763   PARSE_MD_FIELDS();
4764 #undef VISIT_MD_FIELDS
4765 
4766   Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4767                                          align.Val, encoding.Val, flags.Val));
4768   return false;
4769 }
4770 
4771 /// parseDIStringType:
4772 ///   ::= !DIStringType(name: "character(4)", size: 32, align: 32)
parseDIStringType(MDNode * & Result,bool IsDistinct)4773 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
4774 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4775   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type));                   \
4776   OPTIONAL(name, MDStringField, );                                             \
4777   OPTIONAL(stringLength, MDField, );                                           \
4778   OPTIONAL(stringLengthExpression, MDField, );                                 \
4779   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4780   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4781   OPTIONAL(encoding, DwarfAttEncodingField, );
4782   PARSE_MD_FIELDS();
4783 #undef VISIT_MD_FIELDS
4784 
4785   Result = GET_OR_DISTINCT(DIStringType,
4786                            (Context, tag.Val, name.Val, stringLength.Val,
4787                             stringLengthExpression.Val, size.Val, align.Val,
4788                             encoding.Val));
4789   return false;
4790 }
4791 
4792 /// parseDIDerivedType:
4793 ///   ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4794 ///                      line: 7, scope: !1, baseType: !2, size: 32,
4795 ///                      align: 32, offset: 0, flags: 0, extraData: !3,
4796 ///                      dwarfAddressSpace: 3)
parseDIDerivedType(MDNode * & Result,bool IsDistinct)4797 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4798 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4799   REQUIRED(tag, DwarfTagField, );                                              \
4800   OPTIONAL(name, MDStringField, );                                             \
4801   OPTIONAL(file, MDField, );                                                   \
4802   OPTIONAL(line, LineField, );                                                 \
4803   OPTIONAL(scope, MDField, );                                                  \
4804   REQUIRED(baseType, MDField, );                                               \
4805   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4806   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4807   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
4808   OPTIONAL(flags, DIFlagField, );                                              \
4809   OPTIONAL(extraData, MDField, );                                              \
4810   OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
4811   PARSE_MD_FIELDS();
4812 #undef VISIT_MD_FIELDS
4813 
4814   Optional<unsigned> DWARFAddressSpace;
4815   if (dwarfAddressSpace.Val != UINT32_MAX)
4816     DWARFAddressSpace = dwarfAddressSpace.Val;
4817 
4818   Result = GET_OR_DISTINCT(DIDerivedType,
4819                            (Context, tag.Val, name.Val, file.Val, line.Val,
4820                             scope.Val, baseType.Val, size.Val, align.Val,
4821                             offset.Val, DWARFAddressSpace, flags.Val,
4822                             extraData.Val));
4823   return false;
4824 }
4825 
parseDICompositeType(MDNode * & Result,bool IsDistinct)4826 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
4827 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4828   REQUIRED(tag, DwarfTagField, );                                              \
4829   OPTIONAL(name, MDStringField, );                                             \
4830   OPTIONAL(file, MDField, );                                                   \
4831   OPTIONAL(line, LineField, );                                                 \
4832   OPTIONAL(scope, MDField, );                                                  \
4833   OPTIONAL(baseType, MDField, );                                               \
4834   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4835   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4836   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
4837   OPTIONAL(flags, DIFlagField, );                                              \
4838   OPTIONAL(elements, MDField, );                                               \
4839   OPTIONAL(runtimeLang, DwarfLangField, );                                     \
4840   OPTIONAL(vtableHolder, MDField, );                                           \
4841   OPTIONAL(templateParams, MDField, );                                         \
4842   OPTIONAL(identifier, MDStringField, );                                       \
4843   OPTIONAL(discriminator, MDField, );                                          \
4844   OPTIONAL(dataLocation, MDField, );                                           \
4845   OPTIONAL(associated, MDField, );                                             \
4846   OPTIONAL(allocated, MDField, );                                              \
4847   OPTIONAL(rank, MDSignedOrMDField, );
4848   PARSE_MD_FIELDS();
4849 #undef VISIT_MD_FIELDS
4850 
4851   Metadata *Rank = nullptr;
4852   if (rank.isMDSignedField())
4853     Rank = ConstantAsMetadata::get(ConstantInt::getSigned(
4854         Type::getInt64Ty(Context), rank.getMDSignedValue()));
4855   else if (rank.isMDField())
4856     Rank = rank.getMDFieldValue();
4857 
4858   // If this has an identifier try to build an ODR type.
4859   if (identifier.Val)
4860     if (auto *CT = DICompositeType::buildODRType(
4861             Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4862             scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4863             elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
4864             discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
4865             Rank)) {
4866       Result = CT;
4867       return false;
4868     }
4869 
4870   // Create a new node, and save it in the context if it belongs in the type
4871   // map.
4872   Result = GET_OR_DISTINCT(
4873       DICompositeType,
4874       (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4875        size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4876        runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4877        discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
4878        Rank));
4879   return false;
4880 }
4881 
parseDISubroutineType(MDNode * & Result,bool IsDistinct)4882 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4883 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4884   OPTIONAL(flags, DIFlagField, );                                              \
4885   OPTIONAL(cc, DwarfCCField, );                                                \
4886   REQUIRED(types, MDField, );
4887   PARSE_MD_FIELDS();
4888 #undef VISIT_MD_FIELDS
4889 
4890   Result = GET_OR_DISTINCT(DISubroutineType,
4891                            (Context, flags.Val, cc.Val, types.Val));
4892   return false;
4893 }
4894 
4895 /// parseDIFileType:
4896 ///   ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4897 ///                   checksumkind: CSK_MD5,
4898 ///                   checksum: "000102030405060708090a0b0c0d0e0f",
4899 ///                   source: "source file contents")
parseDIFile(MDNode * & Result,bool IsDistinct)4900 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
4901   // The default constructed value for checksumkind is required, but will never
4902   // be used, as the parser checks if the field was actually Seen before using
4903   // the Val.
4904 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4905   REQUIRED(filename, MDStringField, );                                         \
4906   REQUIRED(directory, MDStringField, );                                        \
4907   OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5));                \
4908   OPTIONAL(checksum, MDStringField, );                                         \
4909   OPTIONAL(source, MDStringField, );
4910   PARSE_MD_FIELDS();
4911 #undef VISIT_MD_FIELDS
4912 
4913   Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4914   if (checksumkind.Seen && checksum.Seen)
4915     OptChecksum.emplace(checksumkind.Val, checksum.Val);
4916   else if (checksumkind.Seen || checksum.Seen)
4917     return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4918 
4919   Optional<MDString *> OptSource;
4920   if (source.Seen)
4921     OptSource = source.Val;
4922   Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4923                                     OptChecksum, OptSource));
4924   return false;
4925 }
4926 
4927 /// parseDICompileUnit:
4928 ///   ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4929 ///                      isOptimized: true, flags: "-O2", runtimeVersion: 1,
4930 ///                      splitDebugFilename: "abc.debug",
4931 ///                      emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4932 ///                      globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
4933 ///                      sysroot: "/", sdk: "MacOSX.sdk")
parseDICompileUnit(MDNode * & Result,bool IsDistinct)4934 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4935   if (!IsDistinct)
4936     return Lex.Error("missing 'distinct', required for !DICompileUnit");
4937 
4938 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4939   REQUIRED(language, DwarfLangField, );                                        \
4940   REQUIRED(file, MDField, (/* AllowNull */ false));                            \
4941   OPTIONAL(producer, MDStringField, );                                         \
4942   OPTIONAL(isOptimized, MDBoolField, );                                        \
4943   OPTIONAL(flags, MDStringField, );                                            \
4944   OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX));                  \
4945   OPTIONAL(splitDebugFilename, MDStringField, );                               \
4946   OPTIONAL(emissionKind, EmissionKindField, );                                 \
4947   OPTIONAL(enums, MDField, );                                                  \
4948   OPTIONAL(retainedTypes, MDField, );                                          \
4949   OPTIONAL(globals, MDField, );                                                \
4950   OPTIONAL(imports, MDField, );                                                \
4951   OPTIONAL(macros, MDField, );                                                 \
4952   OPTIONAL(dwoId, MDUnsignedField, );                                          \
4953   OPTIONAL(splitDebugInlining, MDBoolField, = true);                           \
4954   OPTIONAL(debugInfoForProfiling, MDBoolField, = false);                       \
4955   OPTIONAL(nameTableKind, NameTableKindField, );                               \
4956   OPTIONAL(rangesBaseAddress, MDBoolField, = false);                           \
4957   OPTIONAL(sysroot, MDStringField, );                                          \
4958   OPTIONAL(sdk, MDStringField, );
4959   PARSE_MD_FIELDS();
4960 #undef VISIT_MD_FIELDS
4961 
4962   Result = DICompileUnit::getDistinct(
4963       Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4964       runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4965       retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4966       splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4967       rangesBaseAddress.Val, sysroot.Val, sdk.Val);
4968   return false;
4969 }
4970 
4971 /// parseDISubprogram:
4972 ///   ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4973 ///                     file: !1, line: 7, type: !2, isLocal: false,
4974 ///                     isDefinition: true, scopeLine: 8, containingType: !3,
4975 ///                     virtuality: DW_VIRTUALTIY_pure_virtual,
4976 ///                     virtualIndex: 10, thisAdjustment: 4, flags: 11,
4977 ///                     spFlags: 10, isOptimized: false, templateParams: !4,
4978 ///                     declaration: !5, retainedNodes: !6, thrownTypes: !7)
parseDISubprogram(MDNode * & Result,bool IsDistinct)4979 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
4980   auto Loc = Lex.getLoc();
4981 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4982   OPTIONAL(scope, MDField, );                                                  \
4983   OPTIONAL(name, MDStringField, );                                             \
4984   OPTIONAL(linkageName, MDStringField, );                                      \
4985   OPTIONAL(file, MDField, );                                                   \
4986   OPTIONAL(line, LineField, );                                                 \
4987   OPTIONAL(type, MDField, );                                                   \
4988   OPTIONAL(isLocal, MDBoolField, );                                            \
4989   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
4990   OPTIONAL(scopeLine, LineField, );                                            \
4991   OPTIONAL(containingType, MDField, );                                         \
4992   OPTIONAL(virtuality, DwarfVirtualityField, );                                \
4993   OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX));                    \
4994   OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX));          \
4995   OPTIONAL(flags, DIFlagField, );                                              \
4996   OPTIONAL(spFlags, DISPFlagField, );                                          \
4997   OPTIONAL(isOptimized, MDBoolField, );                                        \
4998   OPTIONAL(unit, MDField, );                                                   \
4999   OPTIONAL(templateParams, MDField, );                                         \
5000   OPTIONAL(declaration, MDField, );                                            \
5001   OPTIONAL(retainedNodes, MDField, );                                          \
5002   OPTIONAL(thrownTypes, MDField, );
5003   PARSE_MD_FIELDS();
5004 #undef VISIT_MD_FIELDS
5005 
5006   // An explicit spFlags field takes precedence over individual fields in
5007   // older IR versions.
5008   DISubprogram::DISPFlags SPFlags =
5009       spFlags.Seen ? spFlags.Val
5010                    : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
5011                                              isOptimized.Val, virtuality.Val);
5012   if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5013     return Lex.Error(
5014         Loc,
5015         "missing 'distinct', required for !DISubprogram that is a Definition");
5016   Result = GET_OR_DISTINCT(
5017       DISubprogram,
5018       (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
5019        type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5020        thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5021        declaration.Val, retainedNodes.Val, thrownTypes.Val));
5022   return false;
5023 }
5024 
5025 /// parseDILexicalBlock:
5026 ///   ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
parseDILexicalBlock(MDNode * & Result,bool IsDistinct)5027 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
5028 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5029   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5030   OPTIONAL(file, MDField, );                                                   \
5031   OPTIONAL(line, LineField, );                                                 \
5032   OPTIONAL(column, ColumnField, );
5033   PARSE_MD_FIELDS();
5034 #undef VISIT_MD_FIELDS
5035 
5036   Result = GET_OR_DISTINCT(
5037       DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
5038   return false;
5039 }
5040 
5041 /// parseDILexicalBlockFile:
5042 ///   ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
parseDILexicalBlockFile(MDNode * & Result,bool IsDistinct)5043 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
5044 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5045   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5046   OPTIONAL(file, MDField, );                                                   \
5047   REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5048   PARSE_MD_FIELDS();
5049 #undef VISIT_MD_FIELDS
5050 
5051   Result = GET_OR_DISTINCT(DILexicalBlockFile,
5052                            (Context, scope.Val, file.Val, discriminator.Val));
5053   return false;
5054 }
5055 
5056 /// parseDICommonBlock:
5057 ///   ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
parseDICommonBlock(MDNode * & Result,bool IsDistinct)5058 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
5059 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5060   REQUIRED(scope, MDField, );                                                  \
5061   OPTIONAL(declaration, MDField, );                                            \
5062   OPTIONAL(name, MDStringField, );                                             \
5063   OPTIONAL(file, MDField, );                                                   \
5064   OPTIONAL(line, LineField, );
5065   PARSE_MD_FIELDS();
5066 #undef VISIT_MD_FIELDS
5067 
5068   Result = GET_OR_DISTINCT(DICommonBlock,
5069                            (Context, scope.Val, declaration.Val, name.Val,
5070                             file.Val, line.Val));
5071   return false;
5072 }
5073 
5074 /// parseDINamespace:
5075 ///   ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
parseDINamespace(MDNode * & Result,bool IsDistinct)5076 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
5077 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5078   REQUIRED(scope, MDField, );                                                  \
5079   OPTIONAL(name, MDStringField, );                                             \
5080   OPTIONAL(exportSymbols, MDBoolField, );
5081   PARSE_MD_FIELDS();
5082 #undef VISIT_MD_FIELDS
5083 
5084   Result = GET_OR_DISTINCT(DINamespace,
5085                            (Context, scope.Val, name.Val, exportSymbols.Val));
5086   return false;
5087 }
5088 
5089 /// parseDIMacro:
5090 ///   ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
5091 ///   "SomeValue")
parseDIMacro(MDNode * & Result,bool IsDistinct)5092 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
5093 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5094   REQUIRED(type, DwarfMacinfoTypeField, );                                     \
5095   OPTIONAL(line, LineField, );                                                 \
5096   REQUIRED(name, MDStringField, );                                             \
5097   OPTIONAL(value, MDStringField, );
5098   PARSE_MD_FIELDS();
5099 #undef VISIT_MD_FIELDS
5100 
5101   Result = GET_OR_DISTINCT(DIMacro,
5102                            (Context, type.Val, line.Val, name.Val, value.Val));
5103   return false;
5104 }
5105 
5106 /// parseDIMacroFile:
5107 ///   ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
parseDIMacroFile(MDNode * & Result,bool IsDistinct)5108 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
5109 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5110   OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file));       \
5111   OPTIONAL(line, LineField, );                                                 \
5112   REQUIRED(file, MDField, );                                                   \
5113   OPTIONAL(nodes, MDField, );
5114   PARSE_MD_FIELDS();
5115 #undef VISIT_MD_FIELDS
5116 
5117   Result = GET_OR_DISTINCT(DIMacroFile,
5118                            (Context, type.Val, line.Val, file.Val, nodes.Val));
5119   return false;
5120 }
5121 
5122 /// parseDIModule:
5123 ///   ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
5124 ///   "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
5125 ///   file: !1, line: 4, isDecl: false)
parseDIModule(MDNode * & Result,bool IsDistinct)5126 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
5127 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5128   REQUIRED(scope, MDField, );                                                  \
5129   REQUIRED(name, MDStringField, );                                             \
5130   OPTIONAL(configMacros, MDStringField, );                                     \
5131   OPTIONAL(includePath, MDStringField, );                                      \
5132   OPTIONAL(apinotes, MDStringField, );                                         \
5133   OPTIONAL(file, MDField, );                                                   \
5134   OPTIONAL(line, LineField, );                                                 \
5135   OPTIONAL(isDecl, MDBoolField, );
5136   PARSE_MD_FIELDS();
5137 #undef VISIT_MD_FIELDS
5138 
5139   Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
5140                                       configMacros.Val, includePath.Val,
5141                                       apinotes.Val, line.Val, isDecl.Val));
5142   return false;
5143 }
5144 
5145 /// parseDITemplateTypeParameter:
5146 ///   ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
parseDITemplateTypeParameter(MDNode * & Result,bool IsDistinct)5147 bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
5148 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5149   OPTIONAL(name, MDStringField, );                                             \
5150   REQUIRED(type, MDField, );                                                   \
5151   OPTIONAL(defaulted, MDBoolField, );
5152   PARSE_MD_FIELDS();
5153 #undef VISIT_MD_FIELDS
5154 
5155   Result = GET_OR_DISTINCT(DITemplateTypeParameter,
5156                            (Context, name.Val, type.Val, defaulted.Val));
5157   return false;
5158 }
5159 
5160 /// parseDITemplateValueParameter:
5161 ///   ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
5162 ///                                 name: "V", type: !1, defaulted: false,
5163 ///                                 value: i32 7)
parseDITemplateValueParameter(MDNode * & Result,bool IsDistinct)5164 bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
5165 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5166   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter));      \
5167   OPTIONAL(name, MDStringField, );                                             \
5168   OPTIONAL(type, MDField, );                                                   \
5169   OPTIONAL(defaulted, MDBoolField, );                                          \
5170   REQUIRED(value, MDField, );
5171 
5172   PARSE_MD_FIELDS();
5173 #undef VISIT_MD_FIELDS
5174 
5175   Result = GET_OR_DISTINCT(
5176       DITemplateValueParameter,
5177       (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
5178   return false;
5179 }
5180 
5181 /// parseDIGlobalVariable:
5182 ///   ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
5183 ///                         file: !1, line: 7, type: !2, isLocal: false,
5184 ///                         isDefinition: true, templateParams: !3,
5185 ///                         declaration: !4, align: 8)
parseDIGlobalVariable(MDNode * & Result,bool IsDistinct)5186 bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
5187 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5188   REQUIRED(name, MDStringField, (/* AllowEmpty */ false));                     \
5189   OPTIONAL(scope, MDField, );                                                  \
5190   OPTIONAL(linkageName, MDStringField, );                                      \
5191   OPTIONAL(file, MDField, );                                                   \
5192   OPTIONAL(line, LineField, );                                                 \
5193   OPTIONAL(type, MDField, );                                                   \
5194   OPTIONAL(isLocal, MDBoolField, );                                            \
5195   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
5196   OPTIONAL(templateParams, MDField, );                                         \
5197   OPTIONAL(declaration, MDField, );                                            \
5198   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
5199   PARSE_MD_FIELDS();
5200 #undef VISIT_MD_FIELDS
5201 
5202   Result =
5203       GET_OR_DISTINCT(DIGlobalVariable,
5204                       (Context, scope.Val, name.Val, linkageName.Val, file.Val,
5205                        line.Val, type.Val, isLocal.Val, isDefinition.Val,
5206                        declaration.Val, templateParams.Val, align.Val));
5207   return false;
5208 }
5209 
5210 /// parseDILocalVariable:
5211 ///   ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
5212 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
5213 ///                        align: 8)
5214 ///   ::= !DILocalVariable(scope: !0, name: "foo",
5215 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
5216 ///                        align: 8)
parseDILocalVariable(MDNode * & Result,bool IsDistinct)5217 bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
5218 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5219   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5220   OPTIONAL(name, MDStringField, );                                             \
5221   OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX));                             \
5222   OPTIONAL(file, MDField, );                                                   \
5223   OPTIONAL(line, LineField, );                                                 \
5224   OPTIONAL(type, MDField, );                                                   \
5225   OPTIONAL(flags, DIFlagField, );                                              \
5226   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
5227   PARSE_MD_FIELDS();
5228 #undef VISIT_MD_FIELDS
5229 
5230   Result = GET_OR_DISTINCT(DILocalVariable,
5231                            (Context, scope.Val, name.Val, file.Val, line.Val,
5232                             type.Val, arg.Val, flags.Val, align.Val));
5233   return false;
5234 }
5235 
5236 /// parseDILabel:
5237 ///   ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
parseDILabel(MDNode * & Result,bool IsDistinct)5238 bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
5239 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5240   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5241   REQUIRED(name, MDStringField, );                                             \
5242   REQUIRED(file, MDField, );                                                   \
5243   REQUIRED(line, LineField, );
5244   PARSE_MD_FIELDS();
5245 #undef VISIT_MD_FIELDS
5246 
5247   Result = GET_OR_DISTINCT(DILabel,
5248                            (Context, scope.Val, name.Val, file.Val, line.Val));
5249   return false;
5250 }
5251 
5252 /// parseDIExpression:
5253 ///   ::= !DIExpression(0, 7, -1)
parseDIExpression(MDNode * & Result,bool IsDistinct)5254 bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
5255   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5256   Lex.Lex();
5257 
5258   if (parseToken(lltok::lparen, "expected '(' here"))
5259     return true;
5260 
5261   SmallVector<uint64_t, 8> Elements;
5262   if (Lex.getKind() != lltok::rparen)
5263     do {
5264       if (Lex.getKind() == lltok::DwarfOp) {
5265         if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
5266           Lex.Lex();
5267           Elements.push_back(Op);
5268           continue;
5269         }
5270         return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
5271       }
5272 
5273       if (Lex.getKind() == lltok::DwarfAttEncoding) {
5274         if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
5275           Lex.Lex();
5276           Elements.push_back(Op);
5277           continue;
5278         }
5279         return tokError(Twine("invalid DWARF attribute encoding '") +
5280                         Lex.getStrVal() + "'");
5281       }
5282 
5283       if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5284         return tokError("expected unsigned integer");
5285 
5286       auto &U = Lex.getAPSIntVal();
5287       if (U.ugt(UINT64_MAX))
5288         return tokError("element too large, limit is " + Twine(UINT64_MAX));
5289       Elements.push_back(U.getZExtValue());
5290       Lex.Lex();
5291     } while (EatIfPresent(lltok::comma));
5292 
5293   if (parseToken(lltok::rparen, "expected ')' here"))
5294     return true;
5295 
5296   Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
5297   return false;
5298 }
5299 
5300 /// parseDIGlobalVariableExpression:
5301 ///   ::= !DIGlobalVariableExpression(var: !0, expr: !1)
parseDIGlobalVariableExpression(MDNode * & Result,bool IsDistinct)5302 bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
5303                                                bool IsDistinct) {
5304 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5305   REQUIRED(var, MDField, );                                                    \
5306   REQUIRED(expr, MDField, );
5307   PARSE_MD_FIELDS();
5308 #undef VISIT_MD_FIELDS
5309 
5310   Result =
5311       GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
5312   return false;
5313 }
5314 
5315 /// parseDIObjCProperty:
5316 ///   ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5317 ///                       getter: "getFoo", attributes: 7, type: !2)
parseDIObjCProperty(MDNode * & Result,bool IsDistinct)5318 bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
5319 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5320   OPTIONAL(name, MDStringField, );                                             \
5321   OPTIONAL(file, MDField, );                                                   \
5322   OPTIONAL(line, LineField, );                                                 \
5323   OPTIONAL(setter, MDStringField, );                                           \
5324   OPTIONAL(getter, MDStringField, );                                           \
5325   OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX));                      \
5326   OPTIONAL(type, MDField, );
5327   PARSE_MD_FIELDS();
5328 #undef VISIT_MD_FIELDS
5329 
5330   Result = GET_OR_DISTINCT(DIObjCProperty,
5331                            (Context, name.Val, file.Val, line.Val, setter.Val,
5332                             getter.Val, attributes.Val, type.Val));
5333   return false;
5334 }
5335 
5336 /// parseDIImportedEntity:
5337 ///   ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5338 ///                         line: 7, name: "foo")
parseDIImportedEntity(MDNode * & Result,bool IsDistinct)5339 bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5340 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5341   REQUIRED(tag, DwarfTagField, );                                              \
5342   REQUIRED(scope, MDField, );                                                  \
5343   OPTIONAL(entity, MDField, );                                                 \
5344   OPTIONAL(file, MDField, );                                                   \
5345   OPTIONAL(line, LineField, );                                                 \
5346   OPTIONAL(name, MDStringField, );
5347   PARSE_MD_FIELDS();
5348 #undef VISIT_MD_FIELDS
5349 
5350   Result = GET_OR_DISTINCT(
5351       DIImportedEntity,
5352       (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
5353   return false;
5354 }
5355 
5356 #undef PARSE_MD_FIELD
5357 #undef NOP_FIELD
5358 #undef REQUIRE_FIELD
5359 #undef DECLARE_FIELD
5360 
5361 /// parseMetadataAsValue
5362 ///  ::= metadata i32 %local
5363 ///  ::= metadata i32 @global
5364 ///  ::= metadata i32 7
5365 ///  ::= metadata !0
5366 ///  ::= metadata !{...}
5367 ///  ::= metadata !"string"
parseMetadataAsValue(Value * & V,PerFunctionState & PFS)5368 bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5369   // Note: the type 'metadata' has already been parsed.
5370   Metadata *MD;
5371   if (parseMetadata(MD, &PFS))
5372     return true;
5373 
5374   V = MetadataAsValue::get(Context, MD);
5375   return false;
5376 }
5377 
5378 /// parseValueAsMetadata
5379 ///  ::= i32 %local
5380 ///  ::= i32 @global
5381 ///  ::= i32 7
parseValueAsMetadata(Metadata * & MD,const Twine & TypeMsg,PerFunctionState * PFS)5382 bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5383                                     PerFunctionState *PFS) {
5384   Type *Ty;
5385   LocTy Loc;
5386   if (parseType(Ty, TypeMsg, Loc))
5387     return true;
5388   if (Ty->isMetadataTy())
5389     return error(Loc, "invalid metadata-value-metadata roundtrip");
5390 
5391   Value *V;
5392   if (parseValue(Ty, V, PFS))
5393     return true;
5394 
5395   MD = ValueAsMetadata::get(V);
5396   return false;
5397 }
5398 
5399 /// parseMetadata
5400 ///  ::= i32 %local
5401 ///  ::= i32 @global
5402 ///  ::= i32 7
5403 ///  ::= !42
5404 ///  ::= !{...}
5405 ///  ::= !"string"
5406 ///  ::= !DILocation(...)
parseMetadata(Metadata * & MD,PerFunctionState * PFS)5407 bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5408   if (Lex.getKind() == lltok::MetadataVar) {
5409     MDNode *N;
5410     if (parseSpecializedMDNode(N))
5411       return true;
5412     MD = N;
5413     return false;
5414   }
5415 
5416   // ValueAsMetadata:
5417   // <type> <value>
5418   if (Lex.getKind() != lltok::exclaim)
5419     return parseValueAsMetadata(MD, "expected metadata operand", PFS);
5420 
5421   // '!'.
5422   assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
5423   Lex.Lex();
5424 
5425   // MDString:
5426   //   ::= '!' STRINGCONSTANT
5427   if (Lex.getKind() == lltok::StringConstant) {
5428     MDString *S;
5429     if (parseMDString(S))
5430       return true;
5431     MD = S;
5432     return false;
5433   }
5434 
5435   // MDNode:
5436   // !{ ... }
5437   // !7
5438   MDNode *N;
5439   if (parseMDNodeTail(N))
5440     return true;
5441   MD = N;
5442   return false;
5443 }
5444 
5445 //===----------------------------------------------------------------------===//
5446 // Function Parsing.
5447 //===----------------------------------------------------------------------===//
5448 
convertValIDToValue(Type * Ty,ValID & ID,Value * & V,PerFunctionState * PFS,bool IsCall)5449 bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5450                                    PerFunctionState *PFS, bool IsCall) {
5451   if (Ty->isFunctionTy())
5452     return error(ID.Loc, "functions are not values, refer to them as pointers");
5453 
5454   switch (ID.Kind) {
5455   case ValID::t_LocalID:
5456     if (!PFS)
5457       return error(ID.Loc, "invalid use of function-local name");
5458     V = PFS->getVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5459     return V == nullptr;
5460   case ValID::t_LocalName:
5461     if (!PFS)
5462       return error(ID.Loc, "invalid use of function-local name");
5463     V = PFS->getVal(ID.StrVal, Ty, ID.Loc, IsCall);
5464     return V == nullptr;
5465   case ValID::t_InlineAsm: {
5466     if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
5467       return error(ID.Loc, "invalid type for inline asm constraint string");
5468     V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
5469                        (ID.UIntVal >> 1) & 1,
5470                        (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
5471     return false;
5472   }
5473   case ValID::t_GlobalName:
5474     V = getGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
5475     return V == nullptr;
5476   case ValID::t_GlobalID:
5477     V = getGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5478     return V == nullptr;
5479   case ValID::t_APSInt:
5480     if (!Ty->isIntegerTy())
5481       return error(ID.Loc, "integer constant must have integer type");
5482     ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5483     V = ConstantInt::get(Context, ID.APSIntVal);
5484     return false;
5485   case ValID::t_APFloat:
5486     if (!Ty->isFloatingPointTy() ||
5487         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5488       return error(ID.Loc, "floating point constant invalid for type");
5489 
5490     // The lexer has no type info, so builds all half, bfloat, float, and double
5491     // FP constants as double.  Fix this here.  Long double does not need this.
5492     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5493       // Check for signaling before potentially converting and losing that info.
5494       bool IsSNAN = ID.APFloatVal.isSignaling();
5495       bool Ignored;
5496       if (Ty->isHalfTy())
5497         ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5498                               &Ignored);
5499       else if (Ty->isBFloatTy())
5500         ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
5501                               &Ignored);
5502       else if (Ty->isFloatTy())
5503         ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5504                               &Ignored);
5505       if (IsSNAN) {
5506         // The convert call above may quiet an SNaN, so manufacture another
5507         // SNaN. The bitcast works because the payload (significand) parameter
5508         // is truncated to fit.
5509         APInt Payload = ID.APFloatVal.bitcastToAPInt();
5510         ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
5511                                          ID.APFloatVal.isNegative(), &Payload);
5512       }
5513     }
5514     V = ConstantFP::get(Context, ID.APFloatVal);
5515 
5516     if (V->getType() != Ty)
5517       return error(ID.Loc, "floating point constant does not have type '" +
5518                                getTypeString(Ty) + "'");
5519 
5520     return false;
5521   case ValID::t_Null:
5522     if (!Ty->isPointerTy())
5523       return error(ID.Loc, "null must be a pointer type");
5524     V = ConstantPointerNull::get(cast<PointerType>(Ty));
5525     return false;
5526   case ValID::t_Undef:
5527     // FIXME: LabelTy should not be a first-class type.
5528     if (!Ty->isFirstClassType() || Ty->isLabelTy())
5529       return error(ID.Loc, "invalid type for undef constant");
5530     V = UndefValue::get(Ty);
5531     return false;
5532   case ValID::t_EmptyArray:
5533     if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5534       return error(ID.Loc, "invalid empty array initializer");
5535     V = UndefValue::get(Ty);
5536     return false;
5537   case ValID::t_Zero:
5538     // FIXME: LabelTy should not be a first-class type.
5539     if (!Ty->isFirstClassType() || Ty->isLabelTy())
5540       return error(ID.Loc, "invalid type for null constant");
5541     V = Constant::getNullValue(Ty);
5542     return false;
5543   case ValID::t_None:
5544     if (!Ty->isTokenTy())
5545       return error(ID.Loc, "invalid type for none constant");
5546     V = Constant::getNullValue(Ty);
5547     return false;
5548   case ValID::t_Poison:
5549     // FIXME: LabelTy should not be a first-class type.
5550     if (!Ty->isFirstClassType() || Ty->isLabelTy())
5551       return error(ID.Loc, "invalid type for poison constant");
5552     V = PoisonValue::get(Ty);
5553     return false;
5554   case ValID::t_Constant:
5555     if (ID.ConstantVal->getType() != Ty)
5556       return error(ID.Loc, "constant expression type mismatch");
5557     V = ID.ConstantVal;
5558     return false;
5559   case ValID::t_ConstantStruct:
5560   case ValID::t_PackedConstantStruct:
5561     if (StructType *ST = dyn_cast<StructType>(Ty)) {
5562       if (ST->getNumElements() != ID.UIntVal)
5563         return error(ID.Loc,
5564                      "initializer with struct type has wrong # elements");
5565       if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5566         return error(ID.Loc, "packed'ness of initializer and type don't match");
5567 
5568       // Verify that the elements are compatible with the structtype.
5569       for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5570         if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5571           return error(
5572               ID.Loc,
5573               "element " + Twine(i) +
5574                   " of struct initializer doesn't match struct element type");
5575 
5576       V = ConstantStruct::get(
5577           ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5578     } else
5579       return error(ID.Loc, "constant expression type mismatch");
5580     return false;
5581   }
5582   llvm_unreachable("Invalid ValID");
5583 }
5584 
parseConstantValue(Type * Ty,Constant * & C)5585 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5586   C = nullptr;
5587   ValID ID;
5588   auto Loc = Lex.getLoc();
5589   if (parseValID(ID, /*PFS=*/nullptr))
5590     return true;
5591   switch (ID.Kind) {
5592   case ValID::t_APSInt:
5593   case ValID::t_APFloat:
5594   case ValID::t_Undef:
5595   case ValID::t_Constant:
5596   case ValID::t_ConstantStruct:
5597   case ValID::t_PackedConstantStruct: {
5598     Value *V;
5599     if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
5600       return true;
5601     assert(isa<Constant>(V) && "Expected a constant value");
5602     C = cast<Constant>(V);
5603     return false;
5604   }
5605   case ValID::t_Null:
5606     C = Constant::getNullValue(Ty);
5607     return false;
5608   default:
5609     return error(Loc, "expected a constant value");
5610   }
5611 }
5612 
parseValue(Type * Ty,Value * & V,PerFunctionState * PFS)5613 bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5614   V = nullptr;
5615   ValID ID;
5616   return parseValID(ID, PFS) ||
5617          convertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
5618 }
5619 
parseTypeAndValue(Value * & V,PerFunctionState * PFS)5620 bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5621   Type *Ty = nullptr;
5622   return parseType(Ty) || parseValue(Ty, V, PFS);
5623 }
5624 
parseTypeAndBasicBlock(BasicBlock * & BB,LocTy & Loc,PerFunctionState & PFS)5625 bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5626                                       PerFunctionState &PFS) {
5627   Value *V;
5628   Loc = Lex.getLoc();
5629   if (parseTypeAndValue(V, PFS))
5630     return true;
5631   if (!isa<BasicBlock>(V))
5632     return error(Loc, "expected a basic block");
5633   BB = cast<BasicBlock>(V);
5634   return false;
5635 }
5636 
5637 /// FunctionHeader
5638 ///   ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5639 ///       OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5640 ///       '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5641 ///       OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
parseFunctionHeader(Function * & Fn,bool IsDefine)5642 bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine) {
5643   // parse the linkage.
5644   LocTy LinkageLoc = Lex.getLoc();
5645   unsigned Linkage;
5646   unsigned Visibility;
5647   unsigned DLLStorageClass;
5648   bool DSOLocal;
5649   AttrBuilder RetAttrs;
5650   unsigned CC;
5651   bool HasLinkage;
5652   Type *RetType = nullptr;
5653   LocTy RetTypeLoc = Lex.getLoc();
5654   if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5655                            DSOLocal) ||
5656       parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
5657       parseType(RetType, RetTypeLoc, true /*void allowed*/))
5658     return true;
5659 
5660   // Verify that the linkage is ok.
5661   switch ((GlobalValue::LinkageTypes)Linkage) {
5662   case GlobalValue::ExternalLinkage:
5663     break; // always ok.
5664   case GlobalValue::ExternalWeakLinkage:
5665     if (IsDefine)
5666       return error(LinkageLoc, "invalid linkage for function definition");
5667     break;
5668   case GlobalValue::PrivateLinkage:
5669   case GlobalValue::InternalLinkage:
5670   case GlobalValue::AvailableExternallyLinkage:
5671   case GlobalValue::LinkOnceAnyLinkage:
5672   case GlobalValue::LinkOnceODRLinkage:
5673   case GlobalValue::WeakAnyLinkage:
5674   case GlobalValue::WeakODRLinkage:
5675     if (!IsDefine)
5676       return error(LinkageLoc, "invalid linkage for function declaration");
5677     break;
5678   case GlobalValue::AppendingLinkage:
5679   case GlobalValue::CommonLinkage:
5680     return error(LinkageLoc, "invalid function linkage type");
5681   }
5682 
5683   if (!isValidVisibilityForLinkage(Visibility, Linkage))
5684     return error(LinkageLoc,
5685                  "symbol with local linkage must have default visibility");
5686 
5687   if (!FunctionType::isValidReturnType(RetType))
5688     return error(RetTypeLoc, "invalid function return type");
5689 
5690   LocTy NameLoc = Lex.getLoc();
5691 
5692   std::string FunctionName;
5693   if (Lex.getKind() == lltok::GlobalVar) {
5694     FunctionName = Lex.getStrVal();
5695   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
5696     unsigned NameID = Lex.getUIntVal();
5697 
5698     if (NameID != NumberedVals.size())
5699       return tokError("function expected to be numbered '%" +
5700                       Twine(NumberedVals.size()) + "'");
5701   } else {
5702     return tokError("expected function name");
5703   }
5704 
5705   Lex.Lex();
5706 
5707   if (Lex.getKind() != lltok::lparen)
5708     return tokError("expected '(' in function argument list");
5709 
5710   SmallVector<ArgInfo, 8> ArgList;
5711   bool IsVarArg;
5712   AttrBuilder FuncAttrs;
5713   std::vector<unsigned> FwdRefAttrGrps;
5714   LocTy BuiltinLoc;
5715   std::string Section;
5716   std::string Partition;
5717   MaybeAlign Alignment;
5718   std::string GC;
5719   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
5720   unsigned AddrSpace = 0;
5721   Constant *Prefix = nullptr;
5722   Constant *Prologue = nullptr;
5723   Constant *PersonalityFn = nullptr;
5724   Comdat *C;
5725 
5726   if (parseArgumentList(ArgList, IsVarArg) ||
5727       parseOptionalUnnamedAddr(UnnamedAddr) ||
5728       parseOptionalProgramAddrSpace(AddrSpace) ||
5729       parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5730                                  BuiltinLoc) ||
5731       (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
5732       (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
5733       parseOptionalComdat(FunctionName, C) ||
5734       parseOptionalAlignment(Alignment) ||
5735       (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
5736       (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
5737       (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
5738       (EatIfPresent(lltok::kw_personality) &&
5739        parseGlobalTypeAndValue(PersonalityFn)))
5740     return true;
5741 
5742   if (FuncAttrs.contains(Attribute::Builtin))
5743     return error(BuiltinLoc, "'builtin' attribute not valid on function");
5744 
5745   // If the alignment was parsed as an attribute, move to the alignment field.
5746   if (FuncAttrs.hasAlignmentAttr()) {
5747     Alignment = FuncAttrs.getAlignment();
5748     FuncAttrs.removeAttribute(Attribute::Alignment);
5749   }
5750 
5751   // Okay, if we got here, the function is syntactically valid.  Convert types
5752   // and do semantic checks.
5753   std::vector<Type*> ParamTypeList;
5754   SmallVector<AttributeSet, 8> Attrs;
5755 
5756   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5757     ParamTypeList.push_back(ArgList[i].Ty);
5758     Attrs.push_back(ArgList[i].Attrs);
5759   }
5760 
5761   AttributeList PAL =
5762       AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5763                          AttributeSet::get(Context, RetAttrs), Attrs);
5764 
5765   if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
5766     return error(RetTypeLoc, "functions with 'sret' argument must return void");
5767 
5768   FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
5769   PointerType *PFT = PointerType::get(FT, AddrSpace);
5770 
5771   Fn = nullptr;
5772   if (!FunctionName.empty()) {
5773     // If this was a definition of a forward reference, remove the definition
5774     // from the forward reference table and fill in the forward ref.
5775     auto FRVI = ForwardRefVals.find(FunctionName);
5776     if (FRVI != ForwardRefVals.end()) {
5777       Fn = M->getFunction(FunctionName);
5778       if (!Fn)
5779         return error(FRVI->second.second, "invalid forward reference to "
5780                                           "function as global value!");
5781       if (Fn->getType() != PFT)
5782         return error(FRVI->second.second,
5783                      "invalid forward reference to "
5784                      "function '" +
5785                          FunctionName +
5786                          "' with wrong type: "
5787                          "expected '" +
5788                          getTypeString(PFT) + "' but was '" +
5789                          getTypeString(Fn->getType()) + "'");
5790       ForwardRefVals.erase(FRVI);
5791     } else if ((Fn = M->getFunction(FunctionName))) {
5792       // Reject redefinitions.
5793       return error(NameLoc,
5794                    "invalid redefinition of function '" + FunctionName + "'");
5795     } else if (M->getNamedValue(FunctionName)) {
5796       return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
5797     }
5798 
5799   } else {
5800     // If this is a definition of a forward referenced function, make sure the
5801     // types agree.
5802     auto I = ForwardRefValIDs.find(NumberedVals.size());
5803     if (I != ForwardRefValIDs.end()) {
5804       Fn = cast<Function>(I->second.first);
5805       if (Fn->getType() != PFT)
5806         return error(NameLoc, "type of definition and forward reference of '@" +
5807                                   Twine(NumberedVals.size()) +
5808                                   "' disagree: "
5809                                   "expected '" +
5810                                   getTypeString(PFT) + "' but was '" +
5811                                   getTypeString(Fn->getType()) + "'");
5812       ForwardRefValIDs.erase(I);
5813     }
5814   }
5815 
5816   if (!Fn)
5817     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5818                           FunctionName, M);
5819   else // Move the forward-reference to the correct spot in the module.
5820     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5821 
5822   assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5823 
5824   if (FunctionName.empty())
5825     NumberedVals.push_back(Fn);
5826 
5827   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5828   maybeSetDSOLocal(DSOLocal, *Fn);
5829   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
5830   Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
5831   Fn->setCallingConv(CC);
5832   Fn->setAttributes(PAL);
5833   Fn->setUnnamedAddr(UnnamedAddr);
5834   Fn->setAlignment(MaybeAlign(Alignment));
5835   Fn->setSection(Section);
5836   Fn->setPartition(Partition);
5837   Fn->setComdat(C);
5838   Fn->setPersonalityFn(PersonalityFn);
5839   if (!GC.empty()) Fn->setGC(GC);
5840   Fn->setPrefixData(Prefix);
5841   Fn->setPrologueData(Prologue);
5842   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5843 
5844   // Add all of the arguments we parsed to the function.
5845   Function::arg_iterator ArgIt = Fn->arg_begin();
5846   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5847     // If the argument has a name, insert it into the argument symbol table.
5848     if (ArgList[i].Name.empty()) continue;
5849 
5850     // Set the name, if it conflicted, it will be auto-renamed.
5851     ArgIt->setName(ArgList[i].Name);
5852 
5853     if (ArgIt->getName() != ArgList[i].Name)
5854       return error(ArgList[i].Loc,
5855                    "redefinition of argument '%" + ArgList[i].Name + "'");
5856   }
5857 
5858   if (IsDefine)
5859     return false;
5860 
5861   // Check the declaration has no block address forward references.
5862   ValID ID;
5863   if (FunctionName.empty()) {
5864     ID.Kind = ValID::t_GlobalID;
5865     ID.UIntVal = NumberedVals.size() - 1;
5866   } else {
5867     ID.Kind = ValID::t_GlobalName;
5868     ID.StrVal = FunctionName;
5869   }
5870   auto Blocks = ForwardRefBlockAddresses.find(ID);
5871   if (Blocks != ForwardRefBlockAddresses.end())
5872     return error(Blocks->first.Loc,
5873                  "cannot take blockaddress inside a declaration");
5874   return false;
5875 }
5876 
resolveForwardRefBlockAddresses()5877 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5878   ValID ID;
5879   if (FunctionNumber == -1) {
5880     ID.Kind = ValID::t_GlobalName;
5881     ID.StrVal = std::string(F.getName());
5882   } else {
5883     ID.Kind = ValID::t_GlobalID;
5884     ID.UIntVal = FunctionNumber;
5885   }
5886 
5887   auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5888   if (Blocks == P.ForwardRefBlockAddresses.end())
5889     return false;
5890 
5891   for (const auto &I : Blocks->second) {
5892     const ValID &BBID = I.first;
5893     GlobalValue *GV = I.second;
5894 
5895     assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5896            "Expected local id or name");
5897     BasicBlock *BB;
5898     if (BBID.Kind == ValID::t_LocalName)
5899       BB = getBB(BBID.StrVal, BBID.Loc);
5900     else
5901       BB = getBB(BBID.UIntVal, BBID.Loc);
5902     if (!BB)
5903       return P.error(BBID.Loc, "referenced value is not a basic block");
5904 
5905     GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5906     GV->eraseFromParent();
5907   }
5908 
5909   P.ForwardRefBlockAddresses.erase(Blocks);
5910   return false;
5911 }
5912 
5913 /// parseFunctionBody
5914 ///   ::= '{' BasicBlock+ UseListOrderDirective* '}'
parseFunctionBody(Function & Fn)5915 bool LLParser::parseFunctionBody(Function &Fn) {
5916   if (Lex.getKind() != lltok::lbrace)
5917     return tokError("expected '{' in function body");
5918   Lex.Lex();  // eat the {.
5919 
5920   int FunctionNumber = -1;
5921   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
5922 
5923   PerFunctionState PFS(*this, Fn, FunctionNumber);
5924 
5925   // Resolve block addresses and allow basic blocks to be forward-declared
5926   // within this function.
5927   if (PFS.resolveForwardRefBlockAddresses())
5928     return true;
5929   SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5930 
5931   // We need at least one basic block.
5932   if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
5933     return tokError("function body requires at least one basic block");
5934 
5935   while (Lex.getKind() != lltok::rbrace &&
5936          Lex.getKind() != lltok::kw_uselistorder)
5937     if (parseBasicBlock(PFS))
5938       return true;
5939 
5940   while (Lex.getKind() != lltok::rbrace)
5941     if (parseUseListOrder(&PFS))
5942       return true;
5943 
5944   // Eat the }.
5945   Lex.Lex();
5946 
5947   // Verify function is ok.
5948   return PFS.finishFunction();
5949 }
5950 
5951 /// parseBasicBlock
5952 ///   ::= (LabelStr|LabelID)? Instruction*
parseBasicBlock(PerFunctionState & PFS)5953 bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
5954   // If this basic block starts out with a name, remember it.
5955   std::string Name;
5956   int NameID = -1;
5957   LocTy NameLoc = Lex.getLoc();
5958   if (Lex.getKind() == lltok::LabelStr) {
5959     Name = Lex.getStrVal();
5960     Lex.Lex();
5961   } else if (Lex.getKind() == lltok::LabelID) {
5962     NameID = Lex.getUIntVal();
5963     Lex.Lex();
5964   }
5965 
5966   BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
5967   if (!BB)
5968     return true;
5969 
5970   std::string NameStr;
5971 
5972   // parse the instructions in this block until we get a terminator.
5973   Instruction *Inst;
5974   do {
5975     // This instruction may have three possibilities for a name: a) none
5976     // specified, b) name specified "%foo =", c) number specified: "%4 =".
5977     LocTy NameLoc = Lex.getLoc();
5978     int NameID = -1;
5979     NameStr = "";
5980 
5981     if (Lex.getKind() == lltok::LocalVarID) {
5982       NameID = Lex.getUIntVal();
5983       Lex.Lex();
5984       if (parseToken(lltok::equal, "expected '=' after instruction id"))
5985         return true;
5986     } else if (Lex.getKind() == lltok::LocalVar) {
5987       NameStr = Lex.getStrVal();
5988       Lex.Lex();
5989       if (parseToken(lltok::equal, "expected '=' after instruction name"))
5990         return true;
5991     }
5992 
5993     switch (parseInstruction(Inst, BB, PFS)) {
5994     default:
5995       llvm_unreachable("Unknown parseInstruction result!");
5996     case InstError: return true;
5997     case InstNormal:
5998       BB->getInstList().push_back(Inst);
5999 
6000       // With a normal result, we check to see if the instruction is followed by
6001       // a comma and metadata.
6002       if (EatIfPresent(lltok::comma))
6003         if (parseInstructionMetadata(*Inst))
6004           return true;
6005       break;
6006     case InstExtraComma:
6007       BB->getInstList().push_back(Inst);
6008 
6009       // If the instruction parser ate an extra comma at the end of it, it
6010       // *must* be followed by metadata.
6011       if (parseInstructionMetadata(*Inst))
6012         return true;
6013       break;
6014     }
6015 
6016     // Set the name on the instruction.
6017     if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6018       return true;
6019   } while (!Inst->isTerminator());
6020 
6021   return false;
6022 }
6023 
6024 //===----------------------------------------------------------------------===//
6025 // Instruction Parsing.
6026 //===----------------------------------------------------------------------===//
6027 
6028 /// parseInstruction - parse one of the many different instructions.
6029 ///
parseInstruction(Instruction * & Inst,BasicBlock * BB,PerFunctionState & PFS)6030 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
6031                                PerFunctionState &PFS) {
6032   lltok::Kind Token = Lex.getKind();
6033   if (Token == lltok::Eof)
6034     return tokError("found end of file when expecting more instructions");
6035   LocTy Loc = Lex.getLoc();
6036   unsigned KeywordVal = Lex.getUIntVal();
6037   Lex.Lex();  // Eat the keyword.
6038 
6039   switch (Token) {
6040   default:
6041     return error(Loc, "expected instruction opcode");
6042   // Terminator Instructions.
6043   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
6044   case lltok::kw_ret:
6045     return parseRet(Inst, BB, PFS);
6046   case lltok::kw_br:
6047     return parseBr(Inst, PFS);
6048   case lltok::kw_switch:
6049     return parseSwitch(Inst, PFS);
6050   case lltok::kw_indirectbr:
6051     return parseIndirectBr(Inst, PFS);
6052   case lltok::kw_invoke:
6053     return parseInvoke(Inst, PFS);
6054   case lltok::kw_resume:
6055     return parseResume(Inst, PFS);
6056   case lltok::kw_cleanupret:
6057     return parseCleanupRet(Inst, PFS);
6058   case lltok::kw_catchret:
6059     return parseCatchRet(Inst, PFS);
6060   case lltok::kw_catchswitch:
6061     return parseCatchSwitch(Inst, PFS);
6062   case lltok::kw_catchpad:
6063     return parseCatchPad(Inst, PFS);
6064   case lltok::kw_cleanuppad:
6065     return parseCleanupPad(Inst, PFS);
6066   case lltok::kw_callbr:
6067     return parseCallBr(Inst, PFS);
6068   // Unary Operators.
6069   case lltok::kw_fneg: {
6070     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6071     int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
6072     if (Res != 0)
6073       return Res;
6074     if (FMF.any())
6075       Inst->setFastMathFlags(FMF);
6076     return false;
6077   }
6078   // Binary Operators.
6079   case lltok::kw_add:
6080   case lltok::kw_sub:
6081   case lltok::kw_mul:
6082   case lltok::kw_shl: {
6083     bool NUW = EatIfPresent(lltok::kw_nuw);
6084     bool NSW = EatIfPresent(lltok::kw_nsw);
6085     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
6086 
6087     if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6088       return true;
6089 
6090     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
6091     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
6092     return false;
6093   }
6094   case lltok::kw_fadd:
6095   case lltok::kw_fsub:
6096   case lltok::kw_fmul:
6097   case lltok::kw_fdiv:
6098   case lltok::kw_frem: {
6099     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6100     int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
6101     if (Res != 0)
6102       return Res;
6103     if (FMF.any())
6104       Inst->setFastMathFlags(FMF);
6105     return 0;
6106   }
6107 
6108   case lltok::kw_sdiv:
6109   case lltok::kw_udiv:
6110   case lltok::kw_lshr:
6111   case lltok::kw_ashr: {
6112     bool Exact = EatIfPresent(lltok::kw_exact);
6113 
6114     if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6115       return true;
6116     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
6117     return false;
6118   }
6119 
6120   case lltok::kw_urem:
6121   case lltok::kw_srem:
6122     return parseArithmetic(Inst, PFS, KeywordVal,
6123                            /*IsFP*/ false);
6124   case lltok::kw_and:
6125   case lltok::kw_or:
6126   case lltok::kw_xor:
6127     return parseLogical(Inst, PFS, KeywordVal);
6128   case lltok::kw_icmp:
6129     return parseCompare(Inst, PFS, KeywordVal);
6130   case lltok::kw_fcmp: {
6131     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6132     int Res = parseCompare(Inst, PFS, KeywordVal);
6133     if (Res != 0)
6134       return Res;
6135     if (FMF.any())
6136       Inst->setFastMathFlags(FMF);
6137     return 0;
6138   }
6139 
6140   // Casts.
6141   case lltok::kw_trunc:
6142   case lltok::kw_zext:
6143   case lltok::kw_sext:
6144   case lltok::kw_fptrunc:
6145   case lltok::kw_fpext:
6146   case lltok::kw_bitcast:
6147   case lltok::kw_addrspacecast:
6148   case lltok::kw_uitofp:
6149   case lltok::kw_sitofp:
6150   case lltok::kw_fptoui:
6151   case lltok::kw_fptosi:
6152   case lltok::kw_inttoptr:
6153   case lltok::kw_ptrtoint:
6154     return parseCast(Inst, PFS, KeywordVal);
6155   // Other.
6156   case lltok::kw_select: {
6157     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6158     int Res = parseSelect(Inst, PFS);
6159     if (Res != 0)
6160       return Res;
6161     if (FMF.any()) {
6162       if (!isa<FPMathOperator>(Inst))
6163         return error(Loc, "fast-math-flags specified for select without "
6164                           "floating-point scalar or vector return type");
6165       Inst->setFastMathFlags(FMF);
6166     }
6167     return 0;
6168   }
6169   case lltok::kw_va_arg:
6170     return parseVAArg(Inst, PFS);
6171   case lltok::kw_extractelement:
6172     return parseExtractElement(Inst, PFS);
6173   case lltok::kw_insertelement:
6174     return parseInsertElement(Inst, PFS);
6175   case lltok::kw_shufflevector:
6176     return parseShuffleVector(Inst, PFS);
6177   case lltok::kw_phi: {
6178     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6179     int Res = parsePHI(Inst, PFS);
6180     if (Res != 0)
6181       return Res;
6182     if (FMF.any()) {
6183       if (!isa<FPMathOperator>(Inst))
6184         return error(Loc, "fast-math-flags specified for phi without "
6185                           "floating-point scalar or vector return type");
6186       Inst->setFastMathFlags(FMF);
6187     }
6188     return 0;
6189   }
6190   case lltok::kw_landingpad:
6191     return parseLandingPad(Inst, PFS);
6192   case lltok::kw_freeze:
6193     return parseFreeze(Inst, PFS);
6194   // Call.
6195   case lltok::kw_call:
6196     return parseCall(Inst, PFS, CallInst::TCK_None);
6197   case lltok::kw_tail:
6198     return parseCall(Inst, PFS, CallInst::TCK_Tail);
6199   case lltok::kw_musttail:
6200     return parseCall(Inst, PFS, CallInst::TCK_MustTail);
6201   case lltok::kw_notail:
6202     return parseCall(Inst, PFS, CallInst::TCK_NoTail);
6203   // Memory.
6204   case lltok::kw_alloca:
6205     return parseAlloc(Inst, PFS);
6206   case lltok::kw_load:
6207     return parseLoad(Inst, PFS);
6208   case lltok::kw_store:
6209     return parseStore(Inst, PFS);
6210   case lltok::kw_cmpxchg:
6211     return parseCmpXchg(Inst, PFS);
6212   case lltok::kw_atomicrmw:
6213     return parseAtomicRMW(Inst, PFS);
6214   case lltok::kw_fence:
6215     return parseFence(Inst, PFS);
6216   case lltok::kw_getelementptr:
6217     return parseGetElementPtr(Inst, PFS);
6218   case lltok::kw_extractvalue:
6219     return parseExtractValue(Inst, PFS);
6220   case lltok::kw_insertvalue:
6221     return parseInsertValue(Inst, PFS);
6222   }
6223 }
6224 
6225 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
parseCmpPredicate(unsigned & P,unsigned Opc)6226 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
6227   if (Opc == Instruction::FCmp) {
6228     switch (Lex.getKind()) {
6229     default:
6230       return tokError("expected fcmp predicate (e.g. 'oeq')");
6231     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
6232     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
6233     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
6234     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
6235     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
6236     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
6237     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
6238     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
6239     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
6240     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
6241     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
6242     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
6243     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
6244     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
6245     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
6246     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
6247     }
6248   } else {
6249     switch (Lex.getKind()) {
6250     default:
6251       return tokError("expected icmp predicate (e.g. 'eq')");
6252     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
6253     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
6254     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
6255     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
6256     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
6257     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
6258     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
6259     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
6260     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
6261     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
6262     }
6263   }
6264   Lex.Lex();
6265   return false;
6266 }
6267 
6268 //===----------------------------------------------------------------------===//
6269 // Terminator Instructions.
6270 //===----------------------------------------------------------------------===//
6271 
6272 /// parseRet - parse a return instruction.
6273 ///   ::= 'ret' void (',' !dbg, !1)*
6274 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
parseRet(Instruction * & Inst,BasicBlock * BB,PerFunctionState & PFS)6275 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
6276                         PerFunctionState &PFS) {
6277   SMLoc TypeLoc = Lex.getLoc();
6278   Type *Ty = nullptr;
6279   if (parseType(Ty, true /*void allowed*/))
6280     return true;
6281 
6282   Type *ResType = PFS.getFunction().getReturnType();
6283 
6284   if (Ty->isVoidTy()) {
6285     if (!ResType->isVoidTy())
6286       return error(TypeLoc, "value doesn't match function result type '" +
6287                                 getTypeString(ResType) + "'");
6288 
6289     Inst = ReturnInst::Create(Context);
6290     return false;
6291   }
6292 
6293   Value *RV;
6294   if (parseValue(Ty, RV, PFS))
6295     return true;
6296 
6297   if (ResType != RV->getType())
6298     return error(TypeLoc, "value doesn't match function result type '" +
6299                               getTypeString(ResType) + "'");
6300 
6301   Inst = ReturnInst::Create(Context, RV);
6302   return false;
6303 }
6304 
6305 /// parseBr
6306 ///   ::= 'br' TypeAndValue
6307 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
parseBr(Instruction * & Inst,PerFunctionState & PFS)6308 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
6309   LocTy Loc, Loc2;
6310   Value *Op0;
6311   BasicBlock *Op1, *Op2;
6312   if (parseTypeAndValue(Op0, Loc, PFS))
6313     return true;
6314 
6315   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
6316     Inst = BranchInst::Create(BB);
6317     return false;
6318   }
6319 
6320   if (Op0->getType() != Type::getInt1Ty(Context))
6321     return error(Loc, "branch condition must have 'i1' type");
6322 
6323   if (parseToken(lltok::comma, "expected ',' after branch condition") ||
6324       parseTypeAndBasicBlock(Op1, Loc, PFS) ||
6325       parseToken(lltok::comma, "expected ',' after true destination") ||
6326       parseTypeAndBasicBlock(Op2, Loc2, PFS))
6327     return true;
6328 
6329   Inst = BranchInst::Create(Op1, Op2, Op0);
6330   return false;
6331 }
6332 
6333 /// parseSwitch
6334 ///  Instruction
6335 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
6336 ///  JumpTable
6337 ///    ::= (TypeAndValue ',' TypeAndValue)*
parseSwitch(Instruction * & Inst,PerFunctionState & PFS)6338 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6339   LocTy CondLoc, BBLoc;
6340   Value *Cond;
6341   BasicBlock *DefaultBB;
6342   if (parseTypeAndValue(Cond, CondLoc, PFS) ||
6343       parseToken(lltok::comma, "expected ',' after switch condition") ||
6344       parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
6345       parseToken(lltok::lsquare, "expected '[' with switch table"))
6346     return true;
6347 
6348   if (!Cond->getType()->isIntegerTy())
6349     return error(CondLoc, "switch condition must have integer type");
6350 
6351   // parse the jump table pairs.
6352   SmallPtrSet<Value*, 32> SeenCases;
6353   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
6354   while (Lex.getKind() != lltok::rsquare) {
6355     Value *Constant;
6356     BasicBlock *DestBB;
6357 
6358     if (parseTypeAndValue(Constant, CondLoc, PFS) ||
6359         parseToken(lltok::comma, "expected ',' after case value") ||
6360         parseTypeAndBasicBlock(DestBB, PFS))
6361       return true;
6362 
6363     if (!SeenCases.insert(Constant).second)
6364       return error(CondLoc, "duplicate case value in switch");
6365     if (!isa<ConstantInt>(Constant))
6366       return error(CondLoc, "case value is not a constant integer");
6367 
6368     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
6369   }
6370 
6371   Lex.Lex();  // Eat the ']'.
6372 
6373   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
6374   for (unsigned i = 0, e = Table.size(); i != e; ++i)
6375     SI->addCase(Table[i].first, Table[i].second);
6376   Inst = SI;
6377   return false;
6378 }
6379 
6380 /// parseIndirectBr
6381 ///  Instruction
6382 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
parseIndirectBr(Instruction * & Inst,PerFunctionState & PFS)6383 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
6384   LocTy AddrLoc;
6385   Value *Address;
6386   if (parseTypeAndValue(Address, AddrLoc, PFS) ||
6387       parseToken(lltok::comma, "expected ',' after indirectbr address") ||
6388       parseToken(lltok::lsquare, "expected '[' with indirectbr"))
6389     return true;
6390 
6391   if (!Address->getType()->isPointerTy())
6392     return error(AddrLoc, "indirectbr address must have pointer type");
6393 
6394   // parse the destination list.
6395   SmallVector<BasicBlock*, 16> DestList;
6396 
6397   if (Lex.getKind() != lltok::rsquare) {
6398     BasicBlock *DestBB;
6399     if (parseTypeAndBasicBlock(DestBB, PFS))
6400       return true;
6401     DestList.push_back(DestBB);
6402 
6403     while (EatIfPresent(lltok::comma)) {
6404       if (parseTypeAndBasicBlock(DestBB, PFS))
6405         return true;
6406       DestList.push_back(DestBB);
6407     }
6408   }
6409 
6410   if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6411     return true;
6412 
6413   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
6414   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
6415     IBI->addDestination(DestList[i]);
6416   Inst = IBI;
6417   return false;
6418 }
6419 
6420 /// parseInvoke
6421 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6422 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
parseInvoke(Instruction * & Inst,PerFunctionState & PFS)6423 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
6424   LocTy CallLoc = Lex.getLoc();
6425   AttrBuilder RetAttrs, FnAttrs;
6426   std::vector<unsigned> FwdRefAttrGrps;
6427   LocTy NoBuiltinLoc;
6428   unsigned CC;
6429   unsigned InvokeAddrSpace;
6430   Type *RetType = nullptr;
6431   LocTy RetTypeLoc;
6432   ValID CalleeID;
6433   SmallVector<ParamInfo, 16> ArgList;
6434   SmallVector<OperandBundleDef, 2> BundleList;
6435 
6436   BasicBlock *NormalBB, *UnwindBB;
6437   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6438       parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
6439       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6440       parseValID(CalleeID) || parseParameterList(ArgList, PFS) ||
6441       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6442                                  NoBuiltinLoc) ||
6443       parseOptionalOperandBundles(BundleList, PFS) ||
6444       parseToken(lltok::kw_to, "expected 'to' in invoke") ||
6445       parseTypeAndBasicBlock(NormalBB, PFS) ||
6446       parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
6447       parseTypeAndBasicBlock(UnwindBB, PFS))
6448     return true;
6449 
6450   // If RetType is a non-function pointer type, then this is the short syntax
6451   // for the call, which means that RetType is just the return type.  Infer the
6452   // rest of the function argument types from the arguments that are present.
6453   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6454   if (!Ty) {
6455     // Pull out the types of all of the arguments...
6456     std::vector<Type*> ParamTypes;
6457     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6458       ParamTypes.push_back(ArgList[i].V->getType());
6459 
6460     if (!FunctionType::isValidReturnType(RetType))
6461       return error(RetTypeLoc, "Invalid result type for LLVM function");
6462 
6463     Ty = FunctionType::get(RetType, ParamTypes, false);
6464   }
6465 
6466   CalleeID.FTy = Ty;
6467 
6468   // Look up the callee.
6469   Value *Callee;
6470   if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
6471                           Callee, &PFS, /*IsCall=*/true))
6472     return true;
6473 
6474   // Set up the Attribute for the function.
6475   SmallVector<Value *, 8> Args;
6476   SmallVector<AttributeSet, 8> ArgAttrs;
6477 
6478   // Loop through FunctionType's arguments and ensure they are specified
6479   // correctly.  Also, gather any parameter attributes.
6480   FunctionType::param_iterator I = Ty->param_begin();
6481   FunctionType::param_iterator E = Ty->param_end();
6482   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6483     Type *ExpectedTy = nullptr;
6484     if (I != E) {
6485       ExpectedTy = *I++;
6486     } else if (!Ty->isVarArg()) {
6487       return error(ArgList[i].Loc, "too many arguments specified");
6488     }
6489 
6490     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6491       return error(ArgList[i].Loc, "argument is not of expected type '" +
6492                                        getTypeString(ExpectedTy) + "'");
6493     Args.push_back(ArgList[i].V);
6494     ArgAttrs.push_back(ArgList[i].Attrs);
6495   }
6496 
6497   if (I != E)
6498     return error(CallLoc, "not enough parameters specified for call");
6499 
6500   if (FnAttrs.hasAlignmentAttr())
6501     return error(CallLoc, "invoke instructions may not have an alignment");
6502 
6503   // Finish off the Attribute and check them
6504   AttributeList PAL =
6505       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6506                          AttributeSet::get(Context, RetAttrs), ArgAttrs);
6507 
6508   InvokeInst *II =
6509       InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
6510   II->setCallingConv(CC);
6511   II->setAttributes(PAL);
6512   ForwardRefAttrGroups[II] = FwdRefAttrGrps;
6513   Inst = II;
6514   return false;
6515 }
6516 
6517 /// parseResume
6518 ///   ::= 'resume' TypeAndValue
parseResume(Instruction * & Inst,PerFunctionState & PFS)6519 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
6520   Value *Exn; LocTy ExnLoc;
6521   if (parseTypeAndValue(Exn, ExnLoc, PFS))
6522     return true;
6523 
6524   ResumeInst *RI = ResumeInst::Create(Exn);
6525   Inst = RI;
6526   return false;
6527 }
6528 
parseExceptionArgs(SmallVectorImpl<Value * > & Args,PerFunctionState & PFS)6529 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
6530                                   PerFunctionState &PFS) {
6531   if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
6532     return true;
6533 
6534   while (Lex.getKind() != lltok::rsquare) {
6535     // If this isn't the first argument, we need a comma.
6536     if (!Args.empty() &&
6537         parseToken(lltok::comma, "expected ',' in argument list"))
6538       return true;
6539 
6540     // parse the argument.
6541     LocTy ArgLoc;
6542     Type *ArgTy = nullptr;
6543     if (parseType(ArgTy, ArgLoc))
6544       return true;
6545 
6546     Value *V;
6547     if (ArgTy->isMetadataTy()) {
6548       if (parseMetadataAsValue(V, PFS))
6549         return true;
6550     } else {
6551       if (parseValue(ArgTy, V, PFS))
6552         return true;
6553     }
6554     Args.push_back(V);
6555   }
6556 
6557   Lex.Lex();  // Lex the ']'.
6558   return false;
6559 }
6560 
6561 /// parseCleanupRet
6562 ///   ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
parseCleanupRet(Instruction * & Inst,PerFunctionState & PFS)6563 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
6564   Value *CleanupPad = nullptr;
6565 
6566   if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6567     return true;
6568 
6569   if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
6570     return true;
6571 
6572   if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6573     return true;
6574 
6575   BasicBlock *UnwindBB = nullptr;
6576   if (Lex.getKind() == lltok::kw_to) {
6577     Lex.Lex();
6578     if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6579       return true;
6580   } else {
6581     if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
6582       return true;
6583     }
6584   }
6585 
6586   Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
6587   return false;
6588 }
6589 
6590 /// parseCatchRet
6591 ///   ::= 'catchret' from Parent Value 'to' TypeAndValue
parseCatchRet(Instruction * & Inst,PerFunctionState & PFS)6592 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
6593   Value *CatchPad = nullptr;
6594 
6595   if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
6596     return true;
6597 
6598   if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
6599     return true;
6600 
6601   BasicBlock *BB;
6602   if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
6603       parseTypeAndBasicBlock(BB, PFS))
6604     return true;
6605 
6606   Inst = CatchReturnInst::Create(CatchPad, BB);
6607   return false;
6608 }
6609 
6610 /// parseCatchSwitch
6611 ///   ::= 'catchswitch' within Parent
parseCatchSwitch(Instruction * & Inst,PerFunctionState & PFS)6612 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6613   Value *ParentPad;
6614 
6615   if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6616     return true;
6617 
6618   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6619       Lex.getKind() != lltok::LocalVarID)
6620     return tokError("expected scope value for catchswitch");
6621 
6622   if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6623     return true;
6624 
6625   if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6626     return true;
6627 
6628   SmallVector<BasicBlock *, 32> Table;
6629   do {
6630     BasicBlock *DestBB;
6631     if (parseTypeAndBasicBlock(DestBB, PFS))
6632       return true;
6633     Table.push_back(DestBB);
6634   } while (EatIfPresent(lltok::comma));
6635 
6636   if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6637     return true;
6638 
6639   if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
6640     return true;
6641 
6642   BasicBlock *UnwindBB = nullptr;
6643   if (EatIfPresent(lltok::kw_to)) {
6644     if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6645       return true;
6646   } else {
6647     if (parseTypeAndBasicBlock(UnwindBB, PFS))
6648       return true;
6649   }
6650 
6651   auto *CatchSwitch =
6652       CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6653   for (BasicBlock *DestBB : Table)
6654     CatchSwitch->addHandler(DestBB);
6655   Inst = CatchSwitch;
6656   return false;
6657 }
6658 
6659 /// parseCatchPad
6660 ///   ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
parseCatchPad(Instruction * & Inst,PerFunctionState & PFS)6661 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
6662   Value *CatchSwitch = nullptr;
6663 
6664   if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
6665     return true;
6666 
6667   if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6668     return tokError("expected scope value for catchpad");
6669 
6670   if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6671     return true;
6672 
6673   SmallVector<Value *, 8> Args;
6674   if (parseExceptionArgs(Args, PFS))
6675     return true;
6676 
6677   Inst = CatchPadInst::Create(CatchSwitch, Args);
6678   return false;
6679 }
6680 
6681 /// parseCleanupPad
6682 ///   ::= 'cleanuppad' within Parent ParamList
parseCleanupPad(Instruction * & Inst,PerFunctionState & PFS)6683 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
6684   Value *ParentPad = nullptr;
6685 
6686   if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6687     return true;
6688 
6689   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6690       Lex.getKind() != lltok::LocalVarID)
6691     return tokError("expected scope value for cleanuppad");
6692 
6693   if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6694     return true;
6695 
6696   SmallVector<Value *, 8> Args;
6697   if (parseExceptionArgs(Args, PFS))
6698     return true;
6699 
6700   Inst = CleanupPadInst::Create(ParentPad, Args);
6701   return false;
6702 }
6703 
6704 //===----------------------------------------------------------------------===//
6705 // Unary Operators.
6706 //===----------------------------------------------------------------------===//
6707 
6708 /// parseUnaryOp
6709 ///  ::= UnaryOp TypeAndValue ',' Value
6710 ///
6711 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6712 /// operand is allowed.
parseUnaryOp(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc,bool IsFP)6713 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6714                             unsigned Opc, bool IsFP) {
6715   LocTy Loc; Value *LHS;
6716   if (parseTypeAndValue(LHS, Loc, PFS))
6717     return true;
6718 
6719   bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6720                     : LHS->getType()->isIntOrIntVectorTy();
6721 
6722   if (!Valid)
6723     return error(Loc, "invalid operand type for instruction");
6724 
6725   Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6726   return false;
6727 }
6728 
6729 /// parseCallBr
6730 ///   ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6731 ///       OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6732 ///       '[' LabelList ']'
parseCallBr(Instruction * & Inst,PerFunctionState & PFS)6733 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
6734   LocTy CallLoc = Lex.getLoc();
6735   AttrBuilder RetAttrs, FnAttrs;
6736   std::vector<unsigned> FwdRefAttrGrps;
6737   LocTy NoBuiltinLoc;
6738   unsigned CC;
6739   Type *RetType = nullptr;
6740   LocTy RetTypeLoc;
6741   ValID CalleeID;
6742   SmallVector<ParamInfo, 16> ArgList;
6743   SmallVector<OperandBundleDef, 2> BundleList;
6744 
6745   BasicBlock *DefaultDest;
6746   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6747       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6748       parseValID(CalleeID) || parseParameterList(ArgList, PFS) ||
6749       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6750                                  NoBuiltinLoc) ||
6751       parseOptionalOperandBundles(BundleList, PFS) ||
6752       parseToken(lltok::kw_to, "expected 'to' in callbr") ||
6753       parseTypeAndBasicBlock(DefaultDest, PFS) ||
6754       parseToken(lltok::lsquare, "expected '[' in callbr"))
6755     return true;
6756 
6757   // parse the destination list.
6758   SmallVector<BasicBlock *, 16> IndirectDests;
6759 
6760   if (Lex.getKind() != lltok::rsquare) {
6761     BasicBlock *DestBB;
6762     if (parseTypeAndBasicBlock(DestBB, PFS))
6763       return true;
6764     IndirectDests.push_back(DestBB);
6765 
6766     while (EatIfPresent(lltok::comma)) {
6767       if (parseTypeAndBasicBlock(DestBB, PFS))
6768         return true;
6769       IndirectDests.push_back(DestBB);
6770     }
6771   }
6772 
6773   if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6774     return true;
6775 
6776   // If RetType is a non-function pointer type, then this is the short syntax
6777   // for the call, which means that RetType is just the return type.  Infer the
6778   // rest of the function argument types from the arguments that are present.
6779   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6780   if (!Ty) {
6781     // Pull out the types of all of the arguments...
6782     std::vector<Type *> ParamTypes;
6783     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6784       ParamTypes.push_back(ArgList[i].V->getType());
6785 
6786     if (!FunctionType::isValidReturnType(RetType))
6787       return error(RetTypeLoc, "Invalid result type for LLVM function");
6788 
6789     Ty = FunctionType::get(RetType, ParamTypes, false);
6790   }
6791 
6792   CalleeID.FTy = Ty;
6793 
6794   // Look up the callee.
6795   Value *Callee;
6796   if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
6797                           /*IsCall=*/true))
6798     return true;
6799 
6800   // Set up the Attribute for the function.
6801   SmallVector<Value *, 8> Args;
6802   SmallVector<AttributeSet, 8> ArgAttrs;
6803 
6804   // Loop through FunctionType's arguments and ensure they are specified
6805   // correctly.  Also, gather any parameter attributes.
6806   FunctionType::param_iterator I = Ty->param_begin();
6807   FunctionType::param_iterator E = Ty->param_end();
6808   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6809     Type *ExpectedTy = nullptr;
6810     if (I != E) {
6811       ExpectedTy = *I++;
6812     } else if (!Ty->isVarArg()) {
6813       return error(ArgList[i].Loc, "too many arguments specified");
6814     }
6815 
6816     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6817       return error(ArgList[i].Loc, "argument is not of expected type '" +
6818                                        getTypeString(ExpectedTy) + "'");
6819     Args.push_back(ArgList[i].V);
6820     ArgAttrs.push_back(ArgList[i].Attrs);
6821   }
6822 
6823   if (I != E)
6824     return error(CallLoc, "not enough parameters specified for call");
6825 
6826   if (FnAttrs.hasAlignmentAttr())
6827     return error(CallLoc, "callbr instructions may not have an alignment");
6828 
6829   // Finish off the Attribute and check them
6830   AttributeList PAL =
6831       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6832                          AttributeSet::get(Context, RetAttrs), ArgAttrs);
6833 
6834   CallBrInst *CBI =
6835       CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
6836                          BundleList);
6837   CBI->setCallingConv(CC);
6838   CBI->setAttributes(PAL);
6839   ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
6840   Inst = CBI;
6841   return false;
6842 }
6843 
6844 //===----------------------------------------------------------------------===//
6845 // Binary Operators.
6846 //===----------------------------------------------------------------------===//
6847 
6848 /// parseArithmetic
6849 ///  ::= ArithmeticOps TypeAndValue ',' Value
6850 ///
6851 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6852 /// operand is allowed.
parseArithmetic(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc,bool IsFP)6853 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
6854                                unsigned Opc, bool IsFP) {
6855   LocTy Loc; Value *LHS, *RHS;
6856   if (parseTypeAndValue(LHS, Loc, PFS) ||
6857       parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6858       parseValue(LHS->getType(), RHS, PFS))
6859     return true;
6860 
6861   bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6862                     : LHS->getType()->isIntOrIntVectorTy();
6863 
6864   if (!Valid)
6865     return error(Loc, "invalid operand type for instruction");
6866 
6867   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6868   return false;
6869 }
6870 
6871 /// parseLogical
6872 ///  ::= ArithmeticOps TypeAndValue ',' Value {
parseLogical(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc)6873 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
6874                             unsigned Opc) {
6875   LocTy Loc; Value *LHS, *RHS;
6876   if (parseTypeAndValue(LHS, Loc, PFS) ||
6877       parseToken(lltok::comma, "expected ',' in logical operation") ||
6878       parseValue(LHS->getType(), RHS, PFS))
6879     return true;
6880 
6881   if (!LHS->getType()->isIntOrIntVectorTy())
6882     return error(Loc,
6883                  "instruction requires integer or integer vector operands");
6884 
6885   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6886   return false;
6887 }
6888 
6889 /// parseCompare
6890 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
6891 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
parseCompare(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc)6892 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
6893                             unsigned Opc) {
6894   // parse the integer/fp comparison predicate.
6895   LocTy Loc;
6896   unsigned Pred;
6897   Value *LHS, *RHS;
6898   if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
6899       parseToken(lltok::comma, "expected ',' after compare value") ||
6900       parseValue(LHS->getType(), RHS, PFS))
6901     return true;
6902 
6903   if (Opc == Instruction::FCmp) {
6904     if (!LHS->getType()->isFPOrFPVectorTy())
6905       return error(Loc, "fcmp requires floating point operands");
6906     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6907   } else {
6908     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
6909     if (!LHS->getType()->isIntOrIntVectorTy() &&
6910         !LHS->getType()->isPtrOrPtrVectorTy())
6911       return error(Loc, "icmp requires integer operands");
6912     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6913   }
6914   return false;
6915 }
6916 
6917 //===----------------------------------------------------------------------===//
6918 // Other Instructions.
6919 //===----------------------------------------------------------------------===//
6920 
6921 /// parseCast
6922 ///   ::= CastOpc TypeAndValue 'to' Type
parseCast(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc)6923 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
6924                          unsigned Opc) {
6925   LocTy Loc;
6926   Value *Op;
6927   Type *DestTy = nullptr;
6928   if (parseTypeAndValue(Op, Loc, PFS) ||
6929       parseToken(lltok::kw_to, "expected 'to' after cast value") ||
6930       parseType(DestTy))
6931     return true;
6932 
6933   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6934     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
6935     return error(Loc, "invalid cast opcode for cast from '" +
6936                           getTypeString(Op->getType()) + "' to '" +
6937                           getTypeString(DestTy) + "'");
6938   }
6939   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6940   return false;
6941 }
6942 
6943 /// parseSelect
6944 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
parseSelect(Instruction * & Inst,PerFunctionState & PFS)6945 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6946   LocTy Loc;
6947   Value *Op0, *Op1, *Op2;
6948   if (parseTypeAndValue(Op0, Loc, PFS) ||
6949       parseToken(lltok::comma, "expected ',' after select condition") ||
6950       parseTypeAndValue(Op1, PFS) ||
6951       parseToken(lltok::comma, "expected ',' after select value") ||
6952       parseTypeAndValue(Op2, PFS))
6953     return true;
6954 
6955   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6956     return error(Loc, Reason);
6957 
6958   Inst = SelectInst::Create(Op0, Op1, Op2);
6959   return false;
6960 }
6961 
6962 /// parseVAArg
6963 ///   ::= 'va_arg' TypeAndValue ',' Type
parseVAArg(Instruction * & Inst,PerFunctionState & PFS)6964 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
6965   Value *Op;
6966   Type *EltTy = nullptr;
6967   LocTy TypeLoc;
6968   if (parseTypeAndValue(Op, PFS) ||
6969       parseToken(lltok::comma, "expected ',' after vaarg operand") ||
6970       parseType(EltTy, TypeLoc))
6971     return true;
6972 
6973   if (!EltTy->isFirstClassType())
6974     return error(TypeLoc, "va_arg requires operand with first class type");
6975 
6976   Inst = new VAArgInst(Op, EltTy);
6977   return false;
6978 }
6979 
6980 /// parseExtractElement
6981 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
parseExtractElement(Instruction * & Inst,PerFunctionState & PFS)6982 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6983   LocTy Loc;
6984   Value *Op0, *Op1;
6985   if (parseTypeAndValue(Op0, Loc, PFS) ||
6986       parseToken(lltok::comma, "expected ',' after extract value") ||
6987       parseTypeAndValue(Op1, PFS))
6988     return true;
6989 
6990   if (!ExtractElementInst::isValidOperands(Op0, Op1))
6991     return error(Loc, "invalid extractelement operands");
6992 
6993   Inst = ExtractElementInst::Create(Op0, Op1);
6994   return false;
6995 }
6996 
6997 /// parseInsertElement
6998 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
parseInsertElement(Instruction * & Inst,PerFunctionState & PFS)6999 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
7000   LocTy Loc;
7001   Value *Op0, *Op1, *Op2;
7002   if (parseTypeAndValue(Op0, Loc, PFS) ||
7003       parseToken(lltok::comma, "expected ',' after insertelement value") ||
7004       parseTypeAndValue(Op1, PFS) ||
7005       parseToken(lltok::comma, "expected ',' after insertelement value") ||
7006       parseTypeAndValue(Op2, PFS))
7007     return true;
7008 
7009   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
7010     return error(Loc, "invalid insertelement operands");
7011 
7012   Inst = InsertElementInst::Create(Op0, Op1, Op2);
7013   return false;
7014 }
7015 
7016 /// parseShuffleVector
7017 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
parseShuffleVector(Instruction * & Inst,PerFunctionState & PFS)7018 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
7019   LocTy Loc;
7020   Value *Op0, *Op1, *Op2;
7021   if (parseTypeAndValue(Op0, Loc, PFS) ||
7022       parseToken(lltok::comma, "expected ',' after shuffle mask") ||
7023       parseTypeAndValue(Op1, PFS) ||
7024       parseToken(lltok::comma, "expected ',' after shuffle value") ||
7025       parseTypeAndValue(Op2, PFS))
7026     return true;
7027 
7028   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
7029     return error(Loc, "invalid shufflevector operands");
7030 
7031   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
7032   return false;
7033 }
7034 
7035 /// parsePHI
7036 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
parsePHI(Instruction * & Inst,PerFunctionState & PFS)7037 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
7038   Type *Ty = nullptr;  LocTy TypeLoc;
7039   Value *Op0, *Op1;
7040 
7041   if (parseType(Ty, TypeLoc) ||
7042       parseToken(lltok::lsquare, "expected '[' in phi value list") ||
7043       parseValue(Ty, Op0, PFS) ||
7044       parseToken(lltok::comma, "expected ',' after insertelement value") ||
7045       parseValue(Type::getLabelTy(Context), Op1, PFS) ||
7046       parseToken(lltok::rsquare, "expected ']' in phi value list"))
7047     return true;
7048 
7049   bool AteExtraComma = false;
7050   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
7051 
7052   while (true) {
7053     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
7054 
7055     if (!EatIfPresent(lltok::comma))
7056       break;
7057 
7058     if (Lex.getKind() == lltok::MetadataVar) {
7059       AteExtraComma = true;
7060       break;
7061     }
7062 
7063     if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
7064         parseValue(Ty, Op0, PFS) ||
7065         parseToken(lltok::comma, "expected ',' after insertelement value") ||
7066         parseValue(Type::getLabelTy(Context), Op1, PFS) ||
7067         parseToken(lltok::rsquare, "expected ']' in phi value list"))
7068       return true;
7069   }
7070 
7071   if (!Ty->isFirstClassType())
7072     return error(TypeLoc, "phi node must have first class type");
7073 
7074   PHINode *PN = PHINode::Create(Ty, PHIVals.size());
7075   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
7076     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
7077   Inst = PN;
7078   return AteExtraComma ? InstExtraComma : InstNormal;
7079 }
7080 
7081 /// parseLandingPad
7082 ///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
7083 /// Clause
7084 ///   ::= 'catch' TypeAndValue
7085 ///   ::= 'filter'
7086 ///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
parseLandingPad(Instruction * & Inst,PerFunctionState & PFS)7087 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
7088   Type *Ty = nullptr; LocTy TyLoc;
7089 
7090   if (parseType(Ty, TyLoc))
7091     return true;
7092 
7093   std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
7094   LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
7095 
7096   while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
7097     LandingPadInst::ClauseType CT;
7098     if (EatIfPresent(lltok::kw_catch))
7099       CT = LandingPadInst::Catch;
7100     else if (EatIfPresent(lltok::kw_filter))
7101       CT = LandingPadInst::Filter;
7102     else
7103       return tokError("expected 'catch' or 'filter' clause type");
7104 
7105     Value *V;
7106     LocTy VLoc;
7107     if (parseTypeAndValue(V, VLoc, PFS))
7108       return true;
7109 
7110     // A 'catch' type expects a non-array constant. A filter clause expects an
7111     // array constant.
7112     if (CT == LandingPadInst::Catch) {
7113       if (isa<ArrayType>(V->getType()))
7114         error(VLoc, "'catch' clause has an invalid type");
7115     } else {
7116       if (!isa<ArrayType>(V->getType()))
7117         error(VLoc, "'filter' clause has an invalid type");
7118     }
7119 
7120     Constant *CV = dyn_cast<Constant>(V);
7121     if (!CV)
7122       return error(VLoc, "clause argument must be a constant");
7123     LP->addClause(CV);
7124   }
7125 
7126   Inst = LP.release();
7127   return false;
7128 }
7129 
7130 /// parseFreeze
7131 ///   ::= 'freeze' Type Value
parseFreeze(Instruction * & Inst,PerFunctionState & PFS)7132 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
7133   LocTy Loc;
7134   Value *Op;
7135   if (parseTypeAndValue(Op, Loc, PFS))
7136     return true;
7137 
7138   Inst = new FreezeInst(Op);
7139   return false;
7140 }
7141 
7142 /// parseCall
7143 ///   ::= 'call' OptionalFastMathFlags OptionalCallingConv
7144 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7145 ///   ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
7146 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7147 ///   ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
7148 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7149 ///   ::= 'notail' 'call'  OptionalFastMathFlags OptionalCallingConv
7150 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
parseCall(Instruction * & Inst,PerFunctionState & PFS,CallInst::TailCallKind TCK)7151 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
7152                          CallInst::TailCallKind TCK) {
7153   AttrBuilder RetAttrs, FnAttrs;
7154   std::vector<unsigned> FwdRefAttrGrps;
7155   LocTy BuiltinLoc;
7156   unsigned CallAddrSpace;
7157   unsigned CC;
7158   Type *RetType = nullptr;
7159   LocTy RetTypeLoc;
7160   ValID CalleeID;
7161   SmallVector<ParamInfo, 16> ArgList;
7162   SmallVector<OperandBundleDef, 2> BundleList;
7163   LocTy CallLoc = Lex.getLoc();
7164 
7165   if (TCK != CallInst::TCK_None &&
7166       parseToken(lltok::kw_call,
7167                  "expected 'tail call', 'musttail call', or 'notail call'"))
7168     return true;
7169 
7170   FastMathFlags FMF = EatFastMathFlagsIfPresent();
7171 
7172   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7173       parseOptionalProgramAddrSpace(CallAddrSpace) ||
7174       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7175       parseValID(CalleeID) ||
7176       parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
7177                          PFS.getFunction().isVarArg()) ||
7178       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
7179       parseOptionalOperandBundles(BundleList, PFS))
7180     return true;
7181 
7182   // If RetType is a non-function pointer type, then this is the short syntax
7183   // for the call, which means that RetType is just the return type.  Infer the
7184   // rest of the function argument types from the arguments that are present.
7185   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
7186   if (!Ty) {
7187     // Pull out the types of all of the arguments...
7188     std::vector<Type*> ParamTypes;
7189     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
7190       ParamTypes.push_back(ArgList[i].V->getType());
7191 
7192     if (!FunctionType::isValidReturnType(RetType))
7193       return error(RetTypeLoc, "Invalid result type for LLVM function");
7194 
7195     Ty = FunctionType::get(RetType, ParamTypes, false);
7196   }
7197 
7198   CalleeID.FTy = Ty;
7199 
7200   // Look up the callee.
7201   Value *Callee;
7202   if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
7203                           &PFS, /*IsCall=*/true))
7204     return true;
7205 
7206   // Set up the Attribute for the function.
7207   SmallVector<AttributeSet, 8> Attrs;
7208 
7209   SmallVector<Value*, 8> Args;
7210 
7211   // Loop through FunctionType's arguments and ensure they are specified
7212   // correctly.  Also, gather any parameter attributes.
7213   FunctionType::param_iterator I = Ty->param_begin();
7214   FunctionType::param_iterator E = Ty->param_end();
7215   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7216     Type *ExpectedTy = nullptr;
7217     if (I != E) {
7218       ExpectedTy = *I++;
7219     } else if (!Ty->isVarArg()) {
7220       return error(ArgList[i].Loc, "too many arguments specified");
7221     }
7222 
7223     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7224       return error(ArgList[i].Loc, "argument is not of expected type '" +
7225                                        getTypeString(ExpectedTy) + "'");
7226     Args.push_back(ArgList[i].V);
7227     Attrs.push_back(ArgList[i].Attrs);
7228   }
7229 
7230   if (I != E)
7231     return error(CallLoc, "not enough parameters specified for call");
7232 
7233   if (FnAttrs.hasAlignmentAttr())
7234     return error(CallLoc, "call instructions may not have an alignment");
7235 
7236   // Finish off the Attribute and check them
7237   AttributeList PAL =
7238       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7239                          AttributeSet::get(Context, RetAttrs), Attrs);
7240 
7241   CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
7242   CI->setTailCallKind(TCK);
7243   CI->setCallingConv(CC);
7244   if (FMF.any()) {
7245     if (!isa<FPMathOperator>(CI)) {
7246       CI->deleteValue();
7247       return error(CallLoc, "fast-math-flags specified for call without "
7248                             "floating-point scalar or vector return type");
7249     }
7250     CI->setFastMathFlags(FMF);
7251   }
7252   CI->setAttributes(PAL);
7253   ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
7254   Inst = CI;
7255   return false;
7256 }
7257 
7258 //===----------------------------------------------------------------------===//
7259 // Memory Instructions.
7260 //===----------------------------------------------------------------------===//
7261 
7262 /// parseAlloc
7263 ///   ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
7264 ///       (',' 'align' i32)? (',', 'addrspace(n))?
parseAlloc(Instruction * & Inst,PerFunctionState & PFS)7265 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
7266   Value *Size = nullptr;
7267   LocTy SizeLoc, TyLoc, ASLoc;
7268   MaybeAlign Alignment;
7269   unsigned AddrSpace = 0;
7270   Type *Ty = nullptr;
7271 
7272   bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
7273   bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
7274 
7275   if (parseType(Ty, TyLoc))
7276     return true;
7277 
7278   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
7279     return error(TyLoc, "invalid type for alloca");
7280 
7281   bool AteExtraComma = false;
7282   if (EatIfPresent(lltok::comma)) {
7283     if (Lex.getKind() == lltok::kw_align) {
7284       if (parseOptionalAlignment(Alignment))
7285         return true;
7286       if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7287         return true;
7288     } else if (Lex.getKind() == lltok::kw_addrspace) {
7289       ASLoc = Lex.getLoc();
7290       if (parseOptionalAddrSpace(AddrSpace))
7291         return true;
7292     } else if (Lex.getKind() == lltok::MetadataVar) {
7293       AteExtraComma = true;
7294     } else {
7295       if (parseTypeAndValue(Size, SizeLoc, PFS))
7296         return true;
7297       if (EatIfPresent(lltok::comma)) {
7298         if (Lex.getKind() == lltok::kw_align) {
7299           if (parseOptionalAlignment(Alignment))
7300             return true;
7301           if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7302             return true;
7303         } else if (Lex.getKind() == lltok::kw_addrspace) {
7304           ASLoc = Lex.getLoc();
7305           if (parseOptionalAddrSpace(AddrSpace))
7306             return true;
7307         } else if (Lex.getKind() == lltok::MetadataVar) {
7308           AteExtraComma = true;
7309         }
7310       }
7311     }
7312   }
7313 
7314   if (Size && !Size->getType()->isIntegerTy())
7315     return error(SizeLoc, "element count must have integer type");
7316 
7317   SmallPtrSet<Type *, 4> Visited;
7318   if (!Alignment && !Ty->isSized(&Visited))
7319     return error(TyLoc, "Cannot allocate unsized type");
7320   if (!Alignment)
7321     Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
7322   AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
7323   AI->setUsedWithInAlloca(IsInAlloca);
7324   AI->setSwiftError(IsSwiftError);
7325   Inst = AI;
7326   return AteExtraComma ? InstExtraComma : InstNormal;
7327 }
7328 
7329 /// parseLoad
7330 ///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
7331 ///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
7332 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
parseLoad(Instruction * & Inst,PerFunctionState & PFS)7333 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
7334   Value *Val; LocTy Loc;
7335   MaybeAlign Alignment;
7336   bool AteExtraComma = false;
7337   bool isAtomic = false;
7338   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7339   SyncScope::ID SSID = SyncScope::System;
7340 
7341   if (Lex.getKind() == lltok::kw_atomic) {
7342     isAtomic = true;
7343     Lex.Lex();
7344   }
7345 
7346   bool isVolatile = false;
7347   if (Lex.getKind() == lltok::kw_volatile) {
7348     isVolatile = true;
7349     Lex.Lex();
7350   }
7351 
7352   Type *Ty;
7353   LocTy ExplicitTypeLoc = Lex.getLoc();
7354   if (parseType(Ty) ||
7355       parseToken(lltok::comma, "expected comma after load's type") ||
7356       parseTypeAndValue(Val, Loc, PFS) ||
7357       parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7358       parseOptionalCommaAlign(Alignment, AteExtraComma))
7359     return true;
7360 
7361   if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
7362     return error(Loc, "load operand must be a pointer to a first class type");
7363   if (isAtomic && !Alignment)
7364     return error(Loc, "atomic load must have explicit non-zero alignment");
7365   if (Ordering == AtomicOrdering::Release ||
7366       Ordering == AtomicOrdering::AcquireRelease)
7367     return error(Loc, "atomic load cannot use Release ordering");
7368 
7369   if (Ty != cast<PointerType>(Val->getType())->getElementType())
7370     return error(ExplicitTypeLoc,
7371                  "explicit pointee type doesn't match operand's pointee type");
7372   SmallPtrSet<Type *, 4> Visited;
7373   if (!Alignment && !Ty->isSized(&Visited))
7374     return error(ExplicitTypeLoc, "loading unsized types is not allowed");
7375   if (!Alignment)
7376     Alignment = M->getDataLayout().getABITypeAlign(Ty);
7377   Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
7378   return AteExtraComma ? InstExtraComma : InstNormal;
7379 }
7380 
7381 /// parseStore
7382 
7383 ///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
7384 ///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
7385 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
parseStore(Instruction * & Inst,PerFunctionState & PFS)7386 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
7387   Value *Val, *Ptr; LocTy Loc, PtrLoc;
7388   MaybeAlign Alignment;
7389   bool AteExtraComma = false;
7390   bool isAtomic = false;
7391   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7392   SyncScope::ID SSID = SyncScope::System;
7393 
7394   if (Lex.getKind() == lltok::kw_atomic) {
7395     isAtomic = true;
7396     Lex.Lex();
7397   }
7398 
7399   bool isVolatile = false;
7400   if (Lex.getKind() == lltok::kw_volatile) {
7401     isVolatile = true;
7402     Lex.Lex();
7403   }
7404 
7405   if (parseTypeAndValue(Val, Loc, PFS) ||
7406       parseToken(lltok::comma, "expected ',' after store operand") ||
7407       parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7408       parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7409       parseOptionalCommaAlign(Alignment, AteExtraComma))
7410     return true;
7411 
7412   if (!Ptr->getType()->isPointerTy())
7413     return error(PtrLoc, "store operand must be a pointer");
7414   if (!Val->getType()->isFirstClassType())
7415     return error(Loc, "store operand must be a first class value");
7416   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
7417     return error(Loc, "stored value and pointer type do not match");
7418   if (isAtomic && !Alignment)
7419     return error(Loc, "atomic store must have explicit non-zero alignment");
7420   if (Ordering == AtomicOrdering::Acquire ||
7421       Ordering == AtomicOrdering::AcquireRelease)
7422     return error(Loc, "atomic store cannot use Acquire ordering");
7423   SmallPtrSet<Type *, 4> Visited;
7424   if (!Alignment && !Val->getType()->isSized(&Visited))
7425     return error(Loc, "storing unsized types is not allowed");
7426   if (!Alignment)
7427     Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
7428 
7429   Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
7430   return AteExtraComma ? InstExtraComma : InstNormal;
7431 }
7432 
7433 /// parseCmpXchg
7434 ///   ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7435 ///       TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
parseCmpXchg(Instruction * & Inst,PerFunctionState & PFS)7436 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
7437   Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
7438   bool AteExtraComma = false;
7439   AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
7440   AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
7441   SyncScope::ID SSID = SyncScope::System;
7442   bool isVolatile = false;
7443   bool isWeak = false;
7444 
7445   if (EatIfPresent(lltok::kw_weak))
7446     isWeak = true;
7447 
7448   if (EatIfPresent(lltok::kw_volatile))
7449     isVolatile = true;
7450 
7451   if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7452       parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
7453       parseTypeAndValue(Cmp, CmpLoc, PFS) ||
7454       parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
7455       parseTypeAndValue(New, NewLoc, PFS) ||
7456       parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
7457       parseOrdering(FailureOrdering))
7458     return true;
7459 
7460   if (SuccessOrdering == AtomicOrdering::Unordered ||
7461       FailureOrdering == AtomicOrdering::Unordered)
7462     return tokError("cmpxchg cannot be unordered");
7463   if (isStrongerThan(FailureOrdering, SuccessOrdering))
7464     return tokError("cmpxchg failure argument shall be no stronger than the "
7465                     "success argument");
7466   if (FailureOrdering == AtomicOrdering::Release ||
7467       FailureOrdering == AtomicOrdering::AcquireRelease)
7468     return tokError(
7469         "cmpxchg failure ordering cannot include release semantics");
7470   if (!Ptr->getType()->isPointerTy())
7471     return error(PtrLoc, "cmpxchg operand must be a pointer");
7472   if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
7473     return error(CmpLoc, "compare value and pointer type do not match");
7474   if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
7475     return error(NewLoc, "new value and pointer type do not match");
7476   if (!New->getType()->isFirstClassType())
7477     return error(NewLoc, "cmpxchg operand must be a first class value");
7478 
7479   Align Alignment(
7480       PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7481           Cmp->getType()));
7482 
7483   AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
7484       Ptr, Cmp, New, Alignment, SuccessOrdering, FailureOrdering, SSID);
7485   CXI->setVolatile(isVolatile);
7486   CXI->setWeak(isWeak);
7487   Inst = CXI;
7488   return AteExtraComma ? InstExtraComma : InstNormal;
7489 }
7490 
7491 /// parseAtomicRMW
7492 ///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7493 ///       'singlethread'? AtomicOrdering
parseAtomicRMW(Instruction * & Inst,PerFunctionState & PFS)7494 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
7495   Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
7496   bool AteExtraComma = false;
7497   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7498   SyncScope::ID SSID = SyncScope::System;
7499   bool isVolatile = false;
7500   bool IsFP = false;
7501   AtomicRMWInst::BinOp Operation;
7502 
7503   if (EatIfPresent(lltok::kw_volatile))
7504     isVolatile = true;
7505 
7506   switch (Lex.getKind()) {
7507   default:
7508     return tokError("expected binary operation in atomicrmw");
7509   case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
7510   case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
7511   case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
7512   case lltok::kw_and: Operation = AtomicRMWInst::And; break;
7513   case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
7514   case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
7515   case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
7516   case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
7517   case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
7518   case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
7519   case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
7520   case lltok::kw_fadd:
7521     Operation = AtomicRMWInst::FAdd;
7522     IsFP = true;
7523     break;
7524   case lltok::kw_fsub:
7525     Operation = AtomicRMWInst::FSub;
7526     IsFP = true;
7527     break;
7528   }
7529   Lex.Lex();  // Eat the operation.
7530 
7531   if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7532       parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
7533       parseTypeAndValue(Val, ValLoc, PFS) ||
7534       parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7535     return true;
7536 
7537   if (Ordering == AtomicOrdering::Unordered)
7538     return tokError("atomicrmw cannot be unordered");
7539   if (!Ptr->getType()->isPointerTy())
7540     return error(PtrLoc, "atomicrmw operand must be a pointer");
7541   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
7542     return error(ValLoc, "atomicrmw value and pointer type do not match");
7543 
7544   if (Operation == AtomicRMWInst::Xchg) {
7545     if (!Val->getType()->isIntegerTy() &&
7546         !Val->getType()->isFloatingPointTy()) {
7547       return error(ValLoc,
7548                    "atomicrmw " + AtomicRMWInst::getOperationName(Operation) +
7549                        " operand must be an integer or floating point type");
7550     }
7551   } else if (IsFP) {
7552     if (!Val->getType()->isFloatingPointTy()) {
7553       return error(ValLoc, "atomicrmw " +
7554                                AtomicRMWInst::getOperationName(Operation) +
7555                                " operand must be a floating point type");
7556     }
7557   } else {
7558     if (!Val->getType()->isIntegerTy()) {
7559       return error(ValLoc, "atomicrmw " +
7560                                AtomicRMWInst::getOperationName(Operation) +
7561                                " operand must be an integer");
7562     }
7563   }
7564 
7565   unsigned Size = Val->getType()->getPrimitiveSizeInBits();
7566   if (Size < 8 || (Size & (Size - 1)))
7567     return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
7568                          " integer");
7569   Align Alignment(
7570       PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7571           Val->getType()));
7572   AtomicRMWInst *RMWI =
7573       new AtomicRMWInst(Operation, Ptr, Val, Alignment, Ordering, SSID);
7574   RMWI->setVolatile(isVolatile);
7575   Inst = RMWI;
7576   return AteExtraComma ? InstExtraComma : InstNormal;
7577 }
7578 
7579 /// parseFence
7580 ///   ::= 'fence' 'singlethread'? AtomicOrdering
parseFence(Instruction * & Inst,PerFunctionState & PFS)7581 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
7582   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7583   SyncScope::ID SSID = SyncScope::System;
7584   if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7585     return true;
7586 
7587   if (Ordering == AtomicOrdering::Unordered)
7588     return tokError("fence cannot be unordered");
7589   if (Ordering == AtomicOrdering::Monotonic)
7590     return tokError("fence cannot be monotonic");
7591 
7592   Inst = new FenceInst(Context, Ordering, SSID);
7593   return InstNormal;
7594 }
7595 
7596 /// parseGetElementPtr
7597 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
parseGetElementPtr(Instruction * & Inst,PerFunctionState & PFS)7598 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
7599   Value *Ptr = nullptr;
7600   Value *Val = nullptr;
7601   LocTy Loc, EltLoc;
7602 
7603   bool InBounds = EatIfPresent(lltok::kw_inbounds);
7604 
7605   Type *Ty = nullptr;
7606   LocTy ExplicitTypeLoc = Lex.getLoc();
7607   if (parseType(Ty) ||
7608       parseToken(lltok::comma, "expected comma after getelementptr's type") ||
7609       parseTypeAndValue(Ptr, Loc, PFS))
7610     return true;
7611 
7612   Type *BaseType = Ptr->getType();
7613   PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
7614   if (!BasePointerType)
7615     return error(Loc, "base of getelementptr must be a pointer");
7616 
7617   if (Ty != BasePointerType->getElementType())
7618     return error(ExplicitTypeLoc,
7619                  "explicit pointee type doesn't match operand's pointee type");
7620 
7621   SmallVector<Value*, 16> Indices;
7622   bool AteExtraComma = false;
7623   // GEP returns a vector of pointers if at least one of parameters is a vector.
7624   // All vector parameters should have the same vector width.
7625   ElementCount GEPWidth = BaseType->isVectorTy()
7626                               ? cast<VectorType>(BaseType)->getElementCount()
7627                               : ElementCount::getFixed(0);
7628 
7629   while (EatIfPresent(lltok::comma)) {
7630     if (Lex.getKind() == lltok::MetadataVar) {
7631       AteExtraComma = true;
7632       break;
7633     }
7634     if (parseTypeAndValue(Val, EltLoc, PFS))
7635       return true;
7636     if (!Val->getType()->isIntOrIntVectorTy())
7637       return error(EltLoc, "getelementptr index must be an integer");
7638 
7639     if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
7640       ElementCount ValNumEl = ValVTy->getElementCount();
7641       if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
7642         return error(
7643             EltLoc,
7644             "getelementptr vector index has a wrong number of elements");
7645       GEPWidth = ValNumEl;
7646     }
7647     Indices.push_back(Val);
7648   }
7649 
7650   SmallPtrSet<Type*, 4> Visited;
7651   if (!Indices.empty() && !Ty->isSized(&Visited))
7652     return error(Loc, "base element of getelementptr must be sized");
7653 
7654   if (!GetElementPtrInst::getIndexedType(Ty, Indices))
7655     return error(Loc, "invalid getelementptr indices");
7656   Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
7657   if (InBounds)
7658     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
7659   return AteExtraComma ? InstExtraComma : InstNormal;
7660 }
7661 
7662 /// parseExtractValue
7663 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
parseExtractValue(Instruction * & Inst,PerFunctionState & PFS)7664 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
7665   Value *Val; LocTy Loc;
7666   SmallVector<unsigned, 4> Indices;
7667   bool AteExtraComma;
7668   if (parseTypeAndValue(Val, Loc, PFS) ||
7669       parseIndexList(Indices, AteExtraComma))
7670     return true;
7671 
7672   if (!Val->getType()->isAggregateType())
7673     return error(Loc, "extractvalue operand must be aggregate type");
7674 
7675   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
7676     return error(Loc, "invalid indices for extractvalue");
7677   Inst = ExtractValueInst::Create(Val, Indices);
7678   return AteExtraComma ? InstExtraComma : InstNormal;
7679 }
7680 
7681 /// parseInsertValue
7682 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
parseInsertValue(Instruction * & Inst,PerFunctionState & PFS)7683 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
7684   Value *Val0, *Val1; LocTy Loc0, Loc1;
7685   SmallVector<unsigned, 4> Indices;
7686   bool AteExtraComma;
7687   if (parseTypeAndValue(Val0, Loc0, PFS) ||
7688       parseToken(lltok::comma, "expected comma after insertvalue operand") ||
7689       parseTypeAndValue(Val1, Loc1, PFS) ||
7690       parseIndexList(Indices, AteExtraComma))
7691     return true;
7692 
7693   if (!Val0->getType()->isAggregateType())
7694     return error(Loc0, "insertvalue operand must be aggregate type");
7695 
7696   Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
7697   if (!IndexedType)
7698     return error(Loc0, "invalid indices for insertvalue");
7699   if (IndexedType != Val1->getType())
7700     return error(Loc1, "insertvalue operand and field disagree in type: '" +
7701                            getTypeString(Val1->getType()) + "' instead of '" +
7702                            getTypeString(IndexedType) + "'");
7703   Inst = InsertValueInst::Create(Val0, Val1, Indices);
7704   return AteExtraComma ? InstExtraComma : InstNormal;
7705 }
7706 
7707 //===----------------------------------------------------------------------===//
7708 // Embedded metadata.
7709 //===----------------------------------------------------------------------===//
7710 
7711 /// parseMDNodeVector
7712 ///   ::= { Element (',' Element)* }
7713 /// Element
7714 ///   ::= 'null' | TypeAndValue
parseMDNodeVector(SmallVectorImpl<Metadata * > & Elts)7715 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
7716   if (parseToken(lltok::lbrace, "expected '{' here"))
7717     return true;
7718 
7719   // Check for an empty list.
7720   if (EatIfPresent(lltok::rbrace))
7721     return false;
7722 
7723   do {
7724     // Null is a special case since it is typeless.
7725     if (EatIfPresent(lltok::kw_null)) {
7726       Elts.push_back(nullptr);
7727       continue;
7728     }
7729 
7730     Metadata *MD;
7731     if (parseMetadata(MD, nullptr))
7732       return true;
7733     Elts.push_back(MD);
7734   } while (EatIfPresent(lltok::comma));
7735 
7736   return parseToken(lltok::rbrace, "expected end of metadata node");
7737 }
7738 
7739 //===----------------------------------------------------------------------===//
7740 // Use-list order directives.
7741 //===----------------------------------------------------------------------===//
sortUseListOrder(Value * V,ArrayRef<unsigned> Indexes,SMLoc Loc)7742 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7743                                 SMLoc Loc) {
7744   if (V->use_empty())
7745     return error(Loc, "value has no uses");
7746 
7747   unsigned NumUses = 0;
7748   SmallDenseMap<const Use *, unsigned, 16> Order;
7749   for (const Use &U : V->uses()) {
7750     if (++NumUses > Indexes.size())
7751       break;
7752     Order[&U] = Indexes[NumUses - 1];
7753   }
7754   if (NumUses < 2)
7755     return error(Loc, "value only has one use");
7756   if (Order.size() != Indexes.size() || NumUses > Indexes.size())
7757     return error(Loc,
7758                  "wrong number of indexes, expected " + Twine(V->getNumUses()));
7759 
7760   V->sortUseList([&](const Use &L, const Use &R) {
7761     return Order.lookup(&L) < Order.lookup(&R);
7762   });
7763   return false;
7764 }
7765 
7766 /// parseUseListOrderIndexes
7767 ///   ::= '{' uint32 (',' uint32)+ '}'
parseUseListOrderIndexes(SmallVectorImpl<unsigned> & Indexes)7768 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7769   SMLoc Loc = Lex.getLoc();
7770   if (parseToken(lltok::lbrace, "expected '{' here"))
7771     return true;
7772   if (Lex.getKind() == lltok::rbrace)
7773     return Lex.Error("expected non-empty list of uselistorder indexes");
7774 
7775   // Use Offset, Max, and IsOrdered to check consistency of indexes.  The
7776   // indexes should be distinct numbers in the range [0, size-1], and should
7777   // not be in order.
7778   unsigned Offset = 0;
7779   unsigned Max = 0;
7780   bool IsOrdered = true;
7781   assert(Indexes.empty() && "Expected empty order vector");
7782   do {
7783     unsigned Index;
7784     if (parseUInt32(Index))
7785       return true;
7786 
7787     // Update consistency checks.
7788     Offset += Index - Indexes.size();
7789     Max = std::max(Max, Index);
7790     IsOrdered &= Index == Indexes.size();
7791 
7792     Indexes.push_back(Index);
7793   } while (EatIfPresent(lltok::comma));
7794 
7795   if (parseToken(lltok::rbrace, "expected '}' here"))
7796     return true;
7797 
7798   if (Indexes.size() < 2)
7799     return error(Loc, "expected >= 2 uselistorder indexes");
7800   if (Offset != 0 || Max >= Indexes.size())
7801     return error(Loc,
7802                  "expected distinct uselistorder indexes in range [0, size)");
7803   if (IsOrdered)
7804     return error(Loc, "expected uselistorder indexes to change the order");
7805 
7806   return false;
7807 }
7808 
7809 /// parseUseListOrder
7810 ///   ::= 'uselistorder' Type Value ',' UseListOrderIndexes
parseUseListOrder(PerFunctionState * PFS)7811 bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
7812   SMLoc Loc = Lex.getLoc();
7813   if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7814     return true;
7815 
7816   Value *V;
7817   SmallVector<unsigned, 16> Indexes;
7818   if (parseTypeAndValue(V, PFS) ||
7819       parseToken(lltok::comma, "expected comma in uselistorder directive") ||
7820       parseUseListOrderIndexes(Indexes))
7821     return true;
7822 
7823   return sortUseListOrder(V, Indexes, Loc);
7824 }
7825 
7826 /// parseUseListOrderBB
7827 ///   ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
parseUseListOrderBB()7828 bool LLParser::parseUseListOrderBB() {
7829   assert(Lex.getKind() == lltok::kw_uselistorder_bb);
7830   SMLoc Loc = Lex.getLoc();
7831   Lex.Lex();
7832 
7833   ValID Fn, Label;
7834   SmallVector<unsigned, 16> Indexes;
7835   if (parseValID(Fn) ||
7836       parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7837       parseValID(Label) ||
7838       parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7839       parseUseListOrderIndexes(Indexes))
7840     return true;
7841 
7842   // Check the function.
7843   GlobalValue *GV;
7844   if (Fn.Kind == ValID::t_GlobalName)
7845     GV = M->getNamedValue(Fn.StrVal);
7846   else if (Fn.Kind == ValID::t_GlobalID)
7847     GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7848   else
7849     return error(Fn.Loc, "expected function name in uselistorder_bb");
7850   if (!GV)
7851     return error(Fn.Loc,
7852                  "invalid function forward reference in uselistorder_bb");
7853   auto *F = dyn_cast<Function>(GV);
7854   if (!F)
7855     return error(Fn.Loc, "expected function name in uselistorder_bb");
7856   if (F->isDeclaration())
7857     return error(Fn.Loc, "invalid declaration in uselistorder_bb");
7858 
7859   // Check the basic block.
7860   if (Label.Kind == ValID::t_LocalID)
7861     return error(Label.Loc, "invalid numeric label in uselistorder_bb");
7862   if (Label.Kind != ValID::t_LocalName)
7863     return error(Label.Loc, "expected basic block name in uselistorder_bb");
7864   Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
7865   if (!V)
7866     return error(Label.Loc, "invalid basic block in uselistorder_bb");
7867   if (!isa<BasicBlock>(V))
7868     return error(Label.Loc, "expected basic block in uselistorder_bb");
7869 
7870   return sortUseListOrder(V, Indexes, Loc);
7871 }
7872 
7873 /// ModuleEntry
7874 ///   ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7875 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
parseModuleEntry(unsigned ID)7876 bool LLParser::parseModuleEntry(unsigned ID) {
7877   assert(Lex.getKind() == lltok::kw_module);
7878   Lex.Lex();
7879 
7880   std::string Path;
7881   if (parseToken(lltok::colon, "expected ':' here") ||
7882       parseToken(lltok::lparen, "expected '(' here") ||
7883       parseToken(lltok::kw_path, "expected 'path' here") ||
7884       parseToken(lltok::colon, "expected ':' here") ||
7885       parseStringConstant(Path) ||
7886       parseToken(lltok::comma, "expected ',' here") ||
7887       parseToken(lltok::kw_hash, "expected 'hash' here") ||
7888       parseToken(lltok::colon, "expected ':' here") ||
7889       parseToken(lltok::lparen, "expected '(' here"))
7890     return true;
7891 
7892   ModuleHash Hash;
7893   if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
7894       parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
7895       parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
7896       parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
7897       parseUInt32(Hash[4]))
7898     return true;
7899 
7900   if (parseToken(lltok::rparen, "expected ')' here") ||
7901       parseToken(lltok::rparen, "expected ')' here"))
7902     return true;
7903 
7904   auto ModuleEntry = Index->addModule(Path, ID, Hash);
7905   ModuleIdMap[ID] = ModuleEntry->first();
7906 
7907   return false;
7908 }
7909 
7910 /// TypeIdEntry
7911 ///   ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
parseTypeIdEntry(unsigned ID)7912 bool LLParser::parseTypeIdEntry(unsigned ID) {
7913   assert(Lex.getKind() == lltok::kw_typeid);
7914   Lex.Lex();
7915 
7916   std::string Name;
7917   if (parseToken(lltok::colon, "expected ':' here") ||
7918       parseToken(lltok::lparen, "expected '(' here") ||
7919       parseToken(lltok::kw_name, "expected 'name' here") ||
7920       parseToken(lltok::colon, "expected ':' here") ||
7921       parseStringConstant(Name))
7922     return true;
7923 
7924   TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7925   if (parseToken(lltok::comma, "expected ',' here") ||
7926       parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
7927     return true;
7928 
7929   // Check if this ID was forward referenced, and if so, update the
7930   // corresponding GUIDs.
7931   auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7932   if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7933     for (auto TIDRef : FwdRefTIDs->second) {
7934       assert(!*TIDRef.first &&
7935              "Forward referenced type id GUID expected to be 0");
7936       *TIDRef.first = GlobalValue::getGUID(Name);
7937     }
7938     ForwardRefTypeIds.erase(FwdRefTIDs);
7939   }
7940 
7941   return false;
7942 }
7943 
7944 /// TypeIdSummary
7945 ///   ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
parseTypeIdSummary(TypeIdSummary & TIS)7946 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
7947   if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
7948       parseToken(lltok::colon, "expected ':' here") ||
7949       parseToken(lltok::lparen, "expected '(' here") ||
7950       parseTypeTestResolution(TIS.TTRes))
7951     return true;
7952 
7953   if (EatIfPresent(lltok::comma)) {
7954     // Expect optional wpdResolutions field
7955     if (parseOptionalWpdResolutions(TIS.WPDRes))
7956       return true;
7957   }
7958 
7959   if (parseToken(lltok::rparen, "expected ')' here"))
7960     return true;
7961 
7962   return false;
7963 }
7964 
7965 static ValueInfo EmptyVI =
7966     ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
7967 
7968 /// TypeIdCompatibleVtableEntry
7969 ///   ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
7970 ///   TypeIdCompatibleVtableInfo
7971 ///   ')'
parseTypeIdCompatibleVtableEntry(unsigned ID)7972 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
7973   assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);
7974   Lex.Lex();
7975 
7976   std::string Name;
7977   if (parseToken(lltok::colon, "expected ':' here") ||
7978       parseToken(lltok::lparen, "expected '(' here") ||
7979       parseToken(lltok::kw_name, "expected 'name' here") ||
7980       parseToken(lltok::colon, "expected ':' here") ||
7981       parseStringConstant(Name))
7982     return true;
7983 
7984   TypeIdCompatibleVtableInfo &TI =
7985       Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
7986   if (parseToken(lltok::comma, "expected ',' here") ||
7987       parseToken(lltok::kw_summary, "expected 'summary' here") ||
7988       parseToken(lltok::colon, "expected ':' here") ||
7989       parseToken(lltok::lparen, "expected '(' here"))
7990     return true;
7991 
7992   IdToIndexMapType IdToIndexMap;
7993   // parse each call edge
7994   do {
7995     uint64_t Offset;
7996     if (parseToken(lltok::lparen, "expected '(' here") ||
7997         parseToken(lltok::kw_offset, "expected 'offset' here") ||
7998         parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
7999         parseToken(lltok::comma, "expected ',' here"))
8000       return true;
8001 
8002     LocTy Loc = Lex.getLoc();
8003     unsigned GVId;
8004     ValueInfo VI;
8005     if (parseGVReference(VI, GVId))
8006       return true;
8007 
8008     // Keep track of the TypeIdCompatibleVtableInfo array index needing a
8009     // forward reference. We will save the location of the ValueInfo needing an
8010     // update, but can only do so once the std::vector is finalized.
8011     if (VI == EmptyVI)
8012       IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8013     TI.push_back({Offset, VI});
8014 
8015     if (parseToken(lltok::rparen, "expected ')' in call"))
8016       return true;
8017   } while (EatIfPresent(lltok::comma));
8018 
8019   // Now that the TI vector is finalized, it is safe to save the locations
8020   // of any forward GV references that need updating later.
8021   for (auto I : IdToIndexMap) {
8022     auto &Infos = ForwardRefValueInfos[I.first];
8023     for (auto P : I.second) {
8024       assert(TI[P.first].VTableVI == EmptyVI &&
8025              "Forward referenced ValueInfo expected to be empty");
8026       Infos.emplace_back(&TI[P.first].VTableVI, P.second);
8027     }
8028   }
8029 
8030   if (parseToken(lltok::rparen, "expected ')' here") ||
8031       parseToken(lltok::rparen, "expected ')' here"))
8032     return true;
8033 
8034   // Check if this ID was forward referenced, and if so, update the
8035   // corresponding GUIDs.
8036   auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8037   if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8038     for (auto TIDRef : FwdRefTIDs->second) {
8039       assert(!*TIDRef.first &&
8040              "Forward referenced type id GUID expected to be 0");
8041       *TIDRef.first = GlobalValue::getGUID(Name);
8042     }
8043     ForwardRefTypeIds.erase(FwdRefTIDs);
8044   }
8045 
8046   return false;
8047 }
8048 
8049 /// TypeTestResolution
8050 ///   ::= 'typeTestRes' ':' '(' 'kind' ':'
8051 ///         ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
8052 ///         'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
8053 ///         [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
8054 ///         [',' 'inlinesBits' ':' UInt64]? ')'
parseTypeTestResolution(TypeTestResolution & TTRes)8055 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
8056   if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
8057       parseToken(lltok::colon, "expected ':' here") ||
8058       parseToken(lltok::lparen, "expected '(' here") ||
8059       parseToken(lltok::kw_kind, "expected 'kind' here") ||
8060       parseToken(lltok::colon, "expected ':' here"))
8061     return true;
8062 
8063   switch (Lex.getKind()) {
8064   case lltok::kw_unknown:
8065     TTRes.TheKind = TypeTestResolution::Unknown;
8066     break;
8067   case lltok::kw_unsat:
8068     TTRes.TheKind = TypeTestResolution::Unsat;
8069     break;
8070   case lltok::kw_byteArray:
8071     TTRes.TheKind = TypeTestResolution::ByteArray;
8072     break;
8073   case lltok::kw_inline:
8074     TTRes.TheKind = TypeTestResolution::Inline;
8075     break;
8076   case lltok::kw_single:
8077     TTRes.TheKind = TypeTestResolution::Single;
8078     break;
8079   case lltok::kw_allOnes:
8080     TTRes.TheKind = TypeTestResolution::AllOnes;
8081     break;
8082   default:
8083     return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
8084   }
8085   Lex.Lex();
8086 
8087   if (parseToken(lltok::comma, "expected ',' here") ||
8088       parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
8089       parseToken(lltok::colon, "expected ':' here") ||
8090       parseUInt32(TTRes.SizeM1BitWidth))
8091     return true;
8092 
8093   // parse optional fields
8094   while (EatIfPresent(lltok::comma)) {
8095     switch (Lex.getKind()) {
8096     case lltok::kw_alignLog2:
8097       Lex.Lex();
8098       if (parseToken(lltok::colon, "expected ':'") ||
8099           parseUInt64(TTRes.AlignLog2))
8100         return true;
8101       break;
8102     case lltok::kw_sizeM1:
8103       Lex.Lex();
8104       if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
8105         return true;
8106       break;
8107     case lltok::kw_bitMask: {
8108       unsigned Val;
8109       Lex.Lex();
8110       if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
8111         return true;
8112       assert(Val <= 0xff);
8113       TTRes.BitMask = (uint8_t)Val;
8114       break;
8115     }
8116     case lltok::kw_inlineBits:
8117       Lex.Lex();
8118       if (parseToken(lltok::colon, "expected ':'") ||
8119           parseUInt64(TTRes.InlineBits))
8120         return true;
8121       break;
8122     default:
8123       return error(Lex.getLoc(), "expected optional TypeTestResolution field");
8124     }
8125   }
8126 
8127   if (parseToken(lltok::rparen, "expected ')' here"))
8128     return true;
8129 
8130   return false;
8131 }
8132 
8133 /// OptionalWpdResolutions
8134 ///   ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
8135 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
parseOptionalWpdResolutions(std::map<uint64_t,WholeProgramDevirtResolution> & WPDResMap)8136 bool LLParser::parseOptionalWpdResolutions(
8137     std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
8138   if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
8139       parseToken(lltok::colon, "expected ':' here") ||
8140       parseToken(lltok::lparen, "expected '(' here"))
8141     return true;
8142 
8143   do {
8144     uint64_t Offset;
8145     WholeProgramDevirtResolution WPDRes;
8146     if (parseToken(lltok::lparen, "expected '(' here") ||
8147         parseToken(lltok::kw_offset, "expected 'offset' here") ||
8148         parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8149         parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
8150         parseToken(lltok::rparen, "expected ')' here"))
8151       return true;
8152     WPDResMap[Offset] = WPDRes;
8153   } while (EatIfPresent(lltok::comma));
8154 
8155   if (parseToken(lltok::rparen, "expected ')' here"))
8156     return true;
8157 
8158   return false;
8159 }
8160 
8161 /// WpdRes
8162 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
8163 ///         [',' OptionalResByArg]? ')'
8164 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
8165 ///         ',' 'singleImplName' ':' STRINGCONSTANT ','
8166 ///         [',' OptionalResByArg]? ')'
8167 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
8168 ///         [',' OptionalResByArg]? ')'
parseWpdRes(WholeProgramDevirtResolution & WPDRes)8169 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
8170   if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
8171       parseToken(lltok::colon, "expected ':' here") ||
8172       parseToken(lltok::lparen, "expected '(' here") ||
8173       parseToken(lltok::kw_kind, "expected 'kind' here") ||
8174       parseToken(lltok::colon, "expected ':' here"))
8175     return true;
8176 
8177   switch (Lex.getKind()) {
8178   case lltok::kw_indir:
8179     WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
8180     break;
8181   case lltok::kw_singleImpl:
8182     WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
8183     break;
8184   case lltok::kw_branchFunnel:
8185     WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
8186     break;
8187   default:
8188     return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
8189   }
8190   Lex.Lex();
8191 
8192   // parse optional fields
8193   while (EatIfPresent(lltok::comma)) {
8194     switch (Lex.getKind()) {
8195     case lltok::kw_singleImplName:
8196       Lex.Lex();
8197       if (parseToken(lltok::colon, "expected ':' here") ||
8198           parseStringConstant(WPDRes.SingleImplName))
8199         return true;
8200       break;
8201     case lltok::kw_resByArg:
8202       if (parseOptionalResByArg(WPDRes.ResByArg))
8203         return true;
8204       break;
8205     default:
8206       return error(Lex.getLoc(),
8207                    "expected optional WholeProgramDevirtResolution field");
8208     }
8209   }
8210 
8211   if (parseToken(lltok::rparen, "expected ')' here"))
8212     return true;
8213 
8214   return false;
8215 }
8216 
8217 /// OptionalResByArg
8218 ///   ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
8219 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
8220 ///                ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
8221 ///                  'virtualConstProp' )
8222 ///                [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
8223 ///                [',' 'bit' ':' UInt32]? ')'
parseOptionalResByArg(std::map<std::vector<uint64_t>,WholeProgramDevirtResolution::ByArg> & ResByArg)8224 bool LLParser::parseOptionalResByArg(
8225     std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
8226         &ResByArg) {
8227   if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
8228       parseToken(lltok::colon, "expected ':' here") ||
8229       parseToken(lltok::lparen, "expected '(' here"))
8230     return true;
8231 
8232   do {
8233     std::vector<uint64_t> Args;
8234     if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
8235         parseToken(lltok::kw_byArg, "expected 'byArg here") ||
8236         parseToken(lltok::colon, "expected ':' here") ||
8237         parseToken(lltok::lparen, "expected '(' here") ||
8238         parseToken(lltok::kw_kind, "expected 'kind' here") ||
8239         parseToken(lltok::colon, "expected ':' here"))
8240       return true;
8241 
8242     WholeProgramDevirtResolution::ByArg ByArg;
8243     switch (Lex.getKind()) {
8244     case lltok::kw_indir:
8245       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
8246       break;
8247     case lltok::kw_uniformRetVal:
8248       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
8249       break;
8250     case lltok::kw_uniqueRetVal:
8251       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
8252       break;
8253     case lltok::kw_virtualConstProp:
8254       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
8255       break;
8256     default:
8257       return error(Lex.getLoc(),
8258                    "unexpected WholeProgramDevirtResolution::ByArg kind");
8259     }
8260     Lex.Lex();
8261 
8262     // parse optional fields
8263     while (EatIfPresent(lltok::comma)) {
8264       switch (Lex.getKind()) {
8265       case lltok::kw_info:
8266         Lex.Lex();
8267         if (parseToken(lltok::colon, "expected ':' here") ||
8268             parseUInt64(ByArg.Info))
8269           return true;
8270         break;
8271       case lltok::kw_byte:
8272         Lex.Lex();
8273         if (parseToken(lltok::colon, "expected ':' here") ||
8274             parseUInt32(ByArg.Byte))
8275           return true;
8276         break;
8277       case lltok::kw_bit:
8278         Lex.Lex();
8279         if (parseToken(lltok::colon, "expected ':' here") ||
8280             parseUInt32(ByArg.Bit))
8281           return true;
8282         break;
8283       default:
8284         return error(Lex.getLoc(),
8285                      "expected optional whole program devirt field");
8286       }
8287     }
8288 
8289     if (parseToken(lltok::rparen, "expected ')' here"))
8290       return true;
8291 
8292     ResByArg[Args] = ByArg;
8293   } while (EatIfPresent(lltok::comma));
8294 
8295   if (parseToken(lltok::rparen, "expected ')' here"))
8296     return true;
8297 
8298   return false;
8299 }
8300 
8301 /// OptionalResByArg
8302 ///   ::= 'args' ':' '(' UInt64[, UInt64]* ')'
parseArgs(std::vector<uint64_t> & Args)8303 bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
8304   if (parseToken(lltok::kw_args, "expected 'args' here") ||
8305       parseToken(lltok::colon, "expected ':' here") ||
8306       parseToken(lltok::lparen, "expected '(' here"))
8307     return true;
8308 
8309   do {
8310     uint64_t Val;
8311     if (parseUInt64(Val))
8312       return true;
8313     Args.push_back(Val);
8314   } while (EatIfPresent(lltok::comma));
8315 
8316   if (parseToken(lltok::rparen, "expected ')' here"))
8317     return true;
8318 
8319   return false;
8320 }
8321 
8322 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
8323 
resolveFwdRef(ValueInfo * Fwd,ValueInfo & Resolved)8324 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
8325   bool ReadOnly = Fwd->isReadOnly();
8326   bool WriteOnly = Fwd->isWriteOnly();
8327   assert(!(ReadOnly && WriteOnly));
8328   *Fwd = Resolved;
8329   if (ReadOnly)
8330     Fwd->setReadOnly();
8331   if (WriteOnly)
8332     Fwd->setWriteOnly();
8333 }
8334 
8335 /// Stores the given Name/GUID and associated summary into the Index.
8336 /// Also updates any forward references to the associated entry ID.
addGlobalValueToIndex(std::string Name,GlobalValue::GUID GUID,GlobalValue::LinkageTypes Linkage,unsigned ID,std::unique_ptr<GlobalValueSummary> Summary)8337 void LLParser::addGlobalValueToIndex(
8338     std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
8339     unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
8340   // First create the ValueInfo utilizing the Name or GUID.
8341   ValueInfo VI;
8342   if (GUID != 0) {
8343     assert(Name.empty());
8344     VI = Index->getOrInsertValueInfo(GUID);
8345   } else {
8346     assert(!Name.empty());
8347     if (M) {
8348       auto *GV = M->getNamedValue(Name);
8349       assert(GV);
8350       VI = Index->getOrInsertValueInfo(GV);
8351     } else {
8352       assert(
8353           (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
8354           "Need a source_filename to compute GUID for local");
8355       GUID = GlobalValue::getGUID(
8356           GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
8357       VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
8358     }
8359   }
8360 
8361   // Resolve forward references from calls/refs
8362   auto FwdRefVIs = ForwardRefValueInfos.find(ID);
8363   if (FwdRefVIs != ForwardRefValueInfos.end()) {
8364     for (auto VIRef : FwdRefVIs->second) {
8365       assert(VIRef.first->getRef() == FwdVIRef &&
8366              "Forward referenced ValueInfo expected to be empty");
8367       resolveFwdRef(VIRef.first, VI);
8368     }
8369     ForwardRefValueInfos.erase(FwdRefVIs);
8370   }
8371 
8372   // Resolve forward references from aliases
8373   auto FwdRefAliasees = ForwardRefAliasees.find(ID);
8374   if (FwdRefAliasees != ForwardRefAliasees.end()) {
8375     for (auto AliaseeRef : FwdRefAliasees->second) {
8376       assert(!AliaseeRef.first->hasAliasee() &&
8377              "Forward referencing alias already has aliasee");
8378       assert(Summary && "Aliasee must be a definition");
8379       AliaseeRef.first->setAliasee(VI, Summary.get());
8380     }
8381     ForwardRefAliasees.erase(FwdRefAliasees);
8382   }
8383 
8384   // Add the summary if one was provided.
8385   if (Summary)
8386     Index->addGlobalValueSummary(VI, std::move(Summary));
8387 
8388   // Save the associated ValueInfo for use in later references by ID.
8389   if (ID == NumberedValueInfos.size())
8390     NumberedValueInfos.push_back(VI);
8391   else {
8392     // Handle non-continuous numbers (to make test simplification easier).
8393     if (ID > NumberedValueInfos.size())
8394       NumberedValueInfos.resize(ID + 1);
8395     NumberedValueInfos[ID] = VI;
8396   }
8397 }
8398 
8399 /// parseSummaryIndexFlags
8400 ///   ::= 'flags' ':' UInt64
parseSummaryIndexFlags()8401 bool LLParser::parseSummaryIndexFlags() {
8402   assert(Lex.getKind() == lltok::kw_flags);
8403   Lex.Lex();
8404 
8405   if (parseToken(lltok::colon, "expected ':' here"))
8406     return true;
8407   uint64_t Flags;
8408   if (parseUInt64(Flags))
8409     return true;
8410   if (Index)
8411     Index->setFlags(Flags);
8412   return false;
8413 }
8414 
8415 /// parseBlockCount
8416 ///   ::= 'blockcount' ':' UInt64
parseBlockCount()8417 bool LLParser::parseBlockCount() {
8418   assert(Lex.getKind() == lltok::kw_blockcount);
8419   Lex.Lex();
8420 
8421   if (parseToken(lltok::colon, "expected ':' here"))
8422     return true;
8423   uint64_t BlockCount;
8424   if (parseUInt64(BlockCount))
8425     return true;
8426   if (Index)
8427     Index->setBlockCount(BlockCount);
8428   return false;
8429 }
8430 
8431 /// parseGVEntry
8432 ///   ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
8433 ///         [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
8434 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
parseGVEntry(unsigned ID)8435 bool LLParser::parseGVEntry(unsigned ID) {
8436   assert(Lex.getKind() == lltok::kw_gv);
8437   Lex.Lex();
8438 
8439   if (parseToken(lltok::colon, "expected ':' here") ||
8440       parseToken(lltok::lparen, "expected '(' here"))
8441     return true;
8442 
8443   std::string Name;
8444   GlobalValue::GUID GUID = 0;
8445   switch (Lex.getKind()) {
8446   case lltok::kw_name:
8447     Lex.Lex();
8448     if (parseToken(lltok::colon, "expected ':' here") ||
8449         parseStringConstant(Name))
8450       return true;
8451     // Can't create GUID/ValueInfo until we have the linkage.
8452     break;
8453   case lltok::kw_guid:
8454     Lex.Lex();
8455     if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
8456       return true;
8457     break;
8458   default:
8459     return error(Lex.getLoc(), "expected name or guid tag");
8460   }
8461 
8462   if (!EatIfPresent(lltok::comma)) {
8463     // No summaries. Wrap up.
8464     if (parseToken(lltok::rparen, "expected ')' here"))
8465       return true;
8466     // This was created for a call to an external or indirect target.
8467     // A GUID with no summary came from a VALUE_GUID record, dummy GUID
8468     // created for indirect calls with VP. A Name with no GUID came from
8469     // an external definition. We pass ExternalLinkage since that is only
8470     // used when the GUID must be computed from Name, and in that case
8471     // the symbol must have external linkage.
8472     addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
8473                           nullptr);
8474     return false;
8475   }
8476 
8477   // Have a list of summaries
8478   if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
8479       parseToken(lltok::colon, "expected ':' here") ||
8480       parseToken(lltok::lparen, "expected '(' here"))
8481     return true;
8482   do {
8483     switch (Lex.getKind()) {
8484     case lltok::kw_function:
8485       if (parseFunctionSummary(Name, GUID, ID))
8486         return true;
8487       break;
8488     case lltok::kw_variable:
8489       if (parseVariableSummary(Name, GUID, ID))
8490         return true;
8491       break;
8492     case lltok::kw_alias:
8493       if (parseAliasSummary(Name, GUID, ID))
8494         return true;
8495       break;
8496     default:
8497       return error(Lex.getLoc(), "expected summary type");
8498     }
8499   } while (EatIfPresent(lltok::comma));
8500 
8501   if (parseToken(lltok::rparen, "expected ')' here") ||
8502       parseToken(lltok::rparen, "expected ')' here"))
8503     return true;
8504 
8505   return false;
8506 }
8507 
8508 /// FunctionSummary
8509 ///   ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8510 ///         ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8511 ///         [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
8512 ///         [',' OptionalRefs]? ')'
parseFunctionSummary(std::string Name,GlobalValue::GUID GUID,unsigned ID)8513 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
8514                                     unsigned ID) {
8515   assert(Lex.getKind() == lltok::kw_function);
8516   Lex.Lex();
8517 
8518   StringRef ModulePath;
8519   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8520       /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
8521       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8522   unsigned InstCount;
8523   std::vector<FunctionSummary::EdgeTy> Calls;
8524   FunctionSummary::TypeIdInfo TypeIdInfo;
8525   std::vector<FunctionSummary::ParamAccess> ParamAccesses;
8526   std::vector<ValueInfo> Refs;
8527   // Default is all-zeros (conservative values).
8528   FunctionSummary::FFlags FFlags = {};
8529   if (parseToken(lltok::colon, "expected ':' here") ||
8530       parseToken(lltok::lparen, "expected '(' here") ||
8531       parseModuleReference(ModulePath) ||
8532       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8533       parseToken(lltok::comma, "expected ',' here") ||
8534       parseToken(lltok::kw_insts, "expected 'insts' here") ||
8535       parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
8536     return true;
8537 
8538   // parse optional fields
8539   while (EatIfPresent(lltok::comma)) {
8540     switch (Lex.getKind()) {
8541     case lltok::kw_funcFlags:
8542       if (parseOptionalFFlags(FFlags))
8543         return true;
8544       break;
8545     case lltok::kw_calls:
8546       if (parseOptionalCalls(Calls))
8547         return true;
8548       break;
8549     case lltok::kw_typeIdInfo:
8550       if (parseOptionalTypeIdInfo(TypeIdInfo))
8551         return true;
8552       break;
8553     case lltok::kw_refs:
8554       if (parseOptionalRefs(Refs))
8555         return true;
8556       break;
8557     case lltok::kw_params:
8558       if (parseOptionalParamAccesses(ParamAccesses))
8559         return true;
8560       break;
8561     default:
8562       return error(Lex.getLoc(), "expected optional function summary field");
8563     }
8564   }
8565 
8566   if (parseToken(lltok::rparen, "expected ')' here"))
8567     return true;
8568 
8569   auto FS = std::make_unique<FunctionSummary>(
8570       GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
8571       std::move(Calls), std::move(TypeIdInfo.TypeTests),
8572       std::move(TypeIdInfo.TypeTestAssumeVCalls),
8573       std::move(TypeIdInfo.TypeCheckedLoadVCalls),
8574       std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
8575       std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
8576       std::move(ParamAccesses));
8577 
8578   FS->setModulePath(ModulePath);
8579 
8580   addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8581                         ID, std::move(FS));
8582 
8583   return false;
8584 }
8585 
8586 /// VariableSummary
8587 ///   ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8588 ///         [',' OptionalRefs]? ')'
parseVariableSummary(std::string Name,GlobalValue::GUID GUID,unsigned ID)8589 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
8590                                     unsigned ID) {
8591   assert(Lex.getKind() == lltok::kw_variable);
8592   Lex.Lex();
8593 
8594   StringRef ModulePath;
8595   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8596       /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
8597       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8598   GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
8599                                         /* WriteOnly */ false,
8600                                         /* Constant */ false,
8601                                         GlobalObject::VCallVisibilityPublic);
8602   std::vector<ValueInfo> Refs;
8603   VTableFuncList VTableFuncs;
8604   if (parseToken(lltok::colon, "expected ':' here") ||
8605       parseToken(lltok::lparen, "expected '(' here") ||
8606       parseModuleReference(ModulePath) ||
8607       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8608       parseToken(lltok::comma, "expected ',' here") ||
8609       parseGVarFlags(GVarFlags))
8610     return true;
8611 
8612   // parse optional fields
8613   while (EatIfPresent(lltok::comma)) {
8614     switch (Lex.getKind()) {
8615     case lltok::kw_vTableFuncs:
8616       if (parseOptionalVTableFuncs(VTableFuncs))
8617         return true;
8618       break;
8619     case lltok::kw_refs:
8620       if (parseOptionalRefs(Refs))
8621         return true;
8622       break;
8623     default:
8624       return error(Lex.getLoc(), "expected optional variable summary field");
8625     }
8626   }
8627 
8628   if (parseToken(lltok::rparen, "expected ')' here"))
8629     return true;
8630 
8631   auto GS =
8632       std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
8633 
8634   GS->setModulePath(ModulePath);
8635   GS->setVTableFuncs(std::move(VTableFuncs));
8636 
8637   addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8638                         ID, std::move(GS));
8639 
8640   return false;
8641 }
8642 
8643 /// AliasSummary
8644 ///   ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
8645 ///         'aliasee' ':' GVReference ')'
parseAliasSummary(std::string Name,GlobalValue::GUID GUID,unsigned ID)8646 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
8647                                  unsigned ID) {
8648   assert(Lex.getKind() == lltok::kw_alias);
8649   LocTy Loc = Lex.getLoc();
8650   Lex.Lex();
8651 
8652   StringRef ModulePath;
8653   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8654       /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
8655       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8656   if (parseToken(lltok::colon, "expected ':' here") ||
8657       parseToken(lltok::lparen, "expected '(' here") ||
8658       parseModuleReference(ModulePath) ||
8659       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8660       parseToken(lltok::comma, "expected ',' here") ||
8661       parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
8662       parseToken(lltok::colon, "expected ':' here"))
8663     return true;
8664 
8665   ValueInfo AliaseeVI;
8666   unsigned GVId;
8667   if (parseGVReference(AliaseeVI, GVId))
8668     return true;
8669 
8670   if (parseToken(lltok::rparen, "expected ')' here"))
8671     return true;
8672 
8673   auto AS = std::make_unique<AliasSummary>(GVFlags);
8674 
8675   AS->setModulePath(ModulePath);
8676 
8677   // Record forward reference if the aliasee is not parsed yet.
8678   if (AliaseeVI.getRef() == FwdVIRef) {
8679     ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
8680   } else {
8681     auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
8682     assert(Summary && "Aliasee must be a definition");
8683     AS->setAliasee(AliaseeVI, Summary);
8684   }
8685 
8686   addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8687                         ID, std::move(AS));
8688 
8689   return false;
8690 }
8691 
8692 /// Flag
8693 ///   ::= [0|1]
parseFlag(unsigned & Val)8694 bool LLParser::parseFlag(unsigned &Val) {
8695   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
8696     return tokError("expected integer");
8697   Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
8698   Lex.Lex();
8699   return false;
8700 }
8701 
8702 /// OptionalFFlags
8703 ///   := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8704 ///        [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8705 ///        [',' 'returnDoesNotAlias' ':' Flag]? ')'
8706 ///        [',' 'noInline' ':' Flag]? ')'
8707 ///        [',' 'alwaysInline' ':' Flag]? ')'
8708 
parseOptionalFFlags(FunctionSummary::FFlags & FFlags)8709 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
8710   assert(Lex.getKind() == lltok::kw_funcFlags);
8711   Lex.Lex();
8712 
8713   if (parseToken(lltok::colon, "expected ':' in funcFlags") |
8714       parseToken(lltok::lparen, "expected '(' in funcFlags"))
8715     return true;
8716 
8717   do {
8718     unsigned Val = 0;
8719     switch (Lex.getKind()) {
8720     case lltok::kw_readNone:
8721       Lex.Lex();
8722       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8723         return true;
8724       FFlags.ReadNone = Val;
8725       break;
8726     case lltok::kw_readOnly:
8727       Lex.Lex();
8728       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8729         return true;
8730       FFlags.ReadOnly = Val;
8731       break;
8732     case lltok::kw_noRecurse:
8733       Lex.Lex();
8734       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8735         return true;
8736       FFlags.NoRecurse = Val;
8737       break;
8738     case lltok::kw_returnDoesNotAlias:
8739       Lex.Lex();
8740       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8741         return true;
8742       FFlags.ReturnDoesNotAlias = Val;
8743       break;
8744     case lltok::kw_noInline:
8745       Lex.Lex();
8746       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8747         return true;
8748       FFlags.NoInline = Val;
8749       break;
8750     case lltok::kw_alwaysInline:
8751       Lex.Lex();
8752       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8753         return true;
8754       FFlags.AlwaysInline = Val;
8755       break;
8756     default:
8757       return error(Lex.getLoc(), "expected function flag type");
8758     }
8759   } while (EatIfPresent(lltok::comma));
8760 
8761   if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
8762     return true;
8763 
8764   return false;
8765 }
8766 
8767 /// OptionalCalls
8768 ///   := 'calls' ':' '(' Call [',' Call]* ')'
8769 /// Call ::= '(' 'callee' ':' GVReference
8770 ///            [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> & Calls)8771 bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
8772   assert(Lex.getKind() == lltok::kw_calls);
8773   Lex.Lex();
8774 
8775   if (parseToken(lltok::colon, "expected ':' in calls") |
8776       parseToken(lltok::lparen, "expected '(' in calls"))
8777     return true;
8778 
8779   IdToIndexMapType IdToIndexMap;
8780   // parse each call edge
8781   do {
8782     ValueInfo VI;
8783     if (parseToken(lltok::lparen, "expected '(' in call") ||
8784         parseToken(lltok::kw_callee, "expected 'callee' in call") ||
8785         parseToken(lltok::colon, "expected ':'"))
8786       return true;
8787 
8788     LocTy Loc = Lex.getLoc();
8789     unsigned GVId;
8790     if (parseGVReference(VI, GVId))
8791       return true;
8792 
8793     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
8794     unsigned RelBF = 0;
8795     if (EatIfPresent(lltok::comma)) {
8796       // Expect either hotness or relbf
8797       if (EatIfPresent(lltok::kw_hotness)) {
8798         if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
8799           return true;
8800       } else {
8801         if (parseToken(lltok::kw_relbf, "expected relbf") ||
8802             parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
8803           return true;
8804       }
8805     }
8806     // Keep track of the Call array index needing a forward reference.
8807     // We will save the location of the ValueInfo needing an update, but
8808     // can only do so once the std::vector is finalized.
8809     if (VI.getRef() == FwdVIRef)
8810       IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
8811     Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
8812 
8813     if (parseToken(lltok::rparen, "expected ')' in call"))
8814       return true;
8815   } while (EatIfPresent(lltok::comma));
8816 
8817   // Now that the Calls vector is finalized, it is safe to save the locations
8818   // of any forward GV references that need updating later.
8819   for (auto I : IdToIndexMap) {
8820     auto &Infos = ForwardRefValueInfos[I.first];
8821     for (auto P : I.second) {
8822       assert(Calls[P.first].first.getRef() == FwdVIRef &&
8823              "Forward referenced ValueInfo expected to be empty");
8824       Infos.emplace_back(&Calls[P.first].first, P.second);
8825     }
8826   }
8827 
8828   if (parseToken(lltok::rparen, "expected ')' in calls"))
8829     return true;
8830 
8831   return false;
8832 }
8833 
8834 /// Hotness
8835 ///   := ('unknown'|'cold'|'none'|'hot'|'critical')
parseHotness(CalleeInfo::HotnessType & Hotness)8836 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
8837   switch (Lex.getKind()) {
8838   case lltok::kw_unknown:
8839     Hotness = CalleeInfo::HotnessType::Unknown;
8840     break;
8841   case lltok::kw_cold:
8842     Hotness = CalleeInfo::HotnessType::Cold;
8843     break;
8844   case lltok::kw_none:
8845     Hotness = CalleeInfo::HotnessType::None;
8846     break;
8847   case lltok::kw_hot:
8848     Hotness = CalleeInfo::HotnessType::Hot;
8849     break;
8850   case lltok::kw_critical:
8851     Hotness = CalleeInfo::HotnessType::Critical;
8852     break;
8853   default:
8854     return error(Lex.getLoc(), "invalid call edge hotness");
8855   }
8856   Lex.Lex();
8857   return false;
8858 }
8859 
8860 /// OptionalVTableFuncs
8861 ///   := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
8862 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
parseOptionalVTableFuncs(VTableFuncList & VTableFuncs)8863 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
8864   assert(Lex.getKind() == lltok::kw_vTableFuncs);
8865   Lex.Lex();
8866 
8867   if (parseToken(lltok::colon, "expected ':' in vTableFuncs") |
8868       parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
8869     return true;
8870 
8871   IdToIndexMapType IdToIndexMap;
8872   // parse each virtual function pair
8873   do {
8874     ValueInfo VI;
8875     if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
8876         parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
8877         parseToken(lltok::colon, "expected ':'"))
8878       return true;
8879 
8880     LocTy Loc = Lex.getLoc();
8881     unsigned GVId;
8882     if (parseGVReference(VI, GVId))
8883       return true;
8884 
8885     uint64_t Offset;
8886     if (parseToken(lltok::comma, "expected comma") ||
8887         parseToken(lltok::kw_offset, "expected offset") ||
8888         parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
8889       return true;
8890 
8891     // Keep track of the VTableFuncs array index needing a forward reference.
8892     // We will save the location of the ValueInfo needing an update, but
8893     // can only do so once the std::vector is finalized.
8894     if (VI == EmptyVI)
8895       IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
8896     VTableFuncs.push_back({VI, Offset});
8897 
8898     if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
8899       return true;
8900   } while (EatIfPresent(lltok::comma));
8901 
8902   // Now that the VTableFuncs vector is finalized, it is safe to save the
8903   // locations of any forward GV references that need updating later.
8904   for (auto I : IdToIndexMap) {
8905     auto &Infos = ForwardRefValueInfos[I.first];
8906     for (auto P : I.second) {
8907       assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
8908              "Forward referenced ValueInfo expected to be empty");
8909       Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
8910     }
8911   }
8912 
8913   if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
8914     return true;
8915 
8916   return false;
8917 }
8918 
8919 /// ParamNo := 'param' ':' UInt64
parseParamNo(uint64_t & ParamNo)8920 bool LLParser::parseParamNo(uint64_t &ParamNo) {
8921   if (parseToken(lltok::kw_param, "expected 'param' here") ||
8922       parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
8923     return true;
8924   return false;
8925 }
8926 
8927 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
parseParamAccessOffset(ConstantRange & Range)8928 bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
8929   APSInt Lower;
8930   APSInt Upper;
8931   auto ParseAPSInt = [&](APSInt &Val) {
8932     if (Lex.getKind() != lltok::APSInt)
8933       return tokError("expected integer");
8934     Val = Lex.getAPSIntVal();
8935     Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
8936     Val.setIsSigned(true);
8937     Lex.Lex();
8938     return false;
8939   };
8940   if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
8941       parseToken(lltok::colon, "expected ':' here") ||
8942       parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
8943       parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
8944       parseToken(lltok::rsquare, "expected ']' here"))
8945     return true;
8946 
8947   ++Upper;
8948   Range =
8949       (Lower == Upper && !Lower.isMaxValue())
8950           ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
8951           : ConstantRange(Lower, Upper);
8952 
8953   return false;
8954 }
8955 
8956 /// ParamAccessCall
8957 ///   := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
parseParamAccessCall(FunctionSummary::ParamAccess::Call & Call,IdLocListType & IdLocList)8958 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
8959                                     IdLocListType &IdLocList) {
8960   if (parseToken(lltok::lparen, "expected '(' here") ||
8961       parseToken(lltok::kw_callee, "expected 'callee' here") ||
8962       parseToken(lltok::colon, "expected ':' here"))
8963     return true;
8964 
8965   unsigned GVId;
8966   ValueInfo VI;
8967   LocTy Loc = Lex.getLoc();
8968   if (parseGVReference(VI, GVId))
8969     return true;
8970 
8971   Call.Callee = VI;
8972   IdLocList.emplace_back(GVId, Loc);
8973 
8974   if (parseToken(lltok::comma, "expected ',' here") ||
8975       parseParamNo(Call.ParamNo) ||
8976       parseToken(lltok::comma, "expected ',' here") ||
8977       parseParamAccessOffset(Call.Offsets))
8978     return true;
8979 
8980   if (parseToken(lltok::rparen, "expected ')' here"))
8981     return true;
8982 
8983   return false;
8984 }
8985 
8986 /// ParamAccess
8987 ///   := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
8988 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
parseParamAccess(FunctionSummary::ParamAccess & Param,IdLocListType & IdLocList)8989 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
8990                                 IdLocListType &IdLocList) {
8991   if (parseToken(lltok::lparen, "expected '(' here") ||
8992       parseParamNo(Param.ParamNo) ||
8993       parseToken(lltok::comma, "expected ',' here") ||
8994       parseParamAccessOffset(Param.Use))
8995     return true;
8996 
8997   if (EatIfPresent(lltok::comma)) {
8998     if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
8999         parseToken(lltok::colon, "expected ':' here") ||
9000         parseToken(lltok::lparen, "expected '(' here"))
9001       return true;
9002     do {
9003       FunctionSummary::ParamAccess::Call Call;
9004       if (parseParamAccessCall(Call, IdLocList))
9005         return true;
9006       Param.Calls.push_back(Call);
9007     } while (EatIfPresent(lltok::comma));
9008 
9009     if (parseToken(lltok::rparen, "expected ')' here"))
9010       return true;
9011   }
9012 
9013   if (parseToken(lltok::rparen, "expected ')' here"))
9014     return true;
9015 
9016   return false;
9017 }
9018 
9019 /// OptionalParamAccesses
9020 ///   := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
parseOptionalParamAccesses(std::vector<FunctionSummary::ParamAccess> & Params)9021 bool LLParser::parseOptionalParamAccesses(
9022     std::vector<FunctionSummary::ParamAccess> &Params) {
9023   assert(Lex.getKind() == lltok::kw_params);
9024   Lex.Lex();
9025 
9026   if (parseToken(lltok::colon, "expected ':' here") ||
9027       parseToken(lltok::lparen, "expected '(' here"))
9028     return true;
9029 
9030   IdLocListType VContexts;
9031   size_t CallsNum = 0;
9032   do {
9033     FunctionSummary::ParamAccess ParamAccess;
9034     if (parseParamAccess(ParamAccess, VContexts))
9035       return true;
9036     CallsNum += ParamAccess.Calls.size();
9037     assert(VContexts.size() == CallsNum);
9038     Params.emplace_back(std::move(ParamAccess));
9039   } while (EatIfPresent(lltok::comma));
9040 
9041   if (parseToken(lltok::rparen, "expected ')' here"))
9042     return true;
9043 
9044   // Now that the Params is finalized, it is safe to save the locations
9045   // of any forward GV references that need updating later.
9046   IdLocListType::const_iterator ItContext = VContexts.begin();
9047   for (auto &PA : Params) {
9048     for (auto &C : PA.Calls) {
9049       if (C.Callee.getRef() == FwdVIRef)
9050         ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
9051                                                             ItContext->second);
9052       ++ItContext;
9053     }
9054   }
9055   assert(ItContext == VContexts.end());
9056 
9057   return false;
9058 }
9059 
9060 /// OptionalRefs
9061 ///   := 'refs' ':' '(' GVReference [',' GVReference]* ')'
parseOptionalRefs(std::vector<ValueInfo> & Refs)9062 bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
9063   assert(Lex.getKind() == lltok::kw_refs);
9064   Lex.Lex();
9065 
9066   if (parseToken(lltok::colon, "expected ':' in refs") ||
9067       parseToken(lltok::lparen, "expected '(' in refs"))
9068     return true;
9069 
9070   struct ValueContext {
9071     ValueInfo VI;
9072     unsigned GVId;
9073     LocTy Loc;
9074   };
9075   std::vector<ValueContext> VContexts;
9076   // parse each ref edge
9077   do {
9078     ValueContext VC;
9079     VC.Loc = Lex.getLoc();
9080     if (parseGVReference(VC.VI, VC.GVId))
9081       return true;
9082     VContexts.push_back(VC);
9083   } while (EatIfPresent(lltok::comma));
9084 
9085   // Sort value contexts so that ones with writeonly
9086   // and readonly ValueInfo  are at the end of VContexts vector.
9087   // See FunctionSummary::specialRefCounts()
9088   llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
9089     return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
9090   });
9091 
9092   IdToIndexMapType IdToIndexMap;
9093   for (auto &VC : VContexts) {
9094     // Keep track of the Refs array index needing a forward reference.
9095     // We will save the location of the ValueInfo needing an update, but
9096     // can only do so once the std::vector is finalized.
9097     if (VC.VI.getRef() == FwdVIRef)
9098       IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
9099     Refs.push_back(VC.VI);
9100   }
9101 
9102   // Now that the Refs vector is finalized, it is safe to save the locations
9103   // of any forward GV references that need updating later.
9104   for (auto I : IdToIndexMap) {
9105     auto &Infos = ForwardRefValueInfos[I.first];
9106     for (auto P : I.second) {
9107       assert(Refs[P.first].getRef() == FwdVIRef &&
9108              "Forward referenced ValueInfo expected to be empty");
9109       Infos.emplace_back(&Refs[P.first], P.second);
9110     }
9111   }
9112 
9113   if (parseToken(lltok::rparen, "expected ')' in refs"))
9114     return true;
9115 
9116   return false;
9117 }
9118 
9119 /// OptionalTypeIdInfo
9120 ///   := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
9121 ///         [',' TypeCheckedLoadVCalls]?  [',' TypeTestAssumeConstVCalls]?
9122 ///         [',' TypeCheckedLoadConstVCalls]? ')'
parseOptionalTypeIdInfo(FunctionSummary::TypeIdInfo & TypeIdInfo)9123 bool LLParser::parseOptionalTypeIdInfo(
9124     FunctionSummary::TypeIdInfo &TypeIdInfo) {
9125   assert(Lex.getKind() == lltok::kw_typeIdInfo);
9126   Lex.Lex();
9127 
9128   if (parseToken(lltok::colon, "expected ':' here") ||
9129       parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9130     return true;
9131 
9132   do {
9133     switch (Lex.getKind()) {
9134     case lltok::kw_typeTests:
9135       if (parseTypeTests(TypeIdInfo.TypeTests))
9136         return true;
9137       break;
9138     case lltok::kw_typeTestAssumeVCalls:
9139       if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
9140                            TypeIdInfo.TypeTestAssumeVCalls))
9141         return true;
9142       break;
9143     case lltok::kw_typeCheckedLoadVCalls:
9144       if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
9145                            TypeIdInfo.TypeCheckedLoadVCalls))
9146         return true;
9147       break;
9148     case lltok::kw_typeTestAssumeConstVCalls:
9149       if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
9150                               TypeIdInfo.TypeTestAssumeConstVCalls))
9151         return true;
9152       break;
9153     case lltok::kw_typeCheckedLoadConstVCalls:
9154       if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
9155                               TypeIdInfo.TypeCheckedLoadConstVCalls))
9156         return true;
9157       break;
9158     default:
9159       return error(Lex.getLoc(), "invalid typeIdInfo list type");
9160     }
9161   } while (EatIfPresent(lltok::comma));
9162 
9163   if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9164     return true;
9165 
9166   return false;
9167 }
9168 
9169 /// TypeTests
9170 ///   ::= 'typeTests' ':' '(' (SummaryID | UInt64)
9171 ///         [',' (SummaryID | UInt64)]* ')'
parseTypeTests(std::vector<GlobalValue::GUID> & TypeTests)9172 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
9173   assert(Lex.getKind() == lltok::kw_typeTests);
9174   Lex.Lex();
9175 
9176   if (parseToken(lltok::colon, "expected ':' here") ||
9177       parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9178     return true;
9179 
9180   IdToIndexMapType IdToIndexMap;
9181   do {
9182     GlobalValue::GUID GUID = 0;
9183     if (Lex.getKind() == lltok::SummaryID) {
9184       unsigned ID = Lex.getUIntVal();
9185       LocTy Loc = Lex.getLoc();
9186       // Keep track of the TypeTests array index needing a forward reference.
9187       // We will save the location of the GUID needing an update, but
9188       // can only do so once the std::vector is finalized.
9189       IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
9190       Lex.Lex();
9191     } else if (parseUInt64(GUID))
9192       return true;
9193     TypeTests.push_back(GUID);
9194   } while (EatIfPresent(lltok::comma));
9195 
9196   // Now that the TypeTests vector is finalized, it is safe to save the
9197   // locations of any forward GV references that need updating later.
9198   for (auto I : IdToIndexMap) {
9199     auto &Ids = ForwardRefTypeIds[I.first];
9200     for (auto P : I.second) {
9201       assert(TypeTests[P.first] == 0 &&
9202              "Forward referenced type id GUID expected to be 0");
9203       Ids.emplace_back(&TypeTests[P.first], P.second);
9204     }
9205   }
9206 
9207   if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9208     return true;
9209 
9210   return false;
9211 }
9212 
9213 /// VFuncIdList
9214 ///   ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
parseVFuncIdList(lltok::Kind Kind,std::vector<FunctionSummary::VFuncId> & VFuncIdList)9215 bool LLParser::parseVFuncIdList(
9216     lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
9217   assert(Lex.getKind() == Kind);
9218   Lex.Lex();
9219 
9220   if (parseToken(lltok::colon, "expected ':' here") ||
9221       parseToken(lltok::lparen, "expected '(' here"))
9222     return true;
9223 
9224   IdToIndexMapType IdToIndexMap;
9225   do {
9226     FunctionSummary::VFuncId VFuncId;
9227     if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
9228       return true;
9229     VFuncIdList.push_back(VFuncId);
9230   } while (EatIfPresent(lltok::comma));
9231 
9232   if (parseToken(lltok::rparen, "expected ')' here"))
9233     return true;
9234 
9235   // Now that the VFuncIdList vector is finalized, it is safe to save the
9236   // locations of any forward GV references that need updating later.
9237   for (auto I : IdToIndexMap) {
9238     auto &Ids = ForwardRefTypeIds[I.first];
9239     for (auto P : I.second) {
9240       assert(VFuncIdList[P.first].GUID == 0 &&
9241              "Forward referenced type id GUID expected to be 0");
9242       Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
9243     }
9244   }
9245 
9246   return false;
9247 }
9248 
9249 /// ConstVCallList
9250 ///   ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
parseConstVCallList(lltok::Kind Kind,std::vector<FunctionSummary::ConstVCall> & ConstVCallList)9251 bool LLParser::parseConstVCallList(
9252     lltok::Kind Kind,
9253     std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
9254   assert(Lex.getKind() == Kind);
9255   Lex.Lex();
9256 
9257   if (parseToken(lltok::colon, "expected ':' here") ||
9258       parseToken(lltok::lparen, "expected '(' here"))
9259     return true;
9260 
9261   IdToIndexMapType IdToIndexMap;
9262   do {
9263     FunctionSummary::ConstVCall ConstVCall;
9264     if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
9265       return true;
9266     ConstVCallList.push_back(ConstVCall);
9267   } while (EatIfPresent(lltok::comma));
9268 
9269   if (parseToken(lltok::rparen, "expected ')' here"))
9270     return true;
9271 
9272   // Now that the ConstVCallList vector is finalized, it is safe to save the
9273   // locations of any forward GV references that need updating later.
9274   for (auto I : IdToIndexMap) {
9275     auto &Ids = ForwardRefTypeIds[I.first];
9276     for (auto P : I.second) {
9277       assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
9278              "Forward referenced type id GUID expected to be 0");
9279       Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
9280     }
9281   }
9282 
9283   return false;
9284 }
9285 
9286 /// ConstVCall
9287 ///   ::= '(' VFuncId ',' Args ')'
parseConstVCall(FunctionSummary::ConstVCall & ConstVCall,IdToIndexMapType & IdToIndexMap,unsigned Index)9288 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
9289                                IdToIndexMapType &IdToIndexMap, unsigned Index) {
9290   if (parseToken(lltok::lparen, "expected '(' here") ||
9291       parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
9292     return true;
9293 
9294   if (EatIfPresent(lltok::comma))
9295     if (parseArgs(ConstVCall.Args))
9296       return true;
9297 
9298   if (parseToken(lltok::rparen, "expected ')' here"))
9299     return true;
9300 
9301   return false;
9302 }
9303 
9304 /// VFuncId
9305 ///   ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
9306 ///         'offset' ':' UInt64 ')'
parseVFuncId(FunctionSummary::VFuncId & VFuncId,IdToIndexMapType & IdToIndexMap,unsigned Index)9307 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
9308                             IdToIndexMapType &IdToIndexMap, unsigned Index) {
9309   assert(Lex.getKind() == lltok::kw_vFuncId);
9310   Lex.Lex();
9311 
9312   if (parseToken(lltok::colon, "expected ':' here") ||
9313       parseToken(lltok::lparen, "expected '(' here"))
9314     return true;
9315 
9316   if (Lex.getKind() == lltok::SummaryID) {
9317     VFuncId.GUID = 0;
9318     unsigned ID = Lex.getUIntVal();
9319     LocTy Loc = Lex.getLoc();
9320     // Keep track of the array index needing a forward reference.
9321     // We will save the location of the GUID needing an update, but
9322     // can only do so once the caller's std::vector is finalized.
9323     IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
9324     Lex.Lex();
9325   } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
9326              parseToken(lltok::colon, "expected ':' here") ||
9327              parseUInt64(VFuncId.GUID))
9328     return true;
9329 
9330   if (parseToken(lltok::comma, "expected ',' here") ||
9331       parseToken(lltok::kw_offset, "expected 'offset' here") ||
9332       parseToken(lltok::colon, "expected ':' here") ||
9333       parseUInt64(VFuncId.Offset) ||
9334       parseToken(lltok::rparen, "expected ')' here"))
9335     return true;
9336 
9337   return false;
9338 }
9339 
9340 /// GVFlags
9341 ///   ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
9342 ///         'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
9343 ///         'dsoLocal' ':' Flag ',' 'canAutoHide' ':' Flag ')'
parseGVFlags(GlobalValueSummary::GVFlags & GVFlags)9344 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
9345   assert(Lex.getKind() == lltok::kw_flags);
9346   Lex.Lex();
9347 
9348   if (parseToken(lltok::colon, "expected ':' here") ||
9349       parseToken(lltok::lparen, "expected '(' here"))
9350     return true;
9351 
9352   do {
9353     unsigned Flag = 0;
9354     switch (Lex.getKind()) {
9355     case lltok::kw_linkage:
9356       Lex.Lex();
9357       if (parseToken(lltok::colon, "expected ':'"))
9358         return true;
9359       bool HasLinkage;
9360       GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
9361       assert(HasLinkage && "Linkage not optional in summary entry");
9362       Lex.Lex();
9363       break;
9364     case lltok::kw_notEligibleToImport:
9365       Lex.Lex();
9366       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9367         return true;
9368       GVFlags.NotEligibleToImport = Flag;
9369       break;
9370     case lltok::kw_live:
9371       Lex.Lex();
9372       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9373         return true;
9374       GVFlags.Live = Flag;
9375       break;
9376     case lltok::kw_dsoLocal:
9377       Lex.Lex();
9378       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9379         return true;
9380       GVFlags.DSOLocal = Flag;
9381       break;
9382     case lltok::kw_canAutoHide:
9383       Lex.Lex();
9384       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9385         return true;
9386       GVFlags.CanAutoHide = Flag;
9387       break;
9388     default:
9389       return error(Lex.getLoc(), "expected gv flag type");
9390     }
9391   } while (EatIfPresent(lltok::comma));
9392 
9393   if (parseToken(lltok::rparen, "expected ')' here"))
9394     return true;
9395 
9396   return false;
9397 }
9398 
9399 /// GVarFlags
9400 ///   ::= 'varFlags' ':' '(' 'readonly' ':' Flag
9401 ///                      ',' 'writeonly' ':' Flag
9402 ///                      ',' 'constant' ':' Flag ')'
parseGVarFlags(GlobalVarSummary::GVarFlags & GVarFlags)9403 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
9404   assert(Lex.getKind() == lltok::kw_varFlags);
9405   Lex.Lex();
9406 
9407   if (parseToken(lltok::colon, "expected ':' here") ||
9408       parseToken(lltok::lparen, "expected '(' here"))
9409     return true;
9410 
9411   auto ParseRest = [this](unsigned int &Val) {
9412     Lex.Lex();
9413     if (parseToken(lltok::colon, "expected ':'"))
9414       return true;
9415     return parseFlag(Val);
9416   };
9417 
9418   do {
9419     unsigned Flag = 0;
9420     switch (Lex.getKind()) {
9421     case lltok::kw_readonly:
9422       if (ParseRest(Flag))
9423         return true;
9424       GVarFlags.MaybeReadOnly = Flag;
9425       break;
9426     case lltok::kw_writeonly:
9427       if (ParseRest(Flag))
9428         return true;
9429       GVarFlags.MaybeWriteOnly = Flag;
9430       break;
9431     case lltok::kw_constant:
9432       if (ParseRest(Flag))
9433         return true;
9434       GVarFlags.Constant = Flag;
9435       break;
9436     case lltok::kw_vcall_visibility:
9437       if (ParseRest(Flag))
9438         return true;
9439       GVarFlags.VCallVisibility = Flag;
9440       break;
9441     default:
9442       return error(Lex.getLoc(), "expected gvar flag type");
9443     }
9444   } while (EatIfPresent(lltok::comma));
9445   return parseToken(lltok::rparen, "expected ')' here");
9446 }
9447 
9448 /// ModuleReference
9449 ///   ::= 'module' ':' UInt
parseModuleReference(StringRef & ModulePath)9450 bool LLParser::parseModuleReference(StringRef &ModulePath) {
9451   // parse module id.
9452   if (parseToken(lltok::kw_module, "expected 'module' here") ||
9453       parseToken(lltok::colon, "expected ':' here") ||
9454       parseToken(lltok::SummaryID, "expected module ID"))
9455     return true;
9456 
9457   unsigned ModuleID = Lex.getUIntVal();
9458   auto I = ModuleIdMap.find(ModuleID);
9459   // We should have already parsed all module IDs
9460   assert(I != ModuleIdMap.end());
9461   ModulePath = I->second;
9462   return false;
9463 }
9464 
9465 /// GVReference
9466 ///   ::= SummaryID
parseGVReference(ValueInfo & VI,unsigned & GVId)9467 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
9468   bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
9469   if (!ReadOnly)
9470     WriteOnly = EatIfPresent(lltok::kw_writeonly);
9471   if (parseToken(lltok::SummaryID, "expected GV ID"))
9472     return true;
9473 
9474   GVId = Lex.getUIntVal();
9475   // Check if we already have a VI for this GV
9476   if (GVId < NumberedValueInfos.size()) {
9477     assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
9478     VI = NumberedValueInfos[GVId];
9479   } else
9480     // We will create a forward reference to the stored location.
9481     VI = ValueInfo(false, FwdVIRef);
9482 
9483   if (ReadOnly)
9484     VI.setReadOnly();
9485   if (WriteOnly)
9486     VI.setWriteOnly();
9487   return false;
9488 }
9489