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